LifeMate — Personal, Family & Learning Companion

feat/learning-content-operations
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 342 lines 12.8 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 testWidgets(
121 'range dashboard uses period counters and preserves explicitly labelled history',
122 (tester) async {
123 final api = _api((_) async => _response(_report('تکلیف بازه')));
124 await tester.pumpWidget(_page(api));
125 await tester.pumpAndSettle();
126 expect(find.text('2 تکلیف در بازه'), findsOneWidget);
127 expect(find.text('50٪ تکمیل تکلیف‌های بازه'), findsOneWidget);
128 expect(find.textContaining('کل سابقه مجاز: 99 تکلیف'), findsOneWidget);
129 expect(find.text('زمان برنامه‌ریزی‌شده: 30 دقیقه'), findsOneWidget);
130 expect(find.text('زمان ثبت‌شده: 25 دقیقه'), findsOneWidget);
131 expect(find.text('خارج از بازه بدون زمان'), findsNothing);
132 expect(find.text('درس تاریخی'), findsNothing);
133 await tester.scrollUntilVisible(
134 find.text('تکلیف قدیمی با زمان این بازه'), 250);
135 expect(find.text('تکلیف قدیمی با زمان این بازه'), findsOneWidget);
136 expect(
137 find.textContaining('موعد این تکلیف خارج از بازه است'), findsOneWidget);
138 await tester.pumpWidget(const SizedBox());
139 api.close();
140 });
141
142 testWidgets(
143 'older server counters are clearly historical and do not claim period completion',
144 (tester) async {
145 final data = _report('تکلیف تاریخی')
146 ..remove('periodMetrics')
147 ..remove('periodSubjects')
148 ..remove('periodExams');
149 final api = _api((_) async => _response(data));
150 await tester.pumpWidget(_page(api));
151 await tester.pumpAndSettle();
152 expect(find.textContaining('سرور آمار تکلیف‌های بازه را ارائه نکرده'),
153 findsOneWidget);
154 expect(find.text('99 تکلیف در کل سابقه مجاز'), findsOneWidget);
155 expect(find.text('91٪ تکمیل تکلیف‌های بازه'), findsNothing);
156 await tester.pumpWidget(const SizedBox());
157 api.close();
158 });
159
160 testWidgets(
161 'delayed previous-child report cannot overwrite the newly selected child',
162 (tester) async {
163 final first = Completer<http.Response>();
164 var calls = 0;
165 final api = _api((request) {
166 calls++;
167 return request.url.path.contains('/children/first/')
168 ? first.future
169 : Future.value(_response(_report('گزارش فرزند دوم')));
170 });
171 await tester.pumpWidget(_page(api, childId: 'first'));
172 await tester.pump();
173 await tester.pumpWidget(_page(api, childId: 'second'));
174 await tester.pumpAndSettle();
175 expect(calls, 2);
176 await tester.scrollUntilVisible(find.text('گزارش فرزند دوم'), 250);
177 first.complete(_response(_report('گزارش فرزند اول قدیمی')));
178 await tester.pumpAndSettle();
179 expect(find.text('گزارش فرزند اول قدیمی'), findsNothing);
180 expect(find.text('گزارش فرزند دوم'), findsOneWidget);
181 await tester.pumpWidget(const SizedBox());
182 api.close();
183 });
184
185 testWidgets('signed-out report never requests or exposes a child report',
186 (tester) async {
187 var calls = 0;
188 final api = _api((_) async {
189 calls++;
190 return _response(_report('اطلاعات خصوصی بدون حساب'));
191 })
192 ..accessToken = null;
193 await tester.pumpWidget(_page(api));
194 await tester.pumpAndSettle();
195 expect(calls, 0);
196 expect(find.text('اطلاعات خصوصی بدون حساب'), findsNothing);
197 expect(find.textContaining('نشست ورود معتبر نیست'), findsOneWidget);
198 await tester.pumpWidget(const SizedBox());
199 api.close();
200 });
201
202 testWidgets(
203 'malformed period response is refused instead of fabricated zeroes',
204 (tester) async {
205 final data = _report('پاسخ نامعتبر')
206 ..['periodMetrics'] = {'totalTasks': -1};
207 final api = _api((_) async => _response(data));
208 await tester.pumpWidget(_page(api));
209 await tester.pumpAndSettle();
210 expect(find.text('-1 تکلیف در بازه'), findsNothing);
211 expect(find.text('0٪ تکمیل تکلیف‌های بازه'), findsNothing);
212 expect(find.textContaining('پاسخ معتبر نداد'), findsOneWidget);
213 await tester.pumpWidget(const SizedBox());
214 api.close();
215 });
216
217 testWidgets(
218 'failed refresh clears period metrics without old permission proof',
219 (tester) async {
220 var fail = false;
221 final api = _api((_) async => fail
222 ? http.Response('{"error":"synthetic_failed"}', 500,
223 headers: {'content-type': 'application/json'})
224 : _response(_report('تکلیف مجاز قبلی')));
225 await tester.pumpWidget(_page(api));
226 await tester.pumpAndSettle();
227 expect(find.text('2 تکلیف در بازه'), findsOneWidget);
228 fail = true;
229 await tester.pump(const Duration(seconds: 15));
230 await tester.pumpAndSettle();
231 expect(find.text('2 تکلیف در بازه'), findsNothing);
232 expect(find.textContaining('اطلاعات فرزند بدون تأیید مجوز فعلی'),
233 findsOneWidget);
234 await tester.pumpWidget(const SizedBox());
235 api.close();
236 });
237
238 testWidgets('family dashboard clears prior account while replacement waits',
239 (tester) async {
240 final second = Completer<http.Response>();
241 final firstApi =
242 _api((request) async => _response(request.url.path.endsWith('/members')
243 ? {
244 'members': [
245 {
246 'user_id': 'first-child',
247 'role': 'teen_minor',
248 'display_name': 'فرزند حساب پیشین'
249 }
250 ]
251 }
252 : {
253 'families': [
254 {
255 'id': 'family',
256 'role': 'parent_guardian',
257 'name': 'خانواده اول'
258 }
259 ]
260 }));
261 final secondApi = _api((_) => second.future)
262 ..currentUserId = 'second-synthetic-parent';
263 Widget family(HttpIdentityApi api) =>
264 MaterialApp(home: Scaffold(body: ParentFamilyDashboard(api: api)));
265 await tester.pumpWidget(family(firstApi));
266 await tester.pumpAndSettle();
267 expect(find.text('فرزند حساب پیشین'), findsOneWidget);
268 await tester.pumpWidget(family(secondApi));
269 await tester.pump();
270 expect(find.text('فرزند حساب پیشین'), findsNothing);
271 second.complete(_response({'families': []}));
272 await tester.pumpAndSettle();
273 expect(find.text('فرزند متصل نمایش داده نشد'), findsOneWidget);
274 await tester.pumpWidget(const SizedBox());
275 firstApi.close();
276 secondApi.close();
277 });
278
279 testWidgets(
280 'pausing clears a report and resumed fetch must freshly authorize',
281 (tester) async {
282 final delayed = Completer<http.Response>();
283 var calls = 0;
284 final api = _api((_) {
285 calls++;
286 return calls == 1
287 ? Future.value(_response(_report('داده مجاز قبلی')))
288 : delayed.future;
289 });
290 await tester.pumpWidget(_page(api));
291 await tester.pumpAndSettle();
292 expect(find.text('2 تکلیف در بازه'), findsOneWidget);
293 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
294 await tester.pump();
295 expect(find.text('2 تکلیف در بازه'), findsNothing);
296 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
297 await tester.pump();
298 expect(find.text('2 تکلیف در بازه'), findsNothing);
299 delayed.complete(_response(_report('داده تازه مجاز')));
300 await tester.pumpAndSettle();
301 expect(calls, 2);
302 expect(find.text('2 تکلیف در بازه'), findsOneWidget);
303 await tester.pumpWidget(const SizedBox());
304 api.close();
305 });
306
307 for (final field in ['from', 'familyId', 'childId']) {
308 testWidgets('report rejects mismatched requested $field', (tester) async {
309 final data = _report('گزارش خارج از درخواست');
310 data[field] =
311 field == 'from' ? '2025-01-01T00:00:00Z' : 'another-synthetic-id';
312 final api = _api((_) async => _response(data));
313 await tester.pumpWidget(_page(api));
314 await tester.pumpAndSettle();
315 expect(find.text('2 تکلیف در بازه'), findsNothing);
316 expect(find.textContaining('پاسخ معتبر نداد'), findsOneWidget);
317 await tester.pumpWidget(const SizedBox());
318 api.close();
319 });
320 }
321
322 testWidgets('same API account switch requests new report immediately',
323 (tester) async {
324 var calls = 0;
325 final api = _api((_) async {
326 calls++;
327 return _response(
328 _report(calls == 1 ? 'گزارش حساب اول' : 'گزارش حساب دوم'));
329 });
330 await tester.pumpWidget(_page(api));
331 await tester.pumpAndSettle();
332 expect(calls, 1);
333 api.currentUserId = 'another-synthetic-parent';
334 await tester.pumpWidget(_page(api));
335 await tester.pumpAndSettle();
336 expect(calls, 2);
337 await tester.scrollUntilVisible(find.text('گزارش حساب دوم'), 200);
338 expect(find.text('گزارش حساب اول'), findsNothing);
339 await tester.pumpWidget(const SizedBox());
340 api.close();
341 });
342 }