@davoodmehraban89 / LifeMate / commits / 866d77a
Fork 0

LifeMate — Personal, Family & Learning Companion

feat(api): add validated private school CRUD and safe archives

Codex committed Oct 8, 2026 at 16:14 UTC 866d77ae56ea1ac052e014a85ca1453e1841c5a3
7 files changed +582 -59
backend/migrations/0012_school_archive.sql new
+28
@@ -0,0 +1,28 @@
1 +begin;
2 +
3 +alter table subject add column archived_at timestamptz;
4 +alter table subject add column updated_at timestamptz;
5 +update subject set updated_at=created_at;
6 +alter table subject alter column updated_at set default now();
7 +alter table subject alter column updated_at set not null;
8 +create index subject_active_owner_idx on subject(student_user_id,created_at desc) where archived_at is null;
9 +
10 +alter table class_session add column archived_at timestamptz;
11 +alter table class_session add column updated_at timestamptz;
12 +update class_session set updated_at=created_at;
13 +alter table class_session alter column updated_at set default now();
14 +alter table class_session alter column updated_at set not null;
15 +create index class_session_active_subject_idx on class_session(subject_id,weekday,starts_at) where archived_at is null;
16 +
17 +alter table learning_checkin add column archived_at timestamptz;
18 +alter table learning_checkin add column updated_at timestamptz;
19 +alter table learning_checkin add column occurred_at timestamptz;
20 +update learning_checkin set updated_at=created_at,occurred_at=created_at;
21 +alter table learning_checkin alter column updated_at set default now();
22 +alter table learning_checkin alter column updated_at set not null;
23 +alter table learning_checkin alter column occurred_at set default now();
24 +alter table learning_checkin alter column occurred_at set not null;
25 +alter table learning_checkin add column source text not null default 'self_reported' check(source='self_reported');
26 +create index learning_checkin_active_owner_idx on learning_checkin(owner_user_id,occurred_at desc) where archived_at is null;
27 +
28 +commit;
backend/src/phase3.js
+34 -29
@@ -3,6 +3,13 @@ import express from 'express';
3 import { applyPlanMutation, createPlanItem, updatePlanItem, planTransaction, serializePlanItem, validUuid, PlanMutationError } from './plan_mutations.js';
4
5 const allowedKinds = new Set(['task','event','routine','goal','assignment','exam','study_session']);
6 +const schoolText = (value, max = 120) => typeof value === 'string' && Boolean(value.trim()) && value.trim().length <= max;
7 +const schoolOptionalText = (value, max = 120) => value == null || (typeof value === 'string' && value.trim().length <= max);
8 +function schoolDate(value) {
9 + if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000-')) return false;
10 + const date = new Date(`${value}T00:00:00Z`);
11 + return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
12 +}
13
14 function asDate(value) {
15 if (value == null || value === '') return null;
@@ -213,10 +220,14 @@ export function createPhase3Router({ pool, auth }) {
220 });
221
222 router.post('/school/years', auth, async (req, res) => {
216 - const title = String(req.body.title ?? '').trim();
217 - const startsOn = req.body.startsOn;
218 - const endsOn = req.body.endsOn;
219 - const lifeContextId = req.body.lifeContextId;
223 + const body = req.body ?? {};
224 + const title = String(body.title ?? '').trim();
225 + const startsOn = body.startsOn;
226 + const endsOn = body.endsOn;
227 + const lifeContextId = body.lifeContextId;
228 + if (!validUuid(lifeContextId) || !schoolText(body.title) || !schoolDate(startsOn) || !schoolDate(endsOn) || endsOn < startsOn) {
229 + return res.status(400).json({ error: 'invalid_academic_year' });
230 + }
231 const ctx = await pool.query(
232 `select 1 from life_context
233 where id=$1 and user_id=$2 and kind='student' and active`,
@@ -234,58 +245,52 @@ export function createPhase3Router({ pool, auth }) {
245 });
246
247 router.post('/school/years/:yearId/terms', auth, async (req, res) => {
248 + const body = req.body ?? {};
249 + if (!validUuid(req.params.yearId) || !schoolText(body.title) || !schoolDate(body.startsOn) || !schoolDate(body.endsOn) || body.endsOn < body.startsOn) {
250 + return res.status(400).json({ error: 'invalid_academic_term' });
251 + }
252 const y = await pool.query(
238 - 'select student_user_id from academic_year where id=$1',
253 + 'select student_user_id,active,starts_on::text,ends_on::text from academic_year where id=$1',
254 [req.params.yearId],
255 );
256 if (!y.rowCount) return res.status(404).json({ error: 'not_found' });
257 if (y.rows[0].student_user_id !== req.identity.sub) {
258 return res.status(403).json({ error: 'forbidden' });
259 }
260 + if (!y.rows[0].active || body.startsOn < y.rows[0].starts_on || body.endsOn > y.rows[0].ends_on) {
261 + return res.status(400).json({ error: 'invalid_academic_term' });
262 + }
263 const r = await pool.query(
264 `insert into academic_term(academic_year_id,title,starts_on,ends_on)
265 values($1,$2,$3,$4) returning *`,
248 - [req.params.yearId, String(req.body.title ?? '').trim(), req.body.startsOn, req.body.endsOn],
266 + [req.params.yearId, String(body.title ?? '').trim(), body.startsOn, body.endsOn],
267 );
268 res.status(201).json(r.rows[0]);
269 });
270
271 router.post('/school/terms/:termId/subjects', auth, async (req, res) => {
272 + const body = req.body ?? {};
273 + if (!validUuid(req.params.termId) || !schoolText(body.name) ||
274 + !schoolOptionalText(body.teacherName) ||
275 + !schoolOptionalText(body.colorKey, 40)) return res.status(400).json({ error: 'invalid_subject' });
276 const t = await pool.query(
277 `select y.student_user_id
278 from academic_term t
279 join academic_year y on y.id=t.academic_year_id
258 - where t.id=$1`,
280 + join life_context l on l.id=y.life_context_id
281 + where t.id=$1 and y.active and l.active`,
282 [req.params.termId],
283 );
284 if (!t.rowCount) return res.status(404).json({ error: 'not_found' });
285 if (t.rows[0].student_user_id !== req.identity.sub) {
286 return res.status(403).json({ error: 'forbidden' });
287 }
265 - const name = String(req.body.name ?? '').trim();
288 + const name = String(body.name ?? '').trim();
289 if (!name) return res.status(400).json({ error: 'invalid_subject' });
290 const r = await pool.query(
291 `insert into subject(student_user_id,academic_term_id,name,teacher_name,color_key)
292 values($1,$2,$3,$4,$5) returning *`,
270 - [req.identity.sub, req.params.termId, name, req.body.teacherName || null, req.body.colorKey || null],
271 - );
272 - res.status(201).json(r.rows[0]);
273 - });
274 -
275 - router.post('/school/subjects/:subjectId/classes', auth, async (req, res) => {
276 - const s = await pool.query('select student_user_id from subject where id=$1', [req.params.subjectId]);
277 - if (!s.rowCount) return res.status(404).json({ error: 'not_found' });
278 - if (s.rows[0].student_user_id !== req.identity.sub) {
279 - return res.status(403).json({ error: 'forbidden' });
280 - }
281 - const weekday = Number(req.body.weekday);
282 - if (!Number.isInteger(weekday) || weekday < 1 || weekday > 7) {
283 - return res.status(400).json({ error: 'invalid_weekday' });
284 - }
285 - const r = await pool.query(
286 - `insert into class_session(subject_id,weekday,starts_at,ends_at,location,recurrence_until)
287 - values($1,$2,$3,$4,$5,$6) returning *`,
288 - [req.params.subjectId, weekday, req.body.startsAt, req.body.endsAt, req.body.location || null, req.body.recurrenceUntil || null],
293 + [req.identity.sub, req.params.termId, name, body.teacherName?.trim() || null, body.colorKey?.trim() || null],
294 );
295 res.status(201).json(r.rows[0]);
296 });
@@ -307,7 +312,7 @@ export function createPhase3Router({ pool, auth }) {
312 `select s.*,t.title as term_title,y.title as year_title
313 from subject s join academic_term t on t.id=s.academic_term_id
314 join academic_year y on y.id=t.academic_year_id
310 - where s.student_user_id=$1 and ($1=$2 or exists(select 1 from plan_item p
315 + where s.student_user_id=$1 and s.archived_at is null and ($1=$2 or exists(select 1 from plan_item p
316 where p.subject_id=s.id and can_view_plan_item($2,p.id))) order by s.name`,
317 [studentUserId, req.identity.sub],
318 ),
@@ -346,7 +351,7 @@ export function createPhase3Router({ pool, auth }) {
351 `select c.*,s.name as subject_name,s.color_key
352 from class_session c
353 join subject s on s.id=c.subject_id
349 - where s.student_user_id=$1 and ($1=$2 or exists(select 1 from plan_item p
354 + where s.student_user_id=$1 and s.archived_at is null and c.archived_at is null and ($1=$2 or exists(select 1 from plan_item p
355 where p.subject_id=s.id and can_view_plan_item($2,p.id)))
356 order by c.weekday,c.starts_at`,
357 [req.params.studentUserId, req.identity.sub],
backend/src/phase4.js
-30
@@ -140,36 +140,6 @@ export function createPhase4Router({ pool, auth, sensitiveFeaturesEnabled = proc
140 res.status(204).end();
141 });
142
143 - router.post('/learning/checkins', async (req, res) => {
144 - const confidence = Number(req.body.confidence);
145 - const difficulty = Number(req.body.difficulty);
146 - if (
147 - !Number.isInteger(confidence) ||
148 - confidence < 1 ||
149 - confidence > 5 ||
150 - !Number.isInteger(difficulty) ||
151 - difficulty < 1 ||
152 - difficulty > 5
153 - ) {
154 - return res.status(400).json({ error: 'invalid_input' });
155 - }
156 - if (req.body.learningGoalId) {
157 - const goal = await pool.query('select 1 from learning_goal where id=$1 and owner_user_id=$2', [req.body.learningGoalId, req.identity.sub]);
158 - if (!goal.rowCount) return res.status(403).json({ error: 'learning_goal_forbidden' });
159 - }
160 - const result = await pool.query(
161 - 'insert into learning_checkin(owner_user_id,learning_goal_id,confidence,difficulty,note) values($1,$2,$3,$4,$5) returning *',
162 - [
163 - req.identity.sub,
164 - req.body.learningGoalId || null,
165 - confidence,
166 - difficulty,
167 - clampText(req.body.note, 2000) || null,
168 - ],
169 - );
170 - res.status(201).json(result.rows[0]);
171 - });
172 -
143 router.post('/wellbeing/checkins', requireSensitive, async (req, res) => {
144 const mood = Number(req.body.mood);
145 const energy = Number(req.body.energy);
backend/src/school_crud_router.js new
+224
@@ -0,0 +1,224 @@
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 +}
backend/src/server.js
+2
@@ -11,6 +11,7 @@ import { createSessionAuth } from './session_auth.js';
11 import { createAuthRouter } from './auth_router.js';
12 import { createStudySessionsRouter } from './study_sessions.js';
13 import { createProfileRouter } from './profile_router.js';
14 +import { createSchoolCrudRouter } from './school_crud_router.js';
15 import { normalizeEmail, normalizePhone, isEmail } from './auth_contacts.js';
16 import { createEmailProvider, safelyDeliver } from './auth_delivery.js';
17
@@ -383,6 +384,7 @@ app.delete('/v1/families/:familyId/guardians', auth, async (req, res) => {
384 familyResponse(res, result);
385 });
386
387 +app.use('/v1', createSchoolCrudRouter({ pool, auth }));
388 app.use('/v1', createPhase3Router({ pool, auth }));
389 app.use('/v1', createPhase4Router({ pool, auth }));
390 app.use('/v1', createPhase6Router({ pool, auth }));
backend/tests/privacy_regression.test.js
+2
@@ -7,6 +7,7 @@ import jwt from 'jsonwebtoken';
7 import pg from 'pg';
8 import { createPhase4Router } from '../src/phase4.js';
9 import { createPhase6Router } from '../src/phase6.js';
10 +import { createSchoolCrudRouter } from '../src/school_crud_router.js';
11 import { createSessionAuth } from '../src/session_auth.js';
12 import { operationalErrorHandler } from '../src/operations.js';
13
@@ -23,6 +24,7 @@ async function serve(options) {
24 const app = express();
25 app.use(express.json({ limit: '64kb' }));
26 const auth = createSessionAuth({ pool, jwtSecret: secret });
27 + app.use('/v1', createSchoolCrudRouter({ pool, auth }));
28 app.use('/v1', createPhase4Router({ pool, auth, ...options }));
29 app.use('/v1', createPhase6Router({ pool, auth, ...options }));
30 app.use(operationalErrorHandler);
backend/tests/school_crud.test.js new
+292
@@ -0,0 +1,292 @@
1 +import test, { after, before } from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import crypto from 'node:crypto';
4 +import { spawn } from 'node:child_process';
5 +import { once } from 'node:events';
6 +import net from 'node:net';
7 +import pg from 'pg';
8 +import jwt from 'jsonwebtoken';
9 +import fs from 'node:fs/promises';
10 +
11 +assert.ok(process.env.DATABASE_URL, 'School tests require migrated synthetic PostgreSQL');
12 +assert.ok(process.env.JWT_SECRET?.length >= 32, 'School tests require a synthetic JWT secret');
13 +const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
14 +const users = [], families = [];
15 +let child, base, output = '', errors = '';
16 +
17 +async function start() {
18 + const reservation = net.createServer().listen(0, '127.0.0.1');
19 + await once(reservation, 'listening');
20 + const port = reservation.address().port;
21 + await new Promise((resolve) => reservation.close(resolve));
22 + base = `http://127.0.0.1:${port}`;
23 + let startup = '';
24 + child = spawn(process.execPath, ['src/entrypoint.js'], {
25 + env: { ...process.env, NODE_ENV: 'production', PORT: String(port), EMAIL_FROM: '', RESEND_API_KEY: '', SMTP_HOST: '',
26 + CORS_ORIGINS: '', TRUSTED_PROXY_CIDRS: '', ENABLE_SENSITIVE_FEATURES: 'false',
27 + RATE_LIMIT_AUTH_MAX: '2000', RATE_LIMIT_GENERAL_MAX: '4000', RATE_LIMIT_AI_MAX: '2000' },
28 + stdio: ['ignore', 'pipe', 'pipe'],
29 + });
30 + child.stdout.on('data', (chunk) => { output += chunk.toString(); startup += chunk.toString(); });
31 + child.stderr.on('data', (chunk) => { errors += chunk.toString(); });
32 + await new Promise((resolve, reject) => {
33 + const timer = setTimeout(() => reject(new Error('School fixture startup timed out')), 10000);
34 + const onData = () => {
35 + if (!startup.includes('"type":"startup"')) return;
36 + clearTimeout(timer); child.stdout.off('data', onData); resolve();
37 + };
38 + child.stdout.on('data', onData);
39 + child.once('error', (error) => { clearTimeout(timer); reject(error); });
40 + });
41 +}
42 +async function stop() {
43 + if (child && child.exitCode === null && child.signalCode === null) {
44 + const closed = once(child, 'close'); child.kill('SIGTERM'); await closed;
45 + }
46 +}
47 +before(start);
48 +after(async () => {
49 + await stop();
50 + try {
51 + await pool.query('delete from access_audit where family_id=any($1::uuid[]) or actor_user_id=any($2::uuid[])', [families, users]);
52 + await pool.query('delete from family_workspace where id=any($1::uuid[])', [families]);
53 + await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
54 + } finally { await pool.end(); }
55 +});
56 +async function user() {
57 + const id = crypto.randomUUID(), sid = crypto.randomUUID();
58 + users.push(id);
59 + await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', [id, `school-fixture:${id}`, `school-${id}@example.test`]);
60 + await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic School User','adult_blue')", [id]);
61 + await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')", [sid, id, crypto.randomBytes(32).toString('hex')]);
62 + return { id, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, process.env.JWT_SECRET, { issuer: 'lifemate', expiresIn: '15m' }) };
63 +}
64 +async function request(path, { method = 'GET', actor, body } = {}) {
65 + const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json', ...(actor ? { authorization: `Bearer ${actor.token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
66 + const text = await response.text();
67 + return { status: response.status, body: text && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(text) : text || null };
68 +}
69 +async function school(actor = undefined) {
70 + actor ??= await user();
71 + const context = await request('/v1/life-contexts', { method: 'POST', actor, body: { kind: 'student', title: 'Synthetic School' } });
72 + assert.equal(context.status, 201);
73 + const year = await request('/v1/school/years', { method: 'POST', actor, body: { lifeContextId: context.body.id, title: 'Synthetic Year', startsOn: '2026-09-01', endsOn: '2027-06-30' } });
74 + assert.equal(year.status, 201);
75 + const term = await request(`/v1/school/years/${year.body.id}/terms`, { method: 'POST', actor, body: { title: 'Synthetic Term', startsOn: '2026-09-01', endsOn: '2027-01-31' } });
76 + assert.equal(term.status, 201);
77 + const subject = await request(`/v1/school/terms/${term.body.id}/subjects`, { method: 'POST', actor, body: { name: 'Synthetic Math', teacherName: 'Synthetic Teacher', colorKey: 'blue' } });
78 + assert.equal(subject.status, 201);
79 + const lesson = await request(`/v1/school/subjects/${subject.body.id}/classes`, { method: 'POST', actor, body: { weekday: 1, startsAt: '09:00', endsAt: '10:00', location: 'Synthetic Room', recurrenceUntil: '2027-01-31' } });
80 + assert.equal(lesson.status, 201);
81 + return { actor, context: context.body, year: year.body, term: term.body, subject: subject.body, lesson: lesson.body };
82 +}
83 +async function familyFixture() {
84 + const f = await school();
85 + const parent = await user(), outsider = await user();
86 + const familyId = crypto.randomUUID(); families.push(familyId);
87 + await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic School Family',$2)", [familyId, parent.id]);
88 + await pool.query("insert into family_membership(family_id,user_id,role) values($1,$2,'teen_minor'),($1,$3,'parent_guardian')", [familyId, f.actor.id, parent.id]);
89 + await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, parent.id, f.actor.id]);
90 + return { ...f, parent, outsider, familyId };
91 +}
92 +
93 +test('subject create/read/edit survives a real API process restart and archive preserves homework and report names', async () => {
94 + const f = await familyFixture();
95 + const path = `/v1/school/subjects/${f.subject.id}`;
96 + assert.equal((await request(path, { actor: f.actor })).status, 200);
97 + const updated = await request(path, { method: 'PATCH', actor: f.actor, body: { name: 'Renamed Math', teacherName: null, colorKey: 'green' } });
98 + assert.equal(updated.status, 200);
99 + const homework = await request('/v1/plan-items', { method: 'POST', actor: f.actor, body: { kind: 'assignment', title: 'Historical Math Homework', subjectId: f.subject.id, familyId: f.familyId, visibility: 'parent_guardian', notes: 'PRIVATE-SCHOOL-NOTE-MARKER' } });
100 + assert.equal(homework.status, 201);
101 + await stop(); await start();
102 + const reopened = await request(path, { actor: f.actor });
103 + assert.equal(reopened.status, 200);
104 + assert.equal(reopened.body.name, 'Renamed Math');
105 + assert.equal(reopened.body.teacher_name, null);
106 + assert.equal((await request(path, { method: 'DELETE', actor: f.actor })).status, 204);
107 + assert.equal((await request(path, { method: 'DELETE', actor: f.actor })).status, 204);
108 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body: { name: 'Must Not Restore' } })).status, 409);
109 + assert.ok((await request(path, { actor: f.actor })).body.archived_at);
110 + const current = await request(`/v1/school/${f.actor.id}/overview`, { actor: f.actor });
111 + assert.equal(current.status, 200);
112 + assert.equal(current.body.subjects.some((item) => item.id === f.subject.id), false);
113 + assert.equal((await request(`/v1/school/${f.actor.id}/timetable`, { actor: f.actor })).body.classes.length, 0);
114 + const stored = (await pool.query('select p.subject_id,s.name,s.archived_at from plan_item p join subject s on s.id=p.subject_id where p.id=$1', [homework.body.id])).rows[0];
115 + assert.equal(stored.subject_id, f.subject.id);
116 + assert.equal(stored.name, 'Renamed Math');
117 + assert.ok(stored.archived_at);
118 + const report = await request(`/v1/families/${f.familyId}/children/${f.actor.id}/learning-report`, { actor: f.parent });
119 + assert.equal(report.status, 200);
120 + assert.equal(report.body.items.find((item) => item.id === homework.body.id).subjectName, 'Renamed Math');
121 + assert.equal(JSON.stringify(report.body).includes('PRIVATE-SCHOOL-NOTE-MARKER'), false);
122 +});
123 +
124 +test('class edits validate real times/dates and ownership, and archive remains persistent and owner-only', async () => {
125 + const f = await school();
126 + const other = await school();
127 + const path = `/v1/school/classes/${f.lesson.id}`;
128 + assert.equal((await request(path, { actor: f.actor })).status, 200);
129 + for (const bad of [{ weekday: 8 }, { weekday: '2' }, { startsAt: '10:00', endsAt: '09:00' }, { startsAt: '25:00' }, { endsAt: '10:00Z' }, { recurrenceUntil: '2026-02-30' }, { recurrenceUntil: '2027-02-01' }, { location: 'x'.repeat(241) }]) {
130 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body: bad })).status, 400);
131 + }
132 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body: { subjectId: other.subject.id } })).status, 403);
133 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body: { weekday: 3, startsAt: '11:15', endsAt: '12:00', location: null, recurrenceUntil: null } })).status, 200);
134 + await stop(); await start();
135 + const reopened = await request(path, { actor: f.actor });
136 + assert.equal(reopened.body.weekday, 3);
137 + assert.equal(reopened.body.starts_at, '11:15:00');
138 + assert.equal(reopened.body.location, null);
139 + assert.equal((await request(path, { method: 'DELETE', actor: other.actor })).status, 404);
140 + assert.equal((await request(path, { method: 'DELETE', actor: f.actor })).status, 204);
141 + assert.equal((await request(path, { method: 'DELETE', actor: f.actor })).status, 204);
142 + assert.equal((await request(`/v1/school/${f.actor.id}/timetable`, { actor: f.actor })).body.classes.length, 0);
143 + assert.ok((await pool.query('select archived_at from class_session where id=$1', [f.lesson.id])).rows[0].archived_at);
144 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body: { weekday: 2 } })).status, 409);
145 +});
146 +
147 +test('guardians can read only currently authorized school projections and cannot mutate owner courses/classes', async () => {
148 + const f = await familyFixture();
149 + await request('/v1/plan-items', { method: 'POST', actor: f.actor, body: { title: 'Shared Class Homework', kind: 'assignment', familyId: f.familyId, subjectId: f.subject.id, visibility: 'parent_guardian' } });
150 + for (const actor of [f.parent, f.outsider]) {
151 + for (const path of [`/v1/school/subjects/${f.subject.id}`, `/v1/school/classes/${f.lesson.id}`]) {
152 + for (const method of ['GET', 'PATCH', 'DELETE']) assert.equal((await request(path, { method, actor, body: method === 'PATCH' ? { name: 'Forbidden', weekday: 2 } : undefined })).status, 404);
153 + }
154 + }
155 + assert.equal((await request(`/v1/school/${f.actor.id}/timetable`, { actor: f.parent })).body.classes.length, 1);
156 + assert.equal((await request(`/v1/school/${f.actor.id}/timetable`, { actor: f.outsider })).status, 403);
157 + await pool.query('update guardian_relationship set active=false where family_id=$1', [f.familyId]);
158 + assert.equal((await request(`/v1/school/${f.actor.id}/overview`, { actor: f.parent })).status, 403);
159 + await pool.query('update guardian_relationship set active=true where family_id=$1', [f.familyId]);
160 + await pool.query('update family_workspace set archived_at=now() where id=$1', [f.familyId]);
161 + assert.equal((await request(`/v1/school/${f.actor.id}/timetable`, { actor: f.parent })).status, 403);
162 + assert.equal((await request(`/v1/school/subjects/${f.subject.id}`, { actor: f.actor })).status, 200);
163 +});
164 +
165 +test('subject edits require an active owned term and reject invalid fields without partial changes', async () => {
166 + const f = await school(), other = await school();
167 + const path = `/v1/school/subjects/${f.subject.id}`;
168 + for (const body of [{ name: '' }, { name: 'x'.repeat(121) }, { teacherName: 'x'.repeat(121) }, { colorKey: 'x'.repeat(41) }, { academicTermId: 'invalid' }]) {
169 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body })).status, 400);
170 + }
171 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body: { name: 'Must Not Change', academicTermId: other.term.id } })).status, 403);
172 + assert.equal((await request(path, { actor: f.actor })).body.name, 'Synthetic Math');
173 + const nextTerm = await request(`/v1/school/years/${f.year.id}/terms`, { method: 'POST', actor: f.actor, body: { title: 'Next Term', startsOn: '2027-02-01', endsOn: '2027-06-30' } });
174 + assert.equal(nextTerm.status, 201);
175 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body: { academicTermId: nextTerm.body.id } })).status, 400);
176 + assert.equal((await request(`/v1/school/classes/${f.lesson.id}`, { method: 'PATCH', actor: f.actor, body: { recurrenceUntil: null } })).status, 200);
177 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body: { academicTermId: nextTerm.body.id } })).status, 200);
178 + await pool.query('update academic_year set active=false where id=$1', [f.year.id]);
179 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body: { name: 'Inactive Term' } })).status, 409);
180 +});
181 +
182 +test('school create rejects malformed dates/times and archived subject links without inserting records', async () => {
183 + const f = await school();
184 + for (const body of [
185 + { title: 'Invalid Year', startsOn: '2026-02-30', endsOn: '2026-06-30' },
186 + { title: 'Reversed Year', startsOn: '2027-06-30', endsOn: '2026-09-01' },
187 + { title: 'x'.repeat(121), startsOn: '2026-09-01', endsOn: '2027-06-30' },
188 + ]) assert.equal((await request('/v1/school/years', { method: 'POST', actor: f.actor, body: { ...body, lifeContextId: f.context.id } })).status, 400);
189 + assert.equal((await request(`/v1/school/years/${f.year.id}/terms`, { method: 'POST', actor: f.actor, body: { title: 'Outside Year', startsOn: '2026-08-01', endsOn: '2027-01-31' } })).status, 400);
190 + assert.equal((await request(`/v1/school/terms/${f.term.id}/subjects`, { method: 'POST', actor: f.actor, body: { name: 'x'.repeat(121) } })).status, 400);
191 + const classPath = `/v1/school/subjects/${f.subject.id}/classes`;
192 + for (const body of [{ weekday: 0, startsAt: '09:00', endsAt: '10:00' }, { weekday: 1, startsAt: '25:00', endsAt: '26:00' }, { weekday: 1, startsAt: '10:00', endsAt: '09:00' }, { weekday: 1, startsAt: '09:00', endsAt: '10:00', recurrenceUntil: '2026-02-30' }]) {
193 + assert.equal((await request(classPath, { method: 'POST', actor: f.actor, body })).status, 400);
194 + }
195 + assert.equal((await request(`/v1/school/subjects/${f.subject.id}`, { method: 'DELETE', actor: f.actor })).status, 204);
196 + assert.equal((await request(classPath, { method: 'POST', actor: f.actor, body: { weekday: 1, startsAt: '09:00', endsAt: '10:00' } })).status, 409);
197 + assert.equal((await pool.query('select count(*)::int as n from class_session where subject_id=$1', [f.subject.id])).rows[0].n, 1);
198 +});
199 +
200 +test('learning check-ins have persistent owner CRUD, explicit self-report timestamps and private notes', async () => {
201 + const f = await familyFixture();
202 + const goal = await request('/v1/learning/goals', { method: 'POST', actor: f.actor, body: { title: 'Synthetic Goal', subjectId: f.subject.id } });
203 + assert.equal(goal.status, 201);
204 + const created = await request('/v1/learning/checkins', { method: 'POST', actor: f.actor, body: { learningGoalId: goal.body.id, confidence: 2, difficulty: 4, note: 'PRIVATE-CHECKIN-SYNTHETIC-MARKER' } });
205 + assert.equal(created.status, 201);
206 + assert.equal(created.body.source, 'self_reported');
207 + assert.equal(created.body.isEvidenceOfStudy, false);
208 + assert.ok(created.body.occurred_at);
209 + const path = `/v1/learning/checkins/${created.body.id}`;
210 + assert.equal((await request(path, { actor: f.actor })).body.note, 'PRIVATE-CHECKIN-SYNTHETIC-MARKER');
211 + for (const actor of [f.parent, f.outsider]) {
212 + assert.equal((await request(path, { actor })).status, 404);
213 + assert.equal((await request(path, { method: 'PATCH', actor, body: { note: 'Forbidden' } })).status, 404);
214 + assert.equal((await request(path, { method: 'DELETE', actor })).status, 404);
215 + assert.equal(JSON.stringify((await request('/v1/learning/checkins', { actor })).body).includes('PRIVATE-CHECKIN-SYNTHETIC-MARKER'), false);
216 + }
217 + const occurredAt = new Date(Date.now() - 86400000).toISOString();
218 + const updated = await request(path, { method: 'PATCH', actor: f.actor, body: { confidence: 5, difficulty: 1, note: null, occurredAt } });
219 + assert.equal(updated.status, 200);
220 + await stop(); await start();
221 + const reopened = await request(path, { actor: f.actor });
222 + assert.equal(reopened.status, 200);
223 + assert.equal(reopened.body.confidence, 5);
224 + assert.equal(reopened.body.note, null);
225 + assert.equal(reopened.body.occurred_at, occurredAt);
226 + assert.equal((await request(path, { method: 'DELETE', actor: f.actor })).status, 204);
227 + assert.equal((await request(path, { method: 'DELETE', actor: f.actor })).status, 204);
228 + assert.equal((await request('/v1/learning/checkins', { actor: f.actor })).body.items.some((item) => item.id === created.body.id), false);
229 + assert.equal((await request(path, { method: 'PATCH', actor: f.actor, body: { confidence: 3 } })).status, 409);
230 + const stored = (await pool.query('select archived_at,note,learning_goal_id from learning_checkin where id=$1', [created.body.id])).rows[0];
231 + assert.ok(stored.archived_at);
232 + assert.equal(stored.learning_goal_id, goal.body.id);
233 + assert.equal(stored.note, null);
234 + assert.equal(errors.includes('PRIVATE-CHECKIN-SYNTHETIC-MARKER'), false);
235 + assert.equal(output.includes('PRIVATE-CHECKIN-SYNTHETIC-MARKER'), false);
236 +});
237 +
238 +test('check-in validation rejects forged/archived goals, invalid timestamps and claimed evidence without data loss', async () => {
239 + const actor = await user(), other = await user();
240 + const own = await request('/v1/learning/goals', { method: 'POST', actor, body: { title: 'Own Goal' } });
241 + const foreign = await request('/v1/learning/goals', { method: 'POST', actor: other, body: { title: 'Foreign Goal' } });
242 + const body = { confidence: 3, difficulty: 3, note: 'Unchanged Note', learningGoalId: own.body.id };
243 + assert.equal((await request('/v1/learning/checkins', { method: 'POST', actor, body: { ...body, learningGoalId: foreign.body.id } })).status, 403);
244 + const created = await request('/v1/learning/checkins', { method: 'POST', actor, body });
245 + assert.equal(created.status, 201);
246 + const path = `/v1/learning/checkins/${created.body.id}`;
247 + for (const bad of [{ confidence: 0 }, { difficulty: 6 }, { difficulty: '3' }, { note: 'x'.repeat(2001) }, { occurredAt: '2026-02-30T12:00:00Z' }, { occurredAt: new Date(Date.now() + 300000).toISOString() }, { source: 'verified' }, { isEvidenceOfStudy: true }]) {
248 + assert.equal((await request(path, { method: 'PATCH', actor, body: { ...bad, note: bad.note ?? 'Must Not Save' } })).status, 400);
249 + }
250 + assert.equal((await request(path, { method: 'PATCH', actor, body: { learningGoalId: foreign.body.id } })).status, 403);
251 + assert.equal((await request(path, { actor })).body.note, 'Unchanged Note');
252 + assert.equal((await request(`/v1/learning/goals/${own.body.id}`, { method: 'DELETE', actor })).status, 204);
253 + assert.equal((await request('/v1/learning/checkins', { method: 'POST', actor, body })).status, 403);
254 + assert.equal((await request(path, { method: 'PATCH', actor, body: { learningGoalId: own.body.id } })).status, 403);
255 + assert.equal((await request(path, { method: 'PATCH', actor, body: { learningGoalId: null, note: 'Detached Private Note' } })).status, 200);
256 +});
257 +
258 +test('every new school/check-in operation requires current verified sessions and validates IDs', async () => {
259 + const id = crypto.randomUUID();
260 + const actor = await user();
261 + for (const path of [`/v1/school/subjects/${id}`, `/v1/school/classes/${id}`, `/v1/learning/checkins/${id}`]) {
262 + for (const method of ['GET', 'PATCH', 'DELETE']) assert.equal((await request(path, { method, body: method === 'PATCH' ? {} : undefined })).status, 401);
263 + }
264 + for (const path of ['/v1/school/subjects/bad', '/v1/school/classes/bad', '/v1/learning/checkins/bad']) {
265 + assert.equal((await request(path, { actor })).status, 400);
266 + }
267 + await pool.query('update app_user set disabled_at=now() where id=$1', [actor.id]);
268 + assert.equal((await request('/v1/learning/checkins', { actor })).status, 401);
269 +});
270 +
271 +test('school and check-in migration preserves legacy IDs, linked homework, notes and original timestamps', async () => {
272 + const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
273 + await client.connect();
274 + try {
275 + await client.query(`create temporary table subject(id uuid primary key,student_user_id uuid,name text,created_at timestamptz);
276 + create temporary table class_session(id uuid primary key,subject_id uuid,weekday smallint,starts_at time,created_at timestamptz);
277 + create temporary table learning_checkin(id uuid primary key,owner_user_id uuid,learning_goal_id uuid,note text,confidence smallint,created_at timestamptz);
278 + create temporary table plan_item(id uuid primary key,subject_id uuid)`);
279 + const subjectId = crypto.randomUUID(), classId = crypto.randomUUID(), checkinId = crypto.randomUUID(), owner = crypto.randomUUID(), goalId = crypto.randomUUID();
280 + await client.query("insert into subject values($1,$2,'Legacy Course','2025-01-01T09:00:00Z')", [subjectId, owner]);
281 + await client.query("insert into class_session values($1,$2,2,'09:00','2025-01-02T09:00:00Z')", [classId, subjectId]);
282 + await client.query("insert into learning_checkin values($1,$2,$3,'Legacy Private Note',4,'2025-01-03T09:00:00Z')", [checkinId, owner, goalId]);
283 + await client.query('insert into plan_item values($1,$2)', [crypto.randomUUID(), subjectId]);
284 + await client.query(await fs.readFile(new URL('../migrations/0012_school_archive.sql', import.meta.url), 'utf8'));
285 + const course = (await client.query('select s.id,s.name,s.created_at=s.updated_at as timestamp_preserved,s.archived_at,p.subject_id from subject s join plan_item p on p.subject_id=s.id')).rows[0];
286 + assert.equal(course.id, subjectId); assert.equal(course.subject_id, subjectId); assert.equal(course.name, 'Legacy Course'); assert.equal(course.timestamp_preserved, true); assert.equal(course.archived_at, null);
287 + const lesson = (await client.query('select id,subject_id,weekday,starts_at,created_at=updated_at as timestamp_preserved,archived_at from class_session')).rows[0];
288 + assert.equal(lesson.id, classId); assert.equal(lesson.subject_id, subjectId); assert.equal(lesson.weekday, 2); assert.equal(lesson.timestamp_preserved, true); assert.equal(lesson.archived_at, null);
289 + const checkin = (await client.query('select id,learning_goal_id,note,confidence,source,created_at=occurred_at and created_at=updated_at as timestamp_preserved,archived_at from learning_checkin')).rows[0];
290 + assert.equal(checkin.id, checkinId); assert.equal(checkin.learning_goal_id, goalId); assert.equal(checkin.note, 'Legacy Private Note'); assert.equal(checkin.confidence, 4); assert.equal(checkin.source, 'self_reported'); assert.equal(checkin.timestamp_preserved, true); assert.equal(checkin.archived_at, null);
291 + } finally { await client.end(); }
292 +});