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