LifeMate — Personal, Family & Learning Companion

fix/personal-upgrade-delivery-guard
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 449 lines 17.1 KB
Raw
1 import 'dart:async';
2 import 'dart:convert';
3 import 'package:flutter/material.dart';
4 import 'package:flutter_test/flutter_test.dart';
5 import 'package:http/http.dart' as http;
6 import 'package:http/testing.dart';
7 import 'package:lifemate/api.dart';
8 import 'package:lifemate/dashboard_ui.dart';
9 import 'package:lifemate/session_store.dart';
10
11 class _MemorySession extends SessionStore {
12 String? value;
13 @override
14 Future<String?> read() async => value;
15 @override
16 Future<void> write(String next) async => value = next;
17 @override
18 Future<void> clear() async => value = null;
19 }
20
21 http.Response _response(Map<String, dynamic> body) =>
22 http.Response(jsonEncode(body), 200,
23 headers: {'content-type': 'application/json'});
24 DateTime _rangeEnd() {
25 final now = DateTime.now().toUtc().add(const Duration(hours: 3, minutes: 30));
26 return DateTime.utc(now.year, now.month, now.day + 1)
27 .subtract(const Duration(hours: 3, minutes: 30));
28 }
29
30 Map<String, dynamic> _report(String taskTitle) => {
31 'metrics': {
32 'totalTasks': 99,
33 'completedTasks': 90,
34 'completionPercent': 91,
35 'plannedDurationSeconds': 60000,
36 'recordedDurationSeconds': 1500
37 },
38 'allTimeTaskMetrics': {'totalTasks': 99, 'completedTasks': 90},
39 'periodMetrics': {
40 'totalTasks': 2,
41 'completedTasks': 1,
42 'completionPercent': 50,
43 'overdueTasks': 0,
44 'plannedDurationSeconds': 1800,
45 'recordedDurationSeconds': 1500,
46 'examCount': 1,
47 'gradedExamCount': 1,
48 'gradePercent': 75
49 },
50 'items': [
51 {
52 'id': 'period-plan',
53 'title': taskTitle,
54 'kind': 'assignment',
55 'taskInRange': true,
56 'recordedDurationSeconds': 600
57 },
58 {
59 'id': 'old-plan',
60 'title': 'خارج از بازه بدون زمان',
61 'kind': 'assignment',
62 'taskInRange': false,
63 'recordedDurationSeconds': 0
64 },
65 {
66 'id': 'recorded-old-plan',
67 'title': 'تکلیف قدیمی با زمان این بازه',
68 'kind': 'assignment',
69 'taskInRange': false,
70 'recordedDurationSeconds': 900
71 },
72 ],
73 'daily': [],
74 'subjects': [
75 {'subjectName': 'درس تاریخی', 'totalTasks': 99}
76 ],
77 'periodSubjects': [
78 {
79 'subjectId': 'subject-a',
80 'subjectName': 'ریاضی',
81 'totalTasks': 2,
82 'completedTasks': 1,
83 'recordedDurationSeconds': 1500,
84 'gradePercent': 75,
85 'gradedExamCount': 1
86 }
87 ],
88 'periodExams': [
89 {
90 'id': 'exam',
91 'title': 'امتحان مجاز',
92 'kind': 'exam',
93 'gradePoints': 15,
94 'gradeOutOf': 20,
95 'dueAt': '2026-10-10T10:00:00Z'
96 }
97 ],
98 'asOf': '2026-10-11T10:00:00Z',
99 'lastSyncAt': '2026-10-11T09:00:00Z',
100 'from': _rangeEnd().subtract(const Duration(days: 7)).toIso8601String(),
101 'to': _rangeEnd().toIso8601String(),
102 'timezone': 'Asia/Tehran',
103 'taskDatePolicy': 'due_at_then_starts_at',
104 'rangeConvention': 'inclusive_from_exclusive_to',
105 'completionBasis': 'current_status_of_period_tasks',
106 };
107
108 HttpIdentityApi _api(Future<http.Response> Function(http.Request) handler) =>
109 HttpIdentityApi(
110 baseUrl: 'https://synthetic.example.test',
111 client: MockClient(handler),
112 sessionStore: _MemorySession())
113 ..accessToken = 'synthetic-token'
114 ..currentUserId = 'synthetic-parent';
115 Widget _page(HttpIdentityApi api, {String childId = 'child'}) => MaterialApp(
116 home: LearningReportPage(
117 api: api, familyId: 'family', childId: childId, childName: 'فرزند'));
118
119 void main() {
120 for (final entry in <int, String>{
121 0: '0 دقیقه',
122 4: '4 ثانیه',
123 29: '29 ثانیه',
124 30: '30 ثانیه',
125 59: '59 ثانیه',
126 60: '1 دقیقه',
127 61: '1 دقیقه و 1 ثانیه',
128 90: '1 دقیقه و 30 ثانیه',
129 1500: '25 دقیقه',
130 }.entries) {
131 testWidgets('recorded ${entry.key} seconds keeps exact parent report time',
132 (tester) async {
133 final report = _report('تکلیف با زمان دقیق');
134 (report['periodMetrics'] as Map)['recordedDurationSeconds'] = entry.key;
135 final api = _api((_) async => _response(report));
136 await tester.pumpWidget(_page(api));
137 await tester.pumpAndSettle();
138 expect(find.text('زمان ثبت‌شده: ${entry.value}'), findsOneWidget);
139 expect(find.text('زمان برنامه‌ریزی‌شده: 30 دقیقه'), findsOneWidget);
140 await tester.pumpWidget(const SizedBox());
141 api.close();
142 });
143 }
144
145 testWidgets('short duration remains exact in daily, subject and task rows',
146 (tester) async {
147 final report = _report('تکلیف چهارثانیه‌ای');
148 (report['periodMetrics'] as Map)['recordedDurationSeconds'] = 4;
149 report['daily'] = [
150 {'date': '2026-10-11', 'recordedDurationSeconds': 4}
151 ];
152 (report['periodSubjects'] as List).single['recordedDurationSeconds'] = 4;
153 report['items'] = [
154 {
155 'id': 'short-task',
156 'title': 'تکلیف چهارثانیه‌ای',
157 'kind': 'assignment',
158 'taskInRange': true,
159 'plannedDurationSeconds': 1800,
160 'recordedDurationSeconds': 4
161 }
162 ];
163 final api = _api((_) async => _response(report));
164 await tester.pumpWidget(_page(api));
165 await tester.pumpAndSettle();
166 await tester.scrollUntilVisible(find.text('4 ثانیه'), 200);
167 expect(find.text('4 ثانیه'), findsOneWidget);
168 await tester.scrollUntilVisible(
169 find.textContaining('1/2 تکمیل تکلیف‌های بازه · 4 ثانیه'), 200);
170 expect(find.textContaining('1/2 تکمیل تکلیف‌های بازه · 4 ثانیه'),
171 findsOneWidget);
172 await tester.scrollUntilVisible(
173 find.textContaining('برنامه 30 دقیقه · ثبت 4 ثانیه'), 200);
174 expect(
175 find.textContaining('برنامه 30 دقیقه · ثبت 4 ثانیه'), findsOneWidget);
176 await tester.pumpWidget(const SizedBox());
177 api.close();
178 });
179
180 testWidgets('legacy report preserves planned seconds without rounding',
181 (tester) async {
182 final report = _report('تکلیف سرور قبلی')
183 ..remove('periodMetrics')
184 ..remove('periodSubjects')
185 ..remove('periodExams');
186 (report['metrics'] as Map)
187 ..['plannedDurationSeconds'] = 95
188 ..['recordedDurationSeconds'] = 4;
189 final api = _api((_) async => _response(report));
190 await tester.pumpWidget(_page(api));
191 await tester.pumpAndSettle();
192 expect(
193 find.text('زمان برنامه‌ریزی‌شده: 1 دقیقه و 35 ثانیه'), findsOneWidget);
194 expect(find.text('زمان ثبت‌شده: 4 ثانیه'), findsOneWidget);
195 expect(find.textContaining('سرور آمار تکلیف‌های بازه را ارائه نکرده'),
196 findsOneWidget);
197 await tester.pumpWidget(const SizedBox());
198 api.close();
199 });
200
201 testWidgets('mixed duration fits a narrow RTL daily report', (tester) async {
202 tester.view.physicalSize = const Size(320, 960);
203 tester.view.devicePixelRatio = 1;
204 addTearDown(tester.view.resetPhysicalSize);
205 addTearDown(tester.view.resetDevicePixelRatio);
206 final report = _report('تکلیف نیم‌دقیقه اضافه');
207 report['daily'] = [
208 {'date': '2026-10-11', 'recordedDurationSeconds': 90}
209 ];
210 final api = _api((_) async => _response(report));
211 await tester.pumpWidget(MaterialApp(
212 home: Directionality(
213 textDirection: TextDirection.rtl,
214 child: LearningReportPage(
215 api: api,
216 familyId: 'family',
217 childId: 'child',
218 childName: 'فرزند'))));
219 await tester.pumpAndSettle();
220 await tester.scrollUntilVisible(find.text('1 دقیقه و 30 ثانیه'), 200);
221 expect(find.text('1 دقیقه و 30 ثانیه'), findsOneWidget);
222 expect(tester.takeException(), isNull);
223 await tester.pumpWidget(const SizedBox());
224 api.close();
225 });
226
227 testWidgets(
228 'range dashboard uses period counters and preserves explicitly labelled history',
229 (tester) async {
230 final api = _api((_) async => _response(_report('تکلیف بازه')));
231 await tester.pumpWidget(_page(api));
232 await tester.pumpAndSettle();
233 expect(find.text('2 تکلیف در بازه'), findsOneWidget);
234 expect(find.text('50٪ تکمیل تکلیف‌های بازه'), findsOneWidget);
235 expect(find.textContaining('کل سابقه مجاز: 99 تکلیف'), findsOneWidget);
236 expect(find.text('زمان برنامه‌ریزی‌شده: 30 دقیقه'), findsOneWidget);
237 expect(find.text('زمان ثبت‌شده: 25 دقیقه'), findsOneWidget);
238 expect(find.text('خارج از بازه بدون زمان'), findsNothing);
239 expect(find.text('درس تاریخی'), findsNothing);
240 await tester.scrollUntilVisible(
241 find.text('تکلیف قدیمی با زمان این بازه'), 250);
242 expect(find.text('تکلیف قدیمی با زمان این بازه'), findsOneWidget);
243 expect(
244 find.textContaining('موعد این تکلیف خارج از بازه است'), findsOneWidget);
245 await tester.pumpWidget(const SizedBox());
246 api.close();
247 });
248
249 testWidgets(
250 'older server counters are clearly historical and do not claim period completion',
251 (tester) async {
252 final data = _report('تکلیف تاریخی')
253 ..remove('periodMetrics')
254 ..remove('periodSubjects')
255 ..remove('periodExams');
256 final api = _api((_) async => _response(data));
257 await tester.pumpWidget(_page(api));
258 await tester.pumpAndSettle();
259 expect(find.textContaining('سرور آمار تکلیف‌های بازه را ارائه نکرده'),
260 findsOneWidget);
261 expect(find.text('99 تکلیف در کل سابقه مجاز'), findsOneWidget);
262 expect(find.text('91٪ تکمیل تکلیف‌های بازه'), findsNothing);
263 await tester.pumpWidget(const SizedBox());
264 api.close();
265 });
266
267 testWidgets(
268 'delayed previous-child report cannot overwrite the newly selected child',
269 (tester) async {
270 final first = Completer<http.Response>();
271 var calls = 0;
272 final api = _api((request) {
273 calls++;
274 return request.url.path.contains('/children/first/')
275 ? first.future
276 : Future.value(_response(_report('گزارش فرزند دوم')));
277 });
278 await tester.pumpWidget(_page(api, childId: 'first'));
279 await tester.pump();
280 await tester.pumpWidget(_page(api, childId: 'second'));
281 await tester.pumpAndSettle();
282 expect(calls, 2);
283 await tester.scrollUntilVisible(find.text('گزارش فرزند دوم'), 250);
284 first.complete(_response(_report('گزارش فرزند اول قدیمی')));
285 await tester.pumpAndSettle();
286 expect(find.text('گزارش فرزند اول قدیمی'), findsNothing);
287 expect(find.text('گزارش فرزند دوم'), findsOneWidget);
288 await tester.pumpWidget(const SizedBox());
289 api.close();
290 });
291
292 testWidgets('signed-out report never requests or exposes a child report',
293 (tester) async {
294 var calls = 0;
295 final api = _api((_) async {
296 calls++;
297 return _response(_report('اطلاعات خصوصی بدون حساب'));
298 })
299 ..accessToken = null;
300 await tester.pumpWidget(_page(api));
301 await tester.pumpAndSettle();
302 expect(calls, 0);
303 expect(find.text('اطلاعات خصوصی بدون حساب'), findsNothing);
304 expect(find.textContaining('نشست ورود معتبر نیست'), findsOneWidget);
305 await tester.pumpWidget(const SizedBox());
306 api.close();
307 });
308
309 testWidgets(
310 'malformed period response is refused instead of fabricated zeroes',
311 (tester) async {
312 final data = _report('پاسخ نامعتبر')
313 ..['periodMetrics'] = {'totalTasks': -1};
314 final api = _api((_) async => _response(data));
315 await tester.pumpWidget(_page(api));
316 await tester.pumpAndSettle();
317 expect(find.text('-1 تکلیف در بازه'), findsNothing);
318 expect(find.text('0٪ تکمیل تکلیف‌های بازه'), findsNothing);
319 expect(find.textContaining('پاسخ معتبر نداد'), findsOneWidget);
320 await tester.pumpWidget(const SizedBox());
321 api.close();
322 });
323
324 testWidgets(
325 'failed refresh clears period metrics without old permission proof',
326 (tester) async {
327 var fail = false;
328 final api = _api((_) async => fail
329 ? http.Response('{"error":"synthetic_failed"}', 500,
330 headers: {'content-type': 'application/json'})
331 : _response(_report('تکلیف مجاز قبلی')));
332 await tester.pumpWidget(_page(api));
333 await tester.pumpAndSettle();
334 expect(find.text('2 تکلیف در بازه'), findsOneWidget);
335 fail = true;
336 await tester.pump(const Duration(seconds: 15));
337 await tester.pumpAndSettle();
338 expect(find.text('2 تکلیف در بازه'), findsNothing);
339 expect(find.textContaining('اطلاعات فرزند بدون تأیید مجوز فعلی'),
340 findsOneWidget);
341 await tester.pumpWidget(const SizedBox());
342 api.close();
343 });
344
345 testWidgets('family dashboard clears prior account while replacement waits',
346 (tester) async {
347 final second = Completer<http.Response>();
348 final firstApi =
349 _api((request) async => _response(request.url.path.endsWith('/members')
350 ? {
351 'members': [
352 {
353 'user_id': 'first-child',
354 'role': 'teen_minor',
355 'display_name': 'فرزند حساب پیشین'
356 }
357 ]
358 }
359 : {
360 'families': [
361 {
362 'id': 'family',
363 'role': 'parent_guardian',
364 'name': 'خانواده اول'
365 }
366 ]
367 }));
368 final secondApi = _api((_) => second.future)
369 ..currentUserId = 'second-synthetic-parent';
370 Widget family(HttpIdentityApi api) =>
371 MaterialApp(home: Scaffold(body: ParentFamilyDashboard(api: api)));
372 await tester.pumpWidget(family(firstApi));
373 await tester.pumpAndSettle();
374 expect(find.text('فرزند حساب پیشین'), findsOneWidget);
375 await tester.pumpWidget(family(secondApi));
376 await tester.pump();
377 expect(find.text('فرزند حساب پیشین'), findsNothing);
378 second.complete(_response({'families': []}));
379 await tester.pumpAndSettle();
380 expect(find.text('فرزند متصل نمایش داده نشد'), findsOneWidget);
381 await tester.pumpWidget(const SizedBox());
382 firstApi.close();
383 secondApi.close();
384 });
385
386 testWidgets(
387 'pausing clears a report and resumed fetch must freshly authorize',
388 (tester) async {
389 final delayed = Completer<http.Response>();
390 var calls = 0;
391 final api = _api((_) {
392 calls++;
393 return calls == 1
394 ? Future.value(_response(_report('داده مجاز قبلی')))
395 : delayed.future;
396 });
397 await tester.pumpWidget(_page(api));
398 await tester.pumpAndSettle();
399 expect(find.text('2 تکلیف در بازه'), findsOneWidget);
400 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
401 await tester.pump();
402 expect(find.text('2 تکلیف در بازه'), findsNothing);
403 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
404 await tester.pump();
405 expect(find.text('2 تکلیف در بازه'), findsNothing);
406 delayed.complete(_response(_report('داده تازه مجاز')));
407 await tester.pumpAndSettle();
408 expect(calls, 2);
409 expect(find.text('2 تکلیف در بازه'), findsOneWidget);
410 await tester.pumpWidget(const SizedBox());
411 api.close();
412 });
413
414 for (final field in ['from', 'familyId', 'childId']) {
415 testWidgets('report rejects mismatched requested $field', (tester) async {
416 final data = _report('گزارش خارج از درخواست');
417 data[field] =
418 field == 'from' ? '2025-01-01T00:00:00Z' : 'another-synthetic-id';
419 final api = _api((_) async => _response(data));
420 await tester.pumpWidget(_page(api));
421 await tester.pumpAndSettle();
422 expect(find.text('2 تکلیف در بازه'), findsNothing);
423 expect(find.textContaining('پاسخ معتبر نداد'), findsOneWidget);
424 await tester.pumpWidget(const SizedBox());
425 api.close();
426 });
427 }
428
429 testWidgets('same API account switch requests new report immediately',
430 (tester) async {
431 var calls = 0;
432 final api = _api((_) async {
433 calls++;
434 return _response(
435 _report(calls == 1 ? 'گزارش حساب اول' : 'گزارش حساب دوم'));
436 });
437 await tester.pumpWidget(_page(api));
438 await tester.pumpAndSettle();
439 expect(calls, 1);
440 api.currentUserId = 'another-synthetic-parent';
441 await tester.pumpWidget(_page(api));
442 await tester.pumpAndSettle();
443 expect(calls, 2);
444 await tester.scrollUntilVisible(find.text('گزارش حساب دوم'), 200);
445 expect(find.text('گزارش حساب اول'), findsNothing);
446 await tester.pumpWidget(const SizedBox());
447 api.close();
448 });
449 }