LifeMate — Personal, Family & Learning Companion

phase-4/ai-learning-wellbeing
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 1,070 lines 36.8 KB
Raw
1 import 'package:flutter/material.dart';
2 import 'package:flutter_localizations/flutter_localizations.dart';
3
4 import 'api.dart';
5 import 'phase3_ui.dart';
6 import 'phase4_ui.dart';
7
8 void main() => runApp(LifeMateApp());
9
10 class LifeMateApp extends StatelessWidget {
11 LifeMateApp({super.key, IdentityApi? api}) : api = api ?? HttpIdentityApi();
12 final IdentityApi api;
13
14 @override
15 Widget build(BuildContext context) {
16 final uri = Uri.base;
17 final token = uri.queryParameters['token'];
18 Widget entry = SignInPage(
19 api: api,
20 invitationToken:
21 token != null && uri.path.contains('accept-invitation') ? token : null,
22 );
23 if (token != null && uri.path.contains('verify-email')) {
24 entry = VerifyEmailPage(api: api, token: token);
25 } else if (token != null && uri.path.contains('reset-password')) {
26 entry = ResetPasswordPage(api: api, token: token);
27 }
28 return MaterialApp(
29 debugShowCheckedModeBanner: false,
30 locale: const Locale('fa'),
31 supportedLocales: const [Locale('fa'), Locale('en')],
32 localizationsDelegates: const [
33 GlobalMaterialLocalizations.delegate,
34 GlobalWidgetsLocalizations.delegate,
35 GlobalCupertinoLocalizations.delegate,
36 ],
37 theme: ThemeData(
38 colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF4D86E8)),
39 scaffoldBackgroundColor: const Color(0xFFF8FAFD),
40 inputDecorationTheme:
41 const InputDecorationTheme(border: OutlineInputBorder()),
42 useMaterial3: true,
43 ),
44 home: Directionality(textDirection: TextDirection.rtl, child: entry),
45 );
46 }
47 }
48
49 String errorText(Object error) {
50 if (error is ApiException) {
51 switch (error.code) {
52 case 'invalid_credentials':
53 return 'ایمیل یا رمز عبور صحیح نیست.';
54 case 'email_not_verified':
55 return 'ابتدا ایمیل حساب را تأیید کن.';
56 case 'account_exists':
57 return 'برای این ایمیل قبلاً حساب ساخته شده است.';
58 case 'invalid_password':
59 return 'رمز عبور باید حداقل ۱۰ کاراکتر باشد.';
60 case 'invalid_current_password':
61 return 'رمز فعلی صحیح نیست.';
62 case 'invalid_or_expired_token':
63 return 'لینک منقضی شده یا معتبر نیست.';
64 case 'forbidden':
65 return 'برای این عملیات دسترسی نداری.';
66 }
67 }
68 return 'عملیات انجام نشد. دوباره تلاش کن.';
69 }
70
71 class SignInPage extends StatefulWidget {
72 const SignInPage({super.key, required this.api, this.invitationToken});
73 final IdentityApi api;
74 final String? invitationToken;
75 @override
76 State<SignInPage> createState() => _SignInPageState();
77 }
78
79 class _SignInPageState extends State<SignInPage> {
80 final email = TextEditingController();
81 final password = TextEditingController();
82 bool busy = false;
83 String? error;
84
85 Future<void> submit() async {
86 setState(() {
87 busy = true;
88 error = null;
89 });
90 try {
91 await widget.api.login(email.text, password.text);
92 if (widget.invitationToken != null) {
93 await widget.api.acceptInvitation(widget.invitationToken!);
94 }
95 if (!mounted) return;
96 Navigator.of(context).pushReplacement(
97 MaterialPageRoute(builder: (_) => HomeShell(api: widget.api)),
98 );
99 } catch (e) {
100 if (mounted) setState(() => error = errorText(e));
101 } finally {
102 if (mounted) setState(() => busy = false);
103 }
104 }
105
106 @override
107 Widget build(BuildContext context) => Scaffold(
108 body: SafeArea(
109 child: Center(
110 child: ConstrainedBox(
111 constraints: const BoxConstraints(maxWidth: 440),
112 child: ListView(
113 padding: const EdgeInsets.all(28),
114 shrinkWrap: true,
115 children: [
116 const Icon(Icons.route_rounded, size: 64),
117 const SizedBox(height: 16),
118 const Text('LifeMate',
119 textAlign: TextAlign.center,
120 style:
121 TextStyle(fontSize: 32, fontWeight: FontWeight.w700)),
122 const Text('همراه شخصی، تحصیلی و خانوادگی',
123 textAlign: TextAlign.center),
124 const SizedBox(height: 28),
125 if (widget.invitationToken != null) ...[
126 const Card(
127 child: Padding(
128 padding: EdgeInsets.all(12),
129 child: Text(
130 'برای قبول دعوت خانواده، با همان ایمیل دعوت‌شده وارد شو.'),
131 ),
132 ),
133 const SizedBox(height: 12),
134 ],
135 TextField(
136 controller: email,
137 keyboardType: TextInputType.emailAddress,
138 decoration: const InputDecoration(labelText: 'ایمیل'),
139 ),
140 const SizedBox(height: 12),
141 TextField(
142 controller: password,
143 obscureText: true,
144 decoration: const InputDecoration(labelText: 'رمز عبور'),
145 ),
146 if (error != null) ...[
147 const SizedBox(height: 12),
148 Text(error!,
149 style: TextStyle(
150 color: Theme.of(context).colorScheme.error)),
151 ],
152 const SizedBox(height: 16),
153 FilledButton(
154 onPressed: busy ? null : submit,
155 child: Text(busy ? 'در حال ورود...' : 'ورود'),
156 ),
157 TextButton(
158 onPressed: busy
159 ? null
160 : () => Navigator.of(context).push(MaterialPageRoute(
161 builder: (_) => RecoveryPage(api: widget.api))),
162 child: const Text('رمز عبور را فراموش کرده‌ام'),
163 ),
164 TextButton(
165 onPressed: busy
166 ? null
167 : () => Navigator.of(context).push(MaterialPageRoute(
168 builder: (_) => RegistrationPage(api: widget.api))),
169 child: const Text('ساخت حساب جدید'),
170 ),
171 ],
172 ),
173 ),
174 ),
175 ),
176 );
177 }
178
179 class RegistrationPage extends StatefulWidget {
180 const RegistrationPage({super.key, required this.api});
181 final IdentityApi api;
182 @override
183 State<RegistrationPage> createState() => _RegistrationPageState();
184 }
185
186 class _RegistrationPageState extends State<RegistrationPage> {
187 final name = TextEditingController();
188 final email = TextEditingController();
189 final password = TextEditingController();
190 final confirm = TextEditingController();
191 bool busy = false;
192 String? error;
193
194 Future<void> submit() async {
195 if (password.text != confirm.text) {
196 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
197 return;
198 }
199 setState(() {
200 busy = true;
201 error = null;
202 });
203 try {
204 await widget.api.register(
205 displayName: name.text, email: email.text, password: password.text);
206 if (!mounted) return;
207 ScaffoldMessenger.of(context).showSnackBar(
208 const SnackBar(content: Text('حساب ساخته شد. ایمیل تأیید را بررسی کن.')),
209 );
210 Navigator.pop(context);
211 } catch (e) {
212 if (mounted) setState(() => error = errorText(e));
213 } finally {
214 if (mounted) setState(() => busy = false);
215 }
216 }
217
218 @override
219 Widget build(BuildContext context) => SimpleFormPage(
220 title: 'ساخت حساب',
221 busy: busy,
222 error: error,
223 action: 'ثبت‌نام و ارسال ایمیل تأیید',
224 onPressed: submit,
225 fields: [
226 TextField(
227 controller: name,
228 decoration: const InputDecoration(labelText: 'نام')),
229 TextField(
230 controller: email,
231 keyboardType: TextInputType.emailAddress,
232 decoration: const InputDecoration(labelText: 'ایمیل')),
233 TextField(
234 controller: password,
235 obscureText: true,
236 decoration: const InputDecoration(labelText: 'رمز عبور')),
237 TextField(
238 controller: confirm,
239 obscureText: true,
240 decoration: const InputDecoration(labelText: 'تکرار رمز عبور')),
241 ],
242 );
243 }
244
245 class RecoveryPage extends StatefulWidget {
246 const RecoveryPage({super.key, required this.api});
247 final IdentityApi api;
248 @override
249 State<RecoveryPage> createState() => _RecoveryPageState();
250 }
251
252 class _RecoveryPageState extends State<RecoveryPage> {
253 final email = TextEditingController();
254 bool busy = false;
255 bool sent = false;
256 String? error;
257
258 Future<void> submit() async {
259 setState(() {
260 busy = true;
261 error = null;
262 });
263 try {
264 await widget.api.forgotPassword(email.text);
265 if (mounted) setState(() => sent = true);
266 } catch (e) {
267 if (mounted) setState(() => error = errorText(e));
268 } finally {
269 if (mounted) setState(() => busy = false);
270 }
271 }
272
273 @override
274 Widget build(BuildContext context) => SimpleFormPage(
275 title: 'بازیابی رمز عبور',
276 busy: busy,
277 error: error,
278 action: sent ? 'لینک ارسال شد' : 'ارسال لینک بازیابی',
279 onPressed: sent ? null : submit,
280 fields: [
281 TextField(
282 controller: email,
283 keyboardType: TextInputType.emailAddress,
284 decoration: const InputDecoration(labelText: 'ایمیل تأییدشده')),
285 if (sent)
286 const Text(
287 'اگر حسابی با این ایمیل وجود داشته باشد، لینک بازیابی ارسال می‌شود.'),
288 ],
289 );
290 }
291
292 class VerifyEmailPage extends StatefulWidget {
293 const VerifyEmailPage({super.key, required this.api, required this.token});
294 final IdentityApi api;
295 final String token;
296 @override
297 State<VerifyEmailPage> createState() => _VerifyEmailPageState();
298 }
299
300 class _VerifyEmailPageState extends State<VerifyEmailPage> {
301 String message = 'در حال تأیید ایمیل...';
302 @override
303 void initState() {
304 super.initState();
305 verify();
306 }
307
308 Future<void> verify() async {
309 try {
310 await widget.api.verifyEmail(widget.token);
311 if (mounted) setState(() => message = 'ایمیل با موفقیت تأیید شد.');
312 } catch (e) {
313 if (mounted) setState(() => message = errorText(e));
314 }
315 }
316
317 @override
318 Widget build(BuildContext context) =>
319 Scaffold(body: Center(child: Text(message)));
320 }
321
322 class ResetPasswordPage extends StatefulWidget {
323 const ResetPasswordPage({super.key, required this.api, required this.token});
324 final IdentityApi api;
325 final String token;
326 @override
327 State<ResetPasswordPage> createState() => _ResetPasswordPageState();
328 }
329
330 class _ResetPasswordPageState extends State<ResetPasswordPage> {
331 final password = TextEditingController();
332 final confirm = TextEditingController();
333 bool busy = false;
334 bool done = false;
335 String? error;
336
337 Future<void> submit() async {
338 if (password.text != confirm.text) {
339 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
340 return;
341 }
342 setState(() {
343 busy = true;
344 error = null;
345 });
346 try {
347 await widget.api.resetPassword(widget.token, password.text);
348 if (mounted) setState(() => done = true);
349 } catch (e) {
350 if (mounted) setState(() => error = errorText(e));
351 } finally {
352 if (mounted) setState(() => busy = false);
353 }
354 }
355
356 @override
357 Widget build(BuildContext context) => SimpleFormPage(
358 title: 'ساخت رمز جدید',
359 busy: busy,
360 error: error,
361 action: done ? 'رمز تغییر کرد' : 'ذخیره رمز جدید',
362 onPressed: done ? null : submit,
363 fields: [
364 TextField(
365 controller: password,
366 obscureText: true,
367 decoration: const InputDecoration(labelText: 'رمز جدید')),
368 TextField(
369 controller: confirm,
370 obscureText: true,
371 decoration: const InputDecoration(labelText: 'تکرار رمز جدید')),
372 ],
373 );
374 }
375
376 class ChangePasswordPage extends StatefulWidget {
377 const ChangePasswordPage({super.key, required this.api});
378 final IdentityApi api;
379 @override
380 State<ChangePasswordPage> createState() => _ChangePasswordPageState();
381 }
382
383 class _ChangePasswordPageState extends State<ChangePasswordPage> {
384 final current = TextEditingController();
385 final next = TextEditingController();
386 final confirm = TextEditingController();
387 bool busy = false;
388 String? error;
389
390 Future<void> submit() async {
391 if (next.text != confirm.text) {
392 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
393 return;
394 }
395 setState(() {
396 busy = true;
397 error = null;
398 });
399 try {
400 await widget.api.changePassword(current.text, next.text);
401 if (!mounted) return;
402 ScaffoldMessenger.of(context)
403 .showSnackBar(const SnackBar(content: Text('رمز عبور تغییر کرد.')));
404 Navigator.pop(context);
405 } catch (e) {
406 if (mounted) setState(() => error = errorText(e));
407 } finally {
408 if (mounted) setState(() => busy = false);
409 }
410 }
411
412 @override
413 Widget build(BuildContext context) => SimpleFormPage(
414 title: 'تغییر رمز عبور',
415 busy: busy,
416 error: error,
417 action: 'ذخیره رمز جدید',
418 onPressed: submit,
419 fields: [
420 TextField(
421 controller: current,
422 obscureText: true,
423 decoration: const InputDecoration(labelText: 'رمز فعلی')),
424 TextField(
425 controller: next,
426 obscureText: true,
427 decoration: const InputDecoration(labelText: 'رمز جدید')),
428 TextField(
429 controller: confirm,
430 obscureText: true,
431 decoration: const InputDecoration(labelText: 'تکرار رمز جدید')),
432 ],
433 );
434 }
435
436 class SimpleFormPage extends StatelessWidget {
437 const SimpleFormPage({
438 super.key,
439 required this.title,
440 required this.fields,
441 required this.action,
442 required this.onPressed,
443 this.busy = false,
444 this.error,
445 });
446 final String title;
447 final List<Widget> fields;
448 final String action;
449 final VoidCallback? onPressed;
450 final bool busy;
451 final String? error;
452
453 @override
454 Widget build(BuildContext context) => Scaffold(
455 appBar: AppBar(title: Text(title)),
456 body: Center(
457 child: ConstrainedBox(
458 constraints: const BoxConstraints(maxWidth: 520),
459 child: ListView(
460 padding: const EdgeInsets.all(24),
461 children: [
462 for (final field in fields)
463 Padding(
464 padding: const EdgeInsets.only(bottom: 12), child: field),
465 if (error != null)
466 Padding(
467 padding: const EdgeInsets.only(bottom: 12),
468 child: Text(error!,
469 style: TextStyle(
470 color: Theme.of(context).colorScheme.error)),
471 ),
472 FilledButton(
473 onPressed: busy ? null : onPressed,
474 child: Text(busy ? 'لطفاً صبر کن...' : action)),
475 ],
476 ),
477 ),
478 ),
479 );
480 }
481
482 class HomeShell extends StatefulWidget {
483 const HomeShell({super.key, required this.api});
484 final IdentityApi api;
485
486 @override
487 State<HomeShell> createState() => _HomeShellState();
488 }
489
490 class _HomeShellState extends State<HomeShell> {
491 int index = 0;
492 String themePreference = 'adult_blue';
493 bool adultShell = false;
494
495 static const studentPages = [
496 'امروز',
497 'برنامه هفتگی',
498 'تقویم',
499 'تکالیف و کارها',
500 'امتحان‌ها و نمرات',
501 'تمرکز',
502 'همراه هوشمند',
503 ];
504
505 static const adultPages = [
506 'امروز',
507 'برنامه‌ریز',
508 'خانواده',
509 'راهنما',
510 'من',
511 ];
512
513 @override
514 void initState() {
515 super.initState();
516 loadContext();
517 }
518
519 Future<void> loadContext() async {
520 try {
521 final profile = await widget.api.getProfile();
522 final families = await widget.api.listFamilies();
523 final hasAdultRole = families.any(
524 (family) =>
525 family['role'] == 'parent_guardian' ||
526 family['role'] == 'adult_member',
527 );
528 if (mounted) {
529 setState(() {
530 themePreference =
531 profile['theme_preference']?.toString() ?? 'adult_blue';
532 adultShell = hasAdultRole;
533 index = 0;
534 });
535 }
536 } catch (_) {}
537 }
538
539 List<String> get pages => adultShell ? adultPages : studentPages;
540
541 Color get accent => themePreference == 'girl_pink'
542 ? const Color(0xFFE58FB0)
543 : const Color(0xFF4D86E8);
544
545 List<NavigationDestination> get destinations => adultShell
546 ? const [
547 NavigationDestination(
548 icon: Icon(Icons.home_outlined),
549 label: 'امروز',
550 ),
551 NavigationDestination(
552 icon: Icon(Icons.event_note_outlined),
553 label: 'برنامه‌ریز',
554 ),
555 NavigationDestination(
556 icon: Icon(Icons.family_restroom_outlined),
557 label: 'خانواده',
558 ),
559 NavigationDestination(
560 icon: Icon(Icons.assistant_outlined),
561 label: 'راهنما',
562 ),
563 NavigationDestination(
564 icon: Icon(Icons.person_outline),
565 label: 'من',
566 ),
567 ]
568 : const [
569 NavigationDestination(
570 icon: Icon(Icons.home_outlined),
571 label: 'امروز',
572 ),
573 NavigationDestination(
574 icon: Icon(Icons.schedule_outlined),
575 label: 'برنامه',
576 ),
577 NavigationDestination(
578 icon: Icon(Icons.calendar_month_outlined),
579 label: 'تقویم',
580 ),
581 NavigationDestination(
582 icon: Icon(Icons.task_alt_outlined),
583 label: 'کارها',
584 ),
585 NavigationDestination(
586 icon: Icon(Icons.school_outlined),
587 label: 'امتحان‌ها',
588 ),
589 ];
590
591 void selectPage(int next) {
592 setState(() => index = next);
593 }
594
595 @override
596 Widget build(BuildContext context) => Theme(
597 data: Theme.of(context).copyWith(
598 colorScheme: ColorScheme.fromSeed(seedColor: accent),
599 scaffoldBackgroundColor: Colors.white,
600 ),
601 child: Scaffold(
602 appBar: AppBar(
603 title: Text(pages[index]),
604 actions: [
605 IconButton(
606 onPressed: () => Navigator.of(context).push(
607 MaterialPageRoute(
608 builder: (_) => ProfileFamilyPage(api: widget.api),
609 ),
610 ),
611 icon: const Icon(Icons.person_outline),
612 ),
613 ],
614 ),
615 body: (pages[index] == 'همراه هوشمند' || pages[index] == 'راهنما')
616 ? Phase4Hub(api: widget.api, adultShell: adultShell)
617 : Phase3HomeContent(
618 api: widget.api,
619 page: pages[index],
620 adultShell: adultShell,
621 ),
622 bottomNavigationBar: NavigationBar(
623 selectedIndex: index > 4 ? 0 : index,
624 onDestinationSelected: selectPage,
625 destinations: destinations,
626 ),
627 drawer: Drawer(
628 child: SafeArea(
629 child: ListView(
630 children: [
631 const ListTile(
632 title: Text('LifeMate'),
633 subtitle: Text('منوی اصلی'),
634 ),
635 ...pages.asMap().entries.map(
636 (entry) => ListTile(
637 title: Text(entry.value),
638 onTap: () {
639 selectPage(entry.key);
640 Navigator.pop(context);
641 },
642 ),
643 ),
644 if (!adultShell) ...[
645 const Divider(),
646 ListTile(
647 leading: const Icon(Icons.family_restroom),
648 title: const Text('خانواده'),
649 onTap: () => Navigator.of(context).push(
650 MaterialPageRoute(
651 builder: (_) => ProfileFamilyPage(api: widget.api),
652 ),
653 ),
654 ),
655 ],
656 ],
657 ),
658 ),
659 ),
660 ),
661 );
662 }
663
664 class ProfileFamilyPage extends StatefulWidget {
665 const ProfileFamilyPage({super.key, required this.api});
666 final IdentityApi api;
667 @override
668 State<ProfileFamilyPage> createState() => _ProfileFamilyPageState();
669 }
670
671 class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
672 late Future<List<dynamic>> data;
673 @override
674 void initState() {
675 super.initState();
676 data = load();
677 }
678
679 Future<List<dynamic>> load() async =>
680 [await widget.api.getProfile(), await widget.api.listFamilies()];
681
682 Future<void> editProfile(Map<String, dynamic> profile) async {
683 final name = TextEditingController(
684 text: profile['display_name']?.toString() ?? '');
685 final theme = ValueNotifier<String>(
686 profile['theme_preference']?.toString() ?? 'adult_blue');
687 final saved = await showDialog<bool>(
688 context: context,
689 builder: (dialogContext) => AlertDialog(
690 title: const Text('ویرایش پروفایل'),
691 content: Column(mainAxisSize: MainAxisSize.min, children: [
692 TextField(
693 controller: name,
694 decoration: const InputDecoration(labelText: 'نام')),
695 const SizedBox(height: 12),
696 ValueListenableBuilder<String>(
697 valueListenable: theme,
698 builder: (_, value, __) => DropdownButtonFormField<String>(
699 initialValue: value,
700 decoration: const InputDecoration(labelText: 'تم'),
701 items: const [
702 DropdownMenuItem(
703 value: 'girl_pink', child: Text('سفید / صورتی')),
704 DropdownMenuItem(
705 value: 'boy_blue', child: Text('سفید / آبی نوجوان')),
706 DropdownMenuItem(
707 value: 'adult_blue', child: Text('سفید / آبی بزرگسال')),
708 ],
709 onChanged: (v) {
710 if (v != null) theme.value = v;
711 },
712 ),
713 ),
714 ]),
715 actions: [
716 TextButton(
717 onPressed: () => Navigator.pop(dialogContext, false),
718 child: const Text('انصراف')),
719 FilledButton(
720 onPressed: () async {
721 await widget.api.updateProfile(
722 displayName: name.text.trim(),
723 themePreference: theme.value);
724 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
725 },
726 child: const Text('ذخیره'),
727 ),
728 ],
729 ),
730 );
731 name.dispose();
732 theme.dispose();
733 if (saved == true && mounted) setState(() => data = load());
734 }
735
736 Future<void> createFamily() async {
737 final name = TextEditingController();
738 final created = await showDialog<bool>(
739 context: context,
740 builder: (dialogContext) => AlertDialog(
741 title: const Text('ساخت فضای خانواده'),
742 content: TextField(
743 controller: name,
744 decoration: const InputDecoration(labelText: 'نام خانواده')),
745 actions: [
746 TextButton(
747 onPressed: () => Navigator.pop(dialogContext, false),
748 child: const Text('انصراف')),
749 FilledButton(
750 onPressed: () async {
751 if (name.text.trim().isEmpty) return;
752 await widget.api
753 .createFamily(name.text.trim(), role: 'parent_guardian');
754 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
755 },
756 child: const Text('ساخت'),
757 ),
758 ],
759 ),
760 );
761 name.dispose();
762 if (created == true && mounted) setState(() => data = load());
763 }
764
765 Future<void> invite(String familyId) async {
766 final email = TextEditingController();
767 final choice = ValueNotifier<String>('daughter');
768 final sent = await showDialog<bool>(
769 context: context,
770 builder: (dialogContext) => AlertDialog(
771 title: const Text('دعوت فرزند / عضو'),
772 content: Column(mainAxisSize: MainAxisSize.min, children: [
773 TextField(
774 controller: email,
775 keyboardType: TextInputType.emailAddress,
776 decoration: const InputDecoration(labelText: 'ایمیل')),
777 const SizedBox(height: 12),
778 ValueListenableBuilder<String>(
779 valueListenable: choice,
780 builder: (_, value, __) => DropdownButtonFormField<String>(
781 initialValue: value,
782 decoration: const InputDecoration(labelText: 'نوع عضو'),
783 items: const [
784 DropdownMenuItem(
785 value: 'daughter', child: Text('فرزند دختر — سفید / صورتی')),
786 DropdownMenuItem(
787 value: 'son', child: Text('فرزند پسر — سفید / آبی')),
788 DropdownMenuItem(
789 value: 'parent', child: Text('والد / سرپرست — سفید / آبی')),
790 DropdownMenuItem(
791 value: 'adult', child: Text('عضو بزرگسال — سفید / آبی')),
792 ],
793 onChanged: (v) {
794 if (v != null) choice.value = v;
795 },
796 ),
797 ),
798 ]),
799 actions: [
800 TextButton(
801 onPressed: () => Navigator.pop(dialogContext, false),
802 child: const Text('انصراف')),
803 FilledButton(
804 onPressed: () async {
805 final selected = choice.value;
806 final role = selected == 'parent'
807 ? 'parent_guardian'
808 : selected == 'adult'
809 ? 'adult_member'
810 : 'teen_minor';
811 final theme = selected == 'daughter'
812 ? 'girl_pink'
813 : selected == 'son'
814 ? 'boy_blue'
815 : 'adult_blue';
816 await widget.api.inviteMember(
817 familyId: familyId,
818 email: email.text,
819 role: role,
820 themePreference: theme);
821 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
822 },
823 child: const Text('ارسال دعوت'),
824 ),
825 ],
826 ),
827 );
828 email.dispose();
829 choice.dispose();
830 if (sent == true && mounted) {
831 ScaffoldMessenger.of(context)
832 .showSnackBar(const SnackBar(content: Text('دعوت ارسال شد.')));
833 }
834 }
835
836 @override
837 Widget build(BuildContext context) => Scaffold(
838 appBar: AppBar(title: const Text('پروفایل و خانواده')),
839 body: FutureBuilder<List<dynamic>>(
840 future: data,
841 builder: (context, snapshot) {
842 if (snapshot.hasError) {
843 return Center(child: Text(errorText(snapshot.error!)));
844 }
845 if (!snapshot.hasData) {
846 return const Center(child: CircularProgressIndicator());
847 }
848 final profile = snapshot.data![0] as Map<String, dynamic>;
849 final families = snapshot.data![1] as List<Map<String, dynamic>>;
850 return ListView(
851 padding: const EdgeInsets.all(20),
852 children: [
853 Card(
854 child: ListTile(
855 leading: const CircleAvatar(child: Icon(Icons.person)),
856 title: Text(
857 profile['display_name']?.toString() ?? 'پروفایل من'),
858 subtitle:
859 Text(profile['email_normalized']?.toString() ?? ''),
860 trailing: IconButton(
861 onPressed: () => editProfile(profile),
862 icon: const Icon(Icons.edit_outlined)),
863 ),
864 ),
865 const SizedBox(height: 12),
866 if (families.isEmpty)
867 Card(
868 child: ListTile(
869 leading: const Icon(Icons.family_restroom),
870 title: const Text('هنوز فضای خانواده ساخته نشده'),
871 trailing: IconButton(
872 onPressed: createFamily,
873 icon: const Icon(Icons.add)),
874 ),
875 )
876 else
877 ...families.map((family) => Card(
878 child: ListTile(
879 leading: const Icon(Icons.family_restroom),
880 title:
881 Text(family['name']?.toString() ?? 'خانواده'),
882 subtitle: Text(
883 '${family['is_admin'] == true ? 'مدیر خانواده · ' : ''}${family['role'] ?? ''}'),
884 onTap: () => Navigator.of(context).push(
885 MaterialPageRoute(
886 builder: (_) => FamilyMembersPage(
887 api: widget.api,
888 familyId: family['id'].toString(),
889 familyName:
890 family['name']?.toString() ?? 'خانواده',
891 isAdmin: family['is_admin'] == true,
892 ),
893 ),
894 ),
895 trailing: IconButton(
896 onPressed: () => invite(family['id'].toString()),
897 icon: const Icon(Icons.person_add_alt)),
898 ),
899 )),
900 ListTile(
901 leading: const Icon(Icons.password),
902 title: const Text('تغییر رمز عبور'),
903 onTap: () => Navigator.of(context).push(MaterialPageRoute(
904 builder: (_) => ChangePasswordPage(api: widget.api))),
905 ),
906 const ListTile(
907 leading: Icon(Icons.privacy_tip_outlined),
908 title: Text('حریم خصوصی و دسترسی‌ها'),
909 subtitle:
910 Text('خصوصی، اعضای منتخب، والد/سرپرست، خانواده، ایمنی'),
911 ),
912 ],
913 );
914 },
915 ),
916 floatingActionButton: FloatingActionButton.extended(
917 onPressed: createFamily,
918 icon: const Icon(Icons.add),
919 label: const Text('خانواده')),
920 );
921 }
922
923 class FamilyMembersPage extends StatefulWidget {
924 const FamilyMembersPage({
925 super.key,
926 required this.api,
927 required this.familyId,
928 required this.familyName,
929 required this.isAdmin,
930 });
931 final IdentityApi api;
932 final String familyId;
933 final String familyName;
934 final bool isAdmin;
935 @override
936 State<FamilyMembersPage> createState() => _FamilyMembersPageState();
937 }
938
939 class _FamilyMembersPageState extends State<FamilyMembersPage> {
940 late Future<List<Map<String, dynamic>>> members;
941 @override
942 void initState() {
943 super.initState();
944 members = widget.api.listFamilyMembers(widget.familyId);
945 }
946
947 String roleLabel(String role) => switch (role) {
948 'parent_guardian' => 'والد / سرپرست',
949 'teen_minor' => 'فرزند / نوجوان',
950 'adult_member' => 'عضو بزرگسال',
951 _ => role,
952 };
953
954 Future<void> configureGuardian(List<Map<String, dynamic>> items) async {
955 final guardians =
956 items.where((m) => m['role'] == 'parent_guardian').toList();
957 final minors = items.where((m) => m['role'] == 'teen_minor').toList();
958 if (guardians.isEmpty || minors.isEmpty) {
959 ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
960 content: Text('برای ثبت سرپرستی، حداقل یک والد و یک فرزند لازم است.')));
961 return;
962 }
963 final guardianId =
964 ValueNotifier<String>(guardians.first['user_id'].toString());
965 final minorId = ValueNotifier<String>(minors.first['user_id'].toString());
966 final saved = await showDialog<bool>(
967 context: context,
968 builder: (dialogContext) => AlertDialog(
969 title: const Text('رابطه والد و فرزند'),
970 content: Column(mainAxisSize: MainAxisSize.min, children: [
971 ValueListenableBuilder<String>(
972 valueListenable: guardianId,
973 builder: (_, value, __) => DropdownButtonFormField<String>(
974 initialValue: value,
975 decoration: const InputDecoration(labelText: 'والد / سرپرست'),
976 items: guardians
977 .map((m) => DropdownMenuItem(
978 value: m['user_id'].toString(),
979 child: Text(m['display_name']?.toString() ?? 'والد')))
980 .toList(),
981 onChanged: (v) {
982 if (v != null) guardianId.value = v;
983 },
984 ),
985 ),
986 const SizedBox(height: 12),
987 ValueListenableBuilder<String>(
988 valueListenable: minorId,
989 builder: (_, value, __) => DropdownButtonFormField<String>(
990 initialValue: value,
991 decoration: const InputDecoration(labelText: 'فرزند'),
992 items: minors
993 .map((m) => DropdownMenuItem(
994 value: m['user_id'].toString(),
995 child: Text(m['display_name']?.toString() ?? 'فرزند')))
996 .toList(),
997 onChanged: (v) {
998 if (v != null) minorId.value = v;
999 },
1000 ),
1001 ),
1002 ]),
1003 actions: [
1004 TextButton(
1005 onPressed: () => Navigator.pop(dialogContext, false),
1006 child: const Text('انصراف')),
1007 FilledButton(
1008 onPressed: () async {
1009 await widget.api.setGuardian(
1010 familyId: widget.familyId,
1011 guardianUserId: guardianId.value,
1012 minorUserId: minorId.value);
1013 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
1014 },
1015 child: const Text('ثبت رابطه'),
1016 ),
1017 ],
1018 ),
1019 );
1020 guardianId.dispose();
1021 minorId.dispose();
1022 if (saved == true && mounted) {
1023 ScaffoldMessenger.of(context).showSnackBar(
1024 const SnackBar(content: Text('رابطه سرپرستی ثبت شد.')));
1025 }
1026 }
1027
1028 @override
1029 Widget build(BuildContext context) => Scaffold(
1030 appBar: AppBar(title: Text(widget.familyName)),
1031 body: FutureBuilder<List<Map<String, dynamic>>>(
1032 future: members,
1033 builder: (context, snapshot) {
1034 if (snapshot.hasError) {
1035 return Center(child: Text(errorText(snapshot.error!)));
1036 }
1037 if (!snapshot.hasData) {
1038 return const Center(child: CircularProgressIndicator());
1039 }
1040 final items = snapshot.data!;
1041 return ListView(
1042 padding: const EdgeInsets.all(20),
1043 children: [
1044 for (final member in items)
1045 Card(
1046 child: ListTile(
1047 leading: const CircleAvatar(child: Icon(Icons.person)),
1048 title:
1049 Text(member['display_name']?.toString() ?? 'عضو'),
1050 subtitle:
1051 Text(roleLabel(member['role']?.toString() ?? '')),
1052 trailing: member['is_admin'] == true
1053 ? const Chip(label: Text('مدیر'))
1054 : null,
1055 ),
1056 ),
1057 if (widget.isAdmin) ...[
1058 const SizedBox(height: 12),
1059 FilledButton.icon(
1060 onPressed: () => configureGuardian(items),
1061 icon: const Icon(Icons.supervisor_account_outlined),
1062 label: const Text('تنظیم رابطه والد و فرزند'),
1063 ),
1064 ],
1065 ],
1066 );
1067 },
1068 ),
1069 );
1070 }