LifeMate — Personal, Family & Learning Companion

feat/flutter-mobile-navigation
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 339 lines 13.3 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('/study/sessions')) {
193 body = {'sessions': []};
194 } else if (req.method == 'POST') {
195 final mutation =
196 (jsonDecode(req.body)['mutations'] as List).single as Map;
197 sentVersion = mutation['expectedVersion'];
198 body = {
199 'results': [
200 {
201 'id': mutation['id'],
202 'status': 'accepted',
203 'acceptedAt': '2026-10-16T11:00:00Z',
204 'item': {
205 ...item,
206 'version': version + 1,
207 'status': 'completed'
208 }
209 }
210 ]
211 };
212 } else {
213 body = {
214 'items': [
215 {...item, 'version': version}
216 ]
217 };
218 }
219 return http.Response(jsonEncode(body), 200,
220 headers: {'content-type': 'application/json; charset=utf-8'});
221 }))
222 ..accessToken = 'synthetic-token'
223 ..currentUserId = 'synthetic-owner';
224 await planner(tester, api);
225 await tester.tap(find.text('کار با تایمر'));
226 await tester.pumpAndSettle();
227 await tester.tap(find.byKey(const ValueKey('detail-study')));
228 await tester.pump(const Duration(milliseconds: 400));
229 await tester.pump(const Duration(milliseconds: 400));
230 version = 2; // server version advanced while study route was open
231 await tester.tap(find.byType(BackButton).last);
232 await tester.pumpAndSettle();
233 await tester.tap(find.byKey(const ValueKey('detail-complete')));
234 await tester.pumpAndSettle();
235 expect(sentVersion, 2);
236 await tester.pumpWidget(const SizedBox());
237 api.close();
238 });
239 testWidgets('revoked shared details disappear on polling', (tester) async {
240 bool visible = true;
241 final api = HttpIdentityApi(
242 baseUrl: 'https://visibility-detail.example.test/api',
243 client: MockClient((req) async => http.Response(
244 jsonEncode({
245 'items': visible
246 ? [
247 {
248 'id': '30000000-0000-4000-8000-000000000005',
249 'owner_user_id': 'other-owner',
250 'title': 'اشتراک موقت ساختگی',
251 'kind': 'assignment',
252 'status': 'planned',
253 'visibility': 'family',
254 'version': 1
255 }
256 ]
257 : []
258 }),
259 200,
260 headers: {'content-type': 'application/json; charset=utf-8'})))
261 ..accessToken = 'synthetic-token'
262 ..currentUserId = 'synthetic-reader';
263 await planner(tester, api);
264 await tester.tap(find.text('اشتراک موقت ساختگی'));
265 await tester.pumpAndSettle();
266 visible = false;
267 await tester.pump(const Duration(seconds: 16));
268 await tester.pumpAndSettle();
269 expect(find.text('اشتراک موقت ساختگی'), findsNothing);
270 await tester.pumpWidget(const SizedBox());
271 api.close();
272 });
273 testWidgets('shared snapshot is hidden across background and resume',
274 (tester) async {
275 final api = HttpIdentityApi(
276 baseUrl: 'https://background-detail.example.test/api',
277 client: MockClient((req) async => http.Response(
278 jsonEncode({
279 'items': [
280 {
281 'id': '30000000-0000-4000-8000-000000000006',
282 'owner_user_id': 'other-owner',
283 'title': 'اشتراک پس‌زمینه ساختگی',
284 'kind': 'assignment',
285 'status': 'planned',
286 'visibility': 'family',
287 'version': 1
288 }
289 ]
290 }),
291 200,
292 headers: {'content-type': 'application/json; charset=utf-8'})))
293 ..accessToken = 'synthetic-token'
294 ..currentUserId = 'synthetic-reader';
295 await planner(tester, api);
296 await tester.tap(find.text('اشتراک پس‌زمینه ساختگی'));
297 await tester.pumpAndSettle();
298 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
299 await tester.pump();
300 expect(find.text('اشتراک پس‌زمینه ساختگی'), findsNothing);
301 await tester.pumpWidget(const SizedBox());
302 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
303 api.close();
304 });
305 testWidgets('shared non-owner detail is read-only and has no timer',
306 (tester) async {
307 final api = HttpIdentityApi(
308 baseUrl: 'https://detail.example.test/api',
309 client: MockClient((req) async => http.Response(
310 jsonEncode({
311 'items': [
312 {
313 'id': '30000000-0000-4000-8000-000000000003',
314 'owner_user_id': 'other-owner',
315 'title': 'کار مشترک',
316 'kind': 'assignment',
317 'status': 'planned',
318 'visibility': 'family',
319 'version': 1
320 }
321 ]
322 }),
323 200,
324 headers: {'content-type': 'application/json; charset=utf-8'})))
325 ..accessToken = 'synthetic-token'
326 ..currentUserId = 'synthetic-reader';
327 await planner(tester, api);
328 await tester.tap(find.text('کار مشترک'));
329 await tester.pumpAndSettle();
330 expect(find.byKey(const ValueKey('plan-details')), findsOneWidget);
331 expect(find.byKey(const ValueKey('detail-edit')), findsNothing);
332 expect(find.byKey(const ValueKey('detail-complete')), findsNothing);
333 expect(find.byKey(const ValueKey('detail-archive')), findsNothing);
334 expect(find.byKey(const ValueKey('detail-study')), findsNothing);
335 expect(find.textContaining('فقط مشاهده'), findsOneWidget);
336 await tester.pumpWidget(const SizedBox());
337 api.close();
338 });
339 }