LifeMate — Personal, Family & Learning Companion

docs/owner-guide-and-delivery-plan
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 223 lines 9.16 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 if (path.contains('/planner-series/')) {
28 return {
29 'series': {
30 'id': path.split('/').last,
31 'owner_user_id': currentUserId,
32 'title': 'Server recurring',
33 'version': 2,
34 }
35 };
36 }
37 return {
38 'id': path.split('/').last,
39 'title': 'Server current',
40 'version': 7
41 };
42 }
43 }
44
45 void main() {
46 TestWidgetsFlutterBinding.ensureInitialized();
47 setUp(() {
48 SharedPreferencesAsyncPlatform.instance =
49 InMemorySharedPreferencesAsync.withData({});
50 String? pending;
51 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
52 .setMockMethodCallHandler(
53 const MethodChannel('lifeguide/local_write_guard'), (call) async {
54 if (call.method == 'getBlocked') return pending != null;
55 if (call.method == 'beginWrite') return pending = 'test-owned';
56 if (call.method == 'completeWrite' && call.arguments == pending) {
57 pending = null;
58 return true;
59 }
60 throw PlatformException(code: 'local_storage_restart_required');
61 });
62 });
63
64 Map<String, dynamic> mutation(int id, String entity,
65 {String operation = 'update'}) =>
66 {
67 'id': '00000000-0000-4000-8000-${id.toString().padLeft(12, '0')}',
68 'entityType': 'plan_item',
69 'entityId': entity,
70 'operation': operation,
71 'expectedVersion': id,
72 'payload': {'title': 'Local $id', 'notes': 'Private draft $id'}
73 };
74
75 test(
76 'explicit discard journals the complete entity chain and preserves unrelated changes',
77 () async {
78 final store = OfflineStore.forNamespace('discard|owner');
79 const target = '00000000-0000-4000-8000-000000000100';
80 const other = '00000000-0000-4000-8000-000000000200';
81 final first = mutation(1, target),
82 dependent = mutation(2, target),
83 unrelated = mutation(3, other);
84 await store.enqueue(first,
85 optimisticItem: {'id': target, 'title': 'Local first', 'version': 2});
86 await store.markQueued(first['id'] as String, 'conflict');
87 await store.enqueue(dependent,
88 optimisticItem: {'id': target, 'title': 'Local latest', 'version': 3});
89 await store.enqueue(unrelated,
90 optimisticItem: {'id': other, 'title': 'Unrelated', 'version': 4});
91 await store.cacheToday([
92 {'id': target, 'title': 'Server old', 'version': 1}
93 ]);
94 final canonical = {'id': target, 'title': 'Server current', 'version': 9};
95 await store.discardEntityChanges(target, serverItem: canonical);
96 expect((await store.readQueue()).map((m) => m['id']), [unrelated['id']]);
97 final reopened = OfflineStore.forNamespace(store.scope);
98 final journal = await reopened.readDiscardedChanges();
99 expect(journal, hasLength(2));
100 expect(journal.map((m) => m['id']), [first['id'], dependent['id']]);
101 expect(journal.first['payload'], first['payload']);
102 expect(journal.last['payload'], dependent['payload']);
103 expect(
104 journal.every(
105 (m) => DateTime.tryParse(m['discardedAt'] as String) != null),
106 isTrue);
107 expect((await reopened.readPlanner()).firstWhere((m) => m['id'] == target),
108 canonical);
109 expect((await reopened.readToday()).single, canonical);
110 expect(await reopened.readLastAck(), isNull);
111 });
112
113 test(
114 'discarding an unsent creation removes its optimistic item and retains recovery payload',
115 () async {
116 final store = OfflineStore.forNamespace('discard-new|owner');
117 const id = '00000000-0000-4000-8000-000000000100';
118 final create = mutation(1, id, operation: 'create');
119 await store.enqueue(create,
120 optimisticItem: {'id': id, 'title': 'Never sent', 'version': 1});
121 await store.discardEntityChanges(id);
122 expect(await store.readQueue(), isEmpty);
123 expect(await store.readPlanner(), isEmpty);
124 expect((await store.readDiscardedChanges()).single['payload'],
125 create['payload']);
126 expect(await store.readLastAck(), isNull);
127 });
128
129 test(
130 'a mismatched server entity cannot discard the queue or create a journal',
131 () async {
132 final store = OfflineStore.forNamespace('discard-invalid|owner');
133 const id = '00000000-0000-4000-8000-000000000100';
134 await store.enqueue(mutation(1, id));
135 await expectLater(
136 store.discardEntityChanges(id,
137 serverItem: {'id': 'other', 'version': 1}),
138 throwsA(isA<Exception>()));
139 expect(await store.readQueue(), hasLength(1));
140 expect(await store.readDiscardedChanges(), isEmpty);
141 });
142
143 testWidgets(
144 'rejected series can leave queue only after explicit recoverable choice',
145 (tester) async {
146 final api = _ConflictApi();
147 final store = OfflineStore.forApi(api);
148 const id = '00000000-0000-4000-8000-000000000100';
149 final draft = {
150 ...mutation(1, id, operation: 'create'),
151 'entityType': 'planner_series'
152 };
153 await store.enqueue(draft);
154 await store.markQueued(draft['id'] as String, 'rejected');
155 await tester.pumpWidget(MaterialApp(home: SyncChangesPage(api: api)));
156 await tester.pumpAndSettle();
157 await tester.tap(find.text('بررسی و انتخاب'));
158 await tester.pumpAndSettle();
159 expect(find.text('نسخه سرور 2: Server recurring'), findsOneWidget);
160 expect(await store.readQueue(), hasLength(1));
161 await tester.tap(find.text('استفاده از نسخه سرور'));
162 await tester.pumpAndSettle();
163 expect(await store.readQueue(), isEmpty);
164 expect((await store.readDiscardedChanges()).single['payload'],
165 draft['payload']);
166 expect((await store.readList('planner_series')).single['title'],
167 'Server recurring');
168 expect(await store.readPlanner(), isEmpty);
169 await tester.pumpWidget(const SizedBox());
170 });
171 testWidgets(
172 'conflict dialog preserves local changes until explicit use-server choice',
173 (tester) async {
174 final api = _ConflictApi();
175 final store = OfflineStore.forApi(api);
176 const id = '00000000-0000-4000-8000-000000000100';
177 final pending = mutation(1, id);
178 await store.enqueue(pending);
179 await store.markQueued(pending['id'] as String, 'conflict');
180 await tester.pumpWidget(MaterialApp(home: SyncChangesPage(api: api)));
181 await tester.pumpAndSettle();
182 await tester.tap(find.text('بررسی و انتخاب'));
183 await tester.pumpAndSettle();
184 expect(find.text('نسخه سرور 7: Server current'), findsOneWidget);
185 expect(await store.readQueue(), hasLength(1));
186 await tester.tap(find.text('نگه‌داشتن تغییر محلی'));
187 await tester.pumpAndSettle();
188 expect(await store.readDiscardedChanges(), isEmpty);
189 await tester.tap(find.text('بررسی و انتخاب'));
190 await tester.pumpAndSettle();
191 await tester.tap(find.text('استفاده از نسخه سرور'));
192 await tester.pumpAndSettle();
193 expect(await store.readQueue(), isEmpty);
194 expect((await store.readDiscardedChanges()).single['payload'],
195 pending['payload']);
196 expect((await store.readPlanner()).single['version'], 7);
197 expect(find.text('Private draft 1'), findsNothing);
198 expect(await store.readLastAck(), isNull);
199 });
200
201 testWidgets(
202 '403 shows no comparison or cached title and retains every pending payload',
203 (tester) async {
204 final api = _ConflictApi(denied: true);
205 final store = OfflineStore.forApi(api);
206 const id = '00000000-0000-4000-8000-000000000100';
207 final pending = mutation(1, id);
208 await store.enqueue(pending,
209 optimisticItem: {'id': id, 'title': 'Cached forbidden title'});
210 await store.markQueued(pending['id'] as String, 'conflict');
211 await tester.pumpWidget(MaterialApp(home: SyncChangesPage(api: api)));
212 await tester.pumpAndSettle();
213 await tester.tap(find.text('بررسی و انتخاب'));
214 await tester.pumpAndSettle();
215 expect(
216 find.text('برای این اطلاعات یا عملیات دسترسی نداری.'), findsOneWidget);
217 expect(find.byType(AlertDialog), findsNothing);
218 expect(find.text('Cached forbidden title'), findsNothing);
219 expect(find.text('Local 1'), findsNothing);
220 expect(await store.readQueue(), hasLength(1));
221 expect(await store.readDiscardedChanges(), isEmpty);
222 });
223 }