LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 643 lines 26.2 KB
Raw
1 import 'dart:convert';
2 import 'package:http/http.dart' as http;
3 import 'package:http/testing.dart';
4 import 'package:lifemate/runtime_config.dart';
5 import 'package:lifemate/runtime_controller.dart';
6 import 'package:lifemate/session_store.dart';
7 import 'package:lifemate/offline_store.dart';
8 import 'package:lifemate/plan_sync.dart';
9 import 'package:flutter/services.dart';
10 import 'package:flutter/material.dart';
11 import 'package:flutter_test/flutter_test.dart';
12 import 'package:lifemate/api.dart';
13 import 'package:lifemate/main.dart';
14 import 'package:lifemate/phase3_ui.dart';
15 import 'package:lifemate/phase4_ui.dart';
16 import 'package:lifemate/sync_changes_ui.dart';
17 import 'package:shared_preferences/shared_preferences.dart';
18 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
19 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
20
21 import 'app_test.dart' show FakeApi;
22
23 class _FailingProfileApi extends FakeApi {
24 @override
25 Future<Map<String, dynamic>> updateProfile(
26 {String? displayName,
27 String? birthDate,
28 String? themePreference,
29 String? profileCategory}) async =>
30 throw const ApiException(500, 'server_failed');
31 }
32
33 class _MemorySession extends SessionStore {
34 String? value;
35 @override
36 Future<String?> read() async => value;
37 @override
38 Future<void> write(String next) async {
39 value = next;
40 }
41
42 @override
43 Future<void> clear() async {
44 value = null;
45 }
46 }
47
48 class _ServerFailureApi extends FakeApi {
49 @override
50 Future<List<Map<String, dynamic>>> listPlanItems(
51 {DateTime? from, DateTime? to, String? kind}) async =>
52 throw const ApiException(500, 'server_failed');
53 }
54
55 class _PlannerWritesApi extends FakeApi {
56 final mutations = <Map<String, dynamic>>[];
57 @override
58 Future<Map<String, dynamic>> submitSyncMutations(
59 List<Map<String, dynamic>> changes) async {
60 mutations.addAll(changes);
61 return {
62 'results': changes
63 .map((m) => {
64 'id': m['id'],
65 'status': 'accepted',
66 'item': {
67 'id': m['entityId'],
68 ...(m['payload'] as Map),
69 'version': (m['expectedVersion'] as int) + 1,
70 'status': 'planned'
71 },
72 'acceptedAt': '2026-10-08T10:00:00Z'
73 })
74 .toList()
75 };
76 }
77 }
78
79 class _CategoryApi extends FakeApi {
80 _CategoryApi(this.category, {super.role});
81 String category;
82 @override
83 Future<Map<String, dynamic>> getProfile() async =>
84 {...await super.getProfile(), 'profile_category': category};
85 @override
86 Future<Map<String, dynamic>> updateProfile(
87 {String? displayName,
88 String? birthDate,
89 String? themePreference,
90 String? profileCategory}) async {
91 if (profileCategory != null) category = profileCategory;
92 return {
93 ...await super.updateProfile(
94 displayName: displayName,
95 birthDate: birthDate,
96 themePreference: themePreference),
97 'profile_category': category
98 };
99 }
100 }
101
102 class _OfflinePlannerApi extends FakeApi {
103 @override
104 Future<List<Map<String, dynamic>>> listPlanItems(
105 {DateTime? from, DateTime? to, String? kind}) async =>
106 throw const ApiException(0, 'network_unavailable');
107 @override
108 Future<Map<String, dynamic>> submitSyncMutations(
109 List<Map<String, dynamic>> changes) async =>
110 throw const ApiException(0, 'network_unavailable');
111 }
112
113 class _CategoryWithoutFamiliesApi extends _CategoryApi {
114 _CategoryWithoutFamiliesApi() : super('adult');
115 @override
116 Future<List<Map<String, dynamic>>> listFamilies() async =>
117 throw const ApiException(500, 'server_failed');
118 }
119
120 void main() {
121 setUp(() {
122 SharedPreferences.setMockInitialValues({});
123 SharedPreferencesAsyncPlatform.instance =
124 InMemorySharedPreferencesAsync.withData({});
125 String? pending;
126 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
127 .setMockMethodCallHandler(
128 const MethodChannel('lifeguide/local_write_guard'), (call) async {
129 if (call.method == 'getBlocked') return pending != null;
130 if (call.method == 'beginWrite') return pending = 'owned-ui-test-token';
131 if (call.method == 'completeWrite' && call.arguments == pending) {
132 pending = null;
133 return true;
134 }
135 throw PlatformException(code: 'local_storage_restart_required');
136 });
137 });
138
139 testWidgets('empty runtime endpoints open setup before constructing an API',
140 (tester) async {
141 await tester.pumpWidget(LifeMateApp());
142 await tester.pumpAndSettle();
143 expect(find.text('اتصال لایف‌گاید'), findsOneWidget);
144 expect(find.text('ورود'), findsNothing);
145 });
146
147 test('auth errors do not disclose an existing account', () {
148 expect(errorText(const ApiException(409, 'account_exists')),
149 'عملیات انجام نشد. دوباره تلاش کن.');
150 });
151
152 testWidgets('authenticated notification inbox is offered only in home drawer',
153 (tester) async {
154 await tester.pumpWidget(LifeMateApp(api: FakeApi()));
155 await tester.pumpAndSettle();
156 expect(find.text('اعلان‌های درون برنامه'), findsNothing);
157 await tester.pumpWidget(MaterialApp(home: HomeShell(api: FakeApi())));
158 await tester.pumpAndSettle();
159 tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
160 await tester.pumpAndSettle();
161 expect(find.text('اعلان‌های درون برنامه'), findsOneWidget);
162 });
163
164 testWidgets('home drawer opens durable pending changes screen',
165 (tester) async {
166 await tester.pumpWidget(MaterialApp(home: HomeShell(api: FakeApi())));
167 await tester.pumpAndSettle();
168 tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
169 await tester.pumpAndSettle();
170 await tester.scrollUntilVisible(find.text('تغییرهای معلق و تعارض‌ها'), 100,
171 scrollable: find
172 .descendant(
173 of: find.byType(Drawer), matching: find.byType(Scrollable))
174 .first);
175 await tester.pumpAndSettle();
176 await tester.tap(find.text('تغییرهای معلق و تعارض‌ها'));
177 await tester.pumpAndSettle();
178 expect(find.byType(SyncChangesPage), findsOneWidget);
179 expect(find.text('تغییر معلقی باقی نمانده است.'), findsOneWidget);
180 });
181
182 testWidgets('sensitive guide remains disabled in the online shell',
183 (tester) async {
184 await tester.pumpWidget(MaterialApp(home: HomeShell(api: FakeApi())));
185 await tester.pumpAndSettle();
186 tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
187 await tester.pumpAndSettle();
188 await tester.tap(find.text('همراه هوشمند'));
189 await tester.pumpAndSettle();
190 expect(find.byType(Phase4Hub), findsNothing);
191 expect(find.textContaining('در این مرحله فعال نیست'), findsOneWidget);
192 });
193
194 testWidgets('online planner offers homework without school setup',
195 (tester) async {
196 await tester.pumpWidget(MaterialApp(
197 home: Scaffold(body: PlannerPage(api: FakeApi())),
198 ));
199 await tester.pumpAndSettle();
200 await tester.tap(find.text('جدید'));
201 await tester.pumpAndSettle();
202 await tester.tap(find.byType(DropdownButtonFormField<String>).first);
203 await tester.pumpAndSettle();
204 expect(find.text('تکلیف'), findsOneWidget);
205 });
206 testWidgets('profile save failure is visible and dialog remains editable',
207 (tester) async {
208 await tester.pumpWidget(
209 MaterialApp(home: ProfileFamilyPage(api: _FailingProfileApi())));
210 await tester.pumpAndSettle();
211 await tester.tap(find.byIcon(Icons.edit_outlined));
212 await tester.pumpAndSettle();
213 await tester.tap(find.text('ذخیره'));
214 await tester.pumpAndSettle();
215 expect(tester.takeException(), isNull);
216 expect(find.textContaining('سرور پاسخ معتبر نداد'), findsOneWidget);
217 expect(find.byType(AlertDialog), findsOneWidget);
218 });
219 testWidgets(
220 'configured authenticated runtime opens home and settings uses child navigator',
221 (tester) async {
222 final session = _MemorySession();
223 final api = HttpIdentityApi(
224 baseUrl: 'https://synthetic.example.test/service',
225 sessionStore: session,
226 client: MockClient((req) async {
227 final value = req.url.path.endsWith('/me')
228 ? {
229 'user_id': 'child',
230 'display_name': 'فرزند',
231 'theme_preference': 'girl_pink'
232 }
233 : req.url.path.endsWith('/families')
234 ? {'families': []}
235 : {'items': []};
236 return http.Response(jsonEncode(value), 200,
237 headers: {'content-type': 'application/json'});
238 }))
239 ..accessToken = 'synthetic-token'
240 ..currentUserId = 'child';
241 final runtime = RuntimeController(sessionStore: session)
242 ..initialized = true
243 ..config = RuntimeConfig(apiBaseUrl: api.baseUrl)
244 ..api = api;
245 await tester.pumpWidget(LifeMateApp(runtime: runtime));
246 await tester.pumpAndSettle();
247 expect(find.byType(HomeShell), findsOneWidget);
248 expect(find.text('ورود'), findsNothing);
249 tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
250 await tester.pumpAndSettle();
251 await tester.tap(find.text('تنظیم اتصال'));
252 await tester.pumpAndSettle();
253 expect(tester.takeException(), isNull);
254 expect(find.text('اتصال لایف‌گاید'), findsOneWidget);
255 await runtime.signOut();
256 await tester.pumpAndSettle();
257 expect(find.text('ورود'), findsOneWidget);
258 expect(find.text('اتصال لایف‌گاید'), findsNothing);
259 await tester.pumpWidget(const SizedBox());
260 runtime.dispose();
261 });
262 testWidgets('server failure never presents cached planner as live',
263 (tester) async {
264 final api = _ServerFailureApi();
265 await OfflineStore.forApi(api).cachePlanner([
266 {'id': 'old', 'title': 'نسخه قدیمی', 'kind': 'task', 'status': 'planned'}
267 ]);
268 await tester
269 .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
270 await tester.pumpAndSettle();
271 expect(find.text('نسخه قدیمی'), findsNothing);
272 expect(find.textContaining('سرور پاسخ معتبر نداد'), findsOneWidget);
273 expect(find.textContaining('نسخه ذخیره‌شده'), findsNothing);
274 await tester.pumpWidget(const SizedBox());
275 });
276 testWidgets(
277 'homework sharing requires explicit family and sends planned time',
278 (tester) async {
279 final api = _PlannerWritesApi();
280 await tester
281 .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
282 await tester.pumpAndSettle();
283 await tester.tap(find.text('جدید'));
284 await tester.pumpAndSettle();
285 await tester.enterText(find.widgetWithText(TextField, 'عنوان'), 'ریاضی');
286 await tester.tap(find.byType(DropdownButtonFormField<String>).first);
287 await tester.pumpAndSettle();
288 await tester.tap(find.text('تکلیف').last);
289 await tester.pumpAndSettle();
290 await tester.ensureVisible(find.byType(SwitchListTile));
291 await tester.tap(find.byType(SwitchListTile));
292 await tester.pumpAndSettle();
293 await tester.tap(find.text('ذخیره'));
294 await tester.pumpAndSettle();
295 expect(find.textContaining('خانواده‌ای را'), findsOneWidget);
296 expect(api.mutations, isEmpty);
297 await tester
298 .ensureVisible(find.byType(DropdownButtonFormField<String>).last);
299 await tester.tap(find.byType(DropdownButtonFormField<String>).last);
300 await tester.pumpAndSettle();
301 await tester.tap(find.text('خانواده').last);
302 await tester.pumpAndSettle();
303 await tester.tap(find.text('ذخیره'));
304 await tester.pumpAndSettle();
305 final payload = api.mutations.single['payload'] as Map;
306 expect(payload['kind'], 'assignment');
307 expect(payload['familyId'], 'family-1');
308 expect(payload['visibility'], 'parent_guardian');
309 expect(payload['plannedDurationSeconds'], 1800);
310 await tester.pumpWidget(const SizedBox());
311 });
312 testWidgets(
313 'phone registration exposes actual unavailable SMS error without delivery claim',
314 (tester) async {
315 Map? payload;
316 final api = HttpIdentityApi(
317 baseUrl: 'https://synthetic.example.test',
318 client: MockClient((req) async {
319 payload = jsonDecode(req.body) as Map;
320 return http.Response('{"error":"sms_unavailable"}', 503,
321 headers: {'content-type': 'application/json'});
322 }));
323 await tester.pumpWidget(MaterialApp(home: RegistrationPage(api: api)));
324 await tester.pumpAndSettle();
325 await tester.tap(find.text('تلفن'));
326 await tester.pumpAndSettle();
327 await tester.enterText(find.widgetWithText(TextField, 'نام'), 'فرزند');
328 await tester.enterText(
329 find.widgetWithText(TextField, 'شماره تلفن'), '+989123456789');
330 await tester.enterText(
331 find.widgetWithText(TextField, 'رمز عبور'), 'synthetic-password');
332 await tester.enterText(
333 find.widgetWithText(TextField, 'تکرار رمز عبور'), 'synthetic-password');
334 await tester.tap(find.text('ثبت درخواست'));
335 await tester.pumpAndSettle();
336 expect(payload!['phone'], '+989123456789');
337 expect(payload!.containsKey('email'), isFalse);
338 expect(find.textContaining('سرویس پیامک فعال نیست'), findsOneWidget);
339 expect(find.textContaining('درخواست بررسی شد'), findsNothing);
340 await tester.pumpWidget(const SizedBox());
341 api.close();
342 });
343 testWidgets('profile category controls shell without granting family role',
344 (tester) async {
345 await tester.pumpWidget(MaterialApp(
346 home: HomeShell(api: _CategoryApi('adult', role: 'teen_minor'))));
347 await tester.pumpAndSettle();
348 expect(find.text('برنامه‌ریز'), findsOneWidget);
349 await tester.pumpWidget(const SizedBox());
350 });
351 testWidgets(
352 'offline homework can be edited while its create awaits acknowledgement',
353 (tester) async {
354 final api = _OfflinePlannerApi();
355 await tester
356 .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
357 await tester.pumpAndSettle();
358 await tester.tap(find.text('جدید'));
359 await tester.pumpAndSettle();
360 await tester.enterText(find.widgetWithText(TextField, 'عنوان'), 'ریاضی');
361 await tester.tap(find.text('ذخیره'));
362 await tester.pumpAndSettle();
363 await tester.tap(find.byType(PopupMenuButton<String>));
364 await tester.pumpAndSettle();
365 await tester.tap(find.text('ویرایش'));
366 await tester.pumpAndSettle();
367 await tester.enterText(
368 find.widgetWithText(TextField, 'عنوان'), 'ریاضی جدید');
369 await tester.tap(find.text('ذخیره'));
370 await tester.pumpAndSettle();
371 expect(find.byType(AlertDialog), findsNothing);
372 expect(find.text('ریاضی جدید'), findsOneWidget);
373 expect(await OfflineStore.forApi(api).pendingCount(), 2);
374 await tester.pumpWidget(const SizedBox());
375 });
376 testWidgets(
377 'email ownership verification requires explicit new password submission',
378 (tester) async {
379 Map? submitted;
380 final api = HttpIdentityApi(
381 baseUrl: 'https://synthetic.example.test',
382 client: MockClient((req) async {
383 submitted = jsonDecode(req.body) as Map;
384 return http.Response('{}', 200,
385 headers: {'content-type': 'application/json'});
386 }));
387 await tester.pumpWidget(
388 MaterialApp(home: VerifyEmailPage(api: api, token: 'synthetic-proof')));
389 await tester.pumpAndSettle();
390 expect(submitted, isNull);
391 await tester.enterText(
392 find.widgetWithText(TextField, 'رمز عبور جدید'), 'synthetic-password');
393 await tester.enterText(
394 find.widgetWithText(TextField, 'تکرار رمز عبور'), 'synthetic-password');
395 await tester.tap(find.text('تأیید و تعیین رمز عبور'));
396 await tester.pumpAndSettle();
397 expect(submitted,
398 {'token': 'synthetic-proof', 'newPassword': 'synthetic-password'});
399 expect(find.text('ایمیل تأیید شد'), findsOneWidget);
400 await tester.pumpWidget(const SizedBox());
401 api.close();
402 });
403 testWidgets('editing a private task can explicitly change guardian sharing',
404 (tester) async {
405 final api = _PlannerWritesApi();
406 await tester.pumpWidget(MaterialApp(
407 home: Scaffold(
408 body: Builder(
409 builder: (context) => TextButton(
410 onPressed: () => showDialog(
411 context: context,
412 builder: (_) => PlanItemDialog(api: api, item: {
413 'id': 'saved-plan',
414 'title': 'ریاضی',
415 'kind': 'assignment',
416 'status': 'planned',
417 'visibility': 'private',
418 'version': 1
419 })),
420 child: const Text('باز کردن'))))));
421 await tester.tap(find.text('باز کردن'));
422 await tester.pumpAndSettle();
423 await tester.ensureVisible(find.byType(SwitchListTile));
424 await tester.tap(find.byType(SwitchListTile));
425 await tester.pumpAndSettle();
426 await tester
427 .ensureVisible(find.byType(DropdownButtonFormField<String>).last);
428 await tester.tap(find.byType(DropdownButtonFormField<String>).last);
429 await tester.pumpAndSettle();
430 await tester.tap(find.text('خانواده').last);
431 await tester.pumpAndSettle();
432 await tester.tap(find.text('ذخیره'));
433 await tester.pumpAndSettle();
434 expect((api.mutations.single['payload'] as Map)['visibility'],
435 'parent_guardian');
436 expect(find.byType(AlertDialog), findsNothing);
437 await tester.pumpWidget(const SizedBox());
438 });
439 testWidgets('profile category routing does not depend on family availability',
440 (tester) async {
441 await tester.pumpWidget(
442 MaterialApp(home: HomeShell(api: _CategoryWithoutFamiliesApi())));
443 await tester.pumpAndSettle();
444 expect(find.text('برنامه‌ریز'), findsOneWidget);
445 await tester.pumpWidget(const SizedBox());
446 });
447 testWidgets(
448 'logout warns before discarding an unsent change and cancel preserves identity',
449 (tester) async {
450 final session = _MemorySession();
451 final api = HttpIdentityApi(
452 baseUrl: 'https://synthetic.example.test',
453 sessionStore: session,
454 client: MockClient((req) async => http.Response(
455 jsonEncode(req.url.path.endsWith('/profile')
456 ? {
457 'profile_category': 'adult',
458 'theme_preference': 'adult_blue'
459 }
460 : req.url.path.endsWith('/families')
461 ? {'families': []}
462 : {'items': []}),
463 200,
464 headers: {'content-type': 'application/json'})))
465 ..accessToken = 'synthetic-token'
466 ..currentUserId = 'child';
467 final runtime = RuntimeController(sessionStore: session)
468 ..initialized = true
469 ..config = RuntimeConfig(apiBaseUrl: api.baseUrl)
470 ..api = api;
471 await OfflineStore.forApi(api).enqueue({
472 'id': '9f7b762c-905f-48a1-81b3-ded3ed72d3c0',
473 'entityId': '3a940940-f482-4b5a-937a-d74cc9ef9daf',
474 'entityType': 'plan_item',
475 'operation': 'create',
476 'expectedVersion': 0,
477 'payload': {'kind': 'task', 'title': 'معلق'}
478 });
479 await tester.pumpWidget(LifeMateApp(runtime: runtime));
480 await tester.pumpAndSettle();
481 tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
482 await tester.pumpAndSettle();
483 await tester.scrollUntilVisible(find.text('خروج از حساب'), 100,
484 scrollable: find
485 .descendant(
486 of: find.byType(Drawer), matching: find.byType(Scrollable))
487 .first);
488 await tester.pumpAndSettle();
489 await tester.tap(find.text('خروج از حساب'));
490 await tester.pumpAndSettle();
491 expect(find.textContaining('تغییر معلق'), findsOneWidget);
492 expect(api.accessToken, isNotNull);
493 await tester.tap(find.text('انصراف'));
494 await tester.pumpAndSettle();
495 expect(api.accessToken, isNotNull);
496 expect(await OfflineStore.forApi(api).pendingCount(), 1);
497 await tester.pumpWidget(const SizedBox());
498 runtime.dispose();
499 });
500 testWidgets(
501 'endpoint save warns before discard and cancel preserves endpoint and queue',
502 (tester) async {
503 final session = _MemorySession();
504 final api = HttpIdentityApi(
505 baseUrl: 'https://synthetic.example.test',
506 sessionStore: session,
507 client: MockClient((req) async => http.Response(
508 jsonEncode(req.url.path.endsWith('/profile')
509 ? {
510 'profile_category': 'adult',
511 'theme_preference': 'adult_blue'
512 }
513 : req.url.path.endsWith('/families')
514 ? {'families': []}
515 : {'items': []}),
516 200,
517 headers: {'content-type': 'application/json'})))
518 ..accessToken = 'synthetic-token'
519 ..currentUserId = 'child';
520 final runtime = RuntimeController(sessionStore: session)
521 ..initialized = true
522 ..config = RuntimeConfig(apiBaseUrl: api.baseUrl)
523 ..api = api;
524 await OfflineStore.forApi(api).enqueue({
525 'id': '9f7b762c-905f-48a1-81b3-ded3ed72d3c0',
526 'entityId': '3a940940-f482-4b5a-937a-d74cc9ef9daf',
527 'entityType': 'plan_item',
528 'operation': 'create',
529 'expectedVersion': 0,
530 'payload': {'kind': 'task', 'title': 'معلق'}
531 });
532 await tester.pumpWidget(LifeMateApp(runtime: runtime));
533 await tester.pumpAndSettle();
534 tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
535 await tester.pumpAndSettle();
536 await tester.tap(find.text('تنظیم اتصال'));
537 await tester.pumpAndSettle();
538 await tester.enterText(find.widgetWithText(TextField, 'نشانی اتصال API'),
539 'https://other.synthetic.example.test');
540 await tester.ensureVisible(find.text('ذخیره و ادامه'));
541 await tester.pumpAndSettle();
542 await tester.tap(find.text('ذخیره و ادامه'));
543 await tester.pumpAndSettle();
544 expect(find.textContaining('تغییر معلق'), findsOneWidget);
545 await tester.tap(find.text('انصراف'));
546 await tester.pumpAndSettle();
547 expect(runtime.config.apiBaseUrl, 'https://synthetic.example.test');
548 expect(api.accessToken, isNotNull);
549 expect(await OfflineStore.forApi(api).pendingCount(), 1);
550 await tester.pumpWidget(const SizedBox());
551 runtime.dispose();
552 });
553 testWidgets(
554 'offline planner fallback shows owned rows and hides shared child rows',
555 (tester) async {
556 final api = HttpIdentityApi(
557 baseUrl: 'https://synthetic.example.test',
558 client: MockClient((_) async =>
559 throw http.ClientException('synthetic transport failure')))
560 ..accessToken = 'synthetic-token'
561 ..currentUserId = 'parent';
562 await OfflineStore.forApi(api).cachePlanner([
563 {
564 'id': 'own',
565 'owner_user_id': 'parent',
566 'title': 'کار خودم',
567 'kind': 'task',
568 'status': 'planned'
569 },
570 {
571 'id': 'shared-child',
572 'owner_user_id': 'child',
573 'title': 'داده فرزند',
574 'kind': 'assignment',
575 'status': 'planned'
576 }
577 ]);
578 await tester
579 .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
580 await tester.pumpAndSettle();
581 expect(find.text('کار خودم'), findsOneWidget);
582 expect(find.text('داده فرزند'), findsNothing);
583 expect(find.textContaining('داده زنده نیست'), findsOneWidget);
584 await tester.pumpWidget(const SizedBox());
585 api.close();
586 });
587 testWidgets(
588 'offline owned pending create remains visible without a server owner field',
589 (tester) async {
590 final api = HttpIdentityApi(
591 baseUrl: 'https://synthetic.example.test',
592 client: MockClient((_) async =>
593 throw http.ClientException('synthetic transport failure')))
594 ..accessToken = 'synthetic-token'
595 ..currentUserId = 'child';
596 await PlanSync(api).create(
597 {'kind': 'assignment', 'title': 'تکلیف خودم', 'visibility': 'private'});
598 await tester
599 .pumpWidget(MaterialApp(home: Scaffold(body: PlannerPage(api: api))));
600 await tester.pumpAndSettle();
601 expect(find.text('تکلیف خودم'), findsOneWidget);
602 expect(find.textContaining('در انتظار تأیید سرور'), findsWidgets);
603 await tester.pumpWidget(const SizedBox());
604 api.close();
605 });
606 testWidgets(
607 'owner exam grade edit sends normalized points and current version',
608 (tester) async {
609 final api = _PlannerWritesApi();
610 await tester.pumpWidget(MaterialApp(
611 home: Scaffold(
612 body: Builder(
613 builder: (context) => TextButton(
614 onPressed: () => showDialog(
615 context: context,
616 builder: (_) => PlanItemDialog(api: api, item: {
617 'id': 'saved-exam',
618 'title': 'امتحان ریاضی',
619 'kind': 'exam',
620 'status': 'planned',
621 'visibility': 'private',
622 'version': 4
623 })),
624 child: const Text('باز کردن'))))));
625 await tester.tap(find.text('باز کردن'));
626 await tester.pumpAndSettle();
627 await tester
628 .ensureVisible(find.widgetWithText(TextField, 'نمره (اختیاری)'));
629 await tester.enterText(
630 find.widgetWithText(TextField, 'نمره (اختیاری)'), '۱۵٫۵');
631 await tester
632 .ensureVisible(find.widgetWithText(TextField, 'سقف نمره (اختیاری)'));
633 await tester.enterText(
634 find.widgetWithText(TextField, 'سقف نمره (اختیاری)'), '۲۰');
635 await tester.tap(find.text('ذخیره'));
636 await tester.pumpAndSettle();
637 expect(api.mutations.single['expectedVersion'], 4);
638 expect((api.mutations.single['payload'] as Map)['gradePoints'], 15.5);
639 expect((api.mutations.single['payload'] as Map)['gradeOutOf'], 20);
640 expect(find.byType(AlertDialog), findsNothing);
641 await tester.pumpWidget(const SizedBox());
642 });
643 }