LifeMate — Personal, Family & Learning Companion

feat/flutter-mobile-navigation
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
dart 1,069 lines 41.7 KB
Raw
1 import 'dart:async';
2 import 'package:flutter/material.dart';
3 import 'api.dart';
4 import 'offline_store.dart';
5 import 'plan_sync.dart';
6 import 'plan_details_ui.dart';
7 import 'study_ui.dart';
8 import 'dashboard_ui.dart';
9 import 'school_management_ui.dart';
10
11 String faKind(String kind) => switch (kind) {
12 'assignment' => 'تکلیف',
13 'exam' => 'امتحان',
14 'study_session' => 'مطالعه',
15 'event' => 'رویداد',
16 'routine' => 'روتین',
17 'goal' => 'هدف',
18 _ => 'کار',
19 };
20 DateTime? parseDate(dynamic value) =>
21 value == null ? null : DateTime.tryParse(value.toString())?.toLocal();
22 String shortDate(dynamic value) {
23 final d = parseDate(value);
24 return d == null
25 ? ''
26 : '${d.month}/${d.day} · ${d.hour}:${d.minute.toString().padLeft(2, '0')}';
27 }
28
29 String uiErrorText(Object error) {
30 if (error is ApiException) {
31 if (error.code == 'local_storage_restart_required') {
32 return 'وضعیت ذخیره نامشخص است. برنامه را از تنظیمات دستگاه «توقف اجباری» کن و دوباره باز کن.';
33 }
34 if (error.code == 'local_storage_failed' ||
35 error.code == 'local_data_corrupt') {
36 return 'خواندن یا ذخیره داده دستگاه انجام نشد. تغییر تأیید نشده است.';
37 }
38 if (error.statusCode == 401) return 'نشست ورود معتبر نیست. دوباره وارد شو.';
39 if (error.statusCode == 403) {
40 return 'برای این اطلاعات یا عملیات دسترسی نداری.';
41 }
42 if (error.code == 'sync_conflict' || error.code == 'version_conflict') {
43 return 'نسخه داده تغییر کرده است. تغییر معلق نگه داشته شد؛ ابتدا اطلاعات سرور را بررسی کن.';
44 }
45 if (error.code == 'sync_pending') {
46 return 'تغییر قبلی هنوز تأیید نشده است. ابتدا همگام‌سازی را دوباره امتحان کن.';
47 }
48 if (error.code == 'sms_unavailable') {
49 return 'سرویس پیامک فعال نیست. ارسال کد تأیید نشده است.';
50 }
51 if (error.code == 'invalid_or_expired_otp') {
52 return 'کد معتبر نیست یا منقضی شده است.';
53 }
54 if (error.code == 'rate_limited') {
55 return 'درخواست‌ها زیاد است. کمی صبر کن و دوباره تلاش کن.';
56 }
57 if (error.statusCode >= 500) {
58 return 'سرور پاسخ معتبر نداد. اطلاعات تازه دریافت نشده است.';
59 }
60 }
61 if (isOfflineFailure(error)) {
62 return 'اتصال برقرار نیست. اطلاعات تازه دریافت نشده است.';
63 }
64 return 'عملیات انجام نشد. دوباره تلاش کن.';
65 }
66
67 Future<List<Map<String, dynamic>>> ownedPlanFallback(
68 IdentityApi api, OfflineStore store,
69 {required bool today}) async {
70 final rows = today ? await store.readToday() : await store.readPlanner();
71 if (api is! HttpIdentityApi) return rows;
72 final userId = api.currentUserId;
73 if (userId == null) {
74 throw const ApiException(401, 'authenticated_cache_required');
75 }
76 // Only locally generated creates can establish ownership before an ACK.
77 final ownPending = (await store.readQueue())
78 .where((m) =>
79 m['entityType'] == 'plan_item' &&
80 m['operation'] == 'create' &&
81 m['queueStatus'] != 'rejected')
82 .map((m) => m['entityId'])
83 .toSet();
84 return rows
85 .where((row) =>
86 row['owner_user_id'] == userId ||
87 row['ownerUserId'] == userId ||
88 ownPending.contains(row['id']))
89 .toList();
90 }
91
92 String numberInput(String value) {
93 const digits = '۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩';
94 return value
95 .trim()
96 .split('')
97 .map((c) {
98 final i = digits.indexOf(c);
99 return i < 0 ? c : (i % 10).toString();
100 })
101 .join()
102 .replaceAll('٫', '.')
103 .replaceAll('٬', '');
104 }
105
106 class Phase3HomeContent extends StatelessWidget {
107 const Phase3HomeContent(
108 {super.key,
109 required this.api,
110 required this.page,
111 required this.adultShell});
112 final IdentityApi api;
113 final String page;
114 final bool adultShell;
115 @override
116 Widget build(BuildContext context) {
117 if (page == 'امروز') return TodayPage(api: api);
118 if (['برنامه‌ریز', 'برنامه هفتگی', 'تقویم', 'تکالیف و کارها']
119 .contains(page)) {
120 return PlannerPage(api: api);
121 }
122 if (page == 'خانواده') return ParentFamilyDashboard(api: api);
123 if (page == 'تمرکز') return StudyHub(api: api);
124 if (page == 'امتحان‌ها و نمرات') return SchoolPage(api: api);
125 return const CoreNotice(
126 title: 'لایف‌گاید', subtitle: 'این بخش در این مرحله فعال نیست.');
127 }
128 }
129
130 class CoreNotice extends StatelessWidget {
131 const CoreNotice({super.key, required this.title, required this.subtitle});
132 final String title, subtitle;
133 @override
134 Widget build(BuildContext context) => Center(
135 child: Card(
136 margin: const EdgeInsets.all(20),
137 child: Padding(
138 padding: const EdgeInsets.all(24),
139 child: Column(mainAxisSize: MainAxisSize.min, children: [
140 Text(title, style: Theme.of(context).textTheme.headlineSmall),
141 const SizedBox(height: 8),
142 Text(subtitle, textAlign: TextAlign.center)
143 ]))));
144 }
145
146 class LoadError extends StatelessWidget {
147 const LoadError({super.key, required this.error, required this.retry});
148 final Object error;
149 final VoidCallback retry;
150 @override
151 Widget build(BuildContext context) => Center(
152 child: Padding(
153 padding: const EdgeInsets.all(20),
154 child: Column(mainAxisSize: MainAxisSize.min, children: [
155 Text(uiErrorText(error), textAlign: TextAlign.center),
156 TextButton(onPressed: retry, child: const Text('تلاش دوباره'))
157 ])));
158 }
159
160 class SyncNotice extends StatelessWidget {
161 const SyncNotice(
162 {super.key, required this.offline, required this.pending, this.syncedAt});
163 final bool offline;
164 final int pending;
165 final DateTime? syncedAt;
166 @override
167 Widget build(BuildContext context) => Card(
168 child: ListTile(
169 leading: Icon(
170 offline ? Icons.cloud_off_outlined : Icons.cloud_done_outlined),
171 title: Text(offline
172 ? 'نسخه ذخیره‌شده؛ داده زنده نیست'
173 : 'آخرین دریافت از سرور'),
174 subtitle: Text(
175 '${syncedAt == null ? 'زمان دریافت نامشخص' : shortDate(syncedAt!.toIso8601String())}${pending > 0 ? '\n$pending تغییر در انتظار تأیید سرور' : ''}')));
176 }
177
178 class TodayPage extends StatelessWidget {
179 const TodayPage({super.key, required this.api});
180 final IdentityApi api;
181 @override
182 Widget build(BuildContext context) => _PlanList(api: api, today: true);
183 }
184
185 class PlannerPage extends StatelessWidget {
186 const PlannerPage({super.key, required this.api});
187 final IdentityApi api;
188 @override
189 Widget build(BuildContext context) => _PlanList(api: api, today: false);
190 }
191
192 class _PlanList extends StatefulWidget {
193 const _PlanList({required this.api, required this.today});
194 final IdentityApi api;
195 final bool today;
196 @override
197 State<_PlanList> createState() => _PlanListState();
198 }
199
200 class _PlanListState extends State<_PlanList> with WidgetsBindingObserver {
201 late Future<LoadResult> future;
202 Timer? poll;
203 bool loading = false;
204 String? busyId;
205 String? operationError;
206 Set<String> ownedCreates = {};
207 ValueNotifier<Map<String, dynamic>?>? sharedDetail;
208 String? sharedDetailId;
209 @override
210 void initState() {
211 super.initState();
212 WidgetsBinding.instance.addObserver(this);
213 future = load();
214 startPoll();
215 }
216
217 void startPoll() {
218 poll?.cancel();
219 poll = Timer.periodic(const Duration(seconds: 15), (_) {
220 if (!loading && busyId == null) reload();
221 });
222 }
223
224 @override
225 void didChangeAppLifecycleState(AppLifecycleState state) {
226 if (state == AppLifecycleState.resumed) {
227 startPoll();
228 reload();
229 } else {
230 poll?.cancel();
231 }
232 }
233
234 @override
235 void dispose() {
236 poll?.cancel();
237 WidgetsBinding.instance.removeObserver(this);
238 super.dispose();
239 }
240
241 Future<LoadResult> load() async {
242 loading = true;
243 try {
244 final store = OfflineStore.forApi(widget.api);
245 await PlanSync(widget.api, store: store).flush();
246 final now = DateTime.now();
247 final from = DateTime(now.year, now.month, now.day);
248 final to = from.add(const Duration(days: 1));
249 List<Map<String, dynamic>> items;
250 var reminders = <Map<String, dynamic>>[];
251 bool offline = false;
252 try {
253 items = widget.today
254 ? await widget.api.getToday(from: from, to: to)
255 : await widget.api.listPlanItems();
256 if (widget.today) reminders = await widget.api.claimDueReminders();
257 // The store merges queued mutations atomically with each fresh cache.
258 if (widget.today) {
259 await store.cacheToday(items);
260 items = await store.readToday();
261 } else {
262 await store.cachePlanner(items);
263 items = await store.readPlanner();
264 }
265 } catch (error) {
266 if (!isOfflineFailure(error)) rethrow;
267 offline = true;
268 items = await ownedPlanFallback(widget.api, store, today: widget.today);
269 }
270 if (sharedDetailId != null) {
271 sharedDetail?.value = offline
272 ? null
273 : items.where((row) => row['id'] == sharedDetailId).firstOrNull;
274 }
275 ownedCreates = (await store.readQueue())
276 .where((m) =>
277 m['entityType'] == 'plan_item' &&
278 m['operation'] == 'create' &&
279 m['queueStatus'] != 'rejected')
280 .map((m) => m['entityId'].toString())
281 .toSet();
282 return LoadResult(
283 items.where((i) => i['status'] != 'cancelled').toList(), offline,
284 pending: await store.pendingCount(),
285 syncedAt: await store.readLastSync(),
286 reminders: reminders);
287 } catch (_) {
288 sharedDetail?.value = null;
289 rethrow;
290 } finally {
291 loading = false;
292 }
293 }
294
295 Future<void> reload() async {
296 if (!mounted) return;
297 setState(() {
298 future = load();
299 });
300 try {
301 await future;
302 } catch (_) {/* FutureBuilder renders the error. */}
303 }
304
305 Future<MutationOutcome?> edit(
306 [Map<String, dynamic>? item, bool notify = true]) async {
307 final outcome = await showDialog<MutationOutcome>(
308 context: context,
309 builder: (_) => PlanItemDialog(api: widget.api, item: item));
310 if (outcome != null && mounted) {
311 if (notify) {
312 ScaffoldMessenger.of(context).showSnackBar(SnackBar(
313 content: Text(outcome.queued
314 ? 'تغییر روی دستگاه ثبت شد؛ در انتظار تأیید سرور.'
315 : 'تغییر توسط سرور تأیید شد.')));
316 }
317 await reload();
318 }
319 return outcome;
320 }
321
322 bool owns(Map<String, dynamic> item) {
323 final api = widget.api;
324 if (api is! HttpIdentityApi) return true;
325 final owner = item['owner_user_id'] ?? item['ownerUserId'];
326 return api.currentUserId != null &&
327 (owner == api.currentUserId ||
328 (owner == null && ownedCreates.contains(item['id'])));
329 }
330
331 Future<void> openDetails(Map<String, dynamic> item, bool offline) async {
332 final canEdit = owns(item);
333 final updates = canEdit ? null : ValueNotifier<Map<String, dynamic>?>(item);
334 sharedDetail = updates;
335 sharedDetailId = canEdit ? null : item['id'].toString();
336 await Navigator.of(context).push(MaterialPageRoute(
337 builder: (_) => PlanDetailsPage(
338 item: item,
339 sharedUpdates: updates,
340 canEdit: canEdit,
341 offline: offline,
342 canStudy: canEdit &&
343 widget.api is HttpIdentityApi &&
344 ['assignment', 'task', 'study_session'].contains(item['kind']),
345 onAction: (current, action) =>
346 this.action(current, action, rethrowFailure: true),
347 kindLabel: faKind,
348 dateLabel: shortDate,
349 errorLabel: uiErrorText)));
350 if (identical(sharedDetail, updates)) {
351 sharedDetail = null;
352 sharedDetailId = null;
353 }
354 updates?.dispose();
355 if (mounted) await reload();
356 }
357
358 Future<MutationOutcome?> action(Map<String, dynamic> item, String action,
359 {bool rethrowFailure = false}) async {
360 if (busyId != null) return null;
361 if (!owns(item)) {
362 if (rethrowFailure) throw const ApiException(403, 'forbidden');
363 return null;
364 }
365 if (action == 'edit') {
366 return edit(item, !rethrowFailure);
367 }
368 if (action == 'study') {
369 if (item['pending_sync'] == true) {
370 setState(() => operationError =
371 'تکلیف هنوز در سرور تأیید نشده است؛ تایمر پس از همگام‌سازی فعال می‌شود.');
372 return null;
373 }
374 if (widget.api is! HttpIdentityApi) {
375 setState(() => operationError = 'اتصال مطالعه در دسترس نیست.');
376 return null;
377 }
378 await Navigator.of(context).push(MaterialPageRoute(
379 builder: (_) =>
380 StudyTimerPage(api: widget.api as HttpIdentityApi, item: item)));
381 if (!mounted) return null;
382 await reload();
383 final fresh = await future;
384 if (fresh.offline) throw const ApiException(0, 'network_unavailable');
385 final current =
386 fresh.items.where((row) => row['id'] == item['id']).firstOrNull;
387 if (current == null) throw const ApiException(404, 'not_found');
388 return MutationOutcome(
389 queued: current['pending_sync'] == true, item: current);
390 }
391 if (action == 'archive') {
392 final confirmed = await showDialog<bool>(
393 context: context,
394 builder: (c) => AlertDialog(
395 title: const Text('بایگانی مورد'),
396 content: Text('«${item['title']}» بایگانی شود؟'),
397 actions: [
398 TextButton(
399 onPressed: () => Navigator.pop(c, false),
400 child: const Text('انصراف')),
401 FilledButton(
402 onPressed: () => Navigator.pop(c, true),
403 child: const Text('بایگانی'))
404 ]));
405 if (confirmed != true || !mounted) return null;
406 }
407 setState(() {
408 busyId = item['id'].toString();
409 operationError = null;
410 });
411 try {
412 final sync = PlanSync(widget.api);
413 final outcome = action == 'archive'
414 ? await sync.archive(item)
415 : await sync.complete(item);
416 if (mounted) {
417 // Detail has an inline receipt; avoid covering its action controls.
418 if (!rethrowFailure || action == 'archive') {
419 ScaffoldMessenger.of(context).showSnackBar(SnackBar(
420 content: Text(outcome.queued
421 ? 'تغییر در انتظار تأیید سرور است.'
422 : 'سرور تغییر را تأیید کرد.')));
423 }
424 await reload();
425 }
426 return outcome;
427 } catch (error) {
428 if (mounted) setState(() => operationError = uiErrorText(error));
429 if (rethrowFailure) rethrow;
430 } finally {
431 if (mounted) setState(() => busyId = null);
432 }
433 return null;
434 }
435
436 @override
437 Widget build(BuildContext context) => FutureBuilder<LoadResult>(
438 future: future,
439 builder: (context, s) {
440 if (s.hasError) return LoadError(error: s.error!, retry: reload);
441 if (!s.hasData) return const Center(child: CircularProgressIndicator());
442 final data = s.data!;
443 return RefreshIndicator(
444 onRefresh: reload,
445 child: ListView(padding: const EdgeInsets.all(16), children: [
446 ...data.reminders.map((r) => Card(
447 child: ListTile(
448 leading: const Icon(Icons.notifications_active_outlined),
449 title: Text('یادآوری · ${r['title'] ?? 'برنامه'}'),
450 subtitle:
451 const Text('موعد این مورد رسیده یا نزدیک است.')))),
452 SyncNotice(
453 offline: data.offline,
454 pending: data.pending,
455 syncedAt: data.syncedAt),
456 if (operationError != null)
457 Card(
458 child: Padding(
459 padding: const EdgeInsets.all(12),
460 child: Text(operationError!,
461 style: TextStyle(
462 color: Theme.of(context).colorScheme.error)))),
463 Row(children: [
464 Expanded(
465 child: Text(widget.today ? 'امروز' : 'برنامه‌ریز',
466 style: Theme.of(context).textTheme.headlineSmall)),
467 if (!widget.today)
468 FilledButton.icon(
469 onPressed: busyId == null ? () => edit() : null,
470 icon: const Icon(Icons.add),
471 label: const Text('جدید'))
472 ]),
473 if (data.items.isEmpty)
474 const EmptyCard(
475 icon: Icons.task_alt,
476 title: 'موردی در این برنامه نیست',
477 subtitle: 'از برنامه‌ریز کار یا تکلیف جدید اضافه کن.'),
478 ...data.items.map((item) => Card(
479 child: ListTile(
480 leading: Icon(item['status'] == 'completed'
481 ? Icons.check_circle_outline
482 : Icons.radio_button_unchecked),
483 onTap: busyId == null
484 ? () => openDetails(item, data.offline)
485 : null,
486 title: Text(item['title']?.toString() ?? ''),
487 subtitle: Text(
488 '${faKind(item['kind']?.toString() ?? 'task')} · ${shortDate(item['startsAt'] ?? item['starts_at'] ?? item['dueAt'] ?? item['due_at'])}${item['pending_sync'] == true ? '\nدر انتظار تأیید سرور' : ''}'),
489 trailing: busyId == item['id']
490 ? const SizedBox(
491 width: 24,
492 height: 24,
493 child: CircularProgressIndicator())
494 : !owns(item)
495 ? const Icon(Icons.visibility_outlined)
496 : PopupMenuButton<String>(
497 onSelected: (v) => action(item, v),
498 itemBuilder: (_) => [
499 const PopupMenuItem(
500 value: 'edit', child: Text('ویرایش')),
501 const PopupMenuItem(
502 value: 'complete',
503 child: Text('انجام شد')),
504 if (item['pending_sync'] != true &&
505 widget.api is HttpIdentityApi &&
506 [
507 'assignment',
508 'task',
509 'study_session'
510 ].contains(item['kind']))
511 const PopupMenuItem(
512 value: 'study',
513 child: Text('تایمر مطالعه')),
514 const PopupMenuItem(
515 value: 'archive',
516 child: Text('بایگانی')),
517 ]),
518 ))),
519 ]));
520 });
521 }
522
523 class PlanItemDialog extends StatefulWidget {
524 const PlanItemDialog(
525 {super.key,
526 required this.api,
527 this.item,
528 this.initialKind = 'task',
529 this.subjects = const []});
530 final IdentityApi api;
531 final Map<String, dynamic>? item;
532 final String initialKind;
533 final List<Map<String, dynamic>> subjects;
534 @override
535 State<PlanItemDialog> createState() => _PlanItemDialogState();
536 }
537
538 class _PlanItemDialogState extends State<PlanItemDialog> {
539 late final TextEditingController title, notes, minutes, points, outOf;
540 late String kind;
541 String priority = 'normal', status = 'planned';
542 late DateTime when;
543 bool shared = false, busy = false, sharingChanged = false;
544 String originalVisibility = 'private';
545 String? subjectId;
546 String? familyId, error;
547 List<Map<String, dynamic>> families = [];
548 @override
549 void initState() {
550 super.initState();
551 final i = widget.item;
552 title = TextEditingController(text: i?['title']?.toString() ?? '');
553 notes = TextEditingController(text: i?['notes']?.toString() ?? '');
554 points = TextEditingController(
555 text: (i?['grade_points'] ?? i?['gradePoints'])?.toString() ?? '');
556 outOf = TextEditingController(
557 text: (i?['grade_out_of'] ?? i?['gradeOutOf'])?.toString() ?? '');
558 minutes = TextEditingController(
559 text: (((i?['planned_duration_seconds'] ??
560 i?['plannedDurationSeconds'] ??
561 1800) as num) ~/
562 60)
563 .toString());
564 kind = i?['kind']?.toString() ?? widget.initialKind;
565 priority = i?['priority']?.toString() ?? 'normal';
566 status = i?['status']?.toString() ?? 'planned';
567 when = parseDate(i?['due_at'] ?? i?['dueAt'] ?? i?['starts_at']) ??
568 DateTime.now().add(const Duration(hours: 1));
569 originalVisibility = i?['visibility']?.toString() ?? 'private';
570 shared = originalVisibility != 'private';
571 subjectId = i?['subject_id']?.toString() ?? i?['subjectId']?.toString();
572 if (subjectId == null && widget.subjects.isNotEmpty) {
573 subjectId = widget.subjects.first['id'].toString();
574 }
575 familyId = i?['family_id']?.toString() ?? i?['familyId']?.toString();
576 loadFamilies();
577 }
578
579 Future<void> loadFamilies() async {
580 try {
581 final rows = await widget.api.listFamilies();
582 if (mounted) setState(() => families = rows);
583 } catch (e) {
584 if (mounted) setState(() => error = uiErrorText(e));
585 }
586 }
587
588 @override
589 void dispose() {
590 title.dispose();
591 notes.dispose();
592 minutes.dispose();
593 points.dispose();
594 outOf.dispose();
595 super.dispose();
596 }
597
598 Future<void> pickDate() async {
599 final date = await showDatePicker(
600 context: context,
601 initialDate: when,
602 firstDate: DateTime(2020),
603 lastDate: DateTime(2100));
604 if (date == null || !mounted) return;
605 final time = await showTimePicker(
606 context: context, initialTime: TimeOfDay.fromDateTime(when));
607 if (time != null && mounted) {
608 setState(() => when =
609 DateTime(date.year, date.month, date.day, time.hour, time.minute));
610 }
611 }
612
613 Future<void> save() async {
614 if (busy) return;
615 if (title.text.trim().isEmpty) {
616 setState(() => error = 'عنوان را وارد کن.');
617 return;
618 }
619 final duration = int.tryParse(numberInput(minutes.text));
620 if (duration == null || duration < 0 || duration > 1440) {
621 setState(
622 () => error = 'زمان برنامه‌ریزی‌شده باید بین صفر و ۱۴۴۰ دقیقه باشد.');
623 return;
624 }
625 final graded = ['assignment', 'exam'].contains(kind);
626 final hasGrade =
627 points.text.trim().isNotEmpty || outOf.text.trim().isNotEmpty;
628 final gradePoints = num.tryParse(numberInput(points.text)),
629 gradeOutOf = num.tryParse(numberInput(outOf.text));
630 if (graded &&
631 hasGrade &&
632 (gradePoints == null ||
633 gradeOutOf == null ||
634 !gradePoints.isFinite ||
635 !gradeOutOf.isFinite ||
636 gradePoints < 0 ||
637 gradeOutOf <= 0 ||
638 gradePoints > gradeOutOf ||
639 gradeOutOf > 999999.99)) {
640 setState(() => error =
641 'نمره و سقف نمره را با هم وارد کن؛ نمره باید بین صفر و سقف باشد.');
642 return;
643 }
644 if (shared && familyId == null) {
645 setState(() => error = 'خانواده‌ای را برای اشتراک با والد انتخاب کن.');
646 return;
647 }
648 setState(() {
649 busy = true;
650 error = null;
651 });
652 try {
653 final item = widget.item;
654 final visibility = widget.item != null && !sharingChanged
655 ? originalVisibility
656 : shared
657 ? 'parent_guardian'
658 : 'private';
659 final payload = <String, dynamic>{
660 'kind': kind,
661 'title': title.text.trim(),
662 'priority': priority,
663 'status': status,
664 'notes': notes.text.trim(),
665 'dueAt': when.toUtc().toIso8601String(),
666 'plannedDurationSeconds': duration * 60,
667 'visibility': visibility,
668 'familyId': visibility != 'private' ? familyId : null,
669 if (subjectId != null) 'subjectId': subjectId,
670 if (graded &&
671 (hasGrade ||
672 widget.item?['grade_points'] != null ||
673 widget.item?['gradePoints'] != null)) ...{
674 'gradePoints': hasGrade ? gradePoints : null,
675 'gradeOutOf': hasGrade ? gradeOutOf : null
676 }
677 };
678 final sync = PlanSync(widget.api);
679 final result = item == null
680 ? await sync.create(payload)
681 : await sync.update(item, payload);
682 if (mounted) Navigator.pop(context, result);
683 } catch (e) {
684 if (mounted) setState(() => error = uiErrorText(e));
685 } finally {
686 if (mounted) setState(() => busy = false);
687 }
688 }
689
690 @override
691 Widget build(BuildContext context) => PopScope(
692 canPop: !busy,
693 child: AlertDialog(
694 title: Text(widget.item == null ? 'مورد جدید' : 'ویرایش مورد'),
695 content: SizedBox(
696 width: 440,
697 child: SingleChildScrollView(
698 child: Column(mainAxisSize: MainAxisSize.min, children: [
699 TextField(
700 controller: title,
701 enabled: !busy,
702 decoration: const InputDecoration(labelText: 'عنوان')),
703 const SizedBox(height: 12),
704 DropdownButtonFormField<String>(
705 initialValue: kind,
706 decoration: const InputDecoration(labelText: 'نوع'),
707 items: [
708 for (final k in [
709 'task',
710 'assignment',
711 'exam',
712 'event',
713 'routine',
714 'goal',
715 'study_session'
716 ])
717 DropdownMenuItem(value: k, child: Text(faKind(k)))
718 ],
719 onChanged:
720 busy ? null : (v) => setState(() => kind = v ?? kind)),
721 if (widget.subjects.isNotEmpty)
722 DropdownButtonFormField<String>(
723 initialValue: subjectId,
724 decoration: const InputDecoration(labelText: 'درس'),
725 items: widget.subjects
726 .map((row) => DropdownMenuItem(
727 value: row['id'].toString(),
728 child: Text(row['name']?.toString() ?? 'درس')))
729 .toList(),
730 onChanged:
731 busy ? null : (v) => setState(() => subjectId = v)),
732 const SizedBox(height: 12),
733 DropdownButtonFormField<String>(
734 initialValue: priority,
735 decoration: const InputDecoration(labelText: 'اولویت'),
736 items: const [
737 DropdownMenuItem(value: 'low', child: Text('کم')),
738 DropdownMenuItem(value: 'normal', child: Text('معمولی')),
739 DropdownMenuItem(value: 'high', child: Text('زیاد')),
740 DropdownMenuItem(value: 'urgent', child: Text('فوری'))
741 ],
742 onChanged: busy
743 ? null
744 : (v) => setState(() => priority = v ?? priority)),
745 if (widget.item != null)
746 DropdownButtonFormField<String>(
747 initialValue: status,
748 decoration: const InputDecoration(labelText: 'وضعیت'),
749 items: const [
750 DropdownMenuItem(
751 value: 'planned', child: Text('برنامه‌ریزی‌شده')),
752 DropdownMenuItem(
753 value: 'in_progress', child: Text('در حال انجام')),
754 DropdownMenuItem(
755 value: 'completed', child: Text('انجام‌شده'))
756 ],
757 onChanged: busy
758 ? null
759 : (v) => setState(() => status = v ?? status)),
760 const SizedBox(height: 12),
761 TextField(
762 controller: minutes,
763 enabled: !busy,
764 keyboardType: TextInputType.number,
765 decoration: const InputDecoration(
766 labelText: 'زمان برنامه‌ریزی‌شده (دقیقه)')),
767 if (['assignment', 'exam'].contains(kind)) ...[
768 TextField(
769 controller: points,
770 enabled: !busy,
771 keyboardType:
772 const TextInputType.numberWithOptions(decimal: true),
773 decoration:
774 const InputDecoration(labelText: 'نمره (اختیاری)')),
775 TextField(
776 controller: outOf,
777 enabled: !busy,
778 keyboardType:
779 const TextInputType.numberWithOptions(decimal: true),
780 decoration: const InputDecoration(
781 labelText: 'سقف نمره (اختیاری)')),
782 ],
783 TextButton.icon(
784 onPressed: busy ? null : pickDate,
785 icon: const Icon(Icons.calendar_month),
786 label: Text('موعد · ${shortDate(when.toIso8601String())}')),
787 TextField(
788 controller: notes,
789 enabled: !busy,
790 maxLines: 2,
791 decoration: const InputDecoration(
792 labelText: 'یادداشت خصوصی',
793 helperText:
794 'یادداشت در گزارش والد نمایش داده نمی‌شود.')),
795 SwitchListTile(
796 title: const Text('اشتراک تکلیف با والد / سرپرست'),
797 subtitle: const Text(
798 'عنوان، وضعیت و زمان ثبت‌شده برای سرپرست مجاز دیده می‌شود.'),
799 value: shared,
800 onChanged: busy
801 ? null
802 : (v) => setState(() {
803 shared = v;
804 sharingChanged = true;
805 })),
806 if (widget.item != null &&
807 !['private', 'parent_guardian']
808 .contains(originalVisibility) &&
809 !sharingChanged)
810 const Text(
811 'دامنه اشتراک فعلی با ذخیره حفظ می‌شود؛ تغییر کلید، آن را به والد یا خصوصی تغییر می‌دهد.'),
812 if (shared)
813 DropdownButtonFormField<String>(
814 initialValue: familyId,
815 decoration: const InputDecoration(labelText: 'خانواده'),
816 items: families
817 .map((f) => DropdownMenuItem(
818 value: f['id'].toString(),
819 child: Text(f['name']?.toString() ?? 'خانواده')))
820 .toList(),
821 onChanged:
822 busy ? null : (v) => setState(() => familyId = v)),
823 if (error != null)
824 Padding(
825 padding: const EdgeInsets.only(top: 12),
826 child: Text(error!,
827 style: TextStyle(
828 color: Theme.of(context).colorScheme.error))),
829 ]))),
830 actions: [
831 TextButton(
832 onPressed: busy ? null : () => Navigator.pop(context),
833 child: const Text('انصراف')),
834 FilledButton(
835 onPressed: busy ? null : save,
836 child: Text(busy ? 'در حال ثبت...' : 'ذخیره'))
837 ]));
838 }
839
840 class SchoolPage extends StatefulWidget {
841 const SchoolPage({super.key, required this.api});
842 final IdentityApi api;
843 @override
844 State<SchoolPage> createState() => _SchoolPageState();
845 }
846
847 class _SchoolPageState extends State<SchoolPage> {
848 late Future<SchoolLoad> future;
849 bool writing = false;
850 String? writeError;
851 @override
852 void initState() {
853 super.initState();
854 future = load();
855 }
856
857 Future<SchoolLoad> load() async {
858 final profile = await widget.api.getProfile();
859 final userId = profile['user_id']?.toString() ?? '';
860 if (userId.isEmpty) return SchoolLoad(userId, const {}, false);
861 try {
862 final overview = await widget.api.getSchoolOverview(userId);
863 await OfflineStore.forApi(widget.api).cacheSchool([
864 {'userId': userId, 'overview': overview}
865 ]);
866 return SchoolLoad(userId, overview, false);
867 } catch (failure) {
868 if (!isOfflineFailure(failure)) rethrow;
869 final cached = await OfflineStore.forApi(widget.api).readSchool();
870 if (cached.isNotEmpty) {
871 return SchoolLoad(
872 cached.first['userId']?.toString() ?? userId,
873 Map<String, dynamic>.from(
874 cached.first['overview'] as Map? ?? const {}),
875 true,
876 );
877 }
878 return SchoolLoad(userId, const {}, true);
879 }
880 }
881
882 Future<void> reload() async {
883 setState(() {
884 future = load();
885 });
886 try {
887 await future;
888 } catch (_) {/* FutureBuilder renders retry failure. */}
889 }
890
891 Future<void> openManagement() async {
892 if (widget.api is! HttpIdentityApi || writing) return;
893 await Navigator.of(context).push(MaterialPageRoute<void>(
894 builder: (_) =>
895 SchoolManagementPage(api: widget.api as HttpIdentityApi)));
896 if (mounted) await reload();
897 }
898
899 Future<void> addSchoolItem(String kind) async {
900 try {
901 final overview = await future;
902 if (!mounted) return;
903 final subjects = (overview.overview['subjects'] as List? ?? [])
904 .map((raw) => Map<String, dynamic>.from(raw as Map))
905 .toList();
906 final saved = await showDialog<MutationOutcome>(
907 context: context,
908 builder: (_) => PlanItemDialog(
909 api: widget.api, initialKind: kind, subjects: subjects));
910 if (saved != null && mounted) await reload();
911 } catch (error) {
912 if (mounted) setState(() => writeError = uiErrorText(error));
913 }
914 }
915
916 @override
917 Widget build(BuildContext context) => FutureBuilder<SchoolLoad>(
918 future: future,
919 builder: (context, snapshot) {
920 if (snapshot.hasError) {
921 return LoadError(error: snapshot.error!, retry: reload);
922 }
923 if (!snapshot.hasData) {
924 return const Center(child: CircularProgressIndicator());
925 }
926 final data = snapshot.data!;
927 final years = data.overview['years'] as List<dynamic>? ?? const [];
928 final subjects =
929 data.overview['subjects'] as List<dynamic>? ?? const [];
930 final workload =
931 data.overview['workload'] as List<dynamic>? ?? const [];
932 final grades = data.overview['grades'] as List<dynamic>? ?? const [];
933 return ListView(
934 padding: const EdgeInsets.all(16),
935 children: [
936 if (writing) const LinearProgressIndicator(),
937 if (writeError != null) Text(writeError!),
938 if (data.offline)
939 const Card(
940 child: ListTile(
941 leading: Icon(Icons.cloud_off_outlined),
942 title: Text('اطلاعات مدرسه از کش نمایش داده می‌شود'))),
943 if (years.isEmpty)
944 EmptyCard(
945 icon: Icons.school_outlined,
946 title: 'مدرسه را آماده کن',
947 subtitle:
948 'عنوان‌ها، تاریخ سال و نیمسال و درس‌ها را خودت انتخاب کن.',
949 action: FilledButton.icon(
950 onPressed: writing || widget.api is! HttpIdentityApi
951 ? null
952 : openManagement,
953 icon: const Icon(Icons.school_outlined),
954 label: const Text('مدیریت مدرسه'),
955 ),
956 )
957 else ...[
958 Card(
959 child: Padding(
960 padding: const EdgeInsets.all(16),
961 child: Column(
962 crossAxisAlignment: CrossAxisAlignment.stretch,
963 children: [
964 Text('مدرسه',
965 style: Theme.of(context).textTheme.headlineSmall),
966 TextButton.icon(
967 onPressed:
968 writing || widget.api is! HttpIdentityApi
969 ? null
970 : openManagement,
971 icon: const Icon(Icons.manage_accounts_outlined),
972 label: const Text('مدیریت مدرسه')),
973 const SizedBox(height: 10),
974 Wrap(spacing: 8, runSpacing: 8, children: [
975 Chip(label: Text('${subjects.length} درس')),
976 Chip(
977 label:
978 Text('${workload.length} کار درسی پیش‌رو')),
979 Chip(label: Text('${grades.length} نمره')),
980 ]),
981 const SizedBox(height: 12),
982 Row(children: [
983 Expanded(
984 child: FilledButton.icon(
985 onPressed: () => addSchoolItem('assignment'),
986 icon: const Icon(Icons.assignment_add),
987 label: const Text('تکلیف'),
988 )),
989 const SizedBox(width: 8),
990 Expanded(
991 child: OutlinedButton.icon(
992 onPressed: () => addSchoolItem('exam'),
993 icon: const Icon(Icons.quiz_outlined),
994 label: const Text('امتحان'),
995 )),
996 ]),
997 ]),
998 ),
999 ),
1000 const SizedBox(height: 12),
1001 Text('درس‌ها', style: Theme.of(context).textTheme.titleMedium),
1002 ...subjects.map((raw) {
1003 final row = Map<String, dynamic>.from(raw as Map);
1004 return Card(
1005 child: ListTile(
1006 leading: const Icon(Icons.menu_book_outlined),
1007 title: Text(row['name']?.toString() ?? ''),
1008 subtitle: Text(row['teacher_name']?.toString() ??
1009 row['term_title']?.toString() ??
1010 ''),
1011 ));
1012 }),
1013 const SizedBox(height: 12),
1014 Text('کارهای درسی پیش‌رو',
1015 style: Theme.of(context).textTheme.titleMedium),
1016 ...workload.map((raw) {
1017 final row = Map<String, dynamic>.from(raw as Map);
1018 return Card(
1019 child: ListTile(
1020 title: Text(row['title']?.toString() ?? ''),
1021 subtitle: Text(
1022 '${faKind(row['kind']?.toString() ?? '')} · ${shortDate(row['due_at'] ?? row['starts_at'])}'),
1023 ));
1024 }),
1025 ],
1026 ],
1027 );
1028 },
1029 );
1030 }
1031
1032 class EmptyCard extends StatelessWidget {
1033 const EmptyCard(
1034 {super.key,
1035 required this.icon,
1036 required this.title,
1037 required this.subtitle,
1038 this.action});
1039 final IconData icon;
1040 final String title, subtitle;
1041 final Widget? action;
1042 @override
1043 Widget build(BuildContext context) => Card(
1044 child: Padding(
1045 padding: const EdgeInsets.all(22),
1046 child: Column(children: [
1047 Icon(icon, size: 42),
1048 Text(title, style: Theme.of(context).textTheme.titleMedium),
1049 const SizedBox(height: 6),
1050 Text(subtitle, textAlign: TextAlign.center),
1051 if (action != null) action!
1052 ])));
1053 }
1054
1055 class LoadResult {
1056 const LoadResult(this.items, this.offline,
1057 {this.pending = 0, this.syncedAt, this.reminders = const []});
1058 final List<Map<String, dynamic>> items, reminders;
1059 final bool offline;
1060 final int pending;
1061 final DateTime? syncedAt;
1062 }
1063
1064 class SchoolLoad {
1065 const SchoolLoad(this.userId, this.overview, this.offline);
1066 final String userId;
1067 final Map<String, dynamic> overview;
1068 final bool offline;
1069 }