LifeMate — Personal, Family & Learning Companion

feat/learning-content-operations
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 533 lines 21.9 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 minutes(dynamic seconds) =>
352 '${((seconds as num? ?? 0) / 60).round()} دقیقه';
353 @override
354 Widget build(BuildContext context) {
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,
372 (v, row) => (row['recordedDurationSeconds'] as num? ?? 0) > v
373 ? row['recordedDurationSeconds'] as num
374 : v);
375 final tehranNow =
376 DateTime.now().toUtc().add(const Duration(hours: 3, minutes: 30));
377 final todayCount = items.where((raw) {
378 final i = raw as Map;
379 final at =
380 DateTime.tryParse((i['dueAt'] ?? i['startsAt'] ?? '').toString())
381 ?.toUtc()
382 .add(const Duration(hours: 3, minutes: 30));
383 return at != null &&
384 at.year == tehranNow.year &&
385 at.month == tehranNow.month &&
386 at.day == tehranNow.day;
387 }).length;
388 return Scaffold(
389 appBar: AppBar(title: Text('گزارش یادگیری · ${widget.childName}')),
390 body: ListView(padding: const EdgeInsets.all(16), children: [
391 const Text(
392 'زمان ثبت‌شده، گزارش شخصی است و اثبات مطالعه نیست. تأیید سرپرست فقط در صورت ثبت صریح سرور نمایش داده می‌شود.'),
393 SegmentedButton<int>(
394 segments: const [
395 ButtonSegment(value: 7, label: Text('هفتگی')),
396 ButtonSegment(value: 30, label: Text('ماهانه'))
397 ],
398 selected: {
399 days
400 },
401 onSelectionChanged: busy
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(),
411 if (error != null)
412 Card(
413 child: ListTile(
414 leading: const Icon(Icons.warning_amber),
415 title: Text(error!),
416 subtitle: Text(report == null
417 ? 'اطلاعات فرزند بدون تأیید مجوز فعلی نمایش داده نمی‌شود.'
418 : 'داده قبلی به‌روز نیست؛ وضعیت زنده تأیید نشده است.'))),
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 مورد امروز (تهران)')),
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) {
459 final row = raw as Map;
460 return Padding(
461 padding: const EdgeInsets.symmetric(vertical: 4),
462 child: Row(children: [
463 SizedBox(width: 100, child: Text(row['date'].toString())),
464 Expanded(
465 child: LinearProgressIndicator(
466 value:
467 (row['recordedDurationSeconds'] as num? ?? 0) /
468 max)),
469 const SizedBox(width: 8),
470 Text(minutes(row['recordedDurationSeconds']))
471 ]));
472 }),
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(
480 '${row['completedTasks']}/${row['totalTasks']} تکمیل ${hasPeriod ? 'تکلیف‌های بازه' : 'کل سابقه'} · ${minutes(row['recordedDurationSeconds'])}${hasPeriod && row['gradePercent'] != null ? '\nنمره وزنی امتحان‌های مجاز: ${row['gradePercent']}٪ (${row['gradedExamCount']} امتحان)' : ''}'));
481 }),
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),
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';
513 final state = verified
514 ? 'تأیید صریح سرپرست'
515 : switch (i['activityState']) {
516 'started' => 'شروع ثبت‌شده',
517 'paused' => 'مکث ثبت‌شده',
518 'completed' => 'انجام‌شده به گزارش فرزند',
519 _ => 'برنامه‌ریزی‌شده'
520 };
521 return Card(
522 child: ListTile(
523 title: Text(i['title']?.toString() ?? ''),
524 subtitle: Text(
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(
529 onPressed: busy ? null : load,
530 child: const Text('تازه‌سازی گزارش')),
531 ]));
532 }
533 }