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 195 lines 7.01 KB
Raw
1 import 'dart:async';
2 import 'dart:convert';
3
4 import 'api.dart';
5 import 'offline_store.dart';
6 import 'plan_sync.dart' show newMutationId;
7
8 class PlannerSeriesOutcome {
9 const PlannerSeriesOutcome({required this.queued, required this.id});
10 final bool queued;
11 final String id;
12 }
13
14 /// An unsent series is a durable draft, never a fabricated server occurrence.
15 /// The UUID and frozen payload survive a lost response and process restart.
16 class PlannerSeriesSync {
17 PlannerSeriesSync(this.api, {OfflineStore? store})
18 : store = store ?? OfflineStore.forApi(api),
19 _scope = api.cacheNamespace;
20 final HttpIdentityApi api;
21 final OfflineStore store;
22 final String? _scope;
23 static final _tails = <String, Future<void>>{};
24
25 void _checkScope() {
26 if (_scope == null || api.cacheNamespace != _scope) {
27 throw const ApiException(401, 'cache_scope_closed');
28 }
29 }
30
31 Future<T> _serial<T>(Future<T> Function() action) async {
32 final previous = _tails[store.scope];
33 final release = Completer<void>();
34 _tails[store.scope] = release.future;
35 if (previous != null) await previous;
36 try {
37 _checkScope();
38 return await action();
39 } finally {
40 if (identical(_tails[store.scope], release.future)) {
41 _tails.remove(store.scope);
42 }
43 release.complete();
44 }
45 }
46
47 Future<PlannerSeriesOutcome> create(Map<String, dynamic> payload,
48 {String? id}) =>
49 _serial(() async {
50 final seriesId = id ?? newMutationId();
51 final body = <String, dynamic>{...payload, 'id': seriesId};
52 final existing = (await store.readQueue())
53 .where((m) =>
54 m['entityType'] == 'planner_series' &&
55 m['entityId'] == seriesId)
56 .firstOrNull;
57 if (existing != null) {
58 if (_canonical(existing['payload']) != _canonical(body)) {
59 throw const ApiException(409, 'mutation_id_reused');
60 }
61 _throwTerminal(existing);
62 } else {
63 // An already acknowledged retry cannot create another series.
64 final accepted = (await store.readList('planner_series'))
65 .where((s) => s['id'] == seriesId)
66 .firstOrNull;
67 if (accepted != null) {
68 if (_canonical(accepted['_create_payload']) != _canonical(body)) {
69 throw const ApiException(409, 'mutation_id_reused');
70 }
71 return PlannerSeriesOutcome(queued: false, id: seriesId);
72 }
73 await store.enqueue({
74 'id': seriesId,
75 'entityType': 'planner_series',
76 'entityId': seriesId,
77 'operation': 'create',
78 'payload': body,
79 });
80 }
81 await _flush();
82 return PlannerSeriesOutcome(
83 queued: (await store.readQueue()).any((m) => m['id'] == seriesId),
84 id: seriesId);
85 });
86
87 Future<void> flush() => _serial(_flush);
88
89 void _throwTerminal(Map<String, dynamic> queued) {
90 if (queued['queueStatus'] == 'conflict' ||
91 queued['queueStatus'] == 'rejected') {
92 throw ApiException(queued['queueStatus'] == 'conflict' ? 409 : 422,
93 queued['lastError']?.toString() ?? 'sync_rejected');
94 }
95 }
96
97 Future<void> _flush() async {
98 for (final queued in await store.readQueue()) {
99 if (queued['entityType'] != 'planner_series') continue;
100 // A rejected draft stays visible in the recovery journal; it must not
101 // prevent unrelated plans from loading or other drafts from syncing.
102 if (queued['queueStatus'] == 'conflict' ||
103 queued['queueStatus'] == 'rejected') {
104 continue;
105 }
106 _checkScope();
107 try {
108 final response = await api.requestJson('POST', '/v1/planner-series',
109 body: Map<String, dynamic>.from(queued['payload'] as Map));
110 _checkScope();
111 final series = response['series'];
112 final items = response['items'];
113 if (series is! Map ||
114 series['id'] != queued['entityId'] ||
115 series['owner_user_id'] != api.currentUserId ||
116 (int.tryParse(series['version'].toString()) ?? 0) < 1 ||
117 items is! List ||
118 items.any((item) =>
119 item is! Map ||
120 item['id'] is! String ||
121 item['series_id'] != series['id'] ||
122 item['owner_user_id'] != api.currentUserId)) {
123 throw const ApiException(502, 'invalid_series_acknowledgement');
124 }
125 await store.acknowledge(queued['id'] as String,
126 item: {
127 ...Map<String, dynamic>.from(series),
128 '_create_payload': queued['payload']
129 },
130 cacheKey: 'planner_series');
131 // Fresh occurrence rows merge with other queued item edits in the store.
132 final planner = await store.readPlanner();
133 final byId = {for (final row in planner) row['id']: row};
134 for (final row in items) {
135 byId[row['id']] = Map<String, dynamic>.from(row);
136 }
137 await store.cachePlanner(byId.values.toList());
138 } catch (error) {
139 if (isOfflineFailure(error)) return;
140 if (error is ApiException &&
141 error.statusCode >= 400 &&
142 error.statusCode < 500 &&
143 error.statusCode != 401 &&
144 error.statusCode != 429) {
145 await store.markQueued(queued['id'] as String,
146 error.statusCode == 409 ? 'conflict' : 'rejected',
147 error: error.code);
148 }
149 rethrow;
150 }
151 }
152 }
153
154 /// Repeated materialization only fills missing dates; occurrence edits stay.
155 Future<void> materialize(DateTime from, DateTime to) async {
156 _checkScope();
157 final response = await api.requestJson('GET', '/v1/planner-series');
158 _checkScope();
159 final series = response['series'];
160 if (series is! List) {
161 throw const ApiException(502, 'invalid_series_response');
162 }
163 for (final row in series) {
164 if (row is! Map ||
165 row['id'] is! String ||
166 row['owner_user_id'] != api.currentUserId) {
167 throw const ApiException(502, 'invalid_series_response');
168 }
169 if (row['status'] == 'archived' || row['archived_at'] != null) continue;
170 await api.requestJson(
171 'POST', '/v1/planner-series/${row['id']}/materialize',
172 body: {'from': plannerDate(from), 'to': plannerDate(to)});
173 _checkScope();
174 }
175 }
176 }
177
178 String _canonical(dynamic value) => jsonEncode(_sorted(value));
179 dynamic _sorted(dynamic value) {
180 if (value is Map) {
181 final keys = value.keys.map((k) => k.toString()).toList()..sort();
182 return {for (final key in keys) key: _sorted(value[key])};
183 }
184 if (value is List) return value.map(_sorted).toList();
185 return value;
186 }
187
188 String plannerDate(DateTime date) =>
189 '${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
190
191 List<DateTime> plannerWeekDays(DateTime date) {
192 final day = DateTime(date.year, date.month, date.day);
193 final saturday = day.subtract(Duration(days: (day.weekday + 1) % 7));
194 return List.generate(7, (i) => saturday.add(Duration(days: i)));
195 }