LifeMate — Personal, Family & Learning Companion

fix/personal-jalali-dates
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 458 lines 16.1 KB
Raw
1 import 'dart:async';
2 import 'dart:convert';
3
4 import 'package:flutter/material.dart';
5 import 'package:flutter/services.dart';
6 import 'package:flutter_test/flutter_test.dart';
7 import 'package:http/http.dart' as http;
8 import 'package:http/testing.dart';
9 import 'package:lifemate/api.dart';
10 import 'package:lifemate/family_management_ui.dart';
11 import 'package:lifemate/offline_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 familyId = 'a1111111-1111-4111-8111-111111111111';
16 const actorId = 'b1111111-1111-4111-8111-111111111111';
17 const targetId = 'c1111111-1111-4111-8111-111111111111';
18 const mutationId = 'd1111111-1111-4111-8111-111111111111';
19 const at = '2026-10-11T12:00:00Z';
20 http.Response response(Object body, [int status = 200]) =>
21 http.Response(jsonEncode(body), status,
22 headers: {'content-type': 'application/json; charset=utf-8'});
23 Map<String, dynamic> family(
24 {bool admin = true, String name = 'خانواده آزمایشی'}) =>
25 {'id': familyId, 'name': name, 'role': 'adult_member', 'is_admin': admin};
26 Map<String, dynamic> member(String id, String name,
27 {bool admin = false, int version = 1, String role = 'adult_member'}) =>
28 {
29 'user_id': id,
30 'display_name': name,
31 'role': role,
32 'is_admin': admin,
33 'theme_preference': 'adult_blue',
34 'version': version,
35 'updated_at': at
36 };
37 HttpIdentityApi fixture(Future<http.Response> Function(http.Request) handler) =>
38 HttpIdentityApi(
39 baseUrl: 'https://family.example.test/api', client: MockClient(handler))
40 ..accessToken = 'synthetic-token'
41 ..currentUserId = actorId;
42
43 void main() {
44 TestWidgetsFlutterBinding.ensureInitialized();
45 setUp(() {
46 SharedPreferencesAsyncPlatform.instance =
47 InMemorySharedPreferencesAsync.withData({});
48 String? token;
49 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
50 .setMockMethodCallHandler(
51 const MethodChannel('lifeguide/local_write_guard'), (call) async {
52 if (call.method == 'getBlocked') return token != null;
53 if (call.method == 'beginWrite') return token = 'family-write';
54 if (call.method == 'completeWrite' && call.arguments == token) {
55 token = null;
56 return true;
57 }
58 throw PlatformException(code: 'local_storage_restart_required');
59 });
60 });
61
62 test('role receipt lost after commit retries identical metadata after reopen',
63 () async {
64 var lost = true;
65 final sent = <String>[];
66 final api = fixture((request) async {
67 if (request.method == 'GET') return response(family());
68 sent.add(request.body);
69 if (lost) throw http.ClientException('lost receipt');
70 return response({
71 'members': [
72 {
73 'userId': targetId,
74 'role': 'parent_guardian',
75 'isAdmin': false,
76 'version': 2,
77 'updatedAt': at,
78 'endedAt': null
79 }
80 ],
81 'acknowledgement': {
82 'mutationId': mutationId,
83 'familyId': familyId,
84 'targetId': targetId,
85 'operation': 'role',
86 'status': 'already_applied'
87 }
88 });
89 });
90 final body = {
91 'mutationId': mutationId,
92 'expectedVersion': 1,
93 'role': 'parent_guardian'
94 };
95 await expectLater(
96 FamilyOperationSync(api, familyId).submit('role', targetId, body),
97 throwsA(predicate(isOfflineFailure)));
98 final pending = (await FamilyOperationSync(api, familyId).pending()).single;
99 expect(pending['payload'], body);
100 expect(jsonEncode(pending), isNot(contains('display_name')));
101 expect(await OfflineStore.forApi(api).readList('family'), isEmpty);
102 lost = false;
103 await FamilyOperationSync(api, familyId).retry(pending);
104 expect(sent.length, 2);
105 expect(sent.first, sent.last);
106 expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
107 api.close();
108 });
109
110 test(
111 'former administrator may replay only journalled transfer and new changes require actual admin',
112 () async {
113 var admin = true, lost = true;
114 final api = fixture((request) async {
115 if (request.method == 'GET') return response(family(admin: admin));
116 if (lost) {
117 admin = false;
118 throw http.ClientException('lost receipt');
119 }
120 return response({
121 'members': [
122 {
123 'userId': actorId,
124 'role': 'adult_member',
125 'isAdmin': false,
126 'version': 2,
127 'updatedAt': at,
128 'endedAt': null
129 },
130 {
131 'userId': targetId,
132 'role': 'adult_member',
133 'isAdmin': true,
134 'version': 2,
135 'updatedAt': at,
136 'endedAt': null
137 }
138 ],
139 'acknowledgement': {
140 'mutationId': mutationId,
141 'familyId': familyId,
142 'targetId': targetId,
143 'operation': 'admin_transfer',
144 'status': 'already_applied'
145 }
146 });
147 });
148 final sync = FamilyOperationSync(api, familyId);
149 await expectLater(
150 sync.submit('admin_transfer', targetId, {
151 'mutationId': mutationId,
152 'targetUserId': targetId,
153 'expectedVersion': 1,
154 'expectedActorVersion': 1
155 }),
156 throwsA(predicate(isOfflineFailure)));
157 final pending = (await sync.pending()).single;
158 lost = false;
159 await FamilyOperationSync(api, familyId).retry(pending);
160 await expectLater(
161 sync.submit('role', targetId, {
162 'mutationId': mutationId,
163 'expectedVersion': 2,
164 'role': 'parent_guardian'
165 }),
166 throwsA(isA<ApiException>()));
167 expect(await sync.pending(), isEmpty);
168 api.close();
169 });
170
171 test(
172 'wrong transfer receipt never removes durable metadata, and scope change blocks retries',
173 () async {
174 final api = fixture((request) async => request.method == 'GET'
175 ? response(family())
176 : response({
177 'members': [
178 {
179 'userId': targetId,
180 'role': 'adult_member',
181 'isAdmin': true,
182 'version': 2,
183 'updatedAt': at,
184 'endedAt': null
185 }
186 ],
187 'acknowledgement': {
188 'mutationId': mutationId,
189 'familyId': familyId,
190 'targetId': targetId,
191 'operation': 'admin_transfer',
192 'status': 'accepted'
193 }
194 }));
195 final sync = FamilyOperationSync(api, familyId);
196 await expectLater(
197 sync.submit('admin_transfer', targetId, {
198 'mutationId': mutationId,
199 'targetUserId': targetId,
200 'expectedVersion': 1,
201 'expectedActorVersion': 1
202 }),
203 throwsA(isA<ApiException>()));
204 final saved = (await sync.pending()).single;
205 api.currentUserId = targetId;
206 await expectLater(sync.retry(saved), throwsA(isA<ApiException>()));
207 expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
208 api.close();
209 });
210
211 testWidgets(
212 'adult role does not grant management and network failure clears the member list',
213 (tester) async {
214 var offline = false;
215 final api = fixture((request) async {
216 if (offline) throw http.ClientException('offline');
217 if (request.url.path.endsWith('/members')) {
218 return response({
219 'members': [member(actorId, 'والد آزمایشی')]
220 });
221 }
222 return response(family(admin: false));
223 });
224 await tester.pumpWidget(
225 MaterialApp(home: FamilyManagementPage(api: api, familyId: familyId)));
226 await tester.pumpAndSettle();
227 expect(find.text('والد آزمایشی'), findsOneWidget);
228 expect(find.text('بایگانی خانواده'), findsNothing);
229 expect(find.text('دعوت عضو'), findsNothing);
230 offline = true;
231 await tester.tap(find.byKey(const Key('family-management-refresh')));
232 await tester.pumpAndSettle();
233 expect(find.text('والد آزمایشی'), findsNothing);
234 expect(find.textContaining('اتصال'), findsWidgets);
235 await tester.pumpWidget(const SizedBox());
236 api.close();
237 });
238
239 testWidgets(
240 'late family read cannot restore members after newer access denial',
241 (tester) async {
242 final delayed = Completer<http.Response>();
243 var reads = 0;
244 final api = fixture((request) async {
245 if (request.url.path.endsWith('/members')) {
246 return response({
247 'members': [member(actorId, 'والد آزمایشی')]
248 });
249 }
250 return ++reads == 1
251 ? delayed.future
252 : response({'error': 'forbidden'}, 403);
253 });
254 await tester.pumpWidget(
255 MaterialApp(home: FamilyManagementPage(api: api, familyId: familyId)));
256 await tester.pump();
257 await tester.tap(find.byKey(const Key('family-management-refresh')));
258 await tester.pumpAndSettle();
259 delayed.complete(response(family(admin: false)));
260 await tester.pumpAndSettle();
261 expect(find.text('والد آزمایشی'), findsNothing);
262 expect(find.textContaining('دسترسی'), findsWidgets);
263 await tester.pumpWidget(const SizedBox());
264 api.close();
265 });
266 test(
267 'a role mutation cannot trust missing or contradictory server administrator flags',
268 () async {
269 for (final raw in [
270 {'id': familyId, 'role': 'adult_member'},
271 {'id': familyId, 'role': 'teen_minor', 'is_admin': true},
272 ]) {
273 var writes = 0;
274 final api = fixture((request) async {
275 if (request.method == 'GET') return response(raw);
276 writes++;
277 return response({});
278 });
279 final sync = FamilyOperationSync(api, familyId);
280 await expectLater(
281 sync.submit('role', targetId, {
282 'mutationId': mutationId,
283 'expectedVersion': 1,
284 'role': 'parent_guardian'
285 }),
286 throwsA(isA<ApiException>()));
287 expect(writes, 0);
288 expect(await sync.pending(), isEmpty);
289 api.close();
290 }
291 });
292
293 testWidgets(
294 'role change needs confirmation and refreshes canonical role without dropdown crash',
295 (tester) async {
296 var role = 'adult_member', version = 1;
297 final writes = <Map<String, dynamic>>[];
298 final api = fixture((request) async {
299 if (request.url.path.endsWith('/members')) {
300 return response({
301 'members': [
302 member(actorId, 'مدیر آزمایشی', admin: true),
303 member(targetId, 'عضو آزمایشی', version: version, role: role),
304 ]
305 });
306 }
307 if (request.method == 'GET' &&
308 request.url.path.endsWith('/invitations')) {
309 return response({'invitations': [], 'nextCursor': null, 'total': 0});
310 }
311 if (request.method == 'GET') return response(family());
312 final body = jsonDecode(request.body) as Map<String, dynamic>;
313 writes.add(body);
314 role = body['role'] as String;
315 version++;
316 return response({
317 'members': [
318 {
319 'userId': targetId,
320 'role': role,
321 'isAdmin': false,
322 'version': version,
323 'updatedAt': at,
324 'endedAt': null,
325 }
326 ],
327 'acknowledgement': {
328 'mutationId': body['mutationId'],
329 'familyId': familyId,
330 'targetId': targetId,
331 'operation': 'role',
332 'status': 'accepted',
333 }
334 });
335 });
336 await tester.pumpWidget(
337 MaterialApp(home: FamilyManagementPage(api: api, familyId: familyId)));
338 await tester.pumpAndSettle();
339 final dropdown = find.byKey(const Key('family-member-role-$targetId'));
340 await tester.ensureVisible(dropdown);
341 await tester.pumpAndSettle();
342 await tester.tap(dropdown);
343 await tester.pumpAndSettle();
344 await tester.tap(find.text('سرپرست').last);
345 await tester.pumpAndSettle();
346 expect(find.text('تغییر نقش عضو'), findsOneWidget);
347 await tester.tap(find.text('انصراف'));
348 await tester.pumpAndSettle();
349 expect(writes, isEmpty);
350 await tester.tap(dropdown);
351 await tester.pumpAndSettle();
352 await tester.tap(find.text('سرپرست').last);
353 await tester.pumpAndSettle();
354 await tester.tap(find.text('تأیید تغییر'));
355 await tester.pumpAndSettle();
356 expect(writes, hasLength(1));
357 expect(writes.single['expectedVersion'], 1);
358 expect(writes.single['mutationId'], isA<String>());
359 expect(role, 'parent_guardian');
360 expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
361 expect(tester.takeException(), isNull);
362 await tester.pumpWidget(const SizedBox());
363 api.close();
364 });
365
366 testWidgets(
367 'revoked access clears members, invitation hints and any contact draft',
368 (tester) async {
369 var denied = false;
370 final api = fixture((request) async {
371 if (denied) return response({'error': 'forbidden'}, 403);
372 if (request.url.path.endsWith('/members')) {
373 return response({
374 'members': [
375 member(actorId, 'مدیر آزمایشی', admin: true),
376 member(targetId, 'عضو آزمایشی'),
377 ]
378 });
379 }
380 if (request.url.path.endsWith('/invitations')) {
381 return response({
382 'invitations': [
383 {
384 'id': mutationId,
385 'intendedRole': 'adult_member',
386 'status': 'pending',
387 'version': 1,
388 'createdAt': at,
389 'expiresAt': '2026-10-12T12:00:00Z',
390 'recipientHint': '***@example.test',
391 }
392 ],
393 'nextCursor': null,
394 'total': 1
395 });
396 }
397 return response(family());
398 });
399 await tester.pumpWidget(
400 MaterialApp(home: FamilyManagementPage(api: api, familyId: familyId)));
401 await tester.pumpAndSettle();
402 await tester.scrollUntilVisible(find.text('***@example.test'), 400,
403 scrollable: find.byType(Scrollable).first);
404 expect(find.text('***@example.test'), findsOneWidget);
405 final draft =
406 tester.widget<TextField>(find.byType(TextField).last).controller!;
407 draft.text = 'synthetic-private-recipient@example.test';
408 denied = true;
409 await tester.tap(find.byKey(const Key('family-management-refresh')));
410 await tester.pumpAndSettle();
411 expect(find.text('***@example.test'), findsNothing);
412 expect(find.text('عضو آزمایشی'), findsNothing);
413 expect(find.text('دعوت عضو'), findsNothing);
414 expect(draft.text, isEmpty);
415 expect(find.textContaining('دسترسی'), findsWidgets);
416 expect(await OfflineStore.forApi(api).readList('family'), isEmpty);
417 await tester.pumpWidget(const SizedBox());
418 api.close();
419 });
420
421 testWidgets(
422 'unknown result of legacy family rename only refreshes and never retries the write automatically',
423 (tester) async {
424 var renamed = false, patches = 0;
425 final api = fixture((request) async {
426 if (request.method == 'PATCH') {
427 patches++;
428 renamed = true;
429 throw http.ClientException('synthetic receipt lost');
430 }
431 if (request.url.path.endsWith('/members')) {
432 return response({
433 'members': [
434 member(actorId, 'مدیر آزمایشی', admin: true),
435 ]
436 });
437 }
438 if (request.url.path.endsWith('/invitations')) {
439 return response({'invitations': [], 'nextCursor': null, 'total': 0});
440 }
441 return response(
442 family(name: renamed ? 'نام تازه سرور' : 'خانواده آزمایشی'));
443 });
444 await tester.pumpWidget(
445 MaterialApp(home: FamilyManagementPage(api: api, familyId: familyId)));
446 await tester.pumpAndSettle();
447 await tester.enterText(find.byType(TextField).first, 'نام تازه سرور');
448 await tester.tap(find.text('ذخیره نام خانواده'));
449 await tester.pumpAndSettle();
450 expect(patches, 1);
451 expect(find.text('نام تازه سرور'), findsWidgets);
452 expect(find.textContaining('نتیجه عملیات ممکن است نامشخص باشد'),
453 findsOneWidget);
454 expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
455 await tester.pumpWidget(const SizedBox());
456 api.close();
457 });
458 }