LifeMate — Personal, Family & Learning Companion

phase-2/product-foundation-identity
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
6 void main() => runApp(LifeMateApp());
7
8 class LifeMateApp extends StatelessWidget {
9 LifeMateApp({super.key, IdentityApi? api}) : api = api ?? HttpIdentityApi();
10 final IdentityApi api;
11
12 @override
13 Widget build(BuildContext context) {
14 final uri = Uri.base;
15 final token = uri.queryParameters['token'];
16 Widget entry = SignInPage(
17 api: api,
18 invitationToken:
19 token != null && uri.path.contains('accept-invitation') ? token : null,
20 );
21 if (token != null && uri.path.contains('verify-email')) {
22 entry = VerifyEmailPage(api: api, token: token);
23 } else if (token != null && uri.path.contains('reset-password')) {
24 entry = ResetPasswordPage(api: api, token: token);
25 }
26 return MaterialApp(
27 debugShowCheckedModeBanner: false,
28 locale: const Locale('fa'),
29 supportedLocales: const [Locale('fa'), Locale('en')],
30 localizationsDelegates: const [
31 GlobalMaterialLocalizations.delegate,
32 GlobalWidgetsLocalizations.delegate,
33 GlobalCupertinoLocalizations.delegate,
34 ],
35 theme: ThemeData(
36 colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF4D86E8)),
37 scaffoldBackgroundColor: const Color(0xFFF8FAFD),
38 inputDecorationTheme:
39 const InputDecorationTheme(border: OutlineInputBorder()),
40 useMaterial3: true,
41 ),
42 home: Directionality(textDirection: TextDirection.rtl, child: entry),
43 );
44 }
45 }
46
47 String errorText(Object error) {
48 if (error is ApiException) {
49 switch (error.code) {
50 case 'invalid_credentials':
51 return 'ایمیل یا رمز عبور صحیح نیست.';
52 case 'email_not_verified':
53 return 'ابتدا ایمیل حساب را تأیید کن.';
54 case 'account_exists':
55 return 'برای این ایمیل قبلاً حساب ساخته شده است.';
56 case 'invalid_password':
57 return 'رمز عبور باید حداقل ۱۰ کاراکتر باشد.';
58 case 'invalid_current_password':
59 return 'رمز فعلی صحیح نیست.';
60 case 'invalid_or_expired_token':
61 return 'لینک منقضی شده یا معتبر نیست.';
62 case 'forbidden':
63 return 'برای این عملیات دسترسی نداری.';
64 }
65 }
66 return 'عملیات انجام نشد. دوباره تلاش کن.';
67 }
68
69 class SignInPage extends StatefulWidget {
70 const SignInPage({super.key, required this.api, this.invitationToken});
71 final IdentityApi api;
72 final String? invitationToken;
73 @override
74 State<SignInPage> createState() => _SignInPageState();
75 }
76
77 class _SignInPageState extends State<SignInPage> {
78 final email = TextEditingController();
79 final password = TextEditingController();
80 bool busy = false;
81 String? error;
82
83 Future<void> submit() async {
84 setState(() {
85 busy = true;
86 error = null;
87 });
88 try {
89 await widget.api.login(email.text, password.text);
90 if (widget.invitationToken != null) {
91 await widget.api.acceptInvitation(widget.invitationToken!);
92 }
93 if (!mounted) return;
94 Navigator.of(context).pushReplacement(
95 MaterialPageRoute(builder: (_) => HomeShell(api: widget.api)),
96 );
97 } catch (e) {
98 if (mounted) setState(() => error = errorText(e));
99 } finally {
100 if (mounted) setState(() => busy = false);
101 }
102 }
103
104 @override
105 Widget build(BuildContext context) => Scaffold(
106 body: SafeArea(
107 child: Center(
108 child: ConstrainedBox(
109 constraints: const BoxConstraints(maxWidth: 440),
110 child: ListView(
111 padding: const EdgeInsets.all(28),
112 shrinkWrap: true,
113 children: [
114 const Icon(Icons.route_rounded, size: 64),
115 const SizedBox(height: 16),
116 const Text('LifeMate',
117 textAlign: TextAlign.center,
118 style:
119 TextStyle(fontSize: 32, fontWeight: FontWeight.w700)),
120 const Text('همراه شخصی، تحصیلی و خانوادگی',
121 textAlign: TextAlign.center),
122 const SizedBox(height: 28),
123 if (widget.invitationToken != null) ...[
124 const Card(
125 child: Padding(
126 padding: EdgeInsets.all(12),
127 child: Text(
128 'برای قبول دعوت خانواده، با همان ایمیل دعوت‌شده وارد شو.'),
129 ),
130 ),
131 const SizedBox(height: 12),
132 ],
133 TextField(
134 controller: email,
135 keyboardType: TextInputType.emailAddress,
136 decoration: const InputDecoration(labelText: 'ایمیل'),
137 ),
138 const SizedBox(height: 12),
139 TextField(
140 controller: password,
141 obscureText: true,
142 decoration: const InputDecoration(labelText: 'رمز عبور'),
143 ),
144 if (error != null) ...[
145 const SizedBox(height: 12),
146 Text(error!,
147 style: TextStyle(
148 color: Theme.of(context).colorScheme.error)),
149 ],
150 const SizedBox(height: 16),
151 FilledButton(
152 onPressed: busy ? null : submit,
153 child: Text(busy ? 'در حال ورود...' : 'ورود'),
154 ),
155 TextButton(
156 onPressed: busy
157 ? null
158 : () => Navigator.of(context).push(MaterialPageRoute(
159 builder: (_) => RecoveryPage(api: widget.api))),
160 child: const Text('رمز عبور را فراموش کرده‌ام'),
161 ),
162 TextButton(
163 onPressed: busy
164 ? null
165 : () => Navigator.of(context).push(MaterialPageRoute(
166 builder: (_) => RegistrationPage(api: widget.api))),
167 child: const Text('ساخت حساب جدید'),
168 ),
169 ],
170 ),
171 ),
172 ),
173 ),
174 );
175 }
176
177 class RegistrationPage extends StatefulWidget {
178 const RegistrationPage({super.key, required this.api});
179 final IdentityApi api;
180 @override
181 State<RegistrationPage> createState() => _RegistrationPageState();
182 }
183
184 class _RegistrationPageState extends State<RegistrationPage> {
185 final name = TextEditingController();
186 final email = TextEditingController();
187 final password = TextEditingController();
188 final confirm = TextEditingController();
189 bool busy = false;
190 String? error;
191
192 Future<void> submit() async {
193 if (password.text != confirm.text) {
194 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
195 return;
196 }
197 setState(() {
198 busy = true;
199 error = null;
200 });
201 try {
202 await widget.api.register(
203 displayName: name.text, email: email.text, password: password.text);
204 if (!mounted) return;
205 ScaffoldMessenger.of(context).showSnackBar(
206 const SnackBar(content: Text('حساب ساخته شد. ایمیل تأیید را بررسی کن.')),
207 );
208 Navigator.pop(context);
209 } catch (e) {
210 if (mounted) setState(() => error = errorText(e));
211 } finally {
212 if (mounted) setState(() => busy = false);
213 }
214 }
215
216 @override
217 Widget build(BuildContext context) => SimpleFormPage(
218 title: 'ساخت حساب',
219 busy: busy,
220 error: error,
221 action: 'ثبت‌نام و ارسال ایمیل تأیید',
222 onPressed: submit,
223 fields: [
224 TextField(
225 controller: name,
226 decoration: const InputDecoration(labelText: 'نام')),
227 TextField(
228 controller: email,
229 keyboardType: TextInputType.emailAddress,
230 decoration: const InputDecoration(labelText: 'ایمیل')),
231 TextField(
232 controller: password,
233 obscureText: true,
234 decoration: const InputDecoration(labelText: 'رمز عبور')),
235 TextField(
236 controller: confirm,
237 obscureText: true,
238 decoration: const InputDecoration(labelText: 'تکرار رمز عبور')),
239 ],
240 );
241 }
242
243 class RecoveryPage extends StatefulWidget {
244 const RecoveryPage({super.key, required this.api});
245 final IdentityApi api;
246 @override
247 State<RecoveryPage> createState() => _RecoveryPageState();
248 }
249
250 class _RecoveryPageState extends State<RecoveryPage> {
251 final email = TextEditingController();
252 bool busy = false;
253 bool sent = false;
254 String? error;
255
256 Future<void> submit() async {
257 setState(() {
258 busy = true;
259 error = null;
260 });
261 try {
262 await widget.api.forgotPassword(email.text);
263 if (mounted) setState(() => sent = true);
264 } catch (e) {
265 if (mounted) setState(() => error = errorText(e));
266 } finally {
267 if (mounted) setState(() => busy = false);
268 }
269 }
270
271 @override
272 Widget build(BuildContext context) => SimpleFormPage(
273 title: 'بازیابی رمز عبور',
274 busy: busy,
275 error: error,
276 action: sent ? 'لینک ارسال شد' : 'ارسال لینک بازیابی',
277 onPressed: sent ? null : submit,
278 fields: [
279 TextField(
280 controller: email,
281 keyboardType: TextInputType.emailAddress,
282 decoration: const InputDecoration(labelText: 'ایمیل تأییدشده')),
283 if (sent)
284 const Text(
285 'اگر حسابی با این ایمیل وجود داشته باشد، لینک بازیابی ارسال می‌شود.'),
286 ],
287 );
288 }
289
290 class VerifyEmailPage extends StatefulWidget {
291 const VerifyEmailPage({super.key, required this.api, required this.token});
292 final IdentityApi api;
293 final String token;
294 @override
295 State<VerifyEmailPage> createState() => _VerifyEmailPageState();
296 }
297
298 class _VerifyEmailPageState extends State<VerifyEmailPage> {
299 String message = 'در حال تأیید ایمیل...';
300 @override
301 void initState() {
302 super.initState();
303 verify();
304 }
305
306 Future<void> verify() async {
307 try {
308 await widget.api.verifyEmail(widget.token);
309 if (mounted) setState(() => message = 'ایمیل با موفقیت تأیید شد.');
310 } catch (e) {
311 if (mounted) setState(() => message = errorText(e));
312 }
313 }
314
315 @override
316 Widget build(BuildContext context) =>
317 Scaffold(body: Center(child: Text(message)));
318 }
319
320 class ResetPasswordPage extends StatefulWidget {
321 const ResetPasswordPage({super.key, required this.api, required this.token});
322 final IdentityApi api;
323 final String token;
324 @override
325 State<ResetPasswordPage> createState() => _ResetPasswordPageState();
326 }
327
328 class _ResetPasswordPageState extends State<ResetPasswordPage> {
329 final password = TextEditingController();
330 final confirm = TextEditingController();
331 bool busy = false;
332 bool done = false;
333 String? error;
334
335 Future<void> submit() async {
336 if (password.text != confirm.text) {
337 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
338 return;
339 }
340 setState(() {
341 busy = true;
342 error = null;
343 });
344 try {
345 await widget.api.resetPassword(widget.token, password.text);
346 if (mounted) setState(() => done = true);
347 } catch (e) {
348 if (mounted) setState(() => error = errorText(e));
349 } finally {
350 if (mounted) setState(() => busy = false);
351 }
352 }
353
354 @override
355 Widget build(BuildContext context) => SimpleFormPage(
356 title: 'ساخت رمز جدید',
357 busy: busy,
358 error: error,
359 action: done ? 'رمز تغییر کرد' : 'ذخیره رمز جدید',
360 onPressed: done ? null : submit,
361 fields: [
362 TextField(
363 controller: password,
364 obscureText: true,
365 decoration: const InputDecoration(labelText: 'رمز جدید')),
366 TextField(
367 controller: confirm,
368 obscureText: true,
369 decoration: const InputDecoration(labelText: 'تکرار رمز جدید')),
370 ],
371 );
372 }
373
374 class ChangePasswordPage extends StatefulWidget {
375 const ChangePasswordPage({super.key, required this.api});
376 final IdentityApi api;
377 @override
378 State<ChangePasswordPage> createState() => _ChangePasswordPageState();
379 }
380
381 class _ChangePasswordPageState extends State<ChangePasswordPage> {
382 final current = TextEditingController();
383 final next = TextEditingController();
384 final confirm = TextEditingController();
385 bool busy = false;
386 String? error;
387
388 Future<void> submit() async {
389 if (next.text != confirm.text) {
390 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
391 return;
392 }
393 setState(() {
394 busy = true;
395 error = null;
396 });
397 try {
398 await widget.api.changePassword(current.text, next.text);
399 if (!mounted) return;
400 ScaffoldMessenger.of(context)
401 .showSnackBar(const SnackBar(content: Text('رمز عبور تغییر کرد.')));
402 Navigator.pop(context);
403 } catch (e) {
404 if (mounted) setState(() => error = errorText(e));
405 } finally {
406 if (mounted) setState(() => busy = false);
407 }
408 }
409
410 @override
411 Widget build(BuildContext context) => SimpleFormPage(
412 title: 'تغییر رمز عبور',
413 busy: busy,
414 error: error,
415 action: 'ذخیره رمز جدید',
416 onPressed: submit,
417 fields: [
418 TextField(
419 controller: current,
420 obscureText: true,
421 decoration: const InputDecoration(labelText: 'رمز فعلی')),
422 TextField(
423 controller: next,
424 obscureText: true,
425 decoration: const InputDecoration(labelText: 'رمز جدید')),
426 TextField(
427 controller: confirm,
428 obscureText: true,
429 decoration: const InputDecoration(labelText: 'تکرار رمز جدید')),
430 ],
431 );
432 }
433
434 class SimpleFormPage extends StatelessWidget {
435 const SimpleFormPage({
436 super.key,
437 required this.title,
438 required this.fields,
439 required this.action,
440 required this.onPressed,
441 this.busy = false,
442 this.error,
443 });
444 final String title;
445 final List<Widget> fields;
446 final String action;
447 final VoidCallback? onPressed;
448 final bool busy;
449 final String? error;
450
451 @override
452 Widget build(BuildContext context) => Scaffold(
453 appBar: AppBar(title: Text(title)),
454 body: Center(
455 child: ConstrainedBox(
456 constraints: const BoxConstraints(maxWidth: 520),
457 child: ListView(
458 padding: const EdgeInsets.all(24),
459 children: [
460 for (final field in fields)
461 Padding(
462 padding: const EdgeInsets.only(bottom: 12), child: field),
463 if (error != null)
464 Padding(
465 padding: const EdgeInsets.only(bottom: 12),
466 child: Text(error!,
467 style: TextStyle(
468 color: Theme.of(context).colorScheme.error)),
469 ),
470 FilledButton(
471 onPressed: busy ? null : onPressed,
472 child: Text(busy ? 'لطفاً صبر کن...' : action)),
473 ],
474 ),
475 ),
476 ),
477 );
478 }
479
480 class HomeShell extends StatefulWidget {
481 const HomeShell({super.key, required this.api});
482 final IdentityApi api;
483
484 @override
485 State<HomeShell> createState() => _HomeShellState();
486 }
487
488 class _HomeShellState extends State<HomeShell> {
489 int index = 0;
490 String themePreference = 'adult_blue';
491 bool adultShell = false;
492
493 static const studentPages = [
494 'امروز',
495 'برنامه هفتگی',
496 'تقویم',
497 'تکالیف و کارها',
498 'امتحان‌ها و نمرات',
499 'تمرکز',
500 'همراه هوشمند',
501 ];
502
503 static const adultPages = [
504 'امروز',
505 'برنامه‌ریز',
506 'خانواده',
507 'راهنما',
508 'من',
509 ];
510
511 @override
512 void initState() {
513 super.initState();
514 loadContext();
515 }
516
517 Future<void> loadContext() async {
518 try {
519 final profile = await widget.api.getProfile();
520 final families = await widget.api.listFamilies();
521 final hasAdultRole = families.any(
522 (family) =>
523 family['role'] == 'parent_guardian' ||
524 family['role'] == 'adult_member',
525 );
526 if (mounted) {
527 setState(() {
528 themePreference =
529 profile['theme_preference']?.toString() ?? 'adult_blue';
530 adultShell = hasAdultRole;
531 index = 0;
532 });
533 }
534 } catch (_) {}
535 }
536
537 List<String> get pages => adultShell ? adultPages : studentPages;
538
539 Color get accent => themePreference == 'girl_pink'
540 ? const Color(0xFFE58FB0)
541 : const Color(0xFF4D86E8);
542
543 List<NavigationDestination> get destinations => adultShell
544 ? const [
545 NavigationDestination(
546 icon: Icon(Icons.home_outlined),
547 label: 'امروز',
548 ),
549 NavigationDestination(
550 icon: Icon(Icons.event_note_outlined),
551 label: 'برنامه‌ریز',
552 ),
553 NavigationDestination(
554 icon: Icon(Icons.family_restroom_outlined),
555 label: 'خانواده',
556 ),
557 NavigationDestination(
558 icon: Icon(Icons.assistant_outlined),
559 label: 'راهنما',
560 ),
561 NavigationDestination(
562 icon: Icon(Icons.person_outline),
563 label: 'من',
564 ),
565 ]
566 : const [
567 NavigationDestination(
568 icon: Icon(Icons.home_outlined),
569 label: 'امروز',
570 ),
571 NavigationDestination(
572 icon: Icon(Icons.schedule_outlined),
573 label: 'برنامه',
574 ),
575 NavigationDestination(
576 icon: Icon(Icons.calendar_month_outlined),
577 label: 'تقویم',
578 ),
579 NavigationDestination(
580 icon: Icon(Icons.task_alt_outlined),
581 label: 'کارها',
582 ),
583 NavigationDestination(
584 icon: Icon(Icons.school_outlined),
585 label: 'امتحان‌ها',
586 ),
587 ];
588
589 void selectPage(int next) {
590 setState(() => index = next);
591 }
592
593 @override
594 Widget build(BuildContext context) => Theme(
595 data: Theme.of(context).copyWith(
596 colorScheme: ColorScheme.fromSeed(seedColor: accent),
597 scaffoldBackgroundColor: Colors.white,
598 ),
599 child: Scaffold(
600 appBar: AppBar(
601 title: Text(pages[index]),
602 actions: [
603 IconButton(
604 onPressed: () => Navigator.of(context).push(
605 MaterialPageRoute(
606 builder: (_) => ProfileFamilyPage(api: widget.api),
607 ),
608 ),
609 icon: const Icon(Icons.person_outline),
610 ),
611 ],
612 ),
613 body: Center(
614 child: Text(
615 pages[index],
616 style: Theme.of(context).textTheme.headlineMedium,
617 ),
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 }