LifeMate — Personal, Family & Learning Companion

feat/child-identity-schema
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
dart 485 lines 18.2 KB
Raw
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 }