LifeMate — Personal, Family & Learning Companion
design/mobile-navigation-review
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 | |
| 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 | function taskMetrics(items, asOf) { |
| 110 | const completedTasks = items.filter((item) => item.status === 'completed').length; |
| 111 | return { |
| 112 | totalTasks: items.length, completedTasks, |
| 113 | completionPercent: items.length ? Math.round(completedTasks * 100 / items.length) : 0, |
| 114 | overdueTasks: items.filter((item) => item.status !== 'completed' && item.dueAt && new Date(item.dueAt) < asOf).length, |
| 115 | plannedDurationSeconds: items.reduce((sum, item) => sum + item.plannedDurationSeconds, 0), |
| 116 | }; |
| 117 | } |
| 118 | function examMetrics(items) { |
| 119 | const exams = items.filter((item) => item.kind === 'exam'); |
| 120 | const graded = exams.filter((item) => item.gradePoints !== null && item.gradeOutOf !== null && item.gradeOutOf > 0); |
| 121 | const denominator = graded.reduce((sum, item) => sum + Number(item.gradeOutOf), 0); |
| 122 | const numerator = graded.reduce((sum, item) => sum + Number(item.gradePoints), 0); |
| 123 | return { examCount: exams.length, gradedExamCount: graded.length, |
| 124 | gradePercent: denominator ? Math.round(numerator * 10000 / denominator) / 100 : null }; |
| 125 | } |
| 126 | function subjectMetrics(items, periodOnly = false) { |
| 127 | const groups = new Map(); |
| 128 | for (const item of items) { |
| 129 | // Names can repeat across terms. A task belongs to exactly one subject; |
| 130 | // neither labels nor sharing grants multiply its counts or recorded time. |
| 131 | const key = item.subjectId; |
| 132 | if (!groups.has(key)) groups.set(key, []); |
| 133 | groups.get(key).push(item); |
| 134 | } |
| 135 | return [...groups.entries()].map(([subjectId, subjectItems]) => { |
| 136 | const cohort = periodOnly ? subjectItems.filter((item) => item.taskInRange) : subjectItems; |
| 137 | return { subjectId, subjectName: subjectItems[0].subjectName ?? 'بدون درس', |
| 138 | totalTasks: cohort.length, completedTasks: cohort.filter((item) => item.status === 'completed').length, |
| 139 | recordedDurationSeconds: subjectItems.reduce((sum, item) => sum + item.recordedDurationSeconds, 0), |
| 140 | ...(periodOnly ? examMetrics(cohort) : {}) }; |
| 141 | }); |
| 142 | } |
| 143 | async function mutation(pool, req, res, resource, execute, authorize = null) { |
| 144 | if (!uuid(req.body?.mutationId)) return res.status(400).json({ error: 'mutation_id_required' }); |
| 145 | const hash = crypto.createHash('sha256').update(JSON.stringify(canonical({ resource, payload: req.body }))).digest('hex'); |
| 146 | const client = await pool.connect(); |
| 147 | try { |
| 148 | await client.query('begin'); |
| 149 | // Serializes one actor's duplicate retries before touching any data. |
| 150 | await ownerLock(client, req.identity.sub); |
| 151 | // Guardian confirmation retries must not bypass a subsequently revoked |
| 152 | // relation, role, membership or resource grant through the idempotency ledger. |
| 153 | const authorized = authorize ? await authorize(client) : null; |
| 154 | const previous = await client.query('select * from study_mutation where user_id=$1 and id=$2', [req.identity.sub, req.body.mutationId]); |
| 155 | if (previous.rowCount) { |
| 156 | if (previous.rows[0].request_hash !== hash) fail(409, 'mutation_payload_conflict'); |
| 157 | const response = previous.rows[0].response_body; |
| 158 | response.acknowledgement.status = 'already_applied'; |
| 159 | await client.query('commit'); |
| 160 | return res.status(previous.rows[0].response_status).json(response); |
| 161 | } |
| 162 | const { body, status = 200 } = await execute(client, authorized); |
| 163 | const acceptedAt = (await client.query('select clock_timestamp() as ts')).rows[0].ts; |
| 164 | body.acknowledgement = { mutationId: req.body.mutationId, acceptedAt, status: 'accepted' }; |
| 165 | await client.query( |
| 166 | 'insert into study_mutation(user_id,id,request_hash,response_body,response_status,accepted_at) values($1,$2,$3,$4::jsonb,$5,$6)', |
| 167 | [req.identity.sub, req.body.mutationId, hash, JSON.stringify(body), status, acceptedAt], |
| 168 | ); |
| 169 | await client.query('commit'); |
| 170 | return res.status(status).json(body); |
| 171 | } catch (error) { |
| 172 | await client.query('rollback').catch(() => {}); |
| 173 | if (error instanceof InputError) return res.status(error.status).json({ error: error.code, ...error.details }); |
| 174 | if (error.code === '23505') return res.status(409).json({ error: 'study_session_exists' }); |
| 175 | throw error; |
| 176 | } finally { client.release(); } |
| 177 | } |
| 178 | |
| 179 | export function createStudySessionsRouter({ pool, auth }) { |
| 180 | const router = express.Router(); |
| 181 | router.use(auth); |
| 182 | router.post('/study/sessions', async (req, res) => mutation(pool, req, res, 'session:create', async (client) => { |
| 183 | const { id, planItemId, source, childId } = req.body; |
| 184 | if (!uuid(id) || !uuid(planItemId) || !sources.has(source) || req.body.recordedDurationSeconds !== undefined) fail(400, 'invalid_study_session'); |
| 185 | if (childId !== undefined && childId !== req.identity.sub) fail(403, 'forbidden'); |
| 186 | const startedAt = eventTime(req.body.startedAt); |
| 187 | const endedAt = source === 'self_reported' ? eventTime(req.body.endedAt) : null; |
| 188 | if ((endedAt && endedAt <= startedAt) || (source === 'timer' && req.body.endedAt !== undefined)) fail(400, 'invalid_study_interval'); |
| 189 | const plan = await planForOwner(client, planItemId, req.identity.sub); |
| 190 | if (plan.status === 'completed') fail(409, 'activity_completed'); |
| 191 | await ensureNoOverlap(client, req.identity.sub, startedAt, endedAt); |
| 192 | const seconds = endedAt ? Math.floor((endedAt - startedAt) / 1000) : 0; |
| 193 | const row = (await client.query( |
| 194 | `insert into study_session(id,child_user_id,plan_item_id,source,status,started_at,ended_at,last_event_at,recorded_duration_seconds) |
| 195 | values($1,$2,$3,$4,$5,$6,$7,$8,$9) returning *`, |
| 196 | [id, req.identity.sub, planItemId, source, endedAt ? 'completed' : 'running', startedAt, endedAt, endedAt ?? startedAt, seconds], |
| 197 | )).rows[0]; |
| 198 | await client.query('insert into study_interval(session_id,starts_at,ends_at) values($1,$2,$3)', [id, startedAt, endedAt]); |
| 199 | const state = await setActivity(client, plan, req.identity.sub, endedAt ? 'paused' : 'started', source === 'timer' ? 'client_timer' : 'self_reported', endedAt ?? startedAt); |
| 200 | return { status: 201, body: { session: await sessionJson(client, row), activity: state } }; |
| 201 | })); |
| 202 | router.get('/study/sessions', async (req, res) => { |
| 203 | if (req.query.planItemId !== undefined && !uuid(req.query.planItemId)) return res.status(400).json({ error: 'invalid_id' }); |
| 204 | res.json(await readSnapshot(pool, async (client) => { |
| 205 | const result = await client.query( |
| 206 | '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', |
| 207 | [req.identity.sub, req.query.planItemId ?? null], |
| 208 | ); |
| 209 | return { sessions: await Promise.all(result.rows.map((x) => sessionJson(client, x))), asOf: new Date() }; |
| 210 | })); |
| 211 | }); |
| 212 | router.get('/study/sessions/:id', async (req, res) => { |
| 213 | if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' }); |
| 214 | try { res.json(await readSnapshot(pool, async (client) => ({ session: await sessionJson(client, await sessionForOwner(client, req.params.id, req.identity.sub)), asOf: new Date() }))); } |
| 215 | catch (error) { if (error instanceof InputError) return res.status(error.status).json({ error: error.code }); throw error; } |
| 216 | }); |
| 217 | router.patch('/study/sessions/:id', async (req, res) => { |
| 218 | if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' }); |
| 219 | return mutation(pool, req, res, `session:correct:${req.params.id}`, async (client) => { |
| 220 | const row = await sessionForOwner(client, req.params.id, req.identity.sub, true); |
| 221 | checkVersion(req.body.expectedVersion, row.version); |
| 222 | if (row.source !== 'self_reported' || row.status !== 'completed') fail(409, 'only_completed_self_report_can_be_corrected'); |
| 223 | if (req.body.recordedDurationSeconds !== undefined) fail(400, 'duration_is_server_computed'); |
| 224 | const startedAt = eventTime(req.body.startedAt); |
| 225 | const endedAt = eventTime(req.body.endedAt); |
| 226 | if (endedAt <= startedAt) fail(400, 'invalid_study_interval'); |
| 227 | await ensureNoOverlap(client, req.identity.sub, startedAt, endedAt, row.id); |
| 228 | await client.query('delete from study_interval where session_id=$1', [row.id]); |
| 229 | await client.query('insert into study_interval(session_id,starts_at,ends_at) values($1,$2,$3)', [row.id, startedAt, endedAt]); |
| 230 | const updated = (await client.query( |
| 231 | `update study_session set started_at=$2,ended_at=$3,last_event_at=$3,recorded_duration_seconds=$4, |
| 232 | version=version+1,last_sync_at=now(),updated_at=now() where id=$1 returning *`, |
| 233 | [row.id, startedAt, endedAt, Math.floor((endedAt - startedAt) / 1000)], |
| 234 | )).rows[0]; |
| 235 | return { body: { session: await sessionJson(client, updated) } }; |
| 236 | }); |
| 237 | }); |
| 238 | router.post('/study/sessions/:id/events', async (req, res) => { |
| 239 | if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' }); |
| 240 | return mutation(pool, req, res, `session:event:${req.params.id}`, async (client) => { |
| 241 | const row = await sessionForOwner(client, req.params.id, req.identity.sub, true); |
| 242 | checkVersion(req.body.expectedVersion, row.version); |
| 243 | if (row.status === 'completed' || row.status === 'archived') fail(409, 'study_session_closed'); |
| 244 | const { action } = req.body; |
| 245 | if (!['pause', 'resume', 'stop'].includes(action)) fail(400, 'invalid_study_action'); |
| 246 | const when = eventTime(req.body.occurredAt); |
| 247 | if (when < new Date(row.last_event_at)) fail(409, 'non_monotonic_session_time'); |
| 248 | const plan = await planForOwner(client, row.plan_item_id, req.identity.sub); |
| 249 | if (action === 'resume') { |
| 250 | if (row.status !== 'paused') fail(409, 'study_not_paused'); |
| 251 | if (plan.status === 'completed') fail(409, 'activity_completed'); |
| 252 | await ensureNoOverlap(client, req.identity.sub, when); |
| 253 | await client.query('insert into study_interval(session_id,starts_at) values($1,$2)', [row.id, when]); |
| 254 | } else if (row.status === 'running') { |
| 255 | await client.query('update study_interval set ends_at=$2 where session_id=$1 and ends_at is null', [row.id, when]); |
| 256 | } else if (action === 'pause') fail(409, 'study_not_running'); |
| 257 | const updated = (await client.query( |
| 258 | `update study_session set status=$2,ended_at=$3,last_event_at=$4, |
| 259 | recorded_duration_seconds=(select floor(coalesce(sum(extract(epoch from ends_at-starts_at)),0))::int from study_interval where session_id=$1), |
| 260 | version=version+1,last_sync_at=now(),updated_at=now() where id=$1 returning *`, |
| 261 | [row.id, action === 'stop' ? 'completed' : action === 'pause' ? 'paused' : 'running', action === 'stop' ? when : null, when], |
| 262 | )).rows[0]; |
| 263 | const current = await activity(client, plan); |
| 264 | const state = plan.status === 'completed' ? current : await setActivity(client, plan, req.identity.sub, action === 'resume' ? 'started' : 'paused', 'client_timer', when); |
| 265 | return { body: { session: await sessionJson(client, updated), activity: state } }; |
| 266 | }); |
| 267 | }); |
| 268 | router.delete('/study/sessions/:id', async (req, res) => { |
| 269 | if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' }); |
| 270 | return mutation(pool, req, res, `session:archive:${req.params.id}`, async (client) => { |
| 271 | const row = await sessionForOwner(client, req.params.id, req.identity.sub, true); |
| 272 | checkVersion(req.body.expectedVersion, row.version); |
| 273 | if (row.status === 'running' || row.status === 'paused') fail(409, 'stop_session_before_archive'); |
| 274 | if (row.status === 'archived') fail(409, 'study_session_closed'); |
| 275 | 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]; |
| 276 | return { body: { session: await sessionJson(client, updated) } }; |
| 277 | }); |
| 278 | }); |
| 279 | router.post('/plan-items/:id/activity-state', async (req, res) => { |
| 280 | if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' }); |
| 281 | const authorize = async (client) => { |
| 282 | const result = await client.query('select * from plan_item where id=$1', [req.params.id]); |
| 283 | if (!result.rowCount) fail(404, 'not_found'); |
| 284 | const candidate = result.rows[0]; |
| 285 | if (candidate.owner_user_id !== req.identity.sub) await ownerLock(client, candidate.owner_user_id); |
| 286 | const plan = (await client.query('select * from plan_item where id=$1 for update', [req.params.id])).rows[0]; |
| 287 | if (!plan) fail(404, 'not_found'); |
| 288 | if (req.body.state === 'verified') { |
| 289 | 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'); |
| 290 | const shared = await client.query(`select 1 from plan_item p where p.id=$1 and ${sharedItem}`, [plan.id, req.identity.sub]); |
| 291 | if (!shared.rowCount) fail(403, 'forbidden'); |
| 292 | } else if (plan.owner_user_id !== req.identity.sub) fail(403, 'forbidden'); |
| 293 | return plan; |
| 294 | }; |
| 295 | return mutation(pool, req, res, `activity:${req.params.id}`, async (client, plan) => { |
| 296 | const verified = req.body.state === 'verified'; |
| 297 | if (plan.status === 'cancelled') fail(409, 'activity_archived'); |
| 298 | const current = await activity(client, plan); |
| 299 | checkVersion(req.body.expectedVersion, plan.activity_version); |
| 300 | const state = req.body.state; |
| 301 | if (!states.has(state)) fail(400, 'invalid_activity_state'); |
| 302 | const source = req.body.source; |
| 303 | const when = eventTime(req.body.occurredAt); |
| 304 | let confirmation = null; |
| 305 | if (verified) { |
| 306 | confirmation = typeof req.body.confirmation === 'string' ? req.body.confirmation.trim() : ''; |
| 307 | if (source !== 'guardian_confirmation' || !confirmation || confirmation.length > 1000) fail(400, 'explicit_confirmation_required'); |
| 308 | if (current.state !== 'completed') fail(409, 'complete_before_verification'); |
| 309 | } else if (!['client_timer', 'self_reported'].includes(source) || req.body.confirmation !== undefined) fail(400, 'invalid_activity_source'); |
| 310 | if (state === current.state) fail(409, 'activity_state_unchanged'); |
| 311 | if (['completed', 'verified'].includes(current.state) && !['planned', 'verified'].includes(state)) fail(409, 'reopen_activity_first'); |
| 312 | const next = await setActivity(client, plan, req.identity.sub, state, source, when, confirmation); |
| 313 | const updated = (await client.query('select version from plan_item where id=$1', [plan.id])).rows[0]; |
| 314 | return { body: { activity: next, planItemId: plan.id, planVersion: Number(updated.version) } }; |
| 315 | }, authorize); |
| 316 | }); |
| 317 | router.get('/plan-items/:id/activity-state', async (req, res) => { |
| 318 | if (!uuid(req.params.id)) return res.status(400).json({ error: 'invalid_id' }); |
| 319 | try { |
| 320 | res.json(await readSnapshot(pool, async (client) => { |
| 321 | const plan = (await client.query('select * from plan_item where id=$1', [req.params.id])).rows[0]; |
| 322 | if (!plan) fail(404, 'not_found'); |
| 323 | if (plan.owner_user_id !== req.identity.sub) { |
| 324 | if (!plan.family_id || !await guardian(client, plan.family_id, req.identity.sub, plan.owner_user_id)) fail(403, 'forbidden'); |
| 325 | 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'); |
| 326 | } |
| 327 | const rows = (await client.query( |
| 328 | '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], |
| 329 | )).rows.reverse(); |
| 330 | return { planItemId: plan.id, planVersion: Number(plan.version), activity: await activity(client, plan), |
| 331 | history: rows.map((x) => ({ state: x.state, source: x.source, occurredAt: x.occurred_at, acceptedAt: x.accepted_at, |
| 332 | version: Number(x.version), confirmedBy: x.state === 'verified' ? x.actor_user_id : null })), asOf: new Date() }; |
| 333 | })); |
| 334 | } catch (error) { if (error instanceof InputError) return res.status(error.status).json({ error: error.code }); throw error; } |
| 335 | }); |
| 336 | router.get('/families/:familyId/children/:childId/learning-report', async (req, res) => { |
| 337 | if (!uuid(req.params.familyId) || !uuid(req.params.childId)) return res.status(400).json({ error: 'invalid_id' }); |
| 338 | const to = req.query.to === undefined ? new Date() : instant(req.query.to); |
| 339 | const from = req.query.from === undefined && to ? new Date(to.getTime() - 30 * 86400000) : instant(req.query.from); |
| 340 | if (!from || !to || to <= from || to - from > 366 * 86400000) return res.status(400).json({ error: 'invalid_report_range' }); |
| 341 | const client = await pool.connect(); |
| 342 | try { |
| 343 | await client.query('begin isolation level repeatable read read only'); |
| 344 | if (!await guardian(client, req.params.familyId, req.identity.sub, req.params.childId)) { await client.query('rollback'); return res.status(403).json({ error: 'forbidden' }); } |
| 345 | const asOf = (await client.query('select clock_timestamp() as ts')).rows[0].ts; |
| 346 | const items = (await client.query( |
| 347 | `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, |
| 348 | p.activity_version,p.subject_id,sub.name as subject_name,p.grade_points,p.grade_out_of, |
| 349 | e.state as activity_state,e.source as activity_source,e.occurred_at as activity_at |
| 350 | from plan_item p left join subject sub on sub.id=p.subject_id |
| 351 | 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 |
| 352 | where p.family_id=$1 and p.owner_user_id=$3 and p.status<>'cancelled' and ${sharedItem} |
| 353 | order by coalesce(p.starts_at,p.due_at,p.created_at),p.id`, |
| 354 | [req.params.familyId, req.identity.sub, req.params.childId], |
| 355 | )).rows; |
| 356 | const ids = items.map((x) => x.id); |
| 357 | const intervals = (await client.query( |
| 358 | `select s.id,s.plan_item_id,s.source,s.last_sync_at,s.version, |
| 359 | greatest(i.starts_at,$2::timestamptz) as starts_at, |
| 360 | least(coalesce(i.ends_at,$4::timestamptz),$3::timestamptz,$4::timestamptz) as ends_at |
| 361 | from study_session s join study_interval i on i.session_id=s.id |
| 362 | where s.plan_item_id=any($1::uuid[]) and s.archived_at is null and i.starts_at<$3 |
| 363 | and coalesce(i.ends_at,$4)>$2 |
| 364 | order by s.id,i.starts_at,i.id`, [ids, from, to, asOf], |
| 365 | )).rows.filter((x) => x.ends_at > x.starts_at); |
| 366 | const timeByItem = new Map(); |
| 367 | const daily = new Map(); |
| 368 | let totalMilliseconds = 0; |
| 369 | for (const interval of intervals) { |
| 370 | const milliseconds = interval.ends_at - interval.starts_at; |
| 371 | totalMilliseconds += milliseconds; |
| 372 | timeByItem.set(interval.plan_item_id, (timeByItem.get(interval.plan_item_id) ?? 0) + milliseconds); |
| 373 | // Split at Tehran midnight. Recorded time is never inferred as learning evidence. |
| 374 | let start = interval.starts_at.getTime(); |
| 375 | const end = interval.ends_at.getTime(); |
| 376 | while (start < end) { |
| 377 | const local = new Date(start + 210 * 60000); |
| 378 | const key = local.toISOString().slice(0, 10); |
| 379 | const next = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate() + 1) - 210 * 60000; |
| 380 | const part = Math.min(end, next) - start; |
| 381 | daily.set(key, (daily.get(key) ?? 0) + part); |
| 382 | start += part; |
| 383 | } |
| 384 | } |
| 385 | const projected = items.map((x) => ({ id: x.id, title: x.title, kind: x.kind, status: x.status, priority: x.priority, version: Number(x.version), |
| 386 | startsAt: x.starts_at, dueAt: x.due_at, plannedDurationSeconds: x.planned_duration_seconds ?? (x.duration_minutes ?? 0) * 60, |
| 387 | scheduledAt: x.due_at ?? x.starts_at, |
| 388 | taskInRange: Boolean((x.due_at ?? x.starts_at) && (x.due_at ?? x.starts_at) >= from && (x.due_at ?? x.starts_at) < to), |
| 389 | recordedDurationSeconds: Math.floor((timeByItem.get(x.id) ?? 0) / 1000), completedAt: x.completed_at, |
| 390 | activityState: x.activity_state ?? (x.status === 'completed' ? 'completed' : x.status === 'in_progress' ? 'started' : 'planned'), |
| 391 | activitySource: x.activity_source ?? 'self_reported', activityAt: x.activity_at ?? x.updated_at, |
| 392 | subjectId: x.subject_id, subjectName: x.subject_name, gradePoints: x.grade_points, gradeOutOf: x.grade_out_of })); |
| 393 | const planned = projected.filter((item) => item.taskInRange); |
| 394 | const allTimeTaskMetrics = taskMetrics(projected, asOf); |
| 395 | const periodMetrics = { ...taskMetrics(planned, asOf), recordedDurationSeconds: Math.floor(totalMilliseconds / 1000), ...examMetrics(planned) }; |
| 396 | const latest = [...items.map((x) => x.updated_at), ...intervals.map((x) => x.last_sync_at)].sort((a, b) => b - a)[0] ?? null; |
| 397 | const response = { childId: req.params.childId, familyId: req.params.familyId, from, to, asOf, lastSyncAt: latest, |
| 398 | sourceVersion: crypto.createHash('sha256').update(JSON.stringify({ from, to, items: projected, |
| 399 | intervals: intervals.map((x) => [x.id, x.version, x.last_sync_at, x.starts_at, x.ends_at]) })).digest('hex'), |
| 400 | timezone: 'Asia/Tehran', recordingDisclaimerKey: 'recorded_time_is_not_proof_of_study', items: projected, |
| 401 | taskDatePolicy: 'due_at_then_starts_at', rangeConvention: 'inclusive_from_exclusive_to', completionBasis: 'current_status_of_period_tasks', |
| 402 | periodMetrics, allTimeTaskMetrics, |
| 403 | // Legacy task counters stay historical for existing consumers. New |
| 404 | // clients use periodMetrics, so a range selector cannot relabel history. |
| 405 | metrics: { ...allTimeTaskMetrics, plannedInRangeDurationSeconds: periodMetrics.plannedDurationSeconds, |
| 406 | recordedDurationSeconds: Math.floor(totalMilliseconds / 1000) }, |
| 407 | daily: [...daily.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([date, ms]) => ({ date, recordedDurationSeconds: Math.floor(ms / 1000) })), |
| 408 | subjects: subjectMetrics(projected), |
| 409 | periodSubjects: subjectMetrics(projected.filter((item) => item.taskInRange || item.recordedDurationSeconds > 0), true), |
| 410 | periodExams: planned.filter((item) => item.kind === 'exam'), |
| 411 | sources: [...new Set(intervals.map((x) => x.source))].sort(), isEvidenceOfStudy: false }; |
| 412 | await client.query('commit'); |
| 413 | res.json(response); |
| 414 | } catch (error) { await client.query('rollback').catch(() => {}); throw error; } |
| 415 | finally { client.release(); } |
| 416 | }); |
| 417 | return router; |
| 418 | } |