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 543 lines 22.3 KB
Raw
1 import 'dart:async';
2 import 'package:flutter/material.dart';
3 import 'api.dart';
4 import 'phase3_ui.dart';
5
6 class ParentFamilyDashboard extends StatefulWidget {
7 const ParentFamilyDashboard({super.key, required this.api});
8 final IdentityApi api;
9 @override
10 State<ParentFamilyDashboard> createState() => _ParentFamilyDashboardState();
11 }
12
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>>[];
75 final families = await api.listFamilies();
76 current();
77 for (final f in families) {
78 if (f['role'] != 'parent_guardian') continue;
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 }
85 }
86 }
87 return rows;
88 }
89
90 void reload() {
91 setState(() {
92 loadEpoch++;
93 accountScope = scopeFor(widget.api);
94 data = load();
95 });
96 }
97
98 @override
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);
107 if (!s.hasData) {
108 return const Center(child: CircularProgressIndicator());
109 }
110 return ListView(padding: const EdgeInsets.all(16), children: [
111 const Text(
112 'فقط اطلاعاتی که سرور طبق رابطه سرپرستی و اشتراک هر تکلیف مجاز بداند نمایش داده می‌شود.'),
113 if (s.data!.isEmpty)
114 const EmptyCard(
115 icon: Icons.family_restroom,
116 title: 'فرزند متصل نمایش داده نشد',
117 subtitle:
118 'عضویت خانواده و رابطه سرپرستی را در پروفایل بررسی کن.'),
119 ...s.data!.map((child) => Card(
120 child: ListTile(
121 title: Text(child['display_name']?.toString() ?? 'فرزند'),
122 subtitle: Text(child['familyName']?.toString() ?? ''),
123 trailing: const Icon(Icons.chevron_left),
124 onTap: () {
125 if (widget.api is HttpIdentityApi) {
126 Navigator.push(
127 context,
128 MaterialPageRoute(
129 builder: (_) => LearningReportPage(
130 api: widget.api as HttpIdentityApi,
131 familyId: child['familyId'].toString(),
132 childId: child['user_id'].toString(),
133 childName:
134 child['display_name']?.toString() ??
135 'فرزند')));
136 }
137 }))),
138 TextButton(onPressed: reload, child: const Text('تازه‌سازی اعضا'))
139 ]);
140 });
141 }
142
143 class LearningReportPage extends StatefulWidget {
144 const LearningReportPage(
145 {super.key,
146 required this.api,
147 required this.familyId,
148 required this.childId,
149 required this.childName});
150 final HttpIdentityApi api;
151 final String familyId, childId, childName;
152 @override
153 State<LearningReportPage> createState() => _LearningReportPageState();
154 }
155
156 class _LearningReportPageState extends State<LearningReportPage>
157 with WidgetsBindingObserver {
158 Map<String, dynamic>? report;
159 bool busy = false;
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 }
174
175 void startPoll() {
176 poll?.cancel();
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) {
200 startPoll();
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;
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,
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) {
251 if (mounted && epoch == loadEpoch) {
252 setState(() {
253 error = uiErrorText(e);
254 report = null;
255 reportNamespace = null;
256 });
257 }
258 } finally {
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
351 String formatDurationSeconds(dynamic seconds) {
352 final total = (seconds as num? ?? 0).toInt();
353 final minutes = total ~/ 60;
354 final remainder = total % 60;
355 if (remainder == 0) return '$minutes دقیقه';
356 if (minutes == 0) return '$remainder ثانیه';
357 return '$minutes دقیقه و $remainder ثانیه';
358 }
359
360 @override
361 Widget build(BuildContext context) {
362 final r = reportNamespace == widget.api.cacheNamespace ? report : null;
363 final hasPeriod = r?['periodMetrics'] is Map;
364 final m =
365 (hasPeriod ? (r?['periodMetrics']) : (r?['metrics'])) as Map? ?? {};
366 final allTime = r?['allTimeTaskMetrics'] as Map?;
367 final items = (r?['items'] as List? ?? []).where((raw) {
368 final item = raw as Map;
369 return !hasPeriod ||
370 item['taskInRange'] == true ||
371 (item['recordedDurationSeconds'] as num? ?? 0) > 0;
372 }).toList();
373 final subjects =
374 (hasPeriod ? (r?['periodSubjects']) : (r?['subjects'])) as List? ?? [];
375 final exams = r?['periodExams'] as List? ?? [];
376 final daily = r?['daily'] as List? ?? [];
377 final max = daily.fold<num>(
378 1,
379 (v, row) => (row['recordedDurationSeconds'] as num? ?? 0) > v
380 ? row['recordedDurationSeconds'] as num
381 : v);
382 final tehranNow =
383 DateTime.now().toUtc().add(const Duration(hours: 3, minutes: 30));
384 final todayCount = items.where((raw) {
385 final i = raw as Map;
386 final at =
387 DateTime.tryParse((i['dueAt'] ?? i['startsAt'] ?? '').toString())
388 ?.toUtc()
389 .add(const Duration(hours: 3, minutes: 30));
390 return at != null &&
391 at.year == tehranNow.year &&
392 at.month == tehranNow.month &&
393 at.day == tehranNow.day;
394 }).length;
395 return Scaffold(
396 appBar: AppBar(title: Text('گزارش یادگیری · ${widget.childName}')),
397 body: ListView(padding: const EdgeInsets.all(16), children: [
398 const Text(
399 'زمان ثبت‌شده، گزارش شخصی است و اثبات مطالعه نیست. تأیید سرپرست فقط در صورت ثبت صریح سرور نمایش داده می‌شود.'),
400 SegmentedButton<int>(
401 segments: const [
402 ButtonSegment(value: 7, label: Text('هفتگی')),
403 ButtonSegment(value: 30, label: Text('ماهانه'))
404 ],
405 selected: {
406 days
407 },
408 onSelectionChanged: busy
409 ? null
410 : (v) {
411 setState(() => days = v.first);
412 report = null;
413 reportNamespace = null;
414 error = null;
415 load();
416 }),
417 if (busy) const LinearProgressIndicator(),
418 if (error != null)
419 Card(
420 child: ListTile(
421 leading: const Icon(Icons.warning_amber),
422 title: Text(error!),
423 subtitle: Text(report == null
424 ? 'اطلاعات فرزند بدون تأیید مجوز فعلی نمایش داده نمی‌شود.'
425 : 'داده قبلی به‌روز نیست؛ وضعیت زنده تأیید نشده است.'))),
426 if (r != null) ...[
427 Text(
428 'دریافت سرور: ${shortDate(r['asOf'])} · آخرین ثبت: ${shortDate(r['lastSyncAt'])}'),
429 if (hasPeriod) ...[
430 Text('بازه $days روز اخیر تا پایان امروز (تهران)',
431 style: Theme.of(context).textTheme.titleMedium),
432 const Text(
433 'شمارش تکلیف‌ها بر اساس موعد و سپس زمان شروع است؛ تکلیف بی‌تاریخ در شمارش بازه نیست. تکمیل، وضعیت فعلی همین تکلیف‌هاست و به معنی یادگیری تأییدشده نیست.'),
434 ] else
435 const Text(
436 'سرور آمار تکلیف‌های بازه را ارائه نکرده؛ شمارش تکلیف‌ها مربوط به کل سابقه مجاز است.'),
437 Wrap(spacing: 8, children: [
438 Chip(label: Text('$todayCount مورد امروز (تهران)')),
439 Chip(
440 label: Text(
441 '${m['totalTasks'] ?? 0} تکلیف ${hasPeriod ? 'در بازه' : 'در کل سابقه مجاز'}')),
442 Chip(
443 label: Text(
444 '${m['completedTasks'] ?? 0} انجام‌شده ${hasPeriod ? 'در بازه' : 'در کل سابقه مجاز'}')),
445 Chip(
446 label: Text(
447 '${m['overdueTasks'] ?? 0} عقب‌افتاده ${hasPeriod ? 'در بازه' : 'در کل سابقه مجاز'}')),
448 Chip(
449 label: Text(
450 '${m['completionPercent'] ?? 0}٪ تکمیل ${hasPeriod ? 'تکلیف‌های بازه' : 'کل سابقه مجاز'}'))
451 ]),
452 if (hasPeriod && allTime != null)
453 Text(
454 'کل سابقه مجاز: ${allTime['totalTasks'] ?? 0} تکلیف · ${allTime['completedTasks'] ?? 0} انجام‌شده'),
455 Text(
456 'زمان برنامه‌ریزی‌شده: ${formatDurationSeconds(m['plannedInRangeDurationSeconds'] ?? m['plannedDurationSeconds'])}'),
457 if (!hasPeriod && m['plannedInRangeDurationSeconds'] == null)
458 const Text(
459 'زمان برنامه‌ریزی‌شده مربوط به کل سابقه مجاز است؛ زمان بازه جداگانه از سرور دریافت نشده است.'),
460 Text(
461 'زمان ثبت‌شده: ${formatDurationSeconds(m['recordedDurationSeconds'])}'),
462 const Text(
463 'زمان ثبت‌شده فقط بخش جلسه‌های مجاز داخل بازه است؛ ممکن است به تکلیفی با موعد خارج از بازه مربوط باشد.'),
464 Text('روند زمان ثبت‌شده',
465 style: Theme.of(context).textTheme.titleLarge),
466 ...daily.map((raw) {
467 final row = raw as Map;
468 return Padding(
469 padding: const EdgeInsets.symmetric(vertical: 4),
470 child: Row(children: [
471 SizedBox(width: 100, child: Text(row['date'].toString())),
472 Expanded(
473 child: LinearProgressIndicator(
474 value:
475 (row['recordedDurationSeconds'] as num? ?? 0) /
476 max)),
477 const SizedBox(width: 8),
478 Flexible(
479 child: Text(formatDurationSeconds(
480 row['recordedDurationSeconds'])))
481 ]));
482 }),
483 Text(hasPeriod ? 'درس‌ها در بازه' : 'درس‌ها در کل سابقه مجاز',
484 style: Theme.of(context).textTheme.titleLarge),
485 ...subjects.map((raw) {
486 final row = raw as Map;
487 return ListTile(
488 title: Text(row['subjectName']?.toString() ?? 'بدون درس'),
489 subtitle: Text(
490 '${row['completedTasks']}/${row['totalTasks']} تکمیل ${hasPeriod ? 'تکلیف‌های بازه' : 'کل سابقه'} · ${formatDurationSeconds(row['recordedDurationSeconds'])}${hasPeriod && row['gradePercent'] != null ? '\nنمره وزنی امتحان‌های مجاز: ${row['gradePercent']}٪ (${row['gradedExamCount']} امتحان)' : ''}'));
491 }),
492 if (hasPeriod) ...[
493 Text('امتحان‌های مجاز در بازه',
494 style: Theme.of(context).textTheme.titleLarge),
495 const Text(
496 'این نمره‌ها مربوط به امتحان‌های ثبت‌شده مدرسه‌اند. نتیجه کوییز درس در تاریخچه خصوصی یادگیری است و در این گزارش جمع نمی‌شود.'),
497 Text(
498 '${m['examCount'] ?? 0} امتحان · ${m['gradedExamCount'] ?? 0} نمره ثبت‌شده${m['gradePercent'] == null ? '' : ' · نمره وزنی ${m['gradePercent']}٪'}'),
499 if (exams.isEmpty)
500 const Text('امتحان مجازی برای این بازه ثبت نشده است.'),
501 ...exams.map((raw) {
502 final exam = raw as Map;
503 return ListTile(
504 title: Text(exam['title']?.toString() ?? ''),
505 subtitle: Text(
506 'موعد: ${shortDate(exam['scheduledAt'] ?? exam['dueAt'] ?? exam['startsAt'])}\n${exam['gradePoints'] == null ? 'نمره ثبت نشده' : 'نمره ثبت‌شده ${exam['gradePoints']}/${exam['gradeOutOf']}؛ گزارش ثبت‌شده، تأیید مستقل نیست.'}'));
507 }),
508 ],
509 Text(
510 hasPeriod
511 ? 'تکلیف‌ها و زمان‌های ثبت‌شده'
512 : 'تکلیف‌ها و امتحان‌ها',
513 style: Theme.of(context).textTheme.titleLarge),
514 ...items
515 .where((raw) =>
516 !hasPeriod ||
517 (raw as Map)['kind'] != 'exam' ||
518 raw['taskInRange'] != true)
519 .map((raw) {
520 final i = raw as Map;
521 final verified = i['activityState'] == 'verified' &&
522 i['activitySource'] == 'guardian_confirmation';
523 final state = verified
524 ? 'تأیید صریح سرپرست'
525 : switch (i['activityState']) {
526 'started' => 'شروع ثبت‌شده',
527 'paused' => 'مکث ثبت‌شده',
528 'completed' => 'انجام‌شده به گزارش فرزند',
529 _ => 'برنامه‌ریزی‌شده'
530 };
531 return Card(
532 child: ListTile(
533 title: Text(i['title']?.toString() ?? ''),
534 subtitle: Text(
535 '${faKind(i['kind']?.toString() ?? 'task')} · $state\nآخرین ثبت وضعیت: ${shortDate(i['activityAt'])}\nموعد: ${shortDate(i['dueAt'] ?? i['startsAt'])}\nبرنامه ${formatDurationSeconds(i['plannedDurationSeconds'])} · ثبت ${formatDurationSeconds(i['recordedDurationSeconds'])}${hasPeriod && i['taskInRange'] != true ? '\nموعد این تکلیف خارج از بازه است؛ فقط زمان ثبت‌شده در بازه نمایش داده می‌شود.' : ''}${i['gradePoints'] == null ? '' : '\nنمره ${i['gradePoints']}/${i['gradeOutOf']}'}')));
536 }),
537 ],
538 TextButton(
539 onPressed: busy ? null : load,
540 child: const Text('تازه‌سازی گزارش')),
541 ]));
542 }
543 }