LifeMate — Personal, Family & Learning Companion
fix/study-duration-display
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:convert'; |
| 3 | |
| 4 | import 'package:flutter/services.dart'; |
| 5 | import 'package:flutter_test/flutter_test.dart'; |
| 6 | import 'package:http/http.dart' as http; |
| 7 | import 'package:http/testing.dart'; |
| 8 | import 'package:lifemate/api.dart'; |
| 9 | import 'package:lifemate/learning_goal_sync.dart'; |
| 10 | import 'package:lifemate/offline_store.dart'; |
| 11 | import 'package:lifemate/session_store.dart'; |
| 12 | import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; |
| 13 | import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; |
| 14 | |
| 15 | const userId = '10000000-0000-4000-8000-000000000001'; |
| 16 | const otherUserId = '10000000-0000-4000-8000-000000000002'; |
| 17 | const goalId = '20000000-0000-4000-8000-000000000001'; |
| 18 | const at = '2026-10-11T12:00:00Z'; |
| 19 | |
| 20 | class MemorySession implements SessionStore { |
| 21 | @override |
| 22 | Future<String?> read() async => null; |
| 23 | @override |
| 24 | Future<void> write(String value) async {} |
| 25 | @override |
| 26 | Future<void> clear() async {} |
| 27 | } |
| 28 | |
| 29 | http.Response response(Object body, [int status = 200]) => |
| 30 | http.Response(jsonEncode(body), status, |
| 31 | headers: {'content-type': 'application/json; charset=utf-8'}); |
| 32 | |
| 33 | Map<String, dynamic> goal( |
| 34 | {String id = goalId, |
| 35 | int version = 1, |
| 36 | String title = 'هدف خصوصی آزمایشی', |
| 37 | String status = 'active', |
| 38 | String owner = userId}) => |
| 39 | { |
| 40 | 'id': id, |
| 41 | 'owner_user_id': owner, |
| 42 | 'subject_id': null, |
| 43 | 'title': title, |
| 44 | 'target': null, |
| 45 | 'status': status, |
| 46 | 'version': version, |
| 47 | 'created_at': at, |
| 48 | 'updated_at': at, |
| 49 | 'archived_at': status == 'archived' ? at : null, |
| 50 | }; |
| 51 | |
| 52 | class GoalFixture { |
| 53 | GoalFixture( |
| 54 | {String endpoint = 'https://goals.test/api', String user = userId}) { |
| 55 | api = HttpIdentityApi( |
| 56 | baseUrl: endpoint, |
| 57 | client: MockClient(handle), |
| 58 | sessionStore: MemorySession()) |
| 59 | ..accessToken = 'synthetic-token' |
| 60 | ..currentUserId = user; |
| 61 | store = OfflineStore.forNamespace(api.cacheNamespace!, |
| 62 | session: OfflineSession()); |
| 63 | sync = LearningGoalSync(api, store: store); |
| 64 | } |
| 65 | late HttpIdentityApi api; |
| 66 | late OfflineStore store; |
| 67 | late LearningGoalSync sync; |
| 68 | final goals = <String, Map<String, dynamic>>{}; |
| 69 | final receipts = <String, Map<String, dynamic>>{}; |
| 70 | final requests = <http.Request>[]; |
| 71 | bool offline = false, commitThenDisconnect = false; |
| 72 | int? errorCode; |
| 73 | Completer<void>? delay; |
| 74 | Map<String, dynamic> Function(Map<String, dynamic>)? alterResponse; |
| 75 | final retainedCheckins = <Map<String, dynamic>>[ |
| 76 | {'goalId': goalId, 'note': 'private synthetic history'} |
| 77 | ]; |
| 78 | |
| 79 | Future<http.Response> handle(http.Request request) async { |
| 80 | requests.add(request); |
| 81 | if (delay != null) await delay!.future; |
| 82 | if (offline) throw http.ClientException('synthetic offline'); |
| 83 | if (errorCode != null) { |
| 84 | return response({'error': 'synthetic_denial'}, errorCode!); |
| 85 | } |
| 86 | if (request.method == 'GET') { |
| 87 | if (request.url.path.endsWith('/goals')) { |
| 88 | return response({ |
| 89 | 'items': |
| 90 | goals.values.where((g) => g['status'] != 'archived').toList(), |
| 91 | 'fetchedAt': at |
| 92 | }); |
| 93 | } |
| 94 | final row = goals[request.url.path.split('/').last]; |
| 95 | return response( |
| 96 | row ?? {'error': 'goal_not_found'}, row == null ? 404 : 200); |
| 97 | } |
| 98 | final body = jsonDecode(request.body) as Map<String, dynamic>; |
| 99 | final id = request.method == 'POST' |
| 100 | ? body['id'] as String |
| 101 | : request.url.path.split('/').last; |
| 102 | final operation = request.method == 'POST' |
| 103 | ? 'create' |
| 104 | : request.method == 'PATCH' |
| 105 | ? 'update' |
| 106 | : 'archive'; |
| 107 | final mutationId = body['mutationId'] as String; |
| 108 | expect( |
| 109 | (await store.readQueue()).any((m) => |
| 110 | m['id'] == mutationId && |
| 111 | m['payload'].toString() == body.toString()), |
| 112 | isTrue); |
| 113 | final old = receipts[mutationId]; |
| 114 | if (old == null) { |
| 115 | if ((goals[id]?['version'] ?? 0) != body['expectedVersion']) { |
| 116 | return response({'error': 'version_conflict'}, 409); |
| 117 | } |
| 118 | goals[id] = { |
| 119 | ...goal( |
| 120 | id: id, |
| 121 | version: (body['expectedVersion'] as int) + 1, |
| 122 | title: body['title'] as String? ?? |
| 123 | goals[id]?['title'] as String? ?? |
| 124 | '', |
| 125 | status: operation == 'archive' |
| 126 | ? 'archived' |
| 127 | : body['status'] as String? ?? |
| 128 | goals[id]?['status'] as String? ?? |
| 129 | 'active', |
| 130 | owner: api.currentUserId!), |
| 131 | 'target': |
| 132 | body.containsKey('target') ? body['target'] : goals[id]?['target'], |
| 133 | 'subject_id': body.containsKey('subjectId') |
| 134 | ? body['subjectId'] |
| 135 | : goals[id]?['subject_id'], |
| 136 | }; |
| 137 | receipts[mutationId] = { |
| 138 | 'mutationId': mutationId, |
| 139 | 'goalId': id, |
| 140 | 'operation': operation, |
| 141 | 'appliedVersion': body['expectedVersion'] + 1, |
| 142 | 'acceptedAt': at, |
| 143 | }; |
| 144 | } |
| 145 | if (commitThenDisconnect) { |
| 146 | commitThenDisconnect = false; |
| 147 | throw http.ClientException('synthetic receipt lost after commit'); |
| 148 | } |
| 149 | var result = <String, dynamic>{ |
| 150 | 'goal': {...goals[id]!}, |
| 151 | 'acknowledgement': { |
| 152 | ...receipts[mutationId]!, |
| 153 | 'status': old == null ? 'accepted' : 'already_applied' |
| 154 | } |
| 155 | }; |
| 156 | if (alterResponse != null) result = alterResponse!(result); |
| 157 | return response( |
| 158 | result, request.method == 'POST' && old == null ? 201 : 200); |
| 159 | } |
| 160 | |
| 161 | LearningGoalSync reopen() => LearningGoalSync(api, |
| 162 | store: OfflineStore.forNamespace(store.scope, session: OfflineSession())); |
| 163 | } |
| 164 | |
| 165 | Matcher code(String value) => |
| 166 | throwsA(isA<ApiException>().having((e) => e.code, 'code', value)); |
| 167 | |
| 168 | void main() { |
| 169 | TestWidgetsFlutterBinding.ensureInitialized(); |
| 170 | setUp(() { |
| 171 | SharedPreferencesAsyncPlatform.instance = |
| 172 | InMemorySharedPreferencesAsync.withData({}); |
| 173 | String? token; |
| 174 | TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger |
| 175 | .setMockMethodCallHandler( |
| 176 | const MethodChannel('lifeguide/local_write_guard'), (call) async { |
| 177 | if (call.method == 'getBlocked') return token != null; |
| 178 | if (call.method == 'beginWrite') return token = 'goal-sync-test'; |
| 179 | if (call.method == 'completeWrite' && call.arguments == token) { |
| 180 | token = null; |
| 181 | return true; |
| 182 | } |
| 183 | throw PlatformException(code: 'local_storage_restart_required'); |
| 184 | }); |
| 185 | }); |
| 186 | |
| 187 | test( |
| 188 | 'create, fresh handle read, edit, complete and archive retain history and server versions', |
| 189 | () async { |
| 190 | final f = GoalFixture(); |
| 191 | final created = |
| 192 | await f.sync.create(title: ' هدف ریاضی ', target: ' حل تمرین '); |
| 193 | expect(created['queued'], false); |
| 194 | final id = created['goal']['id'] as String; |
| 195 | expect(created['goal']['title'], 'هدف ریاضی'); |
| 196 | f.offline = true; |
| 197 | final reopened = await f.reopen().read(); |
| 198 | expect(reopened['offline'], true); |
| 199 | expect((reopened['items'] as List).single['id'], id); |
| 200 | f.offline = false; |
| 201 | final edited = |
| 202 | await f.sync.update(id, 1, {'title': 'تمرین جمع', 'target': null}); |
| 203 | expect(edited['goal']['version'], 2); |
| 204 | expect(edited['goal']['target'], isNull); |
| 205 | await f.reopen().update(id, 2, {'status': 'completed'}); |
| 206 | expect((await f.sync.read())['items'].single['status'], 'completed'); |
| 207 | await f.sync.archive(id, 3); |
| 208 | f.offline = true; |
| 209 | expect((await f.reopen().read())['items'], isEmpty); |
| 210 | expect(f.goals[id]?['status'], 'archived'); |
| 211 | expect(f.retainedCheckins, hasLength(1)); |
| 212 | expect(await f.store.readQueue(), isEmpty); |
| 213 | f.api.close(); |
| 214 | }); |
| 215 | |
| 216 | test( |
| 217 | 'offline create survives fresh handle and retries one stable UUID with one server row', |
| 218 | () async { |
| 219 | final f = GoalFixture()..offline = true; |
| 220 | final created = await f.sync.create(title: 'هدف آفلاین'); |
| 221 | expect(created['queued'], true); |
| 222 | final queued = (await f.store.readQueue()).single; |
| 223 | final reopened = f.reopen(); |
| 224 | expect((await reopened.read())['items'].single['pending_sync'], true); |
| 225 | expect((await reopened.read())['fetchedAt'], isNull); |
| 226 | f.offline = false; |
| 227 | await reopened.flush(); |
| 228 | await reopened.flush(); |
| 229 | expect(f.goals, hasLength(1)); |
| 230 | expect(f.receipts.keys.single, queued['id']); |
| 231 | expect(await f.store.readQueue(), isEmpty); |
| 232 | f.api.close(); |
| 233 | }); |
| 234 | |
| 235 | test( |
| 236 | 'lost create acknowledgement replays exact bytes and current archive dominates old receipt', |
| 237 | () async { |
| 238 | final f = GoalFixture()..commitThenDisconnect = true; |
| 239 | expect((await f.sync.create(title: 'هدف آزمایشی'))['queued'], true); |
| 240 | final saved = (await f.store.readQueue()).single; |
| 241 | final id = saved['entityId'] as String; |
| 242 | f.goals[id] = { |
| 243 | ...f.goals[id]!, |
| 244 | 'status': 'archived', |
| 245 | 'version': 3, |
| 246 | 'archived_at': at |
| 247 | }; |
| 248 | await f.reopen().flush(); |
| 249 | final writes = f.requests.where((r) => r.method == 'POST').toList(); |
| 250 | expect(writes, hasLength(2)); |
| 251 | expect(writes.first.body, writes.last.body); |
| 252 | expect(f.receipts, hasLength(1)); |
| 253 | expect(await f.store.readQueue(), isEmpty); |
| 254 | f.offline = true; |
| 255 | expect((await f.reopen().read())['items'], isEmpty); |
| 256 | f.api.close(); |
| 257 | }); |
| 258 | |
| 259 | for (final corrupt in [ |
| 260 | 'id', |
| 261 | 'mutation', |
| 262 | 'version', |
| 263 | 'operation', |
| 264 | 'title', |
| 265 | 'acceptedAt' |
| 266 | ]) { |
| 267 | test('malformed $corrupt receipt cannot erase a goal intent', () async { |
| 268 | final f = GoalFixture(); |
| 269 | f.alterResponse = (raw) { |
| 270 | final row = {...raw['goal'] as Map}; |
| 271 | final ack = {...raw['acknowledgement'] as Map}; |
| 272 | if (corrupt == 'id') row['id'] = goalId; |
| 273 | if (corrupt == 'mutation') ack['mutationId'] = goalId; |
| 274 | if (corrupt == 'version') ack['appliedVersion'] = 2; |
| 275 | if (corrupt == 'operation') ack['operation'] = 'archive'; |
| 276 | if (corrupt == 'title') row['title'] = 'متن متفاوت'; |
| 277 | if (corrupt == 'acceptedAt') ack['acceptedAt'] = 'yesterday'; |
| 278 | return {'goal': row, 'acknowledgement': ack}; |
| 279 | }; |
| 280 | await expectLater(f.sync.create(title: 'هدف واقعی'), |
| 281 | code('invalid_goal_acknowledgement')); |
| 282 | expect(await f.store.readQueue(), hasLength(1)); |
| 283 | f.api.close(); |
| 284 | }); |
| 285 | } |
| 286 | |
| 287 | test( |
| 288 | 'version conflict stays queued until explicit server recovery, with local intent journalled', |
| 289 | () async { |
| 290 | final f = GoalFixture(); |
| 291 | f.goals[goalId] = goal(); |
| 292 | await f.sync.read(); |
| 293 | f.goals[goalId] = goal(version: 2, title: 'نسخه دیگر دستگاه'); |
| 294 | await expectLater(f.sync.update(goalId, 1, {'title': 'نسخه محلی'}), |
| 295 | code('version_conflict')); |
| 296 | expect((await f.store.readQueue()).single['queueStatus'], 'conflict'); |
| 297 | await expectLater(f.reopen().flush(), code('goal_version_conflict')); |
| 298 | await f.reopen().useServer(goalId); |
| 299 | expect(await f.store.readQueue(), isEmpty); |
| 300 | expect(jsonEncode(await f.store.readDiscardedChanges()), |
| 301 | contains('نسخه محلی')); |
| 302 | f.offline = true; |
| 303 | expect( |
| 304 | (await f.reopen().read())['items'].single['title'], 'نسخه دیگر دستگاه'); |
| 305 | f.api.close(); |
| 306 | }); |
| 307 | |
| 308 | test('403 clears private goal cache without deleting an offline intent', |
| 309 | () async { |
| 310 | final f = GoalFixture(); |
| 311 | f.goals[goalId] = goal(); |
| 312 | await f.sync.read(); |
| 313 | f.offline = true; |
| 314 | await f.sync.update(goalId, 1, {'title': 'تغییر ارسالنشده'}); |
| 315 | f.offline = false; |
| 316 | f.errorCode = 403; |
| 317 | await expectLater(f.sync.read(), throwsA(isA<ApiException>())); |
| 318 | expect(await f.store.readList('learning_goals'), isEmpty); |
| 319 | expect(await f.store.readList('learning_goals_received'), isEmpty); |
| 320 | expect(await f.store.readQueue(), hasLength(1)); |
| 321 | f.api.close(); |
| 322 | }); |
| 323 | |
| 324 | test( |
| 325 | 'account change while receiving a goal blocks acknowledgement and isolates caches', |
| 326 | () async { |
| 327 | final f = GoalFixture()..delay = Completer<void>(); |
| 328 | final pending = f.sync.create(title: 'حساب نخست'); |
| 329 | await Future<void>.delayed(Duration.zero); |
| 330 | f.api.currentUserId = otherUserId; |
| 331 | f.delay!.complete(); |
| 332 | await expectLater(pending, throwsA(isA<ApiException>())); |
| 333 | expect(await OfflineStore.forApi(f.api).readQueue(), isEmpty); |
| 334 | expect(await f.store.readQueue(), hasLength(1)); |
| 335 | f.api.close(); |
| 336 | }); |
| 337 | |
| 338 | for (final invalid in [ |
| 339 | {'expectedVersion': 0, 'title': 'new'}, |
| 340 | {'expectedVersion': -1, 'title': 'new'}, |
| 341 | {'expectedVersion': 1, 'title': 'bad\u0000title'}, |
| 342 | {'expectedVersion': 1, 'unknown': true}, |
| 343 | {'expectedVersion': 1}, |
| 344 | ]) { |
| 345 | test('invalid update $invalid is rejected before enqueue or HTTP', |
| 346 | () async { |
| 347 | final f = GoalFixture(); |
| 348 | final version = invalid['expectedVersion'] as int; |
| 349 | final changes = {...invalid}..remove('expectedVersion'); |
| 350 | await expectLater( |
| 351 | f.sync.update(goalId, version, changes), code('invalid_goal_input')); |
| 352 | expect(await f.store.readQueue(), isEmpty); |
| 353 | expect(f.requests, isEmpty); |
| 354 | f.api.close(); |
| 355 | }); |
| 356 | } |
| 357 | |
| 358 | test('foreign-owner cached row is never rendered as private offline data', |
| 359 | () async { |
| 360 | final f = GoalFixture()..offline = true; |
| 361 | await f.store.writeList('learning_goals', [goal(owner: otherUserId)]); |
| 362 | await expectLater(f.sync.read(), code('invalid_learning_goal')); |
| 363 | f.api.close(); |
| 364 | }); |
| 365 | } |