LifeMate — Personal, Family & Learning Companion
feat: complete learning management UI and safe offline startup
Quinn White committed
Oct 12, 2026 at 03:08 UTC
fcbaa1263fd25b5de8337fc8d04300e2b9433290
35 files changed
+8396
-154
.github/workflows/ci.yml
+1
@@ -101,6 +101,7 @@ jobs:
101
- run: flutter analyze
102
- run: flutter test
103
- run: node tool/test_web_bootstrap.mjs
104
+ - run: node --test tool/test_offline_worker.mjs
105
- run: flutter build web --release --no-web-resources-cdn --pwa-strategy=none
106
- run: node tool/test_web_bootstrap.mjs
107
- name: Bundle local resources and reject external runtime services
apps/lifemate/lib/content_review_sync.dart
new
+388
@@ -0,0 +1,388 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'api.dart';
5
+import 'offline_store.dart';
6
+import 'learning_feedback_ui.dart' show feedbackCategories;
7
+
8
+const contentReviewStatuses = <String, String>{
9
+ 'received': 'دریافتشده',
10
+ 'triaged': 'بررسی اولیه',
11
+ 'planned': 'در برنامه بررسی و توسعه',
12
+ 'declined': 'پذیرفتهنشده',
13
+ 'released': 'انتشار ثبتشده',
14
+};
15
+const contentReviewTransitions = <String, List<String>>{
16
+ 'received': ['triaged', 'declined'],
17
+ 'triaged': ['planned', 'declined'],
18
+ 'planned': ['triaged', 'declined'],
19
+ 'declined': ['triaged'],
20
+};
21
+const _permissions = {'feedback.read', 'feedback.review', 'brief.prepare'};
22
+final _uuidPattern = RegExp(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$');
23
+bool _uuid(dynamic value) => value is String && _uuidPattern.hasMatch(value);
24
+bool _version(dynamic value) =>
25
+ value is int && value > 0 && value <= 2147483647;
26
+bool _date(dynamic value) =>
27
+ value is String && DateTime.tryParse(value) != null;
28
+bool _text(dynamic value, [int limit = 2000]) =>
29
+ value is String &&
30
+ value.trim().isNotEmpty &&
31
+ value.length <= limit &&
32
+ !value.contains('\u0000');
33
+bool _exact(Map value, Set<String> keys) =>
34
+ value.length == keys.length && value.keys.every(keys.contains);
35
+Never _invalid() => throw const ApiException(502, 'invalid_content_response');
36
+Map<String, dynamic> _freeze(Map value) =>
37
+ Map<String, dynamic>.from(jsonDecode(jsonEncode(value)) as Map);
38
+
39
+/// Reviewer mutations retain only IDs, versions and requested statuses. There
40
+/// is no local inbox, permission cache, chosen summary or automatic offline send.
41
+class ContentReviewSync {
42
+ ContentReviewSync(this.api, {OfflineStore? store})
43
+ : store = store ?? OfflineStore.forApi(api);
44
+ final HttpIdentityApi api;
45
+ final OfflineStore store;
46
+ static final _tails = <String, Future<void>>{};
47
+
48
+ Future<void> _scope() async {
49
+ if (api.cacheNamespace != store.scope) {
50
+ throw const ApiException(401, 'cache_scope_closed');
51
+ }
52
+ await store.readQueue(); // Rejects handles from an invalidated generation.
53
+ if (api.cacheNamespace != store.scope) {
54
+ throw const ApiException(401, 'cache_scope_closed');
55
+ }
56
+ }
57
+
58
+ Future<T> _serial<T>(Future<T> Function() operation) async {
59
+ final previous = _tails[store.scope];
60
+ final release = Completer<void>();
61
+ _tails[store.scope] = release.future;
62
+ if (previous != null) await previous;
63
+ try {
64
+ await _scope();
65
+ final result = await operation();
66
+ await _scope();
67
+ return result;
68
+ } finally {
69
+ if (identical(_tails[store.scope], release.future)) {
70
+ _tails.remove(store.scope);
71
+ }
72
+ release.complete();
73
+ }
74
+ }
75
+
76
+ Future<Set<String>> capabilities() async {
77
+ await _scope();
78
+ final response =
79
+ await api.requestJson('GET', '/v1/me/content-capabilities');
80
+ await _scope();
81
+ if (!_exact(response, {'permissions'}) ||
82
+ response['permissions'] is! List) {
83
+ _invalid();
84
+ }
85
+ final values = response['permissions'] as List;
86
+ if (values.any((value) => !_permissions.contains(value)) ||
87
+ values.toSet().length != values.length) {
88
+ _invalid();
89
+ }
90
+ return Set<String>.from(values);
91
+ }
92
+
93
+ Future<void> _require(String permission) async {
94
+ final allowed = await capabilities();
95
+ if (!allowed.contains('feedback.read') || !allowed.contains(permission)) {
96
+ throw const ApiException(403, 'content_permission_required');
97
+ }
98
+ }
99
+
100
+ Map<String, dynamic> _feedback(dynamic raw) {
101
+ if (raw is! Map ||
102
+ !_exact(raw, {
103
+ 'id',
104
+ 'unitId',
105
+ 'category',
106
+ 'summary',
107
+ 'status',
108
+ 'version',
109
+ 'createdAt',
110
+ 'updatedAt'
111
+ }) ||
112
+ !_uuid(raw['id']) ||
113
+ (raw['unitId'] != null && !_uuid(raw['unitId'])) ||
114
+ !feedbackCategories.containsKey(raw['category']) ||
115
+ !_text(raw['summary'], 1000) ||
116
+ !contentReviewStatuses.containsKey(raw['status']) ||
117
+ !_version(raw['version']) ||
118
+ !_date(raw['createdAt']) ||
119
+ !_date(raw['updatedAt'])) {
120
+ _invalid();
121
+ }
122
+ return _freeze(raw);
123
+ }
124
+
125
+ Future<Map<String, dynamic>> inbox({String? status, String? cursor}) async {
126
+ await _scope();
127
+ if ((status != null && !contentReviewStatuses.containsKey(status)) ||
128
+ (cursor != null && !_uuid(cursor))) {
129
+ throw const ApiException(400, 'invalid_content_query');
130
+ }
131
+ final query = Uri(queryParameters: {
132
+ 'limit': '20',
133
+ if (status != null) 'status': status,
134
+ if (cursor != null) 'cursor': cursor
135
+ }).query;
136
+ final response =
137
+ await api.requestJson('GET', '/v1/content-review/feedback?$query');
138
+ await _scope();
139
+ if (!_exact(response, {'feedback', 'nextCursor', 'total'}) ||
140
+ response['feedback'] is! List ||
141
+ (response['feedback'] as List).length > 20 ||
142
+ response['total'] is! int ||
143
+ response['total'] < 0 ||
144
+ (response['nextCursor'] != null && !_uuid(response['nextCursor']))) {
145
+ _invalid();
146
+ }
147
+ final rows = (response['feedback'] as List).map(_feedback).toList();
148
+ if (rows.map((row) => row['id']).toSet().length != rows.length ||
149
+ rows.any((row) => status != null && row['status'] != status) ||
150
+ response['total'] < rows.length) {
151
+ _invalid();
152
+ }
153
+ return {...response, 'feedback': rows};
154
+ }
155
+
156
+ Map<String, dynamic> _reviewBody(Map value) {
157
+ if (!_exact(value, {'mutationId', 'expectedVersion', 'status'}) ||
158
+ !_uuid(value['mutationId']) ||
159
+ !_version(value['expectedVersion']) ||
160
+ !const {'triaged', 'planned', 'declined'}.contains(value['status'])) {
161
+ throw const ApiException(400, 'invalid_review_mutation');
162
+ }
163
+ return _freeze(value);
164
+ }
165
+
166
+ Map<String, dynamic> _briefBody(Map value) {
167
+ if (!_exact(value, {'mutationId', 'feedback'}) ||
168
+ !_uuid(value['mutationId']) ||
169
+ value['feedback'] is! List ||
170
+ (value['feedback'] as List).isEmpty ||
171
+ (value['feedback'] as List).length > 20) {
172
+ throw const ApiException(400, 'invalid_brief_mutation');
173
+ }
174
+ final ids = <String>{};
175
+ for (final row in value['feedback'] as List) {
176
+ if (row is! Map ||
177
+ !_exact(row, {'id', 'expectedVersion'}) ||
178
+ !_uuid(row['id']) ||
179
+ !_version(row['expectedVersion']) ||
180
+ !ids.add(row['id'] as String)) {
181
+ throw const ApiException(400, 'invalid_brief_mutation');
182
+ }
183
+ }
184
+ return _freeze(value);
185
+ }
186
+
187
+ Future<List<Map<String, dynamic>>> pending() async {
188
+ await _scope();
189
+ final rows = (await store.readQueue())
190
+ .where((row) =>
191
+ row['entityType'] == 'content_review' ||
192
+ row['entityType'] == 'content_brief')
193
+ .toList();
194
+ await _scope();
195
+ return rows;
196
+ }
197
+
198
+ Future<Map<String, dynamic>> review(String id, Map<String, dynamic> body) {
199
+ final frozen = _reviewBody(body);
200
+ if (!_uuid(id)) throw const ApiException(400, 'invalid_review_mutation');
201
+ return _serial(() async {
202
+ await _require('feedback.review'); // No new offline reviewer change.
203
+ final mutation = {
204
+ 'id': frozen['mutationId'],
205
+ 'entityId': id,
206
+ 'entityType': 'content_review',
207
+ 'operation': 'review',
208
+ 'payload': frozen
209
+ };
210
+ await store.enqueue(mutation);
211
+ return _send(mutation);
212
+ });
213
+ }
214
+
215
+ Future<Map<String, dynamic>> prepareBrief(Map<String, dynamic> body) {
216
+ final frozen = _briefBody(body);
217
+ return _serial(() async {
218
+ await _require('brief.prepare');
219
+ final mutation = {
220
+ 'id': frozen['mutationId'],
221
+ 'entityId': frozen['mutationId'],
222
+ 'entityType': 'content_brief',
223
+ 'operation': 'prepare',
224
+ 'payload': frozen
225
+ };
226
+ await store.enqueue(mutation);
227
+ return _send(mutation);
228
+ });
229
+ }
230
+
231
+ Future<Map<String, dynamic>> retry(Map<String, dynamic> pending) =>
232
+ _serial(() async {
233
+ final stored = (await this.pending())
234
+ .where((row) => row['id'] == pending['id'])
235
+ .firstOrNull;
236
+ if (stored == null || jsonEncode(stored) != jsonEncode(pending)) {
237
+ throw const ApiException(409, 'content_pending_changed');
238
+ }
239
+ await _require(stored['entityType'] == 'content_review'
240
+ ? 'feedback.review'
241
+ : 'brief.prepare');
242
+ return _send(stored);
243
+ });
244
+
245
+ Future<Map<String, dynamic>> _send(Map<String, dynamic> mutation) async {
246
+ final review = mutation['entityType'] == 'content_review';
247
+ final body = review
248
+ ? _reviewBody(mutation['payload'] as Map)
249
+ : _briefBody(mutation['payload'] as Map);
250
+ await _scope();
251
+ final response = await api.requestJson(
252
+ review ? 'PATCH' : 'POST',
253
+ review
254
+ ? '/v1/content-review/feedback/${Uri.encodeComponent(mutation['entityId'] as String)}'
255
+ : '/v1/content-review/briefs',
256
+ body: body);
257
+ await _scope();
258
+ final ack = response['acknowledgement'];
259
+ if (ack is! Map ||
260
+ !_exact(
261
+ ack, {'mutationId', review ? 'feedbackId' : 'briefId', 'status'}) ||
262
+ ack['mutationId'] != mutation['id'] ||
263
+ !const {'accepted', 'already_applied'}.contains(ack['status'])) {
264
+ _invalid();
265
+ }
266
+ String acceptedAt;
267
+ Map<String, dynamic>? brief;
268
+ if (review) {
269
+ if (!_exact(response, {'feedback', 'acknowledgement'})) _invalid();
270
+ final row = _feedback(response['feedback']);
271
+ if (row['id'] != mutation['entityId'] ||
272
+ ack['feedbackId'] != row['id'] ||
273
+ row['version'] < (body['expectedVersion'] as int) + 1 ||
274
+ (ack['status'] == 'accepted' &&
275
+ (row['version'] != (body['expectedVersion'] as int) + 1 ||
276
+ row['status'] != body['status']))) {
277
+ _invalid();
278
+ }
279
+ acceptedAt = row['updatedAt'] as String;
280
+ // Do not return/store the summary in the durable mutation result.
281
+ } else {
282
+ if (!_exact(response, {'brief', 'acknowledgement'})) _invalid();
283
+ brief = _brief(response['brief']);
284
+ if (ack['briefId'] != brief['id'] ||
285
+ brief['sourceCount'] != (body['feedback'] as List).length) {
286
+ _invalid();
287
+ }
288
+ acceptedAt = brief['createdAt'] as String;
289
+ }
290
+ await store.acknowledge(mutation['id'] as String, acceptedAt: acceptedAt);
291
+ return {'acknowledgement': _freeze(ack), if (brief != null) 'brief': brief};
292
+ }
293
+
294
+ Map<String, dynamic> _brief(dynamic raw) {
295
+ if (raw is! Map ||
296
+ !_exact(raw, {
297
+ 'id',
298
+ 'title',
299
+ 'createdAt',
300
+ 'sourceCount',
301
+ 'categories',
302
+ 'units',
303
+ 'tasks',
304
+ 'notice'
305
+ }) ||
306
+ !_uuid(raw['id']) ||
307
+ raw['title'] != 'پیشنهاد بررسی و توسعه محتوای آموزشی' ||
308
+ !_date(raw['createdAt']) ||
309
+ raw['sourceCount'] is! int ||
310
+ raw['sourceCount'] < 1 ||
311
+ raw['sourceCount'] > 20 ||
312
+ raw['categories'] is! List ||
313
+ raw['units'] is! List ||
314
+ (raw['units'] as List).length > raw['sourceCount'] ||
315
+ raw['tasks'] is! List ||
316
+ jsonEncode(raw['tasks']) !=
317
+ jsonEncode(const [
318
+ 'نسخه رسمی کتاب و هدف یادگیری این درس را بررسی کنید.',
319
+ 'محتوای پیشنهادی و سؤالهای تمرینی را بهطور کامل بازبینی کنید.',
320
+ 'برای تغییر پیشنهادی معیار پذیرش، آزمون و PR مستقل تهیه کنید.',
321
+ 'انتشار محتوا و استقرار فقط پس از بازبینی و مجوز جداگانه انجام شود.'
322
+ ]) ||
323
+ raw['notice'] !=
324
+ 'این پیشنهاد ساختاری فاقد متن بازخورد و اطلاعات خصوصی است؛ تأیید محتوا یا دستور انتشار نیست.') {
325
+ _invalid();
326
+ }
327
+ var count = 0;
328
+ final categories = <String>{};
329
+ for (final row in raw['categories'] as List) {
330
+ if (row is! Map ||
331
+ !_exact(row, {'category', 'count'}) ||
332
+ !feedbackCategories.containsKey(row['category']) ||
333
+ row['count'] is! int ||
334
+ row['count'] < 1 ||
335
+ !categories.add(row['category'] as String)) {
336
+ _invalid();
337
+ }
338
+ count += row['count'] as int;
339
+ }
340
+ if (count != raw['sourceCount']) _invalid();
341
+ final units = <String>{};
342
+ for (final row in raw['units'] as List) {
343
+ if (row is! Map ||
344
+ !_exact(row, {
345
+ 'id',
346
+ 'title',
347
+ 'bookCode',
348
+ 'bookTitle',
349
+ 'gradeLevel',
350
+ 'trackCode',
351
+ 'editionYear',
352
+ 'editionStatus'
353
+ }) ||
354
+ !_uuid(row['id']) ||
355
+ !units.add(row['id'] as String) ||
356
+ !_text(row['title']) ||
357
+ !_text(row['bookTitle']) ||
358
+ !_text(row['bookCode'], 80) ||
359
+ row['gradeLevel'] is! int ||
360
+ row['gradeLevel'] < 1 ||
361
+ row['gradeLevel'] > 12 ||
362
+ row['trackCode'] is! List ||
363
+ (row['trackCode'] as List).any((value) => !const {
364
+ 'common',
365
+ 'math',
366
+ 'experimental',
367
+ 'humanities'
368
+ }.contains(value)) ||
369
+ (row['editionYear'] != null && !_text(row['editionYear'], 40)) ||
370
+ !const {'verified', 'unverified'}.contains(row['editionStatus'])) {
371
+ _invalid();
372
+ }
373
+ }
374
+ return _freeze(raw);
375
+ }
376
+
377
+ Future<Map<String, dynamic>> readBrief(String id) async {
378
+ if (!_uuid(id)) throw const ApiException(400, 'invalid_brief_id');
379
+ await _require('brief.prepare');
380
+ final response = await api.requestJson(
381
+ 'GET', '/v1/content-review/briefs/${Uri.encodeComponent(id)}');
382
+ await _scope();
383
+ if (!_exact(response, {'brief'})) _invalid();
384
+ final brief = _brief(response['brief']);
385
+ if (brief['id'] != id) _invalid();
386
+ return brief;
387
+ }
388
+}
apps/lifemate/lib/content_review_ui.dart
new
+398
@@ -0,0 +1,398 @@
1
+import 'dart:async';
2
+
3
+import 'package:flutter/material.dart';
4
+import 'package:flutter/services.dart';
5
+
6
+import 'api.dart';
7
+import 'content_review_sync.dart';
8
+import 'learning_feedback_ui.dart' show feedbackCategories;
9
+import 'offline_store.dart';
10
+import 'plan_sync.dart' show newMutationId;
11
+
12
+String contentReviewError(Object error) {
13
+ if (isOfflineFailure(error)) {
14
+ return 'اتصال برقرار نیست؛ متنهای صندوق پاک شدند. دریافت تازه یا تلاش دستی لازم است.';
15
+ }
16
+ if (error is ApiException) {
17
+ if (error.statusCode == 401 || error.statusCode == 403) {
18
+ return 'مجوز معتبر بررسی محتوا لازم است. عضویت خانواده این دسترسی را نمیدهد.';
19
+ }
20
+ if (error.statusCode == 404) {
21
+ return 'این بازخورد دیگر در دسترس نیست؛ ممکن است رضایت ارسال پس گرفته شده باشد.';
22
+ }
23
+ if (error.statusCode == 409) {
24
+ return 'نسخه یا رضایت منبع تغییر کرده است. صندوق را تازه کن؛ تغییر یا پیشنهاد قدیمی تأیید نشد.';
25
+ }
26
+ }
27
+ return 'پاسخ معتبر دریافت نشد؛ متنهای قبلی نمایش داده نمیشوند.';
28
+}
29
+
30
+/// Online-only operations over voluntarily shared educational feedback. Parent
31
+/// and family roles do not imply reviewer access; every server call checks it.
32
+class ContentReviewPage extends StatefulWidget {
33
+ const ContentReviewPage({super.key, required this.api});
34
+ final HttpIdentityApi api;
35
+ @override
36
+ State<ContentReviewPage> createState() => _ContentReviewPageState();
37
+}
38
+
39
+class _ContentReviewPageState extends State<ContentReviewPage>
40
+ with WidgetsBindingObserver {
41
+ late final ContentReviewSync sync;
42
+ Timer? poll;
43
+ Set<String> permissions = {};
44
+ List<Map<String, dynamic>> rows = [], pending = [];
45
+ Set<String> selected = {};
46
+ Map<String, dynamic>? brief;
47
+ String? filter, cursor, nextCursor, message;
48
+ int epoch = 0, total = 0;
49
+ bool loading = false, mutating = false, active = true;
50
+ DateTime? refreshedAt;
51
+
52
+ bool get canReview => permissions.contains('feedback.review');
53
+ bool get canPrepare => permissions.contains('brief.prepare');
54
+ bool current(int request) =>
55
+ mounted &&
56
+ active &&
57
+ request == epoch &&
58
+ widget.api.cacheNamespace == sync.store.scope;
59
+
60
+ @override
61
+ void initState() {
62
+ super.initState();
63
+ sync = ContentReviewSync(widget.api);
64
+ WidgetsBinding.instance.addObserver(this);
65
+ refresh();
66
+ poll = Timer.periodic(const Duration(seconds: 30), (_) {
67
+ if (active && !mutating && !loading) refresh();
68
+ });
69
+ }
70
+
71
+ void clearContent() {
72
+ rows = [];
73
+ permissions = {};
74
+ selected = {};
75
+ brief = null;
76
+ refreshedAt = null;
77
+ total = 0;
78
+ nextCursor = null;
79
+ }
80
+
81
+ @override
82
+ void didChangeAppLifecycleState(AppLifecycleState state) {
83
+ active = state == AppLifecycleState.resumed;
84
+ ++epoch;
85
+ if (!mounted) return;
86
+ setState(() {
87
+ clearContent();
88
+ loading = false;
89
+ });
90
+ if (active && !mutating) refresh();
91
+ }
92
+
93
+ @override
94
+ void dispose() {
95
+ ++epoch;
96
+ poll?.cancel();
97
+ WidgetsBinding.instance.removeObserver(this);
98
+ super.dispose();
99
+ }
100
+
101
+ Future<void> refresh({bool firstPage = false}) async {
102
+ if (!mounted || !active || mutating) return;
103
+ final request = ++epoch;
104
+ if (firstPage) cursor = null;
105
+ setState(() {
106
+ clearContent();
107
+ loading = true;
108
+ message = null;
109
+ });
110
+ try {
111
+ final granted = await sync.capabilities();
112
+ if (!current(request)) return;
113
+ final durable = await sync.pending();
114
+ if (!current(request)) return;
115
+ if (!granted.contains('feedback.read')) {
116
+ setState(() {
117
+ pending = durable;
118
+ message = 'مجوز بررسی محتوا برای این حساب فعال نیست.';
119
+ loading = false;
120
+ });
121
+ return;
122
+ }
123
+ final result = await sync.inbox(status: filter, cursor: cursor);
124
+ if (!current(request)) return;
125
+ setState(() {
126
+ permissions = granted;
127
+ pending = durable;
128
+ rows = List<Map<String, dynamic>>.from(result['feedback'] as List);
129
+ nextCursor = result['nextCursor'] as String?;
130
+ total = result['total'] as int;
131
+ refreshedAt = DateTime.now();
132
+ loading = false;
133
+ });
134
+ } catch (error) {
135
+ if (!current(request)) return;
136
+ setState(() {
137
+ clearContent();
138
+ message = contentReviewError(error);
139
+ loading = false;
140
+ if (error is ApiException && error.statusCode == 404) cursor = null;
141
+ });
142
+ }
143
+ }
144
+
145
+ Future<void> action(Future<Map<String, dynamic>> Function() operation,
146
+ {bool showBrief = false}) async {
147
+ if (mutating || !active) return;
148
+ final request = ++epoch;
149
+ setState(() {
150
+ mutating = true;
151
+ clearContent();
152
+ message = null;
153
+ });
154
+ Map<String, dynamic>? prepared;
155
+ String? outcome;
156
+ try {
157
+ final result = await operation();
158
+ if (!current(request)) return;
159
+ prepared = result['brief'] as Map<String, dynamic>?;
160
+ outcome =
161
+ 'تأیید سرور دریافت شد. این عملیات انتشار آموزش یا اجرای توسعه نیست.';
162
+ } catch (error) {
163
+ if (!current(request)) return;
164
+ outcome = contentReviewError(error);
165
+ } finally {
166
+ if (mounted) setState(() => mutating = false);
167
+ }
168
+ if (!mounted || !active || widget.api.cacheNamespace != sync.store.scope) {
169
+ return;
170
+ }
171
+ await refresh(firstPage: false);
172
+ if (!mounted || !active || widget.api.cacheNamespace != sync.store.scope) {
173
+ return;
174
+ }
175
+ // A failed refresh must not reintroduce a brief or hide revoked access.
176
+ setState(() {
177
+ if (showBrief && canPrepare && prepared != null) brief = prepared;
178
+ message ??= outcome;
179
+ });
180
+ }
181
+
182
+ Future<void> copyBrief() async {
183
+ final id = brief?['id'] as String?;
184
+ if (id == null || mutating || !active) return;
185
+ final request = ++epoch;
186
+ setState(() {
187
+ mutating = true;
188
+ brief = null;
189
+ message = 'اعتبار رضایت و نسخه منابع در سرور دوباره بررسی میشود.';
190
+ });
191
+ try {
192
+ final fresh = await sync.readBrief(id);
193
+ if (!current(request)) return;
194
+ final lines = <String>[
195
+ fresh['title'] as String,
196
+ 'زمان تهیه: ${fresh['createdAt']}',
197
+ 'تعداد منابع رضایتداده: ${fresh['sourceCount']}',
198
+ ...(fresh['categories'] as List).map(
199
+ (row) => '${feedbackCategories[row['category']]}: ${row['count']}'),
200
+ ...(fresh['units'] as List).map((row) =>
201
+ 'پایه ${row['gradeLevel']}، ${row['bookTitle']} (${row['bookCode']})، ${row['title']}؛ نسخه ${row['editionYear'] ?? 'نامشخص'}، ${row['editionStatus'] == 'verified' ? 'منبع بررسیشده' : 'نسخه تأییدنشده'}'),
202
+ ...(fresh['tasks'] as List).cast<String>(),
203
+ fresh['notice'] as String,
204
+ ];
205
+ await Clipboard.setData(ClipboardData(text: lines.join('\n')));
206
+ if (!current(request)) return;
207
+ setState(() {
208
+ brief = fresh;
209
+ message =
210
+ 'پیشنهاد ساختاری پس از بررسی تازه سرور کپی شد؛ متن بازخورد در آن نیست.';
211
+ });
212
+ } catch (error) {
213
+ if (current(request)) {
214
+ setState(() {
215
+ clearContent();
216
+ message = contentReviewError(error);
217
+ });
218
+ }
219
+ } finally {
220
+ if (mounted) setState(() => mutating = false);
221
+ }
222
+ }
223
+
224
+ @override
225
+ Widget build(BuildContext context) => Directionality(
226
+ textDirection: TextDirection.rtl,
227
+ child: Scaffold(
228
+ appBar: AppBar(title: const Text('بررسی محتوای آموزشی'), actions: [
229
+ IconButton(
230
+ key: const Key('content-refresh'),
231
+ tooltip: 'دریافت تازه از سرور',
232
+ onPressed: mutating ? null : () => refresh(),
233
+ icon: const Icon(Icons.refresh))
234
+ ]),
235
+ body: ListView(padding: const EdgeInsets.all(16), children: [
236
+ const Text(
237
+ 'فقط خلاصهای که کاربر با رضایت برای تیم محتوا فرستاده است نمایش داده میشود. این صندوق شامل گفتوگوها، یادداشتها یا اطلاعات سلامت نیست.'),
238
+ const SizedBox(height: 8),
239
+ const Text(
240
+ 'متنهای صندوق فقط هنگام اتصال در حافظهاند. پیشنهاد توسعه بهصورت دستی بازبینی میشود؛ هوش مصنوعی، پیامرسانی و انتشار خودکار اجرا نمیشوند.'),
241
+ if (loading || mutating) const LinearProgressIndicator(),
242
+ Text(refreshedAt == null
243
+ ? 'داده تازه تأییدشده در دسترس نیست.'
244
+ : 'آخرین دریافت: ${refreshedAt!.hour.toString().padLeft(2, '0')}:${refreshedAt!.minute.toString().padLeft(2, '0')}؛ تازهسازی هر ۳۰ ثانیه، مجموع $total بازخورد.'),
245
+ if (message != null)
246
+ Padding(
247
+ padding: const EdgeInsets.symmetric(vertical: 8),
248
+ child: Text(message!)),
249
+ DropdownButtonFormField<String>(
250
+ key: ValueKey('content-filter-${filter ?? 'all'}'),
251
+ initialValue: filter ?? 'all',
252
+ decoration: const InputDecoration(labelText: 'فیلتر وضعیت'),
253
+ items: [
254
+ const DropdownMenuItem(
255
+ value: 'all', child: Text('همه وضعیتها')),
256
+ ...contentReviewStatuses.entries.map((entry) =>
257
+ DropdownMenuItem(
258
+ value: entry.key, child: Text(entry.value)))
259
+ ],
260
+ onChanged: mutating
261
+ ? null
262
+ : (value) {
263
+ filter = value == 'all' ? null : value;
264
+ refresh(firstPage: true);
265
+ }),
266
+ ...rows.map((row) => Card(
267
+ child: Padding(
268
+ padding: const EdgeInsets.all(12),
269
+ child: Column(
270
+ crossAxisAlignment: CrossAxisAlignment.start,
271
+ children: [
272
+ Text(row['summary'] as String),
273
+ const SizedBox(height: 6),
274
+ Text(
275
+ '${feedbackCategories[row['category']]} · ${contentReviewStatuses[row['status']]} · نسخه ${row['version']}'),
276
+ Text('زمان ثبت در سرور: ${row['createdAt']}'),
277
+ if (row['unitId'] == null)
278
+ const Text('پیشنهاد عمومی آموزش'),
279
+ if (canReview &&
280
+ contentReviewTransitions
281
+ .containsKey(row['status']))
282
+ DropdownButtonFormField<String>(
283
+ key: Key('review-status-${row['id']}'),
284
+ decoration: const InputDecoration(
285
+ labelText: 'تغییر مرحله بررسی'),
286
+ hint: const Text('انتخاب مرحله بعد'),
287
+ items: contentReviewTransitions[row['status']]!
288
+ .map((status) => DropdownMenuItem(
289
+ value: status,
290
+ child: Text(
291
+ contentReviewStatuses[status]!)))
292
+ .toList(),
293
+ onChanged: mutating
294
+ ? null
295
+ : (value) {
296
+ if (value == null) return;
297
+ final body = {
298
+ 'mutationId': newMutationId(),
299
+ 'expectedVersion': row['version'],
300
+ 'status': value
301
+ };
302
+ action(() => sync.review(
303
+ row['id'] as String, body));
304
+ }),
305
+ if (canPrepare && row['status'] == 'planned')
306
+ CheckboxListTile(
307
+ contentPadding: EdgeInsets.zero,
308
+ title: const Text(
309
+ 'انتخاب برای پیشنهاد ساختاری توسعه'),
310
+ value: selected.contains(row['id']),
311
+ onChanged: mutating
312
+ ? null
313
+ : (value) => setState(() {
314
+ if (value == true &&
315
+ selected.length < 20) {
316
+ selected.add(row['id'] as String);
317
+ }
318
+ if (value != true) {
319
+ selected.remove(row['id']);
320
+ }
321
+ })),
322
+ ])))),
323
+ if (!loading &&
324
+ permissions.contains('feedback.read') &&
325
+ rows.isEmpty)
326
+ const Text('بازخورد رضایتدادهای در این صفحه نیست.'),
327
+ if (nextCursor != null)
328
+ TextButton(
329
+ onPressed: mutating
330
+ ? null
331
+ : () {
332
+ cursor = nextCursor;
333
+ refresh();
334
+ },
335
+ child: const Text('صفحه بعد')),
336
+ if (cursor != null)
337
+ TextButton(
338
+ onPressed: mutating ? null : () => refresh(firstPage: true),
339
+ child: const Text('بازگشت به صفحه اول')),
340
+ if (canPrepare)
341
+ FilledButton(
342
+ onPressed: selected.isEmpty || mutating
343
+ ? null
344
+ : () {
345
+ final sources = rows
346
+ .where((row) => selected.contains(row['id']))
347
+ .map((row) => {
348
+ 'id': row['id'],
349
+ 'expectedVersion': row['version']
350
+ })
351
+ .toList();
352
+ final body = {
353
+ 'mutationId': newMutationId(),
354
+ 'feedback': sources
355
+ };
356
+ action(() => sync.prepareBrief(body),
357
+ showBrief: true);
358
+ },
359
+ child: const Text('تهیه پیشنهاد توسعه، بدون متن بازخورد')),
360
+ if (brief != null)
361
+ Card(
362
+ child: Padding(
363
+ padding: const EdgeInsets.all(12),
364
+ child: Column(
365
+ crossAxisAlignment: CrossAxisAlignment.start,
366
+ children: [
367
+ Text(brief!['title'] as String),
368
+ Text('تعداد منابع: ${brief!['sourceCount']}'),
369
+ Text(brief!['notice'] as String),
370
+ TextButton(
371
+ key: const Key('copy-content-brief'),
372
+ onPressed: mutating ? null : copyBrief,
373
+ child: const Text(
374
+ 'بررسی دوباره منابع و کپی پیشنهاد')),
375
+ ]))),
376
+ if (pending.isNotEmpty) ...[
377
+ const Divider(),
378
+ Text(
379
+ '${pending.length} عملیات بدون دریافت تأیید سرور یا با تعارض روی این دستگاه مانده است. فقط شناسهها و مرحله در صفاند؛ ارسال خودکار انجام نمیشود.'),
380
+ ...pending.map((row) => ListTile(
381
+ title: Text(row['entityType'] == 'content_review'
382
+ ? 'تغییر مرحله بررسی'
383
+ : 'تهیه پیشنهاد توسعه'),
384
+ subtitle: const Text(
385
+ 'تلاش دستی با همان شناسه و نسخه؛ ممکن است عملیات قبلاً در سرور ثبت شده باشد.'),
386
+ trailing: TextButton(
387
+ onPressed: mutating ||
388
+ !permissions.contains('feedback.read') ||
389
+ !(row['entityType'] == 'content_review'
390
+ ? canReview
391
+ : canPrepare)
392
+ ? null
393
+ : () => action(() => sync.retry(row),
394
+ showBrief: row['entityType'] == 'content_brief'),
395
+ child: const Text('تلاش دوباره')))),
396
+ ],
397
+ ])));
398
+}
apps/lifemate/lib/dashboard_ui.dart
+277
-31
@@ -2,7 +2,6 @@ import 'dart:async';
2
import 'package:flutter/material.dart';
3
import 'api.dart';
4
import 'phase3_ui.dart';
5
-import 'offline_store.dart';
5
6
class ParentFamilyDashboard extends StatefulWidget {
7
const ParentFamilyDashboard({super.key, required this.api});
@@ -11,20 +10,75 @@ class ParentFamilyDashboard extends StatefulWidget {
10
State<ParentFamilyDashboard> createState() => _ParentFamilyDashboardState();
11
}
12
14
-class _ParentFamilyDashboardState extends State<ParentFamilyDashboard> {
13
+class _ParentFamilyDashboardState extends State<ParentFamilyDashboard>
14
+ with WidgetsBindingObserver {
15
late Future<List<Map<String, dynamic>>> data;
16
+ Object? accountScope;
17
+ int loadEpoch = 0;
18
+ bool active = true;
19
@override
20
void initState() {
21
super.initState();
22
+ WidgetsBinding.instance.addObserver(this);
23
+ accountScope = scopeFor(widget.api);
24
data = load();
25
}
26
27
+ Object? scopeFor(IdentityApi api) =>
28
+ api is HttpIdentityApi ? api.cacheNamespace : api;
29
+
30
+ @override
31
+ void didUpdateWidget(covariant ParentFamilyDashboard oldWidget) {
32
+ super.didUpdateWidget(oldWidget);
33
+ if (oldWidget.api != widget.api || accountScope != scopeFor(widget.api)) {
34
+ accountScope = scopeFor(widget.api);
35
+ loadEpoch++;
36
+ data = load();
37
+ }
38
+ }
39
+
40
+ @override
41
+ void didChangeAppLifecycleState(AppLifecycleState state) {
42
+ if (!mounted) return;
43
+ setState(() {
44
+ loadEpoch++;
45
+ active = state == AppLifecycleState.resumed;
46
+ if (active) {
47
+ accountScope = scopeFor(widget.api);
48
+ data = load();
49
+ }
50
+ });
51
+ }
52
+
53
+ @override
54
+ void dispose() {
55
+ loadEpoch++;
56
+ WidgetsBinding.instance.removeObserver(this);
57
+ super.dispose();
58
+ }
59
+
60
Future<List<Map<String, dynamic>>> load() async {
61
+ final api = widget.api;
62
+ final scope = scopeFor(api);
63
+ final epoch = loadEpoch;
64
+ void current() {
65
+ if (scope == null ||
66
+ scope != scopeFor(widget.api) ||
67
+ api != widget.api ||
68
+ epoch != loadEpoch) {
69
+ throw const ApiException(401, 'family_dashboard_scope_changed');
70
+ }
71
+ }
72
+
73
+ current();
74
final rows = <Map<String, dynamic>>[];
24
- for (final f in await widget.api.listFamilies()) {
75
+ final families = await api.listFamilies();
76
+ current();
77
+ for (final f in families) {
78
if (f['role'] != 'parent_guardian') continue;
26
- for (final child
27
- in await widget.api.listFamilyMembers(f['id'].toString())) {
79
+ final members = await api.listFamilyMembers(f['id'].toString());
80
+ current();
81
+ for (final child in members) {
82
if (child['role'] == 'teen_minor') {
83
rows.add({...child, 'familyId': f['id'], 'familyName': f['name']});
84
}
@@ -35,13 +89,18 @@ class _ParentFamilyDashboardState extends State<ParentFamilyDashboard> {
89
90
void reload() {
91
setState(() {
92
+ loadEpoch++;
93
+ accountScope = scopeFor(widget.api);
94
data = load();
95
});
96
}
97
98
@override
43
- Widget build(BuildContext context) =>
44
- FutureBuilder<List<Map<String, dynamic>>>(
99
+ Widget build(BuildContext context) => !active
100
+ ? const Center(
101
+ child: Text('برای دریافت مجوز و اطلاعات تازه به برنامه برگردید.'))
102
+ : FutureBuilder<List<Map<String, dynamic>>>(
103
+ key: ValueKey(loadEpoch),
104
future: data,
105
builder: (context, s) {
106
if (s.hasError) return LoadError(error: s.error!, retry: reload);
@@ -101,10 +160,14 @@ class _LearningReportPageState extends State<LearningReportPage>
160
String? error;
161
int days = 7;
162
Timer? poll;
163
+ int loadEpoch = 0;
164
+ String? reportNamespace;
165
+ String? boundNamespace;
166
@override
167
void initState() {
168
super.initState();
169
WidgetsBinding.instance.addObserver(this);
170
+ boundNamespace = widget.api.cacheNamespace;
171
startPoll();
172
load();
173
}
@@ -114,6 +177,23 @@ class _LearningReportPageState extends State<LearningReportPage>
177
poll = Timer.periodic(const Duration(seconds: 15), (_) => load());
178
}
179
180
+ @override
181
+ void didUpdateWidget(covariant LearningReportPage oldWidget) {
182
+ super.didUpdateWidget(oldWidget);
183
+ if (oldWidget.api != widget.api ||
184
+ oldWidget.familyId != widget.familyId ||
185
+ oldWidget.childId != widget.childId ||
186
+ boundNamespace != widget.api.cacheNamespace) {
187
+ loadEpoch++;
188
+ boundNamespace = widget.api.cacheNamespace;
189
+ report = null;
190
+ reportNamespace = null;
191
+ error = null;
192
+ busy = false;
193
+ load();
194
+ }
195
+ }
196
+
197
@override
198
void didChangeAppLifecycleState(AppLifecycleState s) {
199
if (s == AppLifecycleState.resumed) {
@@ -121,48 +201,150 @@ class _LearningReportPageState extends State<LearningReportPage>
201
load();
202
} else {
203
poll?.cancel();
204
+ loadEpoch++;
205
+ setState(() {
206
+ busy = false;
207
+ report = null;
208
+ reportNamespace = null;
209
+ });
210
}
211
}
212
213
@override
214
void dispose() {
215
poll?.cancel();
216
+ loadEpoch++;
217
WidgetsBinding.instance.removeObserver(this);
218
super.dispose();
219
}
220
221
Future<void> load() async {
222
if (busy) return;
136
- setState(() => busy = true);
223
+ final epoch = ++loadEpoch;
224
+ final namespace = widget.api.cacheNamespace;
225
+ setState(() {
226
+ busy = true;
227
+ report = null;
228
+ reportNamespace = null;
229
+ });
230
try {
231
final tehranNow =
232
DateTime.now().toUtc().add(const Duration(hours: 3, minutes: 30));
233
final to =
234
DateTime.utc(tehranNow.year, tehranNow.month, tehranNow.day + 1)
235
.subtract(const Duration(hours: 3, minutes: 30));
236
+ final from = to.subtract(Duration(days: days));
237
final result = await widget.api.getLearningReport(
238
widget.familyId, widget.childId,
145
- from: to.subtract(Duration(days: days)), to: to);
146
- if (mounted) {
239
+ from: from, to: to);
240
+ validateReport(result, from: from, to: to);
241
+ if (mounted &&
242
+ epoch == loadEpoch &&
243
+ namespace == widget.api.cacheNamespace) {
244
setState(() {
245
report = result;
246
+ reportNamespace = namespace;
247
error = null;
248
});
249
}
250
} catch (e) {
153
- if (mounted) {
251
+ if (mounted && epoch == loadEpoch) {
252
setState(() {
253
error = uiErrorText(e);
156
- if (isOfflineFailure(e) ||
157
- (e is ApiException &&
158
- e.statusCode >= 400 &&
159
- e.statusCode < 500)) {
160
- report = null;
161
- }
254
+ report = null;
255
+ reportNamespace = null;
256
});
257
}
258
} finally {
165
- if (mounted) setState(() => busy = false);
259
+ if (mounted && epoch == loadEpoch) setState(() => busy = false);
260
+ }
261
+ }
262
+
263
+ /// A missing modern period contract is explicitly historical. A present,
264
+ /// malformed period contract must never be interpreted as zero completion.
265
+ void validateReport(Map<String, dynamic> response,
266
+ {required DateTime from, required DateTime to}) {
267
+ Never invalid() => throw const ApiException(502, 'invalid_learning_report');
268
+ bool count(dynamic value) => value is int && value >= 0;
269
+ bool percent(dynamic value) =>
270
+ value is num && value.isFinite && value >= 0 && value <= 100;
271
+ bool instant(dynamic value) =>
272
+ value is String &&
273
+ RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) &&
274
+ DateTime.tryParse(value) != null;
275
+ if (response['items'] is! List ||
276
+ response['daily'] is! List ||
277
+ response['subjects'] is! List ||
278
+ response['metrics'] is! Map ||
279
+ !instant(response['asOf']) ||
280
+ (response['familyId'] != null &&
281
+ response['familyId'] != widget.familyId) ||
282
+ (response['childId'] != null &&
283
+ response['childId'] != widget.childId)) {
284
+ invalid();
285
+ }
286
+ if (!response.containsKey('periodMetrics')) return;
287
+ final metrics = response['periodMetrics'];
288
+ if (metrics is! Map ||
289
+ response['periodSubjects'] is! List ||
290
+ response['periodExams'] is! List ||
291
+ !instant(response['from']) ||
292
+ !instant(response['to']) ||
293
+ DateTime.parse(response['from'] as String) != from ||
294
+ DateTime.parse(response['to'] as String) != to ||
295
+ response['timezone'] != 'Asia/Tehran' ||
296
+ response['taskDatePolicy'] != 'due_at_then_starts_at' ||
297
+ response['rangeConvention'] != 'inclusive_from_exclusive_to' ||
298
+ response['completionBasis'] != 'current_status_of_period_tasks') {
299
+ invalid();
300
+ }
301
+ for (final key in const [
302
+ 'totalTasks',
303
+ 'completedTasks',
304
+ 'overdueTasks',
305
+ 'plannedDurationSeconds',
306
+ 'recordedDurationSeconds',
307
+ 'examCount',
308
+ 'gradedExamCount',
309
+ ]) {
310
+ if (!count(metrics[key])) invalid();
311
+ }
312
+ if (!percent(metrics['completionPercent']) ||
313
+ metrics['completedTasks'] > metrics['totalTasks'] ||
314
+ metrics['overdueTasks'] > metrics['totalTasks'] ||
315
+ metrics['examCount'] > metrics['totalTasks'] ||
316
+ metrics['gradedExamCount'] > metrics['examCount'] ||
317
+ metrics['completionPercent'] !=
318
+ (metrics['totalTasks'] == 0
319
+ ? 0
320
+ : ((metrics['completedTasks'] as int) *
321
+ 100 /
322
+ (metrics['totalTasks'] as int))
323
+ .round()) ||
324
+ (metrics['gradePercent'] != null &&
325
+ !percent(metrics['gradePercent']))) {
326
+ invalid();
327
+ }
328
+ for (final item in response['items'] as List) {
329
+ if (item is! Map ||
330
+ item['taskInRange'] is! bool ||
331
+ !count(item['recordedDurationSeconds'])) {
332
+ invalid();
333
+ }
334
+ }
335
+ for (final subject in response['periodSubjects'] as List) {
336
+ if (subject is! Map ||
337
+ !count(subject['totalTasks']) ||
338
+ !count(subject['completedTasks']) ||
339
+ subject['completedTasks'] > subject['totalTasks'] ||
340
+ !count(subject['recordedDurationSeconds']) ||
341
+ (subject['gradePercent'] != null &&
342
+ !percent(subject['gradePercent']))) {
343
+ invalid();
344
+ }
345
+ }
346
+ for (final exam in response['periodExams'] as List) {
347
+ if (exam is! Map || exam['kind'] != 'exam') invalid();
348
}
349
}
350
@@ -170,9 +352,20 @@ class _LearningReportPageState extends State<LearningReportPage>
352
'${((seconds as num? ?? 0) / 60).round()} دقیقه';
353
@override
354
Widget build(BuildContext context) {
173
- final r = report;
174
- final m = r?['metrics'] as Map? ?? {};
175
- final items = r?['items'] as List? ?? [];
355
+ final r = reportNamespace == widget.api.cacheNamespace ? report : null;
356
+ final hasPeriod = r?['periodMetrics'] is Map;
357
+ final m =
358
+ (hasPeriod ? (r?['periodMetrics']) : (r?['metrics'])) as Map? ?? {};
359
+ final allTime = r?['allTimeTaskMetrics'] as Map?;
360
+ final items = (r?['items'] as List? ?? []).where((raw) {
361
+ final item = raw as Map;
362
+ return !hasPeriod ||
363
+ item['taskInRange'] == true ||
364
+ (item['recordedDurationSeconds'] as num? ?? 0) > 0;
365
+ }).toList();
366
+ final subjects =
367
+ (hasPeriod ? (r?['periodSubjects']) : (r?['subjects'])) as List? ?? [];
368
+ final exams = r?['periodExams'] as List? ?? [];
369
final daily = r?['daily'] as List? ?? [];
370
final max = daily.fold<num>(
371
1,
@@ -209,6 +402,9 @@ class _LearningReportPageState extends State<LearningReportPage>
402
? null
403
: (v) {
404
setState(() => days = v.first);
405
+ report = null;
406
+ reportNamespace = null;
407
+ error = null;
408
load();
409
}),
410
if (busy) const LinearProgressIndicator(),
@@ -223,16 +419,40 @@ class _LearningReportPageState extends State<LearningReportPage>
419
if (r != null) ...[
420
Text(
421
'دریافت سرور: ${shortDate(r['asOf'])} · آخرین ثبت: ${shortDate(r['lastSyncAt'])}'),
422
+ if (hasPeriod) ...[
423
+ Text('بازه $days روز اخیر تا پایان امروز (تهران)',
424
+ style: Theme.of(context).textTheme.titleMedium),
425
+ const Text(
426
+ 'شمارش تکلیفها بر اساس موعد و سپس زمان شروع است؛ تکلیف بیتاریخ در شمارش بازه نیست. تکمیل، وضعیت فعلی همین تکلیفهاست و به معنی یادگیری تأییدشده نیست.'),
427
+ ] else
428
+ const Text(
429
+ 'سرور آمار تکلیفهای بازه را ارائه نکرده؛ شمارش تکلیفها مربوط به کل سابقه مجاز است.'),
430
Wrap(spacing: 8, children: [
431
Chip(label: Text('$todayCount مورد امروز (تهران)')),
228
- Chip(label: Text('${m['totalTasks'] ?? 0} تکلیف')),
229
- Chip(label: Text('${m['completedTasks'] ?? 0} انجامشده')),
230
- Chip(label: Text('${m['overdueTasks'] ?? 0} عقبافتاده')),
231
- Chip(label: Text('${m['completionPercent'] ?? 0}٪ تکمیل'))
432
+ Chip(
433
+ label: Text(
434
+ '${m['totalTasks'] ?? 0} تکلیف ${hasPeriod ? 'در بازه' : 'در کل سابقه مجاز'}')),
435
+ Chip(
436
+ label: Text(
437
+ '${m['completedTasks'] ?? 0} انجامشده ${hasPeriod ? 'در بازه' : 'در کل سابقه مجاز'}')),
438
+ Chip(
439
+ label: Text(
440
+ '${m['overdueTasks'] ?? 0} عقبافتاده ${hasPeriod ? 'در بازه' : 'در کل سابقه مجاز'}')),
441
+ Chip(
442
+ label: Text(
443
+ '${m['completionPercent'] ?? 0}٪ تکمیل ${hasPeriod ? 'تکلیفهای بازه' : 'کل سابقه مجاز'}'))
444
]),
445
+ if (hasPeriod && allTime != null)
446
+ Text(
447
+ 'کل سابقه مجاز: ${allTime['totalTasks'] ?? 0} تکلیف · ${allTime['completedTasks'] ?? 0} انجامشده'),
448
Text(
449
'زمان برنامهریزیشده: ${minutes(m['plannedInRangeDurationSeconds'] ?? m['plannedDurationSeconds'])}'),
450
+ if (!hasPeriod && m['plannedInRangeDurationSeconds'] == null)
451
+ const Text(
452
+ 'زمان برنامهریزیشده مربوط به کل سابقه مجاز است؛ زمان بازه جداگانه از سرور دریافت نشده است.'),
453
Text('زمان ثبتشده: ${minutes(m['recordedDurationSeconds'])}'),
454
+ const Text(
455
+ 'زمان ثبتشده فقط بخش جلسههای مجاز داخل بازه است؛ ممکن است به تکلیفی با موعد خارج از بازه مربوط باشد.'),
456
Text('روند زمان ثبتشده',
457
style: Theme.of(context).textTheme.titleLarge),
458
...daily.map((raw) {
@@ -250,17 +470,43 @@ class _LearningReportPageState extends State<LearningReportPage>
470
Text(minutes(row['recordedDurationSeconds']))
471
]));
472
}),
253
- Text('درسها', style: Theme.of(context).textTheme.titleLarge),
254
- ...(r['subjects'] as List? ?? []).map((raw) {
473
+ Text(hasPeriod ? 'درسها در بازه' : 'درسها در کل سابقه مجاز',
474
+ style: Theme.of(context).textTheme.titleLarge),
475
+ ...subjects.map((raw) {
476
final row = raw as Map;
477
return ListTile(
478
title: Text(row['subjectName']?.toString() ?? 'بدون درس'),
479
subtitle: Text(
259
- '${row['completedTasks']}/${row['totalTasks']} تکمیل · ${minutes(row['recordedDurationSeconds'])}'));
480
+ '${row['completedTasks']}/${row['totalTasks']} تکمیل ${hasPeriod ? 'تکلیفهای بازه' : 'کل سابقه'} · ${minutes(row['recordedDurationSeconds'])}${hasPeriod && row['gradePercent'] != null ? '\nنمره وزنی امتحانهای مجاز: ${row['gradePercent']}٪ (${row['gradedExamCount']} امتحان)' : ''}'));
481
}),
261
- Text('تکلیفها و امتحانها',
482
+ if (hasPeriod) ...[
483
+ Text('امتحانهای مجاز در بازه',
484
+ style: Theme.of(context).textTheme.titleLarge),
485
+ const Text(
486
+ 'این نمرهها مربوط به امتحانهای ثبتشده مدرسهاند. نتیجه کوییز درس در تاریخچه خصوصی یادگیری است و در این گزارش جمع نمیشود.'),
487
+ Text(
488
+ '${m['examCount'] ?? 0} امتحان · ${m['gradedExamCount'] ?? 0} نمره ثبتشده${m['gradePercent'] == null ? '' : ' · نمره وزنی ${m['gradePercent']}٪'}'),
489
+ if (exams.isEmpty)
490
+ const Text('امتحان مجازی برای این بازه ثبت نشده است.'),
491
+ ...exams.map((raw) {
492
+ final exam = raw as Map;
493
+ return ListTile(
494
+ title: Text(exam['title']?.toString() ?? ''),
495
+ subtitle: Text(
496
+ 'موعد: ${shortDate(exam['scheduledAt'] ?? exam['dueAt'] ?? exam['startsAt'])}\n${exam['gradePoints'] == null ? 'نمره ثبت نشده' : 'نمره ثبتشده ${exam['gradePoints']}/${exam['gradeOutOf']}؛ گزارش ثبتشده، تأیید مستقل نیست.'}'));
497
+ }),
498
+ ],
499
+ Text(
500
+ hasPeriod
501
+ ? 'تکلیفها و زمانهای ثبتشده'
502
+ : 'تکلیفها و امتحانها',
503
style: Theme.of(context).textTheme.titleLarge),
263
- ...items.map((raw) {
504
+ ...items
505
+ .where((raw) =>
506
+ !hasPeriod ||
507
+ (raw as Map)['kind'] != 'exam' ||
508
+ raw['taskInRange'] != true)
509
+ .map((raw) {
510
final i = raw as Map;
511
final verified = i['activityState'] == 'verified' &&
512
i['activitySource'] == 'guardian_confirmation';
@@ -276,7 +522,7 @@ class _LearningReportPageState extends State<LearningReportPage>
522
child: ListTile(
523
title: Text(i['title']?.toString() ?? ''),
524
subtitle: Text(
279
- '${faKind(i['kind']?.toString() ?? 'task')} · $state\nآخرین ثبت وضعیت: ${shortDate(i['activityAt'])}\nموعد: ${shortDate(i['dueAt'] ?? i['startsAt'])}\nبرنامه ${minutes(i['plannedDurationSeconds'])} · ثبت ${minutes(i['recordedDurationSeconds'])}${i['gradePoints'] == null ? '' : '\nنمره ${i['gradePoints']}/${i['gradeOutOf']}'}')));
525
+ '${faKind(i['kind']?.toString() ?? 'task')} · $state\nآخرین ثبت وضعیت: ${shortDate(i['activityAt'])}\nموعد: ${shortDate(i['dueAt'] ?? i['startsAt'])}\nبرنامه ${minutes(i['plannedDurationSeconds'])} · ثبت ${minutes(i['recordedDurationSeconds'])}${hasPeriod && i['taskInRange'] != true ? '\nموعد این تکلیف خارج از بازه است؛ فقط زمان ثبتشده در بازه نمایش داده میشود.' : ''}${i['gradePoints'] == null ? '' : '\nنمره ${i['gradePoints']}/${i['gradeOutOf']}'}')));
526
}),
527
],
528
TextButton(
apps/lifemate/lib/education_ui.dart
+25
-10
@@ -1,5 +1,7 @@
1
import 'dart:async';
2
+import 'dart:ui' show SemanticsRole;
3
4
+import 'package:flutter/foundation.dart' show kIsWeb;
5
import 'package:flutter/material.dart';
6
7
import 'api.dart';
@@ -595,6 +597,16 @@ class _LearningLessonPageState extends State<LearningLessonPage> {
597
final current = unit?['progress'];
598
final pending = current is Map && current['pending_sync'] == true;
599
final conflict = current is Map && current['queueStatus'] == 'conflict';
600
+ final progressLines = [
601
+ 'پیشرفت شخصی: ${current is Map ? {
602
+ 'not_started': 'شروع نشده',
603
+ 'in_progress': 'در حال یادگیری',
604
+ 'completed': 'تکمیل طبق گزارش من'
605
+ }[current['status']] ?? 'نامشخص' : 'شروع نشده'}',
606
+ if (pending) 'تغییر روی دستگاه ذخیره شده؛ تأیید سرور دریافت نشده است.',
607
+ if (current is Map && current['updatedAt'] != null)
608
+ 'آخرین ثبت سرور: ${current['updatedAt']}',
609
+ ];
610
final units = (course?['units'] as List? ?? []).whereType<Map>().toList();
611
final index = units.indexWhere((u) => u['id'] == widget.unitId);
612
void move(int to) =>
@@ -654,16 +666,19 @@ class _LearningLessonPageState extends State<LearningLessonPage> {
666
api: widget.api, unitId: widget.unitId))),
667
icon: const Icon(Icons.feedback_outlined),
668
label: const Text('گزارش ایراد این درس')),
657
- Text('پیشرفت شخصی: ${current is Map ? {
658
- 'not_started': 'شروع نشده',
659
- 'in_progress': 'در حال یادگیری',
660
- 'completed': 'تکمیل طبق گزارش من'
661
- }[current['status']] ?? 'نامشخص' : 'شروع نشده'}'),
662
- if (pending)
663
- const Text(
664
- 'تغییر روی دستگاه ذخیره شده؛ تأیید سرور دریافت نشده است.'),
665
- if (current is Map && current['updatedAt'] != null)
666
- Text('آخرین ثبت سرور: ${current['updatedAt']}'),
669
+ Semantics(
670
+ key: const ValueKey('learning-progress-announcement'),
671
+ container: true,
672
+ // Flutter disallows status + liveRegion on the same node.
673
+ // Web status has implicit ARIA live semantics; native uses the flag.
674
+ role: kIsWeb ? SemanticsRole.status : SemanticsRole.none,
675
+ liveRegion: !kIsWeb,
676
+ excludeSemantics: true,
677
+ textDirection: Directionality.of(context),
678
+ label: progressLines.join('\n'),
679
+ child: Column(
680
+ crossAxisAlignment: CrossAxisAlignment.start,
681
+ children: progressLines.map((line) => Text(line)).toList())),
682
if (conflict)
683
TextButton(
684
onPressed: busy ? null : resolve,
apps/lifemate/lib/family_management_ui.dart
new
+928
@@ -0,0 +1,928 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'package:flutter/material.dart';
5
+
6
+import 'api.dart';
7
+import 'offline_store.dart';
8
+import 'plan_sync.dart' show newMutationId;
9
+
10
+const familyRoleLabels = <String, String>{
11
+ 'parent_guardian': 'سرپرست',
12
+ 'teen_minor': 'فرزند',
13
+ 'adult_member': 'عضو بزرگسال',
14
+};
15
+final _familyUuid = RegExp(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$');
16
+bool _uuid(dynamic value) => value is String && _familyUuid.hasMatch(value);
17
+bool _version(dynamic value) =>
18
+ value is int && value > 0 && value <= 2147483647;
19
+bool _date(dynamic value) =>
20
+ value is String &&
21
+ RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) &&
22
+ DateTime.tryParse(value) != null;
23
+bool _exact(Map value, Set<String> keys) =>
24
+ value.length == keys.length && value.keys.every(keys.contains);
25
+Map<String, dynamic> _freeze(Map value) =>
26
+ Map<String, dynamic>.from(jsonDecode(jsonEncode(value)) as Map);
27
+Never _invalid() => throw const ApiException(502, 'invalid_family_response');
28
+
29
+String familyManagementError(Object error) {
30
+ if (isOfflineFailure(error)) {
31
+ return 'اتصال برقرار نیست. نتیجه عملیات ممکن است نامشخص باشد؛ وضعیت را تازه کن. تغییر خودکار یا تلاش کور انجام نمیشود.';
32
+ }
33
+ if (error is ApiException) {
34
+ if (error.statusCode == 401 || error.statusCode == 403) {
35
+ return 'نشست یا دسترسی این خانواده معتبر نیست؛ اطلاعات قبلی پاک شدند.';
36
+ }
37
+ if (error.code == 'last_admin_required') {
38
+ return 'آخرین مدیر فعال را نمیتوان حذف یا از مدیریت خارج کرد؛ ابتدا مدیریت را به بزرگسال فعال منتقل کن.';
39
+ }
40
+ if (error.code == 'age_confirmation_required' ||
41
+ error.code == 'minor_role_restricted' ||
42
+ error.code == 'minor_role_upgrade_forbidden' ||
43
+ error.code == 'minor_cannot_admin') {
44
+ return 'سن مجاز برای نقش بزرگسال باید در سرور تأیید شود؛ نوع پروفایل مجوز مدیریت نمیدهد.';
45
+ }
46
+ if (error.statusCode == 409) {
47
+ return 'نسخه یا وضعیت عضویت تغییر کرده است. ابتدا وضعیت تازه سرور را بررسی کن؛ درخواست قدیمی در صف محفوظ است.';
48
+ }
49
+ if (error.statusCode == 404) {
50
+ return 'عضویت یا دعوت دیگر در دسترس نیست؛ وضعیت تازه را دریافت کن.';
51
+ }
52
+ }
53
+ return 'عملیات با پاسخ معتبر تأیید نشد؛ ابتدا وضعیت تازه سرور را بررسی کن.';
54
+}
55
+
56
+/// Metadata-only journal for versioned family operations. Permissions, member
57
+/// names, invitation contacts and tokens are never cached in this journal.
58
+class FamilyOperationSync {
59
+ FamilyOperationSync(this.api, this.familyId, {OfflineStore? store})
60
+ : store = store ?? OfflineStore.forApi(api) {
61
+ if (!_uuid(familyId)) throw ArgumentError('Invalid family ID');
62
+ }
63
+ final HttpIdentityApi api;
64
+ final String familyId;
65
+ final OfflineStore store;
66
+ static final _tails = <String, Future<void>>{};
67
+ String get path => '/v1/families/${Uri.encodeComponent(familyId)}';
68
+
69
+ Future<void> scope() async {
70
+ if (api.cacheNamespace != store.scope) {
71
+ throw const ApiException(401, 'cache_scope_closed');
72
+ }
73
+ await store.readQueue();
74
+ if (api.cacheNamespace != store.scope) {
75
+ throw const ApiException(401, 'cache_scope_closed');
76
+ }
77
+ }
78
+
79
+ Future<Map<String, dynamic>> request(String method, String suffix,
80
+ {Map<String, dynamic>? body}) async {
81
+ await scope();
82
+ final response = await api.requestJson(method, '$path$suffix', body: body);
83
+ await scope();
84
+ return response;
85
+ }
86
+
87
+ Future<T> _serial<T>(Future<T> Function() operation) async {
88
+ final previous = _tails[store.scope];
89
+ final release = Completer<void>();
90
+ _tails[store.scope] = release.future;
91
+ if (previous != null) await previous;
92
+ try {
93
+ await scope();
94
+ return await operation();
95
+ } finally {
96
+ if (identical(_tails[store.scope], release.future)) {
97
+ _tails.remove(store.scope);
98
+ }
99
+ release.complete();
100
+ }
101
+ }
102
+
103
+ Future<void> _membership({required bool admin}) async {
104
+ final result = await request('GET', '');
105
+ if (result['id'] != familyId ||
106
+ result['is_admin'] is! bool ||
107
+ !familyRoleLabels.containsKey(result['role']) ||
108
+ (result['is_admin'] == true && result['role'] == 'teen_minor')) {
109
+ _invalid();
110
+ }
111
+ if (admin && result['is_admin'] != true) {
112
+ throw const ApiException(403, 'family_admin_required');
113
+ }
114
+ }
115
+
116
+ Map<String, dynamic> _body(String operation, String targetId, Map value) {
117
+ final keys = operation == 'role'
118
+ ? {'mutationId', 'expectedVersion', 'role'}
119
+ : operation == 'invitation_revoke'
120
+ ? {'mutationId', 'expectedVersion', 'action'}
121
+ : operation == 'admin_transfer'
122
+ ? {
123
+ 'mutationId',
124
+ 'targetUserId',
125
+ 'expectedVersion',
126
+ 'expectedActorVersion'
127
+ }
128
+ : <String>{};
129
+ if (!_uuid(targetId) ||
130
+ keys.isEmpty ||
131
+ !_exact(value, keys) ||
132
+ !_uuid(value['mutationId']) ||
133
+ !_version(value['expectedVersion']) ||
134
+ (operation == 'role' && !familyRoleLabels.containsKey(value['role'])) ||
135
+ (operation == 'invitation_revoke' && value['action'] != 'revoke') ||
136
+ (operation == 'admin_transfer' &&
137
+ (value['targetUserId'] != targetId ||
138
+ !_version(value['expectedActorVersion']) ||
139
+ targetId == api.currentUserId))) {
140
+ throw const ApiException(400, 'invalid_family_operation');
141
+ }
142
+ return _freeze(value);
143
+ }
144
+
145
+ Future<List<Map<String, dynamic>>> pending() async {
146
+ await scope();
147
+ final values = (await store.readQueue())
148
+ .where((row) =>
149
+ row['entityType'] == 'family_operation' &&
150
+ row['entityId'] == familyId)
151
+ .toList();
152
+ await scope();
153
+ return values;
154
+ }
155
+
156
+ Future<Map<String, dynamic>> submit(
157
+ String operation, String targetId, Map<String, dynamic> body) {
158
+ final frozen = _body(operation, targetId, body);
159
+ return _serial(() async {
160
+ await _membership(
161
+ admin: true); // No new operation under cached authority.
162
+ final mutation = {
163
+ 'id': frozen['mutationId'],
164
+ 'entityId': familyId,
165
+ 'entityType': 'family_operation',
166
+ 'operation': operation,
167
+ 'targetId': targetId,
168
+ 'payload': frozen
169
+ };
170
+ await store.enqueue(mutation);
171
+ return _send(mutation);
172
+ });
173
+ }
174
+
175
+ Future<Map<String, dynamic>> retry(Map<String, dynamic> mutation) =>
176
+ _serial(() async {
177
+ final saved = (await pending())
178
+ .where((row) => row['id'] == mutation['id'])
179
+ .firstOrNull;
180
+ if (saved == null || jsonEncode(saved) != jsonEncode(mutation)) {
181
+ throw const ApiException(409, 'family_pending_changed');
182
+ }
183
+ // A successful transfer removes the sender's admin flag. Its exact prior
184
+ // receipt may still be read by that active member; the server decides.
185
+ await _membership(admin: false);
186
+ return _send(saved);
187
+ });
188
+ Future<Map<String, dynamic>> _send(Map<String, dynamic> mutation) async {
189
+ final operation = mutation['operation'] as String;
190
+ final targetId = mutation['targetId'] as String;
191
+ final body = _body(operation, targetId, mutation['payload'] as Map);
192
+ final suffix = operation == 'role'
193
+ ? '/members/$targetId/role'
194
+ : operation == 'invitation_revoke'
195
+ ? '/invitations/$targetId'
196
+ : '/admin-transfer';
197
+ final result = await request(
198
+ operation == 'admin_transfer' ? 'POST' : 'PATCH', suffix,
199
+ body: body);
200
+ final ack = result['acknowledgement'];
201
+ if (ack is! Map ||
202
+ !_exact(ack,
203
+ {'mutationId', 'familyId', 'targetId', 'operation', 'status'}) ||
204
+ ack['mutationId'] != mutation['id'] ||
205
+ ack['familyId'] != familyId ||
206
+ ack['targetId'] != targetId ||
207
+ ack['operation'] != operation ||
208
+ !const {'accepted', 'already_applied'}.contains(ack['status'])) {
209
+ _invalid();
210
+ }
211
+ final accepted = ack['status'] == 'accepted';
212
+ String acceptedAt;
213
+ if (operation == 'invitation_revoke') {
214
+ final row = result['invitation'];
215
+ if (!_exact(result, {'invitation', 'acknowledgement'}) ||
216
+ row is! Map ||
217
+ !_exact(row, {'id', 'status', 'version', 'createdAt', 'expiresAt'}) ||
218
+ row['id'] != targetId ||
219
+ row['status'] != 'revoked' ||
220
+ !_version(row['version']) ||
221
+ row['version'] < body['expectedVersion'] + 1 ||
222
+ (accepted && row['version'] != body['expectedVersion'] + 1) ||
223
+ !_date(row['createdAt']) ||
224
+ !_date(row['expiresAt'])) {
225
+ _invalid();
226
+ }
227
+ acceptedAt = DateTime.now().toUtc().toIso8601String();
228
+ } else {
229
+ if (!_exact(result, {'members', 'acknowledgement'}) ||
230
+ result['members'] is! List) {
231
+ _invalid();
232
+ }
233
+ final rows = result['members'] as List;
234
+ if (rows.length != (operation == 'role' ? 1 : 2)) _invalid();
235
+ final byId = <String, Map>{};
236
+ for (final row in rows) {
237
+ if (row is! Map ||
238
+ !_exact(row, {
239
+ 'userId',
240
+ 'role',
241
+ 'isAdmin',
242
+ 'version',
243
+ 'updatedAt',
244
+ 'endedAt'
245
+ }) ||
246
+ !_uuid(row['userId']) ||
247
+ !familyRoleLabels.containsKey(row['role']) ||
248
+ row['isAdmin'] is! bool ||
249
+ !_version(row['version']) ||
250
+ !_date(row['updatedAt']) ||
251
+ (row['endedAt'] != null && !_date(row['endedAt'])) ||
252
+ byId.containsKey(row['userId'])) {
253
+ _invalid();
254
+ }
255
+ byId[row['userId'] as String] = row;
256
+ }
257
+ final target = byId[targetId];
258
+ if (target == null ||
259
+ target['version'] < body['expectedVersion'] + 1 ||
260
+ (accepted &&
261
+ (target['version'] != body['expectedVersion'] + 1 ||
262
+ target['endedAt'] != null))) {
263
+ _invalid();
264
+ }
265
+ if (operation == 'role') {
266
+ if (accepted && target['role'] != body['role']) _invalid();
267
+ } else {
268
+ final actor = byId[api.currentUserId];
269
+ if (actor == null ||
270
+ actor['version'] < body['expectedActorVersion'] + 1 ||
271
+ (accepted &&
272
+ (actor['version'] != body['expectedActorVersion'] + 1 ||
273
+ actor['isAdmin'] != false ||
274
+ actor['endedAt'] != null ||
275
+ target['isAdmin'] != true ||
276
+ target['role'] == 'teen_minor'))) {
277
+ _invalid();
278
+ }
279
+ }
280
+ acceptedAt = target['updatedAt'] as String;
281
+ }
282
+ await scope();
283
+ await store.acknowledge(mutation['id'] as String, acceptedAt: acceptedAt);
284
+ return {'acknowledgement': _freeze(ack)};
285
+ }
286
+}
287
+
288
+class FamilyManagementPage extends StatefulWidget {
289
+ const FamilyManagementPage(
290
+ {super.key, required this.api, required this.familyId});
291
+ final HttpIdentityApi api;
292
+ final String familyId;
293
+ @override
294
+ State<FamilyManagementPage> createState() => _FamilyManagementPageState();
295
+}
296
+
297
+class _FamilyManagementPageState extends State<FamilyManagementPage>
298
+ with WidgetsBindingObserver {
299
+ late final FamilyOperationSync sync;
300
+ Timer? timer;
301
+ Map<String, dynamic>? family;
302
+ List<Map<String, dynamic>> members = [], invitations = [], pending = [];
303
+ final name = TextEditingController(), contact = TextEditingController();
304
+ String contactKind = 'email', inviteRole = 'adult_member';
305
+ String? guardianId, childId, invitationCursor, nextInvitationCursor, message;
306
+ int epoch = 0;
307
+ bool loading = false, busy = false, active = true;
308
+ DateTime? refreshed;
309
+ bool get admin => family?['is_admin'] == true;
310
+ Map<String, dynamic>? get self => members
311
+ .where((row) => row['user_id'] == widget.api.currentUserId)
312
+ .firstOrNull;
313
+ bool current(int request) =>
314
+ mounted &&
315
+ active &&
316
+ epoch == request &&
317
+ widget.api.cacheNamespace == sync.store.scope;
318
+
319
+ @override
320
+ void initState() {
321
+ super.initState();
322
+ sync = FamilyOperationSync(widget.api, widget.familyId);
323
+ WidgetsBinding.instance.addObserver(this);
324
+ refresh();
325
+ timer = Timer.periodic(const Duration(seconds: 30), (_) {
326
+ if (active && !busy && !loading) refresh();
327
+ });
328
+ }
329
+
330
+ void clear({bool privateInputs = true}) {
331
+ family = null;
332
+ members = [];
333
+ invitations = [];
334
+ guardianId = null;
335
+ childId = null;
336
+ refreshed = null;
337
+ nextInvitationCursor = null;
338
+ name.clear();
339
+ if (privateInputs) contact.clear();
340
+ }
341
+
342
+ @override
343
+ void didChangeAppLifecycleState(AppLifecycleState state) {
344
+ active = state == AppLifecycleState.resumed;
345
+ ++epoch;
346
+ if (mounted) {
347
+ setState(() {
348
+ clear();
349
+ loading = false;
350
+ });
351
+ }
352
+ if (active && !busy) refresh();
353
+ }
354
+
355
+ @override
356
+ void dispose() {
357
+ ++epoch;
358
+ timer?.cancel();
359
+ WidgetsBinding.instance.removeObserver(this);
360
+ name.dispose();
361
+ contact.dispose();
362
+ super.dispose();
363
+ }
364
+
365
+ Map<String, dynamic> validateFamily(Map raw) {
366
+ if (raw['id'] != widget.familyId ||
367
+ raw['name'] is! String ||
368
+ (raw['name'] as String).trim().isEmpty ||
369
+ (raw['name'] as String).length > 120 ||
370
+ raw['is_admin'] is! bool ||
371
+ !familyRoleLabels.containsKey(raw['role']) ||
372
+ (raw['is_admin'] == true && raw['role'] == 'teen_minor')) {
373
+ _invalid();
374
+ }
375
+ return {
376
+ 'id': raw['id'],
377
+ 'name': raw['name'],
378
+ 'role': raw['role'],
379
+ 'is_admin': raw['is_admin']
380
+ };
381
+ }
382
+
383
+ Map<String, dynamic> validateMember(dynamic raw) {
384
+ if (raw is! Map ||
385
+ !_uuid(raw['user_id']) ||
386
+ !familyRoleLabels.containsKey(raw['role']) ||
387
+ raw['is_admin'] is! bool ||
388
+ (raw['display_name'] != null &&
389
+ (raw['display_name'] is! String ||
390
+ (raw['display_name'] as String).length > 120)) ||
391
+ (raw['version'] != null && !_version(raw['version'])) ||
392
+ (raw['account_disabled'] != null && raw['account_disabled'] is! bool)) {
393
+ _invalid();
394
+ }
395
+ return {
396
+ 'user_id': raw['user_id'],
397
+ 'display_name': raw['display_name'] ?? 'عضو خانواده',
398
+ 'role': raw['role'],
399
+ 'is_admin': raw['is_admin'],
400
+ 'version': raw['version'],
401
+ 'account_disabled': raw['account_disabled'] == true
402
+ };
403
+ }
404
+
405
+ Map<String, dynamic> validateInvitation(dynamic raw) {
406
+ if (raw is! Map ||
407
+ !_exact(raw, {
408
+ 'id',
409
+ 'intendedRole',
410
+ 'status',
411
+ 'version',
412
+ 'createdAt',
413
+ 'expiresAt',
414
+ 'recipientHint'
415
+ }) ||
416
+ !_uuid(raw['id']) ||
417
+ !familyRoleLabels.containsKey(raw['intendedRole']) ||
418
+ !const {'pending', 'expired'}.contains(raw['status']) ||
419
+ !_version(raw['version']) ||
420
+ !_date(raw['createdAt']) ||
421
+ !_date(raw['expiresAt']) ||
422
+ raw['recipientHint'] is! String ||
423
+ (raw['recipientHint'] as String).length > 120) {
424
+ _invalid();
425
+ }
426
+ return _freeze(raw);
427
+ }
428
+
429
+ Future<void> refresh({bool firstInvitations = false}) async {
430
+ if (!active || busy || !mounted) return;
431
+ final request = ++epoch;
432
+ if (firstInvitations) invitationCursor = null;
433
+ setState(() {
434
+ clear(privateInputs: false);
435
+ loading = true;
436
+ message = null;
437
+ });
438
+ try {
439
+ final fresh = validateFamily(await sync.request('GET', ''));
440
+ if (!current(request)) return;
441
+ final data = await sync.request('GET', '/members');
442
+ if (data['members'] is! List) _invalid();
443
+ final people = (data['members'] as List).map(validateMember).toList();
444
+ if (people.map((row) => row['user_id']).toSet().length != people.length) {
445
+ _invalid();
446
+ }
447
+ final queued = await sync.pending();
448
+ if (!current(request)) return;
449
+ List<Map<String, dynamic>> invites = [];
450
+ String? next;
451
+ if (fresh['is_admin'] == true) {
452
+ final query = Uri(queryParameters: {
453
+ 'limit': '20',
454
+ if (invitationCursor != null) 'cursor': invitationCursor!
455
+ }).query;
456
+ final result = await sync.request('GET', '/invitations?$query');
457
+ if (!_exact(result, {'invitations', 'nextCursor', 'total'}) ||
458
+ result['invitations'] is! List ||
459
+ (result['invitations'] as List).length > 20 ||
460
+ result['total'] is! int ||
461
+ result['total'] < 0 ||
462
+ (result['nextCursor'] != null && !_uuid(result['nextCursor']))) {
463
+ _invalid();
464
+ }
465
+ invites =
466
+ (result['invitations'] as List).map(validateInvitation).toList();
467
+ next = result['nextCursor'] as String?;
468
+ }
469
+ if (!current(request)) return;
470
+ setState(() {
471
+ family = fresh;
472
+ members = people;
473
+ invitations = invites;
474
+ pending = queued;
475
+ nextInvitationCursor = next;
476
+ refreshed = DateTime.now();
477
+ name.text = fresh['name'] as String;
478
+ loading = false;
479
+ });
480
+ } catch (error) {
481
+ if (!current(request)) return;
482
+ setState(() {
483
+ clear();
484
+ loading = false;
485
+ message = familyManagementError(error);
486
+ });
487
+ }
488
+ }
489
+
490
+ Future<bool> confirm(String title, String explanation) async =>
491
+ await showDialog<bool>(
492
+ context: context,
493
+ builder: (context) => Directionality(
494
+ textDirection: TextDirection.rtl,
495
+ child: AlertDialog(
496
+ title: Text(title),
497
+ content: Text(explanation),
498
+ actions: [
499
+ TextButton(
500
+ onPressed: () => Navigator.pop(context, false),
501
+ child: const Text('انصراف')),
502
+ FilledButton(
503
+ onPressed: () => Navigator.pop(context, true),
504
+ child: const Text('تأیید تغییر'))
505
+ ]))) ==
506
+ true;
507
+
508
+ Future<void> perform(Future<void> Function() operation,
509
+ {bool archived = false}) async {
510
+ if (busy || !active) return;
511
+ final request = ++epoch;
512
+ setState(() {
513
+ busy = true;
514
+ clear();
515
+ message = null;
516
+ });
517
+ String? outcome;
518
+ bool success = false;
519
+ try {
520
+ await operation();
521
+ if (!current(request)) return;
522
+ success = true;
523
+ outcome = 'عملیات در سرور تأیید شد؛ وضعیت تازه دریافت میشود.';
524
+ } catch (error) {
525
+ if (!current(request)) return;
526
+ outcome = familyManagementError(error);
527
+ } finally {
528
+ if (mounted) setState(() => busy = false);
529
+ }
530
+ if (!mounted || !active || widget.api.cacheNamespace != sync.store.scope) {
531
+ return;
532
+ }
533
+ if (archived && success) {
534
+ setState(() => message =
535
+ 'خانواده بایگانی شد؛ دعوتها و ارتباطهای سرپرستی غیرفعال شدند. دادههای خصوصی افراد حذف نشدهاند.');
536
+ return;
537
+ }
538
+ await refresh();
539
+ if (!mounted || !active || widget.api.cacheNamespace != sync.store.scope) {
540
+ return;
541
+ }
542
+ setState(() => message ??= outcome);
543
+ }
544
+
545
+ Future<void> createInvitation() async {
546
+ final recipient = contact.text.trim();
547
+ if (recipient.isEmpty || recipient.length > 254) {
548
+ setState(() => message = 'ایمیل یا شماره گیرنده را تکمیل کن.');
549
+ return;
550
+ }
551
+ final role = inviteRole, kind = contactKind;
552
+ Map<String, dynamic>? created;
553
+ await perform(() async {
554
+ created = await widget.api.createFamilyInvitation(
555
+ familyId: widget.familyId,
556
+ email: kind == 'email' ? recipient : null,
557
+ phone: kind == 'phone' ? recipient : null,
558
+ role: role);
559
+ await sync.scope();
560
+ if (!_uuid(created?['id']) ||
561
+ created?['invitationToken'] is! String ||
562
+ (created!['invitationToken'] as String).isEmpty ||
563
+ !_date(created?['expires_at'])) {
564
+ _invalid();
565
+ }
566
+ });
567
+ if (created == null ||
568
+ !mounted ||
569
+ !active ||
570
+ !admin ||
571
+ widget.api.cacheNamespace != sync.store.scope) {
572
+ return;
573
+ }
574
+ contact.clear();
575
+ final token = created!['invitationToken'] as String;
576
+ await showDialog<void>(
577
+ context: context,
578
+ builder: (context) => Directionality(
579
+ textDirection: TextDirection.rtl,
580
+ child: AlertDialog(
581
+ title: const Text('دعوت در سرور ساخته شد'),
582
+ content: SingleChildScrollView(
583
+ child: Column(
584
+ mainAxisSize: MainAxisSize.min,
585
+ crossAxisAlignment: CrossAxisAlignment.start,
586
+ children: [
587
+ const Text(
588
+ 'این کد را فقط به گیرنده موردنظر بده. ورود با تماس تأییدشده مطابق دعوت لازم است. کد در حافظه دستگاه ذخیره دائمی نمیشود.'),
589
+ SelectableText(token, textDirection: TextDirection.ltr),
590
+ const Text(
591
+ 'ارسال واقعی ایمیل یا پیامک تضمین نشده است؛ فراهمکننده پیامک باید جداگانه پیکربندی شود.'),
592
+ ])),
593
+ actions: [
594
+ TextButton(
595
+ onPressed: () => Navigator.pop(context),
596
+ child: const Text('بستن'))
597
+ ])));
598
+ }
599
+
600
+ @override
601
+ Widget build(BuildContext context) => Directionality(
602
+ textDirection: TextDirection.rtl,
603
+ child: Scaffold(
604
+ appBar: AppBar(title: const Text('مدیریت خانواده'), actions: [
605
+ IconButton(
606
+ key: const Key('family-management-refresh'),
607
+ tooltip: 'دریافت وضعیت تازه خانواده',
608
+ onPressed: busy ? null : () => refresh(),
609
+ icon: const Icon(Icons.refresh))
610
+ ]),
611
+ body: ListView(padding: const EdgeInsets.all(16), children: [
612
+ const Text(
613
+ 'نقش سرپرست یا بزرگسال بهتنهایی مدیریت خانواده نیست. مجوزهای این صفحه از عضویت فعلی سرور میآیند؛ اطلاعات خصوصی اعضا در این صفحه نمایش داده نمیشود.'),
614
+ if (loading || busy) const LinearProgressIndicator(),
615
+ Text(refreshed == null
616
+ ? 'وضعیت تازه خانواده در دسترس نیست.'
617
+ : 'آخرین دریافت: ${refreshed!.hour.toString().padLeft(2, '0')}:${refreshed!.minute.toString().padLeft(2, '0')}؛ تازهسازی هر ۳۰ ثانیه.'),
618
+ if (message != null) Text(message!),
619
+ if (family != null) ...[
620
+ Text(family!['name'] as String,
621
+ style: Theme.of(context).textTheme.titleLarge),
622
+ Text(
623
+ 'نقش عضویت شما: ${familyRoleLabels[family!['role']]}${admin ? ' · مدیر خانواده' : ''}'),
624
+ if (admin) ...[
625
+ TextField(
626
+ controller: name,
627
+ enabled: !busy,
628
+ maxLength: 120,
629
+ decoration:
630
+ const InputDecoration(labelText: 'نام خانواده')),
631
+ TextButton(
632
+ onPressed: busy
633
+ ? null
634
+ : () {
635
+ final value = name.text.trim();
636
+ if (value.isEmpty || value.length > 120) {
637
+ setState(() => message =
638
+ 'نام خانواده باید بین ۱ تا ۱۲۰ نویسه باشد.');
639
+ return;
640
+ }
641
+ perform(() async {
642
+ final result = await sync
643
+ .request('PATCH', '', body: {'name': value});
644
+ if (result['id'] != widget.familyId ||
645
+ result['name'] != value) {
646
+ _invalid();
647
+ }
648
+ });
649
+ },
650
+ child: const Text('ذخیره نام خانواده')),
651
+ TextButton(
652
+ onPressed: busy
653
+ ? null
654
+ : () async {
655
+ if (!await confirm('بایگانی خانواده',
656
+ 'دسترسی خانوادگی، دعوتهای باز و ارتباطهای سرپرستی این خانواده غیرفعال میشوند. دادههای خصوصی اعضا حذف نمیشوند.')) {
657
+ return;
658
+ }
659
+ await perform(() async {
660
+ await sync.request('DELETE', '');
661
+ }, archived: true);
662
+ },
663
+ child: const Text('بایگانی خانواده')),
664
+ ],
665
+ const Divider(),
666
+ const Text('اعضای فعال خانواده'),
667
+ ...members.map((person) => Card(
668
+ child: Padding(
669
+ padding: const EdgeInsets.all(12),
670
+ child: Column(
671
+ crossAxisAlignment: CrossAxisAlignment.start,
672
+ children: [
673
+ Text(person['display_name'] as String),
674
+ Text(
675
+ '${familyRoleLabels[person['role']]}${person['is_admin'] == true ? ' · مدیر' : ''}${person['account_disabled'] == true ? ' · حساب غیرفعال' : ''}'),
676
+ if (admin) ...[
677
+ if (person['version'] != null &&
678
+ person['account_disabled'] != true)
679
+ DropdownButtonFormField<String>(
680
+ key: Key(
681
+ 'family-member-role-${person['user_id']}'),
682
+ decoration: const InputDecoration(
683
+ labelText: 'تغییر نقش عضویت'),
684
+ hint: const Text('انتخاب نقش جدید'),
685
+ items: familyRoleLabels.entries
686
+ .where((entry) =>
687
+ entry.key != person['role'])
688
+ .map((entry) => DropdownMenuItem(
689
+ value: entry.key,
690
+ child: Text(entry.value)))
691
+ .toList(),
692
+ onChanged: busy
693
+ ? null
694
+ : (value) async {
695
+ if (value == null ||
696
+ !await confirm('تغییر نقش عضو',
697
+ 'نقش عضویت ${person['display_name']} به ${familyRoleLabels[value]} تغییر میکند. ارتباطهای سرپرستی ناسازگار ممکن است لغو شوند؛ تغییر سن و مجوزهای خصوصی را سرور کنترل میکند.')) {
698
+ return;
699
+ }
700
+ final body = {
701
+ 'mutationId': newMutationId(),
702
+ 'expectedVersion':
703
+ person['version'],
704
+ 'role': value
705
+ };
706
+ await perform(() async {
707
+ await sync.submit(
708
+ 'role',
709
+ person['user_id'] as String,
710
+ body);
711
+ });
712
+ }),
713
+ if (person['user_id'] !=
714
+ widget.api.currentUserId &&
715
+ person['role'] != 'teen_minor' &&
716
+ person['account_disabled'] != true &&
717
+ person['version'] != null &&
718
+ self?['version'] != null)
719
+ TextButton(
720
+ onPressed: busy
721
+ ? null
722
+ : () async {
723
+ final actorVersion =
724
+ self!['version'];
725
+ if (!await confirm('انتقال مدیریت',
726
+ 'مدیریت به ${person['display_name']} منتقل میشود و دسترسی مدیریت شما برداشته خواهد شد. فقط بزرگسال فعال و مجاز میتواند مدیر شود.')) {
727
+ return;
728
+ }
729
+ final body = {
730
+ 'mutationId': newMutationId(),
731
+ 'targetUserId': person['user_id'],
732
+ 'expectedVersion':
733
+ person['version'],
734
+ 'expectedActorVersion':
735
+ actorVersion
736
+ };
737
+ await perform(() async {
738
+ await sync.submit(
739
+ 'admin_transfer',
740
+ person['user_id'] as String,
741
+ body);
742
+ });
743
+ },
744
+ child: Text(
745
+ 'انتقال مدیریت به ${person['display_name']}')),
746
+ TextButton(
747
+ onPressed: busy
748
+ ? null
749
+ : () async {
750
+ if (!await confirm('پایان عضویت',
751
+ 'عضویت ${person['display_name']} و ارتباطهای سرپرستی مرتبط لغو میشود. اطلاعات خصوصی این فرد حذف نمیشود. حذف آخرین مدیر فعال مجاز نیست.')) {
752
+ return;
753
+ }
754
+ await perform(() async {
755
+ await sync.request('DELETE',
756
+ '/members/${person['user_id']}');
757
+ });
758
+ },
759
+ child: Text(
760
+ 'پایان عضویت ${person['display_name']}')),
761
+ ],
762
+ ])))),
763
+ if (admin) ...[
764
+ const Divider(),
765
+ const Text('دعوت عضو'),
766
+ DropdownButtonFormField<String>(
767
+ initialValue: contactKind,
768
+ decoration:
769
+ const InputDecoration(labelText: 'نوع تماس گیرنده'),
770
+ items: const [
771
+ DropdownMenuItem(value: 'email', child: Text('ایمیل')),
772
+ DropdownMenuItem(
773
+ value: 'phone', child: Text('شماره تلفن'))
774
+ ],
775
+ onChanged: busy
776
+ ? null
777
+ : (value) => setState(() {
778
+ contactKind = value!;
779
+ contact.clear();
780
+ })),
781
+ TextField(
782
+ controller: contact,
783
+ enabled: !busy,
784
+ textDirection: TextDirection.ltr,
785
+ keyboardType: contactKind == 'email'
786
+ ? TextInputType.emailAddress
787
+ : TextInputType.phone,
788
+ decoration: InputDecoration(
789
+ labelText: contactKind == 'email'
790
+ ? 'ایمیل گیرنده'
791
+ : 'شماره تلفن با کد کشور')),
792
+ DropdownButtonFormField<String>(
793
+ initialValue: inviteRole,
794
+ decoration: const InputDecoration(labelText: 'نقش موردنظر'),
795
+ items: familyRoleLabels.entries
796
+ .map((entry) => DropdownMenuItem(
797
+ value: entry.key, child: Text(entry.value)))
798
+ .toList(),
799
+ onChanged: busy
800
+ ? null
801
+ : (value) => setState(() => inviteRole = value!)),
802
+ FilledButton(
803
+ onPressed: busy ? null : createInvitation,
804
+ child: const Text('ساخت دعوت')),
805
+ const Text(
806
+ 'دعوت، دسترسی خودکار به داده خصوصی یا ارتباط سرپرستی ایجاد نمیکند. ایمیل اجباری نیست؛ ارسال پیامک وابسته به فراهمکننده جداگانه است.'),
807
+ const Text('دعوتهای باز'),
808
+ ...invitations.map((invite) => ListTile(
809
+ title: Text(invite['recipientHint'] as String),
810
+ subtitle: Text(
811
+ '${familyRoleLabels[invite['intendedRole']]} · ${invite['status'] == 'expired' ? 'منقضیشده' : 'منتظر پذیرش'} · تا ${invite['expiresAt']}'),
812
+ trailing: TextButton(
813
+ onPressed: busy
814
+ ? null
815
+ : () async {
816
+ if (!await confirm('لغو دعوت',
817
+ 'کد این دعوت دیگر قابل پذیرش نخواهد بود.')) {
818
+ return;
819
+ }
820
+ await perform(() async {
821
+ await sync.submit('invitation_revoke',
822
+ invite['id'] as String, {
823
+ 'mutationId': newMutationId(),
824
+ 'expectedVersion': invite['version'],
825
+ 'action': 'revoke'
826
+ });
827
+ });
828
+ },
829
+ child: const Text('لغو دعوت')))),
830
+ if (nextInvitationCursor != null)
831
+ TextButton(
832
+ onPressed: busy
833
+ ? null
834
+ : () {
835
+ invitationCursor = nextInvitationCursor;
836
+ refresh();
837
+ },
838
+ child: const Text('دعوتهای بعدی')),
839
+ if (invitationCursor != null)
840
+ TextButton(
841
+ onPressed:
842
+ busy ? null : () => refresh(firstInvitations: true),
843
+ child: const Text('صفحه اول دعوتها')),
844
+ const Divider(),
845
+ const Text('ارتباط مجاز سرپرست و فرزند'),
846
+ const Text(
847
+ 'این فرم فقط ارتباط را فعال یا لغو میکند؛ هیچ اطلاعات خصوصی یا وضعیت مطالعه پنهانی را نمایش نمیدهد.'),
848
+ DropdownButtonFormField<String>(
849
+ initialValue: guardianId,
850
+ decoration: const InputDecoration(labelText: 'سرپرست'),
851
+ items: members
852
+ .where((person) =>
853
+ person['role'] == 'parent_guardian' &&
854
+ person['account_disabled'] != true)
855
+ .map((person) => DropdownMenuItem(
856
+ value: person['user_id'] as String,
857
+ child: Text(person['display_name'] as String)))
858
+ .toList(),
859
+ onChanged: busy
860
+ ? null
861
+ : (value) => setState(() => guardianId = value)),
862
+ DropdownButtonFormField<String>(
863
+ initialValue: childId,
864
+ decoration: const InputDecoration(labelText: 'فرزند'),
865
+ items: members
866
+ .where((person) =>
867
+ person['role'] == 'teen_minor' &&
868
+ person['account_disabled'] != true)
869
+ .map((person) => DropdownMenuItem(
870
+ value: person['user_id'] as String,
871
+ child: Text(person['display_name'] as String)))
872
+ .toList(),
873
+ onChanged: busy
874
+ ? null
875
+ : (value) => setState(() => childId = value)),
876
+ Wrap(
877
+ spacing: 8,
878
+ children: ['POST', 'DELETE']
879
+ .map((method) => TextButton(
880
+ onPressed: busy ||
881
+ guardianId == null ||
882
+ childId == null
883
+ ? null
884
+ : () async {
885
+ final body = {
886
+ 'guardianUserId': guardianId,
887
+ 'minorUserId': childId
888
+ };
889
+ if (!await confirm(
890
+ method == 'POST'
891
+ ? 'فعالکردن ارتباط سرپرستی'
892
+ : 'لغو ارتباط سرپرستی',
893
+ 'مجوزهای خانوادگی همین سرپرست و فرزند طبق سیاست سرور تغییر میکنند؛ دادههای خصوصی خودکار به اشتراک گذاشته نمیشوند.')) {
894
+ return;
895
+ }
896
+ await perform(() async {
897
+ await sync.request(method, '/guardians',
898
+ body: body);
899
+ });
900
+ },
901
+ child: Text(method == 'POST'
902
+ ? 'فعالکردن ارتباط'
903
+ : 'لغو ارتباط')))
904
+ .toList()),
905
+ ],
906
+ ],
907
+ if (pending.isNotEmpty) ...[
908
+ const Divider(),
909
+ Text(
910
+ '${pending.length} عملیات نسخهدار بدون تأیید نهایی در صف دستگاه است. فقط شناسه و نسخه نگهداری میشود؛ ارسال خودکار انجام نمیشود.'),
911
+ ...pending.map((queued) => ListTile(
912
+ title: Text(queued['operation'] == 'role'
913
+ ? 'تغییر نقش عضویت'
914
+ : queued['operation'] == 'admin_transfer'
915
+ ? 'انتقال مدیریت'
916
+ : 'لغو دعوت'),
917
+ subtitle: const Text(
918
+ 'تلاش دستی با همان درخواست؛ ممکن است قبلاً در سرور اجرا شده باشد.'),
919
+ trailing: TextButton(
920
+ onPressed: busy || family == null
921
+ ? null
922
+ : () => perform(() async {
923
+ await sync.retry(queued);
924
+ }),
925
+ child: const Text('دریافت دوباره تأیید')))),
926
+ ],
927
+ ])));
928
+}
apps/lifemate/lib/learning_feedback_ui.dart
+9
-1
@@ -15,6 +15,14 @@ const feedbackCategories = {
15
'topic_request': 'پیشنهاد موضوع آموزشی',
16
};
17
18
+const feedbackStatusLabels = {
19
+ 'received': 'دریافتشده',
20
+ 'triaged': 'بررسی اولیه',
21
+ 'planned': 'در برنامه بررسی و توسعه',
22
+ 'released': 'انتشار ثبتشده',
23
+ 'declined': 'پذیرفتهنشده',
24
+};
25
+
26
/// Explicitly chosen feedback only; never extracts private conversations.
27
class LearningFeedbackSync {
28
LearningFeedbackSync(this.api, {OfflineStore? store})
@@ -305,7 +313,7 @@ class _LearningFeedbackPageState extends State<LearningFeedbackPage> {
313
? row['summary']?.toString() ?? 'بازخورد'
314
: 'رضایت ارسال پس گرفته شد'),
315
subtitle: Text(row['withdrawnAt'] == null
308
- ? 'وضعیت بررسی: ${row['status'] ?? 'دریافتشده'}'
316
+ ? 'وضعیت بررسی: ${feedbackStatusLabels[row['status']] ?? 'نامشخص'}'
317
: 'متن بازخورد حذف شده است.'),
318
trailing: row['withdrawnAt'] != null
319
? null
apps/lifemate/lib/learning_goal_sync.dart
new
+365
@@ -0,0 +1,365 @@
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
+/// Private goal intent is persisted before delivery, scoped to API+account.
9
+/// Acknowledgement and current server state are distinct on an old retry.
10
+class LearningGoalSync {
11
+ LearningGoalSync(this.api, {OfflineStore? store})
12
+ : store = store ?? OfflineStore.forApi(api);
13
+ final HttpIdentityApi api;
14
+ final OfflineStore store;
15
+ static final _tails = <String, Future<void>>{};
16
+ static const _cache = 'learning_goals';
17
+ static const _meta = 'learning_goals_received';
18
+ static final _uuid = RegExp(r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$',
19
+ caseSensitive: false);
20
+ void _scope() {
21
+ if (api.cacheNamespace != store.scope) {
22
+ throw const ApiException(401, 'cache_scope_closed');
23
+ }
24
+ }
25
+
26
+ Future<T> _serial<T>(Future<T> Function() run) {
27
+ final previous = _tails[store.scope], release = Completer<void>();
28
+ _tails[store.scope] = release.future;
29
+ return (() async {
30
+ if (previous != null) await previous;
31
+ try {
32
+ _scope();
33
+ await store.readQueue();
34
+ _scope();
35
+ final result = await run();
36
+ _scope();
37
+ return result;
38
+ } finally {
39
+ if (identical(_tails[store.scope], release.future)) {
40
+ _tails.remove(store.scope);
41
+ }
42
+ release.complete();
43
+ }
44
+ })();
45
+ }
46
+
47
+ static bool _time(dynamic value) =>
48
+ value is String &&
49
+ RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) &&
50
+ DateTime.tryParse(value) != null;
51
+ Map<String, dynamic> _goal(dynamic raw) {
52
+ if (raw is! Map ||
53
+ raw['id'] is! String ||
54
+ !_uuid.hasMatch(raw['id']) ||
55
+ raw['owner_user_id'] != api.currentUserId ||
56
+ raw['title'] is! String ||
57
+ (raw['title'] as String).trim().isEmpty ||
58
+ (raw['title'] as String).length > 240 ||
59
+ (raw['title'] as String).contains('\u0000') ||
60
+ (raw['target'] != null &&
61
+ (raw['target'] is! String ||
62
+ (raw['target'] as String).length > 1000 ||
63
+ (raw['target'] as String).contains('\u0000'))) ||
64
+ (raw['subject_id'] != null &&
65
+ (raw['subject_id'] is! String ||
66
+ !_uuid.hasMatch(raw['subject_id'] as String))) ||
67
+ raw['version'] is! int ||
68
+ raw['version'] < 1 ||
69
+ !['active', 'completed', 'archived'].contains(raw['status']) ||
70
+ !_time(raw['created_at']) ||
71
+ !_time(raw['updated_at']) ||
72
+ (raw['status'] == 'archived'
73
+ ? !_time(raw['archived_at'])
74
+ : raw['archived_at'] != null)) {
75
+ throw const ApiException(502, 'invalid_learning_goal');
76
+ }
77
+ return {...Map<String, dynamic>.from(raw), 'pending_sync': false};
78
+ }
79
+
80
+ Future<List<Map<String, dynamic>>> pending() async {
81
+ _scope();
82
+ final queue = await store.readQueue();
83
+ _scope();
84
+ return queue.where((m) => m['entityType'] == 'learning_goal').toList();
85
+ }
86
+
87
+ Future<Map<String, dynamic>> read() => _serial(() async {
88
+ var offline = false;
89
+ late List<Map<String, dynamic>> goals;
90
+ try {
91
+ final response = await api.requestJson('GET', '/v1/learning/goals');
92
+ _scope();
93
+ if (response['items'] is! List || !_time(response['fetchedAt'])) {
94
+ throw const ApiException(502, 'invalid_learning_goals');
95
+ }
96
+ goals = (response['items'] as List).map(_goal).toList();
97
+ if (goals.map((g) => g['id']).toSet().length != goals.length ||
98
+ goals.any((g) => g['status'] == 'archived')) {
99
+ throw const ApiException(502, 'invalid_learning_goals');
100
+ }
101
+ await store.writeList(_cache, goals);
102
+ await store.writeList(_meta, [
103
+ {'fetchedAt': response['fetchedAt']}
104
+ ]);
105
+ } catch (error) {
106
+ _scope();
107
+ if (error is ApiException && error.statusCode == 403) {
108
+ // A denied read must never fall back to yesterday's private list.
109
+ // Retain intent in the shared journal for explicit recovery.
110
+ await store.writeList(_cache, []);
111
+ await store.writeList(_meta, []);
112
+ _scope();
113
+ }
114
+ if (!isOfflineFailure(error)) rethrow;
115
+ goals = (await store.readList(_cache)).map(_goal).toList();
116
+ offline = true;
117
+ }
118
+ final byId = {
119
+ for (final g in goals) g['id']: Map<String, dynamic>.from(g)
120
+ };
121
+ final mutations = await pending();
122
+ for (final mutation in mutations) {
123
+ _validateMutation(mutation);
124
+ final body = Map<String, dynamic>.from(mutation['payload'] as Map);
125
+ final id = mutation['entityId'];
126
+ final previous = byId[id];
127
+ if (previous == null && mutation['operation'] != 'create') continue;
128
+ byId[id] = {
129
+ ...?previous,
130
+ 'id': id,
131
+ 'owner_user_id': api.currentUserId,
132
+ 'title': body['title'] ?? previous?['title'],
133
+ 'target': body.containsKey('target')
134
+ ? body['target']
135
+ : previous?['target'],
136
+ 'status': body['status'] ?? previous?['status'] ?? 'active',
137
+ 'version': body['expectedVersion'],
138
+ 'pending_sync': true,
139
+ 'pending_archive': mutation['operation'] == 'archive',
140
+ 'queueStatus': mutation['queueStatus'],
141
+ };
142
+ }
143
+ final meta = await store.readList(_meta);
144
+ _scope();
145
+ final visible =
146
+ byId.values.where((g) => g['status'] != 'archived').toList();
147
+ final visibleIds = visible.map((g) => g['id']).toSet();
148
+ return {
149
+ 'items': visible,
150
+ 'offline': offline,
151
+ 'fetchedAt': meta.firstOrNull?['fetchedAt'],
152
+ 'pendingCount': mutations.length,
153
+ 'unlistedPending': [
154
+ for (final mutation in mutations)
155
+ if (!visibleIds.contains(mutation['entityId']))
156
+ {
157
+ 'id': mutation['entityId'],
158
+ 'operation': mutation['operation'],
159
+ 'queueStatus': mutation['queueStatus']
160
+ }
161
+ ]
162
+ };
163
+ });
164
+ Future<Map<String, dynamic>> create(
165
+ {required String title, String? target, String? subjectId}) {
166
+ final id = newMutationId();
167
+ return _mutate(id, 'create', {
168
+ 'id': id,
169
+ 'title': title,
170
+ 'target': target,
171
+ 'subjectId': subjectId,
172
+ 'expectedVersion': 0
173
+ });
174
+ }
175
+
176
+ Future<Map<String, dynamic>> update(
177
+ String id, int version, Map<String, dynamic> changes) =>
178
+ _mutate(id, 'update', {...changes, 'expectedVersion': version});
179
+ Future<Map<String, dynamic>> archive(String id, int version) =>
180
+ _mutate(id, 'archive', {'expectedVersion': version});
181
+ Future<Map<String, dynamic>> _mutate(
182
+ String id, String operation, Map<String, dynamic> raw) {
183
+ id = id.toLowerCase();
184
+ final normalized = {...raw};
185
+ if (normalized['title'] is String) {
186
+ normalized['title'] = (normalized['title'] as String).trim();
187
+ }
188
+ if (normalized['target'] is String) {
189
+ final target = (normalized['target'] as String).trim();
190
+ normalized['target'] = target.isEmpty ? null : target;
191
+ }
192
+ if (normalized['subjectId'] is String) {
193
+ normalized['subjectId'] =
194
+ (normalized['subjectId'] as String).toLowerCase();
195
+ }
196
+ final body =
197
+ jsonDecode(jsonEncode({...normalized, 'mutationId': newMutationId()}))
198
+ as Map<String, dynamic>;
199
+ return _serial(() async {
200
+ _validateBody(id, operation, body);
201
+ if ((await pending()).any((m) => m['entityId'] == id)) {
202
+ throw const ApiException(409, 'goal_sync_pending');
203
+ }
204
+ final mutation = {
205
+ 'id': body['mutationId'],
206
+ 'entityId': id,
207
+ 'entityType': 'learning_goal',
208
+ 'operation': operation,
209
+ 'expectedVersion': body['expectedVersion'],
210
+ 'payload': body
211
+ };
212
+ await store.enqueue(mutation);
213
+ try {
214
+ return {'queued': false, 'goal': await _send(mutation)};
215
+ } catch (error) {
216
+ _scope();
217
+ if (!isOfflineFailure(error)) rethrow;
218
+ return {'queued': true, 'goalId': id};
219
+ }
220
+ });
221
+ }
222
+
223
+ void _validateBody(String id, String operation, Map body,
224
+ {String code = 'invalid_goal_input'}) {
225
+ final allowed = {
226
+ 'mutationId',
227
+ 'expectedVersion',
228
+ if (operation == 'create') 'id',
229
+ if (operation != 'archive') ...['title', 'target', 'subjectId', 'status'],
230
+ };
231
+ final version = body['expectedVersion'];
232
+ if (!_uuid.hasMatch(id) ||
233
+ !['create', 'update', 'archive'].contains(operation) ||
234
+ body.keys.any((key) => !allowed.contains(key)) ||
235
+ body['mutationId'] is! String ||
236
+ !_uuid.hasMatch(body['mutationId'] as String) ||
237
+ version is! int ||
238
+ version < 0 ||
239
+ version >= 2147483647 ||
240
+ (operation == 'create'
241
+ ? (version != 0 || body['id'] != id || !body.containsKey('title'))
242
+ : version == 0) ||
243
+ (operation == 'update' &&
244
+ !['title', 'target', 'subjectId', 'status']
245
+ .any(body.containsKey)) ||
246
+ (body.containsKey('title') &&
247
+ (body['title'] is! String ||
248
+ (body['title'] as String).trim().isEmpty ||
249
+ (body['title'] as String).length > 240 ||
250
+ (body['title'] as String).contains('\u0000'))) ||
251
+ (body['target'] != null &&
252
+ (body['target'] is! String ||
253
+ (body['target'] as String).length > 1000 ||
254
+ (body['target'] as String).contains('\u0000'))) ||
255
+ (body['subjectId'] != null &&
256
+ (body['subjectId'] is! String ||
257
+ !_uuid.hasMatch(body['subjectId'] as String))) ||
258
+ (body.containsKey('status') &&
259
+ !['active', 'completed'].contains(body['status']))) {
260
+ throw ApiException(400, code);
261
+ }
262
+ }
263
+
264
+ void _validateMutation(Map<String, dynamic> mutation) {
265
+ if (mutation['entityType'] != 'learning_goal' ||
266
+ mutation['entityId'] is! String ||
267
+ mutation['operation'] is! String ||
268
+ mutation['payload'] is! Map ||
269
+ mutation['payload']['mutationId'] != mutation['id'] ||
270
+ mutation['payload']['expectedVersion'] != mutation['expectedVersion']) {
271
+ throw const ApiException(422, 'invalid_goal_mutation');
272
+ }
273
+ _validateBody(mutation['entityId'] as String,
274
+ mutation['operation'] as String, mutation['payload'] as Map,
275
+ code: 'invalid_goal_mutation');
276
+ }
277
+
278
+ Future<Map<String, dynamic>> _send(Map<String, dynamic> mutation) async {
279
+ _validateMutation(mutation);
280
+ final body = Map<String, dynamic>.from(mutation['payload'] as Map);
281
+ final id = mutation['entityId'], operation = mutation['operation'];
282
+ if (mutation['entityType'] != 'learning_goal' ||
283
+ !['create', 'update', 'archive'].contains(operation) ||
284
+ body['mutationId'] != mutation['id'] ||
285
+ id is! String ||
286
+ !_uuid.hasMatch(id) ||
287
+ body['expectedVersion'] is! int ||
288
+ body['expectedVersion'] != mutation['expectedVersion'] ||
289
+ (operation == 'create' &&
290
+ (body['id'] != id || body['expectedVersion'] != 0))) {
291
+ throw const ApiException(422, 'invalid_goal_mutation');
292
+ }
293
+ late Map<String, dynamic> response;
294
+ try {
295
+ response = await api.requestJson(
296
+ operation == 'create'
297
+ ? 'POST'
298
+ : operation == 'update'
299
+ ? 'PATCH'
300
+ : 'DELETE',
301
+ '/v1/learning/goals${operation == 'create' ? '' : '/$id'}',
302
+ body: body);
303
+ _scope();
304
+ } catch (error) {
305
+ _scope();
306
+ if (error is ApiException && error.statusCode == 403) {
307
+ await store.writeList(_cache, []);
308
+ await store.writeList(_meta, []);
309
+ _scope();
310
+ }
311
+ if (error is ApiException && error.statusCode == 409) {
312
+ await store.markQueued(mutation['id'] as String, 'conflict',
313
+ error: error.code);
314
+ }
315
+ rethrow;
316
+ }
317
+ final ack = response['acknowledgement'];
318
+ final goal = _goal(response['goal']);
319
+ if (goal['id'] != id ||
320
+ ack is! Map ||
321
+ ack['mutationId'] != mutation['id'] ||
322
+ ack['goalId'] != id ||
323
+ ack['operation'] != operation ||
324
+ ack['appliedVersion'] != body['expectedVersion'] + 1 ||
325
+ goal['version'] < ack['appliedVersion'] ||
326
+ !_time(ack['acceptedAt']) ||
327
+ !['accepted', 'already_applied'].contains(ack['status'])) {
328
+ throw const ApiException(502, 'invalid_goal_acknowledgement');
329
+ }
330
+ if (goal['version'] == ack['appliedVersion']) {
331
+ if ((operation == 'archive' && goal['status'] != 'archived') ||
332
+ ['title', 'target', 'subjectId', 'status'].any((key) =>
333
+ body.containsKey(key) &&
334
+ goal[key == 'subjectId' ? 'subject_id' : key] != body[key])) {
335
+ throw const ApiException(502, 'invalid_goal_acknowledgement');
336
+ }
337
+ }
338
+ await store.acknowledge(mutation['id'] as String,
339
+ item: goal, acceptedAt: ack['acceptedAt'] as String, cacheKey: _cache);
340
+ _scope();
341
+ return goal;
342
+ }
343
+
344
+ Future<void> flush() => _serial(() async {
345
+ for (final mutation in await pending()) {
346
+ if (mutation['queueStatus'] == 'conflict') {
347
+ throw const ApiException(409, 'goal_version_conflict');
348
+ }
349
+ await _send(mutation);
350
+ }
351
+ });
352
+ Future<void> useServer(String id) => _serial(() async {
353
+ final response = await api.requestJson('GET', '/v1/learning/goals/$id');
354
+ _scope();
355
+ final server = _goal(response);
356
+ if (server['id'] != id ||
357
+ (await store.readQueue()).any((m) =>
358
+ m['entityId'] == id && m['entityType'] != 'learning_goal')) {
359
+ throw const ApiException(409, 'sync_entity_collision');
360
+ }
361
+ await store.discardEntityChanges(id,
362
+ serverItem: server, cacheKey: _cache, entityType: 'learning_goal');
363
+ _scope();
364
+ });
365
+}
apps/lifemate/lib/learning_goals_ui.dart
new
+875
@@ -0,0 +1,875 @@
1
+import 'package:flutter/material.dart';
2
+
3
+import 'api.dart';
4
+import 'learning_goal_sync.dart';
5
+import 'offline_store.dart' show isOfflineFailure;
6
+
7
+bool _goalAuthFailure(Object error) =>
8
+ error is ApiException &&
9
+ (error.statusCode == 401 || error.statusCode == 403);
10
+
11
+String _goalError(Object error) {
12
+ if (isOfflineFailure(error)) {
13
+ return 'اتصال برقرار نیست؛ تغییر ذخیرهشده هنوز تأیید سرور ندارد.';
14
+ }
15
+ if (_goalAuthFailure(error)) {
16
+ return 'نشست یا دسترسی معتبر نیست؛ هدفهای خصوصی قبلی از صفحه پاک شدند.';
17
+ }
18
+ if (error is ApiException && error.statusCode == 409) {
19
+ return 'این هدف یک تغییر معلق یا تعارض نسخه دارد؛ ابتدا همگامسازی و نسخه سرور را بررسی کن.';
20
+ }
21
+ return 'عملیات با پاسخ معتبر سرور تأیید نشد؛ وضعیت را تازه کن.';
22
+}
23
+
24
+class LearningGoalsPage extends StatefulWidget {
25
+ const LearningGoalsPage({super.key, required this.api});
26
+ final HttpIdentityApi api;
27
+ @override
28
+ State<LearningGoalsPage> createState() => _LearningGoalsPageState();
29
+}
30
+
31
+class _LearningGoalsPageState extends State<LearningGoalsPage>
32
+ with WidgetsBindingObserver {
33
+ late final LearningGoalSync sync;
34
+ Map<String, dynamic>? snapshot;
35
+ String? error;
36
+ bool busy = false, editing = false, active = true, stale = false;
37
+ int epoch = 0;
38
+ BuildContext? privateDialog;
39
+
40
+ bool current(int request) => mounted && active && epoch == request;
41
+ @override
42
+ void initState() {
43
+ super.initState();
44
+ sync = LearningGoalSync(widget.api);
45
+ WidgetsBinding.instance.addObserver(this);
46
+ load();
47
+ }
48
+
49
+ @override
50
+ void dispose() {
51
+ ++epoch;
52
+ WidgetsBinding.instance.removeObserver(this);
53
+ super.dispose();
54
+ }
55
+
56
+ void closePrivateDialog() {
57
+ final dialog = privateDialog;
58
+ privateDialog = null;
59
+ if (dialog?.mounted != true) return;
60
+ final route = ModalRoute.of(dialog!);
61
+ if (route != null && route.isActive) {
62
+ Navigator.of(dialog).removeRoute(route);
63
+ }
64
+ }
65
+
66
+ @override
67
+ void didChangeAppLifecycleState(AppLifecycleState state) {
68
+ active = state == AppLifecycleState.resumed;
69
+ ++epoch;
70
+ if (!active) closePrivateDialog();
71
+ if (mounted) {
72
+ setState(() {
73
+ snapshot = null;
74
+ busy = false;
75
+ editing = false;
76
+ stale = false;
77
+ });
78
+ }
79
+ if (active) load();
80
+ }
81
+
82
+ Future<void> load({bool retry = false}) async {
83
+ if (busy || editing || !active) return;
84
+ final request = ++epoch;
85
+ setState(() => busy = true);
86
+ try {
87
+ if (retry) await sync.flush();
88
+ final value = await sync.read();
89
+ if (current(request)) {
90
+ setState(() {
91
+ snapshot = value;
92
+ error = null;
93
+ stale = false;
94
+ });
95
+ }
96
+ } catch (e) {
97
+ if (current(request)) {
98
+ setState(() {
99
+ if (_goalAuthFailure(e)) snapshot = null;
100
+ stale = snapshot != null;
101
+ error = _goalError(e);
102
+ });
103
+ }
104
+ } finally {
105
+ if (current(request)) setState(() => busy = false);
106
+ }
107
+ }
108
+
109
+ Future<void> edit([Map<String, dynamic>? goal]) async {
110
+ if (busy || editing || !active) return;
111
+ final request = ++epoch;
112
+ setState(() => editing = true);
113
+ final result = await showDialog<Map<String, dynamic>>(
114
+ context: context,
115
+ barrierDismissible: false,
116
+ builder: (dialog) {
117
+ privateDialog = dialog;
118
+ return _LearningGoalEditor(
119
+ sync: sync,
120
+ goal: goal,
121
+ onAuthFailure: (e) {
122
+ if (!current(request)) return;
123
+ setState(() {
124
+ snapshot = null;
125
+ error = _goalError(e);
126
+ stale = false;
127
+ });
128
+ closePrivateDialog();
129
+ });
130
+ });
131
+ privateDialog = null;
132
+ if (!mounted || !current(request)) return;
133
+ setState(() => editing = false);
134
+ if (result == null) {
135
+ if (snapshot != null) await load();
136
+ return;
137
+ }
138
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
139
+ content: Text(result['queued'] == true
140
+ ? 'هدف روی دستگاه نگهداری شد؛ تأیید سرور هنوز دریافت نشده است.'
141
+ : 'هدف در سرور ثبت و تأیید شد.')));
142
+ await load();
143
+ }
144
+
145
+ Future<bool> confirm(String title, String description, String action) async =>
146
+ await showDialog<bool>(
147
+ context: context,
148
+ builder: (dialog) => Directionality(
149
+ textDirection: TextDirection.rtl,
150
+ child: AlertDialog(
151
+ title: Text(title),
152
+ content: Text(description),
153
+ actions: [
154
+ TextButton(
155
+ onPressed: () => Navigator.pop(dialog, false),
156
+ child: const Text('انصراف')),
157
+ FilledButton(
158
+ onPressed: () => Navigator.pop(dialog, true),
159
+ child: Text(action))
160
+ ]))) ==
161
+ true;
162
+
163
+ Future<void> change(Map<String, dynamic> goal, {bool archive = false}) async {
164
+ if (busy || editing || !active) return;
165
+ if (archive &&
166
+ !await confirm(
167
+ 'بایگانی هدف؟',
168
+ 'هدف از فهرست جاری کنار میرود؛ سابقه پیشرفت مرتبط نگهداری میشود.',
169
+ 'بایگانی')) {
170
+ return;
171
+ }
172
+ if (!mounted || !active || busy) return;
173
+ final request = ++epoch;
174
+ setState(() => busy = true);
175
+ Object? failed;
176
+ try {
177
+ final result = archive
178
+ ? await sync.archive(goal['id'] as String, goal['version'] as int)
179
+ : await sync.update(goal['id'] as String, goal['version'] as int, {
180
+ 'status': goal['status'] == 'completed' ? 'active' : 'completed'
181
+ });
182
+ if (mounted && current(request)) {
183
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
184
+ content: Text(result['queued'] == true
185
+ ? 'تغییر ذخیره شد؛ هنوز به تأیید سرور نرسیده است.'
186
+ : 'تغییر در سرور تأیید شد.')));
187
+ }
188
+ } catch (e) {
189
+ failed = e;
190
+ }
191
+ if (!current(request)) return;
192
+ setState(() => busy = false);
193
+ if (failed == null || !_goalAuthFailure(failed)) await load();
194
+ if (failed != null && mounted && active) {
195
+ setState(() {
196
+ if (_goalAuthFailure(failed!)) snapshot = null;
197
+ stale = snapshot != null;
198
+ error = _goalError(failed);
199
+ });
200
+ }
201
+ }
202
+
203
+ Future<void> useServer(Map<String, dynamic> goal) async {
204
+ if (busy ||
205
+ !active ||
206
+ !await confirm(
207
+ 'استفاده از نسخه سرور؟',
208
+ 'تغییر محلی در سابقه بازیابی نگهداری میشود و نسخه فعلی سرور جای آن را میگیرد.',
209
+ 'استفاده از سرور')) {
210
+ return;
211
+ }
212
+ if (!mounted || !active || busy) return;
213
+ final request = ++epoch;
214
+ setState(() => busy = true);
215
+ try {
216
+ await sync.useServer(goal['id'] as String);
217
+ } catch (e) {
218
+ if (current(request)) {
219
+ setState(() {
220
+ if (_goalAuthFailure(e)) snapshot = null;
221
+ error = _goalError(e);
222
+ stale = snapshot != null;
223
+ });
224
+ }
225
+ return;
226
+ } finally {
227
+ if (current(request)) setState(() => busy = false);
228
+ }
229
+ if (current(request)) await load();
230
+ }
231
+
232
+ @override
233
+ Widget build(BuildContext context) {
234
+ final goals = (snapshot?['items'] as List? ?? []).whereType<Map>().toList();
235
+ final pending = snapshot?['pendingCount'] ??
236
+ goals.where((g) => g['pending_sync'] == true).length;
237
+ final unlisted =
238
+ (snapshot?['unlistedPending'] as List? ?? []).whereType<Map>();
239
+ return Directionality(
240
+ textDirection: TextDirection.rtl,
241
+ child: Scaffold(
242
+ appBar: AppBar(title: const Text('هدفهای یادگیری')),
243
+ body: ListView(padding: const EdgeInsets.all(16), children: [
244
+ const Text(
245
+ 'هدفها و نتیجه مورد نظر خصوصیاند؛ عضویت خانواده اجازه دیدن آنها را ایجاد نمیکند.'),
246
+ const Text('تکمیل هدف، گزارش خودت است و اثبات یادگیری نیست.'),
247
+ if (busy) const LinearProgressIndicator(),
248
+ if (error != null) Text(error!),
249
+ if (stale)
250
+ const Text('تازهسازی ناموفق؛ این داده ممکن است قدیمی باشد.'),
251
+ if (snapshot?['offline'] == true)
252
+ const Text('آفلاین؛ داده ذخیرهشده ممکن است قدیمی باشد.'),
253
+ if (snapshot?['fetchedAt'] != null)
254
+ Text('آخرین دریافت سرور: ${snapshot!['fetchedAt']}'),
255
+ if (snapshot != null) Text('تغییر ارسالنشده: $pending'),
256
+ FilledButton.icon(
257
+ onPressed: busy || editing || !active ? null : () => edit(),
258
+ icon: const Icon(Icons.add),
259
+ label: const Text('هدف جدید')),
260
+ OutlinedButton(
261
+ onPressed: busy || editing || !active
262
+ ? null
263
+ : () => load(retry: true),
264
+ child: const Text('همگامسازی و تازهسازی')),
265
+ if (!busy && snapshot != null && goals.isEmpty)
266
+ const Text('هنوز هدف جاری ثبت نشده است.'),
267
+ ...unlisted.map((row) => ListTile(
268
+ title: const Text('تغییر معلق برای هدف خارج از فهرست جاری'),
269
+ subtitle: const Text(
270
+ 'درخواست محلی حفظ شده است؛ بازیابی نسخه سرور به انتخاب شما نیاز دارد.'),
271
+ trailing: TextButton(
272
+ onPressed: busy
273
+ ? null
274
+ : () => useServer(Map<String, dynamic>.from(row)),
275
+ child: const Text('بررسی نسخه سرور')))),
276
+ ...goals.map((raw) {
277
+ final goal = Map<String, dynamic>.from(raw);
278
+ final blocked =
279
+ busy || !active || stale || goal['pending_sync'] == true;
280
+ return Card(
281
+ child: Padding(
282
+ padding: const EdgeInsets.all(12),
283
+ child: Column(
284
+ crossAxisAlignment: CrossAxisAlignment.start,
285
+ children: [
286
+ Text(goal['title']?.toString() ?? '',
287
+ style:
288
+ Theme.of(context).textTheme.titleMedium),
289
+ if (goal['target'] != null)
290
+ Text(goal['target'].toString()),
291
+ Text(goal['status'] == 'completed'
292
+ ? 'تکمیل طبق گزارش من'
293
+ : 'هدف فعال'),
294
+ if (goal['pending_sync'] == true)
295
+ Text(goal['pending_archive'] == true
296
+ ? 'بایگانی در انتظار تأیید سرور'
297
+ : 'تغییر در انتظار تأیید سرور'),
298
+ if (goal['updated_at'] != null &&
299
+ goal['pending_sync'] != true)
300
+ Text('آخرین ثبت سرور: ${goal['updated_at']}'),
301
+ if (goal['queueStatus'] == 'conflict')
302
+ TextButton(
303
+ onPressed:
304
+ busy ? null : () => useServer(goal),
305
+ child: const Text('حل تعارض با نسخه سرور')),
306
+ Wrap(spacing: 8, children: [
307
+ TextButton(
308
+ onPressed: blocked
309
+ ? null
310
+ : () => Navigator.of(context).push(
311
+ MaterialPageRoute(
312
+ builder: (_) =>
313
+ LearningGoalHistoryPage(
314
+ api: widget.api,
315
+ goalId: goal['id']
316
+ as String))),
317
+ child:
318
+ const Text('بازتاب و سابقه یادگیری')),
319
+ TextButton(
320
+ onPressed:
321
+ blocked ? null : () => edit(goal),
322
+ child: const Text('ویرایش')),
323
+ TextButton(
324
+ onPressed:
325
+ blocked ? null : () => change(goal),
326
+ child: Text(goal['status'] == 'completed'
327
+ ? 'فعالکردن دوباره'
328
+ : 'تکمیل طبق گزارش من')),
329
+ TextButton(
330
+ onPressed: blocked
331
+ ? null
332
+ : () => change(goal, archive: true),
333
+ child: const Text('بایگانی')),
334
+ ])
335
+ ])));
336
+ })
337
+ ])));
338
+ }
339
+}
340
+
341
+/// The dialog owns its controllers until its route has actually unmounted.
342
+/// Disposing them when showDialog's result resolves is too early during pop.
343
+class _LearningGoalEditor extends StatefulWidget {
344
+ const _LearningGoalEditor(
345
+ {required this.sync, required this.goal, required this.onAuthFailure});
346
+ final LearningGoalSync sync;
347
+ final Map<String, dynamic>? goal;
348
+ final void Function(Object error) onAuthFailure;
349
+ @override
350
+ State<_LearningGoalEditor> createState() => _LearningGoalEditorState();
351
+}
352
+
353
+class _LearningGoalEditorState extends State<_LearningGoalEditor> {
354
+ late final TextEditingController title, target;
355
+ bool saving = false;
356
+ String? failure;
357
+ @override
358
+ void initState() {
359
+ super.initState();
360
+ title =
361
+ TextEditingController(text: widget.goal?['title']?.toString() ?? '');
362
+ target =
363
+ TextEditingController(text: widget.goal?['target']?.toString() ?? '');
364
+ }
365
+
366
+ @override
367
+ void dispose() {
368
+ title.dispose();
369
+ target.dispose();
370
+ super.dispose();
371
+ }
372
+
373
+ Future<void> save() async {
374
+ if (saving) return;
375
+ if (title.text.trim().isEmpty) {
376
+ setState(() => failure = 'عنوان هدف را بنویس.');
377
+ return;
378
+ }
379
+ setState(() {
380
+ saving = true;
381
+ failure = null;
382
+ });
383
+ try {
384
+ final goal = widget.goal;
385
+ final result = goal == null
386
+ ? await widget.sync.create(title: title.text, target: target.text)
387
+ : await widget.sync.update(
388
+ goal['id'] as String,
389
+ goal['version'] as int,
390
+ {'title': title.text, 'target': target.text});
391
+ if (mounted) Navigator.pop(context, result);
392
+ } catch (e) {
393
+ if (!mounted) return;
394
+ if (_goalAuthFailure(e)) {
395
+ widget.onAuthFailure(e);
396
+ return;
397
+ }
398
+ setState(() {
399
+ failure = _goalError(e);
400
+ saving = false;
401
+ });
402
+ }
403
+ }
404
+
405
+ @override
406
+ Widget build(BuildContext context) => PopScope(
407
+ canPop: !saving,
408
+ child: Directionality(
409
+ textDirection: TextDirection.rtl,
410
+ child: AlertDialog(
411
+ title: Text(widget.goal == null ? 'هدف جدید' : 'ویرایش هدف'),
412
+ content: SingleChildScrollView(
413
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
414
+ TextField(
415
+ controller: title,
416
+ maxLength: 240,
417
+ enabled: !saving,
418
+ decoration: const InputDecoration(labelText: 'عنوان هدف')),
419
+ TextField(
420
+ controller: target,
421
+ maxLength: 1000,
422
+ maxLines: 3,
423
+ enabled: !saving,
424
+ decoration: const InputDecoration(
425
+ labelText: 'نتیجه مورد نظر (اختیاری)')),
426
+ if (failure != null) Text(failure!)
427
+ ])),
428
+ actions: [
429
+ TextButton(
430
+ onPressed: saving ? null : () => Navigator.pop(context),
431
+ child: const Text('انصراف')),
432
+ FilledButton(
433
+ onPressed: saving ? null : save,
434
+ child: Text(saving ? 'در حال ذخیره…' : 'ذخیره'))
435
+ ])));
436
+}
437
+
438
+/// Existing owner-only check-in API. These legacy writes are online-only and
439
+/// have no durable idempotency receipt; an unknown result is explicitly reviewed.
440
+String _reflectionError(Object error) {
441
+ if (isOfflineFailure(error)) {
442
+ return 'اتصال برقرار نیست؛ دریافت بازتابها به سرور نیاز دارد.';
443
+ }
444
+ if (_goalAuthFailure(error)) {
445
+ return 'نشست یا دسترسی معتبر نیست؛ بازتابهای خصوصی قبلی از صفحه پاک شدند.';
446
+ }
447
+ if (error is ApiException && error.statusCode == 409) {
448
+ return 'وضعیت بازتاب در سرور تغییر کرده است؛ سابقه را تازه کن.';
449
+ }
450
+ return 'عملیات با پاسخ معتبر سرور تأیید نشد؛ سابقه را تازه کن.';
451
+}
452
+
453
+class LearningGoalHistoryPage extends StatefulWidget {
454
+ const LearningGoalHistoryPage(
455
+ {super.key, required this.api, required this.goalId});
456
+ final HttpIdentityApi api;
457
+ final String goalId;
458
+ @override
459
+ State<LearningGoalHistoryPage> createState() =>
460
+ _LearningGoalHistoryPageState();
461
+}
462
+
463
+class _LearningGoalHistoryPageState extends State<LearningGoalHistoryPage>
464
+ with WidgetsBindingObserver {
465
+ late final String scope;
466
+ List<Map<String, dynamic>> rows = [];
467
+ String? error;
468
+ String? notice;
469
+ DateTime? received;
470
+ bool loading = false, editing = false, active = true;
471
+ bool archivedGoal = true, uncertain = false;
472
+ int epoch = 0;
473
+ BuildContext? editorContext;
474
+ static final uuid = RegExp(r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$',
475
+ caseSensitive: false);
476
+ bool current(int request) => mounted && active && epoch == request;
477
+ @override
478
+ void initState() {
479
+ super.initState();
480
+ scope = widget.api.cacheNamespace ?? '';
481
+ WidgetsBinding.instance.addObserver(this);
482
+ load();
483
+ }
484
+
485
+ @override
486
+ void dispose() {
487
+ ++epoch;
488
+ WidgetsBinding.instance.removeObserver(this);
489
+ super.dispose();
490
+ }
491
+
492
+ void closeEditor() {
493
+ final dialog = editorContext;
494
+ editorContext = null;
495
+ if (dialog?.mounted != true) return;
496
+ final route = ModalRoute.of(dialog!);
497
+ if (route != null && route.isActive) {
498
+ Navigator.of(dialog).removeRoute(route);
499
+ }
500
+ }
501
+
502
+ @override
503
+ void didChangeAppLifecycleState(AppLifecycleState state) {
504
+ active = state == AppLifecycleState.resumed;
505
+ ++epoch;
506
+ if (!active) closeEditor();
507
+ if (mounted) {
508
+ setState(() {
509
+ rows = [];
510
+ received = null;
511
+ loading = false;
512
+ editing = false;
513
+ });
514
+ }
515
+ if (active) load();
516
+ }
517
+
518
+ void checkScope() {
519
+ if (scope.isEmpty || scope != widget.api.cacheNamespace) {
520
+ throw const ApiException(401, 'cache_scope_closed');
521
+ }
522
+ }
523
+
524
+ Future<Map<String, dynamic>> request(String method, String path,
525
+ {Map<String, dynamic>? body}) async {
526
+ checkScope();
527
+ final value = await widget.api.requestJson(method, path, body: body);
528
+ checkScope();
529
+ return value;
530
+ }
531
+
532
+ bool timestamp(dynamic value) =>
533
+ value is String &&
534
+ RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) &&
535
+ DateTime.tryParse(value) != null;
536
+ Map<String, dynamic> validateRow(Map value) {
537
+ if (value['id'] is! String ||
538
+ !uuid.hasMatch(value['id'] as String) ||
539
+ value['owner_user_id'] != widget.api.currentUserId ||
540
+ (value['learning_goal_id'] != null &&
541
+ (value['learning_goal_id'] is! String ||
542
+ !uuid.hasMatch(value['learning_goal_id'] as String))) ||
543
+ ![1, 2, 3, 4, 5].contains(value['confidence']) ||
544
+ ![1, 2, 3, 4, 5].contains(value['difficulty']) ||
545
+ (value['note'] != null &&
546
+ (value['note'] is! String ||
547
+ (value['note'] as String).length > 2000)) ||
548
+ value['source'] != 'self_reported' ||
549
+ value['isEvidenceOfStudy'] != false ||
550
+ !timestamp(value['occurred_at']) ||
551
+ !timestamp(value['created_at']) ||
552
+ !timestamp(value['updated_at']) ||
553
+ (value['archived_at'] != null && !timestamp(value['archived_at']))) {
554
+ throw const ApiException(502, 'invalid_learning_checkin');
555
+ }
556
+ return {
557
+ 'id': value['id'],
558
+ 'learning_goal_id': value['learning_goal_id'],
559
+ 'confidence': value['confidence'],
560
+ 'difficulty': value['difficulty'],
561
+ 'note': value['note'],
562
+ 'occurred_at': value['occurred_at'],
563
+ 'updated_at': value['updated_at'],
564
+ 'archived_at': value['archived_at'],
565
+ };
566
+ }
567
+
568
+ Future<void> load() async {
569
+ if (!active || editing) return;
570
+ final requestId = ++epoch;
571
+ setState(() {
572
+ rows = [];
573
+ received = null;
574
+ error = null;
575
+ loading = true;
576
+ archivedGoal = true;
577
+ });
578
+ try {
579
+ if (!uuid.hasMatch(widget.goalId)) {
580
+ throw const ApiException(400, 'invalid_goal_input');
581
+ }
582
+ final goal = await request('GET', '/v1/learning/goals/${widget.goalId}');
583
+ if (goal['id'] != widget.goalId ||
584
+ goal['owner_user_id'] != widget.api.currentUserId ||
585
+ !['active', 'completed', 'archived'].contains(goal['status'])) {
586
+ throw const ApiException(502, 'invalid_learning_goal');
587
+ }
588
+ final result = await request('GET', '/v1/learning/checkins');
589
+ if (result['items'] is! List) {
590
+ throw const ApiException(502, 'invalid_learning_checkins');
591
+ }
592
+ final values = <Map<String, dynamic>>[];
593
+ final ids = <String>{};
594
+ for (final raw in result['items'] as List) {
595
+ if (raw is! Map) {
596
+ throw const ApiException(502, 'invalid_learning_checkins');
597
+ }
598
+ final row = validateRow(Map<String, dynamic>.from(raw));
599
+ if (!ids.add(row['id'] as String) || row['archived_at'] != null) {
600
+ throw const ApiException(502, 'invalid_learning_checkins');
601
+ }
602
+ if (row['learning_goal_id'] == widget.goalId) values.add(row);
603
+ }
604
+ if (!current(requestId)) return;
605
+ setState(() {
606
+ rows = values;
607
+ received = DateTime.now();
608
+ archivedGoal = goal['status'] == 'archived';
609
+ });
610
+ } catch (e) {
611
+ if (current(requestId)) setState(() => error = _reflectionError(e));
612
+ } finally {
613
+ if (current(requestId)) setState(() => loading = false);
614
+ }
615
+ }
616
+
617
+ Future<void> edit([Map<String, dynamic>? row]) async {
618
+ if (!active ||
619
+ loading ||
620
+ editing ||
621
+ uncertain ||
622
+ (row == null && archivedGoal)) {
623
+ return;
624
+ }
625
+ final requestId = ++epoch;
626
+ setState(() => editing = true);
627
+ final result = await showDialog<Map<String, dynamic>>(
628
+ context: context,
629
+ barrierDismissible: false,
630
+ builder: (dialog) {
631
+ editorContext = dialog;
632
+ return _LearningCheckinEditor(
633
+ row: row,
634
+ save: (body) async {
635
+ final value = await request(row == null ? 'POST' : 'PATCH',
636
+ '/v1/learning/checkins${row == null ? '' : '/${row['id']}'}',
637
+ body: {
638
+ if (row == null) 'learningGoalId': widget.goalId,
639
+ ...body,
640
+ });
641
+ final confirmed = validateRow(value);
642
+ if (confirmed['learning_goal_id'] != widget.goalId ||
643
+ confirmed['archived_at'] != null ||
644
+ (row != null && confirmed['id'] != row['id']) ||
645
+ ['confidence', 'difficulty', 'note']
646
+ .any((key) => confirmed[key] != body[key])) {
647
+ throw const ApiException(502, 'invalid_learning_checkin');
648
+ }
649
+ },
650
+ onAuthFailure: (e) {
651
+ if (!current(requestId)) return;
652
+ setState(() {
653
+ rows = [];
654
+ received = null;
655
+ error = _reflectionError(e);
656
+ });
657
+ closeEditor();
658
+ });
659
+ });
660
+ editorContext = null;
661
+ if (!mounted || !current(requestId)) return;
662
+ setState(() => editing = false);
663
+ if (result == null) return;
664
+ if (result['uncertain'] == true) {
665
+ setState(() {
666
+ uncertain = true;
667
+ notice =
668
+ 'نتیجه ثبت قبلی ممکن است نامشخص باشد؛ سابقه تازه را بررسی کن. ثبت دوباره خودکار انجام نمیشود.';
669
+ });
670
+ } else {
671
+ setState(() => notice =
672
+ 'بازتاب در سرور ثبت شد؛ این گزارش شخصی است و اثبات یادگیری نیست.');
673
+ }
674
+ await load();
675
+ }
676
+
677
+ Future<void> archive(Map<String, dynamic> row) async {
678
+ if (!active || loading || editing || uncertain) return;
679
+ final accepted = await showDialog<bool>(
680
+ context: context,
681
+ builder: (dialog) => AlertDialog(
682
+ title: const Text('بایگانی بازتاب؟'),
683
+ content: const Text(
684
+ 'این بازتاب از فهرست جاری کنار میرود؛ هدف و سایر سوابق حذف نمیشوند.'),
685
+ actions: [
686
+ TextButton(
687
+ onPressed: () => Navigator.pop(dialog, false),
688
+ child: const Text('انصراف')),
689
+ FilledButton(
690
+ onPressed: () => Navigator.pop(dialog, true),
691
+ child: const Text('تأیید بایگانی'))
692
+ ]));
693
+ if (!mounted || !active || accepted != true) return;
694
+ setState(() {
695
+ loading = true;
696
+ rows = [];
697
+ received = null;
698
+ });
699
+ Object? failure;
700
+ try {
701
+ await request('DELETE', '/v1/learning/checkins/${row['id']}');
702
+ } catch (e) {
703
+ failure = e;
704
+ }
705
+ if (!mounted || !active) return;
706
+ setState(() => loading = false);
707
+ await load();
708
+ if (!mounted || !active) return;
709
+ if (failure != null) {
710
+ setState(() {
711
+ notice =
712
+ 'نتیجه بایگانی ممکن است نامشخص باشد؛ سابقه تازه را بررسی کن. تلاش خودکار انجام نمیشود.';
713
+ });
714
+ }
715
+ }
716
+
717
+ @override
718
+ Widget build(BuildContext context) => Directionality(
719
+ textDirection: TextDirection.rtl,
720
+ child: Scaffold(
721
+ appBar: AppBar(title: const Text('بازتاب یادگیری')),
722
+ body: ListView(padding: const EdgeInsets.all(16), children: [
723
+ const Text(
724
+ 'این سابقه و یادداشتها خصوصیاند و فقط با حساب صاحب آن دریافت میشوند.'),
725
+ const Text(
726
+ 'اعتماد و سختی، گزارش شخصی شما هستند؛ اثبات یادگیری یا زمان مطالعه نیستند.'),
727
+ const Text(
728
+ 'ثبت و ویرایش این بازتابها به اتصال سرور نیاز دارد؛ این صفحه ذخیره آفلاین ندارد.'),
729
+ if (loading) const LinearProgressIndicator(),
730
+ if (error != null) Text(error!),
731
+ if (notice != null) Text(notice!),
732
+ if (received != null)
733
+ Text(
734
+ 'آخرین دریافت سابقه: ${received!.toUtc().toIso8601String()}'),
735
+ if (uncertain && received != null)
736
+ OutlinedButton(
737
+ onPressed: () => setState(() {
738
+ uncertain = false;
739
+ notice = null;
740
+ }),
741
+ child: const Text('سابقه را بررسی کردم')),
742
+ FilledButton(
743
+ onPressed:
744
+ loading || editing || !active || archivedGoal || uncertain
745
+ ? null
746
+ : () => edit(),
747
+ child: const Text('ثبت بازتاب')),
748
+ OutlinedButton(
749
+ onPressed: editing || !active ? null : load,
750
+ child: const Text('تازهسازی سابقه')),
751
+ if (received != null && rows.isEmpty)
752
+ const Text('هنوز بازتاب جاری برای این هدف ثبت نشده است.'),
753
+ ...rows.map((row) => Card(
754
+ child: Padding(
755
+ padding: const EdgeInsets.all(12),
756
+ child: Column(
757
+ crossAxisAlignment: CrossAxisAlignment.start,
758
+ children: [
759
+ Text(
760
+ 'اعتماد به یادگیری: ${row['confidence']} از ۵ · سختی: ${row['difficulty']} از ۵'),
761
+ if (row['note'] != null) Text(row['note'] as String),
762
+ Text('زمان ثبت: ${row['occurred_at']}'),
763
+ Wrap(spacing: 8, children: [
764
+ TextButton(
765
+ onPressed: loading || editing || uncertain
766
+ ? null
767
+ : () => edit(row),
768
+ child: const Text('ویرایش بازتاب')),
769
+ TextButton(
770
+ onPressed: loading || editing || uncertain
771
+ ? null
772
+ : () => archive(row),
773
+ child: const Text('بایگانی بازتاب'))
774
+ ])
775
+ ]))))
776
+ ])));
777
+}
778
+
779
+class _LearningCheckinEditor extends StatefulWidget {
780
+ const _LearningCheckinEditor(
781
+ {required this.row, required this.save, required this.onAuthFailure});
782
+ final Map<String, dynamic>? row;
783
+ final Future<void> Function(Map<String, dynamic> body) save;
784
+ final void Function(Object error) onAuthFailure;
785
+ @override
786
+ State<_LearningCheckinEditor> createState() => _LearningCheckinEditorState();
787
+}
788
+
789
+class _LearningCheckinEditorState extends State<_LearningCheckinEditor> {
790
+ late final TextEditingController note;
791
+ late int confidence, difficulty;
792
+ bool saving = false;
793
+ String? error;
794
+ @override
795
+ void initState() {
796
+ super.initState();
797
+ note = TextEditingController(text: widget.row?['note'] as String? ?? '');
798
+ confidence = widget.row?['confidence'] as int? ?? 3;
799
+ difficulty = widget.row?['difficulty'] as int? ?? 3;
800
+ }
801
+
802
+ @override
803
+ void dispose() {
804
+ note.dispose();
805
+ super.dispose();
806
+ }
807
+
808
+ Future<void> save() async {
809
+ if (saving) return;
810
+ setState(() {
811
+ saving = true;
812
+ error = null;
813
+ });
814
+ try {
815
+ await widget.save({
816
+ 'confidence': confidence,
817
+ 'difficulty': difficulty,
818
+ 'note': note.text.trim().isEmpty ? null : note.text.trim()
819
+ });
820
+ if (mounted) Navigator.pop(context, {'uncertain': false});
821
+ } catch (e) {
822
+ if (!mounted) return;
823
+ if (_goalAuthFailure(e)) {
824
+ widget.onAuthFailure(e);
825
+ return;
826
+ }
827
+ if (isOfflineFailure(e) || (e is ApiException && e.statusCode >= 500)) {
828
+ Navigator.pop(context, {'uncertain': true});
829
+ return;
830
+ }
831
+ setState(() {
832
+ saving = false;
833
+ error = _reflectionError(e);
834
+ });
835
+ }
836
+ }
837
+
838
+ Widget scale(String label, int value, void Function(int value) change) =>
839
+ DropdownButtonFormField<int>(
840
+ initialValue: value,
841
+ decoration: InputDecoration(labelText: label),
842
+ items: [
843
+ for (var i = 1; i <= 5; i++)
844
+ DropdownMenuItem(value: i, child: Text('$i از ۵'))
845
+ ],
846
+ onChanged: saving ? null : (value) => setState(() => change(value!)));
847
+ @override
848
+ Widget build(BuildContext context) => PopScope(
849
+ canPop: !saving,
850
+ child: Directionality(
851
+ textDirection: TextDirection.rtl,
852
+ child: AlertDialog(
853
+ title: Text(widget.row == null ? 'بازتاب جدید' : 'ویرایش بازتاب'),
854
+ content: SingleChildScrollView(
855
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
856
+ scale('اعتماد به یادگیری', confidence, (v) => confidence = v),
857
+ scale('سختی یادگیری', difficulty, (v) => difficulty = v),
858
+ TextField(
859
+ controller: note,
860
+ maxLength: 2000,
861
+ maxLines: 3,
862
+ enabled: !saving,
863
+ decoration: const InputDecoration(
864
+ labelText: 'یادداشت خصوصی (اختیاری)')),
865
+ if (error != null) Text(error!)
866
+ ])),
867
+ actions: [
868
+ TextButton(
869
+ onPressed: saving ? null : () => Navigator.pop(context),
870
+ child: const Text('انصراف')),
871
+ FilledButton(
872
+ onPressed: saving ? null : save,
873
+ child: Text(saving ? 'در حال ثبت…' : 'ذخیره'))
874
+ ])));
875
+}
apps/lifemate/lib/learning_reviews_ui.dart
new
+485
@@ -0,0 +1,485 @@
1
+import 'dart:async';
2
+
3
+import 'package:flutter/material.dart';
4
+
5
+import 'api.dart';
6
+import 'offline_store.dart';
7
+
8
+/// Owner-private server receipts, separate from unanswered/unsent work.
9
+/// This page never grades answers or changes a learner's progress.
10
+class LearningReviewsPage extends StatefulWidget {
11
+ const LearningReviewsPage(
12
+ {super.key, required this.api, required this.onOpenLesson});
13
+ final HttpIdentityApi api;
14
+ final Future<void> Function(BuildContext, String unitId) onOpenLesson;
15
+ @override
16
+ State<LearningReviewsPage> createState() => _LearningReviewsPageState();
17
+}
18
+
19
+class _LearningReviewsPageState extends State<LearningReviewsPage>
20
+ with WidgetsBindingObserver {
21
+ static final _uuid =
22
+ RegExp(r'^[a-fA-F0-9]{8}(-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}$');
23
+ List<Map<String, dynamic>> _reviews = [], _attempts = [];
24
+ Map<String, Map<String, dynamic>> _titles = {};
25
+ String? _scope, _error, _reviewsFetchedAt, _attemptsFetchedAt, _opening;
26
+ OfflineStore? _store;
27
+ int? _pending;
28
+ int _epoch = 0;
29
+ bool _busy = false;
30
+ Timer? _poll;
31
+
32
+ @override
33
+ void initState() {
34
+ super.initState();
35
+ WidgetsBinding.instance.addObserver(this);
36
+ _bindScope();
37
+ _startPoll();
38
+ _load();
39
+ }
40
+
41
+ void _bindScope() {
42
+ _scope = widget.api.cacheNamespace;
43
+ _store = _scope == null ? null : OfflineStore.forApi(widget.api);
44
+ }
45
+
46
+ void _startPoll() {
47
+ _poll?.cancel();
48
+ _poll = Timer.periodic(const Duration(seconds: 30), (_) => _load());
49
+ }
50
+
51
+ void _clearServerData() {
52
+ _reviews = [];
53
+ _attempts = [];
54
+ _titles = {};
55
+ _reviewsFetchedAt = _attemptsFetchedAt = null;
56
+ }
57
+
58
+ @override
59
+ void didUpdateWidget(covariant LearningReviewsPage oldWidget) {
60
+ super.didUpdateWidget(oldWidget);
61
+ if (oldWidget.api != widget.api || _scope != widget.api.cacheNamespace) {
62
+ _epoch++;
63
+ _busy = false;
64
+ _pending = null;
65
+ _opening = null;
66
+ _clearServerData();
67
+ _bindScope();
68
+ _load();
69
+ }
70
+ }
71
+
72
+ @override
73
+ void didChangeAppLifecycleState(AppLifecycleState state) {
74
+ if (state == AppLifecycleState.resumed) {
75
+ _startPoll();
76
+ _load();
77
+ } else {
78
+ _poll?.cancel();
79
+ _epoch++;
80
+ if (mounted) {
81
+ setState(() {
82
+ _busy = false;
83
+ _opening = null;
84
+ _pending = null;
85
+ _clearServerData();
86
+ });
87
+ }
88
+ }
89
+ }
90
+
91
+ @override
92
+ void dispose() {
93
+ _epoch++;
94
+ _poll?.cancel();
95
+ WidgetsBinding.instance.removeObserver(this);
96
+ super.dispose();
97
+ }
98
+
99
+ bool _current(int epoch) => mounted && epoch == _epoch;
100
+
101
+ void _checkScope() {
102
+ if (_scope == null || widget.api.cacheNamespace != _scope) {
103
+ throw const ApiException(401, 'learning_history_scope_changed');
104
+ }
105
+ }
106
+
107
+ Future<List<Map<String, dynamic>>> _guard() async {
108
+ _checkScope();
109
+ final queue = await _store!.readQueue();
110
+ _checkScope();
111
+ return queue;
112
+ }
113
+
114
+ static bool _instant(dynamic value) =>
115
+ value is String &&
116
+ RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) &&
117
+ DateTime.tryParse(value) != null;
118
+ static bool _id(dynamic value) => value is String && _uuid.hasMatch(value);
119
+ static bool _text(dynamic value) =>
120
+ value is String && value.trim().isNotEmpty && value.length <= 2000;
121
+ static Never _invalid() =>
122
+ throw const ApiException(502, 'invalid_learning_history_response');
123
+
124
+ static List<Map<String, dynamic>> _parseReviews(
125
+ Map<String, dynamic> response) {
126
+ if (!_instant(response['fetchedAt']) || response['reviews'] is! List) {
127
+ _invalid();
128
+ }
129
+ final rows = response['reviews'] as List;
130
+ final units = <String>{};
131
+ if (rows.length > 100) _invalid();
132
+ return rows.map((row) {
133
+ if (row is! Map ||
134
+ !_id(row['unitId']) ||
135
+ !units.add(row['unitId'] as String) ||
136
+ !_instant(row['nextReviewAt']) ||
137
+ row['schedulePolicy'] != 'pilot-1-or-3-days') {
138
+ _invalid();
139
+ }
140
+ return Map<String, dynamic>.from(row);
141
+ }).toList();
142
+ }
143
+
144
+ static List<Map<String, dynamic>> _parseAttempts(
145
+ Map<String, dynamic> response) {
146
+ if (!_instant(response['fetchedAt']) || response['attempts'] is! List) {
147
+ _invalid();
148
+ }
149
+ final rows = response['attempts'] as List;
150
+ final ids = <String>{};
151
+ if (rows.length > 100) _invalid();
152
+ return rows.map((row) {
153
+ if (row is! Map ||
154
+ !_id(row['attemptId']) ||
155
+ !ids.add(row['attemptId'] as String) ||
156
+ !_id(row['unitId']) ||
157
+ !_id(row['assessmentId']) ||
158
+ !_id(row['mutationId']) ||
159
+ row['assessmentVersion'] is! int ||
160
+ row['assessmentVersion'] < 1 ||
161
+ row['source'] != 'quiz_answers' ||
162
+ !['unsure', 'somewhat', 'confident'].contains(row['confidence']) ||
163
+ row['total'] is! int ||
164
+ row['total'] < 1 ||
165
+ row['total'] > 20 ||
166
+ row['correctCount'] is! int ||
167
+ row['correctCount'] < 0 ||
168
+ row['correctCount'] > row['total'] ||
169
+ row['resultLabel'] !=
170
+ (row['correctCount'] == row['total']
171
+ ? 'answered_correctly'
172
+ : 'needs_practice') ||
173
+ !_instant(row['acceptedAt']) ||
174
+ !_instant(row['nextReviewAt']) ||
175
+ row['schedulePolicy'] != 'pilot-1-or-3-days' ||
176
+ row['feedback'] is! List ||
177
+ (row['feedback'] as List).length != row['total']) {
178
+ _invalid();
179
+ }
180
+ final questions = <String>{};
181
+ var correct = 0;
182
+ for (final feedback in row['feedback'] as List) {
183
+ if (feedback is! Map ||
184
+ !_text(feedback['questionId']) ||
185
+ !questions.add(feedback['questionId'] as String) ||
186
+ !_text(feedback['objectiveId']) ||
187
+ feedback['correct'] is! bool ||
188
+ !_text(feedback['explanationFa']) ||
189
+ !_text(feedback['remediationFa'])) {
190
+ _invalid();
191
+ }
192
+ if (feedback['correct'] == true) correct++;
193
+ }
194
+ if (correct != row['correctCount']) _invalid();
195
+ return Map<String, dynamic>.from(row);
196
+ }).toList();
197
+ }
198
+
199
+ Future<Map<String, dynamic>> _locate(String id) async {
200
+ try {
201
+ final response = await widget.api
202
+ .requestJson('GET', '/v1/education/units/${Uri.encodeComponent(id)}');
203
+ _checkScope();
204
+ final unit = response['unit'];
205
+ if (!_instant(response['fetchedAt']) ||
206
+ unit is! Map ||
207
+ unit['id'] != id ||
208
+ !_id(unit['courseId']) ||
209
+ !_text(unit['titleFa'])) {
210
+ _invalid();
211
+ }
212
+ return {...Map<String, dynamic>.from(unit), 'available': true};
213
+ } catch (failure) {
214
+ _checkScope();
215
+ if (failure is ApiException && [401, 403].contains(failure.statusCode)) {
216
+ rethrow;
217
+ }
218
+ return {
219
+ 'id': id,
220
+ 'titleFa': failure is ApiException && failure.statusCode == 404
221
+ ? 'درس از دسترس خارج شده'
222
+ : 'نام درس دریافت نشد',
223
+ 'available': false,
224
+ };
225
+ }
226
+ }
227
+
228
+ Future<Map<String, Map<String, dynamic>>> _locateTitles(
229
+ Iterable<String> units, int epoch) async {
230
+ final ids = units.toSet().take(100).toList();
231
+ final titles = <String, Map<String, dynamic>>{};
232
+ // Bounded requests; do not issue one unbounded Future per receipt.
233
+ for (var at = 0; at < ids.length; at += 4) {
234
+ if (!_current(epoch)) return {};
235
+ final batch = ids.skip(at).take(4).toList();
236
+ final result = await Future.wait(batch.map(_locate));
237
+ _checkScope();
238
+ for (var index = 0; index < batch.length; index++) {
239
+ titles[batch[index]] = result[index];
240
+ }
241
+ }
242
+ return titles;
243
+ }
244
+
245
+ String _failure(Object failure) {
246
+ if (failure is ApiException && [401, 403].contains(failure.statusCode)) {
247
+ return 'نشست یا دسترسی معتبر نیست؛ دوباره وارد حساب خود شوید.';
248
+ }
249
+ if (isOfflineFailure(failure)) {
250
+ return 'اتصال برقرار نیست؛ تاریخچه تازه از سرور دریافت نشد.';
251
+ }
252
+ if (failure is ApiException && failure.code.startsWith('local_')) {
253
+ return 'وضعیت ارسالهای دستگاه خوانده نشد؛ دادهای حذف نشده است.';
254
+ }
255
+ return 'پاسخ معتبر دریافت نشد؛ دوباره تلاش کنید.';
256
+ }
257
+
258
+ Future<void> _load() async {
259
+ if (_busy || !mounted || _opening != null) return;
260
+ final epoch = ++_epoch;
261
+ setState(() {
262
+ _busy = true;
263
+ _error = null;
264
+ _clearServerData();
265
+ });
266
+ try {
267
+ final queue = await _guard();
268
+ if (!_current(epoch)) return;
269
+ setState(() => _pending =
270
+ queue.where((row) => row['entityType'] == 'learning_attempt').length);
271
+ final responses = await Future.wait([
272
+ widget.api.requestJson('GET', '/v1/me/learning-reviews'),
273
+ widget.api.requestJson('GET', '/v1/me/learning-attempts'),
274
+ ], eagerError: true);
275
+ _checkScope();
276
+ if (!_current(epoch)) return;
277
+ final reviews = _parseReviews(responses[0]);
278
+ final attempts = _parseAttempts(responses[1]);
279
+ final titles = await _locateTitles([
280
+ ...reviews.map((row) => row['unitId'] as String),
281
+ ...attempts.map((row) => row['unitId'] as String),
282
+ ], epoch);
283
+ await _guard(); // Reject a handle invalidated while network was pending.
284
+ if (!_current(epoch)) return;
285
+ setState(() {
286
+ _reviews = reviews;
287
+ _attempts = attempts;
288
+ _titles = titles;
289
+ _reviewsFetchedAt = responses[0]['fetchedAt'] as String;
290
+ _attemptsFetchedAt = responses[1]['fetchedAt'] as String;
291
+ });
292
+ } catch (failure) {
293
+ if (!_current(epoch)) return;
294
+ setState(() {
295
+ _clearServerData();
296
+ _error = _failure(failure);
297
+ if (failure is ApiException &&
298
+ [401, 403].contains(failure.statusCode)) {
299
+ _pending = null;
300
+ }
301
+ });
302
+ } finally {
303
+ if (_current(epoch)) setState(() => _busy = false);
304
+ }
305
+ }
306
+
307
+ Future<void> _open(String id) async {
308
+ if (_opening != null || _busy) return;
309
+ final epoch = _epoch;
310
+ _poll?.cancel();
311
+ setState(() => _opening = id);
312
+ try {
313
+ await _guard();
314
+ if (!_current(epoch)) return;
315
+ var title = _titles[id];
316
+ if (title?['available'] != true) {
317
+ title = await _locate(id);
318
+ await _guard();
319
+ if (!_current(epoch)) return;
320
+ setState(() => _titles[id] = title!);
321
+ }
322
+ if (title?['available'] != true) {
323
+ throw const ApiException(404, 'unit_not_available');
324
+ }
325
+ if (!mounted) return;
326
+ await widget.onOpenLesson(context, id);
327
+ await _guard();
328
+ } catch (failure) {
329
+ if (!_current(epoch)) return;
330
+ setState(() {
331
+ _error = failure is ApiException && failure.statusCode == 404
332
+ ? 'این درس فعلاً در کتابخانه فعال در دسترس نیست.'
333
+ : _failure(failure);
334
+ if (failure is ApiException &&
335
+ [401, 403].contains(failure.statusCode)) {
336
+ _clearServerData();
337
+ _pending = null;
338
+ }
339
+ });
340
+ } finally {
341
+ if (_current(epoch)) {
342
+ setState(() => _opening = null);
343
+ _startPoll();
344
+ }
345
+ }
346
+ }
347
+
348
+ String _title(String id) =>
349
+ _titles[id]?['titleFa'] as String? ?? 'نام درس هنوز دریافت نشده';
350
+ String _number(int value) {
351
+ const digits = '۰۱۲۳۴۵۶۷۸۹';
352
+ return value.toString().split('').map((v) => digits[int.parse(v)]).join();
353
+ }
354
+
355
+ Widget _review(Map<String, dynamic> row) {
356
+ final id = row['unitId'] as String;
357
+ final due = !DateTime.parse(row['nextReviewAt'] as String)
358
+ .isAfter(DateTime.now().toUtc());
359
+ return Card(
360
+ key: Key('review-$id'),
361
+ child: Padding(
362
+ padding: const EdgeInsets.all(12),
363
+ child: Column(
364
+ crossAxisAlignment: CrossAxisAlignment.stretch,
365
+ children: [
366
+ Text(_title(id),
367
+ style: Theme.of(context).textTheme.titleMedium),
368
+ Align(
369
+ alignment: AlignmentDirectional.centerStart,
370
+ child: Chip(
371
+ avatar: Icon(due ? Icons.history : Icons.schedule),
372
+ label: Text(due ? 'موعد رسیده' : 'مرور آینده'))),
373
+ Text('زمان پیشنهادی مرور: ${row['nextReviewAt']}'),
374
+ TextButton.icon(
375
+ key: Key('open-review-$id'),
376
+ onPressed:
377
+ _opening == null && !_busy ? () => _open(id) : null,
378
+ icon: const Icon(Icons.menu_book_outlined),
379
+ label: Text(_opening == id
380
+ ? 'در حال بازکردن…'
381
+ : 'بازکردن درس برای مرور')),
382
+ ])));
383
+ }
384
+
385
+ Widget _attempt(Map<String, dynamic> row) {
386
+ final id = row['unitId'] as String;
387
+ final feedback = row['feedback'] as List;
388
+ final confidence = switch (row['confidence']) {
389
+ 'confident' => 'مطمئن بودم',
390
+ 'somewhat' => 'تا حدی مطمئن بودم',
391
+ _ => 'مطمئن نبودم',
392
+ };
393
+ return Card(
394
+ key: Key('attempt-${row['attemptId']}'),
395
+ child: ExpansionTile(
396
+ title: Text(_title(id)),
397
+ subtitle: Column(
398
+ crossAxisAlignment: CrossAxisAlignment.stretch,
399
+ children: [
400
+ Text(
401
+ '${_number(row['correctCount'] as int)} پاسخ درست از ${_number(row['total'] as int)}'),
402
+ Text(row['resultLabel'] == 'needs_practice'
403
+ ? 'نیاز به تمرین'
404
+ : 'پاسخهای این تلاش درست بودند'),
405
+ Text('ثبت و تأیید سرور: ${row['acceptedAt']}'),
406
+ Text('اعتماد گزارششده: $confidence'),
407
+ Text(
408
+ 'نسخه آزمون: ${_number(row['assessmentVersion'] as int)}'),
409
+ const Text('برای دیدن توضیح پاسخها باز کنید.'),
410
+ ]),
411
+ children: [
412
+ for (var index = 0; index < feedback.length; index++)
413
+ Padding(
414
+ padding: const EdgeInsets.all(12),
415
+ child: Column(
416
+ crossAxisAlignment: CrossAxisAlignment.stretch,
417
+ children: [
418
+ Text(
419
+ 'پرسش ${_number(index + 1)} · ${feedback[index]['correct'] == true ? 'پاسخ درست ثبت شد' : 'تمرین بیشتر پیشنهاد میشود'}'),
420
+ Text(feedback[index]['explanationFa'] as String),
421
+ Text(feedback[index]['remediationFa'] as String),
422
+ ])),
423
+ TextButton.icon(
424
+ key: Key('open-attempt-${row['attemptId']}'),
425
+ onPressed:
426
+ _opening == null && !_busy ? () => _open(id) : null,
427
+ icon: const Icon(Icons.menu_book_outlined),
428
+ label: const Text('بازکردن درس')),
429
+ ]));
430
+ }
431
+
432
+ @override
433
+ Widget build(BuildContext context) => Directionality(
434
+ textDirection: TextDirection.rtl,
435
+ child: Scaffold(
436
+ appBar: AppBar(title: const Text('مرور و تاریخچه یادگیری')),
437
+ body: RefreshIndicator(
438
+ onRefresh: _load,
439
+ child: ListView(
440
+ padding: const EdgeInsets.all(16),
441
+ physics: const AlwaysScrollableScrollPhysics(),
442
+ children: [
443
+ const Text(
444
+ 'نتیجه آزمون بهتنهایی اثبات تسلط نیست. این صفحه فقط پاسخهای تصحیحشده و تأییدشده سرور را نشان میدهد.'),
445
+ const SizedBox(height: 8),
446
+ const Text(
447
+ 'زمان مرور پیشنهاد آزمایشی ۱ یا ۳ روزه است؛ به معنی اجبار یا تضمین یادگیری نیست.'),
448
+ if (_pending != null)
449
+ Text(
450
+ 'ارسال آزمون در انتظار تأیید یا بررسی روی این دستگاه: ${_number(_pending!)}'),
451
+ if (_busy) ...[
452
+ const SizedBox(height: 12),
453
+ const LinearProgressIndicator(),
454
+ const Text('در حال دریافت اطلاعات از سرور…'),
455
+ ],
456
+ if (_error != null)
457
+ Card(
458
+ child: ListTile(
459
+ leading: const Icon(Icons.warning_amber),
460
+ title: Text(_error!),
461
+ subtitle: const Text(
462
+ 'تأیید تازه دریافت نشده؛ پاسخهای ارسالنشده حذف نمیشوند.'))),
463
+ if (_reviewsFetchedAt != null) ...[
464
+ Text('دریافت مرورها از سرور: $_reviewsFetchedAt'),
465
+ Text('مرورهای موعددار',
466
+ style: Theme.of(context).textTheme.titleLarge),
467
+ if (_reviews.isEmpty) const Text('مروری ثبت نشده است.'),
468
+ ..._reviews.map(_review),
469
+ ],
470
+ if (_attemptsFetchedAt != null) ...[
471
+ Text('دریافت تاریخچه از سرور: $_attemptsFetchedAt'),
472
+ Text('تاریخچه آزمونهای پذیرفتهشده',
473
+ style: Theme.of(context).textTheme.titleLarge),
474
+ const Text('تا ۱۰۰ تلاش اخیر حساب خودتان از سرور'),
475
+ if (_attempts.isEmpty)
476
+ const Text('هنوز نتیجه پذیرفتهشدهای ثبت نشده است.'),
477
+ ..._attempts.map(_attempt),
478
+ ],
479
+ TextButton.icon(
480
+ key: const Key('refresh-learning-history'),
481
+ onPressed: _busy || _opening != null ? null : _load,
482
+ icon: const Icon(Icons.refresh),
483
+ label: const Text('تازهسازی از سرور')),
484
+ ]))));
485
+}
apps/lifemate/lib/main.dart
+133
-13
@@ -1,3 +1,5 @@
1
+import 'dart:async';
2
+
3
import 'package:flutter/services.dart';
4
import 'package:flutter/material.dart';
5
import 'package:flutter_localizations/flutter_localizations.dart';
@@ -5,6 +7,11 @@ import 'package:flutter_localizations/flutter_localizations.dart';
7
import 'api.dart';
8
import 'iran_hub.dart';
9
import 'education_ui.dart';
10
+import 'content_review_sync.dart';
11
+import 'content_review_ui.dart';
12
+import 'learning_reviews_ui.dart';
13
+import 'learning_goals_ui.dart';
14
+import 'family_management_ui.dart';
15
import 'phase3_ui.dart';
16
import 'runtime_controller.dart';
17
import 'endpoint_settings.dart';
@@ -1021,11 +1028,17 @@ class HomeShell extends StatefulWidget {
1028
State<HomeShell> createState() => _HomeShellState();
1029
}
1030
1024
-class _HomeShellState extends State<HomeShell> {
1031
+class _HomeShellState extends State<HomeShell> with WidgetsBindingObserver {
1032
int index = 0;
1033
String themePreference = 'adult_blue';
1034
bool adultShell = false;
1035
String? contextError;
1036
+ Set<String> contentPermissions = {};
1037
+ Timer? capabilityPoll;
1038
+ int capabilityEpoch = 0;
1039
+
1040
+ HttpIdentityApi? get httpApi =>
1041
+ widget.api is HttpIdentityApi ? widget.api as HttpIdentityApi : null;
1042
1043
static const studentPages = [
1044
'امروز',
@@ -1050,13 +1063,82 @@ class _HomeShellState extends State<HomeShell> {
1063
@override
1064
void initState() {
1065
super.initState();
1066
+ WidgetsBinding.instance.addObserver(this);
1067
loadContext();
1068
+ if (httpApi != null) {
1069
+ loadCapabilities();
1070
+ capabilityPoll = Timer.periodic(
1071
+ const Duration(seconds: 30), (_) => loadCapabilities());
1072
+ }
1073
+ }
1074
+
1075
+ @override
1076
+ void dispose() {
1077
+ capabilityEpoch++;
1078
+ capabilityPoll?.cancel();
1079
+ WidgetsBinding.instance.removeObserver(this);
1080
+ super.dispose();
1081
+ }
1082
+
1083
+ @override
1084
+ void didChangeAppLifecycleState(AppLifecycleState state) {
1085
+ capabilityEpoch++;
1086
+ if (mounted) setState(() => contentPermissions = {});
1087
+ if (state == AppLifecycleState.resumed) loadCapabilities();
1088
+ }
1089
+
1090
+ Future<void> loadCapabilities() async {
1091
+ final api = httpApi;
1092
+ final scope = api?.cacheNamespace;
1093
+ final epoch = ++capabilityEpoch;
1094
+ if (mounted) setState(() => contentPermissions = {});
1095
+ if (api == null || scope == null) return;
1096
+ try {
1097
+ final permissions = await ContentReviewSync(api).capabilities();
1098
+ if (mounted &&
1099
+ epoch == capabilityEpoch &&
1100
+ identical(api, httpApi) &&
1101
+ scope == api.cacheNamespace) {
1102
+ setState(() => contentPermissions = permissions);
1103
+ }
1104
+ } catch (_) {
1105
+ // A menu is only a navigation aid. The actual operations always re-check
1106
+ // current server capabilities; family/profile roles never grant them.
1107
+ }
1108
+ }
1109
+
1110
+ Future<void> openReviewedLesson(BuildContext origin, String unitId) async {
1111
+ final api = httpApi;
1112
+ if (api == null) return;
1113
+ final scope = api.cacheNamespace;
1114
+ try {
1115
+ final result = await api.requestJson(
1116
+ 'GET', '/v1/education/units/${Uri.encodeComponent(unitId)}');
1117
+ if (!origin.mounted || scope == null || scope != api.cacheNamespace) {
1118
+ return;
1119
+ }
1120
+ final unit = result['unit'];
1121
+ if (unit is! Map || unit['id'] != unitId || unit['courseId'] is! String) {
1122
+ throw const ApiException(502, 'invalid_unit_response');
1123
+ }
1124
+ await Navigator.of(origin).push(MaterialPageRoute(
1125
+ builder: (_) => LearningLessonPage(
1126
+ api: api, courseId: unit['courseId'] as String, unitId: unitId)));
1127
+ } catch (error) {
1128
+ if (origin.mounted && scope == api.cacheNamespace) {
1129
+ ScaffoldMessenger.of(origin).showSnackBar(SnackBar(
1130
+ content: Text(error is ApiException && error.statusCode == 404
1131
+ ? 'این درس دیگر در فهرست فعال نیست؛ تاریخچه ثبتشده محفوظ است.'
1132
+ : uiErrorText(error))));
1133
+ }
1134
+ }
1135
}
1136
1137
Future<void> loadContext() async {
1138
+ final scope = httpApi?.cacheNamespace;
1139
try {
1140
final profile = await widget.api.getProfile();
1059
- if (mounted) {
1141
+ if (mounted && (httpApi == null || scope == httpApi!.cacheNamespace)) {
1142
setState(() {
1143
themePreference =
1144
profile['theme_preference']?.toString() ?? 'adult_blue';
@@ -1219,6 +1301,39 @@ class _HomeShellState extends State<HomeShell> {
1301
Navigator.of(context).push(MaterialPageRoute(
1302
builder: (_) => SyncChangesPage(api: widget.api)));
1303
}),
1304
+ if (httpApi != null)
1305
+ ListTile(
1306
+ leading: const Icon(Icons.flag_outlined),
1307
+ title: const Text('اهداف یادگیری'),
1308
+ onTap: () {
1309
+ Navigator.pop(context);
1310
+ Navigator.of(context).push(MaterialPageRoute(
1311
+ builder: (_) =>
1312
+ LearningGoalsPage(api: httpApi!)));
1313
+ }),
1314
+ if (httpApi != null)
1315
+ ListTile(
1316
+ leading: const Icon(Icons.history_edu_outlined),
1317
+ title: const Text('مرور و تاریخچه یادگیری'),
1318
+ onTap: () {
1319
+ Navigator.pop(context);
1320
+ Navigator.of(context).push(MaterialPageRoute(
1321
+ builder: (_) => LearningReviewsPage(
1322
+ api: httpApi!,
1323
+ onOpenLesson: openReviewedLesson)));
1324
+ }),
1325
+ if (httpApi != null &&
1326
+ contentPermissions.contains('feedback.read'))
1327
+ ListTile(
1328
+ leading: const Icon(Icons.fact_check_outlined),
1329
+ title: const Text('بررسی محتوای آموزشی'),
1330
+ onTap: () async {
1331
+ Navigator.pop(context);
1332
+ await Navigator.of(context).push(MaterialPageRoute(
1333
+ builder: (_) =>
1334
+ ContentReviewPage(api: httpApi!)));
1335
+ if (mounted) await loadCapabilities();
1336
+ }),
1337
if (widget.onEndpointSettings != null && !kIsWeb)
1338
ListTile(
1339
leading: const Icon(Icons.settings_ethernet),
@@ -1371,17 +1486,22 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
1486
title: Text(family['name']?.toString() ?? 'خانواده'),
1487
subtitle: Text(
1488
'${family['is_admin'] == true ? 'مدیر خانواده · ' : ''}${family['role'] ?? ''}'),
1374
- onTap: () => Navigator.of(context).push(
1375
- MaterialPageRoute(
1376
- builder: (_) => FamilyMembersPage(
1377
- api: widget.api,
1378
- familyId: family['id'].toString(),
1379
- familyName:
1380
- family['name']?.toString() ?? 'خانواده',
1381
- isAdmin: family['is_admin'] == true,
1382
- ),
1383
- ),
1384
- ),
1489
+ onTap: () async {
1490
+ final api = widget.api;
1491
+ await Navigator.of(context).push(MaterialPageRoute(
1492
+ builder: (_) => api is HttpIdentityApi
1493
+ ? FamilyManagementPage(
1494
+ api: api,
1495
+ familyId: family['id'].toString())
1496
+ : FamilyMembersPage(
1497
+ api: api,
1498
+ familyId: family['id'].toString(),
1499
+ familyName:
1500
+ family['name']?.toString() ??
1501
+ 'خانواده',
1502
+ isAdmin: family['is_admin'] == true)));
1503
+ if (mounted) setState(() => data = load());
1504
+ },
1505
trailing: IconButton(
1506
onPressed: family['is_admin'] == true
1507
? () => invite(family['id'].toString())
apps/lifemate/lib/phase3_ui.dart
+20
-40
@@ -5,6 +5,7 @@ import 'offline_store.dart';
5
import 'plan_sync.dart';
6
import 'study_ui.dart';
7
import 'dashboard_ui.dart';
8
+import 'school_management_ui.dart';
9
10
String faKind(String kind) => switch (kind) {
11
'assignment' => 'تکلیف',
@@ -802,42 +803,12 @@ class _SchoolPageState extends State<SchoolPage> {
803
} catch (_) {/* FutureBuilder renders retry failure. */}
804
}
805
805
- Future<void> quickSetup() async {
806
- if (writing) return;
807
- setState(() {
808
- writing = true;
809
- writeError = null;
810
- });
811
- try {
812
- var contexts = await widget.api.listLifeContexts();
813
- Map<String, dynamic>? student;
814
- for (final row in contexts) {
815
- if (row['kind'] == 'student') {
816
- student = row;
817
- break;
818
- }
819
- }
820
- student ??=
821
- await widget.api.createLifeContext(kind: 'student', title: 'مدرسه');
822
- final now = DateTime.now();
823
- final year = await widget.api.createAcademicYear({
824
- 'lifeContextId': student['id'],
825
- 'title': 'سال تحصیلی ${now.year}-${now.year + 1}',
826
- 'startsOn': '${now.year}-09-01',
827
- 'endsOn': '${now.year + 1}-06-30',
828
- });
829
- final term = await widget.api.createAcademicTerm(year['id'].toString(), {
830
- 'title': 'نیمسال اول',
831
- 'startsOn': '${now.year}-09-01',
832
- 'endsOn': '${now.year + 1}-01-31',
833
- });
834
- await widget.api.createSubject(term['id'].toString(), {'name': 'ریاضی'});
835
- await reload();
836
- } catch (error) {
837
- if (mounted) setState(() => writeError = uiErrorText(error));
838
- } finally {
839
- if (mounted) setState(() => writing = false);
840
- }
806
+ Future<void> openManagement() async {
807
+ if (widget.api is! HttpIdentityApi || writing) return;
808
+ await Navigator.of(context).push(MaterialPageRoute<void>(
809
+ builder: (_) =>
810
+ SchoolManagementPage(api: widget.api as HttpIdentityApi)));
811
+ if (mounted) await reload();
812
}
813
814
Future<void> addSchoolItem(String kind) async {
@@ -889,11 +860,13 @@ class _SchoolPageState extends State<SchoolPage> {
860
icon: Icons.school_outlined,
861
title: 'مدرسه را آماده کن',
862
subtitle:
892
- 'سال تحصیلی، نیمسال و اولین درس را با شروع سریع بساز.',
863
+ 'عنوانها، تاریخ سال و نیمسال و درسها را خودت انتخاب کن.',
864
action: FilledButton.icon(
894
- onPressed: writing ? null : quickSetup,
895
- icon: const Icon(Icons.auto_fix_high),
896
- label: const Text('شروع سریع'),
865
+ onPressed: writing || widget.api is! HttpIdentityApi
866
+ ? null
867
+ : openManagement,
868
+ icon: const Icon(Icons.school_outlined),
869
+ label: const Text('مدیریت مدرسه'),
870
),
871
)
872
else ...[
@@ -905,6 +878,13 @@ class _SchoolPageState extends State<SchoolPage> {
878
children: [
879
Text('مدرسه',
880
style: Theme.of(context).textTheme.headlineSmall),
881
+ TextButton.icon(
882
+ onPressed:
883
+ writing || widget.api is! HttpIdentityApi
884
+ ? null
885
+ : openManagement,
886
+ icon: const Icon(Icons.manage_accounts_outlined),
887
+ label: const Text('مدیریت مدرسه')),
888
const SizedBox(height: 10),
889
Wrap(spacing: 8, runSpacing: 8, children: [
890
Chip(label: Text('${subjects.length} درس')),
apps/lifemate/lib/phase4_ui.dart
+49
-38
@@ -1,6 +1,7 @@
1
import 'package:flutter/material.dart';
2
3
import 'api.dart';
4
+import 'learning_goals_ui.dart';
5
6
class Phase4Hub extends StatefulWidget {
7
const Phase4Hub({super.key, required this.api, this.adultShell = false});
@@ -17,7 +18,9 @@ class _Phase4HubState extends State<Phase4Hub> {
18
@override
19
void initState() {
20
super.initState();
20
- goals = widget.api.listLearningGoals();
21
+ goals = widget.api is HttpIdentityApi
22
+ ? Future.value([])
23
+ : widget.api.listLearningGoals();
24
}
25
26
Future<void> addGoal() async {
@@ -277,9 +280,15 @@ class _Phase4HubState extends State<Phase4Hub> {
280
const SizedBox(width: 8),
281
Expanded(
282
child: OutlinedButton.icon(
280
- onPressed: addGoal,
283
+ onPressed: widget.api is HttpIdentityApi
284
+ ? () => Navigator.of(context).push(MaterialPageRoute(
285
+ builder: (_) => LearningGoalsPage(
286
+ api: widget.api as HttpIdentityApi)))
287
+ : addGoal,
288
icon: const Icon(Icons.flag_outlined),
282
- label: const Text('هدف یادگیری'),
289
+ label: Text(widget.api is HttpIdentityApi
290
+ ? 'مدیریت هدفهای یادگیری'
291
+ : 'هدف یادگیری'),
292
),
293
),
294
],
@@ -296,42 +305,44 @@ class _Phase4HubState extends State<Phase4Hub> {
305
),
306
),
307
const SizedBox(height: 12),
299
- Text('هدفهای یادگیری',
300
- style: Theme.of(context).textTheme.titleMedium),
301
- FutureBuilder<List<Map<String, dynamic>>>(
302
- future: goals,
303
- builder: (context, snapshot) {
304
- if (!snapshot.hasData) {
305
- return const Padding(
306
- padding: EdgeInsets.all(20),
307
- child: Center(child: CircularProgressIndicator()),
308
- );
309
- }
310
- if (snapshot.data!.isEmpty) {
311
- return const Card(
312
- child: ListTile(
313
- leading: Icon(Icons.flag_outlined),
314
- title: Text('هنوز هدفی ثبت نشده'),
315
- ),
316
- );
317
- }
318
- return Column(
319
- children: snapshot.data!
320
- .map(
321
- (goal) => Card(
322
- child: ListTile(
323
- leading: const Icon(Icons.flag_circle_outlined),
324
- title: Text(goal['title']?.toString() ?? ''),
325
- subtitle: Text(goal['target']?.toString() ?? ''),
326
- trailing: const Icon(Icons.add_chart_outlined),
327
- onTap: () => learningCheckin(goal),
308
+ if (widget.api is! HttpIdentityApi)
309
+ Text('هدفهای یادگیری',
310
+ style: Theme.of(context).textTheme.titleMedium),
311
+ if (widget.api is! HttpIdentityApi)
312
+ FutureBuilder<List<Map<String, dynamic>>>(
313
+ future: goals,
314
+ builder: (context, snapshot) {
315
+ if (!snapshot.hasData) {
316
+ return const Padding(
317
+ padding: EdgeInsets.all(20),
318
+ child: Center(child: CircularProgressIndicator()),
319
+ );
320
+ }
321
+ if (snapshot.data!.isEmpty) {
322
+ return const Card(
323
+ child: ListTile(
324
+ leading: Icon(Icons.flag_outlined),
325
+ title: Text('هنوز هدفی ثبت نشده'),
326
+ ),
327
+ );
328
+ }
329
+ return Column(
330
+ children: snapshot.data!
331
+ .map(
332
+ (goal) => Card(
333
+ child: ListTile(
334
+ leading: const Icon(Icons.flag_circle_outlined),
335
+ title: Text(goal['title']?.toString() ?? ''),
336
+ subtitle: Text(goal['target']?.toString() ?? ''),
337
+ trailing: const Icon(Icons.add_chart_outlined),
338
+ onTap: () => learningCheckin(goal),
339
+ ),
340
),
329
- ),
330
- )
331
- .toList(),
332
- );
333
- },
334
- ),
341
+ )
342
+ .toList(),
343
+ );
344
+ },
345
+ ),
346
],
347
);
348
}
apps/lifemate/lib/school_management_ui.dart
new
+1106
@@ -0,0 +1,1106 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'package:flutter/material.dart';
5
+
6
+import 'api.dart';
7
+import 'offline_store.dart';
8
+import 'plan_sync.dart' show newMutationId;
9
+
10
+const _schoolTypes = ['contexts', 'years', 'terms'];
11
+final _schoolUuid = RegExp(r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$',
12
+ caseSensitive: false);
13
+String _latinDigits(String value) {
14
+ const all = '۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩';
15
+ return value.trim().split('').map((c) {
16
+ final n = all.indexOf(c);
17
+ return n < 0 ? c : '${n % 10}';
18
+ }).join();
19
+}
20
+
21
+String _faDigits(String value) => value
22
+ .split('')
23
+ .map((c) => int.tryParse(c) == null ? c : '۰۱۲۳۴۵۶۷۸۹'[int.parse(c)])
24
+ .join();
25
+String _dateText(DateTime value) =>
26
+ '${value.year.toString().padLeft(4, '0')}-${value.month.toString().padLeft(2, '0')}-${value.day.toString().padLeft(2, '0')}';
27
+bool _schoolDate(dynamic value) =>
28
+ value is String &&
29
+ RegExp(r'^\d{4}-\d{2}-\d{2}$').hasMatch(value) &&
30
+ !value.startsWith('0000-') &&
31
+ DateTime.tryParse(value) != null &&
32
+ _dateText(DateTime.parse(value)) == value;
33
+bool _schoolTime(dynamic value) =>
34
+ value is String &&
35
+ RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) &&
36
+ DateTime.tryParse(value) != null;
37
+
38
+/// The existing account/endpoint queue stores intent before delivery. Setup
39
+/// progresses only after the preceding parent has a canonical server ACK.
40
+class SchoolLifecycleSync {
41
+ SchoolLifecycleSync(this.api, {OfflineStore? store})
42
+ : store = store ?? OfflineStore.forApi(api);
43
+ final HttpIdentityApi api;
44
+ final OfflineStore store;
45
+ static final _tails = <String, Future<void>>{};
46
+ void _scope() {
47
+ if (api.cacheNamespace != store.scope) {
48
+ throw const ApiException(401, 'cache_scope_closed');
49
+ }
50
+ }
51
+
52
+ Future<T> _serial<T>(Future<T> Function() run) async {
53
+ final before = _tails[store.scope], release = Completer<void>();
54
+ _tails[store.scope] = release.future;
55
+ if (before != null) await before;
56
+ try {
57
+ _scope();
58
+ await store.readQueue();
59
+ final value = await run();
60
+ _scope();
61
+ return value;
62
+ } finally {
63
+ if (identical(_tails[store.scope], release.future)) {
64
+ _tails.remove(store.scope);
65
+ }
66
+ release.complete();
67
+ }
68
+ }
69
+
70
+ Map<String, dynamic> _entity(String type, dynamic raw) {
71
+ if (raw is! Map ||
72
+ raw['id'] is! String ||
73
+ !_schoolUuid.hasMatch(raw['id']) ||
74
+ raw['title'] is! String ||
75
+ (raw['title'] as String).trim().isEmpty ||
76
+ raw['version'] is! int ||
77
+ raw['version'] < 1 ||
78
+ raw['active'] is! bool ||
79
+ !_schoolTime(raw['created_at']) ||
80
+ !_schoolTime(raw['updated_at'])) {
81
+ throw const ApiException(502, 'invalid_school_entity');
82
+ }
83
+ if (type == 'contexts' &&
84
+ (raw['user_id'] != api.currentUserId ||
85
+ !['student', 'work', 'personal'].contains(raw['kind']))) {
86
+ throw const ApiException(502, 'invalid_school_entity');
87
+ }
88
+ if (type != 'contexts' &&
89
+ (!_schoolDate(raw['starts_on']) ||
90
+ !_schoolDate(raw['ends_on']) ||
91
+ (raw['ends_on'] as String).compareTo(raw['starts_on'] as String) <
92
+ 0)) {
93
+ throw const ApiException(502, 'invalid_school_entity');
94
+ }
95
+ final parent = type == 'years'
96
+ ? raw['life_context_id']
97
+ : type == 'terms'
98
+ ? raw['academic_year_id']
99
+ : null;
100
+ if (type != 'contexts' &&
101
+ (parent is! String ||
102
+ !_schoolUuid.hasMatch(parent) ||
103
+ (type == 'years' && raw['student_user_id'] != api.currentUserId))) {
104
+ throw const ApiException(502, 'invalid_school_entity');
105
+ }
106
+ return Map<String, dynamic>.from(raw);
107
+ }
108
+
109
+ Future<List<Map<String, dynamic>>> pending() async {
110
+ _scope();
111
+ final rows = await store.readQueue();
112
+ _scope();
113
+ return rows
114
+ .where((row) => _schoolTypes
115
+ .any((type) => row['entityType'] == 'school_lifecycle_$type'))
116
+ .toList();
117
+ }
118
+
119
+ Future<Map<String, dynamic>> read() => _serial(() async {
120
+ var offline = false;
121
+ final result = <String, dynamic>{};
122
+ try {
123
+ final raw = await api.requestJson('GET', '/v1/school/lifecycle');
124
+ _scope();
125
+ if (!_schoolTime(raw['fetchedAt'])) {
126
+ throw const ApiException(502, 'invalid_school_snapshot');
127
+ }
128
+ for (final type in _schoolTypes) {
129
+ if (raw[type] is! List || (raw[type] as List).length > 500) {
130
+ throw const ApiException(502, 'invalid_school_snapshot');
131
+ }
132
+ final rows =
133
+ (raw[type] as List).map((row) => _entity(type, row)).toList();
134
+ if (rows.map((row) => row['id']).toSet().length != rows.length) {
135
+ throw const ApiException(502, 'invalid_school_snapshot');
136
+ }
137
+ result[type] = rows;
138
+ }
139
+ final contexts = {
140
+ for (final row in result['contexts'] as List) row['id']
141
+ };
142
+ final years = {for (final row in result['years'] as List) row['id']};
143
+ if ((result['years'] as List)
144
+ .any((row) => !contexts.contains(row['life_context_id'])) ||
145
+ (result['terms'] as List)
146
+ .any((row) => !years.contains(row['academic_year_id']))) {
147
+ throw const ApiException(502, 'invalid_school_snapshot');
148
+ }
149
+ for (final type in _schoolTypes) {
150
+ await store.writeList('school_lifecycle_$type',
151
+ result[type] as List<Map<String, dynamic>>);
152
+ }
153
+ await store.writeList('school_lifecycle_received', [
154
+ {'fetchedAt': raw['fetchedAt']}
155
+ ]);
156
+ } catch (error) {
157
+ _scope();
158
+ if (!isOfflineFailure(error)) rethrow;
159
+ offline = true;
160
+ for (final type in _schoolTypes) {
161
+ result[type] = (await store.readList('school_lifecycle_$type'))
162
+ .map((row) => _entity(type, row))
163
+ .toList();
164
+ }
165
+ }
166
+ final received = await store.readList('school_lifecycle_received');
167
+ return {
168
+ ...result,
169
+ 'offline': offline,
170
+ 'fetchedAt': received.firstOrNull?['fetchedAt'],
171
+ 'pending': await pending()
172
+ };
173
+ });
174
+ void _validate(String type, Map<String, dynamic> body) {
175
+ if (!_schoolTypes.contains(type) ||
176
+ body['mutationId'] is! String ||
177
+ !_schoolUuid.hasMatch(body['mutationId']) ||
178
+ body['entityId'] is! String ||
179
+ !_schoolUuid.hasMatch(body['entityId']) ||
180
+ !['create', 'update', 'archive'].contains(body['operation']) ||
181
+ body['expectedVersion'] is! int ||
182
+ body['expectedVersion'] < 0 ||
183
+ body['expectedVersion'] > 2147483646 ||
184
+ (body['operation'] == 'create'
185
+ ? body['expectedVersion'] != 0
186
+ : body['expectedVersion'] < 1) ||
187
+ body['data'] is! Map) {
188
+ throw const ApiException(400, 'invalid_school_mutation');
189
+ }
190
+ final data = body['data'] as Map, operation = body['operation'];
191
+ final keys = operation == 'archive'
192
+ ? <String>[]
193
+ : type == 'contexts'
194
+ ? ['title', 'kind']
195
+ : [
196
+ 'title',
197
+ 'startsOn',
198
+ 'endsOn',
199
+ if (operation == 'create')
200
+ type == 'years' ? 'lifeContextId' : 'academicYearId'
201
+ ];
202
+ if (data.keys.any((key) => !keys.contains(key)) ||
203
+ (operation == 'create' && keys.any((key) => !data.containsKey(key))) ||
204
+ (operation == 'update' && data.isEmpty)) {
205
+ throw const ApiException(400, 'invalid_school_input');
206
+ }
207
+ if ((data.containsKey('title') &&
208
+ (data['title'] is! String ||
209
+ (data['title'] as String).trim().isEmpty ||
210
+ (data['title'] as String).length > 120)) ||
211
+ (data.containsKey('kind') &&
212
+ !['student', 'work', 'personal'].contains(data['kind']))) {
213
+ throw const ApiException(400, 'invalid_school_input');
214
+ }
215
+ for (final key in ['startsOn', 'endsOn']) {
216
+ if (data.containsKey(key) && !_schoolDate(data[key])) {
217
+ throw const ApiException(400, 'invalid_school_date');
218
+ }
219
+ }
220
+ if (data['startsOn'] is String &&
221
+ data['endsOn'] is String &&
222
+ (data['endsOn'] as String).compareTo(data['startsOn'] as String) < 0) {
223
+ throw const ApiException(400, 'invalid_school_date');
224
+ }
225
+ for (final key in ['lifeContextId', 'academicYearId']) {
226
+ if (data.containsKey(key) &&
227
+ (data[key] is! String || !_schoolUuid.hasMatch(data[key]))) {
228
+ throw const ApiException(400, 'invalid_school_input');
229
+ }
230
+ }
231
+ }
232
+
233
+ Future<Map<String, dynamic>> mutate(
234
+ String type, String operation, Map<String, dynamic> data,
235
+ {String? entityId, int expectedVersion = 0}) {
236
+ final normalized = {...data};
237
+ if (normalized['title'] is String) {
238
+ normalized['title'] = (normalized['title'] as String).trim();
239
+ }
240
+ for (final key in ['startsOn', 'endsOn']) {
241
+ if (normalized[key] is String) {
242
+ normalized[key] = _latinDigits(normalized[key]);
243
+ }
244
+ }
245
+ final body = Map<String, dynamic>.from(jsonDecode(jsonEncode({
246
+ 'mutationId': newMutationId(),
247
+ 'entityId': entityId ?? newMutationId(),
248
+ 'operation': operation,
249
+ 'expectedVersion': expectedVersion,
250
+ 'data': normalized
251
+ })) as Map);
252
+ _validate(type, body);
253
+ return _serial(() async {
254
+ if ((await pending()).any((row) => row['entityId'] == body['entityId'])) {
255
+ throw const ApiException(409, 'school_sync_pending');
256
+ }
257
+ final record = {
258
+ 'id': body['mutationId'],
259
+ 'entityId': body['entityId'],
260
+ 'entityType': 'school_lifecycle_$type',
261
+ 'operation': operation,
262
+ 'expectedVersion': expectedVersion,
263
+ 'payload': body
264
+ };
265
+ await store.enqueue(record);
266
+ try {
267
+ return {'queued': false, 'entity': await _send(type, record)};
268
+ } catch (error) {
269
+ _scope();
270
+ if (!isOfflineFailure(error)) rethrow;
271
+ return {'queued': true, 'entityId': body['entityId']};
272
+ }
273
+ });
274
+ }
275
+
276
+ Future<Map<String, dynamic>> _send(
277
+ String type, Map<String, dynamic> record) async {
278
+ final body = Map<String, dynamic>.from(record['payload'] as Map);
279
+ _validate(type, body);
280
+ if (record['id'] != body['mutationId'] ||
281
+ record['entityId'] != body['entityId'] ||
282
+ record['entityType'] != 'school_lifecycle_$type' ||
283
+ record['operation'] != body['operation'] ||
284
+ record['expectedVersion'] != body['expectedVersion']) {
285
+ throw const ApiException(422, 'invalid_school_mutation');
286
+ }
287
+ late Map<String, dynamic> raw;
288
+ try {
289
+ raw = await api.requestJson(
290
+ 'POST', '/v1/school/lifecycle/$type/mutations',
291
+ body: body);
292
+ _scope();
293
+ } catch (error) {
294
+ _scope();
295
+ if (error is ApiException &&
296
+ [400, 404, 409, 422].contains(error.statusCode)) {
297
+ await store.markQueued(record['id'] as String,
298
+ error.statusCode == 409 ? 'conflict' : 'rejected',
299
+ error: error.code);
300
+ }
301
+ rethrow;
302
+ }
303
+ final row = _entity(type, raw['entity']), ack = raw['acknowledgement'];
304
+ if (row['id'] != body['entityId'] ||
305
+ ack is! Map ||
306
+ ack['mutationId'] != body['mutationId'] ||
307
+ ack['entityId'] != body['entityId'] ||
308
+ ack['entityType'] != type ||
309
+ ack['operation'] != body['operation'] ||
310
+ !['accepted', 'already_applied'].contains(ack['status']) ||
311
+ ack['appliedVersion'] != body['expectedVersion'] + 1 ||
312
+ row['version'] < ack['appliedVersion'] ||
313
+ !_schoolTime(ack['acceptedAt'])) {
314
+ throw const ApiException(502, 'invalid_school_acknowledgement');
315
+ }
316
+ if (row['version'] == ack['appliedVersion']) {
317
+ const columns = {
318
+ 'title': 'title',
319
+ 'kind': 'kind',
320
+ 'startsOn': 'starts_on',
321
+ 'endsOn': 'ends_on',
322
+ 'lifeContextId': 'life_context_id',
323
+ 'academicYearId': 'academic_year_id'
324
+ };
325
+ if ((body['operation'] == 'archive'
326
+ ? row['active'] != false
327
+ : row['active'] != true) ||
328
+ (body['data'] as Map)
329
+ .entries
330
+ .any((entry) => row[columns[entry.key]] != entry.value)) {
331
+ throw const ApiException(502, 'invalid_school_acknowledgement');
332
+ }
333
+ }
334
+ await store.acknowledge(record['id'] as String,
335
+ item: row,
336
+ acceptedAt: ack['acceptedAt'] as String,
337
+ cacheKey: 'school_lifecycle_$type');
338
+ _scope();
339
+ return row;
340
+ }
341
+
342
+ Future<void> flush() => _serial(() async {
343
+ for (final record in await pending()) {
344
+ if (['conflict', 'rejected'].contains(record['queueStatus'])) {
345
+ throw const ApiException(409, 'school_sync_conflict');
346
+ }
347
+ final type = (record['entityType'] as String)
348
+ .replaceFirst('school_lifecycle_', '');
349
+ await _send(type, record);
350
+ }
351
+ });
352
+ Future<void> useServer(String type, String entityId) async {
353
+ final snapshot = await read();
354
+ if (snapshot['offline'] == true) {
355
+ throw const ApiException(409, 'server_snapshot_required');
356
+ }
357
+ await _serial(() async {
358
+ final row = (snapshot[type] as List<Map<String, dynamic>>)
359
+ .where((row) => row['id'] == entityId)
360
+ .firstOrNull;
361
+ await store.discardEntityChanges(entityId,
362
+ serverItem: row,
363
+ entityType: 'school_lifecycle_$type',
364
+ cacheKey: 'school_lifecycle_$type');
365
+ });
366
+ }
367
+}
368
+
369
+String _schoolError(Object error) {
370
+ if (isOfflineFailure(error)) {
371
+ return 'اتصال برقرار نیست؛ تغییرهای ذخیرهشده هنوز تأیید سرور ندارند.';
372
+ }
373
+ if (error is ApiException) {
374
+ if ([401, 403].contains(error.statusCode)) {
375
+ return 'نشست یا دسترسی معتبر نیست؛ اطلاعات قبلی از صفحه پاک شد.';
376
+ }
377
+ if (error.statusCode == 409) {
378
+ return 'تغییر معلق، تعارض نسخه یا محدودیت اطلاعات وابسته وجود دارد. وضعیت سرور را بررسی کن.';
379
+ }
380
+ if (error.statusCode == 400) {
381
+ return 'عنوان، تاریخ و محدوده سال یا نیمسال را بررسی کن.';
382
+ }
383
+ }
384
+ return 'عملیات با پاسخ معتبر سرور تأیید نشد. وضعیت را تازه کن.';
385
+}
386
+
387
+class SchoolManagementPage extends StatefulWidget {
388
+ const SchoolManagementPage({super.key, required this.api});
389
+ final HttpIdentityApi api;
390
+ @override
391
+ State<SchoolManagementPage> createState() => _SchoolManagementPageState();
392
+}
393
+
394
+class _SchoolManagementPageState extends State<SchoolManagementPage> {
395
+ late final SchoolLifecycleSync sync;
396
+ Map<String, dynamic>? snapshot;
397
+ List<Map<String, dynamic>> subjects = [], classes = [];
398
+ bool busy = false, childrenFresh = false;
399
+ String? error, notice;
400
+ int epoch = 0;
401
+ @override
402
+ void initState() {
403
+ super.initState();
404
+ sync = SchoolLifecycleSync(widget.api);
405
+ load();
406
+ }
407
+
408
+ @override
409
+ void dispose() {
410
+ epoch++;
411
+ super.dispose();
412
+ }
413
+
414
+ bool get writable => !busy && snapshot != null;
415
+ Future<void> load({bool retry = false}) async {
416
+ if (busy) return;
417
+ final mine = ++epoch;
418
+ setState(() {
419
+ busy = true;
420
+ childrenFresh = false;
421
+ });
422
+ try {
423
+ if (retry) await sync.flush();
424
+ final value = await sync.read();
425
+ if (!mounted || mine != epoch) return;
426
+ setState(() {
427
+ snapshot = value;
428
+ error = null;
429
+ subjects = [];
430
+ classes = [];
431
+ });
432
+ if (value['offline'] != true) {
433
+ final overview =
434
+ await widget.api.getSchoolOverview(widget.api.currentUserId!);
435
+ final timetable =
436
+ await widget.api.getTimetable(widget.api.currentUserId!);
437
+ if (!mounted ||
438
+ mine != epoch ||
439
+ widget.api.cacheNamespace != sync.store.scope) {
440
+ return;
441
+ }
442
+ setState(() {
443
+ subjects = (overview['subjects'] as List? ?? [])
444
+ .map((raw) => Map<String, dynamic>.from(raw as Map))
445
+ .toList();
446
+ classes = timetable;
447
+ childrenFresh = true;
448
+ });
449
+ }
450
+ } catch (failure) {
451
+ if (mounted && mine == epoch) {
452
+ setState(() {
453
+ if (failure is ApiException &&
454
+ [401, 403].contains(failure.statusCode)) {
455
+ snapshot = null;
456
+ subjects = [];
457
+ classes = [];
458
+ }
459
+ notice = _schoolError(failure);
460
+ });
461
+ }
462
+ } finally {
463
+ if (mounted && mine == epoch) setState(() => busy = false);
464
+ }
465
+ }
466
+
467
+ List<Map<String, dynamic>> rows(String type) =>
468
+ (snapshot?[type] as List? ?? [])
469
+ .map((raw) => Map<String, dynamic>.from(raw as Map))
470
+ .toList();
471
+ bool contextActive(String id) => rows('contexts').any((row) =>
472
+ row['id'] == id && row['active'] == true && row['kind'] == 'student');
473
+ bool yearActive(String id) => rows('years').any((row) =>
474
+ row['id'] == id &&
475
+ row['active'] == true &&
476
+ contextActive(row['life_context_id'].toString()));
477
+ bool termActive(String id) => rows('terms').any((row) =>
478
+ row['id'] == id &&
479
+ row['active'] == true &&
480
+ yearActive(row['academic_year_id'].toString()));
481
+
482
+ Future<void> editLifecycle(String type, [Map<String, dynamic>? row]) async {
483
+ if (!writable) return;
484
+ final title = TextEditingController(text: row?['title']?.toString() ?? '');
485
+ final starts =
486
+ TextEditingController(text: row?['starts_on']?.toString() ?? '');
487
+ final ends = TextEditingController(text: row?['ends_on']?.toString() ?? '');
488
+ final draftId = row?['id']?.toString() ?? newMutationId();
489
+ var attempted = false;
490
+ var kind = row?['kind']?.toString() ?? 'student';
491
+ String? parentId;
492
+ final parents = type == 'years'
493
+ ? rows('contexts')
494
+ .where((row) => row['active'] == true && row['kind'] == 'student')
495
+ .toList()
496
+ : rows('years')
497
+ .where((row) => yearActive(row['id'].toString()))
498
+ .toList();
499
+ if (row != null) {
500
+ parentId = row[type == 'years' ? 'life_context_id' : 'academic_year_id']
501
+ ?.toString();
502
+ }
503
+ var saving = false;
504
+ String? failure;
505
+ final saved = await showDialog<bool>(
506
+ context: context,
507
+ barrierDismissible: false,
508
+ builder: (dialog) => StatefulBuilder(builder: (context, local) {
509
+ Future<void> pick(TextEditingController target) async {
510
+ final initial = DateTime.tryParse(_latinDigits(target.text));
511
+ final selected = await showDatePicker(
512
+ context: context,
513
+ initialDate: initial != null &&
514
+ initial.year >= 1900 &&
515
+ initial.year <= 2200
516
+ ? initial
517
+ : DateTime.now(),
518
+ firstDate: DateTime(1900),
519
+ lastDate: DateTime(2200, 12, 31));
520
+ if (selected != null) {
521
+ local(() => target.text = _dateText(selected));
522
+ }
523
+ }
524
+
525
+ return AlertDialog(
526
+ title: Text(row == null
527
+ ? 'ایجاد ${_typeLabel(type)}'
528
+ : 'ویرایش ${_typeLabel(type)}'),
529
+ content: SingleChildScrollView(
530
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
531
+ TextField(
532
+ controller: title,
533
+ enabled: !saving,
534
+ maxLength: 120,
535
+ decoration: const InputDecoration(labelText: 'عنوان')),
536
+ if (type == 'contexts')
537
+ DropdownButtonFormField<String>(
538
+ initialValue: kind,
539
+ decoration:
540
+ const InputDecoration(labelText: 'نوع زمینه'),
541
+ items: const [
542
+ DropdownMenuItem(
543
+ value: 'student', child: Text('مدرسه')),
544
+ DropdownMenuItem(value: 'work', child: Text('کار')),
545
+ DropdownMenuItem(
546
+ value: 'personal', child: Text('شخصی'))
547
+ ],
548
+ onChanged: saving
549
+ ? null
550
+ : (value) => local(() => kind = value!)),
551
+ if (type != 'contexts' && row == null)
552
+ DropdownButtonFormField<String>(
553
+ initialValue: parentId,
554
+ decoration: InputDecoration(
555
+ labelText:
556
+ type == 'years' ? 'مدرسه فعال' : 'سال فعال'),
557
+ items: parents
558
+ .map((parent) => DropdownMenuItem(
559
+ value: parent['id'].toString(),
560
+ child: Text(parent['title'].toString())))
561
+ .toList(),
562
+ onChanged: saving
563
+ ? null
564
+ : (value) => local(() => parentId = value)),
565
+ if (type != 'contexts') ...[
566
+ const Text(
567
+ 'تاریخ میلادی: YYYY-MM-DD؛ تاریخ شروع و پایان را خودت انتخاب کن.'),
568
+ TextField(
569
+ controller: starts,
570
+ enabled: !saving,
571
+ textDirection: TextDirection.ltr,
572
+ decoration: InputDecoration(
573
+ labelText: 'تاریخ شروع میلادی',
574
+ suffixIcon: IconButton(
575
+ onPressed: saving ? null : () => pick(starts),
576
+ icon: const Icon(Icons.calendar_month)))),
577
+ TextField(
578
+ controller: ends,
579
+ enabled: !saving,
580
+ textDirection: TextDirection.ltr,
581
+ decoration: InputDecoration(
582
+ labelText: 'تاریخ پایان میلادی',
583
+ suffixIcon: IconButton(
584
+ onPressed: saving ? null : () => pick(ends),
585
+ icon: const Icon(Icons.calendar_month)))),
586
+ ],
587
+ if (failure != null)
588
+ Text(failure!,
589
+ style: TextStyle(
590
+ color: Theme.of(context).colorScheme.error)),
591
+ ])),
592
+ actions: [
593
+ TextButton(
594
+ onPressed:
595
+ saving ? null : () => Navigator.pop(dialog, false),
596
+ child: const Text('انصراف')),
597
+ FilledButton(
598
+ onPressed: saving
599
+ ? null
600
+ : () async {
601
+ if (type != 'contexts' &&
602
+ row == null &&
603
+ parentId == null) {
604
+ local(() => failure =
605
+ 'ابتدا یک زمینه یا سال فعال انتخاب کن.');
606
+ return;
607
+ }
608
+ local(() {
609
+ saving = true;
610
+ failure = null;
611
+ });
612
+ try {
613
+ final data = {
614
+ 'title': title.text,
615
+ if (type == 'contexts') 'kind': kind,
616
+ if (type != 'contexts') ...{
617
+ 'startsOn': starts.text,
618
+ 'endsOn': ends.text
619
+ },
620
+ if (type != 'contexts' && row == null)
621
+ type == 'years'
622
+ ? 'lifeContextId'
623
+ : 'academicYearId': parentId
624
+ };
625
+ attempted = true;
626
+ final result = await sync.mutate(type,
627
+ row == null ? 'create' : 'update', data,
628
+ entityId: draftId,
629
+ expectedVersion:
630
+ row?['version'] as int? ?? 0);
631
+ if (mounted) {
632
+ notice = result['queued'] == true
633
+ ? 'در دستگاه ذخیره شد؛ تا تأیید سرور، مرحله وابسته را نساز.'
634
+ : 'تغییر با تأیید سرور ثبت شد.';
635
+ }
636
+ if (dialog.mounted) {
637
+ Navigator.pop(dialog, true);
638
+ }
639
+ } catch (e) {
640
+ if (dialog.mounted) {
641
+ local(() {
642
+ failure = _schoolError(e);
643
+ saving = false;
644
+ });
645
+ }
646
+ }
647
+ },
648
+ child: Text(saving ? 'در حال ثبت…' : 'ثبت')),
649
+ ]);
650
+ }));
651
+ title.dispose();
652
+ starts.dispose();
653
+ ends.dispose();
654
+ if ((saved == true || attempted) && mounted) await load();
655
+ }
656
+
657
+ Future<void> archive(String type, Map<String, dynamic> row) async {
658
+ final confirmed = await showDialog<bool>(
659
+ context: context,
660
+ builder: (dialog) => AlertDialog(
661
+ title: const Text('بایگانی'),
662
+ content: const Text(
663
+ 'اطلاعات، تکالیف و سابقه حذف نمیشوند. ویرایش اطلاعات وابسته متوقف میشود.'),
664
+ actions: [
665
+ TextButton(
666
+ onPressed: () => Navigator.pop(dialog, false),
667
+ child: const Text('انصراف')),
668
+ FilledButton(
669
+ onPressed: () => Navigator.pop(dialog, true),
670
+ child: const Text('بایگانی'))
671
+ ]));
672
+ if (confirmed != true || !mounted || busy) return;
673
+ setState(() => busy = true);
674
+ try {
675
+ final result = await sync.mutate(type, 'archive', {},
676
+ entityId: row['id'].toString(),
677
+ expectedVersion: row['version'] as int);
678
+ notice = result['queued'] == true
679
+ ? 'بایگانی در انتظار تأیید سرور است.'
680
+ : 'بایگانی با تأیید سرور ثبت شد.';
681
+ } catch (e) {
682
+ if (mounted) setState(() => notice = _schoolError(e));
683
+ } finally {
684
+ if (mounted) {
685
+ setState(() => busy = false);
686
+ await load();
687
+ }
688
+ }
689
+ }
690
+
691
+ Future<void> childWrite(Future<void> Function() action) async {
692
+ if (!writable || !childrenFresh) return;
693
+ setState(() {
694
+ busy = true;
695
+ notice = null;
696
+ });
697
+ try {
698
+ await action();
699
+ if (mounted) notice = 'تغییر اطلاعات درسی با پاسخ سرور ثبت شد.';
700
+ } catch (failure) {
701
+ if (mounted) {
702
+ if (isOfflineFailure(failure) ||
703
+ failure is ApiException && failure.statusCode >= 500) {
704
+ notice =
705
+ 'نتیجه ارسال نامشخص است. این عملیات خودکار تکرار نمیشود؛ پیش از ثبت دوباره، فهرست سرور را تازه و بررسی کن.';
706
+ } else {
707
+ error = _schoolError(failure);
708
+ }
709
+ }
710
+ } finally {
711
+ if (mounted) {
712
+ setState(() => busy = false);
713
+ await load();
714
+ }
715
+ }
716
+ }
717
+
718
+ Future<void> editSubject([Map<String, dynamic>? row]) async {
719
+ final name = TextEditingController(text: row?['name']?.toString() ?? '');
720
+ final teacher =
721
+ TextEditingController(text: row?['teacher_name']?.toString() ?? '');
722
+ var termId = row?['academic_term_id']?.toString();
723
+ final active =
724
+ rows('terms').where((row) => termActive(row['id'].toString())).toList();
725
+ final data = await showDialog<Map<String, dynamic>>(
726
+ context: context,
727
+ builder: (dialog) => StatefulBuilder(
728
+ builder: (context, local) => AlertDialog(
729
+ title: Text(row == null ? 'درس جدید' : 'ویرایش درس'),
730
+ content: SingleChildScrollView(
731
+ child:
732
+ Column(mainAxisSize: MainAxisSize.min, children: [
733
+ TextField(
734
+ controller: name,
735
+ maxLength: 120,
736
+ decoration:
737
+ const InputDecoration(labelText: 'نام درس')),
738
+ TextField(
739
+ controller: teacher,
740
+ maxLength: 120,
741
+ decoration: const InputDecoration(
742
+ labelText: 'نام دبیر؛ اختیاری')),
743
+ DropdownButtonFormField<String>(
744
+ initialValue: termId,
745
+ decoration:
746
+ const InputDecoration(labelText: 'نیمسال فعال'),
747
+ items: active
748
+ .map((term) => DropdownMenuItem(
749
+ value: term['id'].toString(),
750
+ child: Text(term['title'].toString())))
751
+ .toList(),
752
+ onChanged: (value) => local(() => termId = value))
753
+ ])),
754
+ actions: [
755
+ TextButton(
756
+ onPressed: () => Navigator.pop(dialog),
757
+ child: const Text('انصراف')),
758
+ FilledButton(
759
+ onPressed: () =>
760
+ name.text.trim().isEmpty || termId == null
761
+ ? null
762
+ : Navigator.pop(dialog, {
763
+ 'name': name.text.trim(),
764
+ 'teacherName': teacher.text.trim().isEmpty
765
+ ? null
766
+ : teacher.text.trim(),
767
+ 'academicTermId': termId
768
+ }),
769
+ child: const Text('ثبت'))
770
+ ])));
771
+ name.dispose();
772
+ teacher.dispose();
773
+ if (data == null || !mounted) return;
774
+ await childWrite(() async {
775
+ if (row == null) {
776
+ final payload = {...data}..remove('academicTermId');
777
+ await widget.api
778
+ .createSubject(data['academicTermId'].toString(), payload);
779
+ } else {
780
+ await widget.api.requestJson(
781
+ 'PATCH', '/v1/school/subjects/${row['id']}',
782
+ body: data);
783
+ }
784
+ });
785
+ }
786
+
787
+ Future<void> editClass([Map<String, dynamic>? row]) async {
788
+ final starts = TextEditingController(
789
+ text: row?['starts_at']?.toString().substring(0, 5) ?? '');
790
+ final ends = TextEditingController(
791
+ text: row?['ends_at']?.toString().substring(0, 5) ?? '');
792
+ final location =
793
+ TextEditingController(text: row?['location']?.toString() ?? '');
794
+ final until = TextEditingController(
795
+ text: row?['recurrence_until']?.toString().substring(0, 10) ?? '');
796
+ var subjectId = row?['subject_id']?.toString(),
797
+ weekday = row?['weekday'] as int? ?? 1;
798
+ const weekdays = [
799
+ 'شنبه',
800
+ 'یکشنبه',
801
+ 'دوشنبه',
802
+ 'سهشنبه',
803
+ 'چهارشنبه',
804
+ 'پنجشنبه',
805
+ 'جمعه'
806
+ ];
807
+ final data = await showDialog<Map<String, dynamic>>(
808
+ context: context,
809
+ builder: (dialog) => StatefulBuilder(
810
+ builder: (context, local) => AlertDialog(
811
+ title: Text(row == null ? 'کلاس جدید' : 'ویرایش کلاس'),
812
+ content: SingleChildScrollView(
813
+ child:
814
+ Column(mainAxisSize: MainAxisSize.min, children: [
815
+ DropdownButtonFormField<String>(
816
+ initialValue: subjectId,
817
+ decoration:
818
+ const InputDecoration(labelText: 'درس فعال'),
819
+ items: subjects
820
+ .map((subject) => DropdownMenuItem(
821
+ value: subject['id'].toString(),
822
+ child: Text(subject['name'].toString())))
823
+ .toList(),
824
+ onChanged: (value) => local(() => subjectId = value)),
825
+ DropdownButtonFormField<int>(
826
+ initialValue: weekday,
827
+ decoration:
828
+ const InputDecoration(labelText: 'روز هفته'),
829
+ items: List.generate(
830
+ 7,
831
+ (i) => DropdownMenuItem(
832
+ value: i + 1, child: Text(weekdays[i]))),
833
+ onChanged: (value) => local(() => weekday = value!)),
834
+ TextField(
835
+ controller: starts,
836
+ textDirection: TextDirection.ltr,
837
+ decoration: const InputDecoration(
838
+ labelText: 'شروع کلاس HH:mm')),
839
+ TextField(
840
+ controller: ends,
841
+ textDirection: TextDirection.ltr,
842
+ decoration: const InputDecoration(
843
+ labelText: 'پایان کلاس HH:mm')),
844
+ TextField(
845
+ controller: location,
846
+ maxLength: 240,
847
+ decoration:
848
+ const InputDecoration(labelText: 'محل؛ اختیاری')),
849
+ TextField(
850
+ controller: until,
851
+ textDirection: TextDirection.ltr,
852
+ decoration: const InputDecoration(
853
+ labelText:
854
+ 'آخرین تکرار میلادی YYYY-MM-DD؛ اختیاری'))
855
+ ])),
856
+ actions: [
857
+ TextButton(
858
+ onPressed: () => Navigator.pop(dialog),
859
+ child: const Text('انصراف')),
860
+ FilledButton(
861
+ onPressed: () => subjectId == null
862
+ ? null
863
+ : Navigator.pop(dialog, {
864
+ 'subjectId': subjectId,
865
+ 'weekday': weekday,
866
+ 'startsAt': _latinDigits(starts.text),
867
+ 'endsAt': _latinDigits(ends.text),
868
+ 'location': location.text.trim().isEmpty
869
+ ? null
870
+ : location.text.trim(),
871
+ 'recurrenceUntil': until.text.trim().isEmpty
872
+ ? null
873
+ : _latinDigits(until.text)
874
+ }),
875
+ child: const Text('ثبت'))
876
+ ])));
877
+ starts.dispose();
878
+ ends.dispose();
879
+ location.dispose();
880
+ until.dispose();
881
+ if (data == null || !mounted) return;
882
+ await childWrite(() async {
883
+ if (row == null) {
884
+ final payload = {...data}..remove('subjectId');
885
+ await widget.api
886
+ .createClassSession(data['subjectId'].toString(), payload);
887
+ } else {
888
+ await widget.api.requestJson('PATCH', '/v1/school/classes/${row['id']}',
889
+ body: data);
890
+ }
891
+ });
892
+ }
893
+
894
+ Future<void> archiveChild(String path) async {
895
+ final yes = await showDialog<bool>(
896
+ context: context,
897
+ builder: (dialog) => AlertDialog(
898
+ title: const Text('بایگانی اطلاعات درسی'),
899
+ content: const Text('سابقه و تکالیف وابسته حفظ میشود.'),
900
+ actions: [
901
+ TextButton(
902
+ onPressed: () => Navigator.pop(dialog, false),
903
+ child: const Text('انصراف')),
904
+ FilledButton(
905
+ onPressed: () => Navigator.pop(dialog, true),
906
+ child: const Text('بایگانی'))
907
+ ]));
908
+ if (yes == true && mounted) {
909
+ await childWrite(() async {
910
+ await widget.api.requestJson('DELETE', path);
911
+ });
912
+ }
913
+ }
914
+
915
+ @override
916
+ Widget build(BuildContext context) => Scaffold(
917
+ appBar: AppBar(title: const Text('مدیریت مدرسه'), actions: [
918
+ IconButton(
919
+ onPressed: busy ? null : () => load(),
920
+ icon: const Icon(Icons.refresh),
921
+ tooltip: 'تازهکردن')
922
+ ]),
923
+ body: Directionality(
924
+ textDirection: TextDirection.rtl,
925
+ child: ListView(padding: const EdgeInsets.all(16), children: [
926
+ const Text(
927
+ 'این اطلاعات خصوصی است. ابتدا مدرسه، سپس سال با تاریخ دلخواه، نیمسال، درس و کلاس را بساز. هیچ درس یا تاریخی خودکار ساخته نمیشود.'),
928
+ if (busy) const LinearProgressIndicator(),
929
+ if (error != null)
930
+ Text(error!,
931
+ style: TextStyle(color: Theme.of(context).colorScheme.error)),
932
+ if (notice != null)
933
+ Semantics(liveRegion: true, child: Text(notice!)),
934
+ if (snapshot != null)
935
+ Text(snapshot!['offline'] == true
936
+ ? 'نسخه ذخیرهشده؛ داده زنده نیست'
937
+ : 'آخرین دریافت سرور: ${snapshot!['fetchedAt'] ?? 'نامشخص'}'),
938
+ if (snapshot != null &&
939
+ (snapshot!['pending'] as List).isNotEmpty) ...[
940
+ FilledButton(
941
+ onPressed: busy ? null : () => load(retry: true),
942
+ child: const Text('ارسال دوباره تغییرهای ذخیرهشده')),
943
+ ...(snapshot!['pending'] as List).map((raw) {
944
+ final record = Map<String, dynamic>.from(raw as Map);
945
+ final type = (record['entityType'] as String)
946
+ .replaceFirst('school_lifecycle_', '');
947
+ return Card(
948
+ child: ListTile(
949
+ title:
950
+ Text('${_typeLabel(type)}: در انتظار تأیید سرور'),
951
+ subtitle: Text(record['queueStatus'] == 'conflict'
952
+ ? 'تعارض نسخه؛ تغییر محلی نگه داشته شده است'
953
+ : '${record['operation']} · ${(record['payload'] as Map)['data']['title'] ?? ''}'),
954
+ trailing: TextButton(
955
+ onPressed: busy
956
+ ? null
957
+ : () async {
958
+ final yes = await showDialog<bool>(
959
+ context: context,
960
+ builder: (dialog) => AlertDialog(
961
+ title: const Text(
962
+ 'انتخاب نسخه سرور'),
963
+ content: const Text(
964
+ 'تغییر محلی از صف کنار میرود و در سابقه بازیابی دستگاه نگه داشته میشود.'),
965
+ actions: [
966
+ TextButton(
967
+ onPressed: () =>
968
+ Navigator.pop(
969
+ dialog, false),
970
+ child:
971
+ const Text('انصراف')),
972
+ FilledButton(
973
+ onPressed: () =>
974
+ Navigator.pop(
975
+ dialog, true),
976
+ child: const Text(
977
+ 'نسخه سرور'))
978
+ ]));
979
+ if (yes == true && mounted) {
980
+ try {
981
+ await sync.useServer(type,
982
+ record['entityId'].toString());
983
+ await load();
984
+ } catch (e) {
985
+ if (mounted) {
986
+ setState(
987
+ () => error = _schoolError(e));
988
+ }
989
+ }
990
+ }
991
+ },
992
+ child: const Text('بررسی نسخه سرور'))));
993
+ }),
994
+ ],
995
+ for (final type in _schoolTypes) ...[
996
+ Row(children: [
997
+ Expanded(
998
+ child: Text(_typeLabel(type),
999
+ style: Theme.of(context).textTheme.titleMedium)),
1000
+ TextButton.icon(
1001
+ onPressed: writable ? () => editLifecycle(type) : null,
1002
+ icon: const Icon(Icons.add),
1003
+ label: const Text('ایجاد'))
1004
+ ]),
1005
+ ...rows(type).map((row) {
1006
+ final ancestorActive = type == 'contexts' ||
1007
+ (type == 'years'
1008
+ ? contextActive(row['life_context_id'].toString())
1009
+ : yearActive(row['academic_year_id'].toString()));
1010
+ final pending = (snapshot!['pending'] as List)
1011
+ .any((m) => m['entityId'] == row['id']);
1012
+ return Card(
1013
+ child: ListTile(
1014
+ title: Text(row['title'].toString()),
1015
+ subtitle: Text(
1016
+ '${row['active'] == true ? (ancestorActive ? 'فعال' : 'زمینه بالادست بایگانی شده') : 'بایگانیشده'} · نسخه ${_faDigits(row['version'].toString())}${type == 'contexts' ? '' : '\n${_faDigits(row['starts_on'].toString())} تا ${_faDigits(row['ends_on'].toString())} (میلادی)'}'),
1017
+ trailing: Wrap(children: [
1018
+ IconButton(
1019
+ onPressed: writable &&
1020
+ !pending &&
1021
+ row['active'] == true &&
1022
+ ancestorActive
1023
+ ? () => editLifecycle(type, row)
1024
+ : null,
1025
+ icon: const Icon(Icons.edit_outlined),
1026
+ tooltip: 'ویرایش ${_typeLabel(type)}'),
1027
+ IconButton(
1028
+ onPressed:
1029
+ writable && !pending && row['active'] == true
1030
+ ? () => archive(type, row)
1031
+ : null,
1032
+ icon: const Icon(Icons.archive_outlined),
1033
+ tooltip: 'بایگانی ${_typeLabel(type)}')
1034
+ ])));
1035
+ }),
1036
+ ],
1037
+ Row(children: [
1038
+ Expanded(
1039
+ child: Text('درسها',
1040
+ style: Theme.of(context).textTheme.titleMedium)),
1041
+ TextButton.icon(
1042
+ onPressed:
1043
+ writable && childrenFresh ? () => editSubject() : null,
1044
+ icon: const Icon(Icons.add),
1045
+ label: const Text('درس جدید'))
1046
+ ]),
1047
+ ...subjects.map((row) => Card(
1048
+ child: ListTile(
1049
+ title: Text(row['name'].toString()),
1050
+ subtitle: Text(row['teacher_name']?.toString() ??
1051
+ row['term_title']?.toString() ??
1052
+ ''),
1053
+ trailing: Wrap(children: [
1054
+ IconButton(
1055
+ onPressed: writable && childrenFresh
1056
+ ? () => editSubject(row)
1057
+ : null,
1058
+ icon: const Icon(Icons.edit_outlined),
1059
+ tooltip: 'ویرایش درس'),
1060
+ IconButton(
1061
+ onPressed: writable && childrenFresh
1062
+ ? () => archiveChild(
1063
+ '/v1/school/subjects/${row['id']}')
1064
+ : null,
1065
+ icon: const Icon(Icons.archive_outlined),
1066
+ tooltip: 'بایگانی درس')
1067
+ ])))),
1068
+ Row(children: [
1069
+ Expanded(
1070
+ child: Text('کلاسها',
1071
+ style: Theme.of(context).textTheme.titleMedium)),
1072
+ TextButton.icon(
1073
+ onPressed:
1074
+ writable && childrenFresh ? () => editClass() : null,
1075
+ icon: const Icon(Icons.add),
1076
+ label: const Text('کلاس جدید'))
1077
+ ]),
1078
+ ...classes.map((row) => Card(
1079
+ child: ListTile(
1080
+ title: Text(row['subject_name']?.toString() ?? 'کلاس'),
1081
+ subtitle: Text(
1082
+ 'روز ${_faDigits(row['weekday'].toString())} · ${_faDigits(row['starts_at'].toString())} تا ${_faDigits(row['ends_at'].toString())}'),
1083
+ trailing: Wrap(children: [
1084
+ IconButton(
1085
+ onPressed: writable && childrenFresh
1086
+ ? () => editClass(row)
1087
+ : null,
1088
+ icon: const Icon(Icons.edit_outlined),
1089
+ tooltip: 'ویرایش کلاس'),
1090
+ IconButton(
1091
+ onPressed: writable && childrenFresh
1092
+ ? () => archiveChild(
1093
+ '/v1/school/classes/${row['id']}')
1094
+ : null,
1095
+ icon: const Icon(Icons.archive_outlined),
1096
+ tooltip: 'بایگانی کلاس')
1097
+ ])))),
1098
+ ])));
1099
+}
1100
+
1101
+String _typeLabel(String type) => switch (type) {
1102
+ 'contexts' => 'زمینه مدرسه و زندگی',
1103
+ 'years' => 'سال تحصیلی',
1104
+ 'terms' => 'نیمسال',
1105
+ _ => 'اطلاعات مدرسه'
1106
+ };
apps/lifemate/lib/sync_changes_ui.dart
+40
-5
@@ -223,6 +223,34 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
223
_ => 'در انتظار تأیید سرور',
224
};
225
226
+ String _entityTitle(Map<String, dynamic> mutation) =>
227
+ switch (mutation['entityType']) {
228
+ 'study_session' => 'ثبت مطالعه',
229
+ 'learning_progress' => 'پیشرفت درس',
230
+ 'learning_attempt' => 'پاسخ آزمون',
231
+ 'learning_feedback' => 'بازخورد آموزشی',
232
+ 'learning_goal' => 'هدف یادگیری',
233
+ 'family_operation' => 'تغییر خانواده',
234
+ 'content_review' => 'بررسی بازخورد',
235
+ 'content_brief' => 'درخواست برنامه توسعه محتوا',
236
+ 'school_lifecycle_contexts' => 'فضای تحصیلی',
237
+ 'school_lifecycle_years' => 'سال تحصیلی',
238
+ 'school_lifecycle_terms' => 'نیمسال تحصیلی',
239
+ _ => 'تغییر کار',
240
+ };
241
+
242
+ String? _manualRetryPage(Map<String, dynamic> mutation) =>
243
+ switch (mutation['entityType']) {
244
+ 'learning_goal' => 'اهداف یادگیری',
245
+ 'family_operation' => 'مدیریت خانواده',
246
+ 'content_review' || 'content_brief' => 'بررسی محتوای آموزشی',
247
+ 'school_lifecycle_contexts' ||
248
+ 'school_lifecycle_years' ||
249
+ 'school_lifecycle_terms' =>
250
+ 'مدیریت فضای تحصیلی',
251
+ _ => null,
252
+ };
253
+
254
String _details(Map row, {bool server = false}) {
255
const labels = {
256
'title': 'عنوان',
@@ -274,6 +302,11 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
302
onPressed: busy || !storeReady ? null : _retry,
303
icon: const Icon(Icons.sync),
304
label: const Text('تلاش دوباره برای همگامسازی')),
305
+ if (queue.any((row) => _manualRetryPage(row) != null))
306
+ const Padding(
307
+ padding: EdgeInsets.symmetric(vertical: 12),
308
+ child: Text(
309
+ 'تغییرهای خانواده، اهداف و مدیریت محتوا یا تحصیل از صفحه مربوط بررسی و دوباره ارسال میشوند. این دکمه آنها را ارسال نمیکند.')),
310
if (queue.isEmpty)
311
const Padding(
312
padding: EdgeInsets.all(16),
@@ -283,10 +316,12 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
316
title: Text(hiddenEntities.contains(mutation['entityId'])
317
? 'تغییر بدون دسترسی'
318
: (mutation['payload'] as Map)['title']?.toString() ??
286
- (mutation['entityType'] == 'study_session'
287
- ? 'ثبت مطالعه'
288
- : 'تغییر کار')),
289
- subtitle: Text(_status(mutation['queueStatus'])),
319
+ _entityTitle(mutation)),
320
+ subtitle: Text([
321
+ _status(mutation['queueStatus']),
322
+ if (_manualRetryPage(mutation) case final page?)
323
+ 'بررسی و ارسال از «$page»',
324
+ ].join('\n')),
325
trailing: mutation['entityType'] == 'plan_item' &&
326
['conflict', 'rejected']
327
.contains(mutation['queueStatus']) &&
@@ -301,7 +336,7 @@ class _SyncChangesPageState extends State<SyncChangesPage> {
336
Text('پیشنویسهای نگهداریشده',
337
style: Theme.of(context).textTheme.titleMedium),
338
const Text(
304
- 'این تغییرها ارسال نمیشوند. عنوان را برای بازیابی دستی در ویرایش کار نگه داشتهایم.'),
339
+ 'این تغییرها ارسال نمیشوند. اطلاعات آنها برای بازیابی دستی در صفحه مربوط نگه داشته شده است.'),
340
for (final entry in journal)
341
ListTile(
342
title: Text(
apps/lifemate/pubspec.yaml
+1
-1
@@ -1,5 +1,5 @@
1
name: lifemate
2
-version: 0.6.0+5
2
+version: 0.7.0+6
3
publish_to: none
4
description: LifeGuide personal, family and learning companion.
5
environment:
apps/lifemate/test/content_review_navigation_test.dart
new
+114
@@ -0,0 +1,114 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'package:flutter/material.dart';
5
+import 'package:flutter/services.dart';
6
+import 'package:flutter_test/flutter_test.dart';
7
+import 'package:http/http.dart' as http;
8
+import 'package:http/testing.dart';
9
+import 'package:lifemate/api.dart';
10
+import 'package:lifemate/main.dart';
11
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
12
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
13
+
14
+// Explicit HTTP fixtures exercise navigation; they do not certify server grants.
15
+void main() {
16
+ TestWidgetsFlutterBinding.ensureInitialized();
17
+ setUp(() {
18
+ SharedPreferencesAsyncPlatform.instance =
19
+ InMemorySharedPreferencesAsync.withData({});
20
+ String? token;
21
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
22
+ .setMockMethodCallHandler(
23
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
24
+ if (call.method == 'getBlocked') return token != null;
25
+ if (call.method == 'beginWrite') return token = 'navigation-fixture';
26
+ if (call.method == 'completeWrite' && call.arguments == token) {
27
+ token = null;
28
+ return true;
29
+ }
30
+ throw PlatformException(code: 'local_storage_restart_required');
31
+ });
32
+ });
33
+ http.Response json(Object data, [int status = 200]) =>
34
+ http.Response(jsonEncode(data), status,
35
+ headers: {'content-type': 'application/json; charset=utf-8'});
36
+
37
+ HttpIdentityApi client(Future<http.Response> Function() permissions) =>
38
+ HttpIdentityApi(
39
+ baseUrl: 'https://navigation.example.test/api',
40
+ client: MockClient((request) async {
41
+ if (request.url.path.endsWith('/content-capabilities')) {
42
+ return permissions();
43
+ }
44
+ if (request.url.path.endsWith('/profile')) {
45
+ return json({
46
+ 'user_id': 'synthetic-parent',
47
+ 'display_name': 'والد آزمایشی',
48
+ 'profile_category': 'adult',
49
+ 'theme_preference': 'adult_blue',
50
+ });
51
+ }
52
+ return json({'items': [], 'families': []});
53
+ }))
54
+ ..accessToken = 'synthetic-token'
55
+ ..currentUserId = 'synthetic-parent';
56
+
57
+ Future<void> openDrawer(WidgetTester tester) async {
58
+ tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
59
+ await tester.pumpAndSettle();
60
+ }
61
+
62
+ testWidgets('parent category grants no content operations menu',
63
+ (tester) async {
64
+ final api = client(() async => json({'permissions': []}));
65
+ await tester.pumpWidget(MaterialApp(home: HomeShell(api: api)));
66
+ await tester.pumpAndSettle();
67
+ await openDrawer(tester);
68
+ expect(find.text('بررسی محتوای آموزشی'), findsNothing);
69
+ await tester.pumpWidget(const SizedBox());
70
+ api.close();
71
+ });
72
+
73
+ testWidgets('explicit read capability is shown and failed refresh removes it',
74
+ (tester) async {
75
+ var failed = false;
76
+ final api = client(() async => failed
77
+ ? json({'error': 'synthetic_failure'}, 503)
78
+ : json({
79
+ 'permissions': ['feedback.read']
80
+ }));
81
+ await tester.pumpWidget(MaterialApp(home: HomeShell(api: api)));
82
+ await tester.pumpAndSettle();
83
+ await openDrawer(tester);
84
+ await tester.scrollUntilVisible(find.text('بررسی محتوای آموزشی'), 100,
85
+ scrollable: find
86
+ .descendant(
87
+ of: find.byType(Drawer), matching: find.byType(Scrollable))
88
+ .first);
89
+ expect(find.text('بررسی محتوای آموزشی'), findsOneWidget);
90
+ failed = true;
91
+ await tester.pump(const Duration(seconds: 31));
92
+ await tester.pumpAndSettle();
93
+ expect(find.text('بررسی محتوای آموزشی'), findsNothing);
94
+ await tester.pumpWidget(const SizedBox());
95
+ api.close();
96
+ });
97
+
98
+ testWidgets('late grant response from a previous account is discarded',
99
+ (tester) async {
100
+ final delayed = Completer<http.Response>();
101
+ final api = client(() => delayed.future);
102
+ await tester.pumpWidget(MaterialApp(home: HomeShell(api: api)));
103
+ await tester.pump();
104
+ api.currentUserId = 'another-synthetic-account';
105
+ delayed.complete(json({
106
+ 'permissions': ['feedback.read']
107
+ }));
108
+ await tester.pumpAndSettle();
109
+ await openDrawer(tester);
110
+ expect(find.text('بررسی محتوای آموزشی'), findsNothing);
111
+ await tester.pumpWidget(const SizedBox());
112
+ api.close();
113
+ });
114
+}
apps/lifemate/test/content_review_test.dart
new
+410
@@ -0,0 +1,410 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'package:flutter/material.dart';
5
+import 'package:flutter/services.dart';
6
+import 'package:flutter_test/flutter_test.dart';
7
+import 'package:http/http.dart' as http;
8
+import 'package:http/testing.dart';
9
+import 'package:lifemate/api.dart';
10
+import 'package:lifemate/content_review_sync.dart';
11
+import 'package:lifemate/content_review_ui.dart';
12
+import 'package:lifemate/offline_store.dart';
13
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
14
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
15
+
16
+const feedbackId = '81111111-1111-4111-8111-111111111111';
17
+const mutationId = '91111111-1111-4111-8111-111111111111';
18
+const created = '2026-10-11T10:00:00Z';
19
+const briefId = 'a1111111-1111-4111-8111-111111111111';
20
+Map<String, dynamic> validBrief() => {
21
+ 'id': briefId,
22
+ 'title': 'پیشنهاد بررسی و توسعه محتوای آموزشی',
23
+ 'createdAt': created,
24
+ 'sourceCount': 1,
25
+ 'categories': [
26
+ {'category': 'topic_request', 'count': 1}
27
+ ],
28
+ 'units': [],
29
+ 'tasks': [
30
+ 'نسخه رسمی کتاب و هدف یادگیری این درس را بررسی کنید.',
31
+ 'محتوای پیشنهادی و سؤالهای تمرینی را بهطور کامل بازبینی کنید.',
32
+ 'برای تغییر پیشنهادی معیار پذیرش، آزمون و PR مستقل تهیه کنید.',
33
+ 'انتشار محتوا و استقرار فقط پس از بازبینی و مجوز جداگانه انجام شود.'
34
+ ],
35
+ 'notice':
36
+ 'این پیشنهاد ساختاری فاقد متن بازخورد و اطلاعات خصوصی است؛ تأیید محتوا یا دستور انتشار نیست.'
37
+ };
38
+Map<String, dynamic> feedback({String status = 'received', int version = 1}) =>
39
+ {
40
+ 'id': feedbackId,
41
+ 'unitId': null,
42
+ 'category': 'topic_request',
43
+ 'summary': 'تمرین جمع به روش تصویری',
44
+ 'status': status,
45
+ 'version': version,
46
+ 'createdAt': created,
47
+ 'updatedAt': created,
48
+ };
49
+http.Response jsonResponse(Object value, [int status = 200]) =>
50
+ http.Response(jsonEncode(value), status,
51
+ headers: {'content-type': 'application/json; charset=utf-8'});
52
+HttpIdentityApi apiWith(Future<http.Response> Function(http.Request) handler,
53
+ {String actor = 'synthetic-reviewer'}) =>
54
+ HttpIdentityApi(
55
+ baseUrl: 'https://review.example.test/api', client: MockClient(handler))
56
+ ..accessToken = 'synthetic-token'
57
+ ..currentUserId = actor;
58
+
59
+void main() {
60
+ TestWidgetsFlutterBinding.ensureInitialized();
61
+ setUp(() {
62
+ SharedPreferencesAsyncPlatform.instance =
63
+ InMemorySharedPreferencesAsync.withData({});
64
+ String? token;
65
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
66
+ .setMockMethodCallHandler(
67
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
68
+ if (call.method == 'getBlocked') return token != null;
69
+ if (call.method == 'beginWrite') return token = 'review-write';
70
+ if (call.method == 'completeWrite' && call.arguments == token) {
71
+ token = null;
72
+ return true;
73
+ }
74
+ throw PlatformException(code: 'local_storage_restart_required');
75
+ });
76
+ });
77
+
78
+ test(
79
+ 'lost review acknowledgement keeps only metadata and retries exact body after reopen',
80
+ () async {
81
+ var lost = true;
82
+ final sent = <String>[];
83
+ final api = apiWith((request) async {
84
+ if (request.url.path.endsWith('/content-capabilities')) {
85
+ return jsonResponse({
86
+ 'permissions': ['feedback.read', 'feedback.review']
87
+ });
88
+ }
89
+ sent.add(request.body);
90
+ if (lost) throw http.ClientException('synthetic lost receipt');
91
+ return jsonResponse({
92
+ 'feedback': feedback(status: 'triaged', version: 2),
93
+ 'acknowledgement': {
94
+ 'mutationId': mutationId,
95
+ 'feedbackId': feedbackId,
96
+ 'status': 'already_applied'
97
+ }
98
+ });
99
+ });
100
+ final body = {
101
+ 'mutationId': mutationId,
102
+ 'expectedVersion': 1,
103
+ 'status': 'triaged'
104
+ };
105
+ await expectLater(ContentReviewSync(api).review(feedbackId, body),
106
+ throwsA(predicate(isOfflineFailure)));
107
+ final durable = await OfflineStore.forApi(api).readQueue();
108
+ expect(durable.single['payload'], body);
109
+ expect(jsonEncode(durable), isNot(contains('تمرین جمع')));
110
+ expect(await OfflineStore.forApi(api).readList('content_review'), isEmpty);
111
+ lost = false;
112
+ await ContentReviewSync(api).retry(durable.single);
113
+ expect(sent.length, 2);
114
+ expect(sent[0], sent[1]);
115
+ expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
116
+ api.close();
117
+ });
118
+
119
+ test(
120
+ 'wrong receipt leaves pending metadata and another account cannot retry it',
121
+ () async {
122
+ final api = apiWith((request) async => request.method == 'GET'
123
+ ? jsonResponse({
124
+ 'permissions': ['feedback.read', 'feedback.review']
125
+ })
126
+ : jsonResponse({
127
+ 'feedback': feedback(status: 'triaged', version: 2),
128
+ 'acknowledgement': {
129
+ 'mutationId': 'wrong',
130
+ 'feedbackId': feedbackId,
131
+ 'status': 'accepted'
132
+ }
133
+ }));
134
+ final sync = ContentReviewSync(api);
135
+ await expectLater(
136
+ sync.review(feedbackId, {
137
+ 'mutationId': mutationId,
138
+ 'expectedVersion': 1,
139
+ 'status': 'triaged'
140
+ }),
141
+ throwsA(isA<ApiException>()));
142
+ final pending = (await sync.pending()).single;
143
+ api.currentUserId = 'other-account';
144
+ await expectLater(sync.retry(pending), throwsA(isA<ApiException>()));
145
+ expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
146
+ api.close();
147
+ });
148
+
149
+ test('offline capability check never creates a reviewer mutation', () async {
150
+ final api =
151
+ apiWith((request) async => throw http.ClientException('offline'));
152
+ await expectLater(
153
+ ContentReviewSync(api).review(feedbackId, {
154
+ 'mutationId': mutationId,
155
+ 'expectedVersion': 1,
156
+ 'status': 'triaged'
157
+ }),
158
+ throwsA(predicate(isOfflineFailure)));
159
+ expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
160
+ api.close();
161
+ });
162
+
163
+ test(
164
+ 'lost brief receipt retries immutable metadata and never exports a summary',
165
+ () async {
166
+ var lost = true;
167
+ final sent = <String>[];
168
+ final api = apiWith((request) async {
169
+ if (request.url.path.endsWith('/content-capabilities')) {
170
+ return jsonResponse({
171
+ 'permissions': ['feedback.read', 'brief.prepare']
172
+ });
173
+ }
174
+ sent.add(request.body);
175
+ if (lost) throw http.ClientException('lost response');
176
+ return jsonResponse({
177
+ 'brief': validBrief(),
178
+ 'acknowledgement': {
179
+ 'mutationId': mutationId,
180
+ 'briefId': briefId,
181
+ 'status': 'already_applied'
182
+ }
183
+ });
184
+ });
185
+ final body = <String, dynamic>{
186
+ 'mutationId': mutationId,
187
+ 'feedback': [
188
+ {'id': feedbackId, 'expectedVersion': 3}
189
+ ]
190
+ };
191
+ final result = ContentReviewSync(api).prepareBrief(body);
192
+ (body['feedback'] as List).single['expectedVersion'] = 999;
193
+ await expectLater(result, throwsA(predicate(isOfflineFailure)));
194
+ final saved = (await ContentReviewSync(api).pending()).single;
195
+ expect((saved['payload'] as Map)['feedback'], [
196
+ {'id': feedbackId, 'expectedVersion': 3}
197
+ ]);
198
+ expect(jsonEncode(saved), isNot(contains('summary')));
199
+ lost = false;
200
+ final accepted = await ContentReviewSync(api).retry(saved);
201
+ expect(sent[0], sent[1]);
202
+ expect(accepted['brief'], validBrief());
203
+ expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
204
+ api.close();
205
+ });
206
+
207
+ test(
208
+ 'current newer state can acknowledge an applied review but wrong accepted transition cannot',
209
+ () async {
210
+ var replay = false;
211
+ final api = apiWith((request) async {
212
+ if (request.method == 'GET') {
213
+ return jsonResponse({
214
+ 'permissions': ['feedback.read', 'feedback.review']
215
+ });
216
+ }
217
+ return jsonResponse({
218
+ 'feedback': feedback(status: 'planned', version: 3),
219
+ 'acknowledgement': {
220
+ 'mutationId': mutationId,
221
+ 'feedbackId': feedbackId,
222
+ 'status': replay ? 'already_applied' : 'accepted'
223
+ }
224
+ });
225
+ });
226
+ final sync = ContentReviewSync(api);
227
+ await expectLater(
228
+ sync.review(feedbackId, {
229
+ 'mutationId': mutationId,
230
+ 'expectedVersion': 1,
231
+ 'status': 'triaged'
232
+ }),
233
+ throwsA(isA<ApiException>()));
234
+ expect(await sync.pending(), hasLength(1));
235
+ replay = true;
236
+ await sync.retry((await sync.pending()).single);
237
+ expect(await sync.pending(), isEmpty);
238
+ api.close();
239
+ });
240
+
241
+ test(
242
+ 'inbox rejects injected private fields and preserves actual paging/filter query',
243
+ () async {
244
+ final api = apiWith((request) async {
245
+ expect(request.url.queryParameters,
246
+ {'limit': '20', 'cursor': feedbackId, 'status': 'planned'});
247
+ return jsonResponse({
248
+ 'feedback': [
249
+ {
250
+ ...feedback(status: 'planned'),
251
+ 'ownerEmail': 'synthetic@example.test'
252
+ }
253
+ ],
254
+ 'nextCursor': null,
255
+ 'total': 1
256
+ });
257
+ });
258
+ await expectLater(
259
+ ContentReviewSync(api).inbox(status: 'planned', cursor: feedbackId),
260
+ throwsA(isA<ApiException>()));
261
+ expect(await OfflineStore.forApi(api).readList('content_review'), isEmpty);
262
+ api.close();
263
+ });
264
+
265
+ test('revoked scope discards a delayed inbox response', () async {
266
+ final delayed = Completer<http.Response>();
267
+ final api = apiWith((request) => delayed.future);
268
+ final sync = ContentReviewSync(api);
269
+ final request = sync.inbox();
270
+ await Future<void>.delayed(Duration.zero);
271
+ await OfflineStore.invalidateNamespace(api.cacheNamespace!);
272
+ delayed.complete(jsonResponse({
273
+ 'feedback': [feedback()],
274
+ 'nextCursor': null,
275
+ 'total': 1
276
+ }));
277
+ await expectLater(request, throwsA(isA<ApiException>()));
278
+ api.close();
279
+ });
280
+
281
+ testWidgets(
282
+ 'read-only reviewer sees Persian status but no moderation buttons, and network failure clears summaries',
283
+ (tester) async {
284
+ var failing = false;
285
+ final api = apiWith((request) async {
286
+ if (failing) throw http.ClientException('synthetic offline');
287
+ if (request.url.path.endsWith('/content-capabilities')) {
288
+ return jsonResponse({
289
+ 'permissions': ['feedback.read']
290
+ });
291
+ }
292
+ return jsonResponse({
293
+ 'feedback': [feedback()],
294
+ 'nextCursor': null,
295
+ 'total': 1
296
+ });
297
+ });
298
+ await tester.pumpWidget(MaterialApp(home: ContentReviewPage(api: api)));
299
+ await tester.pumpAndSettle();
300
+ expect(find.text('تمرین جمع به روش تصویری'), findsOneWidget);
301
+ expect(find.textContaining('دریافتشده'), findsWidgets);
302
+ expect(find.byKey(const Key('review-status-$feedbackId')), findsNothing);
303
+ failing = true;
304
+ await tester.tap(find.byKey(const Key('content-refresh')));
305
+ await tester.pumpAndSettle();
306
+ expect(find.text('تمرین جمع به روش تصویری'), findsNothing);
307
+ expect(find.textContaining('اتصال'), findsWidgets);
308
+ await tester.pumpWidget(const SizedBox());
309
+ api.close();
310
+ });
311
+
312
+ testWidgets(
313
+ 'late inbox response cannot expose summaries after newer permission revocation',
314
+ (tester) async {
315
+ final delayed = Completer<http.Response>();
316
+ var capabilityReads = 0;
317
+ final api = apiWith((request) async {
318
+ if (request.url.path.endsWith('/content-capabilities')) {
319
+ capabilityReads++;
320
+ return jsonResponse({
321
+ 'permissions': capabilityReads == 1 ? ['feedback.read'] : []
322
+ });
323
+ }
324
+ return delayed.future;
325
+ });
326
+ await tester.pumpWidget(MaterialApp(home: ContentReviewPage(api: api)));
327
+ await tester.pump();
328
+ await tester.pump();
329
+ await tester.tap(find.byKey(const Key('content-refresh')));
330
+ await tester.pumpAndSettle();
331
+ delayed.complete(jsonResponse({
332
+ 'feedback': [feedback()],
333
+ 'nextCursor': null,
334
+ 'total': 1
335
+ }));
336
+ await tester.pumpAndSettle();
337
+ expect(find.text('تمرین جمع به روش تصویری'), findsNothing);
338
+ expect(find.textContaining('مجوز'), findsWidgets);
339
+ await tester.pumpWidget(const SizedBox());
340
+ api.close();
341
+ });
342
+
343
+ testWidgets(
344
+ 'withdrawn brief is revalidated before clipboard and never copied',
345
+ (tester) async {
346
+ tester.view.physicalSize = const Size(1000, 1600);
347
+ tester.view.devicePixelRatio = 1;
348
+ addTearDown(tester.view.resetPhysicalSize);
349
+ addTearDown(tester.view.resetDevicePixelRatio);
350
+ final clipboardWrites = <Object?>[];
351
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
352
+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {
353
+ if (call.method == 'Clipboard.setData') {
354
+ clipboardWrites.add(call.arguments);
355
+ }
356
+ return null;
357
+ });
358
+ addTearDown(() => TestDefaultBinaryMessengerBinding
359
+ .instance.defaultBinaryMessenger
360
+ .setMockMethodCallHandler(SystemChannels.platform, null));
361
+ var revalidated = false;
362
+ final api = apiWith((request) async {
363
+ if (request.url.path.endsWith('/content-capabilities')) {
364
+ return jsonResponse({
365
+ 'permissions': ['feedback.read', 'brief.prepare']
366
+ });
367
+ }
368
+ if (request.method == 'POST') {
369
+ final body = jsonDecode(request.body) as Map;
370
+ expect(body['feedback'], [
371
+ {'id': feedbackId, 'expectedVersion': 3}
372
+ ]);
373
+ return jsonResponse({
374
+ 'brief': validBrief(),
375
+ 'acknowledgement': {
376
+ 'mutationId': body['mutationId'],
377
+ 'briefId': briefId,
378
+ 'status': 'accepted'
379
+ }
380
+ });
381
+ }
382
+ if (request.url.path.endsWith('/briefs/$briefId')) {
383
+ revalidated = true;
384
+ return jsonResponse({'error': 'brief_invalidated'}, 409);
385
+ }
386
+ return jsonResponse({
387
+ 'feedback': [feedback(status: 'planned', version: 3)],
388
+ 'nextCursor': null,
389
+ 'total': 1
390
+ });
391
+ });
392
+ await tester.pumpWidget(MaterialApp(home: ContentReviewPage(api: api)));
393
+ await tester.pumpAndSettle();
394
+ await tester.tap(find.byType(Checkbox));
395
+ await tester.pumpAndSettle();
396
+ await tester.tap(find.text('تهیه پیشنهاد توسعه، بدون متن بازخورد'));
397
+ await tester.pumpAndSettle();
398
+ expect(find.byKey(const Key('copy-content-brief')), findsOneWidget);
399
+ await tester.ensureVisible(find.byKey(const Key('copy-content-brief')));
400
+ await tester.tap(find.byKey(const Key('copy-content-brief')));
401
+ await tester.pumpAndSettle();
402
+ expect(revalidated, true);
403
+ expect(clipboardWrites, isEmpty);
404
+ expect(find.byKey(const Key('copy-content-brief')), findsNothing);
405
+ expect(find.text('تمرین جمع به روش تصویری'), findsNothing);
406
+ expect(find.textContaining('نسخه یا رضایت'), findsOneWidget);
407
+ await tester.pumpWidget(const SizedBox());
408
+ api.close();
409
+ });
410
+}
apps/lifemate/test/dashboard_periods_test.dart
new
+342
@@ -0,0 +1,342 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+import 'package:flutter/material.dart';
4
+import 'package:flutter_test/flutter_test.dart';
5
+import 'package:http/http.dart' as http;
6
+import 'package:http/testing.dart';
7
+import 'package:lifemate/api.dart';
8
+import 'package:lifemate/dashboard_ui.dart';
9
+import 'package:lifemate/session_store.dart';
10
+
11
+class _MemorySession extends SessionStore {
12
+ String? value;
13
+ @override
14
+ Future<String?> read() async => value;
15
+ @override
16
+ Future<void> write(String next) async => value = next;
17
+ @override
18
+ Future<void> clear() async => value = null;
19
+}
20
+
21
+http.Response _response(Map<String, dynamic> body) =>
22
+ http.Response(jsonEncode(body), 200,
23
+ headers: {'content-type': 'application/json'});
24
+DateTime _rangeEnd() {
25
+ final now = DateTime.now().toUtc().add(const Duration(hours: 3, minutes: 30));
26
+ return DateTime.utc(now.year, now.month, now.day + 1)
27
+ .subtract(const Duration(hours: 3, minutes: 30));
28
+}
29
+
30
+Map<String, dynamic> _report(String taskTitle) => {
31
+ 'metrics': {
32
+ 'totalTasks': 99,
33
+ 'completedTasks': 90,
34
+ 'completionPercent': 91,
35
+ 'plannedDurationSeconds': 60000,
36
+ 'recordedDurationSeconds': 1500
37
+ },
38
+ 'allTimeTaskMetrics': {'totalTasks': 99, 'completedTasks': 90},
39
+ 'periodMetrics': {
40
+ 'totalTasks': 2,
41
+ 'completedTasks': 1,
42
+ 'completionPercent': 50,
43
+ 'overdueTasks': 0,
44
+ 'plannedDurationSeconds': 1800,
45
+ 'recordedDurationSeconds': 1500,
46
+ 'examCount': 1,
47
+ 'gradedExamCount': 1,
48
+ 'gradePercent': 75
49
+ },
50
+ 'items': [
51
+ {
52
+ 'id': 'period-plan',
53
+ 'title': taskTitle,
54
+ 'kind': 'assignment',
55
+ 'taskInRange': true,
56
+ 'recordedDurationSeconds': 600
57
+ },
58
+ {
59
+ 'id': 'old-plan',
60
+ 'title': 'خارج از بازه بدون زمان',
61
+ 'kind': 'assignment',
62
+ 'taskInRange': false,
63
+ 'recordedDurationSeconds': 0
64
+ },
65
+ {
66
+ 'id': 'recorded-old-plan',
67
+ 'title': 'تکلیف قدیمی با زمان این بازه',
68
+ 'kind': 'assignment',
69
+ 'taskInRange': false,
70
+ 'recordedDurationSeconds': 900
71
+ },
72
+ ],
73
+ 'daily': [],
74
+ 'subjects': [
75
+ {'subjectName': 'درس تاریخی', 'totalTasks': 99}
76
+ ],
77
+ 'periodSubjects': [
78
+ {
79
+ 'subjectId': 'subject-a',
80
+ 'subjectName': 'ریاضی',
81
+ 'totalTasks': 2,
82
+ 'completedTasks': 1,
83
+ 'recordedDurationSeconds': 1500,
84
+ 'gradePercent': 75,
85
+ 'gradedExamCount': 1
86
+ }
87
+ ],
88
+ 'periodExams': [
89
+ {
90
+ 'id': 'exam',
91
+ 'title': 'امتحان مجاز',
92
+ 'kind': 'exam',
93
+ 'gradePoints': 15,
94
+ 'gradeOutOf': 20,
95
+ 'dueAt': '2026-10-10T10:00:00Z'
96
+ }
97
+ ],
98
+ 'asOf': '2026-10-11T10:00:00Z',
99
+ 'lastSyncAt': '2026-10-11T09:00:00Z',
100
+ 'from': _rangeEnd().subtract(const Duration(days: 7)).toIso8601String(),
101
+ 'to': _rangeEnd().toIso8601String(),
102
+ 'timezone': 'Asia/Tehran',
103
+ 'taskDatePolicy': 'due_at_then_starts_at',
104
+ 'rangeConvention': 'inclusive_from_exclusive_to',
105
+ 'completionBasis': 'current_status_of_period_tasks',
106
+ };
107
+
108
+HttpIdentityApi _api(Future<http.Response> Function(http.Request) handler) =>
109
+ HttpIdentityApi(
110
+ baseUrl: 'https://synthetic.example.test',
111
+ client: MockClient(handler),
112
+ sessionStore: _MemorySession())
113
+ ..accessToken = 'synthetic-token'
114
+ ..currentUserId = 'synthetic-parent';
115
+Widget _page(HttpIdentityApi api, {String childId = 'child'}) => MaterialApp(
116
+ home: LearningReportPage(
117
+ api: api, familyId: 'family', childId: childId, childName: 'فرزند'));
118
+
119
+void main() {
120
+ testWidgets(
121
+ 'range dashboard uses period counters and preserves explicitly labelled history',
122
+ (tester) async {
123
+ final api = _api((_) async => _response(_report('تکلیف بازه')));
124
+ await tester.pumpWidget(_page(api));
125
+ await tester.pumpAndSettle();
126
+ expect(find.text('2 تکلیف در بازه'), findsOneWidget);
127
+ expect(find.text('50٪ تکمیل تکلیفهای بازه'), findsOneWidget);
128
+ expect(find.textContaining('کل سابقه مجاز: 99 تکلیف'), findsOneWidget);
129
+ expect(find.text('زمان برنامهریزیشده: 30 دقیقه'), findsOneWidget);
130
+ expect(find.text('زمان ثبتشده: 25 دقیقه'), findsOneWidget);
131
+ expect(find.text('خارج از بازه بدون زمان'), findsNothing);
132
+ expect(find.text('درس تاریخی'), findsNothing);
133
+ await tester.scrollUntilVisible(
134
+ find.text('تکلیف قدیمی با زمان این بازه'), 250);
135
+ expect(find.text('تکلیف قدیمی با زمان این بازه'), findsOneWidget);
136
+ expect(
137
+ find.textContaining('موعد این تکلیف خارج از بازه است'), findsOneWidget);
138
+ await tester.pumpWidget(const SizedBox());
139
+ api.close();
140
+ });
141
+
142
+ testWidgets(
143
+ 'older server counters are clearly historical and do not claim period completion',
144
+ (tester) async {
145
+ final data = _report('تکلیف تاریخی')
146
+ ..remove('periodMetrics')
147
+ ..remove('periodSubjects')
148
+ ..remove('periodExams');
149
+ final api = _api((_) async => _response(data));
150
+ await tester.pumpWidget(_page(api));
151
+ await tester.pumpAndSettle();
152
+ expect(find.textContaining('سرور آمار تکلیفهای بازه را ارائه نکرده'),
153
+ findsOneWidget);
154
+ expect(find.text('99 تکلیف در کل سابقه مجاز'), findsOneWidget);
155
+ expect(find.text('91٪ تکمیل تکلیفهای بازه'), findsNothing);
156
+ await tester.pumpWidget(const SizedBox());
157
+ api.close();
158
+ });
159
+
160
+ testWidgets(
161
+ 'delayed previous-child report cannot overwrite the newly selected child',
162
+ (tester) async {
163
+ final first = Completer<http.Response>();
164
+ var calls = 0;
165
+ final api = _api((request) {
166
+ calls++;
167
+ return request.url.path.contains('/children/first/')
168
+ ? first.future
169
+ : Future.value(_response(_report('گزارش فرزند دوم')));
170
+ });
171
+ await tester.pumpWidget(_page(api, childId: 'first'));
172
+ await tester.pump();
173
+ await tester.pumpWidget(_page(api, childId: 'second'));
174
+ await tester.pumpAndSettle();
175
+ expect(calls, 2);
176
+ await tester.scrollUntilVisible(find.text('گزارش فرزند دوم'), 250);
177
+ first.complete(_response(_report('گزارش فرزند اول قدیمی')));
178
+ await tester.pumpAndSettle();
179
+ expect(find.text('گزارش فرزند اول قدیمی'), findsNothing);
180
+ expect(find.text('گزارش فرزند دوم'), findsOneWidget);
181
+ await tester.pumpWidget(const SizedBox());
182
+ api.close();
183
+ });
184
+
185
+ testWidgets('signed-out report never requests or exposes a child report',
186
+ (tester) async {
187
+ var calls = 0;
188
+ final api = _api((_) async {
189
+ calls++;
190
+ return _response(_report('اطلاعات خصوصی بدون حساب'));
191
+ })
192
+ ..accessToken = null;
193
+ await tester.pumpWidget(_page(api));
194
+ await tester.pumpAndSettle();
195
+ expect(calls, 0);
196
+ expect(find.text('اطلاعات خصوصی بدون حساب'), findsNothing);
197
+ expect(find.textContaining('نشست ورود معتبر نیست'), findsOneWidget);
198
+ await tester.pumpWidget(const SizedBox());
199
+ api.close();
200
+ });
201
+
202
+ testWidgets(
203
+ 'malformed period response is refused instead of fabricated zeroes',
204
+ (tester) async {
205
+ final data = _report('پاسخ نامعتبر')
206
+ ..['periodMetrics'] = {'totalTasks': -1};
207
+ final api = _api((_) async => _response(data));
208
+ await tester.pumpWidget(_page(api));
209
+ await tester.pumpAndSettle();
210
+ expect(find.text('-1 تکلیف در بازه'), findsNothing);
211
+ expect(find.text('0٪ تکمیل تکلیفهای بازه'), findsNothing);
212
+ expect(find.textContaining('پاسخ معتبر نداد'), findsOneWidget);
213
+ await tester.pumpWidget(const SizedBox());
214
+ api.close();
215
+ });
216
+
217
+ testWidgets(
218
+ 'failed refresh clears period metrics without old permission proof',
219
+ (tester) async {
220
+ var fail = false;
221
+ final api = _api((_) async => fail
222
+ ? http.Response('{"error":"synthetic_failed"}', 500,
223
+ headers: {'content-type': 'application/json'})
224
+ : _response(_report('تکلیف مجاز قبلی')));
225
+ await tester.pumpWidget(_page(api));
226
+ await tester.pumpAndSettle();
227
+ expect(find.text('2 تکلیف در بازه'), findsOneWidget);
228
+ fail = true;
229
+ await tester.pump(const Duration(seconds: 15));
230
+ await tester.pumpAndSettle();
231
+ expect(find.text('2 تکلیف در بازه'), findsNothing);
232
+ expect(find.textContaining('اطلاعات فرزند بدون تأیید مجوز فعلی'),
233
+ findsOneWidget);
234
+ await tester.pumpWidget(const SizedBox());
235
+ api.close();
236
+ });
237
+
238
+ testWidgets('family dashboard clears prior account while replacement waits',
239
+ (tester) async {
240
+ final second = Completer<http.Response>();
241
+ final firstApi =
242
+ _api((request) async => _response(request.url.path.endsWith('/members')
243
+ ? {
244
+ 'members': [
245
+ {
246
+ 'user_id': 'first-child',
247
+ 'role': 'teen_minor',
248
+ 'display_name': 'فرزند حساب پیشین'
249
+ }
250
+ ]
251
+ }
252
+ : {
253
+ 'families': [
254
+ {
255
+ 'id': 'family',
256
+ 'role': 'parent_guardian',
257
+ 'name': 'خانواده اول'
258
+ }
259
+ ]
260
+ }));
261
+ final secondApi = _api((_) => second.future)
262
+ ..currentUserId = 'second-synthetic-parent';
263
+ Widget family(HttpIdentityApi api) =>
264
+ MaterialApp(home: Scaffold(body: ParentFamilyDashboard(api: api)));
265
+ await tester.pumpWidget(family(firstApi));
266
+ await tester.pumpAndSettle();
267
+ expect(find.text('فرزند حساب پیشین'), findsOneWidget);
268
+ await tester.pumpWidget(family(secondApi));
269
+ await tester.pump();
270
+ expect(find.text('فرزند حساب پیشین'), findsNothing);
271
+ second.complete(_response({'families': []}));
272
+ await tester.pumpAndSettle();
273
+ expect(find.text('فرزند متصل نمایش داده نشد'), findsOneWidget);
274
+ await tester.pumpWidget(const SizedBox());
275
+ firstApi.close();
276
+ secondApi.close();
277
+ });
278
+
279
+ testWidgets(
280
+ 'pausing clears a report and resumed fetch must freshly authorize',
281
+ (tester) async {
282
+ final delayed = Completer<http.Response>();
283
+ var calls = 0;
284
+ final api = _api((_) {
285
+ calls++;
286
+ return calls == 1
287
+ ? Future.value(_response(_report('داده مجاز قبلی')))
288
+ : delayed.future;
289
+ });
290
+ await tester.pumpWidget(_page(api));
291
+ await tester.pumpAndSettle();
292
+ expect(find.text('2 تکلیف در بازه'), findsOneWidget);
293
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
294
+ await tester.pump();
295
+ expect(find.text('2 تکلیف در بازه'), findsNothing);
296
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
297
+ await tester.pump();
298
+ expect(find.text('2 تکلیف در بازه'), findsNothing);
299
+ delayed.complete(_response(_report('داده تازه مجاز')));
300
+ await tester.pumpAndSettle();
301
+ expect(calls, 2);
302
+ expect(find.text('2 تکلیف در بازه'), findsOneWidget);
303
+ await tester.pumpWidget(const SizedBox());
304
+ api.close();
305
+ });
306
+
307
+ for (final field in ['from', 'familyId', 'childId']) {
308
+ testWidgets('report rejects mismatched requested $field', (tester) async {
309
+ final data = _report('گزارش خارج از درخواست');
310
+ data[field] =
311
+ field == 'from' ? '2025-01-01T00:00:00Z' : 'another-synthetic-id';
312
+ final api = _api((_) async => _response(data));
313
+ await tester.pumpWidget(_page(api));
314
+ await tester.pumpAndSettle();
315
+ expect(find.text('2 تکلیف در بازه'), findsNothing);
316
+ expect(find.textContaining('پاسخ معتبر نداد'), findsOneWidget);
317
+ await tester.pumpWidget(const SizedBox());
318
+ api.close();
319
+ });
320
+ }
321
+
322
+ testWidgets('same API account switch requests new report immediately',
323
+ (tester) async {
324
+ var calls = 0;
325
+ final api = _api((_) async {
326
+ calls++;
327
+ return _response(
328
+ _report(calls == 1 ? 'گزارش حساب اول' : 'گزارش حساب دوم'));
329
+ });
330
+ await tester.pumpWidget(_page(api));
331
+ await tester.pumpAndSettle();
332
+ expect(calls, 1);
333
+ api.currentUserId = 'another-synthetic-parent';
334
+ await tester.pumpWidget(_page(api));
335
+ await tester.pumpAndSettle();
336
+ expect(calls, 2);
337
+ await tester.scrollUntilVisible(find.text('گزارش حساب دوم'), 200);
338
+ expect(find.text('گزارش حساب اول'), findsNothing);
339
+ await tester.pumpWidget(const SizedBox());
340
+ api.close();
341
+ });
342
+}
apps/lifemate/test/education_ui_test.dart
+125
@@ -1,5 +1,7 @@
1
import 'dart:convert';
2
+import 'dart:ui' show SemanticsRole;
3
4
+import 'package:flutter/foundation.dart' show kIsWeb;
5
import 'package:flutter/material.dart';
6
import 'package:flutter/services.dart';
7
import 'package:flutter_test/flutter_test.dart';
@@ -50,6 +52,120 @@ void main() {
52
..accessToken = 'synthetic-fixture-token'
53
..currentUserId = 'synthetic-learner';
54
55
+ Future<void> showProgress(WidgetTester tester) async {
56
+ await tester.scrollUntilVisible(find.textContaining('پیشرفت شخصی:'), 100,
57
+ scrollable: find.byType(Scrollable).first);
58
+ await tester.pumpAndSettle();
59
+ }
60
+
61
+ void expectProgressAnnouncement(WidgetTester tester, String label) {
62
+ final announcement = find.bySemanticsLabel(label);
63
+ expect(announcement, findsOneWidget);
64
+ expect(
65
+ tester.getSemantics(announcement),
66
+ matchesSemantics(
67
+ label: label,
68
+ role: kIsWeb ? SemanticsRole.status : SemanticsRole.none,
69
+ isLiveRegion: !kIsWeb,
70
+ textDirection: TextDirection.rtl));
71
+ }
72
+
73
+ testWidgets(
74
+ 'progress live region announces acknowledged status and timestamp after update and reopen',
75
+ (tester) async {
76
+ final semantics = tester.ensureSemantics();
77
+ Map<String, dynamic>? progress;
78
+ final api = makeApi((request) async {
79
+ if (request.method == 'PUT') {
80
+ final submitted = jsonDecode(request.body) as Map<String, dynamic>;
81
+ progress = {
82
+ ...submitted,
83
+ 'unitId': firstId,
84
+ 'version': 1,
85
+ 'updatedAt': '2026-10-11T10:00:00Z',
86
+ 'acceptedAt': '2026-10-11T10:00:00Z'
87
+ };
88
+ return response(progress!);
89
+ }
90
+ return response({
91
+ 'id': courseId,
92
+ 'titleFa': 'کتاب آزمایشی',
93
+ 'units': [
94
+ {
95
+ 'id': firstId,
96
+ 'titleFa': 'درس آزمایشی',
97
+ 'videos': [],
98
+ 'progress': progress
99
+ }
100
+ ]
101
+ });
102
+ });
103
+ Widget lesson() => screen(
104
+ LearningLessonPage(api: api, courseId: courseId, unitId: firstId));
105
+ await tester.pumpWidget(lesson());
106
+ await tester.pumpAndSettle();
107
+ await showProgress(tester);
108
+ expectProgressAnnouncement(tester, 'پیشرفت شخصی: شروع نشده');
109
+ await tester.tap(find.text('در حال یادگیری'));
110
+ await tester.pumpAndSettle();
111
+ await showProgress(tester);
112
+ const accepted =
113
+ 'پیشرفت شخصی: در حال یادگیری\nآخرین ثبت سرور: 2026-10-11T10:00:00Z';
114
+ expectProgressAnnouncement(tester, accepted);
115
+ expect(find.bySemanticsLabel('پیشرفت شخصی: شروع نشده'), findsNothing);
116
+ await tester.pumpWidget(const SizedBox());
117
+ await tester.pumpAndSettle();
118
+ await tester.pumpWidget(lesson());
119
+ await tester.pumpAndSettle();
120
+ await showProgress(tester);
121
+ expectProgressAnnouncement(tester, accepted);
122
+ expect(tester.takeException(), isNull);
123
+ await tester.pumpWidget(const SizedBox());
124
+ semantics.dispose();
125
+ api.close();
126
+ });
127
+
128
+ testWidgets(
129
+ 'pending progress announcement preserves the prior server timestamp',
130
+ (tester) async {
131
+ final semantics = tester.ensureSemantics();
132
+ final api = makeApi((request) async {
133
+ if (request.method == 'PUT') {
134
+ throw http.ClientException('synthetic offline');
135
+ }
136
+ return response({
137
+ 'id': courseId,
138
+ 'titleFa': 'کتاب آزمایشی',
139
+ 'units': [
140
+ {
141
+ 'id': firstId,
142
+ 'titleFa': 'درس آزمایشی',
143
+ 'videos': [],
144
+ 'progress': {
145
+ 'unitId': firstId,
146
+ 'status': 'in_progress',
147
+ 'source': 'self_reported',
148
+ 'version': 1,
149
+ 'updatedAt': '2026-10-11T09:00:00Z'
150
+ }
151
+ }
152
+ ]
153
+ });
154
+ });
155
+ await tester.pumpWidget(screen(
156
+ LearningLessonPage(api: api, courseId: courseId, unitId: firstId)));
157
+ await tester.pumpAndSettle();
158
+ await tester.tap(find.text('طبق گزارش من تکمیل شد'));
159
+ await tester.pumpAndSettle();
160
+ await showProgress(tester);
161
+ expectProgressAnnouncement(tester,
162
+ 'پیشرفت شخصی: تکمیل طبق گزارش من\nتغییر روی دستگاه ذخیره شده؛ تأیید سرور دریافت نشده است.\nآخرین ثبت سرور: 2026-10-11T09:00:00Z');
163
+ expect(tester.takeException(), isNull);
164
+ await tester.pumpWidget(const SizedBox());
165
+ semantics.dispose();
166
+ api.close();
167
+ });
168
+
169
testWidgets(
170
'no education profile asks selection without silently choosing grade7',
171
(tester) async {
@@ -164,6 +280,7 @@ void main() {
280
testWidgets(
281
'permission denial removes previously displayed personal progress',
282
(tester) async {
283
+ final semantics = tester.ensureSemantics();
284
var denied = false;
285
final api = makeApi((request) async {
286
if (denied) return http.Response('{"error":"forbidden"}', 403);
@@ -190,16 +307,24 @@ void main() {
307
LearningLessonPage(api: api, courseId: courseId, unitId: firstId)));
308
await tester.pumpAndSettle();
309
expect(find.textContaining('تکمیل طبق گزارش من'), findsOneWidget);
310
+ await showProgress(tester);
311
+ expectProgressAnnouncement(tester,
312
+ 'پیشرفت شخصی: تکمیل طبق گزارش من\nآخرین ثبت سرور: 2026-10-09T10:00:00Z');
313
denied = true;
314
await tester.scrollUntilVisible(find.text('همگامسازی و تازهسازی'), 250,
315
scrollable: find.byType(Scrollable).first);
316
await tester.tap(find.text('همگامسازی و تازهسازی'));
317
await tester.pumpAndSettle();
318
expect(find.textContaining('تکمیل طبق گزارش من'), findsNothing);
319
+ expect(
320
+ find.bySemanticsLabel(
321
+ RegExp('تکمیل طبق گزارش من|2026-10-09T10:00:00Z')),
322
+ findsNothing);
323
expect(find.text('درس خصوصی آزمایشی'), findsNothing);
324
expect(find.textContaining('نشست معتبر لازم است'), findsOneWidget);
325
expect(tester.takeException(), isNull);
326
await tester.pumpWidget(const SizedBox());
327
+ semantics.dispose();
328
api.close();
329
});
330
apps/lifemate/test/family_management_test.dart
new
+458
@@ -0,0 +1,458 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'package:flutter/material.dart';
5
+import 'package:flutter/services.dart';
6
+import 'package:flutter_test/flutter_test.dart';
7
+import 'package:http/http.dart' as http;
8
+import 'package:http/testing.dart';
9
+import 'package:lifemate/api.dart';
10
+import 'package:lifemate/family_management_ui.dart';
11
+import 'package:lifemate/offline_store.dart';
12
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
13
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
14
+
15
+const familyId = 'a1111111-1111-4111-8111-111111111111';
16
+const actorId = 'b1111111-1111-4111-8111-111111111111';
17
+const targetId = 'c1111111-1111-4111-8111-111111111111';
18
+const mutationId = 'd1111111-1111-4111-8111-111111111111';
19
+const at = '2026-10-11T12:00:00Z';
20
+http.Response response(Object body, [int status = 200]) =>
21
+ http.Response(jsonEncode(body), status,
22
+ headers: {'content-type': 'application/json; charset=utf-8'});
23
+Map<String, dynamic> family(
24
+ {bool admin = true, String name = 'خانواده آزمایشی'}) =>
25
+ {'id': familyId, 'name': name, 'role': 'adult_member', 'is_admin': admin};
26
+Map<String, dynamic> member(String id, String name,
27
+ {bool admin = false, int version = 1, String role = 'adult_member'}) =>
28
+ {
29
+ 'user_id': id,
30
+ 'display_name': name,
31
+ 'role': role,
32
+ 'is_admin': admin,
33
+ 'theme_preference': 'adult_blue',
34
+ 'version': version,
35
+ 'updated_at': at
36
+ };
37
+HttpIdentityApi fixture(Future<http.Response> Function(http.Request) handler) =>
38
+ HttpIdentityApi(
39
+ baseUrl: 'https://family.example.test/api', client: MockClient(handler))
40
+ ..accessToken = 'synthetic-token'
41
+ ..currentUserId = actorId;
42
+
43
+void main() {
44
+ TestWidgetsFlutterBinding.ensureInitialized();
45
+ setUp(() {
46
+ SharedPreferencesAsyncPlatform.instance =
47
+ InMemorySharedPreferencesAsync.withData({});
48
+ String? token;
49
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
50
+ .setMockMethodCallHandler(
51
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
52
+ if (call.method == 'getBlocked') return token != null;
53
+ if (call.method == 'beginWrite') return token = 'family-write';
54
+ if (call.method == 'completeWrite' && call.arguments == token) {
55
+ token = null;
56
+ return true;
57
+ }
58
+ throw PlatformException(code: 'local_storage_restart_required');
59
+ });
60
+ });
61
+
62
+ test('role receipt lost after commit retries identical metadata after reopen',
63
+ () async {
64
+ var lost = true;
65
+ final sent = <String>[];
66
+ final api = fixture((request) async {
67
+ if (request.method == 'GET') return response(family());
68
+ sent.add(request.body);
69
+ if (lost) throw http.ClientException('lost receipt');
70
+ return response({
71
+ 'members': [
72
+ {
73
+ 'userId': targetId,
74
+ 'role': 'parent_guardian',
75
+ 'isAdmin': false,
76
+ 'version': 2,
77
+ 'updatedAt': at,
78
+ 'endedAt': null
79
+ }
80
+ ],
81
+ 'acknowledgement': {
82
+ 'mutationId': mutationId,
83
+ 'familyId': familyId,
84
+ 'targetId': targetId,
85
+ 'operation': 'role',
86
+ 'status': 'already_applied'
87
+ }
88
+ });
89
+ });
90
+ final body = {
91
+ 'mutationId': mutationId,
92
+ 'expectedVersion': 1,
93
+ 'role': 'parent_guardian'
94
+ };
95
+ await expectLater(
96
+ FamilyOperationSync(api, familyId).submit('role', targetId, body),
97
+ throwsA(predicate(isOfflineFailure)));
98
+ final pending = (await FamilyOperationSync(api, familyId).pending()).single;
99
+ expect(pending['payload'], body);
100
+ expect(jsonEncode(pending), isNot(contains('display_name')));
101
+ expect(await OfflineStore.forApi(api).readList('family'), isEmpty);
102
+ lost = false;
103
+ await FamilyOperationSync(api, familyId).retry(pending);
104
+ expect(sent.length, 2);
105
+ expect(sent.first, sent.last);
106
+ expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
107
+ api.close();
108
+ });
109
+
110
+ test(
111
+ 'former administrator may replay only journalled transfer and new changes require actual admin',
112
+ () async {
113
+ var admin = true, lost = true;
114
+ final api = fixture((request) async {
115
+ if (request.method == 'GET') return response(family(admin: admin));
116
+ if (lost) {
117
+ admin = false;
118
+ throw http.ClientException('lost receipt');
119
+ }
120
+ return response({
121
+ 'members': [
122
+ {
123
+ 'userId': actorId,
124
+ 'role': 'adult_member',
125
+ 'isAdmin': false,
126
+ 'version': 2,
127
+ 'updatedAt': at,
128
+ 'endedAt': null
129
+ },
130
+ {
131
+ 'userId': targetId,
132
+ 'role': 'adult_member',
133
+ 'isAdmin': true,
134
+ 'version': 2,
135
+ 'updatedAt': at,
136
+ 'endedAt': null
137
+ }
138
+ ],
139
+ 'acknowledgement': {
140
+ 'mutationId': mutationId,
141
+ 'familyId': familyId,
142
+ 'targetId': targetId,
143
+ 'operation': 'admin_transfer',
144
+ 'status': 'already_applied'
145
+ }
146
+ });
147
+ });
148
+ final sync = FamilyOperationSync(api, familyId);
149
+ await expectLater(
150
+ sync.submit('admin_transfer', targetId, {
151
+ 'mutationId': mutationId,
152
+ 'targetUserId': targetId,
153
+ 'expectedVersion': 1,
154
+ 'expectedActorVersion': 1
155
+ }),
156
+ throwsA(predicate(isOfflineFailure)));
157
+ final pending = (await sync.pending()).single;
158
+ lost = false;
159
+ await FamilyOperationSync(api, familyId).retry(pending);
160
+ await expectLater(
161
+ sync.submit('role', targetId, {
162
+ 'mutationId': mutationId,
163
+ 'expectedVersion': 2,
164
+ 'role': 'parent_guardian'
165
+ }),
166
+ throwsA(isA<ApiException>()));
167
+ expect(await sync.pending(), isEmpty);
168
+ api.close();
169
+ });
170
+
171
+ test(
172
+ 'wrong transfer receipt never removes durable metadata, and scope change blocks retries',
173
+ () async {
174
+ final api = fixture((request) async => request.method == 'GET'
175
+ ? response(family())
176
+ : response({
177
+ 'members': [
178
+ {
179
+ 'userId': targetId,
180
+ 'role': 'adult_member',
181
+ 'isAdmin': true,
182
+ 'version': 2,
183
+ 'updatedAt': at,
184
+ 'endedAt': null
185
+ }
186
+ ],
187
+ 'acknowledgement': {
188
+ 'mutationId': mutationId,
189
+ 'familyId': familyId,
190
+ 'targetId': targetId,
191
+ 'operation': 'admin_transfer',
192
+ 'status': 'accepted'
193
+ }
194
+ }));
195
+ final sync = FamilyOperationSync(api, familyId);
196
+ await expectLater(
197
+ sync.submit('admin_transfer', targetId, {
198
+ 'mutationId': mutationId,
199
+ 'targetUserId': targetId,
200
+ 'expectedVersion': 1,
201
+ 'expectedActorVersion': 1
202
+ }),
203
+ throwsA(isA<ApiException>()));
204
+ final saved = (await sync.pending()).single;
205
+ api.currentUserId = targetId;
206
+ await expectLater(sync.retry(saved), throwsA(isA<ApiException>()));
207
+ expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
208
+ api.close();
209
+ });
210
+
211
+ testWidgets(
212
+ 'adult role does not grant management and network failure clears the member list',
213
+ (tester) async {
214
+ var offline = false;
215
+ final api = fixture((request) async {
216
+ if (offline) throw http.ClientException('offline');
217
+ if (request.url.path.endsWith('/members')) {
218
+ return response({
219
+ 'members': [member(actorId, 'والد آزمایشی')]
220
+ });
221
+ }
222
+ return response(family(admin: false));
223
+ });
224
+ await tester.pumpWidget(
225
+ MaterialApp(home: FamilyManagementPage(api: api, familyId: familyId)));
226
+ await tester.pumpAndSettle();
227
+ expect(find.text('والد آزمایشی'), findsOneWidget);
228
+ expect(find.text('بایگانی خانواده'), findsNothing);
229
+ expect(find.text('دعوت عضو'), findsNothing);
230
+ offline = true;
231
+ await tester.tap(find.byKey(const Key('family-management-refresh')));
232
+ await tester.pumpAndSettle();
233
+ expect(find.text('والد آزمایشی'), findsNothing);
234
+ expect(find.textContaining('اتصال'), findsWidgets);
235
+ await tester.pumpWidget(const SizedBox());
236
+ api.close();
237
+ });
238
+
239
+ testWidgets(
240
+ 'late family read cannot restore members after newer access denial',
241
+ (tester) async {
242
+ final delayed = Completer<http.Response>();
243
+ var reads = 0;
244
+ final api = fixture((request) async {
245
+ if (request.url.path.endsWith('/members')) {
246
+ return response({
247
+ 'members': [member(actorId, 'والد آزمایشی')]
248
+ });
249
+ }
250
+ return ++reads == 1
251
+ ? delayed.future
252
+ : response({'error': 'forbidden'}, 403);
253
+ });
254
+ await tester.pumpWidget(
255
+ MaterialApp(home: FamilyManagementPage(api: api, familyId: familyId)));
256
+ await tester.pump();
257
+ await tester.tap(find.byKey(const Key('family-management-refresh')));
258
+ await tester.pumpAndSettle();
259
+ delayed.complete(response(family(admin: false)));
260
+ await tester.pumpAndSettle();
261
+ expect(find.text('والد آزمایشی'), findsNothing);
262
+ expect(find.textContaining('دسترسی'), findsWidgets);
263
+ await tester.pumpWidget(const SizedBox());
264
+ api.close();
265
+ });
266
+ test(
267
+ 'a role mutation cannot trust missing or contradictory server administrator flags',
268
+ () async {
269
+ for (final raw in [
270
+ {'id': familyId, 'role': 'adult_member'},
271
+ {'id': familyId, 'role': 'teen_minor', 'is_admin': true},
272
+ ]) {
273
+ var writes = 0;
274
+ final api = fixture((request) async {
275
+ if (request.method == 'GET') return response(raw);
276
+ writes++;
277
+ return response({});
278
+ });
279
+ final sync = FamilyOperationSync(api, familyId);
280
+ await expectLater(
281
+ sync.submit('role', targetId, {
282
+ 'mutationId': mutationId,
283
+ 'expectedVersion': 1,
284
+ 'role': 'parent_guardian'
285
+ }),
286
+ throwsA(isA<ApiException>()));
287
+ expect(writes, 0);
288
+ expect(await sync.pending(), isEmpty);
289
+ api.close();
290
+ }
291
+ });
292
+
293
+ testWidgets(
294
+ 'role change needs confirmation and refreshes canonical role without dropdown crash',
295
+ (tester) async {
296
+ var role = 'adult_member', version = 1;
297
+ final writes = <Map<String, dynamic>>[];
298
+ final api = fixture((request) async {
299
+ if (request.url.path.endsWith('/members')) {
300
+ return response({
301
+ 'members': [
302
+ member(actorId, 'مدیر آزمایشی', admin: true),
303
+ member(targetId, 'عضو آزمایشی', version: version, role: role),
304
+ ]
305
+ });
306
+ }
307
+ if (request.method == 'GET' &&
308
+ request.url.path.endsWith('/invitations')) {
309
+ return response({'invitations': [], 'nextCursor': null, 'total': 0});
310
+ }
311
+ if (request.method == 'GET') return response(family());
312
+ final body = jsonDecode(request.body) as Map<String, dynamic>;
313
+ writes.add(body);
314
+ role = body['role'] as String;
315
+ version++;
316
+ return response({
317
+ 'members': [
318
+ {
319
+ 'userId': targetId,
320
+ 'role': role,
321
+ 'isAdmin': false,
322
+ 'version': version,
323
+ 'updatedAt': at,
324
+ 'endedAt': null,
325
+ }
326
+ ],
327
+ 'acknowledgement': {
328
+ 'mutationId': body['mutationId'],
329
+ 'familyId': familyId,
330
+ 'targetId': targetId,
331
+ 'operation': 'role',
332
+ 'status': 'accepted',
333
+ }
334
+ });
335
+ });
336
+ await tester.pumpWidget(
337
+ MaterialApp(home: FamilyManagementPage(api: api, familyId: familyId)));
338
+ await tester.pumpAndSettle();
339
+ final dropdown = find.byKey(const Key('family-member-role-$targetId'));
340
+ await tester.ensureVisible(dropdown);
341
+ await tester.pumpAndSettle();
342
+ await tester.tap(dropdown);
343
+ await tester.pumpAndSettle();
344
+ await tester.tap(find.text('سرپرست').last);
345
+ await tester.pumpAndSettle();
346
+ expect(find.text('تغییر نقش عضو'), findsOneWidget);
347
+ await tester.tap(find.text('انصراف'));
348
+ await tester.pumpAndSettle();
349
+ expect(writes, isEmpty);
350
+ await tester.tap(dropdown);
351
+ await tester.pumpAndSettle();
352
+ await tester.tap(find.text('سرپرست').last);
353
+ await tester.pumpAndSettle();
354
+ await tester.tap(find.text('تأیید تغییر'));
355
+ await tester.pumpAndSettle();
356
+ expect(writes, hasLength(1));
357
+ expect(writes.single['expectedVersion'], 1);
358
+ expect(writes.single['mutationId'], isA<String>());
359
+ expect(role, 'parent_guardian');
360
+ expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
361
+ expect(tester.takeException(), isNull);
362
+ await tester.pumpWidget(const SizedBox());
363
+ api.close();
364
+ });
365
+
366
+ testWidgets(
367
+ 'revoked access clears members, invitation hints and any contact draft',
368
+ (tester) async {
369
+ var denied = false;
370
+ final api = fixture((request) async {
371
+ if (denied) return response({'error': 'forbidden'}, 403);
372
+ if (request.url.path.endsWith('/members')) {
373
+ return response({
374
+ 'members': [
375
+ member(actorId, 'مدیر آزمایشی', admin: true),
376
+ member(targetId, 'عضو آزمایشی'),
377
+ ]
378
+ });
379
+ }
380
+ if (request.url.path.endsWith('/invitations')) {
381
+ return response({
382
+ 'invitations': [
383
+ {
384
+ 'id': mutationId,
385
+ 'intendedRole': 'adult_member',
386
+ 'status': 'pending',
387
+ 'version': 1,
388
+ 'createdAt': at,
389
+ 'expiresAt': '2026-10-12T12:00:00Z',
390
+ 'recipientHint': '***@example.test',
391
+ }
392
+ ],
393
+ 'nextCursor': null,
394
+ 'total': 1
395
+ });
396
+ }
397
+ return response(family());
398
+ });
399
+ await tester.pumpWidget(
400
+ MaterialApp(home: FamilyManagementPage(api: api, familyId: familyId)));
401
+ await tester.pumpAndSettle();
402
+ await tester.scrollUntilVisible(find.text('***@example.test'), 400,
403
+ scrollable: find.byType(Scrollable).first);
404
+ expect(find.text('***@example.test'), findsOneWidget);
405
+ final draft =
406
+ tester.widget<TextField>(find.byType(TextField).last).controller!;
407
+ draft.text = 'synthetic-private-recipient@example.test';
408
+ denied = true;
409
+ await tester.tap(find.byKey(const Key('family-management-refresh')));
410
+ await tester.pumpAndSettle();
411
+ expect(find.text('***@example.test'), findsNothing);
412
+ expect(find.text('عضو آزمایشی'), findsNothing);
413
+ expect(find.text('دعوت عضو'), findsNothing);
414
+ expect(draft.text, isEmpty);
415
+ expect(find.textContaining('دسترسی'), findsWidgets);
416
+ expect(await OfflineStore.forApi(api).readList('family'), isEmpty);
417
+ await tester.pumpWidget(const SizedBox());
418
+ api.close();
419
+ });
420
+
421
+ testWidgets(
422
+ 'unknown result of legacy family rename only refreshes and never retries the write automatically',
423
+ (tester) async {
424
+ var renamed = false, patches = 0;
425
+ final api = fixture((request) async {
426
+ if (request.method == 'PATCH') {
427
+ patches++;
428
+ renamed = true;
429
+ throw http.ClientException('synthetic receipt lost');
430
+ }
431
+ if (request.url.path.endsWith('/members')) {
432
+ return response({
433
+ 'members': [
434
+ member(actorId, 'مدیر آزمایشی', admin: true),
435
+ ]
436
+ });
437
+ }
438
+ if (request.url.path.endsWith('/invitations')) {
439
+ return response({'invitations': [], 'nextCursor': null, 'total': 0});
440
+ }
441
+ return response(
442
+ family(name: renamed ? 'نام تازه سرور' : 'خانواده آزمایشی'));
443
+ });
444
+ await tester.pumpWidget(
445
+ MaterialApp(home: FamilyManagementPage(api: api, familyId: familyId)));
446
+ await tester.pumpAndSettle();
447
+ await tester.enterText(find.byType(TextField).first, 'نام تازه سرور');
448
+ await tester.tap(find.text('ذخیره نام خانواده'));
449
+ await tester.pumpAndSettle();
450
+ expect(patches, 1);
451
+ expect(find.text('نام تازه سرور'), findsWidgets);
452
+ expect(find.textContaining('نتیجه عملیات ممکن است نامشخص باشد'),
453
+ findsOneWidget);
454
+ expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
455
+ await tester.pumpWidget(const SizedBox());
456
+ api.close();
457
+ });
458
+}
apps/lifemate/test/learning_goal_sync_test.dart
new
+365
@@ -0,0 +1,365 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'package:flutter/services.dart';
5
+import 'package:flutter_test/flutter_test.dart';
6
+import 'package:http/http.dart' as http;
7
+import 'package:http/testing.dart';
8
+import 'package:lifemate/api.dart';
9
+import 'package:lifemate/learning_goal_sync.dart';
10
+import 'package:lifemate/offline_store.dart';
11
+import 'package:lifemate/session_store.dart';
12
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
13
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
14
+
15
+const userId = '10000000-0000-4000-8000-000000000001';
16
+const otherUserId = '10000000-0000-4000-8000-000000000002';
17
+const goalId = '20000000-0000-4000-8000-000000000001';
18
+const at = '2026-10-11T12:00:00Z';
19
+
20
+class MemorySession implements SessionStore {
21
+ @override
22
+ Future<String?> read() async => null;
23
+ @override
24
+ Future<void> write(String value) async {}
25
+ @override
26
+ Future<void> clear() async {}
27
+}
28
+
29
+http.Response response(Object body, [int status = 200]) =>
30
+ http.Response(jsonEncode(body), status,
31
+ headers: {'content-type': 'application/json; charset=utf-8'});
32
+
33
+Map<String, dynamic> goal(
34
+ {String id = goalId,
35
+ int version = 1,
36
+ String title = 'هدف خصوصی آزمایشی',
37
+ String status = 'active',
38
+ String owner = userId}) =>
39
+ {
40
+ 'id': id,
41
+ 'owner_user_id': owner,
42
+ 'subject_id': null,
43
+ 'title': title,
44
+ 'target': null,
45
+ 'status': status,
46
+ 'version': version,
47
+ 'created_at': at,
48
+ 'updated_at': at,
49
+ 'archived_at': status == 'archived' ? at : null,
50
+ };
51
+
52
+class GoalFixture {
53
+ GoalFixture(
54
+ {String endpoint = 'https://goals.test/api', String user = userId}) {
55
+ api = HttpIdentityApi(
56
+ baseUrl: endpoint,
57
+ client: MockClient(handle),
58
+ sessionStore: MemorySession())
59
+ ..accessToken = 'synthetic-token'
60
+ ..currentUserId = user;
61
+ store = OfflineStore.forNamespace(api.cacheNamespace!,
62
+ session: OfflineSession());
63
+ sync = LearningGoalSync(api, store: store);
64
+ }
65
+ late HttpIdentityApi api;
66
+ late OfflineStore store;
67
+ late LearningGoalSync sync;
68
+ final goals = <String, Map<String, dynamic>>{};
69
+ final receipts = <String, Map<String, dynamic>>{};
70
+ final requests = <http.Request>[];
71
+ bool offline = false, commitThenDisconnect = false;
72
+ int? errorCode;
73
+ Completer<void>? delay;
74
+ Map<String, dynamic> Function(Map<String, dynamic>)? alterResponse;
75
+ final retainedCheckins = <Map<String, dynamic>>[
76
+ {'goalId': goalId, 'note': 'private synthetic history'}
77
+ ];
78
+
79
+ Future<http.Response> handle(http.Request request) async {
80
+ requests.add(request);
81
+ if (delay != null) await delay!.future;
82
+ if (offline) throw http.ClientException('synthetic offline');
83
+ if (errorCode != null) {
84
+ return response({'error': 'synthetic_denial'}, errorCode!);
85
+ }
86
+ if (request.method == 'GET') {
87
+ if (request.url.path.endsWith('/goals')) {
88
+ return response({
89
+ 'items':
90
+ goals.values.where((g) => g['status'] != 'archived').toList(),
91
+ 'fetchedAt': at
92
+ });
93
+ }
94
+ final row = goals[request.url.path.split('/').last];
95
+ return response(
96
+ row ?? {'error': 'goal_not_found'}, row == null ? 404 : 200);
97
+ }
98
+ final body = jsonDecode(request.body) as Map<String, dynamic>;
99
+ final id = request.method == 'POST'
100
+ ? body['id'] as String
101
+ : request.url.path.split('/').last;
102
+ final operation = request.method == 'POST'
103
+ ? 'create'
104
+ : request.method == 'PATCH'
105
+ ? 'update'
106
+ : 'archive';
107
+ final mutationId = body['mutationId'] as String;
108
+ expect(
109
+ (await store.readQueue()).any((m) =>
110
+ m['id'] == mutationId &&
111
+ m['payload'].toString() == body.toString()),
112
+ isTrue);
113
+ final old = receipts[mutationId];
114
+ if (old == null) {
115
+ if ((goals[id]?['version'] ?? 0) != body['expectedVersion']) {
116
+ return response({'error': 'version_conflict'}, 409);
117
+ }
118
+ goals[id] = {
119
+ ...goal(
120
+ id: id,
121
+ version: (body['expectedVersion'] as int) + 1,
122
+ title: body['title'] as String? ??
123
+ goals[id]?['title'] as String? ??
124
+ '',
125
+ status: operation == 'archive'
126
+ ? 'archived'
127
+ : body['status'] as String? ??
128
+ goals[id]?['status'] as String? ??
129
+ 'active',
130
+ owner: api.currentUserId!),
131
+ 'target':
132
+ body.containsKey('target') ? body['target'] : goals[id]?['target'],
133
+ 'subject_id': body.containsKey('subjectId')
134
+ ? body['subjectId']
135
+ : goals[id]?['subject_id'],
136
+ };
137
+ receipts[mutationId] = {
138
+ 'mutationId': mutationId,
139
+ 'goalId': id,
140
+ 'operation': operation,
141
+ 'appliedVersion': body['expectedVersion'] + 1,
142
+ 'acceptedAt': at,
143
+ };
144
+ }
145
+ if (commitThenDisconnect) {
146
+ commitThenDisconnect = false;
147
+ throw http.ClientException('synthetic receipt lost after commit');
148
+ }
149
+ var result = <String, dynamic>{
150
+ 'goal': {...goals[id]!},
151
+ 'acknowledgement': {
152
+ ...receipts[mutationId]!,
153
+ 'status': old == null ? 'accepted' : 'already_applied'
154
+ }
155
+ };
156
+ if (alterResponse != null) result = alterResponse!(result);
157
+ return response(
158
+ result, request.method == 'POST' && old == null ? 201 : 200);
159
+ }
160
+
161
+ LearningGoalSync reopen() => LearningGoalSync(api,
162
+ store: OfflineStore.forNamespace(store.scope, session: OfflineSession()));
163
+}
164
+
165
+Matcher code(String value) =>
166
+ throwsA(isA<ApiException>().having((e) => e.code, 'code', value));
167
+
168
+void main() {
169
+ TestWidgetsFlutterBinding.ensureInitialized();
170
+ setUp(() {
171
+ SharedPreferencesAsyncPlatform.instance =
172
+ InMemorySharedPreferencesAsync.withData({});
173
+ String? token;
174
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
175
+ .setMockMethodCallHandler(
176
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
177
+ if (call.method == 'getBlocked') return token != null;
178
+ if (call.method == 'beginWrite') return token = 'goal-sync-test';
179
+ if (call.method == 'completeWrite' && call.arguments == token) {
180
+ token = null;
181
+ return true;
182
+ }
183
+ throw PlatformException(code: 'local_storage_restart_required');
184
+ });
185
+ });
186
+
187
+ test(
188
+ 'create, fresh handle read, edit, complete and archive retain history and server versions',
189
+ () async {
190
+ final f = GoalFixture();
191
+ final created =
192
+ await f.sync.create(title: ' هدف ریاضی ', target: ' حل تمرین ');
193
+ expect(created['queued'], false);
194
+ final id = created['goal']['id'] as String;
195
+ expect(created['goal']['title'], 'هدف ریاضی');
196
+ f.offline = true;
197
+ final reopened = await f.reopen().read();
198
+ expect(reopened['offline'], true);
199
+ expect((reopened['items'] as List).single['id'], id);
200
+ f.offline = false;
201
+ final edited =
202
+ await f.sync.update(id, 1, {'title': 'تمرین جمع', 'target': null});
203
+ expect(edited['goal']['version'], 2);
204
+ expect(edited['goal']['target'], isNull);
205
+ await f.reopen().update(id, 2, {'status': 'completed'});
206
+ expect((await f.sync.read())['items'].single['status'], 'completed');
207
+ await f.sync.archive(id, 3);
208
+ f.offline = true;
209
+ expect((await f.reopen().read())['items'], isEmpty);
210
+ expect(f.goals[id]?['status'], 'archived');
211
+ expect(f.retainedCheckins, hasLength(1));
212
+ expect(await f.store.readQueue(), isEmpty);
213
+ f.api.close();
214
+ });
215
+
216
+ test(
217
+ 'offline create survives fresh handle and retries one stable UUID with one server row',
218
+ () async {
219
+ final f = GoalFixture()..offline = true;
220
+ final created = await f.sync.create(title: 'هدف آفلاین');
221
+ expect(created['queued'], true);
222
+ final queued = (await f.store.readQueue()).single;
223
+ final reopened = f.reopen();
224
+ expect((await reopened.read())['items'].single['pending_sync'], true);
225
+ expect((await reopened.read())['fetchedAt'], isNull);
226
+ f.offline = false;
227
+ await reopened.flush();
228
+ await reopened.flush();
229
+ expect(f.goals, hasLength(1));
230
+ expect(f.receipts.keys.single, queued['id']);
231
+ expect(await f.store.readQueue(), isEmpty);
232
+ f.api.close();
233
+ });
234
+
235
+ test(
236
+ 'lost create acknowledgement replays exact bytes and current archive dominates old receipt',
237
+ () async {
238
+ final f = GoalFixture()..commitThenDisconnect = true;
239
+ expect((await f.sync.create(title: 'هدف آزمایشی'))['queued'], true);
240
+ final saved = (await f.store.readQueue()).single;
241
+ final id = saved['entityId'] as String;
242
+ f.goals[id] = {
243
+ ...f.goals[id]!,
244
+ 'status': 'archived',
245
+ 'version': 3,
246
+ 'archived_at': at
247
+ };
248
+ await f.reopen().flush();
249
+ final writes = f.requests.where((r) => r.method == 'POST').toList();
250
+ expect(writes, hasLength(2));
251
+ expect(writes.first.body, writes.last.body);
252
+ expect(f.receipts, hasLength(1));
253
+ expect(await f.store.readQueue(), isEmpty);
254
+ f.offline = true;
255
+ expect((await f.reopen().read())['items'], isEmpty);
256
+ f.api.close();
257
+ });
258
+
259
+ for (final corrupt in [
260
+ 'id',
261
+ 'mutation',
262
+ 'version',
263
+ 'operation',
264
+ 'title',
265
+ 'acceptedAt'
266
+ ]) {
267
+ test('malformed $corrupt receipt cannot erase a goal intent', () async {
268
+ final f = GoalFixture();
269
+ f.alterResponse = (raw) {
270
+ final row = {...raw['goal'] as Map};
271
+ final ack = {...raw['acknowledgement'] as Map};
272
+ if (corrupt == 'id') row['id'] = goalId;
273
+ if (corrupt == 'mutation') ack['mutationId'] = goalId;
274
+ if (corrupt == 'version') ack['appliedVersion'] = 2;
275
+ if (corrupt == 'operation') ack['operation'] = 'archive';
276
+ if (corrupt == 'title') row['title'] = 'متن متفاوت';
277
+ if (corrupt == 'acceptedAt') ack['acceptedAt'] = 'yesterday';
278
+ return {'goal': row, 'acknowledgement': ack};
279
+ };
280
+ await expectLater(f.sync.create(title: 'هدف واقعی'),
281
+ code('invalid_goal_acknowledgement'));
282
+ expect(await f.store.readQueue(), hasLength(1));
283
+ f.api.close();
284
+ });
285
+ }
286
+
287
+ test(
288
+ 'version conflict stays queued until explicit server recovery, with local intent journalled',
289
+ () async {
290
+ final f = GoalFixture();
291
+ f.goals[goalId] = goal();
292
+ await f.sync.read();
293
+ f.goals[goalId] = goal(version: 2, title: 'نسخه دیگر دستگاه');
294
+ await expectLater(f.sync.update(goalId, 1, {'title': 'نسخه محلی'}),
295
+ code('version_conflict'));
296
+ expect((await f.store.readQueue()).single['queueStatus'], 'conflict');
297
+ await expectLater(f.reopen().flush(), code('goal_version_conflict'));
298
+ await f.reopen().useServer(goalId);
299
+ expect(await f.store.readQueue(), isEmpty);
300
+ expect(jsonEncode(await f.store.readDiscardedChanges()),
301
+ contains('نسخه محلی'));
302
+ f.offline = true;
303
+ expect(
304
+ (await f.reopen().read())['items'].single['title'], 'نسخه دیگر دستگاه');
305
+ f.api.close();
306
+ });
307
+
308
+ test('403 clears private goal cache without deleting an offline intent',
309
+ () async {
310
+ final f = GoalFixture();
311
+ f.goals[goalId] = goal();
312
+ await f.sync.read();
313
+ f.offline = true;
314
+ await f.sync.update(goalId, 1, {'title': 'تغییر ارسالنشده'});
315
+ f.offline = false;
316
+ f.errorCode = 403;
317
+ await expectLater(f.sync.read(), throwsA(isA<ApiException>()));
318
+ expect(await f.store.readList('learning_goals'), isEmpty);
319
+ expect(await f.store.readList('learning_goals_received'), isEmpty);
320
+ expect(await f.store.readQueue(), hasLength(1));
321
+ f.api.close();
322
+ });
323
+
324
+ test(
325
+ 'account change while receiving a goal blocks acknowledgement and isolates caches',
326
+ () async {
327
+ final f = GoalFixture()..delay = Completer<void>();
328
+ final pending = f.sync.create(title: 'حساب نخست');
329
+ await Future<void>.delayed(Duration.zero);
330
+ f.api.currentUserId = otherUserId;
331
+ f.delay!.complete();
332
+ await expectLater(pending, throwsA(isA<ApiException>()));
333
+ expect(await OfflineStore.forApi(f.api).readQueue(), isEmpty);
334
+ expect(await f.store.readQueue(), hasLength(1));
335
+ f.api.close();
336
+ });
337
+
338
+ for (final invalid in [
339
+ {'expectedVersion': 0, 'title': 'new'},
340
+ {'expectedVersion': -1, 'title': 'new'},
341
+ {'expectedVersion': 1, 'title': 'bad\u0000title'},
342
+ {'expectedVersion': 1, 'unknown': true},
343
+ {'expectedVersion': 1},
344
+ ]) {
345
+ test('invalid update $invalid is rejected before enqueue or HTTP',
346
+ () async {
347
+ final f = GoalFixture();
348
+ final version = invalid['expectedVersion'] as int;
349
+ final changes = {...invalid}..remove('expectedVersion');
350
+ await expectLater(
351
+ f.sync.update(goalId, version, changes), code('invalid_goal_input'));
352
+ expect(await f.store.readQueue(), isEmpty);
353
+ expect(f.requests, isEmpty);
354
+ f.api.close();
355
+ });
356
+ }
357
+
358
+ test('foreign-owner cached row is never rendered as private offline data',
359
+ () async {
360
+ final f = GoalFixture()..offline = true;
361
+ await f.store.writeList('learning_goals', [goal(owner: otherUserId)]);
362
+ await expectLater(f.sync.read(), code('invalid_learning_goal'));
363
+ f.api.close();
364
+ });
365
+}
apps/lifemate/test/learning_goals_ui_test.dart
new
+382
@@ -0,0 +1,382 @@
1
+import 'dart:convert';
2
+import 'package:flutter/material.dart';
3
+import 'package:flutter/services.dart';
4
+import 'package:flutter_test/flutter_test.dart';
5
+import 'package:http/http.dart' as http;
6
+import 'package:http/testing.dart';
7
+import 'package:lifemate/api.dart';
8
+import 'package:lifemate/phase4_ui.dart';
9
+import 'package:lifemate/learning_goals_ui.dart';
10
+import 'learning_goal_sync_test.dart' as support;
11
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
12
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
13
+
14
+void main() {
15
+ TestWidgetsFlutterBinding.ensureInitialized();
16
+ setUp(() {
17
+ SharedPreferencesAsyncPlatform.instance =
18
+ InMemorySharedPreferencesAsync.withData({});
19
+ String? token;
20
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
21
+ .setMockMethodCallHandler(
22
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
23
+ if (call.method == 'getBlocked') return token != null;
24
+ if (call.method == 'beginWrite') return token = 'goal-widget-test';
25
+ if (call.method == 'completeWrite' && call.arguments == token) {
26
+ token = null;
27
+ return true;
28
+ }
29
+ throw PlatformException(code: 'local_storage_restart_required');
30
+ });
31
+ });
32
+ testWidgets(
33
+ 'HTTP hub opens private goal CRUD screen with truthful server freshness',
34
+ (tester) async {
35
+ final api = HttpIdentityApi(
36
+ baseUrl: 'https://goals.example.test/api',
37
+ client: MockClient((request) async => http.Response(
38
+ jsonEncode({'items': [], 'fetchedAt': '2026-10-11T10:00:00Z'}), 200,
39
+ headers: {'content-type': 'application/json; charset=utf-8'})))
40
+ ..accessToken = 'synthetic'
41
+ ..currentUserId = '10000000-0000-4000-8000-000000000001';
42
+ await tester.pumpWidget(MaterialApp(
43
+ home: Directionality(
44
+ textDirection: TextDirection.rtl,
45
+ child: Scaffold(body: Phase4Hub(api: api)))));
46
+ await tester.pumpAndSettle();
47
+ await tester.scrollUntilVisible(find.text('مدیریت هدفهای یادگیری'), 200,
48
+ scrollable: find.byType(Scrollable).first);
49
+ await tester.tap(find.text('مدیریت هدفهای یادگیری'));
50
+ await tester.pumpAndSettle();
51
+ expect(find.text('هدفهای یادگیری'), findsOneWidget);
52
+ expect(find.text('هدف جدید'), findsOneWidget);
53
+ expect(find.textContaining('خصوصی'), findsOneWidget);
54
+ expect(find.textContaining('آخرین دریافت سرور:'), findsOneWidget);
55
+ expect(tester.takeException(), isNull);
56
+ await tester.pumpWidget(const SizedBox());
57
+ api.close();
58
+ });
59
+ Future<void> showPage(WidgetTester tester, HttpIdentityApi api) async {
60
+ await tester.pumpWidget(MaterialApp(
61
+ home: Directionality(
62
+ textDirection: TextDirection.rtl,
63
+ child: LearningGoalsPage(api: api))));
64
+ await tester.pumpAndSettle();
65
+ }
66
+
67
+ testWidgets(
68
+ 'goal creation, edit, completion and confirmed archive use versioned API operations',
69
+ (tester) async {
70
+ final f = support.GoalFixture();
71
+ await showPage(tester, f.api);
72
+ await tester.tap(find.text('هدف جدید'));
73
+ await tester.pumpAndSettle();
74
+ await tester.enterText(find.byType(TextField).at(0), 'هدف ریاضی');
75
+ await tester.enterText(find.byType(TextField).at(1), 'جمع با درک مفهوم');
76
+ await tester.tap(find.text('ذخیره'));
77
+ await tester.pumpAndSettle();
78
+ expect(find.text('هدف ریاضی'), findsOneWidget);
79
+ expect(find.text('تغییر ارسالنشده: 0'), findsOneWidget);
80
+ await tester.tap(find.text('ویرایش'));
81
+ await tester.pumpAndSettle();
82
+ await tester.enterText(find.byType(TextField).at(0), 'تمرین جمع');
83
+ await tester.tap(find.text('ذخیره'));
84
+ await tester.pumpAndSettle();
85
+ expect(find.text('هدف ریاضی'), findsNothing);
86
+ expect(find.text('تمرین جمع'), findsOneWidget);
87
+ await tester.tap(find.widgetWithText(TextButton, 'تکمیل طبق گزارش من'));
88
+ await tester.pumpAndSettle();
89
+ expect(find.text('فعالکردن دوباره'), findsOneWidget);
90
+ await tester.tap(find.widgetWithText(TextButton, 'بایگانی'));
91
+ await tester.pumpAndSettle();
92
+ expect(find.text('بایگانی هدف؟'), findsOneWidget);
93
+ await tester.tap(find.widgetWithText(TextButton, 'انصراف'));
94
+ await tester.pumpAndSettle();
95
+ expect(f.goals.values.single['status'], 'completed');
96
+ await tester.tap(find.widgetWithText(TextButton, 'بایگانی'));
97
+ await tester.pumpAndSettle();
98
+ await tester.tap(find.widgetWithText(FilledButton, 'بایگانی'));
99
+ await tester.pumpAndSettle();
100
+ expect(find.text('تمرین جمع'), findsNothing);
101
+ expect(f.goals.values.single['status'], 'archived');
102
+ expect(f.goals.values.single['version'], 4);
103
+ expect(f.receipts, hasLength(4));
104
+ await tester.pumpWidget(const SizedBox());
105
+ f.api.close();
106
+ });
107
+
108
+ testWidgets(
109
+ 'offline goal intent remains pending after page reopen and becomes live only after acknowledgement',
110
+ (tester) async {
111
+ final f = support.GoalFixture()..offline = true;
112
+ await showPage(tester, f.api);
113
+ await tester.tap(find.text('هدف جدید'));
114
+ await tester.pumpAndSettle();
115
+ await tester.enterText(find.byType(TextField).first, 'هدف بدون اینترنت');
116
+ await tester.tap(find.text('ذخیره'));
117
+ await tester.pumpAndSettle();
118
+ expect(find.text('تغییر در انتظار تأیید سرور'), findsOneWidget);
119
+ expect(find.text('تغییر ارسالنشده: 1'), findsOneWidget);
120
+ expect(find.textContaining('آخرین ثبت سرور:'), findsNothing);
121
+ await tester.pumpWidget(const SizedBox());
122
+ await showPage(tester, f.api);
123
+ expect(find.text('هدف بدون اینترنت'), findsOneWidget);
124
+ expect(find.text('تغییر ارسالنشده: 1'), findsOneWidget);
125
+ f.offline = false;
126
+ await tester.tap(find.text('همگامسازی و تازهسازی'));
127
+ await tester.pumpAndSettle();
128
+ expect(find.text('تغییر ارسالنشده: 0'), findsOneWidget);
129
+ expect(find.textContaining('آخرین ثبت سرور:'), findsOneWidget);
130
+ expect(f.goals, hasLength(1));
131
+ await tester.pumpWidget(const SizedBox());
132
+ f.api.close();
133
+ });
134
+
135
+ testWidgets('denied refresh removes private goal text and actions',
136
+ (tester) async {
137
+ final f = support.GoalFixture();
138
+ f.goals[support.goalId] = support.goal();
139
+ await showPage(tester, f.api);
140
+ expect(find.text('هدف خصوصی آزمایشی'), findsOneWidget);
141
+ f.errorCode = 403;
142
+ await tester.tap(find.text('همگامسازی و تازهسازی'));
143
+ await tester.pumpAndSettle();
144
+ expect(find.text('هدف خصوصی آزمایشی'), findsNothing);
145
+ expect(find.text('ویرایش'), findsNothing);
146
+ expect(find.textContaining('دسترسی'), findsOneWidget);
147
+ await tester.pumpWidget(const SizedBox());
148
+ f.api.close();
149
+ });
150
+
151
+ testWidgets(
152
+ 'failed response labels retained goals as stale instead of a live snapshot',
153
+ (tester) async {
154
+ final f = support.GoalFixture();
155
+ f.goals[support.goalId] = support.goal();
156
+ await showPage(tester, f.api);
157
+ f.errorCode = 502;
158
+ await tester.tap(find.text('همگامسازی و تازهسازی'));
159
+ await tester.pumpAndSettle();
160
+ expect(find.text('هدف خصوصی آزمایشی'), findsOneWidget);
161
+ expect(find.text('تازهسازی ناموفق؛ این داده ممکن است قدیمی باشد.'),
162
+ findsOneWidget);
163
+ await tester.pumpWidget(const SizedBox());
164
+ f.api.close();
165
+ });
166
+
167
+ testWidgets(
168
+ 'backgrounding clears private goal view and resume revalidates before display',
169
+ (tester) async {
170
+ final f = support.GoalFixture();
171
+ f.goals[support.goalId] = support.goal();
172
+ await showPage(tester, f.api);
173
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
174
+ await tester.pump();
175
+ expect(find.text('هدف خصوصی آزمایشی'), findsNothing);
176
+ f.errorCode = 403;
177
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
178
+ await tester.pumpAndSettle();
179
+ expect(find.text('هدف خصوصی آزمایشی'), findsNothing);
180
+ expect(find.textContaining('دسترسی'), findsOneWidget);
181
+ await tester.pumpWidget(const SizedBox());
182
+ f.api.close();
183
+ });
184
+
185
+ testWidgets(
186
+ 'denied edit closes private text dialog and never restores cached goals',
187
+ (tester) async {
188
+ final f = support.GoalFixture();
189
+ f.goals[support.goalId] = support.goal();
190
+ await showPage(tester, f.api);
191
+ await tester.tap(find.text('ویرایش'));
192
+ await tester.pumpAndSettle();
193
+ f.errorCode = 403;
194
+ await tester.tap(find.text('ذخیره'));
195
+ await tester.pumpAndSettle();
196
+ expect(find.byType(TextField), findsNothing);
197
+ expect(find.text('هدف خصوصی آزمایشی'), findsNothing);
198
+ expect(find.textContaining('دسترسی'), findsOneWidget);
199
+ await tester.pumpWidget(const SizedBox());
200
+ f.api.close();
201
+ });
202
+ testWidgets(
203
+ 'goal-linked private reflection history supports create, edit and safe archive',
204
+ (tester) async {
205
+ final f = _HistoryFixture();
206
+ await tester.pumpWidget(MaterialApp(
207
+ home: LearningGoalHistoryPage(api: f.api, goalId: support.goalId)));
208
+ await tester.pumpAndSettle();
209
+ expect(find.text('ثبت بازتاب'), findsOneWidget);
210
+ await tester.tap(find.text('ثبت بازتاب'));
211
+ await tester.pumpAndSettle();
212
+ await tester.enterText(find.byType(TextField), 'جمع را بهتر فهمیدم');
213
+ await tester.tap(find.text('ذخیره'));
214
+ await tester.pumpAndSettle();
215
+ expect(find.text('جمع را بهتر فهمیدم'), findsOneWidget);
216
+ expect(find.textContaining('اثبات یادگیری'), findsWidgets);
217
+ await tester.tap(find.widgetWithText(TextButton, 'ویرایش بازتاب'));
218
+ await tester.pumpAndSettle();
219
+ await tester.enterText(find.byType(TextField), 'نیاز به تمرین بیشتر دارم');
220
+ await tester.tap(find.text('ذخیره'));
221
+ await tester.pumpAndSettle();
222
+ expect(find.text('جمع را بهتر فهمیدم'), findsNothing);
223
+ expect(find.text('نیاز به تمرین بیشتر دارم'), findsOneWidget);
224
+ await tester.tap(find.widgetWithText(TextButton, 'بایگانی بازتاب'));
225
+ await tester.pumpAndSettle();
226
+ await tester.tap(find.text('تأیید بایگانی'));
227
+ await tester.pumpAndSettle();
228
+ expect(find.text('نیاز به تمرین بیشتر دارم'), findsNothing);
229
+ expect(f.posts, 1);
230
+ expect(f.patches, 1);
231
+ expect(f.archives, 1);
232
+ expect(f.rows.single['archived_at'], support.at);
233
+ await tester.pumpWidget(const SizedBox());
234
+ f.api.close();
235
+ });
236
+
237
+ testWidgets(
238
+ 'reflection receipt loss refreshes history without automatically repeating non-idempotent creation',
239
+ (tester) async {
240
+ final f = _HistoryFixture()..loseReceipt = true;
241
+ await tester.pumpWidget(MaterialApp(
242
+ home: LearningGoalHistoryPage(api: f.api, goalId: support.goalId)));
243
+ await tester.pumpAndSettle();
244
+ await tester.tap(find.text('ثبت بازتاب'));
245
+ await tester.pumpAndSettle();
246
+ await tester.enterText(find.byType(TextField), 'بازتاب نامشخص آزمایشی');
247
+ await tester.tap(find.text('ذخیره'));
248
+ await tester.pumpAndSettle();
249
+ expect(f.posts, 1);
250
+ expect(find.text('بازتاب نامشخص آزمایشی'), findsOneWidget);
251
+ expect(find.textContaining('نتیجه ثبت قبلی ممکن است نامشخص باشد'),
252
+ findsOneWidget);
253
+ await tester.tap(find.text('تازهسازی سابقه'));
254
+ await tester.pumpAndSettle();
255
+ expect(f.posts, 1);
256
+ expect(f.rows, hasLength(1));
257
+ await tester.pumpWidget(const SizedBox());
258
+ f.api.close();
259
+ });
260
+
261
+ testWidgets('denied reflection reads clear note text and mutation controls',
262
+ (tester) async {
263
+ final f = _HistoryFixture()
264
+ ..rows.add(_HistoryFixture.row('یادداشت خصوصی آزمایشی'));
265
+ await tester.pumpWidget(MaterialApp(
266
+ home: LearningGoalHistoryPage(api: f.api, goalId: support.goalId)));
267
+ await tester.pumpAndSettle();
268
+ expect(find.text('یادداشت خصوصی آزمایشی'), findsOneWidget);
269
+ f.denied = true;
270
+ await tester.tap(find.text('تازهسازی سابقه'));
271
+ await tester.pumpAndSettle();
272
+ expect(find.text('یادداشت خصوصی آزمایشی'), findsNothing);
273
+ expect(find.text('ویرایش بازتاب'), findsNothing);
274
+ expect(find.textContaining('دسترسی'), findsOneWidget);
275
+ await tester.pumpWidget(const SizedBox());
276
+ f.api.close();
277
+ });
278
+
279
+ testWidgets(
280
+ 'failed online-only reflection fetch never claims an unsent local record exists',
281
+ (tester) async {
282
+ final f = _HistoryFixture();
283
+ await tester.pumpWidget(MaterialApp(
284
+ home: LearningGoalHistoryPage(api: f.api, goalId: support.goalId)));
285
+ await tester.pumpAndSettle();
286
+ f.offlineRead = true;
287
+ await tester.tap(find.text('تازهسازی سابقه'));
288
+ await tester.pumpAndSettle();
289
+ expect(find.textContaining('تغییر ذخیرهشده'), findsNothing);
290
+ expect(find.text('اتصال برقرار نیست؛ دریافت بازتابها به سرور نیاز دارد.'),
291
+ findsOneWidget);
292
+ expect(f.posts, 0);
293
+ expect(find.textContaining('آخرین دریافت سابقه:'), findsNothing);
294
+ await tester.pumpWidget(const SizedBox());
295
+ f.api.close();
296
+ });
297
+
298
+ testWidgets(
299
+ 'denied reflection edit clears private text and closes the editor safely',
300
+ (tester) async {
301
+ final f = _HistoryFixture()
302
+ ..rows.add(_HistoryFixture.row('یادداشت پیشین خصوصی'));
303
+ await tester.pumpWidget(MaterialApp(
304
+ home: LearningGoalHistoryPage(api: f.api, goalId: support.goalId)));
305
+ await tester.pumpAndSettle();
306
+ await tester.tap(find.text('ویرایش بازتاب'));
307
+ await tester.pumpAndSettle();
308
+ await tester.enterText(find.byType(TextField), 'متن ویرایششده خصوصی');
309
+ f.denied = true;
310
+ await tester.tap(find.text('ذخیره'));
311
+ await tester.pumpAndSettle();
312
+ expect(find.byType(TextField), findsNothing);
313
+ expect(find.text('یادداشت پیشین خصوصی'), findsNothing);
314
+ expect(find.text('متن ویرایششده خصوصی'), findsNothing);
315
+ expect(find.textContaining('دسترسی'), findsOneWidget);
316
+ expect(tester.takeException(), isNull);
317
+ await tester.pumpWidget(const SizedBox());
318
+ f.api.close();
319
+ });
320
+}
321
+
322
+class _HistoryFixture {
323
+ _HistoryFixture() {
324
+ api = HttpIdentityApi(
325
+ baseUrl: 'https://history.example.test/api', client: MockClient(handle))
326
+ ..accessToken = 'synthetic-token'
327
+ ..currentUserId = support.userId;
328
+ }
329
+ late final HttpIdentityApi api;
330
+ final rows = <Map<String, dynamic>>[];
331
+ int posts = 0, patches = 0, archives = 0;
332
+ bool loseReceipt = false, denied = false, offlineRead = false;
333
+ static Map<String, dynamic> row(String note) => {
334
+ 'id': '30000000-0000-4000-8000-000000000001',
335
+ 'owner_user_id': support.userId,
336
+ 'learning_goal_id': support.goalId,
337
+ 'confidence': 3,
338
+ 'difficulty': 3,
339
+ 'note': note,
340
+ 'source': 'self_reported',
341
+ 'isEvidenceOfStudy': false,
342
+ 'occurred_at': support.at,
343
+ 'created_at': support.at,
344
+ 'updated_at': support.at,
345
+ 'archived_at': null,
346
+ };
347
+ Future<http.Response> handle(http.Request request) async {
348
+ if (denied) return support.response({'error': 'forbidden'}, 403);
349
+ if (request.method == 'GET') {
350
+ if (offlineRead) throw http.ClientException('synthetic offline read');
351
+ return request.url.path.contains('/goals/')
352
+ ? support.response(support.goal())
353
+ : support.response(
354
+ {'items': rows.where((r) => r['archived_at'] == null).toList()});
355
+ }
356
+ if (request.method == 'DELETE') {
357
+ archives++;
358
+ rows.single['archived_at'] = support.at;
359
+ return http.Response('', 204);
360
+ }
361
+ final body = jsonDecode(request.body) as Map<String, dynamic>;
362
+ if (request.method == 'POST') {
363
+ posts++;
364
+ rows.add({
365
+ ...row(body['note'] as String),
366
+ 'confidence': body['confidence'],
367
+ 'difficulty': body['difficulty']
368
+ });
369
+ if (loseReceipt) {
370
+ throw http.ClientException('synthetic receipt lost after commit');
371
+ }
372
+ return support.response(rows.last, 201);
373
+ }
374
+ patches++;
375
+ rows.single.addAll({
376
+ 'confidence': body['confidence'],
377
+ 'difficulty': body['difficulty'],
378
+ 'note': body['note']
379
+ });
380
+ return support.response(rows.single);
381
+ }
382
+}
apps/lifemate/test/learning_reviews_test.dart
new
+355
@@ -0,0 +1,355 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+
4
+import 'package:flutter/material.dart';
5
+import 'package:flutter/services.dart';
6
+import 'package:flutter_test/flutter_test.dart';
7
+import 'package:http/http.dart' as http;
8
+import 'package:http/testing.dart';
9
+import 'package:lifemate/api.dart';
10
+import 'package:lifemate/learning_reviews_ui.dart';
11
+import 'package:lifemate/offline_store.dart';
12
+import 'package:lifemate/session_store.dart';
13
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
14
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
15
+
16
+// HTTP/widget fixtures only; not real teaching, device or API/SQL acceptance.
17
+const _unit = '00000000-0000-4000-8000-000000000101';
18
+const _laterUnit = '00000000-0000-4000-8000-000000000102';
19
+const _course = '00000000-0000-4000-8000-000000000103';
20
+const _attemptId = '00000000-0000-4000-8000-000000000104';
21
+const _mutationId = '00000000-0000-4000-8000-000000000105';
22
+const _assessment = '00000000-0000-4000-8000-000000000106';
23
+const _fetchedAt = '2026-10-11T05:00:00Z';
24
+
25
+class _Session implements SessionStore {
26
+ @override
27
+ Future<String?> read() async => null;
28
+ @override
29
+ Future<void> write(String value) async {}
30
+ @override
31
+ Future<void> clear() async {}
32
+}
33
+
34
+Map<String, dynamic> _attempt() => {
35
+ 'mutationId': _mutationId,
36
+ 'attemptId': _attemptId,
37
+ 'unitId': _unit,
38
+ 'assessmentId': _assessment,
39
+ 'assessmentVersion': 2,
40
+ 'correctCount': 1,
41
+ 'total': 2,
42
+ 'feedback': [
43
+ {
44
+ 'questionId': 'q1',
45
+ 'objectiveId': 'o1',
46
+ 'correct': true,
47
+ 'explanationFa': 'توضیح درست صرفاً آزمایشی',
48
+ 'remediationFa': 'مرور اول صرفاً آزمایشی',
49
+ },
50
+ {
51
+ 'questionId': 'q2',
52
+ 'objectiveId': 'o2',
53
+ 'correct': false,
54
+ 'explanationFa': 'توضیح دوم صرفاً آزمایشی',
55
+ 'remediationFa': 'راهنمای تمرین صرفاً آزمایشی',
56
+ },
57
+ ],
58
+ 'resultLabel': 'needs_practice',
59
+ 'nextReviewAt': '2026-10-12T10:00:00Z',
60
+ 'schedulePolicy': 'pilot-1-or-3-days',
61
+ 'source': 'quiz_answers',
62
+ 'acceptedAt': '2026-10-10T10:00:00Z',
63
+ 'confidence': 'unsure',
64
+ };
65
+
66
+class _Fixture {
67
+ _Fixture() {
68
+ api = HttpIdentityApi(
69
+ baseUrl: 'https://reviews.example.test/api',
70
+ client: MockClient(handle),
71
+ sessionStore: _Session())
72
+ ..accessToken = 'synthetic-token'
73
+ ..currentUserId = 'synthetic-review-learner-${next++}';
74
+ store = OfflineStore.forNamespace(api.cacheNamespace!,
75
+ session: OfflineSession());
76
+ }
77
+ static int next = 0;
78
+ late final HttpIdentityApi api;
79
+ late final OfflineStore store;
80
+ final requests = <http.Request>[];
81
+ bool offline = false;
82
+ int? forbidden, locatorFailure;
83
+ Completer<void>? delay;
84
+ List<Map<String, dynamic>> reviews = [
85
+ {
86
+ 'unitId': _unit,
87
+ 'nextReviewAt': '2025-01-01T10:00:00Z',
88
+ 'schedulePolicy': 'pilot-1-or-3-days',
89
+ },
90
+ {
91
+ 'unitId': _laterUnit,
92
+ 'nextReviewAt': '2050-01-01T10:00:00Z',
93
+ 'schedulePolicy': 'pilot-1-or-3-days',
94
+ },
95
+ ];
96
+ List<Map<String, dynamic>> attempts = [_attempt()];
97
+ String fetchedAt = _fetchedAt;
98
+
99
+ http.Response response(Object value, [int status = 200]) =>
100
+ http.Response(jsonEncode(value), status,
101
+ headers: {'content-type': 'application/json; charset=utf-8'});
102
+
103
+ Future<http.Response> handle(http.Request request) async {
104
+ requests.add(request);
105
+ if (delay != null) await delay!.future;
106
+ if (offline) throw http.ClientException('synthetic offline');
107
+ if (forbidden != null) {
108
+ return response({'error': 'synthetic-session-refused'}, forbidden!);
109
+ }
110
+ if (request.url.path.endsWith('/me/learning-reviews')) {
111
+ return response({'reviews': reviews, 'fetchedAt': fetchedAt});
112
+ }
113
+ if (request.url.path.endsWith('/me/learning-attempts')) {
114
+ return response({'attempts': attempts, 'fetchedAt': fetchedAt});
115
+ }
116
+ if (request.url.path.contains('/education/units/')) {
117
+ if (locatorFailure != null) {
118
+ return response({'error': 'unit_not_found'}, locatorFailure!);
119
+ }
120
+ final id = request.url.path.split('/').last;
121
+ return response({
122
+ 'unit': {
123
+ 'id': id,
124
+ 'titleFa': id == _unit ? 'جمع آزمایشی' : 'درس آینده آزمایشی',
125
+ 'courseId': _course,
126
+ },
127
+ 'fetchedAt': _fetchedAt,
128
+ });
129
+ }
130
+ throw StateError('Unexpected synthetic request ${request.url.path}');
131
+ }
132
+}
133
+
134
+Widget _screen(_Fixture fixture,
135
+ {Future<void> Function(BuildContext, String)? open}) =>
136
+ MaterialApp(
137
+ home: LearningReviewsPage(
138
+ api: fixture.api, onOpenLesson: open ?? (_, __) async {}));
139
+
140
+void main() {
141
+ TestWidgetsFlutterBinding.ensureInitialized();
142
+ setUp(() {
143
+ SharedPreferencesAsyncPlatform.instance =
144
+ InMemorySharedPreferencesAsync.withData({});
145
+ String? write;
146
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
147
+ .setMockMethodCallHandler(
148
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
149
+ if (call.method == 'getBlocked') return write != null;
150
+ if (call.method == 'beginWrite') return write = 'synthetic-review-write';
151
+ if (call.method == 'completeWrite' && call.arguments == write) {
152
+ write = null;
153
+ return true;
154
+ }
155
+ throw PlatformException(code: 'local_storage_restart_required');
156
+ });
157
+ });
158
+
159
+ testWidgets(
160
+ 'owner sees due reviews and server-only history with lesson names',
161
+ (tester) async {
162
+ final f = _Fixture();
163
+ String? opened;
164
+ await tester.pumpWidget(_screen(f, open: (_, id) async => opened = id));
165
+ await tester.pumpAndSettle();
166
+ expect(find.text('مرور و تاریخچه یادگیری'), findsOneWidget);
167
+ expect(find.text('موعد رسیده'), findsOneWidget);
168
+ expect(find.text('مرور آینده'), findsOneWidget);
169
+ expect(find.text('جمع آزمایشی'), findsWidgets);
170
+ expect(find.textContaining('بهتنهایی اثبات تسلط نیست'), findsOneWidget);
171
+ expect(f.requests.where((r) => r.url.path.contains('/education/units/')),
172
+ hasLength(2),
173
+ reason: 'Locator titles must be deduplicated');
174
+ expect(f.requests.every((r) => r.method == 'GET'), true);
175
+ expect(
176
+ f.requests.every(
177
+ (r) => r.headers['authorization'] == 'Bearer synthetic-token'),
178
+ true);
179
+ expect(f.requests.every((r) => r.url.query.isEmpty), true,
180
+ reason: 'No child/owner override in private history requests');
181
+ await tester.scrollUntilVisible(
182
+ find.byKey(const Key('attempt-$_attemptId')), 250);
183
+ expect(find.text('۱ پاسخ درست از ۲'), findsOneWidget);
184
+ expect(find.textContaining('نیاز به تمرین'), findsOneWidget);
185
+ expect(find.textContaining(_unit), findsNothing);
186
+ await tester.scrollUntilVisible(
187
+ find.byKey(const Key('review-$_unit')), -250);
188
+ await tester.ensureVisible(find.byKey(const Key('open-review-$_unit')));
189
+ await tester.tap(find.byKey(const Key('open-review-$_unit')));
190
+ await tester.pumpAndSettle();
191
+ expect(opened, _unit);
192
+ await tester.pumpWidget(const SizedBox());
193
+ f.api.close();
194
+ });
195
+
196
+ testWidgets(
197
+ 'pausing during lesson open does not leave resumed history locked',
198
+ (tester) async {
199
+ final f = _Fixture();
200
+ final opening = Completer<void>();
201
+ await tester.pumpWidget(_screen(f, open: (_, __) => opening.future));
202
+ await tester.pumpAndSettle();
203
+ await tester.ensureVisible(find.byKey(const Key('open-review-$_unit')));
204
+ await tester.tap(find.byKey(const Key('open-review-$_unit')));
205
+ await tester.pump();
206
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
207
+ await tester.pump();
208
+ opening.complete();
209
+ await tester.pump();
210
+ final beforeResume = f.requests.length;
211
+ tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
212
+ await tester.pumpAndSettle();
213
+ expect(f.requests.length, greaterThan(beforeResume),
214
+ reason:
215
+ 'A discarded open callback must not block a fresh resumed read');
216
+ expect(find.text('جمع آزمایشی'), findsWidgets);
217
+ await tester.pumpWidget(const SizedBox());
218
+ f.api.close();
219
+ });
220
+
221
+ testWidgets('same API object switching account discards prior receipts',
222
+ (tester) async {
223
+ final f = _Fixture();
224
+ await tester.pumpWidget(_screen(f));
225
+ await tester.pumpAndSettle();
226
+ expect(find.text('جمع آزمایشی'), findsWidgets);
227
+ f.api.currentUserId = 'another-synthetic-review-learner';
228
+ f.reviews = [];
229
+ f.attempts = [];
230
+ await tester.pumpWidget(_screen(f));
231
+ await tester.pumpAndSettle();
232
+ expect(find.text('جمع آزمایشی'), findsNothing);
233
+ expect(find.text('مروری ثبت نشده است.'), findsOneWidget);
234
+ await tester.pumpWidget(const SizedBox());
235
+ f.api.close();
236
+ });
237
+
238
+ for (final failure in [0, 401, 403, 500]) {
239
+ testWidgets(
240
+ 'history clears private receipts after refresh failure $failure',
241
+ (tester) async {
242
+ final f = _Fixture();
243
+ await tester.pumpWidget(_screen(f));
244
+ await tester.pumpAndSettle();
245
+ expect(find.text('جمع آزمایشی'), findsWidgets);
246
+ if (failure == 0) {
247
+ f.offline = true;
248
+ } else {
249
+ f.forbidden = failure;
250
+ }
251
+ await tester.pump(const Duration(seconds: 30));
252
+ await tester.pumpAndSettle();
253
+ expect(find.text('جمع آزمایشی'), findsNothing);
254
+ expect(find.textContaining('تأیید تازه دریافت نشده'), findsOneWidget);
255
+ expect(find.byKey(const Key('attempt-$_attemptId')), findsNothing);
256
+ await tester.pumpWidget(const SizedBox());
257
+ f.api.close();
258
+ });
259
+ }
260
+
261
+ testWidgets('pending answers survive reopen without appearing as graded work',
262
+ (tester) async {
263
+ final f = _Fixture();
264
+ f.attempts = [];
265
+ f.reviews = [];
266
+ await f.store.enqueue({
267
+ 'id': _mutationId,
268
+ 'entityId': _assessment,
269
+ 'entityType': 'learning_attempt',
270
+ 'payload': {
271
+ 'answers': ['PRIVATE-UNSENT-ANSWER'],
272
+ 'unitId': _unit
273
+ },
274
+ });
275
+ final before = jsonEncode(await f.store.readQueue());
276
+ await tester.pumpWidget(_screen(f));
277
+ await tester.pumpAndSettle();
278
+ expect(find.textContaining('روی این دستگاه: ۱'), findsOneWidget);
279
+ expect(
280
+ find.text('هنوز نتیجه پذیرفتهشدهای ثبت نشده است.'), findsOneWidget);
281
+ expect(find.textContaining('PRIVATE-UNSENT-ANSWER'), findsNothing);
282
+ expect(f.requests.every((r) => r.method == 'GET'), true);
283
+ await tester.pumpWidget(const SizedBox());
284
+ await tester.pumpWidget(_screen(f));
285
+ await tester.pumpAndSettle();
286
+ expect(find.textContaining('روی این دستگاه: ۱'), findsOneWidget);
287
+ expect(jsonEncode(await f.store.readQueue()), before,
288
+ reason: 'History never grades or acknowledges queued answers');
289
+ await tester.pumpWidget(const SizedBox());
290
+ f.api.close();
291
+ });
292
+
293
+ testWidgets('late old-account history cannot resurrect after API replacement',
294
+ (tester) async {
295
+ final first = _Fixture()..delay = Completer<void>();
296
+ final second = _Fixture()
297
+ ..reviews = []
298
+ ..attempts = [];
299
+ await tester.pumpWidget(_screen(first));
300
+ await tester.pump();
301
+ await tester.pumpWidget(_screen(second));
302
+ await tester.pumpAndSettle();
303
+ expect(find.text('مروری ثبت نشده است.'), findsOneWidget);
304
+ first.delay!.complete();
305
+ await tester.pumpAndSettle();
306
+ expect(find.text('جمع آزمایشی'), findsNothing);
307
+ expect(find.byKey(const Key('attempt-$_attemptId')), findsNothing);
308
+ await tester.pumpWidget(const SizedBox());
309
+ first.api.close();
310
+ second.api.close();
311
+ });
312
+
313
+ for (final corruption in ['wrong-total', 'duplicate-id', 'bad-time']) {
314
+ testWidgets('malformed history $corruption never displays a graded receipt',
315
+ (tester) async {
316
+ final f = _Fixture();
317
+ if (corruption == 'wrong-total') {
318
+ f.attempts.single['total'] = 3;
319
+ } else if (corruption == 'duplicate-id') {
320
+ f.attempts.add(_attempt());
321
+ } else {
322
+ f.fetchedAt = 'not-a-server-timestamp';
323
+ }
324
+ await tester.pumpWidget(_screen(f));
325
+ await tester.pumpAndSettle();
326
+ expect(find.text('۱ پاسخ درست از ۲'), findsNothing);
327
+ expect(find.textContaining('پاسخ معتبر دریافت نشد'), findsOneWidget);
328
+ await tester.pumpWidget(const SizedBox());
329
+ f.api.close();
330
+ });
331
+ }
332
+
333
+ testWidgets(
334
+ 'removed lesson keeps acknowledged receipt and reports unavailable',
335
+ (tester) async {
336
+ final f = _Fixture()..locatorFailure = 404;
337
+ var opened = false;
338
+ await tester.pumpWidget(_screen(f, open: (_, __) async => opened = true));
339
+ await tester.pumpAndSettle();
340
+ expect(find.text('درس از دسترس خارج شده'), findsWidgets);
341
+ await tester.ensureVisible(find.byKey(const Key('open-review-$_unit')));
342
+ await tester.tap(find.byKey(const Key('open-review-$_unit')));
343
+ await tester.pumpAndSettle();
344
+ expect(opened, false);
345
+ await tester.scrollUntilVisible(
346
+ find.textContaining('فعلاً در کتابخانه فعال در دسترس نیست'), -200);
347
+ expect(find.textContaining('فعلاً در کتابخانه فعال در دسترس نیست'),
348
+ findsOneWidget);
349
+ await tester.scrollUntilVisible(
350
+ find.byKey(const Key('attempt-$_attemptId')), 200);
351
+ expect(find.text('۱ پاسخ درست از ۲'), findsOneWidget);
352
+ await tester.pumpWidget(const SizedBox());
353
+ f.api.close();
354
+ });
355
+}
apps/lifemate/test/online_ui_test.dart
+12
@@ -248,6 +248,12 @@ void main() {
248
expect(find.text('ورود'), findsNothing);
249
tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
250
await tester.pumpAndSettle();
251
+ await tester.scrollUntilVisible(find.text('تنظیم اتصال'), 100,
252
+ scrollable: find
253
+ .descendant(
254
+ of: find.byType(Drawer), matching: find.byType(Scrollable))
255
+ .first);
256
+ await tester.pumpAndSettle();
257
await tester.tap(find.text('تنظیم اتصال'));
258
await tester.pumpAndSettle();
259
expect(tester.takeException(), isNull);
@@ -533,6 +539,12 @@ void main() {
539
await tester.pumpAndSettle();
540
tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
541
await tester.pumpAndSettle();
542
+ await tester.scrollUntilVisible(find.text('تنظیم اتصال'), 100,
543
+ scrollable: find
544
+ .descendant(
545
+ of: find.byType(Drawer), matching: find.byType(Scrollable))
546
+ .first);
547
+ await tester.pumpAndSettle();
548
await tester.tap(find.text('تنظیم اتصال'));
549
await tester.pumpAndSettle();
550
await tester.enterText(find.widgetWithText(TextField, 'نشانی اتصال API'),
apps/lifemate/test/school_lifecycle_sync_test.dart
new
+256
@@ -0,0 +1,256 @@
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/school_management_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
+const owner = '10000000-0000-4000-8000-000000000001';
13
+const secondOwner = '10000000-0000-4000-8000-000000000002';
14
+const stamp = '2026-10-11T12:00:00Z';
15
+const contextId = '20000000-0000-4000-8000-000000000001';
16
+http.Response response(Object body, [int status = 200]) =>
17
+ http.Response(jsonEncode(body), status,
18
+ headers: {'content-type': 'application/json; charset=utf-8'});
19
+Map<String, dynamic> entity(String id,
20
+ {int version = 1, String title = 'مدرسه', bool active = true}) =>
21
+ {
22
+ 'id': id,
23
+ 'title': title,
24
+ 'kind': 'student',
25
+ 'user_id': owner,
26
+ 'active': active,
27
+ 'version': version,
28
+ 'created_at': stamp,
29
+ 'updated_at': stamp
30
+ };
31
+
32
+class Fixture {
33
+ Fixture({String endpoint = 'https://school.test/api', String user = owner}) {
34
+ api = HttpIdentityApi(baseUrl: endpoint, client: MockClient(handle))
35
+ ..accessToken = 'synthetic'
36
+ ..currentUserId = user;
37
+ store = OfflineStore.forApi(api);
38
+ sync = SchoolLifecycleSync(api, store: store);
39
+ }
40
+ late final HttpIdentityApi api;
41
+ late final OfflineStore store;
42
+ late final SchoolLifecycleSync sync;
43
+ final rows = <String, Map<String, dynamic>>{};
44
+ final receipts = <String, Map<String, dynamic>>{};
45
+ final posts = <String>[];
46
+ bool offline = false,
47
+ loseAck = false,
48
+ malformedAck = false,
49
+ conflict = false,
50
+ forged = false;
51
+ Future<http.Response> handle(http.Request request) async {
52
+ if (offline) throw http.ClientException('synthetic offline');
53
+ if (request.method == 'GET') {
54
+ return response({
55
+ 'contexts': rows.values.toList(),
56
+ 'years': [],
57
+ 'terms': [],
58
+ 'fetchedAt': stamp
59
+ });
60
+ }
61
+ posts.add(request.body);
62
+ final body = jsonDecode(request.body) as Map<String, dynamic>;
63
+ if (conflict) return response({'error': 'school_version_conflict'}, 409);
64
+ final type = request.url.path.split('/').reversed.skip(1).first;
65
+ if (!receipts.containsKey(body['mutationId'])) {
66
+ final old = rows[body['entityId']];
67
+ final data = body['data'] as Map;
68
+ final row = entity(body['entityId'],
69
+ version: body['expectedVersion'] + 1,
70
+ title: data['title'] ?? old?['title'] ?? 'مدرسه',
71
+ active: body['operation'] != 'archive');
72
+ rows[row['id']] = row;
73
+ receipts[body['mutationId']] = {
74
+ 'mutationId': body['mutationId'],
75
+ 'entityId': body['entityId'],
76
+ 'entityType': type,
77
+ 'operation': body['operation'],
78
+ 'status': 'accepted',
79
+ 'appliedVersion': row['version'],
80
+ 'acceptedAt': stamp
81
+ };
82
+ }
83
+ if (loseAck) {
84
+ loseAck = false;
85
+ throw http.ClientException('ACK lost after synthetic commit');
86
+ }
87
+ final ack = {
88
+ ...receipts[body['mutationId']]!,
89
+ 'status': posts
90
+ .where(
91
+ (p) => jsonDecode(p)['mutationId'] == body['mutationId'])
92
+ .length >
93
+ 1
94
+ ? 'already_applied'
95
+ : 'accepted'
96
+ };
97
+ if (malformedAck) ack['entityId'] = contextId;
98
+ final row = {...rows[body['entityId']]!};
99
+ if (forged) row['user_id'] = secondOwner;
100
+ return response({'entity': row, 'acknowledgement': ack});
101
+ }
102
+}
103
+
104
+void main() {
105
+ TestWidgetsFlutterBinding.ensureInitialized();
106
+ setUp(() {
107
+ SharedPreferencesAsyncPlatform.instance =
108
+ InMemorySharedPreferencesAsync.withData({});
109
+ String? guard;
110
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
111
+ .setMockMethodCallHandler(
112
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
113
+ if (call.method == 'getBlocked') return guard != null;
114
+ if (call.method == 'beginWrite') return guard = 'school-sync';
115
+ if (call.method == 'completeWrite' && call.arguments == guard) {
116
+ guard = null;
117
+ return true;
118
+ }
119
+ throw PlatformException(code: 'local_storage_restart_required');
120
+ });
121
+ });
122
+ test(
123
+ 'lost ACK is durably retained and reopened helper sends exact bytes once without a duplicate',
124
+ () async {
125
+ final f = Fixture()..loseAck = true;
126
+ final result = await f.sync
127
+ .mutate('contexts', 'create', {'title': ' مدرسه ', 'kind': 'student'});
128
+ expect(result['queued'], true);
129
+ expect(f.rows.length, 1);
130
+ expect((await f.store.readQueue()).length, 1);
131
+ final reopened =
132
+ SchoolLifecycleSync(f.api, store: OfflineStore.forApi(f.api));
133
+ await reopened.flush();
134
+ expect(f.posts.length, 2);
135
+ expect(f.posts[1], f.posts[0]);
136
+ expect(f.rows.length, 1);
137
+ expect(await f.store.readQueue(), isEmpty);
138
+ expect((await reopened.read())['contexts'], hasLength(1));
139
+ f.api.close();
140
+ });
141
+ test(
142
+ 'malformed or foreign-owner ACK does not erase pending intent or acknowledge a create',
143
+ () async {
144
+ for (final forged in [false, true]) {
145
+ final f = Fixture(
146
+ endpoint: 'https://${forged ? 'forged' : 'malformed'}.test/api')
147
+ ..malformedAck = !forged
148
+ ..forged = forged;
149
+ await expectLater(
150
+ f.sync.mutate(
151
+ 'contexts', 'create', {'title': 'مدرسه', 'kind': 'student'}),
152
+ throwsA(
153
+ isA<ApiException>().having((e) => e.statusCode, 'status', 502)));
154
+ expect((await f.store.readQueue()).length, 1);
155
+ expect(await f.store.readLastAck(), isNull);
156
+ final id = (await f.store.readQueue()).single['entityId'] as String;
157
+ await expectLater(
158
+ f.sync.mutate(
159
+ 'contexts', 'create', {'title': 'مدرسه', 'kind': 'student'},
160
+ entityId: id),
161
+ throwsA(
162
+ isA<ApiException>().having((e) => e.statusCode, 'status', 409)));
163
+ expect(f.posts.length, 1);
164
+ f.api.close();
165
+ }
166
+ });
167
+ test(
168
+ 'conflict remains until explicit server choice journals the local intent',
169
+ () async {
170
+ final f = Fixture()..conflict = true;
171
+ f.rows[contextId] = entity(contextId, version: 2, title: 'نسخه سرور');
172
+ await expectLater(
173
+ f.sync.mutate('contexts', 'update', {'title': 'نسخه محلی'},
174
+ entityId: contextId, expectedVersion: 1),
175
+ throwsA(
176
+ isA<ApiException>().having((e) => e.statusCode, 'status', 409)));
177
+ expect((await f.store.readQueue()).single['queueStatus'], 'conflict');
178
+ await expectLater(f.sync.flush(), throwsA(isA<ApiException>()));
179
+ expect(f.posts.length, 1);
180
+ f.conflict = false;
181
+ await f.sync.useServer('contexts', contextId);
182
+ expect(await f.store.readQueue(), isEmpty);
183
+ expect(
184
+ (await f.store.readDiscardedChanges()).single['payload']['data']
185
+ ['title'],
186
+ 'نسخه محلی');
187
+ expect((await f.sync.read())['contexts'].single['title'], 'نسخه سرور');
188
+ f.api.close();
189
+ });
190
+ test(
191
+ 'account and endpoint changes cannot replay previous school intent or cache',
192
+ () async {
193
+ final f = Fixture()..offline = true;
194
+ await f.sync
195
+ .mutate('contexts', 'create', {'title': 'خصوصی', 'kind': 'student'});
196
+ final other = Fixture(user: secondOwner);
197
+ expect(await other.sync.pending(), isEmpty);
198
+ final endpoint = Fixture(endpoint: 'https://other-school.test/api');
199
+ expect(await endpoint.sync.pending(), isEmpty);
200
+ f.api.currentUserId = secondOwner;
201
+ await expectLater(
202
+ f.sync.flush(),
203
+ throwsA(
204
+ isA<ApiException>().having((e) => e.statusCode, 'status', 401)));
205
+ expect(f.posts, isEmpty);
206
+ f.api.close();
207
+ other.api.close();
208
+ endpoint.api.close();
209
+ });
210
+ test(
211
+ 'offline school cache preserves server freshness and never declares cached data live',
212
+ () async {
213
+ final f = Fixture();
214
+ f.rows[contextId] = entity(contextId);
215
+ final online = await f.sync.read();
216
+ expect(online['offline'], false);
217
+ f.offline = true;
218
+ final stale = await f.sync.read();
219
+ expect(stale['offline'], true);
220
+ expect(stale['fetchedAt'], stamp);
221
+ expect(stale['contexts'], hasLength(1));
222
+ f.api.close();
223
+ });
224
+ test(
225
+ 'invalid dates and owner-controlled fields never enter queue or reach API',
226
+ () async {
227
+ final f = Fixture();
228
+ for (final data in [
229
+ {
230
+ 'title': 'year',
231
+ 'startsOn': '2026-02-30',
232
+ 'endsOn': '2027-01-01',
233
+ 'lifeContextId': contextId
234
+ },
235
+ {
236
+ 'title': 'year',
237
+ 'startsOn': '2027-01-01',
238
+ 'endsOn': '2026-01-01',
239
+ 'lifeContextId': contextId
240
+ },
241
+ {
242
+ 'title': 'year',
243
+ 'startsOn': '2026-09-01',
244
+ 'endsOn': '2027-01-01',
245
+ 'lifeContextId': contextId,
246
+ 'active': false
247
+ }
248
+ ]) {
249
+ expect(() => f.sync.mutate('years', 'create', data),
250
+ throwsA(isA<ApiException>()));
251
+ }
252
+ expect(await f.store.readQueue(), isEmpty);
253
+ expect(f.posts, isEmpty);
254
+ f.api.close();
255
+ });
256
+}
apps/lifemate/test/school_management_test.dart
new
+214
@@ -0,0 +1,214 @@
1
+import 'dart:convert';
2
+import 'package:flutter/material.dart';
3
+import 'package:flutter/services.dart';
4
+import 'package:flutter_test/flutter_test.dart';
5
+import 'package:http/http.dart' as http;
6
+import 'package:http/testing.dart';
7
+import 'package:lifemate/api.dart';
8
+import 'package:lifemate/phase3_ui.dart';
9
+import 'package:lifemate/school_management_ui.dart';
10
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
11
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
12
+
13
+void main() {
14
+ TestWidgetsFlutterBinding.ensureInitialized();
15
+ setUp(() {
16
+ SharedPreferencesAsyncPlatform.instance =
17
+ InMemorySharedPreferencesAsync.withData({});
18
+ String? guard;
19
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
20
+ .setMockMethodCallHandler(
21
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
22
+ if (call.method == 'getBlocked') return guard != null;
23
+ if (call.method == 'beginWrite') return guard = 'school-test-guard';
24
+ if (call.method == 'completeWrite' && call.arguments == guard) {
25
+ guard = null;
26
+ return true;
27
+ }
28
+ throw PlatformException(code: 'local_storage_restart_required');
29
+ });
30
+ });
31
+ testWidgets(
32
+ 'school entry replaces hardcoded quick setup with explicit management',
33
+ (tester) async {
34
+ final paths = <String>[];
35
+ final api = HttpIdentityApi(
36
+ baseUrl: 'https://school.example.test/api',
37
+ client: MockClient((request) async {
38
+ paths.add('${request.method} ${request.url.path}');
39
+ return http.Response(
40
+ jsonEncode(request.url.path.endsWith('/profile')
41
+ ? {'user_id': '10000000-0000-4000-8000-000000000001'}
42
+ : {
43
+ 'years': [],
44
+ 'subjects': [],
45
+ 'workload': [],
46
+ 'grades': []
47
+ }),
48
+ 200,
49
+ headers: {'content-type': 'application/json; charset=utf-8'});
50
+ }))
51
+ ..accessToken = 'synthetic'
52
+ ..currentUserId = '10000000-0000-4000-8000-000000000001';
53
+ await tester
54
+ .pumpWidget(MaterialApp(home: Scaffold(body: SchoolPage(api: api))));
55
+ await tester.pumpAndSettle();
56
+ expect(find.text('مدیریت مدرسه'), findsOneWidget);
57
+ expect(find.text('شروع سریع'), findsNothing);
58
+ expect(paths.where((p) => p.startsWith('POST')), isEmpty);
59
+ await tester.pumpWidget(const SizedBox());
60
+ api.close();
61
+ });
62
+ testWidgets(
63
+ 'explicit editor has empty user-picked year dates and never sends quick setup writes',
64
+ (tester) async {
65
+ final posts = <String>[];
66
+ final api = HttpIdentityApi(
67
+ baseUrl: 'https://school-date.test/api',
68
+ client: MockClient((request) async {
69
+ if (request.method != 'GET') posts.add(request.body);
70
+ final data = request.url.path.endsWith('/lifecycle')
71
+ ? schoolSnapshot()
72
+ : request.url.path.endsWith('/timetable')
73
+ ? {'classes': []}
74
+ : {'subjects': [], 'years': [], 'workload': [], 'grades': []};
75
+ return jsonResponse(data);
76
+ }))
77
+ ..accessToken = 'synthetic'
78
+ ..currentUserId = schoolOwner;
79
+ await tester.pumpWidget(MaterialApp(home: SchoolManagementPage(api: api)));
80
+ await tester.pumpAndSettle();
81
+ final createYear = find.widgetWithText(TextButton, 'ایجاد').at(1);
82
+ await tester.ensureVisible(createYear);
83
+ await tester.tap(createYear);
84
+ await tester.pumpAndSettle();
85
+ expect(find.textContaining('تاریخ میلادی: YYYY-MM-DD'), findsOneWidget);
86
+ final fields =
87
+ tester.widgetList<TextField>(find.byType(TextField)).toList();
88
+ expect(
89
+ fields.map((field) => field.controller!.text), everyElement(isEmpty));
90
+ expect(find.byIcon(Icons.calendar_month), findsNWidgets(2));
91
+ expect(posts, isEmpty);
92
+ await tester.tap(find.text('انصراف'));
93
+ await tester.pumpAndSettle();
94
+ await tester.pumpWidget(const SizedBox());
95
+ api.close();
96
+ });
97
+
98
+ testWidgets(
99
+ 'uncertain non-idempotent subject create refetches once and never auto retries',
100
+ (tester) async {
101
+ final subjects = <Map<String, dynamic>>[], writes = <String>[];
102
+ var readsAfterWrite = 0;
103
+ final api = HttpIdentityApi(
104
+ baseUrl: 'https://school-subject.test/api',
105
+ client: MockClient((request) async {
106
+ if (request.method == 'POST') {
107
+ writes.add(request.body);
108
+ final data = jsonDecode(request.body) as Map;
109
+ subjects.add({
110
+ 'id': '40000000-0000-4000-8000-000000000001',
111
+ 'name': data['name'],
112
+ 'teacher_name': data['teacherName'],
113
+ 'academic_term_id': schoolTermId
114
+ });
115
+ throw http.ClientException('synthetic lost ACK after commit');
116
+ }
117
+ if (writes.isNotEmpty) readsAfterWrite++;
118
+ final data = request.url.path.endsWith('/lifecycle')
119
+ ? schoolSnapshot()
120
+ : request.url.path.endsWith('/timetable')
121
+ ? {'classes': []}
122
+ : {
123
+ 'subjects': subjects,
124
+ 'years': [],
125
+ 'workload': [],
126
+ 'grades': []
127
+ };
128
+ return jsonResponse(data);
129
+ }))
130
+ ..accessToken = 'synthetic'
131
+ ..currentUserId = schoolOwner;
132
+ await tester.pumpWidget(MaterialApp(home: SchoolManagementPage(api: api)));
133
+ await tester.pumpAndSettle();
134
+ await tester.scrollUntilVisible(find.text('درس جدید'), 300,
135
+ scrollable: find.byType(Scrollable).first);
136
+ await tester.tap(find.text('درس جدید'));
137
+ await tester.pumpAndSettle();
138
+ await tester.enterText(find.byType(TextField).at(0), 'درس انتخابی');
139
+ await tester.tap(find.text('نیمسال فعال'));
140
+ await tester.pumpAndSettle();
141
+ await tester.tap(find.text('نیمسال انتخابی').last);
142
+ await tester.pumpAndSettle();
143
+ await tester.tap(find.text('ثبت'));
144
+ await tester.pumpAndSettle();
145
+ expect(writes, hasLength(1));
146
+ expect(subjects, hasLength(1));
147
+ expect(readsAfterWrite, greaterThanOrEqualTo(3));
148
+ await tester.drag(find.byType(ListView).first, const Offset(0, 1800));
149
+ await tester.pumpAndSettle();
150
+ expect(find.textContaining('نتیجه ارسال نامشخص است'), findsOneWidget);
151
+ await tester.tap(find.byTooltip('تازهکردن'));
152
+ await tester.pumpAndSettle();
153
+ expect(writes, hasLength(1));
154
+ await tester.pumpWidget(const SizedBox());
155
+ await tester.pumpWidget(MaterialApp(home: SchoolManagementPage(api: api)));
156
+ await tester.pumpAndSettle();
157
+ await tester.scrollUntilVisible(find.text('درس انتخابی'), 300,
158
+ scrollable: find.byType(Scrollable).first);
159
+ expect(find.text('درس انتخابی'), findsOneWidget);
160
+ expect(writes, hasLength(1));
161
+ await tester.pumpWidget(const SizedBox());
162
+ api.close();
163
+ });
164
+}
165
+
166
+const schoolOwner = '10000000-0000-4000-8000-000000000001';
167
+const schoolContextId = '20000000-0000-4000-8000-000000000001';
168
+const schoolYearId = '30000000-0000-4000-8000-000000000001';
169
+const schoolTermId = '30000000-0000-4000-8000-000000000002';
170
+const schoolAt = '2026-10-11T12:00:00Z';
171
+http.Response jsonResponse(Object body) => http.Response(jsonEncode(body), 200,
172
+ headers: {'content-type': 'application/json; charset=utf-8'});
173
+Map<String, dynamic> schoolSnapshot() => {
174
+ 'contexts': [
175
+ {
176
+ 'id': schoolContextId,
177
+ 'user_id': schoolOwner,
178
+ 'kind': 'student',
179
+ 'title': 'مدرسه انتخابی',
180
+ 'active': true,
181
+ 'version': 1,
182
+ 'created_at': schoolAt,
183
+ 'updated_at': schoolAt
184
+ }
185
+ ],
186
+ 'years': [
187
+ {
188
+ 'id': schoolYearId,
189
+ 'student_user_id': schoolOwner,
190
+ 'life_context_id': schoolContextId,
191
+ 'title': 'سال انتخابی',
192
+ 'starts_on': '2026-08-12',
193
+ 'ends_on': '2027-07-05',
194
+ 'active': true,
195
+ 'version': 1,
196
+ 'created_at': schoolAt,
197
+ 'updated_at': schoolAt
198
+ }
199
+ ],
200
+ 'terms': [
201
+ {
202
+ 'id': schoolTermId,
203
+ 'academic_year_id': schoolYearId,
204
+ 'title': 'نیمسال انتخابی',
205
+ 'starts_on': '2026-08-15',
206
+ 'ends_on': '2027-02-10',
207
+ 'active': true,
208
+ 'version': 1,
209
+ 'created_at': schoolAt,
210
+ 'updated_at': schoolAt
211
+ }
212
+ ],
213
+ 'fetchedAt': schoolAt
214
+ };
apps/lifemate/test/study_ui_test.dart
+9
-3
@@ -138,7 +138,8 @@ void main() {
138
await tester.pumpWidget(const SizedBox());
139
api.close();
140
});
141
- testWidgets('parent polling failure labels previous report stale',
141
+ testWidgets(
142
+ 'parent polling failure clears report until current permission succeeds',
143
(tester) async {
144
var fail = false;
145
var calls = 0;
@@ -177,12 +178,16 @@ void main() {
178
childId: 'child',
179
childName: 'فرزند')));
180
await tester.pumpAndSettle();
181
+ await tester.scrollUntilVisible(find.text('ریاضی'), 200);
182
expect(find.text('ریاضی'), findsOneWidget);
183
fail = true;
184
await tester.pump(const Duration(seconds: 15));
185
await tester.pumpAndSettle();
184
- expect(find.textContaining('داده قبلی بهروز نیست'), findsOneWidget);
185
- expect(find.text('ریاضی'), findsOneWidget);
186
+ await tester.scrollUntilVisible(
187
+ find.textContaining('اطلاعات فرزند بدون تأیید مجوز فعلی'), -200);
188
+ expect(find.textContaining('اطلاعات فرزند بدون تأیید مجوز فعلی'),
189
+ findsOneWidget);
190
+ expect(find.text('ریاضی'), findsNothing);
191
expect(calls, 2);
192
await tester.pumpWidget(const SizedBox());
193
await tester.pump(const Duration(seconds: 30));
@@ -224,6 +229,7 @@ void main() {
229
childId: 'child',
230
childName: 'فرزند')));
231
await tester.pumpAndSettle();
232
+ await tester.scrollUntilVisible(find.text('اطلاعات فرزند'), 200);
233
expect(find.text('اطلاعات فرزند'), findsOneWidget);
234
fail = true;
235
await tester.pump(const Duration(seconds: 15));
apps/lifemate/tool/assert-learning-progress-semantics.cjs
new
+51
@@ -0,0 +1,51 @@
1
+// Compiled-browser regression helper. Call only with a dedicated NEW synthetic
2
+// actor in the local HTTPS acceptance harness; pass its independent API result.
3
+// Reads real Chromium semantics. Does not change UI state, APIs or TLS settings.
4
+const assert = require('node:assert/strict');
5
+
6
+const statuses = {
7
+ not_started: 'شروع نشده',
8
+ in_progress: 'در حال یادگیری',
9
+ completed: 'تکمیل طبق گزارش من',
10
+};
11
+
12
+async function assertLearningProgressSemantics(page, progress) {
13
+ const origin = new URL(page.url());
14
+ assert.equal(origin.origin, 'https://127.0.0.1:8445',
15
+ 'Use only the isolated synthetic local HTTPS stack.');
16
+ assert(progress && Object.hasOwn(statuses, progress.status),
17
+ 'Provide the independent API progress snapshot, not a guessed UI label.');
18
+ assert.equal(progress.source, 'self_reported');
19
+ assert.equal(progress.pending_sync === true, false,
20
+ 'This compiled-browser check requires an acknowledged server snapshot.');
21
+ assert(Number.isInteger(progress.version) && progress.version > 0);
22
+ assert(typeof progress.updatedAt === 'string' &&
23
+ /(?:Z|[+-]\d{2}:\d{2})$/.test(progress.updatedAt) &&
24
+ Number.isFinite(Date.parse(progress.updatedAt)));
25
+
26
+ const label = `پیشرفت شخصی: ${statuses[progress.status]}\nآخرین ثبت سرور: ${progress.updatedAt}`;
27
+ const status = page.getByRole('status', {name: label, exact: true});
28
+ await status.waitFor({state: 'attached', timeout: 20000});
29
+ assert.equal(await status.count(), 1,
30
+ 'Progress and server timestamp must share one accessible status node.');
31
+ assert.equal(await status.getAttribute('aria-label'), label);
32
+
33
+ const session = await page.context().newCDPSession(page);
34
+ try {
35
+ const {nodes} = await session.send('Accessibility.getFullAXTree');
36
+ const matches = nodes.filter(node => !node.ignored &&
37
+ node.role?.value === 'status' && node.name?.value === label);
38
+ assert.equal(matches.length, 1,
39
+ 'The updated label must appear in Chromium accessibility, not only DOM attributes.');
40
+ assert.equal(nodes.filter(node => !node.ignored &&
41
+ node.role?.value === 'StaticText' && node.name?.value?.startsWith('پیشرفت شخصی:')).length, 0,
42
+ 'Do not duplicate progress announcements through excluded child Text widgets.');
43
+ return {status: 'PASS', role: 'status', serverVersion: progress.version,
44
+ includesSelfReportedStatus: true, includesServerTimestamp: true,
45
+ accessibleStatusNodeCount: matches.length};
46
+ } finally {
47
+ await session.detach();
48
+ }
49
+}
50
+
51
+module.exports = {assertLearningProgressSemantics};
apps/lifemate/tool/test_offline_worker.mjs
new
+52
@@ -0,0 +1,52 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import fs from 'node:fs/promises';
4
+import vm from 'node:vm';
5
+
6
+const source = await fs.readFile(new URL('../web/lifeguide-sw.js', import.meta.url), 'utf8');
7
+function worker({offline=false}={}) {
8
+ const handlers={},stored=new Map(),requests=[];
9
+ const response=new Response('synthetic public document',{status:200});
10
+ const cache={async put(key,value){stored.set(typeof key==='string'?key:key.url,value);},
11
+ async match(key){return stored.get(typeof key==='string'?key:key.url);}};
12
+ const context={URL,Request,Response,
13
+ self:{location:{href:'https://offline.example.test/lifeguide-sw.js',origin:'https://offline.example.test'},
14
+ addEventListener(name,handler){handlers[name]=handler;},async skipWaiting(){},clients:{async claim(){}}},
15
+ caches:{async open(){return cache;},async keys(){return[];},async delete(){}},
16
+ async fetch(request,options){requests.push({request,options});if(offline)throw new Error('synthetic network down');return response.clone();}};
17
+ vm.runInNewContext(source,context);
18
+ return {handlers,cache,stored,requests,setOffline(value){offline=value;},
19
+ async install(){let done;handlers.install({waitUntil(value){done=value;}});await done;},
20
+ async fetch(path,{mode='navigate',authorization=false,method='GET'}={}) {
21
+ let result;
22
+ const request={url:'https://offline.example.test'+path,mode,method,
23
+ headers:new Headers(authorization?{authorization:'synthetic'}:{})};
24
+ handlers.fetch({request,respondWith(value){result=value;}});
25
+ return result===undefined?undefined:await result;
26
+ }};
27
+}
28
+
29
+test('installation caches only a credential-free public offline notice and retry script',async()=>{
30
+ const w=worker();await w.install();
31
+ assert.equal(w.stored.size,2);
32
+ for(const call of w.requests){assert.equal(call.request.credentials,'omit');assert.equal(call.options.cache,'no-store');}
33
+});
34
+test('cold offline navigation receives public notice; online navigation prefers network',async()=>{
35
+ const w=worker();await w.install();w.setOffline(true);
36
+ assert.equal((await w.fetch('/')).status,200);
37
+ w.setOffline(false);const before=w.requests.length;
38
+ assert.equal((await w.fetch('/')).status,200);
39
+ assert.equal(w.requests.length,before+1);
40
+});
41
+test('API, runtime configuration, auth paths and authenticated requests never receive fallback',async()=>{
42
+ const w=worker();await w.install();w.setOffline(true);
43
+ for(const path of ['/api/health','/api/v1/profile','/config.json','/verify-email?token=synthetic','/accept-invitation?token=synthetic','/unknown']) {
44
+ assert.equal(await w.fetch(path),undefined,path);
45
+ }
46
+ assert.equal(await w.fetch('/',{authorization:true}),undefined);
47
+ assert.equal(await w.fetch('/',{method:'POST'}),undefined);
48
+});
49
+test('uncached private content is never created by offline navigation',async()=>{
50
+ const w=worker();await w.install();const keys=[...w.stored.keys()];w.setOffline(true);
51
+ await w.fetch('/index.html');assert.deepEqual([...w.stored.keys()],keys);
52
+});
apps/lifemate/web/lifeguide-sw.js
+31
-6
@@ -1,9 +1,21 @@
1
-// Fresh application code/settings always come from the network. Cache only
2
-// public static resources; no API, authentication, navigation or personal data.
3
-const CACHE = 'lifeguide-static-v0.5.0-3';
1
+// Current code/settings use the network. A cold disconnected navigation may
2
+// show only a public notice, never cached login, permissions or personal data.
3
+const CACHE = 'lifeguide-static-v0.7.0-6';
4
const BASE_PATH = new URL('.', self.location.href).pathname;
5
-const STATIC_PATH = /^(?:assets|canvaskit|icons)\//;
6
-self.addEventListener('install', () => self.skipWaiting());
5
+const OFFLINE_URL = new URL('offline.html', self.location.href).href;
6
+const RETRY_URL = new URL('offline-retry.js', self.location.href).href;
7
+const STATIC_PATH = /^(?:(?:assets|canvaskit|icons)\/|offline-retry\.js$)/;
8
+self.addEventListener('install', (event) => {
9
+ event.waitUntil((async () => {
10
+ const cache = await caches.open(CACHE);
11
+ for (const url of [OFFLINE_URL, RETRY_URL]) {
12
+ const response = await fetch(new Request(url, {credentials: 'omit'}), {cache: 'no-store'});
13
+ if (!response.ok) throw new Error('Offline notice unavailable');
14
+ await cache.put(url, response);
15
+ }
16
+ await self.skipWaiting();
17
+ })());
18
+});
19
self.addEventListener('activate', (event) => {
20
event.waitUntil((async () => {
21
for (const key of await caches.keys()) {
@@ -19,7 +31,20 @@ self.addEventListener('fetch', (event) => {
31
const url = new URL(request.url);
32
if (request.method !== 'GET' || url.origin !== self.location.origin ||
33
url.search || request.headers.has('authorization') ||
22
- !url.pathname.startsWith(BASE_PATH) ||
34
+ !url.pathname.startsWith(BASE_PATH)) return;
35
+ const relative = url.pathname.slice(BASE_PATH.length);
36
+ if (request.mode === 'navigate' && (relative === '' || relative === 'index.html')) {
37
+ event.respondWith((async () => {
38
+ try { return await fetch(request, {cache: 'no-store'}); }
39
+ catch (error) {
40
+ const stored = await (await caches.open(CACHE)).match(OFFLINE_URL);
41
+ if (stored) return stored;
42
+ throw error;
43
+ }
44
+ })());
45
+ return;
46
+ }
47
+ if (
48
!STATIC_PATH.test(url.pathname.slice(BASE_PATH.length))) return;
49
event.respondWith((async () => {
50
const cache = await caches.open(CACHE);
apps/lifemate/web/offline-retry.js
new
+3
@@ -0,0 +1,3 @@
1
+document.getElementById('offline-retry').addEventListener('click', () => {
2
+ window.location.reload();
3
+});
apps/lifemate/web/offline.html
new
+26
@@ -0,0 +1,26 @@
1
+<!doctype html>
2
+<html lang="fa" dir="rtl">
3
+<head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
6
+ <meta name="theme-color" content="#ffffff">
7
+ <title>لایفگاید — اتصال برقرار نیست</title>
8
+ <style>
9
+ body{margin:0;background:#f8fafd;color:#203047;font-family:system-ui,sans-serif;line-height:1.9}
10
+ main{max-width:38rem;margin:12vh auto;padding:2rem;background:white;border-radius:1rem}
11
+ button{padding:.8rem 1.5rem;border:0;border-radius:.6rem;background:#356bb8;color:white;font:inherit;cursor:pointer}
12
+ button:focus-visible{outline:3px solid #203047;outline-offset:4px}
13
+ @media(max-width:42rem){main{margin:5vh 1rem;padding:1.4rem}}
14
+ </style>
15
+</head>
16
+<body>
17
+ <main>
18
+ <h1>لایفگاید</h1>
19
+ <p role="status">اتصال برقرار نیست. اطلاعات تازه یا ورود به حساب هنوز تأیید نشده است.</p>
20
+ <p>این صفحه تغییرهای ارسالنشده را حذف نمیکند. برای ادامه، اتصال را برقرار کنید و دوباره تلاش کنید. دادههای مرورگر را پاک نکنید.</p>
21
+ <p>اطلاعات خصوصی در این صفحه نمایش داده نمیشود.</p>
22
+ <button type="button" id="offline-retry">تلاش دوباره</button>
23
+ </main>
24
+ <script src="offline-retry.js"></script>
25
+</body>
26
+</html>
scripts/prebuilt-web-check.mjs
+2
-2
@@ -32,7 +32,7 @@ for (const path of files.filter(path => /\.(js|json|html)$/.test(path))) {
32
const text = await readFile(path, 'utf8');
33
assert(!/https?:[^\s"'<>]*(?:gstatic\.com|googleapis\.com|up\.railway\.app)/i.test(text), `External runtime dependency: ${relative(output, path)}`);
34
}
35
-for (const path of ['index.html', 'main.dart.js', 'flutter_bootstrap.js', 'lifeguide-sw.js', 'canvaskit/canvaskit.wasm']) {
35
+for (const path of ['index.html', 'main.dart.js', 'flutter_bootstrap.js', 'lifeguide-sw.js', 'offline.html', 'offline-retry.js', 'canvaskit/canvaskit.wasm']) {
36
assert(files.includes(join(output, path)), `Missing built resource: ${path}`);
37
}
38
for (const name of ['LifeGuidePersian.ttf', 'LifeGuideLatin.ttf', 'LifeGuideEmoji.ttf']) {
@@ -45,7 +45,7 @@ assert(config.apiBaseUrl === '/api', 'Prebuilt default API must use runtime same
45
const builtTitle = /<title>([^<]+)<\/title>/.exec(await readFile(join(output, 'index.html'), 'utf8'))?.[1];
46
const sourceTitle = /<title>([^<]+)<\/title>/.exec(await readFile(join(app, 'web/index.html'), 'utf8'))?.[1];
47
assert(builtTitle === sourceTitle && builtTitle?.includes('LifeGuide'), 'LifeGuide HTML title must match source');
48
-for (const path of ['manifest.json', 'favicon.png', 'icons/Icon-192.png', 'icons/Icon-512.png', 'icons/Icon-maskable-192.png', 'icons/Icon-maskable-512.png']) {
48
+for (const path of ['manifest.json', 'lifeguide-sw.js', 'offline.html', 'offline-retry.js', 'favicon.png', 'icons/Icon-192.png', 'icons/Icon-512.png', 'icons/Icon-maskable-192.png', 'icons/Icon-maskable-512.png']) {
49
assert((await readFile(join(output, path))).equals(await readFile(join(app, 'web', path))), `Built branding differs from source: ${path}`);
50
}
51
const provenance = join(output, 'build-provenance.json');
scripts/test-learning-browser.cjs
+89
-4
@@ -8,6 +8,7 @@ const os = require('node:os');
8
const https = require('node:https');
9
const {spawnSync} = require('node:child_process');
10
const {chromium} = require('../apps/lifemate/node_modules/playwright');
11
+const {assertLearningProgressSemantics} = require('../apps/lifemate/tool/assert-learning-progress-semantics.cjs');
12
13
const root = path.resolve(__dirname, '..');
14
const origin = process.env.LEARNING_BROWSER_ORIGIN || 'https://127.0.0.1:8445';
@@ -23,7 +24,7 @@ assert(/^learning-browser-[a-f0-9]+@example\.test$/.test(email) && password.leng
24
assert(process.env.ROOT_CA && process.env.LEARNING_COMPOSE_ENV,
25
'ROOT_CA and private LEARNING_COMPOSE_ENV paths are required.');
26
const receiptFile = path.resolve(process.argv[2] || path.join(root,
26
- 'docs/audits/evidence/learning-browser-2026-10-11.json'));
27
+ 'docs/audits/evidence/content-operations-browser-2026-10-12.json'));
28
const screenshotFile = receiptFile.replace(/\.json$/, '.png');
29
const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
30
const escaped = value => value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
@@ -185,6 +186,8 @@ async function lesson(page, course, unit) {
186
const stored = dbJson(`select json_build_object('count',count(*),'status',max(status),'source',max(source),'version',max(version)) from learning_progress where owner_user_id='${owner}' and unit_id='${unit.id}';`);
187
assert.deepEqual(stored,{count:1,status:'in_progress',source:'self_reported',version:1});
188
await page.waitForLoadState('networkidle');
189
+ await assertLearningProgressSemantics(page,independent[0]);
190
+ check('compiled Chromium AXTree exposes one RTL status with acknowledged progress and server timestamp');
191
await fs.mkdir(path.dirname(receiptFile),{recursive:true});
192
await page.screenshot({path:receiptFile.replace(/\.json$/, '-progress.png'),fullPage:false});
193
check('UI progress acknowledgement independently verified through API and PostgreSQL');
@@ -234,6 +237,7 @@ async function lesson(page, course, unit) {
237
assert(auth.some(item => item.path === '/api/v1/auth/refresh' && item.status === 200));
238
const afterRestart = (await api('GET','/v1/me/learning-progress',undefined,token)).json.progress;
239
assert.equal(afterRestart.length,1); assert.equal(afterRestart[0].version,1);
240
+ await assertLearningProgressSemantics(page,afterRestart[0]);
241
assert.equal(await page.locator('iframe').count(),0);
242
check('closed and reopened Chromium refreshes persisted session; independent API retains one acknowledged progress record');
243
@@ -246,16 +250,97 @@ async function lesson(page, course, unit) {
250
check('real compiled runtime uses only local API, fonts and CanvasKit without errors');
251
await fs.mkdir(path.dirname(receiptFile),{recursive:true});
252
await page.screenshot({path:screenshotFile,fullPage:false});
253
+
254
+ stage = 'offlineIntent';
255
+ await page.evaluate(async () => {
256
+ await navigator.serviceWorker.ready;
257
+ if (!navigator.serviceWorker.controller) await new Promise(resolve =>
258
+ navigator.serviceWorker.addEventListener('controllerchange',resolve,{once:true}));
259
+ });
260
+ const offlineStart = {requests:paths.length,errors:errors.length,failures:failures.length};
261
+ const offlineKey = 'lifeguide.offline.v2.' + Buffer.from(origin+'/api|'+owner)
262
+ .toString('base64').replaceAll('+','-').replaceAll('/','_');
263
+ await context.setOffline(true);
264
+ await click(page.getByRole('button',{name:'طبق گزارش من تکمیل شد',exact:true}));
265
+ await bodyIncludes(page,'تغییر روی دستگاه ذخیره شده؛ تأیید سرور دریافت نشده است.');
266
+ const pendingBytes = await page.evaluate(key => localStorage.getItem(key),offlineKey);
267
+ assert(pendingBytes,'A real rendered offline action must create durable account-scoped bytes.');
268
+ const pending = JSON.parse(JSON.parse(pendingBytes)).queue;
269
+ assert.equal(pending.length,1);
270
+ assert.equal(pending[0].entityType,'learning_progress');
271
+ assert.equal(pending[0].entityId,unit.id);
272
+ assert.equal(pending[0].payload.status,'completed');
273
+ assert.equal(pending[0].payload.expectedVersion,1);
274
+ assert(uuid.test(pending[0].id));
275
+ assert.equal((await api('GET','/v1/me/learning-progress',undefined,token)).json.progress[0].version,1);
276
+ check('rendered offline action journals one stable progress intent; independent server remains unchanged');
277
+
278
+ stage = 'offlineReopen';
279
+ await page.close();
280
+ page = await context.newPage(); observe(page);
281
+ const disconnected = await page.goto(origin,{waitUntil:'networkidle',timeout:30000});
282
+ assert.equal(disconnected.status(),200);
283
+ assert.equal(await page.locator('html').getAttribute('dir'),'rtl');
284
+ await page.getByRole('status').filter({hasText:'اتصال برقرار نیست'}).waitFor();
285
+ assert.equal(await page.locator('flt-glass-pane').count(),0);
286
+ assert(!(await page.locator('body').innerText()).includes(unit.titleFa));
287
+ assert.equal(await page.evaluate(key => localStorage.getItem(key),offlineKey),pendingBytes);
288
+ for (const endpoint of ['/api/health','/config.json']) {
289
+ const result = await page.evaluate(async endpoint => {
290
+ try { const r=await fetch(endpoint); return {reachable:true,text:await r.text()}; }
291
+ catch { return {reachable:false}; }
292
+ },endpoint);
293
+ assert.equal(result.reachable,false,'Private/API/config paths must not receive cached offline HTML.');
294
+ }
295
+ const cachedUrls = await page.evaluate(async () => {
296
+ const result=[];
297
+ for (const name of await caches.keys()) for (const request of await (await caches.open(name)).keys())
298
+ result.push(new URL(request.url).pathname);
299
+ return result;
300
+ });
301
+ assert(!cachedUrls.some(p=>p==='/'||p==='/index.html'||p==='/config.json'||p.startsWith('/api/')));
302
+ check('closed/reopened offline PWA shows only public RTL notice; exact pending bytes retained, API/config remain unavailable');
303
+
304
+ stage = 'offlineReconnect';
305
+ await context.setOffline(false);
306
+ await page.getByRole('button',{name:'تلاش دوباره',exact:true}).click();
307
+ await page.waitForFunction(() => !document.getElementById('startup-status'),null,{timeout:60000});
308
+ await page.locator('flt-glass-pane').waitFor({state:'attached'});
309
+ const placeholder=page.locator('flt-semantics-placeholder');
310
+ if(await placeholder.count()) await placeholder.evaluate(e=>e.click());
311
+ await school(page); await lesson(page,course,unit);
312
+ const replay = page.waitForResponse(r=>r.url().includes('/api/v1/me/learning-progress/')&&r.request().method()==='PUT');
313
+ await click(page.getByRole('button',{name:'همگامسازی و تازهسازی',exact:true}));
314
+ const accepted = await replay;
315
+ assert.equal(accepted.status(),200);
316
+ const replayBody=accepted.request().postDataJSON();
317
+ assert.deepEqual(replayBody,pending[0].payload);
318
+ await page.waitForLoadState('networkidle');
319
+ const synced=(await api('GET','/v1/me/learning-progress',undefined,token)).json.progress;
320
+ assert.equal(synced.length,1); assert.equal(synced[0].version,2); assert.equal(synced[0].status,'completed');
321
+ await assertLearningProgressSemantics(page,synced[0]);
322
+ const storedAfter=dbJson(`select json_build_object('count',count(*),'version',max(version),'status',max(status)) from learning_progress where owner_user_id='${owner}' and unit_id='${unit.id}';`);
323
+ assert.deepEqual(storedAfter,{count:1,version:2,status:'completed'});
324
+ const afterBytes=await page.evaluate(key=>localStorage.getItem(key),offlineKey);
325
+ assert.equal(JSON.parse(JSON.parse(afterBytes)).queue.length,0);
326
+ await click(page.getByRole('button',{name:'همگامسازی و تازهسازی',exact:true}));
327
+ await page.waitForLoadState('networkidle');
328
+ assert.equal((await api('GET','/v1/me/learning-progress',undefined,token)).json.progress[0].version,2);
329
+ check('manual reconnect authenticates current account and acknowledges identical intent once; second sync creates no duplicate');
330
+ assert.equal(paths.filter(item=>item.origin!==origin).length,0);
331
+ assert.equal(errors.length,offlineStart.errors);
332
const receipt = {date:new Date().toISOString(),mode:'Actual isolated local Compose HTTPS; normal Node and Chromium CA trust; no network interception or TLS bypass',
333
origin,browser:'Chromium',checks,fixture:'Dedicated synthetic account; no real family/private/media data',
251
- counts:{requests:paths.length,externalRequests:0,iframes:0,browserErrors:0,failedRequests:0},
334
+ counts:{requests:paths.length,externalRequests:0,iframes:0,browserErrors:errors.length,
335
+ onlineFailedRequests:offlineStart.failures,expectedOfflineFailedRequests:failures.length-offlineStart.failures},
336
+ offlineEvidence:'Chromium context deliberately disconnected; real UI journals a stable intent, page closes/reopens through actual service worker public fallback, reconnect retries exact body and independent API/SQL verify version2 once. Context stays open during offline page restart; process-kill/storage-eviction/Safari remain UNVERIFIED.',
337
realApprovedVideoCount:0,realApprovedQuestionBankCount:0,
338
visualEvidence:{progressScreenshot:path.basename(receiptFile.replace(/\.json$/, '-progress.png')),
339
reopenedLessonScreenshot:path.basename(screenshotFile),
255
- automatedDynamicProgressSemantics:'UNVERIFIED: dynamic progress/timestamp text was absent from Chromium ARIA after updates; inspect rendered screenshots separately'},
340
+ automatedDynamicProgressSemantics:'Actual Chromium AXTree status label checked after acknowledgement and browser restart; physical screen-reader acceptance remains UNVERIFIED'},
341
interactionMode:'Rendered Flutter semantic controls activated with DOM element.click because RTL hit rectangles are transformed; text entered through rendered fields and keyboard. No API or state injection. Physical touch/pointer/accessibility acceptance is UNVERIFIED.',
342
authResponses:auth,fonts:[...new Set(paths.filter(item => /\.(ttf|otf|woff2)$/.test(item.path)).map(item => item.path))],
258
- limitations:['Real Android devices UNVERIFIED','Safari/Add to Home Screen UNVERIFIED','Video playback and teaching quality UNVERIFIED','Iran VPN-free reachability UNVERIFIED','Offline cold startup UNVERIFIED','Dynamic progress accessibility semantics after updates remain unverified; screenshots require separate visual review']};
343
+ limitations:['Real Android devices UNVERIFIED','Safari/Add to Home Screen UNVERIFIED','Video playback and teaching quality UNVERIFIED','Iran VPN-free reachability UNVERIFIED','Physical touch and screen reader UNVERIFIED']};
344
await fs.writeFile(receiptFile,JSON.stringify(receipt,null,2)+'\n');
345
console.log(JSON.stringify(receipt,null,2));
346
} catch (error) {