1
+import express from 'express';
2
+
3
+const allowedKinds = new Set(['task','event','routine','goal','assignment','exam','study_session']);
4
+const allowedStatus = new Set(['planned','in_progress','completed','cancelled']);
5
+const allowedPriority = new Set(['low','normal','high','urgent']);
6
+const allowedVisibility = new Set(['private','selected_members','parent_guardian','family']);
7
+
8
+function asDate(value) {
9
+ if (value == null || value === '') return null;
10
+ const d = new Date(value);
11
+ return Number.isNaN(d.getTime()) ? null : d;
12
+}
13
+
14
+async function familyMember(pool, familyId, userId) {
15
+ const r = await pool.query(
16
+ 'select role,is_admin from family_membership where family_id=$1 and user_id=$2 and ended_at is null',
17
+ [familyId, userId],
18
+ );
19
+ return r.rows[0] ?? null;
20
+}
21
+
22
+async function assertPlanWrite(pool, itemId, userId) {
23
+ const r = await pool.query('select * from plan_item where id=$1', [itemId]);
24
+ if (!r.rowCount) return { error: 'not_found', status: 404 };
25
+ if (r.rows[0].owner_user_id !== userId) {
26
+ return { error: 'forbidden', status: 403 };
27
+ }
28
+ return { item: r.rows[0] };
29
+}
30
+
31
+async function assertStudentAcademic(pool, studentUserId, viewerUserId) {
32
+ const r = await pool.query(
33
+ 'select can_view_student_academic($1,$2) as allowed',
34
+ [viewerUserId, studentUserId],
35
+ );
36
+ return r.rows[0]?.allowed === true;
37
+}
38
+
39
+async function audit(pool, actorUserId, familyId, action, targetType, targetId, metadata = {}) {
40
+ await pool.query(
41
+ `insert into access_audit(actor_user_id,family_id,action,target_type,target_id,metadata)
42
+ values($1,$2,$3,$4,$5,$6::jsonb)`,
43
+ [actorUserId, familyId, action, targetType, String(targetId ?? ''), JSON.stringify(metadata)],
44
+ );
45
+}
46
+
47
+export function createPhase3Router({ pool, auth }) {
48
+ const router = express.Router();
49
+
50
+ router.get('/today', auth, async (req, res) => {
51
+ const from = asDate(req.query.from) ?? new Date();
52
+ const to = asDate(req.query.to) ?? new Date(from.getTime() + 24 * 60 * 60 * 1000);
53
+ const r = await pool.query(
54
+ `select p.*
55
+ from plan_item p
56
+ where can_view_plan_item($1,p.id)
57
+ and p.status not in ('completed','cancelled')
58
+ and coalesce(p.starts_at,p.due_at,p.created_at) >= $2
59
+ and coalesce(p.starts_at,p.due_at,p.created_at) < $3
60
+ order by coalesce(p.starts_at,p.due_at,p.created_at), p.priority desc`,
61
+ [req.identity.sub, from, to],
62
+ );
63
+ res.json({ items: r.rows });
64
+ });
65
+
66
+ router.get('/plan-items', auth, async (req, res) => {
67
+ const from = asDate(req.query.from);
68
+ const to = asDate(req.query.to);
69
+ const values = [req.identity.sub];
70
+ const filters = ['can_view_plan_item($1,p.id)'];
71
+ if (from) {
72
+ values.push(from);
73
+ filters.push(`coalesce(p.starts_at,p.due_at,p.created_at) >= $${values.length}`);
74
+ }
75
+ if (to) {
76
+ values.push(to);
77
+ filters.push(`coalesce(p.starts_at,p.due_at,p.created_at) < $${values.length}`);
78
+ }
79
+ if (req.query.kind && allowedKinds.has(String(req.query.kind))) {
80
+ values.push(String(req.query.kind));
81
+ filters.push(`p.kind = $${values.length}`);
82
+ }
83
+ const r = await pool.query(
84
+ `select p.*
85
+ from plan_item p
86
+ where ${filters.join(' and ')}
87
+ order by coalesce(p.starts_at,p.due_at,p.created_at), p.created_at`,
88
+ values,
89
+ );
90
+ res.json({ items: r.rows });
91
+ });
92
+
93
+ router.post('/plan-items', auth, async (req, res) => {
94
+ const kind = String(req.body.kind ?? 'task');
95
+ const title = String(req.body.title ?? '').trim();
96
+ const priority = String(req.body.priority ?? 'normal');
97
+ const visibility = String(req.body.visibility ?? 'private');
98
+ const familyId = req.body.familyId || null;
99
+ const startsAt = asDate(req.body.startsAt);
100
+ const dueAt = asDate(req.body.dueAt);
101
+ if (!allowedKinds.has(kind) || !title || !allowedPriority.has(priority) || !allowedVisibility.has(visibility)) {
102
+ return res.status(400).json({ error: 'invalid_plan_item' });
103
+ }
104
+ if (familyId) {
105
+ const member = await familyMember(pool, familyId, req.identity.sub);
106
+ if (!member) return res.status(403).json({ error: 'family_membership_required' });
107
+ }
108
+ if ((visibility === 'family' || visibility === 'parent_guardian') && !familyId) {
109
+ return res.status(400).json({ error: 'family_required_for_visibility' });
110
+ }
111
+ if (req.body.subjectId) {
112
+ const s = await pool.query('select student_user_id from subject where id=$1', [req.body.subjectId]);
113
+ if (!s.rowCount || s.rows[0].student_user_id !== req.identity.sub) {
114
+ return res.status(403).json({ error: 'subject_forbidden' });
115
+ }
116
+ }
117
+
118
+ const client = await pool.connect();
119
+ try {
120
+ await client.query('begin');
121
+ const r = await client.query(
122
+ `insert into plan_item(
123
+ owner_user_id,family_id,subject_id,kind,title,notes,status,priority,visibility,
124
+ starts_at,due_at,duration_minutes,recurrence_rule,parent_item_id
125
+ ) values($1,$2,$3,$4,$5,$6,'planned',$7,$8,$9,$10,$11,$12,$13)
126
+ returning *`,
127
+ [
128
+ req.identity.sub, familyId, req.body.subjectId || null, kind, title,
129
+ req.body.notes || null, priority, visibility, startsAt, dueAt,
130
+ req.body.durationMinutes || null, req.body.recurrenceRule || null,
131
+ req.body.parentItemId || null,
132
+ ],
133
+ );
134
+ const item = r.rows[0];
135
+
136
+ const selected = Array.isArray(req.body.selectedMemberIds)
137
+ ? [...new Set(req.body.selectedMemberIds.map(String))]
138
+ : [];
139
+ if (visibility === 'selected_members') {
140
+ if (!familyId || selected.length === 0) {
141
+ await client.query('rollback');
142
+ return res.status(400).json({ error: 'selected_members_required' });
143
+ }
144
+ for (const userId of selected) {
145
+ const m = await client.query(
146
+ 'select 1 from family_membership where family_id=$1 and user_id=$2 and ended_at is null',
147
+ [familyId, userId],
148
+ );
149
+ if (!m.rowCount) {
150
+ await client.query('rollback');
151
+ return res.status(400).json({ error: 'selected_member_not_in_family' });
152
+ }
153
+ await client.query(
154
+ `insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by)
155
+ values('plan_item',$1,$2,$3)
156
+ on conflict do nothing`,
157
+ [item.id, userId, req.identity.sub],
158
+ );
159
+ }
160
+ }
161
+
162
+ const leadTimes = Array.isArray(req.body.reminderMinutesBefore)
163
+ ? [...new Set(req.body.reminderMinutesBefore.map(Number))]
164
+ : [];
165
+ const baseTime = startsAt ?? dueAt;
166
+ if (baseTime) {
167
+ for (const minutes of leadTimes) {
168
+ if (!Number.isInteger(minutes) || minutes < 0 || minutes > 10080) continue;
169
+ await client.query(
170
+ `insert into reminder(plan_item_id,owner_user_id,minutes_before,scheduled_for)
171
+ values($1,$2,$3,$4::timestamptz - make_interval(mins => $3))
172
+ on conflict(plan_item_id,owner_user_id,minutes_before)
173
+ do update set scheduled_for=excluded.scheduled_for,status='scheduled',claimed_at=null`,
174
+ [item.id, req.identity.sub, minutes, baseTime],
175
+ );
176
+ }
177
+ }
178
+
179
+ await client.query('commit');
180
+ res.status(201).json(item);
181
+ } catch (e) {
182
+ await client.query('rollback').catch(() => {});
183
+ throw e;
184
+ } finally {
185
+ client.release();
186
+ }
187
+ });
188
+
189
+ router.patch('/plan-items/:itemId', auth, async (req, res) => {
190
+ const access = await assertPlanWrite(pool, req.params.itemId, req.identity.sub);
191
+ if (access.error) return res.status(access.status).json({ error: access.error });
192
+
193
+ const fields = [];
194
+ const values = [req.params.itemId];
195
+ const add = (column, value, cast = '') => {
196
+ values.push(value);
197
+ fields.push(`${column}=$${values.length}${cast}`);
198
+ };
199
+ if (req.body.title != null) {
200
+ const title = String(req.body.title).trim();
201
+ if (!title) return res.status(400).json({ error: 'invalid_title' });
202
+ add('title', title);
203
+ }
204
+ if (req.body.notes !== undefined) add('notes', req.body.notes || null);
205
+ if (req.body.status != null) {
206
+ const status = String(req.body.status);
207
+ if (!allowedStatus.has(status)) return res.status(400).json({ error: 'invalid_status' });
208
+ add('status', status);
209
+ if (status === 'completed') add('completed_at', new Date());
210
+ if (status !== 'completed') add('completed_at', null);
211
+ }
212
+ if (req.body.priority != null) {
213
+ const priority = String(req.body.priority);
214
+ if (!allowedPriority.has(priority)) return res.status(400).json({ error: 'invalid_priority' });
215
+ add('priority', priority);
216
+ }
217
+ if (req.body.startsAt !== undefined) add('starts_at', asDate(req.body.startsAt));
218
+ if (req.body.dueAt !== undefined) add('due_at', asDate(req.body.dueAt));
219
+ if (req.body.durationMinutes !== undefined) add('duration_minutes', req.body.durationMinutes || null);
220
+ if (!fields.length) return res.status(400).json({ error: 'no_changes' });
221
+ fields.push('updated_at=now()');
222
+
223
+ const client = await pool.connect();
224
+ try {
225
+ await client.query('begin');
226
+ const r = await client.query(
227
+ `update plan_item set ${fields.join(',')} where id=$1 returning *`,
228
+ values,
229
+ );
230
+ if (r.rows[0].status === 'completed' || r.rows[0].status === 'cancelled') {
231
+ await client.query(
232
+ `update reminder set status='cancelled'
233
+ where plan_item_id=$1 and status in ('scheduled','claimed')`,
234
+ [req.params.itemId],
235
+ );
236
+ } else {
237
+ await client.query('select recompute_reminder_schedule($1)', [req.params.itemId]);
238
+ }
239
+ await client.query('commit');
240
+ res.json(r.rows[0]);
241
+ } catch (e) {
242
+ await client.query('rollback').catch(() => {});
243
+ throw e;
244
+ } finally {
245
+ client.release();
246
+ }
247
+ });
248
+
249
+ router.post('/plan-items/:itemId/reminders', auth, async (req, res) => {
250
+ const access = await assertPlanWrite(pool, req.params.itemId, req.identity.sub);
251
+ if (access.error) return res.status(access.status).json({ error: access.error });
252
+ const minutes = Number(req.body.minutesBefore);
253
+ if (!Number.isInteger(minutes) || minutes < 0 || minutes > 10080) {
254
+ return res.status(400).json({ error: 'invalid_reminder' });
255
+ }
256
+ const baseTime = access.item.starts_at ?? access.item.due_at;
257
+ if (!baseTime) return res.status(400).json({ error: 'plan_item_has_no_time' });
258
+ const r = await pool.query(
259
+ `insert into reminder(plan_item_id,owner_user_id,minutes_before,scheduled_for)
260
+ values($1,$2,$3,$4::timestamptz - make_interval(mins => $3))
261
+ on conflict(plan_item_id,owner_user_id,minutes_before)
262
+ do update set scheduled_for=excluded.scheduled_for,status='scheduled',claimed_at=null
263
+ returning *`,
264
+ [req.params.itemId, req.identity.sub, minutes, baseTime],
265
+ );
266
+ res.status(201).json(r.rows[0]);
267
+ });
268
+
269
+ router.post('/reminders/claim-due', auth, async (req, res) => {
270
+ const limit = Math.min(Math.max(Number(req.body.limit ?? 20), 1), 100);
271
+ const client = await pool.connect();
272
+ try {
273
+ await client.query('begin');
274
+ const r = await client.query(
275
+ `select r.id,r.plan_item_id,r.owner_user_id,p.title,r.scheduled_for
276
+ from reminder r
277
+ join plan_item p on p.id=r.plan_item_id
278
+ where r.owner_user_id=$1
279
+ and r.status='scheduled'
280
+ and r.scheduled_for <= now()
281
+ and p.status not in ('completed','cancelled')
282
+ order by r.scheduled_for
283
+ for update skip locked
284
+ limit $2`,
285
+ [req.identity.sub, limit],
286
+ );
287
+ for (const row of r.rows) {
288
+ await client.query(
289
+ `update reminder set status='claimed',claimed_at=now() where id=$1`,
290
+ [row.id],
291
+ );
292
+ await client.query(
293
+ `insert into notification_outbox(reminder_id,user_id,payload)
294
+ values($1,$2,$3::jsonb)
295
+ on conflict(reminder_id) do nothing`,
296
+ [row.id, row.owner_user_id, JSON.stringify({
297
+ type: 'plan_reminder',
298
+ planItemId: row.plan_item_id,
299
+ title: row.title,
300
+ scheduledFor: row.scheduled_for,
301
+ })],
302
+ );
303
+ }
304
+ await client.query('commit');
305
+ res.json({ claimed: r.rows.length, reminders: r.rows });
306
+ } catch (e) {
307
+ await client.query('rollback').catch(() => {});
308
+ throw e;
309
+ } finally {
310
+ client.release();
311
+ }
312
+ });
313
+
314
+ router.get('/notification-outbox', auth, async (req, res) => {
315
+ const r = await pool.query(
316
+ `select id,reminder_id,payload,available_at,delivered_at,attempts
317
+ from notification_outbox
318
+ where user_id=$1
319
+ order by available_at desc
320
+ limit 100`,
321
+ [req.identity.sub],
322
+ );
323
+ res.json({ notifications: r.rows });
324
+ });
325
+
326
+ router.get('/life-contexts', auth, async (req, res) => {
327
+ const r = await pool.query(
328
+ 'select * from life_context where user_id=$1 and active order by created_at',
329
+ [req.identity.sub],
330
+ );
331
+ res.json({ contexts: r.rows });
332
+ });
333
+
334
+ router.post('/life-contexts', auth, async (req, res) => {
335
+ const kind = String(req.body.kind ?? '');
336
+ const title = String(req.body.title ?? '').trim();
337
+ if (!['student','work','personal'].includes(kind) || !title) {
338
+ return res.status(400).json({ error: 'invalid_life_context' });
339
+ }
340
+ const r = await pool.query(
341
+ 'insert into life_context(user_id,kind,title) values($1,$2,$3) returning *',
342
+ [req.identity.sub, kind, title],
343
+ );
344
+ res.status(201).json(r.rows[0]);
345
+ });
346
+
347
+ router.post('/school/years', auth, async (req, res) => {
348
+ const title = String(req.body.title ?? '').trim();
349
+ const startsOn = req.body.startsOn;
350
+ const endsOn = req.body.endsOn;
351
+ const lifeContextId = req.body.lifeContextId;
352
+ const ctx = await pool.query(
353
+ `select 1 from life_context
354
+ where id=$1 and user_id=$2 and kind='student' and active`,
355
+ [lifeContextId, req.identity.sub],
356
+ );
357
+ if (!ctx.rowCount || !title || !startsOn || !endsOn) {
358
+ return res.status(400).json({ error: 'invalid_academic_year' });
359
+ }
360
+ const r = await pool.query(
361
+ `insert into academic_year(student_user_id,life_context_id,title,starts_on,ends_on)
362
+ values($1,$2,$3,$4,$5) returning *`,
363
+ [req.identity.sub, lifeContextId, title, startsOn, endsOn],
364
+ );
365
+ res.status(201).json(r.rows[0]);
366
+ });
367
+
368
+ router.post('/school/years/:yearId/terms', auth, async (req, res) => {
369
+ const y = await pool.query(
370
+ 'select student_user_id from academic_year where id=$1',
371
+ [req.params.yearId],
372
+ );
373
+ if (!y.rowCount) return res.status(404).json({ error: 'not_found' });
374
+ if (y.rows[0].student_user_id !== req.identity.sub) {
375
+ return res.status(403).json({ error: 'forbidden' });
376
+ }
377
+ const r = await pool.query(
378
+ `insert into academic_term(academic_year_id,title,starts_on,ends_on)
379
+ values($1,$2,$3,$4) returning *`,
380
+ [req.params.yearId, String(req.body.title ?? '').trim(), req.body.startsOn, req.body.endsOn],
381
+ );
382
+ res.status(201).json(r.rows[0]);
383
+ });
384
+
385
+ router.post('/school/terms/:termId/subjects', auth, async (req, res) => {
386
+ const t = await pool.query(
387
+ `select y.student_user_id
388
+ from academic_term t
389
+ join academic_year y on y.id=t.academic_year_id
390
+ where t.id=$1`,
391
+ [req.params.termId],
392
+ );
393
+ if (!t.rowCount) return res.status(404).json({ error: 'not_found' });
394
+ if (t.rows[0].student_user_id !== req.identity.sub) {
395
+ return res.status(403).json({ error: 'forbidden' });
396
+ }
397
+ const name = String(req.body.name ?? '').trim();
398
+ if (!name) return res.status(400).json({ error: 'invalid_subject' });
399
+ const r = await pool.query(
400
+ `insert into subject(student_user_id,academic_term_id,name,teacher_name,color_key)
401
+ values($1,$2,$3,$4,$5) returning *`,
402
+ [req.identity.sub, req.params.termId, name, req.body.teacherName || null, req.body.colorKey || null],
403
+ );
404
+ res.status(201).json(r.rows[0]);
405
+ });
406
+
407
+ router.post('/school/subjects/:subjectId/classes', auth, async (req, res) => {
408
+ const s = await pool.query('select student_user_id from subject where id=$1', [req.params.subjectId]);
409
+ if (!s.rowCount) return res.status(404).json({ error: 'not_found' });
410
+ if (s.rows[0].student_user_id !== req.identity.sub) {
411
+ return res.status(403).json({ error: 'forbidden' });
412
+ }
413
+ const weekday = Number(req.body.weekday);
414
+ if (!Number.isInteger(weekday) || weekday < 1 || weekday > 7) {
415
+ return res.status(400).json({ error: 'invalid_weekday' });
416
+ }
417
+ const r = await pool.query(
418
+ `insert into class_session(subject_id,weekday,starts_at,ends_at,location,recurrence_until)
419
+ values($1,$2,$3,$4,$5,$6) returning *`,
420
+ [req.params.subjectId, weekday, req.body.startsAt, req.body.endsAt, req.body.location || null, req.body.recurrenceUntil || null],
421
+ );
422
+ res.status(201).json(r.rows[0]);
423
+ });
424
+
425
+ router.get('/school/:studentUserId/overview', auth, async (req, res) => {
426
+ const studentUserId = req.params.studentUserId;
427
+ if (!(await assertStudentAcademic(pool, studentUserId, req.identity.sub))) {
428
+ return res.status(403).json({ error: 'forbidden' });
429
+ }
430
+ const [years, subjects, workload, grades] = await Promise.all([
431
+ pool.query(
432
+ `select * from academic_year where student_user_id=$1 and active order by starts_on desc`,
433
+ [studentUserId],
434
+ ),
435
+ pool.query(
436
+ `select s.*,t.title as term_title,y.title as year_title
437
+ from subject s join academic_term t on t.id=s.academic_term_id
438
+ join academic_year y on y.id=t.academic_year_id
439
+ where s.student_user_id=$1 order by s.name`,
440
+ [studentUserId],
441
+ ),
442
+ pool.query(
443
+ `select *
444
+ from plan_item
445
+ where owner_user_id=$1
446
+ and kind in ('assignment','exam','study_session')
447
+ and status not in ('completed','cancelled')
448
+ order by coalesce(due_at,starts_at) nulls last`,
449
+ [studentUserId],
450
+ ),
451
+ pool.query(
452
+ `select id,title,subject_id,grade_points,grade_out_of,due_at
453
+ from plan_item
454
+ where owner_user_id=$1
455
+ and grade_points is not null
456
+ and grade_out_of is not null
457
+ order by due_at desc nulls last`,
458
+ [studentUserId],
459
+ ),
460
+ ]);
461
+ res.json({
462
+ years: years.rows,
463
+ subjects: subjects.rows,
464
+ workload: workload.rows,
465
+ grades: grades.rows,
466
+ });
467
+ });
468
+
469
+ router.get('/school/:studentUserId/timetable', auth, async (req, res) => {
470
+ if (!(await assertStudentAcademic(pool, req.params.studentUserId, req.identity.sub))) {
471
+ return res.status(403).json({ error: 'forbidden' });
472
+ }
473
+ const r = await pool.query(
474
+ `select c.*,s.name as subject_name,s.color_key
475
+ from class_session c
476
+ join subject s on s.id=c.subject_id
477
+ where s.student_user_id=$1
478
+ order by c.weekday,c.starts_at`,
479
+ [req.params.studentUserId],
480
+ );
481
+ res.json({ classes: r.rows });
482
+ });
483
+
484
+ router.patch('/school/plan-items/:itemId/grade', auth, async (req, res) => {
485
+ const access = await assertPlanWrite(pool, req.params.itemId, req.identity.sub);
486
+ if (access.error) return res.status(access.status).json({ error: access.error });
487
+ if (!['assignment','exam'].includes(access.item.kind)) {
488
+ return res.status(400).json({ error: 'grade_not_applicable' });
489
+ }
490
+ const points = Number(req.body.points);
491
+ const outOf = Number(req.body.outOf);
492
+ if (!Number.isFinite(points) || !Number.isFinite(outOf) || outOf <= 0 || points < 0 || points > outOf) {
493
+ return res.status(400).json({ error: 'invalid_grade' });
494
+ }
495
+ const r = await pool.query(
496
+ `update plan_item set grade_points=$2,grade_out_of=$3,updated_at=now()
497
+ where id=$1 returning *`,
498
+ [req.params.itemId, points, outOf],
499
+ );
500
+ res.json(r.rows[0]);
501
+ });
502
+
503
+ router.get('/families/:familyId/calendar', auth, async (req, res) => {
504
+ const member = await familyMember(pool, req.params.familyId, req.identity.sub);
505
+ if (!member) return res.status(403).json({ error: 'forbidden' });
506
+ const r = await pool.query(
507
+ `select p.*,pr.display_name as owner_name
508
+ from plan_item p
509
+ join profile pr on pr.user_id=p.owner_user_id
510
+ where p.family_id=$1
511
+ and can_view_plan_item($2,p.id)
512
+ and p.status <> 'cancelled'
513
+ order by coalesce(p.starts_at,p.due_at,p.created_at)`,
514
+ [req.params.familyId, req.identity.sub],
515
+ );
516
+ res.json({ items: r.rows });
517
+ });
518
+
519
+ router.get('/families/:familyId/children/:studentUserId/support-summary', auth, async (req, res) => {
520
+ const familyId = req.params.familyId;
521
+ const studentUserId = req.params.studentUserId;
522
+ const g = await pool.query(
523
+ `select 1 from guardian_relationship
524
+ where family_id=$1 and guardian_user_id=$2 and minor_user_id=$3 and active`,
525
+ [familyId, req.identity.sub, studentUserId],
526
+ );
527
+ if (!g.rowCount) return res.status(403).json({ error: 'guardian_required' });
528
+
529
+ const [upcoming, completed, overdue, study, grades] = await Promise.all([
530
+ pool.query(
531
+ `select id,kind,title,due_at,starts_at,priority,status
532
+ from plan_item
533
+ where owner_user_id=$1
534
+ and kind in ('assignment','exam','study_session')
535
+ and status not in ('completed','cancelled')
536
+ and coalesce(due_at,starts_at) >= now()
537
+ and coalesce(due_at,starts_at) < now()+interval '14 days'
538
+ order by coalesce(due_at,starts_at) limit 20`,
539
+ [studentUserId],
540
+ ),
541
+ pool.query(
542
+ `select count(*)::int as n from plan_item
543
+ where owner_user_id=$1 and kind in ('assignment','study_session') and status='completed'
544
+ and completed_at >= now()-interval '7 days'`,
545
+ [studentUserId],
546
+ ),
547
+ pool.query(
548
+ `select count(*)::int as n from plan_item
549
+ where owner_user_id=$1 and kind in ('assignment','study_session')
550
+ and status not in ('completed','cancelled') and due_at < now()`,
551
+ [studentUserId],
552
+ ),
553
+ pool.query(
554
+ `select coalesce(sum(duration_minutes),0)::int as minutes
555
+ from plan_item
556
+ where owner_user_id=$1 and kind='study_session' and status='completed'
557
+ and completed_at >= now()-interval '7 days'`,
558
+ [studentUserId],
559
+ ),
560
+ pool.query(
561
+ `select
562
+ case when sum(grade_out_of)>0 then round(sum(grade_points)/sum(grade_out_of)*100,1) end as percent
563
+ from plan_item
564
+ where owner_user_id=$1 and grade_points is not null and grade_out_of is not null`,
565
+ [studentUserId],
566
+ ),
567
+ ]);
568
+ await audit(pool, req.identity.sub, familyId, 'parent.support_summary.view', 'student', studentUserId);
569
+ res.json({
570
+ upcoming: upcoming.rows,
571
+ metrics: {
572
+ completedLast7Days: completed.rows[0].n,
573
+ overdue: overdue.rows[0].n,
574
+ studyMinutesLast7Days: study.rows[0].minutes,
575
+ gradePercent: grades.rows[0].percent == null ? null : Number(grades.rows[0].percent),
576
+ },
577
+ });
578
+ });
579
+
580
+ router.post('/sync/mutations', auth, async (req, res) => {
581
+ const mutations = Array.isArray(req.body.mutations) ? req.body.mutations : [];
582
+ if (mutations.length > 100) {
583
+ return res.status(400).json({ error: 'too_many_mutations' });
584
+ }
585
+
586
+ const client = await pool.connect();
587
+ const results = [];
588
+ try {
589
+ for (const mutation of mutations) {
590
+ const id = String(mutation.id ?? '');
591
+ const operation = String(mutation.operation ?? '');
592
+ const entityType = String(mutation.entityType ?? 'plan_item');
593
+ const entityId = mutation.entityId ? String(mutation.entityId) : null;
594
+ const clientUpdatedAt = asDate(mutation.clientUpdatedAt);
595
+ const payload = mutation.payload && typeof mutation.payload === 'object'
596
+ ? mutation.payload
597
+ : {};
598
+
599
+ if (
600
+ !id ||
601
+ entityType !== 'plan_item' ||
602
+ !entityId ||
603
+ !clientUpdatedAt ||
604
+ !['update', 'complete', 'reschedule'].includes(operation)
605
+ ) {
606
+ results.push({ id, status: 'rejected', error: 'invalid_mutation' });
607
+ continue;
608
+ }
609
+
610
+ await client.query('begin');
611
+ try {
612
+ const duplicate = await client.query(
613
+ 'select accepted_at from sync_mutation where id=$1 and user_id=$2',
614
+ [id, req.identity.sub],
615
+ );
616
+ if (duplicate.rowCount) {
617
+ await client.query('rollback');
618
+ results.push({
619
+ id,
620
+ status: 'already_applied',
621
+ acceptedAt: duplicate.rows[0].accepted_at,
622
+ });
623
+ continue;
624
+ }
625
+
626
+ const current = await client.query(
627
+ 'select * from plan_item where id=$1 for update',
628
+ [entityId],
629
+ );
630
+ if (!current.rowCount) {
631
+ await client.query('rollback');
632
+ results.push({ id, status: 'rejected', error: 'not_found' });
633
+ continue;
634
+ }
635
+ const item = current.rows[0];
636
+ if (item.owner_user_id !== req.identity.sub) {
637
+ await client.query('rollback');
638
+ results.push({ id, status: 'rejected', error: 'forbidden' });
639
+ continue;
640
+ }
641
+
642
+ const serverUpdatedAt = new Date(item.updated_at);
643
+ if (serverUpdatedAt.getTime() > clientUpdatedAt.getTime() + 1000) {
644
+ await client.query('rollback');
645
+ results.push({
646
+ id,
647
+ status: 'conflict',
648
+ serverUpdatedAt: serverUpdatedAt.toISOString(),
649
+ });
650
+ continue;
651
+ }
652
+
653
+ if (operation === 'complete') {
654
+ await client.query(
655
+ `update plan_item
656
+ set status='completed',completed_at=now(),updated_at=now()
657
+ where id=$1`,
658
+ [entityId],
659
+ );
660
+ await client.query(
661
+ `update reminder set status='cancelled'
662
+ where plan_item_id=$1 and status in ('scheduled','claimed')`,
663
+ [entityId],
664
+ );
665
+ } else if (operation === 'reschedule') {
666
+ const dueAt = asDate(payload.dueAt);
667
+ const startsAt = asDate(payload.startsAt);
668
+ if (!dueAt && !startsAt) {
669
+ await client.query('rollback');
670
+ results.push({ id, status: 'rejected', error: 'invalid_reschedule' });
671
+ continue;
672
+ }
673
+ await client.query(
674
+ `update plan_item
675
+ set due_at=coalesce($2,due_at),
676
+ starts_at=coalesce($3,starts_at),
677
+ updated_at=now()
678
+ where id=$1`,
679
+ [entityId, dueAt, startsAt],
680
+ );
681
+ await client.query('select recompute_reminder_schedule($1)', [entityId]);
682
+ } else {
683
+ const title = payload.title == null ? null : String(payload.title).trim();
684
+ const status = payload.status == null ? null : String(payload.status);
685
+ if (status != null && !allowedStatus.has(status)) {
686
+ await client.query('rollback');
687
+ results.push({ id, status: 'rejected', error: 'invalid_status' });
688
+ continue;
689
+ }
690
+ await client.query(
691
+ `update plan_item
692
+ set title=coalesce($2,title),
693
+ status=coalesce($3::plan_item_status,status),
694
+ updated_at=now()
695
+ where id=$1`,
696
+ [entityId, title || null, status],
697
+ );
698
+ }
699
+
700
+ await client.query(
701
+ `insert into sync_mutation(
702
+ id,user_id,entity_type,entity_id,operation,client_updated_at,payload
703
+ ) values($1,$2,$3,$4,$5,$6,$7::jsonb)`,
704
+ [
705
+ id,
706
+ req.identity.sub,
707
+ entityType,
708
+ entityId,
709
+ operation,
710
+ clientUpdatedAt,
711
+ JSON.stringify(payload),
712
+ ],
713
+ );
714
+ await client.query('commit');
715
+ results.push({ id, status: 'accepted' });
716
+ } catch (error) {
717
+ await client.query('rollback').catch(() => {});
718
+ throw error;
719
+ }
720
+ }
721
+ res.json({ results });
722
+ } finally {
723
+ client.release();
724
+ }
725
+ });
726
+
727
+ return router;
728
+}