LifeMate — Personal, Family & Learning Companion

phase-3/planner-school-family-core
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 776 lines 30.7 KB
Raw
1 // ignore_for_file: prefer_interpolation_to_compose_strings, curly_braces_in_flow_control_structures, use_build_context_synchronously
2
3 import 'dart:math';
4 import 'package:flutter/material.dart';
5 import 'api.dart';
6 import 'offline_store.dart';
7
8 String faKind(String kind) {
9 switch (kind) {
10 case 'assignment': return 'تکلیف';
11 case 'exam': return 'امتحان';
12 case 'study_session': return 'مطالعه';
13 case 'event': return 'رویداد';
14 case 'routine': return 'روتین';
15 case 'goal': return 'هدف';
16 default: return 'کار';
17 }
18 }
19
20 DateTime? parseDate(dynamic value) {
21 if (value == null) return null;
22 return DateTime.tryParse(value.toString())?.toLocal();
23 }
24
25 String shortDate(dynamic value) {
26 final d = parseDate(value);
27 if (d == null) return '';
28 final minute = d.minute.toString().padLeft(2, '0');
29 return d.month.toString() + '/' + d.day.toString() + ' · ' +
30 d.hour.toString() + ':' + minute;
31 }
32
33 class Phase3HomeContent extends StatelessWidget {
34 const Phase3HomeContent({
35 super.key,
36 required this.api,
37 required this.page,
38 required this.adultShell,
39 });
40 final IdentityApi api;
41 final String page;
42 final bool adultShell;
43
44 @override
45 Widget build(BuildContext context) {
46 if (page == 'امروز') return TodayPage(api: api);
47 if (page == 'برنامه‌ریز' || page == 'برنامه هفتگی' || page == 'تقویم' || page == 'تکالیف و کارها') {
48 return PlannerPage(api: api);
49 }
50 if (page == 'خانواده') return ParentFamilyDashboard(api: api);
51 if (page == 'امتحان‌ها و نمرات') return SchoolPage(api: api);
52 if (page == 'تمرکز') {
53 return const CoreNotice(
54 title: 'تمرکز',
55 subtitle: 'جلسه مطالعه در برنامه‌ریز فعال است؛ تایمر پیشرفته در فاز بعد اضافه می‌شود.',
56 );
57 }
58 if (page == 'همراه هوشمند' || page == 'راهنما') {
59 return const CoreNotice(
60 title: 'راهنمای هوشمند',
61 subtitle: 'هسته برنامه‌ریزی این فاز مستقل از AI است و راهنمای هوشمند در فاز ۴ فعال می‌شود.',
62 );
63 }
64 return SchoolPage(api: api);
65 }
66 }
67
68 class CoreNotice extends StatelessWidget {
69 const CoreNotice({super.key, required this.title, required this.subtitle});
70 final String title;
71 final String subtitle;
72 @override
73 Widget build(BuildContext context) => Center(
74 child: Card(
75 margin: const EdgeInsets.all(20),
76 child: Padding(
77 padding: const EdgeInsets.all(24),
78 child: Column(mainAxisSize: MainAxisSize.min, children: [
79 Text(title, style: Theme.of(context).textTheme.headlineSmall),
80 const SizedBox(height: 8),
81 Text(subtitle, textAlign: TextAlign.center),
82 ]),
83 ),
84 ),
85 );
86 }
87
88 class TodayPage extends StatefulWidget {
89 const TodayPage({super.key, required this.api});
90 final IdentityApi api;
91 @override
92 State<TodayPage> createState() => _TodayPageState();
93 }
94
95 class _TodayPageState extends State<TodayPage> {
96 late Future<LoadResult> future;
97 @override
98 void initState() {
99 super.initState();
100 future = load();
101 }
102
103 Future<LoadResult> load() async {
104 final now = DateTime.now();
105 final from = DateTime(now.year, now.month, now.day);
106 final to = from.add(const Duration(days: 1));
107 try {
108 final items = await widget.api.getToday(from: from, to: to);
109 final reminders = await widget.api.claimDueReminders();
110 await OfflineStore.instance.cacheToday(items);
111 return LoadResult(items, false, reminders: reminders);
112 } catch (_) {
113 return LoadResult(await OfflineStore.instance.readToday(), true);
114 }
115 }
116
117 Future<void> refresh() async {
118 setState(() => future = load());
119 await future;
120 }
121
122 Future<void> complete(Map<String, dynamic> item) async {
123 try {
124 await widget.api.updatePlanItem(item['id'].toString(), {'status': 'completed'});
125 await refresh();
126 } catch (_) {
127 await OfflineStore.instance.enqueue({
128 'id': DateTime.now().microsecondsSinceEpoch.toString() + '-' + Random().nextInt(99999).toString(),
129 'entityType': 'plan_item',
130 'entityId': item['id'],
131 'operation': 'complete',
132 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
133 'payload': {'status': 'completed'},
134 });
135 if (mounted) {
136 ScaffoldMessenger.of(context).showSnackBar(
137 const SnackBar(content: Text('آفلاین هستی؛ تغییر برای همگام‌سازی ذخیره شد.')),
138 );
139 }
140 }
141 }
142
143 @override
144 Widget build(BuildContext context) => FutureBuilder<LoadResult>(
145 future: future,
146 builder: (context, snapshot) {
147 if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
148 final result = snapshot.data!;
149 return RefreshIndicator(
150 onRefresh: refresh,
151 child: ListView(
152 padding: const EdgeInsets.all(16),
153 children: [
154 if (result.offline)
155 const Card(child: ListTile(
156 leading: Icon(Icons.cloud_off_outlined),
157 title: Text('نمایش نسخه آفلاین'),
158 )),
159 if (result.reminders.isNotEmpty)
160 ...result.reminders.map((reminder) => Card(
161 child: ListTile(
162 leading: const Icon(Icons.notifications_active_outlined),
163 title: Text('یادآوری · ' + (reminder['title']?.toString() ?? 'برنامه')),
164 subtitle: const Text('زمان این مورد رسیده یا نزدیک است.'),
165 ),
166 )),
167 Card(
168 child: Padding(
169 padding: const EdgeInsets.all(18),
170 child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
171 Text('امروز', style: Theme.of(context).textTheme.headlineSmall),
172 const SizedBox(height: 6),
173 Text(result.items.length.toString() + ' مورد در برنامه امروز'),
174 ]),
175 ),
176 ),
177 const SizedBox(height: 8),
178 if (result.items.isEmpty)
179 const EmptyCard(
180 icon: Icons.check_circle_outline,
181 title: 'امروز خلوت است',
182 subtitle: 'از برنامه‌ریز یک کار، رویداد یا جلسه مطالعه اضافه کن.',
183 )
184 else
185 ...result.items.map((item) => Card(
186 child: ListTile(
187 leading: const Icon(Icons.radio_button_unchecked),
188 title: Text(item['title']?.toString() ?? ''),
189 subtitle: Text(
190 faKind(item['kind']?.toString() ?? 'task') +
191 (shortDate(item['starts_at'] ?? item['due_at']).isEmpty ? '' : ' · ' + shortDate(item['starts_at'] ?? item['due_at'])),
192 ),
193 trailing: IconButton(
194 onPressed: () => complete(item),
195 icon: const Icon(Icons.check_circle_outline),
196 ),
197 ),
198 )),
199 ],
200 ),
201 );
202 },
203 );
204 }
205
206 class PlannerPage extends StatefulWidget {
207 const PlannerPage({super.key, required this.api});
208 final IdentityApi api;
209 @override
210 State<PlannerPage> createState() => _PlannerPageState();
211 }
212
213 class _PlannerPageState extends State<PlannerPage> {
214 late Future<LoadResult> future;
215 @override
216 void initState() {
217 super.initState();
218 future = load();
219 flushQueue();
220 }
221
222 Future<void> flushQueue() async {
223 final queue = await OfflineStore.instance.readQueue();
224 if (queue.isEmpty) return;
225 try {
226 final result = await widget.api.submitSyncMutations(queue);
227 final applied = <String>{};
228 for (final raw in (result['results'] as List<dynamic>? ?? const [])) {
229 final row = Map<String, dynamic>.from(raw as Map);
230 if (row['status'] == 'accepted' || row['status'] == 'already_applied') {
231 applied.add(row['id'].toString());
232 }
233 }
234 await OfflineStore.instance.removeQueued(applied);
235 } catch (_) {}
236 }
237
238 Future<LoadResult> load() async {
239 final now = DateTime.now();
240 final from = DateTime(now.year, now.month, now.day).subtract(const Duration(days: 1));
241 final to = from.add(const Duration(days: 15));
242 try {
243 final items = await widget.api.listPlanItems(from: from, to: to);
244 await OfflineStore.instance.cachePlanner(items);
245 return LoadResult(items, false);
246 } catch (_) {
247 return LoadResult(await OfflineStore.instance.readPlanner(), true);
248 }
249 }
250
251 Future<void> reload() async {
252 setState(() => future = load());
253 await future;
254 }
255
256 Future<void> createItem() async {
257 final title = TextEditingController();
258 final kind = ValueNotifier<String>('task');
259 final visibility = ValueNotifier<String>('private');
260 final families = await widget.api.listFamilies();
261 final familyId = families.isEmpty ? null : families.first['id']?.toString();
262 final when = DateTime.now().add(const Duration(hours: 1));
263
264 final saved = await showDialog<bool>(
265 context: context,
266 builder: (dialogContext) => AlertDialog(
267 title: const Text('مورد جدید'),
268 content: Column(mainAxisSize: MainAxisSize.min, children: [
269 TextField(controller: title, decoration: const InputDecoration(labelText: 'عنوان')),
270 const SizedBox(height: 12),
271 ValueListenableBuilder<String>(
272 valueListenable: kind,
273 builder: (_, value, __) => DropdownButtonFormField<String>(
274 initialValue: value,
275 decoration: const InputDecoration(labelText: 'نوع'),
276 items: const [
277 DropdownMenuItem(value: 'task', child: Text('کار')),
278 DropdownMenuItem(value: 'event', child: Text('رویداد')),
279 DropdownMenuItem(value: 'routine', child: Text('روتین')),
280 DropdownMenuItem(value: 'goal', child: Text('هدف')),
281 DropdownMenuItem(value: 'study_session', child: Text('جلسه مطالعه')),
282 ],
283 onChanged: (v) { if (v != null) kind.value = v; },
284 ),
285 ),
286 const SizedBox(height: 12),
287 ValueListenableBuilder<String>(
288 valueListenable: visibility,
289 builder: (_, value, __) => DropdownButtonFormField<String>(
290 initialValue: value,
291 decoration: const InputDecoration(labelText: 'اشتراک'),
292 items: const [
293 DropdownMenuItem(value: 'private', child: Text('خصوصی')),
294 DropdownMenuItem(value: 'family', child: Text('خانواده')),
295 DropdownMenuItem(value: 'parent_guardian', child: Text('والد / سرپرست')),
296 ],
297 onChanged: (v) { if (v != null) visibility.value = v; },
298 ),
299 ),
300 ]),
301 actions: [
302 TextButton(onPressed: () => Navigator.pop(dialogContext, false), child: const Text('انصراف')),
303 FilledButton(
304 onPressed: () async {
305 if (title.text.trim().isEmpty) return;
306 final shared = visibility.value != 'private';
307 await widget.api.createPlanItem({
308 'kind': kind.value,
309 'title': title.text.trim(),
310 'startsAt': when.toUtc().toIso8601String(),
311 'dueAt': when.add(const Duration(hours: 1)).toUtc().toIso8601String(),
312 'visibility': visibility.value,
313 if (shared && familyId != null) 'familyId': familyId,
314 'reminderMinutesBefore': [15],
315 });
316 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
317 },
318 child: const Text('ذخیره'),
319 ),
320 ],
321 ),
322 );
323 title.dispose();
324 kind.dispose();
325 visibility.dispose();
326 if (saved == true && mounted) await reload();
327 }
328
329 Future<void> reschedule(Map<String, dynamic> item) async {
330 final base = parseDate(item['due_at'] ?? item['starts_at']) ?? DateTime.now();
331 final next = base.add(const Duration(days: 1));
332 try {
333 await widget.api.updatePlanItem(item['id'].toString(), {
334 if (item['starts_at'] != null) 'startsAt': next.toUtc().toIso8601String(),
335 if (item['due_at'] != null) 'dueAt': next.toUtc().toIso8601String(),
336 });
337 await reload();
338 } catch (_) {
339 await OfflineStore.instance.enqueue({
340 'id': DateTime.now().microsecondsSinceEpoch.toString() + '-' + Random().nextInt(99999).toString(),
341 'entityType': 'plan_item',
342 'entityId': item['id'],
343 'operation': 'reschedule',
344 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
345 'payload': {'dueAt': next.toUtc().toIso8601String()},
346 });
347 }
348 }
349
350 @override
351 Widget build(BuildContext context) => FutureBuilder<LoadResult>(
352 future: future,
353 builder: (context, snapshot) {
354 if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
355 final result = snapshot.data!;
356 return Scaffold(
357 backgroundColor: Colors.transparent,
358 floatingActionButton: FloatingActionButton.extended(
359 onPressed: createItem,
360 icon: const Icon(Icons.add),
361 label: const Text('جدید'),
362 ),
363 body: RefreshIndicator(
364 onRefresh: reload,
365 child: ListView(
366 padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
367 children: [
368 if (result.offline)
369 const Card(child: ListTile(
370 leading: Icon(Icons.cloud_off_outlined),
371 title: Text('حالت آفلاین'),
372 subtitle: Text('آخرین برنامه ذخیره‌شده نمایش داده می‌شود.'),
373 )),
374 if (result.items.isEmpty)
375 const EmptyCard(
376 icon: Icons.event_note_outlined,
377 title: 'هنوز برنامه‌ای نداری',
378 subtitle: 'کار، رویداد، روتین، هدف یا جلسه مطالعه اضافه کن.',
379 )
380 else
381 ...result.items.map((item) => Card(
382 child: ListTile(
383 title: Text(item['title']?.toString() ?? ''),
384 subtitle: Text(
385 faKind(item['kind']?.toString() ?? 'task') +
386 (shortDate(item['starts_at'] ?? item['due_at']).isEmpty ? '' : ' · ' + shortDate(item['starts_at'] ?? item['due_at'])),
387 ),
388 trailing: PopupMenuButton<String>(
389 onSelected: (value) async {
390 if (value == 'complete') {
391 await widget.api.updatePlanItem(item['id'].toString(), {'status': 'completed'});
392 await reload();
393 } else if (value == 'tomorrow') {
394 await reschedule(item);
395 }
396 },
397 itemBuilder: (_) => const [
398 PopupMenuItem(value: 'complete', child: Text('انجام شد')),
399 PopupMenuItem(value: 'tomorrow', child: Text('انتقال به فردا')),
400 ],
401 ),
402 ),
403 )),
404 ],
405 ),
406 ),
407 );
408 },
409 );
410 }
411
412 class SchoolPage extends StatefulWidget {
413 const SchoolPage({super.key, required this.api});
414 final IdentityApi api;
415 @override
416 State<SchoolPage> createState() => _SchoolPageState();
417 }
418
419 class _SchoolPageState extends State<SchoolPage> {
420 late Future<SchoolLoad> future;
421 @override
422 void initState() {
423 super.initState();
424 future = load();
425 }
426
427 Future<SchoolLoad> load() async {
428 final profile = await widget.api.getProfile();
429 final userId = profile['user_id']?.toString() ?? '';
430 if (userId.isEmpty) return SchoolLoad(userId, const {}, false);
431 try {
432 final overview = await widget.api.getSchoolOverview(userId);
433 await OfflineStore.instance.cacheSchool([{'userId': userId, 'overview': overview}]);
434 return SchoolLoad(userId, overview, false);
435 } catch (_) {
436 final cached = await OfflineStore.instance.readSchool();
437 if (cached.isNotEmpty) {
438 return SchoolLoad(
439 cached.first['userId']?.toString() ?? userId,
440 Map<String, dynamic>.from(cached.first['overview'] as Map? ?? const {}),
441 true,
442 );
443 }
444 return SchoolLoad(userId, const {}, true);
445 }
446 }
447
448 Future<void> reload() async {
449 setState(() => future = load());
450 await future;
451 }
452
453 Future<void> quickSetup() async {
454 var contexts = await widget.api.listLifeContexts();
455 Map<String, dynamic>? student;
456 for (final row in contexts) {
457 if (row['kind'] == 'student') { student = row; break; }
458 }
459 student ??= await widget.api.createLifeContext(kind: 'student', title: 'مدرسه');
460 final now = DateTime.now();
461 final year = await widget.api.createAcademicYear({
462 'lifeContextId': student['id'],
463 'title': 'سال تحصیلی ' + now.year.toString() + '-' + (now.year + 1).toString(),
464 'startsOn': now.year.toString() + '-09-01',
465 'endsOn': (now.year + 1).toString() + '-06-30',
466 });
467 final term = await widget.api.createAcademicTerm(year['id'].toString(), {
468 'title': 'نیمسال اول',
469 'startsOn': now.year.toString() + '-09-01',
470 'endsOn': (now.year + 1).toString() + '-01-31',
471 });
472 await widget.api.createSubject(term['id'].toString(), {'name': 'ریاضی'});
473 await reload();
474 }
475
476 Future<void> addSchoolItem(String kind) async {
477 final data = await future;
478 final subjects = data.overview['subjects'] as List<dynamic>? ?? const [];
479 if (subjects.isEmpty) return;
480 final title = TextEditingController();
481 final first = Map<String, dynamic>.from(subjects.first as Map);
482 final selected = ValueNotifier<String>(first['id'].toString());
483 final saved = await showDialog<bool>(
484 context: context,
485 builder: (dialogContext) => AlertDialog(
486 title: Text(kind == 'exam' ? 'امتحان جدید' : 'تکلیف جدید'),
487 content: Column(mainAxisSize: MainAxisSize.min, children: [
488 TextField(controller: title, decoration: const InputDecoration(labelText: 'عنوان')),
489 const SizedBox(height: 12),
490 ValueListenableBuilder<String>(
491 valueListenable: selected,
492 builder: (_, value, __) => DropdownButtonFormField<String>(
493 initialValue: value,
494 decoration: const InputDecoration(labelText: 'درس'),
495 items: subjects.map((raw) {
496 final row = Map<String, dynamic>.from(raw as Map);
497 return DropdownMenuItem<String>(
498 value: row['id'].toString(),
499 child: Text(row['name']?.toString() ?? ''),
500 );
501 }).toList(),
502 onChanged: (v) { if (v != null) selected.value = v; },
503 ),
504 ),
505 ]),
506 actions: [
507 TextButton(onPressed: () => Navigator.pop(dialogContext, false), child: const Text('انصراف')),
508 FilledButton(
509 onPressed: () async {
510 if (title.text.trim().isEmpty) return;
511 final due = DateTime.now().add(const Duration(days: 2));
512 await widget.api.createPlanItem({
513 'kind': kind,
514 'title': title.text.trim(),
515 'subjectId': selected.value,
516 'dueAt': due.toUtc().toIso8601String(),
517 'visibility': 'private',
518 'reminderMinutesBefore': [60, 1440],
519 });
520 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
521 },
522 child: const Text('ذخیره'),
523 ),
524 ],
525 ),
526 );
527 title.dispose();
528 selected.dispose();
529 if (saved == true && mounted) await reload();
530 }
531
532 @override
533 Widget build(BuildContext context) => FutureBuilder<SchoolLoad>(
534 future: future,
535 builder: (context, snapshot) {
536 if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
537 final data = snapshot.data!;
538 final years = data.overview['years'] as List<dynamic>? ?? const [];
539 final subjects = data.overview['subjects'] as List<dynamic>? ?? const [];
540 final workload = data.overview['workload'] as List<dynamic>? ?? const [];
541 final grades = data.overview['grades'] as List<dynamic>? ?? const [];
542 return ListView(
543 padding: const EdgeInsets.all(16),
544 children: [
545 if (data.offline)
546 const Card(child: ListTile(leading: Icon(Icons.cloud_off_outlined), title: Text('اطلاعات مدرسه از کش نمایش داده می‌شود'))),
547 if (years.isEmpty)
548 EmptyCard(
549 icon: Icons.school_outlined,
550 title: 'مدرسه را آماده کن',
551 subtitle: 'سال تحصیلی، نیمسال و اولین درس را با شروع سریع بساز.',
552 action: FilledButton.icon(
553 onPressed: quickSetup,
554 icon: const Icon(Icons.auto_fix_high),
555 label: const Text('شروع سریع'),
556 ),
557 )
558 else ...[
559 Card(
560 child: Padding(
561 padding: const EdgeInsets.all(16),
562 child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
563 Text('مدرسه', style: Theme.of(context).textTheme.headlineSmall),
564 const SizedBox(height: 10),
565 Wrap(spacing: 8, runSpacing: 8, children: [
566 Chip(label: Text(subjects.length.toString() + ' درس')),
567 Chip(label: Text(workload.length.toString() + ' کار درسی پیش‌رو')),
568 Chip(label: Text(grades.length.toString() + ' نمره')),
569 ]),
570 const SizedBox(height: 12),
571 Row(children: [
572 Expanded(child: FilledButton.icon(
573 onPressed: () => addSchoolItem('assignment'),
574 icon: const Icon(Icons.assignment_add),
575 label: const Text('تکلیف'),
576 )),
577 const SizedBox(width: 8),
578 Expanded(child: OutlinedButton.icon(
579 onPressed: () => addSchoolItem('exam'),
580 icon: const Icon(Icons.quiz_outlined),
581 label: const Text('امتحان'),
582 )),
583 ]),
584 ]),
585 ),
586 ),
587 const SizedBox(height: 12),
588 Text('درس‌ها', style: Theme.of(context).textTheme.titleMedium),
589 ...subjects.map((raw) {
590 final row = Map<String, dynamic>.from(raw as Map);
591 return Card(child: ListTile(
592 leading: const Icon(Icons.menu_book_outlined),
593 title: Text(row['name']?.toString() ?? ''),
594 subtitle: Text(row['teacher_name']?.toString() ?? row['term_title']?.toString() ?? ''),
595 ));
596 }),
597 const SizedBox(height: 12),
598 Text('کارهای درسی پیش‌رو', style: Theme.of(context).textTheme.titleMedium),
599 ...workload.map((raw) {
600 final row = Map<String, dynamic>.from(raw as Map);
601 return Card(child: ListTile(
602 title: Text(row['title']?.toString() ?? ''),
603 subtitle: Text(faKind(row['kind']?.toString() ?? '') + ' · ' + shortDate(row['due_at'] ?? row['starts_at'])),
604 ));
605 }),
606 ],
607 ],
608 );
609 },
610 );
611 }
612
613 class ParentFamilyDashboard extends StatefulWidget {
614 const ParentFamilyDashboard({super.key, required this.api});
615 final IdentityApi api;
616 @override
617 State<ParentFamilyDashboard> createState() => _ParentFamilyDashboardState();
618 }
619
620 class _ParentFamilyDashboardState extends State<ParentFamilyDashboard> {
621 late Future<List<Map<String, dynamic>>> families;
622 @override
623 void initState() {
624 super.initState();
625 families = widget.api.listFamilies();
626 }
627
628 @override
629 Widget build(BuildContext context) => FutureBuilder<List<Map<String, dynamic>>>(
630 future: families,
631 builder: (context, snapshot) {
632 if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
633 if (snapshot.data!.isEmpty) {
634 return const EmptyCard(
635 icon: Icons.family_restroom,
636 title: 'خانواده‌ای متصل نیست',
637 subtitle: 'از بخش پروفایل فضای خانواده بساز یا به آن بپیوند.',
638 );
639 }
640 return ListView(
641 padding: const EdgeInsets.all(16),
642 children: snapshot.data!.map((family) => FamilyDashboardCard(api: widget.api, family: family)).toList(),
643 );
644 },
645 );
646 }
647
648 class FamilyDashboardCard extends StatefulWidget {
649 const FamilyDashboardCard({super.key, required this.api, required this.family});
650 final IdentityApi api;
651 final Map<String, dynamic> family;
652 @override
653 State<FamilyDashboardCard> createState() => _FamilyDashboardCardState();
654 }
655
656 class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
657 late Future<List<Map<String, dynamic>>> members;
658 @override
659 void initState() {
660 super.initState();
661 members = widget.api.listFamilyMembers(widget.family['id'].toString());
662 }
663
664 Future<void> openChild(Map<String, dynamic> child) async {
665 final summary = await widget.api.getChildSupportSummary(
666 widget.family['id'].toString(),
667 child['user_id'].toString(),
668 );
669 if (!mounted) return;
670 final metrics = Map<String, dynamic>.from(summary['metrics'] as Map? ?? const {});
671 final upcoming = summary['upcoming'] as List<dynamic>? ?? const [];
672 await showDialog<void>(
673 context: context,
674 builder: (dialogContext) => AlertDialog(
675 title: Text('خلاصه حمایت · ' + (child['display_name']?.toString() ?? 'فرزند')),
676 content: SizedBox(
677 width: 520,
678 child: SingleChildScrollView(
679 child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
680 Wrap(spacing: 8, runSpacing: 8, children: [
681 Chip(label: Text((metrics['overdue'] ?? 0).toString() + ' عقب‌افتاده')),
682 Chip(label: Text((metrics['completedLast7Days'] ?? 0).toString() + ' انجام‌شده')),
683 Chip(label: Text((metrics['studyMinutesLast7Days'] ?? 0).toString() + ' دقیقه مطالعه')),
684 if (metrics['gradePercent'] != null) Chip(label: Text('میانگین ' + metrics['gradePercent'].toString() + '٪')),
685 ]),
686 const SizedBox(height: 10),
687 const Text('موارد پیش‌رو'),
688 ...upcoming.take(8).map((raw) {
689 final row = Map<String, dynamic>.from(raw as Map);
690 return ListTile(
691 dense: true,
692 title: Text(row['title']?.toString() ?? ''),
693 subtitle: Text(faKind(row['kind']?.toString() ?? '') + ' · ' + shortDate(row['due_at'] ?? row['starts_at'])),
694 );
695 }),
696 ]),
697 ),
698 ),
699 actions: [
700 TextButton(onPressed: () => Navigator.pop(dialogContext), child: const Text('بستن')),
701 ],
702 ),
703 );
704 }
705
706 @override
707 Widget build(BuildContext context) => Card(
708 child: Padding(
709 padding: const EdgeInsets.all(14),
710 child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
711 Text(widget.family['name']?.toString() ?? 'خانواده', style: Theme.of(context).textTheme.titleLarge),
712 const SizedBox(height: 8),
713 FutureBuilder<List<Map<String, dynamic>>>(
714 future: members,
715 builder: (context, snapshot) {
716 if (!snapshot.hasData) return const LinearProgressIndicator();
717 final children = snapshot.data!.where((row) => row['role'] == 'teen_minor').toList();
718 if (children.isEmpty) return const Text('هنوز فرزند/نوجوانی به این خانواده متصل نیست.');
719 return Column(
720 children: children.map((child) => ListTile(
721 leading: const CircleAvatar(child: Icon(Icons.school_outlined)),
722 title: Text(child['display_name']?.toString() ?? 'فرزند'),
723 subtitle: const Text('برنامه، تکالیف، امتحان‌ها و پیشرفت مجاز'),
724 trailing: const Icon(Icons.chevron_left),
725 onTap: () => openChild(child),
726 )).toList(),
727 );
728 },
729 ),
730 ]),
731 ),
732 );
733 }
734
735 class EmptyCard extends StatelessWidget {
736 const EmptyCard({
737 super.key,
738 required this.icon,
739 required this.title,
740 required this.subtitle,
741 this.action,
742 });
743 final IconData icon;
744 final String title;
745 final String subtitle;
746 final Widget? action;
747
748 @override
749 Widget build(BuildContext context) => Card(
750 child: Padding(
751 padding: const EdgeInsets.all(22),
752 child: Column(children: [
753 Icon(icon, size: 42),
754 const SizedBox(height: 10),
755 Text(title, style: Theme.of(context).textTheme.titleMedium),
756 const SizedBox(height: 6),
757 Text(subtitle, textAlign: TextAlign.center),
758 if (action != null) ...[const SizedBox(height: 14), action!],
759 ]),
760 ),
761 );
762 }
763
764 class LoadResult {
765 const LoadResult(this.items, this.offline, {this.reminders = const []});
766 final List<Map<String, dynamic>> items;
767 final bool offline;
768 final List<Map<String, dynamic>> reminders;
769 }
770
771 class SchoolLoad {
772 const SchoolLoad(this.userId, this.overview, this.offline);
773 final String userId;
774 final Map<String, dynamic> overview;
775 final bool offline;
776 }