LifeMate — Personal, Family & Learning Companion
feat/learning-content-operations
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 crypto from 'node:crypto'; |
| 2 | import express from 'express'; |
| 3 | import { schoolLifecycleError, assertSchoolSession } from './school_lifecycle.js'; |
| 4 | import { applyPlanMutation, createPlanItem, updatePlanItem, planTransaction, serializePlanItem, validUuid, PlanMutationError } from './plan_mutations.js'; |
| 5 | |
| 6 | const allowedKinds = new Set(['task','event','routine','goal','assignment','exam','study_session']); |
| 7 | const schoolText = (value, max = 120) => typeof value === 'string' && Boolean(value.trim()) && value.trim().length <= max; |
| 8 | const schoolOptionalText = (value, max = 120) => value == null || (typeof value === 'string' && value.trim().length <= max); |
| 9 | function schoolDate(value) { |
| 10 | if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000-')) return false; |
| 11 | const date = new Date(`${value}T00:00:00Z`); |
| 12 | return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value; |
| 13 | } |
| 14 | |
| 15 | |
| 16 | // These legacy create paths retain their contracts; the database lifecycle |
| 17 | // guards also serialize them with new archive/date changes. |
| 18 | const schoolRoute = (pool, handler, write = true) => async (req, res, next) => { |
| 19 | const client = await pool.connect(); |
| 20 | try { |
| 21 | await client.query('begin'); |
| 22 | const account = await client.query(`select 1 from app_user where id=$1 and disabled_at is null for ${write ? 'update' : 'share'}`, [req.identity.sub]); |
| 23 | if (!account.rowCount) { await client.query('rollback'); return res.status(401).json({ error: 'session_invalid' }); } |
| 24 | await assertSchoolSession(client, req.identity); |
| 25 | const result = await handler(req, client); |
| 26 | await assertSchoolSession(client, req.identity); |
| 27 | await client.query('commit'); |
| 28 | res.status(result.status).json(result.body); |
| 29 | } catch (raw) { |
| 30 | await client.query('rollback').catch(() => {}); |
| 31 | const error = schoolLifecycleError(raw); |
| 32 | if (error.status && (error.code?.startsWith('school_') || error.code === 'session_invalid')) return res.status(error.status).json({ error: error.code }); |
| 33 | next(error); |
| 34 | } finally { client.release(); } |
| 35 | }; |
| 36 | |
| 37 | function asDate(value) { |
| 38 | if (value == null || value === '') return null; |
| 39 | const d = new Date(value); |
| 40 | return Number.isNaN(d.getTime()) ? null : d; |
| 41 | } |
| 42 | |
| 43 | async function familyMember(pool, familyId, userId) { |
| 44 | const r = await pool.query( |
| 45 | 'select m.role,m.is_admin from family_membership m join family_workspace f on f.id=m.family_id where m.family_id=$1 and m.user_id=$2 and m.ended_at is null and f.archived_at is null', |
| 46 | [familyId, userId], |
| 47 | ); |
| 48 | return r.rows[0] ?? null; |
| 49 | } |
| 50 | |
| 51 | async function assertPlanWrite(pool, itemId, userId) { |
| 52 | if (!validUuid(itemId)) return { error: 'invalid_id', status: 400 }; |
| 53 | const r = await pool.query('select * from plan_item where id=$1', [itemId]); |
| 54 | if (!r.rowCount) return { error: 'not_found', status: 404 }; |
| 55 | if (r.rows[0].owner_user_id !== userId) { |
| 56 | return { error: 'forbidden', status: 403 }; |
| 57 | } |
| 58 | if (r.rows[0].family_id && !(await familyMember(pool, r.rows[0].family_id, userId))) return { error: 'family_membership_required', status: 403 }; |
| 59 | return { item: r.rows[0] }; |
| 60 | } |
| 61 | |
| 62 | async function assertStudentAcademic(pool, studentUserId, viewerUserId) { |
| 63 | if (!validUuid(studentUserId)) return false; |
| 64 | const r = await pool.query( |
| 65 | 'select can_view_student_academic($1,$2) as allowed', |
| 66 | [viewerUserId, studentUserId], |
| 67 | ); |
| 68 | return r.rows[0]?.allowed === true; |
| 69 | } |
| 70 | |
| 71 | async function audit(pool, actorUserId, familyId, action, targetType, targetId, metadata = {}) { |
| 72 | await pool.query( |
| 73 | `insert into access_audit(actor_user_id,family_id,action,target_type,target_id,metadata) |
| 74 | values($1,$2,$3,$4,$5,$6::jsonb)`, |
| 75 | [actorUserId, familyId, action, targetType, String(targetId ?? ''), JSON.stringify(metadata)], |
| 76 | ); |
| 77 | } |
| 78 | |
| 79 | export function createPhase3Router({ pool, auth }) { |
| 80 | const router = express.Router(); |
| 81 | |
| 82 | router.get('/today', auth, async (req, res) => { |
| 83 | const from = asDate(req.query.from) ?? new Date(); |
| 84 | const to = asDate(req.query.to) ?? new Date(from.getTime() + 24 * 60 * 60 * 1000); |
| 85 | const r = await pool.query( |
| 86 | `select p.* |
| 87 | from plan_item p |
| 88 | where can_view_plan_item($1,p.id) |
| 89 | and p.status not in ('completed','cancelled') |
| 90 | and coalesce(p.starts_at,p.due_at,p.created_at) >= $2 |
| 91 | and coalesce(p.starts_at,p.due_at,p.created_at) < $3 |
| 92 | order by coalesce(p.starts_at,p.due_at,p.created_at), p.priority desc`, |
| 93 | [req.identity.sub, from, to], |
| 94 | ); |
| 95 | res.json({ items: r.rows.map((item) => serializePlanItem(item, req.identity.sub)), asOf: new Date() }); |
| 96 | }); |
| 97 | |
| 98 | router.get('/plan-items', auth, async (req, res) => { |
| 99 | const from = asDate(req.query.from); |
| 100 | const to = asDate(req.query.to); |
| 101 | const values = [req.identity.sub]; |
| 102 | const filters = ["can_view_plan_item($1,p.id)", "p.status<>'cancelled'"]; |
| 103 | if (from) { |
| 104 | values.push(from); |
| 105 | filters.push(`coalesce(p.starts_at,p.due_at,p.created_at) >= $${values.length}`); |
| 106 | } |
| 107 | if (to) { |
| 108 | values.push(to); |
| 109 | filters.push(`coalesce(p.starts_at,p.due_at,p.created_at) < $${values.length}`); |
| 110 | } |
| 111 | if (req.query.kind && allowedKinds.has(String(req.query.kind))) { |
| 112 | values.push(String(req.query.kind)); |
| 113 | filters.push(`p.kind = $${values.length}`); |
| 114 | } |
| 115 | const r = await pool.query( |
| 116 | `select p.* |
| 117 | from plan_item p |
| 118 | where ${filters.join(' and ')} |
| 119 | order by coalesce(p.starts_at,p.due_at,p.created_at), p.created_at`, |
| 120 | values, |
| 121 | ); |
| 122 | res.json({ items: r.rows.map((item) => serializePlanItem(item, req.identity.sub)), asOf: new Date() }); |
| 123 | }); |
| 124 | |
| 125 | router.get('/plan-items/:itemId', auth, async (req, res) => { |
| 126 | if (!validUuid(req.params.itemId)) return res.status(400).json({ error: 'invalid_id' }); |
| 127 | const result = await pool.query('select * from plan_item where id=$1 and can_view_plan_item($2,id)', [req.params.itemId, req.identity.sub]); |
| 128 | if (!result.rowCount) return res.status(404).json({ error: 'not_found' }); |
| 129 | res.json(serializePlanItem(result.rows[0], req.identity.sub)); |
| 130 | }); |
| 131 | |
| 132 | router.post('/plan-items', auth, async (req, res) => { |
| 133 | const item = await planTransaction(pool, req.identity.sub, (client) => createPlanItem(client, req.identity.sub, req.body, req.body.id ?? crypto.randomUUID())); |
| 134 | res.status(201).json(serializePlanItem(item, req.identity.sub)); |
| 135 | }); |
| 136 | |
| 137 | router.patch('/plan-items/:itemId', auth, async (req, res) => { |
| 138 | const item = await planTransaction(pool, req.identity.sub, (client) => updatePlanItem(client, req.identity.sub, req.params.itemId, req.body, req.body.expectedVersion)); |
| 139 | res.json(serializePlanItem(item, req.identity.sub)); |
| 140 | }); |
| 141 | |
| 142 | router.delete('/plan-items/:itemId', auth, async (req, res) => { |
| 143 | const item = await planTransaction(pool, req.identity.sub, (client) => updatePlanItem(client, req.identity.sub, req.params.itemId, { status: 'cancelled' }, req.body.expectedVersion)); |
| 144 | res.json(serializePlanItem(item, req.identity.sub)); |
| 145 | }); |
| 146 | |
| 147 | router.post('/plan-items/:itemId/reminders', auth, async (req, res) => { |
| 148 | const access = await assertPlanWrite(pool, req.params.itemId, req.identity.sub); |
| 149 | if (access.error) return res.status(access.status).json({ error: access.error }); |
| 150 | const minutes = Number(req.body.minutesBefore); |
| 151 | if (!Number.isInteger(minutes) || minutes < 0 || minutes > 10080) { |
| 152 | return res.status(400).json({ error: 'invalid_reminder' }); |
| 153 | } |
| 154 | const baseTime = access.item.starts_at ?? access.item.due_at; |
| 155 | if (!baseTime) return res.status(400).json({ error: 'plan_item_has_no_time' }); |
| 156 | const r = await pool.query( |
| 157 | `insert into reminder(plan_item_id,owner_user_id,minutes_before,scheduled_for) |
| 158 | values($1,$2,$3,$4::timestamptz - make_interval(mins => $3)) |
| 159 | on conflict(plan_item_id,owner_user_id,minutes_before) |
| 160 | do update set scheduled_for=excluded.scheduled_for,status='scheduled',claimed_at=null |
| 161 | returning *`, |
| 162 | [req.params.itemId, req.identity.sub, minutes, baseTime], |
| 163 | ); |
| 164 | res.status(201).json(r.rows[0]); |
| 165 | }); |
| 166 | |
| 167 | router.post('/reminders/claim-due', auth, async (req, res) => { |
| 168 | const limit = Math.min(Math.max(Number(req.body.limit ?? 20), 1), 100); |
| 169 | const client = await pool.connect(); |
| 170 | try { |
| 171 | await client.query('begin'); |
| 172 | const r = await client.query( |
| 173 | `select r.id,r.plan_item_id,r.owner_user_id,p.title,r.scheduled_for |
| 174 | from reminder r |
| 175 | join plan_item p on p.id=r.plan_item_id |
| 176 | where r.owner_user_id=$1 |
| 177 | and r.status='scheduled' |
| 178 | and r.scheduled_for <= now() |
| 179 | and p.status not in ('completed','cancelled') |
| 180 | order by r.scheduled_for |
| 181 | for update skip locked |
| 182 | limit $2`, |
| 183 | [req.identity.sub, limit], |
| 184 | ); |
| 185 | for (const row of r.rows) { |
| 186 | await client.query( |
| 187 | `update reminder set status='claimed',claimed_at=now() where id=$1`, |
| 188 | [row.id], |
| 189 | ); |
| 190 | await client.query( |
| 191 | `insert into notification_outbox(reminder_id,user_id,payload) |
| 192 | values($1,$2,$3::jsonb) |
| 193 | on conflict(reminder_id) do nothing`, |
| 194 | [row.id, row.owner_user_id, JSON.stringify({ |
| 195 | type: 'plan_reminder', |
| 196 | planItemId: row.plan_item_id, |
| 197 | title: row.title, |
| 198 | scheduledFor: row.scheduled_for, |
| 199 | })], |
| 200 | ); |
| 201 | } |
| 202 | await client.query('commit'); |
| 203 | res.json({ claimed: r.rows.length, reminders: r.rows }); |
| 204 | } catch (e) { |
| 205 | await client.query('rollback').catch(() => {}); |
| 206 | throw e; |
| 207 | } finally { |
| 208 | client.release(); |
| 209 | } |
| 210 | }); |
| 211 | |
| 212 | router.get('/notification-outbox', auth, async (req, res) => { |
| 213 | const r = await pool.query( |
| 214 | `select id,reminder_id,payload,available_at,delivered_at,attempts |
| 215 | from notification_outbox |
| 216 | where user_id=$1 |
| 217 | order by available_at desc |
| 218 | limit 100`, |
| 219 | [req.identity.sub], |
| 220 | ); |
| 221 | res.json({ notifications: r.rows }); |
| 222 | }); |
| 223 | |
| 224 | router.get('/life-contexts', auth, schoolRoute(pool, async (req, client) => { |
| 225 | const r = await client.query( |
| 226 | 'select * from life_context where user_id=$1 and active order by created_at', |
| 227 | [req.identity.sub], |
| 228 | ); |
| 229 | return { status: 200, body: { contexts: r.rows } }; |
| 230 | }, false)); |
| 231 | |
| 232 | router.post('/life-contexts', auth, schoolRoute(pool, async (req, client) => { |
| 233 | const kind = String(req.body.kind ?? ''); |
| 234 | const title = String(req.body.title ?? '').trim(); |
| 235 | if (!['student','work','personal'].includes(kind) || !schoolText(req.body.title)) { |
| 236 | return { status: 400, body: { error: 'invalid_life_context' } }; |
| 237 | } |
| 238 | const r = await client.query( |
| 239 | 'insert into life_context(user_id,kind,title) values($1,$2,$3) returning *', |
| 240 | [req.identity.sub, kind, title], |
| 241 | ); |
| 242 | return { status: 201, body: r.rows[0] }; |
| 243 | })); |
| 244 | |
| 245 | router.post('/school/years', auth, schoolRoute(pool, async (req, client) => { |
| 246 | const body = req.body ?? {}; |
| 247 | const title = String(body.title ?? '').trim(); |
| 248 | const startsOn = body.startsOn; |
| 249 | const endsOn = body.endsOn; |
| 250 | const lifeContextId = body.lifeContextId; |
| 251 | if (!validUuid(lifeContextId) || !schoolText(body.title) || !schoolDate(startsOn) || !schoolDate(endsOn) || endsOn < startsOn) { |
| 252 | return { status: 400, body: { error: 'invalid_academic_year' } }; |
| 253 | } |
| 254 | const ctx = await client.query( |
| 255 | `select 1 from life_context |
| 256 | where id=$1 and user_id=$2 and kind='student' and active`, |
| 257 | [lifeContextId, req.identity.sub], |
| 258 | ); |
| 259 | if (!ctx.rowCount || !title || !startsOn || !endsOn) { |
| 260 | return { status: 400, body: { error: 'invalid_academic_year' } }; |
| 261 | } |
| 262 | const r = await client.query( |
| 263 | `insert into academic_year(student_user_id,life_context_id,title,starts_on,ends_on) |
| 264 | values($1,$2,$3,$4,$5) returning *`, |
| 265 | [req.identity.sub, lifeContextId, title, startsOn, endsOn], |
| 266 | ); |
| 267 | return { status: 201, body: r.rows[0] }; |
| 268 | })); |
| 269 | |
| 270 | router.post('/school/years/:yearId/terms', auth, schoolRoute(pool, async (req, client) => { |
| 271 | const body = req.body ?? {}; |
| 272 | if (!validUuid(req.params.yearId) || !schoolText(body.title) || !schoolDate(body.startsOn) || !schoolDate(body.endsOn) || body.endsOn < body.startsOn) { |
| 273 | return { status: 400, body: { error: 'invalid_academic_term' } }; |
| 274 | } |
| 275 | const y = await client.query( |
| 276 | 'select student_user_id,active,starts_on::text,ends_on::text from academic_year where id=$1', |
| 277 | [req.params.yearId], |
| 278 | ); |
| 279 | if (!y.rowCount) return { status: 404, body: { error: 'not_found' } }; |
| 280 | if (y.rows[0].student_user_id !== req.identity.sub) { |
| 281 | return { status: 403, body: { error: 'forbidden' } }; |
| 282 | } |
| 283 | if (!y.rows[0].active || body.startsOn < y.rows[0].starts_on || body.endsOn > y.rows[0].ends_on) { |
| 284 | return { status: 400, body: { error: 'invalid_academic_term' } }; |
| 285 | } |
| 286 | const r = await client.query( |
| 287 | `insert into academic_term(academic_year_id,title,starts_on,ends_on) |
| 288 | values($1,$2,$3,$4) returning *`, |
| 289 | [req.params.yearId, String(body.title ?? '').trim(), body.startsOn, body.endsOn], |
| 290 | ); |
| 291 | return { status: 201, body: r.rows[0] }; |
| 292 | })); |
| 293 | |
| 294 | router.post('/school/terms/:termId/subjects', auth, schoolRoute(pool, async (req, client) => { |
| 295 | const body = req.body ?? {}; |
| 296 | if (!validUuid(req.params.termId) || !schoolText(body.name) || |
| 297 | !schoolOptionalText(body.teacherName) || |
| 298 | !schoolOptionalText(body.colorKey, 40)) return { status: 400, body: { error: 'invalid_subject' } }; |
| 299 | const t = await client.query( |
| 300 | `select y.student_user_id |
| 301 | from academic_term t |
| 302 | join academic_year y on y.id=t.academic_year_id |
| 303 | join life_context l on l.id=y.life_context_id |
| 304 | where t.id=$1 and t.active and y.active and l.active`, |
| 305 | [req.params.termId], |
| 306 | ); |
| 307 | if (!t.rowCount) return { status: 404, body: { error: 'not_found' } }; |
| 308 | if (t.rows[0].student_user_id !== req.identity.sub) { |
| 309 | return { status: 403, body: { error: 'forbidden' } }; |
| 310 | } |
| 311 | const name = String(body.name ?? '').trim(); |
| 312 | if (!name) return { status: 400, body: { error: 'invalid_subject' } }; |
| 313 | const r = await client.query( |
| 314 | `insert into subject(student_user_id,academic_term_id,name,teacher_name,color_key) |
| 315 | values($1,$2,$3,$4,$5) returning *`, |
| 316 | [req.identity.sub, req.params.termId, name, body.teacherName?.trim() || null, body.colorKey?.trim() || null], |
| 317 | ); |
| 318 | return { status: 201, body: r.rows[0] }; |
| 319 | })); |
| 320 | |
| 321 | router.get('/school/:studentUserId/overview', auth, schoolRoute(pool, async (req, client) => { |
| 322 | const studentUserId = req.params.studentUserId; |
| 323 | if (!(await assertStudentAcademic(client, studentUserId, req.identity.sub))) { |
| 324 | return { status: 403, body: { error: 'forbidden' } }; |
| 325 | } |
| 326 | const [years, subjects, workload, grades] = await Promise.all([ |
| 327 | client.query( |
| 328 | `select y.* from academic_year y join life_context l on l.id=y.life_context_id where y.student_user_id=$1 and l.user_id=$1 and y.active and l.active |
| 329 | and ($1=$2 or exists(select 1 from academic_term t join subject s on s.academic_term_id=t.id |
| 330 | join plan_item p on p.subject_id=s.id where t.academic_year_id=y.id and can_view_plan_item($2,p.id))) |
| 331 | order by y.starts_on desc`, |
| 332 | [studentUserId, req.identity.sub], |
| 333 | ), |
| 334 | client.query( |
| 335 | `select s.*,t.title as term_title,y.title as year_title |
| 336 | from subject s join academic_term t on t.id=s.academic_term_id |
| 337 | join academic_year y on y.id=t.academic_year_id |
| 338 | join life_context l on l.id=y.life_context_id |
| 339 | where t.active and y.active and l.active and l.user_id=$1 and s.student_user_id=$1 and s.archived_at is null and ($1=$2 or exists(select 1 from plan_item p |
| 340 | where p.subject_id=s.id and can_view_plan_item($2,p.id))) order by s.name`, |
| 341 | [studentUserId, req.identity.sub], |
| 342 | ), |
| 343 | client.query( |
| 344 | `select * |
| 345 | from plan_item |
| 346 | where owner_user_id=$1 and can_view_plan_item($2,id) |
| 347 | and kind in ('assignment','exam','study_session') |
| 348 | and status not in ('completed','cancelled') |
| 349 | order by coalesce(due_at,starts_at) nulls last`, |
| 350 | [studentUserId, req.identity.sub], |
| 351 | ), |
| 352 | client.query( |
| 353 | `select id,title,subject_id,grade_points,grade_out_of,due_at |
| 354 | from plan_item |
| 355 | where owner_user_id=$1 and can_view_plan_item($2,id) |
| 356 | and grade_points is not null |
| 357 | and grade_out_of is not null |
| 358 | order by due_at desc nulls last`, |
| 359 | [studentUserId, req.identity.sub], |
| 360 | ), |
| 361 | ]); |
| 362 | if (!(await assertStudentAcademic(client, studentUserId, req.identity.sub))) return { status: 403, body: { error: 'forbidden' } }; |
| 363 | return { status: 200, body: { |
| 364 | years: years.rows, |
| 365 | subjects: subjects.rows, |
| 366 | workload: workload.rows.map((item) => serializePlanItem(item, req.identity.sub)), |
| 367 | grades: grades.rows, |
| 368 | } }; |
| 369 | }, false)); |
| 370 | |
| 371 | router.get('/school/:studentUserId/timetable', auth, schoolRoute(pool, async (req, client) => { |
| 372 | if (!(await assertStudentAcademic(client, req.params.studentUserId, req.identity.sub))) { |
| 373 | return { status: 403, body: { error: 'forbidden' } }; |
| 374 | } |
| 375 | const r = await client.query( |
| 376 | `select c.*,s.name as subject_name,s.color_key |
| 377 | from class_session c |
| 378 | join subject s on s.id=c.subject_id |
| 379 | join academic_term t on t.id=s.academic_term_id |
| 380 | join academic_year y on y.id=t.academic_year_id |
| 381 | join life_context l on l.id=y.life_context_id |
| 382 | where t.active and y.active and l.active and l.user_id=$1 and 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 |
| 383 | where p.subject_id=s.id and can_view_plan_item($2,p.id))) |
| 384 | order by c.weekday,c.starts_at`, |
| 385 | [req.params.studentUserId, req.identity.sub], |
| 386 | ); |
| 387 | if (!(await assertStudentAcademic(client, req.params.studentUserId, req.identity.sub))) return { status: 403, body: { error: 'forbidden' } }; |
| 388 | return { status: 200, body: { classes: r.rows } }; |
| 389 | }, false)); |
| 390 | |
| 391 | router.patch('/school/plan-items/:itemId/grade', auth, async (req, res) => { |
| 392 | const access = await assertPlanWrite(pool, req.params.itemId, req.identity.sub); |
| 393 | if (access.error) return res.status(access.status).json({ error: access.error }); |
| 394 | if (!['assignment','exam'].includes(access.item.kind)) { |
| 395 | return res.status(400).json({ error: 'grade_not_applicable' }); |
| 396 | } |
| 397 | const points = Number(req.body.points); |
| 398 | const outOf = Number(req.body.outOf); |
| 399 | if (!Number.isFinite(points) || !Number.isFinite(outOf) || outOf <= 0 || points < 0 || points > outOf) { |
| 400 | return res.status(400).json({ error: 'invalid_grade' }); |
| 401 | } |
| 402 | const item = await planTransaction(pool, req.identity.sub, (client) => updatePlanItem(client, |
| 403 | req.identity.sub, req.params.itemId, { gradePoints: points, gradeOutOf: outOf }, req.body.expectedVersion)); |
| 404 | res.json(serializePlanItem(item, req.identity.sub)); |
| 405 | }); |
| 406 | |
| 407 | router.get('/families/:familyId/calendar', auth, async (req, res) => { |
| 408 | const member = await familyMember(pool, req.params.familyId, req.identity.sub); |
| 409 | if (!member) return res.status(403).json({ error: 'forbidden' }); |
| 410 | const r = await pool.query( |
| 411 | `select p.*,pr.display_name as owner_name |
| 412 | from plan_item p |
| 413 | join profile pr on pr.user_id=p.owner_user_id |
| 414 | where p.family_id=$1 |
| 415 | and can_view_plan_item($2,p.id) |
| 416 | and p.status <> 'cancelled' |
| 417 | order by coalesce(p.starts_at,p.due_at,p.created_at)`, |
| 418 | [req.params.familyId, req.identity.sub], |
| 419 | ); |
| 420 | res.json({ items: r.rows.map((item) => serializePlanItem(item, req.identity.sub)), asOf: new Date() }); |
| 421 | }); |
| 422 | |
| 423 | router.get('/families/:familyId/children/:studentUserId/support-summary', auth, async (req, res) => { |
| 424 | const familyId = req.params.familyId; |
| 425 | const studentUserId = req.params.studentUserId; |
| 426 | const g = await pool.query( |
| 427 | `select 1 where is_active_guardian($1,$2,$3)`, |
| 428 | [familyId, req.identity.sub, studentUserId], |
| 429 | ); |
| 430 | if (!g.rowCount) return res.status(403).json({ error: 'guardian_required' }); |
| 431 | |
| 432 | const [upcoming, completed, overdue, study, grades] = await Promise.all([ |
| 433 | pool.query( |
| 434 | `select id,kind,title,due_at,starts_at,priority,status |
| 435 | from plan_item |
| 436 | where owner_user_id=$1 and family_id=$3 and can_view_plan_item($2,id) |
| 437 | and kind in ('assignment','exam','study_session') |
| 438 | and status not in ('completed','cancelled') |
| 439 | and coalesce(due_at,starts_at) >= now() |
| 440 | and coalesce(due_at,starts_at) < now()+interval '14 days' |
| 441 | order by coalesce(due_at,starts_at) limit 20`, |
| 442 | [studentUserId, req.identity.sub, familyId], |
| 443 | ), |
| 444 | pool.query( |
| 445 | `select count(*)::int as n from plan_item |
| 446 | where owner_user_id=$1 and family_id=$3 and can_view_plan_item($2,id) and kind in ('assignment','study_session') and status='completed' |
| 447 | and completed_at >= now()-interval '7 days'`, |
| 448 | [studentUserId, req.identity.sub, familyId], |
| 449 | ), |
| 450 | pool.query( |
| 451 | `select count(*)::int as n from plan_item |
| 452 | where owner_user_id=$1 and family_id=$3 and can_view_plan_item($2,id) and kind in ('assignment','study_session') |
| 453 | and status not in ('completed','cancelled') and due_at < now()`, |
| 454 | [studentUserId, req.identity.sub, familyId], |
| 455 | ), |
| 456 | pool.query( |
| 457 | `select floor(coalesce(sum(greatest(0,extract(epoch from |
| 458 | least(coalesce(i.ends_at,now()),now())-greatest(i.starts_at,now()-interval '7 days')))),0))::int as seconds |
| 459 | from study_session s join study_interval i on i.session_id=s.id join plan_item p on p.id=s.plan_item_id |
| 460 | where s.child_user_id=$1 and s.archived_at is null and p.family_id=$3 and can_view_plan_item($2,p.id) |
| 461 | and i.starts_at<now() and coalesce(i.ends_at,now())>now()-interval '7 days'`, |
| 462 | [studentUserId, req.identity.sub, familyId], |
| 463 | ), |
| 464 | pool.query( |
| 465 | `select |
| 466 | case when sum(grade_out_of)>0 then round(sum(grade_points)/sum(grade_out_of)*100,1) end as percent |
| 467 | from plan_item |
| 468 | where owner_user_id=$1 and family_id=$3 and can_view_plan_item($2,id) and grade_points is not null and grade_out_of is not null`, |
| 469 | [studentUserId, req.identity.sub, familyId], |
| 470 | ), |
| 471 | ]); |
| 472 | await audit(pool, req.identity.sub, familyId, 'parent.support_summary.view', 'student', studentUserId); |
| 473 | res.json({ |
| 474 | upcoming: upcoming.rows, |
| 475 | metrics: { |
| 476 | completedLast7Days: completed.rows[0].n, |
| 477 | overdue: overdue.rows[0].n, |
| 478 | studyMinutesLast7Days: Math.floor(study.rows[0].seconds / 60), |
| 479 | recordedStudySecondsLast7Days: study.rows[0].seconds, |
| 480 | recordedTimeIsProofOfStudy: false, |
| 481 | gradePercent: grades.rows[0].percent == null ? null : Number(grades.rows[0].percent), |
| 482 | }, |
| 483 | }); |
| 484 | }); |
| 485 | |
| 486 | router.post('/sync/mutations', auth, async (req, res) => { |
| 487 | const mutations = req.body?.mutations; |
| 488 | if (!Array.isArray(mutations) || mutations.length > 100) return res.status(400).json({ error: 'invalid_mutations' }); |
| 489 | const results = []; |
| 490 | for (const mutation of mutations) results.push(await applyPlanMutation(pool, req.identity.sub, mutation)); |
| 491 | res.json({ results, asOf: new Date() }); |
| 492 | }); |
| 493 | |
| 494 | router.use((error, _req, res, next) => { |
| 495 | if (error instanceof PlanMutationError) return res.status(error.status).json({ error: error.code, ...error.details }); |
| 496 | next(error); |
| 497 | }); |
| 498 | |
| 499 | return router; |
| 500 | } |