LifeMate — Personal, Family & Learning Companion
docs/offline-data-rescue-options
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
| 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 | import 'planner_series.dart'; |
| 11 | import 'planner_series_ui.dart'; |
| 12 | import 'device_reminder_coordinator.dart'; |
| 13 | |
| 14 | String faKind(String kind) => switch (kind) { |
| 15 | 'assignment' => 'تکلیف', |
| 16 | 'exam' => 'امتحان', |
| 17 | 'study_session' => 'مطالعه', |
| 18 | 'event' => 'رویداد', |
| 19 | 'routine' => 'روتین', |
| 20 | 'goal' => 'هدف', |
| 21 | _ => 'کار', |
| 22 | }; |
| 23 | DateTime? parseDate(dynamic value) => |
| 24 | value == null ? null : DateTime.tryParse(value.toString())?.toLocal(); |
| 25 | String shortDate(dynamic value) { |
| 26 | final d = parseDate(value); |
| 27 | return d == null |
| 28 | ? '' |
| 29 | : '${d.month}/${d.day} · ${d.hour}:${d.minute.toString().padLeft(2, '0')}'; |
| 30 | } |
| 31 | |
| 32 | String planTimeLabel(Map<String, dynamic> item) { |
| 33 | final start = |
| 34 | item['starts_at'] ?? item['startsAt'] ?? item['due_at'] ?? item['dueAt']; |
| 35 | final end = parseDate(item['ends_at'] ?? item['endsAt']); |
| 36 | return '${shortDate(start)}${end == null ? '' : ' تا ${end.hour.toString().padLeft(2, '0')}:${end.minute.toString().padLeft(2, '0')}'}'; |
| 37 | } |
| 38 | |
| 39 | String uiErrorText(Object error) { |
| 40 | if (error is ApiException) { |
| 41 | if (error.code == 'local_storage_restart_required') { |
| 42 | return 'وضعیت ذخیره نامشخص است. برنامه را از تنظیمات دستگاه «توقف اجباری» کن و دوباره باز کن.'; |
| 43 | } |
| 44 | if (error.code == 'local_storage_failed' || |
| 45 | error.code == 'local_data_corrupt') { |
| 46 | return 'خواندن یا ذخیره داده دستگاه انجام نشد. تغییر تأیید نشده است.'; |
| 47 | } |
| 48 | if (error.statusCode == 401) return 'نشست ورود معتبر نیست. دوباره وارد شو.'; |
| 49 | if (error.statusCode == 403) { |
| 50 | return 'برای این اطلاعات یا عملیات دسترسی نداری.'; |
| 51 | } |
| 52 | if (error.code == 'sync_conflict' || error.code == 'version_conflict') { |
| 53 | return 'نسخه داده تغییر کرده است. تغییر معلق نگه داشته شد؛ ابتدا اطلاعات سرور را بررسی کن.'; |
| 54 | } |
| 55 | if (error.code == 'sync_pending') { |
| 56 | return 'تغییر قبلی هنوز تأیید نشده است. ابتدا همگامسازی را دوباره امتحان کن.'; |
| 57 | } |
| 58 | if (error.code == 'sms_unavailable') { |
| 59 | return 'سرویس پیامک فعال نیست. ارسال کد تأیید نشده است.'; |
| 60 | } |
| 61 | if (error.code == 'invalid_or_expired_otp') { |
| 62 | return 'کد معتبر نیست یا منقضی شده است.'; |
| 63 | } |
| 64 | if (error.code == 'rate_limited') { |
| 65 | return 'درخواستها زیاد است. کمی صبر کن و دوباره تلاش کن.'; |
| 66 | } |
| 67 | if (error.statusCode >= 500) { |
| 68 | return 'سرور پاسخ معتبر نداد. اطلاعات تازه دریافت نشده است.'; |
| 69 | } |
| 70 | } |
| 71 | if (isOfflineFailure(error)) { |
| 72 | return 'اتصال برقرار نیست. اطلاعات تازه دریافت نشده است.'; |
| 73 | } |
| 74 | return 'عملیات انجام نشد. دوباره تلاش کن.'; |
| 75 | } |
| 76 | |
| 77 | Future<List<Map<String, dynamic>>> ownedPlanFallback( |
| 78 | IdentityApi api, OfflineStore store, |
| 79 | {required bool today}) async { |
| 80 | final rows = today ? await store.readToday() : await store.readPlanner(); |
| 81 | if (api is! HttpIdentityApi) return rows; |
| 82 | final userId = api.currentUserId; |
| 83 | if (userId == null) { |
| 84 | throw const ApiException(401, 'authenticated_cache_required'); |
| 85 | } |
| 86 | // Only locally generated creates can establish ownership before an ACK. |
| 87 | final ownPending = (await store.readQueue()) |
| 88 | .where((m) => |
| 89 | m['entityType'] == 'plan_item' && |
| 90 | m['operation'] == 'create' && |
| 91 | m['queueStatus'] != 'rejected') |
| 92 | .map((m) => m['entityId']) |
| 93 | .toSet(); |
| 94 | return rows |
| 95 | .where((row) => |
| 96 | row['owner_user_id'] == userId || |
| 97 | row['ownerUserId'] == userId || |
| 98 | ownPending.contains(row['id'])) |
| 99 | .toList(); |
| 100 | } |
| 101 | |
| 102 | String numberInput(String value) { |
| 103 | const digits = '۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩'; |
| 104 | return value |
| 105 | .trim() |
| 106 | .split('') |
| 107 | .map((c) { |
| 108 | final i = digits.indexOf(c); |
| 109 | return i < 0 ? c : (i % 10).toString(); |
| 110 | }) |
| 111 | .join() |
| 112 | .replaceAll('٫', '.') |
| 113 | .replaceAll('٬', ''); |
| 114 | } |
| 115 | |
| 116 | class Phase3HomeContent extends StatelessWidget { |
| 117 | const Phase3HomeContent( |
| 118 | {super.key, |
| 119 | required this.api, |
| 120 | required this.page, |
| 121 | required this.adultShell}); |
| 122 | final IdentityApi api; |
| 123 | final String page; |
| 124 | final bool adultShell; |
| 125 | @override |
| 126 | Widget build(BuildContext context) { |
| 127 | if (page == 'امروز') return TodayPage(api: api); |
| 128 | if (['برنامهریز', 'برنامه هفتگی', 'تقویم', 'تکالیف و کارها'] |
| 129 | .contains(page)) { |
| 130 | return PlannerPage(api: api); |
| 131 | } |
| 132 | if (page == 'خانواده') return ParentFamilyDashboard(api: api); |
| 133 | if (page == 'تمرکز') return StudyHub(api: api); |
| 134 | if (page == 'امتحانها و نمرات') return SchoolPage(api: api); |
| 135 | return const CoreNotice( |
| 136 | title: 'لایفگاید', subtitle: 'این بخش در این مرحله فعال نیست.'); |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | class CoreNotice extends StatelessWidget { |
| 141 | const CoreNotice({super.key, required this.title, required this.subtitle}); |
| 142 | final String title, subtitle; |
| 143 | @override |
| 144 | Widget build(BuildContext context) => Center( |
| 145 | child: Card( |
| 146 | margin: const EdgeInsets.all(20), |
| 147 | child: Padding( |
| 148 | padding: const EdgeInsets.all(24), |
| 149 | child: Column(mainAxisSize: MainAxisSize.min, children: [ |
| 150 | Text(title, style: Theme.of(context).textTheme.headlineSmall), |
| 151 | const SizedBox(height: 8), |
| 152 | Text(subtitle, textAlign: TextAlign.center) |
| 153 | ])))); |
| 154 | } |
| 155 | |
| 156 | class LoadError extends StatelessWidget { |
| 157 | const LoadError({super.key, required this.error, required this.retry}); |
| 158 | final Object error; |
| 159 | final VoidCallback retry; |
| 160 | @override |
| 161 | Widget build(BuildContext context) => Center( |
| 162 | child: Padding( |
| 163 | padding: const EdgeInsets.all(20), |
| 164 | child: Column(mainAxisSize: MainAxisSize.min, children: [ |
| 165 | Text(uiErrorText(error), textAlign: TextAlign.center), |
| 166 | TextButton(onPressed: retry, child: const Text('تلاش دوباره')) |
| 167 | ]))); |
| 168 | } |
| 169 | |
| 170 | class SyncNotice extends StatelessWidget { |
| 171 | const SyncNotice( |
| 172 | {super.key, required this.offline, required this.pending, this.syncedAt}); |
| 173 | final bool offline; |
| 174 | final int pending; |
| 175 | final DateTime? syncedAt; |
| 176 | @override |
| 177 | Widget build(BuildContext context) => Card( |
| 178 | child: ListTile( |
| 179 | leading: Icon( |
| 180 | offline ? Icons.cloud_off_outlined : Icons.cloud_done_outlined), |
| 181 | title: Text(offline |
| 182 | ? 'نسخه ذخیرهشده؛ داده زنده نیست' |
| 183 | : 'آخرین دریافت از سرور'), |
| 184 | subtitle: Text( |
| 185 | '${syncedAt == null ? 'زمان دریافت نامشخص' : shortDate(syncedAt!.toIso8601String())}${pending > 0 ? '\n$pending تغییر در انتظار تأیید سرور' : ''}'))); |
| 186 | } |
| 187 | |
| 188 | class TodayPage extends StatelessWidget { |
| 189 | const TodayPage( |
| 190 | {super.key, |
| 191 | required this.api, |
| 192 | this.home = false, |
| 193 | this.displayName = '', |
| 194 | this.onOpenPlanner}); |
| 195 | final IdentityApi api; |
| 196 | final bool home; |
| 197 | final String displayName; |
| 198 | final VoidCallback? onOpenPlanner; |
| 199 | @override |
| 200 | Widget build(BuildContext context) => _PlanList( |
| 201 | api: api, |
| 202 | today: true, |
| 203 | home: home, |
| 204 | displayName: displayName, |
| 205 | onOpenPlanner: onOpenPlanner); |
| 206 | } |
| 207 | |
| 208 | class PlannerPage extends StatelessWidget { |
| 209 | const PlannerPage({super.key, required this.api}); |
| 210 | final IdentityApi api; |
| 211 | @override |
| 212 | Widget build(BuildContext context) => _PlanList(api: api, today: false); |
| 213 | } |
| 214 | |
| 215 | class _PlanList extends StatefulWidget { |
| 216 | const _PlanList( |
| 217 | {required this.api, |
| 218 | required this.today, |
| 219 | this.home = false, |
| 220 | this.displayName = '', |
| 221 | this.onOpenPlanner}); |
| 222 | final IdentityApi api; |
| 223 | final bool today; |
| 224 | final bool home; |
| 225 | final String displayName; |
| 226 | final VoidCallback? onOpenPlanner; |
| 227 | @override |
| 228 | State<_PlanList> createState() => _PlanListState(); |
| 229 | } |
| 230 | |
| 231 | class _PlanListState extends State<_PlanList> with WidgetsBindingObserver { |
| 232 | late Future<LoadResult> future; |
| 233 | Timer? poll; |
| 234 | bool loading = false; |
| 235 | String? busyId; |
| 236 | String? operationError; |
| 237 | String? reminderError; |
| 238 | String? materializedWeek; |
| 239 | DateTime selectedDay = DateTime.now(); |
| 240 | Set<String> ownedCreates = {}; |
| 241 | ValueNotifier<Map<String, dynamic>?>? sharedDetail; |
| 242 | String? sharedDetailId; |
| 243 | @override |
| 244 | void initState() { |
| 245 | super.initState(); |
| 246 | WidgetsBinding.instance.addObserver(this); |
| 247 | future = load(); |
| 248 | startPoll(); |
| 249 | } |
| 250 | |
| 251 | void startPoll() { |
| 252 | poll?.cancel(); |
| 253 | poll = Timer.periodic(const Duration(seconds: 15), (_) { |
| 254 | if (!loading && busyId == null) reload(); |
| 255 | }); |
| 256 | } |
| 257 | |
| 258 | @override |
| 259 | void didChangeAppLifecycleState(AppLifecycleState state) { |
| 260 | if (state == AppLifecycleState.resumed) { |
| 261 | startPoll(); |
| 262 | reload(); |
| 263 | } else { |
| 264 | poll?.cancel(); |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | @override |
| 269 | void dispose() { |
| 270 | poll?.cancel(); |
| 271 | WidgetsBinding.instance.removeObserver(this); |
| 272 | super.dispose(); |
| 273 | } |
| 274 | |
| 275 | Future<LoadResult> load() async { |
| 276 | loading = true; |
| 277 | try { |
| 278 | final store = OfflineStore.forApi(widget.api); |
| 279 | await PlanSync(widget.api, store: store).flush(); |
| 280 | final http = widget.api; |
| 281 | if (http is HttpIdentityApi) { |
| 282 | final series = PlannerSeriesSync(http, store: store); |
| 283 | await series.flush(); |
| 284 | try { |
| 285 | final days = |
| 286 | plannerWeekDays(widget.today ? DateTime.now() : selectedDay); |
| 287 | final key = plannerDate(days.first); |
| 288 | if (materializedWeek != key) { |
| 289 | await series.materialize(days.first, days.last); |
| 290 | materializedWeek = key; |
| 291 | } |
| 292 | } catch (error) { |
| 293 | // A missing/new API route is a real compatibility error. Only a |
| 294 | // transport failure may use this account's existing offline rows. |
| 295 | if (!isOfflineFailure(error)) rethrow; |
| 296 | } |
| 297 | } |
| 298 | final now = DateTime.now(); |
| 299 | final from = DateTime(now.year, now.month, now.day); |
| 300 | final to = from.add(const Duration(days: 1)); |
| 301 | List<Map<String, dynamic>> items; |
| 302 | var reminders = <Map<String, dynamic>>[]; |
| 303 | bool offline = false; |
| 304 | try { |
| 305 | items = widget.home |
| 306 | ? await widget.api.listPlanItems(from: from, to: to) |
| 307 | : widget.today |
| 308 | ? await widget.api.getToday(from: from, to: to) |
| 309 | : await widget.api.listPlanItems(); |
| 310 | if (widget.home && http is HttpIdentityApi) { |
| 311 | items = items |
| 312 | .where((row) => row['owner_user_id'] == http.currentUserId) |
| 313 | .toList(); |
| 314 | } |
| 315 | if (widget.today) reminders = await widget.api.claimDueReminders(); |
| 316 | if (http is HttpIdentityApi) { |
| 317 | try { |
| 318 | await DeviceReminderCoordinator(http).reconcile(); |
| 319 | reminderError = null; |
| 320 | } catch (_) { |
| 321 | reminderError = |
| 322 | 'برنامه دریافت شد؛ تازهسازی اعلان این گوشی موفق نشد. تنظیمات اعلان را بررسی کن.'; |
| 323 | } |
| 324 | } |
| 325 | // The store merges queued mutations atomically with each fresh cache. |
| 326 | if (widget.today) { |
| 327 | await store.cacheToday(items); |
| 328 | items = await store.readToday(); |
| 329 | } else { |
| 330 | await store.cachePlanner(items); |
| 331 | items = await store.readPlanner(); |
| 332 | } |
| 333 | } catch (error) { |
| 334 | if (!isOfflineFailure(error)) rethrow; |
| 335 | offline = true; |
| 336 | items = await ownedPlanFallback(widget.api, store, today: widget.today); |
| 337 | } |
| 338 | if (sharedDetailId != null) { |
| 339 | sharedDetail?.value = offline |
| 340 | ? null |
| 341 | : items.where((row) => row['id'] == sharedDetailId).firstOrNull; |
| 342 | } |
| 343 | ownedCreates = (await store.readQueue()) |
| 344 | .where((m) => |
| 345 | m['entityType'] == 'plan_item' && |
| 346 | m['operation'] == 'create' && |
| 347 | m['queueStatus'] != 'rejected') |
| 348 | .map((m) => m['entityId'].toString()) |
| 349 | .toSet(); |
| 350 | return LoadResult( |
| 351 | items.where((i) => i['status'] != 'cancelled').toList(), offline, |
| 352 | pending: await store.pendingCount(), |
| 353 | syncedAt: await store.readLastSync(), |
| 354 | reminders: reminders); |
| 355 | } catch (_) { |
| 356 | sharedDetail?.value = null; |
| 357 | rethrow; |
| 358 | } finally { |
| 359 | loading = false; |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | Future<void> reload() async { |
| 364 | if (!mounted) return; |
| 365 | setState(() { |
| 366 | future = load(); |
| 367 | }); |
| 368 | try { |
| 369 | await future; |
| 370 | } catch (_) {/* FutureBuilder renders the error. */} |
| 371 | } |
| 372 | |
| 373 | Future<MutationOutcome?> edit( |
| 374 | [Map<String, dynamic>? item, bool notify = true]) async { |
| 375 | final outcome = await showDialog<MutationOutcome>( |
| 376 | context: context, |
| 377 | builder: (_) => PlanItemDialog( |
| 378 | api: widget.api, |
| 379 | item: item, |
| 380 | initialDate: widget.today ? null : selectedDay)); |
| 381 | if (outcome != null && mounted) { |
| 382 | if (notify) { |
| 383 | ScaffoldMessenger.of(context).showSnackBar(SnackBar( |
| 384 | content: Text(outcome.queued |
| 385 | ? 'تغییر روی دستگاه ثبت شد؛ در انتظار تأیید سرور.' |
| 386 | : 'تغییر توسط سرور تأیید شد.'))); |
| 387 | } |
| 388 | await reload(); |
| 389 | } |
| 390 | return outcome; |
| 391 | } |
| 392 | |
| 393 | bool owns(Map<String, dynamic> item) { |
| 394 | final api = widget.api; |
| 395 | if (api is! HttpIdentityApi) return true; |
| 396 | final owner = item['owner_user_id'] ?? item['ownerUserId']; |
| 397 | return api.currentUserId != null && |
| 398 | (owner == api.currentUserId || |
| 399 | (owner == null && ownedCreates.contains(item['id']))); |
| 400 | } |
| 401 | |
| 402 | Future<void> addSeries() async { |
| 403 | final api = widget.api; |
| 404 | if (api is! HttpIdentityApi) return; |
| 405 | final result = await showDialog<PlannerSeriesOutcome>( |
| 406 | context: context, |
| 407 | barrierDismissible: false, |
| 408 | builder: (_) => |
| 409 | PlannerSeriesDialog(api: api, initialDate: selectedDay)); |
| 410 | if (result != null && mounted) { |
| 411 | ScaffoldMessenger.of(context).showSnackBar(SnackBar( |
| 412 | content: Text(result.queued |
| 413 | ? 'پیشنویس روی دستگاه ماند؛ نوبتها و اعلان پس از تأیید سرور آماده میشوند.' |
| 414 | : 'برنامهٔ تکراری و نوبتهای آن در سرور ثبت شد.'))); |
| 415 | await reload(); |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | List<Map<String, dynamic>> visibleItems(LoadResult data) { |
| 420 | if (widget.today) { |
| 421 | return widget.home ? data.items.take(4).toList() : data.items; |
| 422 | } |
| 423 | final rows = data.items.where((row) { |
| 424 | final date = parseDate( |
| 425 | row['starts_at'] ?? row['startsAt'] ?? row['due_at'] ?? row['dueAt']); |
| 426 | return date != null && plannerDate(date) == plannerDate(selectedDay); |
| 427 | }).toList(); |
| 428 | rows.sort((a, b) => (a['starts_at'] ?? a['due_at'] ?? '') |
| 429 | .toString() |
| 430 | .compareTo((b['starts_at'] ?? b['due_at'] ?? '').toString())); |
| 431 | return rows; |
| 432 | } |
| 433 | |
| 434 | Widget weekSelector() => |
| 435 | Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ |
| 436 | Row(children: [ |
| 437 | IconButton( |
| 438 | tooltip: 'هفتهٔ قبل', |
| 439 | onPressed: () => setState(() { |
| 440 | selectedDay = selectedDay.subtract(const Duration(days: 7)); |
| 441 | future = load(); |
| 442 | }), |
| 443 | icon: const Icon(Icons.chevron_right)), |
| 444 | Expanded( |
| 445 | child: Text('هفتهٔ من', |
| 446 | style: Theme.of(context).textTheme.titleLarge)), |
| 447 | TextButton( |
| 448 | onPressed: () => setState(() { |
| 449 | selectedDay = DateTime.now(); |
| 450 | future = load(); |
| 451 | }), |
| 452 | child: const Text('امروز')), |
| 453 | IconButton( |
| 454 | tooltip: 'هفتهٔ بعد', |
| 455 | onPressed: () => setState(() { |
| 456 | selectedDay = selectedDay.add(const Duration(days: 7)); |
| 457 | future = load(); |
| 458 | }), |
| 459 | icon: const Icon(Icons.chevron_left)) |
| 460 | ]), |
| 461 | Text( |
| 462 | '${plannerDate(plannerWeekDays(selectedDay).first)} تا ${plannerDate(plannerWeekDays(selectedDay).last)} · میلادی'), |
| 463 | SingleChildScrollView( |
| 464 | scrollDirection: Axis.horizontal, |
| 465 | child: Row(children: [ |
| 466 | for (final day in plannerWeekDays(selectedDay)) |
| 467 | Padding( |
| 468 | padding: const EdgeInsets.only(left: 8), |
| 469 | child: ChoiceChip( |
| 470 | key: ValueKey('planner-day-${day.weekday}'), |
| 471 | label: Text('${const { |
| 472 | 6: 'شنبه', |
| 473 | 7: 'یکشنبه', |
| 474 | 1: 'دوشنبه', |
| 475 | 2: 'سهشنبه', |
| 476 | 3: 'چهارشنبه', |
| 477 | 4: 'پنجشنبه', |
| 478 | 5: 'جمعه' |
| 479 | }[day.weekday]} · ${shortDay(day)}'), |
| 480 | selected: plannerDate(day) == plannerDate(selectedDay), |
| 481 | onSelected: (_) => setState(() => selectedDay = day))) |
| 482 | ])), |
| 483 | const SizedBox(height: 12), |
| 484 | ]); |
| 485 | |
| 486 | String shortDay(DateTime day) => '${day.month}/${day.day}'; |
| 487 | |
| 488 | Future<void> openDetails(Map<String, dynamic> item, bool offline) async { |
| 489 | final canEdit = owns(item); |
| 490 | final updates = canEdit ? null : ValueNotifier<Map<String, dynamic>?>(item); |
| 491 | sharedDetail = updates; |
| 492 | sharedDetailId = canEdit ? null : item['id'].toString(); |
| 493 | await Navigator.of(context).push(MaterialPageRoute( |
| 494 | builder: (_) => PlanDetailsPage( |
| 495 | item: item, |
| 496 | sharedUpdates: updates, |
| 497 | canEdit: canEdit, |
| 498 | offline: offline, |
| 499 | canStudy: canEdit && |
| 500 | widget.api is HttpIdentityApi && |
| 501 | ['assignment', 'task', 'study_session'].contains(item['kind']), |
| 502 | onAction: (current, action) => |
| 503 | this.action(current, action, rethrowFailure: true), |
| 504 | kindLabel: faKind, |
| 505 | dateLabel: shortDate, |
| 506 | errorLabel: uiErrorText))); |
| 507 | if (identical(sharedDetail, updates)) { |
| 508 | sharedDetail = null; |
| 509 | sharedDetailId = null; |
| 510 | } |
| 511 | updates?.dispose(); |
| 512 | if (mounted) await reload(); |
| 513 | } |
| 514 | |
| 515 | Future<MutationOutcome?> action(Map<String, dynamic> item, String action, |
| 516 | {bool rethrowFailure = false}) async { |
| 517 | if (busyId != null) return null; |
| 518 | if (!owns(item)) { |
| 519 | if (rethrowFailure) throw const ApiException(403, 'forbidden'); |
| 520 | return null; |
| 521 | } |
| 522 | if (action == 'edit') { |
| 523 | return edit(item, !rethrowFailure); |
| 524 | } |
| 525 | if (action == 'study') { |
| 526 | if (item['pending_sync'] == true) { |
| 527 | setState(() => operationError = |
| 528 | 'تکلیف هنوز در سرور تأیید نشده است؛ تایمر پس از همگامسازی فعال میشود.'); |
| 529 | return null; |
| 530 | } |
| 531 | if (widget.api is! HttpIdentityApi) { |
| 532 | setState(() => operationError = 'اتصال مطالعه در دسترس نیست.'); |
| 533 | return null; |
| 534 | } |
| 535 | await Navigator.of(context).push(MaterialPageRoute( |
| 536 | builder: (_) => |
| 537 | StudyTimerPage(api: widget.api as HttpIdentityApi, item: item))); |
| 538 | if (!mounted) return null; |
| 539 | await reload(); |
| 540 | final fresh = await future; |
| 541 | if (fresh.offline) throw const ApiException(0, 'network_unavailable'); |
| 542 | final current = |
| 543 | fresh.items.where((row) => row['id'] == item['id']).firstOrNull; |
| 544 | if (current == null) throw const ApiException(404, 'not_found'); |
| 545 | return MutationOutcome( |
| 546 | queued: current['pending_sync'] == true, item: current); |
| 547 | } |
| 548 | if (action == 'archive') { |
| 549 | final confirmed = await showDialog<bool>( |
| 550 | context: context, |
| 551 | builder: (c) => AlertDialog( |
| 552 | title: const Text('بایگانی مورد'), |
| 553 | content: Text('«${item['title']}» بایگانی شود؟'), |
| 554 | actions: [ |
| 555 | TextButton( |
| 556 | onPressed: () => Navigator.pop(c, false), |
| 557 | child: const Text('انصراف')), |
| 558 | FilledButton( |
| 559 | onPressed: () => Navigator.pop(c, true), |
| 560 | child: const Text('بایگانی')) |
| 561 | ])); |
| 562 | if (confirmed != true || !mounted) return null; |
| 563 | } |
| 564 | setState(() { |
| 565 | busyId = item['id'].toString(); |
| 566 | operationError = null; |
| 567 | }); |
| 568 | try { |
| 569 | final sync = PlanSync(widget.api); |
| 570 | final outcome = action == 'archive' |
| 571 | ? await sync.archive(item) |
| 572 | : action == 'start' |
| 573 | ? await sync.update(item, {'status': 'in_progress'}) |
| 574 | : action == 'uncomplete' |
| 575 | ? await sync.update(item, {'status': 'planned'}) |
| 576 | : await sync.complete(item); |
| 577 | if (mounted) { |
| 578 | // Detail has an inline receipt; avoid covering its action controls. |
| 579 | if (!rethrowFailure || action == 'archive') { |
| 580 | ScaffoldMessenger.of(context).showSnackBar(SnackBar( |
| 581 | content: Text(outcome.queued |
| 582 | ? 'تغییر در انتظار تأیید سرور است.' |
| 583 | : 'سرور تغییر را تأیید کرد.'))); |
| 584 | } |
| 585 | await reload(); |
| 586 | } |
| 587 | return outcome; |
| 588 | } catch (error) { |
| 589 | if (mounted) setState(() => operationError = uiErrorText(error)); |
| 590 | if (rethrowFailure) rethrow; |
| 591 | } finally { |
| 592 | if (mounted) setState(() => busyId = null); |
| 593 | } |
| 594 | return null; |
| 595 | } |
| 596 | |
| 597 | @override |
| 598 | Widget build(BuildContext context) => FutureBuilder<LoadResult>( |
| 599 | future: future, |
| 600 | builder: (context, s) { |
| 601 | if (s.hasError) return LoadError(error: s.error!, retry: reload); |
| 602 | if (!s.hasData) return const Center(child: CircularProgressIndicator()); |
| 603 | final data = s.data!; |
| 604 | final visible = visibleItems(data); |
| 605 | final completed = |
| 606 | data.items.where((row) => row['status'] == 'completed').length; |
| 607 | final next = |
| 608 | data.items.where((row) => row['status'] != 'completed').firstOrNull; |
| 609 | return RefreshIndicator( |
| 610 | onRefresh: reload, |
| 611 | child: ListView(padding: const EdgeInsets.all(16), children: [ |
| 612 | ...data.reminders.map((r) => Card( |
| 613 | child: ListTile( |
| 614 | leading: const Icon(Icons.notifications_active_outlined), |
| 615 | title: Text('یادآوری · ${r['title'] ?? 'برنامه'}'), |
| 616 | subtitle: |
| 617 | const Text('موعد این مورد رسیده یا نزدیک است.')))), |
| 618 | SyncNotice( |
| 619 | offline: data.offline, |
| 620 | pending: data.pending, |
| 621 | syncedAt: data.syncedAt), |
| 622 | if (reminderError != null) |
| 623 | Card( |
| 624 | child: Padding( |
| 625 | padding: const EdgeInsets.all(12), |
| 626 | child: Text(reminderError!))), |
| 627 | if (widget.home) ...[ |
| 628 | Text('سلام ${widget.displayName}', |
| 629 | style: Theme.of(context).textTheme.headlineSmall), |
| 630 | const SizedBox(height: 12), |
| 631 | Card( |
| 632 | child: Padding( |
| 633 | padding: const EdgeInsets.all(16), |
| 634 | child: Column( |
| 635 | crossAxisAlignment: CrossAxisAlignment.start, |
| 636 | children: [ |
| 637 | Text('قدم بعدی', |
| 638 | style: |
| 639 | Theme.of(context).textTheme.titleLarge), |
| 640 | const SizedBox(height: 8), |
| 641 | Text(next?['title']?.toString() ?? |
| 642 | 'امروز کاری نداری؛ میتوانی برنامهٔ فردا را آماده کنی.'), |
| 643 | if (next != null) |
| 644 | FilledButton( |
| 645 | onPressed: busyId == null && owns(next) |
| 646 | ? () => action(next, 'start') |
| 647 | : null, |
| 648 | child: const Text('شروع')), |
| 649 | const SizedBox(height: 12), |
| 650 | Text( |
| 651 | '$completed از ${data.items.length} کار امروز انجام شده'), |
| 652 | LinearProgressIndicator( |
| 653 | value: data.items.isEmpty |
| 654 | ? 0 |
| 655 | : completed / data.items.length), |
| 656 | ]))), |
| 657 | ], |
| 658 | if (operationError != null) |
| 659 | Card( |
| 660 | child: Padding( |
| 661 | padding: const EdgeInsets.all(12), |
| 662 | child: Text(operationError!, |
| 663 | style: TextStyle( |
| 664 | color: Theme.of(context).colorScheme.error)))), |
| 665 | Row(children: [ |
| 666 | Expanded( |
| 667 | child: Text(widget.today ? 'کارهای امروز' : 'برنامهریز', |
| 668 | style: Theme.of(context).textTheme.headlineSmall)), |
| 669 | if (!widget.today) |
| 670 | FilledButton.icon( |
| 671 | onPressed: busyId == null ? () => edit() : null, |
| 672 | icon: const Icon(Icons.add), |
| 673 | label: const Text('جدید')) |
| 674 | ]), |
| 675 | if (widget.home) |
| 676 | Align( |
| 677 | alignment: AlignmentDirectional.centerEnd, |
| 678 | child: TextButton( |
| 679 | key: const ValueKey('home-plan'), |
| 680 | onPressed: widget.onOpenPlanner, |
| 681 | child: const Text('دیدن برنامهٔ هفته'))), |
| 682 | if (!widget.today) ...[ |
| 683 | weekSelector(), |
| 684 | if (widget.api is HttpIdentityApi) |
| 685 | OutlinedButton.icon( |
| 686 | onPressed: busyId == null ? addSeries : null, |
| 687 | icon: const Icon(Icons.repeat), |
| 688 | label: const Text('برنامهٔ تکراری')), |
| 689 | const Text( |
| 690 | 'تیک و ویرایش هر نوبت فقط همان روز را تغییر میدهد.'), |
| 691 | ], |
| 692 | if (visible.isEmpty) |
| 693 | const EmptyCard( |
| 694 | icon: Icons.task_alt, |
| 695 | title: 'موردی در این برنامه نیست', |
| 696 | subtitle: 'از برنامهریز کار یا تکلیف جدید اضافه کن.'), |
| 697 | ...visible.map((item) => Card( |
| 698 | child: ListTile( |
| 699 | leading: !owns(item) |
| 700 | ? const Icon(Icons.visibility_outlined) |
| 701 | : IconButton( |
| 702 | key: ValueKey('tick-${item['id']}'), |
| 703 | tooltip: item['status'] == 'completed' |
| 704 | ? 'برگرداندن به برنامه' |
| 705 | : 'انجام شد', |
| 706 | onPressed: busyId == null |
| 707 | ? () => action( |
| 708 | item, |
| 709 | item['status'] == 'completed' |
| 710 | ? 'uncomplete' |
| 711 | : 'complete') |
| 712 | : null, |
| 713 | icon: Icon(item['status'] == 'completed' |
| 714 | ? Icons.check_circle |
| 715 | : Icons.radio_button_unchecked)), |
| 716 | onTap: busyId == null |
| 717 | ? () => openDetails(item, data.offline) |
| 718 | : null, |
| 719 | title: Text(item['title']?.toString() ?? ''), |
| 720 | subtitle: Text( |
| 721 | '${faKind(item['kind']?.toString() ?? 'task')} · ${planTimeLabel(item)}${item['pending_sync'] == true ? '\nدر انتظار تأیید سرور' : ''}'), |
| 722 | trailing: busyId == item['id'] |
| 723 | ? const SizedBox( |
| 724 | width: 24, |
| 725 | height: 24, |
| 726 | child: CircularProgressIndicator()) |
| 727 | : widget.home && |
| 728 | owns(item) && |
| 729 | item['status'] != 'completed' |
| 730 | ? TextButton( |
| 731 | onPressed: busyId == null |
| 732 | ? () => action(item, 'start') |
| 733 | : null, |
| 734 | child: const Text('شروع')) |
| 735 | : !owns(item) |
| 736 | ? const Icon(Icons.visibility_outlined) |
| 737 | : PopupMenuButton<String>( |
| 738 | onSelected: (v) => action(item, v), |
| 739 | itemBuilder: (_) => [ |
| 740 | const PopupMenuItem( |
| 741 | value: 'edit', |
| 742 | child: Text('ویرایش')), |
| 743 | const PopupMenuItem( |
| 744 | value: 'complete', |
| 745 | child: Text('انجام شد')), |
| 746 | if (item['pending_sync'] != true && |
| 747 | widget.api is HttpIdentityApi && |
| 748 | [ |
| 749 | 'assignment', |
| 750 | 'task', |
| 751 | 'study_session' |
| 752 | ].contains(item['kind'])) |
| 753 | const PopupMenuItem( |
| 754 | value: 'study', |
| 755 | child: Text('تایمر مطالعه')), |
| 756 | const PopupMenuItem( |
| 757 | value: 'archive', |
| 758 | child: Text('بایگانی')), |
| 759 | ]), |
| 760 | ))), |
| 761 | if (!widget.today && |
| 762 | data.items.any((row) => |
| 763 | parseDate(row['starts_at'] ?? row['due_at']) == |
| 764 | null)) ...[ |
| 765 | const SizedBox(height: 12), |
| 766 | Text('بدون زمان مشخص', |
| 767 | style: Theme.of(context).textTheme.titleMedium), |
| 768 | for (final item in data.items.where((row) => |
| 769 | parseDate(row['starts_at'] ?? row['due_at']) == null)) |
| 770 | Card( |
| 771 | child: ListTile( |
| 772 | title: Text(item['title']?.toString() ?? ''), |
| 773 | onTap: () => openDetails(item, data.offline))), |
| 774 | ], |
| 775 | ])); |
| 776 | }); |
| 777 | } |
| 778 | |
| 779 | class PlanItemDialog extends StatefulWidget { |
| 780 | const PlanItemDialog( |
| 781 | {super.key, |
| 782 | required this.api, |
| 783 | this.item, |
| 784 | this.initialDate, |
| 785 | this.initialKind = 'task', |
| 786 | this.subjects = const []}); |
| 787 | final IdentityApi api; |
| 788 | final Map<String, dynamic>? item; |
| 789 | final DateTime? initialDate; |
| 790 | final String initialKind; |
| 791 | final List<Map<String, dynamic>> subjects; |
| 792 | @override |
| 793 | State<PlanItemDialog> createState() => _PlanItemDialogState(); |
| 794 | } |
| 795 | |
| 796 | class _PlanItemDialogState extends State<PlanItemDialog> { |
| 797 | late final TextEditingController title, notes, minutes, points, outOf; |
| 798 | late String kind; |
| 799 | String priority = 'normal', status = 'planned'; |
| 800 | late DateTime when; |
| 801 | late DateTime endsWhen; |
| 802 | bool hasRange = false, rangeChanged = false, reminderChanged = false; |
| 803 | int reminderBefore = -1; |
| 804 | bool shared = false, busy = false, sharingChanged = false; |
| 805 | String originalVisibility = 'private'; |
| 806 | String? subjectId; |
| 807 | String? familyId, error; |
| 808 | List<Map<String, dynamic>> families = []; |
| 809 | @override |
| 810 | void initState() { |
| 811 | super.initState(); |
| 812 | final i = widget.item; |
| 813 | title = TextEditingController(text: i?['title']?.toString() ?? ''); |
| 814 | notes = TextEditingController(text: i?['notes']?.toString() ?? ''); |
| 815 | points = TextEditingController( |
| 816 | text: (i?['grade_points'] ?? i?['gradePoints'])?.toString() ?? ''); |
| 817 | outOf = TextEditingController( |
| 818 | text: (i?['grade_out_of'] ?? i?['gradeOutOf'])?.toString() ?? ''); |
| 819 | minutes = TextEditingController( |
| 820 | text: (((i?['planned_duration_seconds'] ?? |
| 821 | i?['plannedDurationSeconds'] ?? |
| 822 | 1800) as num) ~/ |
| 823 | 60) |
| 824 | .toString()); |
| 825 | kind = i?['kind']?.toString() ?? widget.initialKind; |
| 826 | priority = i?['priority']?.toString() ?? 'normal'; |
| 827 | status = i?['status']?.toString() ?? 'planned'; |
| 828 | when = parseDate( |
| 829 | i?['starts_at'] ?? i?['startsAt'] ?? i?['due_at'] ?? i?['dueAt']) ?? |
| 830 | (widget.initialDate == null |
| 831 | ? DateTime.now().add(const Duration(hours: 1)) |
| 832 | : DateTime(widget.initialDate!.year, widget.initialDate!.month, |
| 833 | widget.initialDate!.day, 9)); |
| 834 | hasRange = i == null || i['starts_at'] != null || i['startsAt'] != null; |
| 835 | endsWhen = parseDate(i?['ends_at'] ?? i?['endsAt']) ?? |
| 836 | when.add(Duration(minutes: int.tryParse(minutes.text) ?? 30)); |
| 837 | originalVisibility = i?['visibility']?.toString() ?? 'private'; |
| 838 | shared = originalVisibility != 'private'; |
| 839 | subjectId = i?['subject_id']?.toString() ?? i?['subjectId']?.toString(); |
| 840 | if (subjectId == null && widget.subjects.isNotEmpty) { |
| 841 | subjectId = widget.subjects.first['id'].toString(); |
| 842 | } |
| 843 | familyId = i?['family_id']?.toString() ?? i?['familyId']?.toString(); |
| 844 | if (i?['series_id'] == null) loadFamilies(); |
| 845 | } |
| 846 | |
| 847 | Future<void> loadFamilies() async { |
| 848 | try { |
| 849 | final rows = await widget.api.listFamilies(); |
| 850 | if (mounted) setState(() => families = rows); |
| 851 | } catch (e) { |
| 852 | if (mounted) setState(() => error = uiErrorText(e)); |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | @override |
| 857 | void dispose() { |
| 858 | title.dispose(); |
| 859 | notes.dispose(); |
| 860 | minutes.dispose(); |
| 861 | points.dispose(); |
| 862 | outOf.dispose(); |
| 863 | super.dispose(); |
| 864 | } |
| 865 | |
| 866 | Future<void> pickDate() async { |
| 867 | final date = await showDatePicker( |
| 868 | context: context, |
| 869 | initialDate: when, |
| 870 | firstDate: DateTime(2020), |
| 871 | lastDate: DateTime(2100)); |
| 872 | if (date == null || !mounted) return; |
| 873 | final time = await showTimePicker( |
| 874 | context: context, initialTime: TimeOfDay.fromDateTime(when)); |
| 875 | if (time != null && mounted) { |
| 876 | setState(() { |
| 877 | when = |
| 878 | DateTime(date.year, date.month, date.day, time.hour, time.minute); |
| 879 | endsWhen = DateTime( |
| 880 | date.year, date.month, date.day, endsWhen.hour, endsWhen.minute); |
| 881 | rangeChanged = true; |
| 882 | }); |
| 883 | } |
| 884 | } |
| 885 | |
| 886 | Future<void> pickEnd() async { |
| 887 | final time = await showTimePicker( |
| 888 | context: context, initialTime: TimeOfDay.fromDateTime(endsWhen)); |
| 889 | if (time != null && mounted) { |
| 890 | setState(() { |
| 891 | endsWhen = |
| 892 | DateTime(when.year, when.month, when.day, time.hour, time.minute); |
| 893 | rangeChanged = true; |
| 894 | }); |
| 895 | } |
| 896 | } |
| 897 | |
| 898 | Future<void> save() async { |
| 899 | if (busy) return; |
| 900 | if (title.text.trim().isEmpty) { |
| 901 | setState(() => error = 'عنوان را وارد کن.'); |
| 902 | return; |
| 903 | } |
| 904 | final duration = hasRange |
| 905 | ? endsWhen.difference(when).inMinutes |
| 906 | : int.tryParse(numberInput(minutes.text)); |
| 907 | if (hasRange && (duration == null || duration <= 0 || duration > 1440)) { |
| 908 | setState(() => error = 'پایان باید پس از شروع و در همان روز باشد.'); |
| 909 | return; |
| 910 | } |
| 911 | if (duration == null || duration < 0 || duration > 1440) { |
| 912 | setState( |
| 913 | () => error = 'زمان برنامهریزیشده باید بین صفر و ۱۴۴۰ دقیقه باشد.'); |
| 914 | return; |
| 915 | } |
| 916 | final graded = ['assignment', 'exam'].contains(kind); |
| 917 | final hasGrade = |
| 918 | points.text.trim().isNotEmpty || outOf.text.trim().isNotEmpty; |
| 919 | final gradePoints = num.tryParse(numberInput(points.text)), |
| 920 | gradeOutOf = num.tryParse(numberInput(outOf.text)); |
| 921 | if (graded && |
| 922 | hasGrade && |
| 923 | (gradePoints == null || |
| 924 | gradeOutOf == null || |
| 925 | !gradePoints.isFinite || |
| 926 | !gradeOutOf.isFinite || |
| 927 | gradePoints < 0 || |
| 928 | gradeOutOf <= 0 || |
| 929 | gradePoints > gradeOutOf || |
| 930 | gradeOutOf > 999999.99)) { |
| 931 | setState(() => error = |
| 932 | 'نمره و سقف نمره را با هم وارد کن؛ نمره باید بین صفر و سقف باشد.'); |
| 933 | return; |
| 934 | } |
| 935 | if (shared && familyId == null) { |
| 936 | setState(() => error = 'خانوادهای را برای اشتراک با والد انتخاب کن.'); |
| 937 | return; |
| 938 | } |
| 939 | setState(() { |
| 940 | busy = true; |
| 941 | error = null; |
| 942 | }); |
| 943 | try { |
| 944 | final item = widget.item; |
| 945 | final visibility = widget.item != null && !sharingChanged |
| 946 | ? originalVisibility |
| 947 | : shared |
| 948 | ? 'parent_guardian' |
| 949 | : 'private'; |
| 950 | final payload = <String, dynamic>{ |
| 951 | 'kind': kind, |
| 952 | 'title': title.text.trim(), |
| 953 | 'priority': priority, |
| 954 | 'status': status, |
| 955 | 'notes': notes.text.trim(), |
| 956 | 'dueAt': (hasRange ? endsWhen : when).toUtc().toIso8601String(), |
| 957 | if (item == null || |
| 958 | rangeChanged || |
| 959 | item['starts_at'] != null || |
| 960 | item['startsAt'] != null) ...{ |
| 961 | 'startsAt': hasRange ? when.toUtc().toIso8601String() : null, |
| 962 | 'endsAt': hasRange ? endsWhen.toUtc().toIso8601String() : null, |
| 963 | }, |
| 964 | if (item == null || reminderChanged) |
| 965 | 'reminderMinutesBefore': |
| 966 | reminderBefore < 0 ? <int>[] : [reminderBefore], |
| 967 | 'plannedDurationSeconds': duration * 60, |
| 968 | 'visibility': visibility, |
| 969 | 'familyId': visibility != 'private' ? familyId : null, |
| 970 | if (subjectId != null) 'subjectId': subjectId, |
| 971 | if (graded && |
| 972 | (hasGrade || |
| 973 | widget.item?['grade_points'] != null || |
| 974 | widget.item?['gradePoints'] != null)) ...{ |
| 975 | 'gradePoints': hasGrade ? gradePoints : null, |
| 976 | 'gradeOutOf': hasGrade ? gradeOutOf : null |
| 977 | } |
| 978 | }; |
| 979 | final sync = PlanSync(widget.api); |
| 980 | final result = item == null |
| 981 | ? await sync.create(payload) |
| 982 | : await sync.update(item, payload); |
| 983 | if (mounted) Navigator.pop(context, result); |
| 984 | } catch (e) { |
| 985 | if (mounted) setState(() => error = uiErrorText(e)); |
| 986 | } finally { |
| 987 | if (mounted) setState(() => busy = false); |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | @override |
| 992 | Widget build(BuildContext context) => PopScope( |
| 993 | canPop: !busy, |
| 994 | child: AlertDialog( |
| 995 | title: Text(widget.item == null ? 'مورد جدید' : 'ویرایش مورد'), |
| 996 | content: SizedBox( |
| 997 | width: 440, |
| 998 | child: SingleChildScrollView( |
| 999 | child: Column(mainAxisSize: MainAxisSize.min, children: [ |
| 1000 | TextField( |
| 1001 | controller: title, |
| 1002 | enabled: !busy, |
| 1003 | decoration: const InputDecoration(labelText: 'عنوان')), |
| 1004 | const SizedBox(height: 12), |
| 1005 | DropdownButtonFormField<String>( |
| 1006 | initialValue: kind, |
| 1007 | decoration: const InputDecoration(labelText: 'نوع'), |
| 1008 | items: [ |
| 1009 | for (final k in [ |
| 1010 | 'task', |
| 1011 | 'assignment', |
| 1012 | 'exam', |
| 1013 | 'event', |
| 1014 | 'routine', |
| 1015 | 'goal', |
| 1016 | 'study_session' |
| 1017 | ]) |
| 1018 | DropdownMenuItem(value: k, child: Text(faKind(k))) |
| 1019 | ], |
| 1020 | onChanged: |
| 1021 | busy ? null : (v) => setState(() => kind = v ?? kind)), |
| 1022 | if (widget.subjects.isNotEmpty) |
| 1023 | DropdownButtonFormField<String>( |
| 1024 | initialValue: subjectId, |
| 1025 | decoration: const InputDecoration(labelText: 'درس'), |
| 1026 | items: widget.subjects |
| 1027 | .map((row) => DropdownMenuItem( |
| 1028 | value: row['id'].toString(), |
| 1029 | child: Text(row['name']?.toString() ?? 'درس'))) |
| 1030 | .toList(), |
| 1031 | onChanged: |
| 1032 | busy ? null : (v) => setState(() => subjectId = v)), |
| 1033 | const SizedBox(height: 12), |
| 1034 | DropdownButtonFormField<String>( |
| 1035 | initialValue: priority, |
| 1036 | decoration: const InputDecoration(labelText: 'اولویت'), |
| 1037 | items: const [ |
| 1038 | DropdownMenuItem(value: 'low', child: Text('کم')), |
| 1039 | DropdownMenuItem(value: 'normal', child: Text('معمولی')), |
| 1040 | DropdownMenuItem(value: 'high', child: Text('زیاد')), |
| 1041 | DropdownMenuItem(value: 'urgent', child: Text('فوری')) |
| 1042 | ], |
| 1043 | onChanged: busy |
| 1044 | ? null |
| 1045 | : (v) => setState(() => priority = v ?? priority)), |
| 1046 | if (widget.item != null) |
| 1047 | DropdownButtonFormField<String>( |
| 1048 | initialValue: status, |
| 1049 | decoration: const InputDecoration(labelText: 'وضعیت'), |
| 1050 | items: const [ |
| 1051 | DropdownMenuItem( |
| 1052 | value: 'planned', child: Text('برنامهریزیشده')), |
| 1053 | DropdownMenuItem( |
| 1054 | value: 'in_progress', child: Text('در حال انجام')), |
| 1055 | DropdownMenuItem( |
| 1056 | value: 'completed', child: Text('انجامشده')) |
| 1057 | ], |
| 1058 | onChanged: busy |
| 1059 | ? null |
| 1060 | : (v) => setState(() => status = v ?? status)), |
| 1061 | const SizedBox(height: 12), |
| 1062 | TextField( |
| 1063 | controller: minutes, |
| 1064 | enabled: !busy && !hasRange, |
| 1065 | keyboardType: TextInputType.number, |
| 1066 | decoration: const InputDecoration( |
| 1067 | labelText: 'زمان برنامهریزیشده (دقیقه)')), |
| 1068 | if (['assignment', 'exam'].contains(kind)) ...[ |
| 1069 | TextField( |
| 1070 | controller: points, |
| 1071 | enabled: !busy, |
| 1072 | keyboardType: |
| 1073 | const TextInputType.numberWithOptions(decimal: true), |
| 1074 | decoration: |
| 1075 | const InputDecoration(labelText: 'نمره (اختیاری)')), |
| 1076 | TextField( |
| 1077 | controller: outOf, |
| 1078 | enabled: !busy, |
| 1079 | keyboardType: |
| 1080 | const TextInputType.numberWithOptions(decimal: true), |
| 1081 | decoration: const InputDecoration( |
| 1082 | labelText: 'سقف نمره (اختیاری)')), |
| 1083 | ], |
| 1084 | CheckboxListTile( |
| 1085 | key: const ValueKey('plan-time-range'), |
| 1086 | title: const Text('ساعت شروع و پایان'), |
| 1087 | value: hasRange, |
| 1088 | onChanged: busy |
| 1089 | ? null |
| 1090 | : (value) => setState(() { |
| 1091 | hasRange = value ?? false; |
| 1092 | rangeChanged = true; |
| 1093 | })), |
| 1094 | TextButton.icon( |
| 1095 | onPressed: busy ? null : pickDate, |
| 1096 | icon: const Icon(Icons.calendar_month), |
| 1097 | label: Text( |
| 1098 | '${hasRange ? 'شروع' : 'موعد'} · ${shortDate(when.toIso8601String())}')), |
| 1099 | if (hasRange) |
| 1100 | TextButton.icon( |
| 1101 | key: const ValueKey('plan-end-time'), |
| 1102 | onPressed: busy ? null : pickEnd, |
| 1103 | icon: const Icon(Icons.schedule), |
| 1104 | label: Text( |
| 1105 | 'پایان · ${shortDate(endsWhen.toIso8601String())}')), |
| 1106 | DropdownButtonFormField<int>( |
| 1107 | key: const ValueKey('plan-reminder'), |
| 1108 | initialValue: reminderBefore, |
| 1109 | decoration: InputDecoration( |
| 1110 | labelText: widget.item != null && !reminderChanged |
| 1111 | ? 'یادآوری (فقط در صورت تغییر جایگزین میشود)' |
| 1112 | : 'یادآوری'), |
| 1113 | items: const [ |
| 1114 | DropdownMenuItem(value: -1, child: Text('بدون یادآوری')), |
| 1115 | DropdownMenuItem(value: 0, child: Text('زمان شروع')), |
| 1116 | DropdownMenuItem(value: 5, child: Text('۵ دقیقه قبل')), |
| 1117 | DropdownMenuItem(value: 10, child: Text('۱۰ دقیقه قبل')), |
| 1118 | DropdownMenuItem(value: 15, child: Text('۱۵ دقیقه قبل')) |
| 1119 | ], |
| 1120 | onChanged: busy |
| 1121 | ? null |
| 1122 | : (value) => setState(() { |
| 1123 | reminderBefore = value ?? -1; |
| 1124 | reminderChanged = true; |
| 1125 | })), |
| 1126 | TextField( |
| 1127 | controller: notes, |
| 1128 | enabled: !busy, |
| 1129 | maxLines: 2, |
| 1130 | decoration: const InputDecoration( |
| 1131 | labelText: 'یادداشت خصوصی', |
| 1132 | helperText: |
| 1133 | 'یادداشت در گزارش والد نمایش داده نمیشود.')), |
| 1134 | if (widget.item?['series_id'] != null) |
| 1135 | const Text( |
| 1136 | 'این نوبت خصوصی است؛ ویرایش و تیک فقط همین روز را تغییر میدهد.'), |
| 1137 | if (widget.item?['series_id'] == null) |
| 1138 | SwitchListTile( |
| 1139 | title: const Text('اشتراک تکلیف با والد / سرپرست'), |
| 1140 | subtitle: const Text( |
| 1141 | 'عنوان، وضعیت و زمان ثبتشده برای سرپرست مجاز دیده میشود.'), |
| 1142 | value: shared, |
| 1143 | onChanged: busy |
| 1144 | ? null |
| 1145 | : (v) => setState(() { |
| 1146 | shared = v; |
| 1147 | sharingChanged = true; |
| 1148 | })), |
| 1149 | if (widget.item != null && |
| 1150 | !['private', 'parent_guardian'] |
| 1151 | .contains(originalVisibility) && |
| 1152 | !sharingChanged) |
| 1153 | const Text( |
| 1154 | 'دامنه اشتراک فعلی با ذخیره حفظ میشود؛ تغییر کلید، آن را به والد یا خصوصی تغییر میدهد.'), |
| 1155 | if (shared) |
| 1156 | DropdownButtonFormField<String>( |
| 1157 | initialValue: familyId, |
| 1158 | decoration: const InputDecoration(labelText: 'خانواده'), |
| 1159 | items: families |
| 1160 | .map((f) => DropdownMenuItem( |
| 1161 | value: f['id'].toString(), |
| 1162 | child: Text(f['name']?.toString() ?? 'خانواده'))) |
| 1163 | .toList(), |
| 1164 | onChanged: |
| 1165 | busy ? null : (v) => setState(() => familyId = v)), |
| 1166 | if (error != null) |
| 1167 | Padding( |
| 1168 | padding: const EdgeInsets.only(top: 12), |
| 1169 | child: Text(error!, |
| 1170 | style: TextStyle( |
| 1171 | color: Theme.of(context).colorScheme.error))), |
| 1172 | ]))), |
| 1173 | actions: [ |
| 1174 | TextButton( |
| 1175 | onPressed: busy ? null : () => Navigator.pop(context), |
| 1176 | child: const Text('انصراف')), |
| 1177 | FilledButton( |
| 1178 | onPressed: busy ? null : save, |
| 1179 | child: Text(busy ? 'در حال ثبت...' : 'ذخیره')) |
| 1180 | ])); |
| 1181 | } |
| 1182 | |
| 1183 | class SchoolPage extends StatefulWidget { |
| 1184 | const SchoolPage({super.key, required this.api}); |
| 1185 | final IdentityApi api; |
| 1186 | @override |
| 1187 | State<SchoolPage> createState() => _SchoolPageState(); |
| 1188 | } |
| 1189 | |
| 1190 | class _SchoolPageState extends State<SchoolPage> { |
| 1191 | late Future<SchoolLoad> future; |
| 1192 | bool writing = false; |
| 1193 | String? writeError; |
| 1194 | @override |
| 1195 | void initState() { |
| 1196 | super.initState(); |
| 1197 | future = load(); |
| 1198 | } |
| 1199 | |
| 1200 | Future<SchoolLoad> load() async { |
| 1201 | final profile = await widget.api.getProfile(); |
| 1202 | final userId = profile['user_id']?.toString() ?? ''; |
| 1203 | if (userId.isEmpty) return SchoolLoad(userId, const {}, false); |
| 1204 | try { |
| 1205 | final overview = await widget.api.getSchoolOverview(userId); |
| 1206 | await OfflineStore.forApi(widget.api).cacheSchool([ |
| 1207 | {'userId': userId, 'overview': overview} |
| 1208 | ]); |
| 1209 | return SchoolLoad(userId, overview, false); |
| 1210 | } catch (failure) { |
| 1211 | if (!isOfflineFailure(failure)) rethrow; |
| 1212 | final cached = await OfflineStore.forApi(widget.api).readSchool(); |
| 1213 | if (cached.isNotEmpty) { |
| 1214 | return SchoolLoad( |
| 1215 | cached.first['userId']?.toString() ?? userId, |
| 1216 | Map<String, dynamic>.from( |
| 1217 | cached.first['overview'] as Map? ?? const {}), |
| 1218 | true, |
| 1219 | ); |
| 1220 | } |
| 1221 | return SchoolLoad(userId, const {}, true); |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | Future<void> reload() async { |
| 1226 | setState(() { |
| 1227 | future = load(); |
| 1228 | }); |
| 1229 | try { |
| 1230 | await future; |
| 1231 | } catch (_) {/* FutureBuilder renders retry failure. */} |
| 1232 | } |
| 1233 | |
| 1234 | Future<void> openManagement() async { |
| 1235 | if (widget.api is! HttpIdentityApi || writing) return; |
| 1236 | await Navigator.of(context).push(MaterialPageRoute<void>( |
| 1237 | builder: (_) => |
| 1238 | SchoolManagementPage(api: widget.api as HttpIdentityApi))); |
| 1239 | if (mounted) await reload(); |
| 1240 | } |
| 1241 | |
| 1242 | Future<void> addSchoolItem(String kind) async { |
| 1243 | try { |
| 1244 | final overview = await future; |
| 1245 | if (!mounted) return; |
| 1246 | final subjects = (overview.overview['subjects'] as List? ?? []) |
| 1247 | .map((raw) => Map<String, dynamic>.from(raw as Map)) |
| 1248 | .toList(); |
| 1249 | final saved = await showDialog<MutationOutcome>( |
| 1250 | context: context, |
| 1251 | builder: (_) => PlanItemDialog( |
| 1252 | api: widget.api, initialKind: kind, subjects: subjects)); |
| 1253 | if (saved != null && mounted) await reload(); |
| 1254 | } catch (error) { |
| 1255 | if (mounted) setState(() => writeError = uiErrorText(error)); |
| 1256 | } |
| 1257 | } |
| 1258 | |
| 1259 | @override |
| 1260 | Widget build(BuildContext context) => FutureBuilder<SchoolLoad>( |
| 1261 | future: future, |
| 1262 | builder: (context, snapshot) { |
| 1263 | if (snapshot.hasError) { |
| 1264 | return LoadError(error: snapshot.error!, retry: reload); |
| 1265 | } |
| 1266 | if (!snapshot.hasData) { |
| 1267 | return const Center(child: CircularProgressIndicator()); |
| 1268 | } |
| 1269 | final data = snapshot.data!; |
| 1270 | final years = data.overview['years'] as List<dynamic>? ?? const []; |
| 1271 | final subjects = |
| 1272 | data.overview['subjects'] as List<dynamic>? ?? const []; |
| 1273 | final workload = |
| 1274 | data.overview['workload'] as List<dynamic>? ?? const []; |
| 1275 | final grades = data.overview['grades'] as List<dynamic>? ?? const []; |
| 1276 | return ListView( |
| 1277 | padding: const EdgeInsets.all(16), |
| 1278 | children: [ |
| 1279 | if (writing) const LinearProgressIndicator(), |
| 1280 | if (writeError != null) Text(writeError!), |
| 1281 | if (data.offline) |
| 1282 | const Card( |
| 1283 | child: ListTile( |
| 1284 | leading: Icon(Icons.cloud_off_outlined), |
| 1285 | title: Text('اطلاعات مدرسه از کش نمایش داده میشود'))), |
| 1286 | if (years.isEmpty) |
| 1287 | EmptyCard( |
| 1288 | icon: Icons.school_outlined, |
| 1289 | title: 'مدرسه را آماده کن', |
| 1290 | subtitle: |
| 1291 | 'عنوانها، تاریخ سال و نیمسال و درسها را خودت انتخاب کن.', |
| 1292 | action: FilledButton.icon( |
| 1293 | onPressed: writing || widget.api is! HttpIdentityApi |
| 1294 | ? null |
| 1295 | : openManagement, |
| 1296 | icon: const Icon(Icons.school_outlined), |
| 1297 | label: const Text('مدیریت مدرسه'), |
| 1298 | ), |
| 1299 | ) |
| 1300 | else ...[ |
| 1301 | Card( |
| 1302 | child: Padding( |
| 1303 | padding: const EdgeInsets.all(16), |
| 1304 | child: Column( |
| 1305 | crossAxisAlignment: CrossAxisAlignment.stretch, |
| 1306 | children: [ |
| 1307 | Text('مدرسه', |
| 1308 | style: Theme.of(context).textTheme.headlineSmall), |
| 1309 | TextButton.icon( |
| 1310 | onPressed: |
| 1311 | writing || widget.api is! HttpIdentityApi |
| 1312 | ? null |
| 1313 | : openManagement, |
| 1314 | icon: const Icon(Icons.manage_accounts_outlined), |
| 1315 | label: const Text('مدیریت مدرسه')), |
| 1316 | const SizedBox(height: 10), |
| 1317 | Wrap(spacing: 8, runSpacing: 8, children: [ |
| 1318 | Chip(label: Text('${subjects.length} درس')), |
| 1319 | Chip( |
| 1320 | label: |
| 1321 | Text('${workload.length} کار درسی پیشرو')), |
| 1322 | Chip(label: Text('${grades.length} نمره')), |
| 1323 | ]), |
| 1324 | const SizedBox(height: 12), |
| 1325 | Row(children: [ |
| 1326 | Expanded( |
| 1327 | child: FilledButton.icon( |
| 1328 | onPressed: () => addSchoolItem('assignment'), |
| 1329 | icon: const Icon(Icons.assignment_add), |
| 1330 | label: const Text('تکلیف'), |
| 1331 | )), |
| 1332 | const SizedBox(width: 8), |
| 1333 | Expanded( |
| 1334 | child: OutlinedButton.icon( |
| 1335 | onPressed: () => addSchoolItem('exam'), |
| 1336 | icon: const Icon(Icons.quiz_outlined), |
| 1337 | label: const Text('امتحان'), |
| 1338 | )), |
| 1339 | ]), |
| 1340 | ]), |
| 1341 | ), |
| 1342 | ), |
| 1343 | const SizedBox(height: 12), |
| 1344 | Text('درسها', style: Theme.of(context).textTheme.titleMedium), |
| 1345 | ...subjects.map((raw) { |
| 1346 | final row = Map<String, dynamic>.from(raw as Map); |
| 1347 | return Card( |
| 1348 | child: ListTile( |
| 1349 | leading: const Icon(Icons.menu_book_outlined), |
| 1350 | title: Text(row['name']?.toString() ?? ''), |
| 1351 | subtitle: Text(row['teacher_name']?.toString() ?? |
| 1352 | row['term_title']?.toString() ?? |
| 1353 | ''), |
| 1354 | )); |
| 1355 | }), |
| 1356 | const SizedBox(height: 12), |
| 1357 | Text('کارهای درسی پیشرو', |
| 1358 | style: Theme.of(context).textTheme.titleMedium), |
| 1359 | ...workload.map((raw) { |
| 1360 | final row = Map<String, dynamic>.from(raw as Map); |
| 1361 | return Card( |
| 1362 | child: ListTile( |
| 1363 | title: Text(row['title']?.toString() ?? ''), |
| 1364 | subtitle: Text( |
| 1365 | '${faKind(row['kind']?.toString() ?? '')} · ${shortDate(row['due_at'] ?? row['starts_at'])}'), |
| 1366 | )); |
| 1367 | }), |
| 1368 | ], |
| 1369 | ], |
| 1370 | ); |
| 1371 | }, |
| 1372 | ); |
| 1373 | } |
| 1374 | |
| 1375 | class EmptyCard extends StatelessWidget { |
| 1376 | const EmptyCard( |
| 1377 | {super.key, |
| 1378 | required this.icon, |
| 1379 | required this.title, |
| 1380 | required this.subtitle, |
| 1381 | this.action}); |
| 1382 | final IconData icon; |
| 1383 | final String title, subtitle; |
| 1384 | final Widget? action; |
| 1385 | @override |
| 1386 | Widget build(BuildContext context) => Card( |
| 1387 | child: Padding( |
| 1388 | padding: const EdgeInsets.all(22), |
| 1389 | child: Column(children: [ |
| 1390 | Icon(icon, size: 42), |
| 1391 | Text(title, style: Theme.of(context).textTheme.titleMedium), |
| 1392 | const SizedBox(height: 6), |
| 1393 | Text(subtitle, textAlign: TextAlign.center), |
| 1394 | if (action != null) action! |
| 1395 | ]))); |
| 1396 | } |
| 1397 | |
| 1398 | class LoadResult { |
| 1399 | const LoadResult(this.items, this.offline, |
| 1400 | {this.pending = 0, this.syncedAt, this.reminders = const []}); |
| 1401 | final List<Map<String, dynamic>> items, reminders; |
| 1402 | final bool offline; |
| 1403 | final int pending; |
| 1404 | final DateTime? syncedAt; |
| 1405 | } |
| 1406 | |
| 1407 | class SchoolLoad { |
| 1408 | const SchoolLoad(this.userId, this.overview, this.offline); |
| 1409 | final String userId; |
| 1410 | final Map<String, dynamic> overview; |
| 1411 | final bool offline; |
| 1412 | } |