LifeMate — Personal, Family & Learning Companion

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