LifeMate — Personal, Family & Learning Companion
feat/flutter-mobile-navigation
chore/phase1-repository-cleanup
deploy/stable-web-apk
deployment-static
design/mobile-accessibility-v2
design/mobile-navigation-review
docs/child-education-access-decision
docs/offline-data-rescue-options
docs/owner-guide-and-delivery-plan
docs/phase1-policy-options
docs/public-review-live-2026-10-15
feat/aparat-learning-library
feat/child-device-safety
feat/child-identity-schema
feat/flutter-mobile-navigation
feat/learning-content-operations
feat/local-signing-preflight
feat/online-family-stage0
feat/personal-encrypted-recovery
feat/private-planner-series-api
feat/public-review-page
feat/standalone-weekly-planner
feat/weekly-planner-android
final-feature-1/iran-family-school
fix/auth-abuse-expiry-safety
fix/auth-expiry-after-lock
fix/backend-request-safety
fix/lifeguide-bootstrap-naming-ci
fix/lifeguide-pages-qa-base-preflight
fix/lifeguide-qa-pages-env-deployment
fix/local-task-persistence
fix/managed-child-session-boundary
fix/personal-jalali-dates
fix/personal-notification-controls
fix/personal-upgrade-delivery-guard
fix/sms-approval-gates
fix/study-duration-display
infra/cloudflare-neon-migration
infra/lifeguide-cloudflare-qa
infra/lifeguide-github-pages-qa
infra/lifeguide-supabase-qa
main
phase-1/foundation-completion
phase-2/product-foundation-identity
phase-3/planner-school-family-core
phase-4/ai-learning-wellbeing
phase-5/hardening-observability-release
test/android-reminder-acceptance
test/personal-notification-settings
test/personal-recovery-acceptance
test/role-entry-apk
| 1 | import 'package:flutter/material.dart'; |
| 2 | |
| 3 | import 'api.dart'; |
| 4 | import 'learning_goal_sync.dart'; |
| 5 | import 'offline_store.dart' show isOfflineFailure; |
| 6 | |
| 7 | bool _goalAuthFailure(Object error) => |
| 8 | error is ApiException && |
| 9 | (error.statusCode == 401 || error.statusCode == 403); |
| 10 | |
| 11 | String _goalError(Object error) { |
| 12 | if (isOfflineFailure(error)) { |
| 13 | return 'اتصال برقرار نیست؛ تغییر ذخیرهشده هنوز تأیید سرور ندارد.'; |
| 14 | } |
| 15 | if (_goalAuthFailure(error)) { |
| 16 | return 'نشست یا دسترسی معتبر نیست؛ هدفهای خصوصی قبلی از صفحه پاک شدند.'; |
| 17 | } |
| 18 | if (error is ApiException && error.statusCode == 409) { |
| 19 | return 'این هدف یک تغییر معلق یا تعارض نسخه دارد؛ ابتدا همگامسازی و نسخه سرور را بررسی کن.'; |
| 20 | } |
| 21 | return 'عملیات با پاسخ معتبر سرور تأیید نشد؛ وضعیت را تازه کن.'; |
| 22 | } |
| 23 | |
| 24 | class LearningGoalsPage extends StatefulWidget { |
| 25 | const LearningGoalsPage({super.key, required this.api}); |
| 26 | final HttpIdentityApi api; |
| 27 | @override |
| 28 | State<LearningGoalsPage> createState() => _LearningGoalsPageState(); |
| 29 | } |
| 30 | |
| 31 | class _LearningGoalsPageState extends State<LearningGoalsPage> |
| 32 | with WidgetsBindingObserver { |
| 33 | late final LearningGoalSync sync; |
| 34 | Map<String, dynamic>? snapshot; |
| 35 | String? error; |
| 36 | bool busy = false, editing = false, active = true, stale = false; |
| 37 | int epoch = 0; |
| 38 | BuildContext? privateDialog; |
| 39 | |
| 40 | bool current(int request) => mounted && active && epoch == request; |
| 41 | @override |
| 42 | void initState() { |
| 43 | super.initState(); |
| 44 | sync = LearningGoalSync(widget.api); |
| 45 | WidgetsBinding.instance.addObserver(this); |
| 46 | load(); |
| 47 | } |
| 48 | |
| 49 | @override |
| 50 | void dispose() { |
| 51 | ++epoch; |
| 52 | WidgetsBinding.instance.removeObserver(this); |
| 53 | super.dispose(); |
| 54 | } |
| 55 | |
| 56 | void closePrivateDialog() { |
| 57 | final dialog = privateDialog; |
| 58 | privateDialog = null; |
| 59 | if (dialog?.mounted != true) return; |
| 60 | final route = ModalRoute.of(dialog!); |
| 61 | if (route != null && route.isActive) { |
| 62 | Navigator.of(dialog).removeRoute(route); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | @override |
| 67 | void didChangeAppLifecycleState(AppLifecycleState state) { |
| 68 | active = state == AppLifecycleState.resumed; |
| 69 | ++epoch; |
| 70 | if (!active) closePrivateDialog(); |
| 71 | if (mounted) { |
| 72 | setState(() { |
| 73 | snapshot = null; |
| 74 | busy = false; |
| 75 | editing = false; |
| 76 | stale = false; |
| 77 | }); |
| 78 | } |
| 79 | if (active) load(); |
| 80 | } |
| 81 | |
| 82 | Future<void> load({bool retry = false}) async { |
| 83 | if (busy || editing || !active) return; |
| 84 | final request = ++epoch; |
| 85 | setState(() => busy = true); |
| 86 | try { |
| 87 | if (retry) await sync.flush(); |
| 88 | final value = await sync.read(); |
| 89 | if (current(request)) { |
| 90 | setState(() { |
| 91 | snapshot = value; |
| 92 | error = null; |
| 93 | stale = false; |
| 94 | }); |
| 95 | } |
| 96 | } catch (e) { |
| 97 | if (current(request)) { |
| 98 | setState(() { |
| 99 | if (_goalAuthFailure(e)) snapshot = null; |
| 100 | stale = snapshot != null; |
| 101 | error = _goalError(e); |
| 102 | }); |
| 103 | } |
| 104 | } finally { |
| 105 | if (current(request)) setState(() => busy = false); |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | Future<void> edit([Map<String, dynamic>? goal]) async { |
| 110 | if (busy || editing || !active) return; |
| 111 | final request = ++epoch; |
| 112 | setState(() => editing = true); |
| 113 | final result = await showDialog<Map<String, dynamic>>( |
| 114 | context: context, |
| 115 | barrierDismissible: false, |
| 116 | builder: (dialog) { |
| 117 | privateDialog = dialog; |
| 118 | return _LearningGoalEditor( |
| 119 | sync: sync, |
| 120 | goal: goal, |
| 121 | onAuthFailure: (e) { |
| 122 | if (!current(request)) return; |
| 123 | setState(() { |
| 124 | snapshot = null; |
| 125 | error = _goalError(e); |
| 126 | stale = false; |
| 127 | }); |
| 128 | closePrivateDialog(); |
| 129 | }); |
| 130 | }); |
| 131 | privateDialog = null; |
| 132 | if (!mounted || !current(request)) return; |
| 133 | setState(() => editing = false); |
| 134 | if (result == null) { |
| 135 | if (snapshot != null) await load(); |
| 136 | return; |
| 137 | } |
| 138 | ScaffoldMessenger.of(context).showSnackBar(SnackBar( |
| 139 | content: Text(result['queued'] == true |
| 140 | ? 'هدف روی دستگاه نگهداری شد؛ تأیید سرور هنوز دریافت نشده است.' |
| 141 | : 'هدف در سرور ثبت و تأیید شد.'))); |
| 142 | await load(); |
| 143 | } |
| 144 | |
| 145 | Future<bool> confirm(String title, String description, String action) async => |
| 146 | await showDialog<bool>( |
| 147 | context: context, |
| 148 | builder: (dialog) => Directionality( |
| 149 | textDirection: TextDirection.rtl, |
| 150 | child: AlertDialog( |
| 151 | title: Text(title), |
| 152 | content: Text(description), |
| 153 | actions: [ |
| 154 | TextButton( |
| 155 | onPressed: () => Navigator.pop(dialog, false), |
| 156 | child: const Text('انصراف')), |
| 157 | FilledButton( |
| 158 | onPressed: () => Navigator.pop(dialog, true), |
| 159 | child: Text(action)) |
| 160 | ]))) == |
| 161 | true; |
| 162 | |
| 163 | Future<void> change(Map<String, dynamic> goal, {bool archive = false}) async { |
| 164 | if (busy || editing || !active) return; |
| 165 | if (archive && |
| 166 | !await confirm( |
| 167 | 'بایگانی هدف؟', |
| 168 | 'هدف از فهرست جاری کنار میرود؛ سابقه پیشرفت مرتبط نگهداری میشود.', |
| 169 | 'بایگانی')) { |
| 170 | return; |
| 171 | } |
| 172 | if (!mounted || !active || busy) return; |
| 173 | final request = ++epoch; |
| 174 | setState(() => busy = true); |
| 175 | Object? failed; |
| 176 | try { |
| 177 | final result = archive |
| 178 | ? await sync.archive(goal['id'] as String, goal['version'] as int) |
| 179 | : await sync.update(goal['id'] as String, goal['version'] as int, { |
| 180 | 'status': goal['status'] == 'completed' ? 'active' : 'completed' |
| 181 | }); |
| 182 | if (mounted && current(request)) { |
| 183 | ScaffoldMessenger.of(context).showSnackBar(SnackBar( |
| 184 | content: Text(result['queued'] == true |
| 185 | ? 'تغییر ذخیره شد؛ هنوز به تأیید سرور نرسیده است.' |
| 186 | : 'تغییر در سرور تأیید شد.'))); |
| 187 | } |
| 188 | } catch (e) { |
| 189 | failed = e; |
| 190 | } |
| 191 | if (!current(request)) return; |
| 192 | setState(() => busy = false); |
| 193 | if (failed == null || !_goalAuthFailure(failed)) await load(); |
| 194 | if (failed != null && mounted && active) { |
| 195 | setState(() { |
| 196 | if (_goalAuthFailure(failed!)) snapshot = null; |
| 197 | stale = snapshot != null; |
| 198 | error = _goalError(failed); |
| 199 | }); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | Future<void> useServer(Map<String, dynamic> goal) async { |
| 204 | if (busy || |
| 205 | !active || |
| 206 | !await confirm( |
| 207 | 'استفاده از نسخه سرور؟', |
| 208 | 'تغییر محلی در سابقه بازیابی نگهداری میشود و نسخه فعلی سرور جای آن را میگیرد.', |
| 209 | 'استفاده از سرور')) { |
| 210 | return; |
| 211 | } |
| 212 | if (!mounted || !active || busy) return; |
| 213 | final request = ++epoch; |
| 214 | setState(() => busy = true); |
| 215 | try { |
| 216 | await sync.useServer(goal['id'] as String); |
| 217 | } catch (e) { |
| 218 | if (current(request)) { |
| 219 | setState(() { |
| 220 | if (_goalAuthFailure(e)) snapshot = null; |
| 221 | error = _goalError(e); |
| 222 | stale = snapshot != null; |
| 223 | }); |
| 224 | } |
| 225 | return; |
| 226 | } finally { |
| 227 | if (current(request)) setState(() => busy = false); |
| 228 | } |
| 229 | if (current(request)) await load(); |
| 230 | } |
| 231 | |
| 232 | @override |
| 233 | Widget build(BuildContext context) { |
| 234 | final goals = (snapshot?['items'] as List? ?? []).whereType<Map>().toList(); |
| 235 | final pending = snapshot?['pendingCount'] ?? |
| 236 | goals.where((g) => g['pending_sync'] == true).length; |
| 237 | final unlisted = |
| 238 | (snapshot?['unlistedPending'] as List? ?? []).whereType<Map>(); |
| 239 | return Directionality( |
| 240 | textDirection: TextDirection.rtl, |
| 241 | child: Scaffold( |
| 242 | appBar: AppBar(title: const Text('هدفهای یادگیری')), |
| 243 | body: ListView(padding: const EdgeInsets.all(16), children: [ |
| 244 | const Text( |
| 245 | 'هدفها و نتیجه مورد نظر خصوصیاند؛ عضویت خانواده اجازه دیدن آنها را ایجاد نمیکند.'), |
| 246 | const Text('تکمیل هدف، گزارش خودت است و اثبات یادگیری نیست.'), |
| 247 | if (busy) const LinearProgressIndicator(), |
| 248 | if (error != null) Text(error!), |
| 249 | if (stale) |
| 250 | const Text('تازهسازی ناموفق؛ این داده ممکن است قدیمی باشد.'), |
| 251 | if (snapshot?['offline'] == true) |
| 252 | const Text('آفلاین؛ داده ذخیرهشده ممکن است قدیمی باشد.'), |
| 253 | if (snapshot?['fetchedAt'] != null) |
| 254 | Text('آخرین دریافت سرور: ${snapshot!['fetchedAt']}'), |
| 255 | if (snapshot != null) Text('تغییر ارسالنشده: $pending'), |
| 256 | FilledButton.icon( |
| 257 | onPressed: busy || editing || !active ? null : () => edit(), |
| 258 | icon: const Icon(Icons.add), |
| 259 | label: const Text('هدف جدید')), |
| 260 | OutlinedButton( |
| 261 | onPressed: busy || editing || !active |
| 262 | ? null |
| 263 | : () => load(retry: true), |
| 264 | child: const Text('همگامسازی و تازهسازی')), |
| 265 | if (!busy && snapshot != null && goals.isEmpty) |
| 266 | const Text('هنوز هدف جاری ثبت نشده است.'), |
| 267 | ...unlisted.map((row) => ListTile( |
| 268 | title: const Text('تغییر معلق برای هدف خارج از فهرست جاری'), |
| 269 | subtitle: const Text( |
| 270 | 'درخواست محلی حفظ شده است؛ بازیابی نسخه سرور به انتخاب شما نیاز دارد.'), |
| 271 | trailing: TextButton( |
| 272 | onPressed: busy |
| 273 | ? null |
| 274 | : () => useServer(Map<String, dynamic>.from(row)), |
| 275 | child: const Text('بررسی نسخه سرور')))), |
| 276 | ...goals.map((raw) { |
| 277 | final goal = Map<String, dynamic>.from(raw); |
| 278 | final blocked = |
| 279 | busy || !active || stale || goal['pending_sync'] == true; |
| 280 | return Card( |
| 281 | child: Padding( |
| 282 | padding: const EdgeInsets.all(12), |
| 283 | child: Column( |
| 284 | crossAxisAlignment: CrossAxisAlignment.start, |
| 285 | children: [ |
| 286 | Text(goal['title']?.toString() ?? '', |
| 287 | style: |
| 288 | Theme.of(context).textTheme.titleMedium), |
| 289 | if (goal['target'] != null) |
| 290 | Text(goal['target'].toString()), |
| 291 | Text(goal['status'] == 'completed' |
| 292 | ? 'تکمیل طبق گزارش من' |
| 293 | : 'هدف فعال'), |
| 294 | if (goal['pending_sync'] == true) |
| 295 | Text(goal['pending_archive'] == true |
| 296 | ? 'بایگانی در انتظار تأیید سرور' |
| 297 | : 'تغییر در انتظار تأیید سرور'), |
| 298 | if (goal['updated_at'] != null && |
| 299 | goal['pending_sync'] != true) |
| 300 | Text('آخرین ثبت سرور: ${goal['updated_at']}'), |
| 301 | if (goal['queueStatus'] == 'conflict') |
| 302 | TextButton( |
| 303 | onPressed: |
| 304 | busy ? null : () => useServer(goal), |
| 305 | child: const Text('حل تعارض با نسخه سرور')), |
| 306 | Wrap(spacing: 8, children: [ |
| 307 | TextButton( |
| 308 | onPressed: blocked |
| 309 | ? null |
| 310 | : () => Navigator.of(context).push( |
| 311 | MaterialPageRoute( |
| 312 | builder: (_) => |
| 313 | LearningGoalHistoryPage( |
| 314 | api: widget.api, |
| 315 | goalId: goal['id'] |
| 316 | as String))), |
| 317 | child: |
| 318 | const Text('بازتاب و سابقه یادگیری')), |
| 319 | TextButton( |
| 320 | onPressed: |
| 321 | blocked ? null : () => edit(goal), |
| 322 | child: const Text('ویرایش')), |
| 323 | TextButton( |
| 324 | onPressed: |
| 325 | blocked ? null : () => change(goal), |
| 326 | child: Text(goal['status'] == 'completed' |
| 327 | ? 'فعالکردن دوباره' |
| 328 | : 'تکمیل طبق گزارش من')), |
| 329 | TextButton( |
| 330 | onPressed: blocked |
| 331 | ? null |
| 332 | : () => change(goal, archive: true), |
| 333 | child: const Text('بایگانی')), |
| 334 | ]) |
| 335 | ]))); |
| 336 | }) |
| 337 | ]))); |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | /// The dialog owns its controllers until its route has actually unmounted. |
| 342 | /// Disposing them when showDialog's result resolves is too early during pop. |
| 343 | class _LearningGoalEditor extends StatefulWidget { |
| 344 | const _LearningGoalEditor( |
| 345 | {required this.sync, required this.goal, required this.onAuthFailure}); |
| 346 | final LearningGoalSync sync; |
| 347 | final Map<String, dynamic>? goal; |
| 348 | final void Function(Object error) onAuthFailure; |
| 349 | @override |
| 350 | State<_LearningGoalEditor> createState() => _LearningGoalEditorState(); |
| 351 | } |
| 352 | |
| 353 | class _LearningGoalEditorState extends State<_LearningGoalEditor> { |
| 354 | late final TextEditingController title, target; |
| 355 | bool saving = false; |
| 356 | String? failure; |
| 357 | @override |
| 358 | void initState() { |
| 359 | super.initState(); |
| 360 | title = |
| 361 | TextEditingController(text: widget.goal?['title']?.toString() ?? ''); |
| 362 | target = |
| 363 | TextEditingController(text: widget.goal?['target']?.toString() ?? ''); |
| 364 | } |
| 365 | |
| 366 | @override |
| 367 | void dispose() { |
| 368 | title.dispose(); |
| 369 | target.dispose(); |
| 370 | super.dispose(); |
| 371 | } |
| 372 | |
| 373 | Future<void> save() async { |
| 374 | if (saving) return; |
| 375 | if (title.text.trim().isEmpty) { |
| 376 | setState(() => failure = 'عنوان هدف را بنویس.'); |
| 377 | return; |
| 378 | } |
| 379 | setState(() { |
| 380 | saving = true; |
| 381 | failure = null; |
| 382 | }); |
| 383 | try { |
| 384 | final goal = widget.goal; |
| 385 | final result = goal == null |
| 386 | ? await widget.sync.create(title: title.text, target: target.text) |
| 387 | : await widget.sync.update( |
| 388 | goal['id'] as String, |
| 389 | goal['version'] as int, |
| 390 | {'title': title.text, 'target': target.text}); |
| 391 | if (mounted) Navigator.pop(context, result); |
| 392 | } catch (e) { |
| 393 | if (!mounted) return; |
| 394 | if (_goalAuthFailure(e)) { |
| 395 | widget.onAuthFailure(e); |
| 396 | return; |
| 397 | } |
| 398 | setState(() { |
| 399 | failure = _goalError(e); |
| 400 | saving = false; |
| 401 | }); |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | @override |
| 406 | Widget build(BuildContext context) => PopScope( |
| 407 | canPop: !saving, |
| 408 | child: Directionality( |
| 409 | textDirection: TextDirection.rtl, |
| 410 | child: AlertDialog( |
| 411 | title: Text(widget.goal == null ? 'هدف جدید' : 'ویرایش هدف'), |
| 412 | content: SingleChildScrollView( |
| 413 | child: Column(mainAxisSize: MainAxisSize.min, children: [ |
| 414 | TextField( |
| 415 | controller: title, |
| 416 | maxLength: 240, |
| 417 | enabled: !saving, |
| 418 | decoration: const InputDecoration(labelText: 'عنوان هدف')), |
| 419 | TextField( |
| 420 | controller: target, |
| 421 | maxLength: 1000, |
| 422 | maxLines: 3, |
| 423 | enabled: !saving, |
| 424 | decoration: const InputDecoration( |
| 425 | labelText: 'نتیجه مورد نظر (اختیاری)')), |
| 426 | if (failure != null) Text(failure!) |
| 427 | ])), |
| 428 | actions: [ |
| 429 | TextButton( |
| 430 | onPressed: saving ? null : () => Navigator.pop(context), |
| 431 | child: const Text('انصراف')), |
| 432 | FilledButton( |
| 433 | onPressed: saving ? null : save, |
| 434 | child: Text(saving ? 'در حال ذخیره…' : 'ذخیره')) |
| 435 | ]))); |
| 436 | } |
| 437 | |
| 438 | /// Existing owner-only check-in API. These legacy writes are online-only and |
| 439 | /// have no durable idempotency receipt; an unknown result is explicitly reviewed. |
| 440 | String _reflectionError(Object error) { |
| 441 | if (isOfflineFailure(error)) { |
| 442 | return 'اتصال برقرار نیست؛ دریافت بازتابها به سرور نیاز دارد.'; |
| 443 | } |
| 444 | if (_goalAuthFailure(error)) { |
| 445 | return 'نشست یا دسترسی معتبر نیست؛ بازتابهای خصوصی قبلی از صفحه پاک شدند.'; |
| 446 | } |
| 447 | if (error is ApiException && error.statusCode == 409) { |
| 448 | return 'وضعیت بازتاب در سرور تغییر کرده است؛ سابقه را تازه کن.'; |
| 449 | } |
| 450 | return 'عملیات با پاسخ معتبر سرور تأیید نشد؛ سابقه را تازه کن.'; |
| 451 | } |
| 452 | |
| 453 | class LearningGoalHistoryPage extends StatefulWidget { |
| 454 | const LearningGoalHistoryPage( |
| 455 | {super.key, required this.api, required this.goalId}); |
| 456 | final HttpIdentityApi api; |
| 457 | final String goalId; |
| 458 | @override |
| 459 | State<LearningGoalHistoryPage> createState() => |
| 460 | _LearningGoalHistoryPageState(); |
| 461 | } |
| 462 | |
| 463 | class _LearningGoalHistoryPageState extends State<LearningGoalHistoryPage> |
| 464 | with WidgetsBindingObserver { |
| 465 | late final String scope; |
| 466 | List<Map<String, dynamic>> rows = []; |
| 467 | String? error; |
| 468 | String? notice; |
| 469 | DateTime? received; |
| 470 | bool loading = false, editing = false, active = true; |
| 471 | bool archivedGoal = true, uncertain = false; |
| 472 | int epoch = 0; |
| 473 | BuildContext? editorContext; |
| 474 | static final uuid = RegExp(r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$', |
| 475 | caseSensitive: false); |
| 476 | bool current(int request) => mounted && active && epoch == request; |
| 477 | @override |
| 478 | void initState() { |
| 479 | super.initState(); |
| 480 | scope = widget.api.cacheNamespace ?? ''; |
| 481 | WidgetsBinding.instance.addObserver(this); |
| 482 | load(); |
| 483 | } |
| 484 | |
| 485 | @override |
| 486 | void dispose() { |
| 487 | ++epoch; |
| 488 | WidgetsBinding.instance.removeObserver(this); |
| 489 | super.dispose(); |
| 490 | } |
| 491 | |
| 492 | void closeEditor() { |
| 493 | final dialog = editorContext; |
| 494 | editorContext = null; |
| 495 | if (dialog?.mounted != true) return; |
| 496 | final route = ModalRoute.of(dialog!); |
| 497 | if (route != null && route.isActive) { |
| 498 | Navigator.of(dialog).removeRoute(route); |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | @override |
| 503 | void didChangeAppLifecycleState(AppLifecycleState state) { |
| 504 | active = state == AppLifecycleState.resumed; |
| 505 | ++epoch; |
| 506 | if (!active) closeEditor(); |
| 507 | if (mounted) { |
| 508 | setState(() { |
| 509 | rows = []; |
| 510 | received = null; |
| 511 | loading = false; |
| 512 | editing = false; |
| 513 | }); |
| 514 | } |
| 515 | if (active) load(); |
| 516 | } |
| 517 | |
| 518 | void checkScope() { |
| 519 | if (scope.isEmpty || scope != widget.api.cacheNamespace) { |
| 520 | throw const ApiException(401, 'cache_scope_closed'); |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | Future<Map<String, dynamic>> request(String method, String path, |
| 525 | {Map<String, dynamic>? body}) async { |
| 526 | checkScope(); |
| 527 | final value = await widget.api.requestJson(method, path, body: body); |
| 528 | checkScope(); |
| 529 | return value; |
| 530 | } |
| 531 | |
| 532 | bool timestamp(dynamic value) => |
| 533 | value is String && |
| 534 | RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) && |
| 535 | DateTime.tryParse(value) != null; |
| 536 | Map<String, dynamic> validateRow(Map value) { |
| 537 | if (value['id'] is! String || |
| 538 | !uuid.hasMatch(value['id'] as String) || |
| 539 | value['owner_user_id'] != widget.api.currentUserId || |
| 540 | (value['learning_goal_id'] != null && |
| 541 | (value['learning_goal_id'] is! String || |
| 542 | !uuid.hasMatch(value['learning_goal_id'] as String))) || |
| 543 | ![1, 2, 3, 4, 5].contains(value['confidence']) || |
| 544 | ![1, 2, 3, 4, 5].contains(value['difficulty']) || |
| 545 | (value['note'] != null && |
| 546 | (value['note'] is! String || |
| 547 | (value['note'] as String).length > 2000)) || |
| 548 | value['source'] != 'self_reported' || |
| 549 | value['isEvidenceOfStudy'] != false || |
| 550 | !timestamp(value['occurred_at']) || |
| 551 | !timestamp(value['created_at']) || |
| 552 | !timestamp(value['updated_at']) || |
| 553 | (value['archived_at'] != null && !timestamp(value['archived_at']))) { |
| 554 | throw const ApiException(502, 'invalid_learning_checkin'); |
| 555 | } |
| 556 | return { |
| 557 | 'id': value['id'], |
| 558 | 'learning_goal_id': value['learning_goal_id'], |
| 559 | 'confidence': value['confidence'], |
| 560 | 'difficulty': value['difficulty'], |
| 561 | 'note': value['note'], |
| 562 | 'occurred_at': value['occurred_at'], |
| 563 | 'updated_at': value['updated_at'], |
| 564 | 'archived_at': value['archived_at'], |
| 565 | }; |
| 566 | } |
| 567 | |
| 568 | Future<void> load() async { |
| 569 | if (!active || editing) return; |
| 570 | final requestId = ++epoch; |
| 571 | setState(() { |
| 572 | rows = []; |
| 573 | received = null; |
| 574 | error = null; |
| 575 | loading = true; |
| 576 | archivedGoal = true; |
| 577 | }); |
| 578 | try { |
| 579 | if (!uuid.hasMatch(widget.goalId)) { |
| 580 | throw const ApiException(400, 'invalid_goal_input'); |
| 581 | } |
| 582 | final goal = await request('GET', '/v1/learning/goals/${widget.goalId}'); |
| 583 | if (goal['id'] != widget.goalId || |
| 584 | goal['owner_user_id'] != widget.api.currentUserId || |
| 585 | !['active', 'completed', 'archived'].contains(goal['status'])) { |
| 586 | throw const ApiException(502, 'invalid_learning_goal'); |
| 587 | } |
| 588 | final result = await request('GET', '/v1/learning/checkins'); |
| 589 | if (result['items'] is! List) { |
| 590 | throw const ApiException(502, 'invalid_learning_checkins'); |
| 591 | } |
| 592 | final values = <Map<String, dynamic>>[]; |
| 593 | final ids = <String>{}; |
| 594 | for (final raw in result['items'] as List) { |
| 595 | if (raw is! Map) { |
| 596 | throw const ApiException(502, 'invalid_learning_checkins'); |
| 597 | } |
| 598 | final row = validateRow(Map<String, dynamic>.from(raw)); |
| 599 | if (!ids.add(row['id'] as String) || row['archived_at'] != null) { |
| 600 | throw const ApiException(502, 'invalid_learning_checkins'); |
| 601 | } |
| 602 | if (row['learning_goal_id'] == widget.goalId) values.add(row); |
| 603 | } |
| 604 | if (!current(requestId)) return; |
| 605 | setState(() { |
| 606 | rows = values; |
| 607 | received = DateTime.now(); |
| 608 | archivedGoal = goal['status'] == 'archived'; |
| 609 | }); |
| 610 | } catch (e) { |
| 611 | if (current(requestId)) setState(() => error = _reflectionError(e)); |
| 612 | } finally { |
| 613 | if (current(requestId)) setState(() => loading = false); |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | Future<void> edit([Map<String, dynamic>? row]) async { |
| 618 | if (!active || |
| 619 | loading || |
| 620 | editing || |
| 621 | uncertain || |
| 622 | (row == null && archivedGoal)) { |
| 623 | return; |
| 624 | } |
| 625 | final requestId = ++epoch; |
| 626 | setState(() => editing = true); |
| 627 | final result = await showDialog<Map<String, dynamic>>( |
| 628 | context: context, |
| 629 | barrierDismissible: false, |
| 630 | builder: (dialog) { |
| 631 | editorContext = dialog; |
| 632 | return _LearningCheckinEditor( |
| 633 | row: row, |
| 634 | save: (body) async { |
| 635 | final value = await request(row == null ? 'POST' : 'PATCH', |
| 636 | '/v1/learning/checkins${row == null ? '' : '/${row['id']}'}', |
| 637 | body: { |
| 638 | if (row == null) 'learningGoalId': widget.goalId, |
| 639 | ...body, |
| 640 | }); |
| 641 | final confirmed = validateRow(value); |
| 642 | if (confirmed['learning_goal_id'] != widget.goalId || |
| 643 | confirmed['archived_at'] != null || |
| 644 | (row != null && confirmed['id'] != row['id']) || |
| 645 | ['confidence', 'difficulty', 'note'] |
| 646 | .any((key) => confirmed[key] != body[key])) { |
| 647 | throw const ApiException(502, 'invalid_learning_checkin'); |
| 648 | } |
| 649 | }, |
| 650 | onAuthFailure: (e) { |
| 651 | if (!current(requestId)) return; |
| 652 | setState(() { |
| 653 | rows = []; |
| 654 | received = null; |
| 655 | error = _reflectionError(e); |
| 656 | }); |
| 657 | closeEditor(); |
| 658 | }); |
| 659 | }); |
| 660 | editorContext = null; |
| 661 | if (!mounted || !current(requestId)) return; |
| 662 | setState(() => editing = false); |
| 663 | if (result == null) return; |
| 664 | if (result['uncertain'] == true) { |
| 665 | setState(() { |
| 666 | uncertain = true; |
| 667 | notice = |
| 668 | 'نتیجه ثبت قبلی ممکن است نامشخص باشد؛ سابقه تازه را بررسی کن. ثبت دوباره خودکار انجام نمیشود.'; |
| 669 | }); |
| 670 | } else { |
| 671 | setState(() => notice = |
| 672 | 'بازتاب در سرور ثبت شد؛ این گزارش شخصی است و اثبات یادگیری نیست.'); |
| 673 | } |
| 674 | await load(); |
| 675 | } |
| 676 | |
| 677 | Future<void> archive(Map<String, dynamic> row) async { |
| 678 | if (!active || loading || editing || uncertain) return; |
| 679 | final accepted = await showDialog<bool>( |
| 680 | context: context, |
| 681 | builder: (dialog) => AlertDialog( |
| 682 | title: const Text('بایگانی بازتاب؟'), |
| 683 | content: const Text( |
| 684 | 'این بازتاب از فهرست جاری کنار میرود؛ هدف و سایر سوابق حذف نمیشوند.'), |
| 685 | actions: [ |
| 686 | TextButton( |
| 687 | onPressed: () => Navigator.pop(dialog, false), |
| 688 | child: const Text('انصراف')), |
| 689 | FilledButton( |
| 690 | onPressed: () => Navigator.pop(dialog, true), |
| 691 | child: const Text('تأیید بایگانی')) |
| 692 | ])); |
| 693 | if (!mounted || !active || accepted != true) return; |
| 694 | setState(() { |
| 695 | loading = true; |
| 696 | rows = []; |
| 697 | received = null; |
| 698 | }); |
| 699 | Object? failure; |
| 700 | try { |
| 701 | await request('DELETE', '/v1/learning/checkins/${row['id']}'); |
| 702 | } catch (e) { |
| 703 | failure = e; |
| 704 | } |
| 705 | if (!mounted || !active) return; |
| 706 | setState(() => loading = false); |
| 707 | await load(); |
| 708 | if (!mounted || !active) return; |
| 709 | if (failure != null) { |
| 710 | setState(() { |
| 711 | notice = |
| 712 | 'نتیجه بایگانی ممکن است نامشخص باشد؛ سابقه تازه را بررسی کن. تلاش خودکار انجام نمیشود.'; |
| 713 | }); |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | @override |
| 718 | Widget build(BuildContext context) => Directionality( |
| 719 | textDirection: TextDirection.rtl, |
| 720 | child: Scaffold( |
| 721 | appBar: AppBar(title: const Text('بازتاب یادگیری')), |
| 722 | body: ListView(padding: const EdgeInsets.all(16), children: [ |
| 723 | const Text( |
| 724 | 'این سابقه و یادداشتها خصوصیاند و فقط با حساب صاحب آن دریافت میشوند.'), |
| 725 | const Text( |
| 726 | 'اعتماد و سختی، گزارش شخصی شما هستند؛ اثبات یادگیری یا زمان مطالعه نیستند.'), |
| 727 | const Text( |
| 728 | 'ثبت و ویرایش این بازتابها به اتصال سرور نیاز دارد؛ این صفحه ذخیره آفلاین ندارد.'), |
| 729 | if (loading) const LinearProgressIndicator(), |
| 730 | if (error != null) Text(error!), |
| 731 | if (notice != null) Text(notice!), |
| 732 | if (received != null) |
| 733 | Text( |
| 734 | 'آخرین دریافت سابقه: ${received!.toUtc().toIso8601String()}'), |
| 735 | if (uncertain && received != null) |
| 736 | OutlinedButton( |
| 737 | onPressed: () => setState(() { |
| 738 | uncertain = false; |
| 739 | notice = null; |
| 740 | }), |
| 741 | child: const Text('سابقه را بررسی کردم')), |
| 742 | FilledButton( |
| 743 | onPressed: |
| 744 | loading || editing || !active || archivedGoal || uncertain |
| 745 | ? null |
| 746 | : () => edit(), |
| 747 | child: const Text('ثبت بازتاب')), |
| 748 | OutlinedButton( |
| 749 | onPressed: editing || !active ? null : load, |
| 750 | child: const Text('تازهسازی سابقه')), |
| 751 | if (received != null && rows.isEmpty) |
| 752 | const Text('هنوز بازتاب جاری برای این هدف ثبت نشده است.'), |
| 753 | ...rows.map((row) => Card( |
| 754 | child: Padding( |
| 755 | padding: const EdgeInsets.all(12), |
| 756 | child: Column( |
| 757 | crossAxisAlignment: CrossAxisAlignment.start, |
| 758 | children: [ |
| 759 | Text( |
| 760 | 'اعتماد به یادگیری: ${row['confidence']} از ۵ · سختی: ${row['difficulty']} از ۵'), |
| 761 | if (row['note'] != null) Text(row['note'] as String), |
| 762 | Text('زمان ثبت: ${row['occurred_at']}'), |
| 763 | Wrap(spacing: 8, children: [ |
| 764 | TextButton( |
| 765 | onPressed: loading || editing || uncertain |
| 766 | ? null |
| 767 | : () => edit(row), |
| 768 | child: const Text('ویرایش بازتاب')), |
| 769 | TextButton( |
| 770 | onPressed: loading || editing || uncertain |
| 771 | ? null |
| 772 | : () => archive(row), |
| 773 | child: const Text('بایگانی بازتاب')) |
| 774 | ]) |
| 775 | ])))) |
| 776 | ]))); |
| 777 | } |
| 778 | |
| 779 | class _LearningCheckinEditor extends StatefulWidget { |
| 780 | const _LearningCheckinEditor( |
| 781 | {required this.row, required this.save, required this.onAuthFailure}); |
| 782 | final Map<String, dynamic>? row; |
| 783 | final Future<void> Function(Map<String, dynamic> body) save; |
| 784 | final void Function(Object error) onAuthFailure; |
| 785 | @override |
| 786 | State<_LearningCheckinEditor> createState() => _LearningCheckinEditorState(); |
| 787 | } |
| 788 | |
| 789 | class _LearningCheckinEditorState extends State<_LearningCheckinEditor> { |
| 790 | late final TextEditingController note; |
| 791 | late int confidence, difficulty; |
| 792 | bool saving = false; |
| 793 | String? error; |
| 794 | @override |
| 795 | void initState() { |
| 796 | super.initState(); |
| 797 | note = TextEditingController(text: widget.row?['note'] as String? ?? ''); |
| 798 | confidence = widget.row?['confidence'] as int? ?? 3; |
| 799 | difficulty = widget.row?['difficulty'] as int? ?? 3; |
| 800 | } |
| 801 | |
| 802 | @override |
| 803 | void dispose() { |
| 804 | note.dispose(); |
| 805 | super.dispose(); |
| 806 | } |
| 807 | |
| 808 | Future<void> save() async { |
| 809 | if (saving) return; |
| 810 | setState(() { |
| 811 | saving = true; |
| 812 | error = null; |
| 813 | }); |
| 814 | try { |
| 815 | await widget.save({ |
| 816 | 'confidence': confidence, |
| 817 | 'difficulty': difficulty, |
| 818 | 'note': note.text.trim().isEmpty ? null : note.text.trim() |
| 819 | }); |
| 820 | if (mounted) Navigator.pop(context, {'uncertain': false}); |
| 821 | } catch (e) { |
| 822 | if (!mounted) return; |
| 823 | if (_goalAuthFailure(e)) { |
| 824 | widget.onAuthFailure(e); |
| 825 | return; |
| 826 | } |
| 827 | if (isOfflineFailure(e) || (e is ApiException && e.statusCode >= 500)) { |
| 828 | Navigator.pop(context, {'uncertain': true}); |
| 829 | return; |
| 830 | } |
| 831 | setState(() { |
| 832 | saving = false; |
| 833 | error = _reflectionError(e); |
| 834 | }); |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | Widget scale(String label, int value, void Function(int value) change) => |
| 839 | DropdownButtonFormField<int>( |
| 840 | initialValue: value, |
| 841 | decoration: InputDecoration(labelText: label), |
| 842 | items: [ |
| 843 | for (var i = 1; i <= 5; i++) |
| 844 | DropdownMenuItem(value: i, child: Text('$i از ۵')) |
| 845 | ], |
| 846 | onChanged: saving ? null : (value) => setState(() => change(value!))); |
| 847 | @override |
| 848 | Widget build(BuildContext context) => PopScope( |
| 849 | canPop: !saving, |
| 850 | child: Directionality( |
| 851 | textDirection: TextDirection.rtl, |
| 852 | child: AlertDialog( |
| 853 | title: Text(widget.row == null ? 'بازتاب جدید' : 'ویرایش بازتاب'), |
| 854 | content: SingleChildScrollView( |
| 855 | child: Column(mainAxisSize: MainAxisSize.min, children: [ |
| 856 | scale('اعتماد به یادگیری', confidence, (v) => confidence = v), |
| 857 | scale('سختی یادگیری', difficulty, (v) => difficulty = v), |
| 858 | TextField( |
| 859 | controller: note, |
| 860 | maxLength: 2000, |
| 861 | maxLines: 3, |
| 862 | enabled: !saving, |
| 863 | decoration: const InputDecoration( |
| 864 | labelText: 'یادداشت خصوصی (اختیاری)')), |
| 865 | if (error != null) Text(error!) |
| 866 | ])), |
| 867 | actions: [ |
| 868 | TextButton( |
| 869 | onPressed: saving ? null : () => Navigator.pop(context), |
| 870 | child: const Text('انصراف')), |
| 871 | FilledButton( |
| 872 | onPressed: saving ? null : save, |
| 873 | child: Text(saving ? 'در حال ثبت…' : 'ذخیره')) |
| 874 | ]))); |
| 875 | } |