LifeMate — Personal, Family & Learning Companion

feat/local-signing-preflight
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 347 lines 13.9 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/phase3_ui.dart';
9 import 'package:lifemate/plan_sync.dart';
10 import 'package:shared_preferences/shared_preferences.dart';
11 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
12 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
13 import 'app_test.dart' show FakeApi;
14
15 // Explicit API fixtures for widget behavior; local PostgreSQL acceptance is separate.
16 class TaskApi extends FakeApi {
17 bool offline = false;
18 final items = <Map<String, dynamic>>[
19 {
20 'id': '30000000-0000-4000-8000-000000000001',
21 'title': 'تکلیف اول',
22 'kind': 'assignment',
23 'status': 'planned',
24 'visibility': 'private',
25 'planned_duration_seconds': 1500,
26 'version': 1
27 },
28 {
29 'id': '30000000-0000-4000-8000-000000000002',
30 'title': 'تکلیف دوم',
31 'kind': 'assignment',
32 'status': 'planned',
33 'visibility': 'selected_members',
34 'planned_duration_seconds': 900,
35 'version': 1
36 },
37 ];
38 @override
39 Future<List<Map<String, dynamic>>> listPlanItems(
40 {DateTime? from, DateTime? to, String? kind}) async {
41 if (offline) throw const ApiException(0, 'network_unavailable');
42 return items
43 .where((r) => r['status'] != 'cancelled')
44 .map((r) => Map<String, dynamic>.from(r))
45 .toList();
46 }
47
48 @override
49 Future<Map<String, dynamic>> submitSyncMutations(
50 List<Map<String, dynamic>> mutations) async {
51 if (offline) throw const ApiException(0, 'network_unavailable');
52 return {
53 'results': mutations.map((m) {
54 final item = items.firstWhere((r) => r['id'] == m['entityId']);
55 item.addAll(Map<String, dynamic>.from(m['payload'] as Map));
56 item['version'] = (m['expectedVersion'] as int) + 1;
57 return {
58 'id': m['id'],
59 'status': 'accepted',
60 'item': {...item},
61 'acceptedAt': '2026-10-16T10:00:00Z'
62 };
63 }).toList()
64 };
65 }
66 }
67
68 void main() {
69 TestWidgetsFlutterBinding.ensureInitialized();
70 setUp(() {
71 WidgetController.hitTestWarningShouldBeFatal = true;
72 SharedPreferences.setMockInitialValues({});
73 SharedPreferencesAsyncPlatform.instance =
74 InMemorySharedPreferencesAsync.withData({});
75 String? token;
76 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
77 .setMockMethodCallHandler(
78 const MethodChannel('lifeguide/local_write_guard'), (call) async {
79 if (call.method == 'getBlocked') return token != null;
80 if (call.method == 'beginWrite') return token = 'synthetic-detail-write';
81 if (call.method == 'completeWrite' && call.arguments == token) {
82 token = null;
83 return true;
84 }
85 throw PlatformException(code: 'local_storage_restart_required');
86 });
87 });
88 Future<void> planner(WidgetTester tester, IdentityApi api) async {
89 await tester.pumpWidget(MaterialApp(
90 home: Directionality(
91 textDirection: TextDirection.rtl,
92 child: Scaffold(body: PlannerPage(api: api)))));
93 await tester.pumpAndSettle();
94 }
95
96 testWidgets(
97 'second task opens its own detail and complete uses acknowledged sync',
98 (tester) async {
99 final api = TaskApi();
100 await planner(tester, api);
101 await tester.tap(find.text('تکلیف دوم'));
102 await tester.pumpAndSettle();
103 expect(find.byKey(const ValueKey('plan-details')), findsOneWidget);
104 expect(find.text('تکلیف دوم'), findsOneWidget);
105 expect(find.text('اعضای انتخاب‌شده'), findsOneWidget);
106 await tester.tap(find.byKey(const ValueKey('detail-complete')));
107 await tester.pumpAndSettle();
108 expect(api.items[1]['status'], 'completed');
109 expect(find.text('توسط سرور تأیید شد'), findsOneWidget);
110 expect(find.textContaining('انجام‌شده'), findsOneWidget);
111 await tester.pumpWidget(const SizedBox());
112 });
113 testWidgets('detail edits preserve sharing and archive requires confirmation',
114 (tester) async {
115 final api = TaskApi();
116 await planner(tester, api);
117 await tester.tap(find.text('تکلیف اول'));
118 await tester.pumpAndSettle();
119 await tester.tap(find.byKey(const ValueKey('detail-edit')));
120 await tester.pumpAndSettle();
121 await tester.enterText(
122 find.widgetWithText(TextField, 'عنوان'), 'تکلیف ویرایش‌شده');
123 await tester.tap(find.text('ذخیره'));
124 await tester.pumpAndSettle();
125 expect(find.text('تکلیف ویرایش‌شده'), findsOneWidget);
126 expect(api.items.first['visibility'], 'private');
127 await tester.pump(const Duration(seconds: 5));
128 await tester.ensureVisible(find.byKey(const ValueKey('detail-archive')));
129 await tester.tap(find.byKey(const ValueKey('detail-archive')));
130 await tester.pumpAndSettle();
131 expect(api.items.first['status'], 'planned');
132 await tester.tap(find.text('بایگانی').last);
133 await tester.pumpAndSettle();
134 expect(api.items.first['status'], 'cancelled');
135 expect(find.byKey(const ValueKey('plan-details')), findsNothing);
136 await tester.pumpWidget(const SizedBox());
137 });
138 testWidgets('offline completion is pending rather than server confirmed',
139 (tester) async {
140 final api = TaskApi();
141 await planner(tester, api);
142 await tester.tap(find.text('تکلیف اول'));
143 await tester.pumpAndSettle();
144 api.offline = true;
145 await tester.tap(find.byKey(const ValueKey('detail-complete')));
146 await tester.pumpAndSettle();
147 expect(find.text('در انتظار تأیید سرور'), findsOneWidget);
148 expect(find.text('توسط سرور تأیید شد'), findsNothing);
149 expect(api.items.first['status'], 'planned');
150 expect(find.byKey(const ValueKey('detail-study')), findsNothing);
151 await tester.pumpWidget(const SizedBox());
152 });
153 testWidgets('a scoped offline create remains editable and cannot start study',
154 (tester) async {
155 final api = HttpIdentityApi(
156 baseUrl: 'https://pending-detail.example.test/api',
157 client: MockClient(
158 (_) async => throw http.ClientException('synthetic offline')))
159 ..accessToken = 'synthetic-token'
160 ..currentUserId = 'synthetic-owner';
161 await PlanSync(api).create({
162 'title': 'تکلیف آفلاین ساختگی',
163 'kind': 'assignment',
164 'visibility': 'private'
165 });
166 await planner(tester, api);
167 await tester.tap(find.text('تکلیف آفلاین ساختگی'));
168 await tester.pumpAndSettle();
169 expect(find.byKey(const ValueKey('detail-edit')), findsOneWidget);
170 expect(find.byKey(const ValueKey('detail-study')), findsNothing);
171 expect(find.text('در انتظار تأیید سرور'), findsOneWidget);
172 await tester.pumpWidget(const SizedBox());
173 api.close();
174 });
175 testWidgets(
176 'return from study refreshes changed server version before completion',
177 (tester) async {
178 var version = 1;
179 int? sentVersion;
180 final item = {
181 'id': '30000000-0000-4000-8000-000000000004',
182 'owner_user_id': 'synthetic-owner',
183 'title': 'کار با تایمر',
184 'kind': 'assignment',
185 'status': 'planned',
186 'visibility': 'private'
187 };
188 final api = HttpIdentityApi(
189 baseUrl: 'https://timer-detail.example.test/api',
190 client: MockClient((req) async {
191 Object body;
192 if (req.url.path.endsWith('/planner-series')) {
193 body = {'series': []};
194 } else if (req.url.path.endsWith('/study/sessions')) {
195 body = {'sessions': []};
196 } else if (req.method == 'POST') {
197 final mutation =
198 (jsonDecode(req.body)['mutations'] as List).single as Map;
199 sentVersion = mutation['expectedVersion'];
200 body = {
201 'results': [
202 {
203 'id': mutation['id'],
204 'status': 'accepted',
205 'acceptedAt': '2026-10-16T11:00:00Z',
206 'item': {
207 ...item,
208 'version': version + 1,
209 'status': 'completed'
210 }
211 }
212 ]
213 };
214 } else {
215 body = {
216 'items': [
217 {...item, 'version': version}
218 ]
219 };
220 }
221 return http.Response(jsonEncode(body), 200,
222 headers: {'content-type': 'application/json; charset=utf-8'});
223 }))
224 ..accessToken = 'synthetic-token'
225 ..currentUserId = 'synthetic-owner';
226 await planner(tester, api);
227 await tester.tap(find.text('کار با تایمر'));
228 await tester.pumpAndSettle();
229 await tester.tap(find.byKey(const ValueKey('detail-study')));
230 await tester.pump(const Duration(milliseconds: 400));
231 await tester.pump(const Duration(milliseconds: 400));
232 version = 2; // server version advanced while study route was open
233 await tester.tap(find.byType(BackButton).last);
234 await tester.pumpAndSettle();
235 await tester.tap(find.byKey(const ValueKey('detail-complete')));
236 await tester.pumpAndSettle();
237 expect(sentVersion, 2);
238 await tester.pumpWidget(const SizedBox());
239 api.close();
240 });
241 testWidgets('revoked shared details disappear on polling', (tester) async {
242 bool visible = true;
243 final api = HttpIdentityApi(
244 baseUrl: 'https://visibility-detail.example.test/api',
245 client: MockClient((req) async => http.Response(
246 jsonEncode(req.url.path.endsWith('/planner-series')
247 ? {'series': []}
248 : {
249 'items': visible
250 ? [
251 {
252 'id': '30000000-0000-4000-8000-000000000005',
253 'owner_user_id': 'other-owner',
254 'title': 'اشتراک موقت ساختگی',
255 'kind': 'assignment',
256 'status': 'planned',
257 'visibility': 'family',
258 'version': 1
259 }
260 ]
261 : []
262 }),
263 200,
264 headers: {'content-type': 'application/json; charset=utf-8'})))
265 ..accessToken = 'synthetic-token'
266 ..currentUserId = 'synthetic-reader';
267 await planner(tester, api);
268 await tester.tap(find.text('اشتراک موقت ساختگی'));
269 await tester.pumpAndSettle();
270 visible = false;
271 await tester.pump(const Duration(seconds: 16));
272 await tester.pumpAndSettle();
273 expect(find.text('اشتراک موقت ساختگی'), findsNothing);
274 await tester.pumpWidget(const SizedBox());
275 api.close();
276 });
277 testWidgets('shared snapshot is hidden across background and resume',
278 (tester) async {
279 final api = HttpIdentityApi(
280 baseUrl: 'https://background-detail.example.test/api',
281 client: MockClient((req) async => http.Response(
282 jsonEncode(req.url.path.endsWith('/planner-series')
283 ? {'series': []}
284 : {
285 'items': [
286 {
287 'id': '30000000-0000-4000-8000-000000000006',
288 'owner_user_id': 'other-owner',
289 'title': 'اشتراک پس‌زمینه ساختگی',
290 'kind': 'assignment',
291 'status': 'planned',
292 'visibility': 'family',
293 'version': 1
294 }
295 ]
296 }),
297 200,
298 headers: {'content-type': 'application/json; charset=utf-8'})))
299 ..accessToken = 'synthetic-token'
300 ..currentUserId = 'synthetic-reader';
301 await planner(tester, api);
302 await tester.tap(find.text('اشتراک پس‌زمینه ساختگی'));
303 await tester.pumpAndSettle();
304 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
305 await tester.pump();
306 expect(find.text('اشتراک پس‌زمینه ساختگی'), findsNothing);
307 await tester.pumpWidget(const SizedBox());
308 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
309 api.close();
310 });
311 testWidgets('shared non-owner detail is read-only and has no timer',
312 (tester) async {
313 final api = HttpIdentityApi(
314 baseUrl: 'https://detail.example.test/api',
315 client: MockClient((req) async => http.Response(
316 jsonEncode(req.url.path.endsWith('/planner-series')
317 ? {'series': []}
318 : {
319 'items': [
320 {
321 'id': '30000000-0000-4000-8000-000000000003',
322 'owner_user_id': 'other-owner',
323 'title': 'کار مشترک',
324 'kind': 'assignment',
325 'status': 'planned',
326 'visibility': 'family',
327 'version': 1
328 }
329 ]
330 }),
331 200,
332 headers: {'content-type': 'application/json; charset=utf-8'})))
333 ..accessToken = 'synthetic-token'
334 ..currentUserId = 'synthetic-reader';
335 await planner(tester, api);
336 await tester.tap(find.text('کار مشترک'));
337 await tester.pumpAndSettle();
338 expect(find.byKey(const ValueKey('plan-details')), findsOneWidget);
339 expect(find.byKey(const ValueKey('detail-edit')), findsNothing);
340 expect(find.byKey(const ValueKey('detail-complete')), findsNothing);
341 expect(find.byKey(const ValueKey('detail-archive')), findsNothing);
342 expect(find.byKey(const ValueKey('detail-study')), findsNothing);
343 expect(find.textContaining('فقط مشاهده'), findsOneWidget);
344 await tester.pumpWidget(const SizedBox());
345 api.close();
346 });
347 }