LifeMate — Personal, Family & Learning Companion

feat/private-planner-series-api
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 221 lines 16.2 KB
Raw
1 import crypto from 'node:crypto';
2
3 const kinds = new Set(['task', 'event', 'routine', 'goal', 'assignment', 'exam', 'study_session']);
4 const statuses = new Set(['planned', 'in_progress', 'completed', 'cancelled']);
5 const priorities = new Set(['low', 'normal', 'high', 'urgent']);
6 const scopes = new Set(['private', 'selected_members', 'parent_guardian', 'family']);
7 export const validUuid = (x) => typeof x === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(x);
8 export class PlanMutationError extends Error {
9 constructor(status, code, details = {}) { super(code); this.status = status; this.code = code; this.details = details; }
10 }
11 const fail = (status, code, details) => { throw new PlanMutationError(status, code, details); };
12 export function serializePlanItem(item, viewer) {
13 const result = { ...item, version: Number(item.version), activity_version: Number(item.activity_version) };
14 if (item.owner_user_id !== viewer) delete result.notes;
15 return result;
16 }
17 function canonical(value) {
18 if (Array.isArray(value)) return value.map(canonical);
19 if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
20 return value;
21 }
22 function date(value, field) {
23 if (value === null) return null;
24 if (typeof value !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,6})?(?:Z|[+-]\d\d:\d\d)$/.test(value)) fail(400, `invalid_${field}`);
25 const parsed = new Date(value);
26 if (!Number.isFinite(parsed.getTime())) fail(400, `invalid_${field}`);
27 const calendarDay = value.slice(0, 10), midnight = new Date(calendarDay + 'T00:00:00Z');
28 if (!Number.isFinite(midnight.getTime()) || midnight.toISOString().slice(0, 10) !== calendarDay
29 || !/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$/.test(value.slice(11, 19))) fail(400, `invalid_${field}`);
30 return parsed;
31 }
32 function text(value, field, max, nullable = false) {
33 if (nullable && value === null) return null;
34 if (typeof value !== 'string' || value.length > max || (!nullable && !value.trim())) fail(400, `invalid_${field}`);
35 return nullable ? value : value.trim();
36 }
37 function id(value, field) {
38 if (value === null) return null;
39 if (!validUuid(value)) fail(400, `invalid_${field}`);
40 return value;
41 }
42 function integer(value, field, min, max) {
43 if (value === null) return null;
44 if (!Number.isSafeInteger(value) || value < min || value > max) fail(400, `invalid_${field}`);
45 return value;
46 }
47 function normalize(payload, existing = null) {
48 if (!payload || typeof payload !== 'object' || Array.isArray(payload)) fail(400, 'invalid_plan_item');
49 for (const key of ['ownerUserId', 'owner_user_id', 'version', 'activity_version', 'created_at', 'updated_at', 'completed_at', 'seriesId', 'series_id', 'originalOccurrenceDate', 'original_occurrence_date']) if (key in payload) fail(400, 'server_owned_field');
50 const fields = {};
51 const isCreate = !existing;
52 const defaults = { kind: 'task', title: '', priority: 'normal', visibility: 'private', familyId: null, subjectId: null, learningUnitId: null,
53 notes: null, startsAt: null, endsAt: null, dueAt: null, durationMinutes: null, plannedDurationSeconds: null,
54 recurrenceRule: null, parentItemId: null };
55 const values = isCreate ? { ...defaults, ...payload } : payload;
56 const pick = (key, column, validation) => { if (values[key] !== undefined) fields[column] = validation(values[key]); };
57 pick('kind', 'kind', (x) => { if (!kinds.has(x)) fail(400, 'invalid_kind'); return x; });
58 pick('title', 'title', (x) => text(x, 'title', 240));
59 pick('notes', 'notes', (x) => text(x, 'notes', 10000, true));
60 pick('priority', 'priority', (x) => { if (!priorities.has(x)) fail(400, 'invalid_priority'); return x; });
61 pick('visibility', 'visibility', (x) => { if (!scopes.has(x)) fail(400, 'invalid_visibility'); return x; });
62 pick('status', 'status', (x) => { if (!statuses.has(x) || (isCreate && x !== 'planned')) fail(400, 'invalid_status'); return x; });
63 pick('familyId', 'family_id', (x) => id(x, 'family_id'));
64 pick('subjectId', 'subject_id', (x) => id(x, 'subject_id'));
65 pick('learningUnitId', 'learning_unit_id', (x) => id(x, 'learning_unit_id'));
66 pick('parentItemId', 'parent_item_id', (x) => id(x, 'parent_item_id'));
67 pick('startsAt', 'starts_at', (x) => date(x, 'starts_at'));
68 pick('endsAt', 'ends_at', (x) => date(x, 'ends_at'));
69 pick('dueAt', 'due_at', (x) => date(x, 'due_at'));
70 pick('recurrenceRule', 'recurrence_rule', (x) => text(x, 'recurrence_rule', 1000, true));
71 pick('durationMinutes', 'duration_minutes', (x) => integer(x, 'duration_minutes', 1, 1440));
72 pick('plannedDurationSeconds', 'planned_duration_seconds', (x) => integer(x, 'planned_duration_seconds', 0, 86400));
73 for (const [key, column] of [['gradePoints', 'grade_points'], ['gradeOutOf', 'grade_out_of']]) pick(key, column, (x) => {
74 if (x === null) return null;
75 if (typeof x !== 'number' || !Number.isFinite(x) || x < 0 || x > 999999.99) fail(400, 'invalid_grade');
76 return x;
77 });
78 if (payload.plannedDurationSeconds !== undefined) fields.duration_minutes = payload.plannedDurationSeconds == null || payload.plannedDurationSeconds === 0 ? null : Math.ceil(payload.plannedDurationSeconds / 60);
79 else if (payload.durationMinutes !== undefined) fields.planned_duration_seconds = payload.durationMinutes == null ? null : payload.durationMinutes * 60;
80 const merged = { ...existing, ...fields };
81 if (fields.grade_points !== undefined || fields.grade_out_of !== undefined) {
82 if (!['assignment', 'exam'].includes(merged.kind)) fail(400, 'grade_not_applicable');
83 if (!(merged.grade_points == null && merged.grade_out_of == null)
84 && (merged.grade_points == null || merged.grade_out_of == null || Number(merged.grade_out_of) <= 0 || Number(merged.grade_points) > Number(merged.grade_out_of))) fail(400, 'invalid_grade');
85 }
86 if (merged.starts_at && merged.due_at && new Date(merged.due_at) < new Date(merged.starts_at)) fail(400, 'invalid_date_order');
87 if (merged.ends_at && (!merged.starts_at || new Date(merged.ends_at) <= new Date(merged.starts_at))) fail(400, 'invalid_end_order');
88 if (merged.series_id && (merged.visibility !== 'private' || merged.family_id !== null)) fail(400, 'planner_occurrence_private');
89 if (['family', 'parent_guardian', 'selected_members'].includes(merged.visibility) && !merged.family_id) fail(400, 'family_required_for_visibility');
90 return { fields, merged };
91 }
92 export async function planOwnerLock(client, userId) {
93 await client.query('select pg_advisory_xact_lock(hashtextextended($1::text,0))', [userId]);
94 }
95 async function authorize(client, userId, item) {
96 if (!(await client.query('select 1 from app_user where id=$1 and disabled_at is null', [userId])).rowCount) fail(401, 'unauthorized');
97 if (item && item.owner_user_id !== userId) fail(403, 'forbidden');
98 if (item?.family_id && !(await client.query('select 1 where is_active_family_member($1,$2)', [item.family_id, userId])).rowCount) fail(403, 'family_membership_required');
99 }
100 async function relations(client, userId, item, payload, existing = null) {
101 await authorize(client, userId, item);
102 if (item.learning_unit_id && !(await client.query('select 1 from learning_unit where id=$1 and active', [item.learning_unit_id])).rowCount) fail(400, 'invalid_learning_unit_id');
103 if (item.subject_id && !(await client.query('select 1 from subject where id=$1 and student_user_id=$2', [item.subject_id, userId])).rowCount) fail(403, 'subject_forbidden');
104 if (item.parent_item_id && !(await client.query('select 1 from plan_item where id=$1 and owner_user_id=$2', [item.parent_item_id, userId])).rowCount) fail(403, 'parent_item_forbidden');
105 if (payload.selectedMemberIds !== undefined && (!Array.isArray(payload.selectedMemberIds) || payload.selectedMemberIds.length > 100)) fail(400, 'invalid_selected_members');
106 const selected = payload.selectedMemberIds === undefined ? null : [...new Set(payload.selectedMemberIds)];
107 if (item.visibility === 'selected_members' && (!existing || existing.visibility !== 'selected_members' || existing.family_id !== item.family_id) && (!selected || !selected.length)) fail(400, 'selected_members_required');
108 if (selected) for (const member of selected) {
109 if (!validUuid(member) || !(await client.query('select 1 where is_active_family_member($1,$2)', [item.family_id, member])).rowCount) fail(400, 'selected_member_not_in_family');
110 }
111 return selected;
112 }
113 async function grants(client, item, selected) {
114 if (selected !== null || item.visibility !== 'selected_members') await client.query("delete from sharing_grant where resource_type='plan_item' and resource_id=$1", [item.id]);
115 if (item.visibility === 'selected_members' && selected) for (const member of selected) await client.query(
116 "insert into sharing_grant(resource_type,resource_id,grantee_user_id,granted_by) values('plan_item',$1,$2,$3)", [item.id, member, item.owner_user_id],
117 );
118 }
119 async function reminders(client, item, payload, previous = null) {
120 if (payload.reminderMinutesBefore !== undefined) {
121 if (!Array.isArray(payload.reminderMinutesBefore) || payload.reminderMinutesBefore.length > 100 || payload.reminderMinutesBefore.some((x) => !Number.isSafeInteger(x) || x < 0 || x > 10080)) fail(400, 'invalid_reminders');
122 await client.query('delete from reminder where plan_item_id=$1', [item.id]);
123 const base = item.starts_at ?? item.due_at;
124 if (base) for (const minutes of new Set(payload.reminderMinutesBefore)) await client.query(
125 'insert into reminder(plan_item_id,owner_user_id,minutes_before,scheduled_for) values($1,$2,$3,$4::timestamptz-make_interval(mins=>$3))', [item.id, item.owner_user_id, minutes, base],
126 );
127 }
128 if (['completed', 'cancelled'].includes(item.status)) await client.query("update reminder set status='cancelled' where plan_item_id=$1 and status in ('scheduled','claimed')", [item.id]);
129 else {
130 // Undo before the next scheduled alert restores only this occurrence's
131 // existing choices, never an already-past alert or another day's row.
132 if (previous && ['completed','cancelled'].includes(previous.status)
133 && payload.reminderMinutesBefore === undefined) {
134 await client.query(`update reminder set status='scheduled',claimed_at=null,
135 delivered_at=null,failure_reason=null where plan_item_id=$1 and status='cancelled'
136 and coalesce($2::timestamptz,$3::timestamptz)-make_interval(mins=>minutes_before)>now()`,
137 [item.id,item.starts_at,item.due_at]);
138 }
139 await client.query('select recompute_reminder_schedule($1)', [item.id]);
140 }
141 }
142 export async function createPlanItem(client, userId, payload, itemId = crypto.randomUUID(), occurrence = null) {
143 if (!validUuid(itemId)) fail(400, 'invalid_id');
144 const { fields } = normalize(payload);
145 // Only the server generator supplies this argument; payloads cannot assign
146 // or alter the immutable series/date identity.
147 if (occurrence) { fields.series_id = occurrence.seriesId; fields.original_occurrence_date = occurrence.date; }
148 const selected = await relations(client, userId, { ...fields, owner_user_id: userId }, payload);
149 const columns = ['id', 'owner_user_id', ...Object.keys(fields)];
150 const values = [itemId, userId, ...Object.values(fields)];
151 const row = (await client.query(`insert into plan_item(${columns.join(',')}) values(${values.map((_, i) => `$${i + 1}`).join(',')}) returning *`, values)).rows[0];
152 await grants(client, row, selected);
153 await reminders(client, row, payload);
154 return row;
155 }
156 export async function updatePlanItem(client, userId, itemId, payload, expectedVersion) {
157 if (!validUuid(itemId)) fail(400, 'invalid_id');
158 const current = (await client.query('select * from plan_item where id=$1 for update', [itemId])).rows[0];
159 if (!current) fail(404, 'not_found');
160 await authorize(client, userId, current);
161 if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0) fail(400, 'expected_version_required');
162 if (expectedVersion !== Number(current.version)) fail(409, 'version_conflict', { serverVersion: Number(current.version) });
163 const { fields, merged } = normalize(payload, current);
164 if (!Object.keys(fields).length && payload.selectedMemberIds === undefined && payload.reminderMinutesBefore === undefined) fail(400, 'no_changes');
165 const selected = await relations(client, userId, merged, payload, current);
166 if (fields.status !== undefined) fields.completed_at = fields.status === 'completed' ? current.completed_at ?? new Date() : null;
167 const values = [itemId, ...Object.values(fields)];
168 const update = [...Object.keys(fields).map((key, i) => `${key}=$${i + 2}`), 'updated_at=now()'];
169 const item = (await client.query(`update plan_item set ${update.join(',')} where id=$1 returning *`, values)).rows[0];
170 await grants(client, item, selected);
171 await reminders(client, item, payload, current);
172 return item;
173 }
174 export async function planTransaction(pool, userId, execute) {
175 const client = await pool.connect();
176 try { await client.query('begin'); await planOwnerLock(client, userId); const result = await execute(client); await client.query('commit'); return result; }
177 catch (error) { await client.query('rollback').catch(() => {}); if (error.code === '23505') fail(409, 'plan_item_exists'); throw error; }
178 finally { client.release(); }
179 }
180 export async function applyPlanMutation(pool, userId, mutation) {
181 const idValue = mutation?.id;
182 try {
183 if (!validUuid(idValue) || mutation.entityType !== 'plan_item' || !validUuid(mutation.entityId)
184 || !['create', 'update', 'complete', 'reschedule', 'archive'].includes(mutation.operation)
185 || !mutation.payload || typeof mutation.payload !== 'object' || Array.isArray(mutation.payload)) fail(400, 'invalid_mutation');
186 const hash = crypto.createHash('sha256').update(JSON.stringify(canonical({ entityType: mutation.entityType, entityId: mutation.entityId, operation: mutation.operation, expectedVersion: mutation.expectedVersion ?? null, payload: mutation.payload }))).digest('hex');
187 return await planTransaction(pool, userId, async (client) => {
188 const previous = (await client.query('select * from sync_mutation where user_id=$1 and id=$2', [userId, idValue])).rows[0];
189 if (previous) {
190 const current = (await client.query('select * from plan_item where id=$1', [previous.entity_id])).rows[0];
191 if (!current) fail(404, 'not_found');
192 await authorize(client, userId, current);
193 if (previous.request_hash !== hash || !previous.canonical_item) fail(409, 'mutation_id_reused', { serverVersion: Number(current.version) });
194 return { id: idValue, entityId: previous.entity_id, status: 'already_applied', acceptedAt: previous.accepted_at, item: previous.canonical_item };
195 }
196 let item;
197 if (mutation.operation === 'create') {
198 if (mutation.expectedVersion !== undefined && mutation.expectedVersion !== 0) fail(400, 'create_expected_version_zero');
199 if (mutation.payload.id !== undefined && mutation.payload.id !== mutation.entityId) fail(400, 'entity_id_mismatch');
200 item = await createPlanItem(client, userId, mutation.payload, mutation.entityId);
201 } else {
202 const payload = { ...mutation.payload };
203 if (mutation.operation === 'complete') payload.status = 'completed';
204 if (mutation.operation === 'archive') payload.status = 'cancelled';
205 if (mutation.operation === 'reschedule' && payload.dueAt === undefined && payload.startsAt === undefined) fail(400, 'invalid_reschedule');
206 item = await updatePlanItem(client, userId, mutation.entityId, payload, mutation.expectedVersion);
207 }
208 const canonicalItem = serializePlanItem(item, userId);
209 const accepted = (await client.query(
210 `insert into sync_mutation(id,user_id,entity_type,entity_id,operation,client_updated_at,payload,request_hash,canonical_item)
211 values($1,$2,'plan_item',$3,$4,now(),$5::jsonb,$6,$7::jsonb) returning accepted_at`,
212 [idValue, userId, item.id, mutation.operation, JSON.stringify(mutation.payload), hash, JSON.stringify(canonicalItem)],
213 )).rows[0].accepted_at;
214 return { id: idValue, entityId: item.id, status: 'accepted', acceptedAt: accepted, item: canonicalItem };
215 });
216 } catch (error) {
217 if (!(error instanceof PlanMutationError)) throw error;
218 return { id: idValue ?? null, entityId: mutation?.entityId ?? null,
219 status: error.status === 409 ? 'conflict' : 'rejected', error: error.code, httpStatus: error.status, ...error.details };
220 }
221 }