LifeMate — Personal, Family & Learning Companion

feat/learning-content-operations
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 135 lines 4.55 KB
Raw
1 import 'api.dart';
2 import 'offline_store.dart';
3 import 'plan_sync.dart';
4
5 /// Mutations are persisted before sending. Pending events retain their exact
6 /// body and version, and must be acknowledged before another event is sent.
7 class StudySync {
8 StudySync(this.api, {OfflineStore? store})
9 : store = store ?? OfflineStore.forApi(api);
10 final HttpIdentityApi api;
11 final OfflineStore store;
12 Future<void>? _flush;
13 Future<MutationOutcome> start(String planItemId) async {
14 final sessionId = newMutationId();
15 final mutationId = newMutationId();
16 return _change(
17 'study_start',
18 sessionId,
19 {
20 'id': sessionId,
21 'mutationId': mutationId,
22 'planItemId': planItemId,
23 'source': 'timer',
24 'startedAt': DateTime.now().toUtc().toIso8601String()
25 },
26 mutationId,
27 0);
28 }
29
30 Future<MutationOutcome> event(
31 Map<String, dynamic> session, String action) async {
32 final id = newMutationId();
33 final version = int.tryParse(session['version'].toString()) ?? 0;
34 return _change(
35 'study_event',
36 session['id'].toString(),
37 {
38 'mutationId': id,
39 'expectedVersion': version,
40 'action': action,
41 'occurredAt': DateTime.now().toUtc().toIso8601String()
42 },
43 id,
44 version);
45 }
46
47 Future<MutationOutcome> archive(Map<String, dynamic> session) async {
48 final id = newMutationId();
49 final version = int.tryParse(session['version'].toString()) ?? 0;
50 return _change('study_archive', session['id'].toString(),
51 {'mutationId': id, 'expectedVersion': version}, id, version);
52 }
53
54 Future<MutationOutcome> _change(String operation, String entityId,
55 Map<String, dynamic> payload, String id, int version) async {
56 if ((await store.readQueue())
57 .any((m) => m['entityType'] == 'study_session')) {
58 throw const ApiException(409, 'sync_pending');
59 }
60 final mutation = <String, dynamic>{
61 'id': id,
62 'entityType': 'study_session',
63 'entityId': entityId,
64 'operation': operation,
65 'payload': payload,
66 'expectedVersion': version
67 };
68 await store.enqueue(mutation);
69 try {
70 return await _send(mutation);
71 } catch (error) {
72 if (isOfflineFailure(error)) return const MutationOutcome(queued: true);
73 rethrow;
74 }
75 }
76
77 Future<MutationOutcome> _send(Map<String, dynamic> mutation) async {
78 final body = Map<String, dynamic>.from(mutation['payload'] as Map);
79 final id = mutation['entityId'].toString();
80 Map<String, dynamic> response;
81 try {
82 response = switch (mutation['operation']) {
83 'study_start' => await api.startStudySession(body),
84 'study_event' => await api.recordStudySessionEvent(id, body),
85 'study_archive' => await api.archiveStudySession(id, body),
86 _ => throw const ApiException(422, 'invalid_study_mutation'),
87 };
88 } catch (error) {
89 if (error is ApiException && error.statusCode == 409) {
90 await store.markQueued(mutation['id'].toString(), 'conflict',
91 error: error.code);
92 }
93 rethrow;
94 }
95 final ack = response['acknowledgement'];
96 if (ack is! Map ||
97 ack['mutationId'] != mutation['id'] ||
98 !['accepted', 'already_applied'].contains(ack['status'])) {
99 throw const ApiException(502, 'invalid_sync_acknowledgement');
100 }
101 final raw = response['session'];
102 final acceptedAt = ack['acceptedAt'];
103 final expected = int.tryParse(mutation['expectedVersion'].toString()) ?? 0;
104 if (raw is! Map ||
105 raw['id'] != mutation['entityId'] ||
106 raw['version'] is! int ||
107 raw['version'] < expected + 1 ||
108 acceptedAt is! String ||
109 DateTime.tryParse(acceptedAt) == null) {
110 throw const ApiException(502, 'invalid_sync_acknowledgement');
111 }
112 final session = Map<String, dynamic>.from(raw);
113 await store.acknowledge(mutation['id'].toString(),
114 item: session, acceptedAt: acceptedAt, cacheKey: 'study.sessions');
115 return MutationOutcome(queued: false, item: session);
116 }
117
118 Future<void> flush() =>
119 _flush ??= _flushQueue().whenComplete(() => _flush = null);
120 Future<void> _flushQueue() async {
121 for (final m in await store.readQueue()) {
122 if (m['entityType'] != 'study_session') continue;
123 if (m['queueStatus'] == 'conflict') {
124 throw const ApiException(409, 'sync_conflict');
125 }
126 if (m['queueStatus'] != 'queued') continue;
127 try {
128 await _send(m);
129 } catch (error) {
130 if (isOfflineFailure(error)) return;
131 rethrow;
132 }
133 }
134 }
135 }