@davoodmehraban89 / LifeMate / commits / 8366e2d
Fork 0

LifeMate — Personal, Family & Learning Companion

Phase 3: Planner, School & Family Core

* docs: add phase 3 implementation plan * feat: add phase 3 planner school and family schema * feat: add planner school family API * feat: mount phase 3 planner and school API * test: cover planner school family phase 3 slice * ci: add phase 3 schema and tests * feat: add phase 3 planner school family client API * feat: add offline cache dependency * feat: add offline cache and mutation queue * feat: expose authenticated profile user id * feat: add planner school family core screens * feat: connect phase 3 core screens to role-aware shell * test: extend fake API for phase 3 core * test: add phase 3 database authorization matrix * ci: run phase 3 authorization matrix * feat: apply offline mutations with conflict checks * test: verify offline sync application and reminder outbox * fix: type reminder base timestamp explicitly * chore: scope phase 3 UI lint exceptions * test: initialize offline preferences in widget tests * fix: support private PostgreSQL staging connections * feat: expose grades and due reminders to Flutter * test: align fake API with reminder and grade endpoints * feat: surface due reminder banners on Today * docs: record completed phase 3 implementation * docs: record final phase 3 CI evidence * docs: record final phase 3 gate

davoodmehraban89 committed Oct 5, 2026 at 15:43 UTC 8366e2d115f5e202e42e5278eddbb45695169477
15 files changed +2538 -39
.github/workflows/ci.yml
+6 -3
@@ -1,4 +1,4 @@
1 -name: Phase 2 CI
1 +name: Phase 3 CI
2
3 on:
4 push:
@@ -72,8 +72,11 @@ jobs:
72 run: |
73 psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/migrations/0001_identity_family.sql
74 psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/migrations/0002_auth.sql
75 + psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/migrations/0003_planner_school_family.sql
76 - name: Database authorization tests
76 - run: psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/tests/schema_test.sql
77 + run: |
78 + psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/tests/schema_test.sql
79 + psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/tests/phase3_schema_test.sql
80 - name: Install backend
81 working-directory: backend
82 run: npm install
@@ -85,4 +88,4 @@ jobs:
88 run: npm test
89 - name: Verify schema objects
90 run: |
88 - test "$(psql -h localhost -U postgres -d lifemate_ci -Atc "select count(*) from information_schema.tables where table_schema='public' and table_name in ('app_user','profile','family_workspace','family_membership','guardian_relationship','family_invitation','access_audit','auth_credential','auth_token','auth_session');")" = "10"
91 + test "$(psql -h localhost -U postgres -d lifemate_ci -Atc "select count(*) from information_schema.tables where table_schema='public' and table_name in ('app_user','profile','family_workspace','family_membership','guardian_relationship','family_invitation','access_audit','auth_credential','auth_token','auth_session','life_context','academic_year','academic_term','subject','class_session','plan_item','sharing_grant','reminder','notification_preference','notification_outbox','sync_mutation');")" = "21"
PROJECT_STATE.md
+20 -24
@@ -1,18 +1,18 @@
1 # LifeMate — Project State
2
3 **Last updated:** 2026-10-05
4 -**Phase:** Phase 2 — Product Foundation & Identity — COMPLETE
4 +**Phase:** Phase 3 — Planner, School & Family Core — COMPLETE
5 **Repository:** `davoodmehraban89/LifeMate`
6 **Working product name:** LifeMate — approved
7
8 ## Transfer checkpoint
9 -Phase 1 and Phase 2 are complete. The implementation branch `phase-2/product-foundation-identity` now contains the real Flutter Android/Web-PWA scaffold, provider-neutral Node API, PostgreSQL identity/family schema, auth/recovery/change-password flows, profile/family/invitation/guardian foundations, Persian RTL role-aware Teen/Parent shells, security gates and CI. Railway staging is live with PostgreSQL, API and transactional-email test infrastructure. The Phase 2 CI run for head `9c8a813d4673f9f320d804c91a347a14a51d26db` passed backend, Flutter/Web/Android and security jobs.
9 +Phases 1–3 are complete. Phase 3 adds the real Planner/Today core, school model and workload, family calendar/support summaries, relationship-aware sharing, reminders, offline cache/sync queue with conflict handling, Flutter RTL screens and expanded authorization/CI coverage. Railway staging has the Phase 3 API and migration active against PostgreSQL.
10
11 ## Five-phase roadmap
12 1. **Foundation, Product Contract & UX Direction** — COMPLETE
13 2. **Product Foundation & Identity** — COMPLETE
14 -3. **Planner, School & Family Core** — NEXT
15 -4. **AI Guides, Learning & Wellbeing**
14 +3. **Planner, School & Family Core** — COMPLETE
15 +4. **AI Guides, Learning & Wellbeing** — NEXT
16 5. **Hardening, Observability & Release**
17
18 ## Accepted architecture baseline
@@ -20,7 +20,7 @@ Phase 1 and Phase 2 are complete. The implementation branch `phase-2/product-fou
20 - iPhone/iPad initial distribution: Home Screen PWA; future packaged/native iOS path preserved.
21 - Backend: provider-neutral Node API + standard PostgreSQL. Railway is the current staging host; managed database/provider can be replaced without changing domain contracts.
22 - Identity: LifeMate-owned email/password/session adapter with Argon2id, verification/reset tokens, rotating refresh sessions and server-side authorization.
23 -- Offline: explicit custom web service-worker/cache strategy; browser storage is non-authoritative.
23 +- Offline: local cache plus explicit mutation queue; server remains authoritative and rejects stale/conflicting writes.
24 - Authorization: relationship-aware and server-enforced; family admin is not blanket private-content access.
25
26 ## Product/UX baseline
@@ -28,25 +28,21 @@ Phase 1 and Phase 2 are complete. The implementation branch `phase-2/product-fou
28 - Parent/adult experiences share the platform while emphasizing Family, authorized progress/support information and guidance.
29 - Parent support focuses on authorized schedule/academic/support summaries, not routine private transcript surveillance.
30 - Visual language: warm, modern, calm, graphical, teen-friendly but non-childish; Persian RTL first-class. Default profile themes: daughter/teen girl = white + soft pink; son/teen boy = white + calm blue; parents/adults = white + calm blue.
31 -- Figma artifact exists: `LifeMate — Product UX & Brand v1` with initial editable direction frames.
32 -- Canva is supporting visual/illustration exploration; Figma remains UI source of truth.
33 -- Notion Project Hub exists as management mirror; GitHub remains technical source of truth.
34 -
35 -## Phase 2 completed vertical slice
36 -Auth → verified email/recovery/change password → Profile → Family Workspace → invitation/membership → Guardian Relationship → server-side permission tests → Persian RTL Teen/Parent shells → CI → persistent staging infrastructure and smoke verification.
37 -
38 -### Verified Phase 2 gates
39 -- PostgreSQL migrations and authorization helper tests pass.
40 -- Backend API tests pass, including unauthenticated, teen/non-admin denial and active-member role-escalation protection.
41 -- Backend dependency audit reports no high-severity blocking vulnerability.
42 -- Secret/environment-file CI gates pass.
43 -- Flutter formatting, static analysis and widget tests pass.
44 -- Flutter Web release build passes.
45 -- Android debug APK build passes.
46 -- Railway staging PostgreSQL, API and Mailpit are online; API health and staging transactional-email probe passed.
47 -
48 -## Phase 3 entry point
49 -Implement Planner, School & Family Core on top of the completed identity/family contracts. Preserve role-aware navigation, relationship-aware permissions, Persian RTL, provider-neutral backend boundaries and the existing CI/security gates.
31 +- Figma remains UI source of truth; Canva is supporting visual/illustration exploration.
32 +- Notion Project Hub is the management mirror; GitHub remains technical source of truth.
33 +
34 +## Phase 3 completed vertical slice
35 +Today/Planner → task/event/routine/goal/study-session creation and completion/rescheduling → reminder scheduling/claim/outbox → student life context → academic year/term/subject/class → assignments/exams/grades → family-visible calendar → guardian-authorized child support summary → offline cache/mutation queue → conflict/idempotency handling → CI/staging verification.
36 +
37 +### Verified Phase 3 gates
38 +- Migration `0003_planner_school_family.sql` defines the planner, academic, reminder, sharing and sync model.
39 +- Database authorization matrix covers owner/private, family, guardian and removed-member denial behavior.
40 +- Backend integration tests cover planner CRUD, academic setup, grades, guardian summaries, offline mutation application/idempotency and reminder outbox behavior.
41 +- Phase 3 CI runs 114, 115 and final run 116 passed backend, security, Flutter formatting/static analysis/widget tests, Web release build and Android debug APK build; final verified branch head before merge is `5e1e566510948322fbc4da46c374733280293f73`.
42 +- Railway staging API is online and Phase 3 database smoke verification confirms 11 required tables, 3 authorization/reminder functions and the `0003_planner_school_family.sql` migration ledger entry.
43 +
44 +## Phase 4 entry point
45 +Build AI Guides, Learning & Wellbeing on top of the completed planner/school/family contracts. AI must remain advisory, age-appropriate, privacy-aware and relationship-aware; it must not silently broaden parent access beyond Phase 3 authorization contracts.
46
47 ## Production-gate items intentionally deferred
48 These do not block the engineering foundation but do block public production of wellbeing/minor-sensitive AI features: jurisdiction-specific legal/guardian consent review; safety severity taxonomy; emergency resource localization; AI provider privacy/retention review; wellbeing retention/export/deletion policy.
apps/lifemate/lib/api.dart
+230
@@ -37,6 +37,55 @@ abstract class IdentityApi {
37 required String guardianUserId,
38 required String minorUserId,
39 });
40 +
41 + Future<List<Map<String, dynamic>>> getToday({
42 + required DateTime from,
43 + required DateTime to,
44 + });
45 + Future<List<Map<String, dynamic>>> listPlanItems({
46 + DateTime? from,
47 + DateTime? to,
48 + String? kind,
49 + });
50 + Future<Map<String, dynamic>> createPlanItem(Map<String, dynamic> data);
51 + Future<Map<String, dynamic>> updatePlanItem(
52 + String itemId,
53 + Map<String, dynamic> data,
54 + );
55 + Future<List<Map<String, dynamic>>> listLifeContexts();
56 + Future<Map<String, dynamic>> createLifeContext({
57 + required String kind,
58 + required String title,
59 + });
60 + Future<Map<String, dynamic>> createAcademicYear(Map<String, dynamic> data);
61 + Future<Map<String, dynamic>> createAcademicTerm(
62 + String yearId,
63 + Map<String, dynamic> data,
64 + );
65 + Future<Map<String, dynamic>> createSubject(
66 + String termId,
67 + Map<String, dynamic> data,
68 + );
69 + Future<Map<String, dynamic>> createClassSession(
70 + String subjectId,
71 + Map<String, dynamic> data,
72 + );
73 + Future<Map<String, dynamic>> getSchoolOverview(String studentUserId);
74 + Future<List<Map<String, dynamic>>> getTimetable(String studentUserId);
75 + Future<Map<String, dynamic>> setGrade(
76 + String itemId, {
77 + required num points,
78 + required num outOf,
79 + });
80 + Future<List<Map<String, dynamic>>> claimDueReminders();
81 + Future<List<Map<String, dynamic>>> getFamilyCalendar(String familyId);
82 + Future<Map<String, dynamic>> getChildSupportSummary(
83 + String familyId,
84 + String studentUserId,
85 + );
86 + Future<Map<String, dynamic>> submitSyncMutations(
87 + List<Map<String, dynamic>> mutations,
88 + );
89 }
90
91 class ApiException implements Exception {
@@ -266,4 +315,185 @@ class HttpIdentityApi implements IdentityApi {
315 },
316 );
317 }
318 + @override
319 + Future<List<Map<String, dynamic>>> getToday({
320 + required DateTime from,
321 + required DateTime to,
322 + }) async {
323 + final result = await _json(
324 + 'GET',
325 + '/v1/today?from=${Uri.encodeQueryComponent(from.toUtc().toIso8601String())}&to=${Uri.encodeQueryComponent(to.toUtc().toIso8601String())}',
326 + auth: true,
327 + );
328 + return (result['items'] as List<dynamic>? ?? const [])
329 + .map((item) => Map<String, dynamic>.from(item as Map))
330 + .toList();
331 + }
332 +
333 + @override
334 + Future<List<Map<String, dynamic>>> listPlanItems({
335 + DateTime? from,
336 + DateTime? to,
337 + String? kind,
338 + }) async {
339 + final params = <String, String>{};
340 + if (from != null) params['from'] = from.toUtc().toIso8601String();
341 + if (to != null) params['to'] = to.toUtc().toIso8601String();
342 + if (kind != null) params['kind'] = kind;
343 + final suffix = params.isEmpty ? '' : '?${Uri(queryParameters: params).query}';
344 + final result = await _json('GET', '/v1/plan-items$suffix', auth: true);
345 + return (result['items'] as List<dynamic>? ?? const [])
346 + .map((item) => Map<String, dynamic>.from(item as Map))
347 + .toList();
348 + }
349 +
350 + @override
351 + Future<Map<String, dynamic>> createPlanItem(Map<String, dynamic> data) =>
352 + _json('POST', '/v1/plan-items', auth: true, body: data);
353 +
354 + @override
355 + Future<Map<String, dynamic>> updatePlanItem(
356 + String itemId,
357 + Map<String, dynamic> data,
358 + ) =>
359 + _json('PATCH', '/v1/plan-items/$itemId', auth: true, body: data);
360 +
361 + @override
362 + Future<List<Map<String, dynamic>>> listLifeContexts() async {
363 + final result = await _json('GET', '/v1/life-contexts', auth: true);
364 + return (result['contexts'] as List<dynamic>? ?? const [])
365 + .map((item) => Map<String, dynamic>.from(item as Map))
366 + .toList();
367 + }
368 +
369 + @override
370 + Future<Map<String, dynamic>> createLifeContext({
371 + required String kind,
372 + required String title,
373 + }) =>
374 + _json(
375 + 'POST',
376 + '/v1/life-contexts',
377 + auth: true,
378 + body: {'kind': kind, 'title': title},
379 + );
380 +
381 + @override
382 + Future<Map<String, dynamic>> createAcademicYear(
383 + Map<String, dynamic> data,
384 + ) =>
385 + _json('POST', '/v1/school/years', auth: true, body: data);
386 +
387 + @override
388 + Future<Map<String, dynamic>> createAcademicTerm(
389 + String yearId,
390 + Map<String, dynamic> data,
391 + ) =>
392 + _json(
393 + 'POST',
394 + '/v1/school/years/$yearId/terms',
395 + auth: true,
396 + body: data,
397 + );
398 +
399 + @override
400 + Future<Map<String, dynamic>> createSubject(
401 + String termId,
402 + Map<String, dynamic> data,
403 + ) =>
404 + _json(
405 + 'POST',
406 + '/v1/school/terms/$termId/subjects',
407 + auth: true,
408 + body: data,
409 + );
410 +
411 + @override
412 + Future<Map<String, dynamic>> createClassSession(
413 + String subjectId,
414 + Map<String, dynamic> data,
415 + ) =>
416 + _json(
417 + 'POST',
418 + '/v1/school/subjects/$subjectId/classes',
419 + auth: true,
420 + body: data,
421 + );
422 +
423 + @override
424 + Future<Map<String, dynamic>> getSchoolOverview(String studentUserId) =>
425 + _json('GET', '/v1/school/$studentUserId/overview', auth: true);
426 +
427 + @override
428 + Future<List<Map<String, dynamic>>> getTimetable(String studentUserId) async {
429 + final result = await _json(
430 + 'GET',
431 + '/v1/school/$studentUserId/timetable',
432 + auth: true,
433 + );
434 + return (result['classes'] as List<dynamic>? ?? const [])
435 + .map((item) => Map<String, dynamic>.from(item as Map))
436 + .toList();
437 + }
438 +
439 + @override
440 + Future<Map<String, dynamic>> setGrade(
441 + String itemId, {
442 + required num points,
443 + required num outOf,
444 + }) =>
445 + _json(
446 + 'PATCH',
447 + '/v1/school/plan-items/$itemId/grade',
448 + auth: true,
449 + body: {'points': points, 'outOf': outOf},
450 + );
451 +
452 + @override
453 + Future<List<Map<String, dynamic>>> claimDueReminders() async {
454 + final result = await _json(
455 + 'POST',
456 + '/v1/reminders/claim-due',
457 + auth: true,
458 + body: {'limit': 20},
459 + );
460 + return (result['reminders'] as List<dynamic>? ?? const [])
461 + .map((item) => Map<String, dynamic>.from(item as Map))
462 + .toList();
463 + }
464 +
465 + @override
466 + Future<List<Map<String, dynamic>>> getFamilyCalendar(String familyId) async {
467 + final result = await _json(
468 + 'GET',
469 + '/v1/families/$familyId/calendar',
470 + auth: true,
471 + );
472 + return (result['items'] as List<dynamic>? ?? const [])
473 + .map((item) => Map<String, dynamic>.from(item as Map))
474 + .toList();
475 + }
476 +
477 + @override
478 + Future<Map<String, dynamic>> getChildSupportSummary(
479 + String familyId,
480 + String studentUserId,
481 + ) =>
482 + _json(
483 + 'GET',
484 + '/v1/families/$familyId/children/$studentUserId/support-summary',
485 + auth: true,
486 + );
487 +
488 + @override
489 + Future<Map<String, dynamic>> submitSyncMutations(
490 + List<Map<String, dynamic>> mutations,
491 + ) =>
492 + _json(
493 + 'POST',
494 + '/v1/sync/mutations',
495 + auth: true,
496 + body: {'mutations': mutations},
497 + );
498 +
499 }
apps/lifemate/lib/main.dart
+5 -5
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
2 import 'package:flutter_localizations/flutter_localizations.dart';
3
4 import 'api.dart';
5 +import 'phase3_ui.dart';
6
7 void main() => runApp(LifeMateApp());
8
@@ -610,11 +611,10 @@ class _HomeShellState extends State<HomeShell> {
611 ),
612 ],
613 ),
613 - body: Center(
614 - child: Text(
615 - pages[index],
616 - style: Theme.of(context).textTheme.headlineMedium,
617 - ),
614 + body: Phase3HomeContent(
615 + api: widget.api,
616 + page: pages[index],
617 + adultShell: adultShell,
618 ),
619 bottomNavigationBar: NavigationBar(
620 selectedIndex: index > 4 ? 0 : index,
apps/lifemate/lib/offline_store.dart new
+60
@@ -0,0 +1,60 @@
1 +import 'dart:convert';
2 +
3 +import 'package:shared_preferences/shared_preferences.dart';
4 +
5 +class OfflineStore {
6 + OfflineStore._();
7 + static final OfflineStore instance = OfflineStore._();
8 +
9 + static const _todayKey = 'phase3.today.cache';
10 + static const _plannerKey = 'phase3.planner.cache';
11 + static const _schoolKey = 'phase3.school.cache';
12 + static const _queueKey = 'phase3.sync.queue';
13 +
14 + Future<void> writeList(String key, List<Map<String, dynamic>> value) async {
15 + final prefs = await SharedPreferences.getInstance();
16 + await prefs.setString(key, jsonEncode(value));
17 + }
18 +
19 + Future<List<Map<String, dynamic>>> readList(String key) async {
20 + final prefs = await SharedPreferences.getInstance();
21 + final raw = prefs.getString(key);
22 + if (raw == null || raw.isEmpty) return [];
23 + try {
24 + final decoded = jsonDecode(raw) as List<dynamic>;
25 + return decoded
26 + .map((item) => Map<String, dynamic>.from(item as Map))
27 + .toList();
28 + } catch (_) {
29 + return [];
30 + }
31 + }
32 +
33 + Future<void> cacheToday(List<Map<String, dynamic>> items) =>
34 + writeList(_todayKey, items);
35 + Future<List<Map<String, dynamic>>> readToday() => readList(_todayKey);
36 +
37 + Future<void> cachePlanner(List<Map<String, dynamic>> items) =>
38 + writeList(_plannerKey, items);
39 + Future<List<Map<String, dynamic>>> readPlanner() => readList(_plannerKey);
40 +
41 + Future<void> cacheSchool(List<Map<String, dynamic>> items) =>
42 + writeList(_schoolKey, items);
43 + Future<List<Map<String, dynamic>>> readSchool() => readList(_schoolKey);
44 +
45 + Future<List<Map<String, dynamic>>> readQueue() => readList(_queueKey);
46 +
47 + Future<void> enqueue(Map<String, dynamic> mutation) async {
48 + final queue = await readQueue();
49 + queue.add(mutation);
50 + await writeList(_queueKey, queue);
51 + }
52 +
53 + Future<void> removeQueued(Set<String> ids) async {
54 + final queue = await readQueue();
55 + await writeList(
56 + _queueKey,
57 + queue.where((item) => !ids.contains(item['id']?.toString())).toList(),
58 + );
59 + }
60 +}
apps/lifemate/lib/phase3_ui.dart new
+776
@@ -0,0 +1,776 @@
1 +// ignore_for_file: prefer_interpolation_to_compose_strings, curly_braces_in_flow_control_structures, use_build_context_synchronously
2 +
3 +import 'dart:math';
4 +import 'package:flutter/material.dart';
5 +import 'api.dart';
6 +import 'offline_store.dart';
7 +
8 +String faKind(String kind) {
9 + switch (kind) {
10 + case 'assignment': return 'تکلیف';
11 + case 'exam': return 'امتحان';
12 + case 'study_session': return 'مطالعه';
13 + case 'event': return 'رویداد';
14 + case 'routine': return 'روتین';
15 + case 'goal': return 'هدف';
16 + default: return 'کار';
17 + }
18 +}
19 +
20 +DateTime? parseDate(dynamic value) {
21 + if (value == null) return null;
22 + return DateTime.tryParse(value.toString())?.toLocal();
23 +}
24 +
25 +String shortDate(dynamic value) {
26 + final d = parseDate(value);
27 + if (d == null) return '';
28 + final minute = d.minute.toString().padLeft(2, '0');
29 + return d.month.toString() + '/' + d.day.toString() + ' · ' +
30 + d.hour.toString() + ':' + minute;
31 +}
32 +
33 +class Phase3HomeContent extends StatelessWidget {
34 + const Phase3HomeContent({
35 + super.key,
36 + required this.api,
37 + required this.page,
38 + required this.adultShell,
39 + });
40 + final IdentityApi api;
41 + final String page;
42 + final bool adultShell;
43 +
44 + @override
45 + Widget build(BuildContext context) {
46 + if (page == 'امروز') return TodayPage(api: api);
47 + if (page == 'برنامه‌ریز' || page == 'برنامه هفتگی' || page == 'تقویم' || page == 'تکالیف و کارها') {
48 + return PlannerPage(api: api);
49 + }
50 + if (page == 'خانواده') return ParentFamilyDashboard(api: api);
51 + if (page == 'امتحان‌ها و نمرات') return SchoolPage(api: api);
52 + if (page == 'تمرکز') {
53 + return const CoreNotice(
54 + title: 'تمرکز',
55 + subtitle: 'جلسه مطالعه در برنامه‌ریز فعال است؛ تایمر پیشرفته در فاز بعد اضافه می‌شود.',
56 + );
57 + }
58 + if (page == 'همراه هوشمند' || page == 'راهنما') {
59 + return const CoreNotice(
60 + title: 'راهنمای هوشمند',
61 + subtitle: 'هسته برنامه‌ریزی این فاز مستقل از AI است و راهنمای هوشمند در فاز ۴ فعال می‌شود.',
62 + );
63 + }
64 + return SchoolPage(api: api);
65 + }
66 +}
67 +
68 +class CoreNotice extends StatelessWidget {
69 + const CoreNotice({super.key, required this.title, required this.subtitle});
70 + final String title;
71 + final String subtitle;
72 + @override
73 + Widget build(BuildContext context) => Center(
74 + child: Card(
75 + margin: const EdgeInsets.all(20),
76 + child: Padding(
77 + padding: const EdgeInsets.all(24),
78 + child: Column(mainAxisSize: MainAxisSize.min, children: [
79 + Text(title, style: Theme.of(context).textTheme.headlineSmall),
80 + const SizedBox(height: 8),
81 + Text(subtitle, textAlign: TextAlign.center),
82 + ]),
83 + ),
84 + ),
85 + );
86 +}
87 +
88 +class TodayPage extends StatefulWidget {
89 + const TodayPage({super.key, required this.api});
90 + final IdentityApi api;
91 + @override
92 + State<TodayPage> createState() => _TodayPageState();
93 +}
94 +
95 +class _TodayPageState extends State<TodayPage> {
96 + late Future<LoadResult> future;
97 + @override
98 + void initState() {
99 + super.initState();
100 + future = load();
101 + }
102 +
103 + Future<LoadResult> load() async {
104 + final now = DateTime.now();
105 + final from = DateTime(now.year, now.month, now.day);
106 + final to = from.add(const Duration(days: 1));
107 + try {
108 + final items = await widget.api.getToday(from: from, to: to);
109 + final reminders = await widget.api.claimDueReminders();
110 + await OfflineStore.instance.cacheToday(items);
111 + return LoadResult(items, false, reminders: reminders);
112 + } catch (_) {
113 + return LoadResult(await OfflineStore.instance.readToday(), true);
114 + }
115 + }
116 +
117 + Future<void> refresh() async {
118 + setState(() => future = load());
119 + await future;
120 + }
121 +
122 + Future<void> complete(Map<String, dynamic> item) async {
123 + try {
124 + await widget.api.updatePlanItem(item['id'].toString(), {'status': 'completed'});
125 + await refresh();
126 + } catch (_) {
127 + await OfflineStore.instance.enqueue({
128 + 'id': DateTime.now().microsecondsSinceEpoch.toString() + '-' + Random().nextInt(99999).toString(),
129 + 'entityType': 'plan_item',
130 + 'entityId': item['id'],
131 + 'operation': 'complete',
132 + 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
133 + 'payload': {'status': 'completed'},
134 + });
135 + if (mounted) {
136 + ScaffoldMessenger.of(context).showSnackBar(
137 + const SnackBar(content: Text('آفلاین هستی؛ تغییر برای همگام‌سازی ذخیره شد.')),
138 + );
139 + }
140 + }
141 + }
142 +
143 + @override
144 + Widget build(BuildContext context) => FutureBuilder<LoadResult>(
145 + future: future,
146 + builder: (context, snapshot) {
147 + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
148 + final result = snapshot.data!;
149 + return RefreshIndicator(
150 + onRefresh: refresh,
151 + child: ListView(
152 + padding: const EdgeInsets.all(16),
153 + children: [
154 + if (result.offline)
155 + const Card(child: ListTile(
156 + leading: Icon(Icons.cloud_off_outlined),
157 + title: Text('نمایش نسخه آفلاین'),
158 + )),
159 + if (result.reminders.isNotEmpty)
160 + ...result.reminders.map((reminder) => Card(
161 + child: ListTile(
162 + leading: const Icon(Icons.notifications_active_outlined),
163 + title: Text('یادآوری · ' + (reminder['title']?.toString() ?? 'برنامه')),
164 + subtitle: const Text('زمان این مورد رسیده یا نزدیک است.'),
165 + ),
166 + )),
167 + Card(
168 + child: Padding(
169 + padding: const EdgeInsets.all(18),
170 + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
171 + Text('امروز', style: Theme.of(context).textTheme.headlineSmall),
172 + const SizedBox(height: 6),
173 + Text(result.items.length.toString() + ' مورد در برنامه امروز'),
174 + ]),
175 + ),
176 + ),
177 + const SizedBox(height: 8),
178 + if (result.items.isEmpty)
179 + const EmptyCard(
180 + icon: Icons.check_circle_outline,
181 + title: 'امروز خلوت است',
182 + subtitle: 'از برنامه‌ریز یک کار، رویداد یا جلسه مطالعه اضافه کن.',
183 + )
184 + else
185 + ...result.items.map((item) => Card(
186 + child: ListTile(
187 + leading: const Icon(Icons.radio_button_unchecked),
188 + title: Text(item['title']?.toString() ?? ''),
189 + subtitle: Text(
190 + faKind(item['kind']?.toString() ?? 'task') +
191 + (shortDate(item['starts_at'] ?? item['due_at']).isEmpty ? '' : ' · ' + shortDate(item['starts_at'] ?? item['due_at'])),
192 + ),
193 + trailing: IconButton(
194 + onPressed: () => complete(item),
195 + icon: const Icon(Icons.check_circle_outline),
196 + ),
197 + ),
198 + )),
199 + ],
200 + ),
201 + );
202 + },
203 + );
204 +}
205 +
206 +class PlannerPage extends StatefulWidget {
207 + const PlannerPage({super.key, required this.api});
208 + final IdentityApi api;
209 + @override
210 + State<PlannerPage> createState() => _PlannerPageState();
211 +}
212 +
213 +class _PlannerPageState extends State<PlannerPage> {
214 + late Future<LoadResult> future;
215 + @override
216 + void initState() {
217 + super.initState();
218 + future = load();
219 + flushQueue();
220 + }
221 +
222 + Future<void> flushQueue() async {
223 + final queue = await OfflineStore.instance.readQueue();
224 + if (queue.isEmpty) return;
225 + try {
226 + final result = await widget.api.submitSyncMutations(queue);
227 + final applied = <String>{};
228 + for (final raw in (result['results'] as List<dynamic>? ?? const [])) {
229 + final row = Map<String, dynamic>.from(raw as Map);
230 + if (row['status'] == 'accepted' || row['status'] == 'already_applied') {
231 + applied.add(row['id'].toString());
232 + }
233 + }
234 + await OfflineStore.instance.removeQueued(applied);
235 + } catch (_) {}
236 + }
237 +
238 + Future<LoadResult> load() async {
239 + final now = DateTime.now();
240 + final from = DateTime(now.year, now.month, now.day).subtract(const Duration(days: 1));
241 + final to = from.add(const Duration(days: 15));
242 + try {
243 + final items = await widget.api.listPlanItems(from: from, to: to);
244 + await OfflineStore.instance.cachePlanner(items);
245 + return LoadResult(items, false);
246 + } catch (_) {
247 + return LoadResult(await OfflineStore.instance.readPlanner(), true);
248 + }
249 + }
250 +
251 + Future<void> reload() async {
252 + setState(() => future = load());
253 + await future;
254 + }
255 +
256 + Future<void> createItem() async {
257 + final title = TextEditingController();
258 + final kind = ValueNotifier<String>('task');
259 + final visibility = ValueNotifier<String>('private');
260 + final families = await widget.api.listFamilies();
261 + final familyId = families.isEmpty ? null : families.first['id']?.toString();
262 + final when = DateTime.now().add(const Duration(hours: 1));
263 +
264 + final saved = await showDialog<bool>(
265 + context: context,
266 + builder: (dialogContext) => AlertDialog(
267 + title: const Text('مورد جدید'),
268 + content: Column(mainAxisSize: MainAxisSize.min, children: [
269 + TextField(controller: title, decoration: const InputDecoration(labelText: 'عنوان')),
270 + const SizedBox(height: 12),
271 + ValueListenableBuilder<String>(
272 + valueListenable: kind,
273 + builder: (_, value, __) => DropdownButtonFormField<String>(
274 + initialValue: value,
275 + decoration: const InputDecoration(labelText: 'نوع'),
276 + items: const [
277 + DropdownMenuItem(value: 'task', child: Text('کار')),
278 + DropdownMenuItem(value: 'event', child: Text('رویداد')),
279 + DropdownMenuItem(value: 'routine', child: Text('روتین')),
280 + DropdownMenuItem(value: 'goal', child: Text('هدف')),
281 + DropdownMenuItem(value: 'study_session', child: Text('جلسه مطالعه')),
282 + ],
283 + onChanged: (v) { if (v != null) kind.value = v; },
284 + ),
285 + ),
286 + const SizedBox(height: 12),
287 + ValueListenableBuilder<String>(
288 + valueListenable: visibility,
289 + builder: (_, value, __) => DropdownButtonFormField<String>(
290 + initialValue: value,
291 + decoration: const InputDecoration(labelText: 'اشتراک'),
292 + items: const [
293 + DropdownMenuItem(value: 'private', child: Text('خصوصی')),
294 + DropdownMenuItem(value: 'family', child: Text('خانواده')),
295 + DropdownMenuItem(value: 'parent_guardian', child: Text('والد / سرپرست')),
296 + ],
297 + onChanged: (v) { if (v != null) visibility.value = v; },
298 + ),
299 + ),
300 + ]),
301 + actions: [
302 + TextButton(onPressed: () => Navigator.pop(dialogContext, false), child: const Text('انصراف')),
303 + FilledButton(
304 + onPressed: () async {
305 + if (title.text.trim().isEmpty) return;
306 + final shared = visibility.value != 'private';
307 + await widget.api.createPlanItem({
308 + 'kind': kind.value,
309 + 'title': title.text.trim(),
310 + 'startsAt': when.toUtc().toIso8601String(),
311 + 'dueAt': when.add(const Duration(hours: 1)).toUtc().toIso8601String(),
312 + 'visibility': visibility.value,
313 + if (shared && familyId != null) 'familyId': familyId,
314 + 'reminderMinutesBefore': [15],
315 + });
316 + if (dialogContext.mounted) Navigator.pop(dialogContext, true);
317 + },
318 + child: const Text('ذخیره'),
319 + ),
320 + ],
321 + ),
322 + );
323 + title.dispose();
324 + kind.dispose();
325 + visibility.dispose();
326 + if (saved == true && mounted) await reload();
327 + }
328 +
329 + Future<void> reschedule(Map<String, dynamic> item) async {
330 + final base = parseDate(item['due_at'] ?? item['starts_at']) ?? DateTime.now();
331 + final next = base.add(const Duration(days: 1));
332 + try {
333 + await widget.api.updatePlanItem(item['id'].toString(), {
334 + if (item['starts_at'] != null) 'startsAt': next.toUtc().toIso8601String(),
335 + if (item['due_at'] != null) 'dueAt': next.toUtc().toIso8601String(),
336 + });
337 + await reload();
338 + } catch (_) {
339 + await OfflineStore.instance.enqueue({
340 + 'id': DateTime.now().microsecondsSinceEpoch.toString() + '-' + Random().nextInt(99999).toString(),
341 + 'entityType': 'plan_item',
342 + 'entityId': item['id'],
343 + 'operation': 'reschedule',
344 + 'clientUpdatedAt': DateTime.now().toUtc().toIso8601String(),
345 + 'payload': {'dueAt': next.toUtc().toIso8601String()},
346 + });
347 + }
348 + }
349 +
350 + @override
351 + Widget build(BuildContext context) => FutureBuilder<LoadResult>(
352 + future: future,
353 + builder: (context, snapshot) {
354 + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
355 + final result = snapshot.data!;
356 + return Scaffold(
357 + backgroundColor: Colors.transparent,
358 + floatingActionButton: FloatingActionButton.extended(
359 + onPressed: createItem,
360 + icon: const Icon(Icons.add),
361 + label: const Text('جدید'),
362 + ),
363 + body: RefreshIndicator(
364 + onRefresh: reload,
365 + child: ListView(
366 + padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
367 + children: [
368 + if (result.offline)
369 + const Card(child: ListTile(
370 + leading: Icon(Icons.cloud_off_outlined),
371 + title: Text('حالت آفلاین'),
372 + subtitle: Text('آخرین برنامه ذخیره‌شده نمایش داده می‌شود.'),
373 + )),
374 + if (result.items.isEmpty)
375 + const EmptyCard(
376 + icon: Icons.event_note_outlined,
377 + title: 'هنوز برنامه‌ای نداری',
378 + subtitle: 'کار، رویداد، روتین، هدف یا جلسه مطالعه اضافه کن.',
379 + )
380 + else
381 + ...result.items.map((item) => Card(
382 + child: ListTile(
383 + title: Text(item['title']?.toString() ?? ''),
384 + subtitle: Text(
385 + faKind(item['kind']?.toString() ?? 'task') +
386 + (shortDate(item['starts_at'] ?? item['due_at']).isEmpty ? '' : ' · ' + shortDate(item['starts_at'] ?? item['due_at'])),
387 + ),
388 + trailing: PopupMenuButton<String>(
389 + onSelected: (value) async {
390 + if (value == 'complete') {
391 + await widget.api.updatePlanItem(item['id'].toString(), {'status': 'completed'});
392 + await reload();
393 + } else if (value == 'tomorrow') {
394 + await reschedule(item);
395 + }
396 + },
397 + itemBuilder: (_) => const [
398 + PopupMenuItem(value: 'complete', child: Text('انجام شد')),
399 + PopupMenuItem(value: 'tomorrow', child: Text('انتقال به فردا')),
400 + ],
401 + ),
402 + ),
403 + )),
404 + ],
405 + ),
406 + ),
407 + );
408 + },
409 + );
410 +}
411 +
412 +class SchoolPage extends StatefulWidget {
413 + const SchoolPage({super.key, required this.api});
414 + final IdentityApi api;
415 + @override
416 + State<SchoolPage> createState() => _SchoolPageState();
417 +}
418 +
419 +class _SchoolPageState extends State<SchoolPage> {
420 + late Future<SchoolLoad> future;
421 + @override
422 + void initState() {
423 + super.initState();
424 + future = load();
425 + }
426 +
427 + Future<SchoolLoad> load() async {
428 + final profile = await widget.api.getProfile();
429 + final userId = profile['user_id']?.toString() ?? '';
430 + if (userId.isEmpty) return SchoolLoad(userId, const {}, false);
431 + try {
432 + final overview = await widget.api.getSchoolOverview(userId);
433 + await OfflineStore.instance.cacheSchool([{'userId': userId, 'overview': overview}]);
434 + return SchoolLoad(userId, overview, false);
435 + } catch (_) {
436 + final cached = await OfflineStore.instance.readSchool();
437 + if (cached.isNotEmpty) {
438 + return SchoolLoad(
439 + cached.first['userId']?.toString() ?? userId,
440 + Map<String, dynamic>.from(cached.first['overview'] as Map? ?? const {}),
441 + true,
442 + );
443 + }
444 + return SchoolLoad(userId, const {}, true);
445 + }
446 + }
447 +
448 + Future<void> reload() async {
449 + setState(() => future = load());
450 + await future;
451 + }
452 +
453 + Future<void> quickSetup() async {
454 + var contexts = await widget.api.listLifeContexts();
455 + Map<String, dynamic>? student;
456 + for (final row in contexts) {
457 + if (row['kind'] == 'student') { student = row; break; }
458 + }
459 + student ??= await widget.api.createLifeContext(kind: 'student', title: 'مدرسه');
460 + final now = DateTime.now();
461 + final year = await widget.api.createAcademicYear({
462 + 'lifeContextId': student['id'],
463 + 'title': 'سال تحصیلی ' + now.year.toString() + '-' + (now.year + 1).toString(),
464 + 'startsOn': now.year.toString() + '-09-01',
465 + 'endsOn': (now.year + 1).toString() + '-06-30',
466 + });
467 + final term = await widget.api.createAcademicTerm(year['id'].toString(), {
468 + 'title': 'نیمسال اول',
469 + 'startsOn': now.year.toString() + '-09-01',
470 + 'endsOn': (now.year + 1).toString() + '-01-31',
471 + });
472 + await widget.api.createSubject(term['id'].toString(), {'name': 'ریاضی'});
473 + await reload();
474 + }
475 +
476 + Future<void> addSchoolItem(String kind) async {
477 + final data = await future;
478 + final subjects = data.overview['subjects'] as List<dynamic>? ?? const [];
479 + if (subjects.isEmpty) return;
480 + final title = TextEditingController();
481 + final first = Map<String, dynamic>.from(subjects.first as Map);
482 + final selected = ValueNotifier<String>(first['id'].toString());
483 + final saved = await showDialog<bool>(
484 + context: context,
485 + builder: (dialogContext) => AlertDialog(
486 + title: Text(kind == 'exam' ? 'امتحان جدید' : 'تکلیف جدید'),
487 + content: Column(mainAxisSize: MainAxisSize.min, children: [
488 + TextField(controller: title, decoration: const InputDecoration(labelText: 'عنوان')),
489 + const SizedBox(height: 12),
490 + ValueListenableBuilder<String>(
491 + valueListenable: selected,
492 + builder: (_, value, __) => DropdownButtonFormField<String>(
493 + initialValue: value,
494 + decoration: const InputDecoration(labelText: 'درس'),
495 + items: subjects.map((raw) {
496 + final row = Map<String, dynamic>.from(raw as Map);
497 + return DropdownMenuItem<String>(
498 + value: row['id'].toString(),
499 + child: Text(row['name']?.toString() ?? ''),
500 + );
501 + }).toList(),
502 + onChanged: (v) { if (v != null) selected.value = v; },
503 + ),
504 + ),
505 + ]),
506 + actions: [
507 + TextButton(onPressed: () => Navigator.pop(dialogContext, false), child: const Text('انصراف')),
508 + FilledButton(
509 + onPressed: () async {
510 + if (title.text.trim().isEmpty) return;
511 + final due = DateTime.now().add(const Duration(days: 2));
512 + await widget.api.createPlanItem({
513 + 'kind': kind,
514 + 'title': title.text.trim(),
515 + 'subjectId': selected.value,
516 + 'dueAt': due.toUtc().toIso8601String(),
517 + 'visibility': 'private',
518 + 'reminderMinutesBefore': [60, 1440],
519 + });
520 + if (dialogContext.mounted) Navigator.pop(dialogContext, true);
521 + },
522 + child: const Text('ذخیره'),
523 + ),
524 + ],
525 + ),
526 + );
527 + title.dispose();
528 + selected.dispose();
529 + if (saved == true && mounted) await reload();
530 + }
531 +
532 + @override
533 + Widget build(BuildContext context) => FutureBuilder<SchoolLoad>(
534 + future: future,
535 + builder: (context, snapshot) {
536 + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
537 + final data = snapshot.data!;
538 + final years = data.overview['years'] as List<dynamic>? ?? const [];
539 + final subjects = data.overview['subjects'] as List<dynamic>? ?? const [];
540 + final workload = data.overview['workload'] as List<dynamic>? ?? const [];
541 + final grades = data.overview['grades'] as List<dynamic>? ?? const [];
542 + return ListView(
543 + padding: const EdgeInsets.all(16),
544 + children: [
545 + if (data.offline)
546 + const Card(child: ListTile(leading: Icon(Icons.cloud_off_outlined), title: Text('اطلاعات مدرسه از کش نمایش داده می‌شود'))),
547 + if (years.isEmpty)
548 + EmptyCard(
549 + icon: Icons.school_outlined,
550 + title: 'مدرسه را آماده کن',
551 + subtitle: 'سال تحصیلی، نیمسال و اولین درس را با شروع سریع بساز.',
552 + action: FilledButton.icon(
553 + onPressed: quickSetup,
554 + icon: const Icon(Icons.auto_fix_high),
555 + label: const Text('شروع سریع'),
556 + ),
557 + )
558 + else ...[
559 + Card(
560 + child: Padding(
561 + padding: const EdgeInsets.all(16),
562 + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
563 + Text('مدرسه', style: Theme.of(context).textTheme.headlineSmall),
564 + const SizedBox(height: 10),
565 + Wrap(spacing: 8, runSpacing: 8, children: [
566 + Chip(label: Text(subjects.length.toString() + ' درس')),
567 + Chip(label: Text(workload.length.toString() + ' کار درسی پیش‌رو')),
568 + Chip(label: Text(grades.length.toString() + ' نمره')),
569 + ]),
570 + const SizedBox(height: 12),
571 + Row(children: [
572 + Expanded(child: FilledButton.icon(
573 + onPressed: () => addSchoolItem('assignment'),
574 + icon: const Icon(Icons.assignment_add),
575 + label: const Text('تکلیف'),
576 + )),
577 + const SizedBox(width: 8),
578 + Expanded(child: OutlinedButton.icon(
579 + onPressed: () => addSchoolItem('exam'),
580 + icon: const Icon(Icons.quiz_outlined),
581 + label: const Text('امتحان'),
582 + )),
583 + ]),
584 + ]),
585 + ),
586 + ),
587 + const SizedBox(height: 12),
588 + Text('درس‌ها', style: Theme.of(context).textTheme.titleMedium),
589 + ...subjects.map((raw) {
590 + final row = Map<String, dynamic>.from(raw as Map);
591 + return Card(child: ListTile(
592 + leading: const Icon(Icons.menu_book_outlined),
593 + title: Text(row['name']?.toString() ?? ''),
594 + subtitle: Text(row['teacher_name']?.toString() ?? row['term_title']?.toString() ?? ''),
595 + ));
596 + }),
597 + const SizedBox(height: 12),
598 + Text('کارهای درسی پیش‌رو', style: Theme.of(context).textTheme.titleMedium),
599 + ...workload.map((raw) {
600 + final row = Map<String, dynamic>.from(raw as Map);
601 + return Card(child: ListTile(
602 + title: Text(row['title']?.toString() ?? ''),
603 + subtitle: Text(faKind(row['kind']?.toString() ?? '') + ' · ' + shortDate(row['due_at'] ?? row['starts_at'])),
604 + ));
605 + }),
606 + ],
607 + ],
608 + );
609 + },
610 + );
611 +}
612 +
613 +class ParentFamilyDashboard extends StatefulWidget {
614 + const ParentFamilyDashboard({super.key, required this.api});
615 + final IdentityApi api;
616 + @override
617 + State<ParentFamilyDashboard> createState() => _ParentFamilyDashboardState();
618 +}
619 +
620 +class _ParentFamilyDashboardState extends State<ParentFamilyDashboard> {
621 + late Future<List<Map<String, dynamic>>> families;
622 + @override
623 + void initState() {
624 + super.initState();
625 + families = widget.api.listFamilies();
626 + }
627 +
628 + @override
629 + Widget build(BuildContext context) => FutureBuilder<List<Map<String, dynamic>>>(
630 + future: families,
631 + builder: (context, snapshot) {
632 + if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
633 + if (snapshot.data!.isEmpty) {
634 + return const EmptyCard(
635 + icon: Icons.family_restroom,
636 + title: 'خانواده‌ای متصل نیست',
637 + subtitle: 'از بخش پروفایل فضای خانواده بساز یا به آن بپیوند.',
638 + );
639 + }
640 + return ListView(
641 + padding: const EdgeInsets.all(16),
642 + children: snapshot.data!.map((family) => FamilyDashboardCard(api: widget.api, family: family)).toList(),
643 + );
644 + },
645 + );
646 +}
647 +
648 +class FamilyDashboardCard extends StatefulWidget {
649 + const FamilyDashboardCard({super.key, required this.api, required this.family});
650 + final IdentityApi api;
651 + final Map<String, dynamic> family;
652 + @override
653 + State<FamilyDashboardCard> createState() => _FamilyDashboardCardState();
654 +}
655 +
656 +class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
657 + late Future<List<Map<String, dynamic>>> members;
658 + @override
659 + void initState() {
660 + super.initState();
661 + members = widget.api.listFamilyMembers(widget.family['id'].toString());
662 + }
663 +
664 + Future<void> openChild(Map<String, dynamic> child) async {
665 + final summary = await widget.api.getChildSupportSummary(
666 + widget.family['id'].toString(),
667 + child['user_id'].toString(),
668 + );
669 + if (!mounted) return;
670 + final metrics = Map<String, dynamic>.from(summary['metrics'] as Map? ?? const {});
671 + final upcoming = summary['upcoming'] as List<dynamic>? ?? const [];
672 + await showDialog<void>(
673 + context: context,
674 + builder: (dialogContext) => AlertDialog(
675 + title: Text('خلاصه حمایت · ' + (child['display_name']?.toString() ?? 'فرزند')),
676 + content: SizedBox(
677 + width: 520,
678 + child: SingleChildScrollView(
679 + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
680 + Wrap(spacing: 8, runSpacing: 8, children: [
681 + Chip(label: Text((metrics['overdue'] ?? 0).toString() + ' عقب‌افتاده')),
682 + Chip(label: Text((metrics['completedLast7Days'] ?? 0).toString() + ' انجام‌شده')),
683 + Chip(label: Text((metrics['studyMinutesLast7Days'] ?? 0).toString() + ' دقیقه مطالعه')),
684 + if (metrics['gradePercent'] != null) Chip(label: Text('میانگین ' + metrics['gradePercent'].toString() + '٪')),
685 + ]),
686 + const SizedBox(height: 10),
687 + const Text('موارد پیش‌رو'),
688 + ...upcoming.take(8).map((raw) {
689 + final row = Map<String, dynamic>.from(raw as Map);
690 + return ListTile(
691 + dense: true,
692 + title: Text(row['title']?.toString() ?? ''),
693 + subtitle: Text(faKind(row['kind']?.toString() ?? '') + ' · ' + shortDate(row['due_at'] ?? row['starts_at'])),
694 + );
695 + }),
696 + ]),
697 + ),
698 + ),
699 + actions: [
700 + TextButton(onPressed: () => Navigator.pop(dialogContext), child: const Text('بستن')),
701 + ],
702 + ),
703 + );
704 + }
705 +
706 + @override
707 + Widget build(BuildContext context) => Card(
708 + child: Padding(
709 + padding: const EdgeInsets.all(14),
710 + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
711 + Text(widget.family['name']?.toString() ?? 'خانواده', style: Theme.of(context).textTheme.titleLarge),
712 + const SizedBox(height: 8),
713 + FutureBuilder<List<Map<String, dynamic>>>(
714 + future: members,
715 + builder: (context, snapshot) {
716 + if (!snapshot.hasData) return const LinearProgressIndicator();
717 + final children = snapshot.data!.where((row) => row['role'] == 'teen_minor').toList();
718 + if (children.isEmpty) return const Text('هنوز فرزند/نوجوانی به این خانواده متصل نیست.');
719 + return Column(
720 + children: children.map((child) => ListTile(
721 + leading: const CircleAvatar(child: Icon(Icons.school_outlined)),
722 + title: Text(child['display_name']?.toString() ?? 'فرزند'),
723 + subtitle: const Text('برنامه، تکالیف، امتحان‌ها و پیشرفت مجاز'),
724 + trailing: const Icon(Icons.chevron_left),
725 + onTap: () => openChild(child),
726 + )).toList(),
727 + );
728 + },
729 + ),
730 + ]),
731 + ),
732 + );
733 +}
734 +
735 +class EmptyCard extends StatelessWidget {
736 + const EmptyCard({
737 + super.key,
738 + required this.icon,
739 + required this.title,
740 + required this.subtitle,
741 + this.action,
742 + });
743 + final IconData icon;
744 + final String title;
745 + final String subtitle;
746 + final Widget? action;
747 +
748 + @override
749 + Widget build(BuildContext context) => Card(
750 + child: Padding(
751 + padding: const EdgeInsets.all(22),
752 + child: Column(children: [
753 + Icon(icon, size: 42),
754 + const SizedBox(height: 10),
755 + Text(title, style: Theme.of(context).textTheme.titleMedium),
756 + const SizedBox(height: 6),
757 + Text(subtitle, textAlign: TextAlign.center),
758 + if (action != null) ...[const SizedBox(height: 14), action!],
759 + ]),
760 + ),
761 + );
762 +}
763 +
764 +class LoadResult {
765 + const LoadResult(this.items, this.offline, {this.reminders = const []});
766 + final List<Map<String, dynamic>> items;
767 + final bool offline;
768 + final List<Map<String, dynamic>> reminders;
769 +}
770 +
771 +class SchoolLoad {
772 + const SchoolLoad(this.userId, this.overview, this.offline);
773 + final String userId;
774 + final Map<String, dynamic> overview;
775 + final bool offline;
776 +}
apps/lifemate/pubspec.yaml
+1
@@ -11,6 +11,7 @@ dependencies:
11 sdk: flutter
12 intl: ^0.20.2
13 http: ^1.5.0
14 + shared_preferences: ^2.5.3
15 dev_dependencies:
16 flutter_test:
17 sdk: flutter
apps/lifemate/test/app_test.dart
+143
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
2 import 'package:flutter_test/flutter_test.dart';
3 import 'package:lifemate/api.dart';
4 import 'package:lifemate/main.dart';
5 +import 'package:shared_preferences/shared_preferences.dart';
6
7 class FakeApi implements IdentityApi {
8 FakeApi({
@@ -46,6 +47,7 @@ class FakeApi implements IdentityApi {
47 Future<Map<String, dynamic>> getProfile() async => {
48 'display_name': role == 'teen_minor' ? 'آرام' : 'والد',
49 'email_normalized': 'user@example.test',
50 + 'user_id': role == 'teen_minor' ? 'teen-1' : 'parent-1',
51 'theme_preference': themePreference,
52 };
53
@@ -98,9 +100,150 @@ class FakeApi implements IdentityApi {
100 required String guardianUserId,
101 required String minorUserId,
102 }) async {}
103 +
104 + @override
105 + Future<List<Map<String, dynamic>>> getToday({
106 + required DateTime from,
107 + required DateTime to,
108 + }) async => [
109 + {
110 + 'id': 'today-1',
111 + 'kind': 'task',
112 + 'title': 'مرور برنامه امروز',
113 + 'status': 'planned',
114 + 'due_at': DateTime.now().add(const Duration(hours: 1)).toUtc().toIso8601String(),
115 + }
116 + ];
117 +
118 + @override
119 + Future<List<Map<String, dynamic>>> listPlanItems({
120 + DateTime? from,
121 + DateTime? to,
122 + String? kind,
123 + }) async => [
124 + {
125 + 'id': 'plan-1',
126 + 'kind': 'task',
127 + 'title': 'تکمیل تمرین',
128 + 'status': 'planned',
129 + 'due_at': DateTime.now().add(const Duration(days: 1)).toUtc().toIso8601String(),
130 + }
131 + ];
132 +
133 + @override
134 + Future<Map<String, dynamic>> createPlanItem(Map<String, dynamic> data) async =>
135 + {'id': 'new-plan', ...data};
136 +
137 + @override
138 + Future<Map<String, dynamic>> updatePlanItem(
139 + String itemId,
140 + Map<String, dynamic> data,
141 + ) async =>
142 + {'id': itemId, ...data};
143 +
144 + @override
145 + Future<List<Map<String, dynamic>>> listLifeContexts() async => [];
146 +
147 + @override
148 + Future<Map<String, dynamic>> createLifeContext({
149 + required String kind,
150 + required String title,
151 + }) async =>
152 + {'id': 'ctx-1', 'kind': kind, 'title': title};
153 +
154 + @override
155 + Future<Map<String, dynamic>> createAcademicYear(
156 + Map<String, dynamic> data,
157 + ) async =>
158 + {'id': 'year-1', ...data};
159 +
160 + @override
161 + Future<Map<String, dynamic>> createAcademicTerm(
162 + String yearId,
163 + Map<String, dynamic> data,
164 + ) async =>
165 + {'id': 'term-1', ...data};
166 +
167 + @override
168 + Future<Map<String, dynamic>> createSubject(
169 + String termId,
170 + Map<String, dynamic> data,
171 + ) async =>
172 + {'id': 'subject-1', ...data};
173 +
174 + @override
175 + Future<Map<String, dynamic>> createClassSession(
176 + String subjectId,
177 + Map<String, dynamic> data,
178 + ) async =>
179 + {'id': 'class-1', ...data};
180 +
181 + @override
182 + Future<Map<String, dynamic>> setGrade(
183 + String itemId, {
184 + required num points,
185 + required num outOf,
186 + }) async =>
187 + {
188 + 'id': itemId,
189 + 'grade_points': points,
190 + 'grade_out_of': outOf,
191 + };
192 +
193 + @override
194 + Future<List<Map<String, dynamic>>> claimDueReminders() async => [];
195 +
196 + @override
197 + Future<Map<String, dynamic>> getSchoolOverview(String studentUserId) async => {
198 + 'years': [
199 + {'id': 'year-1', 'title': 'سال تحصیلی'}
200 + ],
201 + 'subjects': [
202 + {'id': 'subject-1', 'name': 'ریاضی', 'term_title': 'نیمسال اول'}
203 + ],
204 + 'workload': const [],
205 + 'grades': const [],
206 + };
207 +
208 + @override
209 + Future<List<Map<String, dynamic>>> getTimetable(String studentUserId) async =>
210 + [];
211 +
212 + @override
213 + Future<List<Map<String, dynamic>>> getFamilyCalendar(String familyId) async =>
214 + [];
215 +
216 + @override
217 + Future<Map<String, dynamic>> getChildSupportSummary(
218 + String familyId,
219 + String studentUserId,
220 + ) async =>
221 + {
222 + 'upcoming': const [],
223 + 'metrics': {
224 + 'completedLast7Days': 3,
225 + 'overdue': 1,
226 + 'studyMinutesLast7Days': 90,
227 + 'gradePercent': 85,
228 + }
229 + };
230 +
231 + @override
232 + Future<Map<String, dynamic>> submitSyncMutations(
233 + List<Map<String, dynamic>> mutations,
234 + ) async =>
235 + {
236 + 'results': mutations
237 + .map((m) => {'id': m['id'], 'status': 'accepted'})
238 + .toList(),
239 + };
240 }
241
242 void main() {
243 + setUp(() {
244 + SharedPreferences.setMockInitialValues({});
245 + });
246 +
247 testWidgets('starts in Persian RTL with identity actions', (tester) async {
248 await tester.pumpWidget(LifeMateApp(api: FakeApi()));
249
backend/migrations/0003_planner_school_family.sql new
+214
@@ -0,0 +1,214 @@
1 +begin;
2 +
3 +create type life_context_kind as enum ('student','work','personal');
4 +create type plan_item_kind as enum ('task','event','routine','goal','assignment','exam','study_session');
5 +create type plan_item_status as enum ('planned','in_progress','completed','cancelled');
6 +create type plan_priority as enum ('low','normal','high','urgent');
7 +create type sharing_scope as enum ('private','selected_members','parent_guardian','family');
8 +create type reminder_status as enum ('scheduled','claimed','sent','cancelled','failed');
9 +
10 +create table life_context (
11 + id uuid primary key default gen_random_uuid(),
12 + user_id uuid not null references app_user(id) on delete cascade,
13 + kind life_context_kind not null,
14 + title text not null check (char_length(title) between 1 and 120),
15 + active boolean not null default true,
16 + created_at timestamptz not null default now()
17 +);
18 +create index life_context_user_idx on life_context(user_id) where active;
19 +
20 +create table academic_year (
21 + id uuid primary key default gen_random_uuid(),
22 + student_user_id uuid not null references app_user(id) on delete cascade,
23 + life_context_id uuid not null references life_context(id) on delete cascade,
24 + title text not null,
25 + starts_on date not null,
26 + ends_on date not null,
27 + active boolean not null default true,
28 + created_at timestamptz not null default now(),
29 + check (ends_on >= starts_on)
30 +);
31 +create index academic_year_student_idx on academic_year(student_user_id, starts_on desc);
32 +
33 +create table academic_term (
34 + id uuid primary key default gen_random_uuid(),
35 + academic_year_id uuid not null references academic_year(id) on delete cascade,
36 + title text not null,
37 + starts_on date not null,
38 + ends_on date not null,
39 + created_at timestamptz not null default now(),
40 + check (ends_on >= starts_on)
41 +);
42 +
43 +create table subject (
44 + id uuid primary key default gen_random_uuid(),
45 + student_user_id uuid not null references app_user(id) on delete cascade,
46 + academic_term_id uuid not null references academic_term(id) on delete cascade,
47 + name text not null check (char_length(name) between 1 and 120),
48 + teacher_name text,
49 + color_key text,
50 + created_at timestamptz not null default now()
51 +);
52 +create index subject_student_term_idx on subject(student_user_id, academic_term_id);
53 +
54 +create table class_session (
55 + id uuid primary key default gen_random_uuid(),
56 + subject_id uuid not null references subject(id) on delete cascade,
57 + weekday smallint not null check (weekday between 1 and 7),
58 + starts_at time not null,
59 + ends_at time not null,
60 + location text,
61 + recurrence_until date,
62 + created_at timestamptz not null default now(),
63 + check (ends_at > starts_at)
64 +);
65 +create index class_session_subject_weekday_idx on class_session(subject_id, weekday, starts_at);
66 +
67 +create table plan_item (
68 + id uuid primary key default gen_random_uuid(),
69 + owner_user_id uuid not null references app_user(id) on delete cascade,
70 + family_id uuid references family_workspace(id) on delete cascade,
71 + subject_id uuid references subject(id) on delete set null,
72 + kind plan_item_kind not null,
73 + title text not null check (char_length(title) between 1 and 240),
74 + notes text,
75 + status plan_item_status not null default 'planned',
76 + priority plan_priority not null default 'normal',
77 + visibility sharing_scope not null default 'private',
78 + starts_at timestamptz,
79 + due_at timestamptz,
80 + duration_minutes integer check (duration_minutes is null or duration_minutes between 1 and 1440),
81 + recurrence_rule text,
82 + parent_item_id uuid references plan_item(id) on delete set null,
83 + grade_points numeric(8,2),
84 + grade_out_of numeric(8,2),
85 + completed_at timestamptz,
86 + created_at timestamptz not null default now(),
87 + updated_at timestamptz not null default now(),
88 + check (due_at is null or starts_at is null or due_at >= starts_at),
89 + check ((grade_points is null and grade_out_of is null) or (grade_points is not null and grade_out_of is not null and grade_out_of > 0))
90 +);
91 +create index plan_item_owner_time_idx on plan_item(owner_user_id, coalesce(starts_at,due_at), status);
92 +create index plan_item_family_time_idx on plan_item(family_id, coalesce(starts_at,due_at)) where family_id is not null;
93 +create index plan_item_subject_idx on plan_item(subject_id, kind, due_at) where subject_id is not null;
94 +
95 +create table sharing_grant (
96 + resource_type text not null check (resource_type in ('plan_item')),
97 + resource_id uuid not null,
98 + grantee_user_id uuid not null references app_user(id) on delete cascade,
99 + granted_by uuid not null references app_user(id) on delete cascade,
100 + created_at timestamptz not null default now(),
101 + primary key (resource_type, resource_id, grantee_user_id)
102 +);
103 +create index sharing_grant_grantee_idx on sharing_grant(grantee_user_id, resource_type, resource_id);
104 +
105 +create table reminder (
106 + id uuid primary key default gen_random_uuid(),
107 + plan_item_id uuid not null references plan_item(id) on delete cascade,
108 + owner_user_id uuid not null references app_user(id) on delete cascade,
109 + minutes_before integer not null check (minutes_before between 0 and 10080),
110 + scheduled_for timestamptz not null,
111 + status reminder_status not null default 'scheduled',
112 + claimed_at timestamptz,
113 + delivered_at timestamptz,
114 + failure_reason text,
115 + created_at timestamptz not null default now(),
116 + unique(plan_item_id, owner_user_id, minutes_before)
117 +);
118 +create index reminder_due_idx on reminder(scheduled_for) where status='scheduled';
119 +
120 +create table notification_preference (
121 + user_id uuid primary key references app_user(id) on delete cascade,
122 + reminders_enabled boolean not null default true,
123 + quiet_start time,
124 + quiet_end time,
125 + timezone text not null default 'Asia/Tehran',
126 + updated_at timestamptz not null default now()
127 +);
128 +
129 +create table notification_outbox (
130 + id bigint generated always as identity primary key,
131 + reminder_id uuid not null unique references reminder(id) on delete cascade,
132 + user_id uuid not null references app_user(id) on delete cascade,
133 + payload jsonb not null,
134 + available_at timestamptz not null default now(),
135 + delivered_at timestamptz,
136 + attempts integer not null default 0,
137 + last_error text
138 +);
139 +create index notification_outbox_pending_idx on notification_outbox(available_at) where delivered_at is null;
140 +
141 +create table sync_mutation (
142 + id uuid primary key,
143 + user_id uuid not null references app_user(id) on delete cascade,
144 + entity_type text not null,
145 + entity_id uuid,
146 + operation text not null check (operation in ('create','update','complete','reschedule')),
147 + client_updated_at timestamptz not null,
148 + payload jsonb not null,
149 + accepted_at timestamptz not null default now(),
150 + unique(user_id,id)
151 +);
152 +
153 +create function can_view_student_academic(p_viewer uuid, p_student uuid) returns boolean
154 +language sql stable as $$
155 + select p_viewer=p_student or exists(
156 + select 1
157 + from guardian_relationship g
158 + join family_membership gm
159 + on gm.family_id=g.family_id and gm.user_id=g.guardian_user_id and gm.ended_at is null
160 + join family_membership sm
161 + on sm.family_id=g.family_id and sm.user_id=g.minor_user_id and sm.ended_at is null
162 + where g.guardian_user_id=p_viewer
163 + and g.minor_user_id=p_student
164 + and g.active
165 + )
166 +$$;
167 +
168 +create function can_view_plan_item(p_viewer uuid, p_item uuid) returns boolean
169 +language sql stable as $$
170 + select exists(
171 + select 1
172 + from plan_item p
173 + where p.id=p_item
174 + and (
175 + p.owner_user_id=p_viewer
176 + or exists(
177 + select 1 from sharing_grant sg
178 + where sg.resource_type='plan_item'
179 + and sg.resource_id=p.id
180 + and sg.grantee_user_id=p_viewer
181 + )
182 + or (
183 + p.visibility='family'
184 + and p.family_id is not null
185 + and is_active_family_member(p.family_id,p_viewer)
186 + )
187 + or (
188 + p.visibility='parent_guardian'
189 + and p.family_id is not null
190 + and is_active_guardian(p.family_id,p_viewer,p.owner_user_id)
191 + )
192 + )
193 + )
194 +$$;
195 +
196 +create function recompute_reminder_schedule(p_plan_item uuid) returns void
197 +language plpgsql as $$
198 +declare
199 + base_time timestamptz;
200 +begin
201 + select coalesce(starts_at,due_at) into base_time from plan_item where id=p_plan_item;
202 + if base_time is null then
203 + update reminder set status='cancelled' where plan_item_id=p_plan_item and status in ('scheduled','claimed');
204 + return;
205 + end if;
206 + update reminder
207 + set scheduled_for = base_time - make_interval(mins => minutes_before),
208 + status = case when status in ('sent','failed') then status else 'scheduled' end,
209 + claimed_at = null
210 + where plan_item_id=p_plan_item
211 + and status <> 'cancelled';
212 +end $$;
213 +
214 +commit;
backend/scripts/migrate.js
+21 -6
@@ -4,12 +4,27 @@ import pg from 'pg';
4
5 const { Client } = pg;
6 const databaseUrl = process.env.DATABASE_URL;
7 -if (!databaseUrl) throw new Error('DATABASE_URL is required');
8 -
9 -const client = new Client({
10 - connectionString: databaseUrl,
11 - ssl: databaseUrl.includes('localhost') ? false : { rejectUnauthorized: false },
12 -});
7 +const client = new Client(
8 + databaseUrl
9 + ? {
10 + connectionString: databaseUrl,
11 + ssl:
12 + process.env.PGSSLMODE === 'require'
13 + ? { rejectUnauthorized: false }
14 + : false,
15 + }
16 + : {
17 + host: process.env.PGHOST,
18 + port: Number(process.env.PGPORT ?? 5432),
19 + database: process.env.PGDATABASE,
20 + user: process.env.PGUSER,
21 + password: process.env.PGPASSWORD,
22 + ssl:
23 + process.env.PGSSLMODE === 'require'
24 + ? { rejectUnauthorized: false }
25 + : false,
26 + },
27 +);
28
29 await client.connect();
30 try {
backend/src/phase3.js new
+728
@@ -0,0 +1,728 @@
1 +import express from 'express';
2 +
3 +const allowedKinds = new Set(['task','event','routine','goal','assignment','exam','study_session']);
4 +const allowedStatus = new Set(['planned','in_progress','completed','cancelled']);
5 +const allowedPriority = new Set(['low','normal','high','urgent']);
6 +const allowedVisibility = new Set(['private','selected_members','parent_guardian','family']);
7 +
8 +function asDate(value) {
9 + if (value == null || value === '') return null;
10 + const d = new Date(value);
11 + return Number.isNaN(d.getTime()) ? null : d;
12 +}
13 +
14 +async function familyMember(pool, familyId, userId) {
15 + const r = await pool.query(
16 + 'select role,is_admin from family_membership where family_id=$1 and user_id=$2 and ended_at is null',
17 + [familyId, userId],
18 + );
19 + return r.rows[0] ?? null;
20 +}
21 +
22 +async function assertPlanWrite(pool, itemId, userId) {
23 + const r = await pool.query('select * from plan_item where id=$1', [itemId]);
24 + if (!r.rowCount) return { error: 'not_found', status: 404 };
25 + if (r.rows[0].owner_user_id !== userId) {
26 + return { error: 'forbidden', status: 403 };
27 + }
28 + return { item: r.rows[0] };
29 +}
30 +
31 +async function assertStudentAcademic(pool, studentUserId, viewerUserId) {
32 + const r = await pool.query(
33 + 'select can_view_student_academic($1,$2) as allowed',
34 + [viewerUserId, studentUserId],
35 + );
36 + return r.rows[0]?.allowed === true;
37 +}
38 +
39 +async function audit(pool, actorUserId, familyId, action, targetType, targetId, metadata = {}) {
40 + await pool.query(
41 + `insert into access_audit(actor_user_id,family_id,action,target_type,target_id,metadata)
42 + values($1,$2,$3,$4,$5,$6::jsonb)`,
43 + [actorUserId, familyId, action, targetType, String(targetId ?? ''), JSON.stringify(metadata)],
44 + );
45 +}
46 +
47 +export function createPhase3Router({ pool, auth }) {
48 + const router = express.Router();
49 +
50 + router.get('/today', auth, async (req, res) => {
51 + const from = asDate(req.query.from) ?? new Date();
52 + const to = asDate(req.query.to) ?? new Date(from.getTime() + 24 * 60 * 60 * 1000);
53 + const r = await pool.query(
54 + `select p.*
55 + from plan_item p
56 + where can_view_plan_item($1,p.id)
57 + and p.status not in ('completed','cancelled')
58 + and coalesce(p.starts_at,p.due_at,p.created_at) >= $2
59 + and coalesce(p.starts_at,p.due_at,p.created_at) < $3
60 + order by coalesce(p.starts_at,p.due_at,p.created_at), p.priority desc`,
61 + [req.identity.sub, from, to],
62 + );
63 + res.json({ items: r.rows });
64 + });
65 +
66 + router.get('/plan-items', auth, async (req, res) => {
67 + const from = asDate(req.query.from);
68 + const to = asDate(req.query.to);
69 + const values = [req.identity.sub];
70 + const filters = ['can_view_plan_item($1,p.id)'];
71 + if (from) {
72 + values.push(from);
73 + filters.push(`coalesce(p.starts_at,p.due_at,p.created_at) >= $${values.length}`);
74 + }
75 + if (to) {
76 + values.push(to);
77 + filters.push(`coalesce(p.starts_at,p.due_at,p.created_at) < $${values.length}`);
78 + }
79 + if (req.query.kind && allowedKinds.has(String(req.query.kind))) {
80 + values.push(String(req.query.kind));
81 + filters.push(`p.kind = $${values.length}`);
82 + }
83 + const r = await pool.query(
84 + `select p.*
85 + from plan_item p
86 + where ${filters.join(' and ')}
87 + order by coalesce(p.starts_at,p.due_at,p.created_at), p.created_at`,
88 + values,
89 + );
90 + res.json({ items: r.rows });
91 + });
92 +
93 + router.post('/plan-items', auth, async (req, res) => {
94 + const kind = String(req.body.kind ?? 'task');
95 + const title = String(req.body.title ?? '').trim();
96 + const priority = String(req.body.priority ?? 'normal');
97 + const visibility = String(req.body.visibility ?? 'private');
98 + const familyId = req.body.familyId || null;
99 + const startsAt = asDate(req.body.startsAt);
100 + const dueAt = asDate(req.body.dueAt);
101 + if (!allowedKinds.has(kind) || !title || !allowedPriority.has(priority) || !allowedVisibility.has(visibility)) {
102 + return res.status(400).json({ error: 'invalid_plan_item' });
103 + }
104 + if (familyId) {
105 + const member = await familyMember(pool, familyId, req.identity.sub);
106 + if (!member) return res.status(403).json({ error: 'family_membership_required' });
107 + }
108 + if ((visibility === 'family' || visibility === 'parent_guardian') && !familyId) {
109 + return res.status(400).json({ error: 'family_required_for_visibility' });
110 + }
111 + if (req.body.subjectId) {
112 + const s = await pool.query('select student_user_id from subject where id=$1', [req.body.subjectId]);
113 + if (!s.rowCount || s.rows[0].student_user_id !== req.identity.sub) {
114 + return res.status(403).json({ error: 'subject_forbidden' });
115 + }
116 + }
117 +
118 + const client = await pool.connect();
119 + try {
120 + await client.query('begin');
121 + const r = await client.query(
122 + `insert into plan_item(
123 + owner_user_id,family_id,subject_id,kind,title,notes,status,priority,visibility,
124 + starts_at,due_at,duration_minutes,recurrence_rule,parent_item_id
125 + ) values($1,$2,$3,$4,$5,$6,'planned',$7,$8,$9,$10,$11,$12,$13)
126 + returning *`,
127 + [
128 + req.identity.sub, familyId, req.body.subjectId || null, kind, title,
129 + req.body.notes || null, priority, visibility, startsAt, dueAt,
130 + req.body.durationMinutes || null, req.body.recurrenceRule || null,
131 + req.body.parentItemId || null,
132 + ],
133 + );
134 + const item = r.rows[0];
135 +
136 + const selected = Array.isArray(req.body.selectedMemberIds)
137 + ? [...new Set(req.body.selectedMemberIds.map(String))]
138 + : [];
139 + if (visibility === 'selected_members') {
140 + if (!familyId || selected.length === 0) {
141 + await client.query('rollback');
142 + return res.status(400).json({ error: 'selected_members_required' });
143 + }
144 + for (const userId of selected) {
145 + const m = await client.query(
146 + 'select 1 from family_membership where family_id=$1 and user_id=$2 and ended_at is null',
147 + [familyId, userId],
148 + );
149 + if (!m.rowCount) {
150 + await client.query('rollback');
151 + return res.status(400).json({ error: 'selected_member_not_in_family' });
152 + }
153 + await client.query(
154 + `insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by)
155 + values('plan_item',$1,$2,$3)
156 + on conflict do nothing`,
157 + [item.id, userId, req.identity.sub],
158 + );
159 + }
160 + }
161 +
162 + const leadTimes = Array.isArray(req.body.reminderMinutesBefore)
163 + ? [...new Set(req.body.reminderMinutesBefore.map(Number))]
164 + : [];
165 + const baseTime = startsAt ?? dueAt;
166 + if (baseTime) {
167 + for (const minutes of leadTimes) {
168 + if (!Number.isInteger(minutes) || minutes < 0 || minutes > 10080) continue;
169 + await client.query(
170 + `insert into reminder(plan_item_id,owner_user_id,minutes_before,scheduled_for)
171 + values($1,$2,$3,$4::timestamptz - make_interval(mins => $3))
172 + on conflict(plan_item_id,owner_user_id,minutes_before)
173 + do update set scheduled_for=excluded.scheduled_for,status='scheduled',claimed_at=null`,
174 + [item.id, req.identity.sub, minutes, baseTime],
175 + );
176 + }
177 + }
178 +
179 + await client.query('commit');
180 + res.status(201).json(item);
181 + } catch (e) {
182 + await client.query('rollback').catch(() => {});
183 + throw e;
184 + } finally {
185 + client.release();
186 + }
187 + });
188 +
189 + router.patch('/plan-items/:itemId', auth, async (req, res) => {
190 + const access = await assertPlanWrite(pool, req.params.itemId, req.identity.sub);
191 + if (access.error) return res.status(access.status).json({ error: access.error });
192 +
193 + const fields = [];
194 + const values = [req.params.itemId];
195 + const add = (column, value, cast = '') => {
196 + values.push(value);
197 + fields.push(`${column}=$${values.length}${cast}`);
198 + };
199 + if (req.body.title != null) {
200 + const title = String(req.body.title).trim();
201 + if (!title) return res.status(400).json({ error: 'invalid_title' });
202 + add('title', title);
203 + }
204 + if (req.body.notes !== undefined) add('notes', req.body.notes || null);
205 + if (req.body.status != null) {
206 + const status = String(req.body.status);
207 + if (!allowedStatus.has(status)) return res.status(400).json({ error: 'invalid_status' });
208 + add('status', status);
209 + if (status === 'completed') add('completed_at', new Date());
210 + if (status !== 'completed') add('completed_at', null);
211 + }
212 + if (req.body.priority != null) {
213 + const priority = String(req.body.priority);
214 + if (!allowedPriority.has(priority)) return res.status(400).json({ error: 'invalid_priority' });
215 + add('priority', priority);
216 + }
217 + if (req.body.startsAt !== undefined) add('starts_at', asDate(req.body.startsAt));
218 + if (req.body.dueAt !== undefined) add('due_at', asDate(req.body.dueAt));
219 + if (req.body.durationMinutes !== undefined) add('duration_minutes', req.body.durationMinutes || null);
220 + if (!fields.length) return res.status(400).json({ error: 'no_changes' });
221 + fields.push('updated_at=now()');
222 +
223 + const client = await pool.connect();
224 + try {
225 + await client.query('begin');
226 + const r = await client.query(
227 + `update plan_item set ${fields.join(',')} where id=$1 returning *`,
228 + values,
229 + );
230 + if (r.rows[0].status === 'completed' || r.rows[0].status === 'cancelled') {
231 + await client.query(
232 + `update reminder set status='cancelled'
233 + where plan_item_id=$1 and status in ('scheduled','claimed')`,
234 + [req.params.itemId],
235 + );
236 + } else {
237 + await client.query('select recompute_reminder_schedule($1)', [req.params.itemId]);
238 + }
239 + await client.query('commit');
240 + res.json(r.rows[0]);
241 + } catch (e) {
242 + await client.query('rollback').catch(() => {});
243 + throw e;
244 + } finally {
245 + client.release();
246 + }
247 + });
248 +
249 + router.post('/plan-items/:itemId/reminders', auth, async (req, res) => {
250 + const access = await assertPlanWrite(pool, req.params.itemId, req.identity.sub);
251 + if (access.error) return res.status(access.status).json({ error: access.error });
252 + const minutes = Number(req.body.minutesBefore);
253 + if (!Number.isInteger(minutes) || minutes < 0 || minutes > 10080) {
254 + return res.status(400).json({ error: 'invalid_reminder' });
255 + }
256 + const baseTime = access.item.starts_at ?? access.item.due_at;
257 + if (!baseTime) return res.status(400).json({ error: 'plan_item_has_no_time' });
258 + const r = await pool.query(
259 + `insert into reminder(plan_item_id,owner_user_id,minutes_before,scheduled_for)
260 + values($1,$2,$3,$4::timestamptz - make_interval(mins => $3))
261 + on conflict(plan_item_id,owner_user_id,minutes_before)
262 + do update set scheduled_for=excluded.scheduled_for,status='scheduled',claimed_at=null
263 + returning *`,
264 + [req.params.itemId, req.identity.sub, minutes, baseTime],
265 + );
266 + res.status(201).json(r.rows[0]);
267 + });
268 +
269 + router.post('/reminders/claim-due', auth, async (req, res) => {
270 + const limit = Math.min(Math.max(Number(req.body.limit ?? 20), 1), 100);
271 + const client = await pool.connect();
272 + try {
273 + await client.query('begin');
274 + const r = await client.query(
275 + `select r.id,r.plan_item_id,r.owner_user_id,p.title,r.scheduled_for
276 + from reminder r
277 + join plan_item p on p.id=r.plan_item_id
278 + where r.owner_user_id=$1
279 + and r.status='scheduled'
280 + and r.scheduled_for <= now()
281 + and p.status not in ('completed','cancelled')
282 + order by r.scheduled_for
283 + for update skip locked
284 + limit $2`,
285 + [req.identity.sub, limit],
286 + );
287 + for (const row of r.rows) {
288 + await client.query(
289 + `update reminder set status='claimed',claimed_at=now() where id=$1`,
290 + [row.id],
291 + );
292 + await client.query(
293 + `insert into notification_outbox(reminder_id,user_id,payload)
294 + values($1,$2,$3::jsonb)
295 + on conflict(reminder_id) do nothing`,
296 + [row.id, row.owner_user_id, JSON.stringify({
297 + type: 'plan_reminder',
298 + planItemId: row.plan_item_id,
299 + title: row.title,
300 + scheduledFor: row.scheduled_for,
301 + })],
302 + );
303 + }
304 + await client.query('commit');
305 + res.json({ claimed: r.rows.length, reminders: r.rows });
306 + } catch (e) {
307 + await client.query('rollback').catch(() => {});
308 + throw e;
309 + } finally {
310 + client.release();
311 + }
312 + });
313 +
314 + router.get('/notification-outbox', auth, async (req, res) => {
315 + const r = await pool.query(
316 + `select id,reminder_id,payload,available_at,delivered_at,attempts
317 + from notification_outbox
318 + where user_id=$1
319 + order by available_at desc
320 + limit 100`,
321 + [req.identity.sub],
322 + );
323 + res.json({ notifications: r.rows });
324 + });
325 +
326 + router.get('/life-contexts', auth, async (req, res) => {
327 + const r = await pool.query(
328 + 'select * from life_context where user_id=$1 and active order by created_at',
329 + [req.identity.sub],
330 + );
331 + res.json({ contexts: r.rows });
332 + });
333 +
334 + router.post('/life-contexts', auth, async (req, res) => {
335 + const kind = String(req.body.kind ?? '');
336 + const title = String(req.body.title ?? '').trim();
337 + if (!['student','work','personal'].includes(kind) || !title) {
338 + return res.status(400).json({ error: 'invalid_life_context' });
339 + }
340 + const r = await pool.query(
341 + 'insert into life_context(user_id,kind,title) values($1,$2,$3) returning *',
342 + [req.identity.sub, kind, title],
343 + );
344 + res.status(201).json(r.rows[0]);
345 + });
346 +
347 + router.post('/school/years', auth, async (req, res) => {
348 + const title = String(req.body.title ?? '').trim();
349 + const startsOn = req.body.startsOn;
350 + const endsOn = req.body.endsOn;
351 + const lifeContextId = req.body.lifeContextId;
352 + const ctx = await pool.query(
353 + `select 1 from life_context
354 + where id=$1 and user_id=$2 and kind='student' and active`,
355 + [lifeContextId, req.identity.sub],
356 + );
357 + if (!ctx.rowCount || !title || !startsOn || !endsOn) {
358 + return res.status(400).json({ error: 'invalid_academic_year' });
359 + }
360 + const r = await pool.query(
361 + `insert into academic_year(student_user_id,life_context_id,title,starts_on,ends_on)
362 + values($1,$2,$3,$4,$5) returning *`,
363 + [req.identity.sub, lifeContextId, title, startsOn, endsOn],
364 + );
365 + res.status(201).json(r.rows[0]);
366 + });
367 +
368 + router.post('/school/years/:yearId/terms', auth, async (req, res) => {
369 + const y = await pool.query(
370 + 'select student_user_id from academic_year where id=$1',
371 + [req.params.yearId],
372 + );
373 + if (!y.rowCount) return res.status(404).json({ error: 'not_found' });
374 + if (y.rows[0].student_user_id !== req.identity.sub) {
375 + return res.status(403).json({ error: 'forbidden' });
376 + }
377 + const r = await pool.query(
378 + `insert into academic_term(academic_year_id,title,starts_on,ends_on)
379 + values($1,$2,$3,$4) returning *`,
380 + [req.params.yearId, String(req.body.title ?? '').trim(), req.body.startsOn, req.body.endsOn],
381 + );
382 + res.status(201).json(r.rows[0]);
383 + });
384 +
385 + router.post('/school/terms/:termId/subjects', auth, async (req, res) => {
386 + const t = await pool.query(
387 + `select y.student_user_id
388 + from academic_term t
389 + join academic_year y on y.id=t.academic_year_id
390 + where t.id=$1`,
391 + [req.params.termId],
392 + );
393 + if (!t.rowCount) return res.status(404).json({ error: 'not_found' });
394 + if (t.rows[0].student_user_id !== req.identity.sub) {
395 + return res.status(403).json({ error: 'forbidden' });
396 + }
397 + const name = String(req.body.name ?? '').trim();
398 + if (!name) return res.status(400).json({ error: 'invalid_subject' });
399 + const r = await pool.query(
400 + `insert into subject(student_user_id,academic_term_id,name,teacher_name,color_key)
401 + values($1,$2,$3,$4,$5) returning *`,
402 + [req.identity.sub, req.params.termId, name, req.body.teacherName || null, req.body.colorKey || null],
403 + );
404 + res.status(201).json(r.rows[0]);
405 + });
406 +
407 + router.post('/school/subjects/:subjectId/classes', auth, async (req, res) => {
408 + const s = await pool.query('select student_user_id from subject where id=$1', [req.params.subjectId]);
409 + if (!s.rowCount) return res.status(404).json({ error: 'not_found' });
410 + if (s.rows[0].student_user_id !== req.identity.sub) {
411 + return res.status(403).json({ error: 'forbidden' });
412 + }
413 + const weekday = Number(req.body.weekday);
414 + if (!Number.isInteger(weekday) || weekday < 1 || weekday > 7) {
415 + return res.status(400).json({ error: 'invalid_weekday' });
416 + }
417 + const r = await pool.query(
418 + `insert into class_session(subject_id,weekday,starts_at,ends_at,location,recurrence_until)
419 + values($1,$2,$3,$4,$5,$6) returning *`,
420 + [req.params.subjectId, weekday, req.body.startsAt, req.body.endsAt, req.body.location || null, req.body.recurrenceUntil || null],
421 + );
422 + res.status(201).json(r.rows[0]);
423 + });
424 +
425 + router.get('/school/:studentUserId/overview', auth, async (req, res) => {
426 + const studentUserId = req.params.studentUserId;
427 + if (!(await assertStudentAcademic(pool, studentUserId, req.identity.sub))) {
428 + return res.status(403).json({ error: 'forbidden' });
429 + }
430 + const [years, subjects, workload, grades] = await Promise.all([
431 + pool.query(
432 + `select * from academic_year where student_user_id=$1 and active order by starts_on desc`,
433 + [studentUserId],
434 + ),
435 + pool.query(
436 + `select s.*,t.title as term_title,y.title as year_title
437 + from subject s join academic_term t on t.id=s.academic_term_id
438 + join academic_year y on y.id=t.academic_year_id
439 + where s.student_user_id=$1 order by s.name`,
440 + [studentUserId],
441 + ),
442 + pool.query(
443 + `select *
444 + from plan_item
445 + where owner_user_id=$1
446 + and kind in ('assignment','exam','study_session')
447 + and status not in ('completed','cancelled')
448 + order by coalesce(due_at,starts_at) nulls last`,
449 + [studentUserId],
450 + ),
451 + pool.query(
452 + `select id,title,subject_id,grade_points,grade_out_of,due_at
453 + from plan_item
454 + where owner_user_id=$1
455 + and grade_points is not null
456 + and grade_out_of is not null
457 + order by due_at desc nulls last`,
458 + [studentUserId],
459 + ),
460 + ]);
461 + res.json({
462 + years: years.rows,
463 + subjects: subjects.rows,
464 + workload: workload.rows,
465 + grades: grades.rows,
466 + });
467 + });
468 +
469 + router.get('/school/:studentUserId/timetable', auth, async (req, res) => {
470 + if (!(await assertStudentAcademic(pool, req.params.studentUserId, req.identity.sub))) {
471 + return res.status(403).json({ error: 'forbidden' });
472 + }
473 + const r = await pool.query(
474 + `select c.*,s.name as subject_name,s.color_key
475 + from class_session c
476 + join subject s on s.id=c.subject_id
477 + where s.student_user_id=$1
478 + order by c.weekday,c.starts_at`,
479 + [req.params.studentUserId],
480 + );
481 + res.json({ classes: r.rows });
482 + });
483 +
484 + router.patch('/school/plan-items/:itemId/grade', auth, async (req, res) => {
485 + const access = await assertPlanWrite(pool, req.params.itemId, req.identity.sub);
486 + if (access.error) return res.status(access.status).json({ error: access.error });
487 + if (!['assignment','exam'].includes(access.item.kind)) {
488 + return res.status(400).json({ error: 'grade_not_applicable' });
489 + }
490 + const points = Number(req.body.points);
491 + const outOf = Number(req.body.outOf);
492 + if (!Number.isFinite(points) || !Number.isFinite(outOf) || outOf <= 0 || points < 0 || points > outOf) {
493 + return res.status(400).json({ error: 'invalid_grade' });
494 + }
495 + const r = await pool.query(
496 + `update plan_item set grade_points=$2,grade_out_of=$3,updated_at=now()
497 + where id=$1 returning *`,
498 + [req.params.itemId, points, outOf],
499 + );
500 + res.json(r.rows[0]);
501 + });
502 +
503 + router.get('/families/:familyId/calendar', auth, async (req, res) => {
504 + const member = await familyMember(pool, req.params.familyId, req.identity.sub);
505 + if (!member) return res.status(403).json({ error: 'forbidden' });
506 + const r = await pool.query(
507 + `select p.*,pr.display_name as owner_name
508 + from plan_item p
509 + join profile pr on pr.user_id=p.owner_user_id
510 + where p.family_id=$1
511 + and can_view_plan_item($2,p.id)
512 + and p.status <> 'cancelled'
513 + order by coalesce(p.starts_at,p.due_at,p.created_at)`,
514 + [req.params.familyId, req.identity.sub],
515 + );
516 + res.json({ items: r.rows });
517 + });
518 +
519 + router.get('/families/:familyId/children/:studentUserId/support-summary', auth, async (req, res) => {
520 + const familyId = req.params.familyId;
521 + const studentUserId = req.params.studentUserId;
522 + const g = await pool.query(
523 + `select 1 from guardian_relationship
524 + where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3 and active`,
525 + [familyId, req.identity.sub, studentUserId],
526 + );
527 + if (!g.rowCount) return res.status(403).json({ error: 'guardian_required' });
528 +
529 + const [upcoming, completed, overdue, study, grades] = await Promise.all([
530 + pool.query(
531 + `select id,kind,title,due_at,starts_at,priority,status
532 + from plan_item
533 + where owner_user_id=$1
534 + and kind in ('assignment','exam','study_session')
535 + and status not in ('completed','cancelled')
536 + and coalesce(due_at,starts_at) >= now()
537 + and coalesce(due_at,starts_at) < now()+interval '14 days'
538 + order by coalesce(due_at,starts_at) limit 20`,
539 + [studentUserId],
540 + ),
541 + pool.query(
542 + `select count(*)::int as n from plan_item
543 + where owner_user_id=$1 and kind in ('assignment','study_session') and status='completed'
544 + and completed_at >= now()-interval '7 days'`,
545 + [studentUserId],
546 + ),
547 + pool.query(
548 + `select count(*)::int as n from plan_item
549 + where owner_user_id=$1 and kind in ('assignment','study_session')
550 + and status not in ('completed','cancelled') and due_at < now()`,
551 + [studentUserId],
552 + ),
553 + pool.query(
554 + `select coalesce(sum(duration_minutes),0)::int as minutes
555 + from plan_item
556 + where owner_user_id=$1 and kind='study_session' and status='completed'
557 + and completed_at >= now()-interval '7 days'`,
558 + [studentUserId],
559 + ),
560 + pool.query(
561 + `select
562 + case when sum(grade_out_of)>0 then round(sum(grade_points)/sum(grade_out_of)*100,1) end as percent
563 + from plan_item
564 + where owner_user_id=$1 and grade_points is not null and grade_out_of is not null`,
565 + [studentUserId],
566 + ),
567 + ]);
568 + await audit(pool, req.identity.sub, familyId, 'parent.support_summary.view', 'student', studentUserId);
569 + res.json({
570 + upcoming: upcoming.rows,
571 + metrics: {
572 + completedLast7Days: completed.rows[0].n,
573 + overdue: overdue.rows[0].n,
574 + studyMinutesLast7Days: study.rows[0].minutes,
575 + gradePercent: grades.rows[0].percent == null ? null : Number(grades.rows[0].percent),
576 + },
577 + });
578 + });
579 +
580 + router.post('/sync/mutations', auth, async (req, res) => {
581 + const mutations = Array.isArray(req.body.mutations) ? req.body.mutations : [];
582 + if (mutations.length > 100) {
583 + return res.status(400).json({ error: 'too_many_mutations' });
584 + }
585 +
586 + const client = await pool.connect();
587 + const results = [];
588 + try {
589 + for (const mutation of mutations) {
590 + const id = String(mutation.id ?? '');
591 + const operation = String(mutation.operation ?? '');
592 + const entityType = String(mutation.entityType ?? 'plan_item');
593 + const entityId = mutation.entityId ? String(mutation.entityId) : null;
594 + const clientUpdatedAt = asDate(mutation.clientUpdatedAt);
595 + const payload = mutation.payload && typeof mutation.payload === 'object'
596 + ? mutation.payload
597 + : {};
598 +
599 + if (
600 + !id ||
601 + entityType !== 'plan_item' ||
602 + !entityId ||
603 + !clientUpdatedAt ||
604 + !['update', 'complete', 'reschedule'].includes(operation)
605 + ) {
606 + results.push({ id, status: 'rejected', error: 'invalid_mutation' });
607 + continue;
608 + }
609 +
610 + await client.query('begin');
611 + try {
612 + const duplicate = await client.query(
613 + 'select accepted_at from sync_mutation where id=$1 and user_id=$2',
614 + [id, req.identity.sub],
615 + );
616 + if (duplicate.rowCount) {
617 + await client.query('rollback');
618 + results.push({
619 + id,
620 + status: 'already_applied',
621 + acceptedAt: duplicate.rows[0].accepted_at,
622 + });
623 + continue;
624 + }
625 +
626 + const current = await client.query(
627 + 'select * from plan_item where id=$1 for update',
628 + [entityId],
629 + );
630 + if (!current.rowCount) {
631 + await client.query('rollback');
632 + results.push({ id, status: 'rejected', error: 'not_found' });
633 + continue;
634 + }
635 + const item = current.rows[0];
636 + if (item.owner_user_id !== req.identity.sub) {
637 + await client.query('rollback');
638 + results.push({ id, status: 'rejected', error: 'forbidden' });
639 + continue;
640 + }
641 +
642 + const serverUpdatedAt = new Date(item.updated_at);
643 + if (serverUpdatedAt.getTime() > clientUpdatedAt.getTime() + 1000) {
644 + await client.query('rollback');
645 + results.push({
646 + id,
647 + status: 'conflict',
648 + serverUpdatedAt: serverUpdatedAt.toISOString(),
649 + });
650 + continue;
651 + }
652 +
653 + if (operation === 'complete') {
654 + await client.query(
655 + `update plan_item
656 + set status='completed',completed_at=now(),updated_at=now()
657 + where id=$1`,
658 + [entityId],
659 + );
660 + await client.query(
661 + `update reminder set status='cancelled'
662 + where plan_item_id=$1 and status in ('scheduled','claimed')`,
663 + [entityId],
664 + );
665 + } else if (operation === 'reschedule') {
666 + const dueAt = asDate(payload.dueAt);
667 + const startsAt = asDate(payload.startsAt);
668 + if (!dueAt && !startsAt) {
669 + await client.query('rollback');
670 + results.push({ id, status: 'rejected', error: 'invalid_reschedule' });
671 + continue;
672 + }
673 + await client.query(
674 + `update plan_item
675 + set due_at=coalesce($2,due_at),
676 + starts_at=coalesce($3,starts_at),
677 + updated_at=now()
678 + where id=$1`,
679 + [entityId, dueAt, startsAt],
680 + );
681 + await client.query('select recompute_reminder_schedule($1)', [entityId]);
682 + } else {
683 + const title = payload.title == null ? null : String(payload.title).trim();
684 + const status = payload.status == null ? null : String(payload.status);
685 + if (status != null && !allowedStatus.has(status)) {
686 + await client.query('rollback');
687 + results.push({ id, status: 'rejected', error: 'invalid_status' });
688 + continue;
689 + }
690 + await client.query(
691 + `update plan_item
692 + set title=coalesce($2,title),
693 + status=coalesce($3::plan_item_status,status),
694 + updated_at=now()
695 + where id=$1`,
696 + [entityId, title || null, status],
697 + );
698 + }
699 +
700 + await client.query(
701 + `insert into sync_mutation(
702 + id,user_id,entity_type,entity_id,operation,client_updated_at,payload
703 + ) values($1,$2,$3,$4,$5,$6,$7::jsonb)`,
704 + [
705 + id,
706 + req.identity.sub,
707 + entityType,
708 + entityId,
709 + operation,
710 + clientUpdatedAt,
711 + JSON.stringify(payload),
712 + ],
713 + );
714 + await client.query('commit');
715 + results.push({ id, status: 'accepted' });
716 + } catch (error) {
717 + await client.query('rollback').catch(() => {});
718 + throw error;
719 + }
720 + }
721 + res.json({ results });
722 + } finally {
723 + client.release();
724 + }
725 + });
726 +
727 + return router;
728 +}
backend/src/server.js
+4 -1
@@ -5,6 +5,7 @@ import jwt from 'jsonwebtoken';
5 import pg from 'pg';
6 import nodemailer from 'nodemailer';
7 import cors from 'cors';
8 +import { createPhase3Router } from './phase3.js';
9
10 const { Pool } = pg;
11 const app = express();
@@ -373,7 +374,7 @@ app.post('/v1/auth/logout', auth, async (req, res) => {
374
375 app.get('/v1/profile', auth, async (req, res) => {
376 const r = await pool.query(
376 - 'select p.display_name,p.birth_date,p.theme_preference,u.email_normalized,u.email_verified_at from profile p join app_user u on u.id=p.user_id where p.user_id=$1',
377 + 'select u.id as user_id,p.display_name,p.birth_date,p.theme_preference,u.email_normalized,u.email_verified_at from profile p join app_user u on u.id=p.user_id where p.user_id=$1',
378 [req.identity.sub],
379 );
380 if (!r.rowCount) return res.status(404).json({ error: 'profile_not_found' });
@@ -602,6 +603,8 @@ app.post('/v1/families/:familyId/guardians', auth, async (req, res) => {
603 res.status(204).end();
604 });
605
606 +app.use('/v1', createPhase3Router({ pool, auth }));
607 +
608 app.use((err, _req, res, _next) => {
609 console.error(err);
610 res.status(500).json({ error: 'internal_error' });
backend/tests/phase3.test.js new
+260
@@ -0,0 +1,260 @@
1 +import test, { after } from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import crypto from 'node:crypto';
4 +import { app, pool } from '../src/server.js';
5 +
6 +const server = app.listen(0);
7 +const address = server.address();
8 +const base = `http://127.0.0.1:${address.port}`;
9 +
10 +after(async () => {
11 + await new Promise((resolve) => server.close(resolve));
12 + await pool.end();
13 +});
14 +
15 +async function request(path, { method='GET', body, token } = {}) {
16 + const response = await fetch(base + path, {
17 + method,
18 + headers: {
19 + 'content-type': 'application/json',
20 + ...(token ? { authorization: `Bearer ${token}` } : {}),
21 + },
22 + body: body === undefined ? undefined : JSON.stringify(body),
23 + });
24 + const text = await response.text();
25 + return {
26 + status: response.status,
27 + body: text ? JSON.parse(text) : null,
28 + };
29 +}
30 +
31 +async function registerVerified(email, displayName) {
32 + const password = 'Phase3Pass!123';
33 + const reg = await request('/v1/auth/register', {
34 + method:'POST',
35 + body:{ email, displayName, password },
36 + });
37 + assert.equal(reg.status,201);
38 + assert.equal((await request('/v1/auth/verify-email',{
39 + method:'POST', body:{ token:reg.body.verificationToken },
40 + })).status,204);
41 + const login = await request('/v1/auth/login',{
42 + method:'POST', body:{ email, password },
43 + });
44 + assert.equal(login.status,200);
45 + return { token:login.body.accessToken, userId:reg.body.userId, password };
46 +}
47 +
48 +test('phase 3 planner school family vertical slice', async () => {
49 + const suffix = Date.now().toString(36);
50 + const parent = await registerVerified(`p3-parent-${suffix}@example.test`,'Phase3 Parent');
51 + const teen = await registerVerified(`p3-teen-${suffix}@example.test`,'Phase3 Teen');
52 + const outsider = await registerVerified(`p3-outsider-${suffix}@example.test`,'Phase3 Outsider');
53 +
54 + const family = await request('/v1/families',{
55 + method:'POST', token:parent.token,
56 + body:{ name:'Phase3 Family', role:'parent_guardian' },
57 + });
58 + assert.equal(family.status,201);
59 +
60 + const invite = await request(`/v1/families/${family.body.id}/invitations`,{
61 + method:'POST', token:parent.token,
62 + body:{ email:`p3-teen-${suffix}@example.test`, role:'teen_minor', themePreference:'girl_pink' },
63 + });
64 + assert.equal(invite.status,201);
65 + assert.equal((await request('/v1/invitations/accept',{
66 + method:'POST', token:teen.token, body:{ token:invite.body.invitationToken },
67 + })).status,204);
68 +
69 + const members = await request(`/v1/families/${family.body.id}/members`,{token:parent.token});
70 + const parentMember = members.body.members.find((x)=>x.user_id===parent.userId);
71 + const teenMember = members.body.members.find((x)=>x.user_id===teen.userId);
72 + assert.ok(parentMember && teenMember);
73 +
74 + assert.equal((await request(`/v1/families/${family.body.id}/guardians`,{
75 + method:'POST', token:parent.token,
76 + body:{guardianUserId:parent.userId,minorUserId:teen.userId},
77 + })).status,204);
78 +
79 + const ctx = await request('/v1/life-contexts',{
80 + method:'POST', token:teen.token,
81 + body:{kind:'student',title:'مدرسه'},
82 + });
83 + assert.equal(ctx.status,201);
84 +
85 + const year = await request('/v1/school/years',{
86 + method:'POST', token:teen.token,
87 + body:{
88 + lifeContextId:ctx.body.id,
89 + title:'سال تحصیلی ۱۴۰۵-۱۴۰۶',
90 + startsOn:'2026-09-01',
91 + endsOn:'2027-06-30',
92 + },
93 + });
94 + assert.equal(year.status,201);
95 +
96 + const term = await request(`/v1/school/years/${year.body.id}/terms`,{
97 + method:'POST', token:teen.token,
98 + body:{title:'نیمسال اول',startsOn:'2026-09-01',endsOn:'2027-01-31'},
99 + });
100 + assert.equal(term.status,201);
101 +
102 + const subject = await request(`/v1/school/terms/${term.body.id}/subjects`,{
103 + method:'POST', token:teen.token,
104 + body:{name:'ریاضی',teacherName:'دبیر ریاضی',colorKey:'pink'},
105 + });
106 + assert.equal(subject.status,201);
107 +
108 + const klass = await request(`/v1/school/subjects/${subject.body.id}/classes`,{
109 + method:'POST', token:teen.token,
110 + body:{weekday:2,startsAt:'08:00',endsAt:'09:30',location:'کلاس ۷'},
111 + });
112 + assert.equal(klass.status,201);
113 +
114 + const due = new Date(Date.now()+60*60*1000).toISOString();
115 + const assignment = await request('/v1/plan-items',{
116 + method:'POST', token:teen.token,
117 + body:{
118 + kind:'assignment',
119 + title:'تمرین فصل اول ریاضی',
120 + subjectId:subject.body.id,
121 + familyId:family.body.id,
122 + visibility:'parent_guardian',
123 + dueAt:due,
124 + priority:'high',
125 + durationMinutes:45,
126 + reminderMinutesBefore:[30,10],
127 + },
128 + });
129 + assert.equal(assignment.status,201);
130 +
131 + const privateTask = await request('/v1/plan-items',{
132 + method:'POST', token:teen.token,
133 + body:{kind:'task',title:'کار شخصی',visibility:'private',dueAt:due},
134 + });
135 + assert.equal(privateTask.status,201);
136 +
137 + const familyEvent = await request('/v1/plan-items',{
138 + method:'POST', token:parent.token,
139 + body:{
140 + kind:'event', title:'شام خانوادگی', familyId:family.body.id,
141 + visibility:'family', startsAt:due, reminderMinutesBefore:[15],
142 + },
143 + });
144 + assert.equal(familyEvent.status,201);
145 +
146 + const parentCalendar = await request(`/v1/families/${family.body.id}/calendar`,{token:parent.token});
147 + assert.equal(parentCalendar.status,200);
148 + assert.ok(parentCalendar.body.items.some((x)=>x.id===assignment.body.id));
149 + assert.ok(parentCalendar.body.items.some((x)=>x.id===familyEvent.body.id));
150 + assert.ok(!parentCalendar.body.items.some((x)=>x.id===privateTask.body.id));
151 +
152 + const outsiderOverview = await request(`/v1/school/${teen.userId}/overview`,{token:outsider.token});
153 + assert.equal(outsiderOverview.status,403);
154 +
155 + const parentOverview = await request(`/v1/school/${teen.userId}/overview`,{token:parent.token});
156 + assert.equal(parentOverview.status,200);
157 + assert.equal(parentOverview.body.subjects.length,1);
158 + assert.ok(parentOverview.body.workload.some((x)=>x.id===assignment.body.id));
159 +
160 + const parentPrivateAttempt = await request('/v1/plan-items',{token:parent.token});
161 + assert.equal(parentPrivateAttempt.status,200);
162 + assert.ok(!parentPrivateAttempt.body.items.some((x)=>x.id===privateTask.body.id));
163 +
164 + const grade = await request(`/v1/school/plan-items/${assignment.body.id}/grade`,{
165 + method:'PATCH', token:teen.token, body:{points:18,outOf:20},
166 + });
167 + assert.equal(grade.status,200);
168 +
169 + const support = await request(
170 + `/v1/families/${family.body.id}/children/${teen.userId}/support-summary`,
171 + {token:parent.token},
172 + );
173 + assert.equal(support.status,200);
174 + assert.ok(Array.isArray(support.body.upcoming));
175 + assert.equal(support.body.metrics.gradePercent,90);
176 +
177 + const outsiderSupport = await request(
178 + `/v1/families/${family.body.id}/children/${teen.userId}/support-summary`,
179 + {token:outsider.token},
180 + );
181 + assert.equal(outsiderSupport.status,403);
182 +
183 + const rescheduled = new Date(Date.now()+2*60*60*1000).toISOString();
184 + const update = await request(`/v1/plan-items/${assignment.body.id}`,{
185 + method:'PATCH', token:teen.token, body:{dueAt:rescheduled},
186 + });
187 + assert.equal(update.status,200);
188 +
189 + const reminderRows = await pool.query(
190 + 'select minutes_before,status,scheduled_for from reminder where plan_item_id=$1 order by minutes_before',
191 + [assignment.body.id],
192 + );
193 + assert.equal(reminderRows.rowCount,2);
194 + assert.ok(reminderRows.rows.every((x)=>x.status==='scheduled'));
195 +
196 + const completed = await request(`/v1/plan-items/${assignment.body.id}`,{
197 + method:'PATCH', token:teen.token, body:{status:'completed'},
198 + });
199 + assert.equal(completed.status,200);
200 + const cancelled = await pool.query(
201 + "select count(*)::int as n from reminder where plan_item_id=$1 and status='cancelled'",
202 + [assignment.body.id],
203 + );
204 + assert.equal(cancelled.rows[0].n,2);
205 +
206 + const mutationId = crypto.randomUUID();
207 + const sync1 = await request('/v1/sync/mutations',{
208 + method:'POST', token:teen.token,
209 + body:{mutations:[{
210 + id:mutationId, entityType:'plan_item', entityId:privateTask.body.id,
211 + operation:'reschedule', clientUpdatedAt:new Date().toISOString(),
212 + payload:{dueAt:rescheduled},
213 + }]},
214 + });
215 + assert.equal(sync1.status,200);
216 + assert.equal(sync1.body.results[0].status,'accepted');
217 +
218 + const syncedRow = await pool.query(
219 + 'select due_at from plan_item where id=$1',
220 + [privateTask.body.id],
221 + );
222 + assert.equal(
223 + new Date(syncedRow.rows[0].due_at).toISOString(),
224 + new Date(rescheduled).toISOString(),
225 + );
226 +
227 + const sync2 = await request('/v1/sync/mutations',{
228 + method:'POST', token:teen.token,
229 + body:{mutations:[{
230 + id:mutationId, entityType:'plan_item', entityId:privateTask.body.id,
231 + operation:'reschedule', clientUpdatedAt:new Date().toISOString(),
232 + payload:{dueAt:rescheduled},
233 + }]},
234 + });
235 + assert.equal(sync2.body.results[0].status,'already_applied');
236 +
237 + const reminderItem = await request('/v1/plan-items',{
238 + method:'POST', token:teen.token,
239 + body:{
240 + kind:'task',
241 + title:'یادآوری آزمایشی',
242 + visibility:'private',
243 + dueAt:new Date(Date.now()-60*1000).toISOString(),
244 + reminderMinutesBefore:[0],
245 + },
246 + });
247 + assert.equal(reminderItem.status,201);
248 + const claimed = await request('/v1/reminders/claim-due',{
249 + method:'POST', token:teen.token, body:{limit:10},
250 + });
251 + assert.equal(claimed.status,200);
252 + assert.ok(claimed.body.claimed >= 1);
253 + const notifications = await request('/v1/notification-outbox',{token:teen.token});
254 + assert.equal(notifications.status,200);
255 + assert.ok(
256 + notifications.body.notifications.some(
257 + (item)=>item.payload.planItemId===reminderItem.body.id,
258 + ),
259 + );
260 +});
backend/tests/phase3_schema_test.sql new
+45
@@ -0,0 +1,45 @@
1 +\set ON_ERROR_STOP on
2 +begin;
3 +
4 +insert into app_user(id,identity_subject,email_normalized) values
5 +('30000000-0000-0000-0000-000000000001','p3-parent','p3-parent@example.test'),
6 +('30000000-0000-0000-0000-000000000002','p3-teen','p3-teen@example.test'),
7 +('30000000-0000-0000-0000-000000000003','p3-other','p3-other@example.test');
8 +
9 +insert into family_workspace(id,name,created_by) values
10 +('31000000-0000-0000-0000-000000000001','P3 Family','30000000-0000-0000-0000-000000000001');
11 +
12 +insert into family_membership(family_id,user_id,role,is_admin) values
13 +('31000000-0000-0000-0000-000000000001','30000000-0000-0000-0000-000000000001','parent_guardian',true),
14 +('31000000-0000-0000-0000-000000000001','30000000-0000-0000-0000-000000000002','teen_minor',false);
15 +
16 +insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values
17 +('31000000-0000-0000-0000-000000000001','30000000-0000-0000-0000-000000000001','30000000-0000-0000-0000-000000000002');
18 +
19 +insert into plan_item(id,owner_user_id,family_id,kind,title,visibility,due_at) values
20 +('32000000-0000-0000-0000-000000000001','30000000-0000-0000-0000-000000000002','31000000-0000-0000-0000-000000000001','task','Private teen','private',now()+interval '1 day'),
21 +('32000000-0000-0000-0000-000000000002','30000000-0000-0000-0000-000000000002','31000000-0000-0000-0000-000000000001','assignment','Guardian item','parent_guardian',now()+interval '1 day'),
22 +('32000000-0000-0000-0000-000000000003','30000000-0000-0000-0000-000000000001','31000000-0000-0000-0000-000000000001','event','Family event','family',now()+interval '1 day');
23 +
24 +do $$
25 +begin
26 + if not can_view_plan_item('30000000-0000-0000-0000-000000000002','32000000-0000-0000-0000-000000000001') then raise exception 'owner must see private item'; end if;
27 + if can_view_plan_item('30000000-0000-0000-0000-000000000001','32000000-0000-0000-0000-000000000001') then raise exception 'guardian must not see private item'; end if;
28 + if not can_view_plan_item('30000000-0000-0000-0000-000000000001','32000000-0000-0000-0000-000000000002') then raise exception 'guardian must see guardian item'; end if;
29 + if can_view_plan_item('30000000-0000-0000-0000-000000000003','32000000-0000-0000-0000-000000000002') then raise exception 'outsider must not see guardian item'; end if;
30 + if not can_view_plan_item('30000000-0000-0000-0000-000000000002','32000000-0000-0000-0000-000000000003') then raise exception 'family member must see family event'; end if;
31 + if not can_view_student_academic('30000000-0000-0000-0000-000000000001','30000000-0000-0000-0000-000000000002') then raise exception 'guardian academic access missing'; end if;
32 + if can_view_student_academic('30000000-0000-0000-0000-000000000003','30000000-0000-0000-0000-000000000002') then raise exception 'outsider academic access must fail'; end if;
33 +end $$;
34 +
35 +update family_membership set ended_at=now()
36 +where family_id='31000000-0000-0000-0000-000000000001'
37 +and user_id='30000000-0000-0000-0000-000000000001';
38 +
39 +do $$
40 +begin
41 + if can_view_plan_item('30000000-0000-0000-0000-000000000001','32000000-0000-0000-0000-000000000002') then raise exception 'removed guardian must lose plan access'; end if;
42 + if can_view_student_academic('30000000-0000-0000-0000-000000000001','30000000-0000-0000-0000-000000000002') then raise exception 'removed guardian must lose academic access'; end if;
43 +end $$;
44 +
45 +rollback;
docs/plans/PHASE_3_IMPLEMENTATION_PLAN.md new
+25
@@ -0,0 +1,25 @@
1 +# Phase 3 — Planner, School & Family Core Implementation Plan
2 +
3 +Status: IN PROGRESS
4 +Branch: `phase-3/planner-school-family-core`
5 +
6 +## Acceptance contract
7 +Phase 3 is complete only when a family can plan a real week without AI: personal/family calendar items, tasks, routines/goals, reminders, school year/term/subjects/classes/assignments/exams/study sessions/grades, controlled sharing, guardian-authorized child support summary, and offline-aware client behavior all exist and pass CI/staging verification.
8 +
9 +## Implementation slices
10 +1. PostgreSQL planning/school/sharing/notification schema with constraints and indexes.
11 +2. Server authorization helpers and CRUD/query API for Today, Planner, School, Family and Parent Support.
12 +3. Reminder outbox with idempotent due-reminder claiming and completion/reschedule semantics.
13 +4. Flutter provider-neutral client models/API and Persian RTL core screens.
14 +5. Offline-aware read cache + queued safe edits contract for critical planning flows.
15 +6. Permission regression tests: owner, guardian, unrelated member, removed member, unauthenticated.
16 +7. CI schema/API/widget/Web/Android gates.
17 +8. Railway staging migrations + smoke verification.
18 +9. State/docs update, PR review, merge, main CI verification.
19 +
20 +## Scope rules
21 +- MyStudyLife remains the benchmark for student IA, but LifeMate adds family sharing and guardian support.
22 +- AI is not required for any Phase 3 flow.
23 +- Parents receive authorized schedule/workload/progress summaries, not private content.
24 +- Reminder delivery is modeled as an outbox/provider boundary; Phase 3 verifies scheduling and delivery eligibility without coupling the domain to one push vendor.
25 +- Offline cache is non-authoritative; queued edits are limited to operations with explicit conflict semantics.