@davoodmehraban89 / LifeMate / commits / 8af7b70
Fork 0

LifeMate — Personal, Family & Learning Companion

fix: connect local planner and profile UI to durable records

Codex committed Oct 8, 2026 at 05:24 UTC 8af7b705ce95b55cea3be9ac8147bc7d47687738
7 files changed +2150 -626
apps/lifemate/analysis_options.yaml
+5
@@ -1,3 +1,8 @@
1 +analyzer:
2 + exclude:
3 + - build/**
4 + - android/**
5 + - web/**
6 include: package:flutter_lints/flutter.yaml
7 linter:
8 rules:
apps/lifemate/lib/main.dart
+378 -166
@@ -18,8 +18,9 @@ class LifeMateApp extends StatelessWidget {
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,
21 + invitationToken: token != null && uri.path.contains('accept-invitation')
22 + ? token
23 + : null,
24 );
25 if (token != null && uri.path.contains('verify-email')) {
26 entry = VerifyEmailPage(api: api, token: token);
@@ -206,7 +207,8 @@ class _RegistrationPageState extends State<RegistrationPage> {
207 displayName: name.text, email: email.text, password: password.text);
208 if (!mounted) return;
209 ScaffoldMessenger.of(context).showSnackBar(
209 - const SnackBar(content: Text('حساب ساخته شد. ایمیل تأیید را بررسی کن.')),
210 + const SnackBar(
211 + content: Text('حساب ساخته شد. ایمیل تأیید را بررسی کن.')),
212 );
213 Navigator.pop(context);
214 } catch (e) {
@@ -234,7 +236,8 @@ class _RegistrationPageState extends State<RegistrationPage> {
236 TextField(
237 controller: password,
238 obscureText: true,
237 - decoration: const InputDecoration(labelText: 'رمز عبور')),
239 + decoration: const InputDecoration(
240 + labelText: 'رمز عبور', helperText: 'حداقل ۱۰ کاراکتر')),
241 TextField(
242 controller: confirm,
243 obscureText: true,
@@ -481,8 +484,15 @@ class SimpleFormPage extends StatelessWidget {
484 }
485
486 class HomeShell extends StatefulWidget {
484 - const HomeShell({super.key, required this.api});
487 + const HomeShell({
488 + super.key,
489 + required this.api,
490 + this.localOnly = false,
491 + this.profileCategory,
492 + });
493 final IdentityApi api;
494 + final bool localOnly;
495 + final String? profileCategory;
496
497 @override
498 State<HomeShell> createState() => _HomeShellState();
@@ -492,6 +502,8 @@ class _HomeShellState extends State<HomeShell> {
502 int index = 0;
503 String themePreference = 'adult_blue';
504 bool adultShell = false;
505 + String displayName = '';
506 + String? contextError;
507
508 static const studentPages = [
509 'امروز',
@@ -514,85 +526,140 @@ class _HomeShellState extends State<HomeShell> {
526 @override
527 void initState() {
528 super.initState();
529 + adultShell = widget.profileCategory == 'adult';
530 loadContext();
531 }
532
533 Future<void> loadContext() async {
534 try {
535 final profile = await widget.api.getProfile();
523 - final families = await widget.api.listFamilies();
524 - final hasAdultRole = families.any(
525 - (family) =>
536 + final category = widget.profileCategory ?? profile['profile_category'];
537 + var hasAdultRole = category == 'adult';
538 + if (category != 'adult' &&
539 + category != 'girl_minor' &&
540 + category != 'boy_minor' &&
541 + !widget.localOnly) {
542 + final families = await widget.api.listFamilies();
543 + hasAdultRole = families.any((family) =>
544 family['role'] == 'parent_guardian' ||
527 - family['role'] == 'adult_member',
528 - );
545 + family['role'] == 'adult_member');
546 + }
547 if (mounted) {
548 setState(() {
549 themePreference =
550 profile['theme_preference']?.toString() ?? 'adult_blue';
551 + displayName = profile['display_name']?.toString() ?? '';
552 adultShell = hasAdultRole;
534 - index = 0;
553 + if (index >= pages.length) index = pages.length - 1;
554 + contextError = null;
555 });
556 }
537 - } catch (_) {}
557 + } catch (error) {
558 + if (mounted && widget.localOnly) {
559 + setState(() => contextError = localDataErrorText(error));
560 + }
561 + }
562 }
563
540 - List<String> get pages => adultShell ? adultPages : studentPages;
564 + List<String> get pages => widget.localOnly
565 + ? ['امروز', adultShell ? 'برنامه‌ریز' : 'برنامه هفتگی', 'من']
566 + : adultShell
567 + ? adultPages
568 + : studentPages;
569
570 Color get accent => themePreference == 'girl_pink'
571 ? const Color(0xFFE58FB0)
572 : const Color(0xFF4D86E8);
573
546 - List<NavigationDestination> get destinations => adultShell
547 - ? const [
548 - NavigationDestination(
549 - icon: Icon(Icons.home_outlined),
550 - label: 'امروز',
551 - ),
574 + List<NavigationDestination> get destinations => widget.localOnly
575 + ? [
576 + const NavigationDestination(
577 + icon: Icon(Icons.home_outlined), label: 'امروز'),
578 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 - ),
579 + icon: const Icon(Icons.event_note_outlined),
580 + label: adultShell ? 'برنامه‌ریز' : 'برنامه'),
581 + const NavigationDestination(
582 + icon: Icon(Icons.person_outline), label: 'من'),
583 ]
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 - ];
584 + : adultShell
585 + ? const [
586 + NavigationDestination(
587 + icon: Icon(Icons.home_outlined),
588 + label: 'امروز',
589 + ),
590 + NavigationDestination(
591 + icon: Icon(Icons.event_note_outlined),
592 + label: 'برنامه‌ریز',
593 + ),
594 + NavigationDestination(
595 + icon: Icon(Icons.family_restroom_outlined),
596 + label: 'خانواده',
597 + ),
598 + NavigationDestination(
599 + icon: Icon(Icons.assistant_outlined),
600 + label: 'راهنما',
601 + ),
602 + NavigationDestination(
603 + icon: Icon(Icons.person_outline),
604 + label: 'من',
605 + ),
606 + ]
607 + : const [
608 + NavigationDestination(
609 + icon: Icon(Icons.home_outlined),
610 + label: 'امروز',
611 + ),
612 + NavigationDestination(
613 + icon: Icon(Icons.schedule_outlined),
614 + label: 'برنامه',
615 + ),
616 + NavigationDestination(
617 + icon: Icon(Icons.calendar_month_outlined),
618 + label: 'تقویم',
619 + ),
620 + NavigationDestination(
621 + icon: Icon(Icons.task_alt_outlined),
622 + label: 'کارها',
623 + ),
624 + NavigationDestination(
625 + icon: Icon(Icons.school_outlined),
626 + label: 'امتحان‌ها',
627 + ),
628 + ];
629
630 void selectPage(int next) {
631 setState(() => index = next);
632 }
633
634 + Future<void> openProfile() async {
635 + await Navigator.of(context).push(MaterialPageRoute(
636 + builder: (_) =>
637 + ProfileFamilyPage(api: widget.api, localOnly: widget.localOnly),
638 + ));
639 + if (mounted) await loadContext();
640 + }
641 +
642 + Widget get content {
643 + if (pages[index] == 'من') {
644 + return ProfileFamilyPage(
645 + api: widget.api,
646 + localOnly: widget.localOnly,
647 + showAppBar: false,
648 + onProfileUpdated: loadContext,
649 + );
650 + }
651 + if (!widget.localOnly &&
652 + (pages[index] == 'همراه هوشمند' || pages[index] == 'راهنما')) {
653 + return Phase4Hub(api: widget.api, adultShell: adultShell);
654 + }
655 + return Phase3HomeContent(
656 + api: widget.api,
657 + page: pages[index],
658 + adultShell: adultShell,
659 + localOnly: widget.localOnly,
660 + );
661 + }
662 +
663 @override
664 Widget build(BuildContext context) => Theme(
665 data: Theme.of(context).copyWith(
@@ -601,61 +668,69 @@ class _HomeShellState extends State<HomeShell> {
668 ),
669 child: Scaffold(
670 appBar: AppBar(
604 - title: Text(pages[index]),
671 + title: Column(
672 + crossAxisAlignment: CrossAxisAlignment.start,
673 + children: [
674 + Text(pages[index]),
675 + if (widget.localOnly && displayName.isNotEmpty)
676 + Text(displayName,
677 + style: Theme.of(context).textTheme.bodySmall),
678 + ],
679 + ),
680 actions: [
681 IconButton(
607 - onPressed: () => Navigator.of(context).push(
608 - MaterialPageRoute(
609 - builder: (_) => ProfileFamilyPage(api: widget.api),
610 - ),
611 - ),
682 + tooltip: 'پروفایل',
683 + onPressed: openProfile,
684 icon: const Icon(Icons.person_outline),
685 ),
686 ],
687 ),
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 - ),
688 + body: widget.localOnly
689 + ? Column(children: [
690 + const Padding(
691 + padding: EdgeInsets.symmetric(horizontal: 16),
692 + child: LocalDataNotice()),
693 + if (contextError != null)
694 + Padding(
695 + padding: const EdgeInsets.symmetric(horizontal: 16),
696 + child: Row(children: [
697 + Expanded(child: Text(contextError!)),
698 + TextButton(
699 + onPressed: loadContext,
700 + child: const Text('تلاش دوباره')),
701 + ]),
702 + ),
703 + Expanded(child: content),
704 + ])
705 + : content,
706 bottomNavigationBar: NavigationBar(
624 - selectedIndex: index > 4 ? 0 : index,
707 + selectedIndex: index >= destinations.length ? 0 : index,
708 onDestinationSelected: selectPage,
709 destinations: destinations,
710 ),
711 drawer: Drawer(
712 child: SafeArea(
630 - child: ListView(
631 - children: [
632 - const ListTile(
633 - title: Text('LifeMate'),
634 - subtitle: Text('منوی اصلی'),
713 + child: ListView(children: [
714 + const ListTile(
715 + title: Text('LifeMate'), subtitle: Text('منوی اصلی')),
716 + ...pages.asMap().entries.map((entry) => ListTile(
717 + title: Text(entry.value),
718 + onTap: () {
719 + selectPage(entry.key);
720 + Navigator.pop(context);
721 + },
722 + )),
723 + if (widget.localOnly)
724 + const LocalFeaturesNotice()
725 + else if (!adultShell) ...[
726 + const Divider(),
727 + ListTile(
728 + leading: const Icon(Icons.family_restroom),
729 + title: const Text('خانواده'),
730 + onTap: openProfile,
731 ),
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 - ],
732 ],
658 - ),
733 + ]),
734 ),
735 ),
736 ),
@@ -663,8 +738,16 @@ class _HomeShellState extends State<HomeShell> {
738 }
739
740 class ProfileFamilyPage extends StatefulWidget {
666 - const ProfileFamilyPage({super.key, required this.api});
741 + const ProfileFamilyPage(
742 + {super.key,
743 + required this.api,
744 + this.localOnly = false,
745 + this.showAppBar = true,
746 + this.onProfileUpdated});
747 final IdentityApi api;
748 + final bool localOnly;
749 + final bool showAppBar;
750 + final Future<void> Function()? onProfileUpdated;
751 @override
752 State<ProfileFamilyPage> createState() => _ProfileFamilyPageState();
753 }
@@ -677,61 +760,38 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
760 data = load();
761 }
762
680 - Future<List<dynamic>> load() async =>
681 - [await widget.api.getProfile(), await widget.api.listFamilies()];
763 + Future<List<dynamic>> load() async => [
764 + await widget.api.getProfile(),
765 + widget.localOnly
766 + ? <Map<String, dynamic>>[]
767 + : await widget.api.listFamilies(),
768 + ];
769 +
770 + Future<void> retryLoad() async {
771 + setState(() {
772 + data = load();
773 + });
774 + try {
775 + await data;
776 + } catch (_) {}
777 + }
778
779 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');
780 final saved = await showDialog<bool>(
781 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 - ],
782 + barrierDismissible: false,
783 + builder: (_) => _ProfileEditDialog(
784 + api: widget.api,
785 + profile: profile,
786 + localOnly: widget.localOnly,
787 ),
788 );
732 - name.dispose();
733 - theme.dispose();
734 - if (saved == true && mounted) setState(() => data = load());
789 + if (saved == true && mounted) {
790 + setState(() {
791 + data = load();
792 + });
793 + await widget.onProfileUpdated?.call();
794 + }
795 }
796
797 Future<void> createFamily() async {
@@ -760,7 +820,11 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
820 ),
821 );
822 name.dispose();
763 - if (created == true && mounted) setState(() => data = load());
823 + if (created == true && mounted) {
824 + setState(() {
825 + data = load();
826 + });
827 + }
828 }
829
830 Future<void> invite(String familyId) async {
@@ -783,7 +847,8 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
847 decoration: const InputDecoration(labelText: 'نوع عضو'),
848 items: const [
849 DropdownMenuItem(
786 - value: 'daughter', child: Text('فرزند دختر — سفید / صورتی')),
850 + value: 'daughter',
851 + child: Text('فرزند دختر — سفید / صورتی')),
852 DropdownMenuItem(
853 value: 'son', child: Text('فرزند پسر — سفید / آبی')),
854 DropdownMenuItem(
@@ -836,18 +901,56 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
901
902 @override
903 Widget build(BuildContext context) => Scaffold(
839 - appBar: AppBar(title: const Text('پروفایل و خانواده')),
904 + appBar: widget.showAppBar
905 + ? AppBar(
906 + title: Text(
907 + widget.localOnly ? 'پروفایل محلی' : 'پروفایل و خانواده'))
908 + : null,
909 body: FutureBuilder<List<dynamic>>(
910 future: data,
911 builder: (context, snapshot) {
912 if (snapshot.hasError) {
844 - return Center(child: Text(errorText(snapshot.error!)));
913 + return Center(
914 + child: Column(mainAxisSize: MainAxisSize.min, children: [
915 + Text(widget.localOnly
916 + ? localDataErrorText(snapshot.error!)
917 + : errorText(snapshot.error!)),
918 + TextButton(
919 + onPressed: retryLoad, child: const Text('تلاش دوباره')),
920 + ]),
921 + );
922 }
923 if (!snapshot.hasData) {
924 return const Center(child: CircularProgressIndicator());
925 }
926 final profile = snapshot.data![0] as Map<String, dynamic>;
927 final families = snapshot.data![1] as List<Map<String, dynamic>>;
928 + if (widget.localOnly) {
929 + final theme = profile['theme_preference']?.toString();
930 + return ListView(
931 + padding: const EdgeInsets.all(20),
932 + children: [
933 + if (widget.showAppBar) const LocalDataNotice(),
934 + Card(
935 + child: ListTile(
936 + leading: const CircleAvatar(child: Icon(Icons.person)),
937 + title: Text(
938 + profile['display_name']?.toString() ?? 'پروفایل من'),
939 + subtitle: Text(theme == 'girl_pink'
940 + ? 'سفید / صورتی'
941 + : theme == 'boy_blue'
942 + ? 'سفید / آبی نوجوان'
943 + : 'سفید / آبی بزرگسال'),
944 + trailing: IconButton(
945 + tooltip: 'ویرایش پروفایل',
946 + onPressed: () => editProfile(profile),
947 + icon: const Icon(Icons.edit_outlined),
948 + ),
949 + )),
950 + const LocalFeaturesNotice(),
951 + ],
952 + );
953 + }
954 return ListView(
955 padding: const EdgeInsets.all(20),
956 children: [
@@ -870,16 +973,14 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
973 leading: const Icon(Icons.family_restroom),
974 title: const Text('هنوز فضای خانواده ساخته نشده'),
975 trailing: IconButton(
873 - onPressed: createFamily,
874 - icon: const Icon(Icons.add)),
976 + onPressed: createFamily, icon: const Icon(Icons.add)),
977 ),
978 )
979 else
980 ...families.map((family) => Card(
981 child: ListTile(
982 leading: const Icon(Icons.family_restroom),
881 - title:
882 - Text(family['name']?.toString() ?? 'خانواده'),
983 + title: Text(family['name']?.toString() ?? 'خانواده'),
984 subtitle: Text(
985 '${family['is_admin'] == true ? 'مدیر خانواده · ' : ''}${family['role'] ?? ''}'),
986 onTap: () => Navigator.of(context).push(
@@ -901,9 +1002,11 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
1002 ListTile(
1003 leading: const Icon(Icons.public),
1004 title: const Text('خانواده و یادگیری ایران'),
904 - subtitle: const Text('نقش‌ها، پایه تحصیلی، کتاب‌ها، تقویم و یادآوری'),
1005 + subtitle: const Text(
1006 + 'نقش‌ها، پایه تحصیلی، کتاب‌ها، تقویم و یادآوری'),
1007 onTap: () => Navigator.of(context).push(MaterialPageRoute(
906 - builder: (_) => IranianFamilyLearningHub(identity: widget.api),
1008 + builder: (_) =>
1009 + IranianFamilyLearningHub(identity: widget.api),
1010 )),
1011 ),
1012 ListTile(
@@ -922,10 +1025,119 @@ class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
1025 );
1026 },
1027 ),
925 - floatingActionButton: FloatingActionButton.extended(
926 - onPressed: createFamily,
927 - icon: const Icon(Icons.add),
928 - label: const Text('خانواده')),
1028 + floatingActionButton: widget.localOnly
1029 + ? null
1030 + : FloatingActionButton.extended(
1031 + onPressed: createFamily,
1032 + icon: const Icon(Icons.add),
1033 + label: const Text('خانواده')),
1034 + );
1035 +}
1036 +
1037 +class _ProfileEditDialog extends StatefulWidget {
1038 + const _ProfileEditDialog(
1039 + {required this.api, required this.profile, required this.localOnly});
1040 + final IdentityApi api;
1041 + final Map<String, dynamic> profile;
1042 + final bool localOnly;
1043 +
1044 + @override
1045 + State<_ProfileEditDialog> createState() => _ProfileEditDialogState();
1046 +}
1047 +
1048 +class _ProfileEditDialogState extends State<_ProfileEditDialog> {
1049 + late final TextEditingController name;
1050 + late String theme;
1051 + bool saving = false;
1052 + String? error;
1053 +
1054 + @override
1055 + void initState() {
1056 + super.initState();
1057 + name = TextEditingController(
1058 + text: widget.profile['display_name']?.toString() ?? '');
1059 + theme = widget.profile['theme_preference']?.toString() ?? 'adult_blue';
1060 + }
1061 +
1062 + @override
1063 + void dispose() {
1064 + name.dispose();
1065 + super.dispose();
1066 + }
1067 +
1068 + Future<void> save() async {
1069 + if (saving) return;
1070 + if (name.text.trim().isEmpty) {
1071 + setState(() => error = 'نام را وارد کن.');
1072 + return;
1073 + }
1074 + setState(() {
1075 + saving = true;
1076 + error = null;
1077 + });
1078 + try {
1079 + await widget.api
1080 + .updateProfile(displayName: name.text.trim(), themePreference: theme);
1081 + if (mounted) Navigator.pop(context, true);
1082 + } catch (failure) {
1083 + if (mounted) {
1084 + setState(() => error = widget.localOnly
1085 + ? localDataErrorText(failure)
1086 + : errorText(failure));
1087 + }
1088 + } finally {
1089 + if (mounted) setState(() => saving = false);
1090 + }
1091 + }
1092 +
1093 + @override
1094 + Widget build(BuildContext context) => PopScope(
1095 + canPop: !saving,
1096 + child: AlertDialog(
1097 + title: const Text('ویرایش پروفایل'),
1098 + content: SingleChildScrollView(
1099 + child: Column(mainAxisSize: MainAxisSize.min, children: [
1100 + TextField(
1101 + key: const Key('profile-name'),
1102 + controller: name,
1103 + enabled: !saving,
1104 + decoration: const InputDecoration(labelText: 'نام'),
1105 + ),
1106 + const SizedBox(height: 12),
1107 + DropdownButtonFormField<String>(
1108 + initialValue: theme,
1109 + decoration: const InputDecoration(labelText: 'تم'),
1110 + items: const [
1111 + DropdownMenuItem(
1112 + value: 'girl_pink', child: Text('سفید / صورتی')),
1113 + DropdownMenuItem(
1114 + value: 'boy_blue', child: Text('سفید / آبی نوجوان')),
1115 + DropdownMenuItem(
1116 + value: 'adult_blue', child: Text('سفید / آبی بزرگسال')),
1117 + ],
1118 + onChanged: saving
1119 + ? null
1120 + : (value) {
1121 + if (value != null) setState(() => theme = value);
1122 + },
1123 + ),
1124 + if (error != null) ...[
1125 + const SizedBox(height: 12),
1126 + Text(error!,
1127 + style:
1128 + TextStyle(color: Theme.of(context).colorScheme.error)),
1129 + ],
1130 + ]),
1131 + ),
1132 + actions: [
1133 + TextButton(
1134 + onPressed: saving ? null : () => Navigator.pop(context, false),
1135 + child: const Text('انصراف')),
1136 + FilledButton(
1137 + onPressed: saving ? null : save,
1138 + child: Text(saving ? 'در حال ذخیره...' : 'ذخیره')),
1139 + ],
1140 + ),
1141 );
1142 }
1143
@@ -966,7 +1178,8 @@ class _FamilyMembersPageState extends State<FamilyMembersPage> {
1178 final minors = items.where((m) => m['role'] == 'teen_minor').toList();
1179 if (guardians.isEmpty || minors.isEmpty) {
1180 ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
969 - content: Text('برای ثبت سرپرستی، حداقل یک والد و یک فرزند لازم است.')));
1181 + content:
1182 + Text('برای ثبت سرپرستی، حداقل یک والد و یک فرزند لازم است.')));
1183 return;
1184 }
1185 final guardianId =
@@ -1029,8 +1242,8 @@ class _FamilyMembersPageState extends State<FamilyMembersPage> {
1242 guardianId.dispose();
1243 minorId.dispose();
1244 if (saved == true && mounted) {
1032 - ScaffoldMessenger.of(context).showSnackBar(
1033 - const SnackBar(content: Text('رابطه سرپرستی ثبت شد.')));
1245 + ScaffoldMessenger.of(context)
1246 + .showSnackBar(const SnackBar(content: Text('رابطه سرپرستی ثبت شد.')));
1247 }
1248 }
1249
@@ -1054,8 +1267,7 @@ class _FamilyMembersPageState extends State<FamilyMembersPage> {
1267 Card(
1268 child: ListTile(
1269 leading: const CircleAvatar(child: Icon(Icons.person)),
1057 - title:
1058 - Text(member['display_name']?.toString() ?? 'عضو'),
1270 + title: Text(member['display_name']?.toString() ?? 'عضو'),
1271 subtitle:
1272 Text(roleLabel(member['role']?.toString() ?? '')),
1273 trailing: member['is_admin'] == true
apps/lifemate/lib/phase3_ui.dart
+808 -305
@@ -7,13 +7,20 @@ import 'offline_store.dart';
7
8 String faKind(String kind) {
9 switch (kind) {
10 - case 'assignment': return 'تکلیف';
11 - case 'exam': return 'امتحان';
12 - case 'study_session': return 'مطالعه';
13 - case 'event': return 'رویداد';
14 - case 'routine': return 'روتین';
15 - case 'goal': return 'هدف';
16 - default: return 'کار';
10 + case 'assignment':
11 + return 'تکلیف';
12 + case 'exam':
13 + return 'امتحان';
14 + case 'study_session':
15 + return 'مطالعه';
16 + case 'event':
17 + return 'رویداد';
18 + case 'routine':
19 + return 'روتین';
20 + case 'goal':
21 + return 'هدف';
22 + default:
23 + return 'کار';
24 }
25 }
26
@@ -26,8 +33,13 @@ String shortDate(dynamic value) {
33 final d = parseDate(value);
34 if (d == null) return '';
35 final minute = d.minute.toString().padLeft(2, '0');
29 - return d.month.toString() + '/' + d.day.toString() + ' · ' +
30 - d.hour.toString() + ':' + minute;
36 + return d.month.toString() +
37 + '/' +
38 + d.day.toString() +
39 + ' · ' +
40 + d.hour.toString() +
41 + ':' +
42 + minute;
43 }
44
45 class Phase3HomeContent extends StatelessWidget {
@@ -36,29 +48,37 @@ class Phase3HomeContent extends StatelessWidget {
48 required this.api,
49 required this.page,
50 required this.adultShell,
51 + this.localOnly = false,
52 });
53 final IdentityApi api;
54 final String page;
55 final bool adultShell;
56 + final bool localOnly;
57
58 @override
59 Widget build(BuildContext context) {
46 - if (page == 'امروز') return TodayPage(api: api);
47 - if (page == 'برنامه‌ریز' || page == 'برنامه هفتگی' || page == 'تقویم' || page == 'تکالیف و کارها') {
48 - return PlannerPage(api: api);
60 + if (page == 'امروز') return TodayPage(api: api, localOnly: localOnly);
61 + if (page == 'برنامه‌ریز' ||
62 + page == 'برنامه هفتگی' ||
63 + page == 'تقویم' ||
64 + page == 'تکالیف و کارها') {
65 + return PlannerPage(api: api, localOnly: localOnly);
66 }
67 + if (localOnly) return const LocalFeaturesNotice();
68 if (page == 'خانواده') return ParentFamilyDashboard(api: api);
69 if (page == 'امتحان‌ها و نمرات') return SchoolPage(api: api);
70 if (page == 'تمرکز') {
71 return const CoreNotice(
72 title: 'تمرکز',
55 - subtitle: 'جلسه مطالعه در برنامه‌ریز فعال است؛ تایمر پیشرفته در فاز بعد اضافه می‌شود.',
73 + subtitle:
74 + 'جلسه مطالعه در برنامه‌ریز فعال است؛ تایمر پیشرفته در فاز بعد اضافه می‌شود.',
75 );
76 }
77 if (page == 'همراه هوشمند' || page == 'راهنما') {
78 return const CoreNotice(
79 title: 'راهنمای هوشمند',
61 - subtitle: 'هسته برنامه‌ریزی این فاز مستقل از AI است و راهنمای هوشمند در فاز ۴ فعال می‌شود.',
80 + subtitle:
81 + 'هسته برنامه‌ریزی این فاز مستقل از AI است و راهنمای هوشمند در فاز ۴ فعال می‌شود.',
82 );
83 }
84 return SchoolPage(api: api);
@@ -85,15 +105,104 @@ class CoreNotice extends StatelessWidget {
105 );
106 }
107
108 +String localDataErrorText(Object error) {
109 + if (error is ApiException) {
110 + switch (error.code) {
111 + case 'local_storage_restart_required':
112 + return 'وضعیت ذخیره نامشخص است. برنامه را از تنظیمات دستگاه «توقف اجباری» کن و دوباره باز کن.';
113 + case 'local_storage_failed':
114 + return 'ذخیره روی دستگاه انجام نشد. دوباره تلاش کن.';
115 + case 'local_data_corrupt':
116 + return 'اطلاعات ذخیره‌شده روی دستگاه خراب است؛ داده قبلی حفظ شده است.';
117 + case 'local_invalid_item':
118 + return 'عنوان، نوع یا زمان برنامه معتبر نیست.';
119 + case 'local_invalid_profile':
120 + return 'نام و تم پروفایل را بررسی کن.';
121 + case 'local_item_not_found':
122 + return 'این مورد در اطلاعات دستگاه پیدا نشد.';
123 + case 'local_feature_unavailable':
124 + return 'این قابلیت در حالت محلی فعال نیست.';
125 + }
126 + }
127 + return 'دسترسی به اطلاعات روی دستگاه انجام نشد. دوباره تلاش کن.';
128 +}
129 +
130 +String _planErrorText(Object error, bool localOnly) {
131 + if (localOnly || (error is ApiException && error.code.startsWith('local_'))) {
132 + return localDataErrorText(error);
133 + }
134 + return 'عملیات انجام نشد. دوباره تلاش کن.';
135 +}
136 +
137 +class LocalDataNotice extends StatelessWidget {
138 + const LocalDataNotice({super.key});
139 +
140 + @override
141 + Widget build(BuildContext context) => const Card(
142 + child: ListTile(
143 + leading: Icon(Icons.phone_android_outlined),
144 + title: Text('حالت محلی · فقط روی این دستگاه'),
145 + subtitle: Text(
146 + 'همگام‌سازی و پشتیبان سرور ندارد؛ حذف برنامه ممکن است اطلاعات را پاک کند.',
147 + ),
148 + ),
149 + );
150 +}
151 +
152 +class LocalFeaturesNotice extends StatelessWidget {
153 + const LocalFeaturesNotice({super.key});
154 +
155 + @override
156 + Widget build(BuildContext context) => const Card(
157 + child: ListTile(
158 + leading: Icon(Icons.info_outline),
159 + title: Text('قابلیت‌های غیرفعال در حالت محلی'),
160 + subtitle: Text(
161 + 'خانواده، آموزش ساختاریافته، ثبت حال و یادگیری، و همراه هوشمند فعال نیستند.',
162 + ),
163 + ),
164 + );
165 +}
166 +
167 +class _OperationErrorCard extends StatelessWidget {
168 + const _OperationErrorCard({required this.message, required this.onRetry});
169 + final String message;
170 + final VoidCallback onRetry;
171 +
172 + @override
173 + Widget build(BuildContext context) => Card(
174 + child: Padding(
175 + padding: const EdgeInsets.all(16),
176 + child: Column(
177 + crossAxisAlignment: CrossAxisAlignment.stretch,
178 + children: [
179 + Text(message,
180 + style: TextStyle(color: Theme.of(context).colorScheme.error)),
181 + const SizedBox(height: 8),
182 + TextButton(
183 + onPressed: onRetry,
184 + child: const Text('تلاش دوباره'),
185 + ),
186 + ],
187 + ),
188 + ),
189 + );
190 +}
191 +
192 class TodayPage extends StatefulWidget {
89 - const TodayPage({super.key, required this.api});
193 + const TodayPage({super.key, required this.api, this.localOnly = false});
194 final IdentityApi api;
195 + final bool localOnly;
196 @override
197 State<TodayPage> createState() => _TodayPageState();
198 }
199
200 class _TodayPageState extends State<TodayPage> {
201 late Future<LoadResult> future;
202 + final busyItems = <String>{};
203 + String? operationError;
204 + VoidCallback? retryOperation;
205 +
206 @override
207 void initState() {
208 super.initState();
@@ -106,37 +215,70 @@ class _TodayPageState extends State<TodayPage> {
215 final to = from.add(const Duration(days: 1));
216 try {
217 final items = await widget.api.getToday(from: from, to: to);
218 + if (widget.localOnly) return LoadResult(items, false);
219 final reminders = await widget.api.claimDueReminders();
220 await OfflineStore.instance.cacheToday(items);
221 return LoadResult(items, false, reminders: reminders);
112 - } catch (_) {
222 + } catch (error) {
223 + if (widget.localOnly) return LoadResult(const [], false, error: error);
224 return LoadResult(await OfflineStore.instance.readToday(), true);
225 }
226 }
227
228 Future<void> refresh() async {
118 - setState(() => future = load());
229 + if (!mounted) return;
230 + setState(() {
231 + future = load();
232 + });
233 await future;
234 }
235
236 Future<void> complete(Map<String, dynamic> item) async {
237 + final id = item['id'].toString();
238 + if (busyItems.contains(id)) return;
239 + setState(() {
240 + busyItems.add(id);
241 + operationError = null;
242 + retryOperation = null;
243 + });
244 try {
124 - await widget.api.updatePlanItem(item['id'].toString(), {'status': 'completed'});
245 + await widget.api.updatePlanItem(id, {'status': 'completed'});
246 await refresh();
126 - } catch (_) {
127 - await OfflineStore.instance.enqueue({
128 - 'id': DateTime.now().microsecondsSinceEpoch.toString() + '-' + Random().nextInt(99999).toString(),
129 - 'entityType': 'plan_item',
130 - 'entityId': item['id'],
131 - 'operation': 'complete',
132 - 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
133 - 'payload': {'status': 'completed'},
134 - });
135 - if (mounted) {
136 - ScaffoldMessenger.of(context).showSnackBar(
137 - const SnackBar(content: Text('آفلاین هستی؛ تغییر برای همگام‌سازی ذخیره شد.')),
138 - );
247 + } catch (error) {
248 + if (widget.localOnly) {
249 + if (mounted) {
250 + setState(() {
251 + operationError = localDataErrorText(error);
252 + retryOperation = () => complete(item);
253 + });
254 + }
255 + } else {
256 + try {
257 + await OfflineStore.instance.enqueue({
258 + 'id':
259 + '${DateTime.now().microsecondsSinceEpoch}-${Random().nextInt(99999)}',
260 + 'entityType': 'plan_item',
261 + 'entityId': item['id'],
262 + 'operation': 'complete',
263 + 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
264 + 'payload': {'status': 'completed'},
265 + });
266 + if (mounted) {
267 + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
268 + content: Text('آفلاین هستی؛ تغییر برای همگام‌سازی ذخیره شد.'),
269 + ));
270 + }
271 + } catch (queueError) {
272 + if (mounted) {
273 + setState(() {
274 + operationError = _planErrorText(queueError, false);
275 + retryOperation = () => complete(item);
276 + });
277 + }
278 + }
279 }
280 + } finally {
281 + if (mounted) setState(() => busyItems.remove(id));
282 }
283 }
284
@@ -144,34 +286,62 @@ class _TodayPageState extends State<TodayPage> {
286 Widget build(BuildContext context) => FutureBuilder<LoadResult>(
287 future: future,
288 builder: (context, snapshot) {
147 - if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
289 + if (snapshot.hasError) {
290 + return _OperationErrorCard(
291 + message: _planErrorText(snapshot.error!, widget.localOnly),
292 + onRetry: refresh,
293 + );
294 + }
295 + if (!snapshot.hasData) {
296 + return const Center(child: CircularProgressIndicator());
297 + }
298 final result = snapshot.data!;
299 + if (result.error != null) {
300 + return ListView(children: [
301 + _OperationErrorCard(
302 + message: localDataErrorText(result.error!),
303 + onRetry: refresh,
304 + ),
305 + ]);
306 + }
307 return RefreshIndicator(
308 onRefresh: refresh,
309 child: ListView(
310 padding: const EdgeInsets.all(16),
311 children: [
312 + if (operationError != null)
313 + _OperationErrorCard(
314 + message: operationError!,
315 + onRetry: retryOperation!,
316 + ),
317 if (result.offline)
155 - const Card(child: ListTile(
318 + const Card(
319 + child: ListTile(
320 leading: Icon(Icons.cloud_off_outlined),
321 title: Text('نمایش نسخه آفلاین'),
322 )),
159 - if (result.reminders.isNotEmpty)
160 - ...result.reminders.map((reminder) => Card(
161 - child: ListTile(
162 - leading: const Icon(Icons.notifications_active_outlined),
163 - title: Text('یادآوری · ' + (reminder['title']?.toString() ?? 'برنامه')),
164 - subtitle: const Text('زمان این مورد رسیده یا نزدیک است.'),
165 - ),
166 - )),
323 + ...result.reminders.map((reminder) => Card(
324 + child: ListTile(
325 + leading:
326 + const Icon(Icons.notifications_active_outlined),
327 + title:
328 + Text('یادآوری · ${reminder['title'] ?? 'برنامه'}'),
329 + subtitle:
330 + const Text('زمان این مورد رسیده یا نزدیک است.'),
331 + ),
332 + )),
333 Card(
334 child: Padding(
335 padding: const EdgeInsets.all(18),
170 - child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
171 - Text('امروز', style: Theme.of(context).textTheme.headlineSmall),
172 - const SizedBox(height: 6),
173 - Text(result.items.length.toString() + ' مورد در برنامه امروز'),
174 - ]),
336 + child: Column(
337 + crossAxisAlignment: CrossAxisAlignment.stretch,
338 + children: [
339 + Text('امروز',
340 + style: Theme.of(context).textTheme.headlineSmall),
341 + const SizedBox(height: 6),
342 + Text('${result.items.length} مورد در برنامه امروز'),
343 + ],
344 + ),
345 ),
346 ),
347 const SizedBox(height: 8),
@@ -179,23 +349,32 @@ class _TodayPageState extends State<TodayPage> {
349 const EmptyCard(
350 icon: Icons.check_circle_outline,
351 title: 'امروز خلوت است',
182 - subtitle: 'از برنامه‌ریز یک کار، رویداد یا جلسه مطالعه اضافه کن.',
352 + subtitle:
353 + 'از برنامه‌ریز یک کار، تکلیف یا جلسه مطالعه اضافه کن.',
354 )
355 else
356 ...result.items.map((item) => Card(
186 - child: ListTile(
187 - leading: const Icon(Icons.radio_button_unchecked),
188 - title: Text(item['title']?.toString() ?? ''),
189 - subtitle: Text(
190 - faKind(item['kind']?.toString() ?? 'task') +
191 - (shortDate(item['starts_at'] ?? item['due_at']).isEmpty ? '' : ' · ' + shortDate(item['starts_at'] ?? item['due_at'])),
192 - ),
193 - trailing: IconButton(
194 - onPressed: () => complete(item),
195 - icon: const Icon(Icons.check_circle_outline),
196 - ),
197 - ),
198 - )),
357 + child: ListTile(
358 + leading: const Icon(Icons.radio_button_unchecked),
359 + title: Text(item['title']?.toString() ?? ''),
360 + subtitle: Text(
361 + '${faKind(item['kind']?.toString() ?? 'task')} · ${shortDate(item['starts_at'] ?? item['due_at'])}',
362 + ),
363 + trailing: IconButton(
364 + tooltip: 'انجام شد',
365 + onPressed: busyItems.contains(item['id'].toString())
366 + ? null
367 + : () => complete(item),
368 + icon: busyItems.contains(item['id'].toString())
369 + ? const SizedBox(
370 + width: 20,
371 + height: 20,
372 + child: CircularProgressIndicator(
373 + strokeWidth: 2))
374 + : const Icon(Icons.check_circle_outline),
375 + ),
376 + ),
377 + )),
378 ],
379 ),
380 );
@@ -204,25 +383,31 @@ class _TodayPageState extends State<TodayPage> {
383 }
384
385 class PlannerPage extends StatefulWidget {
207 - const PlannerPage({super.key, required this.api});
386 + const PlannerPage({super.key, required this.api, this.localOnly = false});
387 final IdentityApi api;
388 + final bool localOnly;
389 @override
390 State<PlannerPage> createState() => _PlannerPageState();
391 }
392
393 class _PlannerPageState extends State<PlannerPage> {
394 late Future<LoadResult> future;
395 + final busyItems = <String>{};
396 + bool openingForm = false;
397 + String? operationError;
398 + VoidCallback? retryOperation;
399 +
400 @override
401 void initState() {
402 super.initState();
403 future = load();
219 - flushQueue();
404 + if (!widget.localOnly) flushQueue();
405 }
406
407 Future<void> flushQueue() async {
223 - final queue = await OfflineStore.instance.readQueue();
224 - if (queue.isEmpty) return;
408 try {
409 + final queue = await OfflineStore.instance.readQueue();
410 + if (queue.isEmpty) return;
411 final result = await widget.api.submitSyncMutations(queue);
412 final applied = <String>{};
413 for (final raw in (result['results'] as List<dynamic>? ?? const [])) {
@@ -237,113 +422,153 @@ class _PlannerPageState extends State<PlannerPage> {
422
423 Future<LoadResult> load() async {
424 final now = DateTime.now();
240 - final from = DateTime(now.year, now.month, now.day).subtract(const Duration(days: 1));
425 + final from = DateTime(now.year, now.month, now.day)
426 + .subtract(const Duration(days: 1));
427 final to = from.add(const Duration(days: 15));
428 try {
243 - final items = await widget.api.listPlanItems(from: from, to: to);
244 - await OfflineStore.instance.cachePlanner(items);
429 + final items = widget.localOnly
430 + ? await widget.api.listPlanItems()
431 + : await widget.api.listPlanItems(from: from, to: to);
432 + if (!widget.localOnly) await OfflineStore.instance.cachePlanner(items);
433 return LoadResult(items, false);
246 - } catch (_) {
434 + } catch (error) {
435 + if (widget.localOnly) return LoadResult(const [], false, error: error);
436 return LoadResult(await OfflineStore.instance.readPlanner(), true);
437 }
438 }
439
440 Future<void> reload() async {
252 - setState(() => future = load());
441 + if (!mounted) return;
442 + setState(() {
443 + future = load();
444 + });
445 await future;
446 }
447
256 - Future<void> createItem() async {
257 - final title = TextEditingController();
258 - final kind = ValueNotifier<String>('task');
259 - final visibility = ValueNotifier<String>('private');
260 - final families = await widget.api.listFamilies();
261 - final familyId = families.isEmpty ? null : families.first['id']?.toString();
262 - final when = DateTime.now().add(const Duration(hours: 1));
448 + Future<void> showItemForm({Map<String, dynamic>? item}) async {
449 + if (openingForm) return;
450 + setState(() {
451 + openingForm = true;
452 + operationError = null;
453 + retryOperation = null;
454 + });
455 + try {
456 + String? familyId;
457 + if (!widget.localOnly && item == null) {
458 + final families = await widget.api.listFamilies();
459 + familyId = families.isEmpty ? null : families.first['id']?.toString();
460 + }
461 + if (!mounted) return;
462 + final saved = await showDialog<bool>(
463 + context: context,
464 + barrierDismissible: false,
465 + builder: (_) => _PlanItemDialog(
466 + api: widget.api,
467 + localOnly: widget.localOnly,
468 + item: item,
469 + familyId: familyId,
470 + ),
471 + );
472 + if (saved == true) await reload();
473 + } catch (error) {
474 + if (mounted) {
475 + setState(() {
476 + operationError = _planErrorText(error, widget.localOnly);
477 + retryOperation = () => showItemForm(item: item);
478 + });
479 + }
480 + } finally {
481 + if (mounted) setState(() => openingForm = false);
482 + }
483 + }
484
264 - final saved = await showDialog<bool>(
485 + Future<void> mutate(
486 + Map<String, dynamic> item,
487 + Map<String, dynamic> data, {
488 + String? offlineOperation,
489 + }) async {
490 + final id = item['id'].toString();
491 + if (busyItems.contains(id)) return;
492 + setState(() {
493 + busyItems.add(id);
494 + operationError = null;
495 + retryOperation = null;
496 + });
497 + try {
498 + await widget.api.updatePlanItem(id, data);
499 + await reload();
500 + } catch (error) {
501 + var message = _planErrorText(error, widget.localOnly);
502 + if (!widget.localOnly && offlineOperation != null) {
503 + try {
504 + await OfflineStore.instance.enqueue({
505 + 'id':
506 + '${DateTime.now().microsecondsSinceEpoch}-${Random().nextInt(99999)}',
507 + 'entityType': 'plan_item',
508 + 'entityId': item['id'],
509 + 'operation': offlineOperation,
510 + 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
511 + 'payload': data,
512 + });
513 + if (mounted) {
514 + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
515 + content: Text('آفلاین هستی؛ تغییر برای همگام‌سازی ذخیره شد.'),
516 + ));
517 + }
518 + return;
519 + } catch (queueError) {
520 + message = _planErrorText(queueError, false);
521 + }
522 + }
523 + if (mounted) {
524 + setState(() {
525 + operationError = message;
526 + retryOperation =
527 + () => mutate(item, data, offlineOperation: offlineOperation);
528 + });
529 + }
530 + } finally {
531 + if (mounted) setState(() => busyItems.remove(id));
532 + }
533 + }
534 +
535 + Future<void> reschedule(Map<String, dynamic> item) async {
536 + final start = parseDate(item['starts_at']);
537 + final due = parseDate(item['due_at']);
538 + final data = <String, dynamic>{
539 + if (start != null)
540 + 'startsAt':
541 + start.add(const Duration(days: 1)).toUtc().toIso8601String(),
542 + if (due != null)
543 + 'dueAt': due.add(const Duration(days: 1)).toUtc().toIso8601String(),
544 + if (start == null && due == null)
545 + 'dueAt': DateTime.now()
546 + .add(const Duration(days: 1))
547 + .toUtc()
548 + .toIso8601String(),
549 + };
550 + await mutate(item, data, offlineOperation: 'reschedule');
551 + }
552 +
553 + Future<void> archive(Map<String, dynamic> item) async {
554 + final confirmed = await showDialog<bool>(
555 context: context,
556 builder: (dialogContext) => AlertDialog(
267 - title: const Text('مورد جدید'),
268 - content: Column(mainAxisSize: MainAxisSize.min, children: [
269 - TextField(controller: title, decoration: const InputDecoration(labelText: 'عنوان')),
270 - const SizedBox(height: 12),
271 - ValueListenableBuilder<String>(
272 - valueListenable: kind,
273 - builder: (_, value, __) => DropdownButtonFormField<String>(
274 - initialValue: value,
275 - decoration: const InputDecoration(labelText: 'نوع'),
276 - items: const [
277 - DropdownMenuItem(value: 'task', child: Text('کار')),
278 - DropdownMenuItem(value: 'event', child: Text('رویداد')),
279 - DropdownMenuItem(value: 'routine', child: Text('روتین')),
280 - DropdownMenuItem(value: 'goal', child: Text('هدف')),
281 - DropdownMenuItem(value: 'study_session', child: Text('جلسه مطالعه')),
282 - ],
283 - onChanged: (v) { if (v != null) kind.value = v; },
284 - ),
285 - ),
286 - const SizedBox(height: 12),
287 - ValueListenableBuilder<String>(
288 - valueListenable: visibility,
289 - builder: (_, value, __) => DropdownButtonFormField<String>(
290 - initialValue: value,
291 - decoration: const InputDecoration(labelText: 'اشتراک'),
292 - items: const [
293 - DropdownMenuItem(value: 'private', child: Text('خصوصی')),
294 - DropdownMenuItem(value: 'family', child: Text('خانواده')),
295 - DropdownMenuItem(value: 'parent_guardian', child: Text('والد / سرپرست')),
296 - ],
297 - onChanged: (v) { if (v != null) visibility.value = v; },
298 - ),
299 - ),
300 - ]),
557 + title: const Text('بایگانی مورد'),
558 + content:
559 + Text('«${item['title'] ?? ''}» از امروز و برنامه کنار گذاشته شود؟'),
560 actions: [
302 - TextButton(onPressed: () => Navigator.pop(dialogContext, false), child: const Text('انصراف')),
561 + TextButton(
562 + onPressed: () => Navigator.pop(dialogContext, false),
563 + child: const Text('انصراف')),
564 FilledButton(
304 - onPressed: () async {
305 - if (title.text.trim().isEmpty) return;
306 - final shared = visibility.value != 'private';
307 - await widget.api.createPlanItem({
308 - 'kind': kind.value,
309 - 'title': title.text.trim(),
310 - 'startsAt': when.toUtc().toIso8601String(),
311 - 'dueAt': when.add(const Duration(hours: 1)).toUtc().toIso8601String(),
312 - 'visibility': visibility.value,
313 - if (shared && familyId != null) 'familyId': familyId,
314 - 'reminderMinutesBefore': [15],
315 - });
316 - if (dialogContext.mounted) Navigator.pop(dialogContext, true);
317 - },
318 - child: const Text('ذخیره'),
319 - ),
565 + onPressed: () => Navigator.pop(dialogContext, true),
566 + child: const Text('بایگانی')),
567 ],
568 ),
569 );
323 - title.dispose();
324 - kind.dispose();
325 - visibility.dispose();
326 - if (saved == true && mounted) await reload();
327 - }
328 -
329 - Future<void> reschedule(Map<String, dynamic> item) async {
330 - final base = parseDate(item['due_at'] ?? item['starts_at']) ?? DateTime.now();
331 - final next = base.add(const Duration(days: 1));
332 - try {
333 - await widget.api.updatePlanItem(item['id'].toString(), {
334 - if (item['starts_at'] != null) 'startsAt': next.toUtc().toIso8601String(),
335 - if (item['due_at'] != null) 'dueAt': next.toUtc().toIso8601String(),
336 - });
337 - await reload();
338 - } catch (_) {
339 - await OfflineStore.instance.enqueue({
340 - 'id': DateTime.now().microsecondsSinceEpoch.toString() + '-' + Random().nextInt(99999).toString(),
341 - 'entityType': 'plan_item',
342 - 'entityId': item['id'],
343 - 'operation': 'reschedule',
344 - 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
345 - 'payload': {'dueAt': next.toUtc().toIso8601String()},
346 - });
570 + if (confirmed == true && mounted) {
571 + await mutate(item, {'status': 'cancelled'});
572 }
573 }
574
@@ -351,56 +576,104 @@ class _PlannerPageState extends State<PlannerPage> {
576 Widget build(BuildContext context) => FutureBuilder<LoadResult>(
577 future: future,
578 builder: (context, snapshot) {
354 - if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
579 + if (snapshot.hasError) {
580 + return _OperationErrorCard(
581 + message: _planErrorText(snapshot.error!, widget.localOnly),
582 + onRetry: reload,
583 + );
584 + }
585 + if (!snapshot.hasData) {
586 + return const Center(child: CircularProgressIndicator());
587 + }
588 final result = snapshot.data!;
589 return Scaffold(
590 backgroundColor: Colors.transparent,
358 - floatingActionButton: FloatingActionButton.extended(
359 - onPressed: createItem,
360 - icon: const Icon(Icons.add),
361 - label: const Text('جدید'),
362 - ),
591 + floatingActionButton: result.error == null
592 + ? FloatingActionButton.extended(
593 + onPressed: openingForm ? null : () => showItemForm(),
594 + icon: const Icon(Icons.add),
595 + label: const Text('جدید'),
596 + )
597 + : null,
598 body: RefreshIndicator(
599 onRefresh: reload,
600 child: ListView(
601 padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
602 children: [
368 - if (result.offline)
369 - const Card(child: ListTile(
370 - leading: Icon(Icons.cloud_off_outlined),
371 - title: Text('حالت آفلاین'),
372 - subtitle: Text('آخرین برنامه ذخیره‌شده نمایش داده می‌شود.'),
373 - )),
374 - if (result.items.isEmpty)
375 - const EmptyCard(
376 - icon: Icons.event_note_outlined,
377 - title: 'هنوز برنامه‌ای نداری',
378 - subtitle: 'کار، رویداد، روتین، هدف یا جلسه مطالعه اضافه کن.',
603 + if (result.error != null)
604 + _OperationErrorCard(
605 + message: localDataErrorText(result.error!),
606 + onRetry: reload,
607 )
380 - else
381 - ...result.items.map((item) => Card(
382 - child: ListTile(
383 - title: Text(item['title']?.toString() ?? ''),
384 - subtitle: Text(
385 - faKind(item['kind']?.toString() ?? 'task') +
386 - (shortDate(item['starts_at'] ?? item['due_at']).isEmpty ? '' : ' · ' + shortDate(item['starts_at'] ?? item['due_at'])),
387 - ),
388 - trailing: PopupMenuButton<String>(
389 - onSelected: (value) async {
390 - if (value == 'complete') {
391 - await widget.api.updatePlanItem(item['id'].toString(), {'status': 'completed'});
392 - await reload();
393 - } else if (value == 'tomorrow') {
394 - await reschedule(item);
395 - }
396 - },
397 - itemBuilder: (_) => const [
398 - PopupMenuItem(value: 'complete', child: Text('انجام شد')),
399 - PopupMenuItem(value: 'tomorrow', child: Text('انتقال به فردا')),
400 - ],
401 - ),
608 + else ...[
609 + if (operationError != null)
610 + _OperationErrorCard(
611 + message: operationError!,
612 + onRetry: retryOperation!,
613 ),
403 - )),
614 + if (result.offline)
615 + const Card(
616 + child: ListTile(
617 + leading: Icon(Icons.cloud_off_outlined),
618 + title: Text('حالت آفلاین'),
619 + subtitle:
620 + Text('آخرین برنامه ذخیره‌شده نمایش داده می‌شود.'),
621 + )),
622 + if (result.items.isEmpty)
623 + const EmptyCard(
624 + icon: Icons.event_note_outlined,
625 + title: 'هنوز برنامه‌ای نداری',
626 + subtitle:
627 + 'کار، تکلیف، رویداد، روتین، هدف یا جلسه مطالعه اضافه کن.',
628 + )
629 + else
630 + ...result.items.map((item) => Card(
631 + child: ListTile(
632 + title: Text(item['title']?.toString() ?? ''),
633 + subtitle: Text(
634 + '${faKind(item['kind']?.toString() ?? 'task')} · ${shortDate(item['starts_at'] ?? item['due_at'])}',
635 + ),
636 + trailing: busyItems
637 + .contains(item['id'].toString())
638 + ? const SizedBox(
639 + width: 24,
640 + height: 24,
641 + child: CircularProgressIndicator(
642 + strokeWidth: 2))
643 + : PopupMenuButton<String>(
644 + tooltip: 'عملیات برنامه',
645 + onSelected: (value) async {
646 + switch (value) {
647 + case 'edit':
648 + await showItemForm(item: item);
649 + case 'complete':
650 + await mutate(
651 + item, {'status': 'completed'});
652 + case 'tomorrow':
653 + await reschedule(item);
654 + case 'archive':
655 + await archive(item);
656 + }
657 + },
658 + itemBuilder: (_) => [
659 + const PopupMenuItem(
660 + value: 'edit',
661 + child: Text('ویرایش عنوان')),
662 + const PopupMenuItem(
663 + value: 'complete',
664 + child: Text('انجام شد')),
665 + const PopupMenuItem(
666 + value: 'tomorrow',
667 + child: Text('انتقال به فردا')),
668 + if (widget.localOnly)
669 + const PopupMenuItem(
670 + value: 'archive',
671 + child: Text('بایگانی')),
672 + ],
673 + ),
674 + ),
675 + )),
676 + ],
677 ],
678 ),
679 ),
@@ -409,6 +682,153 @@ class _PlannerPageState extends State<PlannerPage> {
682 );
683 }
684
685 +class _PlanItemDialog extends StatefulWidget {
686 + const _PlanItemDialog(
687 + {required this.api, required this.localOnly, this.item, this.familyId});
688 + final IdentityApi api;
689 + final bool localOnly;
690 + final Map<String, dynamic>? item;
691 + final String? familyId;
692 +
693 + @override
694 + State<_PlanItemDialog> createState() => _PlanItemDialogState();
695 +}
696 +
697 +class _PlanItemDialogState extends State<_PlanItemDialog> {
698 + late final TextEditingController title;
699 + String kind = 'task';
700 + String visibility = 'private';
701 + bool saving = false;
702 + String? error;
703 +
704 + @override
705 + void initState() {
706 + super.initState();
707 + title =
708 + TextEditingController(text: widget.item?['title']?.toString() ?? '');
709 + kind = widget.item?['kind']?.toString() ?? 'task';
710 + }
711 +
712 + @override
713 + void dispose() {
714 + title.dispose();
715 + super.dispose();
716 + }
717 +
718 + Future<void> save() async {
719 + if (saving) return;
720 + if (title.text.trim().isEmpty) {
721 + setState(() => error = 'عنوان را وارد کن.');
722 + return;
723 + }
724 + setState(() {
725 + saving = true;
726 + error = null;
727 + });
728 + try {
729 + if (widget.item != null) {
730 + await widget.api.updatePlanItem(widget.item!['id'].toString(), {
731 + 'title': title.text.trim(),
732 + });
733 + } else {
734 + final when = DateTime.now().add(const Duration(hours: 1));
735 + await widget.api.createPlanItem({
736 + 'kind': kind,
737 + 'title': title.text.trim(),
738 + 'startsAt': when.toUtc().toIso8601String(),
739 + 'dueAt': when.add(const Duration(hours: 1)).toUtc().toIso8601String(),
740 + 'visibility': widget.localOnly ? 'private' : visibility,
741 + if (!widget.localOnly &&
742 + visibility != 'private' &&
743 + widget.familyId != null)
744 + 'familyId': widget.familyId,
745 + if (!widget.localOnly) 'reminderMinutesBefore': [15],
746 + });
747 + }
748 + if (mounted) Navigator.pop(context, true);
749 + } catch (failure) {
750 + if (mounted)
751 + setState(() => error = _planErrorText(failure, widget.localOnly));
752 + } finally {
753 + if (mounted) setState(() => saving = false);
754 + }
755 + }
756 +
757 + @override
758 + Widget build(BuildContext context) => PopScope(
759 + canPop: !saving,
760 + child: AlertDialog(
761 + title: Text(widget.item == null ? 'مورد جدید' : 'ویرایش عنوان'),
762 + content: SingleChildScrollView(
763 + child: Column(mainAxisSize: MainAxisSize.min, children: [
764 + TextField(
765 + key: const Key('plan-title'),
766 + controller: title,
767 + enabled: !saving,
768 + decoration: const InputDecoration(labelText: 'عنوان'),
769 + ),
770 + if (widget.item == null) ...[
771 + const SizedBox(height: 12),
772 + DropdownButtonFormField<String>(
773 + key: const Key('plan-kind'),
774 + initialValue: kind,
775 + decoration: const InputDecoration(labelText: 'نوع'),
776 + items: const [
777 + DropdownMenuItem(value: 'task', child: Text('کار')),
778 + DropdownMenuItem(value: 'assignment', child: Text('تکلیف')),
779 + DropdownMenuItem(value: 'event', child: Text('رویداد')),
780 + DropdownMenuItem(value: 'routine', child: Text('روتین')),
781 + DropdownMenuItem(value: 'goal', child: Text('هدف')),
782 + DropdownMenuItem(
783 + value: 'study_session', child: Text('جلسه مطالعه')),
784 + ],
785 + onChanged: saving
786 + ? null
787 + : (value) {
788 + if (value != null) setState(() => kind = value);
789 + },
790 + ),
791 + if (!widget.localOnly) ...[
792 + const SizedBox(height: 12),
793 + DropdownButtonFormField<String>(
794 + initialValue: visibility,
795 + decoration: const InputDecoration(labelText: 'اشتراک'),
796 + items: const [
797 + DropdownMenuItem(value: 'private', child: Text('خصوصی')),
798 + DropdownMenuItem(value: 'family', child: Text('خانواده')),
799 + DropdownMenuItem(
800 + value: 'parent_guardian',
801 + child: Text('والد / سرپرست')),
802 + ],
803 + onChanged: saving
804 + ? null
805 + : (value) {
806 + if (value != null)
807 + setState(() => visibility = value);
808 + },
809 + ),
810 + ],
811 + ],
812 + if (error != null) ...[
813 + const SizedBox(height: 12),
814 + Text(error!,
815 + style:
816 + TextStyle(color: Theme.of(context).colorScheme.error)),
817 + ],
818 + ]),
819 + ),
820 + actions: [
821 + TextButton(
822 + onPressed: saving ? null : () => Navigator.pop(context, false),
823 + child: const Text('انصراف')),
824 + FilledButton(
825 + onPressed: saving ? null : save,
826 + child: Text(saving ? 'در حال ذخیره...' : 'ذخیره')),
827 + ],
828 + ),
829 + );
830 +}
831 +
832 class SchoolPage extends StatefulWidget {
833 const SchoolPage({super.key, required this.api});
834 final IdentityApi api;
@@ -430,14 +850,17 @@ class _SchoolPageState extends State<SchoolPage> {
850 if (userId.isEmpty) return SchoolLoad(userId, const {}, false);
851 try {
852 final overview = await widget.api.getSchoolOverview(userId);
433 - await OfflineStore.instance.cacheSchool([{'userId': userId, 'overview': overview}]);
853 + await OfflineStore.instance.cacheSchool([
854 + {'userId': userId, 'overview': overview}
855 + ]);
856 return SchoolLoad(userId, overview, false);
857 } catch (_) {
858 final cached = await OfflineStore.instance.readSchool();
859 if (cached.isNotEmpty) {
860 return SchoolLoad(
861 cached.first['userId']?.toString() ?? userId,
440 - Map<String, dynamic>.from(cached.first['overview'] as Map? ?? const {}),
862 + Map<String, dynamic>.from(
863 + cached.first['overview'] as Map? ?? const {}),
864 true,
865 );
866 }
@@ -454,13 +877,18 @@ class _SchoolPageState extends State<SchoolPage> {
877 var contexts = await widget.api.listLifeContexts();
878 Map<String, dynamic>? student;
879 for (final row in contexts) {
457 - if (row['kind'] == 'student') { student = row; break; }
880 + if (row['kind'] == 'student') {
881 + student = row;
882 + break;
883 + }
884 }
459 - student ??= await widget.api.createLifeContext(kind: 'student', title: 'مدرسه');
885 + student ??=
886 + await widget.api.createLifeContext(kind: 'student', title: 'مدرسه');
887 final now = DateTime.now();
888 final year = await widget.api.createAcademicYear({
889 'lifeContextId': student['id'],
463 - 'title': 'سال تحصیلی ' + now.year.toString() + '-' + (now.year + 1).toString(),
890 + 'title':
891 + 'سال تحصیلی ' + now.year.toString() + '-' + (now.year + 1).toString(),
892 'startsOn': now.year.toString() + '-09-01',
893 'endsOn': (now.year + 1).toString() + '-06-30',
894 });
@@ -485,7 +913,9 @@ class _SchoolPageState extends State<SchoolPage> {
913 builder: (dialogContext) => AlertDialog(
914 title: Text(kind == 'exam' ? 'امتحان جدید' : 'تکلیف جدید'),
915 content: Column(mainAxisSize: MainAxisSize.min, children: [
488 - TextField(controller: title, decoration: const InputDecoration(labelText: 'عنوان')),
916 + TextField(
917 + controller: title,
918 + decoration: const InputDecoration(labelText: 'عنوان')),
919 const SizedBox(height: 12),
920 ValueListenableBuilder<String>(
921 valueListenable: selected,
@@ -499,12 +929,16 @@ class _SchoolPageState extends State<SchoolPage> {
929 child: Text(row['name']?.toString() ?? ''),
930 );
931 }).toList(),
502 - onChanged: (v) { if (v != null) selected.value = v; },
932 + onChanged: (v) {
933 + if (v != null) selected.value = v;
934 + },
935 ),
936 ),
937 ]),
938 actions: [
507 - TextButton(onPressed: () => Navigator.pop(dialogContext, false), child: const Text('انصراف')),
939 + TextButton(
940 + onPressed: () => Navigator.pop(dialogContext, false),
941 + child: const Text('انصراف')),
942 FilledButton(
943 onPressed: () async {
944 if (title.text.trim().isEmpty) return;
@@ -533,22 +967,29 @@ class _SchoolPageState extends State<SchoolPage> {
967 Widget build(BuildContext context) => FutureBuilder<SchoolLoad>(
968 future: future,
969 builder: (context, snapshot) {
536 - if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
970 + if (!snapshot.hasData)
971 + return const Center(child: CircularProgressIndicator());
972 final data = snapshot.data!;
973 final years = data.overview['years'] as List<dynamic>? ?? const [];
539 - final subjects = data.overview['subjects'] as List<dynamic>? ?? const [];
540 - final workload = data.overview['workload'] as List<dynamic>? ?? const [];
974 + final subjects =
975 + data.overview['subjects'] as List<dynamic>? ?? const [];
976 + final workload =
977 + data.overview['workload'] as List<dynamic>? ?? const [];
978 final grades = data.overview['grades'] as List<dynamic>? ?? const [];
979 return ListView(
980 padding: const EdgeInsets.all(16),
981 children: [
982 if (data.offline)
546 - const Card(child: ListTile(leading: Icon(Icons.cloud_off_outlined), title: Text('اطلاعات مدرسه از کش نمایش داده می‌شود'))),
983 + const Card(
984 + child: ListTile(
985 + leading: Icon(Icons.cloud_off_outlined),
986 + title: Text('اطلاعات مدرسه از کش نمایش داده می‌شود'))),
987 if (years.isEmpty)
988 EmptyCard(
989 icon: Icons.school_outlined,
990 title: 'مدرسه را آماده کن',
551 - subtitle: 'سال تحصیلی، نیمسال و اولین درس را با شروع سریع بساز.',
991 + subtitle:
992 + 'سال تحصیلی، نیمسال و اولین درس را با شروع سریع بساز.',
993 action: FilledButton.icon(
994 onPressed: quickSetup,
995 icon: const Icon(Icons.auto_fix_high),
@@ -559,48 +1000,66 @@ class _SchoolPageState extends State<SchoolPage> {
1000 Card(
1001 child: Padding(
1002 padding: const EdgeInsets.all(16),
562 - child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
563 - Text('مدرسه', style: Theme.of(context).textTheme.headlineSmall),
564 - const SizedBox(height: 10),
565 - Wrap(spacing: 8, runSpacing: 8, children: [
566 - Chip(label: Text(subjects.length.toString() + ' درس')),
567 - Chip(label: Text(workload.length.toString() + ' کار درسی پیش‌رو')),
568 - Chip(label: Text(grades.length.toString() + ' نمره')),
569 - ]),
570 - const SizedBox(height: 12),
571 - Row(children: [
572 - Expanded(child: FilledButton.icon(
573 - onPressed: () => addSchoolItem('assignment'),
574 - icon: const Icon(Icons.assignment_add),
575 - label: const Text('تکلیف'),
576 - )),
577 - const SizedBox(width: 8),
578 - Expanded(child: OutlinedButton.icon(
579 - onPressed: () => addSchoolItem('exam'),
580 - icon: const Icon(Icons.quiz_outlined),
581 - label: const Text('امتحان'),
582 - )),
583 - ]),
584 - ]),
1003 + child: Column(
1004 + crossAxisAlignment: CrossAxisAlignment.stretch,
1005 + children: [
1006 + Text('مدرسه',
1007 + style: Theme.of(context).textTheme.headlineSmall),
1008 + const SizedBox(height: 10),
1009 + Wrap(spacing: 8, runSpacing: 8, children: [
1010 + Chip(
1011 + label:
1012 + Text(subjects.length.toString() + ' درس')),
1013 + Chip(
1014 + label: Text(workload.length.toString() +
1015 + ' کار درسی پیش‌رو')),
1016 + Chip(
1017 + label:
1018 + Text(grades.length.toString() + ' نمره')),
1019 + ]),
1020 + const SizedBox(height: 12),
1021 + Row(children: [
1022 + Expanded(
1023 + child: FilledButton.icon(
1024 + onPressed: () => addSchoolItem('assignment'),
1025 + icon: const Icon(Icons.assignment_add),
1026 + label: const Text('تکلیف'),
1027 + )),
1028 + const SizedBox(width: 8),
1029 + Expanded(
1030 + child: OutlinedButton.icon(
1031 + onPressed: () => addSchoolItem('exam'),
1032 + icon: const Icon(Icons.quiz_outlined),
1033 + label: const Text('امتحان'),
1034 + )),
1035 + ]),
1036 + ]),
1037 ),
1038 ),
1039 const SizedBox(height: 12),
1040 Text('درس‌ها', style: Theme.of(context).textTheme.titleMedium),
1041 ...subjects.map((raw) {
1042 final row = Map<String, dynamic>.from(raw as Map);
591 - return Card(child: ListTile(
1043 + return Card(
1044 + child: ListTile(
1045 leading: const Icon(Icons.menu_book_outlined),
1046 title: Text(row['name']?.toString() ?? ''),
594 - subtitle: Text(row['teacher_name']?.toString() ?? row['term_title']?.toString() ?? ''),
1047 + subtitle: Text(row['teacher_name']?.toString() ??
1048 + row['term_title']?.toString() ??
1049 + ''),
1050 ));
1051 }),
1052 const SizedBox(height: 12),
598 - Text('کارهای درسی پیش‌رو', style: Theme.of(context).textTheme.titleMedium),
1053 + Text('کارهای درسی پیش‌رو',
1054 + style: Theme.of(context).textTheme.titleMedium),
1055 ...workload.map((raw) {
1056 final row = Map<String, dynamic>.from(raw as Map);
601 - return Card(child: ListTile(
1057 + return Card(
1058 + child: ListTile(
1059 title: Text(row['title']?.toString() ?? ''),
603 - subtitle: Text(faKind(row['kind']?.toString() ?? '') + ' · ' + shortDate(row['due_at'] ?? row['starts_at'])),
1060 + subtitle: Text(faKind(row['kind']?.toString() ?? '') +
1061 + ' · ' +
1062 + shortDate(row['due_at'] ?? row['starts_at'])),
1063 ));
1064 }),
1065 ],
@@ -626,10 +1085,12 @@ class _ParentFamilyDashboardState extends State<ParentFamilyDashboard> {
1085 }
1086
1087 @override
629 - Widget build(BuildContext context) => FutureBuilder<List<Map<String, dynamic>>>(
1088 + Widget build(BuildContext context) =>
1089 + FutureBuilder<List<Map<String, dynamic>>>(
1090 future: families,
1091 builder: (context, snapshot) {
632 - if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
1092 + if (!snapshot.hasData)
1093 + return const Center(child: CircularProgressIndicator());
1094 if (snapshot.data!.isEmpty) {
1095 return const EmptyCard(
1096 icon: Icons.family_restroom,
@@ -639,14 +1100,18 @@ class _ParentFamilyDashboardState extends State<ParentFamilyDashboard> {
1100 }
1101 return ListView(
1102 padding: const EdgeInsets.all(16),
642 - children: snapshot.data!.map((family) => FamilyDashboardCard(api: widget.api, family: family)).toList(),
1103 + children: snapshot.data!
1104 + .map((family) =>
1105 + FamilyDashboardCard(api: widget.api, family: family))
1106 + .toList(),
1107 );
1108 },
1109 );
1110 }
1111
1112 class FamilyDashboardCard extends StatefulWidget {
649 - const FamilyDashboardCard({super.key, required this.api, required this.family});
1113 + const FamilyDashboardCard(
1114 + {super.key, required this.api, required this.family});
1115 final IdentityApi api;
1116 final Map<String, dynamic> family;
1117 @override
@@ -688,7 +1153,8 @@ class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
1153 maxLines: 4,
1154 decoration: const InputDecoration(
1155 labelText: 'سؤال شما',
691 - hintText: 'مثلاً چطور بدون فشار درباره امتحان‌ها با او صحبت کنم؟',
1156 + hintText:
1157 + 'مثلاً چطور بدون فشار درباره امتحان‌ها با او صحبت کنم؟',
1158 ),
1159 ),
1160 if (advice != null) ...[
@@ -727,7 +1193,8 @@ class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
1193 });
1194 } catch (_) {
1195 setLocalState(() {
730 - advice = 'دریافت راهنمایی انجام نشد. دوباره تلاش کنید.';
1196 + advice =
1197 + 'دریافت راهنمایی انجام نشد. دوباره تلاش کنید.';
1198 });
1199 } finally {
1200 setLocalState(() => busy = false);
@@ -748,12 +1215,14 @@ class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
1215 final summary = await widget.api.getChildSupportSummary(familyId, childId);
1216 Map<String, dynamic>? wellbeing;
1217 try {
751 - wellbeing = await widget.api.getGuardianWellbeingSummary(familyId, childId);
1218 + wellbeing =
1219 + await widget.api.getGuardianWellbeingSummary(familyId, childId);
1220 } catch (_) {
1221 wellbeing = null;
1222 }
1223 if (!mounted) return;
756 - final metrics = Map<String, dynamic>.from(summary['metrics'] as Map? ?? const {});
1224 + final metrics =
1225 + Map<String, dynamic>.from(summary['metrics'] as Map? ?? const {});
1226 final upcoming = summary['upcoming'] as List<dynamic>? ?? const [];
1227 final wellbeingSummary = wellbeing == null
1228 ? const <String, dynamic>{}
@@ -768,67 +1237,88 @@ class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
1237 await showDialog<void>(
1238 context: context,
1239 builder: (dialogContext) => AlertDialog(
771 - title: Text('خلاصه حمایت · ' + (child['display_name']?.toString() ?? 'فرزند')),
1240 + title: Text(
1241 + 'خلاصه حمایت · ' + (child['display_name']?.toString() ?? 'فرزند')),
1242 content: SizedBox(
1243 width: 520,
1244 child: SingleChildScrollView(
775 - child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
776 - Wrap(spacing: 8, runSpacing: 8, children: [
777 - Chip(label: Text((metrics['overdue'] ?? 0).toString() + ' عقب‌افتاده')),
778 - Chip(label: Text((metrics['completedLast7Days'] ?? 0).toString() + ' انجام‌شده')),
779 - Chip(label: Text((metrics['studyMinutesLast7Days'] ?? 0).toString() + ' دقیقه مطالعه')),
780 - if (metrics['gradePercent'] != null) Chip(label: Text('میانگین ' + metrics['gradePercent'].toString() + '٪')),
781 - ]),
782 - if (wellbeing != null) ...[
783 - const SizedBox(height: 14),
784 - Text('خلاصه حال خوب', style: Theme.of(context).textTheme.titleMedium),
785 - const SizedBox(height: 8),
786 - Wrap(spacing: 8, runSpacing: 8, children: [
787 - Chip(
788 - label: Text(
789 - (wellbeingSummary['checkin_count'] ?? 0).toString() +
790 - ' ثبت مجاز',
791 - ),
792 - ),
793 - if (wellbeingSummary['mood_average'] != null)
1245 + child: Column(
1246 + crossAxisAlignment: CrossAxisAlignment.stretch,
1247 + children: [
1248 + Wrap(spacing: 8, runSpacing: 8, children: [
1249 Chip(
795 - label: Text(
796 - 'حال ' + wellbeingSummary['mood_average'].toString() + '/5',
797 - ),
798 - ),
799 - if (wellbeingSummary['stress_average'] != null)
1250 + label: Text((metrics['overdue'] ?? 0).toString() +
1251 + ' عقب‌افتاده')),
1252 Chip(
801 - label: Text(
802 - 'استرس ' +
803 - wellbeingSummary['stress_average'].toString() +
804 - '/5',
805 - ),
806 - ),
807 - if ((safety['open_urgent_count'] ?? 0) != 0)
1253 + label: Text(
1254 + (metrics['completedLast7Days'] ?? 0).toString() +
1255 + ' انجام‌شده')),
1256 Chip(
809 - avatar: const Icon(Icons.warning_amber_rounded, size: 18),
810 - label: Text(
811 - safety['open_urgent_count'].toString() +
812 - ' هشدار ایمنی نیازمند توجه',
1257 + label: Text(
1258 + (metrics['studyMinutesLast7Days'] ?? 0).toString() +
1259 + ' دقیقه مطالعه')),
1260 + if (metrics['gradePercent'] != null)
1261 + Chip(
1262 + label: Text('میانگین ' +
1263 + metrics['gradePercent'].toString() +
1264 + '٪')),
1265 + ]),
1266 + if (wellbeing != null) ...[
1267 + const SizedBox(height: 14),
1268 + Text('خلاصه حال خوب',
1269 + style: Theme.of(context).textTheme.titleMedium),
1270 + const SizedBox(height: 8),
1271 + Wrap(spacing: 8, runSpacing: 8, children: [
1272 + Chip(
1273 + label: Text(
1274 + (wellbeingSummary['checkin_count'] ?? 0).toString() +
1275 + ' ثبت مجاز',
1276 + ),
1277 ),
1278 + if (wellbeingSummary['mood_average'] != null)
1279 + Chip(
1280 + label: Text(
1281 + 'حال ' +
1282 + wellbeingSummary['mood_average'].toString() +
1283 + '/5',
1284 + ),
1285 + ),
1286 + if (wellbeingSummary['stress_average'] != null)
1287 + Chip(
1288 + label: Text(
1289 + 'استرس ' +
1290 + wellbeingSummary['stress_average'].toString() +
1291 + '/5',
1292 + ),
1293 + ),
1294 + if ((safety['open_urgent_count'] ?? 0) != 0)
1295 + Chip(
1296 + avatar:
1297 + const Icon(Icons.warning_amber_rounded, size: 18),
1298 + label: Text(
1299 + safety['open_urgent_count'].toString() +
1300 + ' هشدار ایمنی نیازمند توجه',
1301 + ),
1302 + ),
1303 + ]),
1304 + const SizedBox(height: 6),
1305 + const Text(
1306 + 'این بخش فقط خلاصه مجاز و سیگنال ایمنی را نشان می‌دهد؛ متن خصوصی گفت‌وگو یا یادداشت نمایش داده نمی‌شود.',
1307 ),
1308 + ],
1309 + const SizedBox(height: 10),
1310 + const Text('موارد پیش‌رو'),
1311 + ...upcoming.take(8).map((raw) {
1312 + final row = Map<String, dynamic>.from(raw as Map);
1313 + return ListTile(
1314 + dense: true,
1315 + title: Text(row['title']?.toString() ?? ''),
1316 + subtitle: Text(faKind(row['kind']?.toString() ?? '') +
1317 + ' · ' +
1318 + shortDate(row['due_at'] ?? row['starts_at'])),
1319 + );
1320 + }),
1321 ]),
816 - const SizedBox(height: 6),
817 - const Text(
818 - 'این بخش فقط خلاصه مجاز و سیگنال ایمنی را نشان می‌دهد؛ متن خصوصی گفت‌وگو یا یادداشت نمایش داده نمی‌شود.',
819 - ),
820 - ],
821 - const SizedBox(height: 10),
822 - const Text('موارد پیش‌رو'),
823 - ...upcoming.take(8).map((raw) {
824 - final row = Map<String, dynamic>.from(raw as Map);
825 - return ListTile(
826 - dense: true,
827 - title: Text(row['title']?.toString() ?? ''),
828 - subtitle: Text(faKind(row['kind']?.toString() ?? '') + ' · ' + shortDate(row['due_at'] ?? row['starts_at'])),
829 - );
830 - }),
831 - ]),
1322 ),
1323 ),
1324 actions: [
@@ -857,23 +1347,34 @@ class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
1347 Widget build(BuildContext context) => Card(
1348 child: Padding(
1349 padding: const EdgeInsets.all(14),
860 - child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
861 - Text(widget.family['name']?.toString() ?? 'خانواده', style: Theme.of(context).textTheme.titleLarge),
1350 + child:
1351 + Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
1352 + Text(widget.family['name']?.toString() ?? 'خانواده',
1353 + style: Theme.of(context).textTheme.titleLarge),
1354 const SizedBox(height: 8),
1355 FutureBuilder<List<Map<String, dynamic>>>(
1356 future: members,
1357 builder: (context, snapshot) {
1358 if (!snapshot.hasData) return const LinearProgressIndicator();
867 - final children = snapshot.data!.where((row) => row['role'] == 'teen_minor').toList();
868 - if (children.isEmpty) return const Text('هنوز فرزند/نوجوانی به این خانواده متصل نیست.');
1359 + final children = snapshot.data!
1360 + .where((row) => row['role'] == 'teen_minor')
1361 + .toList();
1362 + if (children.isEmpty)
1363 + return const Text(
1364 + 'هنوز فرزند/نوجوانی به این خانواده متصل نیست.');
1365 return Column(
870 - children: children.map((child) => ListTile(
871 - leading: const CircleAvatar(child: Icon(Icons.school_outlined)),
872 - title: Text(child['display_name']?.toString() ?? 'فرزند'),
873 - subtitle: const Text('برنامه، تکالیف، امتحان‌ها و پیشرفت مجاز'),
874 - trailing: const Icon(Icons.chevron_left),
875 - onTap: () => openChild(child),
876 - )).toList(),
1366 + children: children
1367 + .map((child) => ListTile(
1368 + leading: const CircleAvatar(
1369 + child: Icon(Icons.school_outlined)),
1370 + title: Text(
1371 + child['display_name']?.toString() ?? 'فرزند'),
1372 + subtitle: const Text(
1373 + 'برنامه، تکالیف، امتحان‌ها و پیشرفت مجاز'),
1374 + trailing: const Icon(Icons.chevron_left),
1375 + onTap: () => openChild(child),
1376 + ))
1377 + .toList(),
1378 );
1379 },
1380 ),
@@ -912,10 +1413,12 @@ class EmptyCard extends StatelessWidget {
1413 }
1414
1415 class LoadResult {
915 - const LoadResult(this.items, this.offline, {this.reminders = const []});
1416 + const LoadResult(this.items, this.offline,
1417 + {this.reminders = const [], this.error});
1418 final List<Map<String, dynamic>> items;
1419 final bool offline;
1420 final List<Map<String, dynamic>> reminders;
1421 + final Object? error;
1422 }
1423
1424 class SchoolLoad {
apps/lifemate/lib/role_entry_main.dart
+179 -107
@@ -3,7 +3,10 @@ import 'package:flutter_localizations/flutter_localizations.dart';
3 import 'package:shared_preferences/shared_preferences.dart';
4
5 import 'api.dart';
6 +import 'local_data_store.dart';
7 +import 'local_only_api.dart';
8 import 'main.dart' show HomeShell;
9 +import 'phase3_ui.dart' show localDataErrorText;
10
11 void main() => runApp(const LifeGuideRoleTestApp());
12
@@ -23,10 +26,12 @@ class LifeGuideRoleTestApp extends StatelessWidget {
26 theme: ThemeData(
27 colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF4D86E8)),
28 scaffoldBackgroundColor: const Color(0xFFF8FAFD),
26 - inputDecorationTheme: const InputDecorationTheme(border: OutlineInputBorder()),
29 + inputDecorationTheme:
30 + const InputDecorationTheme(border: OutlineInputBorder()),
31 useMaterial3: true,
32 ),
29 - home: const Directionality(textDirection: TextDirection.rtl, child: RoleEntryGate()),
33 + home: const Directionality(
34 + textDirection: TextDirection.rtl, child: RoleEntryGate()),
35 );
36 }
37
@@ -41,21 +46,39 @@ class LocalTestProfileStore {
46 static const _displayNameKey = 'lifeguide.local_profile.display_name';
47
48 Future<LocalTestProfile?> load() async {
49 + final saved = await LocalDataStore.readSavedProfile();
50 + if (saved != null) {
51 + return LocalTestProfile(
52 + category: saved['profile_category'] as String,
53 + displayName: saved['display_name'] as String);
54 + }
55 final prefs = await SharedPreferences.getInstance();
56 + await prefs.reload();
57 final category = prefs.getString(_categoryKey);
58 final displayName = prefs.getString(_displayNameKey);
47 - if (category == null || displayName == null || displayName.trim().isEmpty) {
59 + if (!LocalDataStore.categories.contains(category) ||
60 + displayName == null ||
61 + displayName.trim().isEmpty) {
62 return null;
63 }
50 - return LocalTestProfile(category: category, displayName: displayName);
64 + return LocalTestProfile(category: category!, displayName: displayName);
65 }
66
67 Future<void> save(LocalTestProfile profile) async {
68 final name = profile.displayName.trim();
69 if (name.isEmpty) throw ArgumentError('displayName cannot be empty');
56 - final prefs = await SharedPreferences.getInstance();
57 - await prefs.setString(_categoryKey, profile.category);
58 - await prefs.setString(_displayNameKey, name);
70 + if (!LocalDataStore.categories.contains(profile.category)) {
71 + throw ArgumentError('invalid profile category');
72 + }
73 + await LocalDataStore(category: profile.category, displayName: name)
74 + .mutate((data) {
75 + final saved = data['profile'] as Map<String, dynamic>;
76 + if (saved['profile_category'] != profile.category) {
77 + throw const ApiException(
78 + 409, 'local_profile_change_requires_confirmation');
79 + }
80 + saved['display_name'] = name;
81 + });
82 }
83 }
84
@@ -70,6 +93,7 @@ class _RoleEntryGateState extends State<RoleEntryGate> {
93 final store = LocalTestProfileStore();
94 LocalTestProfile? profile;
95 bool loading = true;
96 + String? error;
97
98 @override
99 void initState() {
@@ -78,24 +102,35 @@ class _RoleEntryGateState extends State<RoleEntryGate> {
102 }
103
104 Future<void> _load() async {
81 - final saved = await store.load();
82 - if (!mounted) return;
105 setState(() {
84 - profile = saved;
85 - loading = false;
106 + loading = true;
107 + error = null;
108 });
109 + try {
110 + final saved = await store.load();
111 + if (!mounted) return;
112 + setState(() {
113 + profile = saved;
114 + loading = false;
115 + });
116 + } catch (failure) {
117 + if (mounted) {
118 + setState(() {
119 + loading = false;
120 + error = localDataErrorText(failure);
121 + });
122 + }
123 + }
124 }
125
126 void _openHome(LocalTestProfile value) {
90 - final role = value.category == 'adult' ? 'parent_guardian' : 'teen_minor';
127 Navigator.of(context).pushReplacement(
128 MaterialPageRoute(
129 builder: (_) => HomeShell(
94 - api: LocalRoleTestApi(
95 - role: role,
96 - label: value.displayName,
97 - category: value.category,
98 - ),
130 + localOnly: true,
131 + profileCategory: value.category,
132 + api: LocalOnlyApi(
133 + category: value.category, displayName: value.displayName),
134 ),
135 ),
136 );
@@ -106,6 +141,14 @@ class _RoleEntryGateState extends State<RoleEntryGate> {
141 if (loading) {
142 return const Scaffold(body: Center(child: CircularProgressIndicator()));
143 }
144 + if (error != null) {
145 + return Scaffold(
146 + body: Center(
147 + child: Column(mainAxisSize: MainAxisSize.min, children: [
148 + Text(error!, textAlign: TextAlign.center),
149 + TextButton(onPressed: _load, child: const Text('تلاش دوباره')),
150 + ])));
151 + }
152 if (profile != null) {
153 WidgetsBinding.instance.addPostFrameCallback((_) {
154 if (mounted) _openHome(profile!);
@@ -121,40 +164,37 @@ class _RoleEntryGateState extends State<RoleEntryGate> {
164 }
165 }
166
124 -class RoleEntryPage extends StatelessWidget {
167 +class RoleEntryPage extends StatefulWidget {
168 const RoleEntryPage({super.key, required this.onComplete});
169 final Future<void> Function(LocalTestProfile profile) onComplete;
170
128 - Future<void> _choose(BuildContext context, String category, String fallbackName) async {
129 - final controller = TextEditingController(text: fallbackName);
130 - final name = await showDialog<String>(
131 - context: context,
132 - builder: (dialogContext) => AlertDialog(
133 - title: const Text('اسم این پروفایل چیست؟'),
134 - content: TextField(
135 - controller: controller,
136 - autofocus: true,
137 - textInputAction: TextInputAction.done,
138 - decoration: const InputDecoration(labelText: 'نام نمایشی'),
139 - onSubmitted: (value) {
140 - if (value.trim().isNotEmpty) Navigator.pop(dialogContext, value.trim());
141 - },
142 - ),
143 - actions: [
144 - TextButton(onPressed: () => Navigator.pop(dialogContext), child: const Text('انصراف')),
145 - FilledButton(
146 - onPressed: () {
147 - final value = controller.text.trim();
148 - if (value.isNotEmpty) Navigator.pop(dialogContext, value);
149 - },
150 - child: const Text('ادامه'),
151 - ),
152 - ],
153 - ),
154 - );
155 - controller.dispose();
156 - if (name == null || name.trim().isEmpty) return;
157 - await onComplete(LocalTestProfile(category: category, displayName: name.trim()));
171 + @override
172 + State<RoleEntryPage> createState() => _RoleEntryPageState();
173 +}
174 +
175 +class _RoleEntryPageState extends State<RoleEntryPage> {
176 + bool busy = false;
177 +
178 + Future<void> _choose(
179 + BuildContext context, String category, String fallbackName) async {
180 + if (busy) return;
181 + setState(() => busy = true);
182 + try {
183 + final name = await showDialog<String>(
184 + context: context,
185 + builder: (_) => _ProfileNameDialog(initialName: fallbackName));
186 + if (name == null || name.trim().isEmpty) return;
187 + await widget.onComplete(
188 + LocalTestProfile(category: category, displayName: name.trim()));
189 + } catch (failure) {
190 + if (context.mounted) {
191 + ScaffoldMessenger.of(context).showSnackBar(
192 + SnackBar(content: Text(localDataErrorText(failure))),
193 + );
194 + }
195 + } finally {
196 + if (mounted) setState(() => busy = false);
197 + }
198 }
199
200 @override
@@ -169,19 +209,47 @@ class RoleEntryPage extends StatelessWidget {
209 children: [
210 const Icon(Icons.route_rounded, size: 72),
211 const SizedBox(height: 16),
172 - const Text('Life Guide', textAlign: TextAlign.center, style: TextStyle(fontSize: 32, fontWeight: FontWeight.w700)),
212 + const Text('Life Guide',
213 + textAlign: TextAlign.center,
214 + style:
215 + TextStyle(fontSize: 32, fontWeight: FontWeight.w700)),
216 const SizedBox(height: 8),
174 - const Text('چه کسی وارد می‌شود؟', textAlign: TextAlign.center, style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
217 + const Text('چه کسی وارد می‌شود؟',
218 + textAlign: TextAlign.center,
219 + style:
220 + TextStyle(fontSize: 20, fontWeight: FontWeight.w600)),
221 const SizedBox(height: 8),
176 - const Text('یک‌بار پروفایل را انتخاب و نام‌گذاری کن؛ دفعه‌های بعد مستقیم وارد فضای شخصی خودت می‌شوی.', textAlign: TextAlign.center),
222 + const Text(
223 + 'یک‌بار پروفایل را انتخاب و نام‌گذاری کن؛ دفعه‌های بعد مستقیم وارد فضای شخصی خودت می‌شوی.',
224 + textAlign: TextAlign.center),
225 const SizedBox(height: 28),
178 - _RoleButton(icon: Icons.girl_rounded, title: 'فرزند دختر', subtitle: 'فضای شخصی و تحصیلی با تم دخترانه', onTap: () => _choose(context, 'girl_minor', 'آرام')),
226 + _RoleButton(
227 + icon: Icons.girl_rounded,
228 + title: 'فرزند دختر',
229 + subtitle: 'فضای شخصی و تحصیلی با تم دخترانه',
230 + onTap: busy
231 + ? null
232 + : () => _choose(context, 'girl_minor', 'آرام')),
233 const SizedBox(height: 12),
180 - _RoleButton(icon: Icons.boy_rounded, title: 'فرزند پسر', subtitle: 'فضای شخصی و تحصیلی با تم پسرانه', onTap: () => _choose(context, 'boy_minor', 'فرزند')),
234 + _RoleButton(
235 + icon: Icons.boy_rounded,
236 + title: 'فرزند پسر',
237 + subtitle: 'فضای شخصی و تحصیلی با تم پسرانه',
238 + onTap: busy
239 + ? null
240 + : () => _choose(context, 'boy_minor', 'فرزند')),
241 const SizedBox(height: 12),
182 - _RoleButton(icon: Icons.person_rounded, title: 'بزرگسال', subtitle: 'فضای شخصی، خانواده و مدیریت', onTap: () => _choose(context, 'adult', 'بزرگسال')),
242 + _RoleButton(
243 + icon: Icons.person_rounded,
244 + title: 'بزرگسال',
245 + subtitle: 'فضای شخصی، خانواده و مدیریت',
246 + onTap: busy
247 + ? null
248 + : () => _choose(context, 'adult', 'بزرگسال')),
249 const SizedBox(height: 20),
184 - const Text('نسخه آزمایشی: ورود ایمیل/رمز موقتاً غیرفعال است.', textAlign: TextAlign.center, style: TextStyle(fontSize: 12)),
250 + const Text('نسخه آزمایشی: ورود ایمیل/رمز موقتاً غیرفعال است.',
251 + textAlign: TextAlign.center,
252 + style: TextStyle(fontSize: 12)),
253 ],
254 ),
255 ),
@@ -191,17 +259,23 @@ class RoleEntryPage extends StatelessWidget {
259 }
260
261 class _RoleButton extends StatelessWidget {
194 - const _RoleButton({required this.icon, required this.title, required this.subtitle, required this.onTap});
262 + const _RoleButton(
263 + {required this.icon,
264 + required this.title,
265 + required this.subtitle,
266 + required this.onTap});
267 final IconData icon;
268 final String title;
269 final String subtitle;
198 - final VoidCallback onTap;
270 + final VoidCallback? onTap;
271 @override
272 Widget build(BuildContext context) => Card(
273 child: ListTile(
202 - contentPadding: const EdgeInsets.symmetric(horizontal: 18, vertical: 10),
274 + contentPadding:
275 + const EdgeInsets.symmetric(horizontal: 18, vertical: 10),
276 leading: Icon(icon, size: 36),
204 - title: Text(title, style: const TextStyle(fontWeight: FontWeight.w700)),
277 + title:
278 + Text(title, style: const TextStyle(fontWeight: FontWeight.w700)),
279 subtitle: Text(subtitle),
280 trailing: const Icon(Icons.chevron_left_rounded),
281 onTap: onTap,
@@ -209,52 +283,50 @@ class _RoleButton extends StatelessWidget {
283 );
284 }
285
212 -class LocalRoleTestApi implements IdentityApi {
213 - LocalRoleTestApi({required this.role, required this.label, this.category});
214 - final String role;
215 - final String label;
216 - final String? category;
217 - bool familyCreated = false;
218 - String familyName = 'خانواده من';
219 - @override String? accessToken = 'local-role-test';
220 - @override Future<void> login(String email, String password) async {}
221 - @override Future<void> register({required String displayName, required String email, required String password}) async {}
222 - @override Future<void> verifyEmail(String token) async {}
223 - @override Future<void> forgotPassword(String email) async {}
224 - @override Future<void> resetPassword(String token, String newPassword) async {}
225 - @override Future<void> changePassword(String currentPassword, String newPassword) async {}
226 - @override Future<Map<String,dynamic>> getProfile() async => {'display_name': label, 'email_normalized':'test@lifeguide.local', 'user_id': role == 'teen_minor' ? 'student-test' : 'parent-test', 'theme_preference': category == 'girl_minor' ? 'girl_pink' : category == 'boy_minor' ? 'boy_blue' : 'adult_blue'};
227 - @override Future<Map<String,dynamic>> updateProfile({String? displayName,String? birthDate,String? themePreference}) async => {'display_name':displayName ?? label,'theme_preference':themePreference ?? 'adult_blue'};
228 - @override Future<List<Map<String,dynamic>>> listFamilies() async => familyCreated ? [{'id':'family-test','name':familyName,'role':role,'is_admin':role == 'parent_guardian'}] : [];
229 - @override Future<List<Map<String,dynamic>>> listFamilyMembers(String familyId) async => [];
230 - @override Future<Map<String,dynamic>> createFamily(String name,{String? role}) async { familyCreated=true; familyName=name; return {'id':'family-test','name':name}; }
231 - @override Future<void> inviteMember({required String familyId,required String email,required String role,String? themePreference}) async {}
232 - @override Future<void> acceptInvitation(String token) async {}
233 - @override Future<void> setGuardian({required String familyId,required String guardianUserId,required String minorUserId}) async {}
234 - @override Future<List<Map<String,dynamic>>> getToday({required DateTime from,required DateTime to}) async => [];
235 - @override Future<List<Map<String,dynamic>>> listPlanItems({DateTime? from,DateTime? to,String? kind}) async => [];
236 - @override Future<Map<String,dynamic>> createPlanItem(Map<String,dynamic> data) async => {'id':'new-plan',...data};
237 - @override Future<Map<String,dynamic>> updatePlanItem(String itemId,Map<String,dynamic> data) async => {'id':itemId,...data};
238 - @override Future<List<Map<String,dynamic>>> listLifeContexts() async => [];
239 - @override Future<Map<String,dynamic>> createLifeContext({required String kind,required String title}) async => {'id':'ctx-1','kind':kind,'title':title};
240 - @override Future<Map<String,dynamic>> createAcademicYear(Map<String,dynamic> data) async => {'id':'year-1',...data};
241 - @override Future<Map<String,dynamic>> createAcademicTerm(String yearId,Map<String,dynamic> data) async => {'id':'term-1',...data};
242 - @override Future<Map<String,dynamic>> createSubject(String termId,Map<String,dynamic> data) async => {'id':'subject-1',...data};
243 - @override Future<Map<String,dynamic>> createClassSession(String subjectId,Map<String,dynamic> data) async => {'id':'class-1',...data};
244 - @override Future<Map<String,dynamic>> setGrade(String itemId,{required num points,required num outOf}) async => {'id':itemId};
245 - @override Future<List<Map<String,dynamic>>> claimDueReminders() async => [];
246 - @override Future<Map<String,dynamic>> getSchoolOverview(String studentUserId) async => {'years':[],'subjects':[],'workload':[],'grades':[]};
247 - @override Future<List<Map<String,dynamic>>> getTimetable(String studentUserId) async => [];
248 - @override Future<List<Map<String,dynamic>>> getFamilyCalendar(String familyId) async => [];
249 - @override Future<Map<String,dynamic>> getChildSupportSummary(String familyId,String studentUserId) async => {'upcoming':[],'metrics':{}};
250 - @override Future<Map<String,dynamic>> submitSyncMutations(List<Map<String,dynamic>> mutations) async => {'results':[]};
251 - @override Future<Map<String,dynamic>> createLearningGoal({required String title,String? target,String? subjectId}) async => {'id':'goal-1','title':title};
252 - @override Future<List<Map<String,dynamic>>> listLearningGoals() async => [];
253 - @override Future<Map<String,dynamic>> createLearningCheckin({String? learningGoalId,required int confidence,required int difficulty,String? note}) async => {'id':'checkin-1'};
254 - @override Future<Map<String,dynamic>> createWellbeingCheckin({required int mood,required int energy,required int stress,String? note,String visibility='private'}) async => {'id':'wellbeing-1'};
255 - @override Future<List<Map<String,dynamic>>> listWellbeingCheckins() async => [];
256 - @override Future<Map<String,dynamic>> createAiSession(String kind) async => {'id':'session-1'};
257 - @override Future<Map<String,dynamic>> sendAiMessage(String sessionId,String message) async => {'id':'message-1','body':'پاسخ آزمایشی Life Guide'};
258 - @override Future<Map<String,dynamic>> getGuardianWellbeingSummary(String familyId,String minorUserId) async => {'summary':{},'safety':{},'rawNotesIncluded':false,'rawConversationIncluded':false};
259 - @override Future<Map<String,dynamic>> requestFamilyGuidance(String familyId,String minorUserId,String question) async => {'advice':'پیشنهاد آزمایشی','advisory':true,'medicalDiagnosis':false};
286 +class _ProfileNameDialog extends StatefulWidget {
287 + const _ProfileNameDialog({required this.initialName});
288 + final String initialName;
289 + @override
290 + State<_ProfileNameDialog> createState() => _ProfileNameDialogState();
291 +}
292 +
293 +class _ProfileNameDialogState extends State<_ProfileNameDialog> {
294 + final formKey = GlobalKey<FormState>();
295 + late final name = TextEditingController(text: widget.initialName);
296 +
297 + @override
298 + void dispose() {
299 + name.dispose();
300 + super.dispose();
301 + }
302 +
303 + void submit() {
304 + if (formKey.currentState!.validate()) {
305 + Navigator.pop(context, name.text.trim());
306 + }
307 + }
308 +
309 + @override
310 + Widget build(BuildContext context) => AlertDialog(
311 + title: const Text('اسم این پروفایل چیست؟'),
312 + content: Form(
313 + key: formKey,
314 + child: TextFormField(
315 + controller: name,
316 + autofocus: true,
317 + maxLength: 120,
318 + textInputAction: TextInputAction.done,
319 + decoration: const InputDecoration(labelText: 'نام نمایشی'),
320 + validator: (value) => value == null || value.trim().isEmpty
321 + ? 'نام را وارد کن.'
322 + : null,
323 + onFieldSubmitted: (_) => submit(),
324 + )),
325 + actions: [
326 + TextButton(
327 + onPressed: () => Navigator.pop(context),
328 + child: const Text('انصراف')),
329 + FilledButton(onPressed: submit, child: const Text('ادامه')),
330 + ],
331 + );
332 }
apps/lifemate/test/app_test.dart
+179 -44
@@ -1,4 +1,3 @@
1 -import 'package:flutter/material.dart';
1 import 'package:flutter_test/flutter_test.dart';
2 import 'package:lifemate/api.dart';
3 import 'package:lifemate/main.dart';
@@ -8,51 +7,186 @@ class FakeApi implements IdentityApi {
7 FakeApi({this.role = 'teen_minor', this.themePreference = 'girl_pink'});
8 final String role;
9 final String themePreference;
11 - @override String? accessToken;
12 - @override Future<void> login(String email, String password) async { accessToken = 'test-token'; }
13 - @override Future<void> register({required String displayName, required String email, required String password}) async {}
14 - @override Future<void> verifyEmail(String token) async {}
15 - @override Future<void> forgotPassword(String email) async {}
16 - @override Future<void> resetPassword(String token, String newPassword) async {}
17 - @override Future<void> changePassword(String currentPassword, String newPassword) async {}
18 - @override Future<Map<String,dynamic>> getProfile() async => {'display_name': role == 'teen_minor' ? 'آرام' : 'والد','email_normalized':'user@example.test','user_id':role == 'teen_minor' ? 'teen-1':'parent-1','theme_preference':themePreference};
19 - @override Future<Map<String,dynamic>> updateProfile({String? displayName,String? birthDate,String? themePreference}) async => {'display_name':displayName ?? 'والد','theme_preference':themePreference ?? 'adult_blue'};
20 - @override Future<List<Map<String,dynamic>>> listFamilies() async => [{'id':'family-1','name':'خانواده','role':role,'is_admin':role == 'parent_guardian'}];
21 - @override Future<List<Map<String,dynamic>>> listFamilyMembers(String familyId) async => [];
22 - @override Future<Map<String,dynamic>> createFamily(String name,{String? role}) async => {'id':'family-1','name':name};
23 - @override Future<void> inviteMember({required String familyId,required String email,required String role,String? themePreference}) async {}
24 - @override Future<void> acceptInvitation(String token) async {}
25 - @override Future<void> setGuardian({required String familyId,required String guardianUserId,required String minorUserId}) async {}
26 - @override Future<List<Map<String,dynamic>>> getToday({required DateTime from,required DateTime to}) async => [];
27 - @override Future<List<Map<String,dynamic>>> listPlanItems({DateTime? from,DateTime? to,String? kind}) async => [];
28 - @override Future<Map<String,dynamic>> createPlanItem(Map<String,dynamic> data) async => {'id':'new-plan',...data};
29 - @override Future<Map<String,dynamic>> updatePlanItem(String itemId,Map<String,dynamic> data) async => {'id':itemId,...data};
30 - @override Future<List<Map<String,dynamic>>> listLifeContexts() async => [];
31 - @override Future<Map<String,dynamic>> createLifeContext({required String kind,required String title}) async => {'id':'ctx-1','kind':kind,'title':title};
32 - @override Future<Map<String,dynamic>> createAcademicYear(Map<String,dynamic> data) async => {'id':'year-1',...data};
33 - @override Future<Map<String,dynamic>> createAcademicTerm(String yearId,Map<String,dynamic> data) async => {'id':'term-1',...data};
34 - @override Future<Map<String,dynamic>> createSubject(String termId,Map<String,dynamic> data) async => {'id':'subject-1',...data};
35 - @override Future<Map<String,dynamic>> createClassSession(String subjectId,Map<String,dynamic> data) async => {'id':'class-1',...data};
36 - @override Future<Map<String,dynamic>> setGrade(String itemId,{required num points,required num outOf}) async => {'id':itemId};
37 - @override Future<List<Map<String,dynamic>>> claimDueReminders() async => [];
38 - @override Future<Map<String,dynamic>> getSchoolOverview(String studentUserId) async => {'years':[],'subjects':[],'workload':[],'grades':[]};
39 - @override Future<List<Map<String,dynamic>>> getTimetable(String studentUserId) async => [];
40 - @override Future<List<Map<String,dynamic>>> getFamilyCalendar(String familyId) async => [];
41 - @override Future<Map<String,dynamic>> getChildSupportSummary(String familyId,String studentUserId) async => {'upcoming':[],'metrics':{}};
42 - @override Future<Map<String,dynamic>> submitSyncMutations(List<Map<String,dynamic>> mutations) async => {'results':[]};
43 - @override Future<Map<String,dynamic>> createLearningGoal({required String title,String? target,String? subjectId}) async => {'id':'goal-1','title':title};
44 - @override Future<List<Map<String,dynamic>>> listLearningGoals() async => [];
45 - @override Future<Map<String,dynamic>> createLearningCheckin({String? learningGoalId,required int confidence,required int difficulty,String? note}) async => {'id':'checkin-1'};
46 - @override Future<Map<String,dynamic>> createWellbeingCheckin({required int mood,required int energy,required int stress,String? note,String visibility='private'}) async => {'id':'wellbeing-1'};
47 - @override Future<List<Map<String,dynamic>>> listWellbeingCheckins() async => [];
48 - @override Future<Map<String,dynamic>> createAiSession(String kind) async => {'id':'session-1'};
49 - @override Future<Map<String,dynamic>> sendAiMessage(String sessionId,String message) async => {'id':'message-1','body':'پاسخ آزمایشی همراه هوشمند'};
50 - @override Future<Map<String,dynamic>> getGuardianWellbeingSummary(String familyId,String minorUserId) async => {'summary':{},'safety':{},'rawNotesIncluded':false,'rawConversationIncluded':false};
51 - @override Future<Map<String,dynamic>> requestFamilyGuidance(String familyId,String minorUserId,String question) async => {'advice':'پیشنهاد آزمایشی','advisory':true,'medicalDiagnosis':false};
10 + @override
11 + String? accessToken;
12 + @override
13 + Future<void> login(String email, String password) async {
14 + accessToken = 'test-token';
15 + }
16 +
17 + @override
18 + Future<void> register(
19 + {required String displayName,
20 + required String email,
21 + required String password}) async {}
22 + @override
23 + Future<void> verifyEmail(String token) async {}
24 + @override
25 + Future<void> forgotPassword(String email) async {}
26 + @override
27 + Future<void> resetPassword(String token, String newPassword) async {}
28 + @override
29 + Future<void> changePassword(
30 + String currentPassword, String newPassword) async {}
31 + @override
32 + Future<Map<String, dynamic>> getProfile() async => {
33 + 'display_name': role == 'teen_minor' ? 'آرام' : 'والد',
34 + 'email_normalized': 'user@example.test',
35 + 'user_id': role == 'teen_minor' ? 'teen-1' : 'parent-1',
36 + 'theme_preference': themePreference
37 + };
38 + @override
39 + Future<Map<String, dynamic>> updateProfile(
40 + {String? displayName,
41 + String? birthDate,
42 + String? themePreference}) async =>
43 + {
44 + 'display_name': displayName ?? 'والد',
45 + 'theme_preference': themePreference ?? 'adult_blue'
46 + };
47 + @override
48 + Future<List<Map<String, dynamic>>> listFamilies() async => [
49 + {
50 + 'id': 'family-1',
51 + 'name': 'خانواده',
52 + 'role': role,
53 + 'is_admin': role == 'parent_guardian'
54 + }
55 + ];
56 + @override
57 + Future<List<Map<String, dynamic>>> listFamilyMembers(String familyId) async =>
58 + [];
59 + @override
60 + Future<Map<String, dynamic>> createFamily(String name,
61 + {String? role}) async =>
62 + {'id': 'family-1', 'name': name};
63 + @override
64 + Future<void> inviteMember(
65 + {required String familyId,
66 + required String email,
67 + required String role,
68 + String? themePreference}) async {}
69 + @override
70 + Future<void> acceptInvitation(String token) async {}
71 + @override
72 + Future<void> setGuardian(
73 + {required String familyId,
74 + required String guardianUserId,
75 + required String minorUserId}) async {}
76 + @override
77 + Future<List<Map<String, dynamic>>> getToday(
78 + {required DateTime from, required DateTime to}) async =>
79 + [];
80 + @override
81 + Future<List<Map<String, dynamic>>> listPlanItems(
82 + {DateTime? from, DateTime? to, String? kind}) async =>
83 + [];
84 + @override
85 + Future<Map<String, dynamic>> createPlanItem(
86 + Map<String, dynamic> data) async =>
87 + {'id': 'new-plan', ...data};
88 + @override
89 + Future<Map<String, dynamic>> updatePlanItem(
90 + String itemId, Map<String, dynamic> data) async =>
91 + {'id': itemId, ...data};
92 + @override
93 + Future<List<Map<String, dynamic>>> listLifeContexts() async => [];
94 + @override
95 + Future<Map<String, dynamic>> createLifeContext(
96 + {required String kind, required String title}) async =>
97 + {'id': 'ctx-1', 'kind': kind, 'title': title};
98 + @override
99 + Future<Map<String, dynamic>> createAcademicYear(
100 + Map<String, dynamic> data) async =>
101 + {'id': 'year-1', ...data};
102 + @override
103 + Future<Map<String, dynamic>> createAcademicTerm(
104 + String yearId, Map<String, dynamic> data) async =>
105 + {'id': 'term-1', ...data};
106 + @override
107 + Future<Map<String, dynamic>> createSubject(
108 + String termId, Map<String, dynamic> data) async =>
109 + {'id': 'subject-1', ...data};
110 + @override
111 + Future<Map<String, dynamic>> createClassSession(
112 + String subjectId, Map<String, dynamic> data) async =>
113 + {'id': 'class-1', ...data};
114 + @override
115 + Future<Map<String, dynamic>> setGrade(String itemId,
116 + {required num points, required num outOf}) async =>
117 + {'id': itemId};
118 + @override
119 + Future<List<Map<String, dynamic>>> claimDueReminders() async => [];
120 + @override
121 + Future<Map<String, dynamic>> getSchoolOverview(String studentUserId) async =>
122 + {'years': [], 'subjects': [], 'workload': [], 'grades': []};
123 + @override
124 + Future<List<Map<String, dynamic>>> getTimetable(String studentUserId) async =>
125 + [];
126 + @override
127 + Future<List<Map<String, dynamic>>> getFamilyCalendar(String familyId) async =>
128 + [];
129 + @override
130 + Future<Map<String, dynamic>> getChildSupportSummary(
131 + String familyId, String studentUserId) async =>
132 + {'upcoming': [], 'metrics': {}};
133 + @override
134 + Future<Map<String, dynamic>> submitSyncMutations(
135 + List<Map<String, dynamic>> mutations) async =>
136 + {'results': []};
137 + @override
138 + Future<Map<String, dynamic>> createLearningGoal(
139 + {required String title, String? target, String? subjectId}) async =>
140 + {'id': 'goal-1', 'title': title};
141 + @override
142 + Future<List<Map<String, dynamic>>> listLearningGoals() async => [];
143 + @override
144 + Future<Map<String, dynamic>> createLearningCheckin(
145 + {String? learningGoalId,
146 + required int confidence,
147 + required int difficulty,
148 + String? note}) async =>
149 + {'id': 'checkin-1'};
150 + @override
151 + Future<Map<String, dynamic>> createWellbeingCheckin(
152 + {required int mood,
153 + required int energy,
154 + required int stress,
155 + String? note,
156 + String visibility = 'private'}) async =>
157 + {'id': 'wellbeing-1'};
158 + @override
159 + Future<List<Map<String, dynamic>>> listWellbeingCheckins() async => [];
160 + @override
161 + Future<Map<String, dynamic>> createAiSession(String kind) async =>
162 + {'id': 'session-1'};
163 + @override
164 + Future<Map<String, dynamic>> sendAiMessage(
165 + String sessionId, String message) async =>
166 + {'id': 'message-1', 'body': 'پاسخ آزمایشی همراه هوشمند'};
167 + @override
168 + Future<Map<String, dynamic>> getGuardianWellbeingSummary(
169 + String familyId, String minorUserId) async =>
170 + {
171 + 'summary': {},
172 + 'safety': {},
173 + 'rawNotesIncluded': false,
174 + 'rawConversationIncluded': false
175 + };
176 + @override
177 + Future<Map<String, dynamic>> requestFamilyGuidance(
178 + String familyId, String minorUserId, String question) async =>
179 + {
180 + 'advice': 'پیشنهاد آزمایشی',
181 + 'advisory': true,
182 + 'medicalDiagnosis': false
183 + };
184 }
185
186 void main() {
55 - setUp(() { SharedPreferences.setMockInitialValues({}); });
187 + setUp(() {
188 + SharedPreferences.setMockInitialValues({});
189 + });
190
191 testWidgets('starts in Persian RTL with identity actions', (tester) async {
192 await tester.pumpWidget(LifeMateApp(api: FakeApi()));
@@ -61,7 +195,8 @@ void main() {
195 expect(find.text('رمز عبور را فراموش کرده‌ام'), findsOneWidget);
196 });
197
64 - testWidgets('registration explains 10-character password requirement', (tester) async {
198 + testWidgets('registration explains 10-character password requirement',
199 + (tester) async {
200 await tester.pumpWidget(LifeMateApp(api: FakeApi()));
201 await tester.tap(find.text('ساخت حساب جدید'));
202 await tester.pumpAndSettle();
apps/lifemate/test/local_persistence_ui_test.dart new
+563
@@ -0,0 +1,563 @@
1 +import 'dart:async';
2 +import 'dart:convert';
3 +
4 +import 'package:flutter/material.dart';
5 +import 'package:flutter_test/flutter_test.dart';
6 +import 'package:lifemate/api.dart';
7 +import 'package:lifemate/local_data_store.dart';
8 +import 'package:lifemate/local_only_api.dart';
9 +import 'package:lifemate/main.dart';
10 +import 'package:lifemate/phase3_ui.dart';
11 +import 'package:shared_preferences/shared_preferences.dart';
12 +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
13 +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
14 +
15 +import 'app_test.dart' show FakeApi;
16 +
17 +// This simulates the preferences plugin boundary, not Android process restart.
18 +final class _ControlledWrites extends InMemorySharedPreferencesAsync {
19 + _ControlledWrites(super.data) : super.withData();
20 + bool failWrites = false;
21 + Completer<void>? pendingWrite;
22 +
23 + @override
24 + Future<bool> setString(
25 + String key, String value, SharedPreferencesOptions options) async {
26 + if (pendingWrite != null) await pendingWrite!.future;
27 + if (failWrites) throw StateError('simulated persistent storage failure');
28 + return super.setString(key, value, options);
29 + }
30 +}
31 +
32 +late LocalDataSession _testSession;
33 +const _restartMessage =
34 + 'وضعیت ذخیره نامشخص است. برنامه را از تنظیمات دستگاه «توقف اجباری» کن و دوباره باز کن.';
35 +
36 +LocalOnlyApi _open(
37 + {String category = 'girl_minor', LocalDataSession? session}) =>
38 + LocalOnlyApi(
39 + category: category,
40 + displayName: 'آرام مهرآیین',
41 + store: LocalDataStore(
42 + category: category,
43 + displayName: 'آرام مهرآیین',
44 + session: session ?? _testSession),
45 + );
46 +
47 +// This inspects the simulated native snapshot independently of a poisoned API.
48 +Future<Map<String, dynamic>> _nativeSnapshot() async =>
49 + jsonDecode((await SharedPreferencesAsync().getString(LocalDataStore.key))!)
50 + as Map<String, dynamic>;
51 +
52 +Future<void> _expectRestartRequired(Future<Object?> operation) async {
53 + await expectLater(
54 + operation,
55 + throwsA(isA<ApiException>().having(
56 + (error) => error.code,
57 + 'code',
58 + 'local_storage_restart_required',
59 + )));
60 +}
61 +
62 +Future<_ControlledWrites> _controlWrites(
63 + WidgetTester tester, LocalOnlyApi api) async {
64 + await api.getProfile();
65 + return SharedPreferencesAsyncPlatform.instance! as _ControlledWrites;
66 +}
67 +
68 +class _RoleChangingApi extends FakeApi {
69 + String currentRole = 'teen_minor';
70 +
71 + @override
72 + Future<List<Map<String, dynamic>>> listFamilies() async => [
73 + {'id': 'family-1', 'name': 'خانواده', 'role': currentRole},
74 + ];
75 +}
76 +
77 +class _ProductionItemApi extends FakeApi {
78 + @override
79 + Future<List<Map<String, dynamic>>> listPlanItems({
80 + DateTime? from,
81 + DateTime? to,
82 + String? kind,
83 + }) async =>
84 + [
85 + {'id': 'server-item', 'kind': 'task', 'title': 'کار سرور'},
86 + ];
87 +}
88 +
89 +Future<void> _planner(WidgetTester tester, LocalOnlyApi api) async {
90 + await tester.pumpWidget(MaterialApp(
91 + key: UniqueKey(),
92 + home: Scaffold(body: PlannerPage(api: api, localOnly: true)),
93 + ));
94 + await tester.pumpAndSettle();
95 +}
96 +
97 +Future<void> _createForm(WidgetTester tester,
98 + {String title = 'تمرین ریاضی'}) async {
99 + await tester.tap(find.text('جدید'));
100 + await tester.pumpAndSettle();
101 + await tester.enterText(find.byKey(const Key('plan-title')), title);
102 +}
103 +
104 +Future<void> _itemMenu(WidgetTester tester, String action) async {
105 + await tester.tap(find.byType(PopupMenuButton<String>));
106 + await tester.pumpAndSettle();
107 + await tester.tap(find.text(action));
108 + await tester.pumpAndSettle();
109 +}
110 +
111 +void _localWidgetTest(String name, Future<void> Function(WidgetTester) body) {
112 + testWidgets(name, (tester) async {
113 + await tester.runAsync(() => body(tester));
114 + });
115 +}
116 +
117 +void main() {
118 + setUp(() {
119 + _testSession = LocalDataSession();
120 + SharedPreferences.setMockInitialValues({});
121 + SharedPreferencesAsyncPlatform.instance = _ControlledWrites({});
122 + });
123 +
124 + test('restart-required storage errors describe full process recovery', () {
125 + expect(
126 + localDataErrorText(
127 + const ApiException(500, 'local_storage_restart_required')),
128 + _restartMessage);
129 + });
130 +
131 + _localWidgetTest('saved assignment survives recreated planner UI',
132 + (tester) async {
133 + await _planner(tester, _open());
134 + await _createForm(tester);
135 + await tester.tap(find.byKey(const Key('plan-kind')));
136 + await tester.pumpAndSettle();
137 + await tester.tap(find.text('تکلیف').last);
138 + await tester.pumpAndSettle();
139 + await tester.tap(find.text('ذخیره'));
140 + await tester.pumpAndSettle();
141 +
142 + await _planner(tester, _open());
143 + expect(find.text('تمرین ریاضی'), findsOneWidget);
144 + expect((await _open().listPlanItems()).single['kind'], 'assignment');
145 + });
146 +
147 + _localWidgetTest('planner requires a title before saving', (tester) async {
148 + await _planner(tester, _open());
149 + await _createForm(tester, title: ' ');
150 + await tester.tap(find.text('ذخیره'));
151 + await tester.pumpAndSettle();
152 +
153 + expect(find.text('عنوان را وارد کن.'), findsOneWidget);
154 + expect(await _open().listPlanItems(), isEmpty);
155 + });
156 +
157 + _localWidgetTest('local planner keeps older and future saved items visible',
158 + (tester) async {
159 + await _open().createPlanItem({
160 + 'kind': 'assignment',
161 + 'title': 'تکلیف قبلی',
162 + 'dueAt': DateTime.now()
163 + .subtract(const Duration(days: 40))
164 + .toUtc()
165 + .toIso8601String(),
166 + });
167 + await _open().createPlanItem({
168 + 'kind': 'task',
169 + 'title': 'کار آینده',
170 + 'dueAt': DateTime.now()
171 + .add(const Duration(days: 40))
172 + .toUtc()
173 + .toIso8601String(),
174 + });
175 + await _planner(tester, _open());
176 +
177 + expect(find.text('تکلیف قبلی'), findsOneWidget);
178 + expect(find.text('کار آینده'), findsOneWidget);
179 + });
180 +
181 + _localWidgetTest('edited title survives recreated planner UI',
182 + (tester) async {
183 + await _open().createPlanItem({
184 + 'kind': 'assignment',
185 + 'title': 'تمرین ریاضی',
186 + 'dueAt': DateTime.now().toUtc().toIso8601String(),
187 + });
188 + await _planner(tester, _open());
189 + await _itemMenu(tester, 'ویرایش عنوان');
190 + await tester.enterText(find.byKey(const Key('plan-title')), 'تمرین علوم');
191 + await tester.tap(find.text('ذخیره'));
192 + await tester.pumpAndSettle();
193 +
194 + await _planner(tester, _open());
195 + expect(find.text('تمرین علوم'), findsOneWidget);
196 + expect(find.text('تمرین ریاضی'), findsNothing);
197 + });
198 +
199 + _localWidgetTest('archive requires confirmation and survives recreated UI',
200 + (tester) async {
201 + await _open().createPlanItem({
202 + 'kind': 'assignment',
203 + 'title': 'تمرین ریاضی',
204 + 'dueAt': DateTime.now().toUtc().toIso8601String(),
205 + });
206 + await _planner(tester, _open());
207 + await _itemMenu(tester, 'بایگانی');
208 + expect(find.text('بایگانی مورد'), findsOneWidget);
209 + await tester.tap(find.text('انصراف'));
210 + await tester.pumpAndSettle();
211 + expect(find.text('تمرین ریاضی'), findsOneWidget);
212 +
213 + await _itemMenu(tester, 'بایگانی');
214 + await tester.tap(find.widgetWithText(FilledButton, 'بایگانی'));
215 + await tester.pumpAndSettle();
216 + await _planner(tester, _open());
217 + expect(find.text('تمرین ریاضی'), findsNothing);
218 + await tester.pumpWidget(MaterialApp(
219 + home: Scaffold(body: TodayPage(api: _open(), localOnly: true)),
220 + ));
221 + await tester.pumpAndSettle();
222 + expect(find.text('تمرین ریاضی'), findsNothing);
223 + });
224 +
225 + _localWidgetTest(
226 + 'uncertain local save needs full process restart without sync queue',
227 + (tester) async {
228 + final api = _open();
229 + final platform = await _controlWrites(tester, api);
230 + await _planner(tester, api);
231 + platform.failWrites = true;
232 + await _createForm(tester);
233 + await tester.tap(find.text('ذخیره'));
234 + await tester.pumpAndSettle();
235 +
236 + expect(tester.takeException(), isNull);
237 + expect(find.text(_restartMessage), findsOneWidget);
238 + expect(find.byType(AlertDialog), findsOneWidget);
239 + expect((await _nativeSnapshot())['items'], isEmpty);
240 + await _expectRestartRequired(_open().listPlanItems());
241 + expect(
242 + (await SharedPreferences.getInstance())
243 + .containsKey('phase3.sync.queue'),
244 + isFalse);
245 +
246 + platform.failWrites = false;
247 + await tester.tap(find.text('ذخیره'));
248 + await tester.pumpAndSettle();
249 + expect(find.text(_restartMessage), findsOneWidget);
250 + expect((await _nativeSnapshot())['items'], isEmpty);
251 + await _expectRestartRequired(api.listPlanItems());
252 +
253 + // A new coordinator represents a full process restart in this plugin mock.
254 + final restarted = _open(session: LocalDataSession());
255 + expect(await restarted.listPlanItems(), isEmpty);
256 + await _planner(tester, restarted);
257 + await _createForm(tester);
258 + await tester.tap(find.text('ذخیره'));
259 + await tester.pumpAndSettle();
260 + expect((await restarted.listPlanItems()).single['title'], 'تمرین ریاضی');
261 + });
262 +
263 + _localWidgetTest('save button stays disabled until durable write completes',
264 + (tester) async {
265 + final api = _open();
266 + final platform = await _controlWrites(tester, api);
267 + await _planner(tester, api);
268 + await _createForm(tester);
269 + platform.pendingWrite = Completer<void>();
270 + await tester.tap(find.text('ذخیره'));
271 + await tester.pump();
272 +
273 + final button = tester.widget<FilledButton>(
274 + find.widgetWithText(FilledButton, 'در حال ذخیره...'),
275 + );
276 + expect(button.onPressed, isNull);
277 + platform.pendingWrite!.complete();
278 + platform.pendingWrite = null;
279 + await tester.pumpAndSettle();
280 + expect(await _open().listPlanItems(), hasLength(1));
281 + });
282 +
283 + _localWidgetTest(
284 + 'uncertain Today completion stays visible without server cache or queue',
285 + (tester) async {
286 + final api = _open();
287 + await api.createPlanItem({
288 + 'kind': 'assignment',
289 + 'title': 'تمرین ریاضی',
290 + 'dueAt': DateTime.now().toUtc().toIso8601String(),
291 + });
292 + final platform = await _controlWrites(tester, api);
293 + const serverCache = '[{"id":"server-item","title":"نسخه سرور"}]';
294 + SharedPreferences.setMockInitialValues({'phase3.today.cache': serverCache});
295 + await tester.pumpWidget(MaterialApp(
296 + home: Scaffold(body: TodayPage(api: api, localOnly: true)),
297 + ));
298 + await tester.pumpAndSettle();
299 + expect(find.text('تمرین ریاضی'), findsOneWidget);
300 + expect(find.text('نسخه سرور'), findsNothing);
301 + platform.failWrites = true;
302 + await tester.tap(find.byTooltip('انجام شد'));
303 + await tester.pumpAndSettle();
304 +
305 + expect(tester.takeException(), isNull);
306 + expect(find.text(_restartMessage), findsOneWidget);
307 + expect(find.text('تمرین ریاضی'), findsOneWidget);
308 + final legacy = await SharedPreferences.getInstance();
309 + expect(legacy.getString('phase3.today.cache'), serverCache);
310 + expect(legacy.containsKey('phase3.sync.queue'), isFalse);
311 + expect(((await _nativeSnapshot())['items'] as List).single['status'],
312 + 'planned');
313 + platform.failWrites = false;
314 + await tester.tap(find.text('تلاش دوباره'));
315 + await tester.pumpAndSettle();
316 + expect(find.text(_restartMessage), findsOneWidget);
317 + expect(find.text('تمرین ریاضی'), findsOneWidget);
318 + await _expectRestartRequired(api.listPlanItems());
319 +
320 + final restarted = _open(session: LocalDataSession());
321 + expect((await restarted.listPlanItems()).single['status'], 'planned');
322 + await tester.pumpWidget(MaterialApp(
323 + key: UniqueKey(),
324 + home: Scaffold(body: TodayPage(api: restarted, localOnly: true)),
325 + ));
326 + await tester.pumpAndSettle();
327 + await tester.tap(find.byTooltip('انجام شد'));
328 + await tester.pumpAndSettle();
329 + expect(find.text('تمرین ریاضی'), findsNothing);
330 + });
331 +
332 + _localWidgetTest(
333 + 'uncertain reschedule preserves confirmed data until full process restart',
334 + (tester) async {
335 + final api = _open();
336 + final start = DateTime.now();
337 + final due = start.add(const Duration(hours: 2));
338 + await api.createPlanItem({
339 + 'kind': 'assignment',
340 + 'title': 'تمرین ریاضی',
341 + 'startsAt': start.toUtc().toIso8601String(),
342 + 'dueAt': due.toUtc().toIso8601String(),
343 + });
344 + final platform = await _controlWrites(tester, api);
345 + await _planner(tester, api);
346 + platform.failWrites = true;
347 + await _itemMenu(tester, 'انتقال به فردا');
348 +
349 + expect(tester.takeException(), isNull);
350 + expect(find.text(_restartMessage), findsOneWidget);
351 + expect(((await _nativeSnapshot())['items'] as List).single['starts_at'],
352 + start.toUtc().toIso8601String());
353 + expect(
354 + (await SharedPreferences.getInstance())
355 + .containsKey('phase3.sync.queue'),
356 + isFalse);
357 + platform.failWrites = false;
358 + await tester.tap(find.text('تلاش دوباره'));
359 + await tester.pumpAndSettle();
360 + expect(find.text(_restartMessage), findsOneWidget);
361 + await _expectRestartRequired(api.listPlanItems());
362 +
363 + final restarted = _open(session: LocalDataSession());
364 + expect((await restarted.listPlanItems()).single['starts_at'],
365 + start.toUtc().toIso8601String());
366 + await _planner(tester, restarted);
367 + await _itemMenu(tester, 'انتقال به فردا');
368 + final restored = (await restarted.listPlanItems()).single;
369 + expect(restored['starts_at'],
370 + start.add(const Duration(days: 1)).toUtc().toIso8601String());
371 + expect(restored['due_at'],
372 + due.add(const Duration(days: 1)).toUtc().toIso8601String());
373 + });
374 +
375 + _localWidgetTest(
376 + 'local read error is visible and retries without cached server data',
377 + (tester) async {
378 + SharedPreferences.setMockInitialValues({
379 + 'phase3.planner.cache': jsonEncode([
380 + {'id': 'server-item', 'title': 'نسخه سرور', 'kind': 'task'},
381 + ]),
382 + });
383 + await SharedPreferencesAsync().setString(LocalDataStore.key, '{invalid');
384 + await _planner(tester, _open());
385 + expect(find.textContaining('اطلاعات ذخیره‌شده روی دستگاه خراب است'),
386 + findsOneWidget);
387 + expect(find.text('هنوز برنامه‌ای نداری'), findsNothing);
388 + expect(find.text('نسخه سرور'), findsNothing);
389 + expect(find.text('جدید'), findsNothing);
390 +
391 + await SharedPreferencesAsync().remove(LocalDataStore.key);
392 + await _open().createPlanItem({
393 + 'kind': 'task',
394 + 'title': 'بعد از بازیابی',
395 + 'dueAt': DateTime.now().toUtc().toIso8601String(),
396 + });
397 + await tester.tap(find.text('تلاش دوباره'));
398 + await tester.pumpAndSettle();
399 + expect(find.text('بعد از بازیابی'), findsOneWidget);
400 + });
401 +
402 + for (final category in ['girl_minor', 'boy_minor', 'adult']) {
403 + _localWidgetTest('$category routes by profile category without a family',
404 + (tester) async {
405 + await tester.pumpWidget(MaterialApp(
406 + home: HomeShell(
407 + api: _open(category: category),
408 + localOnly: true,
409 + profileCategory: category),
410 + ));
411 + await tester.pumpAndSettle();
412 + expect(find.byType(NavigationDestination), findsNWidgets(3));
413 + expect(find.text('حالت محلی · فقط روی این دستگاه'), findsOneWidget);
414 + expect(find.text('آرام مهرآیین'), findsOneWidget);
415 + expect(find.byType(SchoolPage), findsNothing);
416 + await tester
417 + .tap(find.text(category == 'adult' ? 'برنامه‌ریز' : 'برنامه'));
418 + await tester.pumpAndSettle();
419 + expect(find.text(category == 'adult' ? 'برنامه‌ریز' : 'برنامه هفتگی'),
420 + findsWidgets);
421 + expect(find.byType(PlannerPage), findsOneWidget);
422 + });
423 + }
424 +
425 + _localWidgetTest('local profile exposes only name and theme editing',
426 + (tester) async {
427 + await tester.pumpWidget(MaterialApp(
428 + home: HomeShell(
429 + api: _open(), localOnly: true, profileCategory: 'girl_minor'),
430 + ));
431 + await tester.pumpAndSettle();
432 + await tester.tap(find.byTooltip('پروفایل'));
433 + await tester.pumpAndSettle();
434 +
435 + expect(find.text('آرام مهرآیین'), findsOneWidget);
436 + expect(find.text('قابلیت‌های غیرفعال در حالت محلی'), findsOneWidget);
437 + expect(find.text('خانواده'), findsNothing);
438 + expect(find.text('تغییر رمز عبور'), findsNothing);
439 + });
440 +
441 + _localWidgetTest(
442 + 'local profile edit persists full name and theme after returning home',
443 + (tester) async {
444 + await tester.pumpWidget(MaterialApp(
445 + home: HomeShell(
446 + api: _open(), localOnly: true, profileCategory: 'girl_minor'),
447 + ));
448 + await tester.pumpAndSettle();
449 + await tester.tap(find.byTooltip('پروفایل'));
450 + await tester.pumpAndSettle();
451 + await tester.tap(find.byIcon(Icons.edit_outlined));
452 + await tester.pumpAndSettle();
453 + await tester.enterText(find.byType(TextField), 'سارا مهرآیین');
454 + await tester.tap(find.byType(DropdownButtonFormField<String>));
455 + await tester.pumpAndSettle();
456 + await tester.tap(find.text('سفید / آبی نوجوان').last);
457 + await tester.pumpAndSettle();
458 + await tester.tap(find.text('ذخیره'));
459 + await tester.pumpAndSettle();
460 + await tester.pageBack();
461 + await tester.pumpAndSettle();
462 +
463 + expect(find.text('سارا مهرآیین'), findsOneWidget);
464 + expect(Theme.of(tester.element(find.byType(TodayPage))).colorScheme.primary,
465 + ColorScheme.fromSeed(seedColor: const Color(0xFF4D86E8)).primary);
466 + final restored = await _open().getProfile();
467 + expect(restored['display_name'], 'سارا مهرآیین');
468 + expect(restored['theme_preference'], 'boy_blue');
469 + });
470 +
471 + _localWidgetTest(
472 + 'uncertain profile save preserves old name until full process restart',
473 + (tester) async {
474 + final api = _open();
475 + final platform = await _controlWrites(tester, api);
476 + await tester.pumpWidget(MaterialApp(
477 + home: HomeShell(api: api, localOnly: true, profileCategory: 'girl_minor'),
478 + ));
479 + await tester.pumpAndSettle();
480 + await tester.tap(find.byTooltip('پروفایل'));
481 + await tester.pumpAndSettle();
482 + await tester.tap(find.byIcon(Icons.edit_outlined));
483 + await tester.pumpAndSettle();
484 + await tester.enterText(find.byType(TextField), 'سارا مهرآیین');
485 + platform.failWrites = true;
486 + await tester.tap(find.text('ذخیره'));
487 + await tester.pumpAndSettle();
488 +
489 + expect(tester.takeException(), isNull);
490 + expect(find.text(_restartMessage), findsOneWidget);
491 + expect(
492 + (await _nativeSnapshot())['profile']['display_name'], 'آرام مهرآیین');
493 + await _expectRestartRequired(_open().getProfile());
494 + platform.failWrites = false;
495 + await tester.tap(find.text('ذخیره'));
496 + await tester.pumpAndSettle();
497 + expect(find.text(_restartMessage), findsOneWidget);
498 + expect(
499 + (await _nativeSnapshot())['profile']['display_name'], 'آرام مهرآیین');
500 +
501 + final restarted = _open(session: LocalDataSession());
502 + expect((await restarted.getProfile())['display_name'], 'آرام مهرآیین');
503 + });
504 +
505 + _localWidgetTest('local profile cannot submit again during a durable write',
506 + (tester) async {
507 + final api = _open();
508 + final platform = await _controlWrites(tester, api);
509 + await tester.pumpWidget(MaterialApp(
510 + home: HomeShell(api: api, localOnly: true, profileCategory: 'girl_minor'),
511 + ));
512 + await tester.pumpAndSettle();
513 + await tester.tap(find.byTooltip('پروفایل'));
514 + await tester.pumpAndSettle();
515 + await tester.tap(find.byIcon(Icons.edit_outlined));
516 + await tester.pumpAndSettle();
517 + await tester.enterText(find.byType(TextField), 'سارا مهرآیین');
518 + platform.pendingWrite = Completer<void>();
519 + await tester.tap(find.text('ذخیره'));
520 + await tester.pump();
521 +
522 + final button = tester.widget<FilledButton>(
523 + find.widgetWithText(FilledButton, 'در حال ذخیره...'),
524 + );
525 + expect(button.onPressed, isNull);
526 + platform.pendingWrite!.complete();
527 + platform.pendingWrite = null;
528 + await tester.pumpAndSettle();
529 + expect((await _open().getProfile())['display_name'], 'سارا مهرآیین');
530 + });
531 +
532 + _localWidgetTest(
533 + 'production shell keeps a valid page when family role changes',
534 + (tester) async {
535 + final api = _RoleChangingApi();
536 + await tester.pumpWidget(MaterialApp(home: HomeShell(api: api)));
537 + await tester.pumpAndSettle();
538 + tester.firstState<ScaffoldState>(find.byType(Scaffold)).openDrawer();
539 + await tester.pumpAndSettle();
540 + await tester.tap(find.text('همراه هوشمند'));
541 + await tester.pumpAndSettle();
542 + await tester.tap(find.byTooltip('پروفایل'));
543 + await tester.pumpAndSettle();
544 + api.currentRole = 'parent_guardian';
545 + await tester.pageBack();
546 + await tester.pumpAndSettle();
547 +
548 + expect(tester.takeException(), isNull);
549 + expect(find.text('من'), findsWidgets);
550 + });
551 +
552 + _localWidgetTest('production planner keeps local archive action unavailable',
553 + (tester) async {
554 + await tester.pumpWidget(MaterialApp(
555 + home: Scaffold(body: PlannerPage(api: _ProductionItemApi())),
556 + ));
557 + await tester.pumpAndSettle();
558 + await tester.tap(find.byType(PopupMenuButton<String>));
559 + await tester.pumpAndSettle();
560 +
561 + expect(find.text('بایگانی'), findsNothing);
562 + });
563 +}
apps/lifemate/test/role_entry_test.dart
+38 -4
@@ -1,13 +1,15 @@
1 +import 'package:flutter/material.dart';
2 import 'package:flutter_test/flutter_test.dart';
3 import 'package:lifemate/role_entry_main.dart';
3 -import 'package:shared_preferences/shared_preferences.dart';
4 +import 'local_test_preferences.dart';
5
6 void main() {
7 setUp(() {
7 - SharedPreferences.setMockInitialValues({});
8 + resetLocalPreferences();
9 });
10
10 - testWidgets('first run offers exactly girl child, boy child, and adult', (tester) async {
11 + testWidgets('first run offers exactly girl child, boy child, and adult',
12 + (tester) async {
13 await tester.pumpWidget(const LifeGuideRoleTestApp());
14 await tester.pumpAndSettle();
15
@@ -22,7 +24,8 @@ void main() {
24 expect(find.text('ورود'), findsNothing);
25 });
26
25 - test('local profile store persists category and edited display name', () async {
27 + test('local profile store persists category and edited display name',
28 + () async {
29 final store = LocalTestProfileStore();
30 await store.save(const LocalTestProfile(
31 category: 'girl_minor',
@@ -44,4 +47,35 @@ void main() {
47 throwsArgumentError,
48 );
49 });
50 +
51 + testWidgets('named entry survives complete widget app recreation',
52 + (tester) async {
53 + await tester.pumpWidget(const LifeGuideRoleTestApp());
54 + await tester.pumpAndSettle();
55 + await tester.tap(find.text('فرزند دختر'));
56 + await tester.pumpAndSettle();
57 + await tester.enterText(find.byType(TextField), 'سارا');
58 + await tester.tap(find.text('ادامه'));
59 + await tester.pumpAndSettle();
60 + expect(find.text('سارا'), findsOneWidget);
61 + expect(find.text('حالت محلی · فقط روی این دستگاه'), findsOneWidget);
62 + await tester.pumpWidget(const SizedBox.shrink());
63 + await tester.pumpAndSettle();
64 + await tester.pumpWidget(const LifeGuideRoleTestApp());
65 + await tester.pumpAndSettle();
66 + expect(find.text('سارا'), findsOneWidget);
67 + expect(find.text('چه کسی وارد می‌شود؟'), findsNothing);
68 + });
69 +
70 + testWidgets('legacy adult selection resumes in adult space', (tester) async {
71 + resetLocalPreferences({
72 + 'lifeguide.local_profile.category': 'adult',
73 + 'lifeguide.local_profile.display_name': 'داوود',
74 + });
75 + await tester.pumpWidget(const LifeGuideRoleTestApp());
76 + await tester.pumpAndSettle();
77 + expect(find.text('داوود'), findsOneWidget);
78 + expect(find.text('من'), findsOneWidget);
79 + expect(find.text('چه کسی وارد می‌شود؟'), findsNothing);
80 + });
81 }