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
dart 304 lines 11 KB
Raw
1 import 'dart:convert';
2 import 'package:flutter/material.dart';
3 import 'package:flutter/services.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/session_store.dart';
9 import 'package:lifemate/study_coordinator.dart';
10 import 'package:lifemate/study_ui.dart';
11 import 'package:lifemate/dashboard_ui.dart';
12 import 'package:lifemate/phase3_ui.dart' show shortDate;
13 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
14 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
15
16 class _MemorySession extends SessionStore {
17 String? value;
18 @override
19 Future<String?> read() async => value;
20 @override
21 Future<void> write(String next) async {
22 value = next;
23 }
24
25 @override
26 Future<void> clear() async {
27 value = null;
28 }
29 }
30
31 HttpIdentityApi apiFor(Future<http.Response> Function(http.Request) handler) =>
32 HttpIdentityApi(
33 baseUrl: 'https://synthetic.example.test/service',
34 client: MockClient(handler),
35 sessionStore: _MemorySession())
36 ..accessToken = 'synthetic-token'
37 ..currentUserId = 'synthetic-child';
38 http.Response jsonResponse(Map<String, dynamic> json, [int status = 200]) =>
39 http.Response(jsonEncode(json), status,
40 headers: {'content-type': 'application/json'});
41 void main() {
42 TestWidgetsFlutterBinding.ensureInitialized();
43 setUp(() {
44 SharedPreferencesAsyncPlatform.instance =
45 InMemorySharedPreferencesAsync.withData({});
46 String? pending;
47 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
48 .setMockMethodCallHandler(
49 const MethodChannel('lifeguide/local_write_guard'), (call) async {
50 if (call.method == 'getBlocked') return pending != null;
51 if (call.method == 'beginWrite') return pending = 'study-test-token';
52 if (call.method == 'completeWrite' && call.arguments == pending) {
53 pending = null;
54 return true;
55 }
56 throw PlatformException(code: 'local_storage_restart_required');
57 });
58 });
59 test('study acknowledgement for another session retains exact queued event',
60 () async {
61 final api = apiFor((req) async {
62 final body = jsonDecode(req.body) as Map;
63 return jsonResponse({
64 'session': {'id': 'different-session', 'version': 1},
65 'acknowledgement': {
66 'mutationId': body['mutationId'],
67 'status': 'accepted',
68 'acceptedAt': '2026-10-08T10:00:00Z'
69 }
70 });
71 });
72 final sync = StudySync(api);
73 await expectLater(sync.start('owned-plan'), throwsA(isA<ApiException>()));
74 expect(await sync.store.readQueue(), hasLength(1));
75 api.close();
76 });
77 test('offline study start reopens and retries the same body once', () async {
78 bool offline = true;
79 final sent = <Map<String, dynamic>>[];
80 final api = apiFor((req) async {
81 final body = Map<String, dynamic>.from(jsonDecode(req.body) as Map);
82 sent.add(body);
83 if (offline) throw http.ClientException('synthetic transport failure');
84 return jsonResponse({
85 'session': {
86 'id': body['id'],
87 'planItemId': body['planItemId'],
88 'status': 'running',
89 'version': 1,
90 'recordedDurationSeconds': 0,
91 'intervals': []
92 },
93 'acknowledgement': {
94 'mutationId': body['mutationId'],
95 'status': 'accepted',
96 'acceptedAt': '2026-10-08T10:00:00Z'
97 }
98 });
99 });
100 final first = await StudySync(api).start('owned-plan');
101 expect(first.queued, isTrue);
102 final reopened = StudySync(api);
103 final retained = await reopened.store.readQueue();
104 expect(retained, hasLength(1));
105 offline = false;
106 await reopened.flush();
107 expect(sent[1], sent[0]);
108 expect(await reopened.store.readQueue(), isEmpty);
109 expect((await reopened.store.readList('study.sessions')).single['status'],
110 'running');
111 api.close();
112 });
113 testWidgets(
114 'timer restores a running server session and labels recorded time',
115 (tester) async {
116 final api = apiFor((req) async => jsonResponse({
117 'sessions': [
118 {
119 'id': 'server-session',
120 'planItemId': 'owned-plan',
121 'status': 'running',
122 'version': 3,
123 'recordedDurationSeconds': 120,
124 'intervals': [],
125 'isEvidenceOfStudy': false
126 }
127 ],
128 'asOf': '2026-10-08T10:00:00Z'
129 }));
130 await tester.pumpWidget(MaterialApp(
131 home: StudyTimerPage(
132 api: api, item: {'id': 'owned-plan', 'title': 'ریاضی'})));
133 await tester.pumpAndSettle();
134 expect(find.text('مکث'), findsOneWidget);
135 expect(find.text('پایان'), findsOneWidget);
136 expect(find.text('2:00'), findsOneWidget);
137 expect(find.textContaining('اثبات مطالعه نیست'), findsOneWidget);
138 await tester.pumpWidget(const SizedBox());
139 api.close();
140 });
141 testWidgets(
142 'parent polling failure clears report until current permission succeeds',
143 (tester) async {
144 var fail = false;
145 var calls = 0;
146 final api = apiFor((req) async {
147 calls++;
148 return fail
149 ? jsonResponse({'error': 'server_failed'}, 500)
150 : jsonResponse({
151 'metrics': {
152 'totalTasks': 1,
153 'completedTasks': 0,
154 'overdueTasks': 0,
155 'completionPercent': 0,
156 'plannedDurationSeconds': 1800,
157 'recordedDurationSeconds': 120
158 },
159 'items': [
160 {
161 'id': 'plan',
162 'title': 'ریاضی',
163 'kind': 'assignment',
164 'activityState': 'started',
165 'activitySource': 'timer'
166 }
167 ],
168 'daily': [],
169 'subjects': [],
170 'asOf': '2026-10-08T10:00:00Z',
171 'lastSyncAt': '2026-10-08T09:00:00Z'
172 });
173 });
174 await tester.pumpWidget(MaterialApp(
175 home: LearningReportPage(
176 api: api,
177 familyId: 'family',
178 childId: 'child',
179 childName: 'فرزند')));
180 await tester.pumpAndSettle();
181 await tester.scrollUntilVisible(find.text('ریاضی'), 200);
182 expect(find.text('ریاضی'), findsOneWidget);
183 fail = true;
184 await tester.pump(const Duration(seconds: 15));
185 await tester.pumpAndSettle();
186 await tester.scrollUntilVisible(
187 find.textContaining('اطلاعات فرزند بدون تأیید مجوز فعلی'), -200);
188 expect(find.textContaining('اطلاعات فرزند بدون تأیید مجوز فعلی'),
189 findsOneWidget);
190 expect(find.text('ریاضی'), findsNothing);
191 expect(calls, 2);
192 await tester.pumpWidget(const SizedBox());
193 await tester.pump(const Duration(seconds: 30));
194 expect(calls, 2);
195 api.close();
196 });
197 for (final denial in [401, 403, 0]) {
198 testWidgets(
199 'parent refresh failure $denial clears previously displayed child data',
200 (tester) async {
201 var fail = false;
202 final api = apiFor((req) async {
203 if (fail) {
204 if (denial == 0) {
205 throw http.ClientException('synthetic transport failure');
206 }
207 return jsonResponse({'error': 'forbidden'}, denial);
208 }
209 return jsonResponse({
210 'metrics': {},
211 'items': [
212 {
213 'id': 'plan',
214 'title': 'اطلاعات فرزند',
215 'kind': 'assignment',
216 'activityState': 'started',
217 'activitySource': 'timer'
218 }
219 ],
220 'daily': [],
221 'subjects': [],
222 'asOf': '2026-10-08T10:00:00Z'
223 });
224 });
225 await tester.pumpWidget(MaterialApp(
226 home: LearningReportPage(
227 api: api,
228 familyId: 'family',
229 childId: 'child',
230 childName: 'فرزند')));
231 await tester.pumpAndSettle();
232 await tester.scrollUntilVisible(find.text('اطلاعات فرزند'), 200);
233 expect(find.text('اطلاعات فرزند'), findsOneWidget);
234 fail = true;
235 await tester.pump(const Duration(seconds: 15));
236 await tester.pumpAndSettle();
237 expect(find.text('اطلاعات فرزند'), findsNothing);
238 expect(
239 find.textContaining(denial == 401
240 ? 'نشست ورود'
241 : denial == 403
242 ? 'دسترسی نداری'
243 : 'اتصال برقرار نیست'),
244 findsOneWidget);
245 await tester.pumpWidget(const SizedBox());
246 api.close();
247 });
248 }
249
250 testWidgets('weekly and monthly reports include the rest of today in Tehran',
251 (tester) async {
252 final now = DateTime.now().toUtc();
253 final tehran = now.add(const Duration(hours: 3, minutes: 30));
254 final dayEnd = DateTime.utc(tehran.year, tehran.month, tehran.day + 1)
255 .subtract(const Duration(hours: 3, minutes: 30));
256 final laterToday = now.add(dayEnd.difference(now) ~/ 2);
257 final windows = <Map<String, DateTime>>[];
258 final api = apiFor((request) async {
259 final from = DateTime.parse(request.url.queryParameters['from']!);
260 final to = DateTime.parse(request.url.queryParameters['to']!);
261 windows.add({'from': from, 'to': to});
262 final included = !laterToday.isBefore(from) && laterToday.isBefore(to);
263 return jsonResponse({
264 'metrics': {
265 'plannedDurationSeconds': 1800,
266 'plannedInRangeDurationSeconds': included ? 1800 : 0,
267 'recordedDurationSeconds': 1500
268 },
269 'items': [
270 {
271 'id': 'today-plan',
272 'title': 'ریاضی امروز',
273 'kind': 'assignment',
274 'dueAt': laterToday.toIso8601String(),
275 'plannedDurationSeconds': 1800,
276 }
277 ],
278 'daily': [],
279 'subjects': [],
280 'asOf': now.toIso8601String(),
281 });
282 });
283 await tester.pumpWidget(MaterialApp(
284 home: LearningReportPage(
285 api: api,
286 familyId: 'family',
287 childId: 'child',
288 childName: 'فرزند')));
289 await tester.pumpAndSettle();
290 expect(windows.single['to'], dayEnd);
291 expect(windows.single['from'], dayEnd.subtract(const Duration(days: 7)));
292 expect(find.text('زمان برنامه‌ریزی‌شده: 30 دقیقه'), findsOneWidget);
293 expect(find.text('زمان ثبت‌شده: 25 دقیقه'), findsOneWidget);
294 expect(
295 find.textContaining('دریافت سرور: ${shortDate(now)}'), findsOneWidget);
296 await tester.tap(find.text('ماهانه'));
297 await tester.pumpAndSettle();
298 expect(windows.last['to'], dayEnd);
299 expect(windows.last['from'], dayEnd.subtract(const Duration(days: 30)));
300 expect(find.text('زمان برنامه‌ریزی‌شده: 30 دقیقه'), findsOneWidget);
301 await tester.pumpWidget(const SizedBox());
302 api.close();
303 });
304 }