LifeMate — Personal, Family & Learning Companion

feat/flutter-mobile-navigation
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
dart 160 lines 5.69 KB
Raw
1 import 'dart:async';
2 import 'dart:math';
3 import 'api.dart';
4 import 'offline_store.dart';
5
6 String newMutationId() {
7 final random = Random.secure();
8 final bytes = List.generate(16, (_) => random.nextInt(256));
9 bytes[6] = (bytes[6] & 15) | 64;
10 bytes[8] = (bytes[8] & 63) | 128;
11 final hex = bytes.map((n) => n.toRadixString(16).padLeft(2, '0')).join();
12 return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';
13 }
14
15 class MutationOutcome {
16 const MutationOutcome({required this.queued, this.item});
17 final bool queued;
18 final Map<String, dynamic>? item;
19 }
20
21 class PlanSync {
22 PlanSync(this.api, {OfflineStore? store})
23 : store = store ?? OfflineStore.forApi(api);
24 final IdentityApi api;
25 final OfflineStore store;
26 static final _tails = <String, Future<void>>{};
27 Future<T> _serial<T>(Future<T> Function() operation) {
28 final previous = _tails[store.scope];
29 final release = Completer<void>();
30 _tails[store.scope] = release.future;
31 return (() async {
32 if (previous != null) await previous;
33 try {
34 return await operation();
35 } finally {
36 if (identical(_tails[store.scope], release.future)) {
37 _tails.remove(store.scope);
38 }
39 release.complete();
40 }
41 })();
42 }
43
44 Future<MutationOutcome> create(Map<String, dynamic> payload) {
45 final item = <String, dynamic>{
46 'id': newMutationId(),
47 'kind': payload['kind'] ?? 'task',
48 'title': payload['title'],
49 'status': 'planned',
50 'visibility': payload['visibility'] ?? 'private',
51 'due_at': payload['dueAt'],
52 'starts_at': payload['startsAt'],
53 'version': 0,
54 'pending_sync': true,
55 'acknowledged': false
56 };
57 return _change('create', item, payload);
58 }
59
60 Future<MutationOutcome> update(
61 Map<String, dynamic> item, Map<String, dynamic> changes) =>
62 _change('update', item, changes);
63 Future<MutationOutcome> complete(Map<String, dynamic> item) =>
64 _change('complete', item, {'status': 'completed'});
65 Future<MutationOutcome> archive(Map<String, dynamic> item) =>
66 _change('archive', item, {'status': 'cancelled'});
67 Future<MutationOutcome> _change(String operation, Map<String, dynamic> item,
68 Map<String, dynamic> payload) =>
69 _serial(() async {
70 final expected = int.tryParse(item['version'].toString()) ?? 0;
71 final mutation = <String, dynamic>{
72 'id': newMutationId(),
73 'entityType': 'plan_item',
74 'entityId': item['id'],
75 'operation': operation,
76 'expectedVersion': expected,
77 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
78 'payload': payload
79 };
80 final optimistic = optimisticPlanItem(item, mutation);
81 await store.enqueue(mutation, optimisticItem: optimistic);
82 try {
83 await _flushQueue();
84 final pending =
85 (await store.readQueue()).any((m) => m['id'] == mutation['id']);
86 final cached = (await store.readPlanner())
87 .where((m) => m['id'] == item['id'])
88 .firstOrNull;
89 return MutationOutcome(queued: pending, item: cached ?? optimistic);
90 } catch (error) {
91 if (isOfflineFailure(error)) {
92 return MutationOutcome(queued: true, item: optimistic);
93 }
94 rethrow;
95 }
96 });
97
98 Future<MutationOutcome> _send(Map<String, dynamic> mutation) async {
99 final response = await api.submitSyncMutations([mutation]);
100 final results = response['results'];
101 if (results is! List ||
102 results.length != 1 ||
103 results.single is! Map ||
104 (results.single as Map)['id'] != mutation['id']) {
105 throw const ApiException(502, 'invalid_sync_acknowledgement');
106 }
107 final result = results.single as Map;
108 if (result['status'] == 'accepted' ||
109 result['status'] == 'already_applied') {
110 final rawItem = result['item'];
111 final version =
112 rawItem is Map ? int.tryParse(rawItem['version'].toString()) : null;
113 final expected =
114 int.tryParse(mutation['expectedVersion'].toString()) ?? 0;
115 final acceptedAt = result['acceptedAt'];
116 if (rawItem is! Map ||
117 rawItem['id'] != mutation['entityId'] ||
118 version == null ||
119 version < expected + 1 ||
120 acceptedAt is! String ||
121 DateTime.tryParse(acceptedAt) == null) {
122 throw const ApiException(502, 'invalid_sync_acknowledgement');
123 }
124 final item = Map<String, dynamic>.from(rawItem);
125 await store.acknowledge(mutation['id'] as String,
126 item: item, acceptedAt: result['acceptedAt'] as String?);
127 return MutationOutcome(queued: false, item: item);
128 }
129 final conflict = result['status'] == 'conflict';
130 await store.markQueued(
131 mutation['id'] as String, conflict ? 'conflict' : 'rejected',
132 error: result['error']?.toString());
133 throw ApiException(
134 conflict ? 409 : 422,
135 conflict
136 ? 'sync_conflict'
137 : (result['error']?.toString() ?? 'sync_rejected'));
138 }
139
140 Future<void> flush() => _serial(_flushQueue);
141 Future<void> _flushQueue() async {
142 for (final queued in await store.readQueue()) {
143 if (queued['entityType'] != 'plan_item') continue;
144 if (queued['queueStatus'] == 'conflict') {
145 throw const ApiException(409, 'sync_conflict');
146 }
147 if (queued['queueStatus'] != 'queued') continue;
148 final mutation = Map<String, dynamic>.from(queued)
149 ..remove('queuedAt')
150 ..remove('queueStatus')
151 ..remove('lastError');
152 try {
153 await _send(mutation);
154 } catch (error) {
155 if (isOfflineFailure(error)) return;
156 rethrow;
157 }
158 }
159 }
160 }