LifeMate — Personal, Family & Learning Companion
feat/weekly-planner-android
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
| 1 | import 'dart:async'; |
| 2 | import 'dart:math'; |
| 3 | import 'api.dart'; |
| 4 | import 'offline_store.dart'; |
| 5 | import 'local_reminders.dart'; |
| 6 | |
| 7 | String newMutationId() { |
| 8 | final random = Random.secure(); |
| 9 | final bytes = List.generate(16, (_) => random.nextInt(256)); |
| 10 | bytes[6] = (bytes[6] & 15) | 64; |
| 11 | bytes[8] = (bytes[8] & 63) | 128; |
| 12 | final hex = bytes.map((n) => n.toRadixString(16).padLeft(2, '0')).join(); |
| 13 | return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}'; |
| 14 | } |
| 15 | |
| 16 | class MutationOutcome { |
| 17 | const MutationOutcome({required this.queued, this.item}); |
| 18 | final bool queued; |
| 19 | final Map<String, dynamic>? item; |
| 20 | } |
| 21 | |
| 22 | class PlanSync { |
| 23 | PlanSync(this.api, {OfflineStore? store, LocalReminderPort? reminders}) |
| 24 | : store = store ?? OfflineStore.forApi(api), |
| 25 | reminders = reminders ?? androidLocalReminders; |
| 26 | final IdentityApi api; |
| 27 | final OfflineStore store; |
| 28 | final LocalReminderPort reminders; |
| 29 | Future<T> withLocalMutationLock<T>(Future<T> Function() work) => |
| 30 | _serial(work); |
| 31 | static final _tails = <String, Future<void>>{}; |
| 32 | Future<T> _serial<T>(Future<T> Function() operation) { |
| 33 | final previous = _tails[store.scope]; |
| 34 | final release = Completer<void>(); |
| 35 | _tails[store.scope] = release.future; |
| 36 | return (() async { |
| 37 | if (previous != null) await previous; |
| 38 | try { |
| 39 | return await operation(); |
| 40 | } finally { |
| 41 | if (identical(_tails[store.scope], release.future)) { |
| 42 | _tails.remove(store.scope); |
| 43 | } |
| 44 | release.complete(); |
| 45 | } |
| 46 | })(); |
| 47 | } |
| 48 | |
| 49 | Future<MutationOutcome> create(Map<String, dynamic> payload) { |
| 50 | final item = <String, dynamic>{ |
| 51 | 'id': newMutationId(), |
| 52 | 'kind': payload['kind'] ?? 'task', |
| 53 | 'title': payload['title'], |
| 54 | 'status': 'planned', |
| 55 | 'visibility': payload['visibility'] ?? 'private', |
| 56 | 'due_at': payload['dueAt'], |
| 57 | 'starts_at': payload['startsAt'], |
| 58 | 'version': 0, |
| 59 | 'pending_sync': true, |
| 60 | 'acknowledged': false |
| 61 | }; |
| 62 | return _change('create', item, payload); |
| 63 | } |
| 64 | |
| 65 | Future<MutationOutcome> update( |
| 66 | Map<String, dynamic> item, Map<String, dynamic> changes) => |
| 67 | _change('update', item, changes); |
| 68 | Future<MutationOutcome> complete(Map<String, dynamic> item) => |
| 69 | _change('complete', item, {'status': 'completed'}); |
| 70 | Future<MutationOutcome> archive(Map<String, dynamic> item) => |
| 71 | _change('archive', item, {'status': 'cancelled'}); |
| 72 | Future<MutationOutcome> _change(String operation, Map<String, dynamic> item, |
| 73 | Map<String, dynamic> payload) => |
| 74 | _serial(() async { |
| 75 | final expected = int.tryParse(item['version'].toString()) ?? 0; |
| 76 | final mutation = <String, dynamic>{ |
| 77 | 'id': newMutationId(), |
| 78 | 'entityType': 'plan_item', |
| 79 | 'entityId': item['id'], |
| 80 | 'operation': operation, |
| 81 | 'expectedVersion': expected, |
| 82 | 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(), |
| 83 | 'payload': payload |
| 84 | }; |
| 85 | final optimistic = optimisticPlanItem(item, mutation); |
| 86 | await store.enqueue(mutation, optimisticItem: optimistic); |
| 87 | try { |
| 88 | await reminders |
| 89 | .suppressPlanItems(store.scope, {item['id'] as String}); |
| 90 | } catch (_) { |
| 91 | // Do not leave a stale alarm after a durable offline edit. If targeted |
| 92 | // cancellation fails, remove this device's full reminder opt-in. |
| 93 | await reminders.deactivate(); |
| 94 | } |
| 95 | try { |
| 96 | await _flushQueue(); |
| 97 | final pending = |
| 98 | (await store.readQueue()).any((m) => m['id'] == mutation['id']); |
| 99 | final cached = (await store.readPlanner()) |
| 100 | .where((m) => m['id'] == item['id']) |
| 101 | .firstOrNull; |
| 102 | return MutationOutcome(queued: pending, item: cached ?? optimistic); |
| 103 | } catch (error) { |
| 104 | if (isOfflineFailure(error)) { |
| 105 | return MutationOutcome(queued: true, item: optimistic); |
| 106 | } |
| 107 | rethrow; |
| 108 | } |
| 109 | }); |
| 110 | |
| 111 | Future<MutationOutcome> _send(Map<String, dynamic> mutation) async { |
| 112 | final response = await api.submitSyncMutations([mutation]); |
| 113 | final results = response['results']; |
| 114 | if (results is! List || |
| 115 | results.length != 1 || |
| 116 | results.single is! Map || |
| 117 | (results.single as Map)['id'] != mutation['id']) { |
| 118 | throw const ApiException(502, 'invalid_sync_acknowledgement'); |
| 119 | } |
| 120 | final result = results.single as Map; |
| 121 | if (result['status'] == 'accepted' || |
| 122 | result['status'] == 'already_applied') { |
| 123 | final rawItem = result['item']; |
| 124 | final version = |
| 125 | rawItem is Map ? int.tryParse(rawItem['version'].toString()) : null; |
| 126 | final expected = |
| 127 | int.tryParse(mutation['expectedVersion'].toString()) ?? 0; |
| 128 | final acceptedAt = result['acceptedAt']; |
| 129 | if (rawItem is! Map || |
| 130 | rawItem['id'] != mutation['entityId'] || |
| 131 | version == null || |
| 132 | version < expected + 1 || |
| 133 | acceptedAt is! String || |
| 134 | DateTime.tryParse(acceptedAt) == null) { |
| 135 | throw const ApiException(502, 'invalid_sync_acknowledgement'); |
| 136 | } |
| 137 | final item = Map<String, dynamic>.from(rawItem); |
| 138 | await store.acknowledge(mutation['id'] as String, |
| 139 | item: item, acceptedAt: result['acceptedAt'] as String?); |
| 140 | return MutationOutcome(queued: false, item: item); |
| 141 | } |
| 142 | final conflict = result['status'] == 'conflict'; |
| 143 | await store.markQueued( |
| 144 | mutation['id'] as String, conflict ? 'conflict' : 'rejected', |
| 145 | error: result['error']?.toString()); |
| 146 | throw ApiException( |
| 147 | conflict ? 409 : 422, |
| 148 | conflict |
| 149 | ? 'sync_conflict' |
| 150 | : (result['error']?.toString() ?? 'sync_rejected')); |
| 151 | } |
| 152 | |
| 153 | Future<void> flush() => _serial(_flushQueue); |
| 154 | Future<void> _flushQueue() async { |
| 155 | for (final queued in await store.readQueue()) { |
| 156 | if (queued['entityType'] != 'plan_item') continue; |
| 157 | if (queued['queueStatus'] == 'conflict') { |
| 158 | throw const ApiException(409, 'sync_conflict'); |
| 159 | } |
| 160 | if (queued['queueStatus'] != 'queued') continue; |
| 161 | final mutation = Map<String, dynamic>.from(queued) |
| 162 | ..remove('queuedAt') |
| 163 | ..remove('queueStatus') |
| 164 | ..remove('lastError'); |
| 165 | try { |
| 166 | await _send(mutation); |
| 167 | } catch (error) { |
| 168 | if (isOfflineFailure(error)) return; |
| 169 | rethrow; |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | } |