LifeMate — Personal, Family & Learning Companion
docs/offline-data-rescue-options
chore/phase1-repository-cleanup
deploy/stable-web-apk
deployment-static
design/mobile-accessibility-v2
design/mobile-navigation-review
docs/child-education-access-decision
docs/offline-data-rescue-options
docs/owner-guide-and-delivery-plan
docs/phase1-policy-options
docs/public-review-live-2026-10-15
feat/aparat-learning-library
feat/child-device-safety
feat/child-identity-schema
feat/flutter-mobile-navigation
feat/learning-content-operations
feat/local-signing-preflight
feat/online-family-stage0
feat/personal-encrypted-recovery
feat/private-planner-series-api
feat/public-review-page
feat/standalone-weekly-planner
feat/weekly-planner-android
final-feature-1/iran-family-school
fix/auth-abuse-expiry-safety
fix/auth-expiry-after-lock
fix/backend-request-safety
fix/lifeguide-bootstrap-naming-ci
fix/lifeguide-pages-qa-base-preflight
fix/lifeguide-qa-pages-env-deployment
fix/local-task-persistence
fix/managed-child-session-boundary
fix/personal-jalali-dates
fix/personal-notification-controls
fix/personal-upgrade-delivery-guard
fix/sms-approval-gates
fix/study-duration-display
infra/cloudflare-neon-migration
infra/lifeguide-cloudflare-qa
infra/lifeguide-github-pages-qa
infra/lifeguide-supabase-qa
main
phase-1/foundation-completion
phase-2/product-foundation-identity
phase-3/planner-school-family-core
phase-4/ai-learning-wellbeing
phase-5/hardening-observability-release
test/android-reminder-acceptance
test/personal-notification-settings
test/personal-recovery-acceptance
test/role-entry-apk
| 1 | import 'dart:async'; |
| 2 | import 'dart:convert'; |
| 3 | |
| 4 | import 'api.dart'; |
| 5 | import 'offline_store.dart'; |
| 6 | import 'learning_feedback_ui.dart' show feedbackCategories; |
| 7 | |
| 8 | const contentReviewStatuses = <String, String>{ |
| 9 | 'received': 'دریافتشده', |
| 10 | 'triaged': 'بررسی اولیه', |
| 11 | 'planned': 'در برنامه بررسی و توسعه', |
| 12 | 'declined': 'پذیرفتهنشده', |
| 13 | 'released': 'انتشار ثبتشده', |
| 14 | }; |
| 15 | const contentReviewTransitions = <String, List<String>>{ |
| 16 | 'received': ['triaged', 'declined'], |
| 17 | 'triaged': ['planned', 'declined'], |
| 18 | 'planned': ['triaged', 'declined'], |
| 19 | 'declined': ['triaged'], |
| 20 | }; |
| 21 | const _permissions = {'feedback.read', 'feedback.review', 'brief.prepare'}; |
| 22 | final _uuidPattern = RegExp(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$'); |
| 23 | bool _uuid(dynamic value) => value is String && _uuidPattern.hasMatch(value); |
| 24 | bool _version(dynamic value) => |
| 25 | value is int && value > 0 && value <= 2147483647; |
| 26 | bool _date(dynamic value) => |
| 27 | value is String && DateTime.tryParse(value) != null; |
| 28 | bool _text(dynamic value, [int limit = 2000]) => |
| 29 | value is String && |
| 30 | value.trim().isNotEmpty && |
| 31 | value.length <= limit && |
| 32 | !value.contains('\u0000'); |
| 33 | bool _exact(Map value, Set<String> keys) => |
| 34 | value.length == keys.length && value.keys.every(keys.contains); |
| 35 | Never _invalid() => throw const ApiException(502, 'invalid_content_response'); |
| 36 | Map<String, dynamic> _freeze(Map value) => |
| 37 | Map<String, dynamic>.from(jsonDecode(jsonEncode(value)) as Map); |
| 38 | |
| 39 | /// Reviewer mutations retain only IDs, versions and requested statuses. There |
| 40 | /// is no local inbox, permission cache, chosen summary or automatic offline send. |
| 41 | class ContentReviewSync { |
| 42 | ContentReviewSync(this.api, {OfflineStore? store}) |
| 43 | : store = store ?? OfflineStore.forApi(api); |
| 44 | final HttpIdentityApi api; |
| 45 | final OfflineStore store; |
| 46 | static final _tails = <String, Future<void>>{}; |
| 47 | |
| 48 | Future<void> _scope() async { |
| 49 | if (api.cacheNamespace != store.scope) { |
| 50 | throw const ApiException(401, 'cache_scope_closed'); |
| 51 | } |
| 52 | await store.readQueue(); // Rejects handles from an invalidated generation. |
| 53 | if (api.cacheNamespace != store.scope) { |
| 54 | throw const ApiException(401, 'cache_scope_closed'); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | Future<T> _serial<T>(Future<T> Function() operation) async { |
| 59 | final previous = _tails[store.scope]; |
| 60 | final release = Completer<void>(); |
| 61 | _tails[store.scope] = release.future; |
| 62 | if (previous != null) await previous; |
| 63 | try { |
| 64 | await _scope(); |
| 65 | final result = await operation(); |
| 66 | await _scope(); |
| 67 | return result; |
| 68 | } finally { |
| 69 | if (identical(_tails[store.scope], release.future)) { |
| 70 | _tails.remove(store.scope); |
| 71 | } |
| 72 | release.complete(); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | Future<Set<String>> capabilities() async { |
| 77 | await _scope(); |
| 78 | final response = |
| 79 | await api.requestJson('GET', '/v1/me/content-capabilities'); |
| 80 | await _scope(); |
| 81 | if (!_exact(response, {'permissions'}) || |
| 82 | response['permissions'] is! List) { |
| 83 | _invalid(); |
| 84 | } |
| 85 | final values = response['permissions'] as List; |
| 86 | if (values.any((value) => !_permissions.contains(value)) || |
| 87 | values.toSet().length != values.length) { |
| 88 | _invalid(); |
| 89 | } |
| 90 | return Set<String>.from(values); |
| 91 | } |
| 92 | |
| 93 | Future<void> _require(String permission) async { |
| 94 | final allowed = await capabilities(); |
| 95 | if (!allowed.contains('feedback.read') || !allowed.contains(permission)) { |
| 96 | throw const ApiException(403, 'content_permission_required'); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | Map<String, dynamic> _feedback(dynamic raw) { |
| 101 | if (raw is! Map || |
| 102 | !_exact(raw, { |
| 103 | 'id', |
| 104 | 'unitId', |
| 105 | 'category', |
| 106 | 'summary', |
| 107 | 'status', |
| 108 | 'version', |
| 109 | 'createdAt', |
| 110 | 'updatedAt' |
| 111 | }) || |
| 112 | !_uuid(raw['id']) || |
| 113 | (raw['unitId'] != null && !_uuid(raw['unitId'])) || |
| 114 | !feedbackCategories.containsKey(raw['category']) || |
| 115 | !_text(raw['summary'], 1000) || |
| 116 | !contentReviewStatuses.containsKey(raw['status']) || |
| 117 | !_version(raw['version']) || |
| 118 | !_date(raw['createdAt']) || |
| 119 | !_date(raw['updatedAt'])) { |
| 120 | _invalid(); |
| 121 | } |
| 122 | return _freeze(raw); |
| 123 | } |
| 124 | |
| 125 | Future<Map<String, dynamic>> inbox({String? status, String? cursor}) async { |
| 126 | await _scope(); |
| 127 | if ((status != null && !contentReviewStatuses.containsKey(status)) || |
| 128 | (cursor != null && !_uuid(cursor))) { |
| 129 | throw const ApiException(400, 'invalid_content_query'); |
| 130 | } |
| 131 | final query = Uri(queryParameters: { |
| 132 | 'limit': '20', |
| 133 | if (status != null) 'status': status, |
| 134 | if (cursor != null) 'cursor': cursor |
| 135 | }).query; |
| 136 | final response = |
| 137 | await api.requestJson('GET', '/v1/content-review/feedback?$query'); |
| 138 | await _scope(); |
| 139 | if (!_exact(response, {'feedback', 'nextCursor', 'total'}) || |
| 140 | response['feedback'] is! List || |
| 141 | (response['feedback'] as List).length > 20 || |
| 142 | response['total'] is! int || |
| 143 | response['total'] < 0 || |
| 144 | (response['nextCursor'] != null && !_uuid(response['nextCursor']))) { |
| 145 | _invalid(); |
| 146 | } |
| 147 | final rows = (response['feedback'] as List).map(_feedback).toList(); |
| 148 | if (rows.map((row) => row['id']).toSet().length != rows.length || |
| 149 | rows.any((row) => status != null && row['status'] != status) || |
| 150 | response['total'] < rows.length) { |
| 151 | _invalid(); |
| 152 | } |
| 153 | return {...response, 'feedback': rows}; |
| 154 | } |
| 155 | |
| 156 | Map<String, dynamic> _reviewBody(Map value) { |
| 157 | if (!_exact(value, {'mutationId', 'expectedVersion', 'status'}) || |
| 158 | !_uuid(value['mutationId']) || |
| 159 | !_version(value['expectedVersion']) || |
| 160 | !const {'triaged', 'planned', 'declined'}.contains(value['status'])) { |
| 161 | throw const ApiException(400, 'invalid_review_mutation'); |
| 162 | } |
| 163 | return _freeze(value); |
| 164 | } |
| 165 | |
| 166 | Map<String, dynamic> _briefBody(Map value) { |
| 167 | if (!_exact(value, {'mutationId', 'feedback'}) || |
| 168 | !_uuid(value['mutationId']) || |
| 169 | value['feedback'] is! List || |
| 170 | (value['feedback'] as List).isEmpty || |
| 171 | (value['feedback'] as List).length > 20) { |
| 172 | throw const ApiException(400, 'invalid_brief_mutation'); |
| 173 | } |
| 174 | final ids = <String>{}; |
| 175 | for (final row in value['feedback'] as List) { |
| 176 | if (row is! Map || |
| 177 | !_exact(row, {'id', 'expectedVersion'}) || |
| 178 | !_uuid(row['id']) || |
| 179 | !_version(row['expectedVersion']) || |
| 180 | !ids.add(row['id'] as String)) { |
| 181 | throw const ApiException(400, 'invalid_brief_mutation'); |
| 182 | } |
| 183 | } |
| 184 | return _freeze(value); |
| 185 | } |
| 186 | |
| 187 | Future<List<Map<String, dynamic>>> pending() async { |
| 188 | await _scope(); |
| 189 | final rows = (await store.readQueue()) |
| 190 | .where((row) => |
| 191 | row['entityType'] == 'content_review' || |
| 192 | row['entityType'] == 'content_brief') |
| 193 | .toList(); |
| 194 | await _scope(); |
| 195 | return rows; |
| 196 | } |
| 197 | |
| 198 | Future<Map<String, dynamic>> review(String id, Map<String, dynamic> body) { |
| 199 | final frozen = _reviewBody(body); |
| 200 | if (!_uuid(id)) throw const ApiException(400, 'invalid_review_mutation'); |
| 201 | return _serial(() async { |
| 202 | await _require('feedback.review'); // No new offline reviewer change. |
| 203 | final mutation = { |
| 204 | 'id': frozen['mutationId'], |
| 205 | 'entityId': id, |
| 206 | 'entityType': 'content_review', |
| 207 | 'operation': 'review', |
| 208 | 'payload': frozen |
| 209 | }; |
| 210 | await store.enqueue(mutation); |
| 211 | return _send(mutation); |
| 212 | }); |
| 213 | } |
| 214 | |
| 215 | Future<Map<String, dynamic>> prepareBrief(Map<String, dynamic> body) { |
| 216 | final frozen = _briefBody(body); |
| 217 | return _serial(() async { |
| 218 | await _require('brief.prepare'); |
| 219 | final mutation = { |
| 220 | 'id': frozen['mutationId'], |
| 221 | 'entityId': frozen['mutationId'], |
| 222 | 'entityType': 'content_brief', |
| 223 | 'operation': 'prepare', |
| 224 | 'payload': frozen |
| 225 | }; |
| 226 | await store.enqueue(mutation); |
| 227 | return _send(mutation); |
| 228 | }); |
| 229 | } |
| 230 | |
| 231 | Future<Map<String, dynamic>> retry(Map<String, dynamic> pending) => |
| 232 | _serial(() async { |
| 233 | final stored = (await this.pending()) |
| 234 | .where((row) => row['id'] == pending['id']) |
| 235 | .firstOrNull; |
| 236 | if (stored == null || jsonEncode(stored) != jsonEncode(pending)) { |
| 237 | throw const ApiException(409, 'content_pending_changed'); |
| 238 | } |
| 239 | await _require(stored['entityType'] == 'content_review' |
| 240 | ? 'feedback.review' |
| 241 | : 'brief.prepare'); |
| 242 | return _send(stored); |
| 243 | }); |
| 244 | |
| 245 | Future<Map<String, dynamic>> _send(Map<String, dynamic> mutation) async { |
| 246 | final review = mutation['entityType'] == 'content_review'; |
| 247 | final body = review |
| 248 | ? _reviewBody(mutation['payload'] as Map) |
| 249 | : _briefBody(mutation['payload'] as Map); |
| 250 | await _scope(); |
| 251 | final response = await api.requestJson( |
| 252 | review ? 'PATCH' : 'POST', |
| 253 | review |
| 254 | ? '/v1/content-review/feedback/${Uri.encodeComponent(mutation['entityId'] as String)}' |
| 255 | : '/v1/content-review/briefs', |
| 256 | body: body); |
| 257 | await _scope(); |
| 258 | final ack = response['acknowledgement']; |
| 259 | if (ack is! Map || |
| 260 | !_exact( |
| 261 | ack, {'mutationId', review ? 'feedbackId' : 'briefId', 'status'}) || |
| 262 | ack['mutationId'] != mutation['id'] || |
| 263 | !const {'accepted', 'already_applied'}.contains(ack['status'])) { |
| 264 | _invalid(); |
| 265 | } |
| 266 | String acceptedAt; |
| 267 | Map<String, dynamic>? brief; |
| 268 | if (review) { |
| 269 | if (!_exact(response, {'feedback', 'acknowledgement'})) _invalid(); |
| 270 | final row = _feedback(response['feedback']); |
| 271 | if (row['id'] != mutation['entityId'] || |
| 272 | ack['feedbackId'] != row['id'] || |
| 273 | row['version'] < (body['expectedVersion'] as int) + 1 || |
| 274 | (ack['status'] == 'accepted' && |
| 275 | (row['version'] != (body['expectedVersion'] as int) + 1 || |
| 276 | row['status'] != body['status']))) { |
| 277 | _invalid(); |
| 278 | } |
| 279 | acceptedAt = row['updatedAt'] as String; |
| 280 | // Do not return/store the summary in the durable mutation result. |
| 281 | } else { |
| 282 | if (!_exact(response, {'brief', 'acknowledgement'})) _invalid(); |
| 283 | brief = _brief(response['brief']); |
| 284 | if (ack['briefId'] != brief['id'] || |
| 285 | brief['sourceCount'] != (body['feedback'] as List).length) { |
| 286 | _invalid(); |
| 287 | } |
| 288 | acceptedAt = brief['createdAt'] as String; |
| 289 | } |
| 290 | await store.acknowledge(mutation['id'] as String, acceptedAt: acceptedAt); |
| 291 | return {'acknowledgement': _freeze(ack), if (brief != null) 'brief': brief}; |
| 292 | } |
| 293 | |
| 294 | Map<String, dynamic> _brief(dynamic raw) { |
| 295 | if (raw is! Map || |
| 296 | !_exact(raw, { |
| 297 | 'id', |
| 298 | 'title', |
| 299 | 'createdAt', |
| 300 | 'sourceCount', |
| 301 | 'categories', |
| 302 | 'units', |
| 303 | 'tasks', |
| 304 | 'notice' |
| 305 | }) || |
| 306 | !_uuid(raw['id']) || |
| 307 | raw['title'] != 'پیشنهاد بررسی و توسعه محتوای آموزشی' || |
| 308 | !_date(raw['createdAt']) || |
| 309 | raw['sourceCount'] is! int || |
| 310 | raw['sourceCount'] < 1 || |
| 311 | raw['sourceCount'] > 20 || |
| 312 | raw['categories'] is! List || |
| 313 | raw['units'] is! List || |
| 314 | (raw['units'] as List).length > raw['sourceCount'] || |
| 315 | raw['tasks'] is! List || |
| 316 | jsonEncode(raw['tasks']) != |
| 317 | jsonEncode(const [ |
| 318 | 'نسخه رسمی کتاب و هدف یادگیری این درس را بررسی کنید.', |
| 319 | 'محتوای پیشنهادی و سؤالهای تمرینی را بهطور کامل بازبینی کنید.', |
| 320 | 'برای تغییر پیشنهادی معیار پذیرش، آزمون و PR مستقل تهیه کنید.', |
| 321 | 'انتشار محتوا و استقرار فقط پس از بازبینی و مجوز جداگانه انجام شود.' |
| 322 | ]) || |
| 323 | raw['notice'] != |
| 324 | 'این پیشنهاد ساختاری فاقد متن بازخورد و اطلاعات خصوصی است؛ تأیید محتوا یا دستور انتشار نیست.') { |
| 325 | _invalid(); |
| 326 | } |
| 327 | var count = 0; |
| 328 | final categories = <String>{}; |
| 329 | for (final row in raw['categories'] as List) { |
| 330 | if (row is! Map || |
| 331 | !_exact(row, {'category', 'count'}) || |
| 332 | !feedbackCategories.containsKey(row['category']) || |
| 333 | row['count'] is! int || |
| 334 | row['count'] < 1 || |
| 335 | !categories.add(row['category'] as String)) { |
| 336 | _invalid(); |
| 337 | } |
| 338 | count += row['count'] as int; |
| 339 | } |
| 340 | if (count != raw['sourceCount']) _invalid(); |
| 341 | final units = <String>{}; |
| 342 | for (final row in raw['units'] as List) { |
| 343 | if (row is! Map || |
| 344 | !_exact(row, { |
| 345 | 'id', |
| 346 | 'title', |
| 347 | 'bookCode', |
| 348 | 'bookTitle', |
| 349 | 'gradeLevel', |
| 350 | 'trackCode', |
| 351 | 'editionYear', |
| 352 | 'editionStatus' |
| 353 | }) || |
| 354 | !_uuid(row['id']) || |
| 355 | !units.add(row['id'] as String) || |
| 356 | !_text(row['title']) || |
| 357 | !_text(row['bookTitle']) || |
| 358 | !_text(row['bookCode'], 80) || |
| 359 | row['gradeLevel'] is! int || |
| 360 | row['gradeLevel'] < 1 || |
| 361 | row['gradeLevel'] > 12 || |
| 362 | row['trackCode'] is! List || |
| 363 | (row['trackCode'] as List).any((value) => !const { |
| 364 | 'common', |
| 365 | 'math', |
| 366 | 'experimental', |
| 367 | 'humanities' |
| 368 | }.contains(value)) || |
| 369 | (row['editionYear'] != null && !_text(row['editionYear'], 40)) || |
| 370 | !const {'verified', 'unverified'}.contains(row['editionStatus'])) { |
| 371 | _invalid(); |
| 372 | } |
| 373 | } |
| 374 | return _freeze(raw); |
| 375 | } |
| 376 | |
| 377 | Future<Map<String, dynamic>> readBrief(String id) async { |
| 378 | if (!_uuid(id)) throw const ApiException(400, 'invalid_brief_id'); |
| 379 | await _require('brief.prepare'); |
| 380 | final response = await api.requestJson( |
| 381 | 'GET', '/v1/content-review/briefs/${Uri.encodeComponent(id)}'); |
| 382 | await _scope(); |
| 383 | if (!_exact(response, {'brief'})) _invalid(); |
| 384 | final brief = _brief(response['brief']); |
| 385 | if (brief['id'] != id) _invalid(); |
| 386 | return brief; |
| 387 | } |
| 388 | } |