LifeMate — Personal, Family & Learning Companion

fix/local-task-persistence
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 525 lines 17 KB
Raw
1 import 'package:flutter/material.dart';
2
3 import 'api.dart';
4
5 class Phase4Hub extends StatefulWidget {
6 const Phase4Hub({super.key, required this.api, this.adultShell = false});
7 final IdentityApi api;
8 final bool adultShell;
9
10 @override
11 State<Phase4Hub> createState() => _Phase4HubState();
12 }
13
14 class _Phase4HubState extends State<Phase4Hub> {
15 late Future<List<Map<String, dynamic>>> goals;
16
17 @override
18 void initState() {
19 super.initState();
20 goals = widget.api.listLearningGoals();
21 }
22
23 Future<void> addGoal() async {
24 final title = TextEditingController();
25 final target = TextEditingController();
26 final saved = await showDialog<bool>(
27 context: context,
28 builder: (dialogContext) => AlertDialog(
29 title: const Text('هدف یادگیری جدید'),
30 content: Column(
31 mainAxisSize: MainAxisSize.min,
32 children: [
33 TextField(
34 controller: title,
35 decoration: const InputDecoration(labelText: 'عنوان'),
36 ),
37 const SizedBox(height: 12),
38 TextField(
39 controller: target,
40 decoration: const InputDecoration(labelText: 'هدف یا نتیجه مطلوب'),
41 ),
42 ],
43 ),
44 actions: [
45 TextButton(
46 onPressed: () => Navigator.pop(dialogContext, false),
47 child: const Text('انصراف'),
48 ),
49 FilledButton(
50 onPressed: () async {
51 if (title.text.trim().isEmpty) return;
52 await widget.api.createLearningGoal(
53 title: title.text.trim(),
54 target: target.text.trim().isEmpty ? null : target.text.trim(),
55 );
56 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
57 },
58 child: const Text('ذخیره'),
59 ),
60 ],
61 ),
62 );
63 title.dispose();
64 target.dispose();
65 if (saved == true && mounted) {
66 setState(() => goals = widget.api.listLearningGoals());
67 }
68 }
69
70 Future<void> learningCheckin(Map<String, dynamic> goal) async {
71 var confidence = 3;
72 var difficulty = 3;
73 final note = TextEditingController();
74 final saved = await showDialog<bool>(
75 context: context,
76 builder: (dialogContext) => StatefulBuilder(
77 builder: (context, setLocalState) => AlertDialog(
78 title: Text('ثبت پیشرفت · ${goal['title'] ?? ''}'),
79 content: Column(
80 mainAxisSize: MainAxisSize.min,
81 children: [
82 _ScaleRow(
83 label: 'اعتماد',
84 value: confidence,
85 onChanged: (v) => setLocalState(() => confidence = v),
86 ),
87 _ScaleRow(
88 label: 'سختی',
89 value: difficulty,
90 onChanged: (v) => setLocalState(() => difficulty = v),
91 ),
92 const SizedBox(height: 12),
93 TextField(
94 controller: note,
95 maxLines: 2,
96 decoration: const InputDecoration(
97 labelText: 'یادداشت کوتاه (اختیاری)',
98 ),
99 ),
100 ],
101 ),
102 actions: [
103 TextButton(
104 onPressed: () => Navigator.pop(dialogContext, false),
105 child: const Text('انصراف'),
106 ),
107 FilledButton(
108 onPressed: () async {
109 await widget.api.createLearningCheckin(
110 learningGoalId: goal['id']?.toString(),
111 confidence: confidence,
112 difficulty: difficulty,
113 note: note.text.trim().isEmpty ? null : note.text.trim(),
114 );
115 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
116 },
117 child: const Text('ثبت'),
118 ),
119 ],
120 ),
121 ),
122 );
123 note.dispose();
124 if (saved == true && mounted) {
125 ScaffoldMessenger.of(context).showSnackBar(
126 const SnackBar(content: Text('پیشرفت یادگیری ثبت شد.')),
127 );
128 }
129 }
130
131 Future<void> wellbeingCheckin() async {
132 var mood = 3;
133 var energy = 3;
134 var stress = 3;
135 var visibility = 'private';
136 final note = TextEditingController();
137
138 final saved = await showDialog<bool>(
139 context: context,
140 builder: (dialogContext) => StatefulBuilder(
141 builder: (context, setLocalState) => AlertDialog(
142 title: const Text('ثبت حال امروز'),
143 content: SingleChildScrollView(
144 child: Column(
145 mainAxisSize: MainAxisSize.min,
146 children: [
147 _ScaleRow(
148 label: 'حال کلی',
149 value: mood,
150 onChanged: (v) => setLocalState(() => mood = v),
151 ),
152 _ScaleRow(
153 label: 'انرژی',
154 value: energy,
155 onChanged: (v) => setLocalState(() => energy = v),
156 ),
157 _ScaleRow(
158 label: 'استرس',
159 value: stress,
160 onChanged: (v) => setLocalState(() => stress = v),
161 ),
162 const SizedBox(height: 12),
163 TextField(
164 controller: note,
165 maxLines: 3,
166 decoration: const InputDecoration(
167 labelText: 'یادداشت خصوصی (اختیاری)',
168 ),
169 ),
170 const SizedBox(height: 12),
171 DropdownButtonFormField<String>(
172 initialValue: visibility,
173 decoration: const InputDecoration(labelText: 'اشتراک وضعیت'),
174 items: const [
175 DropdownMenuItem(
176 value: 'private',
177 child: Text('کاملاً خصوصی'),
178 ),
179 DropdownMenuItem(
180 value: 'guardian_summary',
181 child: Text('فقط در خلاصه آماری والد'),
182 ),
183 ],
184 onChanged: (v) {
185 if (v != null) setLocalState(() => visibility = v);
186 },
187 ),
188 ],
189 ),
190 ),
191 actions: [
192 TextButton(
193 onPressed: () => Navigator.pop(dialogContext, false),
194 child: const Text('انصراف'),
195 ),
196 FilledButton(
197 onPressed: () async {
198 await widget.api.createWellbeingCheckin(
199 mood: mood,
200 energy: energy,
201 stress: stress,
202 note: note.text.trim().isEmpty ? null : note.text.trim(),
203 visibility: visibility,
204 );
205 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
206 },
207 child: const Text('ثبت'),
208 ),
209 ],
210 ),
211 ),
212 );
213 note.dispose();
214 if (saved == true && mounted) {
215 ScaffoldMessenger.of(context).showSnackBar(
216 const SnackBar(content: Text('ثبت شد. متن یادداشت خصوصی باقی می‌ماند.')),
217 );
218 }
219 }
220
221 void openGuide(String kind, String title) {
222 Navigator.of(context).push(
223 MaterialPageRoute(
224 builder: (_) => GuideChatPage(
225 api: widget.api,
226 kind: kind,
227 title: title,
228 ),
229 ),
230 );
231 }
232
233 @override
234 Widget build(BuildContext context) => ListView(
235 padding: const EdgeInsets.all(16),
236 children: [
237 Text(
238 widget.adultShell ? 'راهنمای هوشمند' : 'یادگیری و حال خوب',
239 style: Theme.of(context).textTheme.headlineSmall,
240 ),
241 const SizedBox(height: 6),
242 const Text(
243 'راهنماها پیشنهاد می‌دهند؛ تصمیم و اجرای تغییرها با خودت است.',
244 ),
245 const SizedBox(height: 16),
246 _GuideCard(
247 icon: Icons.school_rounded,
248 title: 'راهنمای مطالعه',
249 subtitle: 'فهم بهتر، مرور فعال و برنامه مطالعه مرحله‌به‌مرحله.',
250 onTap: () => openGuide('study', 'راهنمای مطالعه'),
251 ),
252 _GuideCard(
253 icon: Icons.auto_awesome_rounded,
254 title: 'راهنمای برنامه‌ریزی',
255 subtitle: 'اولویت‌بندی و شکستن کارها بدون تغییر خودکار برنامه.',
256 onTap: () => openGuide('planner', 'راهنمای برنامه‌ریزی'),
257 ),
258 _GuideCard(
259 icon: Icons.self_improvement_rounded,
260 title: 'همراه حال خوب',
261 subtitle: 'گفت‌وگوی حمایتی و غیرتشخیصی برای حال، ارتباط و فشار روزمره.',
262 onTap: () => openGuide('wellbeing', 'همراه حال خوب'),
263 ),
264 const SizedBox(height: 8),
265 Row(
266 children: [
267 Expanded(
268 child: FilledButton.icon(
269 onPressed: wellbeingCheckin,
270 icon: const Icon(Icons.favorite_outline),
271 label: const Text('ثبت حال امروز'),
272 ),
273 ),
274 const SizedBox(width: 8),
275 Expanded(
276 child: OutlinedButton.icon(
277 onPressed: addGoal,
278 icon: const Icon(Icons.flag_outlined),
279 label: const Text('هدف یادگیری'),
280 ),
281 ),
282 ],
283 ),
284 const SizedBox(height: 16),
285 const Card(
286 child: Padding(
287 padding: EdgeInsets.all(16),
288 child: Text(
289 'حریم خصوصی: متن گفت‌وگو و یادداشت حال خوب برای خود کاربر است. '
290 'والد فقط خلاصه‌ای را می‌بیند که مجاز شده باشد؛ در وضعیت ایمنی جدی، '
291 'سیگنال ایمنی جدا از متن خصوصی مدیریت می‌شود.',
292 ),
293 ),
294 ),
295 const SizedBox(height: 12),
296 Text('هدف‌های یادگیری', style: Theme.of(context).textTheme.titleMedium),
297 FutureBuilder<List<Map<String, dynamic>>>(
298 future: goals,
299 builder: (context, snapshot) {
300 if (!snapshot.hasData) {
301 return const Padding(
302 padding: EdgeInsets.all(20),
303 child: Center(child: CircularProgressIndicator()),
304 );
305 }
306 if (snapshot.data!.isEmpty) {
307 return const Card(
308 child: ListTile(
309 leading: Icon(Icons.flag_outlined),
310 title: Text('هنوز هدفی ثبت نشده'),
311 ),
312 );
313 }
314 return Column(
315 children: snapshot.data!
316 .map(
317 (goal) => Card(
318 child: ListTile(
319 leading: const Icon(Icons.flag_circle_outlined),
320 title: Text(goal['title']?.toString() ?? ''),
321 subtitle: Text(goal['target']?.toString() ?? ''),
322 trailing: const Icon(Icons.add_chart_outlined),
323 onTap: () => learningCheckin(goal),
324 ),
325 ),
326 )
327 .toList(),
328 );
329 },
330 ),
331 ],
332 );
333 }
334
335 class GuideChatPage extends StatefulWidget {
336 const GuideChatPage({
337 super.key,
338 required this.api,
339 required this.kind,
340 required this.title,
341 });
342
343 final IdentityApi api;
344 final String kind;
345 final String title;
346
347 @override
348 State<GuideChatPage> createState() => _GuideChatPageState();
349 }
350
351 class _GuideChatPageState extends State<GuideChatPage> {
352 final input = TextEditingController();
353 final messages = <Map<String, String>>[];
354 String? sessionId;
355 bool busy = false;
356
357 Future<void> send() async {
358 final text = input.text.trim();
359 if (text.isEmpty || busy) return;
360 setState(() {
361 busy = true;
362 messages.add({'role': 'user', 'body': text});
363 input.clear();
364 });
365 try {
366 final session = sessionId == null
367 ? await widget.api.createAiSession(widget.kind)
368 : null;
369 sessionId ??= session?['id']?.toString();
370 if (sessionId == null) throw StateError('session_not_created');
371 final reply = await widget.api.sendAiMessage(sessionId!, text);
372 if (mounted) {
373 setState(() {
374 messages.add({
375 'role': 'assistant',
376 'body': reply['body']?.toString() ?? '',
377 });
378 });
379 }
380 } catch (_) {
381 if (mounted) {
382 setState(() {
383 messages.add({
384 'role': 'assistant',
385 'body': 'ارسال انجام نشد. دوباره تلاش کن.',
386 });
387 });
388 }
389 } finally {
390 if (mounted) setState(() => busy = false);
391 }
392 }
393
394 @override
395 void dispose() {
396 input.dispose();
397 super.dispose();
398 }
399
400 @override
401 Widget build(BuildContext context) => Scaffold(
402 appBar: AppBar(title: Text(widget.title)),
403 body: Column(
404 children: [
405 const Padding(
406 padding: EdgeInsets.fromLTRB(16, 8, 16, 4),
407 child: Text(
408 'این راهنما جای پزشک، روان‌شناس یا خدمات اضطراری نیست و تشخیص پزشکی نمی‌دهد.',
409 textAlign: TextAlign.center,
410 ),
411 ),
412 Expanded(
413 child: ListView.builder(
414 padding: const EdgeInsets.all(16),
415 itemCount: messages.length,
416 itemBuilder: (context, index) {
417 final item = messages[index];
418 final mine = item['role'] == 'user';
419 return Align(
420 alignment:
421 mine ? Alignment.centerRight : Alignment.centerLeft,
422 child: Card(
423 child: Padding(
424 padding: const EdgeInsets.all(12),
425 child: ConstrainedBox(
426 constraints: const BoxConstraints(maxWidth: 560),
427 child: Text(item['body'] ?? ''),
428 ),
429 ),
430 ),
431 );
432 },
433 ),
434 ),
435 SafeArea(
436 top: false,
437 child: Padding(
438 padding: const EdgeInsets.all(12),
439 child: Row(
440 children: [
441 Expanded(
442 child: TextField(
443 controller: input,
444 minLines: 1,
445 maxLines: 4,
446 onSubmitted: (_) => send(),
447 decoration: const InputDecoration(
448 hintText: 'اینجا بنویس...',
449 ),
450 ),
451 ),
452 const SizedBox(width: 8),
453 IconButton.filled(
454 onPressed: busy ? null : send,
455 icon: busy
456 ? const SizedBox(
457 width: 18,
458 height: 18,
459 child: CircularProgressIndicator(strokeWidth: 2),
460 )
461 : const Icon(Icons.send_rounded),
462 ),
463 ],
464 ),
465 ),
466 ),
467 ],
468 ),
469 );
470 }
471
472 class _GuideCard extends StatelessWidget {
473 const _GuideCard({
474 required this.icon,
475 required this.title,
476 required this.subtitle,
477 required this.onTap,
478 });
479
480 final IconData icon;
481 final String title;
482 final String subtitle;
483 final VoidCallback onTap;
484
485 @override
486 Widget build(BuildContext context) => Card(
487 child: ListTile(
488 leading: Icon(icon),
489 title: Text(title),
490 subtitle: Text(subtitle),
491 trailing: const Icon(Icons.chevron_left_rounded),
492 onTap: onTap,
493 ),
494 );
495 }
496
497 class _ScaleRow extends StatelessWidget {
498 const _ScaleRow({
499 required this.label,
500 required this.value,
501 required this.onChanged,
502 });
503
504 final String label;
505 final int value;
506 final ValueChanged<int> onChanged;
507
508 @override
509 Widget build(BuildContext context) => Row(
510 children: [
511 SizedBox(width: 70, child: Text(label)),
512 Expanded(
513 child: Slider(
514 value: value.toDouble(),
515 min: 1,
516 max: 5,
517 divisions: 4,
518 label: value.toString(),
519 onChanged: (v) => onChanged(v.round()),
520 ),
521 ),
522 Text(value.toString()),
523 ],
524 );
525 }