LifeMate — Personal, Family & Learning Companion
fix/managed-child-session-boundary
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 familyRoleLabels = <String, String>{ |
| 11 | 'parent_guardian': 'سرپرست', |
| 12 | 'teen_minor': 'فرزند', |
| 13 | 'adult_member': 'عضو بزرگسال', |
| 14 | }; |
| 15 | final _familyUuid = RegExp(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$'); |
| 16 | bool _uuid(dynamic value) => value is String && _familyUuid.hasMatch(value); |
| 17 | bool _version(dynamic value) => |
| 18 | value is int && value > 0 && value <= 2147483647; |
| 19 | bool _date(dynamic value) => |
| 20 | value is String && |
| 21 | RegExp(r'(Z|[+-]\d{2}:\d{2})$').hasMatch(value) && |
| 22 | DateTime.tryParse(value) != null; |
| 23 | bool _exact(Map value, Set<String> keys) => |
| 24 | value.length == keys.length && value.keys.every(keys.contains); |
| 25 | Map<String, dynamic> _freeze(Map value) => |
| 26 | Map<String, dynamic>.from(jsonDecode(jsonEncode(value)) as Map); |
| 27 | Never _invalid() => throw const ApiException(502, 'invalid_family_response'); |
| 28 | |
| 29 | String familyManagementError(Object error) { |
| 30 | if (isOfflineFailure(error)) { |
| 31 | return 'اتصال برقرار نیست. نتیجه عملیات ممکن است نامشخص باشد؛ وضعیت را تازه کن. تغییر خودکار یا تلاش کور انجام نمیشود.'; |
| 32 | } |
| 33 | if (error is ApiException) { |
| 34 | if (error.statusCode == 401 || error.statusCode == 403) { |
| 35 | return 'نشست یا دسترسی این خانواده معتبر نیست؛ اطلاعات قبلی پاک شدند.'; |
| 36 | } |
| 37 | if (error.code == 'last_admin_required') { |
| 38 | return 'آخرین مدیر فعال را نمیتوان حذف یا از مدیریت خارج کرد؛ ابتدا مدیریت را به بزرگسال فعال منتقل کن.'; |
| 39 | } |
| 40 | if (error.code == 'age_confirmation_required' || |
| 41 | error.code == 'minor_role_restricted' || |
| 42 | error.code == 'minor_role_upgrade_forbidden' || |
| 43 | error.code == 'minor_cannot_admin') { |
| 44 | return 'سن مجاز برای نقش بزرگسال باید در سرور تأیید شود؛ نوع پروفایل مجوز مدیریت نمیدهد.'; |
| 45 | } |
| 46 | if (error.statusCode == 409) { |
| 47 | return 'نسخه یا وضعیت عضویت تغییر کرده است. ابتدا وضعیت تازه سرور را بررسی کن؛ درخواست قدیمی در صف محفوظ است.'; |
| 48 | } |
| 49 | if (error.statusCode == 404) { |
| 50 | return 'عضویت یا دعوت دیگر در دسترس نیست؛ وضعیت تازه را دریافت کن.'; |
| 51 | } |
| 52 | } |
| 53 | return 'عملیات با پاسخ معتبر تأیید نشد؛ ابتدا وضعیت تازه سرور را بررسی کن.'; |
| 54 | } |
| 55 | |
| 56 | /// Metadata-only journal for versioned family operations. Permissions, member |
| 57 | /// names, invitation contacts and tokens are never cached in this journal. |
| 58 | class FamilyOperationSync { |
| 59 | FamilyOperationSync(this.api, this.familyId, {OfflineStore? store}) |
| 60 | : store = store ?? OfflineStore.forApi(api) { |
| 61 | if (!_uuid(familyId)) throw ArgumentError('Invalid family ID'); |
| 62 | } |
| 63 | final HttpIdentityApi api; |
| 64 | final String familyId; |
| 65 | final OfflineStore store; |
| 66 | static final _tails = <String, Future<void>>{}; |
| 67 | String get path => '/v1/families/${Uri.encodeComponent(familyId)}'; |
| 68 | |
| 69 | Future<void> scope() async { |
| 70 | if (api.cacheNamespace != store.scope) { |
| 71 | throw const ApiException(401, 'cache_scope_closed'); |
| 72 | } |
| 73 | await store.readQueue(); |
| 74 | if (api.cacheNamespace != store.scope) { |
| 75 | throw const ApiException(401, 'cache_scope_closed'); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | Future<Map<String, dynamic>> request(String method, String suffix, |
| 80 | {Map<String, dynamic>? body}) async { |
| 81 | await scope(); |
| 82 | final response = await api.requestJson(method, '$path$suffix', body: body); |
| 83 | await scope(); |
| 84 | return response; |
| 85 | } |
| 86 | |
| 87 | Future<T> _serial<T>(Future<T> Function() operation) async { |
| 88 | final previous = _tails[store.scope]; |
| 89 | final release = Completer<void>(); |
| 90 | _tails[store.scope] = release.future; |
| 91 | if (previous != null) await previous; |
| 92 | try { |
| 93 | await scope(); |
| 94 | return await operation(); |
| 95 | } finally { |
| 96 | if (identical(_tails[store.scope], release.future)) { |
| 97 | _tails.remove(store.scope); |
| 98 | } |
| 99 | release.complete(); |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | Future<void> _membership({required bool admin}) async { |
| 104 | final result = await request('GET', ''); |
| 105 | if (result['id'] != familyId || |
| 106 | result['is_admin'] is! bool || |
| 107 | !familyRoleLabels.containsKey(result['role']) || |
| 108 | (result['is_admin'] == true && result['role'] == 'teen_minor')) { |
| 109 | _invalid(); |
| 110 | } |
| 111 | if (admin && result['is_admin'] != true) { |
| 112 | throw const ApiException(403, 'family_admin_required'); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | Map<String, dynamic> _body(String operation, String targetId, Map value) { |
| 117 | final keys = operation == 'role' |
| 118 | ? {'mutationId', 'expectedVersion', 'role'} |
| 119 | : operation == 'invitation_revoke' |
| 120 | ? {'mutationId', 'expectedVersion', 'action'} |
| 121 | : operation == 'admin_transfer' |
| 122 | ? { |
| 123 | 'mutationId', |
| 124 | 'targetUserId', |
| 125 | 'expectedVersion', |
| 126 | 'expectedActorVersion' |
| 127 | } |
| 128 | : <String>{}; |
| 129 | if (!_uuid(targetId) || |
| 130 | keys.isEmpty || |
| 131 | !_exact(value, keys) || |
| 132 | !_uuid(value['mutationId']) || |
| 133 | !_version(value['expectedVersion']) || |
| 134 | (operation == 'role' && !familyRoleLabels.containsKey(value['role'])) || |
| 135 | (operation == 'invitation_revoke' && value['action'] != 'revoke') || |
| 136 | (operation == 'admin_transfer' && |
| 137 | (value['targetUserId'] != targetId || |
| 138 | !_version(value['expectedActorVersion']) || |
| 139 | targetId == api.currentUserId))) { |
| 140 | throw const ApiException(400, 'invalid_family_operation'); |
| 141 | } |
| 142 | return _freeze(value); |
| 143 | } |
| 144 | |
| 145 | Future<List<Map<String, dynamic>>> pending() async { |
| 146 | await scope(); |
| 147 | final values = (await store.readQueue()) |
| 148 | .where((row) => |
| 149 | row['entityType'] == 'family_operation' && |
| 150 | row['entityId'] == familyId) |
| 151 | .toList(); |
| 152 | await scope(); |
| 153 | return values; |
| 154 | } |
| 155 | |
| 156 | Future<Map<String, dynamic>> submit( |
| 157 | String operation, String targetId, Map<String, dynamic> body) { |
| 158 | final frozen = _body(operation, targetId, body); |
| 159 | return _serial(() async { |
| 160 | await _membership( |
| 161 | admin: true); // No new operation under cached authority. |
| 162 | final mutation = { |
| 163 | 'id': frozen['mutationId'], |
| 164 | 'entityId': familyId, |
| 165 | 'entityType': 'family_operation', |
| 166 | 'operation': operation, |
| 167 | 'targetId': targetId, |
| 168 | 'payload': frozen |
| 169 | }; |
| 170 | await store.enqueue(mutation); |
| 171 | return _send(mutation); |
| 172 | }); |
| 173 | } |
| 174 | |
| 175 | Future<Map<String, dynamic>> retry(Map<String, dynamic> mutation) => |
| 176 | _serial(() async { |
| 177 | final saved = (await pending()) |
| 178 | .where((row) => row['id'] == mutation['id']) |
| 179 | .firstOrNull; |
| 180 | if (saved == null || jsonEncode(saved) != jsonEncode(mutation)) { |
| 181 | throw const ApiException(409, 'family_pending_changed'); |
| 182 | } |
| 183 | // A successful transfer removes the sender's admin flag. Its exact prior |
| 184 | // receipt may still be read by that active member; the server decides. |
| 185 | await _membership(admin: false); |
| 186 | return _send(saved); |
| 187 | }); |
| 188 | Future<Map<String, dynamic>> _send(Map<String, dynamic> mutation) async { |
| 189 | final operation = mutation['operation'] as String; |
| 190 | final targetId = mutation['targetId'] as String; |
| 191 | final body = _body(operation, targetId, mutation['payload'] as Map); |
| 192 | final suffix = operation == 'role' |
| 193 | ? '/members/$targetId/role' |
| 194 | : operation == 'invitation_revoke' |
| 195 | ? '/invitations/$targetId' |
| 196 | : '/admin-transfer'; |
| 197 | final result = await request( |
| 198 | operation == 'admin_transfer' ? 'POST' : 'PATCH', suffix, |
| 199 | body: body); |
| 200 | final ack = result['acknowledgement']; |
| 201 | if (ack is! Map || |
| 202 | !_exact(ack, |
| 203 | {'mutationId', 'familyId', 'targetId', 'operation', 'status'}) || |
| 204 | ack['mutationId'] != mutation['id'] || |
| 205 | ack['familyId'] != familyId || |
| 206 | ack['targetId'] != targetId || |
| 207 | ack['operation'] != operation || |
| 208 | !const {'accepted', 'already_applied'}.contains(ack['status'])) { |
| 209 | _invalid(); |
| 210 | } |
| 211 | final accepted = ack['status'] == 'accepted'; |
| 212 | String acceptedAt; |
| 213 | if (operation == 'invitation_revoke') { |
| 214 | final row = result['invitation']; |
| 215 | if (!_exact(result, {'invitation', 'acknowledgement'}) || |
| 216 | row is! Map || |
| 217 | !_exact(row, {'id', 'status', 'version', 'createdAt', 'expiresAt'}) || |
| 218 | row['id'] != targetId || |
| 219 | row['status'] != 'revoked' || |
| 220 | !_version(row['version']) || |
| 221 | row['version'] < body['expectedVersion'] + 1 || |
| 222 | (accepted && row['version'] != body['expectedVersion'] + 1) || |
| 223 | !_date(row['createdAt']) || |
| 224 | !_date(row['expiresAt'])) { |
| 225 | _invalid(); |
| 226 | } |
| 227 | acceptedAt = DateTime.now().toUtc().toIso8601String(); |
| 228 | } else { |
| 229 | if (!_exact(result, {'members', 'acknowledgement'}) || |
| 230 | result['members'] is! List) { |
| 231 | _invalid(); |
| 232 | } |
| 233 | final rows = result['members'] as List; |
| 234 | if (rows.length != (operation == 'role' ? 1 : 2)) _invalid(); |
| 235 | final byId = <String, Map>{}; |
| 236 | for (final row in rows) { |
| 237 | if (row is! Map || |
| 238 | !_exact(row, { |
| 239 | 'userId', |
| 240 | 'role', |
| 241 | 'isAdmin', |
| 242 | 'version', |
| 243 | 'updatedAt', |
| 244 | 'endedAt' |
| 245 | }) || |
| 246 | !_uuid(row['userId']) || |
| 247 | !familyRoleLabels.containsKey(row['role']) || |
| 248 | row['isAdmin'] is! bool || |
| 249 | !_version(row['version']) || |
| 250 | !_date(row['updatedAt']) || |
| 251 | (row['endedAt'] != null && !_date(row['endedAt'])) || |
| 252 | byId.containsKey(row['userId'])) { |
| 253 | _invalid(); |
| 254 | } |
| 255 | byId[row['userId'] as String] = row; |
| 256 | } |
| 257 | final target = byId[targetId]; |
| 258 | if (target == null || |
| 259 | target['version'] < body['expectedVersion'] + 1 || |
| 260 | (accepted && |
| 261 | (target['version'] != body['expectedVersion'] + 1 || |
| 262 | target['endedAt'] != null))) { |
| 263 | _invalid(); |
| 264 | } |
| 265 | if (operation == 'role') { |
| 266 | if (accepted && target['role'] != body['role']) _invalid(); |
| 267 | } else { |
| 268 | final actor = byId[api.currentUserId]; |
| 269 | if (actor == null || |
| 270 | actor['version'] < body['expectedActorVersion'] + 1 || |
| 271 | (accepted && |
| 272 | (actor['version'] != body['expectedActorVersion'] + 1 || |
| 273 | actor['isAdmin'] != false || |
| 274 | actor['endedAt'] != null || |
| 275 | target['isAdmin'] != true || |
| 276 | target['role'] == 'teen_minor'))) { |
| 277 | _invalid(); |
| 278 | } |
| 279 | } |
| 280 | acceptedAt = target['updatedAt'] as String; |
| 281 | } |
| 282 | await scope(); |
| 283 | await store.acknowledge(mutation['id'] as String, acceptedAt: acceptedAt); |
| 284 | return {'acknowledgement': _freeze(ack)}; |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | class FamilyManagementPage extends StatefulWidget { |
| 289 | const FamilyManagementPage( |
| 290 | {super.key, required this.api, required this.familyId}); |
| 291 | final HttpIdentityApi api; |
| 292 | final String familyId; |
| 293 | @override |
| 294 | State<FamilyManagementPage> createState() => _FamilyManagementPageState(); |
| 295 | } |
| 296 | |
| 297 | class _FamilyManagementPageState extends State<FamilyManagementPage> |
| 298 | with WidgetsBindingObserver { |
| 299 | late final FamilyOperationSync sync; |
| 300 | Timer? timer; |
| 301 | Map<String, dynamic>? family; |
| 302 | List<Map<String, dynamic>> members = [], invitations = [], pending = []; |
| 303 | final name = TextEditingController(), contact = TextEditingController(); |
| 304 | String contactKind = 'email', inviteRole = 'adult_member'; |
| 305 | String? guardianId, childId, invitationCursor, nextInvitationCursor, message; |
| 306 | int epoch = 0; |
| 307 | bool loading = false, busy = false, active = true; |
| 308 | DateTime? refreshed; |
| 309 | bool get admin => family?['is_admin'] == true; |
| 310 | Map<String, dynamic>? get self => members |
| 311 | .where((row) => row['user_id'] == widget.api.currentUserId) |
| 312 | .firstOrNull; |
| 313 | bool current(int request) => |
| 314 | mounted && |
| 315 | active && |
| 316 | epoch == request && |
| 317 | widget.api.cacheNamespace == sync.store.scope; |
| 318 | |
| 319 | @override |
| 320 | void initState() { |
| 321 | super.initState(); |
| 322 | sync = FamilyOperationSync(widget.api, widget.familyId); |
| 323 | WidgetsBinding.instance.addObserver(this); |
| 324 | refresh(); |
| 325 | timer = Timer.periodic(const Duration(seconds: 30), (_) { |
| 326 | if (active && !busy && !loading) refresh(); |
| 327 | }); |
| 328 | } |
| 329 | |
| 330 | void clear({bool privateInputs = true}) { |
| 331 | family = null; |
| 332 | members = []; |
| 333 | invitations = []; |
| 334 | guardianId = null; |
| 335 | childId = null; |
| 336 | refreshed = null; |
| 337 | nextInvitationCursor = null; |
| 338 | name.clear(); |
| 339 | if (privateInputs) contact.clear(); |
| 340 | } |
| 341 | |
| 342 | @override |
| 343 | void didChangeAppLifecycleState(AppLifecycleState state) { |
| 344 | active = state == AppLifecycleState.resumed; |
| 345 | ++epoch; |
| 346 | if (mounted) { |
| 347 | setState(() { |
| 348 | clear(); |
| 349 | loading = false; |
| 350 | }); |
| 351 | } |
| 352 | if (active && !busy) refresh(); |
| 353 | } |
| 354 | |
| 355 | @override |
| 356 | void dispose() { |
| 357 | ++epoch; |
| 358 | timer?.cancel(); |
| 359 | WidgetsBinding.instance.removeObserver(this); |
| 360 | name.dispose(); |
| 361 | contact.dispose(); |
| 362 | super.dispose(); |
| 363 | } |
| 364 | |
| 365 | Map<String, dynamic> validateFamily(Map raw) { |
| 366 | if (raw['id'] != widget.familyId || |
| 367 | raw['name'] is! String || |
| 368 | (raw['name'] as String).trim().isEmpty || |
| 369 | (raw['name'] as String).length > 120 || |
| 370 | raw['is_admin'] is! bool || |
| 371 | !familyRoleLabels.containsKey(raw['role']) || |
| 372 | (raw['is_admin'] == true && raw['role'] == 'teen_minor')) { |
| 373 | _invalid(); |
| 374 | } |
| 375 | return { |
| 376 | 'id': raw['id'], |
| 377 | 'name': raw['name'], |
| 378 | 'role': raw['role'], |
| 379 | 'is_admin': raw['is_admin'] |
| 380 | }; |
| 381 | } |
| 382 | |
| 383 | Map<String, dynamic> validateMember(dynamic raw) { |
| 384 | if (raw is! Map || |
| 385 | !_uuid(raw['user_id']) || |
| 386 | !familyRoleLabels.containsKey(raw['role']) || |
| 387 | raw['is_admin'] is! bool || |
| 388 | (raw['display_name'] != null && |
| 389 | (raw['display_name'] is! String || |
| 390 | (raw['display_name'] as String).length > 120)) || |
| 391 | (raw['version'] != null && !_version(raw['version'])) || |
| 392 | (raw['account_disabled'] != null && raw['account_disabled'] is! bool)) { |
| 393 | _invalid(); |
| 394 | } |
| 395 | return { |
| 396 | 'user_id': raw['user_id'], |
| 397 | 'display_name': raw['display_name'] ?? 'عضو خانواده', |
| 398 | 'role': raw['role'], |
| 399 | 'is_admin': raw['is_admin'], |
| 400 | 'version': raw['version'], |
| 401 | 'account_disabled': raw['account_disabled'] == true |
| 402 | }; |
| 403 | } |
| 404 | |
| 405 | Map<String, dynamic> validateInvitation(dynamic raw) { |
| 406 | if (raw is! Map || |
| 407 | !_exact(raw, { |
| 408 | 'id', |
| 409 | 'intendedRole', |
| 410 | 'status', |
| 411 | 'version', |
| 412 | 'createdAt', |
| 413 | 'expiresAt', |
| 414 | 'recipientHint' |
| 415 | }) || |
| 416 | !_uuid(raw['id']) || |
| 417 | !familyRoleLabels.containsKey(raw['intendedRole']) || |
| 418 | !const {'pending', 'expired'}.contains(raw['status']) || |
| 419 | !_version(raw['version']) || |
| 420 | !_date(raw['createdAt']) || |
| 421 | !_date(raw['expiresAt']) || |
| 422 | raw['recipientHint'] is! String || |
| 423 | (raw['recipientHint'] as String).length > 120) { |
| 424 | _invalid(); |
| 425 | } |
| 426 | return _freeze(raw); |
| 427 | } |
| 428 | |
| 429 | Future<void> refresh({bool firstInvitations = false}) async { |
| 430 | if (!active || busy || !mounted) return; |
| 431 | final request = ++epoch; |
| 432 | if (firstInvitations) invitationCursor = null; |
| 433 | setState(() { |
| 434 | clear(privateInputs: false); |
| 435 | loading = true; |
| 436 | message = null; |
| 437 | }); |
| 438 | try { |
| 439 | final fresh = validateFamily(await sync.request('GET', '')); |
| 440 | if (!current(request)) return; |
| 441 | final data = await sync.request('GET', '/members'); |
| 442 | if (data['members'] is! List) _invalid(); |
| 443 | final people = (data['members'] as List).map(validateMember).toList(); |
| 444 | if (people.map((row) => row['user_id']).toSet().length != people.length) { |
| 445 | _invalid(); |
| 446 | } |
| 447 | final queued = await sync.pending(); |
| 448 | if (!current(request)) return; |
| 449 | List<Map<String, dynamic>> invites = []; |
| 450 | String? next; |
| 451 | if (fresh['is_admin'] == true) { |
| 452 | final query = Uri(queryParameters: { |
| 453 | 'limit': '20', |
| 454 | if (invitationCursor != null) 'cursor': invitationCursor! |
| 455 | }).query; |
| 456 | final result = await sync.request('GET', '/invitations?$query'); |
| 457 | if (!_exact(result, {'invitations', 'nextCursor', 'total'}) || |
| 458 | result['invitations'] is! List || |
| 459 | (result['invitations'] as List).length > 20 || |
| 460 | result['total'] is! int || |
| 461 | result['total'] < 0 || |
| 462 | (result['nextCursor'] != null && !_uuid(result['nextCursor']))) { |
| 463 | _invalid(); |
| 464 | } |
| 465 | invites = |
| 466 | (result['invitations'] as List).map(validateInvitation).toList(); |
| 467 | next = result['nextCursor'] as String?; |
| 468 | } |
| 469 | if (!current(request)) return; |
| 470 | setState(() { |
| 471 | family = fresh; |
| 472 | members = people; |
| 473 | invitations = invites; |
| 474 | pending = queued; |
| 475 | nextInvitationCursor = next; |
| 476 | refreshed = DateTime.now(); |
| 477 | name.text = fresh['name'] as String; |
| 478 | loading = false; |
| 479 | }); |
| 480 | } catch (error) { |
| 481 | if (!current(request)) return; |
| 482 | setState(() { |
| 483 | clear(); |
| 484 | loading = false; |
| 485 | message = familyManagementError(error); |
| 486 | }); |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | Future<bool> confirm(String title, String explanation) async => |
| 491 | await showDialog<bool>( |
| 492 | context: context, |
| 493 | builder: (context) => Directionality( |
| 494 | textDirection: TextDirection.rtl, |
| 495 | child: AlertDialog( |
| 496 | title: Text(title), |
| 497 | content: Text(explanation), |
| 498 | actions: [ |
| 499 | TextButton( |
| 500 | onPressed: () => Navigator.pop(context, false), |
| 501 | child: const Text('انصراف')), |
| 502 | FilledButton( |
| 503 | onPressed: () => Navigator.pop(context, true), |
| 504 | child: const Text('تأیید تغییر')) |
| 505 | ]))) == |
| 506 | true; |
| 507 | |
| 508 | Future<void> perform(Future<void> Function() operation, |
| 509 | {bool archived = false}) async { |
| 510 | if (busy || !active) return; |
| 511 | final request = ++epoch; |
| 512 | setState(() { |
| 513 | busy = true; |
| 514 | clear(); |
| 515 | message = null; |
| 516 | }); |
| 517 | String? outcome; |
| 518 | bool success = false; |
| 519 | try { |
| 520 | await operation(); |
| 521 | if (!current(request)) return; |
| 522 | success = true; |
| 523 | outcome = 'عملیات در سرور تأیید شد؛ وضعیت تازه دریافت میشود.'; |
| 524 | } catch (error) { |
| 525 | if (!current(request)) return; |
| 526 | outcome = familyManagementError(error); |
| 527 | } finally { |
| 528 | if (mounted) setState(() => busy = false); |
| 529 | } |
| 530 | if (!mounted || !active || widget.api.cacheNamespace != sync.store.scope) { |
| 531 | return; |
| 532 | } |
| 533 | if (archived && success) { |
| 534 | setState(() => message = |
| 535 | 'خانواده بایگانی شد؛ دعوتها و ارتباطهای سرپرستی غیرفعال شدند. دادههای خصوصی افراد حذف نشدهاند.'); |
| 536 | return; |
| 537 | } |
| 538 | await refresh(); |
| 539 | if (!mounted || !active || widget.api.cacheNamespace != sync.store.scope) { |
| 540 | return; |
| 541 | } |
| 542 | setState(() => message ??= outcome); |
| 543 | } |
| 544 | |
| 545 | Future<void> createInvitation() async { |
| 546 | final recipient = contact.text.trim(); |
| 547 | if (recipient.isEmpty || recipient.length > 254) { |
| 548 | setState(() => message = 'ایمیل یا شماره گیرنده را تکمیل کن.'); |
| 549 | return; |
| 550 | } |
| 551 | final role = inviteRole, kind = contactKind; |
| 552 | Map<String, dynamic>? created; |
| 553 | await perform(() async { |
| 554 | created = await widget.api.createFamilyInvitation( |
| 555 | familyId: widget.familyId, |
| 556 | email: kind == 'email' ? recipient : null, |
| 557 | phone: kind == 'phone' ? recipient : null, |
| 558 | role: role); |
| 559 | await sync.scope(); |
| 560 | if (!_uuid(created?['id']) || |
| 561 | created?['invitationToken'] is! String || |
| 562 | (created!['invitationToken'] as String).isEmpty || |
| 563 | !_date(created?['expires_at'])) { |
| 564 | _invalid(); |
| 565 | } |
| 566 | }); |
| 567 | if (created == null || |
| 568 | !mounted || |
| 569 | !active || |
| 570 | !admin || |
| 571 | widget.api.cacheNamespace != sync.store.scope) { |
| 572 | return; |
| 573 | } |
| 574 | contact.clear(); |
| 575 | final token = created!['invitationToken'] as String; |
| 576 | await showDialog<void>( |
| 577 | context: context, |
| 578 | builder: (context) => Directionality( |
| 579 | textDirection: TextDirection.rtl, |
| 580 | child: AlertDialog( |
| 581 | title: const Text('دعوت در سرور ساخته شد'), |
| 582 | content: SingleChildScrollView( |
| 583 | child: Column( |
| 584 | mainAxisSize: MainAxisSize.min, |
| 585 | crossAxisAlignment: CrossAxisAlignment.start, |
| 586 | children: [ |
| 587 | const Text( |
| 588 | 'این کد را فقط به گیرنده موردنظر بده. ورود با تماس تأییدشده مطابق دعوت لازم است. کد در حافظه دستگاه ذخیره دائمی نمیشود.'), |
| 589 | SelectableText(token, textDirection: TextDirection.ltr), |
| 590 | const Text( |
| 591 | 'ارسال واقعی ایمیل یا پیامک تضمین نشده است؛ فراهمکننده پیامک باید جداگانه پیکربندی شود.'), |
| 592 | ])), |
| 593 | actions: [ |
| 594 | TextButton( |
| 595 | onPressed: () => Navigator.pop(context), |
| 596 | child: const Text('بستن')) |
| 597 | ]))); |
| 598 | } |
| 599 | |
| 600 | @override |
| 601 | Widget build(BuildContext context) => Directionality( |
| 602 | textDirection: TextDirection.rtl, |
| 603 | child: Scaffold( |
| 604 | appBar: AppBar(title: const Text('مدیریت خانواده'), actions: [ |
| 605 | IconButton( |
| 606 | key: const Key('family-management-refresh'), |
| 607 | tooltip: 'دریافت وضعیت تازه خانواده', |
| 608 | onPressed: busy ? null : () => refresh(), |
| 609 | icon: const Icon(Icons.refresh)) |
| 610 | ]), |
| 611 | body: ListView(padding: const EdgeInsets.all(16), children: [ |
| 612 | const Text( |
| 613 | 'نقش سرپرست یا بزرگسال بهتنهایی مدیریت خانواده نیست. مجوزهای این صفحه از عضویت فعلی سرور میآیند؛ اطلاعات خصوصی اعضا در این صفحه نمایش داده نمیشود.'), |
| 614 | if (loading || busy) const LinearProgressIndicator(), |
| 615 | Text(refreshed == null |
| 616 | ? 'وضعیت تازه خانواده در دسترس نیست.' |
| 617 | : 'آخرین دریافت: ${refreshed!.hour.toString().padLeft(2, '0')}:${refreshed!.minute.toString().padLeft(2, '0')}؛ تازهسازی هر ۳۰ ثانیه.'), |
| 618 | if (message != null) Text(message!), |
| 619 | if (family != null) ...[ |
| 620 | Text(family!['name'] as String, |
| 621 | style: Theme.of(context).textTheme.titleLarge), |
| 622 | Text( |
| 623 | 'نقش عضویت شما: ${familyRoleLabels[family!['role']]}${admin ? ' · مدیر خانواده' : ''}'), |
| 624 | if (admin) ...[ |
| 625 | TextField( |
| 626 | controller: name, |
| 627 | enabled: !busy, |
| 628 | maxLength: 120, |
| 629 | decoration: |
| 630 | const InputDecoration(labelText: 'نام خانواده')), |
| 631 | TextButton( |
| 632 | onPressed: busy |
| 633 | ? null |
| 634 | : () { |
| 635 | final value = name.text.trim(); |
| 636 | if (value.isEmpty || value.length > 120) { |
| 637 | setState(() => message = |
| 638 | 'نام خانواده باید بین ۱ تا ۱۲۰ نویسه باشد.'); |
| 639 | return; |
| 640 | } |
| 641 | perform(() async { |
| 642 | final result = await sync |
| 643 | .request('PATCH', '', body: {'name': value}); |
| 644 | if (result['id'] != widget.familyId || |
| 645 | result['name'] != value) { |
| 646 | _invalid(); |
| 647 | } |
| 648 | }); |
| 649 | }, |
| 650 | child: const Text('ذخیره نام خانواده')), |
| 651 | TextButton( |
| 652 | onPressed: busy |
| 653 | ? null |
| 654 | : () async { |
| 655 | if (!await confirm('بایگانی خانواده', |
| 656 | 'دسترسی خانوادگی، دعوتهای باز و ارتباطهای سرپرستی این خانواده غیرفعال میشوند. دادههای خصوصی اعضا حذف نمیشوند.')) { |
| 657 | return; |
| 658 | } |
| 659 | await perform(() async { |
| 660 | await sync.request('DELETE', ''); |
| 661 | }, archived: true); |
| 662 | }, |
| 663 | child: const Text('بایگانی خانواده')), |
| 664 | ], |
| 665 | const Divider(), |
| 666 | const Text('اعضای فعال خانواده'), |
| 667 | ...members.map((person) => Card( |
| 668 | child: Padding( |
| 669 | padding: const EdgeInsets.all(12), |
| 670 | child: Column( |
| 671 | crossAxisAlignment: CrossAxisAlignment.start, |
| 672 | children: [ |
| 673 | Text(person['display_name'] as String), |
| 674 | Text( |
| 675 | '${familyRoleLabels[person['role']]}${person['is_admin'] == true ? ' · مدیر' : ''}${person['account_disabled'] == true ? ' · حساب غیرفعال' : ''}'), |
| 676 | if (admin) ...[ |
| 677 | if (person['version'] != null && |
| 678 | person['account_disabled'] != true) |
| 679 | DropdownButtonFormField<String>( |
| 680 | key: Key( |
| 681 | 'family-member-role-${person['user_id']}'), |
| 682 | decoration: const InputDecoration( |
| 683 | labelText: 'تغییر نقش عضویت'), |
| 684 | hint: const Text('انتخاب نقش جدید'), |
| 685 | items: familyRoleLabels.entries |
| 686 | .where((entry) => |
| 687 | entry.key != person['role']) |
| 688 | .map((entry) => DropdownMenuItem( |
| 689 | value: entry.key, |
| 690 | child: Text(entry.value))) |
| 691 | .toList(), |
| 692 | onChanged: busy |
| 693 | ? null |
| 694 | : (value) async { |
| 695 | if (value == null || |
| 696 | !await confirm('تغییر نقش عضو', |
| 697 | 'نقش عضویت ${person['display_name']} به ${familyRoleLabels[value]} تغییر میکند. ارتباطهای سرپرستی ناسازگار ممکن است لغو شوند؛ تغییر سن و مجوزهای خصوصی را سرور کنترل میکند.')) { |
| 698 | return; |
| 699 | } |
| 700 | final body = { |
| 701 | 'mutationId': newMutationId(), |
| 702 | 'expectedVersion': |
| 703 | person['version'], |
| 704 | 'role': value |
| 705 | }; |
| 706 | await perform(() async { |
| 707 | await sync.submit( |
| 708 | 'role', |
| 709 | person['user_id'] as String, |
| 710 | body); |
| 711 | }); |
| 712 | }), |
| 713 | if (person['user_id'] != |
| 714 | widget.api.currentUserId && |
| 715 | person['role'] != 'teen_minor' && |
| 716 | person['account_disabled'] != true && |
| 717 | person['version'] != null && |
| 718 | self?['version'] != null) |
| 719 | TextButton( |
| 720 | onPressed: busy |
| 721 | ? null |
| 722 | : () async { |
| 723 | final actorVersion = |
| 724 | self!['version']; |
| 725 | if (!await confirm('انتقال مدیریت', |
| 726 | 'مدیریت به ${person['display_name']} منتقل میشود و دسترسی مدیریت شما برداشته خواهد شد. فقط بزرگسال فعال و مجاز میتواند مدیر شود.')) { |
| 727 | return; |
| 728 | } |
| 729 | final body = { |
| 730 | 'mutationId': newMutationId(), |
| 731 | 'targetUserId': person['user_id'], |
| 732 | 'expectedVersion': |
| 733 | person['version'], |
| 734 | 'expectedActorVersion': |
| 735 | actorVersion |
| 736 | }; |
| 737 | await perform(() async { |
| 738 | await sync.submit( |
| 739 | 'admin_transfer', |
| 740 | person['user_id'] as String, |
| 741 | body); |
| 742 | }); |
| 743 | }, |
| 744 | child: Text( |
| 745 | 'انتقال مدیریت به ${person['display_name']}')), |
| 746 | TextButton( |
| 747 | onPressed: busy |
| 748 | ? null |
| 749 | : () async { |
| 750 | if (!await confirm('پایان عضویت', |
| 751 | 'عضویت ${person['display_name']} و ارتباطهای سرپرستی مرتبط لغو میشود. اطلاعات خصوصی این فرد حذف نمیشود. حذف آخرین مدیر فعال مجاز نیست.')) { |
| 752 | return; |
| 753 | } |
| 754 | await perform(() async { |
| 755 | await sync.request('DELETE', |
| 756 | '/members/${person['user_id']}'); |
| 757 | }); |
| 758 | }, |
| 759 | child: Text( |
| 760 | 'پایان عضویت ${person['display_name']}')), |
| 761 | ], |
| 762 | ])))), |
| 763 | if (admin) ...[ |
| 764 | const Divider(), |
| 765 | const Text('دعوت عضو'), |
| 766 | DropdownButtonFormField<String>( |
| 767 | initialValue: contactKind, |
| 768 | decoration: |
| 769 | const InputDecoration(labelText: 'نوع تماس گیرنده'), |
| 770 | items: const [ |
| 771 | DropdownMenuItem(value: 'email', child: Text('ایمیل')), |
| 772 | DropdownMenuItem( |
| 773 | value: 'phone', child: Text('شماره تلفن')) |
| 774 | ], |
| 775 | onChanged: busy |
| 776 | ? null |
| 777 | : (value) => setState(() { |
| 778 | contactKind = value!; |
| 779 | contact.clear(); |
| 780 | })), |
| 781 | TextField( |
| 782 | controller: contact, |
| 783 | enabled: !busy, |
| 784 | textDirection: TextDirection.ltr, |
| 785 | keyboardType: contactKind == 'email' |
| 786 | ? TextInputType.emailAddress |
| 787 | : TextInputType.phone, |
| 788 | decoration: InputDecoration( |
| 789 | labelText: contactKind == 'email' |
| 790 | ? 'ایمیل گیرنده' |
| 791 | : 'شماره تلفن با کد کشور')), |
| 792 | DropdownButtonFormField<String>( |
| 793 | initialValue: inviteRole, |
| 794 | decoration: const InputDecoration(labelText: 'نقش موردنظر'), |
| 795 | items: familyRoleLabels.entries |
| 796 | .map((entry) => DropdownMenuItem( |
| 797 | value: entry.key, child: Text(entry.value))) |
| 798 | .toList(), |
| 799 | onChanged: busy |
| 800 | ? null |
| 801 | : (value) => setState(() => inviteRole = value!)), |
| 802 | FilledButton( |
| 803 | onPressed: busy ? null : createInvitation, |
| 804 | child: const Text('ساخت دعوت')), |
| 805 | const Text( |
| 806 | 'دعوت، دسترسی خودکار به داده خصوصی یا ارتباط سرپرستی ایجاد نمیکند. ایمیل اجباری نیست؛ ارسال پیامک وابسته به فراهمکننده جداگانه است.'), |
| 807 | const Text('دعوتهای باز'), |
| 808 | ...invitations.map((invite) => ListTile( |
| 809 | title: Text(invite['recipientHint'] as String), |
| 810 | subtitle: Text( |
| 811 | '${familyRoleLabels[invite['intendedRole']]} · ${invite['status'] == 'expired' ? 'منقضیشده' : 'منتظر پذیرش'} · تا ${invite['expiresAt']}'), |
| 812 | trailing: TextButton( |
| 813 | onPressed: busy |
| 814 | ? null |
| 815 | : () async { |
| 816 | if (!await confirm('لغو دعوت', |
| 817 | 'کد این دعوت دیگر قابل پذیرش نخواهد بود.')) { |
| 818 | return; |
| 819 | } |
| 820 | await perform(() async { |
| 821 | await sync.submit('invitation_revoke', |
| 822 | invite['id'] as String, { |
| 823 | 'mutationId': newMutationId(), |
| 824 | 'expectedVersion': invite['version'], |
| 825 | 'action': 'revoke' |
| 826 | }); |
| 827 | }); |
| 828 | }, |
| 829 | child: const Text('لغو دعوت')))), |
| 830 | if (nextInvitationCursor != null) |
| 831 | TextButton( |
| 832 | onPressed: busy |
| 833 | ? null |
| 834 | : () { |
| 835 | invitationCursor = nextInvitationCursor; |
| 836 | refresh(); |
| 837 | }, |
| 838 | child: const Text('دعوتهای بعدی')), |
| 839 | if (invitationCursor != null) |
| 840 | TextButton( |
| 841 | onPressed: |
| 842 | busy ? null : () => refresh(firstInvitations: true), |
| 843 | child: const Text('صفحه اول دعوتها')), |
| 844 | const Divider(), |
| 845 | const Text('ارتباط مجاز سرپرست و فرزند'), |
| 846 | const Text( |
| 847 | 'این فرم فقط ارتباط را فعال یا لغو میکند؛ هیچ اطلاعات خصوصی یا وضعیت مطالعه پنهانی را نمایش نمیدهد.'), |
| 848 | DropdownButtonFormField<String>( |
| 849 | initialValue: guardianId, |
| 850 | decoration: const InputDecoration(labelText: 'سرپرست'), |
| 851 | items: members |
| 852 | .where((person) => |
| 853 | person['role'] == 'parent_guardian' && |
| 854 | person['account_disabled'] != true) |
| 855 | .map((person) => DropdownMenuItem( |
| 856 | value: person['user_id'] as String, |
| 857 | child: Text(person['display_name'] as String))) |
| 858 | .toList(), |
| 859 | onChanged: busy |
| 860 | ? null |
| 861 | : (value) => setState(() => guardianId = value)), |
| 862 | DropdownButtonFormField<String>( |
| 863 | initialValue: childId, |
| 864 | decoration: const InputDecoration(labelText: 'فرزند'), |
| 865 | items: members |
| 866 | .where((person) => |
| 867 | person['role'] == 'teen_minor' && |
| 868 | person['account_disabled'] != true) |
| 869 | .map((person) => DropdownMenuItem( |
| 870 | value: person['user_id'] as String, |
| 871 | child: Text(person['display_name'] as String))) |
| 872 | .toList(), |
| 873 | onChanged: busy |
| 874 | ? null |
| 875 | : (value) => setState(() => childId = value)), |
| 876 | Wrap( |
| 877 | spacing: 8, |
| 878 | children: ['POST', 'DELETE'] |
| 879 | .map((method) => TextButton( |
| 880 | onPressed: busy || |
| 881 | guardianId == null || |
| 882 | childId == null |
| 883 | ? null |
| 884 | : () async { |
| 885 | final body = { |
| 886 | 'guardianUserId': guardianId, |
| 887 | 'minorUserId': childId |
| 888 | }; |
| 889 | if (!await confirm( |
| 890 | method == 'POST' |
| 891 | ? 'فعالکردن ارتباط سرپرستی' |
| 892 | : 'لغو ارتباط سرپرستی', |
| 893 | 'مجوزهای خانوادگی همین سرپرست و فرزند طبق سیاست سرور تغییر میکنند؛ دادههای خصوصی خودکار به اشتراک گذاشته نمیشوند.')) { |
| 894 | return; |
| 895 | } |
| 896 | await perform(() async { |
| 897 | await sync.request(method, '/guardians', |
| 898 | body: body); |
| 899 | }); |
| 900 | }, |
| 901 | child: Text(method == 'POST' |
| 902 | ? 'فعالکردن ارتباط' |
| 903 | : 'لغو ارتباط'))) |
| 904 | .toList()), |
| 905 | ], |
| 906 | ], |
| 907 | if (pending.isNotEmpty) ...[ |
| 908 | const Divider(), |
| 909 | Text( |
| 910 | '${pending.length} عملیات نسخهدار بدون تأیید نهایی در صف دستگاه است. فقط شناسه و نسخه نگهداری میشود؛ ارسال خودکار انجام نمیشود.'), |
| 911 | ...pending.map((queued) => ListTile( |
| 912 | title: Text(queued['operation'] == 'role' |
| 913 | ? 'تغییر نقش عضویت' |
| 914 | : queued['operation'] == 'admin_transfer' |
| 915 | ? 'انتقال مدیریت' |
| 916 | : 'لغو دعوت'), |
| 917 | subtitle: const Text( |
| 918 | 'تلاش دستی با همان درخواست؛ ممکن است قبلاً در سرور اجرا شده باشد.'), |
| 919 | trailing: TextButton( |
| 920 | onPressed: busy || family == null |
| 921 | ? null |
| 922 | : () => perform(() async { |
| 923 | await sync.retry(queued); |
| 924 | }), |
| 925 | child: const Text('دریافت دوباره تأیید')))), |
| 926 | ], |
| 927 | ]))); |
| 928 | } |