mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-19 01:34:25 +01:00
manual workout: log for future dates (credited on the day)
A manual workout may be dated today..today+7 days (no past dates). A future entry is held out of log.json and earns nothing until its date; the first sync/lock/reset pass on that day ingests and credits it like a workout logged that day. - ingest_manual_records defers records dated after the local day and counts the budget (2/7d, 10/30d) against the workout's own date over logged credits plus pending future records (a pending record never rejects itself) - PC-logged future entries (Tk dialog, --log-manual-workout --date) go to a durable pending ledger re-published on every push (a one-shot publish to devices/pc is overwritten by the next push); tombstones win, entries leave the ledger once logged or deleted - one shared date helper (validate_workout_date) used by the dialog and CLI; the form's date field rides in the sport row to keep the lock screen fitting - poke start_the_day also ingests due local entries after the daily reset - PC admission rule pinned to the phone's by the shared budget fixture (planned.expected_by_date) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015mmTBiMpvyfLuEAXc6nDYT
This commit is contained in:
parent
1a305c0627
commit
e12b840f8c
@ -31,6 +31,9 @@ NO_PHONE_EXTRA_LOCKOUT_SECONDS = 480 # extra 8 minutes on top of base
|
||||
# window is exhausted the "Log Manual Workout" option disappears entirely.
|
||||
MANUAL_WORKOUT_BUDGET_PER_7_DAYS = 2
|
||||
MANUAL_WORKOUT_BUDGET_PER_30_DAYS = 10
|
||||
# A manual workout may be logged AHEAD for a date up to this many days from
|
||||
# today (never a past date); it earns its credit on that date, not before.
|
||||
MANUAL_WORKOUT_MAX_DAYS_AHEAD = 7
|
||||
# Manual entries use the shared MIN_WORKOUT_DURATION_MINUTES bar below —
|
||||
# every workout type answers to the same minimum, whatever the sport.
|
||||
# Minimum chars for the "what was done" activity-details field.
|
||||
@ -111,6 +114,9 @@ WALK_MAX_GAP_SECONDS = 30
|
||||
# Workout records this PC must keep deleted in the sync store, pushed as
|
||||
# tombstones on every tick (see _sync_tombstones for why once is not enough).
|
||||
SYNC_TOMBSTONES_FILE = Path(__file__).resolve().parent / "sync_tombstones.json"
|
||||
# Future-dated manual workouts logged on THIS PC, re-published on every push
|
||||
# until their date (see _manual_pending for why a one-shot publish is erased).
|
||||
MANUAL_PENDING_FILE = Path(__file__).resolve().parent / "manual_pending.json"
|
||||
# Self-expiring marker: "logged in during today's early-bird window, still
|
||||
# waiting to see if a real workout shows up." Not a log.json entry —
|
||||
# it's a same-day pending flag, checked against its own "date" field.
|
||||
|
||||
@ -13,6 +13,11 @@ it bypassed those checks; this routes through the ordinary sync-ingest path
|
||||
(``ingest_manual_records``), so validation, the rolling budget, HMAC signing
|
||||
and workout_id dedup are the shared implementation rather than a second copy
|
||||
that can drift.
|
||||
|
||||
``--date`` may name a FUTURE day (up to 7 days ahead; past dates are refused).
|
||||
Such an entry is not ingested: it is held and published by
|
||||
``_manual_schedule`` and ingested -- and credited -- on its date by the
|
||||
ordinary sync pass.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -22,6 +27,8 @@ import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._manual_future import is_future_date, validate_workout_date
|
||||
from screen_locker._manual_schedule import budget_error, schedule_future_workout
|
||||
from screen_locker._manual_sync import ingest_manual_records
|
||||
from screen_locker._manual_workout import (
|
||||
SPORT_CHOICES,
|
||||
@ -73,7 +80,14 @@ def add_manual_arguments(parser: argparse.ArgumentParser) -> None:
|
||||
default="",
|
||||
help=f"what the activity was; required when --sport {SPORT_OTHER}",
|
||||
)
|
||||
parser.add_argument("--date", default="", help="ISO date; defaults to today")
|
||||
parser.add_argument(
|
||||
"--date",
|
||||
default="",
|
||||
help=(
|
||||
"ISO date, today up to 7 days ahead (no past dates); defaults to "
|
||||
"today. A future date is held and credited automatically on it."
|
||||
),
|
||||
)
|
||||
parser.add_argument("--start", required=True, help="HH:MM")
|
||||
parser.add_argument("--end", required=True, help="HH:MM")
|
||||
parser.add_argument("--location", required=True)
|
||||
@ -114,6 +128,52 @@ def _draft(args: argparse.Namespace) -> ManualWorkoutDraft:
|
||||
)
|
||||
|
||||
|
||||
def _schedule(log_file: Path, draft: ManualWorkoutDraft, date: str) -> int:
|
||||
"""Hold a FUTURE-dated workout and publish it; exit code for the CLI.
|
||||
|
||||
Never written to log.json or signed here: it is ingested by the ordinary
|
||||
sync pass on its date.
|
||||
"""
|
||||
scheduled = schedule_future_workout(log_file, draft, date)
|
||||
if not scheduled.scheduled:
|
||||
_logger.error(
|
||||
"Manual workout %s was NOT scheduled — %s",
|
||||
scheduled.record_id,
|
||||
scheduled.reason,
|
||||
)
|
||||
return 1
|
||||
_logger.info("Manual workout %s: %s", scheduled.record_id, scheduled.reason)
|
||||
return 0
|
||||
|
||||
|
||||
def _log_today(log_file: Path, draft: ManualWorkoutDraft, date: str, start: str) -> int:
|
||||
"""Log today's workout through the ordinary ingest; exit code for the CLI."""
|
||||
record_id = manual_sync_record_id(date, start)
|
||||
payload = build_sync_payload(draft, date)
|
||||
# Today's entry takes the ordinary path, but its budget now also counts
|
||||
# pending future entries (a window containing today contains tomorrow too).
|
||||
over_budget = budget_error(log_file, date)
|
||||
if over_budget is not None:
|
||||
_logger.error("Manual workout %s was NOT logged — %s", record_id, over_budget)
|
||||
return 1
|
||||
|
||||
ingested = ingest_manual_records(log_file, [(record_id, payload)], today=date)
|
||||
if not ingested:
|
||||
_logger.error(
|
||||
"Manual workout %s was NOT logged — see the reason logged above "
|
||||
"(invalid field, exhausted budget, or already logged)",
|
||||
record_id,
|
||||
)
|
||||
return 1
|
||||
_logger.info(
|
||||
"Logged manual workout %s. It publishes to the other devices on the "
|
||||
"next sync pass (workout-sync.timer, every 15 minutes); run "
|
||||
"--sync-only to push it now.",
|
||||
record_id,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def run_manual_log(log_file: Path, argv: Sequence[str]) -> int:
|
||||
"""Log one manual workout headlessly. Returns a process exit code.
|
||||
|
||||
@ -142,21 +202,10 @@ def run_manual_log(log_file: Path, argv: Sequence[str]) -> int:
|
||||
_logger.error("Manual workout REFUSED — %s. Nothing was written.", error)
|
||||
return 1
|
||||
|
||||
record_id = manual_sync_record_id(date, args.start)
|
||||
payload = build_sync_payload(draft, date)
|
||||
|
||||
ingested = ingest_manual_records(log_file, [(record_id, payload)], today=date)
|
||||
if not ingested:
|
||||
_logger.error(
|
||||
"Manual workout %s was NOT logged — see the reason logged above "
|
||||
"(invalid field, exhausted budget, or already logged)",
|
||||
record_id,
|
||||
)
|
||||
date_error = validate_workout_date(date)
|
||||
if date_error is not None:
|
||||
_logger.error("Manual workout REFUSED — %s. Nothing was written.", date_error)
|
||||
return 1
|
||||
_logger.info(
|
||||
"Logged manual workout %s. It publishes to the other devices on the "
|
||||
"next sync pass (workout-sync.timer, every 15 minutes); run "
|
||||
"--sync-only to push it now.",
|
||||
record_id,
|
||||
)
|
||||
return 0
|
||||
if is_future_date(date):
|
||||
return _schedule(log_file, draft, date)
|
||||
return _log_today(log_file, draft, date, args.start)
|
||||
|
||||
222
screen_locker/_manual_future.py
Normal file
222
screen_locker/_manual_future.py
Normal file
@ -0,0 +1,222 @@
|
||||
"""Future-dated manual workouts: the date rule and the per-date budget rule.
|
||||
|
||||
A manual workout may be logged AHEAD of time (``today .. today + 7 days``, never
|
||||
a past date) and earns its normal credit on that date, not before. Two pure
|
||||
rules live here, shared by every entry point (Tk dialog, CLI, sync ingest):
|
||||
|
||||
* :func:`validate_workout_date` -- the one 0..7-days-ahead check;
|
||||
* :func:`budget_error_for_date` -- the rolling budget (2 per 7 days, 10 per 30)
|
||||
counted against the WORKOUT's date, over logged credits AND pending future
|
||||
entries, so a future entry holds its slot from the moment it is logged.
|
||||
|
||||
No I/O beyond reading ``log.json``; the pending ledger and the Firebase pull
|
||||
are in ``_manual_pending`` / ``_manual_schedule``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, date, datetime, timedelta
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._constants import (
|
||||
MANUAL_WORKOUT_BUDGET_PER_7_DAYS,
|
||||
MANUAL_WORKOUT_BUDGET_PER_30_DAYS,
|
||||
MANUAL_WORKOUT_MAX_DAYS_AHEAD,
|
||||
)
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._manual_workout_types import manual_credit_dates
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
__all__ = [
|
||||
"BudgetUsage",
|
||||
"budget_closed_for_all_days",
|
||||
"budget_error_for_date",
|
||||
"budget_usage_for_date",
|
||||
"is_future_date",
|
||||
"parse_workout_date",
|
||||
"validate_workout_date",
|
||||
]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# (window length in days, cap) -- a window of N days is [start, start + N - 1].
|
||||
_WINDOWS: tuple[tuple[int, int], ...] = (
|
||||
(7, MANUAL_WORKOUT_BUDGET_PER_7_DAYS),
|
||||
(30, MANUAL_WORKOUT_BUDGET_PER_30_DAYS),
|
||||
)
|
||||
|
||||
|
||||
def parse_workout_date(value: str) -> date | None:
|
||||
"""Parse a strict ``YYYY-MM-DD`` string, or return None (and warn)."""
|
||||
try:
|
||||
return datetime.strptime(value.strip(), "%Y-%m-%d").replace(tzinfo=UTC).date()
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"Date %r is not YYYY-MM-DD (%s) — treated as invalid", value, exc
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def is_future_date(value: str, *, today: str | None = None) -> bool:
|
||||
"""True if ``value`` is a valid date strictly after today (local day)."""
|
||||
parsed = parse_workout_date(value)
|
||||
reference = parse_workout_date(today or today_str())
|
||||
return parsed is not None and reference is not None and parsed > reference
|
||||
|
||||
|
||||
def validate_workout_date(value: str, *, today: str | None = None) -> str | None:
|
||||
"""Return an error message if ``value`` is not today..today+7 days, else None.
|
||||
|
||||
THE date rule for manual workouts: no past dates (a back-dated entry is the
|
||||
easiest way to fake a missed week) and no more than
|
||||
``MANUAL_WORKOUT_MAX_DAYS_AHEAD`` days ahead.
|
||||
"""
|
||||
parsed = parse_workout_date(value)
|
||||
if parsed is None:
|
||||
return "Workout date must be YYYY-MM-DD"
|
||||
reference = parse_workout_date(today or today_str())
|
||||
if reference is None:
|
||||
return f"Today's date {today!r} is not YYYY-MM-DD"
|
||||
ahead = (parsed - reference).days
|
||||
if ahead < 0:
|
||||
return (
|
||||
f"Workout date {value.strip()} is in the past -- only today or up "
|
||||
f"to {MANUAL_WORKOUT_MAX_DAYS_AHEAD} days ahead"
|
||||
)
|
||||
if ahead > MANUAL_WORKOUT_MAX_DAYS_AHEAD:
|
||||
return (
|
||||
f"Workout date {value.strip()} is {ahead} days ahead -- at most "
|
||||
f"{MANUAL_WORKOUT_MAX_DAYS_AHEAD} days"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _ordinals(dates: Iterable[str]) -> list[int]:
|
||||
"""Day ordinals of every parsable date; unparsable ones are skipped."""
|
||||
days: list[int] = []
|
||||
for value in dates:
|
||||
parsed = parse_workout_date(value)
|
||||
if parsed is not None:
|
||||
days.append(parsed.toordinal())
|
||||
return days
|
||||
|
||||
|
||||
def _fullest_window(days: list[int], ordinal: int, length: int) -> tuple[int, int]:
|
||||
"""Return ``(count, start)`` of the fullest ``length``-day window holding D.
|
||||
|
||||
Counts the entries in ``days`` only (the new entry is not among them), over
|
||||
every window ``[start, start + length - 1]`` that contains ``ordinal``.
|
||||
"""
|
||||
return max(
|
||||
(
|
||||
(sum(1 for day in days if start <= day < start + length), start)
|
||||
for start in range(ordinal - length + 1, ordinal + 1)
|
||||
),
|
||||
key=lambda found: found[0],
|
||||
)
|
||||
|
||||
|
||||
def _existing_days(log_file: Path, pending_dates: Iterable[str]) -> list[int]:
|
||||
"""Ordinals of every logged credit and every pending future entry."""
|
||||
return [*_ordinals(manual_credit_dates(log_file)), *_ordinals(pending_dates)]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BudgetUsage:
|
||||
"""How full the fullest windows around one workout date already are."""
|
||||
|
||||
week: int
|
||||
month: int
|
||||
|
||||
@property
|
||||
def exhausted(self) -> bool:
|
||||
"""True if one more entry on that date would break either cap."""
|
||||
return (
|
||||
self.week >= MANUAL_WORKOUT_BUDGET_PER_7_DAYS
|
||||
or self.month >= MANUAL_WORKOUT_BUDGET_PER_30_DAYS
|
||||
)
|
||||
|
||||
|
||||
def budget_usage_for_date(
|
||||
log_file: Path,
|
||||
workout_date: str,
|
||||
pending_dates: Iterable[str] = (),
|
||||
) -> BudgetUsage | None:
|
||||
"""Return the fullest 7- and 30-day windows containing ``workout_date``.
|
||||
|
||||
The PC's admission rule as numbers: the shared cross-language fixture
|
||||
(``fixtures/manual_budget_merge.json``, ``planned.expected_by_date``) pins
|
||||
these to what the phone computes. None if the date does not parse.
|
||||
"""
|
||||
target = parse_workout_date(workout_date)
|
||||
if target is None:
|
||||
return None
|
||||
days = _existing_days(log_file, pending_dates)
|
||||
ordinal = target.toordinal()
|
||||
return BudgetUsage(
|
||||
week=_fullest_window(days, ordinal, 7)[0],
|
||||
month=_fullest_window(days, ordinal, 30)[0],
|
||||
)
|
||||
|
||||
|
||||
def budget_error_for_date(
|
||||
log_file: Path,
|
||||
workout_date: str,
|
||||
pending_dates: Iterable[str] = (),
|
||||
) -> str | None:
|
||||
"""Return why a manual workout dated ``workout_date`` does not fit, else None.
|
||||
|
||||
Adding an entry dated D is allowed only if EVERY rolling window containing
|
||||
D -- each 7-day window and each 30-day window -- stays within its cap
|
||||
counting the credits already in ``log_file``, the pending future entries
|
||||
in ``pending_dates``, and the new entry itself. Counting against D rather
|
||||
than against today is what lets a full week still schedule next week, and
|
||||
what keeps tomorrow's entry from being free of the cap.
|
||||
|
||||
``pending_dates`` must already exclude the entry being checked (an entry
|
||||
that holds its slot would otherwise reject itself on its own date).
|
||||
"""
|
||||
target = parse_workout_date(workout_date)
|
||||
if target is None:
|
||||
return f"Workout date {workout_date!r} must be YYYY-MM-DD"
|
||||
days = _existing_days(log_file, pending_dates)
|
||||
for length, cap in _WINDOWS:
|
||||
used, start = _fullest_window(days, target.toordinal(), length)
|
||||
if used >= cap:
|
||||
first = date.fromordinal(start)
|
||||
last = first + timedelta(days=length - 1)
|
||||
return (
|
||||
f"Manual-workout budget: {used} already counted/scheduled "
|
||||
f"between {first} and {last}, max {cap} per {length} days"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def budget_closed_for_all_days(
|
||||
log_file: Path,
|
||||
pending_dates: Iterable[str] = (),
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> bool:
|
||||
"""True if no date in today..today+7 could take another manual workout.
|
||||
|
||||
The "Log Manual Workout" button hides only then; "today's window is full"
|
||||
no longer closes it, since a later day may still have room.
|
||||
"""
|
||||
reference = parse_workout_date(today or today_str())
|
||||
if reference is None:
|
||||
_logger.warning("Today %r is not YYYY-MM-DD -- budget treated as closed", today)
|
||||
return True
|
||||
pending = list(pending_dates)
|
||||
return all(
|
||||
budget_error_for_date(
|
||||
log_file, (reference + timedelta(days=offset)).isoformat(), pending
|
||||
)
|
||||
is not None
|
||||
for offset in range(MANUAL_WORKOUT_MAX_DAYS_AHEAD + 1)
|
||||
)
|
||||
217
screen_locker/_manual_pending.py
Normal file
217
screen_locker/_manual_pending.py
Normal file
@ -0,0 +1,217 @@
|
||||
"""Durable ledger of future-dated manual workouts logged on THIS PC.
|
||||
|
||||
A manual workout logged for a later day must not enter ``log.json`` until that
|
||||
day (the weekly check, the budget, the status view and the shutdown derivation
|
||||
all read the log, and would count it early). It has to live somewhere else, and
|
||||
be visible to the phone for budget and deletion -- so it is published to this
|
||||
device's sync log.
|
||||
|
||||
Publishing once is not enough, for the reason ``_sync_tombstones`` documents:
|
||||
``_manual_push`` re-derives this device's log from ``log.json`` on every tick
|
||||
and ``crdt_sync.sync_log`` never reads the device's OWN remote log back, so
|
||||
anything published only once is overwritten by the next push. This ledger is
|
||||
what every push re-publishes (``records_from_workout_log`` merges it in), and
|
||||
ingestion on the workout's date reads the record back through the ordinary
|
||||
pull -- the PC does ingest its own device log -- or from here if Firebase is
|
||||
unreachable that day.
|
||||
|
||||
``{record_id: {payload, hlc, scheduled_at}}`` in ``MANUAL_PENDING_FILE``. The HLC
|
||||
is minted once and stored, so re-pushing the same entry does not churn the
|
||||
store. An entry leaves the ledger once it is in ``log.json`` (its own copy is
|
||||
then published from there) or once it is tombstoned.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from crdt_sync import Hlc, Record
|
||||
|
||||
from screen_locker._constants import MANUAL_PENDING_FILE
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._log_mixin import _entry_workout_id
|
||||
from screen_locker._manual_future import parse_workout_date
|
||||
from screen_locker._manual_workout import MANUAL_WORKOUT_SYNC_KIND
|
||||
from screen_locker._sync_tombstones import tombstone_records
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable, Mapping
|
||||
from pathlib import Path
|
||||
|
||||
__all__ = [
|
||||
"add_pending",
|
||||
"local_pending_records",
|
||||
"pending_future_dates",
|
||||
"pending_ledger_records",
|
||||
"settle_pending",
|
||||
]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_PAYLOAD_FIELD = "payload"
|
||||
|
||||
|
||||
def _ledger_path(path: Path | None) -> Path:
|
||||
"""Resolve the ledger path at call time, so a patched module global applies."""
|
||||
return MANUAL_PENDING_FILE if path is None else path
|
||||
|
||||
|
||||
def _load(path: Path) -> dict[str, dict[str, Any]]:
|
||||
"""Read the ledger; a missing file is empty, a corrupt one is loud."""
|
||||
if not path.exists():
|
||||
return {}
|
||||
try:
|
||||
raw = json.loads(path.read_text())
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
_logger.warning(
|
||||
"Pending manual-workout ledger %s is unreadable (%s) -- treating it "
|
||||
"as EMPTY, so future-dated workouts logged on this PC will not be "
|
||||
"re-published or credited from here",
|
||||
path,
|
||||
exc,
|
||||
)
|
||||
return {}
|
||||
if not isinstance(raw, dict):
|
||||
_logger.warning(
|
||||
"Pending manual-workout ledger %s is not a JSON object -- ignoring it",
|
||||
path,
|
||||
)
|
||||
return {}
|
||||
return {str(rid): entry for rid, entry in raw.items() if isinstance(entry, dict)}
|
||||
|
||||
|
||||
def _save(path: Path, ledger: dict[str, dict[str, Any]]) -> None:
|
||||
"""Write the ledger as sorted, indented JSON."""
|
||||
path.write_text(json.dumps(ledger, indent=2, sort_keys=True) + "\n")
|
||||
|
||||
|
||||
def add_pending(
|
||||
record_id: str,
|
||||
payload: dict[str, object],
|
||||
device_id: str,
|
||||
path: Path | None = None,
|
||||
) -> bool:
|
||||
"""Record a future-dated manual workout. Returns False if already held."""
|
||||
path = _ledger_path(path)
|
||||
ledger = _load(path)
|
||||
if record_id in ledger:
|
||||
return False
|
||||
ledger[record_id] = {
|
||||
"payload": payload,
|
||||
"hlc": Hlc.new_tick(device_id).to_str(),
|
||||
"scheduled_at": datetime.now(tz=UTC).isoformat(),
|
||||
}
|
||||
_save(path, ledger)
|
||||
return True
|
||||
|
||||
|
||||
def local_pending_records(path: Path | None = None) -> list[tuple[str, dict]]:
|
||||
"""Return ``(record_id, payload)`` for every ledgered entry not tombstoned.
|
||||
|
||||
The shape ``ingest_manual_records`` takes, so this PC's own future entries
|
||||
can be ingested on their date even when the Firebase pull is empty or down.
|
||||
"""
|
||||
dead = tombstone_records().keys()
|
||||
return [
|
||||
(rid, entry["payload"])
|
||||
for rid, entry in _load(_ledger_path(path)).items()
|
||||
if rid not in dead and isinstance(entry.get("payload"), dict)
|
||||
]
|
||||
|
||||
|
||||
def pending_ledger_records(path: Path | None = None) -> dict[str, Record]:
|
||||
"""Return the ledger as crdt_sync records, for ``_manual_push`` to publish.
|
||||
|
||||
An entry without a parsable ``hlc`` is skipped with a warning: publishing
|
||||
it clockless would churn the store (or lose to a stale copy).
|
||||
"""
|
||||
records: dict[str, Record] = {}
|
||||
for record_id, entry in _load(_ledger_path(path)).items():
|
||||
payload = entry.get("payload")
|
||||
try:
|
||||
hlc = Hlc.from_str(str(entry.get("hlc")))
|
||||
except (ValueError, TypeError) as exc:
|
||||
_logger.warning(
|
||||
"Pending manual workout %s has no usable hlc (%r: %s) -- NOT "
|
||||
"published, so the phone will not see it",
|
||||
record_id,
|
||||
entry.get("hlc"),
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
if isinstance(payload, dict):
|
||||
records[record_id] = Record(
|
||||
id=record_id, fields={_PAYLOAD_FIELD: (payload, hlc)}
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def _logged_ids(log_file: Path) -> set[str]:
|
||||
"""Every workout id already in ``log.json`` (stored, derived or synced)."""
|
||||
ids: set[str] = set()
|
||||
for day, entries in load_workout_log(log_file).items():
|
||||
for entry in entries:
|
||||
if (own := _entry_workout_id(day, entry)) is not None:
|
||||
ids.add(own)
|
||||
data = entry.get("workout_data", {})
|
||||
if isinstance(data, dict) and data.get("sync_record_id"):
|
||||
ids.add(str(data["sync_record_id"]))
|
||||
return ids
|
||||
|
||||
|
||||
def settle_pending(
|
||||
log_file: Path,
|
||||
deleted_ids: Iterable[str] = (),
|
||||
path: Path | None = None,
|
||||
) -> list[str]:
|
||||
"""Drop ledger entries that are in ``log.json`` or deleted; return their ids.
|
||||
|
||||
``deleted_ids`` come from the merged sync log (a tombstone written on the
|
||||
phone reaches it) and the local tombstone ledger is consulted too.
|
||||
"""
|
||||
path = _ledger_path(path)
|
||||
ledger = _load(path)
|
||||
if not ledger:
|
||||
return []
|
||||
gone = {*deleted_ids, *tombstone_records().keys(), *_logged_ids(log_file)}
|
||||
settled = [rid for rid in ledger if rid in gone]
|
||||
for rid in settled:
|
||||
del ledger[rid]
|
||||
if settled:
|
||||
_save(path, ledger)
|
||||
_logger.info("Pending manual workout(s) settled and dropped: %s", settled)
|
||||
return settled
|
||||
|
||||
|
||||
def pending_future_dates(
|
||||
log_file: Path,
|
||||
records: Iterable[tuple[str, Mapping[str, object]]],
|
||||
*,
|
||||
today: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Return ``{record_id: date}`` of manual records dated AFTER today.
|
||||
|
||||
``records`` is the merged Firebase manual pull and/or the local ledger
|
||||
(the same record id in both counts once). Ids already in ``log.json`` are
|
||||
not pending. Records dated today or earlier are not pending either: they
|
||||
were ingested or rejected, and a budget-skipped old record must not keep
|
||||
occupying a slot for everyone else.
|
||||
"""
|
||||
reference = today or today_str()
|
||||
logged = _logged_ids(log_file)
|
||||
pending: dict[str, str] = {}
|
||||
for record_id, payload in records:
|
||||
day = payload.get("date")
|
||||
if (
|
||||
payload.get("kind") == MANUAL_WORKOUT_SYNC_KIND
|
||||
and isinstance(day, str)
|
||||
and parse_workout_date(day) is not None
|
||||
and day > reference
|
||||
and record_id not in logged
|
||||
):
|
||||
pending[record_id] = day
|
||||
return pending
|
||||
@ -42,6 +42,7 @@ from screen_locker._constants import SYNC_STATE_FILE
|
||||
from screen_locker._device import device_identity
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._log_mixin import _derive_workout_id
|
||||
from screen_locker._manual_pending import pending_ledger_records, settle_pending
|
||||
from screen_locker._sync_retry import with_sync_retry
|
||||
from screen_locker._sync_tombstones import tombstone_records
|
||||
from screen_locker._weekly_check import COUNTED_WORKOUT_TYPES
|
||||
@ -148,6 +149,11 @@ def records_from_workout_log(log_file: Path) -> dict[str, Record]:
|
||||
log[str(record_id)] = Record(
|
||||
id=str(record_id), fields={_PAYLOAD_FIELD: (payload, hlc)}
|
||||
)
|
||||
# Future-dated manual workouts logged here are not in log.json until their
|
||||
# day; the ledger is what keeps them published (and visible to the phone's
|
||||
# budget and delete button). The log's own copy wins once ingested.
|
||||
for record_id, record in pending_ledger_records().items():
|
||||
log.setdefault(record_id, record)
|
||||
# Re-pushed every tick: sync_log never reads this device's own remote
|
||||
# log, so a tombstone written once is overwritten by the next push.
|
||||
log.update(tombstone_records())
|
||||
@ -177,7 +183,7 @@ def push_pc_workouts(log_file: Path) -> PushResult:
|
||||
)
|
||||
return PushResult(pushed=False, record_count=len(log), reason=reason)
|
||||
try:
|
||||
with_sync_retry(
|
||||
merged = with_sync_retry(
|
||||
lambda: sync_log(
|
||||
SyncTarget(
|
||||
client=client,
|
||||
@ -205,5 +211,8 @@ def push_pc_workouts(log_file: Path) -> PushResult:
|
||||
_logger.warning("Workout sync push FAILED for %d workout(s): %s", len(log), exc)
|
||||
return PushResult(pushed=False, record_count=len(log), reason=reason)
|
||||
|
||||
# A future entry deleted on the phone arrives as a tombstone in the merge;
|
||||
# one already ingested is in log.json. Either way it leaves the ledger.
|
||||
settle_pending(log_file, [rid for rid, record in merged.items() if record.deleted])
|
||||
_logger.info("Synced %d workout(s) to Firebase", len(log))
|
||||
return PushResult(pushed=True, record_count=len(log), reason="pushed")
|
||||
|
||||
115
screen_locker/_manual_schedule.py
Normal file
115
screen_locker/_manual_schedule.py
Normal file
@ -0,0 +1,115 @@
|
||||
"""Log a manual workout for a FUTURE day from this PC (Tk dialog and CLI).
|
||||
|
||||
A future-dated entry never touches ``log.json`` or ``write_signed_entry`` and
|
||||
earns nothing today. It is held in the pending ledger (``_manual_pending``),
|
||||
published to this device's sync log so the phone sees it (budget, delete), and
|
||||
ingested on its date by the ordinary sync pass, which pays exactly what a
|
||||
workout logged that day would.
|
||||
|
||||
This module is the one place that decides whether such an entry may be logged:
|
||||
the date window and the per-date budget, over the credits in ``log.json`` plus
|
||||
every pending future entry -- this PC's ledger AND the merged Firebase manual
|
||||
records (a phone-logged one holds a slot too).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._device import device_identity
|
||||
from screen_locker._manual_future import (
|
||||
budget_error_for_date,
|
||||
is_future_date,
|
||||
validate_workout_date,
|
||||
)
|
||||
from screen_locker._manual_pending import (
|
||||
add_pending,
|
||||
local_pending_records,
|
||||
pending_future_dates,
|
||||
)
|
||||
from screen_locker._manual_push import push_pc_workouts
|
||||
from screen_locker._manual_workout import build_sync_payload, manual_sync_record_id
|
||||
from screen_locker._workout_sync import pull_all_manual_records
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from screen_locker._manual_workout import ManualWorkoutDraft
|
||||
|
||||
__all__ = ["ScheduleResult", "budget_error", "schedule_future_workout"]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScheduleResult:
|
||||
"""Outcome of :func:`schedule_future_workout`; ``reason`` is for a human."""
|
||||
|
||||
scheduled: bool
|
||||
record_id: str
|
||||
reason: str
|
||||
|
||||
|
||||
def budget_error(
|
||||
log_file: Path, workout_date: str, *, exclude_id: str | None = None
|
||||
) -> str | None:
|
||||
"""Why a manual workout on ``workout_date`` does not fit the budget, else None.
|
||||
|
||||
Reads the pending future entries from this PC's ledger and from the merged
|
||||
Firebase pull. The pull is best-effort (``pull_all_manual_records`` warns
|
||||
and returns nothing when Firebase is unreachable), so offline this still
|
||||
sees the ledger -- only a phone-logged pending entry can be missed, and the
|
||||
ingest on that day re-checks.
|
||||
"""
|
||||
records = [*pull_all_manual_records(), *local_pending_records()]
|
||||
pending = pending_future_dates(log_file, records)
|
||||
if exclude_id is not None:
|
||||
pending.pop(exclude_id, None)
|
||||
return budget_error_for_date(log_file, workout_date, pending.values())
|
||||
|
||||
|
||||
def schedule_future_workout(
|
||||
log_file: Path, draft: ManualWorkoutDraft, workout_date: str
|
||||
) -> ScheduleResult:
|
||||
"""Hold a validated draft for ``workout_date`` and publish it.
|
||||
|
||||
The caller has run ``validate_manual_workout`` on ``draft``. Refuses (and
|
||||
says why) a date outside today+1..today+7, an exhausted budget, or an
|
||||
entry already scheduled under the same id; otherwise stores it in the
|
||||
pending ledger and pushes immediately, so the phone sees it now rather
|
||||
than on the next 15-minute tick.
|
||||
"""
|
||||
record_id = manual_sync_record_id(workout_date, draft.start_time)
|
||||
date_error = validate_workout_date(workout_date)
|
||||
if date_error is None and not is_future_date(workout_date):
|
||||
date_error = f"{workout_date} is today, not a future date"
|
||||
if date_error is not None:
|
||||
return ScheduleResult(scheduled=False, record_id=record_id, reason=date_error)
|
||||
over_budget = budget_error(log_file, workout_date)
|
||||
if over_budget is not None:
|
||||
return ScheduleResult(scheduled=False, record_id=record_id, reason=over_budget)
|
||||
payload = build_sync_payload(draft, workout_date)
|
||||
if not add_pending(record_id, payload, device_identity().device_id):
|
||||
return ScheduleResult(
|
||||
scheduled=False,
|
||||
record_id=record_id,
|
||||
reason=f"{record_id} is already scheduled",
|
||||
)
|
||||
pushed = push_pc_workouts(log_file)
|
||||
_logger.info(
|
||||
"Scheduled manual workout %s for %s (published=%s: %s)",
|
||||
record_id,
|
||||
workout_date,
|
||||
pushed.pushed,
|
||||
pushed.reason,
|
||||
)
|
||||
if pushed.pushed:
|
||||
reason = f"scheduled for {workout_date}; counts automatically that day"
|
||||
else:
|
||||
reason = (
|
||||
f"scheduled for {workout_date} on this PC (not yet published: "
|
||||
f"{pushed.reason}); it counts automatically that day"
|
||||
)
|
||||
return ScheduleResult(scheduled=True, record_id=record_id, reason=reason)
|
||||
@ -21,8 +21,15 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._log_mixin import _entry_workout_id, write_signed_entry
|
||||
from screen_locker._manual_future import (
|
||||
budget_error_for_date,
|
||||
is_future_date,
|
||||
parse_workout_date,
|
||||
)
|
||||
from screen_locker._manual_pending import pending_future_dates
|
||||
from screen_locker._manual_sync_draft import (
|
||||
_draft_or_report,
|
||||
is_empty_stub,
|
||||
@ -31,7 +38,6 @@ from screen_locker._manual_sync_draft import (
|
||||
from screen_locker._manual_workout import (
|
||||
MANUAL_WORKOUT_SYNC_KIND,
|
||||
build_entry,
|
||||
is_budget_exhausted,
|
||||
validate_manual_workout,
|
||||
)
|
||||
|
||||
@ -75,6 +81,38 @@ def _already_ingested(logs: dict[str, list[dict]], record_id: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _due_date(
|
||||
record_id: str, payload: Mapping[str, object], reference: str
|
||||
) -> str | None:
|
||||
"""Return the record's date if it is a manual record due for ingest, else None.
|
||||
|
||||
None covers every reason to leave it alone this pass: not a manual record,
|
||||
no/unparsable date (warned), or dated after ``reference`` -- deferred, and
|
||||
retried on every later pass so it lands on its date.
|
||||
"""
|
||||
if payload.get("kind") != MANUAL_WORKOUT_SYNC_KIND:
|
||||
return None
|
||||
date = payload.get("date")
|
||||
if not isinstance(date, str):
|
||||
_logger.warning("Manual record %s has no date — skipped", record_id)
|
||||
return None
|
||||
if parse_workout_date(date) is None:
|
||||
_logger.warning(
|
||||
"Manual record %s has an unparsable date %r — skipped", record_id, date
|
||||
)
|
||||
return None
|
||||
if is_future_date(date, today=reference):
|
||||
_logger.info(
|
||||
"Manual record %s is dated %s, after today (%s) — deferred; it "
|
||||
"is ingested and credited on its date",
|
||||
record_id,
|
||||
date,
|
||||
reference,
|
||||
)
|
||||
return None
|
||||
return date
|
||||
|
||||
|
||||
def ingest_manual_records(
|
||||
log_file: Path,
|
||||
records: Iterable[tuple[str, Mapping[str, object]]],
|
||||
@ -90,6 +128,17 @@ def ingest_manual_records(
|
||||
workouts). Idempotent: dedup by ``record_id`` here and by ``workout_id`` in
|
||||
the write chokepoint, so re-syncing the same record is a no-op.
|
||||
|
||||
A record dated AFTER ``today`` (default: the local day) is DEFERRED, not
|
||||
ingested: it stays in the sync store, earns nothing and is not written to
|
||||
``log.json`` (the weekly check, the budget, the status view and the
|
||||
shutdown derivation would all count a future day key early). It is retried
|
||||
on every later pass, so it is ingested -- and credited -- on its date.
|
||||
|
||||
The budget is counted against the workout's own date: the new entry fits
|
||||
only if every rolling window containing that date stays within its cap,
|
||||
over the credits in the log and every OTHER pending future record in
|
||||
``records`` (a future entry holds its slot from the moment it is logged).
|
||||
|
||||
When ``on_ingested`` is given, it's called ``on_ingested(entry, prior_entries)``
|
||||
right after each newly-appended record — ``prior_entries`` being that
|
||||
entry's own date's entries written before it — so the caller (see
|
||||
@ -101,13 +150,15 @@ def ingest_manual_records(
|
||||
|
||||
Returns the record ids actually ingested.
|
||||
"""
|
||||
batch = list(records)
|
||||
if not batch:
|
||||
return []
|
||||
reference = today or today_str()
|
||||
pending = pending_future_dates(log_file, batch, today=reference)
|
||||
ingested: list[str] = []
|
||||
for record_id, payload in records:
|
||||
if payload.get("kind") != MANUAL_WORKOUT_SYNC_KIND:
|
||||
continue
|
||||
date = payload.get("date")
|
||||
if not isinstance(date, str):
|
||||
_logger.warning("Manual record %s has no date — skipped", record_id)
|
||||
for record_id, payload in batch:
|
||||
date = _due_date(record_id, payload, reference)
|
||||
if date is None:
|
||||
continue
|
||||
if _already_ingested(load_workout_log(log_file), record_id):
|
||||
continue
|
||||
@ -118,8 +169,17 @@ def ingest_manual_records(
|
||||
if error is not None:
|
||||
_logger.warning("Manual record %s invalid: %s", record_id, error)
|
||||
continue
|
||||
if is_budget_exhausted(log_file, today=today):
|
||||
_logger.info("Manual-workout budget exhausted — %s not ingested", record_id)
|
||||
over_budget = budget_error_for_date(
|
||||
log_file,
|
||||
date,
|
||||
[day for rid, day in pending.items() if rid != record_id],
|
||||
)
|
||||
if over_budget is not None:
|
||||
_logger.info(
|
||||
"Manual-workout budget exhausted — %s not ingested (%s)",
|
||||
record_id,
|
||||
over_budget,
|
||||
)
|
||||
continue
|
||||
entry = build_entry(draft)
|
||||
entry[_SYNC_ID_FIELD] = record_id
|
||||
|
||||
117
screen_locker/_manual_workout_date.py
Normal file
117
screen_locker/_manual_workout_date.py
Normal file
@ -0,0 +1,117 @@
|
||||
"""Workout-date field of the manual-workout form, and the future-dated path.
|
||||
|
||||
Split out of :mod:`screen_locker._manual_workout_dialog` to keep every file
|
||||
under the 250-line cap; composed back into ``ManualWorkoutDialogMixin`` there,
|
||||
so both hosts (``ScreenLocker`` and ``StatusWindow``) are unchanged.
|
||||
|
||||
A manual workout may be dated today up to 7 days ahead. Today's takes the
|
||||
host's ordinary save path (which, on the lock screen, unlocks). A FUTURE one
|
||||
must not: it earns nothing today, so it is handed to ``_manual_schedule`` and
|
||||
the form shows a "scheduled" screen that returns to the host's cancelled hook
|
||||
-- never ``_on_manual_workout_saved``, which would unlock today.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._manual_future import (
|
||||
budget_closed_for_all_days,
|
||||
is_future_date,
|
||||
validate_workout_date,
|
||||
)
|
||||
from screen_locker._manual_pending import local_pending_records, pending_future_dates
|
||||
from screen_locker._manual_schedule import budget_error, schedule_future_workout
|
||||
from screen_locker._ui_widgets import disable_paste
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from screen_locker._manual_workout import ManualWorkoutDraft
|
||||
|
||||
|
||||
class ManualWorkoutDateMixin:
|
||||
"""Date row, budget gate and future-dated submission of the manual form."""
|
||||
|
||||
def _mw_budget_closed(self) -> bool:
|
||||
"""True if no day in today..today+7 has room (local ledger, no network)."""
|
||||
pending = pending_future_dates(self.log_file, local_pending_records())
|
||||
return budget_closed_for_all_days(self.log_file, pending.values())
|
||||
|
||||
def _mw_date_in_row(self, row: tk.Frame) -> None:
|
||||
"""Pack the workout-date entry (prefilled with today) into ``row``.
|
||||
|
||||
Called from the sport row rather than given a row of its own: the
|
||||
lock cannot scroll, and the form already fills a 768px panel
|
||||
(``scripts/verify_screen_fits.py``), so the field has to cost no height.
|
||||
"""
|
||||
var = tk.StringVar(value=today_str())
|
||||
self._mw_vars["date"] = var
|
||||
entry = tk.Entry(
|
||||
row,
|
||||
textvariable=var,
|
||||
width=11,
|
||||
font=self._colors.font("label"),
|
||||
bg=self._colors.palette.field_bg,
|
||||
fg=self._colors.palette.fg,
|
||||
insertbackground=self._colors.palette.fg,
|
||||
**self._colors.focus_kwargs(),
|
||||
)
|
||||
entry.pack(side="right", padx=self._colors.space("xs"))
|
||||
disable_paste(entry)
|
||||
tk.Label(
|
||||
row,
|
||||
text="Workout date (today to +7 days):",
|
||||
font=self._colors.font("label"),
|
||||
fg=self._colors.palette.fg,
|
||||
bg=self._colors.palette.bg,
|
||||
).pack(side="right", padx=self._colors.space("xs"))
|
||||
|
||||
def _mw_handled_by_date(self, draft: ManualWorkoutDraft) -> bool:
|
||||
"""Apply the date and budget rules; True if the submit is fully handled.
|
||||
|
||||
Handled means an error is on screen or a future entry was scheduled;
|
||||
False means the date is today and within budget, so the caller
|
||||
carries on with the host's ordinary save.
|
||||
"""
|
||||
date = self._mw_vars["date"].get().strip()
|
||||
error = validate_workout_date(date)
|
||||
future = error is None and is_future_date(date)
|
||||
if error is None and not future:
|
||||
error = budget_error(self.log_file, date)
|
||||
if error is not None:
|
||||
self._mw_error_label.config(text=error)
|
||||
return True
|
||||
if not future:
|
||||
return False
|
||||
result = schedule_future_workout(self.log_file, draft, date)
|
||||
if not result.scheduled:
|
||||
self._mw_error_label.config(text=result.reason)
|
||||
return True
|
||||
self._show_manual_workout_scheduled(result.reason)
|
||||
return True
|
||||
|
||||
def _show_manual_workout_scheduled(self, reason: str) -> None:
|
||||
"""Confirm a future entry and go back; it does NOT unlock anything."""
|
||||
self.clear_container()
|
||||
self._label(
|
||||
"✓ Workout Scheduled",
|
||||
role="display",
|
||||
scale=1.3,
|
||||
color=self._colors.palette.success,
|
||||
pad="lg",
|
||||
)
|
||||
self._text(reason, role="subtitle", color=self._colors.palette.success)
|
||||
self._text(
|
||||
"Nothing is credited today. It counts by itself on that date, and "
|
||||
"can be deleted in the phone app until then.",
|
||||
color=self._colors.palette.muted,
|
||||
)
|
||||
row = self._button_row()
|
||||
self._button(
|
||||
row,
|
||||
"OK",
|
||||
bg=self._colors.palette.accent,
|
||||
command=self._on_manual_workout_cancelled,
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
@ -23,6 +23,7 @@ from screen_locker import _manual_workout
|
||||
from screen_locker._constants import (
|
||||
MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
|
||||
)
|
||||
from screen_locker._manual_workout_date import ManualWorkoutDateMixin
|
||||
from screen_locker._manual_workout_sport_fields import ManualWorkoutSportFieldsMixin
|
||||
from screen_locker._manual_workout_widgets import ManualWorkoutFormWidgetsMixin
|
||||
|
||||
@ -34,6 +35,7 @@ _SPORT_LABEL_TO_CODE = {
|
||||
|
||||
|
||||
class ManualWorkoutDialogMixin(
|
||||
ManualWorkoutDateMixin,
|
||||
ManualWorkoutFormWidgetsMixin,
|
||||
ManualWorkoutSportFieldsMixin,
|
||||
):
|
||||
@ -43,7 +45,7 @@ class ManualWorkoutDialogMixin(
|
||||
"""Render the manual-workout evidence form, or a budget-exhausted note."""
|
||||
self.clear_container()
|
||||
self._label("Log Manual Workout", color=self._colors.palette.accent, pad="xs")
|
||||
if _manual_workout.is_budget_exhausted(self.log_file):
|
||||
if self._mw_budget_closed():
|
||||
self._text(
|
||||
"Manual-workout budget exhausted for this window.",
|
||||
color=self._colors.palette.danger,
|
||||
@ -212,6 +214,8 @@ class ManualWorkoutDialogMixin(
|
||||
if error is not None:
|
||||
self._mw_error_label.config(text=error)
|
||||
return
|
||||
if self._mw_handled_by_date(draft):
|
||||
return
|
||||
entry = _manual_workout.build_entry(draft)
|
||||
# Record the manual for cross-device sync (published on the next lock
|
||||
# startup). Local + best-effort — never blocks saving/unlocking.
|
||||
|
||||
@ -75,6 +75,8 @@ class ManualWorkoutSportFieldsMixin:
|
||||
selectcolor=self._colors.palette.field_bg,
|
||||
highlightthickness=0,
|
||||
).pack(side="left", padx=self._colors.space("xs"))
|
||||
# The workout-date field rides in this row, at no extra height.
|
||||
self._mw_date_in_row(row)
|
||||
self._mw_grid(parent, row, full=True)
|
||||
|
||||
def _on_mw_sport_changed(self, selected_label: str) -> None:
|
||||
|
||||
@ -58,6 +58,32 @@ def _parse_iso(date_str: str) -> datetime | None:
|
||||
return None
|
||||
|
||||
|
||||
def manual_credit_dates(log_file: Path) -> list[str]:
|
||||
"""Return the ``YYYY-MM-DD`` of every manual-workout CREDIT in the log.
|
||||
|
||||
One element per workout, decided by
|
||||
:func:`screen_locker._weekly_check.credit_key` -- the single rule every
|
||||
counter shares -- so a synced copy of a workout already logged here is the
|
||||
same credit, not a second budget slot (2026-09-13: a manual rekeyed to its
|
||||
local day, then pulled back in under a fresh workout_id, consumed two
|
||||
slots while the weekly count correctly saw one). Dates that do not parse
|
||||
are warned about by :func:`_parse_iso` and left out.
|
||||
"""
|
||||
dates: list[str] = []
|
||||
for date_str, entries in load_workout_log(log_file).items():
|
||||
if _parse_iso(date_str) is None:
|
||||
continue
|
||||
siblings = day_workout_index(entries)
|
||||
keys = {
|
||||
key
|
||||
for index, entry in enumerate(entries)
|
||||
if (key := credit_key(date_str, index, entry, siblings)) is not None
|
||||
and key[0] == MANUAL_WORKOUT_TYPE
|
||||
}
|
||||
dates.extend([date_str] * len(keys))
|
||||
return dates
|
||||
|
||||
|
||||
def count_in_window(
|
||||
log_file: Path,
|
||||
days: int,
|
||||
@ -69,37 +95,24 @@ def count_in_window(
|
||||
Counted per workout, not per day: each logged manual workout consumes its
|
||||
own budget slot, matching how each one also earns its own weekly-count
|
||||
and shutdown credit (see ``screen_locker._weekly_check.COUNTED_WORKOUT_TYPES``
|
||||
and ``screen_locker._workout_credit``) — the budget is the sole limiter on
|
||||
how many you can log, not a once-per-day collapse.
|
||||
and ``screen_locker._workout_credit``) -- the budget is the sole limiter on
|
||||
how many you can log, not a once-per-day collapse. See
|
||||
:func:`manual_credit_dates` for what "one workout" means.
|
||||
|
||||
"One workout" is decided by :func:`screen_locker._weekly_check.credit_key`,
|
||||
the single rule every counter must share. This used to count raw entries
|
||||
instead, so a synced copy of a workout already in the log (2026-09-13: a
|
||||
manual rekeyed to its local day, then pulled back in under a fresh
|
||||
workout_id) consumed a second budget slot while the weekly count, going
|
||||
through ``credit_key``, correctly saw one — and the budget read exhausted
|
||||
for a week over a workout that was logged once.
|
||||
The window is the ``days`` days ending at ``today`` (inclusive); entries
|
||||
dated after today are NOT in it. Whether a new entry fits is a different
|
||||
question, answered per workout date by ``_manual_future``.
|
||||
"""
|
||||
today_str = today or _today_iso()
|
||||
today_dt = _parse_iso(today_str)
|
||||
if today_dt is None:
|
||||
return 0
|
||||
cutoff = today_dt - timedelta(days=days)
|
||||
count = 0
|
||||
for date_str, entries in load_workout_log(log_file).items():
|
||||
parsed = _parse_iso(date_str)
|
||||
if parsed is None or not (cutoff < parsed <= today_dt):
|
||||
continue
|
||||
siblings = day_workout_index(entries)
|
||||
count += len(
|
||||
{
|
||||
key
|
||||
for index, entry in enumerate(entries)
|
||||
if (key := credit_key(date_str, index, entry, siblings)) is not None
|
||||
and key[0] == MANUAL_WORKOUT_TYPE
|
||||
}
|
||||
)
|
||||
return count
|
||||
return sum(
|
||||
1
|
||||
for date_str in manual_credit_dates(log_file)
|
||||
if (parsed := _parse_iso(date_str)) is not None and cutoff < parsed <= today_dt
|
||||
)
|
||||
|
||||
|
||||
def is_budget_exhausted(
|
||||
|
||||
@ -89,6 +89,10 @@ class PokeLocker(ScreenLocker):
|
||||
self,
|
||||
log_file=self.log_file,
|
||||
)
|
||||
# A future-dated manual workout logged on this PC whose day is today
|
||||
# earns its credit on the first PC action of the day, not at the next
|
||||
# 15-minute tick. Local ledger only: no network on the instant path.
|
||||
self._ingest_due_local_manual_workouts()
|
||||
|
||||
def credit_written(
|
||||
self, entry: dict[str, str], prior_entries: list[dict[str, object]]
|
||||
|
||||
@ -13,6 +13,7 @@ import logging
|
||||
from screen_locker._constants import SHUTDOWN_BASE_FILE
|
||||
from screen_locker._earned import span
|
||||
from screen_locker._earner_units import sync_path_unit
|
||||
from screen_locker._manual_pending import local_pending_records
|
||||
from screen_locker._manual_push import push_pc_workouts
|
||||
from screen_locker._manual_sync import ingest_manual_records
|
||||
from screen_locker._session_sync import ingest_session_records
|
||||
@ -60,18 +61,43 @@ class SyncMixin:
|
||||
live-logged workout would (see
|
||||
``WorkoutCreditMixin._apply_credit_for_written_entry``), regardless of
|
||||
whether it's dated today or back-dated — there's only one current
|
||||
shutdown config, so a back-dated sync still pushes it.
|
||||
shutdown config, so a back-dated sync still pushes it. A record dated
|
||||
after today is deferred by the ingest (nothing credited, nothing in
|
||||
``log.json``) and picked up by the first pass on its date -- which the
|
||||
startup checks run before any lock decision.
|
||||
"""
|
||||
push_pc_workouts(self.log_file)
|
||||
pulled = pull_all_manual_records()
|
||||
seen = {record_id for record_id, _payload in pulled}
|
||||
# This PC's own future-dated entries come back through the pull (the PC
|
||||
# ingests its own device log), but when Firebase is down on their day
|
||||
# the ledger is the only copy -- so it is a source here too.
|
||||
local = [rec for rec in local_pending_records() if rec[0] not in seen]
|
||||
ingested = ingest_manual_records(
|
||||
self.log_file,
|
||||
pull_all_manual_records(),
|
||||
[*pulled, *local],
|
||||
on_ingested=self._credit_ingested_workout,
|
||||
)
|
||||
for record_id in ingested:
|
||||
_logger.info("Ingested synced manual workout: %s", record_id)
|
||||
self.workout_data = {}
|
||||
|
||||
def _ingest_due_local_manual_workouts(self) -> None:
|
||||
"""Ingest this PC's own future-dated entries whose day has come.
|
||||
|
||||
Local-only (no network), so the new-day reset pass on the poke path
|
||||
can run it without costing the phone's instant credit a Firebase
|
||||
round trip. Entries not yet due are deferred by the ingest itself.
|
||||
"""
|
||||
ingested = ingest_manual_records(
|
||||
self.log_file,
|
||||
local_pending_records(),
|
||||
on_ingested=self._credit_ingested_workout,
|
||||
)
|
||||
for record_id in ingested:
|
||||
_logger.info("Ingested due scheduled manual workout: %s", record_id)
|
||||
self.workout_data = {}
|
||||
|
||||
def _ingest_synced_sessions(self) -> None:
|
||||
"""Ingest StrongLifts sessions other devices (or this PC) finished.
|
||||
|
||||
|
||||
@ -83,7 +83,7 @@ class UIFlowsMixin(SickDayFlowMixin, LockoutFlowMixin):
|
||||
width=12,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
self._sick_button(frame)
|
||||
if _manual_workout.is_budget_exhausted(self.log_file):
|
||||
if self._mw_budget_closed():
|
||||
self._text(
|
||||
"Manual-workout budget exhausted. No manual-log option available.",
|
||||
color=self._colors.palette.danger,
|
||||
|
||||
@ -30,7 +30,6 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock import LockConfig
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
|
||||
from screen_locker._status_data import (
|
||||
StatusSnapshot,
|
||||
@ -146,7 +145,7 @@ class StatusWindow(
|
||||
command=self._on_check_phone_clicked,
|
||||
width=14,
|
||||
).pack(side="left", padx=self._colors.space("sm"))
|
||||
if not _manual_workout.is_budget_exhausted(self.log_file):
|
||||
if not self._mw_budget_closed():
|
||||
self._button(
|
||||
frame,
|
||||
"Log Manual Workout",
|
||||
|
||||
@ -36,6 +36,15 @@ ISOLATED_STATE: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
"_sync_tombstones.SYNC_TOMBSTONES_FILE",
|
||||
),
|
||||
),
|
||||
# Future-dated manual workouts held for re-publishing on every push; a test
|
||||
# writing here would publish a fake workout to the phone.
|
||||
(
|
||||
"manual_pending.json",
|
||||
(
|
||||
"_constants.MANUAL_PENDING_FILE",
|
||||
"_manual_pending.MANUAL_PENDING_FILE",
|
||||
),
|
||||
),
|
||||
# The durable lock-decision trail. Written on EVERY locker run, so without
|
||||
# this the suite would append test decisions to the user's real
|
||||
# enforcement history in ~/.local/share/screen_locker/.
|
||||
|
||||
@ -22,6 +22,7 @@ from unittest.mock import MagicMock
|
||||
_TK_MODULES = (
|
||||
"screen_locker.screen_lock",
|
||||
"screen_locker._manual_workout_dialog",
|
||||
"screen_locker._manual_workout_date",
|
||||
"screen_locker._manual_workout_sport_fields",
|
||||
"screen_locker._manual_workout_widgets",
|
||||
"screen_locker._ui_form_fields",
|
||||
|
||||
@ -60,5 +60,47 @@
|
||||
"week": 1,
|
||||
"month": 2,
|
||||
"exhausted": false
|
||||
},
|
||||
"planned": {
|
||||
"_comment": [
|
||||
"Future-dated (planned) manual entries, added 2026-10-16. Readers of the",
|
||||
"top-level today/records/expected above ignore this key, so those",
|
||||
"expectations are unchanged.",
|
||||
"Scenario: the top-level records PLUS extra_records, still as of 'today'.",
|
||||
"A manual workout may be dated up to 7 days ahead; the PC credits it on",
|
||||
"its own date. Budget for adding an entry dated D = the fullest 7-/30-day",
|
||||
"window CONTAINING D, counting past and future live entries (stubs and",
|
||||
"tombstones excluded, as above). expected_by_date maps D to that budget.",
|
||||
"The deleted 08-30 plan proves a cancelled plan frees its slot: live, it",
|
||||
"would put 08-28 and 08-30 in one 7-day window (2/2, exhausted)."
|
||||
],
|
||||
"extra_records": [
|
||||
{
|
||||
"id": "manual:2026-08-28T10:00",
|
||||
"deleted": false,
|
||||
"payload": {
|
||||
"kind": "manual_workout",
|
||||
"type": "manual_workout",
|
||||
"date": "2026-08-28",
|
||||
"start_time": "10:00",
|
||||
"end_time": "11:00"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "manual:2026-08-30T09:00",
|
||||
"deleted": true,
|
||||
"payload": {
|
||||
"kind": "manual_workout",
|
||||
"type": "manual_workout",
|
||||
"date": "2026-08-30",
|
||||
"start_time": "09:00",
|
||||
"end_time": "10:00"
|
||||
}
|
||||
}
|
||||
],
|
||||
"expected_by_date": {
|
||||
"2026-08-27": {"week": 1, "month": 3, "exhausted": false},
|
||||
"2026-08-28": {"week": 1, "month": 3, "exhausted": false}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -16,7 +16,10 @@ import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from screen_locker._log_mixin import write_signed_entry
|
||||
from screen_locker._manual_future import budget_error_for_date, budget_usage_for_date
|
||||
from screen_locker._manual_workout import (
|
||||
MANUAL_WORKOUT_TYPE,
|
||||
count_in_window,
|
||||
@ -94,3 +97,71 @@ def test_an_evidence_less_stub_never_consumes_budget(tmp_path: Path) -> None:
|
||||
|
||||
assert count_in_window(log_file, 7, today=today) == 0
|
||||
assert count_in_window(log_file, 30, today=today) == 0
|
||||
|
||||
|
||||
def _planned_cases() -> list[tuple[str, dict[str, Any]]]:
|
||||
"""Every ``planned.expected_by_date`` entry as ``(date, expectation)``."""
|
||||
return sorted(_fixture()["planned"]["expected_by_date"].items())
|
||||
|
||||
|
||||
def _planned_live_payloads() -> list[dict[str, Any]]:
|
||||
"""The planned scenario: top-level records plus ``extra_records``, live only."""
|
||||
fixture = _fixture()
|
||||
records = [*fixture["records"], *fixture["planned"]["extra_records"]]
|
||||
return _live_payloads(records)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("day", "expected"), _planned_cases())
|
||||
def test_planned_budget_by_workout_date_matches_the_phone(
|
||||
tmp_path: Path, day: str, expected: dict[str, Any]
|
||||
) -> None:
|
||||
"""The per-date admission rule must equal the phone's, entry by entry.
|
||||
|
||||
The planned entries sit in the log here; the PC holds them out of the log
|
||||
until their day, so the same scenario is also run with them as pending
|
||||
dates (next test) and both must agree.
|
||||
"""
|
||||
log_file = _log_from(_planned_live_payloads(), tmp_path / "log.json")
|
||||
|
||||
usage = budget_usage_for_date(log_file, day)
|
||||
|
||||
assert usage is not None
|
||||
assert usage.week == expected["week"]
|
||||
assert usage.month == expected["month"]
|
||||
assert usage.exhausted is expected["exhausted"]
|
||||
assert (budget_error_for_date(log_file, day) is not None) is expected["exhausted"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("day", "expected"), _planned_cases())
|
||||
def test_planned_entries_held_as_pending_count_the_same(
|
||||
tmp_path: Path, day: str, expected: dict[str, Any]
|
||||
) -> None:
|
||||
"""Pending future entries (not yet in the log) hold the same slots."""
|
||||
fixture = _fixture()
|
||||
today = str(fixture["today"])
|
||||
live = _planned_live_payloads()
|
||||
logged = [p for p in live if str(p["date"]) <= today]
|
||||
pending = [str(p["date"]) for p in live if str(p["date"]) > today]
|
||||
log_file = _log_from(logged, tmp_path / "log.json")
|
||||
|
||||
usage = budget_usage_for_date(log_file, day, pending)
|
||||
|
||||
assert usage is not None
|
||||
assert (usage.week, usage.month) == (expected["week"], expected["month"])
|
||||
assert usage.exhausted is expected["exhausted"]
|
||||
|
||||
|
||||
def test_a_cancelled_plan_frees_its_slot(tmp_path: Path) -> None:
|
||||
"""Resurrecting the deleted 08-30 plan must exhaust the week around 08-28."""
|
||||
fixture = _fixture()
|
||||
everything = [
|
||||
r["payload"]
|
||||
for r in [*fixture["records"], *fixture["planned"]["extra_records"]]
|
||||
]
|
||||
log_file = _log_from(everything, tmp_path / "log.json")
|
||||
|
||||
usage = budget_usage_for_date(log_file, "2026-08-28")
|
||||
|
||||
assert usage is not None
|
||||
assert usage.week == 2
|
||||
assert usage.exhausted is True
|
||||
|
||||
@ -13,18 +13,23 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._manual_cli import run_manual_log
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
# The CLI refuses past dates, so the workout is dated today (a fixed date
|
||||
# would silently turn every test into a "past date" refusal one day later).
|
||||
_TODAY = today_str()
|
||||
|
||||
_VALID = (
|
||||
"--sport",
|
||||
"other",
|
||||
"--activity",
|
||||
"padel",
|
||||
"--date",
|
||||
"2026-08-27",
|
||||
_TODAY,
|
||||
"--start",
|
||||
"17:30",
|
||||
"--end",
|
||||
@ -88,7 +93,7 @@ def test_logs_a_valid_workout(tmp_path: Path) -> None:
|
||||
assert data["activity_type"] == "padel"
|
||||
assert data["duration_minutes"] == "90.0"
|
||||
assert data["rpe"] == 4
|
||||
assert entry["workout_id"] == "manual:2026-08-27T17:30"
|
||||
assert entry["workout_id"] == f"manual:{_TODAY}T17:30"
|
||||
assert entry["hmac"]
|
||||
|
||||
|
||||
@ -155,7 +160,7 @@ def test_the_rolling_budget_still_caps_headless_entries(tmp_path: Path) -> None:
|
||||
def test_date_defaults_to_today(tmp_path: Path) -> None:
|
||||
"""Omitting --date files the workout under today rather than failing."""
|
||||
log_file = tmp_path / "log.json"
|
||||
args = [a for a in _args() if a not in {"--date", "2026-08-27"}]
|
||||
args = [a for a in _args() if a not in {"--date", _TODAY}]
|
||||
|
||||
assert run_manual_log(log_file, args) == 0
|
||||
assert _entries(log_file)
|
||||
|
||||
123
screen_locker/tests/test_manual_cli_future.py
Normal file
123
screen_locker/tests/test_manual_cli_future.py
Normal file
@ -0,0 +1,123 @@
|
||||
"""Headless manual-workout logging with ``--date``: future days are held, not logged."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from screen_locker._manual_cli import run_manual_log
|
||||
from screen_locker._manual_push import PushResult
|
||||
from screen_locker.tests.test_manual_cli import _TODAY, _args, _entries
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _days_from_today(days: int) -> str:
|
||||
"""Return the local ISO date ``days`` from today (negative = past)."""
|
||||
return (date.fromisoformat(_TODAY) + timedelta(days=days)).isoformat()
|
||||
|
||||
|
||||
@dataclass
|
||||
class Held:
|
||||
"""The redirected pending ledger and the stubbed publisher."""
|
||||
|
||||
ledger: Path
|
||||
push: MagicMock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def held(tmp_path: Path) -> Iterator[Held]:
|
||||
"""Redirect the pending ledger and stub the publisher: nothing leaves the box."""
|
||||
ledger = tmp_path / "manual_pending.json"
|
||||
with (
|
||||
patch("screen_locker._constants.MANUAL_PENDING_FILE", ledger),
|
||||
patch("screen_locker._manual_pending.MANUAL_PENDING_FILE", ledger),
|
||||
patch(
|
||||
"screen_locker._manual_schedule.push_pc_workouts",
|
||||
return_value=PushResult(pushed=True, record_count=1, reason="pushed"),
|
||||
) as push,
|
||||
patch(
|
||||
"screen_locker._manual_schedule.device_identity",
|
||||
return_value=SimpleNamespace(device_id="pc-test"),
|
||||
),
|
||||
):
|
||||
yield Held(ledger=ledger, push=push)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ahead", [1, 7])
|
||||
def test_a_future_date_is_held_not_logged(
|
||||
tmp_path: Path, held: Held, ahead: int
|
||||
) -> None:
|
||||
"""Today+1 .. today+7 is scheduled: ledger + publish, never log.json."""
|
||||
log_file = tmp_path / "log.json"
|
||||
day = _days_from_today(ahead)
|
||||
|
||||
assert run_manual_log(log_file, _args(date=day)) == 0
|
||||
|
||||
assert _entries(log_file) == []
|
||||
assert list(json.loads(held.ledger.read_text())) == [f"manual:{day}T17:30"]
|
||||
held.push.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ahead", [8, -1])
|
||||
def test_a_date_outside_today_to_plus_seven_is_refused(
|
||||
tmp_path: Path, held: Held, ahead: int
|
||||
) -> None:
|
||||
"""+8 days and yesterday are refused, nothing written or published."""
|
||||
log_file = tmp_path / "log.json"
|
||||
|
||||
assert run_manual_log(log_file, _args(date=_days_from_today(ahead))) == 1
|
||||
|
||||
assert _entries(log_file) == []
|
||||
assert not held.ledger.exists()
|
||||
held.push.assert_not_called()
|
||||
|
||||
|
||||
def test_a_garbled_date_is_refused(tmp_path: Path, held: Held) -> None:
|
||||
"""A date that is not YYYY-MM-DD is refused before anything is written."""
|
||||
assert run_manual_log(tmp_path / "log.json", _args(date="tomorrow")) == 1
|
||||
assert not held.ledger.exists()
|
||||
|
||||
|
||||
def test_a_future_entry_that_breaks_the_budget_is_refused(
|
||||
tmp_path: Path, held: Held
|
||||
) -> None:
|
||||
"""Scheduling counts the logged credits: a full week cannot take a 3rd."""
|
||||
log_file = tmp_path / "log.json"
|
||||
day = _days_from_today(1)
|
||||
assert run_manual_log(log_file, _args(start="07:00", end="08:30")) == 0
|
||||
assert run_manual_log(log_file, _args(start="10:00", end="11:30")) == 0
|
||||
|
||||
# Today holds 2; tomorrow's 7-day window contains today, so it is full too.
|
||||
assert run_manual_log(log_file, _args(date=day)) == 1
|
||||
assert not held.ledger.exists()
|
||||
|
||||
|
||||
def test_scheduling_the_same_entry_twice_is_refused(tmp_path: Path, held: Held) -> None:
|
||||
"""The record id (date + start) is the dedup key for pending entries."""
|
||||
day = _days_from_today(2)
|
||||
log_file = tmp_path / "log.json"
|
||||
|
||||
assert run_manual_log(log_file, _args(date=day)) == 0
|
||||
assert run_manual_log(log_file, _args(date=day)) == 1
|
||||
assert len(json.loads(held.ledger.read_text())) == 1
|
||||
|
||||
|
||||
def test_a_pending_future_entry_counts_against_today(
|
||||
tmp_path: Path, held: Held
|
||||
) -> None:
|
||||
"""Today's entry sees pending future ones: they share a 7-day window."""
|
||||
log_file = tmp_path / "log.json"
|
||||
assert run_manual_log(log_file, _args(date=_days_from_today(1))) == 0
|
||||
assert run_manual_log(log_file, _args(date=_days_from_today(2), start="08:00")) == 0
|
||||
|
||||
assert run_manual_log(log_file, _args()) == 1
|
||||
assert _entries(log_file) == []
|
||||
199
screen_locker/tests/test_manual_future.py
Normal file
199
screen_locker/tests/test_manual_future.py
Normal file
@ -0,0 +1,199 @@
|
||||
"""Tests for the future-dated manual-workout date rule and per-date budget."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from screen_locker import _manual_future
|
||||
from screen_locker._log_mixin import write_signed_entry
|
||||
from screen_locker._manual_future import (
|
||||
BudgetUsage,
|
||||
budget_closed_for_all_days,
|
||||
budget_error_for_date,
|
||||
budget_usage_for_date,
|
||||
is_future_date,
|
||||
parse_workout_date,
|
||||
validate_workout_date,
|
||||
)
|
||||
from screen_locker._manual_workout import MANUAL_WORKOUT_TYPE
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_TODAY = "2026-10-16"
|
||||
|
||||
|
||||
def _plus(days: int, base: str = _TODAY) -> str:
|
||||
"""Return the ISO date ``days`` after ``base``."""
|
||||
return (date.fromisoformat(base) + timedelta(days=days)).isoformat()
|
||||
|
||||
|
||||
def _log(tmp_path: Path, *days: str) -> Path:
|
||||
"""Write one manual workout per day into a real signed log."""
|
||||
log_file = tmp_path / "log.json"
|
||||
for day in days:
|
||||
data = {
|
||||
"type": MANUAL_WORKOUT_TYPE,
|
||||
"start_time": "18:00",
|
||||
"workout_id": f"manual:{day}T18:00",
|
||||
}
|
||||
write_signed_entry(log_file, day, data)
|
||||
return log_file
|
||||
|
||||
|
||||
class TestParseWorkoutDate:
|
||||
"""Strict YYYY-MM-DD parsing."""
|
||||
|
||||
def test_parses_an_iso_date(self) -> None:
|
||||
assert parse_workout_date(" 2026-10-17 ") == date(2026, 10, 17)
|
||||
|
||||
@pytest.mark.parametrize("bad", ["", "tomorrow", "2026-13-01", "20261017"])
|
||||
def test_rejects_and_warns(
|
||||
self, bad: str, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert parse_workout_date(bad) is None
|
||||
assert "not YYYY-MM-DD" in caplog.text
|
||||
|
||||
|
||||
class TestIsFutureDate:
|
||||
"""Strictly after the reference day, valid dates only."""
|
||||
|
||||
def test_tomorrow_is_future_and_today_is_not(self) -> None:
|
||||
assert is_future_date(_plus(1), today=_TODAY) is True
|
||||
assert is_future_date(_TODAY, today=_TODAY) is False
|
||||
assert is_future_date(_plus(-1), today=_TODAY) is False
|
||||
|
||||
def test_garbage_is_not_future(self) -> None:
|
||||
assert is_future_date("nope", today=_TODAY) is False
|
||||
assert is_future_date(_plus(1), today="nope") is False
|
||||
|
||||
def test_defaults_to_the_real_local_day(self) -> None:
|
||||
assert is_future_date("2999-01-01") is True
|
||||
|
||||
|
||||
class TestValidateWorkoutDate:
|
||||
"""The one 0..7 days-ahead rule shared by the form and the CLI."""
|
||||
|
||||
@pytest.mark.parametrize("ahead", [0, 1, 7])
|
||||
def test_accepts_today_through_plus_seven(self, ahead: int) -> None:
|
||||
assert validate_workout_date(_plus(ahead), today=_TODAY) is None
|
||||
|
||||
def test_rejects_the_past(self) -> None:
|
||||
error = validate_workout_date(_plus(-1), today=_TODAY)
|
||||
assert error is not None
|
||||
assert "past" in error
|
||||
|
||||
def test_rejects_eight_days_ahead(self) -> None:
|
||||
error = validate_workout_date(_plus(8), today=_TODAY)
|
||||
assert error is not None
|
||||
assert "8 days ahead" in error
|
||||
|
||||
def test_rejects_a_garbled_date(self) -> None:
|
||||
assert validate_workout_date("soon", today=_TODAY) == (
|
||||
"Workout date must be YYYY-MM-DD"
|
||||
)
|
||||
|
||||
def test_reports_an_unusable_reference_day(self) -> None:
|
||||
error = validate_workout_date(_TODAY, today="garbled")
|
||||
assert error is not None
|
||||
assert "'garbled'" in error
|
||||
|
||||
def test_defaults_to_the_real_local_day(self) -> None:
|
||||
assert validate_workout_date("1999-01-01") is not None
|
||||
|
||||
|
||||
class TestBudgetUsage:
|
||||
"""The fullest windows that contain the workout date."""
|
||||
|
||||
def test_counts_logged_and_pending_in_the_fullest_window(
|
||||
self, tmp_path: Path
|
||||
) -> None:
|
||||
log_file = _log(tmp_path, _plus(-2))
|
||||
usage = budget_usage_for_date(log_file, _plus(1), [_plus(2)])
|
||||
assert usage == BudgetUsage(week=2, month=2)
|
||||
assert usage is not None
|
||||
assert usage.exhausted is True
|
||||
|
||||
def test_an_empty_log_is_not_exhausted(self, tmp_path: Path) -> None:
|
||||
usage = budget_usage_for_date(tmp_path / "none.json", _TODAY)
|
||||
assert usage == BudgetUsage(week=0, month=0)
|
||||
assert usage is not None
|
||||
assert usage.exhausted is False
|
||||
|
||||
def test_the_monthly_cap_alone_exhausts(self) -> None:
|
||||
assert BudgetUsage(week=0, month=10).exhausted is True
|
||||
assert BudgetUsage(week=1, month=9).exhausted is False
|
||||
|
||||
def test_an_unparsable_pending_date_is_ignored(self, tmp_path: Path) -> None:
|
||||
usage = budget_usage_for_date(tmp_path / "none.json", _TODAY, ["garbled"])
|
||||
assert usage == BudgetUsage(week=0, month=0)
|
||||
|
||||
def test_a_bad_date_has_no_usage(self, tmp_path: Path) -> None:
|
||||
assert budget_usage_for_date(tmp_path / "none.json", "x") is None
|
||||
|
||||
|
||||
class TestBudgetErrorForDate:
|
||||
"""Admission is decided per workout date, not against today's window."""
|
||||
|
||||
def test_a_full_week_refuses_a_day_inside_it(self, tmp_path: Path) -> None:
|
||||
log_file = _log(tmp_path, _plus(-6), _plus(-5))
|
||||
error = budget_error_for_date(log_file, _TODAY)
|
||||
assert error is not None
|
||||
assert "max 2 per 7 days" in error
|
||||
|
||||
def test_the_same_week_still_takes_a_day_outside_it(self, tmp_path: Path) -> None:
|
||||
log_file = _log(tmp_path, _plus(-6), _plus(-5))
|
||||
assert budget_error_for_date(log_file, _plus(1)) is None
|
||||
|
||||
def test_pending_future_entries_hold_their_slot(self, tmp_path: Path) -> None:
|
||||
pending = [_plus(1), _plus(2)]
|
||||
error = budget_error_for_date(tmp_path / "none.json", _plus(3), pending)
|
||||
assert error is not None
|
||||
assert budget_error_for_date(tmp_path / "none.json", _plus(9), pending) is None
|
||||
|
||||
def test_the_monthly_cap_applies(
|
||||
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
# With the real caps a 7-day window always trips first (ten entries in
|
||||
# 30 days force two per week), so isolate the 30-day window.
|
||||
monkeypatch.setattr(_manual_future, "_WINDOWS", ((30, 2),))
|
||||
days = [_plus(-10), _plus(10)]
|
||||
error = budget_error_for_date(tmp_path / "none.json", _TODAY, days)
|
||||
assert error is not None
|
||||
assert "per 30 days" in error
|
||||
|
||||
def test_a_bad_date_is_refused(self, tmp_path: Path) -> None:
|
||||
error = budget_error_for_date(tmp_path / "none.json", "later")
|
||||
assert error is not None
|
||||
assert "YYYY-MM-DD" in error
|
||||
|
||||
|
||||
class TestBudgetClosedForAllDays:
|
||||
"""The button hides only when no day today..+7 has room."""
|
||||
|
||||
def test_open_when_empty(self, tmp_path: Path) -> None:
|
||||
assert not budget_closed_for_all_days(tmp_path / "n.json", today=_TODAY)
|
||||
|
||||
def test_a_full_today_does_not_close_next_week(self, tmp_path: Path) -> None:
|
||||
log_file = _log(tmp_path, _plus(-1), _TODAY)
|
||||
assert not budget_closed_for_all_days(log_file, today=_TODAY)
|
||||
|
||||
def test_closed_when_every_day_in_range_is_full(self, tmp_path: Path) -> None:
|
||||
# Two pending on each side keep every window in today..+7 at the cap.
|
||||
pending = [_plus(-3), _plus(-2), _plus(4), _plus(5)]
|
||||
assert budget_closed_for_all_days(tmp_path / "n.json", pending, today=_TODAY)
|
||||
|
||||
def test_a_garbled_today_counts_as_closed(
|
||||
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert budget_closed_for_all_days(tmp_path / "n.json", today="??")
|
||||
assert "budget treated as closed" in caplog.text
|
||||
|
||||
def test_defaults_to_the_real_local_day(self, tmp_path: Path) -> None:
|
||||
assert not budget_closed_for_all_days(tmp_path / "n.json")
|
||||
170
screen_locker/tests/test_manual_future_wiring.py
Normal file
170
screen_locker/tests/test_manual_future_wiring.py
Normal file
@ -0,0 +1,170 @@
|
||||
"""Wiring of future-dated manual workouts: push, sync pass, poke reset, budget helper."""
|
||||
# pylint: disable=protected-access
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from crdt_sync import Record
|
||||
|
||||
from screen_locker import _manual_push, _poke_credit
|
||||
from screen_locker._log_mixin import write_signed_entry
|
||||
from screen_locker._manual_pending import add_pending, local_pending_records
|
||||
from screen_locker._manual_push import push_pc_workouts, records_from_workout_log
|
||||
from screen_locker._manual_workout import MANUAL_WORKOUT_TYPE
|
||||
from screen_locker._manual_workout_types import manual_credit_dates
|
||||
from screen_locker._poke_credit import PokeLocker
|
||||
from screen_locker._sync_tombstones import add_tombstone
|
||||
from screen_locker.tests.conftest import create_locker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
_RID = "manual:2026-10-17T18:00"
|
||||
_PAYLOAD = {"kind": "manual_workout", "date": "2026-10-17", "start_time": "18:00"}
|
||||
|
||||
|
||||
def _write_manual(log_file: Path, record_id: str, day: str) -> None:
|
||||
"""Write one manual workout with a given id into a real signed log."""
|
||||
data = {"type": MANUAL_WORKOUT_TYPE, "start_time": "18:00", "workout_id": record_id}
|
||||
write_signed_entry(log_file, day, data)
|
||||
|
||||
|
||||
class TestPushPublishesThePendingLedger:
|
||||
"""A one-shot publish would be erased by the next push; the ledger is re-pushed."""
|
||||
|
||||
def test_a_pending_entry_is_published_even_with_an_empty_log(
|
||||
self, tmp_path: Path
|
||||
) -> None:
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1")
|
||||
records = records_from_workout_log(tmp_path / "log.json")
|
||||
assert list(records) == [_RID]
|
||||
assert records[_RID].fields["payload"][0] == _PAYLOAD
|
||||
|
||||
def test_the_logs_own_copy_wins_once_ingested(self, tmp_path: Path) -> None:
|
||||
log_file = tmp_path / "log.json"
|
||||
_write_manual(log_file, _RID, "2026-10-17")
|
||||
add_pending(_RID, {**_PAYLOAD, "marker": "ledger"}, "pc-1")
|
||||
payload = records_from_workout_log(log_file)[_RID].fields["payload"][0]
|
||||
assert "marker" not in payload
|
||||
|
||||
def test_a_tombstone_beats_the_pending_entry(self, tmp_path: Path) -> None:
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1")
|
||||
add_tombstone(_RID, "pc-1", "deleted")
|
||||
assert records_from_workout_log(tmp_path / "log.json")[_RID].deleted
|
||||
|
||||
def test_a_push_drops_entries_the_merge_shows_deleted(self, tmp_path: Path) -> None:
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1")
|
||||
merged = {_RID: Record(id=_RID, fields={}, deleted=True)}
|
||||
with (
|
||||
patch.object(
|
||||
_manual_push, "sync_client_or_reason", return_value=(MagicMock(), "")
|
||||
),
|
||||
patch.object(_manual_push, "sync_log", return_value=merged),
|
||||
):
|
||||
result = push_pc_workouts(tmp_path / "log.json")
|
||||
assert result.pushed is True
|
||||
assert local_pending_records() == []
|
||||
|
||||
def test_a_push_keeps_a_live_pending_entry(self, tmp_path: Path) -> None:
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1")
|
||||
merged = {_RID: records_from_workout_log(tmp_path / "log.json")[_RID]}
|
||||
with (
|
||||
patch.object(
|
||||
_manual_push, "sync_client_or_reason", return_value=(MagicMock(), "")
|
||||
),
|
||||
patch.object(_manual_push, "sync_log", return_value=merged),
|
||||
):
|
||||
push_pc_workouts(tmp_path / "log.json")
|
||||
assert [rid for rid, _ in local_pending_records()] == [_RID]
|
||||
|
||||
|
||||
class TestSyncPassReadsTheLedger:
|
||||
"""The 15-minute pass and the login pass both ingest due ledger entries."""
|
||||
|
||||
def test_ledger_entries_join_the_pull_without_duplicating_it(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1")
|
||||
add_pending(
|
||||
"manual:2026-10-18T09:00", {**_PAYLOAD, "date": "2026-10-18"}, "pc-1"
|
||||
)
|
||||
pulled = [(_RID, {"from": "firebase"})]
|
||||
with (
|
||||
patch("screen_locker._sync_mixin.push_pc_workouts"),
|
||||
patch(
|
||||
"screen_locker._sync_mixin.pull_all_manual_records", return_value=pulled
|
||||
),
|
||||
patch(
|
||||
"screen_locker._sync_mixin.ingest_manual_records", return_value=[]
|
||||
) as ingest,
|
||||
):
|
||||
locker._ingest_synced_manual_workouts()
|
||||
records = ingest.call_args.args[1]
|
||||
assert [rid for rid, _ in records] == [_RID, "manual:2026-10-18T09:00"]
|
||||
assert records[0][1] == {"from": "firebase"}
|
||||
|
||||
def test_due_local_entries_are_ingested_with_the_credit_callback(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker.workout_data = {"stale": "state"}
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1")
|
||||
with patch(
|
||||
"screen_locker._sync_mixin.ingest_manual_records", return_value=[_RID]
|
||||
) as ingest:
|
||||
locker._ingest_due_local_manual_workouts()
|
||||
assert ingest.call_args.args[1] == [(_RID, _PAYLOAD)]
|
||||
assert ingest.call_args.kwargs["on_ingested"] == locker._credit_ingested_workout
|
||||
assert locker.workout_data == {}
|
||||
|
||||
|
||||
class TestPokeStartTheDay:
|
||||
"""The new-day reset pass also ingests due scheduled workouts, after the reset."""
|
||||
|
||||
def test_the_reset_is_followed_by_the_local_ingest(
|
||||
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
calls: list[str] = []
|
||||
|
||||
def headless(locker_cls: type[PokeLocker]) -> PokeLocker:
|
||||
locker = object.__new__(locker_cls)
|
||||
locker.log_file = tmp_path / "log.json"
|
||||
locker.workout_data = {}
|
||||
return locker
|
||||
|
||||
monkeypatch.setattr(_poke_credit, "_headless_locker", headless)
|
||||
monkeypatch.setattr(_poke_credit, "process_week_transition", lambda *_: [])
|
||||
monkeypatch.setattr(
|
||||
_poke_credit,
|
||||
"reset_to_base_if_new_day",
|
||||
lambda *_a, **_k: calls.append("reset"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
PokeLocker,
|
||||
"_ingest_due_local_manual_workouts",
|
||||
lambda _self: calls.append("ingest"),
|
||||
)
|
||||
_poke_credit.fresh_locker().start_the_day()
|
||||
assert calls == ["reset", "ingest"]
|
||||
|
||||
|
||||
class TestManualCreditDates:
|
||||
"""One date per credit; unparsable day keys are left out (and warned about)."""
|
||||
|
||||
def test_unparsable_day_keys_are_skipped(
|
||||
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
log_file = tmp_path / "log.json"
|
||||
_write_manual(log_file, "manual:2026-10-10T18:00", "2026-10-10")
|
||||
raw = json.loads(log_file.read_text())
|
||||
raw["garbled"] = raw["2026-10-10"]
|
||||
log_file.write_text(json.dumps(raw))
|
||||
with caplog.at_level("WARNING"):
|
||||
assert manual_credit_dates(log_file) == ["2026-10-10"]
|
||||
assert "unparsable date key" in caplog.text
|
||||
217
screen_locker/tests/test_manual_pending.py
Normal file
217
screen_locker/tests/test_manual_pending.py
Normal file
@ -0,0 +1,217 @@
|
||||
"""Tests for the pending ledger of future-dated manual workouts held on this PC."""
|
||||
# pylint: disable=protected-access
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync import Hlc
|
||||
|
||||
from screen_locker import _manual_pending
|
||||
from screen_locker._log_mixin import write_signed_entry
|
||||
from screen_locker._manual_pending import (
|
||||
add_pending,
|
||||
local_pending_records,
|
||||
pending_future_dates,
|
||||
pending_ledger_records,
|
||||
settle_pending,
|
||||
)
|
||||
from screen_locker._manual_workout import MANUAL_WORKOUT_TYPE
|
||||
from screen_locker._sync_tombstones import add_tombstone
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
_RID = "manual:2026-10-17T18:00"
|
||||
_PAYLOAD = {"kind": "manual_workout", "date": "2026-10-17", "start_time": "18:00"}
|
||||
|
||||
|
||||
def _ledger(tmp_path: Path) -> Path:
|
||||
"""A ledger path inside tmp_path (nothing exists there yet)."""
|
||||
return tmp_path / "pending.json"
|
||||
|
||||
|
||||
def _log_with(tmp_path: Path, record_id: str, day: str) -> Path:
|
||||
"""A real signed log already holding the workout ``record_id`` on ``day``."""
|
||||
log_file = tmp_path / "log.json"
|
||||
data = {"type": MANUAL_WORKOUT_TYPE, "start_time": "18:00"}
|
||||
data["workout_id"] = record_id
|
||||
write_signed_entry(log_file, day, data)
|
||||
return log_file
|
||||
|
||||
|
||||
class TestLedgerFile:
|
||||
"""Reading and writing the ledger is loud about damage."""
|
||||
|
||||
def test_missing_ledger_is_empty(self, tmp_path: Path) -> None:
|
||||
assert local_pending_records(_ledger(tmp_path)) == []
|
||||
|
||||
def test_defaults_to_the_isolated_module_path(self) -> None:
|
||||
assert _manual_pending._ledger_path(None) == _manual_pending.MANUAL_PENDING_FILE
|
||||
|
||||
def test_corrupt_ledger_is_empty_and_warned(
|
||||
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
path.write_text("{not json")
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert local_pending_records(path) == []
|
||||
assert "unreadable" in caplog.text
|
||||
|
||||
def test_non_object_ledger_is_ignored_and_warned(
|
||||
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
path.write_text("[1, 2]")
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert local_pending_records(path) == []
|
||||
assert "not a JSON object" in caplog.text
|
||||
|
||||
def test_non_dict_entries_are_dropped(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
path.write_text(json.dumps({"a": "junk", _RID: {"payload": _PAYLOAD}}))
|
||||
assert local_pending_records(path) == [(_RID, _PAYLOAD)]
|
||||
|
||||
|
||||
class TestAddPending:
|
||||
"""Entries are stored once with a stable, minted-once HLC."""
|
||||
|
||||
def test_stores_payload_and_hlc(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
assert add_pending(_RID, dict(_PAYLOAD), "pc-1", path) is True
|
||||
stored = json.loads(path.read_text())[_RID]
|
||||
assert stored["payload"] == _PAYLOAD
|
||||
assert Hlc.from_str(stored["hlc"]) is not None
|
||||
|
||||
def test_a_second_add_is_a_no_op_that_keeps_the_hlc(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1", path)
|
||||
first = path.read_text()
|
||||
assert add_pending(_RID, {"other": 1}, "pc-1", path) is False
|
||||
assert path.read_text() == first
|
||||
|
||||
|
||||
class TestLocalPendingRecords:
|
||||
"""What ingest reads when Firebase is down on the day."""
|
||||
|
||||
def test_returns_id_and_payload(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1", path)
|
||||
assert local_pending_records(path) == [(_RID, _PAYLOAD)]
|
||||
|
||||
def test_a_tombstoned_entry_is_not_returned(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1", path)
|
||||
add_tombstone(_RID, "pc-1", "deleted")
|
||||
assert local_pending_records(path) == []
|
||||
|
||||
def test_an_entry_without_a_payload_is_skipped(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
path.write_text(json.dumps({_RID: {"hlc": "x"}}))
|
||||
assert local_pending_records(path) == []
|
||||
|
||||
|
||||
class TestPendingLedgerRecords:
|
||||
"""What ``_manual_push`` re-publishes every tick."""
|
||||
|
||||
def test_builds_a_record_with_the_stored_hlc(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1", path)
|
||||
records = pending_ledger_records(path)
|
||||
payload, hlc = records[_RID].fields["payload"]
|
||||
assert payload == _PAYLOAD
|
||||
assert hlc.to_str() == json.loads(path.read_text())[_RID]["hlc"]
|
||||
|
||||
def test_bad_hlc_is_skipped_and_warned(
|
||||
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
path.write_text(json.dumps({_RID: {"payload": _PAYLOAD, "hlc": "garbage"}}))
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert pending_ledger_records(path) == {}
|
||||
assert "NOT published" in caplog.text
|
||||
|
||||
def test_non_dict_payload_is_skipped(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1", path)
|
||||
raw = json.loads(path.read_text())
|
||||
raw[_RID]["payload"] = "nope"
|
||||
path.write_text(json.dumps(raw))
|
||||
assert pending_ledger_records(path) == {}
|
||||
|
||||
|
||||
class TestSettlePending:
|
||||
"""Entries leave the ledger once logged or deleted."""
|
||||
|
||||
def test_empty_ledger_settles_nothing(self, tmp_path: Path) -> None:
|
||||
assert settle_pending(tmp_path / "log.json", path=_ledger(tmp_path)) == []
|
||||
|
||||
def test_an_entry_already_in_the_log_is_dropped(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1", path)
|
||||
log_file = _log_with(tmp_path, _RID, "2026-10-17")
|
||||
assert settle_pending(log_file, path=path) == [_RID]
|
||||
assert json.loads(path.read_text()) == {}
|
||||
|
||||
def test_a_synced_copy_in_the_log_also_settles_it(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1", path)
|
||||
log_file = tmp_path / "log.json"
|
||||
data = {"type": MANUAL_WORKOUT_TYPE, "sync_record_id": _RID}
|
||||
write_signed_entry(log_file, "2026-10-17", data)
|
||||
assert settle_pending(log_file, path=path) == [_RID]
|
||||
|
||||
def test_a_deleted_id_from_the_merge_is_dropped(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1", path)
|
||||
assert settle_pending(tmp_path / "none.json", [_RID], path) == [_RID]
|
||||
|
||||
def test_a_local_tombstone_is_dropped(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1", path)
|
||||
add_tombstone(_RID, "pc-1", "deleted")
|
||||
assert settle_pending(tmp_path / "none.json", path=path) == [_RID]
|
||||
|
||||
def test_a_live_future_entry_stays(self, tmp_path: Path) -> None:
|
||||
path = _ledger(tmp_path)
|
||||
add_pending(_RID, dict(_PAYLOAD), "pc-1", path)
|
||||
assert settle_pending(tmp_path / "none.json", path=path) == []
|
||||
assert _RID in json.loads(path.read_text())
|
||||
|
||||
|
||||
class TestPendingFutureDates:
|
||||
"""Which records still hold a future slot."""
|
||||
|
||||
def test_only_manual_records_after_today_count(self, tmp_path: Path) -> None:
|
||||
records = [
|
||||
("future", {**_PAYLOAD, "date": "2026-10-18"}),
|
||||
("today", {**_PAYLOAD, "date": "2026-10-16"}),
|
||||
("past", {**_PAYLOAD, "date": "2026-10-01"}),
|
||||
("session", {"exercises": [], "date": "2026-10-20"}),
|
||||
("garbled", {**_PAYLOAD, "date": "2026-13-45"}),
|
||||
("nodate", {"kind": "manual_workout"}),
|
||||
]
|
||||
found = pending_future_dates(
|
||||
tmp_path / "none.json", records, today="2026-10-16"
|
||||
)
|
||||
assert found == {"future": "2026-10-18"}
|
||||
|
||||
def test_an_already_logged_id_is_not_pending(self, tmp_path: Path) -> None:
|
||||
log_file = _log_with(tmp_path, _RID, "2026-10-17")
|
||||
found = pending_future_dates(log_file, [(_RID, _PAYLOAD)], today="2026-10-16")
|
||||
assert found == {}
|
||||
|
||||
def test_defaults_to_the_real_local_day(self, tmp_path: Path) -> None:
|
||||
payload = {**_PAYLOAD, "date": "2999-01-01"}
|
||||
found = pending_future_dates(tmp_path / "none.json", [("far", payload)])
|
||||
assert found == {"far": "2999-01-01"}
|
||||
|
||||
def test_an_entry_with_no_derivable_id_is_ignored(self, tmp_path: Path) -> None:
|
||||
log_file = tmp_path / "log.json"
|
||||
log_file.write_text(json.dumps({"2026-10-10": [{"workout_data": {}}]}))
|
||||
found = pending_future_dates(log_file, [(_RID, _PAYLOAD)], today="2026-10-16")
|
||||
assert found == {_RID: "2026-10-17"}
|
||||
151
screen_locker/tests/test_manual_schedule.py
Normal file
151
screen_locker/tests/test_manual_schedule.py
Normal file
@ -0,0 +1,151 @@
|
||||
"""Tests for logging a manual workout for a future day from this PC."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from screen_locker import _manual_schedule
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._manual_push import PushResult
|
||||
from screen_locker._manual_schedule import budget_error, schedule_future_workout
|
||||
from screen_locker._manual_workout import (
|
||||
SPORT_OTHER,
|
||||
ManualWorkoutDraft,
|
||||
build_sync_payload,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _plus(days: int) -> str:
|
||||
"""Return the local ISO date ``days`` from today."""
|
||||
return (date.fromisoformat(today_str()) + timedelta(days=days)).isoformat()
|
||||
|
||||
|
||||
def _draft(start: str = "18:00") -> ManualWorkoutDraft:
|
||||
"""A valid 'other sport' draft."""
|
||||
return ManualWorkoutDraft(
|
||||
sport=SPORT_OTHER,
|
||||
start_time=start,
|
||||
end_time="19:30",
|
||||
location_name="Padel Club",
|
||||
transport_method="bike",
|
||||
cost="40 PLN",
|
||||
rpe=7,
|
||||
went_well="Good rallies and fast footwork",
|
||||
to_improve="Second serve needs more spin work",
|
||||
overall_feeling="Tired but happy, legs felt strong",
|
||||
activity_type_other="padel",
|
||||
activity_details="Ninety minutes of padel doubles, baseline and net play",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def stubs(tmp_path: Path) -> Iterator[SimpleNamespace]:
|
||||
"""Redirect the ledger; stub Firebase pull, the publisher and the identity."""
|
||||
ledger = tmp_path / "pending.json"
|
||||
pulled: list[tuple[str, dict]] = []
|
||||
push = MagicMock(return_value=PushResult(pushed=True, record_count=1, reason="ok"))
|
||||
with (
|
||||
patch("screen_locker._manual_pending.MANUAL_PENDING_FILE", ledger),
|
||||
patch.object(_manual_schedule, "pull_all_manual_records", lambda: list(pulled)),
|
||||
patch.object(_manual_schedule, "push_pc_workouts", push),
|
||||
patch.object(
|
||||
_manual_schedule,
|
||||
"device_identity",
|
||||
lambda: SimpleNamespace(device_id="pc-test"),
|
||||
),
|
||||
):
|
||||
yield SimpleNamespace(
|
||||
ledger=ledger, pulled=pulled, push=push, log_file=tmp_path / "log.json"
|
||||
)
|
||||
|
||||
|
||||
class TestBudgetError:
|
||||
"""Budget sees the Firebase pull AND this PC's ledger."""
|
||||
|
||||
def test_open_when_nothing_is_pending(self, stubs: SimpleNamespace) -> None:
|
||||
assert budget_error(stubs.log_file, _plus(1)) is None
|
||||
|
||||
def test_phone_pending_entries_hold_a_slot(self, stubs: SimpleNamespace) -> None:
|
||||
for offset in (1, 2):
|
||||
payload = build_sync_payload(_draft(f"1{offset}:00"), _plus(offset))
|
||||
stubs.pulled.append((f"manual:{_plus(offset)}T1{offset}:00", payload))
|
||||
assert budget_error(stubs.log_file, _plus(3)) is not None
|
||||
|
||||
def test_excluding_an_id_frees_its_slot(self, stubs: SimpleNamespace) -> None:
|
||||
ids = []
|
||||
for offset in (1, 2):
|
||||
rid = f"manual:{_plus(offset)}T1{offset}:00"
|
||||
ids.append(rid)
|
||||
stubs.pulled.append((rid, build_sync_payload(_draft(), _plus(offset))))
|
||||
assert budget_error(stubs.log_file, _plus(3)) is not None
|
||||
assert budget_error(stubs.log_file, _plus(3), exclude_id=ids[0]) is None
|
||||
|
||||
|
||||
class TestScheduleFutureWorkout:
|
||||
"""Hold a validated draft for a later day and publish it."""
|
||||
|
||||
def test_schedules_stores_and_publishes(self, stubs: SimpleNamespace) -> None:
|
||||
day = _plus(1)
|
||||
|
||||
result = schedule_future_workout(stubs.log_file, _draft(), day)
|
||||
|
||||
assert result.scheduled is True
|
||||
assert result.record_id == f"manual:{day}T18:00"
|
||||
assert "counts automatically" in result.reason
|
||||
assert list(json.loads(stubs.ledger.read_text())) == [result.record_id]
|
||||
stubs.push.assert_called_once_with(stubs.log_file)
|
||||
assert not stubs.log_file.exists()
|
||||
|
||||
def test_an_unpublished_entry_is_still_scheduled_and_says_so(
|
||||
self, stubs: SimpleNamespace
|
||||
) -> None:
|
||||
stubs.push.return_value = PushResult(
|
||||
pushed=False, record_count=1, reason="Firebase down"
|
||||
)
|
||||
result = schedule_future_workout(stubs.log_file, _draft(), _plus(2))
|
||||
assert result.scheduled is True
|
||||
assert "not yet published: Firebase down" in result.reason
|
||||
|
||||
def test_today_is_not_a_future_date(self, stubs: SimpleNamespace) -> None:
|
||||
result = schedule_future_workout(stubs.log_file, _draft(), _plus(0))
|
||||
assert result.scheduled is False
|
||||
assert "is today" in result.reason
|
||||
stubs.push.assert_not_called()
|
||||
|
||||
@pytest.mark.parametrize("ahead", [-1, 8])
|
||||
def test_a_date_outside_the_window_is_refused(
|
||||
self, stubs: SimpleNamespace, ahead: int
|
||||
) -> None:
|
||||
result = schedule_future_workout(stubs.log_file, _draft(), _plus(ahead))
|
||||
assert result.scheduled is False
|
||||
assert not stubs.ledger.exists()
|
||||
|
||||
def test_an_exhausted_budget_is_refused(self, stubs: SimpleNamespace) -> None:
|
||||
assert schedule_future_workout(
|
||||
stubs.log_file, _draft("10:00"), _plus(1)
|
||||
).scheduled
|
||||
assert schedule_future_workout(
|
||||
stubs.log_file, _draft("11:00"), _plus(2)
|
||||
).scheduled
|
||||
refused = schedule_future_workout(stubs.log_file, _draft("12:00"), _plus(3))
|
||||
assert refused.scheduled is False
|
||||
assert "budget" in refused.reason.lower()
|
||||
assert len(json.loads(stubs.ledger.read_text())) == 2
|
||||
|
||||
def test_the_same_entry_twice_is_refused(self, stubs: SimpleNamespace) -> None:
|
||||
day = _plus(1)
|
||||
assert schedule_future_workout(stubs.log_file, _draft(), day).scheduled
|
||||
again = schedule_future_workout(stubs.log_file, _draft(), day)
|
||||
assert again.scheduled is False
|
||||
assert "already scheduled" in again.reason
|
||||
stubs.push.assert_called_once()
|
||||
@ -174,7 +174,7 @@ class TestIngestManualRecords:
|
||||
"""Skips when budget exhausted."""
|
||||
log_file = tmp_path / "log.json"
|
||||
record = _manual_record(_TT_DRAFT)
|
||||
with patch.object(_manual_sync, "is_budget_exhausted", return_value=True):
|
||||
with patch.object(_manual_sync, "budget_error_for_date", return_value="full"):
|
||||
assert ingest_manual_records(log_file, [record], today=_DATE) == []
|
||||
|
||||
def test_writes_unsigned_entry_when_hmac_key_unavailable(
|
||||
|
||||
150
screen_locker/tests/test_manual_sync_future.py
Normal file
150
screen_locker/tests/test_manual_sync_future.py
Normal file
@ -0,0 +1,150 @@
|
||||
"""Future-dated records at the ingest chokepoint: deferred, then credited on the day."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker._manual_sync import ingest_manual_records
|
||||
from screen_locker.tests.test_manual_sync import (
|
||||
_OTHER_DRAFT,
|
||||
_TT_DRAFT,
|
||||
_manual_record,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
_TODAY = "2026-10-16"
|
||||
_TOMORROW = "2026-10-17"
|
||||
|
||||
|
||||
def _days(log_file: Path) -> dict[str, int]:
|
||||
"""Return ``{day: entry count}`` of the log, or {} if it does not exist."""
|
||||
if not log_file.exists():
|
||||
return {}
|
||||
return {d: len(e) for d, e in json.loads(log_file.read_text()).items()}
|
||||
|
||||
|
||||
class TestDeferral:
|
||||
"""A record dated after today stays in the sync store and earns nothing."""
|
||||
|
||||
def test_a_future_record_is_not_ingested_or_credited(
|
||||
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
log_file = tmp_path / "log.json"
|
||||
calls: list[dict] = []
|
||||
with caplog.at_level(logging.INFO):
|
||||
ingested = ingest_manual_records(
|
||||
log_file,
|
||||
[_manual_record(_TT_DRAFT, _TOMORROW)],
|
||||
today=_TODAY,
|
||||
on_ingested=lambda entry, _prior: calls.append(entry),
|
||||
)
|
||||
assert ingested == []
|
||||
assert calls == []
|
||||
assert _days(log_file) == {}
|
||||
assert "deferred" in caplog.text
|
||||
|
||||
def test_the_same_record_is_ingested_and_credited_on_its_day(
|
||||
self, tmp_path: Path
|
||||
) -> None:
|
||||
log_file = tmp_path / "log.json"
|
||||
record = _manual_record(_TT_DRAFT, _TOMORROW)
|
||||
calls: list[dict] = []
|
||||
|
||||
assert ingest_manual_records(log_file, [record], today=_TODAY) == []
|
||||
ingested = ingest_manual_records(
|
||||
log_file,
|
||||
[record],
|
||||
today=_TOMORROW,
|
||||
on_ingested=lambda entry, _prior: calls.append(entry),
|
||||
)
|
||||
|
||||
assert ingested == [record[0]]
|
||||
assert [c["workout_id"] for c in calls] == [record[0]]
|
||||
assert _days(log_file) == {_TOMORROW: 1}
|
||||
|
||||
def test_a_garbled_date_is_skipped_loudly(
|
||||
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
record_id, payload = _manual_record(_TT_DRAFT, _TODAY)
|
||||
payload["date"] = "2026-13-99"
|
||||
with caplog.at_level(logging.WARNING):
|
||||
assert (
|
||||
ingest_manual_records(
|
||||
tmp_path / "log.json", [(record_id, payload)], today=_TODAY
|
||||
)
|
||||
== []
|
||||
)
|
||||
assert "unparsable date" in caplog.text
|
||||
|
||||
def test_an_empty_batch_touches_nothing(self, tmp_path: Path) -> None:
|
||||
assert ingest_manual_records(tmp_path / "log.json", [], today=_TODAY) == []
|
||||
assert not (tmp_path / "log.json").exists()
|
||||
|
||||
def test_a_non_manual_record_is_ignored(self, tmp_path: Path) -> None:
|
||||
assert (
|
||||
ingest_manual_records(
|
||||
tmp_path / "log.json", [("s", {"exercises": []})], today=_TODAY
|
||||
)
|
||||
== []
|
||||
)
|
||||
|
||||
def test_defaults_to_the_real_local_day(self, tmp_path: Path) -> None:
|
||||
record = _manual_record(_TT_DRAFT, "2999-01-01")
|
||||
assert ingest_manual_records(tmp_path / "log.json", [record]) == []
|
||||
|
||||
|
||||
class TestBudgetAgainstTheWorkoutDate:
|
||||
"""The budget is per workout date and counts pending future records."""
|
||||
|
||||
def test_a_pending_record_does_not_reject_itself_on_its_day(
|
||||
self, tmp_path: Path
|
||||
) -> None:
|
||||
log_file = tmp_path / "log.json"
|
||||
mine = _manual_record(_TT_DRAFT, _TOMORROW)
|
||||
later = _manual_record(_OTHER_DRAFT, "2026-10-18")
|
||||
|
||||
ingested = ingest_manual_records(log_file, [mine, later], today=_TOMORROW)
|
||||
|
||||
assert ingested == [mine[0]]
|
||||
assert _days(log_file) == {_TOMORROW: 1}
|
||||
|
||||
def test_other_pending_records_hold_slots_against_a_due_one(
|
||||
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
# Three records inside one 7-day window: whichever comes due while the
|
||||
# other two are still pending would be the third, so it is refused.
|
||||
log_file = tmp_path / "log.json"
|
||||
due = _manual_record(_TT_DRAFT, _TOMORROW)
|
||||
pending = [
|
||||
_manual_record(_OTHER_DRAFT, "2026-10-18"),
|
||||
_manual_record(
|
||||
_OTHER_DRAFT.__class__(
|
||||
**{
|
||||
**_OTHER_DRAFT.__dict__,
|
||||
"start_time": "11:00",
|
||||
"end_time": "12:00",
|
||||
}
|
||||
),
|
||||
"2026-10-19",
|
||||
),
|
||||
]
|
||||
with caplog.at_level(logging.INFO):
|
||||
ingested = ingest_manual_records(log_file, [due, *pending], today=_TOMORROW)
|
||||
assert ingested == []
|
||||
assert "budget exhausted" in caplog.text
|
||||
|
||||
def test_a_logged_week_blocks_a_due_record_inside_it(self, tmp_path: Path) -> None:
|
||||
log_file = tmp_path / "log.json"
|
||||
for day, draft in (("2026-10-12", _TT_DRAFT), ("2026-10-13", _OTHER_DRAFT)):
|
||||
assert ingest_manual_records(
|
||||
log_file, [_manual_record(draft, day)], today=day
|
||||
)
|
||||
blocked = _manual_record(_TT_DRAFT, _TODAY)
|
||||
assert ingest_manual_records(log_file, [blocked], today=_TODAY) == []
|
||||
assert _days(log_file) == {"2026-10-12": 1, "2026-10-13": 1}
|
||||
@ -91,7 +91,7 @@ class TestIngestManualRecordsCallback:
|
||||
log_file = tmp_path / "log.json"
|
||||
record = _manual_record(_TT_DRAFT)
|
||||
calls: list[tuple[dict, list[dict]]] = []
|
||||
with patch.object(_manual_sync, "is_budget_exhausted", return_value=True):
|
||||
with patch.object(_manual_sync, "budget_error_for_date", return_value="full"):
|
||||
ingest_manual_records(
|
||||
log_file,
|
||||
[record],
|
||||
|
||||
155
screen_locker/tests/test_manual_workout_date.py
Normal file
155
screen_locker/tests/test_manual_workout_date.py
Normal file
@ -0,0 +1,155 @@
|
||||
"""Tests for the workout-date field and the future-dated submit path."""
|
||||
# pylint: disable=protected-access
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._manual_schedule import ScheduleResult
|
||||
from screen_locker.tests import test_manual_workout_dialog as dialog_tests
|
||||
from screen_locker.tests.conftest import create_locker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_MOD = "screen_locker._manual_workout_date"
|
||||
|
||||
|
||||
def _plus(days: int) -> str:
|
||||
"""Return the local ISO date ``days`` from today."""
|
||||
return (date.fromisoformat(today_str()) + timedelta(days=days)).isoformat()
|
||||
|
||||
|
||||
def _locker(mock_tk: MagicMock, tmp_path: Path, day: str) -> MagicMock:
|
||||
"""A locker whose form already holds ``day`` in its date variable."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker._mw_vars = {"date": MagicMock()}
|
||||
locker._mw_vars["date"].get.return_value = day
|
||||
locker._mw_error_label = MagicMock()
|
||||
locker._show_manual_workout_scheduled = MagicMock()
|
||||
return locker
|
||||
|
||||
|
||||
class TestBudgetClosed:
|
||||
"""The button gate reads the local ledger only (no network)."""
|
||||
|
||||
def test_open_with_an_empty_log(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
assert locker._mw_budget_closed() is False
|
||||
|
||||
|
||||
class TestDateInRow:
|
||||
"""The date entry rides in the sport row, prefilled with today."""
|
||||
|
||||
def test_prefills_today_and_registers_the_var(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
locker._mw_vars = {}
|
||||
locker._mw_date_in_row(MagicMock())
|
||||
assert locker._mw_vars["date"] is mock_tk.StringVar.return_value
|
||||
assert mock_tk.StringVar.call_args.kwargs["value"] == today_str()
|
||||
|
||||
|
||||
class TestHandledByDate:
|
||||
"""Date and budget rules applied at submit."""
|
||||
|
||||
def test_a_garbled_date_shows_the_error(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = _locker(mock_tk, tmp_path, "soon")
|
||||
assert locker._mw_handled_by_date(MagicMock()) is True
|
||||
locker._mw_error_label.config.assert_called_once()
|
||||
locker._show_manual_workout_scheduled.assert_not_called()
|
||||
|
||||
def test_a_past_date_shows_the_error(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = _locker(mock_tk, tmp_path, _plus(-1))
|
||||
assert locker._mw_handled_by_date(MagicMock()) is True
|
||||
assert "past" in locker._mw_error_label.config.call_args.kwargs["text"]
|
||||
|
||||
def test_today_over_budget_shows_the_error(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = _locker(mock_tk, tmp_path, today_str())
|
||||
with patch(f"{_MOD}.budget_error", return_value="budget full"):
|
||||
assert locker._mw_handled_by_date(MagicMock()) is True
|
||||
locker._mw_error_label.config.assert_called_once_with(text="budget full")
|
||||
|
||||
def test_today_within_budget_is_left_to_the_host(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = _locker(mock_tk, tmp_path, today_str())
|
||||
with patch(f"{_MOD}.budget_error", return_value=None):
|
||||
assert locker._mw_handled_by_date(MagicMock()) is False
|
||||
locker._mw_error_label.config.assert_not_called()
|
||||
|
||||
def test_a_refused_future_entry_shows_why(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = _locker(mock_tk, tmp_path, _plus(2))
|
||||
refused = ScheduleResult(scheduled=False, record_id="r", reason="no room")
|
||||
with patch(f"{_MOD}.schedule_future_workout", return_value=refused):
|
||||
assert locker._mw_handled_by_date(MagicMock()) is True
|
||||
locker._mw_error_label.config.assert_called_once_with(text="no room")
|
||||
locker._show_manual_workout_scheduled.assert_not_called()
|
||||
|
||||
def test_a_scheduled_future_entry_shows_the_confirmation(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = _locker(mock_tk, tmp_path, _plus(2))
|
||||
draft = MagicMock()
|
||||
done = ScheduleResult(scheduled=True, record_id="r", reason="scheduled")
|
||||
with patch(f"{_MOD}.schedule_future_workout", return_value=done) as schedule:
|
||||
assert locker._mw_handled_by_date(draft) is True
|
||||
schedule.assert_called_once_with(locker.log_file, draft, _plus(2))
|
||||
locker._show_manual_workout_scheduled.assert_called_once_with("scheduled")
|
||||
locker._mw_error_label.config.assert_not_called()
|
||||
|
||||
|
||||
class TestScheduledConfirmation:
|
||||
"""The confirmation must go BACK, never through the unlocking save hook."""
|
||||
|
||||
def test_ok_returns_via_the_cancelled_hook_and_never_unlocks(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
saved = MagicMock()
|
||||
cancelled = MagicMock()
|
||||
object.__setattr__(locker, "_on_manual_workout_saved", saved)
|
||||
object.__setattr__(locker, "_on_manual_workout_cancelled", cancelled)
|
||||
mock_tk.Button.reset_mock()
|
||||
|
||||
locker._show_manual_workout_scheduled("scheduled for tomorrow")
|
||||
|
||||
buttons = {
|
||||
c.kwargs.get("text"): c.kwargs for c in mock_tk.Button.call_args_list
|
||||
}
|
||||
assert set(buttons) == {"OK"}
|
||||
buttons["OK"]["command"]()
|
||||
cancelled.assert_called_once_with()
|
||||
saved.assert_not_called()
|
||||
texts = [c.kwargs.get("text", "") for c in mock_tk.Label.call_args_list]
|
||||
assert any("Workout Scheduled" in t for t in texts)
|
||||
assert any("scheduled for tomorrow" in t for t in texts)
|
||||
|
||||
|
||||
class TestSubmitRoutesThroughTheDateRules:
|
||||
"""The dialog's submit stops when the date rules handled the entry."""
|
||||
|
||||
def test_a_handled_entry_never_reaches_the_host_save_hook(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = dialog_tests.TestSubmitManualWorkoutForm()._setup_locker(
|
||||
mock_tk, tmp_path
|
||||
)
|
||||
locker._mw_handled_by_date = MagicMock(return_value=True)
|
||||
locker._submit_manual_workout_form()
|
||||
locker._mw_handled_by_date.assert_called_once()
|
||||
locker._on_manual_workout_saved.assert_not_called()
|
||||
@ -7,11 +7,14 @@ from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker.tests.conftest import create_locker
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_CLOSED = "screen_locker._manual_workout_date.budget_closed_for_all_days"
|
||||
|
||||
|
||||
class TestShowManualWorkoutForm:
|
||||
"""Tests for _show_manual_workout_form."""
|
||||
@ -20,7 +23,7 @@ class TestShowManualWorkoutForm:
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with patch.object(_manual_workout, "is_budget_exhausted", return_value=False):
|
||||
with patch(_CLOSED, return_value=False):
|
||||
locker._show_manual_workout_form()
|
||||
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
|
||||
assert "SUBMIT" in button_texts
|
||||
@ -30,7 +33,7 @@ class TestShowManualWorkoutForm:
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with patch.object(_manual_workout, "is_budget_exhausted", return_value=True):
|
||||
with patch(_CLOSED, return_value=True):
|
||||
locker._show_manual_workout_form()
|
||||
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
|
||||
assert "BACK" in button_texts
|
||||
@ -111,6 +114,7 @@ class TestSubmitManualWorkoutForm:
|
||||
fields: dict[str, object] | None = None,
|
||||
) -> object:
|
||||
defaults: dict[str, object] = {
|
||||
"date": today_str(),
|
||||
"start_time": "12:00",
|
||||
"end_time": "14:00",
|
||||
"location_name": "Osrodek Solec",
|
||||
@ -152,6 +156,7 @@ class TestSubmitManualWorkoutForm:
|
||||
"balls",
|
||||
"activity_type_other",
|
||||
"equipment",
|
||||
"date",
|
||||
):
|
||||
var = MagicMock()
|
||||
var.get.return_value = defaults.get(key, "")
|
||||
@ -236,7 +241,7 @@ class TestInitialKeyboardFocus:
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with patch.object(_manual_workout, "is_budget_exhausted", return_value=False):
|
||||
with patch(_CLOSED, return_value=False):
|
||||
locker._show_manual_workout_form()
|
||||
focused = mock_tk.Entry.return_value.focus_set.call_count
|
||||
assert focused == 1, f"expected exactly one focused entry, got {focused}"
|
||||
|
||||
@ -7,7 +7,6 @@ import pathlib
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker.tests.conftest import create_locker
|
||||
|
||||
# The Dart mirror of the budget caps; read at test time so drift on
|
||||
@ -24,6 +23,8 @@ DART_MANUAL_WORKOUT = (
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_CLOSED = "screen_locker._manual_workout_date.budget_closed_for_all_days"
|
||||
|
||||
|
||||
class TestShowRetryAndManualWorkoutBudget:
|
||||
"""Tests for the "Log Manual Workout" button in _show_retry_and_sick."""
|
||||
@ -34,7 +35,7 @@ class TestShowRetryAndManualWorkoutBudget:
|
||||
"""Shows button when budget available."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with (
|
||||
patch.object(_manual_workout, "is_budget_exhausted", return_value=False),
|
||||
patch(_CLOSED, return_value=False),
|
||||
):
|
||||
locker._show_retry_and_sick("nope")
|
||||
button_texts = {c.kwargs.get("text") for c in mock_tk.Button.call_args_list}
|
||||
@ -46,7 +47,7 @@ class TestShowRetryAndManualWorkoutBudget:
|
||||
"""Hides button when budget exhausted."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
with (
|
||||
patch.object(_manual_workout, "is_budget_exhausted", return_value=True),
|
||||
patch(_CLOSED, return_value=True),
|
||||
):
|
||||
locker._show_retry_and_sick("nope")
|
||||
button_texts: set[str] = set()
|
||||
|
||||
@ -6,7 +6,6 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from screen_locker import _manual_workout
|
||||
from screen_locker._workout_credit import WorkoutCreditResult
|
||||
from screen_locker.tests._status_view_helpers import (
|
||||
_button_texts,
|
||||
@ -18,6 +17,8 @@ from screen_locker.tests._status_view_helpers import (
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_CLOSED = "screen_locker._manual_workout_date.budget_closed_for_all_days"
|
||||
|
||||
|
||||
class TestSectionManualWorkoutBudget:
|
||||
"""Tests for StatusWindow._section_manual_workout_budget."""
|
||||
@ -59,7 +60,7 @@ class TestManualWorkoutButtonVisibility:
|
||||
def test_hidden_when_budget_exhausted(
|
||||
self, mock_tk: MagicMock, temp_log_file: Path
|
||||
) -> None:
|
||||
with patch.object(_manual_workout, "is_budget_exhausted", return_value=True):
|
||||
with patch(_CLOSED, return_value=True):
|
||||
_make_window(mock_tk, _snapshot(), log_file=temp_log_file)
|
||||
assert "Log Manual Workout" not in _button_texts(mock_tk)
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user