LifeMate — Personal, Family & Learning Companion

docs/offline-data-rescue-options
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 612 lines 24.6 KB
Raw
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 final _quizUuid =
11 RegExp(r'^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$');
12 final _quizKey = RegExp(r'^[a-zA-Z0-9_-]{1,80}$');
13 const _confidences = {
14 'unsure': 'مطمئن نیستم',
15 'somewhat': 'تا حدی مطمئنم',
16 'confident': 'مطمئنم',
17 };
18
19 bool _uuid(dynamic value) => value is String && _quizUuid.hasMatch(value);
20 bool _key(dynamic value) => value is String && _quizKey.hasMatch(value);
21 bool _text(dynamic value) =>
22 value is String &&
23 value.trim().isNotEmpty &&
24 value.length <= 2000 &&
25 !value.contains('\u0000');
26 bool _fields(Map value, Set<String> fields) =>
27 value.length == fields.length && value.keys.every(fields.contains);
28
29 Map<String, dynamic> _attemptBody(Map<String, dynamic> value) {
30 if (!_fields(value, {
31 'mutationId',
32 'assessmentId',
33 'assessmentVersion',
34 'answers',
35 'confidence'
36 }) ||
37 !_uuid(value['mutationId']) ||
38 !_uuid(value['assessmentId']) ||
39 value['assessmentVersion'] is! int ||
40 value['assessmentVersion'] < 1 ||
41 !_confidences.containsKey(value['confidence']) ||
42 value['answers'] is! List) {
43 throw const ApiException(422, 'invalid_quiz_attempt');
44 }
45 final answers = value['answers'] as List;
46 final questions = <String>{};
47 if (answers.isEmpty || answers.length > 20) {
48 throw const ApiException(422, 'invalid_quiz_attempt');
49 }
50 for (final answer in answers) {
51 if (answer is! Map ||
52 !_fields(answer, {'questionId', 'choiceId'}) ||
53 !_key(answer['questionId']) ||
54 !_key(answer['choiceId']) ||
55 !questions.add(answer['questionId'] as String)) {
56 throw const ApiException(422, 'invalid_quiz_attempt');
57 }
58 }
59 // Own an immutable-by-caller snapshot before any asynchronous storage work.
60 return Map<String, dynamic>.from(jsonDecode(jsonEncode(value)) as Map);
61 }
62
63 /// Durable, account-scoped quiz answers. A quiz result never changes the
64 /// learner's separate, explicitly reported lesson-progress state.
65 class LearningQuizSync {
66 LearningQuizSync(this.api, {OfflineStore? store})
67 : store = store ?? OfflineStore.forApi(api);
68 final HttpIdentityApi api;
69 final OfflineStore store;
70 static final _tails = <String, Future<void>>{};
71 static const _cache = 'learning_attempts';
72
73 void _scope() {
74 if (api.cacheNamespace != store.scope) {
75 throw const ApiException(401, 'cache_scope_closed');
76 }
77 }
78
79 Future<T> _serial<T>(Future<T> Function() operation) {
80 final previous = _tails[store.scope];
81 final release = Completer<void>();
82 _tails[store.scope] = release.future;
83 return (() async {
84 if (previous != null) await previous;
85 try {
86 _scope();
87 await store.readQueue(); // Also checks the captured store generation.
88 _scope();
89 final result = await operation();
90 _scope();
91 return result;
92 } finally {
93 if (identical(_tails[store.scope], release.future)) {
94 _tails.remove(store.scope);
95 }
96 release.complete();
97 }
98 })();
99 }
100
101 Future<List<Map<String, dynamic>>> pendingForUnit(String unitId) async {
102 _scope();
103 final pending = (await store.readQueue())
104 .where((m) =>
105 m['entityType'] == 'learning_attempt' && m['unitId'] == unitId)
106 .toList();
107 _scope();
108 return pending;
109 }
110
111 Future<Map<String, dynamic>?> readAssessment(String unitId) =>
112 _serial(() async {
113 if (!_uuid(unitId)) {
114 throw const ApiException(400, 'invalid_unit_id');
115 }
116 final response = await api.requestJson('GET',
117 '/v1/education/units/${Uri.encodeComponent(unitId)}/assessment');
118 _scope();
119 // Check generation again before exposing a response to the old page.
120 await store.readQueue();
121 if (response['assessment'] == null &&
122 response['reason'] == 'review_pending') {
123 return null;
124 }
125 final raw = response['assessment'];
126 if (raw is! Map ||
127 !_fields(raw, {'id', 'unitId', 'version', 'questions'}) ||
128 !_uuid(raw['id']) ||
129 raw['unitId'] != unitId ||
130 raw['version'] is! int ||
131 raw['version'] < 1 ||
132 raw['questions'] is! List) {
133 throw const ApiException(502, 'invalid_quiz_assessment');
134 }
135 final questions = raw['questions'] as List;
136 final ids = <String>{};
137 if (questions.isEmpty || questions.length > 20) {
138 throw const ApiException(502, 'invalid_quiz_assessment');
139 }
140 for (final question in questions) {
141 if (question is! Map ||
142 !_fields(
143 question, {'id', 'objectiveId', 'promptFa', 'choices'}) ||
144 !_key(question['id']) ||
145 !ids.add(question['id'] as String) ||
146 !_key(question['objectiveId']) ||
147 !_text(question['promptFa']) ||
148 question['choices'] is! List) {
149 throw const ApiException(502, 'invalid_quiz_assessment');
150 }
151 final choices = question['choices'] as List;
152 final choiceIds = <String>{};
153 if (choices.length < 2 || choices.length > 6) {
154 throw const ApiException(502, 'invalid_quiz_assessment');
155 }
156 for (final choice in choices) {
157 if (choice is! Map ||
158 !_fields(choice, {'id', 'textFa'}) ||
159 !_key(choice['id']) ||
160 !choiceIds.add(choice['id'] as String) ||
161 !_text(choice['textFa'])) {
162 throw const ApiException(502, 'invalid_quiz_assessment');
163 }
164 }
165 }
166 return Map<String, dynamic>.from(raw);
167 });
168
169 Future<Map<String, dynamic>> submit(
170 Map<String, dynamic> body, String unitId) {
171 final frozen = _attemptBody(body);
172 if (!_uuid(unitId)) throw const ApiException(422, 'invalid_unit_id');
173 return _serial(() async {
174 final pending = await pendingForUnit(unitId);
175 if (pending.any((m) => m['id'] != frozen['mutationId'])) {
176 throw const ApiException(409, 'sync_pending');
177 }
178 if (pending.any((m) => m['queueStatus'] != 'queued')) {
179 throw const ApiException(409, 'quiz_pending_rejected');
180 }
181 final mutation = <String, dynamic>{
182 'id': frozen['mutationId'],
183 'entityId': frozen['mutationId'],
184 'entityType': 'learning_attempt',
185 'operation': 'submit',
186 'unitId': unitId, // Local metadata; never put this in the POST body.
187 'payload': frozen,
188 };
189 await store.enqueue(mutation);
190 try {
191 return {'queued': false, 'attempt': await _send(mutation)};
192 } catch (error) {
193 _scope();
194 if (!isOfflineFailure(error)) rethrow;
195 return {'queued': true, 'attempt': null};
196 }
197 });
198 }
199
200 Map<String, dynamic> _ack(
201 Map<String, dynamic> raw, Map<String, dynamic> body, String unitId) {
202 const fields = {
203 'mutationId',
204 'attemptId',
205 'unitId',
206 'assessmentId',
207 'assessmentVersion',
208 'correctCount',
209 'total',
210 'feedback',
211 'resultLabel',
212 'nextReviewAt',
213 'schedulePolicy',
214 'source',
215 'acceptedAt'
216 };
217 Never invalid() =>
218 throw const ApiException(502, 'invalid_sync_acknowledgement');
219 DateTime? date(dynamic value) => value is String && value.endsWith('Z')
220 ? DateTime.tryParse(value)
221 : null;
222 final accepted = date(raw['acceptedAt']);
223 final next = date(raw['nextReviewAt']);
224 final answers = body['answers'] as List;
225 if (!_fields(raw, fields) ||
226 raw['mutationId'] != body['mutationId'] ||
227 !_uuid(raw['attemptId']) ||
228 raw['unitId'] != unitId ||
229 raw['assessmentId'] != body['assessmentId'] ||
230 raw['assessmentVersion'] != body['assessmentVersion'] ||
231 raw['total'] != answers.length ||
232 raw['correctCount'] is! int ||
233 raw['correctCount'] < 0 ||
234 raw['correctCount'] > answers.length ||
235 raw['feedback'] is! List ||
236 raw['source'] != 'quiz_answers' ||
237 raw['schedulePolicy'] != 'pilot-1-or-3-days' ||
238 accepted == null ||
239 next == null) {
240 invalid();
241 }
242 final allCorrect = raw['correctCount'] == answers.length;
243 if (raw['resultLabel'] !=
244 (allCorrect ? 'answered_correctly' : 'needs_practice') ||
245 next.difference(accepted) != Duration(days: allCorrect ? 3 : 1)) {
246 invalid();
247 }
248 final questionIds = answers.map((a) => a['questionId']).toSet();
249 final seen = <String>{};
250 var count = 0;
251 for (final feedback in raw['feedback'] as List) {
252 if (feedback is! Map ||
253 !_fields(feedback, {
254 'questionId',
255 'objectiveId',
256 'correct',
257 'explanationFa',
258 'remediationFa'
259 }) ||
260 !_key(feedback['questionId']) ||
261 !questionIds.contains(feedback['questionId']) ||
262 !seen.add(feedback['questionId'] as String) ||
263 !_key(feedback['objectiveId']) ||
264 feedback['correct'] is! bool ||
265 !_text(feedback['explanationFa']) ||
266 !_text(feedback['remediationFa'])) {
267 invalid();
268 }
269 if (feedback['correct'] == true) count++;
270 }
271 if (seen.length != answers.length || count != raw['correctCount']) {
272 invalid();
273 }
274 return {...raw, 'id': raw['attemptId']};
275 }
276
277 Future<Map<String, dynamic>> _send(Map<String, dynamic> mutation) async {
278 _scope();
279 if (mutation['entityType'] != 'learning_attempt' ||
280 mutation['operation'] != 'submit' ||
281 !_uuid(mutation['unitId']) ||
282 mutation['entityId'] != mutation['id'] ||
283 mutation['payload'] is! Map) {
284 throw const ApiException(422, 'invalid_quiz_attempt');
285 }
286 final body =
287 _attemptBody(Map<String, dynamic>.from(mutation['payload'] as Map));
288 if (body['mutationId'] != mutation['id']) {
289 throw const ApiException(422, 'invalid_quiz_attempt');
290 }
291 await store.readQueue();
292 _scope();
293 final Map<String, dynamic> response;
294 try {
295 response =
296 await api.requestJson('POST', '/v1/me/learning-attempts', body: body);
297 _scope();
298 } catch (error) {
299 _scope();
300 if (error is ApiException &&
301 [400, 404, 409, 422].contains(error.statusCode)) {
302 await store.markQueued(mutation['id'] as String,
303 error.statusCode == 409 ? 'conflict' : 'rejected',
304 error: error.code);
305 }
306 rethrow;
307 }
308 final attempt = _ack(response, body, mutation['unitId'] as String);
309 await store.acknowledge(mutation['id'] as String,
310 item: attempt,
311 acceptedAt: attempt['acceptedAt'] as String,
312 cacheKey: _cache);
313 _scope();
314 return attempt;
315 }
316
317 Future<void> flush() => _serial(() async {
318 for (final mutation in await store.readQueue()) {
319 if (mutation['entityType'] != 'learning_attempt') continue;
320 if (mutation['queueStatus'] == 'conflict') {
321 throw const ApiException(409, 'sync_conflict');
322 }
323 if (mutation['queueStatus'] != 'queued') continue;
324 try {
325 await _send(mutation);
326 } catch (error) {
327 if (isOfflineFailure(error)) return;
328 rethrow;
329 }
330 }
331 });
332
333 /// Explicit cancellation stops retries and journals the original answers.
334 /// It cannot undo an attempt that the server already accepted.
335 Future<void> cancelPending(String mutationId) => _serial(() async {
336 final queue = await store.readQueue();
337 if (!queue.any((m) =>
338 m['id'] == mutationId && m['entityType'] == 'learning_attempt')) {
339 return;
340 }
341 await store.discardEntityChanges(mutationId,
342 entityType: 'learning_attempt', cacheKey: _cache);
343 });
344 }
345
346 class LearningQuizPage extends StatefulWidget {
347 const LearningQuizPage({super.key, required this.api, required this.unitId});
348 final HttpIdentityApi api;
349 final String unitId;
350 @override
351 State<LearningQuizPage> createState() => _LearningQuizPageState();
352 }
353
354 class _LearningQuizPageState extends State<LearningQuizPage> {
355 late final sync = LearningQuizSync(widget.api);
356 Map<String, dynamic>? assessment, pending, attempt;
357 final answers = <String, String>{};
358 String? confidence, message;
359 bool loading = true, busy = false;
360
361 @override
362 void initState() {
363 super.initState();
364 load();
365 }
366
367 bool get matchesPending =>
368 pending == null ||
369 (assessment?['id'] == pending!['assessmentId'] &&
370 assessment?['version'] == pending!['assessmentVersion']);
371
372 bool get complete =>
373 assessment != null &&
374 answers.length == (assessment!['questions'] as List).length &&
375 confidence != null;
376
377 void failure(Object error) {
378 if (error is ApiException && [401, 403].contains(error.statusCode)) {
379 assessment = pending = attempt = null;
380 answers.clear();
381 confidence = null;
382 message = 'برای دیدن آزمون، دوباره وارد حساب خود شوید.';
383 } else if (isOfflineFailure(error)) {
384 message = pending == null
385 ? 'برای دریافت آزمون بازبینی‌شده، اتصال به سرور لازم است.'
386 : 'پاسخ‌ها روی این دستگاه نگه داشته شده‌اند؛ هنوز نتیجهٔ سرور دریافت نشده است.';
387 } else if (error is ApiException && error.statusCode == 409) {
388 message =
389 'این ارسال به بررسی نیاز دارد. پاسخ‌ها حفظ شده‌اند؛ برای شروع دوباره، ارسال را لغو کنید.';
390 } else {
391 message =
392 'آزمون یا تأیید نتیجه دریافت نشد. پاسخ‌های ثبت‌شده حذف نشده‌اند.';
393 }
394 }
395
396 Future<void> load() async {
397 try {
398 final rows = await sync.pendingForUnit(widget.unitId);
399 if (!mounted) return;
400 if (rows.isNotEmpty) {
401 pending = _attemptBody(
402 Map<String, dynamic>.from(rows.first['payload'] as Map));
403 for (final answer in pending!['answers'] as List) {
404 answers[answer['questionId'] as String] =
405 answer['choiceId'] as String;
406 }
407 confidence = pending!['confidence'] as String;
408 message =
409 'پاسخ‌ها روی این دستگاه نگه داشته شده‌اند؛ تا تأیید یا لغو، قابل تغییر نیستند.';
410 }
411 final bank = await sync.readAssessment(widget.unitId);
412 if (mounted) setState(() => assessment = bank);
413 } catch (error) {
414 if (mounted) setState(() => failure(error));
415 } finally {
416 if (mounted) setState(() => loading = false);
417 }
418 }
419
420 Future<void> send() async {
421 if (busy || (pending == null && !complete)) return;
422 final body = pending ??
423 {
424 'mutationId': newMutationId(),
425 'assessmentId': assessment!['id'],
426 'assessmentVersion': assessment!['version'],
427 'answers': [
428 for (final question in assessment!['questions'] as List)
429 {
430 'questionId': question['id'],
431 'choiceId': answers[question['id']]
432 },
433 ],
434 'confidence': confidence,
435 };
436 setState(() {
437 busy = true;
438 message = null;
439 });
440 try {
441 final result = await sync.submit(body, widget.unitId);
442 if (!mounted) return;
443 setState(() {
444 if (result['queued'] == true) {
445 pending = _attemptBody(body);
446 message =
447 'پاسخ‌ها روی این دستگاه نگه داشته شده‌اند؛ هنوز نتیجهٔ سرور دریافت نشده است.';
448 } else {
449 pending = null;
450 attempt = Map<String, dynamic>.from(result['attempt'] as Map);
451 }
452 });
453 } catch (error) {
454 // A permanent rejection or malformed acknowledgement also leaves a
455 // durable pending record, and must never unlock answers for a new ID.
456 try {
457 final rows = await sync.pendingForUnit(widget.unitId);
458 if (rows.isNotEmpty) pending = _attemptBody(body);
459 } catch (_) {/* Keep the original scope/storage error below. */}
460 if (mounted) setState(() => failure(error));
461 } finally {
462 if (mounted) setState(() => busy = false);
463 }
464 }
465
466 Future<void> cancel() async {
467 final confirmed = await showDialog<bool>(
468 context: context,
469 builder: (context) => AlertDialog(
470 title: const Text('لغو تلاش برای ارسال؟'),
471 content: const Text(
472 'ممکن است سرور قبلاً این پاسخ‌ها را دریافت کرده باشد. لغو فقط تلاش بعدی این دستگاه را متوقف می‌کند و نتیجهٔ سرور را حذف نمی‌کند. پاسخ‌ها در سابقهٔ بازیابی محلی نگه داشته می‌شوند.'),
473 actions: [
474 TextButton(
475 onPressed: () => Navigator.pop(context, false),
476 child: const Text('بازگشت')),
477 TextButton(
478 onPressed: () => Navigator.pop(context, true),
479 child: const Text('لغو ارسال')),
480 ],
481 ));
482 if (confirmed != true || !mounted || pending == null) return;
483 setState(() => busy = true);
484 try {
485 await sync.cancelPending(pending!['mutationId'] as String);
486 if (mounted) {
487 setState(() {
488 pending = null;
489 answers.clear();
490 confidence = null;
491 message = 'تلاش برای ارسال لغو شد.';
492 });
493 }
494 } catch (error) {
495 if (mounted) setState(() => failure(error));
496 } finally {
497 if (mounted) setState(() => busy = false);
498 }
499 }
500
501 @override
502 Widget build(BuildContext context) => Directionality(
503 textDirection: TextDirection.rtl,
504 child: Scaffold(
505 appBar: AppBar(title: const Text('تمرین پس از درس')),
506 body: loading
507 ? const Center(child: CircularProgressIndicator())
508 : ListView(padding: const EdgeInsets.all(20), children: [
509 const Text(
510 'این تمرین بر اساس پاسخ‌های شماست؛ نتیجه، نشانهٔ قطعی تسلط یا مطالعهٔ واقعی نیست و وضعیت درس را خودکار تغییر نمی‌دهد.'),
511 if (message != null)
512 Padding(
513 padding: const EdgeInsets.symmetric(vertical: 12),
514 child: Text(message!)),
515 if (attempt != null) ...[
516 Text(
517 '${attempt!['correctCount']} از ${attempt!['total']} پاسخ درست',
518 style: Theme.of(context).textTheme.titleLarge),
519 for (final feedback in attempt!['feedback'] as List)
520 Card(
521 child: Padding(
522 padding: const EdgeInsets.all(16),
523 child: Column(
524 crossAxisAlignment: CrossAxisAlignment.start,
525 children: [
526 Text(feedback['correct'] == true
527 ? 'پاسخ درست بود'
528 : 'این بخش به تمرین نیاز دارد'),
529 Text(feedback['explanationFa'] as String),
530 Text(feedback['remediationFa'] as String),
531 ]))),
532 Text(
533 'مرور بعدی: ${DateTime.parse(attempt!['nextReviewAt'] as String).toLocal().toString().split(" ").first}. این زمان‌بندی پیشنهاد آزمایشی ۱ یا ۳ روزه است، نه تضمین بهترین زمان یادگیری.'),
534 ] else ...[
535 if (assessment == null && message == null)
536 const Padding(
537 padding: EdgeInsets.symmetric(vertical: 24),
538 child: Text(
539 'آزمون این درس در انتظار بازبینی است. تا تأیید محتوای آن، پرسشی نمایش داده نمی‌شود.')),
540 if (assessment != null && matchesPending) ...[
541 for (final question in assessment!['questions'] as List)
542 Card(
543 child: Padding(
544 padding: const EdgeInsets.all(16),
545 child: Column(
546 crossAxisAlignment:
547 CrossAxisAlignment.stretch,
548 children: [
549 Text(question['promptFa'] as String,
550 style: Theme.of(context)
551 .textTheme
552 .titleMedium),
553 const SizedBox(height: 8),
554 for (final choice
555 in question['choices'] as List)
556 Align(
557 alignment: AlignmentDirectional
558 .centerStart,
559 child: ChoiceChip(
560 key: Key(
561 'quiz-choice-${question['id']}-${choice['id']}'),
562 label: Text(
563 choice['textFa'] as String),
564 selected:
565 answers[question['id']] ==
566 choice['id'],
567 onSelected:
568 pending != null || busy
569 ? null
570 : (_) => setState(() =>
571 answers[question['id']
572 as String] =
573 choice['id']
574 as String),
575 )),
576 ]))),
577 const Text('چقدر به پاسخ‌هایتان مطمئن هستید؟'),
578 Wrap(spacing: 8, children: [
579 for (final entry in _confidences.entries)
580 ChoiceChip(
581 key: Key('quiz-confidence-${entry.key}'),
582 label: Text(entry.value),
583 selected: confidence == entry.key,
584 onSelected: pending != null || busy
585 ? null
586 : (_) =>
587 setState(() => confidence = entry.key)),
588 ]),
589 ],
590 if (pending != null) ...[
591 if (!matchesPending)
592 const Text(
593 'نسخهٔ پاسخ‌های ذخیره‌شده با آزمون فعلی متفاوت است. ارسال دوباره، همان پاسخ‌ها و نسخهٔ اصلی را می‌فرستد.'),
594 FilledButton(
595 key: const Key('quiz-retry'),
596 onPressed: busy ? null : send,
597 child: const Text('تلاش دوباره برای همان ارسال')),
598 TextButton(
599 key: const Key('quiz-cancel'),
600 onPressed: busy ? null : cancel,
601 child: const Text('لغو تلاش برای ارسال')),
602 ] else if (assessment != null)
603 FilledButton(
604 key: const Key('quiz-submit'),
605 onPressed: complete && !busy ? send : null,
606 child: const Text('ثبت پاسخ‌ها و دریافت بازخورد')),
607 ],
608 if (busy) const Center(child: CircularProgressIndicator()),
609 ]),
610 ),
611 );
612 }