LifeMate — Personal, Family & Learning Companion

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