LifeMate — Personal, Family & Learning Companion

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