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