LifeMate — Personal, Family & Learning Companion

feat/flutter-mobile-navigation
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,973 lines 73.5 KB
Raw
1 import 'dart:async';
2
3 import 'package:flutter/services.dart';
4 import 'package:flutter/material.dart';
5 import 'package:flutter_localizations/flutter_localizations.dart';
6
7 import 'api.dart';
8 import 'mobile_home.dart';
9 import 'study_ui.dart';
10 import 'dashboard_ui.dart';
11 import 'iran_hub.dart';
12 import 'education_ui.dart';
13 import 'content_review_sync.dart';
14 import 'content_review_ui.dart';
15 import 'learning_reviews_ui.dart';
16 import 'learning_goals_ui.dart';
17 import 'family_management_ui.dart';
18 import 'phase3_ui.dart';
19 import 'runtime_controller.dart';
20 import 'endpoint_settings.dart';
21 import 'offline_store.dart';
22 import 'notifications_ui.dart';
23 import 'sync_changes_ui.dart';
24 import 'web_instance.dart';
25 import 'package:flutter/foundation.dart';
26
27 void main() {
28 requireWebInstanceOwnership();
29 WidgetsFlutterBinding.ensureInitialized();
30 runApp(const LifeMateApp());
31 }
32
33 class LifeMateApp extends StatefulWidget {
34 const LifeMateApp({super.key, this.api, this.runtime});
35 final IdentityApi? api;
36 final RuntimeController? runtime;
37
38 @override
39 State<LifeMateApp> createState() => _LifeMateAppState();
40 }
41
42 class _LifeMateAppState extends State<LifeMateApp> {
43 RuntimeController? runtime;
44 bool invitationAccepted = false;
45 GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
46 Object? navigatorScope;
47
48 @override
49 void initState() {
50 super.initState();
51 if (widget.api == null) {
52 runtime = widget.runtime ??
53 RuntimeController(
54 onScopeDiscarded: OfflineStore.clearNamespace,
55 onScopeQuarantined: OfflineStore.invalidateNamespace);
56 if (!runtime!.initialized) runtime!.initialize();
57 }
58 }
59
60 @override
61 void dispose() {
62 if (widget.runtime == null) runtime?.dispose();
63 super.dispose();
64 }
65
66 Future<void> editEndpoints() async {
67 final controller = runtime!;
68 await navigatorKey.currentState!.push(MaterialPageRoute(
69 builder: (_) => EndpointSettingsPage(
70 initialConfig: controller.config,
71 onSaved: (next) async {
72 final api = controller.api;
73 if (api?.accessToken != null &&
74 !await confirmScopeDiscard(
75 navigatorKey.currentState!.overlay!.context, api!)) {
76 return;
77 }
78 await controller.updateEndpoints(next);
79 },
80 ),
81 ));
82 }
83
84 Widget entry(IdentityApi api, {bool managed = false}) {
85 final uri = Uri.base;
86 final token = uri.queryParameters['token'];
87 final invitation =
88 token != null && uri.path.contains('accept-invitation') ? token : null;
89 if (api.accessToken != null) {
90 if (managed && invitation != null && !invitationAccepted) {
91 return _InvitationGate(
92 api: api,
93 token: invitation,
94 onAccepted: () {
95 if (mounted) setState(() => invitationAccepted = true);
96 });
97 }
98 return HomeShell(
99 api: api,
100 onSignOut: managed ? runtime!.signOut : null,
101 onEndpointSettings: managed ? editEndpoints : null);
102 }
103 if (token != null && uri.path.contains('verify-email')) {
104 return VerifyEmailPage(api: api, token: token);
105 }
106 if (token != null && uri.path.contains('reset-password')) {
107 return ResetPasswordPage(api: api, token: token);
108 }
109 return SignInPage(
110 api: api,
111 invitationToken: invitation,
112 runtimeManaged: managed,
113 sessionQuarantined: api is HttpIdentityApi && api.hasQuarantinedSession,
114 onEndpointSettings: managed ? editEndpoints : null);
115 }
116
117 Widget app(Widget home, {Object? scope}) {
118 if (navigatorScope != scope) {
119 navigatorScope = scope;
120 navigatorKey = GlobalKey<NavigatorState>();
121 invitationAccepted = false;
122 }
123 return MaterialApp(
124 navigatorKey: navigatorKey,
125 key: ValueKey(scope),
126 title: 'LifeGuide · لایف‌گاید',
127 debugShowCheckedModeBanner: false,
128 locale: const Locale('fa'),
129 supportedLocales: const [Locale('fa'), Locale('en')],
130 localizationsDelegates: const [
131 GlobalMaterialLocalizations.delegate,
132 GlobalWidgetsLocalizations.delegate,
133 GlobalCupertinoLocalizations.delegate,
134 ],
135 theme: ThemeData(
136 fontFamily: 'LifeGuidePersian',
137 fontFamilyFallback: const ['LifeGuideLatin', 'LifeGuideEmoji'],
138 colorScheme: ColorScheme.fromSeed(seedColor: MobileHomeMenu.accent),
139 scaffoldBackgroundColor: MobileHomeMenu.paper,
140 inputDecorationTheme:
141 const InputDecorationTheme(border: OutlineInputBorder()),
142 useMaterial3: true,
143 ),
144 home: Directionality(textDirection: TextDirection.rtl, child: home),
145 );
146 }
147
148 @override
149 Widget build(BuildContext context) {
150 if (widget.api != null) return app(entry(widget.api!));
151 return AnimatedBuilder(
152 animation: runtime!,
153 builder: (_, __) {
154 final controller = runtime!;
155 Widget home;
156 if (!controller.initialized) {
157 home = const Scaffold(
158 body: Center(child: CircularProgressIndicator()));
159 } else if (kIsWeb && controller.error != null) {
160 home = Scaffold(
161 appBar: AppBar(title: const Text('اتصال لایف‌گاید')),
162 body: LoadError(
163 error: controller.error!, retry: controller.initialize));
164 } else if (!controller.config.isConfigured ||
165 controller.api == null) {
166 home = EndpointSettingsPage(
167 initialConfig: controller.config,
168 onSaved: controller.updateEndpoints);
169 } else if (controller.error != null &&
170 controller.api!.accessToken == null) {
171 home = Scaffold(
172 appBar: AppBar(title: const Text('اتصال لایف‌گاید')),
173 body: Center(
174 child: Column(mainAxisSize: MainAxisSize.min, children: [
175 const Text('بازیابی اتصال یا ورود انجام نشد.'),
176 Text(errorText(controller.error!)),
177 TextButton(
178 onPressed: controller.initialize,
179 child: const Text('تلاش دوباره')),
180 TextButton(
181 onPressed: editEndpoints, child: const Text('تنظیم اتصال')),
182 ])),
183 );
184 } else {
185 home = entry(controller.api!, managed: true);
186 }
187 return app(home,
188 scope:
189 '${controller.config.apiBaseUrl}|${controller.cacheNamespace ?? 'signed-out'}');
190 });
191 }
192 }
193
194 class _InvitationGate extends StatefulWidget {
195 const _InvitationGate(
196 {required this.api, required this.token, required this.onAccepted});
197 final IdentityApi api;
198 final String token;
199 final VoidCallback onAccepted;
200 @override
201 State<_InvitationGate> createState() => _InvitationGateState();
202 }
203
204 class _InvitationGateState extends State<_InvitationGate> {
205 bool busy = false;
206 String? error;
207 @override
208 void initState() {
209 super.initState();
210 accept();
211 }
212
213 Future<void> accept() async {
214 if (busy) return;
215 setState(() {
216 busy = true;
217 error = null;
218 });
219 try {
220 await widget.api.acceptInvitation(widget.token);
221 if (mounted) widget.onAccepted();
222 } catch (failure) {
223 if (mounted) setState(() => error = errorText(failure));
224 } finally {
225 if (mounted) setState(() => busy = false);
226 }
227 }
228
229 @override
230 Widget build(BuildContext context) => Scaffold(
231 appBar: AppBar(title: const Text('پذیرش دعوت خانواده')),
232 body: Center(
233 child: Column(mainAxisSize: MainAxisSize.min, children: [
234 if (busy) const CircularProgressIndicator(),
235 if (error != null) Text(error!),
236 if (!busy)
237 TextButton(onPressed: accept, child: const Text('تلاش دوباره')),
238 ])),
239 );
240 }
241
242 Future<bool> confirmScopeDiscard(BuildContext context, IdentityApi api) async {
243 int? pending;
244 try {
245 pending = await OfflineStore.forApi(api).pendingCount();
246 } catch (_) {
247 /* Unknown storage must also require an explicit discard choice. */
248 }
249 if (pending == 0) return true;
250 if (!context.mounted) return false;
251 return await showDialog<bool>(
252 context: context,
253 builder: (c) => AlertDialog(
254 title: const Text('تغییرهای تأییدنشده'),
255 content: Text(pending == null
256 ? 'وضعیت تغییر معلق دستگاه قابل خواندن نیست. خروج یا تغییر سرویس، داده و تغییرهای تأییدنشده این حساب را از دستگاه حذف می‌کند.'
257 : '$pending تغییر معلق هنوز در سرور تأیید نشده است. خروج یا تغییر سرویس، این تغییرها و نسخه ذخیره‌شده حساب را از دستگاه حذف می‌کند.'),
258 actions: [
259 TextButton(
260 onPressed: () => Navigator.pop(c, false),
261 child: const Text('انصراف')),
262 FilledButton(
263 onPressed: () => Navigator.pop(c, true),
264 child: const Text('ادامه و حذف تغییرها'))
265 ])) ??
266 false;
267 }
268
269 String errorText(Object error) {
270 if (error is ApiException) {
271 if (error.code.startsWith('local_') ||
272 error.statusCode == 0 ||
273 error.statusCode >= 500 ||
274 error.statusCode == 403 ||
275 [
276 'sync_conflict',
277 'version_conflict',
278 'sms_unavailable',
279 'invalid_or_expired_otp',
280 'rate_limited'
281 ].contains(error.code)) {
282 return uiErrorText(error);
283 }
284 switch (error.code) {
285 case 'invalid_credentials':
286 return 'ایمیل یا رمز عبور صحیح نیست.';
287 case 'email_not_verified':
288 return 'ابتدا ایمیل حساب را تأیید کن.';
289 case 'account_exists':
290 return 'عملیات انجام نشد. دوباره تلاش کن.';
291 case 'invalid_password':
292 return 'رمز عبور باید حداقل ۱۰ کاراکتر باشد.';
293 case 'invalid_current_password':
294 return 'رمز فعلی صحیح نیست.';
295 case 'invalid_or_expired_token':
296 return 'لینک منقضی شده یا معتبر نیست.';
297 case 'forbidden':
298 return 'برای این عملیات دسترسی نداری.';
299 }
300 }
301 return 'عملیات انجام نشد. دوباره تلاش کن.';
302 }
303
304 class SignInPage extends StatefulWidget {
305 const SignInPage(
306 {super.key,
307 required this.api,
308 this.invitationToken,
309 this.runtimeManaged = false,
310 this.sessionQuarantined = false,
311 this.onEndpointSettings});
312 final IdentityApi api;
313 final String? invitationToken;
314 final bool runtimeManaged;
315 final bool sessionQuarantined;
316 final Future<void> Function()? onEndpointSettings;
317 @override
318 State<SignInPage> createState() => _SignInPageState();
319 }
320
321 class _SignInPageState extends State<SignInPage> {
322 final email = TextEditingController();
323 final password = TextEditingController();
324 bool busy = false;
325 String? error;
326
327 Future<void> submit() async {
328 setState(() {
329 busy = true;
330 error = null;
331 });
332 try {
333 await widget.api.login(email.text, password.text);
334 if (!widget.runtimeManaged && widget.invitationToken != null) {
335 await widget.api.acceptInvitation(widget.invitationToken!);
336 }
337 if (!mounted || widget.runtimeManaged) return;
338 Navigator.of(context).pushReplacement(
339 MaterialPageRoute(builder: (_) => HomeShell(api: widget.api)),
340 );
341 } catch (e) {
342 if (mounted) setState(() => error = errorText(e));
343 } finally {
344 if (mounted) setState(() => busy = false);
345 }
346 }
347
348 @override
349 Widget build(BuildContext context) => Scaffold(
350 body: SafeArea(
351 child: Center(
352 child: ConstrainedBox(
353 constraints: const BoxConstraints(maxWidth: 440),
354 child: ListView(
355 padding: const EdgeInsets.all(28),
356 shrinkWrap: true,
357 children: [
358 const Icon(Icons.route_rounded, size: 64),
359 const SizedBox(height: 16),
360 const Text('LifeGuide',
361 textAlign: TextAlign.center,
362 style:
363 TextStyle(fontSize: 32, fontWeight: FontWeight.w700)),
364 const Text('لایف‌گاید · همراه تحصیلی و خانوادگی',
365 textAlign: TextAlign.center),
366 const SizedBox(height: 28),
367 if (widget.sessionQuarantined) ...[
368 const Card(
369 child: Padding(
370 padding: EdgeInsets.all(12),
371 child: Text(
372 'نشستت پایان یافته است. تغییرهای ارسال‌نشده این دستگاه حذف نشده‌اند. برای ادامه با همان حساب و سرویس دوباره وارد شو.'),
373 ),
374 ),
375 const SizedBox(height: 12),
376 ],
377 if (widget.invitationToken != null) ...[
378 const Card(
379 child: Padding(
380 padding: EdgeInsets.all(12),
381 child: Text(
382 'برای قبول دعوت خانواده، با همان ایمیل دعوت‌شده وارد شو.'),
383 ),
384 ),
385 const SizedBox(height: 12),
386 ],
387 TextField(
388 controller: email,
389 keyboardType: TextInputType.emailAddress,
390 decoration:
391 const InputDecoration(labelText: 'ایمیل یا شماره تلفن'),
392 ),
393 const SizedBox(height: 12),
394 TextField(
395 controller: password,
396 obscureText: true,
397 decoration: const InputDecoration(labelText: 'رمز عبور'),
398 ),
399 if (error != null) ...[
400 const SizedBox(height: 12),
401 Text(error!,
402 style: TextStyle(
403 color: Theme.of(context).colorScheme.error)),
404 ],
405 const SizedBox(height: 16),
406 FilledButton(
407 onPressed: busy ? null : submit,
408 child: Text(busy ? 'در حال ورود...' : 'ورود'),
409 ),
410 TextButton(
411 onPressed: busy
412 ? null
413 : () => Navigator.of(context).push(MaterialPageRoute(
414 builder: (_) => RecoveryPage(api: widget.api))),
415 child: const Text('رمز عبور را فراموش کرده‌ام'),
416 ),
417 TextButton(
418 onPressed: busy
419 ? null
420 : () => Navigator.of(context).push(MaterialPageRoute(
421 builder: (_) => RegistrationPage(api: widget.api))),
422 child: const Text('ساخت حساب جدید'),
423 ),
424 if (widget.api is HttpIdentityApi) ...[
425 TextButton(
426 onPressed: busy
427 ? null
428 : () => Navigator.push(
429 context,
430 MaterialPageRoute(
431 builder: (_) => PhoneOtpPage(
432 api: widget.api as HttpIdentityApi))),
433 child: const Text('ورود با کد پیامکی')),
434 TextButton(
435 onPressed: busy
436 ? null
437 : () => Navigator.push(
438 context,
439 MaterialPageRoute(
440 builder: (_) => ResendVerificationPage(
441 api: widget.api as HttpIdentityApi))),
442 child: const Text('ارسال دوباره ایمیل تأیید')),
443 ],
444 if (widget.onEndpointSettings != null && !kIsWeb)
445 TextButton(
446 onPressed: busy ? null : widget.onEndpointSettings,
447 child: const Text('تنظیم اتصال')),
448 ],
449 ),
450 ),
451 ),
452 ),
453 );
454 @override
455 void dispose() {
456 email.dispose();
457 password.dispose();
458 super.dispose();
459 }
460 }
461
462 class RegistrationPage extends StatefulWidget {
463 const RegistrationPage({super.key, required this.api});
464 final IdentityApi api;
465 @override
466 State<RegistrationPage> createState() => _RegistrationPageState();
467 }
468
469 class _RegistrationPageState extends State<RegistrationPage> {
470 final name = TextEditingController(),
471 contact = TextEditingController(),
472 password = TextEditingController(),
473 confirm = TextEditingController();
474 bool phone = false, busy = false;
475 String? error, message;
476 Future<void> submit() async {
477 if (busy) return;
478 if (name.text.trim().isEmpty || contact.text.trim().isEmpty) {
479 setState(() => error = 'نام و یک راه تماس را وارد کن.');
480 return;
481 }
482 if (password.text != confirm.text) {
483 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
484 return;
485 }
486 setState(() {
487 busy = true;
488 error = null;
489 message = null;
490 });
491 try {
492 if (widget.api is HttpIdentityApi) {
493 await (widget.api as HttpIdentityApi).registerContact(
494 displayName: name.text.trim(),
495 password: password.text,
496 email: phone ? null : contact.text.trim(),
497 phone: phone ? contact.text.trim() : null);
498 } else {
499 await widget.api.register(
500 displayName: name.text.trim(),
501 email: contact.text.trim(),
502 password: password.text);
503 }
504 if (mounted) {
505 setState(() => message = phone
506 ? 'درخواست بررسی شد. تحویل پیامک تنها پس از پاسخ سرویس ارسال مشخص می‌شود.'
507 : 'درخواست بررسی شد. اگر این راه تماس واجد شرایط باشد، پیام تأیید ارسال می‌شود؛ تحویل ایمیل تأیید نشده است.');
508 }
509 } catch (e) {
510 if (mounted) setState(() => error = errorText(e));
511 } finally {
512 if (mounted) setState(() => busy = false);
513 }
514 }
515
516 @override
517 void dispose() {
518 name.dispose();
519 contact.dispose();
520 password.dispose();
521 confirm.dispose();
522 super.dispose();
523 }
524
525 @override
526 Widget build(BuildContext context) => SimpleFormPage(
527 title: 'ساخت حساب',
528 busy: busy,
529 error: error,
530 action: 'ثبت درخواست',
531 onPressed: submit,
532 fields: [
533 TextField(
534 controller: name,
535 decoration: const InputDecoration(labelText: 'نام')),
536 if (widget.api is HttpIdentityApi)
537 SegmentedButton<bool>(
538 segments: const [
539 ButtonSegment(value: false, label: Text('ایمیل')),
540 ButtonSegment(value: true, label: Text('تلفن'))
541 ],
542 selected: {
543 phone
544 },
545 onSelectionChanged:
546 busy ? null : (v) => setState(() => phone = v.first)),
547 TextField(
548 controller: contact,
549 keyboardType:
550 phone ? TextInputType.phone : TextInputType.emailAddress,
551 decoration: InputDecoration(
552 labelText: phone ? 'شماره تلفن' : 'ایمیل',
553 helperText: 'فقط یک راه تماس برای این حساب ثبت می‌شود.')),
554 TextField(
555 controller: password,
556 obscureText: true,
557 decoration: const InputDecoration(
558 labelText: 'رمز عبور', helperText: 'حداقل ۱۰ کاراکتر')),
559 TextField(
560 controller: confirm,
561 obscureText: true,
562 decoration: const InputDecoration(labelText: 'تکرار رمز عبور')),
563 if (message != null) Text(message!),
564 if (message != null && phone && widget.api is HttpIdentityApi)
565 TextButton(
566 onPressed: () => Navigator.push(
567 context,
568 MaterialPageRoute(
569 builder: (_) => PhoneOtpPage(
570 api: widget.api as HttpIdentityApi,
571 initialPhone: contact.text,
572 purpose: 'verify'))),
573 child: const Text('تأیید شماره تلفن')),
574 ]);
575 }
576
577 class ResendVerificationPage extends StatefulWidget {
578 const ResendVerificationPage({super.key, required this.api});
579 final HttpIdentityApi api;
580 @override
581 State<ResendVerificationPage> createState() => _ResendVerificationPageState();
582 }
583
584 class _ResendVerificationPageState extends State<ResendVerificationPage> {
585 final email = TextEditingController();
586 bool busy = false;
587 String? error, message;
588 Future<void> send() async {
589 setState(() {
590 busy = true;
591 error = null;
592 message = null;
593 });
594 try {
595 await widget.api.resendVerification(email.text.trim());
596 if (mounted) {
597 setState(() => message =
598 'درخواست بررسی شد. اگر این ایمیل واجد شرایط باشد، پیام تأیید ارسال می‌شود؛ تحویل آن تأیید نشده است.');
599 }
600 } catch (e) {
601 if (mounted) setState(() => error = errorText(e));
602 } finally {
603 if (mounted) setState(() => busy = false);
604 }
605 }
606
607 @override
608 void dispose() {
609 email.dispose();
610 super.dispose();
611 }
612
613 @override
614 Widget build(BuildContext context) => SimpleFormPage(
615 title: 'ارسال دوباره ایمیل تأیید',
616 busy: busy,
617 error: error,
618 action: 'ثبت درخواست ارسال',
619 onPressed: send,
620 fields: [
621 TextField(
622 controller: email,
623 keyboardType: TextInputType.emailAddress,
624 decoration: const InputDecoration(labelText: 'ایمیل')),
625 if (message != null) Text(message!)
626 ]);
627 }
628
629 class PhoneOtpPage extends StatefulWidget {
630 const PhoneOtpPage(
631 {super.key,
632 required this.api,
633 this.initialPhone = '',
634 this.purpose = 'login'});
635 final HttpIdentityApi api;
636 final String initialPhone, purpose;
637 @override
638 State<PhoneOtpPage> createState() => _PhoneOtpPageState();
639 }
640
641 class _PhoneOtpPageState extends State<PhoneOtpPage> {
642 late final TextEditingController phone;
643 final code = TextEditingController(), password = TextEditingController();
644 String? challenge, error, message;
645 bool busy = false;
646 String purpose = 'login';
647 @override
648 void initState() {
649 super.initState();
650 phone = TextEditingController(text: widget.initialPhone);
651 purpose = widget.purpose;
652 }
653
654 Future<void> request() async {
655 setState(() {
656 busy = true;
657 error = null;
658 message = null;
659 challenge = null;
660 });
661 try {
662 final response =
663 await widget.api.requestPhoneOtp(phone.text.trim(), purpose: purpose);
664 final id = response['challengeId'];
665 if (id is! String || id.isEmpty) {
666 throw const ApiException(502, 'invalid_otp_response');
667 }
668 if (mounted) {
669 setState(() {
670 challenge = id;
671 message = 'درخواست کد پذیرفته شد. تحویل پیامک تأیید نشده است.';
672 });
673 }
674 } catch (e) {
675 if (mounted) setState(() => error = errorText(e));
676 } finally {
677 if (mounted) setState(() => busy = false);
678 }
679 }
680
681 Future<void> verify() async {
682 setState(() {
683 busy = true;
684 error = null;
685 });
686 try {
687 await widget.api.verifyPhoneOtp(challenge!, code.text.trim(),
688 newPassword: password.text.isEmpty ? null : password.text);
689 if (mounted) {
690 Navigator.pop(context);
691 }
692 } catch (e) {
693 if (mounted) setState(() => error = errorText(e));
694 } finally {
695 if (mounted) setState(() => busy = false);
696 }
697 }
698
699 @override
700 void dispose() {
701 phone.dispose();
702 code.dispose();
703 password.dispose();
704 super.dispose();
705 }
706
707 @override
708 Widget build(BuildContext context) => SimpleFormPage(
709 title: 'ورود و تأیید تلفن',
710 busy: busy,
711 error: error,
712 action: challenge == null ? 'درخواست کد' : 'تأیید کد',
713 onPressed: challenge == null ? request : verify,
714 fields: [
715 if (challenge == null)
716 DropdownButtonFormField<String>(
717 initialValue: purpose,
718 decoration: const InputDecoration(labelText: 'هدف درخواست'),
719 items: const [
720 DropdownMenuItem(value: 'login', child: Text('ورود')),
721 DropdownMenuItem(
722 value: 'verify', child: Text('تأیید شماره')),
723 DropdownMenuItem(
724 value: 'recovery', child: Text('بازیابی رمز'))
725 ],
726 onChanged: busy
727 ? null
728 : (v) => setState(() => purpose = v ?? purpose)),
729 TextField(
730 controller: phone,
731 enabled: challenge == null && !busy,
732 keyboardType: TextInputType.phone,
733 decoration: const InputDecoration(labelText: 'شماره تلفن')),
734 if (challenge != null)
735 TextField(
736 controller: code,
737 keyboardType: TextInputType.number,
738 decoration: const InputDecoration(labelText: 'کد پیامکی')),
739 if (challenge != null)
740 TextField(
741 controller: password,
742 obscureText: true,
743 decoration: const InputDecoration(
744 labelText: 'رمز عبور جدید',
745 helperText:
746 'برای تأیید اولیه و بازیابی، حداقل ۱۰ کاراکتر لازم است.')),
747 if (message != null) Text(message!),
748 if (challenge != null)
749 TextButton(
750 onPressed: busy ? null : request,
751 child: const Text('درخواست کد تازه')),
752 ]);
753 }
754
755 class RecoveryPage extends StatefulWidget {
756 const RecoveryPage({super.key, required this.api});
757 final IdentityApi api;
758 @override
759 State<RecoveryPage> createState() => _RecoveryPageState();
760 }
761
762 class _RecoveryPageState extends State<RecoveryPage> {
763 final email = TextEditingController();
764 bool busy = false;
765 bool sent = false;
766 String? error;
767
768 Future<void> submit() async {
769 setState(() {
770 busy = true;
771 error = null;
772 });
773 try {
774 await widget.api.forgotPassword(email.text);
775 if (mounted) setState(() => sent = true);
776 } catch (e) {
777 if (mounted) setState(() => error = errorText(e));
778 } finally {
779 if (mounted) setState(() => busy = false);
780 }
781 }
782
783 @override
784 Widget build(BuildContext context) => SimpleFormPage(
785 title: 'بازیابی رمز عبور',
786 busy: busy,
787 error: error,
788 action: sent ? 'درخواست بررسی شد' : 'ارسال لینک بازیابی',
789 onPressed: sent ? null : submit,
790 fields: [
791 TextField(
792 controller: email,
793 keyboardType: TextInputType.emailAddress,
794 decoration: const InputDecoration(labelText: 'ایمیل تأییدشده')),
795 if (sent)
796 const Text(
797 'اگر حسابی با این ایمیل وجود داشته باشد، لینک بازیابی ارسال می‌شود.'),
798 ],
799 );
800 }
801
802 class VerifyEmailPage extends StatefulWidget {
803 const VerifyEmailPage({super.key, required this.api, required this.token});
804 final IdentityApi api;
805 final String token;
806 @override
807 State<VerifyEmailPage> createState() => _VerifyEmailPageState();
808 }
809
810 class _VerifyEmailPageState extends State<VerifyEmailPage> {
811 final password = TextEditingController(), confirm = TextEditingController();
812 bool busy = false, done = false;
813 String? error;
814 Future<void> verify() async {
815 if (password.text != confirm.text) {
816 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
817 return;
818 }
819 setState(() {
820 busy = true;
821 error = null;
822 });
823 try {
824 await widget.api.verifyEmail(widget.token, newPassword: password.text);
825 if (mounted) setState(() => done = true);
826 } catch (e) {
827 if (mounted) setState(() => error = errorText(e));
828 } finally {
829 if (mounted) setState(() => busy = false);
830 }
831 }
832
833 @override
834 void dispose() {
835 password.dispose();
836 confirm.dispose();
837 super.dispose();
838 }
839
840 @override
841 Widget build(BuildContext context) => SimpleFormPage(
842 title: 'تأیید مالکیت ایمیل',
843 busy: busy,
844 error: error,
845 action: done ? 'ایمیل تأیید شد' : 'تأیید و تعیین رمز عبور',
846 onPressed: done ? null : verify,
847 fields: [
848 const Text(
849 'برای تکمیل مالکیت این حساب، رمز عبور جدید خودت را تعیین کن.'),
850 TextField(
851 controller: password,
852 obscureText: true,
853 decoration: const InputDecoration(
854 labelText: 'رمز عبور جدید',
855 helperText: 'حداقل ۱۰ کاراکتر')),
856 TextField(
857 controller: confirm,
858 obscureText: true,
859 decoration: const InputDecoration(labelText: 'تکرار رمز عبور'))
860 ]);
861 }
862
863 class ResetPasswordPage extends StatefulWidget {
864 const ResetPasswordPage({super.key, required this.api, required this.token});
865 final IdentityApi api;
866 final String token;
867 @override
868 State<ResetPasswordPage> createState() => _ResetPasswordPageState();
869 }
870
871 class _ResetPasswordPageState extends State<ResetPasswordPage> {
872 final password = TextEditingController();
873 final confirm = TextEditingController();
874 bool busy = false;
875 bool done = false;
876 String? error;
877
878 Future<void> submit() async {
879 if (password.text != confirm.text) {
880 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
881 return;
882 }
883 setState(() {
884 busy = true;
885 error = null;
886 });
887 try {
888 await widget.api.resetPassword(widget.token, password.text);
889 if (mounted) setState(() => done = true);
890 } catch (e) {
891 if (mounted) setState(() => error = errorText(e));
892 } finally {
893 if (mounted) setState(() => busy = false);
894 }
895 }
896
897 @override
898 Widget build(BuildContext context) => SimpleFormPage(
899 title: 'ساخت رمز جدید',
900 busy: busy,
901 error: error,
902 action: done ? 'رمز تغییر کرد' : 'ذخیره رمز جدید',
903 onPressed: done ? null : submit,
904 fields: [
905 TextField(
906 controller: password,
907 obscureText: true,
908 decoration: const InputDecoration(labelText: 'رمز جدید')),
909 TextField(
910 controller: confirm,
911 obscureText: true,
912 decoration: const InputDecoration(labelText: 'تکرار رمز جدید')),
913 ],
914 );
915 }
916
917 class ChangePasswordPage extends StatefulWidget {
918 const ChangePasswordPage({super.key, required this.api});
919 final IdentityApi api;
920 @override
921 State<ChangePasswordPage> createState() => _ChangePasswordPageState();
922 }
923
924 class _ChangePasswordPageState extends State<ChangePasswordPage> {
925 final current = TextEditingController();
926 final next = TextEditingController();
927 final confirm = TextEditingController();
928 bool busy = false;
929 String? error;
930
931 Future<void> submit() async {
932 if (next.text != confirm.text) {
933 setState(() => error = 'تکرار رمز عبور یکسان نیست.');
934 return;
935 }
936 setState(() {
937 busy = true;
938 error = null;
939 });
940 try {
941 await widget.api.changePassword(current.text, next.text);
942 if (!mounted) return;
943 ScaffoldMessenger.of(context)
944 .showSnackBar(const SnackBar(content: Text('رمز عبور تغییر کرد.')));
945 Navigator.pop(context);
946 } catch (e) {
947 if (mounted) setState(() => error = errorText(e));
948 } finally {
949 if (mounted) setState(() => busy = false);
950 }
951 }
952
953 @override
954 Widget build(BuildContext context) => SimpleFormPage(
955 title: 'تغییر رمز عبور',
956 busy: busy,
957 error: error,
958 action: 'ذخیره رمز جدید',
959 onPressed: submit,
960 fields: [
961 TextField(
962 controller: current,
963 obscureText: true,
964 decoration: const InputDecoration(labelText: 'رمز فعلی')),
965 TextField(
966 controller: next,
967 obscureText: true,
968 decoration: const InputDecoration(labelText: 'رمز جدید')),
969 TextField(
970 controller: confirm,
971 obscureText: true,
972 decoration: const InputDecoration(labelText: 'تکرار رمز جدید')),
973 ],
974 );
975 }
976
977 class SimpleFormPage extends StatelessWidget {
978 const SimpleFormPage({
979 super.key,
980 required this.title,
981 required this.fields,
982 required this.action,
983 required this.onPressed,
984 this.busy = false,
985 this.error,
986 });
987 final String title;
988 final List<Widget> fields;
989 final String action;
990 final VoidCallback? onPressed;
991 final bool busy;
992 final String? error;
993
994 @override
995 Widget build(BuildContext context) => Scaffold(
996 appBar: AppBar(title: Text(title)),
997 body: Center(
998 child: ConstrainedBox(
999 constraints: const BoxConstraints(maxWidth: 520),
1000 child: ListView(
1001 padding: const EdgeInsets.all(24),
1002 children: [
1003 for (final field in fields)
1004 Padding(
1005 padding: const EdgeInsets.only(bottom: 12), child: field),
1006 if (error != null)
1007 Padding(
1008 padding: const EdgeInsets.only(bottom: 12),
1009 child: Text(error!,
1010 style: TextStyle(
1011 color: Theme.of(context).colorScheme.error)),
1012 ),
1013 FilledButton(
1014 onPressed: busy ? null : onPressed,
1015 child: Text(busy ? 'لطفاً صبر کن...' : action)),
1016 ],
1017 ),
1018 ),
1019 ),
1020 );
1021 }
1022
1023 class HomeShell extends StatefulWidget {
1024 const HomeShell(
1025 {super.key, required this.api, this.onSignOut, this.onEndpointSettings});
1026 final IdentityApi api;
1027 final Future<void> Function()? onSignOut;
1028 final Future<void> Function()? onEndpointSettings;
1029
1030 @override
1031 State<HomeShell> createState() => _HomeShellState();
1032 }
1033
1034 class _HomeShellState extends State<HomeShell> with WidgetsBindingObserver {
1035 String page = 'خانه';
1036 String displayName = '';
1037 bool contextLoaded = false;
1038 String themePreference = 'adult_blue';
1039 bool adultShell = false;
1040 String? contextError;
1041 Set<String> contentPermissions = {};
1042 Timer? capabilityPoll;
1043 int capabilityEpoch = 0;
1044
1045 HttpIdentityApi? get httpApi =>
1046 widget.api is HttpIdentityApi ? widget.api as HttpIdentityApi : null;
1047
1048 static const studentPages = [
1049 'خانه',
1050 'برنامه من',
1051 'درس‌ها',
1052 'تمرکز',
1053 'خانواده',
1054 'امتحان‌ها و نمرات',
1055 'همراه هوشمند',
1056 ];
1057 static const adultPages = [
1058 'خانه',
1059 'برنامه‌ریز',
1060 'خانواده',
1061 'گزارش‌ها',
1062 'من',
1063 'راهنما',
1064 'مدرسه من',
1065 ];
1066
1067 @override
1068 void initState() {
1069 super.initState();
1070 WidgetsBinding.instance.addObserver(this);
1071 loadContext();
1072 if (httpApi != null) {
1073 loadCapabilities();
1074 capabilityPoll = Timer.periodic(
1075 const Duration(seconds: 30), (_) => loadCapabilities());
1076 }
1077 }
1078
1079 @override
1080 void dispose() {
1081 capabilityEpoch++;
1082 capabilityPoll?.cancel();
1083 WidgetsBinding.instance.removeObserver(this);
1084 super.dispose();
1085 }
1086
1087 @override
1088 void didChangeAppLifecycleState(AppLifecycleState state) {
1089 capabilityEpoch++;
1090 if (mounted) setState(() => contentPermissions = {});
1091 if (state == AppLifecycleState.resumed) loadCapabilities();
1092 }
1093
1094 Future<void> loadCapabilities() async {
1095 final api = httpApi;
1096 final scope = api?.cacheNamespace;
1097 final epoch = ++capabilityEpoch;
1098 if (mounted) setState(() => contentPermissions = {});
1099 if (api == null || scope == null) return;
1100 try {
1101 final permissions = await ContentReviewSync(api).capabilities();
1102 if (mounted &&
1103 epoch == capabilityEpoch &&
1104 identical(api, httpApi) &&
1105 scope == api.cacheNamespace) {
1106 setState(() => contentPermissions = permissions);
1107 }
1108 } catch (_) {
1109 // A menu is only a navigation aid. The actual operations always re-check
1110 // current server capabilities; family/profile roles never grant them.
1111 }
1112 }
1113
1114 Future<void> openReviewedLesson(BuildContext origin, String unitId) async {
1115 final api = httpApi;
1116 if (api == null) return;
1117 final scope = api.cacheNamespace;
1118 try {
1119 final result = await api.requestJson(
1120 'GET', '/v1/education/units/${Uri.encodeComponent(unitId)}');
1121 if (!origin.mounted || scope == null || scope != api.cacheNamespace) {
1122 return;
1123 }
1124 final unit = result['unit'];
1125 if (unit is! Map || unit['id'] != unitId || unit['courseId'] is! String) {
1126 throw const ApiException(502, 'invalid_unit_response');
1127 }
1128 await Navigator.of(origin).push(MaterialPageRoute(
1129 builder: (_) => LearningLessonPage(
1130 api: api, courseId: unit['courseId'] as String, unitId: unitId)));
1131 } catch (error) {
1132 if (origin.mounted && scope == api.cacheNamespace) {
1133 ScaffoldMessenger.of(origin).showSnackBar(SnackBar(
1134 content: Text(error is ApiException && error.statusCode == 404
1135 ? 'این درس دیگر در فهرست فعال نیست؛ تاریخچه ثبت‌شده محفوظ است.'
1136 : uiErrorText(error))));
1137 }
1138 }
1139 }
1140
1141 Future<void> loadContext() async {
1142 final scope = httpApi?.cacheNamespace;
1143 try {
1144 final profile = await widget.api.getProfile();
1145 if (mounted && (httpApi == null || scope == httpApi!.cacheNamespace)) {
1146 setState(() {
1147 themePreference =
1148 profile['theme_preference']?.toString() ?? 'adult_blue';
1149 final category = profile['profile_category']?.toString();
1150 adultShell = category == 'adult' ||
1151 (!['girl_minor', 'boy_minor'].contains(category) &&
1152 !['girl_pink', 'boy_blue'].contains(themePreference));
1153 displayName = profile['display_name']?.toString() ?? 'همراه';
1154 contextLoaded = true;
1155 contextError = null;
1156 if (!pages.contains(page)) page = 'خانه';
1157 });
1158 }
1159 } catch (error) {
1160 if (mounted) {
1161 setState(() {
1162 contextError = errorText(error);
1163 if (!isOfflineFailure(error)) contextLoaded = false;
1164 });
1165 }
1166 }
1167 }
1168
1169 List<String> get pages => adultShell ? adultPages : studentPages;
1170
1171 // Keep the account's saved accent choice; category never grants permissions.
1172 Color get accountAccent => switch (themePreference) {
1173 'girl_pink' => const Color(0xFFB66D88),
1174 'boy_blue' || 'adult_blue' => const Color(0xFF4B7995),
1175 _ => MobileHomeMenu.accent,
1176 };
1177
1178 List<String> get primaryPages => adultShell
1179 ? ['خانه', 'برنامه‌ریز', 'خانواده', 'گزارش‌ها', 'من']
1180 : ['خانه', 'برنامه من', 'درس‌ها', 'تمرکز', 'خانواده'];
1181
1182 List<NavigationDestination> get destinations => adultShell
1183 ? const [
1184 NavigationDestination(icon: Icon(Icons.home_outlined), label: 'خانه'),
1185 NavigationDestination(
1186 icon: Icon(Icons.event_note_outlined), label: 'برنامه‌ریز'),
1187 NavigationDestination(
1188 icon: Icon(Icons.people_outline), label: 'خانواده'),
1189 NavigationDestination(
1190 icon: Icon(Icons.bar_chart_outlined), label: 'گزارش‌ها'),
1191 NavigationDestination(
1192 icon: Icon(Icons.person_outline), label: 'بیشتر'),
1193 ]
1194 : const [
1195 NavigationDestination(icon: Icon(Icons.home_outlined), label: 'خانه'),
1196 NavigationDestination(
1197 icon: Icon(Icons.event_note_outlined), label: 'برنامه'),
1198 NavigationDestination(
1199 icon: Icon(Icons.menu_book_outlined), label: 'درس‌ها'),
1200 NavigationDestination(
1201 icon: Icon(Icons.timelapse_outlined), label: 'تمرکز'),
1202 NavigationDestination(
1203 icon: Icon(Icons.people_outline), label: 'خانواده'),
1204 ];
1205
1206 void selectPage(String next) {
1207 final refreshProfile = ['من', 'خانواده'].contains(page) && next == 'خانه';
1208 setState(() => page = next);
1209 if (refreshProfile) loadContext();
1210 }
1211
1212 void openHomeMenu(String destination) => selectPage(switch (destination) {
1213 'plan' => adultShell ? 'برنامه‌ریز' : 'برنامه من',
1214 'courses' => 'درس‌ها',
1215 'focus' => 'تمرکز',
1216 'family' => 'خانواده',
1217 'report' => adultShell ? 'گزارش‌ها' : 'گزارش من',
1218 'reminders' => 'یادآوری‌ها',
1219 _ => 'خانه',
1220 });
1221
1222 Widget pageContent() {
1223 if (!contextLoaded) {
1224 return contextError == null
1225 ? const Center(child: CircularProgressIndicator())
1226 : LoadError(
1227 error: const ApiException(503, 'profile_unavailable'),
1228 retry: loadContext);
1229 }
1230 if (page == 'خانه') {
1231 return MobileHomeMenu(
1232 displayName: displayName, adult: adultShell, onOpen: openHomeMenu);
1233 }
1234 if (['درس‌ها', 'مدرسه من'].contains(page)) {
1235 return EducationLibraryPage(api: widget.api);
1236 }
1237 if (page == 'برنامه من') {
1238 return PlannerPage(api: widget.api);
1239 }
1240 if (page == 'تمرکز') {
1241 return StudyHub(api: widget.api);
1242 }
1243 if (page == 'گزارش‌ها') {
1244 return ParentFamilyDashboard(api: widget.api);
1245 }
1246 if (page == 'گزارش من') {
1247 return httpApi == null
1248 ? const CoreNotice(
1249 title: 'گزارش یادگیری',
1250 subtitle: 'برای دریافت گزارش، اتصال به حساب معتبر لازم است.')
1251 : LearningReviewsPage(
1252 api: httpApi!, onOpenLesson: openReviewedLesson);
1253 }
1254 if (page == 'یادآوری‌ها') {
1255 return NotificationInboxPage(api: widget.api, embedded: true);
1256 }
1257 if (page == 'خانواده' || page == 'من') {
1258 return ProfileFamilyPage(api: widget.api, embedded: true);
1259 }
1260 if (page == 'همراه هوشمند' || page == 'راهنما') {
1261 return const CoreNotice(
1262 title: 'همراه هوشمند',
1263 subtitle:
1264 'در این مرحله فعال نیست؛ داده سلامت و گفت‌وگو به سرویس هوشمند ارسال نمی‌شود.');
1265 }
1266 return Phase3HomeContent(
1267 api: widget.api, page: page, adultShell: adultShell);
1268 }
1269
1270 @override
1271 Widget build(BuildContext context) => Theme(
1272 data: Theme.of(context).copyWith(
1273 colorScheme: ColorScheme.fromSeed(seedColor: accountAccent),
1274 scaffoldBackgroundColor: MobileHomeMenu.paper,
1275 appBarTheme: const AppBarTheme(
1276 backgroundColor: MobileHomeMenu.paper,
1277 foregroundColor: MobileHomeMenu.ink,
1278 elevation: 0,
1279 surfaceTintColor: Colors.transparent),
1280 ),
1281 child: PopScope(
1282 canPop: page == 'خانه',
1283 onPopInvokedWithResult: (didPop, _) {
1284 if (!didPop) selectPage('خانه');
1285 },
1286 child: Scaffold(
1287 appBar: AppBar(
1288 leading: page == 'خانه'
1289 ? null
1290 : IconButton(
1291 tooltip: 'برگشت به خانه',
1292 onPressed: () => selectPage('خانه'),
1293 icon: const Icon(Icons.arrow_back)),
1294 title: Text(page == 'خانه' ? 'لایف‌گاید' : page),
1295 actions: [
1296 IconButton(
1297 tooltip: 'یادآوری‌ها',
1298 icon: const Icon(Icons.notifications_none),
1299 onPressed: () => selectPage('یادآوری‌ها')),
1300 IconButton(
1301 tooltip: 'حساب و تنظیمات',
1302 icon: const Icon(Icons.person_outline),
1303 onPressed: () => selectPage('من')),
1304 ],
1305 ),
1306 body: Column(children: [
1307 if (contextLoaded && contextError != null)
1308 MaterialBanner(
1309 content: const Text(
1310 'اطلاعات حساب از آخرین دریافت است؛ تازه‌سازی اتصال انجام نشد.'),
1311 actions: [
1312 TextButton(
1313 onPressed: loadContext,
1314 child: const Text('تلاش دوباره'))
1315 ]),
1316 Expanded(child: pageContent()),
1317 ]),
1318 bottomNavigationBar: NavigationBar(
1319 selectedIndex: primaryPages.contains(page)
1320 ? primaryPages.indexOf(page)
1321 : 0,
1322 onDestinationSelected: (index) =>
1323 selectPage(primaryPages[index]),
1324 destinations: destinations,
1325 ),
1326 drawer: Drawer(
1327 child: SafeArea(
1328 child: ListView(
1329 children: [
1330 const ListTile(
1331 title: Text('LifeGuide'),
1332 subtitle: Text('منوی اصلی'),
1333 ),
1334 ...pages.asMap().entries.map(
1335 (entry) => ListTile(
1336 title: Text(entry.value),
1337 onTap: () {
1338 selectPage(entry.value);
1339 Navigator.pop(context);
1340 },
1341 ),
1342 ),
1343 ListTile(
1344 leading: const Icon(Icons.notifications_outlined),
1345 title: const Text('اعلان‌های درون برنامه'),
1346 onTap: () {
1347 Navigator.pop(context);
1348 Navigator.of(context).push(MaterialPageRoute(
1349 builder: (_) =>
1350 NotificationInboxPage(api: widget.api)));
1351 }),
1352 ListTile(
1353 leading: const Icon(Icons.sync_problem_outlined),
1354 title: const Text('تغییرهای معلق و تعارض‌ها'),
1355 onTap: () {
1356 Navigator.pop(context);
1357 Navigator.of(context).push(MaterialPageRoute(
1358 builder: (_) =>
1359 SyncChangesPage(api: widget.api)));
1360 }),
1361 if (httpApi != null)
1362 ListTile(
1363 leading: const Icon(Icons.flag_outlined),
1364 title: const Text('اهداف یادگیری'),
1365 onTap: () {
1366 Navigator.pop(context);
1367 Navigator.of(context).push(MaterialPageRoute(
1368 builder: (_) =>
1369 LearningGoalsPage(api: httpApi!)));
1370 }),
1371 if (httpApi != null)
1372 ListTile(
1373 leading: const Icon(Icons.history_edu_outlined),
1374 title: const Text('مرور و تاریخچه یادگیری'),
1375 onTap: () {
1376 Navigator.pop(context);
1377 Navigator.of(context).push(MaterialPageRoute(
1378 builder: (_) => LearningReviewsPage(
1379 api: httpApi!,
1380 onOpenLesson: openReviewedLesson)));
1381 }),
1382 if (httpApi != null &&
1383 contentPermissions.contains('feedback.read'))
1384 ListTile(
1385 leading: const Icon(Icons.fact_check_outlined),
1386 title: const Text('بررسی محتوای آموزشی'),
1387 onTap: () async {
1388 Navigator.pop(context);
1389 await Navigator.of(context).push(
1390 MaterialPageRoute(
1391 builder: (_) =>
1392 ContentReviewPage(api: httpApi!)));
1393 if (mounted) await loadCapabilities();
1394 }),
1395 if (widget.onEndpointSettings != null && !kIsWeb)
1396 ListTile(
1397 leading: const Icon(Icons.settings_ethernet),
1398 title: const Text('تنظیم اتصال'),
1399 onTap: () {
1400 Navigator.pop(context);
1401 widget.onEndpointSettings!();
1402 }),
1403 if (widget.onSignOut != null)
1404 ListTile(
1405 leading: const Icon(Icons.logout),
1406 title: const Text('خروج از حساب'),
1407 onTap: () async {
1408 Navigator.pop(context);
1409 try {
1410 if (!await confirmScopeDiscard(
1411 context, widget.api)) {
1412 return;
1413 }
1414 await widget.onSignOut!();
1415 } catch (e) {
1416 if (context.mounted) {
1417 ScaffoldMessenger.of(context).showSnackBar(
1418 SnackBar(content: Text(errorText(e))));
1419 }
1420 }
1421 }),
1422 if (!adultShell) ...[
1423 const Divider(),
1424 ListTile(
1425 leading: const Icon(Icons.family_restroom),
1426 title: const Text('خانواده'),
1427 onTap: () => Navigator.of(context).push(
1428 MaterialPageRoute(
1429 builder: (_) =>
1430 ProfileFamilyPage(api: widget.api),
1431 ),
1432 ),
1433 ),
1434 ],
1435 ],
1436 ),
1437 ),
1438 ),
1439 )),
1440 );
1441 }
1442
1443 class ProfileFamilyPage extends StatefulWidget {
1444 const ProfileFamilyPage(
1445 {super.key, required this.api, this.embedded = false});
1446 final IdentityApi api;
1447 final bool embedded;
1448 @override
1449 State<ProfileFamilyPage> createState() => _ProfileFamilyPageState();
1450 }
1451
1452 class _ProfileFamilyPageState extends State<ProfileFamilyPage> {
1453 late Future<List<dynamic>> data;
1454 @override
1455 void initState() {
1456 super.initState();
1457 data = load();
1458 }
1459
1460 Future<List<dynamic>> load() async =>
1461 [await widget.api.getProfile(), await widget.api.listFamilies()];
1462
1463 Future<void> editProfile(Map<String, dynamic> profile) async {
1464 final saved = await showDialog<bool>(
1465 context: context,
1466 builder: (_) =>
1467 _AccountDialog(api: widget.api, mode: 'profile', profile: profile));
1468 if (saved == true && mounted) {
1469 setState(() {
1470 data = load();
1471 });
1472 }
1473 }
1474
1475 Future<void> createFamily() async {
1476 final saved = await showDialog<bool>(
1477 context: context,
1478 builder: (_) => _AccountDialog(api: widget.api, mode: 'family'));
1479 if (saved == true && mounted) {
1480 setState(() {
1481 data = load();
1482 });
1483 }
1484 }
1485
1486 Future<void> invite(String familyId) async {
1487 final saved = await showDialog<bool>(
1488 context: context,
1489 builder: (_) => _AccountDialog(
1490 api: widget.api, mode: 'invite', familyId: familyId));
1491 if (saved == true && mounted) {
1492 ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
1493 content:
1494 Text('درخواست دعوت پذیرفته شد؛ تحویل پیام تأیید نشده است.')));
1495 }
1496 }
1497
1498 @override
1499 Widget build(BuildContext context) => Scaffold(
1500 appBar: widget.embedded
1501 ? null
1502 : AppBar(title: const Text('پروفایل و خانواده')),
1503 body: FutureBuilder<List<dynamic>>(
1504 future: data,
1505 builder: (context, snapshot) {
1506 if (snapshot.hasError) {
1507 return LoadError(
1508 error: snapshot.error!,
1509 retry: () {
1510 setState(() {
1511 data = load();
1512 });
1513 });
1514 }
1515 if (!snapshot.hasData) {
1516 return const Center(child: CircularProgressIndicator());
1517 }
1518 final profile = snapshot.data![0] as Map<String, dynamic>;
1519 final families = snapshot.data![1] as List<Map<String, dynamic>>;
1520 return ListView(
1521 padding: const EdgeInsets.all(20),
1522 children: [
1523 Card(
1524 child: ListTile(
1525 leading: const CircleAvatar(child: Icon(Icons.person)),
1526 title: Text(
1527 profile['display_name']?.toString() ?? 'پروفایل من'),
1528 subtitle:
1529 Text(profile['email_normalized']?.toString() ?? ''),
1530 trailing: IconButton(
1531 onPressed: () => editProfile(profile),
1532 icon: const Icon(Icons.edit_outlined)),
1533 ),
1534 ),
1535 const SizedBox(height: 12),
1536 if (families.isEmpty)
1537 Card(
1538 child: ListTile(
1539 leading: const Icon(Icons.family_restroom),
1540 title: const Text('هنوز فضای خانواده ساخته نشده'),
1541 trailing: IconButton(
1542 onPressed: createFamily, icon: const Icon(Icons.add)),
1543 ),
1544 )
1545 else
1546 ...families.map((family) => Card(
1547 child: ListTile(
1548 leading: const Icon(Icons.family_restroom),
1549 title: Text(family['name']?.toString() ?? 'خانواده'),
1550 subtitle: Text(
1551 '${family['is_admin'] == true ? 'مدیر خانواده · ' : ''}${family['role'] ?? ''}'),
1552 onTap: () async {
1553 final api = widget.api;
1554 await Navigator.of(context).push(MaterialPageRoute(
1555 builder: (_) => api is HttpIdentityApi
1556 ? FamilyManagementPage(
1557 api: api,
1558 familyId: family['id'].toString())
1559 : FamilyMembersPage(
1560 api: api,
1561 familyId: family['id'].toString(),
1562 familyName:
1563 family['name']?.toString() ??
1564 'خانواده',
1565 isAdmin: family['is_admin'] == true)));
1566 if (mounted) setState(() => data = load());
1567 },
1568 trailing: IconButton(
1569 onPressed: family['is_admin'] == true
1570 ? () => invite(family['id'].toString())
1571 : null,
1572 icon: const Icon(Icons.person_add_alt)),
1573 ),
1574 )),
1575 ListTile(
1576 leading: const Icon(Icons.public),
1577 title: const Text('خانواده و یادگیری ایران'),
1578 subtitle: const Text(
1579 'نقش‌ها، پایه تحصیلی، کتاب‌ها، تقویم و یادآوری'),
1580 onTap: () => Navigator.of(context).push(MaterialPageRoute(
1581 builder: (_) =>
1582 IranianFamilyLearningHub(identity: widget.api),
1583 )),
1584 ),
1585 ListTile(
1586 leading: const Icon(Icons.password),
1587 title: const Text('تغییر رمز عبور'),
1588 onTap: () => Navigator.of(context).push(MaterialPageRoute(
1589 builder: (_) => ChangePasswordPage(api: widget.api))),
1590 ),
1591 const ListTile(
1592 leading: Icon(Icons.privacy_tip_outlined),
1593 title: Text('حریم خصوصی و دسترسی‌ها'),
1594 subtitle:
1595 Text('خصوصی، اعضای منتخب، والد/سرپرست، خانواده، ایمنی'),
1596 ),
1597 ],
1598 );
1599 },
1600 ),
1601 floatingActionButton: FloatingActionButton.extended(
1602 onPressed: createFamily,
1603 icon: const Icon(Icons.add),
1604 label: const Text('خانواده')),
1605 );
1606 }
1607
1608 class FamilyMembersPage extends StatefulWidget {
1609 const FamilyMembersPage({
1610 super.key,
1611 required this.api,
1612 required this.familyId,
1613 required this.familyName,
1614 required this.isAdmin,
1615 });
1616 final IdentityApi api;
1617 final String familyId;
1618 final String familyName;
1619 final bool isAdmin;
1620 @override
1621 State<FamilyMembersPage> createState() => _FamilyMembersPageState();
1622 }
1623
1624 class _FamilyMembersPageState extends State<FamilyMembersPage> {
1625 late Future<List<Map<String, dynamic>>> members;
1626 @override
1627 void initState() {
1628 super.initState();
1629 members = widget.api.listFamilyMembers(widget.familyId);
1630 }
1631
1632 String roleLabel(String role) => switch (role) {
1633 'parent_guardian' => 'والد / سرپرست',
1634 'teen_minor' => 'فرزند / نوجوان',
1635 'adult_member' => 'عضو بزرگسال',
1636 _ => role,
1637 };
1638
1639 Future<void> configureGuardian(List<Map<String, dynamic>> items) async {
1640 if (!items.any((m) => m['role'] == 'parent_guardian') ||
1641 !items.any((m) => m['role'] == 'teen_minor')) {
1642 ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
1643 content:
1644 Text('برای ثبت سرپرستی، حداقل یک والد و یک فرزند لازم است.')));
1645 return;
1646 }
1647 await showDialog<bool>(
1648 context: context,
1649 builder: (_) => _AccountDialog(
1650 api: widget.api,
1651 mode: 'guardian',
1652 familyId: widget.familyId,
1653 members: items));
1654 }
1655
1656 @override
1657 Widget build(BuildContext context) => Scaffold(
1658 appBar: AppBar(title: Text(widget.familyName)),
1659 body: FutureBuilder<List<Map<String, dynamic>>>(
1660 future: members,
1661 builder: (context, snapshot) {
1662 if (snapshot.hasError) {
1663 return LoadError(
1664 error: snapshot.error!,
1665 retry: () {
1666 setState(() {
1667 members = widget.api.listFamilyMembers(widget.familyId);
1668 });
1669 });
1670 }
1671 if (!snapshot.hasData) {
1672 return const Center(child: CircularProgressIndicator());
1673 }
1674 final items = snapshot.data!;
1675 return ListView(
1676 padding: const EdgeInsets.all(20),
1677 children: [
1678 for (final member in items)
1679 Card(
1680 child: ListTile(
1681 leading: const CircleAvatar(child: Icon(Icons.person)),
1682 title: Text(member['display_name']?.toString() ?? 'عضو'),
1683 subtitle:
1684 Text(roleLabel(member['role']?.toString() ?? '')),
1685 trailing: member['is_admin'] == true
1686 ? const Chip(label: Text('مدیر'))
1687 : null,
1688 ),
1689 ),
1690 if (widget.isAdmin) ...[
1691 const SizedBox(height: 12),
1692 FilledButton.icon(
1693 onPressed: () => configureGuardian(items),
1694 icon: const Icon(Icons.supervisor_account_outlined),
1695 label: const Text('تنظیم رابطه والد و فرزند'),
1696 ),
1697 ],
1698 ],
1699 );
1700 },
1701 ),
1702 );
1703 }
1704
1705 class _AccountDialog extends StatefulWidget {
1706 const _AccountDialog(
1707 {required this.api,
1708 required this.mode,
1709 this.profile,
1710 this.familyId,
1711 this.members = const []});
1712 final IdentityApi api;
1713 final String mode;
1714 final Map<String, dynamic>? profile;
1715 final String? familyId;
1716 final List<Map<String, dynamic>> members;
1717 @override
1718 State<_AccountDialog> createState() => _AccountDialogState();
1719 }
1720
1721 class _AccountDialogState extends State<_AccountDialog> {
1722 late final TextEditingController name;
1723 String theme = 'adult_blue', choice = 'daughter', category = 'adult';
1724 bool phoneInvitation = false;
1725 String? invitationLink;
1726 String? guardian, minor, error;
1727 bool busy = false;
1728 @override
1729 void initState() {
1730 super.initState();
1731 name = TextEditingController(
1732 text: widget.profile?['display_name']?.toString() ?? '');
1733 theme = widget.profile?['theme_preference']?.toString() ?? theme;
1734 category = widget.profile?['profile_category']?.toString() ??
1735 (theme == 'girl_pink'
1736 ? 'girl_minor'
1737 : theme == 'boy_blue'
1738 ? 'boy_minor'
1739 : 'adult');
1740 final gs = widget.members.where((m) => m['role'] == 'parent_guardian');
1741 final ms = widget.members.where((m) => m['role'] == 'teen_minor');
1742 guardian = gs.isEmpty ? null : gs.first['user_id'].toString();
1743 minor = ms.isEmpty ? null : ms.first['user_id'].toString();
1744 }
1745
1746 @override
1747 void dispose() {
1748 name.dispose();
1749 super.dispose();
1750 }
1751
1752 Future<void> save() async {
1753 if (busy) return;
1754 if (widget.mode != 'guardian' && name.text.trim().isEmpty) {
1755 setState(() => error = 'این فیلد را وارد کن.');
1756 return;
1757 }
1758 setState(() {
1759 busy = true;
1760 error = null;
1761 });
1762 try {
1763 switch (widget.mode) {
1764 case 'profile':
1765 await widget.api.updateProfile(
1766 displayName: name.text.trim(),
1767 themePreference: theme,
1768 profileCategory: category);
1769 case 'family':
1770 await widget.api
1771 .createFamily(name.text.trim(), role: 'parent_guardian');
1772 case 'invite':
1773 final role = choice == 'parent'
1774 ? 'parent_guardian'
1775 : choice == 'adult'
1776 ? 'adult_member'
1777 : 'teen_minor';
1778 final memberTheme = choice == 'daughter'
1779 ? 'girl_pink'
1780 : choice == 'son'
1781 ? 'boy_blue'
1782 : 'adult_blue';
1783 if (widget.api is HttpIdentityApi) {
1784 final result = await (widget.api as HttpIdentityApi)
1785 .createFamilyInvitation(
1786 familyId: widget.familyId!,
1787 email: phoneInvitation ? null : name.text.trim(),
1788 phone: phoneInvitation ? name.text.trim() : null,
1789 role: role,
1790 themePreference: memberTheme);
1791 final link = result['invitationLink'];
1792 if (link is! String || link.isEmpty) {
1793 throw const ApiException(502, 'invalid_invitation_response');
1794 }
1795 if (mounted) setState(() => invitationLink = link);
1796 } else {
1797 await widget.api.inviteMember(
1798 familyId: widget.familyId!,
1799 email: name.text.trim(),
1800 role: role,
1801 themePreference: memberTheme);
1802 }
1803 case 'guardian':
1804 await widget.api.setGuardian(
1805 familyId: widget.familyId!,
1806 guardianUserId: guardian!,
1807 minorUserId: minor!);
1808 }
1809 if (mounted && invitationLink == null) Navigator.pop(context, true);
1810 } catch (e) {
1811 if (mounted) setState(() => error = errorText(e));
1812 } finally {
1813 if (mounted) setState(() => busy = false);
1814 }
1815 }
1816
1817 @override
1818 Widget build(BuildContext context) => PopScope(
1819 canPop: !busy,
1820 child: AlertDialog(
1821 title: Text(switch (widget.mode) {
1822 'profile' => 'ویرایش پروفایل',
1823 'family' => 'ساخت فضای خانواده',
1824 'invite' => 'دعوت فرزند / عضو',
1825 _ => 'رابطه والد و فرزند'
1826 }),
1827 content: SizedBox(
1828 width: 440,
1829 child: SingleChildScrollView(
1830 child: Column(mainAxisSize: MainAxisSize.min, children: [
1831 if (invitationLink != null) ...[
1832 const Text(
1833 'پیوند دعوت آماده شد. تحویل ایمیل یا پیامک تأیید نشده است؛ پیوند را خودت به عضو موردنظر برسان.'),
1834 SelectableText(invitationLink!),
1835 TextButton.icon(
1836 onPressed: () async {
1837 await Clipboard.setData(
1838 ClipboardData(text: invitationLink!));
1839 },
1840 icon: const Icon(Icons.copy),
1841 label: const Text('کپی پیوند دعوت'))
1842 ],
1843 if (invitationLink == null &&
1844 widget.mode == 'invite' &&
1845 widget.api is HttpIdentityApi)
1846 SegmentedButton<bool>(
1847 segments: const [
1848 ButtonSegment(value: false, label: Text('ایمیل')),
1849 ButtonSegment(value: true, label: Text('تلفن'))
1850 ],
1851 selected: {
1852 phoneInvitation
1853 },
1854 onSelectionChanged: busy
1855 ? null
1856 : (v) => setState(() => phoneInvitation = v.first)),
1857 if (invitationLink == null && widget.mode != 'guardian')
1858 TextField(
1859 controller: name,
1860 enabled: !busy,
1861 decoration: InputDecoration(
1862 labelText: widget.mode == 'invite'
1863 ? (phoneInvitation ? 'شماره تلفن' : 'ایمیل')
1864 : widget.mode == 'family'
1865 ? 'نام خانواده'
1866 : 'نام')),
1867 if (widget.mode == 'profile') ...[
1868 DropdownButtonFormField<String>(
1869 initialValue: category,
1870 decoration:
1871 const InputDecoration(labelText: 'نوع پروفایل'),
1872 items: const [
1873 DropdownMenuItem(
1874 value: 'girl_minor', child: Text('دختر / نوجوان')),
1875 DropdownMenuItem(
1876 value: 'boy_minor', child: Text('پسر / نوجوان')),
1877 DropdownMenuItem(value: 'adult', child: Text('بزرگسال'))
1878 ],
1879 onChanged: busy
1880 ? null
1881 : (v) => setState(() => category = v ?? category)),
1882 const Text(
1883 'نوع پروفایل، نقش یا اجازه سرپرستی خانواده ایجاد نمی‌کند.')
1884 ],
1885 if (widget.mode == 'profile')
1886 DropdownButtonFormField<String>(
1887 initialValue: theme,
1888 decoration: const InputDecoration(labelText: 'تم'),
1889 items: const [
1890 DropdownMenuItem(
1891 value: 'girl_pink', child: Text('سفید / صورتی')),
1892 DropdownMenuItem(
1893 value: 'boy_blue',
1894 child: Text('سفید / آبی نوجوان')),
1895 DropdownMenuItem(
1896 value: 'adult_blue',
1897 child: Text('سفید / آبی بزرگسال'))
1898 ],
1899 onChanged: busy
1900 ? null
1901 : (v) => setState(() => theme = v ?? theme)),
1902 if (invitationLink == null && widget.mode == 'invite')
1903 DropdownButtonFormField<String>(
1904 initialValue: choice,
1905 decoration: const InputDecoration(labelText: 'نوع عضو'),
1906 items: const [
1907 DropdownMenuItem(
1908 value: 'daughter',
1909 child: Text('فرزند دختر — سفید / صورتی')),
1910 DropdownMenuItem(
1911 value: 'son',
1912 child: Text('فرزند پسر — سفید / آبی')),
1913 DropdownMenuItem(
1914 value: 'parent',
1915 child: Text('والد / سرپرست — سفید / آبی')),
1916 DropdownMenuItem(
1917 value: 'adult',
1918 child: Text('عضو بزرگسال — سفید / آبی'))
1919 ],
1920 onChanged: busy
1921 ? null
1922 : (v) => setState(() => choice = v ?? choice)),
1923 if (widget.mode == 'guardian') ...[
1924 DropdownButtonFormField<String>(
1925 initialValue: guardian,
1926 decoration:
1927 const InputDecoration(labelText: 'والد / سرپرست'),
1928 items: widget.members
1929 .where((m) => m['role'] == 'parent_guardian')
1930 .map((m) => DropdownMenuItem(
1931 value: m['user_id'].toString(),
1932 child: Text(
1933 m['display_name']?.toString() ?? 'والد')))
1934 .toList(),
1935 onChanged:
1936 busy ? null : (v) => setState(() => guardian = v)),
1937 DropdownButtonFormField<String>(
1938 initialValue: minor,
1939 decoration: const InputDecoration(labelText: 'فرزند'),
1940 items: widget.members
1941 .where((m) => m['role'] == 'teen_minor')
1942 .map((m) => DropdownMenuItem(
1943 value: m['user_id'].toString(),
1944 child: Text(
1945 m['display_name']?.toString() ?? 'فرزند')))
1946 .toList(),
1947 onChanged:
1948 busy ? null : (v) => setState(() => minor = v)),
1949 const Text(
1950 'ثبت رابطه فقط پس از بررسی مجوز سرور انجام می‌شود.'),
1951 ],
1952 if (error != null)
1953 Text(error!,
1954 style: TextStyle(
1955 color: Theme.of(context).colorScheme.error)),
1956 ]))),
1957 actions: [
1958 TextButton(
1959 onPressed: busy ? null : () => Navigator.pop(context, false),
1960 child: const Text('انصراف')),
1961 FilledButton(
1962 onPressed: busy
1963 ? null
1964 : invitationLink != null
1965 ? () => Navigator.pop(context, true)
1966 : save,
1967 child: Text(busy
1968 ? 'در حال ثبت...'
1969 : invitationLink != null
1970 ? 'بستن'
1971 : 'ذخیره'))
1972 ]));
1973 }