LifeMate — Personal, Family & Learning Companion

fix/backend-request-safety
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 563 lines 21.1 KB
Raw
1 import 'dart:async';
2 import 'dart:convert';
3
4 import 'package:flutter/material.dart';
5 import 'package:flutter_test/flutter_test.dart';
6 import 'package:lifemate/api.dart';
7 import 'package:lifemate/local_data_store.dart';
8 import 'package:lifemate/local_only_api.dart';
9 import 'package:lifemate/main.dart';
10 import 'package:lifemate/phase3_ui.dart';
11 import 'package:shared_preferences/shared_preferences.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 import 'app_test.dart' show FakeApi;
16
17 // This simulates the preferences plugin boundary, not Android process restart.
18 final class _ControlledWrites extends InMemorySharedPreferencesAsync {
19 _ControlledWrites(super.data) : super.withData();
20 bool failWrites = false;
21 Completer<void>? pendingWrite;
22
23 @override
24 Future<bool> setString(
25 String key, String value, SharedPreferencesOptions options) async {
26 if (pendingWrite != null) await pendingWrite!.future;
27 if (failWrites) throw StateError('simulated persistent storage failure');
28 return super.setString(key, value, options);
29 }
30 }
31
32 late LocalDataSession _testSession;
33 const _restartMessage =
34 'وضعیت ذخیره نامشخص است. برنامه را از تنظیمات دستگاه «توقف اجباری» کن و دوباره باز کن.';
35
36 LocalOnlyApi _open(
37 {String category = 'girl_minor', LocalDataSession? session}) =>
38 LocalOnlyApi(
39 category: category,
40 displayName: 'آرام مهرآیین',
41 store: LocalDataStore(
42 category: category,
43 displayName: 'آرام مهرآیین',
44 session: session ?? _testSession),
45 );
46
47 // This inspects the simulated native snapshot independently of a poisoned API.
48 Future<Map<String, dynamic>> _nativeSnapshot() async =>
49 jsonDecode((await SharedPreferencesAsync().getString(LocalDataStore.key))!)
50 as Map<String, dynamic>;
51
52 Future<void> _expectRestartRequired(Future<Object?> operation) async {
53 await expectLater(
54 operation,
55 throwsA(isA<ApiException>().having(
56 (error) => error.code,
57 'code',
58 'local_storage_restart_required',
59 )));
60 }
61
62 Future<_ControlledWrites> _controlWrites(
63 WidgetTester tester, LocalOnlyApi api) async {
64 await api.getProfile();
65 return SharedPreferencesAsyncPlatform.instance! as _ControlledWrites;
66 }
67
68 class _RoleChangingApi extends FakeApi {
69 String currentRole = 'teen_minor';
70
71 @override
72 Future<List<Map<String, dynamic>>> listFamilies() async => [
73 {'id': 'family-1', 'name': 'خانواده', 'role': currentRole},
74 ];
75 }
76
77 class _ProductionItemApi extends FakeApi {
78 @override
79 Future<List<Map<String, dynamic>>> listPlanItems({
80 DateTime? from,
81 DateTime? to,
82 String? kind,
83 }) async =>
84 [
85 {'id': 'server-item', 'kind': 'task', 'title': 'کار سرور'},
86 ];
87 }
88
89 Future<void> _planner(WidgetTester tester, LocalOnlyApi api) async {
90 await tester.pumpWidget(MaterialApp(
91 key: UniqueKey(),
92 home: Scaffold(body: PlannerPage(api: api, localOnly: true)),
93 ));
94 await tester.pumpAndSettle();
95 }
96
97 Future<void> _createForm(WidgetTester tester,
98 {String title = 'تمرین ریاضی'}) async {
99 await tester.tap(find.text('جدید'));
100 await tester.pumpAndSettle();
101 await tester.enterText(find.byKey(const Key('plan-title')), title);
102 }
103
104 Future<void> _itemMenu(WidgetTester tester, String action) async {
105 await tester.tap(find.byType(PopupMenuButton<String>));
106 await tester.pumpAndSettle();
107 await tester.tap(find.text(action));
108 await tester.pumpAndSettle();
109 }
110
111 void _localWidgetTest(String name, Future<void> Function(WidgetTester) body) {
112 testWidgets(name, (tester) async {
113 await tester.runAsync(() => body(tester));
114 });
115 }
116
117 void main() {
118 setUp(() {
119 _testSession = LocalDataSession();
120 SharedPreferences.setMockInitialValues({});
121 SharedPreferencesAsyncPlatform.instance = _ControlledWrites({});
122 });
123
124 test('restart-required storage errors describe full process recovery', () {
125 expect(
126 localDataErrorText(
127 const ApiException(500, 'local_storage_restart_required')),
128 _restartMessage);
129 });
130
131 _localWidgetTest('saved assignment survives recreated planner UI',
132 (tester) async {
133 await _planner(tester, _open());
134 await _createForm(tester);
135 await tester.tap(find.byKey(const Key('plan-kind')));
136 await tester.pumpAndSettle();
137 await tester.tap(find.text('تکلیف').last);
138 await tester.pumpAndSettle();
139 await tester.tap(find.text('ذخیره'));
140 await tester.pumpAndSettle();
141
142 await _planner(tester, _open());
143 expect(find.text('تمرین ریاضی'), findsOneWidget);
144 expect((await _open().listPlanItems()).single['kind'], 'assignment');
145 });
146
147 _localWidgetTest('planner requires a title before saving', (tester) async {
148 await _planner(tester, _open());
149 await _createForm(tester, title: ' ');
150 await tester.tap(find.text('ذخیره'));
151 await tester.pumpAndSettle();
152
153 expect(find.text('عنوان را وارد کن.'), findsOneWidget);
154 expect(await _open().listPlanItems(), isEmpty);
155 });
156
157 _localWidgetTest('local planner keeps older and future saved items visible',
158 (tester) async {
159 await _open().createPlanItem({
160 'kind': 'assignment',
161 'title': 'تکلیف قبلی',
162 'dueAt': DateTime.now()
163 .subtract(const Duration(days: 40))
164 .toUtc()
165 .toIso8601String(),
166 });
167 await _open().createPlanItem({
168 'kind': 'task',
169 'title': 'کار آینده',
170 'dueAt': DateTime.now()
171 .add(const Duration(days: 40))
172 .toUtc()
173 .toIso8601String(),
174 });
175 await _planner(tester, _open());
176
177 expect(find.text('تکلیف قبلی'), findsOneWidget);
178 expect(find.text('کار آینده'), findsOneWidget);
179 });
180
181 _localWidgetTest('edited title survives recreated planner UI',
182 (tester) async {
183 await _open().createPlanItem({
184 'kind': 'assignment',
185 'title': 'تمرین ریاضی',
186 'dueAt': DateTime.now().toUtc().toIso8601String(),
187 });
188 await _planner(tester, _open());
189 await _itemMenu(tester, 'ویرایش عنوان');
190 await tester.enterText(find.byKey(const Key('plan-title')), 'تمرین علوم');
191 await tester.tap(find.text('ذخیره'));
192 await tester.pumpAndSettle();
193
194 await _planner(tester, _open());
195 expect(find.text('تمرین علوم'), findsOneWidget);
196 expect(find.text('تمرین ریاضی'), findsNothing);
197 });
198
199 _localWidgetTest('archive requires confirmation and survives recreated UI',
200 (tester) async {
201 await _open().createPlanItem({
202 'kind': 'assignment',
203 'title': 'تمرین ریاضی',
204 'dueAt': DateTime.now().toUtc().toIso8601String(),
205 });
206 await _planner(tester, _open());
207 await _itemMenu(tester, 'بایگانی');
208 expect(find.text('بایگانی مورد'), findsOneWidget);
209 await tester.tap(find.text('انصراف'));
210 await tester.pumpAndSettle();
211 expect(find.text('تمرین ریاضی'), findsOneWidget);
212
213 await _itemMenu(tester, 'بایگانی');
214 await tester.tap(find.widgetWithText(FilledButton, 'بایگانی'));
215 await tester.pumpAndSettle();
216 await _planner(tester, _open());
217 expect(find.text('تمرین ریاضی'), findsNothing);
218 await tester.pumpWidget(MaterialApp(
219 home: Scaffold(body: TodayPage(api: _open(), localOnly: true)),
220 ));
221 await tester.pumpAndSettle();
222 expect(find.text('تمرین ریاضی'), findsNothing);
223 });
224
225 _localWidgetTest(
226 'uncertain local save needs full process restart without sync queue',
227 (tester) async {
228 final api = _open();
229 final platform = await _controlWrites(tester, api);
230 await _planner(tester, api);
231 platform.failWrites = true;
232 await _createForm(tester);
233 await tester.tap(find.text('ذخیره'));
234 await tester.pumpAndSettle();
235
236 expect(tester.takeException(), isNull);
237 expect(find.text(_restartMessage), findsOneWidget);
238 expect(find.byType(AlertDialog), findsOneWidget);
239 expect((await _nativeSnapshot())['items'], isEmpty);
240 await _expectRestartRequired(_open().listPlanItems());
241 expect(
242 (await SharedPreferences.getInstance())
243 .containsKey('phase3.sync.queue'),
244 isFalse);
245
246 platform.failWrites = false;
247 await tester.tap(find.text('ذخیره'));
248 await tester.pumpAndSettle();
249 expect(find.text(_restartMessage), findsOneWidget);
250 expect((await _nativeSnapshot())['items'], isEmpty);
251 await _expectRestartRequired(api.listPlanItems());
252
253 // A new coordinator represents a full process restart in this plugin mock.
254 final restarted = _open(session: LocalDataSession());
255 expect(await restarted.listPlanItems(), isEmpty);
256 await _planner(tester, restarted);
257 await _createForm(tester);
258 await tester.tap(find.text('ذخیره'));
259 await tester.pumpAndSettle();
260 expect((await restarted.listPlanItems()).single['title'], 'تمرین ریاضی');
261 });
262
263 _localWidgetTest('save button stays disabled until durable write completes',
264 (tester) async {
265 final api = _open();
266 final platform = await _controlWrites(tester, api);
267 await _planner(tester, api);
268 await _createForm(tester);
269 platform.pendingWrite = Completer<void>();
270 await tester.tap(find.text('ذخیره'));
271 await tester.pump();
272
273 final button = tester.widget<FilledButton>(
274 find.widgetWithText(FilledButton, 'در حال ذخیره...'),
275 );
276 expect(button.onPressed, isNull);
277 platform.pendingWrite!.complete();
278 platform.pendingWrite = null;
279 await tester.pumpAndSettle();
280 expect(await _open().listPlanItems(), hasLength(1));
281 });
282
283 _localWidgetTest(
284 'uncertain Today completion stays visible without server cache or queue',
285 (tester) async {
286 final api = _open();
287 await api.createPlanItem({
288 'kind': 'assignment',
289 'title': 'تمرین ریاضی',
290 'dueAt': DateTime.now().toUtc().toIso8601String(),
291 });
292 final platform = await _controlWrites(tester, api);
293 const serverCache = '[{"id":"server-item","title":"نسخه سرور"}]';
294 SharedPreferences.setMockInitialValues({'phase3.today.cache': serverCache});
295 await tester.pumpWidget(MaterialApp(
296 home: Scaffold(body: TodayPage(api: api, localOnly: true)),
297 ));
298 await tester.pumpAndSettle();
299 expect(find.text('تمرین ریاضی'), findsOneWidget);
300 expect(find.text('نسخه سرور'), findsNothing);
301 platform.failWrites = true;
302 await tester.tap(find.byTooltip('انجام شد'));
303 await tester.pumpAndSettle();
304
305 expect(tester.takeException(), isNull);
306 expect(find.text(_restartMessage), findsOneWidget);
307 expect(find.text('تمرین ریاضی'), findsOneWidget);
308 final legacy = await SharedPreferences.getInstance();
309 expect(legacy.getString('phase3.today.cache'), serverCache);
310 expect(legacy.containsKey('phase3.sync.queue'), isFalse);
311 expect(((await _nativeSnapshot())['items'] as List).single['status'],
312 'planned');
313 platform.failWrites = false;
314 await tester.tap(find.text('تلاش دوباره'));
315 await tester.pumpAndSettle();
316 expect(find.text(_restartMessage), findsOneWidget);
317 expect(find.text('تمرین ریاضی'), findsOneWidget);
318 await _expectRestartRequired(api.listPlanItems());
319
320 final restarted = _open(session: LocalDataSession());
321 expect((await restarted.listPlanItems()).single['status'], 'planned');
322 await tester.pumpWidget(MaterialApp(
323 key: UniqueKey(),
324 home: Scaffold(body: TodayPage(api: restarted, localOnly: true)),
325 ));
326 await tester.pumpAndSettle();
327 await tester.tap(find.byTooltip('انجام شد'));
328 await tester.pumpAndSettle();
329 expect(find.text('تمرین ریاضی'), findsNothing);
330 });
331
332 _localWidgetTest(
333 'uncertain reschedule preserves confirmed data until full process restart',
334 (tester) async {
335 final api = _open();
336 final start = DateTime.now();
337 final due = start.add(const Duration(hours: 2));
338 await api.createPlanItem({
339 'kind': 'assignment',
340 'title': 'تمرین ریاضی',
341 'startsAt': start.toUtc().toIso8601String(),
342 'dueAt': due.toUtc().toIso8601String(),
343 });
344 final platform = await _controlWrites(tester, api);
345 await _planner(tester, api);
346 platform.failWrites = true;
347 await _itemMenu(tester, 'انتقال به فردا');
348
349 expect(tester.takeException(), isNull);
350 expect(find.text(_restartMessage), findsOneWidget);
351 expect(((await _nativeSnapshot())['items'] as List).single['starts_at'],
352 start.toUtc().toIso8601String());
353 expect(
354 (await SharedPreferences.getInstance())
355 .containsKey('phase3.sync.queue'),
356 isFalse);
357 platform.failWrites = false;
358 await tester.tap(find.text('تلاش دوباره'));
359 await tester.pumpAndSettle();
360 expect(find.text(_restartMessage), findsOneWidget);
361 await _expectRestartRequired(api.listPlanItems());
362
363 final restarted = _open(session: LocalDataSession());
364 expect((await restarted.listPlanItems()).single['starts_at'],
365 start.toUtc().toIso8601String());
366 await _planner(tester, restarted);
367 await _itemMenu(tester, 'انتقال به فردا');
368 final restored = (await restarted.listPlanItems()).single;
369 expect(restored['starts_at'],
370 start.add(const Duration(days: 1)).toUtc().toIso8601String());
371 expect(restored['due_at'],
372 due.add(const Duration(days: 1)).toUtc().toIso8601String());
373 });
374
375 _localWidgetTest(
376 'local read error is visible and retries without cached server data',
377 (tester) async {
378 SharedPreferences.setMockInitialValues({
379 'phase3.planner.cache': jsonEncode([
380 {'id': 'server-item', 'title': 'نسخه سرور', 'kind': 'task'},
381 ]),
382 });
383 await SharedPreferencesAsync().setString(LocalDataStore.key, '{invalid');
384 await _planner(tester, _open());
385 expect(find.textContaining('اطلاعات ذخیره‌شده روی دستگاه خراب است'),
386 findsOneWidget);
387 expect(find.text('هنوز برنامه‌ای نداری'), findsNothing);
388 expect(find.text('نسخه سرور'), findsNothing);
389 expect(find.text('جدید'), findsNothing);
390
391 await SharedPreferencesAsync().remove(LocalDataStore.key);
392 await _open().createPlanItem({
393 'kind': 'task',
394 'title': 'بعد از بازیابی',
395 'dueAt': DateTime.now().toUtc().toIso8601String(),
396 });
397 await tester.tap(find.text('تلاش دوباره'));
398 await tester.pumpAndSettle();
399 expect(find.text('بعد از بازیابی'), findsOneWidget);
400 });
401
402 for (final category in ['girl_minor', 'boy_minor', 'adult']) {
403 _localWidgetTest('$category routes by profile category without a family',
404 (tester) async {
405 await tester.pumpWidget(MaterialApp(
406 home: HomeShell(
407 api: _open(category: category),
408 localOnly: true,
409 profileCategory: category),
410 ));
411 await tester.pumpAndSettle();
412 expect(find.byType(NavigationDestination), findsNWidgets(3));
413 expect(find.text('حالت محلی · فقط روی این دستگاه'), findsOneWidget);
414 expect(find.text('آرام مهرآیین'), findsOneWidget);
415 expect(find.byType(SchoolPage), findsNothing);
416 await tester
417 .tap(find.text(category == 'adult' ? 'برنامه‌ریز' : 'برنامه'));
418 await tester.pumpAndSettle();
419 expect(find.text(category == 'adult' ? 'برنامه‌ریز' : 'برنامه هفتگی'),
420 findsWidgets);
421 expect(find.byType(PlannerPage), findsOneWidget);
422 });
423 }
424
425 _localWidgetTest('local profile exposes only name and theme editing',
426 (tester) async {
427 await tester.pumpWidget(MaterialApp(
428 home: HomeShell(
429 api: _open(), localOnly: true, profileCategory: 'girl_minor'),
430 ));
431 await tester.pumpAndSettle();
432 await tester.tap(find.byTooltip('پروفایل'));
433 await tester.pumpAndSettle();
434
435 expect(find.text('آرام مهرآیین'), findsOneWidget);
436 expect(find.text('قابلیت‌های غیرفعال در حالت محلی'), findsOneWidget);
437 expect(find.text('خانواده'), findsNothing);
438 expect(find.text('تغییر رمز عبور'), findsNothing);
439 });
440
441 _localWidgetTest(
442 'local profile edit persists full name and theme after returning home',
443 (tester) async {
444 await tester.pumpWidget(MaterialApp(
445 home: HomeShell(
446 api: _open(), localOnly: true, profileCategory: 'girl_minor'),
447 ));
448 await tester.pumpAndSettle();
449 await tester.tap(find.byTooltip('پروفایل'));
450 await tester.pumpAndSettle();
451 await tester.tap(find.byIcon(Icons.edit_outlined));
452 await tester.pumpAndSettle();
453 await tester.enterText(find.byType(TextField), 'سارا مهرآیین');
454 await tester.tap(find.byType(DropdownButtonFormField<String>));
455 await tester.pumpAndSettle();
456 await tester.tap(find.text('سفید / آبی نوجوان').last);
457 await tester.pumpAndSettle();
458 await tester.tap(find.text('ذخیره'));
459 await tester.pumpAndSettle();
460 await tester.pageBack();
461 await tester.pumpAndSettle();
462
463 expect(find.text('سارا مهرآیین'), findsOneWidget);
464 expect(Theme.of(tester.element(find.byType(TodayPage))).colorScheme.primary,
465 ColorScheme.fromSeed(seedColor: const Color(0xFF4D86E8)).primary);
466 final restored = await _open().getProfile();
467 expect(restored['display_name'], 'سارا مهرآیین');
468 expect(restored['theme_preference'], 'boy_blue');
469 });
470
471 _localWidgetTest(
472 'uncertain profile save preserves old name until full process restart',
473 (tester) async {
474 final api = _open();
475 final platform = await _controlWrites(tester, api);
476 await tester.pumpWidget(MaterialApp(
477 home: HomeShell(api: api, localOnly: true, profileCategory: 'girl_minor'),
478 ));
479 await tester.pumpAndSettle();
480 await tester.tap(find.byTooltip('پروفایل'));
481 await tester.pumpAndSettle();
482 await tester.tap(find.byIcon(Icons.edit_outlined));
483 await tester.pumpAndSettle();
484 await tester.enterText(find.byType(TextField), 'سارا مهرآیین');
485 platform.failWrites = true;
486 await tester.tap(find.text('ذخیره'));
487 await tester.pumpAndSettle();
488
489 expect(tester.takeException(), isNull);
490 expect(find.text(_restartMessage), findsOneWidget);
491 expect(
492 (await _nativeSnapshot())['profile']['display_name'], 'آرام مهرآیین');
493 await _expectRestartRequired(_open().getProfile());
494 platform.failWrites = false;
495 await tester.tap(find.text('ذخیره'));
496 await tester.pumpAndSettle();
497 expect(find.text(_restartMessage), findsOneWidget);
498 expect(
499 (await _nativeSnapshot())['profile']['display_name'], 'آرام مهرآیین');
500
501 final restarted = _open(session: LocalDataSession());
502 expect((await restarted.getProfile())['display_name'], 'آرام مهرآیین');
503 });
504
505 _localWidgetTest('local profile cannot submit again during a durable write',
506 (tester) async {
507 final api = _open();
508 final platform = await _controlWrites(tester, api);
509 await tester.pumpWidget(MaterialApp(
510 home: HomeShell(api: api, localOnly: true, profileCategory: 'girl_minor'),
511 ));
512 await tester.pumpAndSettle();
513 await tester.tap(find.byTooltip('پروفایل'));
514 await tester.pumpAndSettle();
515 await tester.tap(find.byIcon(Icons.edit_outlined));
516 await tester.pumpAndSettle();
517 await tester.enterText(find.byType(TextField), 'سارا مهرآیین');
518 platform.pendingWrite = Completer<void>();
519 await tester.tap(find.text('ذخیره'));
520 await tester.pump();
521
522 final button = tester.widget<FilledButton>(
523 find.widgetWithText(FilledButton, 'در حال ذخیره...'),
524 );
525 expect(button.onPressed, isNull);
526 platform.pendingWrite!.complete();
527 platform.pendingWrite = null;
528 await tester.pumpAndSettle();
529 expect((await _open().getProfile())['display_name'], 'سارا مهرآیین');
530 });
531
532 _localWidgetTest(
533 'production shell keeps a valid page when family role changes',
534 (tester) async {
535 final api = _RoleChangingApi();
536 await tester.pumpWidget(MaterialApp(home: HomeShell(api: api)));
537 await tester.pumpAndSettle();
538 tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
539 await tester.pumpAndSettle();
540 await tester.tap(find.text('همراه هوشمند'));
541 await tester.pumpAndSettle();
542 await tester.tap(find.byTooltip('پروفایل'));
543 await tester.pumpAndSettle();
544 api.currentRole = 'parent_guardian';
545 await tester.pageBack();
546 await tester.pumpAndSettle();
547
548 expect(tester.takeException(), isNull);
549 expect(find.text('من'), findsWidgets);
550 });
551
552 _localWidgetTest('production planner keeps local archive action unavailable',
553 (tester) async {
554 await tester.pumpWidget(MaterialApp(
555 home: Scaffold(body: PlannerPage(api: _ProductionItemApi())),
556 ));
557 await tester.pumpAndSettle();
558 await tester.tap(find.byType(PopupMenuButton<String>));
559 await tester.pumpAndSettle();
560
561 expect(find.text('بایگانی'), findsNothing);
562 });
563 }