LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 384 lines 26.3 KB
Raw
1 import crypto from 'node:crypto';
2 import express from 'express';
3
4 const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
5 const states = new Set(['planned', 'started', 'paused', 'completed', 'verified']);
6 const sources = new Set(['timer', 'self_reported']);
7 class InputError extends Error {
8 constructor(status, code, details = {}) { super(code); this.status = status; this.code = code; this.details = details; }
9 }
10 const fail = (status, code, details) => { throw new InputError(status, code, details); };
11 const uuid = (value) => typeof value === 'string' && uuidPattern.test(value);
12 function instant(value) {
13 if (typeof value !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,6})?Z$/.test(value)) return null;
14 const date = new Date(value);
15 return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 19) === value.slice(0, 19) ? date : null;
16 }
17 function eventTime(value) {
18 const date = instant(value);
19 if (!date || date.getTime() > Date.now() + 60000 || date.getTime() < Date.now() - 366 * 86400000) fail(400, 'invalid_timestamp');
20 return date;
21 }
22 function canonical(value) {
23 if (Array.isArray(value)) return value.map(canonical);
24 if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
25 return value;
26 }
27 function checkVersion(expected, actual) {
28 if (!Number.isSafeInteger(expected) || expected < 0) fail(400, 'expected_version_required');
29 if (expected !== Number(actual)) fail(409, 'version_conflict', { serverVersion: Number(actual) });
30 }
31 async function ownerLock(client, userId) {
32 await client.query('select pg_advisory_xact_lock(hashtextextended($1::text,0))', [userId]);
33 }
34 async function guardian(client, familyId, viewerId, childId) {
35 const result = await client.query(
36 `select 1 from family_workspace f
37 where f.id=$1 and f.archived_at is null and is_active_guardian($1,$2,$3)`,
38 [familyId, viewerId, childId],
39 );
40 return result.rowCount > 0;
41 }
42 // Current sharing and both current memberships are required in addition to the
43 // relationship. Reports deliberately project no notes or sensitive table data.
44 const sharedItem = `(p.visibility='parent_guardian' or p.visibility='family'
45 or (p.visibility='selected_members' and exists(
46 select 1 from sharing_grant sg where sg.resource_type='plan_item'
47 and sg.resource_id=p.id and sg.grantee_user_id=$2 and sg.granted_by=p.owner_user_id)))`;
48 async function planForOwner(client, id, userId) {
49 const result = await client.query('select * from plan_item where id=$1 for update', [id]);
50 if (!result.rowCount || result.rows[0].owner_user_id !== userId) fail(404, 'not_found');
51 if (result.rows[0].status === 'cancelled') fail(409, 'activity_archived');
52 return result.rows[0];
53 }
54 async function sessionForOwner(client, id, userId, lock = false) {
55 const result = await client.query(`select * from study_session where id=$1 and child_user_id=$2${lock ? ' for update' : ''}`, [id, userId]);
56 if (!result.rowCount) fail(404, 'not_found');
57 return result.rows[0];
58 }
59 async function activity(client, plan) {
60 const result = await client.query('select * from activity_state_event where plan_item_id=$1 order by version desc limit 1', [plan.id]);
61 const row = result.rows[0];
62 return row ? {
63 state: row.state, version: Number(row.version), occurredAt: row.occurred_at, acceptedAt: row.accepted_at,
64 source: row.source, confirmedBy: row.state === 'verified' ? row.actor_user_id : null,
65 } : { state: plan.status === 'completed' ? 'completed' : plan.status === 'in_progress' ? 'started' : 'planned',
66 version: Number(plan.activity_version), occurredAt: plan.created_at, acceptedAt: plan.updated_at, source: 'self_reported', confirmedBy: null };
67 }
68 async function setActivity(client, plan, actorId, state, source, occurredAt, confirmation = null) {
69 const current = await activity(client, plan);
70 if (new Date(current.occurredAt).getTime() > occurredAt.getTime() && current.version > 0) fail(409, 'non_monotonic_activity_time');
71 const row = (await client.query(
72 `update plan_item set activity_version=activity_version+1,status=$2::plan_item_status,
73 completed_at=case when $2::plan_item_status='completed' then coalesce(completed_at,$3) else null end,updated_at=now()
74 where id=$1 returning *`, [plan.id, ['completed', 'verified'].includes(state) ? 'completed' : state === 'planned' ? 'planned' : 'in_progress', occurredAt],
75 )).rows[0];
76 await client.query(
77 `insert into activity_state_event(plan_item_id,actor_user_id,state,source,occurred_at,version,confirmation)
78 values($1,$2,$3,$4,$5,$6,$7)`, [plan.id, actorId, state, source, occurredAt, row.activity_version, confirmation],
79 );
80 if (row.status === 'completed') await client.query("update reminder set status='cancelled' where plan_item_id=$1 and status in ('scheduled','claimed')", [plan.id]);
81 return activity(client, row);
82 }
83 async function ensureNoOverlap(client, userId, startsAt, endsAt = null, excludedSession = null) {
84 const result = await client.query(
85 `select 1 from study_interval i join study_session s on s.id=i.session_id
86 where s.child_user_id=$1 and s.archived_at is null and ($4::uuid is null or s.id<>$4)
87 and tstzrange(i.starts_at,i.ends_at,'[)') && tstzrange($2::timestamptz,$3::timestamptz,'[)') limit 1`,
88 [userId, startsAt, endsAt, excludedSession],
89 );
90 if (result.rowCount) fail(409, 'study_time_overlap');
91 }
92 async function sessionJson(client, row) {
93 const result = await client.query('select starts_at,ends_at from study_interval where session_id=$1 order by starts_at,id', [row.id]);
94 return { id: row.id, childId: row.child_user_id, planItemId: row.plan_item_id, source: row.source, status: row.status,
95 startedAt: row.started_at, endedAt: row.ended_at, recordedDurationSeconds: row.recorded_duration_seconds,
96 version: row.version, lastSyncAt: row.last_sync_at, lastEventAt: row.last_event_at,
97 intervals: result.rows.map((x) => ({ start: x.starts_at, end: x.ends_at })), isEvidenceOfStudy: false };
98 }
99 async function readSnapshot(pool, read) {
100 const client = await pool.connect();
101 try {
102 await client.query('begin isolation level repeatable read read only');
103 const result = await read(client);
104 await client.query('commit');
105 return result;
106 } catch (error) { await client.query('rollback').catch(() => {}); throw error; }
107 finally { client.release(); }
108 }
109 async function mutation(pool, req, res, resource, execute, authorize = null) {
110 if (!uuid(req.body?.mutationId)) return res.status(400).json({ error: 'mutation_id_required' });
111 const hash = crypto.createHash('sha256').update(JSON.stringify(canonical({ resource, payload: req.body }))).digest('hex');
112 const client = await pool.connect();
113 try {
114 await client.query('begin');
115 // Serializes one actor's duplicate retries before touching any data.
116 await ownerLock(client, req.identity.sub);
117 // Guardian confirmation retries must not bypass a subsequently revoked
118 // relation, role, membership or resource grant through the idempotency ledger.
119 const authorized = authorize ? await authorize(client) : null;
120 const previous = await client.query('select * from study_mutation where user_id=$1 and id=$2', [req.identity.sub, req.body.mutationId]);
121 if (previous.rowCount) {
122 if (previous.rows[0].request_hash !== hash) fail(409, 'mutation_payload_conflict');
123 const response = previous.rows[0].response_body;
124 response.acknowledgement.status = 'already_applied';
125 await client.query('commit');
126 return res.status(previous.rows[0].response_status).json(response);
127 }
128 const { body, status = 200 } = await execute(client, authorized);
129 const acceptedAt = (await client.query('select clock_timestamp() as ts')).rows[0].ts;
130 body.acknowledgement = { mutationId: req.body.mutationId, acceptedAt, status: 'accepted' };
131 await client.query(
132 'insert into study_mutation(user_id,id,request_hash,response_body,response_status,accepted_at) values($1,$2,$3,$4::jsonb,$5,$6)',
133 [req.identity.sub, req.body.mutationId, hash, JSON.stringify(body), status, acceptedAt],
134 );
135 await client.query('commit');
136 return res.status(status).json(body);
137 } catch (error) {
138 await client.query('rollback').catch(() => {});
139 if (error instanceof InputError) return res.status(error.status).json({ error: error.code, ...error.details });
140 if (error.code === '23505') return res.status(409).json({ error: 'study_session_exists' });
141 throw error;
142 } finally { client.release(); }
143 }
144
145 export function createStudySessionsRouter({ pool, auth }) {
146 const router = express.Router();
147 router.use(auth);
148 router.post('/study/sessions', async (req, res) => mutation(pool, req, res, 'session:create', async (client) => {
149 const { id, planItemId, source, childId } = req.body;
150 if (!uuid(id) || !uuid(planItemId) || !sources.has(source) || req.body.recordedDurationSeconds !== undefined) fail(400, 'invalid_study_session');
151 if (childId !== undefined && childId !== req.identity.sub) fail(403, 'forbidden');
152 const startedAt = eventTime(req.body.startedAt);
153 const endedAt = source === 'self_reported' ? eventTime(req.body.endedAt) : null;
154 if ((endedAt && endedAt <= startedAt) || (source === 'timer' && req.body.endedAt !== undefined)) fail(400, 'invalid_study_interval');
155 const plan = await planForOwner(client, planItemId, req.identity.sub);
156 if (plan.status === 'completed') fail(409, 'activity_completed');
157 await ensureNoOverlap(client, req.identity.sub, startedAt, endedAt);
158 const seconds = endedAt ? Math.floor((endedAt - startedAt) / 1000) : 0;
159 const row = (await client.query(
160 `insert into study_session(id,child_user_id,plan_item_id,source,status,started_at,ended_at,last_event_at,recorded_duration_seconds)
161 values($1,$2,$3,$4,$5,$6,$7,$8,$9) returning *`,
162 [id, req.identity.sub, planItemId, source, endedAt ? 'completed' : 'running', startedAt, endedAt, endedAt ?? startedAt, seconds],
163 )).rows[0];
164 await client.query('insert into study_interval(session_id,starts_at,ends_at) values($1,$2,$3)', [id, startedAt, endedAt]);
165 const state = await setActivity(client, plan, req.identity.sub, endedAt ? 'paused' : 'started', source === 'timer' ? 'client_timer' : 'self_reported', endedAt ?? startedAt);
166 return { status: 201, body: { session: await sessionJson(client, row), activity: state } };
167 }));
168 router.get('/study/sessions', async (req, res) => {
169 if (req.query.planItemId !== undefined && !uuid(req.query.planItemId)) return res.status(400).json({ error: 'invalid_id' });
170 res.json(await readSnapshot(pool, async (client) => {
171 const result = await client.query(
172 'select * from study_session where child_user_id=$1 and archived_at is null and ($2::uuid is null or plan_item_id=$2) order by started_at desc limit 500',
173 [req.identity.sub, req.query.planItemId ?? null],
174 );
175 return { sessions: await Promise.all(result.rows.map((x) => sessionJson(client, x))), asOf: new Date() };
176 }));
177 });
178 router.get('/study/sessions/:id', async (req, res) => {
179 if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
180 try { res.json(await readSnapshot(pool, async (client) => ({ session: await sessionJson(client, await sessionForOwner(client, req.params.id, req.identity.sub)), asOf: new Date() }))); }
181 catch (error) { if (error instanceof InputError) return res.status(error.status).json({ error: error.code }); throw error; }
182 });
183 router.patch('/study/sessions/:id', async (req, res) => {
184 if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
185 return mutation(pool, req, res, `session:correct:${req.params.id}`, async (client) => {
186 const row = await sessionForOwner(client, req.params.id, req.identity.sub, true);
187 checkVersion(req.body.expectedVersion, row.version);
188 if (row.source !== 'self_reported' || row.status !== 'completed') fail(409, 'only_completed_self_report_can_be_corrected');
189 if (req.body.recordedDurationSeconds !== undefined) fail(400, 'duration_is_server_computed');
190 const startedAt = eventTime(req.body.startedAt);
191 const endedAt = eventTime(req.body.endedAt);
192 if (endedAt <= startedAt) fail(400, 'invalid_study_interval');
193 await ensureNoOverlap(client, req.identity.sub, startedAt, endedAt, row.id);
194 await client.query('delete from study_interval where session_id=$1', [row.id]);
195 await client.query('insert into study_interval(session_id,starts_at,ends_at) values($1,$2,$3)', [row.id, startedAt, endedAt]);
196 const updated = (await client.query(
197 `update study_session set started_at=$2,ended_at=$3,last_event_at=$3,recorded_duration_seconds=$4,
198 version=version+1,last_sync_at=now(),updated_at=now() where id=$1 returning *`,
199 [row.id, startedAt, endedAt, Math.floor((endedAt - startedAt) / 1000)],
200 )).rows[0];
201 return { body: { session: await sessionJson(client, updated) } };
202 });
203 });
204 router.post('/study/sessions/:id/events', async (req, res) => {
205 if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
206 return mutation(pool, req, res, `session:event:${req.params.id}`, async (client) => {
207 const row = await sessionForOwner(client, req.params.id, req.identity.sub, true);
208 checkVersion(req.body.expectedVersion, row.version);
209 if (row.status === 'completed' || row.status === 'archived') fail(409, 'study_session_closed');
210 const { action } = req.body;
211 if (!['pause', 'resume', 'stop'].includes(action)) fail(400, 'invalid_study_action');
212 const when = eventTime(req.body.occurredAt);
213 if (when < new Date(row.last_event_at)) fail(409, 'non_monotonic_session_time');
214 const plan = await planForOwner(client, row.plan_item_id, req.identity.sub);
215 if (action === 'resume') {
216 if (row.status !== 'paused') fail(409, 'study_not_paused');
217 if (plan.status === 'completed') fail(409, 'activity_completed');
218 await ensureNoOverlap(client, req.identity.sub, when);
219 await client.query('insert into study_interval(session_id,starts_at) values($1,$2)', [row.id, when]);
220 } else if (row.status === 'running') {
221 await client.query('update study_interval set ends_at=$2 where session_id=$1 and ends_at is null', [row.id, when]);
222 } else if (action === 'pause') fail(409, 'study_not_running');
223 const updated = (await client.query(
224 `update study_session set status=$2,ended_at=$3,last_event_at=$4,
225 recorded_duration_seconds=(select floor(coalesce(sum(extract(epoch from ends_at-starts_at)),0))::int from study_interval where session_id=$1),
226 version=version+1,last_sync_at=now(),updated_at=now() where id=$1 returning *`,
227 [row.id, action === 'stop' ? 'completed' : action === 'pause' ? 'paused' : 'running', action === 'stop' ? when : null, when],
228 )).rows[0];
229 const current = await activity(client, plan);
230 const state = plan.status === 'completed' ? current : await setActivity(client, plan, req.identity.sub, action === 'resume' ? 'started' : 'paused', 'client_timer', when);
231 return { body: { session: await sessionJson(client, updated), activity: state } };
232 });
233 });
234 router.delete('/study/sessions/:id', async (req, res) => {
235 if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
236 return mutation(pool, req, res, `session:archive:${req.params.id}`, async (client) => {
237 const row = await sessionForOwner(client, req.params.id, req.identity.sub, true);
238 checkVersion(req.body.expectedVersion, row.version);
239 if (row.status === 'running' || row.status === 'paused') fail(409, 'stop_session_before_archive');
240 if (row.status === 'archived') fail(409, 'study_session_closed');
241 const updated = (await client.query("update study_session set status='archived',archived_at=now(),version=version+1,last_sync_at=now(),updated_at=now() where id=$1 returning *", [row.id])).rows[0];
242 return { body: { session: await sessionJson(client, updated) } };
243 });
244 });
245 router.post('/plan-items/:id/activity-state', async (req, res) => {
246 if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
247 const authorize = async (client) => {
248 const result = await client.query('select * from plan_item where id=$1', [req.params.id]);
249 if (!result.rowCount) fail(404, 'not_found');
250 const candidate = result.rows[0];
251 if (candidate.owner_user_id !== req.identity.sub) await ownerLock(client, candidate.owner_user_id);
252 const plan = (await client.query('select * from plan_item where id=$1 for update', [req.params.id])).rows[0];
253 if (!plan) fail(404, 'not_found');
254 if (req.body.state === 'verified') {
255 if (!plan.family_id || plan.owner_user_id === req.identity.sub || !await guardian(client, plan.family_id, req.identity.sub, plan.owner_user_id)) fail(403, 'forbidden');
256 const shared = await client.query(`select 1 from plan_item p where p.id=$1 and ${sharedItem}`, [plan.id, req.identity.sub]);
257 if (!shared.rowCount) fail(403, 'forbidden');
258 } else if (plan.owner_user_id !== req.identity.sub) fail(403, 'forbidden');
259 return plan;
260 };
261 return mutation(pool, req, res, `activity:${req.params.id}`, async (client, plan) => {
262 const verified = req.body.state === 'verified';
263 if (plan.status === 'cancelled') fail(409, 'activity_archived');
264 const current = await activity(client, plan);
265 checkVersion(req.body.expectedVersion, plan.activity_version);
266 const state = req.body.state;
267 if (!states.has(state)) fail(400, 'invalid_activity_state');
268 const source = req.body.source;
269 const when = eventTime(req.body.occurredAt);
270 let confirmation = null;
271 if (verified) {
272 confirmation = typeof req.body.confirmation === 'string' ? req.body.confirmation.trim() : '';
273 if (source !== 'guardian_confirmation' || !confirmation || confirmation.length > 1000) fail(400, 'explicit_confirmation_required');
274 if (current.state !== 'completed') fail(409, 'complete_before_verification');
275 } else if (!['client_timer', 'self_reported'].includes(source) || req.body.confirmation !== undefined) fail(400, 'invalid_activity_source');
276 if (state === current.state) fail(409, 'activity_state_unchanged');
277 if (['completed', 'verified'].includes(current.state) && !['planned', 'verified'].includes(state)) fail(409, 'reopen_activity_first');
278 const next = await setActivity(client, plan, req.identity.sub, state, source, when, confirmation);
279 const updated = (await client.query('select version from plan_item where id=$1', [plan.id])).rows[0];
280 return { body: { activity: next, planItemId: plan.id, planVersion: Number(updated.version) } };
281 }, authorize);
282 });
283 router.get('/plan-items/:id/activity-state', async (req, res) => {
284 if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' });
285 try {
286 res.json(await readSnapshot(pool, async (client) => {
287 const plan = (await client.query('select * from plan_item where id=$1', [req.params.id])).rows[0];
288 if (!plan) fail(404, 'not_found');
289 if (plan.owner_user_id !== req.identity.sub) {
290 if (!plan.family_id || !await guardian(client, plan.family_id, req.identity.sub, plan.owner_user_id)) fail(403, 'forbidden');
291 if (!(await client.query(`select 1 from plan_item p where p.id=$1 and ${sharedItem}`, [plan.id, req.identity.sub])).rowCount) fail(403, 'forbidden');
292 }
293 const rows = (await client.query(
294 'select state,source,occurred_at,accepted_at,version,actor_user_id from activity_state_event where plan_item_id=$1 order by version desc limit 500', [plan.id],
295 )).rows.reverse();
296 return { planItemId: plan.id, planVersion: Number(plan.version), activity: await activity(client, plan),
297 history: rows.map((x) => ({ state: x.state, source: x.source, occurredAt: x.occurred_at, acceptedAt: x.accepted_at,
298 version: Number(x.version), confirmedBy: x.state === 'verified' ? x.actor_user_id : null })), asOf: new Date() };
299 }));
300 } catch (error) { if (error instanceof InputError) return res.status(error.status).json({ error: error.code }); throw error; }
301 });
302 router.get('/families/:familyId/children/:childId/learning-report', async (req, res) => {
303 if (!uuid(req.params.familyId) || !uuid(req.params.childId)) return res.status(400).json({ error: 'invalid_id' });
304 const to = req.query.to === undefined ? new Date() : instant(req.query.to);
305 const from = req.query.from === undefined && to ? new Date(to.getTime() - 30 * 86400000) : instant(req.query.from);
306 if (!from || !to || to <= from || to - from > 366 * 86400000) return res.status(400).json({ error: 'invalid_report_range' });
307 const client = await pool.connect();
308 try {
309 await client.query('begin isolation level repeatable read read only');
310 if (!await guardian(client, req.params.familyId, req.identity.sub, req.params.childId)) { await client.query('rollback'); return res.status(403).json({ error: 'forbidden' }); }
311 const asOf = (await client.query('select clock_timestamp() as ts')).rows[0].ts;
312 const items = (await client.query(
313 `select p.id,p.title,p.kind,p.status,p.priority,p.starts_at,p.due_at,p.duration_minutes,p.planned_duration_seconds,p.completed_at,p.updated_at,p.version,
314 p.activity_version,sub.name as subject_name,p.grade_points,p.grade_out_of,
315 e.state as activity_state,e.source as activity_source,e.occurred_at as activity_at
316 from plan_item p left join subject sub on sub.id=p.subject_id
317 left join lateral(select state,source,occurred_at from activity_state_event where plan_item_id=p.id order by version desc limit 1) e on true
318 where p.family_id=$1 and p.owner_user_id=$3 and p.status<>'cancelled' and ${sharedItem}
319 order by coalesce(p.starts_at,p.due_at,p.created_at),p.id`,
320 [req.params.familyId, req.identity.sub, req.params.childId],
321 )).rows;
322 const ids = items.map((x) => x.id);
323 const intervals = (await client.query(
324 `select s.id,s.plan_item_id,s.source,s.last_sync_at,s.version,
325 greatest(i.starts_at,$2::timestamptz) as starts_at,
326 least(coalesce(i.ends_at,$4::timestamptz),$3::timestamptz,$4::timestamptz) as ends_at
327 from study_session s join study_interval i on i.session_id=s.id
328 where s.plan_item_id=any($1::uuid[]) and s.archived_at is null and i.starts_at<$3
329 and coalesce(i.ends_at,$4)>$2`, [ids, from, to, asOf],
330 )).rows.filter((x) => x.ends_at > x.starts_at);
331 const timeByItem = new Map();
332 const daily = new Map();
333 let totalMilliseconds = 0;
334 for (const interval of intervals) {
335 const milliseconds = interval.ends_at - interval.starts_at;
336 totalMilliseconds += milliseconds;
337 timeByItem.set(interval.plan_item_id, (timeByItem.get(interval.plan_item_id) ?? 0) + milliseconds);
338 // Split at Tehran midnight. Recorded time is never inferred as learning evidence.
339 let start = interval.starts_at.getTime();
340 const end = interval.ends_at.getTime();
341 while (start < end) {
342 const local = new Date(start + 210 * 60000);
343 const key = local.toISOString().slice(0, 10);
344 const next = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate() + 1) - 210 * 60000;
345 const part = Math.min(end, next) - start;
346 daily.set(key, (daily.get(key) ?? 0) + part);
347 start += part;
348 }
349 }
350 const projected = items.map((x) => ({ id: x.id, title: x.title, kind: x.kind, status: x.status, priority: x.priority, version: Number(x.version),
351 startsAt: x.starts_at, dueAt: x.due_at, plannedDurationSeconds: x.planned_duration_seconds ?? (x.duration_minutes ?? 0) * 60,
352 recordedDurationSeconds: Math.floor((timeByItem.get(x.id) ?? 0) / 1000), completedAt: x.completed_at,
353 activityState: x.activity_state ?? (x.status === 'completed' ? 'completed' : x.status === 'in_progress' ? 'started' : 'planned'),
354 activitySource: x.activity_source ?? 'self_reported', activityAt: x.activity_at ?? x.updated_at,
355 subjectName: x.subject_name, gradePoints: x.grade_points, gradeOutOf: x.grade_out_of }));
356 const planned = projected.filter((x) => { const at = x.startsAt ?? x.dueAt; return at && new Date(at) >= from && new Date(at) < to; });
357 const complete = projected.filter((x) => x.status === 'completed').length;
358 const latest = [...items.map((x) => x.updated_at), ...intervals.map((x) => x.last_sync_at)].sort((a, b) => b - a)[0] ?? null;
359 const subjects = new Map();
360 for (const item of projected) {
361 const key = item.subjectName ?? 'بدون درس';
362 const existing = subjects.get(key) ?? { subjectName: key, totalTasks: 0, completedTasks: 0, recordedDurationSeconds: 0 };
363 existing.totalTasks++;
364 if (item.status === 'completed') existing.completedTasks++;
365 existing.recordedDurationSeconds += item.recordedDurationSeconds;
366 subjects.set(key, existing);
367 }
368 const response = { childId: req.params.childId, familyId: req.params.familyId, from, to, asOf, lastSyncAt: latest,
369 sourceVersion: crypto.createHash('sha256').update(JSON.stringify({ items: items.map((x) => [x.id, x.updated_at, x.activity_version]), intervals: intervals.map((x) => [x.id, x.version, x.last_sync_at]) })).digest('hex'),
370 timezone: 'Asia/Tehran', recordingDisclaimerKey: 'recorded_time_is_not_proof_of_study', items: projected,
371 metrics: { totalTasks: projected.length, completedTasks: complete, completionPercent: projected.length ? Math.round(complete * 100 / projected.length) : 0,
372 overdueTasks: projected.filter((x) => x.status !== 'completed' && x.dueAt && new Date(x.dueAt) < asOf).length,
373 plannedDurationSeconds: projected.reduce((sum, x) => sum + x.plannedDurationSeconds, 0),
374 plannedInRangeDurationSeconds: planned.reduce((sum, x) => sum + x.plannedDurationSeconds, 0),
375 recordedDurationSeconds: Math.floor(totalMilliseconds / 1000) },
376 daily: [...daily.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([date, ms]) => ({ date, recordedDurationSeconds: Math.floor(ms / 1000) })),
377 subjects: [...subjects.values()], sources: [...new Set(intervals.map((x) => x.source))], isEvidenceOfStudy: false };
378 await client.query('commit');
379 res.json(response);
380 } catch (error) { await client.query('rollback').catch(() => {}); throw error; }
381 finally { client.release(); }
382 });
383 return router;
384 }