LifeMate — Personal, Family & Learning Companion

fix/local-task-persistence
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
dart 1,291 lines 43.8 KB
Raw
1 import 'package:flutter/material.dart';
2 import 'package:flutter_localizations/flutter_localizations.dart';
3
4 import 'api.dart';
5 import 'iran_hub.dart';
6 import 'phase3_ui.dart';
7 import 'phase4_ui.dart';
8
9 void main() => runApp(LifeMateApp());
10
11 class LifeMateApp extends StatelessWidget {
12 LifeMateApp({super.key, IdentityApi? api}) : api = api ?? HttpIdentityApi();
13 final IdentityApi api;
14
15 @override
16 Widget build(BuildContext context) {
17 final uri = Uri.base;
18 final token = uri.queryParameters['token'];
19 Widget entry = SignInPage(
20 api: api,
21 invitationToken: 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);
27 } else if (token != null && uri.path.contains('reset-password')) {
28 entry = ResetPasswordPage(api: api, token: token);
29 }
30 return MaterialApp(
31 debugShowCheckedModeBanner: false,
32 locale: const Locale('fa'),
33 supportedLocales: const [Locale('fa'), Locale('en')],
34 localizationsDelegates: const [
35 GlobalMaterialLocalizations.delegate,
36 GlobalWidgetsLocalizations.delegate,
37 GlobalCupertinoLocalizations.delegate,
38 ],
39 theme: ThemeData(
40 colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF4D86E8)),
41 scaffoldBackgroundColor: const Color(0xFFF8FAFD),
42 inputDecorationTheme:
43 const InputDecorationTheme(border: OutlineInputBorder()),
44 useMaterial3: true,
45 ),
46 home: Directionality(textDirection: TextDirection.rtl, child: entry),
47 );
48 }
49 }
50
51 String errorText(Object error) {
52 if (error is ApiException) {
53 switch (error.code) {
54 case 'invalid_credentials':
55 return 'ایمیل یا رمز عبور صحیح نیست.';
56 case 'email_not_verified':
57 return 'ابتدا ایمیل حساب را تأیید کن.';
58 case 'account_exists':
59 return 'برای این ایمیل قبلاً حساب ساخته شده است.';
60 case 'invalid_password':
61 return 'رمز عبور باید حداقل ۱۰ کاراکتر باشد.';
62 case 'invalid_current_password':
63 return 'رمز فعلی صحیح نیست.';
64 case 'invalid_or_expired_token':
65 return 'لینک منقضی شده یا معتبر نیست.';
66 case 'forbidden':
67 return 'برای این عملیات دسترسی نداری.';
68 }
69 }
70 return 'عملیات انجام نشد. دوباره تلاش کن.';
71 }
72
73 class SignInPage extends StatefulWidget {
74 const SignInPage({super.key, required this.api, this.invitationToken});
75 final IdentityApi api;
76 final String? invitationToken;
77 @override
78 State<SignInPage> createState() => _SignInPageState();
79 }
80
81 class _SignInPageState extends State<SignInPage> {
82 final email = TextEditingController();
83 final password = TextEditingController();
84 bool busy = false;
85 String? error;
86
87 Future<void> submit() async {
88 setState(() {
89 busy = true;
90 error = null;
91 });
92 try {
93 await widget.api.login(email.text, password.text);
94 if (widget.invitationToken != null) {
95 await widget.api.acceptInvitation(widget.invitationToken!);
96 }
97 if (!mounted) return;
98 Navigator.of(context).pushReplacement(
99 MaterialPageRoute(builder: (_) => HomeShell(api: widget.api)),
100 );
101 } catch (e) {
102 if (mounted) setState(() => error = errorText(e));
103 } finally {
104 if (mounted) setState(() => busy = false);
105 }
106 }
107
108 @override
109 Widget build(BuildContext context) => Scaffold(
110 body: SafeArea(
111 child: Center(
112 child: ConstrainedBox(
113 constraints: const BoxConstraints(maxWidth: 440),
114 child: ListView(
115 padding: const EdgeInsets.all(28),
116 shrinkWrap: true,
117 children: [
118 const Icon(Icons.route_rounded, size: 64),
119 const SizedBox(height: 16),
120 const Text('LifeMate',
121 textAlign: TextAlign.center,
122 style:
123 TextStyle(fontSize: 32, fontWeight: FontWeight.w700)),
124 const Text('همراه شخصی، تحصیلی و خانوادگی',
125 textAlign: TextAlign.center),
126 const SizedBox(height: 28),
127 if (widget.invitationToken != null) ...[
128 const Card(
129 child: Padding(
130 padding: EdgeInsets.all(12),
131 child: Text(
132 'برای قبول دعوت خانواده، با همان ایمیل دعوت‌شده وارد شو.'),
133 ),
134 ),
135 const SizedBox(height: 12),
136 ],
137 TextField(
138 controller: email,
139 keyboardType: TextInputType.emailAddress,
140 decoration: const InputDecoration(labelText: 'ایمیل'),
141 ),
142 const SizedBox(height: 12),
143 TextField(
144 controller: password,
145 obscureText: true,
146 decoration: const InputDecoration(labelText: 'رمز عبور'),
147 ),
148 if (error != null) ...[
149 const SizedBox(height: 12),
150 Text(error!,
151 style: TextStyle(
152 color: Theme.of(context).colorScheme.error)),
153 ],
154 const SizedBox(height: 16),
155 FilledButton(
156 onPressed: busy ? null : submit,
157 child: Text(busy ? 'در حال ورود...' : 'ورود'),
158 ),
159 TextButton(
160 onPressed: busy
161 ? null
162 : () => Navigator.of(context).push(MaterialPageRoute(
163 builder: (_) => RecoveryPage(api: widget.api))),
164 child: const Text('رمز عبور را فراموش کرده‌ام'),
165 ),
166 TextButton(
167 onPressed: busy
168 ? null
169 : () => Navigator.of(context).push(MaterialPageRoute(
170 builder: (_) => RegistrationPage(api: widget.api))),
171 child: const Text('ساخت حساب جدید'),
172 ),
173 ],
174 ),
175 ),
176 ),
177 ),
178 );
179 }
180
181 class RegistrationPage extends StatefulWidget {
182 const RegistrationPage({super.key, required this.api});
183 final IdentityApi api;
184 @override
185 State<RegistrationPage> createState() => _RegistrationPageState();
186 }
187
188 class _RegistrationPageState extends State<RegistrationPage> {
189 final name = TextEditingController();
190 final email = TextEditingController();
191 final password = TextEditingController();
192 final confirm = TextEditingController();
193 bool busy = false;
194 String? error;
195
196 Future<void> submit() async {
197 if (password.text != confirm.text) {
198 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
199 return;
200 }
201 setState(() {
202 busy = true;
203 error = null;
204 });
205 try {
206 await widget.api.register(
207 displayName: name.text, email: email.text, password: password.text);
208 if (!mounted) return;
209 ScaffoldMessenger.of(context).showSnackBar(
210 const SnackBar(
211 content: Text('حساب ساخته شد. ایمیل تأیید را بررسی کن.')),
212 );
213 Navigator.pop(context);
214 } catch (e) {
215 if (mounted) setState(() => error = errorText(e));
216 } finally {
217 if (mounted) setState(() => busy = false);
218 }
219 }
220
221 @override
222 Widget build(BuildContext context) => SimpleFormPage(
223 title: 'ساخت حساب',
224 busy: busy,
225 error: error,
226 action: 'ثبت‌نام و ارسال ایمیل تأیید',
227 onPressed: submit,
228 fields: [
229 TextField(
230 controller: name,
231 decoration: const InputDecoration(labelText: 'نام')),
232 TextField(
233 controller: email,
234 keyboardType: TextInputType.emailAddress,
235 decoration: const InputDecoration(labelText: 'ایمیل')),
236 TextField(
237 controller: password,
238 obscureText: true,
239 decoration: const InputDecoration(
240 labelText: 'رمز عبور', helperText: 'حداقل ۱۰ کاراکتر')),
241 TextField(
242 controller: confirm,
243 obscureText: true,
244 decoration: const InputDecoration(labelText: 'تکرار رمز عبور')),
245 ],
246 );
247 }
248
249 class RecoveryPage extends StatefulWidget {
250 const RecoveryPage({super.key, required this.api});
251 final IdentityApi api;
252 @override
253 State<RecoveryPage> createState() => _RecoveryPageState();
254 }
255
256 class _RecoveryPageState extends State<RecoveryPage> {
257 final email = TextEditingController();
258 bool busy = false;
259 bool sent = false;
260 String? error;
261
262 Future<void> submit() async {
263 setState(() {
264 busy = true;
265 error = null;
266 });
267 try {
268 await widget.api.forgotPassword(email.text);
269 if (mounted) setState(() => sent = true);
270 } catch (e) {
271 if (mounted) setState(() => error = errorText(e));
272 } finally {
273 if (mounted) setState(() => busy = false);
274 }
275 }
276
277 @override
278 Widget build(BuildContext context) => SimpleFormPage(
279 title: 'بازیابی رمز عبور',
280 busy: busy,
281 error: error,
282 action: sent ? 'لینک ارسال شد' : 'ارسال لینک بازیابی',
283 onPressed: sent ? null : submit,
284 fields: [
285 TextField(
286 controller: email,
287 keyboardType: TextInputType.emailAddress,
288 decoration: const InputDecoration(labelText: 'ایمیل تأییدشده')),
289 if (sent)
290 const Text(
291 'اگر حسابی با این ایمیل وجود داشته باشد، لینک بازیابی ارسال می‌شود.'),
292 ],
293 );
294 }
295
296 class VerifyEmailPage extends StatefulWidget {
297 const VerifyEmailPage({super.key, required this.api, required this.token});
298 final IdentityApi api;
299 final String token;
300 @override
301 State<VerifyEmailPage> createState() => _VerifyEmailPageState();
302 }
303
304 class _VerifyEmailPageState extends State<VerifyEmailPage> {
305 String message = 'در حال تأیید ایمیل...';
306 @override
307 void initState() {
308 super.initState();
309 verify();
310 }
311
312 Future<void> verify() async {
313 try {
314 await widget.api.verifyEmail(widget.token);
315 if (mounted) setState(() => message = 'ایمیل با موفقیت تأیید شد.');
316 } catch (e) {
317 if (mounted) setState(() => message = errorText(e));
318 }
319 }
320
321 @override
322 Widget build(BuildContext context) =>
323 Scaffold(body: Center(child: Text(message)));
324 }
325
326 class ResetPasswordPage extends StatefulWidget {
327 const ResetPasswordPage({super.key, required this.api, required this.token});
328 final IdentityApi api;
329 final String token;
330 @override
331 State<ResetPasswordPage> createState() => _ResetPasswordPageState();
332 }
333
334 class _ResetPasswordPageState extends State<ResetPasswordPage> {
335 final password = TextEditingController();
336 final confirm = TextEditingController();
337 bool busy = false;
338 bool done = false;
339 String? error;
340
341 Future<void> submit() async {
342 if (password.text != confirm.text) {
343 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
344 return;
345 }
346 setState(() {
347 busy = true;
348 error = null;
349 });
350 try {
351 await widget.api.resetPassword(widget.token, password.text);
352 if (mounted) setState(() => done = true);
353 } catch (e) {
354 if (mounted) setState(() => error = errorText(e));
355 } finally {
356 if (mounted) setState(() => busy = false);
357 }
358 }
359
360 @override
361 Widget build(BuildContext context) => SimpleFormPage(
362 title: 'ساخت رمز جدید',
363 busy: busy,
364 error: error,
365 action: done ? 'رمز تغییر کرد' : 'ذخیره رمز جدید',
366 onPressed: done ? null : submit,
367 fields: [
368 TextField(
369 controller: password,
370 obscureText: true,
371 decoration: const InputDecoration(labelText: 'رمز جدید')),
372 TextField(
373 controller: confirm,
374 obscureText: true,
375 decoration: const InputDecoration(labelText: 'تکرار رمز جدید')),
376 ],
377 );
378 }
379
380 class ChangePasswordPage extends StatefulWidget {
381 const ChangePasswordPage({super.key, required this.api});
382 final IdentityApi api;
383 @override
384 State<ChangePasswordPage> createState() => _ChangePasswordPageState();
385 }
386
387 class _ChangePasswordPageState extends State<ChangePasswordPage> {
388 final current = TextEditingController();
389 final next = TextEditingController();
390 final confirm = TextEditingController();
391 bool busy = false;
392 String? error;
393
394 Future<void> submit() async {
395 if (next.text != confirm.text) {
396 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
397 return;
398 }
399 setState(() {
400 busy = true;
401 error = null;
402 });
403 try {
404 await widget.api.changePassword(current.text, next.text);
405 if (!mounted) return;
406 ScaffoldMessenger.of(context)
407 .showSnackBar(const SnackBar(content: Text('رمز عبور تغییر کرد.')));
408 Navigator.pop(context);
409 } catch (e) {
410 if (mounted) setState(() => error = errorText(e));
411 } finally {
412 if (mounted) setState(() => busy = false);
413 }
414 }
415
416 @override
417 Widget build(BuildContext context) => SimpleFormPage(
418 title: 'تغییر رمز عبور',
419 busy: busy,
420 error: error,
421 action: 'ذخیره رمز جدید',
422 onPressed: submit,
423 fields: [
424 TextField(
425 controller: current,
426 obscureText: true,
427 decoration: const InputDecoration(labelText: 'رمز فعلی')),
428 TextField(
429 controller: next,
430 obscureText: true,
431 decoration: const InputDecoration(labelText: 'رمز جدید')),
432 TextField(
433 controller: confirm,
434 obscureText: true,
435 decoration: const InputDecoration(labelText: 'تکرار رمز جدید')),
436 ],
437 );
438 }
439
440 class SimpleFormPage extends StatelessWidget {
441 const SimpleFormPage({
442 super.key,
443 required this.title,
444 required this.fields,
445 required this.action,
446 required this.onPressed,
447 this.busy = false,
448 this.error,
449 });
450 final String title;
451 final List<Widget> fields;
452 final String action;
453 final VoidCallback? onPressed;
454 final bool busy;
455 final String? error;
456
457 @override
458 Widget build(BuildContext context) => Scaffold(
459 appBar: AppBar(title: Text(title)),
460 body: Center(
461 child: ConstrainedBox(
462 constraints: const BoxConstraints(maxWidth: 520),
463 child: ListView(
464 padding: const EdgeInsets.all(24),
465 children: [
466 for (final field in fields)
467 Padding(
468 padding: const EdgeInsets.only(bottom: 12), child: field),
469 if (error != null)
470 Padding(
471 padding: const EdgeInsets.only(bottom: 12),
472 child: Text(error!,
473 style: TextStyle(
474 color: Theme.of(context).colorScheme.error)),
475 ),
476 FilledButton(
477 onPressed: busy ? null : onPressed,
478 child: Text(busy ? 'لطفاً صبر کن...' : action)),
479 ],
480 ),
481 ),
482 ),
483 );
484 }
485
486 class HomeShell extends StatefulWidget {
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();
499 }
500
501 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 'امروز',
510 'برنامه هفتگی',
511 'تقویم',
512 'تکالیف و کارها',
513 'امتحان‌ها و نمرات',
514 'تمرکز',
515 'همراه هوشمند',
516 ];
517
518 static const adultPages = [
519 'امروز',
520 'برنامه‌ریز',
521 'خانواده',
522 'راهنما',
523 'من',
524 ];
525
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();
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' ||
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;
553 if (index >= pages.length) index = pages.length - 1;
554 contextError = null;
555 });
556 }
557 } catch (error) {
558 if (mounted && widget.localOnly) {
559 setState(() => contextError = localDataErrorText(error));
560 }
561 }
562 }
563
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
574 List<NavigationDestination> get destinations => widget.localOnly
575 ? [
576 const NavigationDestination(
577 icon: Icon(Icons.home_outlined), label: 'امروز'),
578 NavigationDestination(
579 icon: const Icon(Icons.event_note_outlined),
580 label: adultShell ? 'برنامه‌ریز' : 'برنامه'),
581 const NavigationDestination(
582 icon: Icon(Icons.person_outline), label: 'من'),
583 ]
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(
666 colorScheme: ColorScheme.fromSeed(seedColor: accent),
667 scaffoldBackgroundColor: Colors.white,
668 ),
669 child: Scaffold(
670 appBar: AppBar(
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(
682 tooltip: 'پروفایل',
683 onPressed: openProfile,
684 icon: const Icon(Icons.person_outline),
685 ),
686 ],
687 ),
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(
707 selectedIndex: index >= destinations.length ? 0 : index,
708 onDestinationSelected: selectPage,
709 destinations: destinations,
710 ),
711 drawer: Drawer(
712 child: SafeArea(
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 ),
732 ],
733 ]),
734 ),
735 ),
736 ),
737 );
738 }
739
740 class ProfileFamilyPage extends StatefulWidget {
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 }
754
755 class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
756 late Future<List<dynamic>> data;
757 @override
758 void initState() {
759 super.initState();
760 data = load();
761 }
762
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 {
780 final saved = await showDialog<bool>(
781 context: context,
782 barrierDismissible: false,
783 builder: (_) => _ProfileEditDialog(
784 api: widget.api,
785 profile: profile,
786 localOnly: widget.localOnly,
787 ),
788 );
789 if (saved == true && mounted) {
790 setState(() {
791 data = load();
792 });
793 await widget.onProfileUpdated?.call();
794 }
795 }
796
797 Future<void> createFamily() async {
798 final name = TextEditingController();
799 final created = await showDialog<bool>(
800 context: context,
801 builder: (dialogContext) => AlertDialog(
802 title: const Text('ساخت فضای خانواده'),
803 content: TextField(
804 controller: name,
805 decoration: const InputDecoration(labelText: 'نام خانواده')),
806 actions: [
807 TextButton(
808 onPressed: () => Navigator.pop(dialogContext, false),
809 child: const Text('انصراف')),
810 FilledButton(
811 onPressed: () async {
812 if (name.text.trim().isEmpty) return;
813 await widget.api
814 .createFamily(name.text.trim(), role: 'parent_guardian');
815 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
816 },
817 child: const Text('ساخت'),
818 ),
819 ],
820 ),
821 );
822 name.dispose();
823 if (created == true && mounted) {
824 setState(() {
825 data = load();
826 });
827 }
828 }
829
830 Future<void> invite(String familyId) async {
831 final email = TextEditingController();
832 final choice = ValueNotifier<String>('daughter');
833 final sent = await showDialog<bool>(
834 context: context,
835 builder: (dialogContext) => AlertDialog(
836 title: const Text('دعوت فرزند / عضو'),
837 content: Column(mainAxisSize: MainAxisSize.min, children: [
838 TextField(
839 controller: email,
840 keyboardType: TextInputType.emailAddress,
841 decoration: const InputDecoration(labelText: 'ایمیل')),
842 const SizedBox(height: 12),
843 ValueListenableBuilder<String>(
844 valueListenable: choice,
845 builder: (_, value, __) => DropdownButtonFormField<String>(
846 initialValue: value,
847 decoration: const InputDecoration(labelText: 'نوع عضو'),
848 items: const [
849 DropdownMenuItem(
850 value: 'daughter',
851 child: Text('فرزند دختر — سفید / صورتی')),
852 DropdownMenuItem(
853 value: 'son', child: Text('فرزند پسر — سفید / آبی')),
854 DropdownMenuItem(
855 value: 'parent', child: Text('والد / سرپرست — سفید / آبی')),
856 DropdownMenuItem(
857 value: 'adult', child: Text('عضو بزرگسال — سفید / آبی')),
858 ],
859 onChanged: (v) {
860 if (v != null) choice.value = v;
861 },
862 ),
863 ),
864 ]),
865 actions: [
866 TextButton(
867 onPressed: () => Navigator.pop(dialogContext, false),
868 child: const Text('انصراف')),
869 FilledButton(
870 onPressed: () async {
871 final selected = choice.value;
872 final role = selected == 'parent'
873 ? 'parent_guardian'
874 : selected == 'adult'
875 ? 'adult_member'
876 : 'teen_minor';
877 final theme = selected == 'daughter'
878 ? 'girl_pink'
879 : selected == 'son'
880 ? 'boy_blue'
881 : 'adult_blue';
882 await widget.api.inviteMember(
883 familyId: familyId,
884 email: email.text,
885 role: role,
886 themePreference: theme);
887 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
888 },
889 child: const Text('ارسال دعوت'),
890 ),
891 ],
892 ),
893 );
894 email.dispose();
895 choice.dispose();
896 if (sent == true && mounted) {
897 ScaffoldMessenger.of(context)
898 .showSnackBar(const SnackBar(content: Text('دعوت ارسال شد.')));
899 }
900 }
901
902 @override
903 Widget build(BuildContext context) => Scaffold(
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) {
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: [
957 Card(
958 child: ListTile(
959 leading: const CircleAvatar(child: Icon(Icons.person)),
960 title: Text(
961 profile['display_name']?.toString() ?? 'پروفایل من'),
962 subtitle:
963 Text(profile['email_normalized']?.toString() ?? ''),
964 trailing: IconButton(
965 onPressed: () => editProfile(profile),
966 icon: const Icon(Icons.edit_outlined)),
967 ),
968 ),
969 const SizedBox(height: 12),
970 if (families.isEmpty)
971 Card(
972 child: ListTile(
973 leading: const Icon(Icons.family_restroom),
974 title: const Text('هنوز فضای خانواده ساخته نشده'),
975 trailing: IconButton(
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),
983 title: Text(family['name']?.toString() ?? 'خانواده'),
984 subtitle: Text(
985 '${family['is_admin'] == true ? 'مدیر خانواده · ' : ''}${family['role'] ?? ''}'),
986 onTap: () => Navigator.of(context).push(
987 MaterialPageRoute(
988 builder: (_) => FamilyMembersPage(
989 api: widget.api,
990 familyId: family['id'].toString(),
991 familyName:
992 family['name']?.toString() ?? 'خانواده',
993 isAdmin: family['is_admin'] == true,
994 ),
995 ),
996 ),
997 trailing: IconButton(
998 onPressed: () => invite(family['id'].toString()),
999 icon: const Icon(Icons.person_add_alt)),
1000 ),
1001 )),
1002 ListTile(
1003 leading: const Icon(Icons.public),
1004 title: const Text('خانواده و یادگیری ایران'),
1005 subtitle: const Text(
1006 'نقش‌ها، پایه تحصیلی، کتاب‌ها، تقویم و یادآوری'),
1007 onTap: () => Navigator.of(context).push(MaterialPageRoute(
1008 builder: (_) =>
1009 IranianFamilyLearningHub(identity: widget.api),
1010 )),
1011 ),
1012 ListTile(
1013 leading: const Icon(Icons.password),
1014 title: const Text('تغییر رمز عبور'),
1015 onTap: () => Navigator.of(context).push(MaterialPageRoute(
1016 builder: (_) => ChangePasswordPage(api: widget.api))),
1017 ),
1018 const ListTile(
1019 leading: Icon(Icons.privacy_tip_outlined),
1020 title: Text('حریم خصوصی و دسترسی‌ها'),
1021 subtitle:
1022 Text('خصوصی، اعضای منتخب، والد/سرپرست، خانواده، ایمنی'),
1023 ),
1024 ],
1025 );
1026 },
1027 ),
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
1144 class FamilyMembersPage extends StatefulWidget {
1145 const FamilyMembersPage({
1146 super.key,
1147 required this.api,
1148 required this.familyId,
1149 required this.familyName,
1150 required this.isAdmin,
1151 });
1152 final IdentityApi api;
1153 final String familyId;
1154 final String familyName;
1155 final bool isAdmin;
1156 @override
1157 State<FamilyMembersPage> createState() => _FamilyMembersPageState();
1158 }
1159
1160 class _FamilyMembersPageState extends State<FamilyMembersPage> {
1161 late Future<List<Map<String, dynamic>>> members;
1162 @override
1163 void initState() {
1164 super.initState();
1165 members = widget.api.listFamilyMembers(widget.familyId);
1166 }
1167
1168 String roleLabel(String role) => switch (role) {
1169 'parent_guardian' => 'والد / سرپرست',
1170 'teen_minor' => 'فرزند / نوجوان',
1171 'adult_member' => 'عضو بزرگسال',
1172 _ => role,
1173 };
1174
1175 Future<void> configureGuardian(List<Map<String, dynamic>> items) async {
1176 final guardians =
1177 items.where((m) => m['role'] == 'parent_guardian').toList();
1178 final minors = items.where((m) => m['role'] == 'teen_minor').toList();
1179 if (guardians.isEmpty || minors.isEmpty) {
1180 ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
1181 content:
1182 Text('برای ثبت سرپرستی، حداقل یک والد و یک فرزند لازم است.')));
1183 return;
1184 }
1185 final guardianId =
1186 ValueNotifier<String>(guardians.first['user_id'].toString());
1187 final minorId = ValueNotifier<String>(minors.first['user_id'].toString());
1188 final saved = await showDialog<bool>(
1189 context: context,
1190 builder: (dialogContext) => AlertDialog(
1191 title: const Text('رابطه والد و فرزند'),
1192 content: Column(mainAxisSize: MainAxisSize.min, children: [
1193 ValueListenableBuilder<String>(
1194 valueListenable: guardianId,
1195 builder: (_, value, __) => DropdownButtonFormField<String>(
1196 initialValue: value,
1197 decoration: const InputDecoration(labelText: 'والد / سرپرست'),
1198 items: guardians
1199 .map((m) => DropdownMenuItem(
1200 value: m['user_id'].toString(),
1201 child: Text(m['display_name']?.toString() ?? 'والد')))
1202 .toList(),
1203 onChanged: (v) {
1204 if (v != null) guardianId.value = v;
1205 },
1206 ),
1207 ),
1208 const SizedBox(height: 12),
1209 ValueListenableBuilder<String>(
1210 valueListenable: minorId,
1211 builder: (_, value, __) => DropdownButtonFormField<String>(
1212 initialValue: value,
1213 decoration: const InputDecoration(labelText: 'فرزند'),
1214 items: minors
1215 .map((m) => DropdownMenuItem(
1216 value: m['user_id'].toString(),
1217 child: Text(m['display_name']?.toString() ?? 'فرزند')))
1218 .toList(),
1219 onChanged: (v) {
1220 if (v != null) minorId.value = v;
1221 },
1222 ),
1223 ),
1224 ]),
1225 actions: [
1226 TextButton(
1227 onPressed: () => Navigator.pop(dialogContext, false),
1228 child: const Text('انصراف')),
1229 FilledButton(
1230 onPressed: () async {
1231 await widget.api.setGuardian(
1232 familyId: widget.familyId,
1233 guardianUserId: guardianId.value,
1234 minorUserId: minorId.value);
1235 if (dialogContext.mounted) Navigator.pop(dialogContext, true);
1236 },
1237 child: const Text('ثبت رابطه'),
1238 ),
1239 ],
1240 ),
1241 );
1242 guardianId.dispose();
1243 minorId.dispose();
1244 if (saved == true && mounted) {
1245 ScaffoldMessenger.of(context)
1246 .showSnackBar(const SnackBar(content: Text('رابطه سرپرستی ثبت شد.')));
1247 }
1248 }
1249
1250 @override
1251 Widget build(BuildContext context) => Scaffold(
1252 appBar: AppBar(title: Text(widget.familyName)),
1253 body: FutureBuilder<List<Map<String, dynamic>>>(
1254 future: members,
1255 builder: (context, snapshot) {
1256 if (snapshot.hasError) {
1257 return Center(child: Text(errorText(snapshot.error!)));
1258 }
1259 if (!snapshot.hasData) {
1260 return const Center(child: CircularProgressIndicator());
1261 }
1262 final items = snapshot.data!;
1263 return ListView(
1264 padding: const EdgeInsets.all(20),
1265 children: [
1266 for (final member in items)
1267 Card(
1268 child: ListTile(
1269 leading: const CircleAvatar(child: Icon(Icons.person)),
1270 title: Text(member['display_name']?.toString() ?? 'عضو'),
1271 subtitle:
1272 Text(roleLabel(member['role']?.toString() ?? '')),
1273 trailing: member['is_admin'] == true
1274 ? const Chip(label: Text('مدیر'))
1275 : null,
1276 ),
1277 ),
1278 if (widget.isAdmin) ...[
1279 const SizedBox(height: 12),
1280 FilledButton.icon(
1281 onPressed: () => configureGuardian(items),
1282 icon: const Icon(Icons.supervisor_account_outlined),
1283 label: const Text('تنظیم رابطه والد و فرزند'),
1284 ),
1285 ],
1286 ],
1287 );
1288 },
1289 ),
1290 );
1291 }