LifeMate — Personal, Family & Learning Companion

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