LifeMate — Personal, Family & Learning Companion
test/personal-recovery-acceptance
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 'dart:convert'; |
| 3 | |
| 4 | import 'package:flutter/material.dart'; |
| 5 | |
| 6 | import 'api.dart'; |
| 7 | import 'offline_store.dart'; |
| 8 | import 'plan_sync.dart' show newMutationId; |
| 9 | |
| 10 | const _schoolTypes = ['contexts', 'years', 'terms']; |
| 11 | final _schoolUuid = RegExp(r'^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$', |
| 12 | caseSensitive: false); |
| 13 | String _latinDigits(String value) { |
| 14 | const all = '۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩'; |
| 15 | return value.trim().split('').map((c) { |
| 16 | final n = all.indexOf(c); |
| 17 | return n < 0 ? c : '${n % 10}'; |
| 18 | }).join(); |
| 19 | } |
| 20 | |
| 21 | String _faDigits(String value) => value |
| 22 | .split('') |
| 23 | .map((c) => int.tryParse(c) == null ? c : '۰۱۲۳۴۵۶۷۸۹'[int.parse(c)]) |
| 24 | .join(); |
| 25 | String _dateText(DateTime value) => |
| 26 | '${value.year.toString().padLeft(4, '0')}-${value.month.toString().padLeft(2, '0')}-${value.day.toString().padLeft(2, '0')}'; |
| 27 | bool _schoolDate(dynamic value) => |
| 28 | value is String && |
| 29 | RegExp(r'^\d{4}-\d{2}-\d{2}$').hasMatch(value) && |
| 30 | !value.startsWith('0000-') && |
| 31 | DateTime.tryParse(value) != null && |
| 32 | _dateText(DateTime.parse(value)) == value; |
| 33 | bool _schoolTime(dynamic value) => |
| 34 | value is String && |
| 35 | RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) && |
| 36 | DateTime.tryParse(value) != null; |
| 37 | |
| 38 | /// The existing account/endpoint queue stores intent before delivery. Setup |
| 39 | /// progresses only after the preceding parent has a canonical server ACK. |
| 40 | class SchoolLifecycleSync { |
| 41 | SchoolLifecycleSync(this.api, {OfflineStore? store}) |
| 42 | : store = store ?? OfflineStore.forApi(api); |
| 43 | final HttpIdentityApi api; |
| 44 | final OfflineStore store; |
| 45 | static final _tails = <String, Future<void>>{}; |
| 46 | void _scope() { |
| 47 | if (api.cacheNamespace != store.scope) { |
| 48 | throw const ApiException(401, 'cache_scope_closed'); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | Future<T> _serial<T>(Future<T> Function() run) async { |
| 53 | final before = _tails[store.scope], release = Completer<void>(); |
| 54 | _tails[store.scope] = release.future; |
| 55 | if (before != null) await before; |
| 56 | try { |
| 57 | _scope(); |
| 58 | await store.readQueue(); |
| 59 | final value = await run(); |
| 60 | _scope(); |
| 61 | return value; |
| 62 | } finally { |
| 63 | if (identical(_tails[store.scope], release.future)) { |
| 64 | _tails.remove(store.scope); |
| 65 | } |
| 66 | release.complete(); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | Map<String, dynamic> _entity(String type, dynamic raw) { |
| 71 | if (raw is! Map || |
| 72 | raw['id'] is! String || |
| 73 | !_schoolUuid.hasMatch(raw['id']) || |
| 74 | raw['title'] is! String || |
| 75 | (raw['title'] as String).trim().isEmpty || |
| 76 | raw['version'] is! int || |
| 77 | raw['version'] < 1 || |
| 78 | raw['active'] is! bool || |
| 79 | !_schoolTime(raw['created_at']) || |
| 80 | !_schoolTime(raw['updated_at'])) { |
| 81 | throw const ApiException(502, 'invalid_school_entity'); |
| 82 | } |
| 83 | if (type == 'contexts' && |
| 84 | (raw['user_id'] != api.currentUserId || |
| 85 | !['student', 'work', 'personal'].contains(raw['kind']))) { |
| 86 | throw const ApiException(502, 'invalid_school_entity'); |
| 87 | } |
| 88 | if (type != 'contexts' && |
| 89 | (!_schoolDate(raw['starts_on']) || |
| 90 | !_schoolDate(raw['ends_on']) || |
| 91 | (raw['ends_on'] as String).compareTo(raw['starts_on'] as String) < |
| 92 | 0)) { |
| 93 | throw const ApiException(502, 'invalid_school_entity'); |
| 94 | } |
| 95 | final parent = type == 'years' |
| 96 | ? raw['life_context_id'] |
| 97 | : type == 'terms' |
| 98 | ? raw['academic_year_id'] |
| 99 | : null; |
| 100 | if (type != 'contexts' && |
| 101 | (parent is! String || |
| 102 | !_schoolUuid.hasMatch(parent) || |
| 103 | (type == 'years' && raw['student_user_id'] != api.currentUserId))) { |
| 104 | throw const ApiException(502, 'invalid_school_entity'); |
| 105 | } |
| 106 | return Map<String, dynamic>.from(raw); |
| 107 | } |
| 108 | |
| 109 | Future<List<Map<String, dynamic>>> pending() async { |
| 110 | _scope(); |
| 111 | final rows = await store.readQueue(); |
| 112 | _scope(); |
| 113 | return rows |
| 114 | .where((row) => _schoolTypes |
| 115 | .any((type) => row['entityType'] == 'school_lifecycle_$type')) |
| 116 | .toList(); |
| 117 | } |
| 118 | |
| 119 | Future<Map<String, dynamic>> read() => _serial(() async { |
| 120 | var offline = false; |
| 121 | final result = <String, dynamic>{}; |
| 122 | try { |
| 123 | final raw = await api.requestJson('GET', '/v1/school/lifecycle'); |
| 124 | _scope(); |
| 125 | if (!_schoolTime(raw['fetchedAt'])) { |
| 126 | throw const ApiException(502, 'invalid_school_snapshot'); |
| 127 | } |
| 128 | for (final type in _schoolTypes) { |
| 129 | if (raw[type] is! List || (raw[type] as List).length > 500) { |
| 130 | throw const ApiException(502, 'invalid_school_snapshot'); |
| 131 | } |
| 132 | final rows = |
| 133 | (raw[type] as List).map((row) => _entity(type, row)).toList(); |
| 134 | if (rows.map((row) => row['id']).toSet().length != rows.length) { |
| 135 | throw const ApiException(502, 'invalid_school_snapshot'); |
| 136 | } |
| 137 | result[type] = rows; |
| 138 | } |
| 139 | final contexts = { |
| 140 | for (final row in result['contexts'] as List) row['id'] |
| 141 | }; |
| 142 | final years = {for (final row in result['years'] as List) row['id']}; |
| 143 | if ((result['years'] as List) |
| 144 | .any((row) => !contexts.contains(row['life_context_id'])) || |
| 145 | (result['terms'] as List) |
| 146 | .any((row) => !years.contains(row['academic_year_id']))) { |
| 147 | throw const ApiException(502, 'invalid_school_snapshot'); |
| 148 | } |
| 149 | for (final type in _schoolTypes) { |
| 150 | await store.writeList('school_lifecycle_$type', |
| 151 | result[type] as List<Map<String, dynamic>>); |
| 152 | } |
| 153 | await store.writeList('school_lifecycle_received', [ |
| 154 | {'fetchedAt': raw['fetchedAt']} |
| 155 | ]); |
| 156 | } catch (error) { |
| 157 | _scope(); |
| 158 | if (!isOfflineFailure(error)) rethrow; |
| 159 | offline = true; |
| 160 | for (final type in _schoolTypes) { |
| 161 | result[type] = (await store.readList('school_lifecycle_$type')) |
| 162 | .map((row) => _entity(type, row)) |
| 163 | .toList(); |
| 164 | } |
| 165 | } |
| 166 | final received = await store.readList('school_lifecycle_received'); |
| 167 | return { |
| 168 | ...result, |
| 169 | 'offline': offline, |
| 170 | 'fetchedAt': received.firstOrNull?['fetchedAt'], |
| 171 | 'pending': await pending() |
| 172 | }; |
| 173 | }); |
| 174 | void _validate(String type, Map<String, dynamic> body) { |
| 175 | if (!_schoolTypes.contains(type) || |
| 176 | body['mutationId'] is! String || |
| 177 | !_schoolUuid.hasMatch(body['mutationId']) || |
| 178 | body['entityId'] is! String || |
| 179 | !_schoolUuid.hasMatch(body['entityId']) || |
| 180 | !['create', 'update', 'archive'].contains(body['operation']) || |
| 181 | body['expectedVersion'] is! int || |
| 182 | body['expectedVersion'] < 0 || |
| 183 | body['expectedVersion'] > 2147483646 || |
| 184 | (body['operation'] == 'create' |
| 185 | ? body['expectedVersion'] != 0 |
| 186 | : body['expectedVersion'] < 1) || |
| 187 | body['data'] is! Map) { |
| 188 | throw const ApiException(400, 'invalid_school_mutation'); |
| 189 | } |
| 190 | final data = body['data'] as Map, operation = body['operation']; |
| 191 | final keys = operation == 'archive' |
| 192 | ? <String>[] |
| 193 | : type == 'contexts' |
| 194 | ? ['title', 'kind'] |
| 195 | : [ |
| 196 | 'title', |
| 197 | 'startsOn', |
| 198 | 'endsOn', |
| 199 | if (operation == 'create') |
| 200 | type == 'years' ? 'lifeContextId' : 'academicYearId' |
| 201 | ]; |
| 202 | if (data.keys.any((key) => !keys.contains(key)) || |
| 203 | (operation == 'create' && keys.any((key) => !data.containsKey(key))) || |
| 204 | (operation == 'update' && data.isEmpty)) { |
| 205 | throw const ApiException(400, 'invalid_school_input'); |
| 206 | } |
| 207 | if ((data.containsKey('title') && |
| 208 | (data['title'] is! String || |
| 209 | (data['title'] as String).trim().isEmpty || |
| 210 | (data['title'] as String).length > 120)) || |
| 211 | (data.containsKey('kind') && |
| 212 | !['student', 'work', 'personal'].contains(data['kind']))) { |
| 213 | throw const ApiException(400, 'invalid_school_input'); |
| 214 | } |
| 215 | for (final key in ['startsOn', 'endsOn']) { |
| 216 | if (data.containsKey(key) && !_schoolDate(data[key])) { |
| 217 | throw const ApiException(400, 'invalid_school_date'); |
| 218 | } |
| 219 | } |
| 220 | if (data['startsOn'] is String && |
| 221 | data['endsOn'] is String && |
| 222 | (data['endsOn'] as String).compareTo(data['startsOn'] as String) < 0) { |
| 223 | throw const ApiException(400, 'invalid_school_date'); |
| 224 | } |
| 225 | for (final key in ['lifeContextId', 'academicYearId']) { |
| 226 | if (data.containsKey(key) && |
| 227 | (data[key] is! String || !_schoolUuid.hasMatch(data[key]))) { |
| 228 | throw const ApiException(400, 'invalid_school_input'); |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | Future<Map<String, dynamic>> mutate( |
| 234 | String type, String operation, Map<String, dynamic> data, |
| 235 | {String? entityId, int expectedVersion = 0}) { |
| 236 | final normalized = {...data}; |
| 237 | if (normalized['title'] is String) { |
| 238 | normalized['title'] = (normalized['title'] as String).trim(); |
| 239 | } |
| 240 | for (final key in ['startsOn', 'endsOn']) { |
| 241 | if (normalized[key] is String) { |
| 242 | normalized[key] = _latinDigits(normalized[key]); |
| 243 | } |
| 244 | } |
| 245 | final body = Map<String, dynamic>.from(jsonDecode(jsonEncode({ |
| 246 | 'mutationId': newMutationId(), |
| 247 | 'entityId': entityId ?? newMutationId(), |
| 248 | 'operation': operation, |
| 249 | 'expectedVersion': expectedVersion, |
| 250 | 'data': normalized |
| 251 | })) as Map); |
| 252 | _validate(type, body); |
| 253 | return _serial(() async { |
| 254 | if ((await pending()).any((row) => row['entityId'] == body['entityId'])) { |
| 255 | throw const ApiException(409, 'school_sync_pending'); |
| 256 | } |
| 257 | final record = { |
| 258 | 'id': body['mutationId'], |
| 259 | 'entityId': body['entityId'], |
| 260 | 'entityType': 'school_lifecycle_$type', |
| 261 | 'operation': operation, |
| 262 | 'expectedVersion': expectedVersion, |
| 263 | 'payload': body |
| 264 | }; |
| 265 | await store.enqueue(record); |
| 266 | try { |
| 267 | return {'queued': false, 'entity': await _send(type, record)}; |
| 268 | } catch (error) { |
| 269 | _scope(); |
| 270 | if (!isOfflineFailure(error)) rethrow; |
| 271 | return {'queued': true, 'entityId': body['entityId']}; |
| 272 | } |
| 273 | }); |
| 274 | } |
| 275 | |
| 276 | Future<Map<String, dynamic>> _send( |
| 277 | String type, Map<String, dynamic> record) async { |
| 278 | final body = Map<String, dynamic>.from(record['payload'] as Map); |
| 279 | _validate(type, body); |
| 280 | if (record['id'] != body['mutationId'] || |
| 281 | record['entityId'] != body['entityId'] || |
| 282 | record['entityType'] != 'school_lifecycle_$type' || |
| 283 | record['operation'] != body['operation'] || |
| 284 | record['expectedVersion'] != body['expectedVersion']) { |
| 285 | throw const ApiException(422, 'invalid_school_mutation'); |
| 286 | } |
| 287 | late Map<String, dynamic> raw; |
| 288 | try { |
| 289 | raw = await api.requestJson( |
| 290 | 'POST', '/v1/school/lifecycle/$type/mutations', |
| 291 | body: body); |
| 292 | _scope(); |
| 293 | } catch (error) { |
| 294 | _scope(); |
| 295 | if (error is ApiException && |
| 296 | [400, 404, 409, 422].contains(error.statusCode)) { |
| 297 | await store.markQueued(record['id'] as String, |
| 298 | error.statusCode == 409 ? 'conflict' : 'rejected', |
| 299 | error: error.code); |
| 300 | } |
| 301 | rethrow; |
| 302 | } |
| 303 | final row = _entity(type, raw['entity']), ack = raw['acknowledgement']; |
| 304 | if (row['id'] != body['entityId'] || |
| 305 | ack is! Map || |
| 306 | ack['mutationId'] != body['mutationId'] || |
| 307 | ack['entityId'] != body['entityId'] || |
| 308 | ack['entityType'] != type || |
| 309 | ack['operation'] != body['operation'] || |
| 310 | !['accepted', 'already_applied'].contains(ack['status']) || |
| 311 | ack['appliedVersion'] != body['expectedVersion'] + 1 || |
| 312 | row['version'] < ack['appliedVersion'] || |
| 313 | !_schoolTime(ack['acceptedAt'])) { |
| 314 | throw const ApiException(502, 'invalid_school_acknowledgement'); |
| 315 | } |
| 316 | if (row['version'] == ack['appliedVersion']) { |
| 317 | const columns = { |
| 318 | 'title': 'title', |
| 319 | 'kind': 'kind', |
| 320 | 'startsOn': 'starts_on', |
| 321 | 'endsOn': 'ends_on', |
| 322 | 'lifeContextId': 'life_context_id', |
| 323 | 'academicYearId': 'academic_year_id' |
| 324 | }; |
| 325 | if ((body['operation'] == 'archive' |
| 326 | ? row['active'] != false |
| 327 | : row['active'] != true) || |
| 328 | (body['data'] as Map) |
| 329 | .entries |
| 330 | .any((entry) => row[columns[entry.key]] != entry.value)) { |
| 331 | throw const ApiException(502, 'invalid_school_acknowledgement'); |
| 332 | } |
| 333 | } |
| 334 | await store.acknowledge(record['id'] as String, |
| 335 | item: row, |
| 336 | acceptedAt: ack['acceptedAt'] as String, |
| 337 | cacheKey: 'school_lifecycle_$type'); |
| 338 | _scope(); |
| 339 | return row; |
| 340 | } |
| 341 | |
| 342 | Future<void> flush() => _serial(() async { |
| 343 | for (final record in await pending()) { |
| 344 | if (['conflict', 'rejected'].contains(record['queueStatus'])) { |
| 345 | throw const ApiException(409, 'school_sync_conflict'); |
| 346 | } |
| 347 | final type = (record['entityType'] as String) |
| 348 | .replaceFirst('school_lifecycle_', ''); |
| 349 | await _send(type, record); |
| 350 | } |
| 351 | }); |
| 352 | Future<void> useServer(String type, String entityId) async { |
| 353 | final snapshot = await read(); |
| 354 | if (snapshot['offline'] == true) { |
| 355 | throw const ApiException(409, 'server_snapshot_required'); |
| 356 | } |
| 357 | await _serial(() async { |
| 358 | final row = (snapshot[type] as List<Map<String, dynamic>>) |
| 359 | .where((row) => row['id'] == entityId) |
| 360 | .firstOrNull; |
| 361 | await store.discardEntityChanges(entityId, |
| 362 | serverItem: row, |
| 363 | entityType: 'school_lifecycle_$type', |
| 364 | cacheKey: 'school_lifecycle_$type'); |
| 365 | }); |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | String _schoolError(Object error) { |
| 370 | if (isOfflineFailure(error)) { |
| 371 | return 'اتصال برقرار نیست؛ تغییرهای ذخیرهشده هنوز تأیید سرور ندارند.'; |
| 372 | } |
| 373 | if (error is ApiException) { |
| 374 | if ([401, 403].contains(error.statusCode)) { |
| 375 | return 'نشست یا دسترسی معتبر نیست؛ اطلاعات قبلی از صفحه پاک شد.'; |
| 376 | } |
| 377 | if (error.statusCode == 409) { |
| 378 | return 'تغییر معلق، تعارض نسخه یا محدودیت اطلاعات وابسته وجود دارد. وضعیت سرور را بررسی کن.'; |
| 379 | } |
| 380 | if (error.statusCode == 400) { |
| 381 | return 'عنوان، تاریخ و محدوده سال یا نیمسال را بررسی کن.'; |
| 382 | } |
| 383 | } |
| 384 | return 'عملیات با پاسخ معتبر سرور تأیید نشد. وضعیت را تازه کن.'; |
| 385 | } |
| 386 | |
| 387 | class SchoolManagementPage extends StatefulWidget { |
| 388 | const SchoolManagementPage({super.key, required this.api}); |
| 389 | final HttpIdentityApi api; |
| 390 | @override |
| 391 | State<SchoolManagementPage> createState() => _SchoolManagementPageState(); |
| 392 | } |
| 393 | |
| 394 | class _SchoolManagementPageState extends State<SchoolManagementPage> { |
| 395 | late final SchoolLifecycleSync sync; |
| 396 | Map<String, dynamic>? snapshot; |
| 397 | List<Map<String, dynamic>> subjects = [], classes = []; |
| 398 | bool busy = false, childrenFresh = false; |
| 399 | String? error, notice; |
| 400 | int epoch = 0; |
| 401 | @override |
| 402 | void initState() { |
| 403 | super.initState(); |
| 404 | sync = SchoolLifecycleSync(widget.api); |
| 405 | load(); |
| 406 | } |
| 407 | |
| 408 | @override |
| 409 | void dispose() { |
| 410 | epoch++; |
| 411 | super.dispose(); |
| 412 | } |
| 413 | |
| 414 | bool get writable => !busy && snapshot != null; |
| 415 | Future<void> load({bool retry = false}) async { |
| 416 | if (busy) return; |
| 417 | final mine = ++epoch; |
| 418 | setState(() { |
| 419 | busy = true; |
| 420 | childrenFresh = false; |
| 421 | }); |
| 422 | try { |
| 423 | if (retry) await sync.flush(); |
| 424 | final value = await sync.read(); |
| 425 | if (!mounted || mine != epoch) return; |
| 426 | setState(() { |
| 427 | snapshot = value; |
| 428 | error = null; |
| 429 | subjects = []; |
| 430 | classes = []; |
| 431 | }); |
| 432 | if (value['offline'] != true) { |
| 433 | final overview = |
| 434 | await widget.api.getSchoolOverview(widget.api.currentUserId!); |
| 435 | final timetable = |
| 436 | await widget.api.getTimetable(widget.api.currentUserId!); |
| 437 | if (!mounted || |
| 438 | mine != epoch || |
| 439 | widget.api.cacheNamespace != sync.store.scope) { |
| 440 | return; |
| 441 | } |
| 442 | setState(() { |
| 443 | subjects = (overview['subjects'] as List? ?? []) |
| 444 | .map((raw) => Map<String, dynamic>.from(raw as Map)) |
| 445 | .toList(); |
| 446 | classes = timetable; |
| 447 | childrenFresh = true; |
| 448 | }); |
| 449 | } |
| 450 | } catch (failure) { |
| 451 | if (mounted && mine == epoch) { |
| 452 | setState(() { |
| 453 | if (failure is ApiException && |
| 454 | [401, 403].contains(failure.statusCode)) { |
| 455 | snapshot = null; |
| 456 | subjects = []; |
| 457 | classes = []; |
| 458 | } |
| 459 | notice = _schoolError(failure); |
| 460 | }); |
| 461 | } |
| 462 | } finally { |
| 463 | if (mounted && mine == epoch) setState(() => busy = false); |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | List<Map<String, dynamic>> rows(String type) => |
| 468 | (snapshot?[type] as List? ?? []) |
| 469 | .map((raw) => Map<String, dynamic>.from(raw as Map)) |
| 470 | .toList(); |
| 471 | bool contextActive(String id) => rows('contexts').any((row) => |
| 472 | row['id'] == id && row['active'] == true && row['kind'] == 'student'); |
| 473 | bool yearActive(String id) => rows('years').any((row) => |
| 474 | row['id'] == id && |
| 475 | row['active'] == true && |
| 476 | contextActive(row['life_context_id'].toString())); |
| 477 | bool termActive(String id) => rows('terms').any((row) => |
| 478 | row['id'] == id && |
| 479 | row['active'] == true && |
| 480 | yearActive(row['academic_year_id'].toString())); |
| 481 | |
| 482 | Future<void> editLifecycle(String type, [Map<String, dynamic>? row]) async { |
| 483 | if (!writable) return; |
| 484 | final title = TextEditingController(text: row?['title']?.toString() ?? ''); |
| 485 | final starts = |
| 486 | TextEditingController(text: row?['starts_on']?.toString() ?? ''); |
| 487 | final ends = TextEditingController(text: row?['ends_on']?.toString() ?? ''); |
| 488 | final draftId = row?['id']?.toString() ?? newMutationId(); |
| 489 | var attempted = false; |
| 490 | var kind = row?['kind']?.toString() ?? 'student'; |
| 491 | String? parentId; |
| 492 | final parents = type == 'years' |
| 493 | ? rows('contexts') |
| 494 | .where((row) => row['active'] == true && row['kind'] == 'student') |
| 495 | .toList() |
| 496 | : rows('years') |
| 497 | .where((row) => yearActive(row['id'].toString())) |
| 498 | .toList(); |
| 499 | if (row != null) { |
| 500 | parentId = row[type == 'years' ? 'life_context_id' : 'academic_year_id'] |
| 501 | ?.toString(); |
| 502 | } |
| 503 | var saving = false; |
| 504 | String? failure; |
| 505 | final saved = await showDialog<bool>( |
| 506 | context: context, |
| 507 | barrierDismissible: false, |
| 508 | builder: (dialog) => StatefulBuilder(builder: (context, local) { |
| 509 | Future<void> pick(TextEditingController target) async { |
| 510 | final initial = DateTime.tryParse(_latinDigits(target.text)); |
| 511 | final selected = await showDatePicker( |
| 512 | context: context, |
| 513 | initialDate: initial != null && |
| 514 | initial.year >= 1900 && |
| 515 | initial.year <= 2200 |
| 516 | ? initial |
| 517 | : DateTime.now(), |
| 518 | firstDate: DateTime(1900), |
| 519 | lastDate: DateTime(2200, 12, 31)); |
| 520 | if (selected != null) { |
| 521 | local(() => target.text = _dateText(selected)); |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | return AlertDialog( |
| 526 | title: Text(row == null |
| 527 | ? 'ایجاد ${_typeLabel(type)}' |
| 528 | : 'ویرایش ${_typeLabel(type)}'), |
| 529 | content: SingleChildScrollView( |
| 530 | child: Column(mainAxisSize: MainAxisSize.min, children: [ |
| 531 | TextField( |
| 532 | controller: title, |
| 533 | enabled: !saving, |
| 534 | maxLength: 120, |
| 535 | decoration: const InputDecoration(labelText: 'عنوان')), |
| 536 | if (type == 'contexts') |
| 537 | DropdownButtonFormField<String>( |
| 538 | initialValue: kind, |
| 539 | decoration: |
| 540 | const InputDecoration(labelText: 'نوع زمینه'), |
| 541 | items: const [ |
| 542 | DropdownMenuItem( |
| 543 | value: 'student', child: Text('مدرسه')), |
| 544 | DropdownMenuItem(value: 'work', child: Text('کار')), |
| 545 | DropdownMenuItem( |
| 546 | value: 'personal', child: Text('شخصی')) |
| 547 | ], |
| 548 | onChanged: saving |
| 549 | ? null |
| 550 | : (value) => local(() => kind = value!)), |
| 551 | if (type != 'contexts' && row == null) |
| 552 | DropdownButtonFormField<String>( |
| 553 | initialValue: parentId, |
| 554 | decoration: InputDecoration( |
| 555 | labelText: |
| 556 | type == 'years' ? 'مدرسه فعال' : 'سال فعال'), |
| 557 | items: parents |
| 558 | .map((parent) => DropdownMenuItem( |
| 559 | value: parent['id'].toString(), |
| 560 | child: Text(parent['title'].toString()))) |
| 561 | .toList(), |
| 562 | onChanged: saving |
| 563 | ? null |
| 564 | : (value) => local(() => parentId = value)), |
| 565 | if (type != 'contexts') ...[ |
| 566 | const Text( |
| 567 | 'تاریخ میلادی: YYYY-MM-DD؛ تاریخ شروع و پایان را خودت انتخاب کن.'), |
| 568 | TextField( |
| 569 | controller: starts, |
| 570 | enabled: !saving, |
| 571 | textDirection: TextDirection.ltr, |
| 572 | decoration: InputDecoration( |
| 573 | labelText: 'تاریخ شروع میلادی', |
| 574 | suffixIcon: IconButton( |
| 575 | onPressed: saving ? null : () => pick(starts), |
| 576 | icon: const Icon(Icons.calendar_month)))), |
| 577 | TextField( |
| 578 | controller: ends, |
| 579 | enabled: !saving, |
| 580 | textDirection: TextDirection.ltr, |
| 581 | decoration: InputDecoration( |
| 582 | labelText: 'تاریخ پایان میلادی', |
| 583 | suffixIcon: IconButton( |
| 584 | onPressed: saving ? null : () => pick(ends), |
| 585 | icon: const Icon(Icons.calendar_month)))), |
| 586 | ], |
| 587 | if (failure != null) |
| 588 | Text(failure!, |
| 589 | style: TextStyle( |
| 590 | color: Theme.of(context).colorScheme.error)), |
| 591 | ])), |
| 592 | actions: [ |
| 593 | TextButton( |
| 594 | onPressed: |
| 595 | saving ? null : () => Navigator.pop(dialog, false), |
| 596 | child: const Text('انصراف')), |
| 597 | FilledButton( |
| 598 | onPressed: saving |
| 599 | ? null |
| 600 | : () async { |
| 601 | if (type != 'contexts' && |
| 602 | row == null && |
| 603 | parentId == null) { |
| 604 | local(() => failure = |
| 605 | 'ابتدا یک زمینه یا سال فعال انتخاب کن.'); |
| 606 | return; |
| 607 | } |
| 608 | local(() { |
| 609 | saving = true; |
| 610 | failure = null; |
| 611 | }); |
| 612 | try { |
| 613 | final data = { |
| 614 | 'title': title.text, |
| 615 | if (type == 'contexts') 'kind': kind, |
| 616 | if (type != 'contexts') ...{ |
| 617 | 'startsOn': starts.text, |
| 618 | 'endsOn': ends.text |
| 619 | }, |
| 620 | if (type != 'contexts' && row == null) |
| 621 | type == 'years' |
| 622 | ? 'lifeContextId' |
| 623 | : 'academicYearId': parentId |
| 624 | }; |
| 625 | attempted = true; |
| 626 | final result = await sync.mutate(type, |
| 627 | row == null ? 'create' : 'update', data, |
| 628 | entityId: draftId, |
| 629 | expectedVersion: |
| 630 | row?['version'] as int? ?? 0); |
| 631 | if (mounted) { |
| 632 | notice = result['queued'] == true |
| 633 | ? 'در دستگاه ذخیره شد؛ تا تأیید سرور، مرحله وابسته را نساز.' |
| 634 | : 'تغییر با تأیید سرور ثبت شد.'; |
| 635 | } |
| 636 | if (dialog.mounted) { |
| 637 | Navigator.pop(dialog, true); |
| 638 | } |
| 639 | } catch (e) { |
| 640 | if (dialog.mounted) { |
| 641 | local(() { |
| 642 | failure = _schoolError(e); |
| 643 | saving = false; |
| 644 | }); |
| 645 | } |
| 646 | } |
| 647 | }, |
| 648 | child: Text(saving ? 'در حال ثبت…' : 'ثبت')), |
| 649 | ]); |
| 650 | })); |
| 651 | title.dispose(); |
| 652 | starts.dispose(); |
| 653 | ends.dispose(); |
| 654 | if ((saved == true || attempted) && mounted) await load(); |
| 655 | } |
| 656 | |
| 657 | Future<void> archive(String type, Map<String, dynamic> row) async { |
| 658 | final confirmed = await showDialog<bool>( |
| 659 | context: context, |
| 660 | builder: (dialog) => AlertDialog( |
| 661 | title: const Text('بایگانی'), |
| 662 | content: const Text( |
| 663 | 'اطلاعات، تکالیف و سابقه حذف نمیشوند. ویرایش اطلاعات وابسته متوقف میشود.'), |
| 664 | actions: [ |
| 665 | TextButton( |
| 666 | onPressed: () => Navigator.pop(dialog, false), |
| 667 | child: const Text('انصراف')), |
| 668 | FilledButton( |
| 669 | onPressed: () => Navigator.pop(dialog, true), |
| 670 | child: const Text('بایگانی')) |
| 671 | ])); |
| 672 | if (confirmed != true || !mounted || busy) return; |
| 673 | setState(() => busy = true); |
| 674 | try { |
| 675 | final result = await sync.mutate(type, 'archive', {}, |
| 676 | entityId: row['id'].toString(), |
| 677 | expectedVersion: row['version'] as int); |
| 678 | notice = result['queued'] == true |
| 679 | ? 'بایگانی در انتظار تأیید سرور است.' |
| 680 | : 'بایگانی با تأیید سرور ثبت شد.'; |
| 681 | } catch (e) { |
| 682 | if (mounted) setState(() => notice = _schoolError(e)); |
| 683 | } finally { |
| 684 | if (mounted) { |
| 685 | setState(() => busy = false); |
| 686 | await load(); |
| 687 | } |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | Future<void> childWrite(Future<void> Function() action) async { |
| 692 | if (!writable || !childrenFresh) return; |
| 693 | setState(() { |
| 694 | busy = true; |
| 695 | notice = null; |
| 696 | }); |
| 697 | try { |
| 698 | await action(); |
| 699 | if (mounted) notice = 'تغییر اطلاعات درسی با پاسخ سرور ثبت شد.'; |
| 700 | } catch (failure) { |
| 701 | if (mounted) { |
| 702 | if (isOfflineFailure(failure) || |
| 703 | failure is ApiException && failure.statusCode >= 500) { |
| 704 | notice = |
| 705 | 'نتیجه ارسال نامشخص است. این عملیات خودکار تکرار نمیشود؛ پیش از ثبت دوباره، فهرست سرور را تازه و بررسی کن.'; |
| 706 | } else { |
| 707 | error = _schoolError(failure); |
| 708 | } |
| 709 | } |
| 710 | } finally { |
| 711 | if (mounted) { |
| 712 | setState(() => busy = false); |
| 713 | await load(); |
| 714 | } |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | Future<void> editSubject([Map<String, dynamic>? row]) async { |
| 719 | final name = TextEditingController(text: row?['name']?.toString() ?? ''); |
| 720 | final teacher = |
| 721 | TextEditingController(text: row?['teacher_name']?.toString() ?? ''); |
| 722 | var termId = row?['academic_term_id']?.toString(); |
| 723 | final active = |
| 724 | rows('terms').where((row) => termActive(row['id'].toString())).toList(); |
| 725 | final data = await showDialog<Map<String, dynamic>>( |
| 726 | context: context, |
| 727 | builder: (dialog) => StatefulBuilder( |
| 728 | builder: (context, local) => AlertDialog( |
| 729 | title: Text(row == null ? 'درس جدید' : 'ویرایش درس'), |
| 730 | content: SingleChildScrollView( |
| 731 | child: |
| 732 | Column(mainAxisSize: MainAxisSize.min, children: [ |
| 733 | TextField( |
| 734 | controller: name, |
| 735 | maxLength: 120, |
| 736 | decoration: |
| 737 | const InputDecoration(labelText: 'نام درس')), |
| 738 | TextField( |
| 739 | controller: teacher, |
| 740 | maxLength: 120, |
| 741 | decoration: const InputDecoration( |
| 742 | labelText: 'نام دبیر؛ اختیاری')), |
| 743 | DropdownButtonFormField<String>( |
| 744 | initialValue: termId, |
| 745 | decoration: |
| 746 | const InputDecoration(labelText: 'نیمسال فعال'), |
| 747 | items: active |
| 748 | .map((term) => DropdownMenuItem( |
| 749 | value: term['id'].toString(), |
| 750 | child: Text(term['title'].toString()))) |
| 751 | .toList(), |
| 752 | onChanged: (value) => local(() => termId = value)) |
| 753 | ])), |
| 754 | actions: [ |
| 755 | TextButton( |
| 756 | onPressed: () => Navigator.pop(dialog), |
| 757 | child: const Text('انصراف')), |
| 758 | FilledButton( |
| 759 | onPressed: () => |
| 760 | name.text.trim().isEmpty || termId == null |
| 761 | ? null |
| 762 | : Navigator.pop(dialog, { |
| 763 | 'name': name.text.trim(), |
| 764 | 'teacherName': teacher.text.trim().isEmpty |
| 765 | ? null |
| 766 | : teacher.text.trim(), |
| 767 | 'academicTermId': termId |
| 768 | }), |
| 769 | child: const Text('ثبت')) |
| 770 | ]))); |
| 771 | name.dispose(); |
| 772 | teacher.dispose(); |
| 773 | if (data == null || !mounted) return; |
| 774 | await childWrite(() async { |
| 775 | if (row == null) { |
| 776 | final payload = {...data}..remove('academicTermId'); |
| 777 | await widget.api |
| 778 | .createSubject(data['academicTermId'].toString(), payload); |
| 779 | } else { |
| 780 | await widget.api.requestJson( |
| 781 | 'PATCH', '/v1/school/subjects/${row['id']}', |
| 782 | body: data); |
| 783 | } |
| 784 | }); |
| 785 | } |
| 786 | |
| 787 | Future<void> editClass([Map<String, dynamic>? row]) async { |
| 788 | final starts = TextEditingController( |
| 789 | text: row?['starts_at']?.toString().substring(0, 5) ?? ''); |
| 790 | final ends = TextEditingController( |
| 791 | text: row?['ends_at']?.toString().substring(0, 5) ?? ''); |
| 792 | final location = |
| 793 | TextEditingController(text: row?['location']?.toString() ?? ''); |
| 794 | final until = TextEditingController( |
| 795 | text: row?['recurrence_until']?.toString().substring(0, 10) ?? ''); |
| 796 | var subjectId = row?['subject_id']?.toString(), |
| 797 | weekday = row?['weekday'] as int? ?? 1; |
| 798 | const weekdays = [ |
| 799 | 'شنبه', |
| 800 | 'یکشنبه', |
| 801 | 'دوشنبه', |
| 802 | 'سهشنبه', |
| 803 | 'چهارشنبه', |
| 804 | 'پنجشنبه', |
| 805 | 'جمعه' |
| 806 | ]; |
| 807 | final data = await showDialog<Map<String, dynamic>>( |
| 808 | context: context, |
| 809 | builder: (dialog) => StatefulBuilder( |
| 810 | builder: (context, local) => AlertDialog( |
| 811 | title: Text(row == null ? 'کلاس جدید' : 'ویرایش کلاس'), |
| 812 | content: SingleChildScrollView( |
| 813 | child: |
| 814 | Column(mainAxisSize: MainAxisSize.min, children: [ |
| 815 | DropdownButtonFormField<String>( |
| 816 | initialValue: subjectId, |
| 817 | decoration: |
| 818 | const InputDecoration(labelText: 'درس فعال'), |
| 819 | items: subjects |
| 820 | .map((subject) => DropdownMenuItem( |
| 821 | value: subject['id'].toString(), |
| 822 | child: Text(subject['name'].toString()))) |
| 823 | .toList(), |
| 824 | onChanged: (value) => local(() => subjectId = value)), |
| 825 | DropdownButtonFormField<int>( |
| 826 | initialValue: weekday, |
| 827 | decoration: |
| 828 | const InputDecoration(labelText: 'روز هفته'), |
| 829 | items: List.generate( |
| 830 | 7, |
| 831 | (i) => DropdownMenuItem( |
| 832 | value: i + 1, child: Text(weekdays[i]))), |
| 833 | onChanged: (value) => local(() => weekday = value!)), |
| 834 | TextField( |
| 835 | controller: starts, |
| 836 | textDirection: TextDirection.ltr, |
| 837 | decoration: const InputDecoration( |
| 838 | labelText: 'شروع کلاس HH:mm')), |
| 839 | TextField( |
| 840 | controller: ends, |
| 841 | textDirection: TextDirection.ltr, |
| 842 | decoration: const InputDecoration( |
| 843 | labelText: 'پایان کلاس HH:mm')), |
| 844 | TextField( |
| 845 | controller: location, |
| 846 | maxLength: 240, |
| 847 | decoration: |
| 848 | const InputDecoration(labelText: 'محل؛ اختیاری')), |
| 849 | TextField( |
| 850 | controller: until, |
| 851 | textDirection: TextDirection.ltr, |
| 852 | decoration: const InputDecoration( |
| 853 | labelText: |
| 854 | 'آخرین تکرار میلادی YYYY-MM-DD؛ اختیاری')) |
| 855 | ])), |
| 856 | actions: [ |
| 857 | TextButton( |
| 858 | onPressed: () => Navigator.pop(dialog), |
| 859 | child: const Text('انصراف')), |
| 860 | FilledButton( |
| 861 | onPressed: () => subjectId == null |
| 862 | ? null |
| 863 | : Navigator.pop(dialog, { |
| 864 | 'subjectId': subjectId, |
| 865 | 'weekday': weekday, |
| 866 | 'startsAt': _latinDigits(starts.text), |
| 867 | 'endsAt': _latinDigits(ends.text), |
| 868 | 'location': location.text.trim().isEmpty |
| 869 | ? null |
| 870 | : location.text.trim(), |
| 871 | 'recurrenceUntil': until.text.trim().isEmpty |
| 872 | ? null |
| 873 | : _latinDigits(until.text) |
| 874 | }), |
| 875 | child: const Text('ثبت')) |
| 876 | ]))); |
| 877 | starts.dispose(); |
| 878 | ends.dispose(); |
| 879 | location.dispose(); |
| 880 | until.dispose(); |
| 881 | if (data == null || !mounted) return; |
| 882 | await childWrite(() async { |
| 883 | if (row == null) { |
| 884 | final payload = {...data}..remove('subjectId'); |
| 885 | await widget.api |
| 886 | .createClassSession(data['subjectId'].toString(), payload); |
| 887 | } else { |
| 888 | await widget.api.requestJson('PATCH', '/v1/school/classes/${row['id']}', |
| 889 | body: data); |
| 890 | } |
| 891 | }); |
| 892 | } |
| 893 | |
| 894 | Future<void> archiveChild(String path) async { |
| 895 | final yes = await showDialog<bool>( |
| 896 | context: context, |
| 897 | builder: (dialog) => AlertDialog( |
| 898 | title: const Text('بایگانی اطلاعات درسی'), |
| 899 | content: const Text('سابقه و تکالیف وابسته حفظ میشود.'), |
| 900 | actions: [ |
| 901 | TextButton( |
| 902 | onPressed: () => Navigator.pop(dialog, false), |
| 903 | child: const Text('انصراف')), |
| 904 | FilledButton( |
| 905 | onPressed: () => Navigator.pop(dialog, true), |
| 906 | child: const Text('بایگانی')) |
| 907 | ])); |
| 908 | if (yes == true && mounted) { |
| 909 | await childWrite(() async { |
| 910 | await widget.api.requestJson('DELETE', path); |
| 911 | }); |
| 912 | } |
| 913 | } |
| 914 | |
| 915 | @override |
| 916 | Widget build(BuildContext context) => Scaffold( |
| 917 | appBar: AppBar(title: const Text('مدیریت مدرسه'), actions: [ |
| 918 | IconButton( |
| 919 | onPressed: busy ? null : () => load(), |
| 920 | icon: const Icon(Icons.refresh), |
| 921 | tooltip: 'تازهکردن') |
| 922 | ]), |
| 923 | body: Directionality( |
| 924 | textDirection: TextDirection.rtl, |
| 925 | child: ListView(padding: const EdgeInsets.all(16), children: [ |
| 926 | const Text( |
| 927 | 'این اطلاعات خصوصی است. ابتدا مدرسه، سپس سال با تاریخ دلخواه، نیمسال، درس و کلاس را بساز. هیچ درس یا تاریخی خودکار ساخته نمیشود.'), |
| 928 | if (busy) const LinearProgressIndicator(), |
| 929 | if (error != null) |
| 930 | Text(error!, |
| 931 | style: TextStyle(color: Theme.of(context).colorScheme.error)), |
| 932 | if (notice != null) |
| 933 | Semantics(liveRegion: true, child: Text(notice!)), |
| 934 | if (snapshot != null) |
| 935 | Text(snapshot!['offline'] == true |
| 936 | ? 'نسخه ذخیرهشده؛ داده زنده نیست' |
| 937 | : 'آخرین دریافت سرور: ${snapshot!['fetchedAt'] ?? 'نامشخص'}'), |
| 938 | if (snapshot != null && |
| 939 | (snapshot!['pending'] as List).isNotEmpty) ...[ |
| 940 | FilledButton( |
| 941 | onPressed: busy ? null : () => load(retry: true), |
| 942 | child: const Text('ارسال دوباره تغییرهای ذخیرهشده')), |
| 943 | ...(snapshot!['pending'] as List).map((raw) { |
| 944 | final record = Map<String, dynamic>.from(raw as Map); |
| 945 | final type = (record['entityType'] as String) |
| 946 | .replaceFirst('school_lifecycle_', ''); |
| 947 | return Card( |
| 948 | child: ListTile( |
| 949 | title: |
| 950 | Text('${_typeLabel(type)}: در انتظار تأیید سرور'), |
| 951 | subtitle: Text(record['queueStatus'] == 'conflict' |
| 952 | ? 'تعارض نسخه؛ تغییر محلی نگه داشته شده است' |
| 953 | : '${record['operation']} · ${(record['payload'] as Map)['data']['title'] ?? ''}'), |
| 954 | trailing: TextButton( |
| 955 | onPressed: busy |
| 956 | ? null |
| 957 | : () async { |
| 958 | final yes = await showDialog<bool>( |
| 959 | context: context, |
| 960 | builder: (dialog) => AlertDialog( |
| 961 | title: const Text( |
| 962 | 'انتخاب نسخه سرور'), |
| 963 | content: const Text( |
| 964 | 'تغییر محلی از صف کنار میرود و در سابقه بازیابی دستگاه نگه داشته میشود.'), |
| 965 | actions: [ |
| 966 | TextButton( |
| 967 | onPressed: () => |
| 968 | Navigator.pop( |
| 969 | dialog, false), |
| 970 | child: |
| 971 | const Text('انصراف')), |
| 972 | FilledButton( |
| 973 | onPressed: () => |
| 974 | Navigator.pop( |
| 975 | dialog, true), |
| 976 | child: const Text( |
| 977 | 'نسخه سرور')) |
| 978 | ])); |
| 979 | if (yes == true && mounted) { |
| 980 | try { |
| 981 | await sync.useServer(type, |
| 982 | record['entityId'].toString()); |
| 983 | await load(); |
| 984 | } catch (e) { |
| 985 | if (mounted) { |
| 986 | setState( |
| 987 | () => error = _schoolError(e)); |
| 988 | } |
| 989 | } |
| 990 | } |
| 991 | }, |
| 992 | child: const Text('بررسی نسخه سرور')))); |
| 993 | }), |
| 994 | ], |
| 995 | for (final type in _schoolTypes) ...[ |
| 996 | Row(children: [ |
| 997 | Expanded( |
| 998 | child: Text(_typeLabel(type), |
| 999 | style: Theme.of(context).textTheme.titleMedium)), |
| 1000 | TextButton.icon( |
| 1001 | onPressed: writable ? () => editLifecycle(type) : null, |
| 1002 | icon: const Icon(Icons.add), |
| 1003 | label: const Text('ایجاد')) |
| 1004 | ]), |
| 1005 | ...rows(type).map((row) { |
| 1006 | final ancestorActive = type == 'contexts' || |
| 1007 | (type == 'years' |
| 1008 | ? contextActive(row['life_context_id'].toString()) |
| 1009 | : yearActive(row['academic_year_id'].toString())); |
| 1010 | final pending = (snapshot!['pending'] as List) |
| 1011 | .any((m) => m['entityId'] == row['id']); |
| 1012 | return Card( |
| 1013 | child: ListTile( |
| 1014 | title: Text(row['title'].toString()), |
| 1015 | subtitle: Text( |
| 1016 | '${row['active'] == true ? (ancestorActive ? 'فعال' : 'زمینه بالادست بایگانی شده') : 'بایگانیشده'} · نسخه ${_faDigits(row['version'].toString())}${type == 'contexts' ? '' : '\n${_faDigits(row['starts_on'].toString())} تا ${_faDigits(row['ends_on'].toString())} (میلادی)'}'), |
| 1017 | trailing: Wrap(children: [ |
| 1018 | IconButton( |
| 1019 | onPressed: writable && |
| 1020 | !pending && |
| 1021 | row['active'] == true && |
| 1022 | ancestorActive |
| 1023 | ? () => editLifecycle(type, row) |
| 1024 | : null, |
| 1025 | icon: const Icon(Icons.edit_outlined), |
| 1026 | tooltip: 'ویرایش ${_typeLabel(type)}'), |
| 1027 | IconButton( |
| 1028 | onPressed: |
| 1029 | writable && !pending && row['active'] == true |
| 1030 | ? () => archive(type, row) |
| 1031 | : null, |
| 1032 | icon: const Icon(Icons.archive_outlined), |
| 1033 | tooltip: 'بایگانی ${_typeLabel(type)}') |
| 1034 | ]))); |
| 1035 | }), |
| 1036 | ], |
| 1037 | Row(children: [ |
| 1038 | Expanded( |
| 1039 | child: Text('درسها', |
| 1040 | style: Theme.of(context).textTheme.titleMedium)), |
| 1041 | TextButton.icon( |
| 1042 | onPressed: |
| 1043 | writable && childrenFresh ? () => editSubject() : null, |
| 1044 | icon: const Icon(Icons.add), |
| 1045 | label: const Text('درس جدید')) |
| 1046 | ]), |
| 1047 | ...subjects.map((row) => Card( |
| 1048 | child: ListTile( |
| 1049 | title: Text(row['name'].toString()), |
| 1050 | subtitle: Text(row['teacher_name']?.toString() ?? |
| 1051 | row['term_title']?.toString() ?? |
| 1052 | ''), |
| 1053 | trailing: Wrap(children: [ |
| 1054 | IconButton( |
| 1055 | onPressed: writable && childrenFresh |
| 1056 | ? () => editSubject(row) |
| 1057 | : null, |
| 1058 | icon: const Icon(Icons.edit_outlined), |
| 1059 | tooltip: 'ویرایش درس'), |
| 1060 | IconButton( |
| 1061 | onPressed: writable && childrenFresh |
| 1062 | ? () => archiveChild( |
| 1063 | '/v1/school/subjects/${row['id']}') |
| 1064 | : null, |
| 1065 | icon: const Icon(Icons.archive_outlined), |
| 1066 | tooltip: 'بایگانی درس') |
| 1067 | ])))), |
| 1068 | Row(children: [ |
| 1069 | Expanded( |
| 1070 | child: Text('کلاسها', |
| 1071 | style: Theme.of(context).textTheme.titleMedium)), |
| 1072 | TextButton.icon( |
| 1073 | onPressed: |
| 1074 | writable && childrenFresh ? () => editClass() : null, |
| 1075 | icon: const Icon(Icons.add), |
| 1076 | label: const Text('کلاس جدید')) |
| 1077 | ]), |
| 1078 | ...classes.map((row) => Card( |
| 1079 | child: ListTile( |
| 1080 | title: Text(row['subject_name']?.toString() ?? 'کلاس'), |
| 1081 | subtitle: Text( |
| 1082 | 'روز ${_faDigits(row['weekday'].toString())} · ${_faDigits(row['starts_at'].toString())} تا ${_faDigits(row['ends_at'].toString())}'), |
| 1083 | trailing: Wrap(children: [ |
| 1084 | IconButton( |
| 1085 | onPressed: writable && childrenFresh |
| 1086 | ? () => editClass(row) |
| 1087 | : null, |
| 1088 | icon: const Icon(Icons.edit_outlined), |
| 1089 | tooltip: 'ویرایش کلاس'), |
| 1090 | IconButton( |
| 1091 | onPressed: writable && childrenFresh |
| 1092 | ? () => archiveChild( |
| 1093 | '/v1/school/classes/${row['id']}') |
| 1094 | : null, |
| 1095 | icon: const Icon(Icons.archive_outlined), |
| 1096 | tooltip: 'بایگانی کلاس') |
| 1097 | ])))), |
| 1098 | ]))); |
| 1099 | } |
| 1100 | |
| 1101 | String _typeLabel(String type) => switch (type) { |
| 1102 | 'contexts' => 'زمینه مدرسه و زندگی', |
| 1103 | 'years' => 'سال تحصیلی', |
| 1104 | 'terms' => 'نیمسال', |
| 1105 | _ => 'اطلاعات مدرسه' |
| 1106 | }; |