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