LifeMate — Personal, Family & Learning Companion

feat/standalone-weekly-planner
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 324 lines 11.5 KB
Raw
1 import 'dart:async';
2
3 import 'api.dart';
4 import 'offline_store.dart';
5 import 'plan_sync.dart' show newMutationId;
6
7 /// Explicit personal reports, never inferred from playback or elapsed time.
8 /// Pending writes are scoped to the authenticated API/account and persisted
9 /// before delivery. Only a matching server acknowledgement removes a write.
10 class LearningSync {
11 LearningSync(this.api, {OfflineStore? store})
12 : store = store ?? OfflineStore.forApi(api);
13
14 final HttpIdentityApi api;
15 final OfflineStore store;
16 static final _tails = <String, Future<void>>{};
17 static const _statuses = {'not_started', 'in_progress', 'completed'};
18 static const _progressCache = 'learning_progress';
19 static final _uuid =
20 RegExp(r'^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$');
21
22 void _checkScope() {
23 if (api.cacheNamespace != store.scope) {
24 throw const ApiException(401, 'cache_scope_closed');
25 }
26 }
27
28 Future<T> _serial<T>(Future<T> Function() operation) {
29 final previous = _tails[store.scope];
30 final release = Completer<void>();
31 _tails[store.scope] = release.future;
32 return (() async {
33 if (previous != null) await previous;
34 try {
35 _checkScope();
36 // Verify the handle generation before making an authenticated request.
37 await store.readQueue();
38 _checkScope();
39 final result = await operation();
40 _checkScope();
41 return result;
42 } finally {
43 if (identical(_tails[store.scope], release.future)) {
44 _tails.remove(store.scope);
45 }
46 release.complete();
47 }
48 })();
49 }
50
51 static bool _timestamp(dynamic value) =>
52 value is String &&
53 RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) &&
54 DateTime.tryParse(value) != null;
55
56 static Map<String, dynamic> _initialProgress(String unitId) => {
57 'id': unitId,
58 'unitId': unitId,
59 'status': 'not_started',
60 'source': 'self_reported',
61 'version': 0,
62 'updatedAt': null,
63 'pending_sync': false,
64 'acknowledged': false,
65 };
66
67 static Map<String, dynamic> _serverProgress(dynamic raw, String unitId) {
68 if (raw is! Map ||
69 raw['unitId'] != unitId ||
70 !_statuses.contains(raw['status']) ||
71 raw['source'] != 'self_reported' ||
72 raw['version'] is! int ||
73 raw['version'] < 0 ||
74 (raw['version'] > 0 && !_timestamp(raw['updatedAt']))) {
75 throw const ApiException(502, 'invalid_learning_progress');
76 }
77 return {
78 ...Map<String, dynamic>.from(raw),
79 'id': unitId,
80 'pending_sync': false,
81 'acknowledged': raw['version'] > 0,
82 };
83 }
84
85 Future<List<Map<String, dynamic>>> pendingFor(String unitId) async {
86 _checkScope();
87 final pending = (await store.readQueue())
88 .where((m) =>
89 m['entityType'] == 'learning_progress' && m['entityId'] == unitId)
90 .toList();
91 _checkScope();
92 return pending;
93 }
94
95 Future<Map<String, dynamic>> readCourse(String id) => _serial(() async {
96 if (!_uuid.hasMatch(id)) {
97 throw const ApiException(400, 'invalid_course_id');
98 }
99 final key = 'learning.course:$id';
100 Map<String, dynamic> course;
101 var offline = false;
102 try {
103 final response = await api.requestJson(
104 'GET', '/v1/education/courses/${Uri.encodeComponent(id)}');
105 _checkScope();
106 final raw = response['course'] ?? response;
107 if (raw is! Map || raw['id'] != id || raw['units'] is! List) {
108 throw const ApiException(502, 'invalid_learning_course');
109 }
110 course = Map<String, dynamic>.from(raw);
111 final known = await store.readList(_progressCache);
112 final ids = <String>{};
113 for (final rawUnit in course['units'] as List) {
114 if (rawUnit is! Map ||
115 rawUnit['id'] is! String ||
116 !_uuid.hasMatch(rawUnit['id']) ||
117 !ids.add(rawUnit['id'])) {
118 throw const ApiException(502, 'invalid_learning_course');
119 }
120 final unitId = rawUnit['id'] as String;
121 final progress = rawUnit['progress'];
122 final server = progress == null
123 ? _initialProgress(unitId)
124 : _serverProgress(progress, unitId);
125 known.removeWhere((p) => p['id'] == unitId);
126 known.add(server);
127 }
128 await store.writeList(_progressCache, known);
129 await store.writeList(key, [course]);
130 } catch (error) {
131 _checkScope();
132 if (!isOfflineFailure(error)) rethrow;
133 final cached = await store.readList(key);
134 if (cached.length != 1) rethrow;
135 course = cached.single;
136 offline = true;
137 }
138 _checkScope();
139 return {
140 ...course,
141 'offline': offline,
142 'units': await _overlayUnits(course['units'] as List),
143 };
144 });
145
146 Future<List<Map<String, dynamic>>> _overlayUnits(List units) async {
147 final known = await store.readList(_progressCache);
148 final pending = await store.readQueue();
149 return [
150 for (final raw in units)
151 {
152 ...Map<String, dynamic>.from(raw as Map),
153 'progress': _overlayProgress(
154 raw['id'] as String,
155 known.where((p) => p['unitId'] == raw['id']).firstOrNull ??
156 _initialProgress(raw['id'] as String),
157 pending),
158 }
159 ];
160 }
161
162 static Map<String, dynamic> _overlayProgress(
163 String id, Map<String, dynamic> base, List<Map<String, dynamic>> queue) {
164 final mutation = queue
165 .where((m) =>
166 m['entityType'] == 'learning_progress' && m['entityId'] == id)
167 .firstOrNull;
168 if (mutation == null) return Map<String, dynamic>.from(base);
169 final payload = mutation['payload'] as Map;
170 return {
171 ...base,
172 'id': id,
173 'unitId': id,
174 'status': payload['status'],
175 'source': 'self_reported',
176 // Retain the acknowledged version; an unsent change has no new version.
177 'version': payload['expectedVersion'],
178 'pending_sync': true,
179 'acknowledged': false,
180 'mutationId': mutation['id'],
181 'queueStatus': mutation['queueStatus'],
182 'sync_conflict': mutation['queueStatus'] == 'conflict',
183 'lastError': mutation['lastError'],
184 'queuedAt': mutation['queuedAt'],
185 };
186 }
187
188 Future<Map<String, dynamic>> setProgress(
189 String unitId, String status, int expectedVersion) =>
190 _serial(() async {
191 if (!_uuid.hasMatch(unitId) ||
192 !_statuses.contains(status) ||
193 expectedVersion < 0) {
194 throw const ApiException(400, 'invalid_learning_progress');
195 }
196 if ((await pendingFor(unitId)).isNotEmpty) {
197 throw const ApiException(409, 'sync_pending');
198 }
199 final mutationId = newMutationId();
200 final mutation = <String, dynamic>{
201 'id': mutationId,
202 'entityId': unitId,
203 'entityType': 'learning_progress',
204 'operation': 'set_progress',
205 'expectedVersion': expectedVersion,
206 'payload': {
207 'status': status,
208 'source': 'self_reported',
209 'mutationId': mutationId,
210 'expectedVersion': expectedVersion,
211 },
212 };
213 // Do not use optimisticItem: that helper writes planner caches.
214 await store.enqueue(mutation);
215 try {
216 final accepted = await _send(mutation);
217 return {'queued': false, 'progress': accepted};
218 } catch (error) {
219 _checkScope();
220 if (!isOfflineFailure(error)) rethrow;
221 final known = await store.readList(_progressCache);
222 return {
223 'queued': true,
224 'progress': _overlayProgress(
225 unitId,
226 known.where((p) => p['unitId'] == unitId).firstOrNull ??
227 _initialProgress(unitId),
228 await store.readQueue()),
229 };
230 }
231 });
232
233 Future<Map<String, dynamic>> _send(Map<String, dynamic> mutation) async {
234 _checkScope();
235 final payload = Map<String, dynamic>.from(mutation['payload'] as Map);
236 final unitId = mutation['entityId'] as String;
237 final expected = payload['expectedVersion'];
238 if (mutation['entityType'] != 'learning_progress' ||
239 mutation['operation'] != 'set_progress' ||
240 !_uuid.hasMatch(unitId) ||
241 payload['mutationId'] != mutation['id'] ||
242 expected is! int ||
243 expected < 0 ||
244 payload['source'] != 'self_reported' ||
245 !_statuses.contains(payload['status'])) {
246 throw const ApiException(422, 'invalid_learning_mutation');
247 }
248 final Map<String, dynamic> ack;
249 try {
250 ack = await api.requestJson(
251 'PUT', '/v1/me/learning-progress/${Uri.encodeComponent(unitId)}',
252 body: payload);
253 _checkScope();
254 } catch (error) {
255 _checkScope();
256 if (error is ApiException && error.statusCode == 409) {
257 await store.markQueued(mutation['id'] as String, 'conflict',
258 error: error.code);
259 }
260 rethrow;
261 }
262 if (ack['mutationId'] != mutation['id'] ||
263 ack['unitId'] != unitId ||
264 ack['status'] != payload['status'] ||
265 ack['source'] != 'self_reported' ||
266 ack['version'] is! int ||
267 ack['version'] != expected + 1 ||
268 !_timestamp(ack['updatedAt']) ||
269 !_timestamp(ack['acceptedAt'])) {
270 throw const ApiException(502, 'invalid_sync_acknowledgement');
271 }
272 final progress = _serverProgress(ack, unitId);
273 await store.acknowledge(mutation['id'] as String,
274 item: progress,
275 acceptedAt: ack['acceptedAt'] as String,
276 cacheKey: _progressCache);
277 return progress;
278 }
279
280 Future<void> flush() => _serial(() async {
281 for (final pending in await store.readQueue()) {
282 if (pending['entityType'] != 'learning_progress') continue;
283 if (pending['queueStatus'] == 'conflict') {
284 throw const ApiException(409, 'sync_conflict');
285 }
286 if (pending['queueStatus'] != 'queued') continue;
287 try {
288 await _send(pending);
289 } catch (error) {
290 if (isOfflineFailure(error)) return;
291 rethrow;
292 }
293 }
294 });
295
296 /// User-selected server value; preserve the rejected report in the durable
297 /// recovery journal in the same write that removes it from the queue.
298 Future<void> resolveUsingServer(String unitId) => _serial(() async {
299 if ((await pendingFor(unitId)).isEmpty) return;
300 final response =
301 await api.requestJson('GET', '/v1/me/learning-progress');
302 _checkScope();
303 final list = response['progress'];
304 if (list is! List || list.any((p) => p is! Map)) {
305 throw const ApiException(502, 'invalid_learning_progress');
306 }
307 final matches = list.where((p) => p['unitId'] == unitId).toList();
308 if (matches.length != 1) {
309 throw const ApiException(502, 'invalid_learning_progress');
310 }
311 final progress = _serverProgress(matches.single, unitId);
312 // The shared store's legacy journal helper filters by entity ID. Do
313 // not let an independently named planner/session record be discarded
314 // by a choice that concerns only lesson progress.
315 final queue = await store.readQueue();
316 if (queue.any((m) =>
317 m['entityId'] == unitId &&
318 m['entityType'] != 'learning_progress')) {
319 throw const ApiException(409, 'sync_entity_collision');
320 }
321 await store.discardEntityChanges(unitId,
322 serverItem: progress, cacheKey: _progressCache);
323 });
324 }