LifeMate — Personal, Family & Learning Companion

feat/learning-content-operations
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
dart 944 lines 28.2 KB
Raw
1 import 'dart:async';
2 import 'dart:convert';
3
4 import 'package:http/http.dart' as http;
5 import 'runtime_config.dart';
6 import 'runtime_http_client.dart';
7 import 'session_store.dart';
8 import 'web_instance.dart';
9
10 abstract class IdentityApi {
11 String? get accessToken;
12
13 Future<void> register({
14 required String displayName,
15 required String email,
16 required String password,
17 });
18
19 Future<void> verifyEmail(String token, {required String newPassword});
20 Future<void> login(String email, String password);
21 Future<void> forgotPassword(String email);
22 Future<void> resetPassword(String token, String newPassword);
23 Future<void> changePassword(String currentPassword, String newPassword);
24 Future<Map<String, dynamic>> getProfile();
25 Future<Map<String, dynamic>> updateProfile({
26 String? displayName,
27 String? birthDate,
28 String? themePreference,
29 String? profileCategory,
30 });
31 Future<List<Map<String, dynamic>>> listFamilies();
32 Future<List<Map<String, dynamic>>> listFamilyMembers(String familyId);
33 Future<Map<String, dynamic>> createFamily(String name, {String? role});
34 Future<void> inviteMember({
35 required String familyId,
36 required String email,
37 required String role,
38 String? themePreference,
39 });
40 Future<void> acceptInvitation(String token);
41 Future<void> setGuardian({
42 required String familyId,
43 required String guardianUserId,
44 required String minorUserId,
45 });
46
47 Future<List<Map<String, dynamic>>> getToday({
48 required DateTime from,
49 required DateTime to,
50 });
51 Future<List<Map<String, dynamic>>> listPlanItems({
52 DateTime? from,
53 DateTime? to,
54 String? kind,
55 });
56 Future<Map<String, dynamic>> createPlanItem(Map<String, dynamic> data);
57 Future<Map<String, dynamic>> updatePlanItem(
58 String itemId,
59 Map<String, dynamic> data,
60 );
61 Future<List<Map<String, dynamic>>> listLifeContexts();
62 Future<Map<String, dynamic>> createLifeContext({
63 required String kind,
64 required String title,
65 });
66 Future<Map<String, dynamic>> createAcademicYear(Map<String, dynamic> data);
67 Future<Map<String, dynamic>> createAcademicTerm(
68 String yearId,
69 Map<String, dynamic> data,
70 );
71 Future<Map<String, dynamic>> createSubject(
72 String termId,
73 Map<String, dynamic> data,
74 );
75 Future<Map<String, dynamic>> createClassSession(
76 String subjectId,
77 Map<String, dynamic> data,
78 );
79 Future<Map<String, dynamic>> getSchoolOverview(String studentUserId);
80 Future<List<Map<String, dynamic>>> getTimetable(String studentUserId);
81 Future<Map<String, dynamic>> setGrade(
82 String itemId, {
83 required num points,
84 required num outOf,
85 });
86 Future<List<Map<String, dynamic>>> claimDueReminders();
87 Future<List<Map<String, dynamic>>> getFamilyCalendar(String familyId);
88 Future<Map<String, dynamic>> getChildSupportSummary(
89 String familyId,
90 String studentUserId,
91 );
92 Future<Map<String, dynamic>> submitSyncMutations(
93 List<Map<String, dynamic>> mutations,
94 );
95
96 Future<Map<String, dynamic>> createLearningGoal({
97 required String title,
98 String? target,
99 String? subjectId,
100 });
101 Future<List<Map<String, dynamic>>> listLearningGoals();
102 Future<Map<String, dynamic>> createLearningCheckin({
103 String? learningGoalId,
104 required int confidence,
105 required int difficulty,
106 String? note,
107 });
108 Future<Map<String, dynamic>> createWellbeingCheckin({
109 required int mood,
110 required int energy,
111 required int stress,
112 String? note,
113 String visibility,
114 });
115 Future<List<Map<String, dynamic>>> listWellbeingCheckins();
116 Future<Map<String, dynamic>> createAiSession(String kind);
117 Future<Map<String, dynamic>> sendAiMessage(
118 String sessionId,
119 String message,
120 );
121 Future<Map<String, dynamic>> getGuardianWellbeingSummary(
122 String familyId,
123 String minorUserId,
124 );
125 Future<Map<String, dynamic>> requestFamilyGuidance(
126 String familyId,
127 String minorUserId,
128 String question,
129 );
130 }
131
132 class ApiException implements Exception {
133 const ApiException(this.statusCode, this.code, {this.details = const {}});
134 final int statusCode;
135 final String code;
136 final Map<String, dynamic> details;
137
138 @override
139 String toString() => 'ApiException($statusCode, $code)';
140 }
141
142 class HttpIdentityApi implements IdentityApi {
143 HttpIdentityApi({
144 String? baseUrl,
145 http.Client? client,
146 SessionStore? sessionStore,
147 this.onSessionChanged,
148 this.onScopeDiscarded,
149 this.onScopeQuarantined,
150 }) : baseUrl = normalizeApiUrl(
151 baseUrl ?? (throw ArgumentError('API configuration is required.'))),
152 _client = client ?? createRuntimeHttpClient(),
153 _sessionStore = sessionStore == null
154 ? createSessionStore()
155 : sessionStore is SerializedSessionStore
156 ? sessionStore
157 : SerializedSessionStore(sessionStore);
158
159 final String baseUrl;
160 final http.Client _client;
161 final SessionStore _sessionStore;
162 void Function()? onSessionChanged;
163 Future<void> Function(String)? onScopeDiscarded;
164 Future<void> Function(String)? onScopeQuarantined;
165 bool hasQuarantinedSession = false;
166 Future<void>? _refreshing;
167 int _sessionGeneration = 0;
168 String? currentUserId;
169 String get endpointIdentity => baseUrl;
170 String? get cacheNamespace => accessToken == null || currentUserId == null
171 ? null
172 : '$endpointIdentity|$currentUserId';
173
174 @override
175 String? accessToken;
176 String? _refreshToken;
177
178 Uri _uri(String path) {
179 if (!path.startsWith('/') ||
180 path.startsWith('//') ||
181 path.contains('://')) {
182 throw ArgumentError('Requests must use a path on the configured API.');
183 }
184 return Uri.parse('$baseUrl$path');
185 }
186
187 Future<Map<String, dynamic>> requestJson(String method, String path,
188 {Map<String, dynamic>? body, bool auth = true}) =>
189 _json(method, path, body: body, auth: auth);
190
191 void close() {
192 _sessionGeneration++;
193 _client.close();
194 }
195
196 Future<void> _acceptTokens(Map<String, dynamic> result,
197 {int? generation}) async {
198 if (generation != null && generation != _sessionGeneration) {
199 throw const ApiException(401, 'session_expired');
200 }
201 final access = result['accessToken'];
202 final refresh = result['refreshToken'];
203 String? userId;
204 try {
205 final claims = jsonDecode(utf8.decode(base64Url.decode(
206 base64Url.normalize((access as String).split('.')[1])))) as Map;
207 userId = claims['sub'] as String?;
208 } catch (_) {
209 throw const ApiException(502, 'invalid_api_response');
210 }
211 if (refresh is! String ||
212 refresh.isEmpty ||
213 userId == null ||
214 userId.isEmpty) {
215 throw const ApiException(502, 'invalid_api_response');
216 }
217 if (currentUserId != null && currentUserId != userId) {
218 await _clearSession();
219 }
220 if (generation != null && generation != _sessionGeneration) {
221 throw const ApiException(401, 'session_expired');
222 }
223 await _sessionStore.write(jsonEncode({
224 'endpoint': endpointIdentity,
225 'refreshToken': refresh,
226 'userId': userId
227 }));
228 if (generation != null && generation != _sessionGeneration) {
229 throw const ApiException(401, 'session_expired');
230 }
231 accessToken = access;
232 _refreshToken = refresh;
233 currentUserId = userId;
234 hasQuarantinedSession = false;
235 onSessionChanged?.call();
236 }
237
238 Future<bool> restoreSession() async {
239 final raw = await _sessionStore.read();
240 if (raw == null) return false;
241 late Map<String, dynamic> session;
242 try {
243 session = jsonDecode(raw) as Map<String, dynamic>;
244 } catch (_) {
245 await _expireSession();
246 return false;
247 }
248 if (session['endpoint'] != endpointIdentity ||
249 session['refreshToken'] is! String ||
250 (session['refreshToken'] as String).isEmpty ||
251 session['userId'] is! String) {
252 final oldScope =
253 session['endpoint'] is String && session['userId'] is String
254 ? '${session['endpoint']}|${session['userId']}'
255 : null;
256 await _expireSession(scopeOverride: oldScope);
257 return false;
258 }
259 _refreshToken = session['refreshToken'] as String;
260 currentUserId = session['userId'] as String;
261 try {
262 await _refresh();
263 return true;
264 } on ApiException catch (error) {
265 if (error.statusCode == 401 || error.statusCode == 403) return false;
266 rethrow;
267 }
268 }
269
270 Future<void> logout({bool revoke = true}) async {
271 final token = _refreshToken;
272 _sessionGeneration++;
273 hasQuarantinedSession = false;
274 await _clearSession();
275 if (revoke && token != null) {
276 try {
277 await _json('POST', '/v1/auth/logout',
278 body: {'refreshToken': token}, retry: false);
279 } catch (_) {/* Local credentials are cleared even when offline. */}
280 }
281 }
282
283 /// Forced expiry never represents user consent to erase unsent work.
284 Future<void> _expireSession({String? scopeOverride}) async {
285 _sessionGeneration++;
286 hasQuarantinedSession = true;
287 await _clearSession(quarantine: true, scopeOverride: scopeOverride);
288 }
289
290 Future<void> _clearSession(
291 {bool quarantine = false, String? scopeOverride}) async {
292 final scope = scopeOverride ??
293 (currentUserId == null ? null : '$endpointIdentity|$currentUserId');
294 accessToken = null;
295 _refreshToken = null;
296 currentUserId = null;
297 Object? failure;
298 StackTrace? failureStack;
299 Future<void>? quarantinePending;
300 // Invalidate old cache handles synchronously, before notifying the signed
301 // out UI or awaiting credential storage. Quarantine performs no disk writes.
302 try {
303 if (quarantine && scope != null) {
304 quarantinePending = onScopeQuarantined?.call(scope);
305 }
306 } catch (error, stack) {
307 failure = error;
308 failureStack = stack;
309 }
310 onSessionChanged?.call();
311 try {
312 await _sessionStore.clear();
313 } catch (error, stack) {
314 failure ??= error;
315 failureStack ??= stack;
316 }
317 try {
318 if (quarantine) {
319 await quarantinePending;
320 } else if (scope != null) {
321 await onScopeDiscarded?.call(scope);
322 }
323 } catch (error, stack) {
324 failure ??= error;
325 failureStack ??= stack;
326 }
327 if (failure != null) {
328 Error.throwWithStackTrace(failure, failureStack!);
329 }
330 }
331
332 Map<String, String> _headers({bool auth = false}) => {
333 'content-type': 'application/json',
334 if (auth && accessToken != null) 'authorization': 'Bearer $accessToken',
335 };
336
337 Future<Map<String, dynamic>> _json(
338 String method,
339 String path, {
340 Map<String, dynamic>? body,
341 bool auth = false,
342 bool retry = true,
343 }) async {
344 requireWebInstanceOwnership();
345 final requestGeneration = _sessionGeneration;
346 if (auth && accessToken == null) {
347 throw const ApiException(401, 'session_expired');
348 }
349 final request = http.Request(method, _uri(path))
350 ..headers.addAll(_headers(auth: auth));
351 if (body != null) request.body = jsonEncode(body);
352
353 late http.Response response;
354 try {
355 response = await (() async =>
356 http.Response.fromStream(await _client.send(request)))()
357 .timeout(const Duration(seconds: 20));
358 } on TimeoutException {
359 throw const ApiException(0, 'request_timeout');
360 } on http.ClientException {
361 throw const ApiException(0, 'network_unavailable');
362 }
363
364 requireWebInstanceOwnership();
365 if (auth && requestGeneration != _sessionGeneration) {
366 throw const ApiException(401, 'session_changed');
367 }
368
369 if (response.statusCode == 401 && auth && retry && _refreshToken != null) {
370 await _refresh();
371 return _json(method, path, body: body, auth: auth, retry: false);
372 }
373
374 if (response.statusCode < 200 || response.statusCode >= 300) {
375 if (response.statusCode == 401 && auth) await _expireSession();
376 var code = 'request_failed';
377 var details = <String, dynamic>{};
378 if (response.body.isNotEmpty) {
379 try {
380 details = jsonDecode(response.body) as Map<String, dynamic>;
381 code = details['error']?.toString() ?? code;
382 } catch (_) {}
383 }
384 throw ApiException(response.statusCode, code, details: details);
385 }
386
387 if (response.body.isEmpty) return <String, dynamic>{};
388 try {
389 return jsonDecode(response.body) as Map<String, dynamic>;
390 } catch (_) {
391 throw const ApiException(502, 'invalid_api_response');
392 }
393 }
394
395 Future<void> _refresh() =>
396 _refreshing ??= _performRefresh().whenComplete(() => _refreshing = null);
397
398 Future<void> _performRefresh() async {
399 final token = _refreshToken;
400 if (token == null) throw const ApiException(401, 'session_expired');
401 final generation = _sessionGeneration;
402 try {
403 final result = await _json(
404 'POST',
405 '/v1/auth/refresh',
406 body: {'refreshToken': token},
407 retry: false,
408 );
409 await _acceptTokens(result, generation: generation);
410 } on ApiException catch (error) {
411 if (generation == _sessionGeneration &&
412 (error.statusCode == 401 || error.statusCode == 403)) {
413 await _expireSession();
414 }
415 rethrow;
416 }
417 }
418
419 @override
420 Future<void> register({
421 required String displayName,
422 required String email,
423 required String password,
424 }) async {
425 await _json('POST', '/v1/auth/register', body: {
426 'displayName': displayName,
427 'email': email,
428 'password': password,
429 });
430 }
431
432 @override
433 Future<void> verifyEmail(String token, {required String newPassword}) async {
434 await _json('POST', '/v1/auth/verify-email',
435 body: {'token': token, 'newPassword': newPassword});
436 }
437
438 @override
439 Future<void> login(String email, String password) async {
440 final generation = ++_sessionGeneration;
441 final result = await _json('POST', '/v1/auth/login', body: {
442 'identifier': email,
443 'password': password,
444 });
445 await _acceptTokens(result, generation: generation);
446 }
447
448 Future<Map<String, dynamic>> registerContact(
449 {required String displayName,
450 required String password,
451 String? email,
452 String? phone}) {
453 return _json('POST', '/v1/auth/register', body: {
454 'displayName': displayName,
455 'password': password,
456 if (email != null) 'email': email,
457 if (phone != null) 'phone': phone
458 });
459 }
460
461 Future<Map<String, dynamic>> authCapabilities() =>
462 _json('GET', '/v1/auth/capabilities');
463 Future<Map<String, dynamic>> resendVerification(String email) =>
464 _json('POST', '/v1/auth/resend-verification', body: {'email': email});
465 Future<Map<String, dynamic>> requestPhoneOtp(String phone,
466 {String purpose = 'login'}) =>
467 _json('POST', '/v1/auth/phone/request-otp',
468 body: {'phone': phone, 'purpose': purpose});
469 Future<void> verifyPhoneOtp(String challengeId, String code,
470 {String? newPassword}) async {
471 final generation = ++_sessionGeneration;
472 final result = await _json('POST', '/v1/auth/phone/verify-otp', body: {
473 'challengeId': challengeId,
474 'code': code,
475 if (newPassword != null) 'newPassword': newPassword
476 });
477 await _acceptTokens(result, generation: generation);
478 }
479
480 Future<Map<String, dynamic>> startStudySession(Map<String, dynamic> body) =>
481 requestJson('POST', '/v1/study/sessions', body: body);
482 Future<Map<String, dynamic>> recordStudySessionEvent(
483 String id, Map<String, dynamic> body) =>
484 requestJson(
485 'POST', '/v1/study/sessions/${Uri.encodeComponent(id)}/events',
486 body: body);
487 Future<List<Map<String, dynamic>>> listStudySessions(
488 {String? planItemId}) async {
489 final suffix = planItemId == null
490 ? ''
491 : '?${Uri(queryParameters: {'planItemId': planItemId}).query}';
492 final result = await requestJson('GET', '/v1/study/sessions$suffix');
493 return (result['sessions'] as List)
494 .map((item) => Map<String, dynamic>.from(item as Map))
495 .toList();
496 }
497
498 Future<Map<String, dynamic>> getStudySession(String id) async =>
499 Map<String, dynamic>.from((await requestJson('GET',
500 '/v1/study/sessions/${Uri.encodeComponent(id)}'))['session'] as Map);
501 Future<Map<String, dynamic>> archiveStudySession(
502 String id, Map<String, dynamic> body) =>
503 requestJson('DELETE', '/v1/study/sessions/${Uri.encodeComponent(id)}',
504 body: body);
505 Future<Map<String, dynamic>> recordActivityState(
506 String id, Map<String, dynamic> body) =>
507 requestJson(
508 'POST', '/v1/plan-items/${Uri.encodeComponent(id)}/activity-state',
509 body: body);
510 Future<Map<String, dynamic>> getActivityState(String id) => requestJson(
511 'GET', '/v1/plan-items/${Uri.encodeComponent(id)}/activity-state');
512 Future<Map<String, dynamic>> updateStudySession(
513 String id, Map<String, dynamic> body) =>
514 requestJson('PATCH', '/v1/study/sessions/${Uri.encodeComponent(id)}',
515 body: body);
516 Future<Map<String, dynamic>> getLearningReport(
517 String familyId, String childId,
518 {DateTime? from, DateTime? to}) {
519 final params = <String, String>{
520 if (from != null) 'from': from.toUtc().toIso8601String(),
521 if (to != null) 'to': to.toUtc().toIso8601String()
522 };
523 final suffix =
524 params.isEmpty ? '' : '?${Uri(queryParameters: params).query}';
525 return requestJson('GET',
526 '/v1/families/${Uri.encodeComponent(familyId)}/children/${Uri.encodeComponent(childId)}/learning-report$suffix');
527 }
528
529 @override
530 Future<void> forgotPassword(String email) async {
531 await _json('POST', '/v1/auth/forgot-password', body: {'email': email});
532 }
533
534 @override
535 Future<void> resetPassword(String token, String newPassword) async {
536 await _json('POST', '/v1/auth/reset-password', body: {
537 'token': token,
538 'newPassword': newPassword,
539 });
540 }
541
542 @override
543 Future<void> changePassword(
544 String currentPassword,
545 String newPassword,
546 ) async {
547 await _json('POST', '/v1/auth/change-password', auth: true, body: {
548 'currentPassword': currentPassword,
549 'newPassword': newPassword,
550 });
551 }
552
553 @override
554 Future<Map<String, dynamic>> getProfile() =>
555 _json('GET', '/v1/profile', auth: true);
556
557 @override
558 Future<Map<String, dynamic>> updateProfile({
559 String? displayName,
560 String? birthDate,
561 String? themePreference,
562 String? profileCategory,
563 }) =>
564 _json('PATCH', '/v1/profile', auth: true, body: {
565 if (displayName != null) 'displayName': displayName,
566 if (birthDate != null) 'birthDate': birthDate,
567 if (themePreference != null) 'themePreference': themePreference,
568 if (profileCategory != null) 'profileCategory': profileCategory,
569 });
570
571 @override
572 Future<List<Map<String, dynamic>>> listFamilies() async {
573 final result = await _json('GET', '/v1/families', auth: true);
574 final families = (result['families'] as List<dynamic>? ?? const []);
575 return families
576 .map((item) => Map<String, dynamic>.from(item as Map))
577 .toList();
578 }
579
580 @override
581 Future<List<Map<String, dynamic>>> listFamilyMembers(String familyId) async {
582 final result = await _json(
583 'GET',
584 '/v1/families/$familyId/members',
585 auth: true,
586 );
587 final members = (result['members'] as List<dynamic>? ?? const []);
588 return members
589 .map((item) => Map<String, dynamic>.from(item as Map))
590 .toList();
591 }
592
593 @override
594 Future<Map<String, dynamic>> createFamily(
595 String name, {
596 String? role,
597 }) =>
598 _json('POST', '/v1/families', auth: true, body: {
599 'name': name,
600 if (role != null) 'role': role,
601 });
602
603 @override
604 Future<void> inviteMember({
605 required String familyId,
606 required String email,
607 required String role,
608 String? themePreference,
609 }) async {
610 await _json(
611 'POST',
612 '/v1/families/$familyId/invitations',
613 auth: true,
614 body: {
615 'email': email,
616 'role': role,
617 if (themePreference != null) 'themePreference': themePreference,
618 },
619 );
620 }
621
622 Future<Map<String, dynamic>> createFamilyInvitation({
623 required String familyId,
624 String? email,
625 String? phone,
626 required String role,
627 String? themePreference,
628 }) =>
629 requestJson(
630 'POST', '/v1/families/${Uri.encodeComponent(familyId)}/invitations',
631 body: {
632 if (email != null) 'email': email,
633 if (phone != null) 'phone': phone,
634 'role': role,
635 if (themePreference != null) 'themePreference': themePreference,
636 });
637
638 @override
639 Future<void> acceptInvitation(String token) async {
640 await _json(
641 'POST',
642 '/v1/invitations/accept',
643 auth: true,
644 body: {'token': token},
645 );
646 }
647
648 @override
649 Future<void> setGuardian({
650 required String familyId,
651 required String guardianUserId,
652 required String minorUserId,
653 }) async {
654 await _json(
655 'POST',
656 '/v1/families/$familyId/guardians',
657 auth: true,
658 body: {
659 'guardianUserId': guardianUserId,
660 'minorUserId': minorUserId,
661 },
662 );
663 }
664
665 @override
666 Future<List<Map<String, dynamic>>> getToday({
667 required DateTime from,
668 required DateTime to,
669 }) async {
670 final result = await _json(
671 'GET',
672 '/v1/today?from=${Uri.encodeQueryComponent(from.toUtc().toIso8601String())}&to=${Uri.encodeQueryComponent(to.toUtc().toIso8601String())}',
673 auth: true,
674 );
675 return (result['items'] as List<dynamic>? ?? const [])
676 .map((item) => Map<String, dynamic>.from(item as Map))
677 .toList();
678 }
679
680 @override
681 Future<List<Map<String, dynamic>>> listPlanItems({
682 DateTime? from,
683 DateTime? to,
684 String? kind,
685 }) async {
686 final params = <String, String>{};
687 if (from != null) params['from'] = from.toUtc().toIso8601String();
688 if (to != null) params['to'] = to.toUtc().toIso8601String();
689 if (kind != null) params['kind'] = kind;
690 final suffix =
691 params.isEmpty ? '' : '?${Uri(queryParameters: params).query}';
692 final result = await _json('GET', '/v1/plan-items$suffix', auth: true);
693 return (result['items'] as List<dynamic>? ?? const [])
694 .map((item) => Map<String, dynamic>.from(item as Map))
695 .toList();
696 }
697
698 @override
699 Future<Map<String, dynamic>> createPlanItem(Map<String, dynamic> data) =>
700 _json('POST', '/v1/plan-items', auth: true, body: data);
701
702 @override
703 Future<Map<String, dynamic>> updatePlanItem(
704 String itemId,
705 Map<String, dynamic> data,
706 ) =>
707 _json('PATCH', '/v1/plan-items/$itemId', auth: true, body: data);
708
709 @override
710 Future<List<Map<String, dynamic>>> listLifeContexts() async {
711 final result = await _json('GET', '/v1/life-contexts', auth: true);
712 return (result['contexts'] as List<dynamic>? ?? const [])
713 .map((item) => Map<String, dynamic>.from(item as Map))
714 .toList();
715 }
716
717 @override
718 Future<Map<String, dynamic>> createLifeContext({
719 required String kind,
720 required String title,
721 }) =>
722 _json(
723 'POST',
724 '/v1/life-contexts',
725 auth: true,
726 body: {'kind': kind, 'title': title},
727 );
728
729 @override
730 Future<Map<String, dynamic>> createAcademicYear(
731 Map<String, dynamic> data,
732 ) =>
733 _json('POST', '/v1/school/years', auth: true, body: data);
734
735 @override
736 Future<Map<String, dynamic>> createAcademicTerm(
737 String yearId,
738 Map<String, dynamic> data,
739 ) =>
740 _json(
741 'POST',
742 '/v1/school/years/$yearId/terms',
743 auth: true,
744 body: data,
745 );
746
747 @override
748 Future<Map<String, dynamic>> createSubject(
749 String termId,
750 Map<String, dynamic> data,
751 ) =>
752 _json(
753 'POST',
754 '/v1/school/terms/$termId/subjects',
755 auth: true,
756 body: data,
757 );
758
759 @override
760 Future<Map<String, dynamic>> createClassSession(
761 String subjectId,
762 Map<String, dynamic> data,
763 ) =>
764 _json(
765 'POST',
766 '/v1/school/subjects/$subjectId/classes',
767 auth: true,
768 body: data,
769 );
770
771 @override
772 Future<Map<String, dynamic>> getSchoolOverview(String studentUserId) =>
773 _json('GET', '/v1/school/$studentUserId/overview', auth: true);
774
775 @override
776 Future<List<Map<String, dynamic>>> getTimetable(String studentUserId) async {
777 final result = await _json(
778 'GET',
779 '/v1/school/$studentUserId/timetable',
780 auth: true,
781 );
782 return (result['classes'] as List<dynamic>? ?? const [])
783 .map((item) => Map<String, dynamic>.from(item as Map))
784 .toList();
785 }
786
787 @override
788 Future<Map<String, dynamic>> setGrade(
789 String itemId, {
790 required num points,
791 required num outOf,
792 }) =>
793 _json(
794 'PATCH',
795 '/v1/school/plan-items/$itemId/grade',
796 auth: true,
797 body: {'points': points, 'outOf': outOf},
798 );
799
800 @override
801 Future<List<Map<String, dynamic>>> claimDueReminders() async {
802 final result = await _json(
803 'POST',
804 '/v1/reminders/claim-due',
805 auth: true,
806 body: {'limit': 20},
807 );
808 return (result['reminders'] as List<dynamic>? ?? const [])
809 .map((item) => Map<String, dynamic>.from(item as Map))
810 .toList();
811 }
812
813 @override
814 Future<List<Map<String, dynamic>>> getFamilyCalendar(String familyId) async {
815 final result = await _json(
816 'GET',
817 '/v1/families/$familyId/calendar',
818 auth: true,
819 );
820 return (result['items'] as List<dynamic>? ?? const [])
821 .map((item) => Map<String, dynamic>.from(item as Map))
822 .toList();
823 }
824
825 @override
826 Future<Map<String, dynamic>> getChildSupportSummary(
827 String familyId,
828 String studentUserId,
829 ) =>
830 _json(
831 'GET',
832 '/v1/families/$familyId/children/$studentUserId/support-summary',
833 auth: true,
834 );
835
836 @override
837 Future<Map<String, dynamic>> submitSyncMutations(
838 List<Map<String, dynamic>> mutations,
839 ) =>
840 _json(
841 'POST',
842 '/v1/sync/mutations',
843 auth: true,
844 body: {'mutations': mutations},
845 );
846
847 @override
848 Future<Map<String, dynamic>> createLearningGoal({
849 required String title,
850 String? target,
851 String? subjectId,
852 }) =>
853 _json('POST', '/v1/learning/goals', auth: true, body: {
854 'title': title,
855 if (target != null) 'target': target,
856 if (subjectId != null) 'subjectId': subjectId,
857 });
858
859 @override
860 Future<List<Map<String, dynamic>>> listLearningGoals() async {
861 final result = await _json('GET', '/v1/learning/goals', auth: true);
862 return (result['items'] as List<dynamic>? ?? const [])
863 .map((item) => Map<String, dynamic>.from(item as Map))
864 .toList();
865 }
866
867 @override
868 Future<Map<String, dynamic>> createLearningCheckin({
869 String? learningGoalId,
870 required int confidence,
871 required int difficulty,
872 String? note,
873 }) =>
874 _json('POST', '/v1/learning/checkins', auth: true, body: {
875 if (learningGoalId != null) 'learningGoalId': learningGoalId,
876 'confidence': confidence,
877 'difficulty': difficulty,
878 if (note != null) 'note': note,
879 });
880
881 @override
882 Future<Map<String, dynamic>> createWellbeingCheckin({
883 required int mood,
884 required int energy,
885 required int stress,
886 String? note,
887 String visibility = 'private',
888 }) =>
889 _json('POST', '/v1/wellbeing/checkins', auth: true, body: {
890 'mood': mood,
891 'energy': energy,
892 'stress': stress,
893 if (note != null) 'note': note,
894 'visibility': visibility,
895 });
896
897 @override
898 Future<List<Map<String, dynamic>>> listWellbeingCheckins() async {
899 final result = await _json('GET', '/v1/wellbeing/checkins', auth: true);
900 return (result['items'] as List<dynamic>? ?? const [])
901 .map((item) => Map<String, dynamic>.from(item as Map))
902 .toList();
903 }
904
905 @override
906 Future<Map<String, dynamic>> createAiSession(String kind) =>
907 _json('POST', '/v1/ai/sessions', auth: true, body: {'kind': kind});
908
909 @override
910 Future<Map<String, dynamic>> sendAiMessage(
911 String sessionId,
912 String message,
913 ) =>
914 _json(
915 'POST',
916 '/v1/ai/sessions/$sessionId/messages',
917 auth: true,
918 body: {'message': message},
919 );
920
921 @override
922 Future<Map<String, dynamic>> getGuardianWellbeingSummary(
923 String familyId,
924 String minorUserId,
925 ) =>
926 _json(
927 'GET',
928 '/v1/families/$familyId/children/$minorUserId/wellbeing-summary',
929 auth: true,
930 );
931
932 @override
933 Future<Map<String, dynamic>> requestFamilyGuidance(
934 String familyId,
935 String minorUserId,
936 String question,
937 ) =>
938 _json(
939 'POST',
940 '/v1/families/$familyId/children/$minorUserId/family-guidance',
941 auth: true,
942 body: {'question': question},
943 );
944 }