LifeMate — Personal, Family & Learning Companion

infra/lifeguide-github-pages-qa
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 245 lines 8.18 KB
Raw
1 import 'dart:async';
2 import 'package:flutter/material.dart';
3 import 'api.dart';
4 import 'offline_store.dart';
5 import 'phase3_ui.dart';
6 import 'study_coordinator.dart';
7
8 class StudyHub extends StatelessWidget {
9 const StudyHub({super.key, required this.api});
10 final IdentityApi api;
11 @override
12 Widget build(BuildContext context) => Column(children: [
13 const Padding(
14 padding: EdgeInsets.all(16),
15 child: Text(
16 'تایمر را از منوی هر تکلیف در برنامه‌ریز باز کن. زمان ثبت‌شده، گزارش شخصی است و اثبات مطالعه نیست.')),
17 Expanded(child: PlannerPage(api: api))
18 ]);
19 }
20
21 class StudyTimerPage extends StatefulWidget {
22 const StudyTimerPage({super.key, required this.api, required this.item});
23 final HttpIdentityApi api;
24 final Map<String, dynamic> item;
25 @override
26 State<StudyTimerPage> createState() => _StudyTimerPageState();
27 }
28
29 class _StudyTimerPageState extends State<StudyTimerPage>
30 with WidgetsBindingObserver {
31 late final StudySync sync;
32 List<Map<String, dynamic>> sessions = [];
33 bool busy = false, loaded = false, offline = false, pending = false;
34 String? error;
35 Timer? ticker, poll;
36 DateTime? fetchedAt;
37 @override
38 void initState() {
39 super.initState();
40 sync = StudySync(widget.api);
41 WidgetsBinding.instance.addObserver(this);
42 timers();
43 load();
44 }
45
46 void timers() {
47 ticker?.cancel();
48 poll?.cancel();
49 ticker = Timer.periodic(const Duration(seconds: 1), (_) {
50 if (mounted) setState(() {});
51 });
52 poll = Timer.periodic(const Duration(seconds: 15), (_) {
53 if (!busy) load();
54 });
55 }
56
57 @override
58 void didChangeAppLifecycleState(AppLifecycleState s) {
59 if (s == AppLifecycleState.resumed) {
60 timers();
61 load();
62 } else {
63 ticker?.cancel();
64 poll?.cancel();
65 }
66 }
67
68 @override
69 void dispose() {
70 ticker?.cancel();
71 poll?.cancel();
72 WidgetsBinding.instance.removeObserver(this);
73 super.dispose();
74 }
75
76 Map<String, dynamic>? get current {
77 final active = sessions
78 .where((s) => s['status'] == 'running' || s['status'] == 'paused');
79 return active.isEmpty ? null : active.first;
80 }
81
82 Future<void> load() async {
83 if (busy) return;
84 setState(() {
85 busy = true;
86 error = null;
87 });
88 try {
89 await sync.flush();
90 final rows = await widget.api
91 .listStudySessions(planItemId: widget.item['id'].toString());
92 final store = sync.store;
93 final all = await store.readList('study.sessions');
94 all.removeWhere((s) => s['planItemId'] == widget.item['id']);
95 all.addAll(rows);
96 await store.writeList('study.sessions', all);
97 final hasPending = (await store.readQueue())
98 .any((m) => m['entityType'] == 'study_session');
99 if (mounted) {
100 setState(() {
101 sessions = rows;
102 loaded = true;
103 offline = false;
104 pending = hasPending;
105 fetchedAt = DateTime.now();
106 });
107 }
108 } catch (e) {
109 if (isOfflineFailure(e)) {
110 try {
111 final cache = await sync.store.readList('study.sessions');
112 final queue = await sync.store.readQueue();
113 if (mounted) {
114 setState(() {
115 sessions = cache
116 .where((s) => s['planItemId'] == widget.item['id'])
117 .toList();
118 loaded = true;
119 offline = true;
120 pending = queue.any((m) => m['entityType'] == 'study_session');
121 error = uiErrorText(e);
122 });
123 }
124 } catch (storage) {
125 if (mounted) setState(() => error = uiErrorText(storage));
126 }
127 } else {
128 if (mounted) {
129 setState(() {
130 error = uiErrorText(e);
131 offline = true;
132 });
133 }
134 }
135 } finally {
136 if (mounted) setState(() => busy = false);
137 }
138 }
139
140 Future<void> act(String action) async {
141 if (busy || pending) return;
142 setState(() {
143 busy = true;
144 error = null;
145 });
146 try {
147 final outcome = action == 'start'
148 ? await sync.start(widget.item['id'].toString())
149 : await sync.event(current!, action);
150 if (mounted) {
151 setState(() {
152 pending = outcome.queued;
153 if (outcome.item != null) {
154 sessions.removeWhere((s) => s['id'] == outcome.item!['id']);
155 sessions.add(outcome.item!);
156 }
157 if (outcome.queued) {
158 offline = true;
159 error =
160 'رویداد روی دستگاه ثبت شد؛ شروع یا پایان در سرور هنوز تأیید نشده است.';
161 }
162 });
163 }
164 } catch (e) {
165 if (mounted) setState(() => error = uiErrorText(e));
166 } finally {
167 if (mounted) setState(() => busy = false);
168 }
169 }
170
171 int elapsed(Map<String, dynamic> session) {
172 var seconds = (session['recordedDurationSeconds'] as num? ?? 0).toInt();
173 if (session['status'] == 'running' && !offline && !pending) {
174 final intervals = session['intervals'] as List? ?? [];
175 if (intervals.isNotEmpty) {
176 final last = intervals.last as Map;
177 if (last['end'] == null) {
178 final start = DateTime.tryParse(last['start'].toString());
179 if (start != null) {
180 final difference =
181 DateTime.now().toUtc().difference(start).inSeconds;
182 if (difference > 0) seconds += difference;
183 }
184 }
185 }
186 }
187 return seconds;
188 }
189
190 String duration(int seconds) =>
191 '${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}';
192 @override
193 Widget build(BuildContext context) => Scaffold(
194 appBar: AppBar(title: const Text('تایمر مطالعه')),
195 body: ListView(padding: const EdgeInsets.all(20), children: [
196 Text(widget.item['title']?.toString() ?? '',
197 style: Theme.of(context).textTheme.headlineSmall),
198 const Text(
199 'زمان ثبت‌شده، گزارش شخصی است و اثبات مطالعه نیست. توقف تایمر تکلیف را انجام‌شده نمی‌کند.'),
200 SyncNotice(
201 offline: offline, pending: pending ? 1 : 0, syncedAt: fetchedAt),
202 if (error != null)
203 Card(
204 child: Padding(
205 padding: const EdgeInsets.all(12), child: Text(error!))),
206 if (!loaded && busy) const LinearProgressIndicator(),
207 if (current != null) ...[
208 Text(duration(elapsed(current!)),
209 textAlign: TextAlign.center,
210 style: Theme.of(context).textTheme.displayMedium),
211 Text(
212 offline
213 ? 'زمان دریافت‌شده قبلی؛ وضعیت فعلی تأیید نشده'
214 : 'نمایش زمان دستگاه؛ مقدار نهایی پس از تأیید سرور ثبت می‌شود.',
215 textAlign: TextAlign.center),
216 Row(children: [
217 Expanded(
218 child: FilledButton(
219 onPressed: busy || pending
220 ? null
221 : () => act(current!['status'] == 'running'
222 ? 'pause'
223 : 'resume'),
224 child: Text(
225 current!['status'] == 'running' ? 'مکث' : 'ادامه'))),
226 const SizedBox(width: 12),
227 Expanded(
228 child: OutlinedButton(
229 onPressed: busy || pending ? null : () => act('stop'),
230 child: const Text('پایان')))
231 ]),
232 ] else
233 FilledButton.icon(
234 onPressed: !loaded || busy || pending ? null : () => act('start'),
235 icon: const Icon(Icons.play_arrow),
236 label: const Text('شروع مطالعه')),
237 TextButton(
238 onPressed: busy ? null : load,
239 child: const Text('همگام‌سازی و تلاش دوباره')),
240 ...sessions.where((s) => s['status'] == 'completed').map((s) => ListTile(
241 title: const Text('جلسه پایان‌یافته'),
242 subtitle: Text(
243 '${duration(elapsed(s))} ثبت‌شده · ${shortDate(s['endedAt'])}'))),
244 ]));
245 }