LifeMate — Personal, Family & Learning Companion

fix/local-task-persistence
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 184 lines 6.45 KB
Raw
1 import 'api.dart';
2 import 'local_data_store.dart';
3
4 /// Real device storage, without login, networking, family sharing or server sync.
5 /// The authenticated application continues to use HttpIdentityApi exclusively.
6 class LocalOnlyApi implements IdentityApi {
7 LocalOnlyApi(
8 {required String category,
9 required String displayName,
10 LocalDataStore? store})
11 : store = store ??
12 LocalDataStore(category: category, displayName: displayName);
13
14 final LocalDataStore store;
15
16 @override
17 String? get accessToken => null;
18
19 @override
20 Future<Map<String, dynamic>> getProfile() async =>
21 Map<String, dynamic>.from((await store.read())['profile'] as Map);
22
23 @override
24 Future<Map<String, dynamic>> updateProfile({
25 String? displayName,
26 String? birthDate,
27 String? themePreference,
28 }) async {
29 if (birthDate != null ||
30 (displayName != null &&
31 (displayName.trim().isEmpty || displayName.trim().length > 120)) ||
32 (themePreference != null &&
33 !LocalDataStore.themes.contains(themePreference))) {
34 throw const ApiException(400, 'local_invalid_profile');
35 }
36 return store.mutate((data) {
37 final profile = data['profile'] as Map<String, dynamic>;
38 if (displayName != null) profile['display_name'] = displayName.trim();
39 if (themePreference != null) {
40 profile['theme_preference'] = themePreference;
41 }
42 return Map<String, dynamic>.from(profile);
43 });
44 }
45
46 @override
47 Future<List<Map<String, dynamic>>> listFamilies() async => [];
48
49 Map<String, dynamic> _fields(Map<String, dynamic> input) {
50 const allowed = {
51 'kind',
52 'title',
53 'notes',
54 'status',
55 'priority',
56 'startsAt',
57 'dueAt',
58 'visibility'
59 };
60 if (input.isEmpty ||
61 input.keys.any((key) => !allowed.contains(key)) ||
62 (input.containsKey('title') &&
63 (input['title'] is! String ||
64 (input['title'] as String).trim().isEmpty ||
65 (input['title'] as String).trim().length > 240)) ||
66 (input.containsKey('kind') &&
67 !LocalDataStore.kinds.contains(input['kind'])) ||
68 (input.containsKey('status') &&
69 !LocalDataStore.statuses.contains(input['status'])) ||
70 (input.containsKey('priority') &&
71 !{'low', 'normal', 'high', 'urgent'}.contains(input['priority'])) ||
72 (input.containsKey('visibility') && input['visibility'] != 'private') ||
73 (input['notes'] != null &&
74 (input['notes'] is! String ||
75 (input['notes'] as String).length > 10000))) {
76 throw const ApiException(400, 'local_invalid_item');
77 }
78 final fields = <String, dynamic>{};
79 for (final entry in input.entries) {
80 if (entry.key == 'startsAt' || entry.key == 'dueAt') {
81 final value = entry.value;
82 if (value != null && value is! String) {
83 throw const ApiException(400, 'local_invalid_item');
84 }
85 final date = value == null ? null : DateTime.tryParse(value as String);
86 if (value != null && date == null) {
87 throw const ApiException(400, 'local_invalid_item');
88 }
89 fields[entry.key == 'startsAt' ? 'starts_at' : 'due_at'] =
90 date?.toUtc().toIso8601String();
91 } else {
92 fields[entry.key] =
93 entry.key == 'title' ? (entry.value as String).trim() : entry.value;
94 }
95 }
96 return fields;
97 }
98
99 void _validateDates(Map<String, dynamic> item) {
100 final start = DateTime.tryParse(item['starts_at']?.toString() ?? '');
101 final due = DateTime.tryParse(item['due_at']?.toString() ?? '');
102 if (start != null && due != null && due.isBefore(start)) {
103 throw const ApiException(400, 'local_invalid_item');
104 }
105 }
106
107 @override
108 Future<Map<String, dynamic>> createPlanItem(
109 Map<String, dynamic> input) async {
110 final fields = _fields(input);
111 if (!fields.containsKey('title') || !fields.containsKey('kind')) {
112 throw const ApiException(400, 'local_invalid_item');
113 }
114 _validateDates(fields);
115 return store.mutate((data) {
116 final now = DateTime.now().toUtc().toIso8601String();
117 final item = <String, dynamic>{
118 'id': LocalDataStore.newId(),
119 'owner_user_id': (data['profile'] as Map)['user_id'],
120 'status': 'planned',
121 'priority': 'normal',
122 'visibility': 'private',
123 'created_at': now,
124 'updated_at': now,
125 ...fields,
126 };
127 (data['items'] as List).add(item);
128 return Map<String, dynamic>.from(item);
129 });
130 }
131
132 @override
133 Future<Map<String, dynamic>> updatePlanItem(
134 String itemId, Map<String, dynamic> input) async {
135 final fields = _fields(input);
136 return store.mutate((data) {
137 final items = data['items'] as List;
138 final index = items.indexWhere((item) => (item as Map)['id'] == itemId);
139 if (index < 0) throw const ApiException(404, 'local_item_not_found');
140 final item = <String, dynamic>{
141 ...Map<String, dynamic>.from(items[index] as Map),
142 ...fields
143 };
144 _validateDates(item);
145 item['updated_at'] = DateTime.now().toUtc().toIso8601String();
146 items[index] = item;
147 return Map<String, dynamic>.from(item);
148 });
149 }
150
151 @override
152 Future<List<Map<String, dynamic>>> listPlanItems(
153 {DateTime? from, DateTime? to, String? kind}) async {
154 final data = await store.read();
155 final items = (data['items'] as List)
156 .map((item) => Map<String, dynamic>.from(item as Map));
157 return items.where((item) {
158 if (item['status'] == 'cancelled' ||
159 (kind != null && kind != item['kind'])) {
160 return false;
161 }
162 final date = DateTime.tryParse(
163 (item['starts_at'] ?? item['due_at'])?.toString() ?? '');
164 // Undated records remain visible in the planner; dates use [from, to).
165 if (date == null) return true;
166 return (from == null || !date.isBefore(from)) &&
167 (to == null || date.isBefore(to));
168 }).toList();
169 }
170
171 @override
172 Future<List<Map<String, dynamic>>> getToday(
173 {required DateTime from, required DateTime to}) async =>
174 (await listPlanItems(from: from, to: to))
175 .where((item) =>
176 item['status'] != 'completed' &&
177 (item['due_at'] != null || item['starts_at'] != null))
178 .toList();
179
180 // Unsupported flows fail visibly instead of manufacturing successful records.
181 @override
182 dynamic noSuchMethod(Invocation invocation) =>
183 throw const ApiException(409, 'local_feature_unavailable');
184 }