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 185 lines 7.71 KB
Raw
1 import 'package:flutter/services.dart';
2 import 'package:flutter/material.dart';
3 import 'package:flutter_test/flutter_test.dart';
4 import 'package:http/http.dart' as http;
5 import 'package:http/testing.dart';
6 import 'package:lifemate/api.dart';
7 import 'package:lifemate/offline_store.dart';
8 import 'package:lifemate/sync_changes_ui.dart';
9 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
10 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
11
12 class _ConflictApi extends HttpIdentityApi {
13 _ConflictApi({this.denied = false})
14 : super(
15 baseUrl: 'https://conflict.example.test',
16 client: MockClient((_) async => http.Response('', 503))) {
17 accessToken = 'synthetic-token';
18 currentUserId = denied ? 'denied-user' : 'test-owner';
19 }
20 final bool denied;
21 int reads = 0;
22 @override
23 Future<Map<String, dynamic>> requestJson(String method, String path,
24 {Map<String, dynamic>? body, bool auth = true}) async {
25 reads++;
26 if (denied) throw const ApiException(403, 'forbidden');
27 return {
28 'id': path.split('/').last,
29 'title': 'Server current',
30 'version': 7
31 };
32 }
33 }
34
35 void main() {
36 TestWidgetsFlutterBinding.ensureInitialized();
37 setUp(() {
38 SharedPreferencesAsyncPlatform.instance =
39 InMemorySharedPreferencesAsync.withData({});
40 String? pending;
41 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
42 .setMockMethodCallHandler(
43 const MethodChannel('lifeguide/local_write_guard'), (call) async {
44 if (call.method == 'getBlocked') return pending != null;
45 if (call.method == 'beginWrite') return pending = 'test-owned';
46 if (call.method == 'completeWrite' && call.arguments == pending) {
47 pending = null;
48 return true;
49 }
50 throw PlatformException(code: 'local_storage_restart_required');
51 });
52 });
53
54 Map<String, dynamic> mutation(int id, String entity,
55 {String operation = 'update'}) =>
56 {
57 'id': '00000000-0000-4000-8000-${id.toString().padLeft(12, '0')}',
58 'entityType': 'plan_item',
59 'entityId': entity,
60 'operation': operation,
61 'expectedVersion': id,
62 'payload': {'title': 'Local $id', 'notes': 'Private draft $id'}
63 };
64
65 test(
66 'explicit discard journals the complete entity chain and preserves unrelated changes',
67 () async {
68 final store = OfflineStore.forNamespace('discard|owner');
69 const target = '00000000-0000-4000-8000-000000000100';
70 const other = '00000000-0000-4000-8000-000000000200';
71 final first = mutation(1, target),
72 dependent = mutation(2, target),
73 unrelated = mutation(3, other);
74 await store.enqueue(first,
75 optimisticItem: {'id': target, 'title': 'Local first', 'version': 2});
76 await store.markQueued(first['id'] as String, 'conflict');
77 await store.enqueue(dependent,
78 optimisticItem: {'id': target, 'title': 'Local latest', 'version': 3});
79 await store.enqueue(unrelated,
80 optimisticItem: {'id': other, 'title': 'Unrelated', 'version': 4});
81 await store.cacheToday([
82 {'id': target, 'title': 'Server old', 'version': 1}
83 ]);
84 final canonical = {'id': target, 'title': 'Server current', 'version': 9};
85 await store.discardEntityChanges(target, serverItem: canonical);
86 expect((await store.readQueue()).map((m) => m['id']), [unrelated['id']]);
87 final reopened = OfflineStore.forNamespace(store.scope);
88 final journal = await reopened.readDiscardedChanges();
89 expect(journal, hasLength(2));
90 expect(journal.map((m) => m['id']), [first['id'], dependent['id']]);
91 expect(journal.first['payload'], first['payload']);
92 expect(journal.last['payload'], dependent['payload']);
93 expect(
94 journal.every(
95 (m) => DateTime.tryParse(m['discardedAt'] as String) != null),
96 isTrue);
97 expect((await reopened.readPlanner()).firstWhere((m) => m['id'] == target),
98 canonical);
99 expect((await reopened.readToday()).single, canonical);
100 expect(await reopened.readLastAck(), isNull);
101 });
102
103 test(
104 'discarding an unsent creation removes its optimistic item and retains recovery payload',
105 () async {
106 final store = OfflineStore.forNamespace('discard-new|owner');
107 const id = '00000000-0000-4000-8000-000000000100';
108 final create = mutation(1, id, operation: 'create');
109 await store.enqueue(create,
110 optimisticItem: {'id': id, 'title': 'Never sent', 'version': 1});
111 await store.discardEntityChanges(id);
112 expect(await store.readQueue(), isEmpty);
113 expect(await store.readPlanner(), isEmpty);
114 expect((await store.readDiscardedChanges()).single['payload'],
115 create['payload']);
116 expect(await store.readLastAck(), isNull);
117 });
118
119 test(
120 'a mismatched server entity cannot discard the queue or create a journal',
121 () async {
122 final store = OfflineStore.forNamespace('discard-invalid|owner');
123 const id = '00000000-0000-4000-8000-000000000100';
124 await store.enqueue(mutation(1, id));
125 await expectLater(
126 store.discardEntityChanges(id,
127 serverItem: {'id': 'other', 'version': 1}),
128 throwsA(isA<Exception>()));
129 expect(await store.readQueue(), hasLength(1));
130 expect(await store.readDiscardedChanges(), isEmpty);
131 });
132
133 testWidgets(
134 'conflict dialog preserves local changes until explicit use-server choice',
135 (tester) async {
136 final api = _ConflictApi();
137 final store = OfflineStore.forApi(api);
138 const id = '00000000-0000-4000-8000-000000000100';
139 final pending = mutation(1, id);
140 await store.enqueue(pending);
141 await store.markQueued(pending['id'] as String, 'conflict');
142 await tester.pumpWidget(MaterialApp(home: SyncChangesPage(api: api)));
143 await tester.pumpAndSettle();
144 await tester.tap(find.text('بررسی و انتخاب'));
145 await tester.pumpAndSettle();
146 expect(find.text('نسخه سرور 7: Server current'), findsOneWidget);
147 expect(await store.readQueue(), hasLength(1));
148 await tester.tap(find.text('نگه‌داشتن تغییر محلی'));
149 await tester.pumpAndSettle();
150 expect(await store.readDiscardedChanges(), isEmpty);
151 await tester.tap(find.text('بررسی و انتخاب'));
152 await tester.pumpAndSettle();
153 await tester.tap(find.text('استفاده از نسخه سرور'));
154 await tester.pumpAndSettle();
155 expect(await store.readQueue(), isEmpty);
156 expect((await store.readDiscardedChanges()).single['payload'],
157 pending['payload']);
158 expect((await store.readPlanner()).single['version'], 7);
159 expect(find.text('Private draft 1'), findsNothing);
160 expect(await store.readLastAck(), isNull);
161 });
162
163 testWidgets(
164 '403 shows no comparison or cached title and retains every pending payload',
165 (tester) async {
166 final api = _ConflictApi(denied: true);
167 final store = OfflineStore.forApi(api);
168 const id = '00000000-0000-4000-8000-000000000100';
169 final pending = mutation(1, id);
170 await store.enqueue(pending,
171 optimisticItem: {'id': id, 'title': 'Cached forbidden title'});
172 await store.markQueued(pending['id'] as String, 'conflict');
173 await tester.pumpWidget(MaterialApp(home: SyncChangesPage(api: api)));
174 await tester.pumpAndSettle();
175 await tester.tap(find.text('بررسی و انتخاب'));
176 await tester.pumpAndSettle();
177 expect(
178 find.text('برای این اطلاعات یا عملیات دسترسی نداری.'), findsOneWidget);
179 expect(find.byType(AlertDialog), findsNothing);
180 expect(find.text('Cached forbidden title'), findsNothing);
181 expect(find.text('Local 1'), findsNothing);
182 expect(await store.readQueue(), hasLength(1));
183 expect(await store.readDiscardedChanges(), isEmpty);
184 });
185 }