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