LifeMate — Personal, Family & Learning Companion

fix/personal-notification-controls
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 464 lines 19.1 KB
Raw
1 import 'dart:math';
2
3 import 'package:path/path.dart' as paths;
4 import 'package:sqflite/sqflite.dart';
5
6 import 'model.dart';
7
8 /// Authoritative private storage for the device-only edition. Opening or writing
9 /// a database failure is surfaced to the caller; no empty fallback replaces it.
10 class StandaloneStore {
11 StandaloneStore._(this._database);
12 final Database _database;
13 static const schemaVersion = 1;
14 static const databaseName = 'lifeguide_standalone_v1.sqlite';
15
16 static Future<StandaloneStore> open(
17 {String? path, DatabaseFactory? factory}) async {
18 final driver = factory ?? databaseFactory;
19 final resolved =
20 path ?? paths.join(await driver.getDatabasesPath(), databaseName);
21 final database = await driver.openDatabase(resolved,
22 options: OpenDatabaseOptions(
23 version: schemaVersion,
24 onConfigure: (db) => db.execute('PRAGMA foreign_keys = ON'),
25 onCreate: (db, version) => _migrate(db, 0, version),
26 onUpgrade: _migrate,
27 onDowngrade: (db, oldVersion, newVersion) async {
28 throw StateError(
29 'The local database requires a newer app version.');
30 },
31 onOpen: (db) async {
32 final check = await db.rawQuery('PRAGMA quick_check');
33 if (check.length != 1 || check.single.values.single != 'ok') {
34 throw StateError('The local database integrity check failed.');
35 }
36 },
37 ));
38 return StandaloneStore._(database);
39 }
40
41 static Future<void> _migrate(
42 Database db, int oldVersion, int newVersion) async {
43 // Sqflite wraps create/upgrade callbacks in one transaction. Future versions
44 // must add ordered migrations here and never clear user tables on failure.
45 if (oldVersion < 1) {
46 await db.execute('''CREATE TABLE local_profiles (
47 singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
48 id TEXT NOT NULL UNIQUE CHECK(length(id) = 36),
49 display_name TEXT NOT NULL CHECK(length(trim(display_name)) BETWEEN 1 AND 80),
50 category TEXT NOT NULL CHECK(category IN ('girl_minor','boy_minor','adult')),
51 companion_name TEXT NOT NULL CHECK(length(trim(companion_name)) BETWEEN 1 AND 40),
52 theme_key TEXT NOT NULL CHECK(theme_key IN ('violet','blue','mint','coral'))
53 )''');
54 await db.execute('''CREATE TABLE local_plans (
55 id TEXT PRIMARY KEY NOT NULL CHECK(length(id) = 36),
56 profile_id TEXT NOT NULL REFERENCES local_profiles(id),
57 title TEXT NOT NULL CHECK(length(trim(title)) BETWEEN 1 AND 200),
58 kind TEXT NOT NULL CHECK(kind IN ('task','event','routine')),
59 recurrence TEXT NOT NULL CHECK(recurrence IN ('once','daily','everyTwoDays','weekly')),
60 start_date TEXT NOT NULL CHECK(length(start_date) = 10),
61 until_date TEXT CHECK(until_date IS NULL OR (length(until_date) = 10 AND until_date >= start_date)),
62 start_minute INTEGER NOT NULL CHECK(start_minute BETWEEN 0 AND 1439),
63 end_minute INTEGER NOT NULL CHECK(end_minute BETWEEN 1 AND 1440 AND end_minute > start_minute),
64 reminder_minutes INTEGER CHECK(reminder_minutes IS NULL OR reminder_minutes IN (0,5,10,15,30)),
65 archived INTEGER NOT NULL DEFAULT 0 CHECK(archived IN (0,1))
66 )''');
67 await db.execute('''CREATE TABLE local_weekly_slots (
68 plan_id TEXT NOT NULL REFERENCES local_plans(id),
69 weekday INTEGER NOT NULL CHECK(weekday BETWEEN 1 AND 7),
70 start_minute INTEGER NOT NULL CHECK(start_minute BETWEEN 0 AND 1439),
71 end_minute INTEGER NOT NULL CHECK(end_minute BETWEEN 1 AND 1440 AND end_minute > start_minute),
72 PRIMARY KEY(plan_id, weekday)
73 )''');
74 await db.execute('''CREATE TABLE local_occurrences (
75 id TEXT PRIMARY KEY NOT NULL CHECK(length(id) = 36),
76 plan_id TEXT NOT NULL REFERENCES local_plans(id),
77 occurrence_date TEXT NOT NULL CHECK(length(occurrence_date) = 10),
78 title TEXT NOT NULL CHECK(length(trim(title)) BETWEEN 1 AND 200),
79 kind TEXT NOT NULL CHECK(kind IN ('task','event','routine')),
80 start_minute INTEGER NOT NULL CHECK(start_minute BETWEEN 0 AND 1439),
81 end_minute INTEGER NOT NULL CHECK(end_minute BETWEEN 1 AND 1440 AND end_minute > start_minute),
82 completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0,1)),
83 archived INTEGER NOT NULL DEFAULT 0 CHECK(archived IN (0,1)),
84 reminder_minutes INTEGER CHECK(reminder_minutes IS NULL OR reminder_minutes IN (0,5,10,15,30)),
85 UNIQUE(plan_id, occurrence_date)
86 )''');
87 await db.execute(
88 'CREATE INDEX local_occurrences_date ON local_occurrences(occurrence_date)');
89 }
90 }
91
92 Future<StandaloneProfile?> profile() async {
93 final rows = await _database.query('local_profiles');
94 return rows.isEmpty ? null : _profile(rows.single);
95 }
96
97 Future<StandaloneProfile> createProfile({
98 required String displayName,
99 required StandaloneProfileCategory category,
100 String companionName = 'همراه',
101 String themeKey = 'violet',
102 }) async {
103 final name = _text(displayName, 'displayName', 80);
104 final companion = _text(companionName, 'companionName', 40);
105 _theme(themeKey);
106 return _database.transaction((tx) async {
107 if ((await tx.query('local_profiles')).isNotEmpty) {
108 throw StateError('This installation already has its local profile.');
109 }
110 final row = <String, Object?>{
111 'singleton': 1,
112 'id': _uuid(),
113 'display_name': name,
114 'category': _categoryKey(category),
115 'companion_name': companion,
116 'theme_key': themeKey,
117 };
118 await tx.insert('local_profiles', row);
119 return _profile(row);
120 });
121 }
122
123 Future<StandaloneProfile> updateProfile(
124 {String? displayName,
125 StandaloneProfileCategory? category,
126 String? companionName,
127 String? themeKey}) async {
128 return _database.transaction((tx) async {
129 final rows = await tx.query('local_profiles');
130 if (rows.isEmpty) throw StateError('Create the local profile first.');
131 final row = Map<String, Object?>.of(rows.single);
132 if (displayName != null) {
133 row['display_name'] = _text(displayName, 'displayName', 80);
134 }
135 if (category != null) row['category'] = _categoryKey(category);
136 if (companionName != null) {
137 row['companion_name'] = _text(companionName, 'companionName', 40);
138 }
139 if (themeKey != null) {
140 _theme(themeKey);
141 row['theme_key'] = themeKey;
142 }
143 await tx.update('local_profiles', row, where: 'singleton = 1');
144 return _profile(row);
145 });
146 }
147
148 Future<StandalonePlan> createPlan(StandalonePlanDraft draft) async {
149 final title = _text(draft.title, 'title', 200);
150 _time(draft.startMinute, draft.endMinute);
151 _date(draft.startDate);
152 _reminder(draft.reminderMinutes);
153 if (draft.untilDate != null) {
154 _date(draft.untilDate!);
155 if (StandaloneDate.daysBetween(draft.startDate, draft.untilDate!) < 0) {
156 throw ArgumentError('untilDate must not precede startDate.');
157 }
158 }
159 if (draft.recurrence == StandaloneRecurrence.weekly) {
160 if (draft.weeklySlots.isEmpty || draft.weeklySlots.length > 7) {
161 throw ArgumentError('Select one to seven weekdays.');
162 }
163 final days = <int>{};
164 for (final slot in draft.weeklySlots) {
165 _time(slot.startMinute, slot.endMinute);
166 if (slot.weekday < 1 || slot.weekday > 7 || !days.add(slot.weekday)) {
167 throw ArgumentError('Each weekday must be valid and unique.');
168 }
169 }
170 } else if (draft.weeklySlots.isNotEmpty) {
171 throw ArgumentError('Weekday slots require weekly recurrence.');
172 }
173 return _database.transaction((tx) async {
174 final profiles = await tx.query('local_profiles');
175 if (profiles.isEmpty) throw StateError('Create the local profile first.');
176 final row = <String, Object?>{
177 'id': _uuid(),
178 'profile_id': profiles.single['id'],
179 'title': title,
180 'kind': draft.kind.name,
181 'recurrence': draft.recurrence.name,
182 'start_date': StandaloneDate.key(draft.startDate),
183 'until_date': draft.untilDate == null
184 ? null
185 : StandaloneDate.key(draft.untilDate!),
186 'start_minute': draft.startMinute,
187 'end_minute': draft.endMinute,
188 'reminder_minutes': draft.reminderMinutes,
189 'archived': 0,
190 };
191 await tx.insert('local_plans', row);
192 for (final slot in draft.weeklySlots) {
193 await tx.insert('local_weekly_slots', {
194 'plan_id': row['id'],
195 'weekday': slot.weekday,
196 'start_minute': slot.startMinute,
197 'end_minute': slot.endMinute
198 });
199 }
200 return _plan(row, draft.weeklySlots);
201 });
202 }
203
204 Future<List<StandalonePlan>> listPlans({bool includeArchived = false}) =>
205 _plans(_database, includeArchived: includeArchived);
206
207 Future<List<StandalonePlan>> _plans(DatabaseExecutor executor,
208 {bool includeArchived = false}) async {
209 final rows = await executor.query('local_plans',
210 where: includeArchived ? null : 'archived = 0', orderBy: 'rowid');
211 final slots =
212 await executor.query('local_weekly_slots', orderBy: 'weekday');
213 return rows
214 .map((row) => _plan(
215 row,
216 slots
217 .where((slot) => slot['plan_id'] == row['id'])
218 .map(_slot)
219 .toList()))
220 .toList();
221 }
222
223 /// Date bounds are inclusive. Materialized occurrences and their exceptions
224 /// survive every later read; UNIQUE(plan_id, occurrence_date) prevents races.
225 Future<List<StandaloneOccurrence>> occurrences(
226 {required DateTime from,
227 required DateTime through,
228 bool includeArchived = false}) async {
229 _date(from);
230 _date(through);
231 final count = StandaloneDate.daysBetween(from, through);
232 if (count < 0 || count > 366) {
233 throw ArgumentError('Read a range of at most 367 calendar dates.');
234 }
235 return _database.transaction((tx) async {
236 final plans = await _plans(tx);
237 for (final plan in plans) {
238 for (var day = 0; day <= count; day++) {
239 final date = StandaloneDate.addDays(from, day);
240 final slot = _slotFor(plan, date);
241 if (slot == null) continue;
242 // Ignore only a duplicate occurrence. All other validation/storage
243 // failures remain errors and roll back this entire transaction.
244 await tx.rawInsert(
245 '''INSERT INTO local_occurrences
246 (id,plan_id,occurrence_date,title,kind,start_minute,end_minute,completed,archived,reminder_minutes)
247 SELECT ?,?,?,?,?,?,?,0,0,?
248 WHERE NOT EXISTS (SELECT 1 FROM local_occurrences WHERE plan_id = ? AND occurrence_date = ?)''',
249 [
250 _uuid(),
251 plan.id,
252 StandaloneDate.key(date),
253 plan.title,
254 plan.kind.name,
255 slot.startMinute,
256 slot.endMinute,
257 plan.reminderMinutes,
258 plan.id,
259 StandaloneDate.key(date),
260 ]);
261 }
262 }
263 final rows = await tx.rawQuery('''SELECT o.* FROM local_occurrences o
264 JOIN local_plans p ON p.id = o.plan_id
265 WHERE o.occurrence_date BETWEEN ? AND ?
266 ${includeArchived ? '' : 'AND o.archived = 0 AND p.archived = 0'}
267 ORDER BY o.occurrence_date, o.start_minute, o.id''',
268 [StandaloneDate.key(from), StandaloneDate.key(through)]);
269 return rows.map(_occurrence).toList();
270 });
271 }
272
273 Future<StandaloneOccurrence?> occurrence(String id) async {
274 final rows = await _database
275 .query('local_occurrences', where: 'id = ?', whereArgs: [id]);
276 return rows.isEmpty ? null : _occurrence(rows.single);
277 }
278
279 Future<StandaloneOccurrence> updateOccurrence(String id,
280 {String? title,
281 int? startMinute,
282 int? endMinute,
283 bool? completed,
284 int? reminderMinutes,
285 bool removeReminder = false}) async {
286 if (removeReminder && reminderMinutes != null) {
287 throw ArgumentError('Choose a reminder or remove it.');
288 }
289 _reminder(reminderMinutes);
290 return _database.transaction((tx) async {
291 final rows = await tx.rawQuery('''SELECT o.*, p.archived AS plan_archived
292 FROM local_occurrences o JOIN local_plans p ON p.id = o.plan_id WHERE o.id = ?''',
293 [id]);
294 if (rows.isEmpty) throw StateError('Occurrence does not exist.');
295 if (rows.single['archived'] == 1 || rows.single['plan_archived'] == 1) {
296 throw StateError('Occurrence is archived.');
297 }
298 final row = Map<String, Object?>.of(rows.single)..remove('plan_archived');
299 if (title != null) row['title'] = _text(title, 'title', 200);
300 if (startMinute != null) row['start_minute'] = startMinute;
301 if (endMinute != null) row['end_minute'] = endMinute;
302 _time(row['start_minute'] as int, row['end_minute'] as int);
303 if (completed != null) row['completed'] = completed ? 1 : 0;
304 if (removeReminder || reminderMinutes != null) {
305 row['reminder_minutes'] = removeReminder ? null : reminderMinutes;
306 }
307 await tx
308 .update('local_occurrences', row, where: 'id = ?', whereArgs: [id]);
309 return _occurrence(row);
310 });
311 }
312
313 Future<void> archiveOccurrence(String id) async {
314 final count = await _database.update('local_occurrences', {'archived': 1},
315 where: 'id = ?', whereArgs: [id]);
316 if (count != 1) throw StateError('Occurrence does not exist.');
317 }
318
319 Future<void> archivePlan(String id) async {
320 final count = await _database.update('local_plans', {'archived': 1},
321 where: 'id = ?', whereArgs: [id]);
322 if (count != 1) throw StateError('Plan does not exist.');
323 }
324
325 /// Bounds are instants, unlike [occurrences]. Include the next date because a
326 /// reminder shortly before midnight can belong to tomorrow's occurrence.
327 Future<List<StandaloneOccurrence>> pendingReminders(
328 {required DateTime from, required DateTime through}) async {
329 if (through.isBefore(from)) throw ArgumentError('Invalid reminder range.');
330 final items = await occurrences(
331 from: StandaloneDate.only(from),
332 through: StandaloneDate.addDays(through, 1));
333 final pending = items
334 .where((item) =>
335 !item.completed &&
336 item.remindAt != null &&
337 !item.remindAt!.isBefore(from) &&
338 !item.remindAt!.isAfter(through))
339 .toList();
340 pending.sort((a, b) => a.remindAt!.compareTo(b.remindAt!));
341 return pending;
342 }
343
344 Future<void> close() => _database.close();
345
346 static StandaloneWeeklySlot? _slotFor(StandalonePlan plan, DateTime date) {
347 final delta = StandaloneDate.daysBetween(plan.startDate, date);
348 if (delta < 0 ||
349 (plan.untilDate != null &&
350 StandaloneDate.daysBetween(date, plan.untilDate!) < 0)) {
351 return null;
352 }
353 if (plan.recurrence == StandaloneRecurrence.once && delta != 0) return null;
354 if (plan.recurrence == StandaloneRecurrence.everyTwoDays && delta.isOdd) {
355 return null;
356 }
357 if (plan.recurrence == StandaloneRecurrence.weekly) {
358 for (final slot in plan.weeklySlots) {
359 if (slot.weekday == date.weekday) return slot;
360 }
361 return null;
362 }
363 return StandaloneWeeklySlot(
364 weekday: date.weekday,
365 startMinute: plan.startMinute,
366 endMinute: plan.endMinute);
367 }
368
369 static StandaloneProfile _profile(Map<String, Object?> row) =>
370 StandaloneProfile(
371 id: row['id'] as String,
372 displayName: row['display_name'] as String,
373 category: switch (row['category']) {
374 'girl_minor' => StandaloneProfileCategory.girlMinor,
375 'boy_minor' => StandaloneProfileCategory.boyMinor,
376 'adult' => StandaloneProfileCategory.adult,
377 _ => throw StateError('Invalid local profile category.')
378 },
379 companionName: row['companion_name'] as String,
380 themeKey: row['theme_key'] as String);
381 static String _categoryKey(StandaloneProfileCategory category) =>
382 switch (category) {
383 StandaloneProfileCategory.girlMinor => 'girl_minor',
384 StandaloneProfileCategory.boyMinor => 'boy_minor',
385 StandaloneProfileCategory.adult => 'adult'
386 };
387 static StandaloneWeeklySlot _slot(Map<String, Object?> row) =>
388 StandaloneWeeklySlot(
389 weekday: row['weekday'] as int,
390 startMinute: row['start_minute'] as int,
391 endMinute: row['end_minute'] as int);
392 static StandalonePlan _plan(
393 Map<String, Object?> row, List<StandaloneWeeklySlot> slots) =>
394 StandalonePlan(
395 id: row['id'] as String,
396 profileId: row['profile_id'] as String,
397 title: row['title'] as String,
398 kind: StandalonePlanKind.values.byName(row['kind'] as String),
399 recurrence:
400 StandaloneRecurrence.values.byName(row['recurrence'] as String),
401 startDate: StandaloneDate.parse(row['start_date'] as String),
402 untilDate: row['until_date'] == null
403 ? null
404 : StandaloneDate.parse(row['until_date'] as String),
405 startMinute: row['start_minute'] as int,
406 endMinute: row['end_minute'] as int,
407 reminderMinutes: row['reminder_minutes'] as int?,
408 archived: row['archived'] == 1,
409 weeklySlots: slots);
410 static StandaloneOccurrence _occurrence(Map<String, Object?> row) =>
411 StandaloneOccurrence(
412 id: row['id'] as String,
413 planId: row['plan_id'] as String,
414 date: StandaloneDate.parse(row['occurrence_date'] as String),
415 title: row['title'] as String,
416 kind: StandalonePlanKind.values.byName(row['kind'] as String),
417 startMinute: row['start_minute'] as int,
418 endMinute: row['end_minute'] as int,
419 completed: row['completed'] == 1,
420 archived: row['archived'] == 1,
421 reminderMinutes: row['reminder_minutes'] as int?);
422 static void _time(int start, int end) {
423 if (start < 0 || start >= 1440 || end <= start || end > 1440) {
424 throw ArgumentError('Choose valid start and end times on the same day.');
425 }
426 }
427
428 static String _text(String value, String name, int max) {
429 final text = value.trim();
430 if (text.isEmpty || text.length > max) {
431 throw ArgumentError.value(
432 value, name, 'Length must be between 1 and $max.');
433 }
434 return text;
435 }
436
437 static void _date(DateTime value) {
438 if (value.year < 1 || value.year > 9999) {
439 throw ArgumentError('Unsupported calendar date.');
440 }
441 }
442
443 static void _reminder(int? value) {
444 if (value != null && !const [0, 5, 10, 15, 30].contains(value)) {
445 throw ArgumentError('Invalid reminder lead time.');
446 }
447 }
448
449 static void _theme(String value) {
450 if (!StandaloneProfile.themeKeys.contains(value)) {
451 throw ArgumentError('Unknown local theme.');
452 }
453 }
454
455 static String _uuid() {
456 final random = Random.secure();
457 final bytes = List<int>.generate(16, (_) => random.nextInt(256));
458 bytes[6] = (bytes[6] & 0x0f) | 0x40;
459 bytes[8] = (bytes[8] & 0x3f) | 0x80;
460 final text =
461 bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
462 return '${text.substring(0, 8)}-${text.substring(8, 12)}-${text.substring(12, 16)}-${text.substring(16, 20)}-${text.substring(20)}';
463 }
464 }