mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-28 03:49:13 +01:00
Compare commits
3 Commits
0b0a18e81c
...
8ba9ee93fa
| Author | SHA1 | Date | |
|---|---|---|---|
| 8ba9ee93fa | |||
| e12b840f8c | |||
| 1a305c0627 |
@ -138,7 +138,7 @@ repos:
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.11.0#subdirectory=earned_time
|
||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays
|
||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.1.0#subdirectory=sickdays
|
||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.2.0#subdirectory=sickdays
|
||||
- mcp>=2,<3
|
||||
- pydantic
|
||||
- id: pylint
|
||||
@ -160,7 +160,7 @@ repos:
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.11.0#subdirectory=earned_time
|
||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays
|
||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.1.0#subdirectory=sickdays
|
||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.2.0#subdirectory=sickdays
|
||||
- mcp>=2,<3
|
||||
- pydantic
|
||||
|
||||
|
||||
@ -57,7 +57,10 @@ constant, not the state file: the file once persisted `base_*_hour`, which
|
||||
made the code's default dead.
|
||||
|
||||
A sick day is a date in the shared `sickdays` pool, read only through
|
||||
`_sick.py`. The reset resolves it with `earned_time.resolve(..., sick=True)`
|
||||
`_sick.py`. It may keep lockers: the workout lock asks
|
||||
`_sick.stands_down_workout` (keep-aware), while everything that only computes
|
||||
shutdown (this floor, `_grace_floor`, `_shutdown_base`, `_shutdown_target`,
|
||||
the preview scripts) asks `is_sick` and ignores keep. The reset resolves it with `earned_time.resolve(..., sick=True)`
|
||||
(shutdown >= 20:00) and saves the lift above the earned sum like the grace
|
||||
lift; a day marked after the reset is lifted by `_sick_floor` on the next
|
||||
live pass. Both are floors, never terms: later credits are paid out of the
|
||||
|
||||
@ -19,6 +19,13 @@ and is paid out of that lift first, so it lands on the ladder value (e.g.
|
||||
20:40), never 20:00 plus its whole reward. `install.sh` migrates the old
|
||||
`sick_history.json` dates into the pool once (`scripts/migrate_sick_history.py`).
|
||||
|
||||
A sick day may *keep* lockers (`sickdays add --keep workout`). A kept workout
|
||||
lock behaves exactly as on a normal day (lock, quota, relaxed-day penalty on
|
||||
that date); only the 20:00 shutdown floor still applies, since it belongs to
|
||||
the day, not to a locker. The one-tap button keeps nothing. The missed-alarm
|
||||
penalty is void on its ring day only if `alarm` is off, and on its penalty day
|
||||
only if `workout` is off. All of it goes through `_sick.stands_down_workout`.
|
||||
|
||||
## Shutdown time
|
||||
|
||||
Every day starts at **19:00** from 2026-10-01, 20:00 before it (`base_minutes()` in
|
||||
|
||||
@ -11,7 +11,7 @@ dependencies = [
|
||||
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync",
|
||||
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays",
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.11.0#subdirectory=earned_time",
|
||||
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.1.0#subdirectory=sickdays",
|
||||
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.2.0#subdirectory=sickdays",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
|
||||
@ -21,7 +21,7 @@ pytest-xdist==3.8.0
|
||||
# module imports it itself, so it is declared rather than assumed.
|
||||
requests==2.34.2
|
||||
ruff==0.17.1
|
||||
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.1.0#subdirectory=sickdays
|
||||
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.2.0#subdirectory=sickdays
|
||||
types-requests==2.33.0.20261006
|
||||
# Direct dependency since the Firebase session stream (_session_stream) catches
|
||||
# urllib3's own errors on the long-lived SSE read; requests pulls it in, but
|
||||
|
||||
@ -25,7 +25,7 @@ import sys
|
||||
from screen_locker._decision_log import LockDecision, record_decision
|
||||
from screen_locker._decision_reasons import reasons_extra
|
||||
from screen_locker._morning_session import has_workout_skip_today
|
||||
from screen_locker._sick import is_sick
|
||||
from screen_locker._sick import stands_down_workout
|
||||
from screen_locker._weekly_check import has_weekly_minimum, is_relaxed_day
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
@ -83,8 +83,11 @@ class AutoUpgradeMixin(_ReasonsMixin):
|
||||
"""
|
||||
|
||||
def _is_sick_day_today(self) -> bool:
|
||||
"""Whether today is a date in the shared sickdays pool."""
|
||||
return is_sick()
|
||||
"""Whether the sickdays pool switches the workout lock off today.
|
||||
|
||||
A sick day that keeps the workout locker is a normal day here.
|
||||
"""
|
||||
return stands_down_workout()
|
||||
|
||||
def _check_early_exits(self) -> None:
|
||||
"""Check startup conditions and exit early when appropriate."""
|
||||
@ -121,7 +124,7 @@ class AutoUpgradeMixin(_ReasonsMixin):
|
||||
elif self._is_sick_day_today():
|
||||
_skip(
|
||||
"sick_day",
|
||||
"Today is a sick day (sickdays pool).",
|
||||
"Today is a sick day (sickdays pool); the workout lock is off.",
|
||||
**self._other_conditions("sick_day"),
|
||||
)
|
||||
elif self.has_logged_today():
|
||||
|
||||
@ -23,7 +23,7 @@ from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
|
||||
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._sick import is_sick
|
||||
from screen_locker._sick import stands_down_workout
|
||||
from screen_locker._weekly_check import RELAXED_DAY_SKIP_TYPE
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@ -128,9 +128,10 @@ def is_early_bird_pending(pending_file: Path, *, today: str | None = None) -> bo
|
||||
|
||||
|
||||
def is_sick_day_today(today: date | None = None) -> bool:
|
||||
"""Return True if ``today`` (default: today) is in the sickdays pool.
|
||||
"""Return True if the sickdays pool switches the workout lock off that day.
|
||||
|
||||
Kept here so callers of the status layer have one predicate module to
|
||||
import from; the answer itself is ``_sick.is_sick``'s.
|
||||
import from; the answer itself is ``_sick.stands_down_workout``'s, so a
|
||||
sick day that keeps the workout locker reads False.
|
||||
"""
|
||||
return is_sick(today)
|
||||
return stands_down_workout(today)
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -137,8 +137,9 @@ def get_flags() -> dict[str, bool]:
|
||||
(``~/src/utils/freedays``), so a true here also means diet-guard, wake-alarm,
|
||||
leetcode-guard and home-guard are standing down today.
|
||||
|
||||
``is_sick_day_today`` reads the shared ``sickdays`` pool (the same fleet-wide
|
||||
answer every gate stands down on), never a screen-locker file.
|
||||
``is_sick_day_today`` reads the shared ``sickdays`` pool and answers "is the
|
||||
workout lock switched off today": a sick day that keeps the ``workout``
|
||||
locker reads False. Never a screen-locker file.
|
||||
"""
|
||||
return {
|
||||
"has_logged_today": has_logged_today(_LOG_FILE),
|
||||
|
||||
@ -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]]
|
||||
|
||||
@ -7,6 +7,15 @@ them and tests have one seam.
|
||||
|
||||
Reading never raises: an unreadable pool is logged by ``sickdays`` and reads
|
||||
as *not sick* -- fail closed, the locks apply.
|
||||
|
||||
Two questions, deliberately not one: a sick day may *keep* some lockers active
|
||||
(``sickdays`` 0.2.0), so
|
||||
|
||||
* :func:`stands_down_workout` -- "is the workout lock off?" -- is sick AND the
|
||||
workout locker not kept. The lock ladder, its explanation, the status view
|
||||
and the missed-alarm penalty's penalised day ask this.
|
||||
* :func:`is_sick` -- "is the day sick at all?" -- feeds only the 20:00
|
||||
shutdown floor, which applies on every sick day whatever it keeps.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -29,11 +38,34 @@ def is_sick(day: date | None = None) -> bool:
|
||||
return sickdays.is_sick_day(day)
|
||||
|
||||
|
||||
def stands_down(locker: str, day: date | None = None) -> bool:
|
||||
"""Whether ``locker`` (a ``sickdays.LOCKER_*``) is off on ``day``.
|
||||
|
||||
For the few consumers that judge a date by a locker other than the workout
|
||||
one (the missed-alarm penalty's ring day is the alarm switch's).
|
||||
"""
|
||||
return sickdays.stands_down(locker, day)
|
||||
|
||||
|
||||
def stands_down_workout(day: date | None = None) -> bool:
|
||||
"""Whether the workout lock is off on ``day`` (default: today).
|
||||
|
||||
True iff the day is sick and does not keep ``sickdays.LOCKER_WORKOUT``.
|
||||
A kept workout lock behaves exactly as on a normal day.
|
||||
"""
|
||||
return stands_down(sickdays.LOCKER_WORKOUT, day)
|
||||
|
||||
|
||||
def sick_dates() -> frozenset[date]:
|
||||
"""Every date the pool marks sick, past and future."""
|
||||
return sickdays.sick_days()
|
||||
|
||||
|
||||
def workout_standdown_dates() -> frozenset[date]:
|
||||
"""Every sick date on which the workout lock is off (keep-aware)."""
|
||||
return frozenset(d for d in sickdays.sick_days() if stands_down_workout(d))
|
||||
|
||||
|
||||
def push_in_background() -> threading.Thread:
|
||||
"""Start one best-effort ``sickdays.sync_quietly`` on a background thread.
|
||||
|
||||
|
||||
@ -16,7 +16,7 @@ from screen_locker._extra_benefits import (
|
||||
has_extended_early_bird,
|
||||
)
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._sick import sick_dates
|
||||
from screen_locker._sick import workout_standdown_dates
|
||||
from screen_locker._weekly_check import (
|
||||
COUNTED_WORKOUT_TYPES,
|
||||
WEEKLY_WORKOUT_MINIMUM,
|
||||
@ -77,7 +77,7 @@ def run_status(locker: ScreenLocker) -> None:
|
||||
monday = today - timedelta(days=today.weekday())
|
||||
log_file: Path = locker.log_file
|
||||
log_data = load_workout_log(log_file)
|
||||
sick_days = sick_dates()
|
||||
sick_days = workout_standdown_dates()
|
||||
|
||||
print("=== Weekly Workout Status ===")
|
||||
|
||||
|
||||
@ -51,7 +51,7 @@ from screen_locker._extra_benefits import (
|
||||
)
|
||||
from screen_locker._log_io import load_workout_log
|
||||
from screen_locker._morning_session import has_workout_skip_today
|
||||
from screen_locker._sick import sick_dates
|
||||
from screen_locker._sick import workout_standdown_dates
|
||||
from screen_locker._weekly_check import (
|
||||
COUNTED_WORKOUT_TYPES,
|
||||
WEEKLY_WORKOUT_MINIMUM,
|
||||
@ -102,7 +102,7 @@ def _day_status(
|
||||
def _week_days(log_file: Path, *, today_local: datetime) -> tuple[DayStatus, ...]:
|
||||
"""Return this ISO week's days from Monday through today."""
|
||||
log_data = load_workout_log(log_file)
|
||||
sick_days = sick_dates()
|
||||
sick_days = workout_standdown_dates()
|
||||
today_date = today_local.date()
|
||||
monday = today_date - timedelta(days=today_date.weekday())
|
||||
days: list[DayStatus] = []
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -8,9 +8,13 @@ here is *HMAC ok, dated today*. Anything else -- missing file, stale date,
|
||||
bad signature -- is "no penalty", i.e. today's ordinary relaxed-day rule.
|
||||
|
||||
The file is void when EITHER its ``issued_date`` (the day of the missed
|
||||
ring) OR its ``penalty_date`` is a sick day (``sickdays``): a sick day stands
|
||||
every gate down, and wake-alarm's own retraction of the file can lag its
|
||||
sync by ~15 min, so it is not relied on here.
|
||||
ring) belongs to a sick day whose ``alarm`` switch is off, OR its
|
||||
``penalty_date`` belongs to a sick day whose ``workout`` lock is off
|
||||
(``sickdays``). Each date is judged by what it owns: the ring is the alarm's,
|
||||
and the penalty it costs -- the relaxed-day leniency -- is the workout lock's.
|
||||
A sick day that keeps that locker leaves its half of the penalty in force.
|
||||
Wake-alarm's own retraction of the file can lag its sync by ~15 min, so it
|
||||
is not relied on here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -21,10 +25,11 @@ import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock.log_integrity import verify_entry_hmac
|
||||
import sickdays
|
||||
|
||||
from screen_locker._constants import WORKDAY_PENALTY_FILE
|
||||
from screen_locker._day import today_str
|
||||
from screen_locker._sick import is_sick
|
||||
from screen_locker._sick import stands_down
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import datetime
|
||||
@ -53,15 +58,20 @@ def workday_penalty_today(now: datetime | None = None) -> bool:
|
||||
entry = _read_verified()
|
||||
if entry is None or entry.get("penalty_date") != today_str(now):
|
||||
return False
|
||||
for field in ("issued_date", "penalty_date"):
|
||||
if _is_sick_iso(entry.get(field)):
|
||||
_logger.warning("Workday penalty void: its %s is a sick day", field)
|
||||
for field, locker in (
|
||||
("issued_date", sickdays.LOCKER_ALARM),
|
||||
("penalty_date", sickdays.LOCKER_WORKOUT),
|
||||
):
|
||||
if _stands_down_iso(entry.get(field), locker):
|
||||
_logger.warning(
|
||||
"Workday penalty void: its %s is a sick day with %s off", field, locker
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _is_sick_iso(value: object) -> bool:
|
||||
"""Whether ``value`` is a ``YYYY-MM-DD`` that the sickdays pool marks sick."""
|
||||
def _stands_down_iso(value: object, locker: str) -> bool:
|
||||
"""Whether ``value`` is a ``YYYY-MM-DD`` on which ``locker`` is switched off."""
|
||||
if value is None:
|
||||
return False # an older file without issued_date: penalty_date rules
|
||||
try:
|
||||
@ -69,4 +79,4 @@ def _is_sick_iso(value: object) -> bool:
|
||||
except ValueError:
|
||||
_logger.warning("Workday penalty: %r is not a date; not a sick day", value)
|
||||
return False
|
||||
return is_sick(day)
|
||||
return stands_down(locker, day)
|
||||
|
||||
@ -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/.
|
||||
|
||||
@ -18,6 +18,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
@ -62,10 +63,15 @@ def _no_sick_days_by_default(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) ->
|
||||
background push never reaches Firebase.
|
||||
"""
|
||||
import sickdays
|
||||
import sickdays._api
|
||||
|
||||
pool = sickdays.Paths.under(tmp_path / "sickdays")
|
||||
monkeypatch.setattr(sickdays._api, "resolve_paths", lambda paths: paths or pool)
|
||||
# Every sickdays module that bound ``resolve_paths`` by name: the readers
|
||||
# (``_api``, which ``stands_down`` / ``kept_lockers`` load through) and the
|
||||
# writers (``set_kept_lockers`` lives in ``_keep_api``). Patching only
|
||||
# ``_api`` once let a keep edit land in the developer's real pool.
|
||||
for name, module in list(sys.modules.items()):
|
||||
if name.startswith("sickdays.") and hasattr(module, "resolve_paths"):
|
||||
monkeypatch.setattr(module, "resolve_paths", lambda paths: paths or pool)
|
||||
monkeypatch.setattr(sickdays, "sync_quietly", lambda **_kw: False)
|
||||
|
||||
|
||||
|
||||
@ -8,17 +8,31 @@ that accepts any date, so a test can mark a fixed past day as well as today.
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import sickdays
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable
|
||||
|
||||
def mark_sick(day: date | str | None = None) -> date:
|
||||
"""Mark ``day`` (default: today, local) sick and return it."""
|
||||
|
||||
def mark_sick(day: date | str | None = None, *, keep: Iterable[str] = ()) -> date:
|
||||
"""Mark ``day`` (default: today, local) sick and return it.
|
||||
|
||||
``keep`` names the lockers (``sickdays.LOCKER_*``) the day keeps active;
|
||||
the default keeps none, i.e. every locker stands down, like the lock
|
||||
screen's one-tap button.
|
||||
"""
|
||||
if day is None:
|
||||
target = sickdays.today()
|
||||
elif isinstance(day, str):
|
||||
target = date.fromisoformat(day)
|
||||
else:
|
||||
target = day
|
||||
sickdays.import_legacy([target])
|
||||
if keep:
|
||||
# ``now=target`` makes a past day "today", so a kept past day can be
|
||||
# written; import_legacy cannot carry a keep set.
|
||||
sickdays.add_sick_day(target, keep=keep, is_free=lambda _day: False, now=target)
|
||||
else:
|
||||
sickdays.import_legacy([target])
|
||||
return target
|
||||
|
||||
@ -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}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -8,6 +8,7 @@ from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
import freedays
|
||||
import sickdays
|
||||
|
||||
from screen_locker._compliance_state import explain_lock_decision
|
||||
from screen_locker.tests._sick_helpers import mark_sick
|
||||
@ -100,6 +101,21 @@ class TestExplainLockDecision:
|
||||
assert result.fired is False
|
||||
assert result.stage == "sick_day"
|
||||
|
||||
def test_a_sick_day_that_keeps_the_workout_lock_does_not_skip(
|
||||
self, tmp_path: Path
|
||||
) -> None:
|
||||
files = self._files(tmp_path)
|
||||
mark_sick(keep=[sickdays.LOCKER_WORKOUT])
|
||||
result = explain_lock_decision(
|
||||
**files,
|
||||
weekly_minimum_met=False,
|
||||
relaxed_day=False,
|
||||
now=datetime.now(tz=UTC).astimezone().replace(hour=12, minute=0),
|
||||
)
|
||||
assert result.stage == "would_lock"
|
||||
sick_step = next(t for t in result.trace if t.name == "sick_day")
|
||||
assert sick_step.fired is False
|
||||
|
||||
def test_already_logged_skips(self, tmp_path: Path) -> None:
|
||||
files = self._files(tmp_path)
|
||||
files["log_file"].write_text(json.dumps({_today(): {"hmac": "sig"}}))
|
||||
|
||||
@ -11,6 +11,7 @@ from unittest.mock import patch
|
||||
|
||||
import earned_time
|
||||
import pytest
|
||||
import sickdays
|
||||
|
||||
from screen_locker import _earned, _grace_floor
|
||||
from screen_locker._grace_floor import (
|
||||
@ -193,6 +194,13 @@ class TestApply:
|
||||
assert "failed to write" in caplog.text
|
||||
assert plan_absorb(0) == (0, 0)
|
||||
|
||||
def test_a_sick_day_that_keeps_the_workout_lock_still_has_no_floor(self) -> None:
|
||||
"""The sick floor is shutdown's, so keep does not bring the grace floor back."""
|
||||
mark_sick(_DAY, keep=[sickdays.LOCKER_WORKOUT])
|
||||
host = Host((18 * 60, 18 * 60, 300))
|
||||
assert host._apply_grace_floor(None, first_done=at("18:55")) is False
|
||||
assert host.config == (18 * 60, 18 * 60, 300)
|
||||
|
||||
def test_a_sick_day_has_no_floor(self) -> None:
|
||||
"""A sick day has the 20:00 sick floor instead."""
|
||||
mark_sick(_DAY)
|
||||
|
||||
@ -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)
|
||||
|
||||
|
||||
@ -8,15 +8,19 @@ from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
import earned_time
|
||||
import sickdays
|
||||
|
||||
from screen_locker import _grace_floor
|
||||
from screen_locker._shutdown_base import base_minutes
|
||||
from screen_locker._shutdown_target import (
|
||||
DayInputs,
|
||||
day_credit_count,
|
||||
derive,
|
||||
gather,
|
||||
gather_inputs,
|
||||
workout_units,
|
||||
)
|
||||
from screen_locker.tests._sick_helpers import mark_sick
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
@ -67,6 +71,19 @@ class TestTarget:
|
||||
assert target.minutes > SICK_FLOOR
|
||||
assert target.lift == 0
|
||||
|
||||
def test_gather_keeps_the_sick_floor_when_the_workout_lock_is_kept(self) -> None:
|
||||
"""Rule 2: the 20:00 floor is the day's, whatever the keep set says."""
|
||||
mark_sick(_DAY, keep=[sickdays.LOCKER_WORKOUT])
|
||||
assert gather_inputs(_DAY, None).sick_day is True
|
||||
|
||||
def test_base_minutes_keeps_the_sick_floor_when_the_workout_lock_is_kept(
|
||||
self,
|
||||
) -> None:
|
||||
plain = base_minutes(_DAY)
|
||||
assert plain < SICK_FLOOR # reading's cut is in force on this date
|
||||
mark_sick(_DAY, keep=[sickdays.LOCKER_WORKOUT])
|
||||
assert base_minutes(_DAY) == SICK_FLOOR
|
||||
|
||||
def test_not_sick_is_the_plain_sum(self) -> None:
|
||||
target = derive(DayInputs(_DAY, _FLAT))
|
||||
assert target.resolution.sick is False
|
||||
|
||||
@ -11,6 +11,8 @@ import freedays
|
||||
import sickdays
|
||||
|
||||
from screen_locker import _sick, _ui_flows_sick
|
||||
from screen_locker._auto_upgrade import AutoUpgradeMixin
|
||||
from screen_locker._compliance_predicates import is_sick_day_today
|
||||
from screen_locker.tests._locker_factories import create_locker_relaxed_day
|
||||
from screen_locker.tests._sick_helpers import mark_sick
|
||||
from screen_locker.tests.conftest import create_locker
|
||||
@ -36,11 +38,59 @@ class TestSeam:
|
||||
assert _sick.is_sick(day - timedelta(days=1)) is False
|
||||
assert _sick.sick_dates() >= {day, old}
|
||||
|
||||
def test_stands_down_workout_follows_the_keep_set(self) -> None:
|
||||
day = mark_sick(keep=[sickdays.LOCKER_WORKOUT])
|
||||
other = mark_sick(day + timedelta(days=1), keep=[sickdays.LOCKER_LEETCODE])
|
||||
assert _sick.stands_down_workout(day) is False
|
||||
assert _sick.stands_down_workout(other) is True
|
||||
assert _sick.stands_down_workout(other + timedelta(days=1)) is False
|
||||
# The shutdown floor ignores keep: the day is sick either way.
|
||||
assert _sick.is_sick(day) is True
|
||||
|
||||
def test_stands_down_workout_defaults_to_today(self) -> None:
|
||||
assert _sick.stands_down_workout() is False
|
||||
mark_sick()
|
||||
assert _sick.stands_down_workout() is True
|
||||
|
||||
def test_workout_standdown_dates_drop_the_kept_days(self) -> None:
|
||||
kept = mark_sick("2026-06-21", keep=[sickdays.LOCKER_WORKOUT])
|
||||
off = mark_sick("2026-07-24")
|
||||
assert _sick.workout_standdown_dates() >= {off}
|
||||
assert kept not in _sick.workout_standdown_dates()
|
||||
assert _sick.sick_dates() >= {kept, off}
|
||||
|
||||
def test_the_startup_ladder_asks_the_workout_switch(self) -> None:
|
||||
"""``_is_sick_day_today`` is what the lock skip reads: keep-aware."""
|
||||
mark_sick(keep=[sickdays.LOCKER_WORKOUT])
|
||||
assert AutoUpgradeMixin._is_sick_day_today(MagicMock()) is False
|
||||
sickdays.set_kept_lockers(sickdays.today(), [sickdays.LOCKER_BOOK])
|
||||
assert AutoUpgradeMixin._is_sick_day_today(MagicMock()) is True
|
||||
|
||||
def test_the_pool_fixture_covers_keep_edits(self) -> None:
|
||||
"""``set_kept_lockers`` must land in the tmp pool, never the real one."""
|
||||
day = mark_sick()
|
||||
sickdays.set_kept_lockers(day, [sickdays.LOCKER_DIET])
|
||||
assert sickdays.kept_lockers(day) == {sickdays.LOCKER_DIET}
|
||||
|
||||
def test_the_status_predicate_follows_the_workout_switch(self) -> None:
|
||||
mark_sick(keep=[sickdays.LOCKER_WORKOUT])
|
||||
assert is_sick_day_today() is False
|
||||
sickdays.set_kept_lockers(sickdays.today(), [sickdays.LOCKER_LEETCODE])
|
||||
assert is_sick_day_today() is True
|
||||
|
||||
def test_mark_today_sick(self) -> None:
|
||||
result = _sick.mark_today_sick()
|
||||
assert result.ok is True
|
||||
assert sickdays.is_sick_day() is True
|
||||
|
||||
def test_the_one_tap_button_keeps_nothing(self) -> None:
|
||||
"""The lock screen's "I'm sick" is ALL-OFF: every locker stands down."""
|
||||
assert _sick.mark_today_sick().ok is True
|
||||
assert sickdays.kept_lockers() == frozenset()
|
||||
for locker in sickdays.LOCKERS:
|
||||
assert sickdays.stands_down(locker) is True
|
||||
assert _sick.stands_down_workout() is True
|
||||
|
||||
def test_already_sick_is_success(self) -> None:
|
||||
mark_sick()
|
||||
result = _sick.mark_today_sick()
|
||||
|
||||
@ -14,6 +14,7 @@ from unittest.mock import patch
|
||||
|
||||
import earned_time
|
||||
import pytest
|
||||
import sickdays
|
||||
|
||||
from screen_locker import _grace_floor, _shutdown, _sick_floor
|
||||
from screen_locker._earned import first_minutes
|
||||
@ -65,6 +66,13 @@ class TestApplySickFloor:
|
||||
assert host._apply_sick_floor() is False
|
||||
assert host.config == (18 * 60, 18 * 60, 300)
|
||||
|
||||
def test_a_kept_workout_lock_does_not_lift_the_floor_away(self) -> None:
|
||||
"""The 20:00 floor is the day's, not the workout lock's: keep is moot."""
|
||||
mark_sick(_DAY, keep=[sickdays.LOCKER_WORKOUT])
|
||||
host = Host((18 * 60, 18 * 60 + 30, 300))
|
||||
assert host._apply_sick_floor() is True
|
||||
assert host.config == (_FLOOR, _FLOOR, 300)
|
||||
|
||||
def test_marked_sick_lifts_to_20_00_and_records_the_lift(self) -> None:
|
||||
mark_sick(_DAY)
|
||||
host = Host((18 * 60, 18 * 60 + 30, 300))
|
||||
|
||||
@ -13,6 +13,7 @@ from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
import freedays
|
||||
import sickdays
|
||||
|
||||
from screen_locker._status_data import format_summary_line, gather_status
|
||||
from screen_locker.tests._sick_helpers import mark_sick
|
||||
@ -46,6 +47,21 @@ class TestGatherStatusLockSuppression:
|
||||
assert snap.lock_explanation.fired is False
|
||||
assert snap.lock_explanation.stage == "sick_day"
|
||||
|
||||
def test_sick_day_keeping_the_workout_lock_still_locks(
|
||||
self, tmp_path: Path
|
||||
) -> None:
|
||||
"""A kept workout lock is a normal day: not marked sick, not skipped."""
|
||||
files = _files(tmp_path)
|
||||
mark_sick("2024-01-05", keep=[sickdays.LOCKER_WORKOUT])
|
||||
with patch(
|
||||
"screen_locker._status_data.has_workout_skip_today", return_value=False
|
||||
):
|
||||
snap = gather_status(**files, now=_FRIDAY_NOON_UTC)
|
||||
|
||||
assert snap.today.is_sick_day is False
|
||||
assert not format_summary_line(snap).endswith("· sick day")
|
||||
assert snap.lock_explanation.stage != "sick_day"
|
||||
|
||||
def test_wake_alarm_skip_stops_lock(self, tmp_path: Path) -> None:
|
||||
"""Wake alarm skip stops lock."""
|
||||
files = _files(tmp_path)
|
||||
|
||||
@ -9,6 +9,7 @@ from unittest.mock import patch
|
||||
|
||||
from gatelock.log_integrity import compute_entry_hmac
|
||||
import pytest
|
||||
import sickdays
|
||||
|
||||
from screen_locker import _workday_penalty
|
||||
from screen_locker._workday_penalty import workday_penalty_today
|
||||
@ -87,3 +88,27 @@ class TestSickDayVoidsThePenalty:
|
||||
_write({"penalty_date": "2026-09-23", "issued_date": "yesterday"})
|
||||
assert workday_penalty_today(NOW) is True
|
||||
assert "not a date" in caplog.text
|
||||
|
||||
|
||||
class TestKeptLockersDecideThePenalty:
|
||||
"""Ring date -> the alarm switch; penalty date -> the workout lock."""
|
||||
|
||||
def test_a_kept_alarm_on_the_ring_day_keeps_the_penalty(self) -> None:
|
||||
mark_sick("2026-09-22", keep=[sickdays.LOCKER_ALARM])
|
||||
_write({"penalty_date": "2026-09-23", "issued_date": "2026-09-22"})
|
||||
assert workday_penalty_today(NOW) is True
|
||||
|
||||
def test_a_kept_workout_on_the_ring_day_still_voids_it(self) -> None:
|
||||
mark_sick("2026-09-22", keep=[sickdays.LOCKER_WORKOUT])
|
||||
_write({"penalty_date": "2026-09-23", "issued_date": "2026-09-22"})
|
||||
assert workday_penalty_today(NOW) is False
|
||||
|
||||
def test_a_kept_workout_on_the_penalty_day_keeps_it(self) -> None:
|
||||
mark_sick("2026-09-23", keep=[sickdays.LOCKER_WORKOUT])
|
||||
_write({"penalty_date": "2026-09-23", "issued_date": "2026-09-22"})
|
||||
assert workday_penalty_today(NOW) is True
|
||||
|
||||
def test_a_kept_alarm_on_the_penalty_day_still_voids_it(self) -> None:
|
||||
mark_sick("2026-09-23", keep=[sickdays.LOCKER_ALARM])
|
||||
_write({"penalty_date": "2026-09-23", "issued_date": "2026-09-22"})
|
||||
assert workday_penalty_today(NOW) is False
|
||||
|
||||
@ -8,7 +8,7 @@ adb, the sudo-written config, the sickdays pool) point at a temporary place.
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, time
|
||||
import importlib
|
||||
import sys
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import earned_time
|
||||
@ -114,8 +114,11 @@ SICK_STEP = "sick"
|
||||
def use_temp_pool(tmp: Path) -> None:
|
||||
"""Point every sickdays read and write at a pool under ``tmp``."""
|
||||
pool = sickdays.Paths.under(tmp / "sickdays")
|
||||
api = importlib.import_module("sickdays._api")
|
||||
vars(api)["resolve_paths"] = lambda paths: paths or pool
|
||||
# Every sickdays module that bound ``resolve_paths`` by name: ``_api`` (the
|
||||
# reads, ``stands_down`` included) and the writers (``_keep_api``, ...).
|
||||
for name, module in tuple(sys.modules.items()):
|
||||
if name.startswith("sickdays.") and "resolve_paths" in vars(module):
|
||||
vars(module)["resolve_paths"] = lambda paths: paths or pool
|
||||
|
||||
|
||||
def sick_pool(day: date, *, sick_day: bool) -> bool:
|
||||
|
||||
@ -3,7 +3,8 @@
|
||||
// See manual_workout_validation.dart for why these are `part` files.
|
||||
part of 'manual_workout.dart';
|
||||
|
||||
/// Counts DAYS with a manual workout in the rolling 7-/30-day windows.
|
||||
/// Counts manual workouts against the rolling 7-/30-day caps, as seen from
|
||||
/// the workout date [date].
|
||||
///
|
||||
/// The budget is counted per ENTRY, not per day: each self-report consumes its
|
||||
/// own slot, so three workouts logged on one day cost three. That matches the
|
||||
@ -16,13 +17,21 @@ part of 'manual_workout.dart';
|
||||
/// its 7-day cap — but 1/2 here, and the phone kept accepting. Callers pass
|
||||
/// one payload per synced record (`manual:<date>T<HH:MM>`), so same-day
|
||||
/// workouts at different times arrive as distinct payloads.
|
||||
///
|
||||
/// Since 2026-10-16 a workout can be PLANNED up to a week ahead, so the count
|
||||
/// is no longer "the trailing window ending today". Each figure is the
|
||||
/// fullest window of that length that contains [date], counting past and
|
||||
/// future entries alike: adding an entry on [date] is only allowed if every
|
||||
/// such window stays within its cap, and the fullest one is the binding
|
||||
/// constraint. With no future entries and [date] = today this is exactly the
|
||||
/// old trailing count, since every other window holds a subset of it.
|
||||
ManualBudget countManualBudget(
|
||||
Iterable<Map<String, dynamic>> payloads,
|
||||
DateTime now,
|
||||
DateTime date,
|
||||
) {
|
||||
final today = DateTime(now.year, now.month, now.day);
|
||||
var week = 0;
|
||||
var month = 0;
|
||||
final target = _dayNumber(date);
|
||||
// Offsets (in days) of every counted entry relative to [date].
|
||||
final offsets = <int>[];
|
||||
for (final payload in payloads) {
|
||||
// Skip evidence-less `{type, kind, date}` stubs. The PC refuses to ingest
|
||||
// these ("no workout data to ingest; skipping permanently"), so counting
|
||||
@ -32,14 +41,33 @@ ManualBudget countManualBudget(
|
||||
if (payload['start_time'] is! String) continue;
|
||||
final dateStr = payload['date'];
|
||||
if (dateStr is! String) continue;
|
||||
final date = DateTime.tryParse(dateStr);
|
||||
if (date == null) continue;
|
||||
final days = today
|
||||
.difference(DateTime(date.year, date.month, date.day))
|
||||
.inDays;
|
||||
if (days < 0) continue;
|
||||
if (days < 7) week++;
|
||||
if (days < 30) month++;
|
||||
final entryDate = DateTime.tryParse(dateStr);
|
||||
if (entryDate == null) continue;
|
||||
offsets.add(_dayNumber(entryDate) - target);
|
||||
}
|
||||
return ManualBudget(week: week, month: month);
|
||||
return ManualBudget(
|
||||
week: _fullestWindow(offsets, 7),
|
||||
month: _fullestWindow(offsets, 30),
|
||||
);
|
||||
}
|
||||
|
||||
/// Days since the epoch for [day]'s calendar date.
|
||||
///
|
||||
/// Built in UTC so a DST change between two local midnights (a 23- or 25-hour
|
||||
/// "day") cannot truncate a one-day difference to zero.
|
||||
int _dayNumber(DateTime day) =>
|
||||
DateTime.utc(day.year, day.month, day.day).millisecondsSinceEpoch ~/
|
||||
Duration.millisecondsPerDay;
|
||||
|
||||
/// The most entries any [length]-day window containing offset 0 holds.
|
||||
int _fullestWindow(List<int> offsets, int length) {
|
||||
var fullest = 0;
|
||||
// A window containing day 0 starts anywhere from `length - 1` days before
|
||||
// it up to day 0 itself.
|
||||
for (var start = 1 - length; start <= 0; start++) {
|
||||
final end = start + length - 1;
|
||||
final count = offsets.where((o) => o >= start && o <= end).length;
|
||||
if (count > fullest) fullest = count;
|
||||
}
|
||||
return fullest;
|
||||
}
|
||||
|
||||
@ -22,6 +22,9 @@ String manualSyncRecordId(String date, String startTime) =>
|
||||
'manual:${date}T${startTime.trim()}';
|
||||
|
||||
/// Builds the crdt-sync [Record] for a manual workout, stamped with [hlc].
|
||||
///
|
||||
/// [date] is the WORKOUT date, which may be up to a week ahead of the day it
|
||||
/// is logged on: the PC credits a planned entry on its own date, never early.
|
||||
Record buildManualRecord(
|
||||
ManualWorkoutDraft draft,
|
||||
String date, {
|
||||
@ -33,15 +36,28 @@ Record buildManualRecord(
|
||||
);
|
||||
}
|
||||
|
||||
/// The tombstone that deletes the manual workout [recordId] on every device.
|
||||
///
|
||||
/// Carries no fields: [mergeRecord] keeps whatever payload this device's log
|
||||
/// already holds and only flips `deleted`, which is sticky. A record logged
|
||||
/// on another device gets a field-less tombstone here, and both readers
|
||||
/// (this app's and the PC's `_tombstoned_ids`) suppress across the whole
|
||||
/// device union, so that is enough. Deleting `log.json` locally instead would
|
||||
/// just be re-ingested on the next sync.
|
||||
Record buildManualTombstone(String recordId, {required Hlc hlc}) =>
|
||||
Record(id: recordId, fields: const {}, deleted: true, deletedHlc: hlc);
|
||||
|
||||
/// Manual-workout counts in the rolling 7-/30-day windows (the shared budget).
|
||||
class ManualBudget {
|
||||
/// Creates a budget snapshot.
|
||||
const ManualBudget({required this.week, required this.month});
|
||||
|
||||
/// Manual workouts in the last 7 days.
|
||||
/// Manual workouts in the fullest 7-day window containing the workout
|
||||
/// date (see [countManualBudget]).
|
||||
final int week;
|
||||
|
||||
/// Manual workouts in the last 30 days.
|
||||
/// Manual workouts in the fullest 30-day window containing the workout
|
||||
/// date.
|
||||
final int month;
|
||||
|
||||
/// Whether either window has reached its limit.
|
||||
|
||||
@ -11,6 +11,9 @@ import 'dart:math';
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:workout_app/models/manual_workout.dart';
|
||||
import 'package:workout_app/sandbox/sandbox_log.dart';
|
||||
import 'package:workout_app/services/done_today.dart';
|
||||
import 'package:workout_app/services/storage_service.dart';
|
||||
import 'package:workout_app/services/workout_sync_service.dart';
|
||||
import 'package:workout_app/ui/theme.dart';
|
||||
@ -19,6 +22,7 @@ import 'package:workout_app/widgets/calendar_widget.dart';
|
||||
part 'history_screen_charts.dart';
|
||||
part 'history_screen_data.dart';
|
||||
part 'history_screen_painter.dart';
|
||||
part 'history_screen_planned.dart';
|
||||
part 'history_screen_tiles.dart';
|
||||
|
||||
const _kTotal = 'Total (all workouts)';
|
||||
@ -35,7 +39,12 @@ class HistoryScreen extends StatefulWidget {
|
||||
/// and it asks Firebase that question directly. On a desktop that has a
|
||||
/// cached refresh token the real factory answers yes, so the guard opens and
|
||||
/// the fetch goes to the network even with the sync token faked away.
|
||||
const HistoryScreen({super.key, this.httpClient, this.firebaseFactory});
|
||||
const HistoryScreen({
|
||||
super.key,
|
||||
this.httpClient,
|
||||
this.firebaseFactory,
|
||||
this.clock,
|
||||
});
|
||||
|
||||
/// Overrides the HTTP client used to read synced workouts (tests only).
|
||||
final http.Client? httpClient;
|
||||
@ -43,21 +52,18 @@ class HistoryScreen extends StatefulWidget {
|
||||
/// Overrides how a Firebase account is discovered (tests only).
|
||||
final Future<FirebaseRestClient?> Function()? firebaseFactory;
|
||||
|
||||
/// Decides which manual entries are still PLANNED (dated after today);
|
||||
/// defaults to [DateTime.now], injected by tests.
|
||||
final DateTime Function()? clock;
|
||||
|
||||
@override
|
||||
State<HistoryScreen> createState() => _HistoryScreenState();
|
||||
}
|
||||
|
||||
/// Synced kinds this phone has no local record of, so showing them can't
|
||||
/// double up an existing session.
|
||||
///
|
||||
/// A `phone_verified` record is the PC's mirror of a StrongLifts session this
|
||||
/// phone already stores in full (and renders from `_rows`), so it is
|
||||
/// deliberately excluded — otherwise the same workout would appear twice.
|
||||
const _kSyncedOnlyKinds = {'runnerup_verified', 'manual_workout'};
|
||||
|
||||
class _HistoryScreenState extends State<HistoryScreen> {
|
||||
List<Map<String, dynamic>> _rows = [];
|
||||
List<Map<String, dynamic>> _syncedRows = [];
|
||||
List<Map<String, dynamic>> _plannedRows = [];
|
||||
bool _loading = true;
|
||||
String _selected = _kTotal;
|
||||
List<String> _exerciseNames = [];
|
||||
@ -96,11 +102,14 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
state = await StorageService.instance.getExerciseState(_selected);
|
||||
// coverage:ignore-end
|
||||
}
|
||||
final synced = _syncedOnly(remote);
|
||||
final today = dayKey((widget.clock ?? DateTime.now)());
|
||||
final synced = _syncedOnly(remote, today);
|
||||
final planned = _plannedOnly(remote, today);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_rows = rows;
|
||||
_syncedRows = synced;
|
||||
_plannedRows = planned;
|
||||
_exerciseNames = names;
|
||||
_selectedState = state;
|
||||
_loading = false;
|
||||
@ -113,10 +122,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
/// Read once per load and used twice: to restore this device's own missing
|
||||
/// sessions into local history, and to list the PC-only records below them.
|
||||
Future<List<Map<String, dynamic>>> _readSyncedPayloads() =>
|
||||
WorkoutSyncService(
|
||||
httpClient: widget.httpClient,
|
||||
firebaseFactory: widget.firebaseFactory,
|
||||
).readMergedWorkoutPayloads();
|
||||
_syncService().readMergedWorkoutPayloads();
|
||||
|
||||
Future<void> _pickExercise(String name) async {
|
||||
ExerciseState? state;
|
||||
@ -147,7 +153,9 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
),
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _rows.isEmpty
|
||||
// Synced and planned entries count too: a phone with no local
|
||||
// sessions must still list (and let the user delete) its plans.
|
||||
: _rows.isEmpty && _syncedRows.isEmpty && _plannedRows.isEmpty
|
||||
? Center(
|
||||
child: Text(
|
||||
'No workouts yet.',
|
||||
@ -173,6 +181,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
|
||||
}
|
||||
|
||||
List<Widget> _buildTotalView() => [
|
||||
..._plannedSection(),
|
||||
const _SectionLabel('TOTAL VOLUME (2-session rolling avg, kg)'),
|
||||
const SizedBox(height: 6),
|
||||
_WeightChart(points: _rollingAvg2(_totalVolumePoints(_rows))),
|
||||
|
||||
@ -125,6 +125,14 @@ Set<String> _allWorkoutDates(
|
||||
...syncedRows.map((r) => '${r['date']}'),
|
||||
};
|
||||
|
||||
/// Synced kinds this phone has no local record of, so showing them can't
|
||||
/// double up an existing session.
|
||||
///
|
||||
/// A `phone_verified` record is the PC's mirror of a StrongLifts session this
|
||||
/// phone already stores in full (and renders from `_rows`), so it is
|
||||
/// deliberately excluded — otherwise the same workout would appear twice.
|
||||
const _kSyncedOnlyKinds = {'runnerup_verified', 'manual_workout'};
|
||||
|
||||
/// Workouts the PC published that this phone has no local record of.
|
||||
///
|
||||
/// The PC pushes its whole `log.json` (RunnerUp runs and manual
|
||||
@ -132,6 +140,37 @@ Set<String> _allWorkoutDates(
|
||||
/// the SAME history. Sorted newest-first to match the local session list.
|
||||
/// StrongLifts sessions are deliberately excluded: they are restored into
|
||||
/// local history instead, so listing them here too would double them up.
|
||||
List<Map<String, dynamic>> _syncedOnly(List<Map<String, dynamic>> payloads) =>
|
||||
payloads.where((p) => _kSyncedOnlyKinds.contains(p['kind'])).toList()
|
||||
///
|
||||
/// Planned manual entries (see [_isPlanned]) are excluded as well: they have
|
||||
/// not happened, so they belong in their own list and never on the calendar,
|
||||
/// which is built from these rows.
|
||||
List<Map<String, dynamic>> _syncedOnly(
|
||||
List<Map<String, dynamic>> payloads,
|
||||
String today,
|
||||
) =>
|
||||
payloads
|
||||
.where((p) => _kSyncedOnlyKinds.contains(p['kind']))
|
||||
.where((p) => !_isPlanned(p, today))
|
||||
.toList()
|
||||
..sort((a, b) => '${b['date']}'.compareTo('${a['date']}'));
|
||||
|
||||
/// Manual entries dated after [today] (`YYYY-MM-DD`), soonest first.
|
||||
List<Map<String, dynamic>> _plannedOnly(
|
||||
List<Map<String, dynamic>> payloads,
|
||||
String today,
|
||||
) =>
|
||||
payloads.where((p) => _isPlanned(p, today)).toList()
|
||||
..sort((a, b) => '${a['date']}'.compareTo('${b['date']}'));
|
||||
|
||||
/// Whether [payload] is a manual workout dated after [today].
|
||||
///
|
||||
/// A plain string comparison is a date comparison for `YYYY-MM-DD` keys. Only
|
||||
/// manual entries can be planned; anything else dated ahead is a clock skew,
|
||||
/// not a plan, and is left where it was.
|
||||
///
|
||||
/// A stub with no `start_time` is never a plan: its record id cannot be
|
||||
/// derived, so a delete would tombstone nothing and the tile would return.
|
||||
bool _isPlanned(Map<String, dynamic> payload, String today) =>
|
||||
payload['kind'] == kManualWorkoutSyncKind &&
|
||||
payload['start_time'] is String &&
|
||||
'${payload['date']}'.compareTo(today) > 0;
|
||||
|
||||
@ -0,0 +1,152 @@
|
||||
// Planned (future-dated) manual workouts: their section and their delete,
|
||||
// plus the sync service both this and the load use.
|
||||
//
|
||||
// A `part` so the extension keeps reaching the private state. Nothing here
|
||||
// calls `setState`: a delete ends in `_load`, which applies the reload.
|
||||
part of 'history_screen.dart';
|
||||
|
||||
/// The PLANNED section of the history view.
|
||||
extension _HistoryPlanned on _HistoryScreenState {
|
||||
/// The sync service, wired to the test seams this screen was built with.
|
||||
WorkoutSyncService _syncService() => WorkoutSyncService(
|
||||
httpClient: widget.httpClient,
|
||||
firebaseFactory: widget.firebaseFactory,
|
||||
);
|
||||
|
||||
/// The planned entries, above everything that already happened; nothing
|
||||
/// when there are none.
|
||||
List<Widget> _plannedSection() => [
|
||||
if (_plannedRows.isNotEmpty) ...[
|
||||
const _SectionLabel('PLANNED (not done yet)'),
|
||||
const SizedBox(height: 8),
|
||||
..._plannedRows.map(
|
||||
(row) => _PlannedWorkoutTile(
|
||||
payload: row,
|
||||
onDelete: () => _deletePlanned(row),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
];
|
||||
|
||||
/// Deletes the planned manual entry [payload] on every device, after a
|
||||
/// confirmation, then re-reads history from sync.
|
||||
///
|
||||
/// Re-reading rather than dropping the tile: the tile only goes once the
|
||||
/// tombstone is really in the log. A failed push keeps it and says why.
|
||||
Future<void> _deletePlanned(Map<String, dynamic> payload) async {
|
||||
final date = '${payload['date']}';
|
||||
final id = manualSyncRecordId(date, '${payload['start_time']}');
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Delete planned workout?'),
|
||||
content: Text(
|
||||
'${payload['source'] ?? 'Manual workout'} on $date at '
|
||||
'${payload['start_time']}. It will not be credited.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('KEEP'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('DELETE'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true || !mounted) return;
|
||||
// Re-checked against the clock: "planned" was decided when History
|
||||
// loaded, and a delete confirmed after midnight would cancel a workout
|
||||
// that is now today's -- one the PC may already have credited.
|
||||
if (!_isPlanned(payload, dayKey((widget.clock ?? DateTime.now)()))) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Not deleted — $date has started, so it is no longer '
|
||||
'a planned workout.',
|
||||
),
|
||||
),
|
||||
);
|
||||
await _load();
|
||||
return;
|
||||
}
|
||||
final result = await _syncService().tombstoneManual(id);
|
||||
SandboxLog.event('manual planned delete', {
|
||||
'id': id,
|
||||
'pushed': result.pushed,
|
||||
'reason': result.reason,
|
||||
});
|
||||
if (!mounted) return;
|
||||
if (!result.pushed) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Not deleted — ${result.reason}')));
|
||||
return;
|
||||
}
|
||||
await _load();
|
||||
}
|
||||
}
|
||||
|
||||
/// A manual workout dated after today: listed, but not as done.
|
||||
///
|
||||
/// The only tile with a delete button. A plan can be cancelled until its day
|
||||
/// comes; anything that already happened stays history.
|
||||
class _PlannedWorkoutTile extends StatelessWidget {
|
||||
const _PlannedWorkoutTile({required this.payload, required this.onDelete});
|
||||
|
||||
final Map<String, dynamic> payload;
|
||||
final VoidCallback onDelete;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final detail = '${payload['source'] ?? ''}';
|
||||
final time = '${payload['start_time'] ?? ''}';
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.only(left: 14, top: 4, bottom: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppRadius.sm),
|
||||
border: Border.all(color: colorScheme.outline),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.event, color: colorScheme.onSurfaceVariant, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${payload['date']} $time · Planned',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
if (detail.isNotEmpty)
|
||||
Text(
|
||||
detail,
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: AppTextSize.caption,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: 'Delete planned workout',
|
||||
icon: Icon(Icons.delete_outline, color: colorScheme.error),
|
||||
onPressed: onDelete,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,101 @@
|
||||
// What the manual-workout form DOES: load the ledger, pick a date, submit.
|
||||
//
|
||||
// A `part` so the extension keeps reaching the private state; it mutates it
|
||||
// through the `_applyState` shim because `setState` is `@protected` and
|
||||
// cannot be called from an extension (same pattern as home_screen_sync.dart).
|
||||
part of 'manual_workout_screen.dart';
|
||||
|
||||
/// Loading, date selection and submission for the manual-workout form.
|
||||
extension _ManualWorkoutActions on _ManualWorkoutScreenState {
|
||||
Future<void> _loadBudget() async {
|
||||
final ledger = await _sync.readManualLedger();
|
||||
if (!mounted) return;
|
||||
_applyState(() {
|
||||
_payloads = ledger.payloads;
|
||||
_tombstoned = ledger.tombstoned;
|
||||
_budgetLoaded = true;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _pickDate() async {
|
||||
final today = _today();
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
// Clamped: a form left open across midnight holds yesterday, and the
|
||||
// picker asserts its initial date is inside the range.
|
||||
initialDate: _date.isBefore(today) ? today : _date,
|
||||
firstDate: today,
|
||||
lastDate: today.add(const Duration(days: kManualWorkoutMaxDaysAhead)),
|
||||
helpText: 'Workout date',
|
||||
);
|
||||
if (picked == null || !mounted) return;
|
||||
SandboxLog.event('manual date picked', {'date': dayKey(picked)});
|
||||
_applyState(() {
|
||||
_date = DateTime(picked.year, picked.month, picked.day);
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
|
||||
/// Why [_date] can no longer be submitted, or null when it can.
|
||||
///
|
||||
/// Re-checked at submit because the clock moves: a form opened at 23:58
|
||||
/// with "today" selected is dated yesterday by the time it is sent.
|
||||
String? _dateError() {
|
||||
final today = _today();
|
||||
if (_date.isBefore(today)) {
|
||||
return 'The workout date ${dayKey(_date)} is in the past — pick '
|
||||
'today or a day ahead.';
|
||||
}
|
||||
final last = today.add(const Duration(days: kManualWorkoutMaxDaysAhead));
|
||||
if (_date.isAfter(last)) {
|
||||
return 'A workout can be planned at most $kManualWorkoutMaxDaysAhead '
|
||||
'days ahead.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
final draft = _draft();
|
||||
final date = dayKey(_date);
|
||||
final recordId = manualSyncRecordId(date, draft.startTime);
|
||||
final error =
|
||||
validateManualWorkout(draft) ??
|
||||
_dateError() ??
|
||||
// A deleted record's id stays deleted forever (tombstones are
|
||||
// sticky), so re-logging the same date and start time would vanish
|
||||
// on every device. Refuse it here, where the user can still act.
|
||||
(_tombstoned.contains(recordId)
|
||||
? 'A workout at ${draft.startTime.trim()} on $date was deleted '
|
||||
'earlier and cannot be logged again — use a different '
|
||||
'start time.'
|
||||
: null);
|
||||
if (error != null) {
|
||||
SandboxLog.event('manual submit refused', {'reason': error});
|
||||
_applyState(() => _error = error);
|
||||
return;
|
||||
}
|
||||
_applyState(() {
|
||||
_error = null;
|
||||
_submitting = true;
|
||||
});
|
||||
final result = await _sync.pushManual(
|
||||
buildManualRecord(draft, date, hlc: Hlc.newTick(currentSyncDeviceId)),
|
||||
);
|
||||
SandboxLog.event('manual submit', {
|
||||
'id': recordId,
|
||||
'pushed': result.pushed,
|
||||
'reason': result.reason,
|
||||
});
|
||||
if (!mounted) return;
|
||||
if (!result.pushed) {
|
||||
// Popping here used to report a workout that never left the phone as
|
||||
// logged. Stay on the filled form and say why, so it can be retried.
|
||||
_applyState(() {
|
||||
_submitting = false;
|
||||
_error = 'Not saved — ${result.reason}';
|
||||
});
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).pop(true);
|
||||
}
|
||||
}
|
||||
@ -8,15 +8,54 @@ part of 'manual_workout_screen.dart';
|
||||
|
||||
/// The form's non-interactive building blocks.
|
||||
extension _ManualWorkoutFormParts on _ManualWorkoutScreenState {
|
||||
/// The budget as seen from the selected date: the fullest 7- and 30-day
|
||||
/// windows around it, planned entries included.
|
||||
Widget _budgetBanner(ManualBudget budget) => Text(
|
||||
'Manual: ${budget.week}/$kManualWorkoutBudgetPer7Days this week · '
|
||||
'${budget.month}/$kManualWorkoutBudgetPer30Days this month',
|
||||
'Manual around ${dayKey(_date)}: '
|
||||
'${budget.week}/$kManualWorkoutBudgetPer7Days per 7 days · '
|
||||
'${budget.month}/$kManualWorkoutBudgetPer30Days per 30 days',
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
fontSize: AppTextSize.body,
|
||||
),
|
||||
);
|
||||
|
||||
/// "today", "tomorrow" or "in N days" for the selected date.
|
||||
String _relativeDay() {
|
||||
// Rounded, not truncated: across a DST change two local midnights are
|
||||
// 23 or 25 hours apart.
|
||||
final days = (_date.difference(_today()).inHours / 24).round();
|
||||
return switch (days) {
|
||||
0 => 'today',
|
||||
1 => 'tomorrow',
|
||||
_ => 'in $days days',
|
||||
};
|
||||
}
|
||||
|
||||
/// The workout date and the button that changes it.
|
||||
Widget _dateRow() => Padding(
|
||||
padding: const EdgeInsets.only(bottom: AppSpacing.sm),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Workout date: ${dayKey(_date)} (${_relativeDay()})',
|
||||
key: const Key('mw_date'),
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
fontSize: AppTextSize.body,
|
||||
),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
key: const Key('mw_pick_date'),
|
||||
onPressed: _submitting ? null : _pickDate,
|
||||
child: const Text('CHANGE DATE'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _section(String title) => Padding(
|
||||
padding: const EdgeInsets.only(top: 16, bottom: 4),
|
||||
child: Text(
|
||||
|
||||
@ -5,6 +5,11 @@
|
||||
/// (2/week, 5/month) computed over the merged cross-device record set. On
|
||||
/// submit it builds the shared sync payload and pushes it to the phone's device
|
||||
/// log; the PC ingests it as a counted `manual_workout`.
|
||||
///
|
||||
/// The workout date defaults to today and may be set up to
|
||||
/// [kManualWorkoutMaxDaysAhead] days ahead (never back): a planned session is
|
||||
/// logged now and credited by the PC on its own date. The budget is read as
|
||||
/// of the chosen date, so moving the date re-evaluates it.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
@ -12,11 +17,19 @@ import 'dart:async';
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:workout_app/models/manual_workout.dart';
|
||||
import 'package:workout_app/sandbox/sandbox_log.dart';
|
||||
import 'package:workout_app/services/done_today.dart';
|
||||
import 'package:workout_app/services/sync_device_id.dart';
|
||||
import 'package:workout_app/services/workout_sync_service.dart';
|
||||
import 'package:workout_app/ui/theme.dart';
|
||||
|
||||
part 'manual_workout_actions.dart';
|
||||
part 'manual_workout_form_parts.dart';
|
||||
|
||||
/// How many days ahead a manual workout may be dated. Past dates are never
|
||||
/// offered: a manual entry is either today's or a planned one.
|
||||
const int kManualWorkoutMaxDaysAhead = 7;
|
||||
|
||||
/// A screen that logs an off-app workout and syncs it to the PC.
|
||||
class ManualWorkoutScreen extends StatefulWidget {
|
||||
/// Creates the manual-workout form. [syncService]/[clock] are injectable for
|
||||
@ -69,9 +82,22 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
|
||||
double _rpe = 5;
|
||||
String? _error;
|
||||
bool _submitting = false;
|
||||
ManualBudget? _budget;
|
||||
List<Map<String, dynamic>> _payloads = const [];
|
||||
Set<String> _tombstoned = const {};
|
||||
bool _budgetLoaded = false;
|
||||
|
||||
/// The workout date (a calendar day, no time). Starts as today.
|
||||
late DateTime _date = _today();
|
||||
|
||||
DateTime _today() {
|
||||
final now = _clock();
|
||||
return DateTime(now.year, now.month, now.day);
|
||||
}
|
||||
|
||||
/// Read fresh on every build, so a date change re-evaluates it without
|
||||
/// another round trip to the sync backend.
|
||||
ManualBudget get _budget => countManualBudget(_payloads, _date);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@ -86,43 +112,15 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadBudget() async {
|
||||
final payloads = await _sync.readMergedManualPayloads();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_budget = countManualBudget(payloads, _clock());
|
||||
_budgetLoaded = true;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
final draft = _draft();
|
||||
final error = validateManualWorkout(draft);
|
||||
if (error != null) {
|
||||
setState(() => _error = error);
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_error = null;
|
||||
_submitting = true;
|
||||
});
|
||||
final now = _clock();
|
||||
final date =
|
||||
'${now.year.toString().padLeft(4, '0')}-'
|
||||
'${now.month.toString().padLeft(2, '0')}-'
|
||||
'${now.day.toString().padLeft(2, '0')}';
|
||||
await _sync.pushManual(
|
||||
buildManualRecord(draft, date, hlc: Hlc.newTick('phone')),
|
||||
);
|
||||
if (!mounted) return;
|
||||
Navigator.of(context).pop(true);
|
||||
}
|
||||
/// Runs [fn] inside `setState` on behalf of this library's extensions,
|
||||
/// which cannot call the `@protected` original.
|
||||
void _applyState(VoidCallback fn) => setState(fn);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final budget = _budget;
|
||||
final exhausted = budget?.exhausted ?? false;
|
||||
final exhausted = budget.exhausted;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
backgroundColor: colorScheme.surfaceContainerHigh,
|
||||
@ -136,12 +134,16 @@ class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
|
||||
: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
_budgetBanner(budget!),
|
||||
// Above the exhausted branch on purpose: a full window around
|
||||
// today must not stop the user picking a free day later on.
|
||||
_dateRow(),
|
||||
_budgetBanner(budget),
|
||||
if (exhausted)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(
|
||||
'Manual-workout budget exhausted for this window.',
|
||||
'Manual-workout budget exhausted for a window '
|
||||
'containing ${dayKey(_date)} — pick another date.',
|
||||
style: TextStyle(color: colorScheme.error),
|
||||
),
|
||||
)
|
||||
|
||||
@ -212,6 +212,22 @@ class WorkoutSyncService {
|
||||
Future<List<Map<String, dynamic>>> readMergedManualPayloads() =>
|
||||
_readMergedPayloads(kind: kManualWorkoutSyncKind);
|
||||
|
||||
/// [readMergedManualPayloads] plus every tombstoned id, from ONE read.
|
||||
///
|
||||
/// The manual-workout form needs both: the payloads for the budget, the
|
||||
/// ids to refuse re-logging onto a deleted record (see [ManualLedger]).
|
||||
Future<ManualLedger> readManualLedger() =>
|
||||
_readMergedLedger(kind: kManualWorkoutSyncKind);
|
||||
|
||||
/// Deletes the manual workout [recordId] everywhere: a crdt-sync
|
||||
/// tombstone through [pushManual]. Only planned (future-dated) entries
|
||||
/// are offered for deletion; the caller enforces that. Same never-throw
|
||||
/// contract as [push]: a failed tombstone leaves the record live, and
|
||||
/// says so.
|
||||
Future<PushResult> tombstoneManual(String recordId) => pushManual(
|
||||
buildManualTombstone(recordId, hlc: Hlc.newTick(currentSyncDeviceId)),
|
||||
);
|
||||
|
||||
/// Every synced workout, whatever kind — manual, StrongLifts or RunnerUp.
|
||||
///
|
||||
/// The PC publishes its whole `log.json` (including verified runs),
|
||||
|
||||
@ -3,18 +3,37 @@
|
||||
// An `extension` in a `part` -- see storage_service_backup.dart for why.
|
||||
part of 'workout_sync_service.dart';
|
||||
|
||||
/// What the sync backends hold: the live payloads plus every tombstoned id.
|
||||
///
|
||||
/// The ids matter to the manual-workout form because a manual record's id is
|
||||
/// derived (`manual:<date>T<HH:MM>`) and deletion is sticky: re-logging the
|
||||
/// same date and start time after deleting a planned entry would land on the
|
||||
/// tombstone and vanish on every device without a word.
|
||||
typedef ManualLedger = ({
|
||||
List<Map<String, dynamic>> payloads,
|
||||
Set<String> tombstoned,
|
||||
});
|
||||
|
||||
/// The ledger an unreadable or unconfigured backend answers with.
|
||||
const ManualLedger _emptyLedger = (
|
||||
payloads: <Map<String, dynamic>>[],
|
||||
tombstoned: <String>{},
|
||||
);
|
||||
|
||||
/// Reads merged workout/manual payloads across every device log.
|
||||
extension WorkoutSyncServiceRead on WorkoutSyncService {
|
||||
Future<List<Map<String, dynamic>>> _readMergedPayloads({
|
||||
String? kind,
|
||||
}) async => (await _readMergedLedger(kind: kind)).payloads;
|
||||
|
||||
|
||||
Future<List<Map<String, dynamic>>> _readMergedPayloads({String? kind}) async {
|
||||
Future<ManualLedger> _readMergedLedger({String? kind}) async {
|
||||
final settings = await SyncSettings.load();
|
||||
if (!settings.isConfigured && !await _hasFirebaseAccount()) {
|
||||
debugPrint(
|
||||
'WorkoutSyncService: NOT reading synced workouts — no sync backend '
|
||||
'configured in Settings, so this phone cannot see the PC history.',
|
||||
);
|
||||
return const [];
|
||||
return _emptyLedger;
|
||||
}
|
||||
|
||||
try {
|
||||
@ -42,14 +61,11 @@ extension WorkoutSyncServiceRead on WorkoutSyncService {
|
||||
'WorkoutSyncService: FAILED reading synced workouts '
|
||||
'(kind=$which) from $owner/$repo: $failure — history may be incomplete.',
|
||||
);
|
||||
return const [];
|
||||
return _emptyLedger;
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> _fetchPayloads(
|
||||
String token,
|
||||
String? kind,
|
||||
) async {
|
||||
Future<ManualLedger> _fetchPayloads(String token, String? kind) async {
|
||||
final github = GitHubClient(
|
||||
owner: owner,
|
||||
repo: repo,
|
||||
@ -79,9 +95,14 @@ extension WorkoutSyncServiceRead on WorkoutSyncService {
|
||||
// delete it, and a per-file skip would just let the live copy win the
|
||||
// merge. Mirrors the PC's `_tombstoned_ids` (screen_locker/_sync_records.py).
|
||||
tombstoned.forEach(merged.remove);
|
||||
return merged.values
|
||||
.map((r) => (r.fields['payload']!.$1! as Map).cast<String, dynamic>())
|
||||
.toList();
|
||||
return (
|
||||
payloads: merged.values
|
||||
.map(
|
||||
(r) => (r.fields['payload']!.$1! as Map).cast<String, dynamic>(),
|
||||
)
|
||||
.toList(),
|
||||
tombstoned: tombstoned,
|
||||
);
|
||||
} finally {
|
||||
github.close();
|
||||
firebase?.close();
|
||||
@ -118,5 +139,4 @@ extension WorkoutSyncServiceRead on WorkoutSyncService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -110,4 +110,43 @@ void main() {
|
||||
expect(budget.week, 0);
|
||||
expect(budget.month, 0);
|
||||
});
|
||||
|
||||
// The `planned` key (2026-10-16): future-dated entries. The top-level
|
||||
// expectations above are the PC's trailing-window reading and stay as-is;
|
||||
// this block pins the phone's admission rule for a workout dated D -- the
|
||||
// fullest 7-/30-day window CONTAINING D, past and planned entries alike.
|
||||
group('planned (future-dated) entries', () {
|
||||
Map<String, dynamic> planned() =>
|
||||
_fixture()['planned'] as Map<String, dynamic>;
|
||||
List<dynamic> allRecords() => [
|
||||
..._fixture()['records'] as List<dynamic>,
|
||||
...planned()['extra_records'] as List<dynamic>,
|
||||
];
|
||||
|
||||
test('budget for each date matches the shared expectation', () {
|
||||
final expected = planned()['expected_by_date'] as Map<String, dynamic>;
|
||||
final payloads = _livePayloads(_deviceLogJson(allRecords()));
|
||||
expect(expected, isNotEmpty);
|
||||
for (final entry in expected.entries) {
|
||||
final want = entry.value as Map<String, dynamic>;
|
||||
final budget = countManualBudget(payloads, DateTime.parse(entry.key));
|
||||
expect(budget.week, want['week'], reason: entry.key);
|
||||
expect(budget.month, want['month'], reason: entry.key);
|
||||
expect(budget.exhausted, want['exhausted'], reason: entry.key);
|
||||
}
|
||||
});
|
||||
|
||||
test('a cancelled plan frees its weekly slot', () {
|
||||
final resurrected = [
|
||||
for (final entry in allRecords().cast<Map<String, dynamic>>())
|
||||
{...entry, 'deleted': false},
|
||||
];
|
||||
final budget = countManualBudget(
|
||||
_livePayloads(_deviceLogJson(resurrected)),
|
||||
DateTime(2026, 8, 28),
|
||||
);
|
||||
expect(budget.week, 2);
|
||||
expect(budget.exhausted, isTrue);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@ -143,15 +143,63 @@ void main() {
|
||||
expect(budget.week, 3);
|
||||
});
|
||||
|
||||
test('ignores dates outside the 30-day window and future dates', () {
|
||||
test('ignores dates outside every window containing the date', () {
|
||||
final budget = countManualBudget([
|
||||
payload('2026-05-01', '10:00'),
|
||||
payload('2026-07-20', '10:00'),
|
||||
payload('2026-09-20', '10:00'),
|
||||
], now);
|
||||
expect(budget.week, 0);
|
||||
expect(budget.month, 0);
|
||||
});
|
||||
|
||||
// Planned entries (2026-10-16): the count is the fullest window that
|
||||
// CONTAINS the workout date, so a future entry costs budget too.
|
||||
test('a future entry counts against a window containing the date', () {
|
||||
final budget = countManualBudget([payload('2026-07-20', '10:00')], now);
|
||||
expect(budget.week, 1);
|
||||
expect(budget.month, 1);
|
||||
});
|
||||
|
||||
test('a past and a future entry six days apart exhaust the week', () {
|
||||
// 07-13 .. 07-19 is one 7-day window holding both, and it contains
|
||||
// 07-16; the trailing window alone would have read 1/2.
|
||||
final budget = countManualBudget([
|
||||
payload('2026-07-13', '10:00'),
|
||||
payload('2026-07-19', '10:00'),
|
||||
], now);
|
||||
expect(budget.week, 2);
|
||||
expect(budget.exhausted, isTrue);
|
||||
});
|
||||
|
||||
test('moving the date away from a full week frees it', () {
|
||||
final payloads = [
|
||||
payload('2026-07-13', '10:00'),
|
||||
payload('2026-07-19', '10:00'),
|
||||
];
|
||||
// 07-26: windows containing it start 07-20 or later, past both.
|
||||
final later = countManualBudget(payloads, DateTime(2026, 7, 26));
|
||||
expect(later.week, 0);
|
||||
expect(later.month, 2);
|
||||
// 07-23: the window 07-17 .. 07-23 still holds 07-19.
|
||||
expect(countManualBudget(payloads, DateTime(2026, 7, 23)).week, 1);
|
||||
});
|
||||
|
||||
test('the date may carry a time of day', () {
|
||||
final budget = countManualBudget([
|
||||
payload('2026-07-16', '10:00'),
|
||||
], DateTime(2026, 7, 16, 23, 59));
|
||||
expect(budget.week, 1);
|
||||
});
|
||||
|
||||
test('a DST change between dates does not shift the day count', () {
|
||||
// Europe's 2026 autumn change is 10-25; 10-19 .. 10-25 is one window.
|
||||
final budget = countManualBudget([
|
||||
payload('2026-10-19', '10:00'),
|
||||
payload('2026-10-25', '10:00'),
|
||||
], DateTime(2026, 10, 25));
|
||||
expect(budget.week, 2);
|
||||
});
|
||||
|
||||
test('skips payloads with missing or unparsable date', () {
|
||||
final budget = countManualBudget([
|
||||
{'start_time': '10:00'},
|
||||
|
||||
@ -0,0 +1,36 @@
|
||||
// The tombstone that deletes a planned manual workout on every device.
|
||||
//
|
||||
// Split from manual_workout_test.dart for the 250-line cap.
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:workout_app/models/manual_workout.dart';
|
||||
|
||||
const _draft = ManualWorkoutDraft(
|
||||
sport: kSportTableTennis,
|
||||
startTime: '18:00',
|
||||
endTime: '19:30',
|
||||
locationName: 'Solec',
|
||||
transportMethod: 'bike',
|
||||
cost: '40 PLN',
|
||||
rpe: 6,
|
||||
wentWell: 'Served consistently and moved feet well',
|
||||
toImprove: 'Backhand topspin needs more consistency',
|
||||
overallFeeling: 'Felt strong focused and in good rhythm',
|
||||
);
|
||||
|
||||
void main() {
|
||||
test('buildManualTombstone is a field-less, deleted record', () {
|
||||
final hlc = Hlc.newTick('phone');
|
||||
final tombstone = buildManualTombstone('manual:2026-07-13T18:00', hlc: hlc);
|
||||
expect(tombstone.id, 'manual:2026-07-13T18:00');
|
||||
expect(tombstone.fields, isEmpty);
|
||||
expect(tombstone.deleted, isTrue);
|
||||
expect(tombstone.deletedHlc, hlc);
|
||||
// Merged onto the live record it keeps the payload and stays deleted.
|
||||
final live = buildManualRecord(_draft, '2026-07-13', hlc: hlc);
|
||||
final merged = mergeRecord(live, tombstone);
|
||||
expect(merged.deleted, isTrue);
|
||||
expect(merged.fields['payload'], live.fields['payload']);
|
||||
expect(tombstone.toJson()['deleted_hlc'], hlc.toStr());
|
||||
});
|
||||
}
|
||||
@ -34,20 +34,20 @@ Future<void> pumpHistory(WidgetTester tester, Widget w) async {
|
||||
Widget wrapHistory({
|
||||
http.Client? httpClient,
|
||||
Future<FirebaseRestClient?> Function()? firebaseFactory,
|
||||
DateTime Function()? clock,
|
||||
}) => MaterialApp(
|
||||
theme: buildAppTheme(),
|
||||
home: HistoryScreen(
|
||||
httpClient: httpClient,
|
||||
firebaseFactory: firebaseFactory ?? () async => null,
|
||||
clock: clock,
|
||||
),
|
||||
);
|
||||
|
||||
/// A GitHub mock serving one PC device log holding a run and a manual.
|
||||
http.Client historySyncMock() {
|
||||
String file(String body) => jsonEncode({
|
||||
'content': base64Encode(utf8.encode(body)),
|
||||
'sha': 'sha',
|
||||
});
|
||||
String file(String body) =>
|
||||
jsonEncode({'content': base64Encode(utf8.encode(body)), 'sha': 'sha'});
|
||||
Record rec(String id, String kind, int ms) => Record(
|
||||
id: id,
|
||||
fields: {
|
||||
|
||||
@ -0,0 +1,80 @@
|
||||
// Shared fixtures for the manual-workout form tests.
|
||||
//
|
||||
// Hoisted to top level so the split test files import one definition (see
|
||||
// _history_test_fixtures.dart for why local copies drift).
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:workout_app/services/workout_sync_service.dart';
|
||||
|
||||
class FakeManualSync extends WorkoutSyncService {
|
||||
FakeManualSync({
|
||||
this.payloads = const [],
|
||||
this.tombstoned = const {},
|
||||
this.result = const PushResult(pushed: true, reason: 'pushed'),
|
||||
});
|
||||
|
||||
final List<Map<String, dynamic>> payloads;
|
||||
final Set<String> tombstoned;
|
||||
final PushResult result;
|
||||
Record? pushed;
|
||||
|
||||
@override
|
||||
Future<ManualLedger> readManualLedger() async =>
|
||||
(payloads: payloads, tombstoned: tombstoned);
|
||||
|
||||
@override
|
||||
Future<PushResult> pushManual(Record record) async {
|
||||
pushed = record;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> manualEntry(String date) => {
|
||||
'kind': 'manual_workout',
|
||||
'date': date,
|
||||
'start_time': '18:00',
|
||||
'end_time': '19:00',
|
||||
};
|
||||
|
||||
/// Opens the date picker, taps [day] of the shown month, confirms.
|
||||
Future<void> pickDay(WidgetTester tester, String day) async {
|
||||
await tester.tap(find.text('CHANGE DATE'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text(day));
|
||||
await tester.tap(find.text('OK'));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
DateTime fixedManualNow() => DateTime(2026, 7, 13, 20);
|
||||
|
||||
Future<void> pumpManual(WidgetTester tester, Widget child) async {
|
||||
// Tall viewport so the whole (long) form is laid out — a ListView only builds
|
||||
// children within the viewport, so off-screen widgets aren't findable.
|
||||
tester.view.physicalSize = const Size(500, 2600);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await tester.pumpWidget(MaterialApp(home: child));
|
||||
await tester.pumpAndSettle(); // let the budget future resolve
|
||||
}
|
||||
|
||||
Future<void> fillValidTt(WidgetTester tester) async {
|
||||
Future<void> enter(String key, String value) =>
|
||||
tester.enterText(find.byKey(Key('mw_$key')), value);
|
||||
await enter('start_time', '18:00');
|
||||
await enter('end_time', '19:30');
|
||||
await enter('location_name', 'Solec');
|
||||
await enter('transport_method', 'bike');
|
||||
await enter('cost', '40 PLN');
|
||||
await enter('matches_won', '3');
|
||||
await enter('matches_lost', '1');
|
||||
await enter('sets_won', '7');
|
||||
await enter('sets_lost', '4');
|
||||
await enter('racket', 'Butterfly');
|
||||
await enter('balls', 'Nittaku');
|
||||
await enter('pain_or_injury', 'sore knee');
|
||||
await enter('went_well', 'Served consistently and moved feet well');
|
||||
await enter('to_improve', 'Backhand topspin needs more consistency');
|
||||
await enter('overall_feeling', 'Felt strong focused and in good rhythm');
|
||||
}
|
||||
@ -0,0 +1,223 @@
|
||||
// Planned (future-dated) manual workouts in the history view: listed apart
|
||||
// from what was done, kept off the calendar, and deletable until their day
|
||||
// through a crdt-sync tombstone.
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
import 'package:workout_app/services/storage_service.dart';
|
||||
import 'package:workout_app/widgets/calendar_widget.dart';
|
||||
|
||||
import '../fake_path_provider.dart';
|
||||
import '../fake_secure_storage.dart';
|
||||
import '_history_test_fixtures.dart';
|
||||
|
||||
const _pcLog = 'screen-locker-sync/devices/pc/log.json';
|
||||
|
||||
Map<String, Object?> _manual(String date, String? start, String source) => {
|
||||
'kind': 'manual_workout',
|
||||
'type': 'manual_workout',
|
||||
'date': date,
|
||||
if (start != null) 'start_time': start,
|
||||
'source': source,
|
||||
};
|
||||
|
||||
String _log(Map<String, Map<String, Object?>> byId) {
|
||||
final hlc = Hlc(wallTimeMs: 1000, counter: 0, nodeId: 'pc');
|
||||
return jsonEncode({
|
||||
for (final e in byId.entries)
|
||||
e.key: Record(id: e.key, fields: {'payload': (e.value, hlc)}).toJson(),
|
||||
});
|
||||
}
|
||||
|
||||
/// A GitHub Contents API that remembers what was PUT, so a reload after a
|
||||
/// delete sees the tombstone. [failPuts] answers every write with a 500.
|
||||
({http.Client client, Map<String, String> files}) _github(
|
||||
Map<String, String> files, {
|
||||
bool failPuts = false,
|
||||
}) {
|
||||
final client = MockClient((req) async {
|
||||
final path = req.url.path;
|
||||
if (!path.contains('/contents/')) return http.Response('{}', 200);
|
||||
final key = Uri.decodeComponent(path.split('/contents/').last);
|
||||
if (req.method == 'PUT') {
|
||||
if (failPuts) return http.Response('boom', 500);
|
||||
final body = jsonDecode(req.body) as Map<String, dynamic>;
|
||||
files[key] = utf8.decode(base64.decode(body['content'] as String));
|
||||
return http.Response('{"content":{"sha":"s"}}', 200);
|
||||
}
|
||||
final text = files[key];
|
||||
if (text != null) {
|
||||
return http.Response(
|
||||
jsonEncode({'content': base64Encode(utf8.encode(text)), 'sha': 's'}),
|
||||
200,
|
||||
);
|
||||
}
|
||||
final children = {
|
||||
for (final k in files.keys)
|
||||
if (k.startsWith('$key/')) k.substring(key.length + 1).split('/').first,
|
||||
};
|
||||
if (children.isEmpty) return http.Response('not found', 404);
|
||||
return http.Response(
|
||||
jsonEncode([
|
||||
for (final c in children) {'name': c, 'type': 'dir'},
|
||||
]),
|
||||
200,
|
||||
);
|
||||
});
|
||||
return (client: client, files: files);
|
||||
}
|
||||
|
||||
Map<String, String> _seed() => {
|
||||
_pcLog: _log({
|
||||
'manual:2026-10-14T18:00': _manual('2026-10-14', '18:00', 'squash'),
|
||||
'manual:2026-10-16T07:00': _manual('2026-10-16', '07:00', 'swim today'),
|
||||
'manual:2026-10-17T10:00': _manual('2026-10-17', '10:00', 'padel'),
|
||||
// A future stub has no start time, hence no derivable id: never a plan.
|
||||
'manual_workout:2026-10-18': _manual('2026-10-18', null, 'stub'),
|
||||
}),
|
||||
};
|
||||
|
||||
DateTime _now() => DateTime(2026, 10, 16, 15);
|
||||
|
||||
/// Lets the real-I/O sync calls finish, then rebuilds.
|
||||
Future<void> _settle(WidgetTester tester, [int rounds = 1]) async {
|
||||
for (var i = 0; i < rounds; i++) {
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 300)),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _open(
|
||||
WidgetTester tester,
|
||||
http.Client client, {
|
||||
DateTime Function() clock = _now,
|
||||
}) async {
|
||||
tester.view.physicalSize = const Size(500, 3000);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await pumpHistory(tester, wrapHistory(httpClient: client, clock: clock));
|
||||
}
|
||||
|
||||
Future<void> _confirmDelete(WidgetTester tester, String button) async {
|
||||
await tester.tap(find.byTooltip('Delete planned workout'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text(button));
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Record _phoneRecord(Map<String, String> files, String id) {
|
||||
final log =
|
||||
jsonDecode(files['screen-locker-sync/devices/phone/log.json']!)
|
||||
as Map<String, dynamic>;
|
||||
return Record.fromJson(log[id] as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
void main() {
|
||||
setUpAll(() {
|
||||
sqfliteFfiInit();
|
||||
databaseFactory = databaseFactoryFfi;
|
||||
});
|
||||
|
||||
setUp(() async {
|
||||
StorageService.resetForTesting();
|
||||
await StorageService.init();
|
||||
installFakePathProvider();
|
||||
installFakeSecureStorage(initial: {'sync.token': 'tok'});
|
||||
});
|
||||
|
||||
testWidgets('a future manual is listed as planned, not as done', (
|
||||
tester,
|
||||
) async {
|
||||
await _open(tester, _github(_seed()).client);
|
||||
|
||||
// No local sessions, but synced and planned entries still show.
|
||||
expect(find.text('No workouts yet.'), findsNothing);
|
||||
expect(find.text('PLANNED (not done yet)'), findsOneWidget);
|
||||
expect(find.text('2026-10-17 10:00 · Planned'), findsOneWidget);
|
||||
expect(find.byTooltip('Delete planned workout'), findsOneWidget);
|
||||
// Today's entry already happened: done, and not deletable.
|
||||
expect(find.text('2026-10-16 · Manual'), findsOneWidget);
|
||||
expect(find.text('2026-10-14 · Manual'), findsOneWidget);
|
||||
expect(find.text('2026-10-18 · Manual'), findsOneWidget);
|
||||
final calendar = tester.widget<WorkoutCalendar>(
|
||||
find.byType(WorkoutCalendar),
|
||||
);
|
||||
expect(calendar.workoutDates, isNot(contains('2026-10-17')));
|
||||
expect(calendar.workoutDates, contains('2026-10-16'));
|
||||
});
|
||||
|
||||
testWidgets('deleting a plan tombstones it and drops the tile', (
|
||||
tester,
|
||||
) async {
|
||||
final github = _github(_seed());
|
||||
await _open(tester, github.client);
|
||||
|
||||
await _confirmDelete(tester, 'DELETE');
|
||||
await _settle(tester, 4);
|
||||
|
||||
final record = _phoneRecord(github.files, 'manual:2026-10-17T10:00');
|
||||
expect(record.deleted, isTrue);
|
||||
expect(record.deletedHlc, isNotNull);
|
||||
// The tile goes only once the reload has read the tombstone back.
|
||||
await _settle(tester, 4);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('PLANNED (not done yet)'), findsNothing);
|
||||
expect(find.text('2026-10-17 10:00 · Planned'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('KEEP leaves the plan alone', (tester) async {
|
||||
final github = _github(_seed());
|
||||
await _open(tester, github.client);
|
||||
|
||||
await _confirmDelete(tester, 'KEEP');
|
||||
await _settle(tester);
|
||||
|
||||
expect(
|
||||
github.files.containsKey('screen-locker-sync/devices/phone/log.json'),
|
||||
isFalse,
|
||||
);
|
||||
expect(find.text('2026-10-17 10:00 · Planned'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a failed delete keeps the tile and says why', (tester) async {
|
||||
await _open(tester, _github(_seed(), failPuts: true).client);
|
||||
|
||||
await _confirmDelete(tester, 'DELETE');
|
||||
await _settle(tester, 2);
|
||||
|
||||
expect(find.textContaining('Not deleted — push failed'), findsOneWidget);
|
||||
expect(find.text('2026-10-17 10:00 · Planned'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a delete confirmed once the day has started is refused', (
|
||||
tester,
|
||||
) async {
|
||||
var now = _now();
|
||||
final github = _github(_seed());
|
||||
await _open(tester, github.client, clock: () => now);
|
||||
|
||||
await tester.tap(find.byTooltip('Delete planned workout'));
|
||||
await tester.pumpAndSettle();
|
||||
now = DateTime(2026, 10, 17, 0, 1);
|
||||
await tester.tap(find.text('DELETE'));
|
||||
await tester.pump();
|
||||
await _settle(tester, 2);
|
||||
|
||||
expect(find.textContaining('no longer a planned workout'), findsOneWidget);
|
||||
expect(
|
||||
github.files.containsKey('screen-locker-sync/devices/phone/log.json'),
|
||||
isFalse,
|
||||
);
|
||||
// Reloaded against the new day: it is done now, not planned.
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('2026-10-17 · Manual'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,178 @@
|
||||
// The workout date on the manual form: today up to a week ahead, the budget
|
||||
// read as of that date, and the refusals around it.
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:workout_app/screens/manual_workout_screen.dart';
|
||||
import 'package:workout_app/services/workout_sync_service.dart';
|
||||
|
||||
import '_manual_screen_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
group('workout date', () {
|
||||
testWidgets('a future date is pushed under that date', (tester) async {
|
||||
final sync = FakeManualSync();
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: sync, clock: fixedManualNow),
|
||||
);
|
||||
await pickDay(tester, '14');
|
||||
expect(find.text('Workout date: 2026-07-14 (tomorrow)'), findsOneWidget);
|
||||
await fillValidTt(tester);
|
||||
await tester.tap(find.text('SUBMIT'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(sync.pushed!.id, 'manual:2026-07-14T18:00');
|
||||
final payload = sync.pushed!.fields['payload']!.$1! as Map;
|
||||
expect(payload['date'], '2026-07-14');
|
||||
});
|
||||
|
||||
testWidgets('the picker offers today to today+7 only', (tester) async {
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(
|
||||
syncService: FakeManualSync(),
|
||||
clock: fixedManualNow,
|
||||
),
|
||||
);
|
||||
await tester.tap(find.text('CHANGE DATE'));
|
||||
await tester.pumpAndSettle();
|
||||
final picker = tester.widget<DatePickerDialog>(
|
||||
find.byType(DatePickerDialog),
|
||||
);
|
||||
expect(picker.firstDate, DateTime(2026, 7, 13));
|
||||
expect(picker.lastDate, DateTime(2026, 7, 20));
|
||||
expect(picker.initialDate, DateTime(2026, 7, 13));
|
||||
await tester.tap(find.text('20'));
|
||||
await tester.tap(find.text('OK'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Workout date: 2026-07-20 (in 7 days)'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('cancelling the picker keeps the date', (tester) async {
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(
|
||||
syncService: FakeManualSync(),
|
||||
clock: fixedManualNow,
|
||||
),
|
||||
);
|
||||
await tester.tap(find.text('CHANGE DATE'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Cancel'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Workout date: 2026-07-13 (today)'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('the budget follows the selected date', (tester) async {
|
||||
// 07-12 and a planned 07-18 share the window 07-12..07-18, which
|
||||
// contains today: today is full, 07-20 is not.
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(
|
||||
syncService: FakeManualSync(
|
||||
payloads: [manualEntry('2026-07-12'), manualEntry('2026-07-18')],
|
||||
),
|
||||
clock: fixedManualNow,
|
||||
),
|
||||
);
|
||||
expect(find.textContaining('2/2 per 7 days'), findsOneWidget);
|
||||
expect(find.textContaining('budget exhausted'), findsOneWidget);
|
||||
expect(find.text('SUBMIT'), findsNothing);
|
||||
// The date row stays reachable while the window is full.
|
||||
await pickDay(tester, '20');
|
||||
expect(
|
||||
find.text(
|
||||
'Manual around 2026-07-20: 1/2 per 7 days · 2/10 per 30 days',
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.textContaining('budget exhausted'), findsNothing);
|
||||
expect(find.text('SUBMIT'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('re-logging onto a deleted record is refused', (tester) async {
|
||||
final sync = FakeManualSync(tombstoned: {'manual:2026-07-13T18:00'});
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: sync, clock: fixedManualNow),
|
||||
);
|
||||
await fillValidTt(tester);
|
||||
await tester.tap(find.text('SUBMIT'));
|
||||
await tester.pump();
|
||||
expect(find.textContaining('was deleted earlier'), findsOneWidget);
|
||||
expect(sync.pushed, isNull);
|
||||
// A different start time is a different record id.
|
||||
await tester.enterText(find.byKey(const Key('mw_start_time')), '17:30');
|
||||
await tester.tap(find.text('SUBMIT'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(sync.pushed!.id, 'manual:2026-07-13T17:30');
|
||||
});
|
||||
|
||||
testWidgets('a failed push keeps the form open and says why', (
|
||||
tester,
|
||||
) async {
|
||||
final sync = FakeManualSync(
|
||||
result: const PushResult(pushed: false, reason: 'push failed: 500'),
|
||||
);
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: sync, clock: fixedManualNow),
|
||||
);
|
||||
await fillValidTt(tester);
|
||||
await tester.tap(find.text('SUBMIT'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(sync.pushed, isNotNull);
|
||||
expect(find.text('Not saved — push failed: 500'), findsOneWidget);
|
||||
expect(find.text('Log Manual Workout'), findsOneWidget);
|
||||
final submit = tester.widget<ElevatedButton>(
|
||||
find.widgetWithText(ElevatedButton, 'SUBMIT'),
|
||||
);
|
||||
expect(submit.onPressed, isNotNull);
|
||||
});
|
||||
|
||||
testWidgets('a date left behind by midnight is refused, then clamped', (
|
||||
tester,
|
||||
) async {
|
||||
var now = DateTime(2026, 7, 13, 23, 59);
|
||||
final sync = FakeManualSync();
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: sync, clock: () => now),
|
||||
);
|
||||
await fillValidTt(tester);
|
||||
now = DateTime(2026, 7, 14, 0, 1);
|
||||
await tester.tap(find.text('SUBMIT'));
|
||||
await tester.pump();
|
||||
expect(find.textContaining('is in the past'), findsOneWidget);
|
||||
expect(sync.pushed, isNull);
|
||||
// The picker would assert on an initial date before its range.
|
||||
await tester.tap(find.text('CHANGE DATE'));
|
||||
await tester.pumpAndSettle();
|
||||
final picker = tester.widget<DatePickerDialog>(
|
||||
find.byType(DatePickerDialog),
|
||||
);
|
||||
expect(picker.initialDate, DateTime(2026, 7, 14));
|
||||
await tester.tap(find.text('OK'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Workout date: 2026-07-14 (today)'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a date beyond the window is refused at submit', (
|
||||
tester,
|
||||
) async {
|
||||
// Only a clock moving backwards can get here; refuse rather than push.
|
||||
var now = DateTime(2026, 7, 13, 12);
|
||||
final sync = FakeManualSync();
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: sync, clock: () => now),
|
||||
);
|
||||
await pickDay(tester, '20');
|
||||
await fillValidTt(tester);
|
||||
now = DateTime(2026, 7, 12, 12);
|
||||
await tester.tap(find.text('SUBMIT'));
|
||||
await tester.pump();
|
||||
expect(find.textContaining('at most 7 days ahead'), findsOneWidget);
|
||||
expect(sync.pushed, isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -5,65 +5,21 @@ import 'package:workout_app/models/manual_workout.dart';
|
||||
import 'package:workout_app/screens/manual_workout_screen.dart';
|
||||
import 'package:workout_app/services/workout_sync_service.dart';
|
||||
|
||||
class _FakeSync extends WorkoutSyncService {
|
||||
_FakeSync({this.payloads = const []});
|
||||
|
||||
final List<Map<String, dynamic>> payloads;
|
||||
Record? pushed;
|
||||
|
||||
@override
|
||||
Future<List<Map<String, dynamic>>> readMergedManualPayloads() async =>
|
||||
payloads;
|
||||
|
||||
@override
|
||||
Future<PushResult> pushManual(Record record) async {
|
||||
pushed = record;
|
||||
return const PushResult(pushed: true, reason: 'pushed');
|
||||
}
|
||||
}
|
||||
|
||||
DateTime _fixedNow() => DateTime(2026, 7, 13, 20);
|
||||
|
||||
Future<void> _pump(WidgetTester tester, Widget child) async {
|
||||
// Tall viewport so the whole (long) form is laid out — a ListView only builds
|
||||
// children within the viewport, so off-screen widgets aren't findable.
|
||||
tester.view.physicalSize = const Size(500, 2600);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await tester.pumpWidget(MaterialApp(home: child));
|
||||
await tester.pumpAndSettle(); // let the budget future resolve
|
||||
}
|
||||
|
||||
Future<void> _fillValidTt(WidgetTester tester) async {
|
||||
Future<void> enter(String key, String value) =>
|
||||
tester.enterText(find.byKey(Key('mw_$key')), value);
|
||||
await enter('start_time', '18:00');
|
||||
await enter('end_time', '19:30');
|
||||
await enter('location_name', 'Solec');
|
||||
await enter('transport_method', 'bike');
|
||||
await enter('cost', '40 PLN');
|
||||
await enter('matches_won', '3');
|
||||
await enter('matches_lost', '1');
|
||||
await enter('sets_won', '7');
|
||||
await enter('sets_lost', '4');
|
||||
await enter('racket', 'Butterfly');
|
||||
await enter('balls', 'Nittaku');
|
||||
await enter('pain_or_injury', 'sore knee');
|
||||
await enter('went_well', 'Served consistently and moved feet well');
|
||||
await enter('to_improve', 'Backhand topspin needs more consistency');
|
||||
await enter('overall_feeling', 'Felt strong focused and in good rhythm');
|
||||
}
|
||||
import '_manual_screen_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('shows the form and budget when not exhausted', (tester) async {
|
||||
await _pump(
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: _FakeSync(), clock: _fixedNow),
|
||||
ManualWorkoutScreen(syncService: FakeManualSync(), clock: fixedManualNow),
|
||||
);
|
||||
expect(find.text('Log Manual Workout'), findsOneWidget);
|
||||
expect(find.text('SUBMIT'), findsOneWidget);
|
||||
expect(find.textContaining('0/2 this week'), findsOneWidget);
|
||||
expect(
|
||||
find.text('Manual around 2026-07-13: 0/2 per 7 days · 0/10 per 30 days'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text('Workout date: 2026-07-13 (today)'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('hides the form when the budget is exhausted', (tester) async {
|
||||
@ -84,11 +40,11 @@ void main() {
|
||||
'end_time': '19:00',
|
||||
},
|
||||
];
|
||||
await _pump(
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(
|
||||
syncService: _FakeSync(payloads: payloads),
|
||||
clock: _fixedNow,
|
||||
syncService: FakeManualSync(payloads: payloads),
|
||||
clock: fixedManualNow,
|
||||
),
|
||||
);
|
||||
expect(find.textContaining('budget exhausted'), findsOneWidget);
|
||||
@ -96,10 +52,10 @@ void main() {
|
||||
});
|
||||
|
||||
testWidgets('shows a validation error and does not push', (tester) async {
|
||||
final sync = _FakeSync();
|
||||
await _pump(
|
||||
final sync = FakeManualSync();
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: sync, clock: _fixedNow),
|
||||
ManualWorkoutScreen(syncService: sync, clock: fixedManualNow),
|
||||
);
|
||||
await tester.tap(find.text('SUBMIT'));
|
||||
await tester.pump();
|
||||
@ -108,12 +64,12 @@ void main() {
|
||||
});
|
||||
|
||||
testWidgets('valid table-tennis workout pushes and pops', (tester) async {
|
||||
final sync = _FakeSync();
|
||||
await _pump(
|
||||
final sync = FakeManualSync();
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: sync, clock: _fixedNow),
|
||||
ManualWorkoutScreen(syncService: sync, clock: fixedManualNow),
|
||||
);
|
||||
await _fillValidTt(tester);
|
||||
await fillValidTt(tester);
|
||||
await tester.tap(find.text('SUBMIT'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(sync.pushed, isNotNull);
|
||||
@ -124,9 +80,9 @@ void main() {
|
||||
});
|
||||
|
||||
testWidgets('switching sport reveals the other-sport fields', (tester) async {
|
||||
await _pump(
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: _FakeSync(), clock: _fixedNow),
|
||||
ManualWorkoutScreen(syncService: FakeManualSync(), clock: fixedManualNow),
|
||||
);
|
||||
expect(find.byKey(const Key('mw_matches_won')), findsOneWidget);
|
||||
await tester.tap(find.byType(DropdownButton<String>));
|
||||
@ -138,9 +94,9 @@ void main() {
|
||||
});
|
||||
|
||||
testWidgets('RPE slider updates the label', (tester) async {
|
||||
await _pump(
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: _FakeSync(), clock: _fixedNow),
|
||||
ManualWorkoutScreen(syncService: FakeManualSync(), clock: fixedManualNow),
|
||||
);
|
||||
expect(find.text('RPE 5'), findsOneWidget);
|
||||
await tester.drag(find.byType(Slider), const Offset(300, 0));
|
||||
@ -149,10 +105,10 @@ void main() {
|
||||
});
|
||||
|
||||
testWidgets('other-sport validation error pushes nothing', (tester) async {
|
||||
final sync = _FakeSync();
|
||||
await _pump(
|
||||
final sync = FakeManualSync();
|
||||
await pumpManual(
|
||||
tester,
|
||||
ManualWorkoutScreen(syncService: sync, clock: _fixedNow),
|
||||
ManualWorkoutScreen(syncService: sync, clock: fixedManualNow),
|
||||
);
|
||||
await tester.tap(find.byType(DropdownButton<String>));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
@ -0,0 +1,72 @@
|
||||
// readManualLedger: the manual payloads plus every tombstoned id, which the
|
||||
// form needs to refuse re-logging onto a deleted record.
|
||||
//
|
||||
// Split from workout_sync_read_test.dart for the 250-line cap.
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crdt_sync/crdt_sync.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart' as http_testing;
|
||||
|
||||
import '../fake_secure_storage.dart';
|
||||
import '_sync_test_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('readManualLedger', () {
|
||||
test('returns live manuals and every tombstoned id', () async {
|
||||
installFakeSecureStorage(initial: {'sync.token': 'tok'});
|
||||
final deleted = Record(
|
||||
id: 'manual:gone',
|
||||
fields: const {},
|
||||
deleted: true,
|
||||
deletedHlc: Hlc(wallTimeMs: 3000, counter: 0, nodeId: 'phone'),
|
||||
);
|
||||
final phoneLog = jsonEncode({'manual:gone': deleted.toJson()});
|
||||
final pcLog = jsonEncode({
|
||||
'manual:a': manualRecord('manual:a', 'NEW', 2000).toJson(),
|
||||
// Live on the PC, deleted on the phone: the tombstone wins.
|
||||
'manual:gone': manualRecord('manual:gone', 'X', 1000).toJson(),
|
||||
});
|
||||
final (:httpClient, putCalls: _) = mockGitHub(
|
||||
contentResponses: {
|
||||
'screen-locker-sync/devices': syncResponse(200, [
|
||||
{'name': 'phone'},
|
||||
{'name': 'pc'},
|
||||
]),
|
||||
'screen-locker-sync/devices/phone/log.json': fileContaining(phoneLog),
|
||||
'screen-locker-sync/devices/pc/log.json': fileContaining(pcLog),
|
||||
},
|
||||
);
|
||||
final ledger = await syncService(
|
||||
httpClient: httpClient,
|
||||
).readManualLedger();
|
||||
expect(ledger.payloads.map((p) => p['cost']), ['NEW']);
|
||||
expect(ledger.tombstoned, {'manual:gone'});
|
||||
});
|
||||
|
||||
test('is empty without a token', () async {
|
||||
installFakeSecureStorage();
|
||||
final (:httpClient, putCalls: _) = mockGitHub();
|
||||
final ledger = await syncService(
|
||||
httpClient: httpClient,
|
||||
).readManualLedger();
|
||||
expect(ledger.payloads, isEmpty);
|
||||
expect(ledger.tombstoned, isEmpty);
|
||||
});
|
||||
|
||||
test('is empty when the backend fails', () async {
|
||||
installFakeSecureStorage(initial: {'sync.token': 'tok'});
|
||||
final httpClient = http_testing.MockClient(
|
||||
(request) async => http.Response('', 500),
|
||||
);
|
||||
final ledger = await syncService(
|
||||
httpClient: httpClient,
|
||||
).readManualLedger();
|
||||
expect(ledger.payloads, isEmpty);
|
||||
expect(ledger.tombstoned, isEmpty);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -180,6 +180,52 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
test('tombstoneManual pushes a sticky delete for the id', () async {
|
||||
installFakeSecureStorage(initial: {'sync.token': 'tok'});
|
||||
final existing = jsonEncode({
|
||||
'manual:2026-07-20T10:00': manualRecord(
|
||||
'manual:2026-07-20T10:00',
|
||||
'40',
|
||||
1000,
|
||||
).toJson(),
|
||||
});
|
||||
final (:httpClient, :putCalls) = mockGitHub(
|
||||
contentResponses: {
|
||||
'screen-locker-sync/devices': syncResponse(200, []),
|
||||
'screen-locker-sync/devices/phone/log.json': fileContaining(existing),
|
||||
},
|
||||
);
|
||||
final result = await syncService(
|
||||
httpClient: httpClient,
|
||||
).tombstoneManual('manual:2026-07-20T10:00');
|
||||
expect(result.pushed, isTrue);
|
||||
final pushedLog =
|
||||
jsonDecode(
|
||||
utf8.decode(
|
||||
base64.decode(logPut(putCalls).body['content'] as String),
|
||||
),
|
||||
)
|
||||
as Map<String, dynamic>;
|
||||
final record = Record.fromJson(
|
||||
pushedLog['manual:2026-07-20T10:00'] as Map<String, dynamic>,
|
||||
);
|
||||
expect(record.deleted, isTrue);
|
||||
expect(record.deletedHlc, isNotNull);
|
||||
// The payload survives the merge; only the delete flag is added.
|
||||
expect((record.fields['payload']!.$1! as Map)['cost'], '40');
|
||||
});
|
||||
|
||||
test('tombstoneManual reports why when sync is not set up', () async {
|
||||
installFakeSecureStorage();
|
||||
final (:httpClient, :putCalls) = mockGitHub();
|
||||
final result = await syncService(
|
||||
httpClient: httpClient,
|
||||
).tombstoneManual('manual:2026-07-20T10:00');
|
||||
expect(result.pushed, isFalse);
|
||||
expect(result.reason, contains('not configured'));
|
||||
expect(putCalls, isEmpty);
|
||||
});
|
||||
|
||||
test('pushManual reports a failure instead of hiding it', () async {
|
||||
installFakeSecureStorage(initial: {'sync.token': 'tok'});
|
||||
final httpClient = http_testing.MockClient(
|
||||
|
||||
Loading…
Reference in New Issue
Block a user