LifeMate — Personal, Family & Learning Companion
test/personal-notification-settings
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
| 1 | import express from 'express'; |
| 2 | import { schoolLifecycleError, assertSchoolSession } from './school_lifecycle.js'; |
| 3 | |
| 4 | const uuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value); |
| 5 | const has = (body, key) => Object.hasOwn(body, key); |
| 6 | class SchoolInputError extends Error { |
| 7 | constructor(status, code) { super(code); this.status = status; this.code = code; } |
| 8 | } |
| 9 | const fail = (status, code) => { throw new SchoolInputError(status, code); }; |
| 10 | function id(value) { if (!uuid(value)) fail(400, 'invalid_id'); return value; } |
| 11 | function text(value, max, nullable = false) { |
| 12 | if (nullable && value == null) return null; |
| 13 | if (nullable && typeof value === 'string' && !value.trim()) return null; |
| 14 | if (typeof value !== 'string' || !value.trim() || value.trim().length > max) fail(400, 'invalid_input'); |
| 15 | return value.trim(); |
| 16 | } |
| 17 | function date(value) { |
| 18 | if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000-')) return null; |
| 19 | const parsed = new Date(`${value}T00:00:00Z`); |
| 20 | return Number.isFinite(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value ? value : null; |
| 21 | } |
| 22 | function time(value) { |
| 23 | if (typeof value !== 'string' || !/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test(value)) fail(400, 'invalid_class_time'); |
| 24 | return value.length === 5 ? value + ':00' : value; |
| 25 | } |
| 26 | function occurred(value) { |
| 27 | 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'); |
| 28 | const parsed = new Date(value); |
| 29 | if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 19) !== value.slice(0, 19) || parsed.getTime() > Date.now() + 60000) fail(400, 'invalid_occurred_at'); |
| 30 | return parsed; |
| 31 | } |
| 32 | const checkinRow = (row) => ({ ...row, isEvidenceOfStudy: false }); |
| 33 | const route = (handler) => async (req, res, next) => { |
| 34 | try { await handler(req, res); } |
| 35 | catch (raw) { |
| 36 | const error = schoolLifecycleError(raw); |
| 37 | if (error instanceof SchoolInputError || (error.status && (error.code?.startsWith('school_') || error.code === 'session_invalid'))) return res.status(error.status).json({ error: error.code }); |
| 38 | next(error); |
| 39 | } |
| 40 | }; |
| 41 | async function transaction(pool, operation, identity, write = true) { |
| 42 | const client = await pool.connect(); |
| 43 | try { |
| 44 | await client.query('begin'); |
| 45 | const account = await client.query(`select 1 from app_user where id=$1 and disabled_at is null for ${write ? 'update' : 'share'}`, [identity.sub]); |
| 46 | if (!account.rowCount) fail(401, 'session_invalid'); |
| 47 | await assertSchoolSession(client, identity); |
| 48 | const result = await operation(client); |
| 49 | await assertSchoolSession(client, identity); |
| 50 | await client.query('commit'); |
| 51 | return result; |
| 52 | } catch (error) { |
| 53 | await client.query('rollback').catch(() => {}); |
| 54 | throw error; |
| 55 | } finally { client.release(); } |
| 56 | } |
| 57 | async function ownedTerm(client, termId, userId, status = 403) { |
| 58 | const result = await client.query(`select t.*,t.starts_on::text as first_day,t.ends_on::text as last_day |
| 59 | from academic_term t join academic_year y on y.id=t.academic_year_id |
| 60 | join life_context l on l.id=y.life_context_id |
| 61 | where t.id=$1 and y.student_user_id=$2 and l.user_id=$2 and t.active and y.active and l.active |
| 62 | for share of t,y,l`, [termId, userId]); |
| 63 | if (!result.rowCount) fail(status, status === 403 ? 'academic_term_forbidden' : 'school_parent_inactive'); |
| 64 | return result.rows[0]; |
| 65 | } |
| 66 | async function activeSubject(client, subjectId, userId) { |
| 67 | const result = await client.query('select * from subject where id=$1 and student_user_id=$2 for share', [subjectId, userId]); |
| 68 | if (!result.rowCount) fail(403, 'subject_forbidden'); |
| 69 | if (result.rows[0].archived_at) fail(409, 'subject_archived'); |
| 70 | return { subject: result.rows[0], term: await ownedTerm(client, result.rows[0].academic_term_id, userId, 409) }; |
| 71 | } |
| 72 | function classFields(body, current) { |
| 73 | const next = { ...current }; |
| 74 | if (has(body, 'weekday')) { |
| 75 | if (!Number.isInteger(body.weekday) || body.weekday < 1 || body.weekday > 7) fail(400, 'invalid_weekday'); |
| 76 | next.weekday = body.weekday; |
| 77 | } |
| 78 | if (has(body, 'startsAt')) next.starts_at = time(body.startsAt); |
| 79 | if (has(body, 'endsAt')) next.ends_at = time(body.endsAt); |
| 80 | if (next.ends_at <= next.starts_at) fail(400, 'invalid_class_time'); |
| 81 | if (has(body, 'location')) next.location = text(body.location, 240, true); |
| 82 | if (has(body, 'recurrenceUntil')) { |
| 83 | if (body.recurrenceUntil != null && !date(body.recurrenceUntil)) fail(400, 'invalid_recurrence_date'); |
| 84 | next.recurrence_until = body.recurrenceUntil ?? null; |
| 85 | } |
| 86 | return next; |
| 87 | } |
| 88 | function checkinFields(body, current) { |
| 89 | const next = { ...current }; |
| 90 | for (const field of ['confidence', 'difficulty']) if (has(body, field)) { |
| 91 | if (!Number.isInteger(body[field]) || body[field] < 1 || body[field] > 5) fail(400, 'invalid_input'); |
| 92 | next[field] = body[field]; |
| 93 | } |
| 94 | if (has(body, 'note')) next.note = text(body.note, 2000, true); |
| 95 | if (has(body, 'learningGoalId')) next.learning_goal_id = body.learningGoalId == null ? null : id(body.learningGoalId); |
| 96 | if (has(body, 'occurredAt')) next.occurred_at = occurred(body.occurredAt); |
| 97 | if ((has(body, 'source') && body.source !== 'self_reported') || (has(body, 'isEvidenceOfStudy') && body.isEvidenceOfStudy !== false)) fail(400, 'self_report_only'); |
| 98 | return next; |
| 99 | } |
| 100 | async function ownedGoal(client, goalId, userId) { |
| 101 | if (goalId == null) return; |
| 102 | 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]); |
| 103 | if (!result.rowCount) fail(403, 'learning_goal_forbidden'); |
| 104 | } |
| 105 | |
| 106 | export function createSchoolCrudRouter({ pool, auth }) { |
| 107 | const router = express.Router(); |
| 108 | router.post('/school/subjects/:id/classes', auth, route(async (req, res) => { |
| 109 | const subjectId = id(req.params.id), body = req.body ?? {}; |
| 110 | if (!['weekday', 'startsAt', 'endsAt'].every((key) => has(body, key))) fail(400, 'invalid_input'); |
| 111 | const next = classFields(body, { location: null, recurrence_until: null }); |
| 112 | const result = await transaction(pool, async (client) => { |
| 113 | const { term } = await activeSubject(client, subjectId, req.identity.sub); |
| 114 | if (next.recurrence_until && (next.recurrence_until < term.first_day || next.recurrence_until > term.last_day)) fail(400, 'class_recurrence_outside_term'); |
| 115 | return (await client.query(`insert into class_session(subject_id,weekday,starts_at,ends_at,location,recurrence_until) |
| 116 | values($1,$2,$3,$4,$5,$6) returning *`, [subjectId, next.weekday, next.starts_at, next.ends_at, next.location, next.recurrence_until])).rows[0]; |
| 117 | }, req.identity); |
| 118 | res.status(201).json(result); |
| 119 | })); |
| 120 | router.get('/school/subjects/:id', auth, route(async (req, res) => { |
| 121 | const result = await transaction(pool, (client) => client.query('select * from subject where id=$1 and student_user_id=$2', [id(req.params.id), req.identity.sub]), req.identity, false); |
| 122 | if (!result.rowCount) fail(404, 'subject_not_found'); |
| 123 | res.json(result.rows[0]); |
| 124 | })); |
| 125 | router.patch('/school/subjects/:id', auth, route(async (req, res) => { |
| 126 | const subjectId = id(req.params.id), body = req.body ?? {}; |
| 127 | if (!['name', 'teacherName', 'colorKey', 'academicTermId'].some((key) => has(body, key))) fail(400, 'invalid_input'); |
| 128 | const name = has(body, 'name') ? text(body.name, 120) : null; |
| 129 | const teacher = has(body, 'teacherName') ? text(body.teacherName, 120, true) : null; |
| 130 | const color = has(body, 'colorKey') ? text(body.colorKey, 40, true) : null; |
| 131 | if (has(body, 'academicTermId')) id(body.academicTermId); |
| 132 | const result = await transaction(pool, async (client) => { |
| 133 | const current = await client.query('select * from subject where id=$1 and student_user_id=$2 for update', [subjectId, req.identity.sub]); |
| 134 | if (!current.rowCount) fail(404, 'subject_not_found'); |
| 135 | if (current.rows[0].archived_at) fail(409, 'subject_archived'); |
| 136 | await ownedTerm(client, current.rows[0].academic_term_id, req.identity.sub, 409); |
| 137 | const termId = body.academicTermId ?? current.rows[0].academic_term_id; |
| 138 | const term = await ownedTerm(client, termId, req.identity.sub, has(body, 'academicTermId') ? 403 : 409); |
| 139 | const invalidClass = await client.query(`select 1 from class_session where subject_id=$1 and archived_at is null |
| 140 | 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]); |
| 141 | if (invalidClass.rowCount) fail(400, 'class_recurrence_outside_term'); |
| 142 | return (await client.query(`update subject set name=coalesce($3,name), |
| 143 | teacher_name=case when $4 then $5 else teacher_name end, |
| 144 | color_key=case when $6 then $7 else color_key end,academic_term_id=$8,updated_at=now() |
| 145 | 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]; |
| 146 | }, req.identity); |
| 147 | res.json(result); |
| 148 | })); |
| 149 | router.delete('/school/subjects/:id', auth, route(async (req, res) => { |
| 150 | const result = await transaction(pool, (client) => client.query(`update subject set updated_at=case when archived_at is null then now() else updated_at end, |
| 151 | archived_at=coalesce(archived_at,now()) where id=$1 and student_user_id=$2 returning id`, [id(req.params.id), req.identity.sub]), req.identity); |
| 152 | if (!result.rowCount) fail(404, 'subject_not_found'); |
| 153 | res.status(204).end(); |
| 154 | })); |
| 155 | |
| 156 | router.get('/school/classes/:id', auth, route(async (req, res) => { |
| 157 | const result = await transaction(pool, (client) => client.query(`select c.*,s.name as subject_name,s.archived_at as subject_archived_at |
| 158 | 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]), req.identity, false); |
| 159 | if (!result.rowCount) fail(404, 'class_not_found'); |
| 160 | res.json(result.rows[0]); |
| 161 | })); |
| 162 | router.patch('/school/classes/:id', auth, route(async (req, res) => { |
| 163 | const classId = id(req.params.id), body = req.body ?? {}; |
| 164 | if (!['subjectId', 'weekday', 'startsAt', 'endsAt', 'location', 'recurrenceUntil'].some((key) => has(body, key))) fail(400, 'invalid_input'); |
| 165 | if (has(body, 'subjectId')) id(body.subjectId); |
| 166 | const result = await transaction(pool, async (client) => { |
| 167 | const current = await client.query(`select c.*,c.recurrence_until::text as recurrence_until |
| 168 | from class_session c join subject s on s.id=c.subject_id |
| 169 | where c.id=$1 and s.student_user_id=$2 for update of c`, [classId, req.identity.sub]); |
| 170 | if (!current.rowCount) fail(404, 'class_not_found'); |
| 171 | if (current.rows[0].archived_at) fail(409, 'class_archived'); |
| 172 | await activeSubject(client, current.rows[0].subject_id, req.identity.sub); |
| 173 | const subjectId = body.subjectId ?? current.rows[0].subject_id; |
| 174 | const { term } = await activeSubject(client, subjectId, req.identity.sub); |
| 175 | const next = classFields(body, current.rows[0]); |
| 176 | if (next.recurrence_until && (next.recurrence_until < term.first_day || next.recurrence_until > term.last_day)) fail(400, 'class_recurrence_outside_term'); |
| 177 | return (await client.query(`update class_session set subject_id=$2,weekday=$3,starts_at=$4,ends_at=$5, |
| 178 | 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]; |
| 179 | }, req.identity); |
| 180 | res.json(result); |
| 181 | })); |
| 182 | router.delete('/school/classes/:id', auth, route(async (req, res) => { |
| 183 | const result = await transaction(pool, (client) => client.query(`update class_session c set updated_at=case when c.archived_at is null then now() else c.updated_at end, |
| 184 | archived_at=coalesce(c.archived_at,now()) from subject s |
| 185 | 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]), req.identity); |
| 186 | if (!result.rowCount) fail(404, 'class_not_found'); |
| 187 | res.status(204).end(); |
| 188 | })); |
| 189 | |
| 190 | router.post('/learning/checkins', auth, route(async (req, res) => { |
| 191 | const body = req.body ?? {}; |
| 192 | if (!has(body, 'confidence') || !has(body, 'difficulty')) fail(400, 'invalid_input'); |
| 193 | const next = checkinFields(body, { learning_goal_id: null, note: null, occurred_at: new Date() }); |
| 194 | const result = await transaction(pool, async (client) => { |
| 195 | await ownedGoal(client, next.learning_goal_id, req.identity.sub); |
| 196 | return (await client.query(`insert into learning_checkin(owner_user_id,learning_goal_id,confidence,difficulty,note,occurred_at) |
| 197 | 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]; |
| 198 | }, req.identity); |
| 199 | res.status(201).json(checkinRow(result)); |
| 200 | })); |
| 201 | router.get('/learning/checkins', auth, route(async (req, res) => { |
| 202 | const result = await transaction(pool, (client) => client.query('select * from learning_checkin where owner_user_id=$1 and archived_at is null order by occurred_at desc,id', [req.identity.sub]), req.identity, false); |
| 203 | res.json({ items: result.rows.map(checkinRow) }); |
| 204 | })); |
| 205 | router.get('/learning/checkins/:id', auth, route(async (req, res) => { |
| 206 | const result = await transaction(pool, (client) => client.query('select * from learning_checkin where id=$1 and owner_user_id=$2', [id(req.params.id), req.identity.sub]), req.identity, false); |
| 207 | if (!result.rowCount) fail(404, 'checkin_not_found'); |
| 208 | res.json(checkinRow(result.rows[0])); |
| 209 | })); |
| 210 | router.patch('/learning/checkins/:id', auth, route(async (req, res) => { |
| 211 | const checkinId = id(req.params.id), body = req.body ?? {}; |
| 212 | if (!['learningGoalId', 'confidence', 'difficulty', 'note', 'occurredAt'].some((key) => has(body, key))) fail(400, 'invalid_input'); |
| 213 | const result = await transaction(pool, async (client) => { |
| 214 | const current = await client.query('select * from learning_checkin where id=$1 and owner_user_id=$2 for update', [checkinId, req.identity.sub]); |
| 215 | if (!current.rowCount) fail(404, 'checkin_not_found'); |
| 216 | if (current.rows[0].archived_at) fail(409, 'checkin_archived'); |
| 217 | const next = checkinFields(body, current.rows[0]); |
| 218 | if (has(body, 'learningGoalId')) await ownedGoal(client, next.learning_goal_id, req.identity.sub); |
| 219 | return (await client.query(`update learning_checkin set learning_goal_id=$3,confidence=$4,difficulty=$5,note=$6, |
| 220 | 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]; |
| 221 | }, req.identity); |
| 222 | res.json(checkinRow(result)); |
| 223 | })); |
| 224 | router.delete('/learning/checkins/:id', auth, route(async (req, res) => { |
| 225 | const result = await transaction(pool, (client) => client.query(`update learning_checkin set updated_at=case when archived_at is null then now() else updated_at end, |
| 226 | archived_at=coalesce(archived_at,now()) where id=$1 and owner_user_id=$2 returning id`, [id(req.params.id), req.identity.sub]), req.identity); |
| 227 | if (!result.rowCount) fail(404, 'checkin_not_found'); |
| 228 | res.status(204).end(); |
| 229 | })); |
| 230 | return router; |
| 231 | } |