@davoodmehraban89 / LifeMate / commits / 9dd91a6
Fork 0

LifeMate — Personal, Family & Learning Companion

feat(planner): persist recurring drafts with stable retry identity

Quinn White committed Oct 18, 2026 at 17:33 UTC 9dd91a6f2754071b03a1c5bc08cd7a3bf206baaa
3 files changed +373
apps/lifemate/lib/planner_series.dart new
+183
@@ -0,0 +1,183 @@
1 +import 'dart:async';
2 +import 'dart:convert';
3 +
4 +import 'api.dart';
5 +import 'offline_store.dart';
6 +import 'plan_sync.dart' show newMutationId;
7 +
8 +class PlannerSeriesOutcome {
9 + const PlannerSeriesOutcome({required this.queued, required this.id});
10 + final bool queued;
11 + final String id;
12 +}
13 +
14 +/// An unsent series is a durable draft, never a fabricated server occurrence.
15 +/// The UUID and frozen payload survive a lost response and process restart.
16 +class PlannerSeriesSync {
17 + PlannerSeriesSync(this.api, {OfflineStore? store})
18 + : store = store ?? OfflineStore.forApi(api),
19 + _scope = api.cacheNamespace;
20 + final HttpIdentityApi api;
21 + final OfflineStore store;
22 + final String? _scope;
23 + static final _tails = <String, Future<void>>{};
24 +
25 + void _checkScope() {
26 + if (_scope == null || api.cacheNamespace != _scope) {
27 + throw const ApiException(401, 'cache_scope_closed');
28 + }
29 + }
30 +
31 + Future<T> _serial<T>(Future<T> Function() action) async {
32 + final previous = _tails[store.scope];
33 + final release = Completer<void>();
34 + _tails[store.scope] = release.future;
35 + if (previous != null) await previous;
36 + try {
37 + _checkScope();
38 + return await action();
39 + } finally {
40 + if (identical(_tails[store.scope], release.future)) {
41 + _tails.remove(store.scope);
42 + }
43 + release.complete();
44 + }
45 + }
46 +
47 + Future<PlannerSeriesOutcome> create(Map<String, dynamic> payload,
48 + {String? id}) =>
49 + _serial(() async {
50 + final seriesId = id ?? newMutationId();
51 + final body = <String, dynamic>{...payload, 'id': seriesId};
52 + final existing = (await store.readQueue())
53 + .where((m) =>
54 + m['entityType'] == 'planner_series' &&
55 + m['entityId'] == seriesId)
56 + .firstOrNull;
57 + if (existing != null) {
58 + if (_canonical(existing['payload']) != _canonical(body)) {
59 + throw const ApiException(409, 'mutation_id_reused');
60 + }
61 + _throwTerminal(existing);
62 + } else {
63 + // An already acknowledged retry cannot create another series.
64 + final accepted = (await store.readList('planner_series'))
65 + .where((s) => s['id'] == seriesId)
66 + .firstOrNull;
67 + if (accepted != null) {
68 + return PlannerSeriesOutcome(queued: false, id: seriesId);
69 + }
70 + await store.enqueue({
71 + 'id': seriesId,
72 + 'entityType': 'planner_series',
73 + 'entityId': seriesId,
74 + 'operation': 'create',
75 + 'payload': body,
76 + });
77 + }
78 + await _flush();
79 + return PlannerSeriesOutcome(
80 + queued: (await store.readQueue()).any((m) => m['id'] == seriesId),
81 + id: seriesId);
82 + });
83 +
84 + Future<void> flush() => _serial(_flush);
85 +
86 + void _throwTerminal(Map<String, dynamic> queued) {
87 + if (queued['queueStatus'] == 'conflict' ||
88 + queued['queueStatus'] == 'rejected') {
89 + throw ApiException(queued['queueStatus'] == 'conflict' ? 409 : 422,
90 + queued['lastError']?.toString() ?? 'sync_rejected');
91 + }
92 + }
93 +
94 + Future<void> _flush() async {
95 + for (final queued in await store.readQueue()) {
96 + if (queued['entityType'] != 'planner_series') continue;
97 + _throwTerminal(queued);
98 + _checkScope();
99 + try {
100 + final response = await api.requestJson('POST', '/v1/planner-series',
101 + body: Map<String, dynamic>.from(queued['payload'] as Map));
102 + _checkScope();
103 + final series = response['series'];
104 + final items = response['items'];
105 + if (series is! Map ||
106 + series['id'] != queued['entityId'] ||
107 + series['owner_user_id'] != api.currentUserId ||
108 + (int.tryParse(series['version'].toString()) ?? 0) < 1 ||
109 + items is! List ||
110 + items.any((item) =>
111 + item is! Map ||
112 + item['id'] is! String ||
113 + item['series_id'] != series['id'] ||
114 + item['owner_user_id'] != api.currentUserId)) {
115 + throw const ApiException(502, 'invalid_series_acknowledgement');
116 + }
117 + await store.acknowledge(queued['id'] as String,
118 + item: Map<String, dynamic>.from(series),
119 + cacheKey: 'planner_series');
120 + // Fresh occurrence rows merge with other queued item edits in the store.
121 + final planner = await store.readPlanner();
122 + final byId = {for (final row in planner) row['id']: row};
123 + for (final row in items) {
124 + byId[row['id']] = Map<String, dynamic>.from(row);
125 + }
126 + await store.cachePlanner(byId.values.toList());
127 + } catch (error) {
128 + if (isOfflineFailure(error)) return;
129 + if (error is ApiException &&
130 + error.statusCode >= 400 &&
131 + error.statusCode < 500 &&
132 + error.statusCode != 429) {
133 + await store.markQueued(queued['id'] as String,
134 + error.statusCode == 409 ? 'conflict' : 'rejected',
135 + error: error.code);
136 + }
137 + rethrow;
138 + }
139 + }
140 + }
141 +
142 + /// Repeated materialization only fills missing dates; occurrence edits stay.
143 + Future<void> materialize(DateTime from, DateTime to) async {
144 + _checkScope();
145 + final response = await api.requestJson('GET', '/v1/planner-series');
146 + _checkScope();
147 + final series = response['series'];
148 + if (series is! List) {
149 + throw const ApiException(502, 'invalid_series_response');
150 + }
151 + for (final row in series) {
152 + if (row is! Map ||
153 + row['id'] is! String ||
154 + row['owner_user_id'] != api.currentUserId) {
155 + throw const ApiException(502, 'invalid_series_response');
156 + }
157 + if (row['status'] == 'archived' || row['archived_at'] != null) continue;
158 + await api.requestJson(
159 + 'POST', '/v1/planner-series/${row['id']}/materialize',
160 + body: {'from': plannerDate(from), 'to': plannerDate(to)});
161 + _checkScope();
162 + }
163 + }
164 +}
165 +
166 +String _canonical(dynamic value) => jsonEncode(_sorted(value));
167 +dynamic _sorted(dynamic value) {
168 + if (value is Map) {
169 + final keys = value.keys.map((k) => k.toString()).toList()..sort();
170 + return {for (final key in keys) key: _sorted(value[key])};
171 + }
172 + if (value is List) return value.map(_sorted).toList();
173 + return value;
174 +}
175 +
176 +String plannerDate(DateTime date) =>
177 + '${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
178 +
179 +List<DateTime> plannerWeekDays(DateTime date) {
180 + final day = DateTime(date.year, date.month, date.day);
181 + final saturday = day.subtract(Duration(days: (day.weekday + 1) % 7));
182 + return List.generate(7, (i) => saturday.add(Duration(days: i)));
183 +}
apps/lifemate/test/planner_series_test.dart new
+178
@@ -0,0 +1,178 @@
1 +import 'dart:convert';
2 +import 'package:flutter/services.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/planner_series.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 +const owner = '10000000-0000-4000-8000-000000000001';
13 +const seriesId = '20000000-0000-4000-8000-000000000001';
14 +const payload = <String, dynamic>{
15 + 'title': 'برنامه ساختگی مدرسه',
16 + 'kind': 'event',
17 + 'timezone': 'Asia/Tehran',
18 + 'startsOn': '2026-10-18',
19 + 'frequency': 'weekly',
20 + 'intervalDays': 1,
21 + 'slots': [
22 + {'weekday': 6, 'start': '08:00', 'end': '12:00'}
23 + ],
24 + 'reminderMinutes': [5]
25 +};
26 +
27 +class Fixture {
28 + Fixture() {
29 + api = HttpIdentityApi(
30 + baseUrl: 'https://weekly.test/api', client: MockClient(handle))
31 + ..accessToken = 'synthetic-token'
32 + ..currentUserId = owner;
33 + store = OfflineStore.forNamespace(api.cacheNamespace!,
34 + session: OfflineSession());
35 + }
36 + late final HttpIdentityApi api;
37 + late final OfflineStore store;
38 + bool offline = false, loseReceipt = false, badOwner = false;
39 + int? status;
40 + int commits = 0;
41 + final requests = <String>[];
42 + final rows = <String, Map<String, dynamic>>{};
43 + PlannerSeriesSync reopen() => PlannerSeriesSync(api,
44 + store: OfflineStore.forNamespace(store.scope, session: OfflineSession()));
45 + Future<http.Response> handle(http.Request request) async {
46 + requests.add(request.body);
47 + if (offline) throw http.ClientException('synthetic offline');
48 + if (status != null) {
49 + return http.Response('{"error":"synthetic_rejection"}', status!);
50 + }
51 + final body = jsonDecode(request.body) as Map<String, dynamic>;
52 + expect((await store.readQueue()).single['payload'], body);
53 + final id = body['id'] as String;
54 + rows.putIfAbsent(id, () {
55 + commits++;
56 + return {
57 + 'id': id,
58 + 'owner_user_id': owner,
59 + 'version': 1,
60 + 'title': body['title'],
61 + };
62 + });
63 + if (loseReceipt) {
64 + loseReceipt = false;
65 + throw http.ClientException('synthetic lost receipt');
66 + }
67 + return http.Response(
68 + jsonEncode({
69 + 'series': {
70 + ...rows[id]!,
71 + if (badOwner) 'owner_user_id': 'other-owner'
72 + },
73 + 'items': [
74 + {
75 + 'id': '30000000-0000-4000-8000-000000000001',
76 + 'series_id': id,
77 + 'owner_user_id': owner,
78 + 'title': body['title'],
79 + 'version': 1,
80 + 'status': 'planned'
81 + }
82 + ]
83 + }),
84 + 200,
85 + headers: {'content-type': 'application/json; charset=utf-8'});
86 + }
87 +}
88 +
89 +void main() {
90 + TestWidgetsFlutterBinding.ensureInitialized();
91 + setUp(() {
92 + SharedPreferencesAsyncPlatform.instance =
93 + InMemorySharedPreferencesAsync.withData({});
94 + String? token;
95 + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
96 + .setMockMethodCallHandler(
97 + const MethodChannel('lifeguide/local_write_guard'), (call) async {
98 + if (call.method == 'getBlocked') return token != null;
99 + if (call.method == 'beginWrite') return token = 'synthetic-series-write';
100 + if (call.method == 'completeWrite' && call.arguments == token) {
101 + token = null;
102 + return true;
103 + }
104 + throw PlatformException(code: 'local_storage_restart_required');
105 + });
106 + });
107 + test('offline durable draft reopens and synchronizes exact ID once',
108 + () async {
109 + final f = Fixture()..offline = true;
110 + expect((await f.reopen().create(payload, id: seriesId)).queued, true);
111 + expect((await f.store.readQueue()).single['entityId'], seriesId);
112 + expect(await f.store.readPlanner(), isEmpty);
113 + f.offline = false;
114 + await f.reopen().flush();
115 + expect(f.commits, 1);
116 + expect(await f.store.readQueue(), isEmpty);
117 + expect((await f.store.readPlanner()).single['series_id'], seriesId);
118 + expect((await f.store.readList('planner_series')).single['id'], seriesId);
119 + expect(f.requests.first, f.requests.last);
120 + });
121 + test('response lost after commit retries same UUID without duplicate',
122 + () async {
123 + final f = Fixture()..loseReceipt = true;
124 + expect((await f.reopen().create(payload, id: seriesId)).queued, true);
125 + expect((await f.reopen().create(payload, id: seriesId)).queued, false);
126 + expect(f.commits, 1);
127 + expect(f.requests.toSet().length, 1);
128 + });
129 + test('terminal 400 is retained and retry never reports queued success',
130 + () async {
131 + final f = Fixture()..status = 400;
132 + await expectLater(
133 + f.reopen().create(payload, id: seriesId), throwsA(isA<ApiException>()));
134 + expect((await f.store.readQueue()).single['queueStatus'], 'rejected');
135 + f.status = null;
136 + await expectLater(
137 + f.reopen().create(payload, id: seriesId),
138 + throwsA(
139 + isA<ApiException>().having((e) => e.statusCode, 'status', 422)));
140 + expect(f.requests.length, 1);
141 + });
142 + test('ambiguous server error keeps exact frozen request for retry', () async {
143 + final f = Fixture()..status = 500;
144 + await expectLater(
145 + f.reopen().create(payload, id: seriesId), throwsA(isA<ApiException>()));
146 + expect((await f.store.readQueue()).single['queueStatus'], 'queued');
147 + await expectLater(
148 + f.reopen().create({...payload, 'title': 'changed'}, id: seriesId),
149 + throwsA(isA<ApiException>()
150 + .having((e) => e.code, 'code', 'mutation_id_reused')));
151 + f.status = null;
152 + expect((await f.reopen().create(payload, id: seriesId)).queued, false);
153 + expect(f.requests.toSet().length, 1);
154 + });
155 + test('foreign owner acknowledgement cannot remove private draft', () async {
156 + final f = Fixture()..badOwner = true;
157 + await expectLater(
158 + f.reopen().create(payload, id: seriesId),
159 + throwsA(isA<ApiException>()
160 + .having((e) => e.code, 'code', 'invalid_series_acknowledgement')));
161 + expect((await f.store.readQueue()).length, 1);
162 + expect(await f.store.readPlanner(), isEmpty);
163 + });
164 + test('old service cannot send after identity changes', () async {
165 + final f = Fixture();
166 + final sync = f.reopen();
167 + f.api.currentUserId = 'other-synthetic-user';
168 + await expectLater(
169 + sync.create(payload, id: seriesId), throwsA(isA<ApiException>()));
170 + expect(f.requests, isEmpty);
171 + });
172 + test('Saturday week and dates retain selected calendar day', () {
173 + final days = plannerWeekDays(DateTime(2026, 10, 18));
174 + expect(days.first.weekday, DateTime.saturday);
175 + expect(plannerDate(days.first), '2026-10-17');
176 + expect(days.last.weekday, DateTime.friday);
177 + });
178 +}
docs/decisions/0016-initial-child-planner-delivery.md new
+12
@@ -0,0 +1,12 @@
1 +# 0016 — مسیر APK اولیهٔ برنامهٔ شخصی کودک
2 +
3 +وضعیت: PROPOSED — تصمیم مالک لازم است؛ کد مجوز یا سرویس زنده تغییر نکرده است.
4 +
5 +مالک بستهٔ برنامهٔ هفتگی، تکرار، یادآوری، تیک مستقل و حفظ داده پس از بازگشایی را برای APK اولیه تأیید کرد. تأیید، مجوز deploy یا بازکردن برنامهٔ خصوصی برای نشست دعوت/بازیابی‌شدهٔ والد نیست. نشست محدود فعلی، برنامه‌ریز خصوصی را عمداً رد می‌کند؛ سرور آنلاین یکپارچه نیز برای تحویل این بسته هنوز آزموده نشده است.
6 +
7 +| گزینه | تحویل | محدودیت |
8 +|---|---|---|
9 +| D-A — APK شخصی مستقل روی گوشی، پیشنهاد برای آزمون اولیه | بدون URL، پیامک یا سرور؛ دادهٔ واقعی فقط داخل همان گوشی، برنامهٔ هفتگی و اعلان محلی. رابط و ذخیره‌سازی واقعی، بدون دادهٔ ساختگی. جداسازی صریح از نسخهٔ آنلاین و بدون انتقال خودکار. | مشاهدهٔ والد، چنددستگاهی، همگام‌سازی و بازیابی از سرور ندارد. تکمیل هدف آنلاین خانواده محسوب نمی‌شود. انتخاب ساختار و بازیابی خصوصی کودک به نسخهٔ آنلاین موکول می‌شود. |
10 +| D-B — فقط APK آنلاین | ساخت کلاینت روی API موجود؛ استفادهٔ کودک پس از تعیین سرور، تأیید ورود/حریم خصوصی و آزمون یکپارچه. دادهٔ محلی فقط کش/صف است. | بدون این پیش‌نیازها، APK نصب می‌شود ولی قابل بهره‌برداری کودک نیست؛ نشانی یا حساب نمایشی جای سرور واقعی قرار نمی‌گیرد. |
11 +
12 +تا پاسخ مالک، توسعهٔ مشترک برنامهٔ تکراری و پورت اعلان Android با دادهٔ ساختگی و آزمون محلی ادامه دارد. هیچ مسیر محلی جدید، انتشار عمومی، دادهٔ واقعی روی میزبان خارجی یا گسترش دسترسی نشست محدود فعال نمی‌شود. برای اعلان، مجوز سیستم، وضعیت دقیق/تقریبی و محدودیت باتری/توقف اجباری باید صریح نمایش و آزموده شود.