LifeMate — Personal, Family & Learning Companion
feat(personal): persist local weekly plans and independent occurrences in SQLite
Quinn White committed
Oct 19, 2026 at 13:16 UTC
4bfe8a2891a1a5aac0ee39e3cb70df3542afd034
5 files changed
+972
-1
apps/lifemate/lib/standalone/model.dart
new
+134
@@ -0,0 +1,134 @@
1
+/// Domain for the explicitly device-only edition. These records are not API
2
+/// identities, cached server records, or acknowledgements of online writes.
3
+enum StandaloneProfileCategory { girlMinor, boyMinor, adult }
4
+
5
+enum StandalonePlanKind { task, event, routine }
6
+
7
+enum StandaloneRecurrence { once, daily, everyTwoDays, weekly }
8
+
9
+class StandaloneProfile {
10
+ const StandaloneProfile(
11
+ {required this.id,
12
+ required this.displayName,
13
+ required this.category,
14
+ required this.companionName,
15
+ required this.themeKey});
16
+ final String id;
17
+ final String displayName;
18
+ final StandaloneProfileCategory category;
19
+ final String companionName;
20
+ final String themeKey;
21
+ static const themeKeys = ['violet', 'blue', 'mint', 'coral'];
22
+}
23
+
24
+/// Calendar operations use UTC only for day arithmetic. Occurrence clock times
25
+/// remain local wall-clock times, including when the local UTC offset changes.
26
+abstract final class StandaloneDate {
27
+ static DateTime only(DateTime value) =>
28
+ DateTime(value.year, value.month, value.day);
29
+ static String key(DateTime value) =>
30
+ '${value.year.toString().padLeft(4, '0')}-${value.month.toString().padLeft(2, '0')}-${value.day.toString().padLeft(2, '0')}';
31
+ static DateTime parse(String value) {
32
+ final parsed = DateTime.parse(value);
33
+ return only(parsed);
34
+ }
35
+
36
+ static int daysBetween(DateTime from, DateTime to) =>
37
+ DateTime.utc(to.year, to.month, to.day)
38
+ .difference(DateTime.utc(from.year, from.month, from.day))
39
+ .inDays;
40
+ static DateTime addDays(DateTime value, int count) =>
41
+ DateTime(value.year, value.month, value.day + count);
42
+}
43
+
44
+class StandaloneWeeklySlot {
45
+ const StandaloneWeeklySlot(
46
+ {required this.weekday,
47
+ required this.startMinute,
48
+ required this.endMinute});
49
+ final int weekday;
50
+ final int startMinute;
51
+ final int endMinute;
52
+}
53
+
54
+class StandalonePlanDraft {
55
+ const StandalonePlanDraft(
56
+ {required this.title,
57
+ required this.kind,
58
+ required this.recurrence,
59
+ required this.startDate,
60
+ required this.startMinute,
61
+ required this.endMinute,
62
+ this.untilDate,
63
+ this.weeklySlots = const [],
64
+ this.reminderMinutes});
65
+ final String title;
66
+ final StandalonePlanKind kind;
67
+ final StandaloneRecurrence recurrence;
68
+ final DateTime startDate;
69
+ final DateTime? untilDate;
70
+ final int startMinute;
71
+ final int endMinute;
72
+ final List<StandaloneWeeklySlot> weeklySlots;
73
+ final int? reminderMinutes;
74
+}
75
+
76
+class StandalonePlan {
77
+ StandalonePlan(
78
+ {required this.id,
79
+ required this.profileId,
80
+ required this.title,
81
+ required this.kind,
82
+ required this.recurrence,
83
+ required this.startDate,
84
+ required this.startMinute,
85
+ required this.endMinute,
86
+ required this.archived,
87
+ this.untilDate,
88
+ List<StandaloneWeeklySlot> weeklySlots = const [],
89
+ this.reminderMinutes})
90
+ : weeklySlots = List.unmodifiable(weeklySlots);
91
+ final String id;
92
+ final String profileId;
93
+ final String title;
94
+ final StandalonePlanKind kind;
95
+ final StandaloneRecurrence recurrence;
96
+ final DateTime startDate;
97
+ final DateTime? untilDate;
98
+ final int startMinute;
99
+ final int endMinute;
100
+ final List<StandaloneWeeklySlot> weeklySlots;
101
+ final int? reminderMinutes;
102
+ final bool archived;
103
+}
104
+
105
+class StandaloneOccurrence {
106
+ const StandaloneOccurrence(
107
+ {required this.id,
108
+ required this.planId,
109
+ required this.date,
110
+ required this.title,
111
+ required this.kind,
112
+ required this.startMinute,
113
+ required this.endMinute,
114
+ required this.completed,
115
+ required this.archived,
116
+ this.reminderMinutes});
117
+ final String id;
118
+ final String planId;
119
+ final DateTime date;
120
+ final String title;
121
+ final StandalonePlanKind kind;
122
+ final int startMinute;
123
+ final int endMinute;
124
+ final bool completed;
125
+ final bool archived;
126
+ final int? reminderMinutes;
127
+ DateTime get startsAt => DateTime(
128
+ date.year, date.month, date.day, startMinute ~/ 60, startMinute % 60);
129
+ DateTime get endsAt => DateTime(
130
+ date.year, date.month, date.day, endMinute ~/ 60, endMinute % 60);
131
+ DateTime? get remindAt => reminderMinutes == null
132
+ ? null
133
+ : startsAt.subtract(Duration(minutes: reminderMinutes!));
134
+}
apps/lifemate/lib/standalone/store.dart
new
+464
@@ -0,0 +1,464 @@
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
+}
apps/lifemate/pubspec.lock
+89
-1
@@ -181,6 +181,14 @@ packages:
181
description: flutter
182
source: sdk
183
version: "0.0.0"
184
+ glob:
185
+ dependency: transitive
186
+ description:
187
+ name: glob
188
+ sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb"
189
+ url: "https://pub.dev"
190
+ source: hosted
191
+ version: "2.2.0"
192
hooks:
193
dependency: transitive
194
description:
@@ -301,6 +309,14 @@ packages:
309
url: "https://pub.dev"
310
source: hosted
311
version: "1.19.0"
312
+ native_toolchain_c:
313
+ dependency: transitive
314
+ description:
315
+ name: native_toolchain_c
316
+ sha256: "90eaad8059ebc2004a63810a4696ea9acdb02473e47ed3b6b3bafb100ac77e31"
317
+ url: "https://pub.dev"
318
+ source: hosted
319
+ version: "0.19.5"
320
objective_c:
321
dependency: transitive
322
description:
@@ -318,7 +334,7 @@ packages:
334
source: hosted
335
version: "3.0.0"
336
path:
321
- dependency: transitive
337
+ dependency: "direct main"
338
description:
339
name: path
340
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
@@ -389,6 +405,14 @@ packages:
405
url: "https://pub.dev"
406
source: hosted
407
version: "2.1.8"
408
+ process:
409
+ dependency: transitive
410
+ description:
411
+ name: process
412
+ sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891"
413
+ url: "https://pub.dev"
414
+ source: hosted
415
+ version: "5.0.6"
416
pub_semver:
417
dependency: transitive
418
description:
@@ -474,6 +498,62 @@ packages:
498
url: "https://pub.dev"
499
source: hosted
500
version: "1.10.2"
501
+ sqflite:
502
+ dependency: "direct main"
503
+ description:
504
+ name: sqflite
505
+ sha256: "273218a1678360a3127fcf15e543381d9b813d413d783bc6e9a53eed4d2eb8fe"
506
+ url: "https://pub.dev"
507
+ source: hosted
508
+ version: "2.4.4+2"
509
+ sqflite_android:
510
+ dependency: transitive
511
+ description:
512
+ name: sqflite_android
513
+ sha256: e4f659c14bdd14464127fcd234a7a96f61fe0f539b8568e5a38f99f5a568a835
514
+ url: "https://pub.dev"
515
+ source: hosted
516
+ version: "2.4.4+1"
517
+ sqflite_common:
518
+ dependency: transitive
519
+ description:
520
+ name: sqflite_common
521
+ sha256: b80e94ff0d551d5f1f8c7d14348d29b576cca3ae30f6e195a7c380552c32b1e0
522
+ url: "https://pub.dev"
523
+ source: hosted
524
+ version: "2.5.14"
525
+ sqflite_common_ffi:
526
+ dependency: "direct dev"
527
+ description:
528
+ name: sqflite_common_ffi
529
+ sha256: "4cb6179390549743fc1a5a2fb8f134e5ad87ce459f6f4e563531487dadd81710"
530
+ url: "https://pub.dev"
531
+ source: hosted
532
+ version: "2.4.4"
533
+ sqflite_darwin:
534
+ dependency: transitive
535
+ description:
536
+ name: sqflite_darwin
537
+ sha256: "8de68fc306040f992aaf378750c16f95e4298c4bb150dd45091d75e42b1f08ee"
538
+ url: "https://pub.dev"
539
+ source: hosted
540
+ version: "2.4.4+1"
541
+ sqflite_platform_interface:
542
+ dependency: transitive
543
+ description:
544
+ name: sqflite_platform_interface
545
+ sha256: c9177b2f3150ed0647b90a94307c28452fe0a5401863044216aed83addd6c7c5
546
+ url: "https://pub.dev"
547
+ source: hosted
548
+ version: "2.4.2"
549
+ sqlite3:
550
+ dependency: transitive
551
+ description:
552
+ name: sqlite3
553
+ sha256: "144132790ec1947fad9f3ddceffd0af2ab80a1f0d1e81a4d094ee6707ec3df0b"
554
+ url: "https://pub.dev"
555
+ source: hosted
556
+ version: "3.7.1"
557
stack_trace:
558
dependency: transitive
559
description:
@@ -498,6 +578,14 @@ packages:
578
url: "https://pub.dev"
579
source: hosted
580
version: "1.4.1"
581
+ synchronized:
582
+ dependency: transitive
583
+ description:
584
+ name: synchronized
585
+ sha256: b3d516dbd3757ff2a458735e4f6cbac9ff261f576f6e87bcb17feabb39e657c5
586
+ url: "https://pub.dev"
587
+ source: hosted
588
+ version: "3.5.0"
589
term_glyph:
590
dependency: transitive
591
description:
apps/lifemate/pubspec.yaml
+3
@@ -17,7 +17,10 @@ dependencies:
17
web: ^1.1.1
18
webview_flutter: ^4.14.1
19
webview_flutter_android: ^4.14.1
20
+ sqflite: ^2.4.2
21
+ path: ^1.9.1
22
dev_dependencies:
23
+ sqflite_common_ffi: ^2.3.6
24
shared_preferences_platform_interface: ^2.4.2
25
flutter_test:
26
sdk: flutter
apps/lifemate/test/standalone_store_test.dart
new
+282
@@ -0,0 +1,282 @@
1
+import 'dart:io';
2
+
3
+import 'package:flutter_test/flutter_test.dart';
4
+import 'package:lifemate/standalone/model.dart';
5
+import 'package:lifemate/standalone/store.dart';
6
+import 'package:sqflite_common_ffi/sqflite_ffi.dart';
7
+
8
+void main() {
9
+ late Directory directory;
10
+ late String path;
11
+ late StandaloneStore store;
12
+ setUpAll(sqfliteFfiInit);
13
+ setUp(() async {
14
+ directory = await Directory.systemTemp.createTemp('lifeguide-local-store-');
15
+ path = '${directory.path}/planner.sqlite';
16
+ store = await StandaloneStore.open(path: path, factory: databaseFactoryFfi);
17
+ });
18
+ tearDown(() async {
19
+ await store.close();
20
+ await directory.delete(recursive: true);
21
+ });
22
+ Future<StandaloneProfile> profile() => store.createProfile(
23
+ displayName: 'نام ساختگی',
24
+ category: StandaloneProfileCategory.girlMinor,
25
+ );
26
+ StandalonePlanDraft daily({
27
+ DateTime? start,
28
+ DateTime? until,
29
+ int? reminder,
30
+ StandaloneRecurrence recurrence = StandaloneRecurrence.daily,
31
+ }) =>
32
+ StandalonePlanDraft(
33
+ title: 'برنامه ساختگی',
34
+ kind: StandalonePlanKind.task,
35
+ recurrence: recurrence,
36
+ startDate: start ?? DateTime(2026, 10, 19),
37
+ untilDate: until,
38
+ startMinute: 480,
39
+ endMinute: 540,
40
+ reminderMinutes: reminder,
41
+ );
42
+ test('real SQLite file preserves profile and independent edits on reopen',
43
+ () async {
44
+ final owner = await profile();
45
+ expect(
46
+ owner.id,
47
+ matches(RegExp(
48
+ r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$')));
49
+ final plan = await store.createPlan(daily());
50
+ final first = await store.occurrences(
51
+ from: DateTime(2026, 10, 19), through: DateTime(2026, 10, 20));
52
+ await store.updateOccurrence(first.first.id,
53
+ title: 'عنوان مستقل',
54
+ startMinute: 600,
55
+ endMinute: 660,
56
+ completed: true);
57
+ await store.close();
58
+ expect(await File(path).length(), greaterThan(0));
59
+ store = await StandaloneStore.open(path: path, factory: databaseFactoryFfi);
60
+ expect((await store.profile())!.id, owner.id);
61
+ final reread = await store.occurrences(
62
+ from: DateTime(2026, 10, 19), through: DateTime(2026, 10, 20));
63
+ expect(reread.map((item) => item.id), first.map((item) => item.id));
64
+ expect(reread.first.title, 'عنوان مستقل');
65
+ expect(reread.first.completed, isTrue);
66
+ expect(reread.first.startMinute, 600);
67
+ expect(reread.last.completed, isFalse);
68
+ expect(reread.last.title, 'برنامه ساختگی');
69
+ await store.archivePlan(plan.id);
70
+ expect(await store.listPlans(), isEmpty);
71
+ expect((await store.occurrence(first.first.id))!.completed, isTrue);
72
+ await store.close();
73
+ store = await StandaloneStore.open(path: path, factory: databaseFactoryFfi);
74
+ expect(
75
+ (await store.listPlans(includeArchived: true)).single.archived, isTrue);
76
+ });
77
+ test('profile edits retain identity and plans; a second profile is rejected',
78
+ () async {
79
+ final owner = await profile();
80
+ await store.createPlan(daily());
81
+ await expectLater(profile(), throwsStateError);
82
+ final updated = await store.updateProfile(
83
+ displayName: 'نام تازه', companionName: 'آوا', themeKey: 'mint');
84
+ expect(updated.id, owner.id);
85
+ expect(updated.displayName, 'نام تازه');
86
+ expect(updated.companionName, 'آوا');
87
+ expect(updated.themeKey, 'mint');
88
+ expect(await store.listPlans(), hasLength(1));
89
+ });
90
+ test('every two days uses calendar dates across month and DST', () async {
91
+ await profile();
92
+ await store.createPlan(daily(
93
+ start: DateTime(2026, 10, 30),
94
+ until: DateTime(2026, 11, 5),
95
+ recurrence: StandaloneRecurrence.everyTwoDays));
96
+ final occurrences = await store.occurrences(
97
+ from: DateTime(2026, 10, 31), through: DateTime(2026, 11, 7));
98
+ expect(occurrences.map((item) => item.date.day), [1, 3, 5]);
99
+ expect(occurrences.every((item) => item.startMinute == 480), isTrue);
100
+ expect(occurrences.every((item) => item.startsAt.hour == 8), isTrue);
101
+ expect(
102
+ StandaloneDate.daysBetween(DateTime(2026, 3, 7), DateTime(2026, 3, 10)),
103
+ 3);
104
+ });
105
+ test('weekly schedules use selected weekdays and independent hours',
106
+ () async {
107
+ await profile();
108
+ await store.createPlan(StandalonePlanDraft(
109
+ title: 'هفتگی ساختگی',
110
+ kind: StandalonePlanKind.routine,
111
+ recurrence: StandaloneRecurrence.weekly,
112
+ startDate: DateTime(2026, 10, 19),
113
+ untilDate: DateTime(2026, 10, 25),
114
+ startMinute: 480,
115
+ endMinute: 540,
116
+ weeklySlots: const [
117
+ StandaloneWeeklySlot(
118
+ weekday: DateTime.monday, startMinute: 480, endMinute: 540),
119
+ StandaloneWeeklySlot(
120
+ weekday: DateTime.friday, startMinute: 1080, endMinute: 1140),
121
+ ],
122
+ ));
123
+ final occurrences = await store.occurrences(
124
+ from: DateTime(2026, 10, 18), through: DateTime(2026, 10, 26));
125
+ expect(occurrences.map((item) => item.date.day), [19, 23]);
126
+ expect(occurrences.map((item) => item.startMinute), [480, 1080]);
127
+ expect(occurrences.map((item) => item.endMinute), [540, 1140]);
128
+ });
129
+ test(
130
+ 'one-off plans produce only their date and overlapping reads never duplicate',
131
+ () async {
132
+ await profile();
133
+ await store.createPlan(daily(recurrence: StandaloneRecurrence.once));
134
+ final reads = await Future.wait(List.generate(
135
+ 4,
136
+ (_) => store.occurrences(
137
+ from: DateTime(2026, 10, 18), through: DateTime(2026, 10, 21))));
138
+ expect(reads.every((items) => items.length == 1), isTrue);
139
+ expect(reads.map((items) => items.single.id).toSet(), hasLength(1));
140
+ });
141
+ test('archived occurrence is never regenerated', () async {
142
+ await profile();
143
+ await store.createPlan(daily());
144
+ final initial = await store.occurrences(
145
+ from: DateTime(2026, 10, 19), through: DateTime(2026, 10, 20));
146
+ await store.archiveOccurrence(initial.first.id);
147
+ final active = await store.occurrences(
148
+ from: DateTime(2026, 10, 19), through: DateTime(2026, 10, 20));
149
+ expect(active.map((item) => item.id), [initial.last.id]);
150
+ expect((await store.occurrence(initial.first.id))!.archived, isTrue);
151
+ });
152
+ test('reminders use edits and exclude completed and archived series',
153
+ () async {
154
+ await profile();
155
+ final plan = await store.createPlan(daily(reminder: 10));
156
+ final occurrences = await store.occurrences(
157
+ from: DateTime(2026, 10, 19), through: DateTime(2026, 10, 21));
158
+ await store.updateOccurrence(occurrences[0].id, completed: true);
159
+ await store.updateOccurrence(occurrences[1].id,
160
+ startMinute: 600, endMinute: 660, reminderMinutes: 30);
161
+ final pending = await store.pendingReminders(
162
+ from: DateTime(2026, 10, 19), through: DateTime(2026, 10, 22));
163
+ expect(
164
+ pending.map((item) => item.id), [occurrences[1].id, occurrences[2].id]);
165
+ expect(pending.first.remindAt, DateTime(2026, 10, 20, 9, 30));
166
+ await store.archivePlan(plan.id);
167
+ expect(
168
+ await store.pendingReminders(
169
+ from: DateTime(2026, 10, 19), through: DateTime(2026, 10, 22)),
170
+ isEmpty);
171
+ expect((await store.occurrence(occurrences[0].id))!.completed, isTrue);
172
+ });
173
+ test('invalid schedule fails before a plan is saved', () async {
174
+ await profile();
175
+ await expectLater(
176
+ store.createPlan(StandalonePlanDraft(
177
+ title: '',
178
+ kind: StandalonePlanKind.task,
179
+ recurrence: StandaloneRecurrence.daily,
180
+ startDate: DateTime(2026, 10, 19),
181
+ startMinute: 600,
182
+ endMinute: 500,
183
+ )),
184
+ throwsArgumentError);
185
+ await expectLater(
186
+ store.createPlan(daily(reminder: 7)), throwsArgumentError);
187
+ expect(await store.listPlans(), isEmpty);
188
+ });
189
+ test('SQLite independently rejects duplicates and invalid times', () async {
190
+ await profile();
191
+ await store.createPlan(daily(recurrence: StandaloneRecurrence.once));
192
+ final item = (await store.occurrences(
193
+ from: DateTime(2026, 10, 19), through: DateTime(2026, 10, 19)))
194
+ .single;
195
+ final database = await databaseFactoryFfi.openDatabase(path);
196
+ await expectLater(
197
+ database.rawInsert(
198
+ 'INSERT INTO local_occurrences SELECT ? AS id, plan_id, occurrence_date, title, kind, start_minute, end_minute, completed, archived, reminder_minutes FROM local_occurrences WHERE id = ?',
199
+ ['00000000-0000-4000-8000-000000000000', item.id],
200
+ ),
201
+ throwsA(isA<DatabaseException>()));
202
+ await expectLater(
203
+ database.rawUpdate(
204
+ 'UPDATE local_occurrences SET end_minute = start_minute WHERE id = ?',
205
+ [item.id]),
206
+ throwsA(isA<DatabaseException>()));
207
+ });
208
+ test('a storage failure rolls back the complete plan transaction', () async {
209
+ await profile();
210
+ final database = await databaseFactoryFfi.openDatabase(path);
211
+ await database.execute(
212
+ "CREATE TRIGGER reject_slot BEFORE INSERT ON local_weekly_slots BEGIN SELECT RAISE(ABORT, 'synthetic disk write rejection'); END");
213
+ await expectLater(
214
+ store.createPlan(StandalonePlanDraft(
215
+ title: 'rollback fixture',
216
+ kind: StandalonePlanKind.routine,
217
+ recurrence: StandaloneRecurrence.weekly,
218
+ startDate: DateTime(2026, 10, 19),
219
+ startMinute: 480,
220
+ endMinute: 540,
221
+ weeklySlots: const [
222
+ StandaloneWeeklySlot(weekday: 1, startMinute: 480, endMinute: 540)
223
+ ],
224
+ )),
225
+ throwsA(isA<DatabaseException>()));
226
+ expect(await store.listPlans(includeArchived: true), isEmpty);
227
+ expect(await database.query('local_weekly_slots'), isEmpty);
228
+ });
229
+ test('schema version is durable and newer data is refused without resetting',
230
+ () async {
231
+ final owner = await profile();
232
+ final database = await databaseFactoryFfi.openDatabase(path);
233
+ expect(await database.getVersion(), StandaloneStore.schemaVersion);
234
+ await database.setVersion(StandaloneStore.schemaVersion + 1);
235
+ await store.close();
236
+ await expectLater(
237
+ StandaloneStore.open(path: path, factory: databaseFactoryFfi),
238
+ throwsStateError);
239
+ final preserved = await databaseFactoryFfi.openDatabase(path);
240
+ expect(await preserved.getVersion(), StandaloneStore.schemaVersion + 1);
241
+ expect((await preserved.query('local_profiles')).single['id'], owner.id);
242
+ await preserved.close();
243
+ });
244
+ test('reminders can be disabled independently and include next-day lead time',
245
+ () async {
246
+ await profile();
247
+ await store.createPlan(StandalonePlanDraft(
248
+ title: 'midnight fixture',
249
+ kind: StandalonePlanKind.event,
250
+ recurrence: StandaloneRecurrence.daily,
251
+ startDate: DateTime(2026, 10, 19),
252
+ startMinute: 10,
253
+ endMinute: 60,
254
+ reminderMinutes: 30,
255
+ ));
256
+ final pending = await store.pendingReminders(
257
+ from: DateTime(2026, 10, 19, 23),
258
+ through: DateTime(2026, 10, 19, 23, 59));
259
+ expect(pending.single.date, DateTime(2026, 10, 20));
260
+ expect(pending.single.remindAt, DateTime(2026, 10, 19, 23, 40));
261
+ await store.updateOccurrence(pending.single.id, removeReminder: true);
262
+ expect(
263
+ await store.pendingReminders(
264
+ from: DateTime(2026, 10, 19, 23),
265
+ through: DateTime(2026, 10, 19, 23, 59)),
266
+ isEmpty);
267
+ });
268
+ test('closed writes throw and corruption never resets the database',
269
+ () async {
270
+ await profile();
271
+ await store.close();
272
+ await expectLater(
273
+ store.updateProfile(displayName: 'not saved'), throwsA(anything));
274
+ final badPath = '${directory.path}/corrupt.sqlite';
275
+ final bytes = [1, 7, 9, 2, 5, 3];
276
+ await File(badPath).writeAsBytes(bytes);
277
+ await expectLater(
278
+ StandaloneStore.open(path: badPath, factory: databaseFactoryFfi),
279
+ throwsA(anything));
280
+ expect(await File(badPath).readAsBytes(), bytes);
281
+ });
282
+}