LifeMate — Personal, Family & Learning Companion

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