LifeMate — Personal, Family & Learning Companion
fix/study-duration-display
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 test, { after } from 'node:test'; |
| 2 | import assert from 'node:assert/strict'; |
| 3 | import crypto from 'node:crypto'; |
| 4 | import express from 'express'; |
| 5 | import jwt from 'jsonwebtoken'; |
| 6 | import pg from 'pg'; |
| 7 | import { createSessionAuth } from '../src/session_auth.js'; |
| 8 | import { createPhase3Router } from '../src/phase3.js'; |
| 9 | |
| 10 | // A missing router must fail the HTTP acceptance assertion, never skip a gate. |
| 11 | const studyModule = await import('../src/study_sessions.js').catch((error) => { |
| 12 | if (error.code === 'ERR_MODULE_NOT_FOUND') return null; |
| 13 | throw error; |
| 14 | }); |
| 15 | if (!process.env.DATABASE_URL) throw new Error('study tests require a synthetic PostgreSQL DATABASE_URL'); |
| 16 | const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); |
| 17 | const jwtSecret = 'synthetic-study-test-secret-32-characters'; |
| 18 | const auth = createSessionAuth({ pool, jwtSecret }); |
| 19 | const app = express(); |
| 20 | app.use(express.json({ limit: '64kb' })); |
| 21 | app.use('/v1', createPhase3Router({ pool, auth })); |
| 22 | if (studyModule) app.use('/v1', studyModule.createStudySessionsRouter({ pool, auth })); |
| 23 | app.use((error, _req, res, _next) => { |
| 24 | console.error(error); |
| 25 | res.status(500).json({ error: 'internal_error' }); |
| 26 | }); |
| 27 | let server = app.listen(0); |
| 28 | let base = `http://127.0.0.1:${server.address().port}`; |
| 29 | after(async () => { |
| 30 | await new Promise((resolve) => server.close(resolve)); |
| 31 | await pool.end(); |
| 32 | }); |
| 33 | |
| 34 | async function request(path, { method = 'GET', body, user } = {}) { |
| 35 | const response = await fetch(base + path, { |
| 36 | method, |
| 37 | headers: { 'content-type': 'application/json', ...(user ? { authorization: `Bearer ${user.token}` } : {}) }, |
| 38 | body: body === undefined ? undefined : JSON.stringify(body), |
| 39 | }); |
| 40 | const raw = await response.text(); |
| 41 | return { status: response.status, body: raw && response.headers.get('content-type')?.includes('application/json') ? JSON.parse(raw) : raw || null }; |
| 42 | } |
| 43 | async function user() { |
| 44 | const id = crypto.randomUUID(); |
| 45 | const sid = crypto.randomUUID(); |
| 46 | await pool.query('insert into app_user(id,identity_subject,email_normalized,email_verified_at) values($1,$2,$3,now())', |
| 47 | [id, `study-test:${id}`, `${id}@example.test`]); |
| 48 | await pool.query("insert into profile(user_id,display_name,theme_preference) values($1,'Synthetic study tester','adult_blue')", [id]); |
| 49 | await pool.query("insert into auth_session(id,user_id,refresh_digest,expires_at) values($1,$2,$3,now()+interval '1 day')", [sid, id, crypto.randomUUID()]); |
| 50 | return { id, sid, token: jwt.sign({ sub: id, sid, aud: 'lifemate-api' }, jwtSecret, { issuer: 'lifemate', expiresIn: '15m' }) }; |
| 51 | } |
| 52 | async function fixture() { |
| 53 | const child = await user(); |
| 54 | const mother = await user(); |
| 55 | const father = await user(); |
| 56 | const outsider = await user(); |
| 57 | const familyId = crypto.randomUUID(); |
| 58 | await pool.query("insert into family_workspace(id,name,created_by) values($1,'Synthetic study family',$2)", [familyId, mother.id]); |
| 59 | for (const [u, role] of [[child, 'teen_minor'], [mother, 'parent_guardian'], [father, 'parent_guardian']]) { |
| 60 | await pool.query('insert into family_membership(family_id,user_id,role,is_admin) values($1,$2,$3,$4)', [familyId, u.id, role, u === mother]); |
| 61 | } |
| 62 | for (const u of [mother, father]) { |
| 63 | await pool.query('insert into guardian_relationship(family_id,guardian_user_id,minor_user_id) values($1,$2,$3)', [familyId, u.id, child.id]); |
| 64 | } |
| 65 | const task = await request('/v1/plan-items', { method: 'POST', user: child, body: { |
| 66 | kind: 'assignment', title: 'تمرین ریاضی آزمایشی', notes: 'PRIVATE-NOTE-DO-NOT-REPORT', familyId, |
| 67 | visibility: 'parent_guardian', durationMinutes: 30, dueAt: new Date(Date.now() + 86400000).toISOString(), |
| 68 | } }); |
| 69 | assert.equal(task.status, 201); |
| 70 | return { child, mother, father, outsider, familyId, task: task.body }; |
| 71 | } |
| 72 | const iso = (ms) => new Date(ms).toISOString(); |
| 73 | const mutationId = () => crypto.randomUUID(); |
| 74 | async function createSession(f, overrides = {}) { |
| 75 | return request('/v1/study/sessions', { method: 'POST', user: f.child, body: { |
| 76 | id: crypto.randomUUID(), mutationId: mutationId(), planItemId: f.task.id, |
| 77 | source: 'timer', startedAt: iso(Date.now() - 3600000), ...overrides, |
| 78 | } }); |
| 79 | } |
| 80 | async function event(f, session, action, occurredAt, overrides = {}) { |
| 81 | return request(`/v1/study/sessions/${session.id}/events`, { method: 'POST', user: f.child, body: { |
| 82 | mutationId: mutationId(), expectedVersion: session.version, action, occurredAt, ...overrides, |
| 83 | } }); |
| 84 | } |
| 85 | const reportPath = (f) => `/v1/families/${f.familyId}/children/${f.child.id}/learning-report`; |
| 86 | |
| 87 | test('real HTTP and independent PostgreSQL prove eight-step homework/study family slice across server restart', async () => { |
| 88 | const f = await fixture(); |
| 89 | const taskRow = await pool.query('select owner_user_id,title from plan_item where id=$1', [f.task.id]); |
| 90 | assert.equal(taskRow.rows[0].owner_user_id, f.child.id); |
| 91 | const motherBefore = await request(reportPath(f), { user: f.mother }); |
| 92 | assert.equal(motherBefore.status, 200); |
| 93 | assert.ok(motherBefore.body.items.some((x) => x.id === f.task.id)); |
| 94 | const startAt = Date.now() - 3600000; |
| 95 | const created = await createSession(f, { startedAt: iso(startAt) }); |
| 96 | assert.equal(created.status, 201); |
| 97 | const stopped = await event(f, created.body.session, 'stop', iso(startAt + 20 * 60000)); |
| 98 | assert.equal(stopped.status, 200); |
| 99 | assert.equal(stopped.body.session.recordedDurationSeconds, 1200); |
| 100 | assert.equal(stopped.body.session.isEvidenceOfStudy, false); |
| 101 | const report = await request(reportPath(f), { user: f.mother }); |
| 102 | assert.equal(report.status, 200); |
| 103 | assert.equal(report.body.metrics.recordedDurationSeconds, 1200); |
| 104 | assert.equal(report.body.metrics.plannedDurationSeconds, 1800); |
| 105 | assert.equal(report.body.recordingDisclaimerKey, 'recorded_time_is_not_proof_of_study'); |
| 106 | assert.ok(!JSON.stringify(report.body).includes('PRIVATE-NOTE-DO-NOT-REPORT')); |
| 107 | const complete = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.child, body: { |
| 108 | mutationId: mutationId(), expectedVersion: stopped.body.activity.version, state: 'completed', |
| 109 | occurredAt: iso(startAt + 21 * 60000), source: 'self_reported', |
| 110 | } }); |
| 111 | assert.equal(complete.status, 200); |
| 112 | const father = await request(reportPath(f), { user: f.father }); |
| 113 | assert.equal(father.body.items.find((x) => x.id === f.task.id).status, 'completed'); |
| 114 | assert.equal(father.body.items.find((x) => x.id === f.task.id).activityState, 'completed'); |
| 115 | assert.ok(father.body.asOf && father.body.lastSyncAt && father.body.sourceVersion); |
| 116 | await new Promise((resolve) => server.close(resolve)); |
| 117 | server = app.listen(0); |
| 118 | base = `http://127.0.0.1:${server.address().port}`; |
| 119 | for (const u of [f.child, f.mother, f.father]) { |
| 120 | const persisted = u === f.child |
| 121 | ? await request(`/v1/study/sessions/${created.body.session.id}`, { user: u }) |
| 122 | : await request(reportPath(f), { user: u }); |
| 123 | assert.equal(persisted.status, 200); |
| 124 | } |
| 125 | const rows = await pool.query('select status,recorded_duration_seconds from study_session where id=$1', [created.body.session.id]); |
| 126 | assert.deepEqual(rows.rows[0], { status: 'completed', recorded_duration_seconds: 1200 }); |
| 127 | }); |
| 128 | |
| 129 | test('pause/resume survives API restart and duration excludes pauses; duplicate offline retries and conflicts never add time twice', async () => { |
| 130 | const f = await fixture(); |
| 131 | const t = Date.now() - 3600000; |
| 132 | const createBody = { id: crypto.randomUUID(), mutationId: mutationId(), planItemId: f.task.id, source: 'timer', startedAt: iso(t) }; |
| 133 | const created = await request('/v1/study/sessions', { method: 'POST', user: f.child, body: createBody }); |
| 134 | assert.equal(created.status, 201); |
| 135 | const replay = await request('/v1/study/sessions', { method: 'POST', user: f.child, body: createBody }); |
| 136 | assert.equal(replay.body.acknowledgement.status, 'already_applied'); |
| 137 | const changedDuplicate = await request('/v1/study/sessions', { method: 'POST', user: f.child, body: { ...createBody, startedAt: iso(t - 1) } }); |
| 138 | assert.equal(changedDuplicate.status, 409); |
| 139 | const paused = await event(f, created.body.session, 'pause', iso(t + 10 * 60000)); |
| 140 | assert.equal(paused.status, 200); |
| 141 | assert.equal(paused.body.session.status, 'paused'); |
| 142 | const stale = await event(f, created.body.session, 'resume', iso(t + 20 * 60000)); |
| 143 | assert.equal(stale.status, 409); |
| 144 | assert.equal(stale.body.error, 'version_conflict'); |
| 145 | await new Promise((resolve) => server.close(resolve)); |
| 146 | server = app.listen(0); |
| 147 | base = `http://127.0.0.1:${server.address().port}`; |
| 148 | const persisted = await request(`/v1/study/sessions/${created.body.session.id}`, { user: f.child }); |
| 149 | assert.equal(persisted.body.session.status, 'paused'); |
| 150 | const resumed = await event(f, persisted.body.session, 'resume', iso(t + 20 * 60000)); |
| 151 | assert.equal(resumed.status, 200); |
| 152 | const stopBody = { mutationId: mutationId(), expectedVersion: resumed.body.session.version, action: 'stop', occurredAt: iso(t + 35 * 60000) }; |
| 153 | const stopped = await request(`/v1/study/sessions/${resumed.body.session.id}/events`, { method: 'POST', user: f.child, body: stopBody }); |
| 154 | assert.equal(stopped.body.session.recordedDurationSeconds, 1500); |
| 155 | const stoppedReplay = await request(`/v1/study/sessions/${resumed.body.session.id}/events`, { method: 'POST', user: f.child, body: stopBody }); |
| 156 | assert.equal(stoppedReplay.body.acknowledgement.status, 'already_applied'); |
| 157 | assert.equal(stoppedReplay.body.session.version, stopped.body.session.version); |
| 158 | const rows = await pool.query('select count(*)::int n,sum(extract(epoch from ends_at-starts_at))::int duration from study_interval where session_id=$1', [created.body.session.id]); |
| 159 | assert.deepEqual(rows.rows[0], { n: 2, duration: 1500 }); |
| 160 | const all = await request('/v1/study/sessions', { user: f.child }); |
| 161 | assert.equal(all.body.sessions.length, 1); |
| 162 | }); |
| 163 | |
| 164 | test('concurrent/overlapping study sessions are rejected and interval boundaries do not double count', async () => { |
| 165 | const f = await fixture(); |
| 166 | const t = Date.now() - 3600000; |
| 167 | const [a, b] = await Promise.all([createSession(f, { startedAt: iso(t) }), createSession(f, { startedAt: iso(t + 1000) })]); |
| 168 | assert.deepEqual([a.status, b.status].sort(), [201, 409]); |
| 169 | const running = (a.status === 201 ? a : b).body.session; |
| 170 | const stopped = await event(f, running, 'stop', iso(t + 600000)); |
| 171 | assert.equal(stopped.status, 200); |
| 172 | const overlap = await createSession(f, { source: 'self_reported', startedAt: iso(t + 300000), endedAt: iso(t + 900000) }); |
| 173 | assert.equal(overlap.status, 409); |
| 174 | assert.equal(overlap.body.error, 'study_time_overlap'); |
| 175 | const boundary = await createSession(f, { source: 'self_reported', startedAt: iso(t + 600000), endedAt: iso(t + 900000) }); |
| 176 | assert.equal(boundary.status, 201); |
| 177 | assert.equal(boundary.body.session.recordedDurationSeconds, 300); |
| 178 | assert.equal(boundary.body.session.source, 'self_reported'); |
| 179 | }); |
| 180 | |
| 181 | test('reports enforce current guardian roles, both memberships, family state, relations and sharing on every read', async () => { |
| 182 | const f = await fixture(); |
| 183 | assert.equal((await request(reportPath(f))).status, 401); |
| 184 | assert.equal((await request(reportPath(f), { user: f.outsider })).status, 403); |
| 185 | const s = await createSession(f); |
| 186 | assert.equal(s.status, 201); |
| 187 | for (const u of [f.mother, f.father, f.outsider]) { |
| 188 | assert.equal((await request(`/v1/study/sessions/${s.body.session.id}`, { user: u })).status, 404); |
| 189 | assert.equal((await request(`/v1/study/sessions/${s.body.session.id}/events`, { method: 'POST', user: u, |
| 190 | body: { mutationId: mutationId(), expectedVersion: 1, action: 'stop', occurredAt: iso(Date.now()) } })).status, 404); |
| 191 | } |
| 192 | await pool.query("update plan_item set visibility='private' where id=$1", [f.task.id]); |
| 193 | const privateReport = await request(reportPath(f), { user: f.mother }); |
| 194 | assert.equal(privateReport.status, 200); |
| 195 | assert.equal(privateReport.body.items.length, 0); |
| 196 | assert.equal(privateReport.body.metrics.recordedDurationSeconds, 0); |
| 197 | await pool.query("update plan_item set visibility='selected_members' where id=$1", [f.task.id]); |
| 198 | await pool.query("insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3)", [f.task.id, f.mother.id, f.child.id]); |
| 199 | assert.equal((await request(reportPath(f), { user: f.mother })).body.items.length, 1); |
| 200 | assert.equal((await request(reportPath(f), { user: f.father })).body.items.length, 0); |
| 201 | await pool.query("update family_membership set role='adult_member' where family_id=$1 and user_id=$2", [f.familyId, f.mother.id]); |
| 202 | assert.equal((await request(reportPath(f), { user: f.mother })).status, 403); |
| 203 | await pool.query("update family_membership set role='parent_guardian',ended_at=now() where family_id=$1 and user_id=$2", [f.familyId, f.mother.id]); |
| 204 | assert.equal((await request(reportPath(f), { user: f.mother })).status, 403); |
| 205 | await pool.query('update family_membership set ended_at=null where family_id=$1 and user_id=$2', [f.familyId, f.mother.id]); |
| 206 | await pool.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [f.familyId, f.mother.id]); |
| 207 | assert.equal((await request(reportPath(f), { user: f.mother })).status, 403); |
| 208 | await pool.query('update guardian_relationship set active=true where family_id=$1 and guardian_user_id=$2', [f.familyId, f.mother.id]); |
| 209 | await pool.query('update family_membership set ended_at=now() where family_id=$1 and user_id=$2', [f.familyId, f.child.id]); |
| 210 | assert.equal((await request(reportPath(f), { user: f.mother })).status, 403); |
| 211 | await pool.query('update family_membership set ended_at=null where family_id=$1 and user_id=$2', [f.familyId, f.child.id]); |
| 212 | await pool.query('update family_workspace set archived_at=now() where id=$1', [f.familyId]); |
| 213 | assert.equal((await request(reportPath(f), { user: f.mother })).status, 403); |
| 214 | }); |
| 215 | |
| 216 | test('activity completion remains self-reported until explicit authorized guardian confirmation; sessions archive safely', async () => { |
| 217 | const f = await fixture(); |
| 218 | const created = await createSession(f, { source: 'self_reported', startedAt: iso(Date.now() - 600000), endedAt: iso(Date.now() - 300000) }); |
| 219 | assert.equal(created.status, 201); |
| 220 | const complete = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.child, |
| 221 | body: { mutationId: mutationId(), expectedVersion: created.body.activity.version, state: 'completed', source: 'self_reported', occurredAt: iso(Date.now() - 200000) } }); |
| 222 | assert.equal(complete.status, 200); |
| 223 | assert.equal(complete.body.activity.state, 'completed'); |
| 224 | const body = { mutationId: mutationId(), expectedVersion: complete.body.activity.version, state: 'verified', source: 'guardian_confirmation', occurredAt: iso(Date.now() - 100000), confirmation: 'I confirm reviewing this homework.' }; |
| 225 | assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.child, body })).status, 403); |
| 226 | assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.outsider, body })).status, 403); |
| 227 | assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.mother, body: { ...body, confirmation: '' } })).status, 400); |
| 228 | const verified = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.mother, body }); |
| 229 | assert.equal(verified.status, 200); |
| 230 | assert.equal(verified.body.activity.state, 'verified'); |
| 231 | assert.equal(verified.body.activity.source, 'guardian_confirmation'); |
| 232 | assert.equal(verified.body.activity.confirmedBy, f.mother.id); |
| 233 | const archived = await request(`/v1/study/sessions/${created.body.session.id}`, { method: 'DELETE', user: f.child, |
| 234 | body: { mutationId: mutationId(), expectedVersion: created.body.session.version } }); |
| 235 | assert.equal(archived.status, 200); |
| 236 | assert.equal(archived.body.session.status, 'archived'); |
| 237 | assert.equal((await request('/v1/study/sessions', { user: f.child })).body.sessions.length, 0); |
| 238 | assert.equal((await request(reportPath(f), { user: f.mother })).body.metrics.recordedDurationSeconds, 0); |
| 239 | }); |
| 240 | |
| 241 | test('malformed IDs, forged owner, future/reversed timestamps, unknown source and client claimed duration fail closed', async () => { |
| 242 | const f = await fixture(); |
| 243 | assert.equal((await createSession(f, { id: 'broken' })).status, 400); |
| 244 | assert.equal((await createSession(f, { childId: f.outsider.id })).status, 403); |
| 245 | assert.equal((await createSession(f, { startedAt: iso(Date.now() + 3600000) })).status, 400); |
| 246 | assert.equal((await createSession(f, { source: 'proof_of_study' })).status, 400); |
| 247 | assert.equal((await createSession(f, { source: 'self_reported', startedAt: iso(Date.now() - 60000), endedAt: iso(Date.now() - 120000) })).status, 400); |
| 248 | assert.equal((await createSession(f, { recordedDurationSeconds: 999999 })).status, 400); |
| 249 | assert.equal((await request('/v1/study/sessions/not-a-uuid', { user: f.child })).status, 400); |
| 250 | assert.equal((await request(`${reportPath(f)}?from=broken`, { user: f.mother })).status, 400); |
| 251 | const expired = { ...f.child, token: jwt.sign({ sub: f.child.id, sid: f.child.sid, aud: 'lifemate-api' }, jwtSecret, { issuer: 'lifemate', expiresIn: -1 }) }; |
| 252 | assert.equal((await request('/v1/study/sessions', { user: expired })).status, 401); |
| 253 | }); |
| 254 | |
| 255 | test('guardian verification retries recheck current permission instead of replaying a revoked grant', async () => { |
| 256 | const f = await fixture(); |
| 257 | const body = { mutationId: mutationId(), expectedVersion: 0, state: 'completed', source: 'self_reported', occurredAt: iso(Date.now() - 10000) }; |
| 258 | const completed = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.child, body }); |
| 259 | assert.equal(completed.status, 200); |
| 260 | const confirmBody = { mutationId: mutationId(), expectedVersion: completed.body.activity.version, state: 'verified', source: 'guardian_confirmation', occurredAt: iso(Date.now()), confirmation: 'Synthetic reviewed homework.' }; |
| 261 | const confirmed = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.mother, body: confirmBody }); |
| 262 | assert.equal(confirmed.status, 200); |
| 263 | await pool.query('update guardian_relationship set active=false where family_id=$1 and guardian_user_id=$2', [f.familyId, f.mother.id]); |
| 264 | assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.mother, body: confirmBody })).status, 403); |
| 265 | }); |
| 266 | |
| 267 | test('report clips intervals at its boundaries and Tehran midnight and excludes outside-range time', async () => { |
| 268 | const f = await fixture(); |
| 269 | const day = new Date(Date.now() - 2 * 86400000).toISOString().slice(0, 10); |
| 270 | const t = new Date(`${day}T20:25:00.000Z`).getTime(); // 23:55 in Tehran |
| 271 | const created = await createSession(f, { source: 'self_reported', startedAt: iso(t), endedAt: iso(t + 20 * 60000) }); |
| 272 | assert.equal(created.status, 201); |
| 273 | const report = await request(`${reportPath(f)}?from=${encodeURIComponent(iso(t + 60000))}&to=${encodeURIComponent(iso(t + 16 * 60000))}`, { user: f.mother }); |
| 274 | assert.equal(report.status, 200); |
| 275 | assert.equal(report.body.metrics.recordedDurationSeconds, 900); |
| 276 | assert.deepEqual(report.body.daily.map((x) => x.recordedDurationSeconds), [240, 660]); |
| 277 | assert.equal(report.body.daily.reduce((total, x) => total + x.recordedDurationSeconds, 0), 900); |
| 278 | }); |
| 279 | |
| 280 | test('owner can correct a self-reported session with version checks and overlap validation; parent cannot edit it', async () => { |
| 281 | const f = await fixture(); |
| 282 | const t = Date.now() - 3600000; |
| 283 | const created = await createSession(f, { source: 'self_reported', startedAt: iso(t), endedAt: iso(t + 600000) }); |
| 284 | assert.equal(created.status, 201); |
| 285 | const body = { mutationId: mutationId(), expectedVersion: 1, startedAt: iso(t + 1000), endedAt: iso(t + 1201000) }; |
| 286 | assert.equal((await request(`/v1/study/sessions/${created.body.session.id}`, { method: 'PATCH', user: f.mother, body })).status, 404); |
| 287 | const corrected = await request(`/v1/study/sessions/${created.body.session.id}`, { method: 'PATCH', user: f.child, body }); |
| 288 | assert.equal(corrected.status, 200); |
| 289 | assert.equal(corrected.body.session.recordedDurationSeconds, 1200); |
| 290 | assert.equal(corrected.body.session.version, 2); |
| 291 | const stale = await request(`/v1/study/sessions/${created.body.session.id}`, { method: 'PATCH', user: f.child, body: { ...body, mutationId: mutationId() } }); |
| 292 | assert.equal(stale.status, 409); |
| 293 | const other = await createSession(f, { source: 'self_reported', startedAt: iso(t + 1800000), endedAt: iso(t + 2100000) }); |
| 294 | assert.equal(other.status, 201); |
| 295 | const overlap = await request(`/v1/study/sessions/${created.body.session.id}`, { method: 'PATCH', user: f.child, |
| 296 | body: { ...body, mutationId: mutationId(), expectedVersion: 2, endedAt: iso(t + 1900000) } }); |
| 297 | assert.equal(overlap.status, 409); |
| 298 | assert.equal(overlap.body.error, 'study_time_overlap'); |
| 299 | assert.equal((await request(`/v1/study/sessions/${created.body.session.id}`, { user: f.child })).body.session.recordedDurationSeconds, 1200); |
| 300 | }); |
| 301 | |
| 302 | test('owner and permitted guardian can read activity history but confirmation text and private records remain hidden', async () => { |
| 303 | const f = await fixture(); |
| 304 | const completed = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.child, body: { |
| 305 | mutationId: mutationId(), expectedVersion: 0, state: 'completed', source: 'self_reported', occurredAt: iso(Date.now() - 1000), |
| 306 | } }); |
| 307 | assert.equal(completed.status, 200); |
| 308 | const confirmed = await request(`/v1/plan-items/${f.task.id}/activity-state`, { method: 'POST', user: f.mother, body: { |
| 309 | mutationId: mutationId(), expectedVersion: completed.body.activity.version, state: 'verified', source: 'guardian_confirmation', occurredAt: iso(Date.now()), confirmation: 'PRIVATE-CONFIRMATION-CONTENT', |
| 310 | } }); |
| 311 | assert.equal(confirmed.status, 200); |
| 312 | const history = await request(`/v1/plan-items/${f.task.id}/activity-state`, { user: f.father }); |
| 313 | assert.equal(history.status, 200); |
| 314 | assert.deepEqual(history.body.history.map((x) => x.state), ['completed', 'verified']); |
| 315 | assert.equal(history.body.activity.state, 'verified'); |
| 316 | assert.ok(!JSON.stringify(history.body).includes('PRIVATE-CONFIRMATION-CONTENT')); |
| 317 | assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { user: f.outsider })).status, 403); |
| 318 | await pool.query("update plan_item set visibility='private' where id=$1", [f.task.id]); |
| 319 | assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { user: f.father })).status, 403); |
| 320 | assert.equal((await request(`/v1/plan-items/${f.task.id}/activity-state`, { user: f.child })).status, 200); |
| 321 | }); |
| 322 | |
| 323 | test('shared report preserves exact planned seconds rather than rounding through the legacy minutes column', async () => { |
| 324 | const f = await fixture(); |
| 325 | const precise = await request('/v1/plan-items', { method: 'POST', user: f.child, body: { |
| 326 | kind: 'assignment', title: 'زمان دقیق آزمایشی', familyId: f.familyId, visibility: 'parent_guardian', plannedDurationSeconds: 95, |
| 327 | } }); |
| 328 | assert.equal(precise.status, 201); |
| 329 | const report = await request(reportPath(f), { user: f.mother }); |
| 330 | assert.equal(report.status, 200); |
| 331 | assert.equal(report.body.items.find((x) => x.id === precise.body.id).plannedDurationSeconds, 95); |
| 332 | assert.equal(report.body.metrics.plannedDurationSeconds, 1895); |
| 333 | }); |