LifeMate — Personal, Family & Learning Companion

test/role-entry-apk
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 260 lines 9.35 KB
Raw
1 import test, { after } from 'node:test';
2 import assert from 'node:assert/strict';
3 import crypto from 'node:crypto';
4 import { app, pool } from '../src/server.js';
5
6 const server = app.listen(0);
7 const address = server.address();
8 const base = `http://127.0.0.1:${address.port}`;
9
10 after(async () => {
11 await new Promise((resolve) => server.close(resolve));
12 await pool.end();
13 });
14
15 async function request(path, { method='GET', body, token } = {}) {
16 const response = await fetch(base + path, {
17 method,
18 headers: {
19 'content-type': 'application/json',
20 ...(token ? { authorization: `Bearer ${token}` } : {}),
21 },
22 body: body === undefined ? undefined : JSON.stringify(body),
23 });
24 const text = await response.text();
25 return {
26 status: response.status,
27 body: text ? JSON.parse(text) : null,
28 };
29 }
30
31 async function registerVerified(email, displayName) {
32 const password = 'Phase3Pass!123';
33 const reg = await request('/v1/auth/register', {
34 method:'POST',
35 body:{ email, displayName, password },
36 });
37 assert.equal(reg.status,201);
38 assert.equal((await request('/v1/auth/verify-email',{
39 method:'POST', body:{ token:reg.body.verificationToken },
40 })).status,204);
41 const login = await request('/v1/auth/login',{
42 method:'POST', body:{ email, password },
43 });
44 assert.equal(login.status,200);
45 return { token:login.body.accessToken, userId:reg.body.userId, password };
46 }
47
48 test('phase 3 planner school family vertical slice', async () => {
49 const suffix = Date.now().toString(36);
50 const parent = await registerVerified(`p3-parent-${suffix}@example.test`,'Phase3 Parent');
51 const teen = await registerVerified(`p3-teen-${suffix}@example.test`,'Phase3 Teen');
52 const outsider = await registerVerified(`p3-outsider-${suffix}@example.test`,'Phase3 Outsider');
53
54 const family = await request('/v1/families',{
55 method:'POST', token:parent.token,
56 body:{ name:'Phase3 Family', role:'parent_guardian' },
57 });
58 assert.equal(family.status,201);
59
60 const invite = await request(`/v1/families/${family.body.id}/invitations`,{
61 method:'POST', token:parent.token,
62 body:{ email:`p3-teen-${suffix}@example.test`, role:'teen_minor', themePreference:'girl_pink' },
63 });
64 assert.equal(invite.status,201);
65 assert.equal((await request('/v1/invitations/accept',{
66 method:'POST', token:teen.token, body:{ token:invite.body.invitationToken },
67 })).status,204);
68
69 const members = await request(`/v1/families/${family.body.id}/members`,{token:parent.token});
70 const parentMember = members.body.members.find((x)=>x.user_id===parent.userId);
71 const teenMember = members.body.members.find((x)=>x.user_id===teen.userId);
72 assert.ok(parentMember && teenMember);
73
74 assert.equal((await request(`/v1/families/${family.body.id}/guardians`,{
75 method:'POST', token:parent.token,
76 body:{guardianUserId:parent.userId,minorUserId:teen.userId},
77 })).status,204);
78
79 const ctx = await request('/v1/life-contexts',{
80 method:'POST', token:teen.token,
81 body:{kind:'student',title:'مدرسه'},
82 });
83 assert.equal(ctx.status,201);
84
85 const year = await request('/v1/school/years',{
86 method:'POST', token:teen.token,
87 body:{
88 lifeContextId:ctx.body.id,
89 title:'سال تحصیلی ۱۴۰۵-۱۴۰۶',
90 startsOn:'2026-09-01',
91 endsOn:'2027-06-30',
92 },
93 });
94 assert.equal(year.status,201);
95
96 const term = await request(`/v1/school/years/${year.body.id}/terms`,{
97 method:'POST', token:teen.token,
98 body:{title:'نیمسال اول',startsOn:'2026-09-01',endsOn:'2027-01-31'},
99 });
100 assert.equal(term.status,201);
101
102 const subject = await request(`/v1/school/terms/${term.body.id}/subjects`,{
103 method:'POST', token:teen.token,
104 body:{name:'ریاضی',teacherName:'دبیر ریاضی',colorKey:'pink'},
105 });
106 assert.equal(subject.status,201);
107
108 const klass = await request(`/v1/school/subjects/${subject.body.id}/classes`,{
109 method:'POST', token:teen.token,
110 body:{weekday:2,startsAt:'08:00',endsAt:'09:30',location:'کلاس ۷'},
111 });
112 assert.equal(klass.status,201);
113
114 const due = new Date(Date.now()+60*60*1000).toISOString();
115 const assignment = await request('/v1/plan-items',{
116 method:'POST', token:teen.token,
117 body:{
118 kind:'assignment',
119 title:'تمرین فصل اول ریاضی',
120 subjectId:subject.body.id,
121 familyId:family.body.id,
122 visibility:'parent_guardian',
123 dueAt:due,
124 priority:'high',
125 durationMinutes:45,
126 reminderMinutesBefore:[30,10],
127 },
128 });
129 assert.equal(assignment.status,201);
130
131 const privateTask = await request('/v1/plan-items',{
132 method:'POST', token:teen.token,
133 body:{kind:'task',title:'کار شخصی',visibility:'private',dueAt:due},
134 });
135 assert.equal(privateTask.status,201);
136
137 const familyEvent = await request('/v1/plan-items',{
138 method:'POST', token:parent.token,
139 body:{
140 kind:'event', title:'شام خانوادگی', familyId:family.body.id,
141 visibility:'family', startsAt:due, reminderMinutesBefore:[15],
142 },
143 });
144 assert.equal(familyEvent.status,201);
145
146 const parentCalendar = await request(`/v1/families/${family.body.id}/calendar`,{token:parent.token});
147 assert.equal(parentCalendar.status,200);
148 assert.ok(parentCalendar.body.items.some((x)=>x.id===assignment.body.id));
149 assert.ok(parentCalendar.body.items.some((x)=>x.id===familyEvent.body.id));
150 assert.ok(!parentCalendar.body.items.some((x)=>x.id===privateTask.body.id));
151
152 const outsiderOverview = await request(`/v1/school/${teen.userId}/overview`,{token:outsider.token});
153 assert.equal(outsiderOverview.status,403);
154
155 const parentOverview = await request(`/v1/school/${teen.userId}/overview`,{token:parent.token});
156 assert.equal(parentOverview.status,200);
157 assert.equal(parentOverview.body.subjects.length,1);
158 assert.ok(parentOverview.body.workload.some((x)=>x.id===assignment.body.id));
159
160 const parentPrivateAttempt = await request('/v1/plan-items',{token:parent.token});
161 assert.equal(parentPrivateAttempt.status,200);
162 assert.ok(!parentPrivateAttempt.body.items.some((x)=>x.id===privateTask.body.id));
163
164 const grade = await request(`/v1/school/plan-items/${assignment.body.id}/grade`,{
165 method:'PATCH', token:teen.token, body:{points:18,outOf:20},
166 });
167 assert.equal(grade.status,200);
168
169 const support = await request(
170 `/v1/families/${family.body.id}/children/${teen.userId}/support-summary`,
171 {token:parent.token},
172 );
173 assert.equal(support.status,200);
174 assert.ok(Array.isArray(support.body.upcoming));
175 assert.equal(support.body.metrics.gradePercent,90);
176
177 const outsiderSupport = await request(
178 `/v1/families/${family.body.id}/children/${teen.userId}/support-summary`,
179 {token:outsider.token},
180 );
181 assert.equal(outsiderSupport.status,403);
182
183 const rescheduled = new Date(Date.now()+2*60*60*1000).toISOString();
184 const update = await request(`/v1/plan-items/${assignment.body.id}`,{
185 method:'PATCH', token:teen.token, body:{dueAt:rescheduled},
186 });
187 assert.equal(update.status,200);
188
189 const reminderRows = await pool.query(
190 'select minutes_before,status,scheduled_for from reminder where plan_item_id=$1 order by minutes_before',
191 [assignment.body.id],
192 );
193 assert.equal(reminderRows.rowCount,2);
194 assert.ok(reminderRows.rows.every((x)=>x.status==='scheduled'));
195
196 const completed = await request(`/v1/plan-items/${assignment.body.id}`,{
197 method:'PATCH', token:teen.token, body:{status:'completed'},
198 });
199 assert.equal(completed.status,200);
200 const cancelled = await pool.query(
201 "select count(*)::int as n from reminder where plan_item_id=$1 and status='cancelled'",
202 [assignment.body.id],
203 );
204 assert.equal(cancelled.rows[0].n,2);
205
206 const mutationId = crypto.randomUUID();
207 const sync1 = await request('/v1/sync/mutations',{
208 method:'POST', token:teen.token,
209 body:{mutations:[{
210 id:mutationId, entityType:'plan_item', entityId:privateTask.body.id,
211 operation:'reschedule', clientUpdatedAt:new Date().toISOString(),
212 payload:{dueAt:rescheduled},
213 }]},
214 });
215 assert.equal(sync1.status,200);
216 assert.equal(sync1.body.results[0].status,'accepted');
217
218 const syncedRow = await pool.query(
219 'select due_at from plan_item where id=$1',
220 [privateTask.body.id],
221 );
222 assert.equal(
223 new Date(syncedRow.rows[0].due_at).toISOString(),
224 new Date(rescheduled).toISOString(),
225 );
226
227 const sync2 = await request('/v1/sync/mutations',{
228 method:'POST', token:teen.token,
229 body:{mutations:[{
230 id:mutationId, entityType:'plan_item', entityId:privateTask.body.id,
231 operation:'reschedule', clientUpdatedAt:new Date().toISOString(),
232 payload:{dueAt:rescheduled},
233 }]},
234 });
235 assert.equal(sync2.body.results[0].status,'already_applied');
236
237 const reminderItem = await request('/v1/plan-items',{
238 method:'POST', token:teen.token,
239 body:{
240 kind:'task',
241 title:'یادآوری آزمایشی',
242 visibility:'private',
243 dueAt:new Date(Date.now()-60*1000).toISOString(),
244 reminderMinutesBefore:[0],
245 },
246 });
247 assert.equal(reminderItem.status,201);
248 const claimed = await request('/v1/reminders/claim-due',{
249 method:'POST', token:teen.token, body:{limit:10},
250 });
251 assert.equal(claimed.status,200);
252 assert.ok(claimed.body.claimed >= 1);
253 const notifications = await request('/v1/notification-outbox',{token:teen.token});
254 assert.equal(notifications.status,200);
255 assert.ok(
256 notifications.body.notifications.some(
257 (item)=>item.payload.planItemId===reminderItem.body.id,
258 ),
259 );
260 });