wake-alarm/phone_app/lib/services/free_day_sync.dart
Krzysztof kuhy Rudnicki 146c427d6d Add the free-day picker, and stop the phone ringing on a free day
The shared pool (~/utils/freedays) was CLI-only: the gates on the PC stood
down, but the phone kept ringing at 08:00 and there was nowhere to mark a
day from bed. This is the one picker for every app.

FreeDayPool is a Dart port of the Python rules with the identical record
shape (id = ISO date; state/consumed/actor/reason on one tick; un-mark is
a state flip, never a tombstone), verified by a real cross-language round
trip: a log written here reads back through freedays.is_free_day and
remaining() with the same verdicts and count, and the PC's live pool reads
here as the same 27 of 35 that `freedays status` prints.

The alarm fires from Kotlin with no engine running, so the pool is
mirrored into a native SharedPreferences set after every mark, release and
sync (channel method setFreeDays), and AlarmReceiver consults it before
starting AlarmService. Fail closed: a missing or corrupt cache rings. All
three branches exercised on the API 36 AVD by broadcasting the receiver.

Firebase only for this namespace -- no GitHub mirror; the alarm record
keeps its own because un-migrated installs depend on it.

Known gap, documented rather than papered over: a day marked on the PC
reaches the phone at the next app launch or picker open, not overnight.
The ring path takes no background dependency by design, so mark on the
phone, or open the app once after marking on the PC.

Verified on the phone (release build, 23181JEGR08034): picker shows the
budget, marks 2026-09-30 with a reason, pushes it to
freedays-sync/devices/<uuid>, releases it with a full refund back to 35.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019pBgaXSJKyY3DarYpDatDF
2026-09-11 13:45:42 +02:00

89 lines
3.0 KiB
Dart

import 'dart:developer' as developer;
import 'package:crdt_sync/crdt_sync.dart';
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
import 'package:wake_alarm_sync/services/firebase_backend.dart';
import 'package:wake_alarm_sync/services/free_day_pool.dart';
/// Moves the free-day pool between this phone and every other device.
///
/// Firebase only. The alarm record keeps its GitHub mirror because that
/// fallback is load-bearing for un-migrated installs; this namespace is new
/// and has no such history, so it gets no second transport.
///
/// Every sync ends by handing the merged pool to the native ring path
/// ([AlarmScheduler.setFreeDays]) — that cache, not the Dart store, is what
/// decides whether the phone rings, so it must never lag a sync.
class FreeDaySync {
/// Creates a syncer; both seams are injectable for tests.
FreeDaySync({
Future<RemoteStore?> Function()? openClient,
AlarmScheduler? scheduler,
}) : _openClient = openClient ?? openFirebase,
_scheduler = scheduler ?? AlarmScheduler();
final Future<RemoteStore?> Function() _openClient;
final AlarmScheduler _scheduler;
/// Pulls, merges and pushes [pool], then refreshes the native cache.
///
/// Returns a status line for the screen. Never throws: this also runs
/// unattended at launch, where a dead network must degrade to a message.
/// The native cache is refreshed even when the sync could not run, so a
/// day marked offline still stands the phone down.
Future<String> sync(FreeDayPool pool) async {
final RemoteStore? client;
try {
client = await _openClient();
} on Object catch (error, stackTrace) {
developer.log(
'free-day sync: could not open Firebase',
name: 'FreeDaySync',
error: error,
stackTrace: stackTrace,
);
await publishToNative(pool);
return 'Error: $error';
}
if (client == null) {
await publishToNative(pool);
return 'Not synced — connect Firebase in Settings.';
}
try {
final merged = await syncLog(
client: client,
deviceId: pool.deviceId,
pathPrefix: FreeDayPool.pathPrefix,
filename: FreeDayPool.filename,
localLog: pool.snapshot(),
encode: logToJson,
decode: logFromJson,
commitMessage: 'freedays: update pool',
);
await pool.replaceAll(merged);
return 'Synced ✓';
} on Exception catch (e) {
return 'Error: $e';
} finally {
await publishToNative(pool);
}
}
/// Writes the pool's free dates where `AlarmReceiver` can read them.
///
/// Swallows a missing platform (widget tests, a probe entry point): the
/// Dart pool is still correct, and the cache is rewritten on the next
/// launch anyway.
Future<void> publishToNative(FreeDayPool pool) async {
try {
await _scheduler.setFreeDays(pool.freeIsoDates());
} on Object catch (error) {
developer.log(
'free-day cache not written: $error',
name: 'FreeDaySync',
error: error,
);
}
}
}