LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 287 lines 11.3 KB
Raw
1 import 'dart:async';
2 import 'package:flutter/material.dart';
3 import 'api.dart';
4 import 'phase3_ui.dart';
5 import 'offline_store.dart';
6
7 class ParentFamilyDashboard extends StatefulWidget {
8 const ParentFamilyDashboard({super.key, required this.api});
9 final IdentityApi api;
10 @override
11 State<ParentFamilyDashboard> createState() => _ParentFamilyDashboardState();
12 }
13
14 class _ParentFamilyDashboardState extends State<ParentFamilyDashboard> {
15 late Future<List<Map<String, dynamic>>> data;
16 @override
17 void initState() {
18 super.initState();
19 data = load();
20 }
21
22 Future<List<Map<String, dynamic>>> load() async {
23 final rows = <Map<String, dynamic>>[];
24 for (final f in await widget.api.listFamilies()) {
25 if (f['role'] != 'parent_guardian') continue;
26 for (final child
27 in await widget.api.listFamilyMembers(f['id'].toString())) {
28 if (child['role'] == 'teen_minor') {
29 rows.add({...child, 'familyId': f['id'], 'familyName': f['name']});
30 }
31 }
32 }
33 return rows;
34 }
35
36 void reload() {
37 setState(() {
38 data = load();
39 });
40 }
41
42 @override
43 Widget build(BuildContext context) =>
44 FutureBuilder<List<Map<String, dynamic>>>(
45 future: data,
46 builder: (context, s) {
47 if (s.hasError) return LoadError(error: s.error!, retry: reload);
48 if (!s.hasData) {
49 return const Center(child: CircularProgressIndicator());
50 }
51 return ListView(padding: const EdgeInsets.all(16), children: [
52 const Text(
53 'فقط اطلاعاتی که سرور طبق رابطه سرپرستی و اشتراک هر تکلیف مجاز بداند نمایش داده می‌شود.'),
54 if (s.data!.isEmpty)
55 const EmptyCard(
56 icon: Icons.family_restroom,
57 title: 'فرزند متصل نمایش داده نشد',
58 subtitle:
59 'عضویت خانواده و رابطه سرپرستی را در پروفایل بررسی کن.'),
60 ...s.data!.map((child) => Card(
61 child: ListTile(
62 title: Text(child['display_name']?.toString() ?? 'فرزند'),
63 subtitle: Text(child['familyName']?.toString() ?? ''),
64 trailing: const Icon(Icons.chevron_left),
65 onTap: () {
66 if (widget.api is HttpIdentityApi) {
67 Navigator.push(
68 context,
69 MaterialPageRoute(
70 builder: (_) => LearningReportPage(
71 api: widget.api as HttpIdentityApi,
72 familyId: child['familyId'].toString(),
73 childId: child['user_id'].toString(),
74 childName:
75 child['display_name']?.toString() ??
76 'فرزند')));
77 }
78 }))),
79 TextButton(onPressed: reload, child: const Text('تازه‌سازی اعضا'))
80 ]);
81 });
82 }
83
84 class LearningReportPage extends StatefulWidget {
85 const LearningReportPage(
86 {super.key,
87 required this.api,
88 required this.familyId,
89 required this.childId,
90 required this.childName});
91 final HttpIdentityApi api;
92 final String familyId, childId, childName;
93 @override
94 State<LearningReportPage> createState() => _LearningReportPageState();
95 }
96
97 class _LearningReportPageState extends State<LearningReportPage>
98 with WidgetsBindingObserver {
99 Map<String, dynamic>? report;
100 bool busy = false;
101 String? error;
102 int days = 7;
103 Timer? poll;
104 @override
105 void initState() {
106 super.initState();
107 WidgetsBinding.instance.addObserver(this);
108 startPoll();
109 load();
110 }
111
112 void startPoll() {
113 poll?.cancel();
114 poll = Timer.periodic(const Duration(seconds: 15), (_) => load());
115 }
116
117 @override
118 void didChangeAppLifecycleState(AppLifecycleState s) {
119 if (s == AppLifecycleState.resumed) {
120 startPoll();
121 load();
122 } else {
123 poll?.cancel();
124 }
125 }
126
127 @override
128 void dispose() {
129 poll?.cancel();
130 WidgetsBinding.instance.removeObserver(this);
131 super.dispose();
132 }
133
134 Future<void> load() async {
135 if (busy) return;
136 setState(() => busy = true);
137 try {
138 final tehranNow =
139 DateTime.now().toUtc().add(const Duration(hours: 3, minutes: 30));
140 final to =
141 DateTime.utc(tehranNow.year, tehranNow.month, tehranNow.day + 1)
142 .subtract(const Duration(hours: 3, minutes: 30));
143 final result = await widget.api.getLearningReport(
144 widget.familyId, widget.childId,
145 from: to.subtract(Duration(days: days)), to: to);
146 if (mounted) {
147 setState(() {
148 report = result;
149 error = null;
150 });
151 }
152 } catch (e) {
153 if (mounted) {
154 setState(() {
155 error = uiErrorText(e);
156 if (isOfflineFailure(e) ||
157 (e is ApiException &&
158 e.statusCode >= 400 &&
159 e.statusCode < 500)) {
160 report = null;
161 }
162 });
163 }
164 } finally {
165 if (mounted) setState(() => busy = false);
166 }
167 }
168
169 String minutes(dynamic seconds) =>
170 '${((seconds as num? ?? 0) / 60).round()} دقیقه';
171 @override
172 Widget build(BuildContext context) {
173 final r = report;
174 final m = r?['metrics'] as Map? ?? {};
175 final items = r?['items'] as List? ?? [];
176 final daily = r?['daily'] as List? ?? [];
177 final max = daily.fold<num>(
178 1,
179 (v, row) => (row['recordedDurationSeconds'] as num? ?? 0) > v
180 ? row['recordedDurationSeconds'] as num
181 : v);
182 final tehranNow =
183 DateTime.now().toUtc().add(const Duration(hours: 3, minutes: 30));
184 final todayCount = items.where((raw) {
185 final i = raw as Map;
186 final at =
187 DateTime.tryParse((i['dueAt'] ?? i['startsAt'] ?? '').toString())
188 ?.toUtc()
189 .add(const Duration(hours: 3, minutes: 30));
190 return at != null &&
191 at.year == tehranNow.year &&
192 at.month == tehranNow.month &&
193 at.day == tehranNow.day;
194 }).length;
195 return Scaffold(
196 appBar: AppBar(title: Text('گزارش یادگیری · ${widget.childName}')),
197 body: ListView(padding: const EdgeInsets.all(16), children: [
198 const Text(
199 'زمان ثبت‌شده، گزارش شخصی است و اثبات مطالعه نیست. تأیید سرپرست فقط در صورت ثبت صریح سرور نمایش داده می‌شود.'),
200 SegmentedButton<int>(
201 segments: const [
202 ButtonSegment(value: 7, label: Text('هفتگی')),
203 ButtonSegment(value: 30, label: Text('ماهانه'))
204 ],
205 selected: {
206 days
207 },
208 onSelectionChanged: busy
209 ? null
210 : (v) {
211 setState(() => days = v.first);
212 load();
213 }),
214 if (busy) const LinearProgressIndicator(),
215 if (error != null)
216 Card(
217 child: ListTile(
218 leading: const Icon(Icons.warning_amber),
219 title: Text(error!),
220 subtitle: Text(report == null
221 ? 'اطلاعات فرزند بدون تأیید مجوز فعلی نمایش داده نمی‌شود.'
222 : 'داده قبلی به‌روز نیست؛ وضعیت زنده تأیید نشده است.'))),
223 if (r != null) ...[
224 Text(
225 'دریافت سرور: ${shortDate(r['asOf'])} · آخرین ثبت: ${shortDate(r['lastSyncAt'])}'),
226 Wrap(spacing: 8, children: [
227 Chip(label: Text('$todayCount مورد امروز (تهران)')),
228 Chip(label: Text('${m['totalTasks'] ?? 0} تکلیف')),
229 Chip(label: Text('${m['completedTasks'] ?? 0} انجام‌شده')),
230 Chip(label: Text('${m['overdueTasks'] ?? 0} عقب‌افتاده')),
231 Chip(label: Text('${m['completionPercent'] ?? 0}٪ تکمیل'))
232 ]),
233 Text(
234 'زمان برنامه‌ریزی‌شده: ${minutes(m['plannedInRangeDurationSeconds'] ?? m['plannedDurationSeconds'])}'),
235 Text('زمان ثبت‌شده: ${minutes(m['recordedDurationSeconds'])}'),
236 Text('روند زمان ثبت‌شده',
237 style: Theme.of(context).textTheme.titleLarge),
238 ...daily.map((raw) {
239 final row = raw as Map;
240 return Padding(
241 padding: const EdgeInsets.symmetric(vertical: 4),
242 child: Row(children: [
243 SizedBox(width: 100, child: Text(row['date'].toString())),
244 Expanded(
245 child: LinearProgressIndicator(
246 value:
247 (row['recordedDurationSeconds'] as num? ?? 0) /
248 max)),
249 const SizedBox(width: 8),
250 Text(minutes(row['recordedDurationSeconds']))
251 ]));
252 }),
253 Text('درس‌ها', style: Theme.of(context).textTheme.titleLarge),
254 ...(r['subjects'] as List? ?? []).map((raw) {
255 final row = raw as Map;
256 return ListTile(
257 title: Text(row['subjectName']?.toString() ?? 'بدون درس'),
258 subtitle: Text(
259 '${row['completedTasks']}/${row['totalTasks']} تکمیل · ${minutes(row['recordedDurationSeconds'])}'));
260 }),
261 Text('تکلیف‌ها و امتحان‌ها',
262 style: Theme.of(context).textTheme.titleLarge),
263 ...items.map((raw) {
264 final i = raw as Map;
265 final verified = i['activityState'] == 'verified' &&
266 i['activitySource'] == 'guardian_confirmation';
267 final state = verified
268 ? 'تأیید صریح سرپرست'
269 : switch (i['activityState']) {
270 'started' => 'شروع ثبت‌شده',
271 'paused' => 'مکث ثبت‌شده',
272 'completed' => 'انجام‌شده به گزارش فرزند',
273 _ => 'برنامه‌ریزی‌شده'
274 };
275 return Card(
276 child: ListTile(
277 title: Text(i['title']?.toString() ?? ''),
278 subtitle: Text(
279 '${faKind(i['kind']?.toString() ?? 'task')} · $state\nآخرین ثبت وضعیت: ${shortDate(i['activityAt'])}\nموعد: ${shortDate(i['dueAt'] ?? i['startsAt'])}\nبرنامه ${minutes(i['plannedDurationSeconds'])} · ثبت ${minutes(i['recordedDurationSeconds'])}${i['gradePoints'] == null ? '' : '\nنمره ${i['gradePoints']}/${i['gradeOutOf']}'}')));
280 }),
281 ],
282 TextButton(
283 onPressed: busy ? null : load,
284 child: const Text('تازه‌سازی گزارش')),
285 ]));
286 }
287 }