LifeMate — Personal, Family & Learning Companion

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