LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
js 224 lines 13.9 KB
Raw
1 import express from 'express';
2
3 const uuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
4 const has = (body, key) => Object.hasOwn(body, key);
5 class SchoolInputError extends Error {
6 constructor(status, code) { super(code); this.status = status; this.code = code; }
7 }
8 const fail = (status, code) => { throw new SchoolInputError(status, code); };
9 function id(value) { if (!uuid(value)) fail(400, 'invalid_id'); return value; }
10 function text(value, max, nullable = false) {
11 if (nullable && value == null) return null;
12 if (nullable && typeof value === 'string' && !value.trim()) return null;
13 if (typeof value !== 'string' || !value.trim() || value.trim().length > max) fail(400, 'invalid_input');
14 return value.trim();
15 }
16 function date(value) {
17 if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000-')) return null;
18 const parsed = new Date(`${value}T00:00:00Z`);
19 return Number.isFinite(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value ? value : null;
20 }
21 function time(value) {
22 if (typeof value !== 'string' || !/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test(value)) fail(400, 'invalid_class_time');
23 return value.length === 5 ? value + ':00' : value;
24 }
25 function occurred(value) {
26 if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/.test(value)) fail(400, 'invalid_occurred_at');
27 const parsed = new Date(value);
28 if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 19) !== value.slice(0, 19) || parsed.getTime() > Date.now() + 60000) fail(400, 'invalid_occurred_at');
29 return parsed;
30 }
31 const checkinRow = (row) => ({ ...row, isEvidenceOfStudy: false });
32 const route = (handler) => async (req, res, next) => {
33 try { await handler(req, res); }
34 catch (error) {
35 if (error instanceof SchoolInputError) return res.status(error.status).json({ error: error.code });
36 next(error);
37 }
38 };
39 async function transaction(pool, operation) {
40 const client = await pool.connect();
41 try {
42 await client.query('begin');
43 const result = await operation(client);
44 await client.query('commit');
45 return result;
46 } catch (error) {
47 await client.query('rollback').catch(() => {});
48 throw error;
49 } finally { client.release(); }
50 }
51 async function ownedTerm(client, termId, userId, status = 403) {
52 const result = await client.query(`select t.*,t.starts_on::text as first_day,t.ends_on::text as last_day
53 from academic_term t join academic_year y on y.id=t.academic_year_id
54 join life_context l on l.id=y.life_context_id
55 where t.id=$1 and y.student_user_id=$2 and l.user_id=$2 and y.active and l.active
56 for share of t,y,l`, [termId, userId]);
57 if (!result.rowCount) fail(status, status === 403 ? 'academic_term_forbidden' : 'school_parent_inactive');
58 return result.rows[0];
59 }
60 async function activeSubject(client, subjectId, userId) {
61 const result = await client.query('select * from subject where id=$1 and student_user_id=$2 for share', [subjectId, userId]);
62 if (!result.rowCount) fail(403, 'subject_forbidden');
63 if (result.rows[0].archived_at) fail(409, 'subject_archived');
64 return { subject: result.rows[0], term: await ownedTerm(client, result.rows[0].academic_term_id, userId, 409) };
65 }
66 function classFields(body, current) {
67 const next = { ...current };
68 if (has(body, 'weekday')) {
69 if (!Number.isInteger(body.weekday) || body.weekday < 1 || body.weekday > 7) fail(400, 'invalid_weekday');
70 next.weekday = body.weekday;
71 }
72 if (has(body, 'startsAt')) next.starts_at = time(body.startsAt);
73 if (has(body, 'endsAt')) next.ends_at = time(body.endsAt);
74 if (next.ends_at <= next.starts_at) fail(400, 'invalid_class_time');
75 if (has(body, 'location')) next.location = text(body.location, 240, true);
76 if (has(body, 'recurrenceUntil')) {
77 if (body.recurrenceUntil != null && !date(body.recurrenceUntil)) fail(400, 'invalid_recurrence_date');
78 next.recurrence_until = body.recurrenceUntil ?? null;
79 }
80 return next;
81 }
82 function checkinFields(body, current) {
83 const next = { ...current };
84 for (const field of ['confidence', 'difficulty']) if (has(body, field)) {
85 if (!Number.isInteger(body[field]) || body[field] < 1 || body[field] > 5) fail(400, 'invalid_input');
86 next[field] = body[field];
87 }
88 if (has(body, 'note')) next.note = text(body.note, 2000, true);
89 if (has(body, 'learningGoalId')) next.learning_goal_id = body.learningGoalId == null ? null : id(body.learningGoalId);
90 if (has(body, 'occurredAt')) next.occurred_at = occurred(body.occurredAt);
91 if ((has(body, 'source') && body.source !== 'self_reported') || (has(body, 'isEvidenceOfStudy') && body.isEvidenceOfStudy !== false)) fail(400, 'self_report_only');
92 return next;
93 }
94 async function ownedGoal(client, goalId, userId) {
95 if (goalId == null) return;
96 const result = await client.query("select 1 from learning_goal where id=$1 and owner_user_id=$2 and status<>'archived' for share", [goalId, userId]);
97 if (!result.rowCount) fail(403, 'learning_goal_forbidden');
98 }
99
100 export function createSchoolCrudRouter({ pool, auth }) {
101 const router = express.Router();
102 router.post('/school/subjects/:id/classes', auth, route(async (req, res) => {
103 const subjectId = id(req.params.id), body = req.body ?? {};
104 if (!['weekday', 'startsAt', 'endsAt'].every((key) => has(body, key))) fail(400, 'invalid_input');
105 const next = classFields(body, { location: null, recurrence_until: null });
106 const result = await transaction(pool, async (client) => {
107 const { term } = await activeSubject(client, subjectId, req.identity.sub);
108 if (next.recurrence_until && (next.recurrence_until < term.first_day || next.recurrence_until > term.last_day)) fail(400, 'class_recurrence_outside_term');
109 return (await client.query(`insert into class_session(subject_id,weekday,starts_at,ends_at,location,recurrence_until)
110 values($1,$2,$3,$4,$5,$6) returning *`, [subjectId, next.weekday, next.starts_at, next.ends_at, next.location, next.recurrence_until])).rows[0];
111 });
112 res.status(201).json(result);
113 }));
114 router.get('/school/subjects/:id', auth, route(async (req, res) => {
115 const result = await pool.query('select * from subject where id=$1 and student_user_id=$2', [id(req.params.id), req.identity.sub]);
116 if (!result.rowCount) fail(404, 'subject_not_found');
117 res.json(result.rows[0]);
118 }));
119 router.patch('/school/subjects/:id', auth, route(async (req, res) => {
120 const subjectId = id(req.params.id), body = req.body ?? {};
121 if (!['name', 'teacherName', 'colorKey', 'academicTermId'].some((key) => has(body, key))) fail(400, 'invalid_input');
122 const name = has(body, 'name') ? text(body.name, 120) : null;
123 const teacher = has(body, 'teacherName') ? text(body.teacherName, 120, true) : null;
124 const color = has(body, 'colorKey') ? text(body.colorKey, 40, true) : null;
125 if (has(body, 'academicTermId')) id(body.academicTermId);
126 const result = await transaction(pool, async (client) => {
127 const current = await client.query('select * from subject where id=$1 and student_user_id=$2 for update', [subjectId, req.identity.sub]);
128 if (!current.rowCount) fail(404, 'subject_not_found');
129 if (current.rows[0].archived_at) fail(409, 'subject_archived');
130 const termId = body.academicTermId ?? current.rows[0].academic_term_id;
131 const term = await ownedTerm(client, termId, req.identity.sub, has(body, 'academicTermId') ? 403 : 409);
132 const invalidClass = await client.query(`select 1 from class_session where subject_id=$1 and archived_at is null
133 and recurrence_until is not null and (recurrence_until<$2::date or recurrence_until>$3::date) limit 1`, [subjectId, term.first_day, term.last_day]);
134 if (invalidClass.rowCount) fail(400, 'class_recurrence_outside_term');
135 return (await client.query(`update subject set name=coalesce($3,name),
136 teacher_name=case when $4 then $5 else teacher_name end,
137 color_key=case when $6 then $7 else color_key end,academic_term_id=$8,updated_at=now()
138 where id=$1 and student_user_id=$2 returning *`, [subjectId, req.identity.sub, name, has(body, 'teacherName'), teacher, has(body, 'colorKey'), color, termId])).rows[0];
139 });
140 res.json(result);
141 }));
142 router.delete('/school/subjects/:id', auth, route(async (req, res) => {
143 const result = await pool.query(`update subject set updated_at=case when archived_at is null then now() else updated_at end,
144 archived_at=coalesce(archived_at,now()) where id=$1 and student_user_id=$2 returning id`, [id(req.params.id), req.identity.sub]);
145 if (!result.rowCount) fail(404, 'subject_not_found');
146 res.status(204).end();
147 }));
148
149 router.get('/school/classes/:id', auth, route(async (req, res) => {
150 const result = await pool.query(`select c.*,s.name as subject_name,s.archived_at as subject_archived_at
151 from class_session c join subject s on s.id=c.subject_id where c.id=$1 and s.student_user_id=$2`, [id(req.params.id), req.identity.sub]);
152 if (!result.rowCount) fail(404, 'class_not_found');
153 res.json(result.rows[0]);
154 }));
155 router.patch('/school/classes/:id', auth, route(async (req, res) => {
156 const classId = id(req.params.id), body = req.body ?? {};
157 if (!['subjectId', 'weekday', 'startsAt', 'endsAt', 'location', 'recurrenceUntil'].some((key) => has(body, key))) fail(400, 'invalid_input');
158 if (has(body, 'subjectId')) id(body.subjectId);
159 const result = await transaction(pool, async (client) => {
160 const current = await client.query(`select c.*,c.recurrence_until::text as recurrence_until
161 from class_session c join subject s on s.id=c.subject_id
162 where c.id=$1 and s.student_user_id=$2 for update of c`, [classId, req.identity.sub]);
163 if (!current.rowCount) fail(404, 'class_not_found');
164 if (current.rows[0].archived_at) fail(409, 'class_archived');
165 await activeSubject(client, current.rows[0].subject_id, req.identity.sub);
166 const subjectId = body.subjectId ?? current.rows[0].subject_id;
167 const { term } = await activeSubject(client, subjectId, req.identity.sub);
168 const next = classFields(body, current.rows[0]);
169 if (next.recurrence_until && (next.recurrence_until < term.first_day || next.recurrence_until > term.last_day)) fail(400, 'class_recurrence_outside_term');
170 return (await client.query(`update class_session set subject_id=$2,weekday=$3,starts_at=$4,ends_at=$5,
171 location=$6,recurrence_until=$7,updated_at=now() where id=$1 returning *`, [classId, subjectId, next.weekday, next.starts_at, next.ends_at, next.location, next.recurrence_until])).rows[0];
172 });
173 res.json(result);
174 }));
175 router.delete('/school/classes/:id', auth, route(async (req, res) => {
176 const result = await pool.query(`update class_session c set updated_at=case when c.archived_at is null then now() else c.updated_at end,
177 archived_at=coalesce(c.archived_at,now()) from subject s
178 where c.id=$1 and c.subject_id=s.id and s.student_user_id=$2 returning c.id`, [id(req.params.id), req.identity.sub]);
179 if (!result.rowCount) fail(404, 'class_not_found');
180 res.status(204).end();
181 }));
182
183 router.post('/learning/checkins', auth, route(async (req, res) => {
184 const body = req.body ?? {};
185 if (!has(body, 'confidence') || !has(body, 'difficulty')) fail(400, 'invalid_input');
186 const next = checkinFields(body, { learning_goal_id: null, note: null, occurred_at: new Date() });
187 const result = await transaction(pool, async (client) => {
188 await ownedGoal(client, next.learning_goal_id, req.identity.sub);
189 return (await client.query(`insert into learning_checkin(owner_user_id,learning_goal_id,confidence,difficulty,note,occurred_at)
190 values($1,$2,$3,$4,$5,$6) returning *`, [req.identity.sub, next.learning_goal_id, next.confidence, next.difficulty, next.note, next.occurred_at])).rows[0];
191 });
192 res.status(201).json(checkinRow(result));
193 }));
194 router.get('/learning/checkins', auth, route(async (req, res) => {
195 const result = await pool.query('select * from learning_checkin where owner_user_id=$1 and archived_at is null order by occurred_at desc,id', [req.identity.sub]);
196 res.json({ items: result.rows.map(checkinRow) });
197 }));
198 router.get('/learning/checkins/:id', auth, route(async (req, res) => {
199 const result = await pool.query('select * from learning_checkin where id=$1 and owner_user_id=$2', [id(req.params.id), req.identity.sub]);
200 if (!result.rowCount) fail(404, 'checkin_not_found');
201 res.json(checkinRow(result.rows[0]));
202 }));
203 router.patch('/learning/checkins/:id', auth, route(async (req, res) => {
204 const checkinId = id(req.params.id), body = req.body ?? {};
205 if (!['learningGoalId', 'confidence', 'difficulty', 'note', 'occurredAt'].some((key) => has(body, key))) fail(400, 'invalid_input');
206 const result = await transaction(pool, async (client) => {
207 const current = await client.query('select * from learning_checkin where id=$1 and owner_user_id=$2 for update', [checkinId, req.identity.sub]);
208 if (!current.rowCount) fail(404, 'checkin_not_found');
209 if (current.rows[0].archived_at) fail(409, 'checkin_archived');
210 const next = checkinFields(body, current.rows[0]);
211 if (has(body, 'learningGoalId')) await ownedGoal(client, next.learning_goal_id, req.identity.sub);
212 return (await client.query(`update learning_checkin set learning_goal_id=$3,confidence=$4,difficulty=$5,note=$6,
213 occurred_at=$7,updated_at=now() where id=$1 and owner_user_id=$2 returning *`, [checkinId, req.identity.sub, next.learning_goal_id, next.confidence, next.difficulty, next.note, next.occurred_at])).rows[0];
214 });
215 res.json(checkinRow(result));
216 }));
217 router.delete('/learning/checkins/:id', auth, route(async (req, res) => {
218 const result = await pool.query(`update learning_checkin set updated_at=case when archived_at is null then now() else updated_at end,
219 archived_at=coalesce(archived_at,now()) where id=$1 and owner_user_id=$2 returning id`, [id(req.params.id), req.identity.sub]);
220 if (!result.rowCount) fail(404, 'checkin_not_found');
221 res.status(204).end();
222 }));
223 return router;
224 }