LifeMate — Personal, Family & Learning Companion

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