@davoodmehraban89 / LifeMate / commits / 2887d4a
Fork 0

LifeMate — Personal, Family & Learning Companion

feat(qa): reviewable atomic private schema migration from original 0001-0010

davoodmehraban89 committed Oct 15, 2026 at 01:24 UTC 2887d4a2203475ab5a821d8425c8c4e40c2e1fcd
1 file changed +1520
supabase/migrations/202610150001_lifeguide_qa_app_schema_0001_0010.sql new
+1520
@@ -0,0 +1,1520 @@
1 +begin;
2 +set local lock_timeout='5s';
3 +set local statement_timeout='120s';
4 +set local search_path=lifeguide_qa,extensions,pg_catalog;
5 +do $preflight$ begin
6 + if current_database()<>'postgres' or to_regnamespace('lifeguide_qa') is null
7 + or to_regclass('lifeguide_qa.setup_probe') is null
8 + or not exists(select 1 from pg_extension where extname='pgcrypto')
9 + or has_schema_privilege('anon','lifeguide_qa','USAGE')
10 + or has_schema_privilege('authenticated','lifeguide_qa','USAGE')
11 + then raise exception 'lifeguide_qa_preflight_denied'; end if;
12 +end $preflight$;
13 +create table if not exists lifeguide_qa.schema_migration (
14 + filename text primary key,
15 + sha256 text not null check (sha256 ~ '^[a-f0-9]{64}$'),
16 + applied_at timestamptz not null default now()
17 +);
18 +-- Original LifeGuide migration 0001_identity_family.sql
19 +
20 +
21 +-- existing pgcrypto is untouched
22 +
23 +create type member_role as enum ('parent_guardian','teen_minor','adult_member');
24 +create type invitation_status as enum ('pending','accepted','revoked','expired');
25 +create type visibility_scope as enum ('private','selected_members','parent_guardian','family','safety_controlled');
26 +
27 +create table app_user (
28 + id uuid primary key default gen_random_uuid(),
29 + identity_subject text not null unique,
30 + email_normalized text not null unique check (email_normalized = lower(email_normalized)),
31 + email_verified_at timestamptz,
32 + created_at timestamptz not null default now(),
33 + disabled_at timestamptz
34 +);
35 +
36 +create table profile (
37 + user_id uuid primary key references app_user(id) on delete cascade,
38 + display_name text not null check (char_length(display_name) between 1 and 100),
39 + birth_date date,
40 + theme_preference text check (theme_preference in ('girl_pink','boy_blue','adult_blue','custom')),
41 + updated_at timestamptz not null default now()
42 +);
43 +
44 +create table family_workspace (
45 + id uuid primary key default gen_random_uuid(),
46 + name text not null check (char_length(name) between 1 and 120),
47 + created_by uuid not null references app_user(id),
48 + created_at timestamptz not null default now(),
49 + archived_at timestamptz
50 +);
51 +
52 +create table family_membership (
53 + family_id uuid not null references family_workspace(id) on delete cascade,
54 + user_id uuid not null references app_user(id) on delete cascade,
55 + role member_role not null,
56 + is_admin boolean not null default false,
57 + joined_at timestamptz not null default now(),
58 + ended_at timestamptz,
59 + primary key (family_id, user_id)
60 +);
61 +
62 +create table guardian_relationship (
63 + family_id uuid not null,
64 + guardian_user_id uuid not null,
65 + minor_user_id uuid not null,
66 + active boolean not null default true,
67 + created_at timestamptz not null default now(),
68 + primary key (family_id, guardian_user_id, minor_user_id),
69 + foreign key (family_id, guardian_user_id) references family_membership(family_id, user_id) on delete cascade,
70 + foreign key (family_id, minor_user_id) references family_membership(family_id, user_id) on delete cascade,
71 + check (guardian_user_id <> minor_user_id)
72 +);
73 +
74 +create table family_invitation (
75 + id uuid primary key default gen_random_uuid(),
76 + family_id uuid not null references family_workspace(id) on delete cascade,
77 + invited_email_normalized text not null check (invited_email_normalized = lower(invited_email_normalized)),
78 + intended_role member_role not null,
79 + intended_theme text check (intended_theme in ('girl_pink','boy_blue','adult_blue','custom')),
80 + token_digest text not null unique,
81 + status invitation_status not null default 'pending',
82 + invited_by uuid not null references app_user(id),
83 + expires_at timestamptz not null,
84 + accepted_by uuid references app_user(id),
85 + created_at timestamptz not null default now(),
86 + accepted_at timestamptz,
87 + check (expires_at > created_at)
88 +);
89 +
90 +create table access_audit (
91 + id bigint generated always as identity primary key,
92 + actor_user_id uuid references app_user(id),
93 + family_id uuid references family_workspace(id),
94 + action text not null,
95 + target_type text not null,
96 + target_id text,
97 + occurred_at timestamptz not null default now(),
98 + metadata jsonb not null default '{}'::jsonb
99 +);
100 +
101 +create index family_membership_user_idx on family_membership(user_id) where ended_at is null;
102 +create index family_membership_admin_idx on family_membership(family_id, is_admin) where ended_at is null and is_admin;
103 +create index family_invitation_pending_idx on family_invitation(family_id, invited_email_normalized) where status = 'pending';
104 +create index access_audit_family_time_idx on access_audit(family_id, occurred_at desc);
105 +
106 +create function is_active_family_member(p_family uuid, p_user uuid) returns boolean
107 +language sql stable as $$
108 + select exists(
109 + select 1 from family_membership m
110 + where m.family_id=p_family and m.user_id=p_user and m.ended_at is null
111 + )
112 +$$;
113 +
114 +create function is_family_admin(p_family uuid, p_user uuid) returns boolean
115 +language sql stable as $$
116 + select exists(
117 + select 1 from family_membership m
118 + where m.family_id=p_family and m.user_id=p_user and m.ended_at is null and m.is_admin
119 + )
120 +$$;
121 +
122 +create function is_active_guardian(p_family uuid, p_guardian uuid, p_minor uuid) returns boolean
123 +language sql stable as $$
124 + select exists(
125 + select 1 from guardian_relationship g
126 + join family_membership gm
127 + on gm.family_id=g.family_id
128 + and gm.user_id=g.guardian_user_id
129 + and gm.ended_at is null
130 + and gm.role='parent_guardian'
131 + join family_membership mm
132 + on mm.family_id=g.family_id
133 + and mm.user_id=g.minor_user_id
134 + and mm.ended_at is null
135 + and mm.role='teen_minor'
136 + where g.family_id=p_family
137 + and g.guardian_user_id=p_guardian
138 + and g.minor_user_id=p_minor
139 + and g.active
140 + )
141 +$$;
142 +
143 +
144 +insert into lifeguide_qa.schema_migration(filename,sha256)
145 +values ('0001_identity_family.sql',encode(digest(convert_to($qa_original_0001$begin;
146 +
147 +create extension if not exists pgcrypto;
148 +
149 +create type member_role as enum ('parent_guardian','teen_minor','adult_member');
150 +create type invitation_status as enum ('pending','accepted','revoked','expired');
151 +create type visibility_scope as enum ('private','selected_members','parent_guardian','family','safety_controlled');
152 +
153 +create table app_user (
154 + id uuid primary key default gen_random_uuid(),
155 + identity_subject text not null unique,
156 + email_normalized text not null unique check (email_normalized = lower(email_normalized)),
157 + email_verified_at timestamptz,
158 + created_at timestamptz not null default now(),
159 + disabled_at timestamptz
160 +);
161 +
162 +create table profile (
163 + user_id uuid primary key references app_user(id) on delete cascade,
164 + display_name text not null check (char_length(display_name) between 1 and 100),
165 + birth_date date,
166 + theme_preference text check (theme_preference in ('girl_pink','boy_blue','adult_blue','custom')),
167 + updated_at timestamptz not null default now()
168 +);
169 +
170 +create table family_workspace (
171 + id uuid primary key default gen_random_uuid(),
172 + name text not null check (char_length(name) between 1 and 120),
173 + created_by uuid not null references app_user(id),
174 + created_at timestamptz not null default now(),
175 + archived_at timestamptz
176 +);
177 +
178 +create table family_membership (
179 + family_id uuid not null references family_workspace(id) on delete cascade,
180 + user_id uuid not null references app_user(id) on delete cascade,
181 + role member_role not null,
182 + is_admin boolean not null default false,
183 + joined_at timestamptz not null default now(),
184 + ended_at timestamptz,
185 + primary key (family_id, user_id)
186 +);
187 +
188 +create table guardian_relationship (
189 + family_id uuid not null,
190 + guardian_user_id uuid not null,
191 + minor_user_id uuid not null,
192 + active boolean not null default true,
193 + created_at timestamptz not null default now(),
194 + primary key (family_id, guardian_user_id, minor_user_id),
195 + foreign key (family_id, guardian_user_id) references family_membership(family_id, user_id) on delete cascade,
196 + foreign key (family_id, minor_user_id) references family_membership(family_id, user_id) on delete cascade,
197 + check (guardian_user_id <> minor_user_id)
198 +);
199 +
200 +create table family_invitation (
201 + id uuid primary key default gen_random_uuid(),
202 + family_id uuid not null references family_workspace(id) on delete cascade,
203 + invited_email_normalized text not null check (invited_email_normalized = lower(invited_email_normalized)),
204 + intended_role member_role not null,
205 + intended_theme text check (intended_theme in ('girl_pink','boy_blue','adult_blue','custom')),
206 + token_digest text not null unique,
207 + status invitation_status not null default 'pending',
208 + invited_by uuid not null references app_user(id),
209 + expires_at timestamptz not null,
210 + accepted_by uuid references app_user(id),
211 + created_at timestamptz not null default now(),
212 + accepted_at timestamptz,
213 + check (expires_at > created_at)
214 +);
215 +
216 +create table access_audit (
217 + id bigint generated always as identity primary key,
218 + actor_user_id uuid references app_user(id),
219 + family_id uuid references family_workspace(id),
220 + action text not null,
221 + target_type text not null,
222 + target_id text,
223 + occurred_at timestamptz not null default now(),
224 + metadata jsonb not null default '{}'::jsonb
225 +);
226 +
227 +create index family_membership_user_idx on family_membership(user_id) where ended_at is null;
228 +create index family_membership_admin_idx on family_membership(family_id, is_admin) where ended_at is null and is_admin;
229 +create index family_invitation_pending_idx on family_invitation(family_id, invited_email_normalized) where status = 'pending';
230 +create index access_audit_family_time_idx on access_audit(family_id, occurred_at desc);
231 +
232 +create function is_active_family_member(p_family uuid, p_user uuid) returns boolean
233 +language sql stable as $$
234 + select exists(
235 + select 1 from family_membership m
236 + where m.family_id=p_family and m.user_id=p_user and m.ended_at is null
237 + )
238 +$$;
239 +
240 +create function is_family_admin(p_family uuid, p_user uuid) returns boolean
241 +language sql stable as $$
242 + select exists(
243 + select 1 from family_membership m
244 + where m.family_id=p_family and m.user_id=p_user and m.ended_at is null and m.is_admin
245 + )
246 +$$;
247 +
248 +create function is_active_guardian(p_family uuid, p_guardian uuid, p_minor uuid) returns boolean
249 +language sql stable as $$
250 + select exists(
251 + select 1 from guardian_relationship g
252 + join family_membership gm
253 + on gm.family_id=g.family_id
254 + and gm.user_id=g.guardian_user_id
255 + and gm.ended_at is null
256 + and gm.role='parent_guardian'
257 + join family_membership mm
258 + on mm.family_id=g.family_id
259 + and mm.user_id=g.minor_user_id
260 + and mm.ended_at is null
261 + and mm.role='teen_minor'
262 + where g.family_id=p_family
263 + and g.guardian_user_id=p_guardian
264 + and g.minor_user_id=p_minor
265 + and g.active
266 + )
267 +$$;
268 +
269 +commit;
270 +$qa_original_0001$,'UTF8'),'sha256'),'hex'));
271 +-- Original LifeGuide migration 0002_auth.sql
272 +
273 +
274 +create table auth_credential (
275 + user_id uuid primary key references app_user(id) on delete cascade,
276 + password_hash text not null,
277 + password_changed_at timestamptz not null default now(),
278 + failed_attempts integer not null default 0 check (failed_attempts >= 0),
279 + locked_until timestamptz
280 +);
281 +
282 +create type auth_token_kind as enum ('email_verification','password_reset');
283 +create table auth_token (
284 + id uuid primary key default gen_random_uuid(),
285 + user_id uuid not null references app_user(id) on delete cascade,
286 + kind auth_token_kind not null,
287 + token_digest text not null unique,
288 + expires_at timestamptz not null,
289 + used_at timestamptz,
290 + created_at timestamptz not null default now(),
291 + check (expires_at > created_at)
292 +);
293 +create index auth_token_active_idx on auth_token(user_id, kind, expires_at) where used_at is null;
294 +
295 +create table auth_session (
296 + id uuid primary key default gen_random_uuid(),
297 + user_id uuid not null references app_user(id) on delete cascade,
298 + refresh_digest text not null unique,
299 + expires_at timestamptz not null,
300 + revoked_at timestamptz,
301 + created_at timestamptz not null default now(),
302 + last_seen_at timestamptz not null default now()
303 +);
304 +create index auth_session_user_active_idx on auth_session(user_id, expires_at) where revoked_at is null;
305 +
306 +
307 +insert into lifeguide_qa.schema_migration(filename,sha256)
308 +values ('0002_auth.sql',encode(digest(convert_to($qa_original_0002$begin;
309 +
310 +create table auth_credential (
311 + user_id uuid primary key references app_user(id) on delete cascade,
312 + password_hash text not null,
313 + password_changed_at timestamptz not null default now(),
314 + failed_attempts integer not null default 0 check (failed_attempts >= 0),
315 + locked_until timestamptz
316 +);
317 +
318 +create type auth_token_kind as enum ('email_verification','password_reset');
319 +create table auth_token (
320 + id uuid primary key default gen_random_uuid(),
321 + user_id uuid not null references app_user(id) on delete cascade,
322 + kind auth_token_kind not null,
323 + token_digest text not null unique,
324 + expires_at timestamptz not null,
325 + used_at timestamptz,
326 + created_at timestamptz not null default now(),
327 + check (expires_at > created_at)
328 +);
329 +create index auth_token_active_idx on auth_token(user_id, kind, expires_at) where used_at is null;
330 +
331 +create table auth_session (
332 + id uuid primary key default gen_random_uuid(),
333 + user_id uuid not null references app_user(id) on delete cascade,
334 + refresh_digest text not null unique,
335 + expires_at timestamptz not null,
336 + revoked_at timestamptz,
337 + created_at timestamptz not null default now(),
338 + last_seen_at timestamptz not null default now()
339 +);
340 +create index auth_session_user_active_idx on auth_session(user_id, expires_at) where revoked_at is null;
341 +
342 +commit;
343 +$qa_original_0002$,'UTF8'),'sha256'),'hex'));
344 +-- Original LifeGuide migration 0003_planner_school_family.sql
345 +
346 +
347 +create type life_context_kind as enum ('student','work','personal');
348 +create type plan_item_kind as enum ('task','event','routine','goal','assignment','exam','study_session');
349 +create type plan_item_status as enum ('planned','in_progress','completed','cancelled');
350 +create type plan_priority as enum ('low','normal','high','urgent');
351 +create type sharing_scope as enum ('private','selected_members','parent_guardian','family');
352 +create type reminder_status as enum ('scheduled','claimed','sent','cancelled','failed');
353 +
354 +create table life_context (
355 + id uuid primary key default gen_random_uuid(),
356 + user_id uuid not null references app_user(id) on delete cascade,
357 + kind life_context_kind not null,
358 + title text not null check (char_length(title) between 1 and 120),
359 + active boolean not null default true,
360 + created_at timestamptz not null default now()
361 +);
362 +create index life_context_user_idx on life_context(user_id) where active;
363 +
364 +create table academic_year (
365 + id uuid primary key default gen_random_uuid(),
366 + student_user_id uuid not null references app_user(id) on delete cascade,
367 + life_context_id uuid not null references life_context(id) on delete cascade,
368 + title text not null,
369 + starts_on date not null,
370 + ends_on date not null,
371 + active boolean not null default true,
372 + created_at timestamptz not null default now(),
373 + check (ends_on >= starts_on)
374 +);
375 +create index academic_year_student_idx on academic_year(student_user_id, starts_on desc);
376 +
377 +create table academic_term (
378 + id uuid primary key default gen_random_uuid(),
379 + academic_year_id uuid not null references academic_year(id) on delete cascade,
380 + title text not null,
381 + starts_on date not null,
382 + ends_on date not null,
383 + created_at timestamptz not null default now(),
384 + check (ends_on >= starts_on)
385 +);
386 +
387 +create table subject (
388 + id uuid primary key default gen_random_uuid(),
389 + student_user_id uuid not null references app_user(id) on delete cascade,
390 + academic_term_id uuid not null references academic_term(id) on delete cascade,
391 + name text not null check (char_length(name) between 1 and 120),
392 + teacher_name text,
393 + color_key text,
394 + created_at timestamptz not null default now()
395 +);
396 +create index subject_student_term_idx on subject(student_user_id, academic_term_id);
397 +
398 +create table class_session (
399 + id uuid primary key default gen_random_uuid(),
400 + subject_id uuid not null references subject(id) on delete cascade,
401 + weekday smallint not null check (weekday between 1 and 7),
402 + starts_at time not null,
403 + ends_at time not null,
404 + location text,
405 + recurrence_until date,
406 + created_at timestamptz not null default now(),
407 + check (ends_at > starts_at)
408 +);
409 +create index class_session_subject_weekday_idx on class_session(subject_id, weekday, starts_at);
410 +
411 +create table plan_item (
412 + id uuid primary key default gen_random_uuid(),
413 + owner_user_id uuid not null references app_user(id) on delete cascade,
414 + family_id uuid references family_workspace(id) on delete cascade,
415 + subject_id uuid references subject(id) on delete set null,
416 + kind plan_item_kind not null,
417 + title text not null check (char_length(title) between 1 and 240),
418 + notes text,
419 + status plan_item_status not null default 'planned',
420 + priority plan_priority not null default 'normal',
421 + visibility sharing_scope not null default 'private',
422 + starts_at timestamptz,
423 + due_at timestamptz,
424 + duration_minutes integer check (duration_minutes is null or duration_minutes between 1 and 1440),
425 + recurrence_rule text,
426 + parent_item_id uuid references plan_item(id) on delete set null,
427 + grade_points numeric(8,2),
428 + grade_out_of numeric(8,2),
429 + completed_at timestamptz,
430 + created_at timestamptz not null default now(),
431 + updated_at timestamptz not null default now(),
432 + check (due_at is null or starts_at is null or due_at >= starts_at),
433 + check ((grade_points is null and grade_out_of is null) or (grade_points is not null and grade_out_of is not null and grade_out_of > 0))
434 +);
435 +create index plan_item_owner_time_idx on plan_item(owner_user_id, coalesce(starts_at,due_at), status);
436 +create index plan_item_family_time_idx on plan_item(family_id, coalesce(starts_at,due_at)) where family_id is not null;
437 +create index plan_item_subject_idx on plan_item(subject_id, kind, due_at) where subject_id is not null;
438 +
439 +create table sharing_grant (
440 + resource_type text not null check (resource_type in ('plan_item')),
441 + resource_id uuid not null,
442 + grantee_user_id uuid not null references app_user(id) on delete cascade,
443 + granted_by uuid not null references app_user(id) on delete cascade,
444 + created_at timestamptz not null default now(),
445 + primary key (resource_type, resource_id, grantee_user_id)
446 +);
447 +create index sharing_grant_grantee_idx on sharing_grant(grantee_user_id, resource_type, resource_id);
448 +
449 +create table reminder (
450 + id uuid primary key default gen_random_uuid(),
451 + plan_item_id uuid not null references plan_item(id) on delete cascade,
452 + owner_user_id uuid not null references app_user(id) on delete cascade,
453 + minutes_before integer not null check (minutes_before between 0 and 10080),
454 + scheduled_for timestamptz not null,
455 + status reminder_status not null default 'scheduled',
456 + claimed_at timestamptz,
457 + delivered_at timestamptz,
458 + failure_reason text,
459 + created_at timestamptz not null default now(),
460 + unique(plan_item_id, owner_user_id, minutes_before)
461 +);
462 +create index reminder_due_idx on reminder(scheduled_for) where status='scheduled';
463 +
464 +create table notification_preference (
465 + user_id uuid primary key references app_user(id) on delete cascade,
466 + reminders_enabled boolean not null default true,
467 + quiet_start time,
468 + quiet_end time,
469 + timezone text not null default 'Asia/Tehran',
470 + updated_at timestamptz not null default now()
471 +);
472 +
473 +create table notification_outbox (
474 + id bigint generated always as identity primary key,
475 + reminder_id uuid not null unique references reminder(id) on delete cascade,
476 + user_id uuid not null references app_user(id) on delete cascade,
477 + payload jsonb not null,
478 + available_at timestamptz not null default now(),
479 + delivered_at timestamptz,
480 + attempts integer not null default 0,
481 + last_error text
482 +);
483 +create index notification_outbox_pending_idx on notification_outbox(available_at) where delivered_at is null;
484 +
485 +create table sync_mutation (
486 + id uuid primary key,
487 + user_id uuid not null references app_user(id) on delete cascade,
488 + entity_type text not null,
489 + entity_id uuid,
490 + operation text not null check (operation in ('create','update','complete','reschedule')),
491 + client_updated_at timestamptz not null,
492 + payload jsonb not null,
493 + accepted_at timestamptz not null default now(),
494 + unique(user_id,id)
495 +);
496 +
497 +create function can_view_student_academic(p_viewer uuid, p_student uuid) returns boolean
498 +language sql stable as $$
499 + select p_viewer=p_student or exists(
500 + select 1
501 + from guardian_relationship g
502 + join family_membership gm
503 + on gm.family_id=g.family_id and gm.user_id=g.guardian_user_id and gm.ended_at is null
504 + join family_membership sm
505 + on sm.family_id=g.family_id and sm.user_id=g.minor_user_id and sm.ended_at is null
506 + where g.guardian_user_id=p_viewer
507 + and g.minor_user_id=p_student
508 + and g.active
509 + )
510 +$$;
511 +
512 +create function can_view_plan_item(p_viewer uuid, p_item uuid) returns boolean
513 +language sql stable as $$
514 + select exists(
515 + select 1
516 + from plan_item p
517 + where p.id=p_item
518 + and (
519 + p.owner_user_id=p_viewer
520 + or exists(
521 + select 1 from sharing_grant sg
522 + where sg.resource_type='plan_item'
523 + and sg.resource_id=p.id
524 + and sg.grantee_user_id=p_viewer
525 + )
526 + or (
527 + p.visibility='family'
528 + and p.family_id is not null
529 + and is_active_family_member(p.family_id,p_viewer)
530 + )
531 + or (
532 + p.visibility='parent_guardian'
533 + and p.family_id is not null
534 + and is_active_guardian(p.family_id,p_viewer,p.owner_user_id)
535 + )
536 + )
537 + )
538 +$$;
539 +
540 +create function recompute_reminder_schedule(p_plan_item uuid) returns void
541 +language plpgsql as $$
542 +declare
543 + base_time timestamptz;
544 +begin
545 + select coalesce(starts_at,due_at) into base_time from plan_item where id=p_plan_item;
546 + if base_time is null then
547 + update reminder set status='cancelled' where plan_item_id=p_plan_item and status in ('scheduled','claimed');
548 + return;
549 + end if;
550 + update reminder
551 + set scheduled_for = base_time - make_interval(mins => minutes_before),
552 + status = case when status in ('sent','failed') then status else 'scheduled' end,
553 + claimed_at = null
554 + where plan_item_id=p_plan_item
555 + and status <> 'cancelled';
556 +end $$;
557 +
558 +
559 +insert into lifeguide_qa.schema_migration(filename,sha256)
560 +values ('0003_planner_school_family.sql',encode(digest(convert_to($qa_original_0003$begin;
561 +
562 +create type life_context_kind as enum ('student','work','personal');
563 +create type plan_item_kind as enum ('task','event','routine','goal','assignment','exam','study_session');
564 +create type plan_item_status as enum ('planned','in_progress','completed','cancelled');
565 +create type plan_priority as enum ('low','normal','high','urgent');
566 +create type sharing_scope as enum ('private','selected_members','parent_guardian','family');
567 +create type reminder_status as enum ('scheduled','claimed','sent','cancelled','failed');
568 +
569 +create table life_context (
570 + id uuid primary key default gen_random_uuid(),
571 + user_id uuid not null references app_user(id) on delete cascade,
572 + kind life_context_kind not null,
573 + title text not null check (char_length(title) between 1 and 120),
574 + active boolean not null default true,
575 + created_at timestamptz not null default now()
576 +);
577 +create index life_context_user_idx on life_context(user_id) where active;
578 +
579 +create table academic_year (
580 + id uuid primary key default gen_random_uuid(),
581 + student_user_id uuid not null references app_user(id) on delete cascade,
582 + life_context_id uuid not null references life_context(id) on delete cascade,
583 + title text not null,
584 + starts_on date not null,
585 + ends_on date not null,
586 + active boolean not null default true,
587 + created_at timestamptz not null default now(),
588 + check (ends_on >= starts_on)
589 +);
590 +create index academic_year_student_idx on academic_year(student_user_id, starts_on desc);
591 +
592 +create table academic_term (
593 + id uuid primary key default gen_random_uuid(),
594 + academic_year_id uuid not null references academic_year(id) on delete cascade,
595 + title text not null,
596 + starts_on date not null,
597 + ends_on date not null,
598 + created_at timestamptz not null default now(),
599 + check (ends_on >= starts_on)
600 +);
601 +
602 +create table subject (
603 + id uuid primary key default gen_random_uuid(),
604 + student_user_id uuid not null references app_user(id) on delete cascade,
605 + academic_term_id uuid not null references academic_term(id) on delete cascade,
606 + name text not null check (char_length(name) between 1 and 120),
607 + teacher_name text,
608 + color_key text,
609 + created_at timestamptz not null default now()
610 +);
611 +create index subject_student_term_idx on subject(student_user_id, academic_term_id);
612 +
613 +create table class_session (
614 + id uuid primary key default gen_random_uuid(),
615 + subject_id uuid not null references subject(id) on delete cascade,
616 + weekday smallint not null check (weekday between 1 and 7),
617 + starts_at time not null,
618 + ends_at time not null,
619 + location text,
620 + recurrence_until date,
621 + created_at timestamptz not null default now(),
622 + check (ends_at > starts_at)
623 +);
624 +create index class_session_subject_weekday_idx on class_session(subject_id, weekday, starts_at);
625 +
626 +create table plan_item (
627 + id uuid primary key default gen_random_uuid(),
628 + owner_user_id uuid not null references app_user(id) on delete cascade,
629 + family_id uuid references family_workspace(id) on delete cascade,
630 + subject_id uuid references subject(id) on delete set null,
631 + kind plan_item_kind not null,
632 + title text not null check (char_length(title) between 1 and 240),
633 + notes text,
634 + status plan_item_status not null default 'planned',
635 + priority plan_priority not null default 'normal',
636 + visibility sharing_scope not null default 'private',
637 + starts_at timestamptz,
638 + due_at timestamptz,
639 + duration_minutes integer check (duration_minutes is null or duration_minutes between 1 and 1440),
640 + recurrence_rule text,
641 + parent_item_id uuid references plan_item(id) on delete set null,
642 + grade_points numeric(8,2),
643 + grade_out_of numeric(8,2),
644 + completed_at timestamptz,
645 + created_at timestamptz not null default now(),
646 + updated_at timestamptz not null default now(),
647 + check (due_at is null or starts_at is null or due_at >= starts_at),
648 + check ((grade_points is null and grade_out_of is null) or (grade_points is not null and grade_out_of is not null and grade_out_of > 0))
649 +);
650 +create index plan_item_owner_time_idx on plan_item(owner_user_id, coalesce(starts_at,due_at), status);
651 +create index plan_item_family_time_idx on plan_item(family_id, coalesce(starts_at,due_at)) where family_id is not null;
652 +create index plan_item_subject_idx on plan_item(subject_id, kind, due_at) where subject_id is not null;
653 +
654 +create table sharing_grant (
655 + resource_type text not null check (resource_type in ('plan_item')),
656 + resource_id uuid not null,
657 + grantee_user_id uuid not null references app_user(id) on delete cascade,
658 + granted_by uuid not null references app_user(id) on delete cascade,
659 + created_at timestamptz not null default now(),
660 + primary key (resource_type, resource_id, grantee_user_id)
661 +);
662 +create index sharing_grant_grantee_idx on sharing_grant(grantee_user_id, resource_type, resource_id);
663 +
664 +create table reminder (
665 + id uuid primary key default gen_random_uuid(),
666 + plan_item_id uuid not null references plan_item(id) on delete cascade,
667 + owner_user_id uuid not null references app_user(id) on delete cascade,
668 + minutes_before integer not null check (minutes_before between 0 and 10080),
669 + scheduled_for timestamptz not null,
670 + status reminder_status not null default 'scheduled',
671 + claimed_at timestamptz,
672 + delivered_at timestamptz,
673 + failure_reason text,
674 + created_at timestamptz not null default now(),
675 + unique(plan_item_id, owner_user_id, minutes_before)
676 +);
677 +create index reminder_due_idx on reminder(scheduled_for) where status='scheduled';
678 +
679 +create table notification_preference (
680 + user_id uuid primary key references app_user(id) on delete cascade,
681 + reminders_enabled boolean not null default true,
682 + quiet_start time,
683 + quiet_end time,
684 + timezone text not null default 'Asia/Tehran',
685 + updated_at timestamptz not null default now()
686 +);
687 +
688 +create table notification_outbox (
689 + id bigint generated always as identity primary key,
690 + reminder_id uuid not null unique references reminder(id) on delete cascade,
691 + user_id uuid not null references app_user(id) on delete cascade,
692 + payload jsonb not null,
693 + available_at timestamptz not null default now(),
694 + delivered_at timestamptz,
695 + attempts integer not null default 0,
696 + last_error text
697 +);
698 +create index notification_outbox_pending_idx on notification_outbox(available_at) where delivered_at is null;
699 +
700 +create table sync_mutation (
701 + id uuid primary key,
702 + user_id uuid not null references app_user(id) on delete cascade,
703 + entity_type text not null,
704 + entity_id uuid,
705 + operation text not null check (operation in ('create','update','complete','reschedule')),
706 + client_updated_at timestamptz not null,
707 + payload jsonb not null,
708 + accepted_at timestamptz not null default now(),
709 + unique(user_id,id)
710 +);
711 +
712 +create function can_view_student_academic(p_viewer uuid, p_student uuid) returns boolean
713 +language sql stable as $$
714 + select p_viewer=p_student or exists(
715 + select 1
716 + from guardian_relationship g
717 + join family_membership gm
718 + on gm.family_id=g.family_id and gm.user_id=g.guardian_user_id and gm.ended_at is null
719 + join family_membership sm
720 + on sm.family_id=g.family_id and sm.user_id=g.minor_user_id and sm.ended_at is null
721 + where g.guardian_user_id=p_viewer
722 + and g.minor_user_id=p_student
723 + and g.active
724 + )
725 +$$;
726 +
727 +create function can_view_plan_item(p_viewer uuid, p_item uuid) returns boolean
728 +language sql stable as $$
729 + select exists(
730 + select 1
731 + from plan_item p
732 + where p.id=p_item
733 + and (
734 + p.owner_user_id=p_viewer
735 + or exists(
736 + select 1 from sharing_grant sg
737 + where sg.resource_type='plan_item'
738 + and sg.resource_id=p.id
739 + and sg.grantee_user_id=p_viewer
740 + )
741 + or (
742 + p.visibility='family'
743 + and p.family_id is not null
744 + and is_active_family_member(p.family_id,p_viewer)
745 + )
746 + or (
747 + p.visibility='parent_guardian'
748 + and p.family_id is not null
749 + and is_active_guardian(p.family_id,p_viewer,p.owner_user_id)
750 + )
751 + )
752 + )
753 +$$;
754 +
755 +create function recompute_reminder_schedule(p_plan_item uuid) returns void
756 +language plpgsql as $$
757 +declare
758 + base_time timestamptz;
759 +begin
760 + select coalesce(starts_at,due_at) into base_time from plan_item where id=p_plan_item;
761 + if base_time is null then
762 + update reminder set status='cancelled' where plan_item_id=p_plan_item and status in ('scheduled','claimed');
763 + return;
764 + end if;
765 + update reminder
766 + set scheduled_for = base_time - make_interval(mins => minutes_before),
767 + status = case when status in ('sent','failed') then status else 'scheduled' end,
768 + claimed_at = null
769 + where plan_item_id=p_plan_item
770 + and status <> 'cancelled';
771 +end $$;
772 +
773 +commit;
774 +$qa_original_0003$,'UTF8'),'sha256'),'hex'));
775 +-- Original LifeGuide migration 0004_ai_learning_wellbeing.sql
776 +create table if not exists learning_goal (
777 + id uuid primary key default gen_random_uuid(),
778 + owner_user_id uuid not null references app_user(id) on delete cascade,
779 + subject_id uuid references subject(id) on delete set null,
780 + title text not null,
781 + target text,
782 + status text not null default 'active' check (status in ('active','completed','archived')),
783 + created_at timestamptz not null default now(), updated_at timestamptz not null default now()
784 +);
785 +create table if not exists learning_checkin (
786 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
787 + learning_goal_id uuid references learning_goal(id) on delete set null,
788 + confidence smallint check(confidence between 1 and 5), difficulty smallint check(difficulty between 1 and 5), note text,
789 + created_at timestamptz not null default now()
790 +);
791 +create table if not exists wellbeing_checkin (
792 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
793 + mood smallint not null check(mood between 1 and 5), energy smallint check(energy between 1 and 5), stress smallint check(stress between 1 and 5), note text,
794 + visibility text not null default 'private' check(visibility in ('private','guardian_summary')),
795 + created_at timestamptz not null default now()
796 +);
797 +create table if not exists ai_guide_session (
798 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
799 + guide_kind text not null check(guide_kind in ('study','planner','wellbeing')),
800 + status text not null default 'active' check(status in ('active','closed')),
801 + created_at timestamptz not null default now(), updated_at timestamptz not null default now()
802 +);
803 +create table if not exists ai_guide_message (
804 + id uuid primary key default gen_random_uuid(), session_id uuid not null references ai_guide_session(id) on delete cascade,
805 + author text not null check(author in ('user','assistant','system')), body text not null,
806 + safety_class text not null default 'ordinary' check(safety_class in ('ordinary','supportive','urgent_review')),
807 + created_at timestamptz not null default now()
808 +);
809 +create table if not exists ai_plan_proposal (
810 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
811 + session_id uuid references ai_guide_session(id) on delete set null, title text not null, proposal jsonb not null,
812 + status text not null default 'proposed' check(status in ('proposed','accepted','rejected')),
813 + created_at timestamptz not null default now(), decided_at timestamptz
814 +);
815 +create index if not exists learning_goal_owner_idx on learning_goal(owner_user_id,status);
816 +create index if not exists wellbeing_checkin_owner_idx on wellbeing_checkin(owner_user_id,created_at desc);
817 +create index if not exists ai_guide_session_owner_idx on ai_guide_session(owner_user_id,created_at desc);
818 +
819 +create table if not exists wellbeing_safety_event (
820 + id uuid primary key default gen_random_uuid(),
821 + owner_user_id uuid not null references app_user(id) on delete cascade,
822 + source_session_id uuid references ai_guide_session(id) on delete set null,
823 + severity text not null check(severity in ('urgent_review')),
824 + status text not null default 'open' check(status in ('open','acknowledged','closed')),
825 + created_at timestamptz not null default now(),
826 + acknowledged_at timestamptz
827 +);
828 +create index if not exists wellbeing_safety_event_owner_idx on wellbeing_safety_event(owner_user_id,created_at desc);
829 +insert into lifeguide_qa.schema_migration(filename,sha256)
830 +values ('0004_ai_learning_wellbeing.sql',encode(digest(convert_to($qa_original_0004$create table if not exists learning_goal (
831 + id uuid primary key default gen_random_uuid(),
832 + owner_user_id uuid not null references app_user(id) on delete cascade,
833 + subject_id uuid references subject(id) on delete set null,
834 + title text not null,
835 + target text,
836 + status text not null default 'active' check (status in ('active','completed','archived')),
837 + created_at timestamptz not null default now(), updated_at timestamptz not null default now()
838 +);
839 +create table if not exists learning_checkin (
840 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
841 + learning_goal_id uuid references learning_goal(id) on delete set null,
842 + confidence smallint check(confidence between 1 and 5), difficulty smallint check(difficulty between 1 and 5), note text,
843 + created_at timestamptz not null default now()
844 +);
845 +create table if not exists wellbeing_checkin (
846 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
847 + mood smallint not null check(mood between 1 and 5), energy smallint check(energy between 1 and 5), stress smallint check(stress between 1 and 5), note text,
848 + visibility text not null default 'private' check(visibility in ('private','guardian_summary')),
849 + created_at timestamptz not null default now()
850 +);
851 +create table if not exists ai_guide_session (
852 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
853 + guide_kind text not null check(guide_kind in ('study','planner','wellbeing')),
854 + status text not null default 'active' check(status in ('active','closed')),
855 + created_at timestamptz not null default now(), updated_at timestamptz not null default now()
856 +);
857 +create table if not exists ai_guide_message (
858 + id uuid primary key default gen_random_uuid(), session_id uuid not null references ai_guide_session(id) on delete cascade,
859 + author text not null check(author in ('user','assistant','system')), body text not null,
860 + safety_class text not null default 'ordinary' check(safety_class in ('ordinary','supportive','urgent_review')),
861 + created_at timestamptz not null default now()
862 +);
863 +create table if not exists ai_plan_proposal (
864 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
865 + session_id uuid references ai_guide_session(id) on delete set null, title text not null, proposal jsonb not null,
866 + status text not null default 'proposed' check(status in ('proposed','accepted','rejected')),
867 + created_at timestamptz not null default now(), decided_at timestamptz
868 +);
869 +create index if not exists learning_goal_owner_idx on learning_goal(owner_user_id,status);
870 +create index if not exists wellbeing_checkin_owner_idx on wellbeing_checkin(owner_user_id,created_at desc);
871 +create index if not exists ai_guide_session_owner_idx on ai_guide_session(owner_user_id,created_at desc);
872 +
873 +create table if not exists wellbeing_safety_event (
874 + id uuid primary key default gen_random_uuid(),
875 + owner_user_id uuid not null references app_user(id) on delete cascade,
876 + source_session_id uuid references ai_guide_session(id) on delete set null,
877 + severity text not null check(severity in ('urgent_review')),
878 + status text not null default 'open' check(status in ('open','acknowledged','closed')),
879 + created_at timestamptz not null default now(),
880 + acknowledged_at timestamptz
881 +);
882 +create index if not exists wellbeing_safety_event_owner_idx on wellbeing_safety_event(owner_user_id,created_at desc);
883 +$qa_original_0004$,'UTF8'),'sha256'),'hex'));
884 +-- Original LifeGuide migration 0005_iran_family_learning.sql
885 +
886 +alter table profile add column if not exists household_persona text check (household_persona in ('mother','father','child','adult')), add column if not exists sex text check (sex in ('female','male','unspecified'));
887 +create table education_profile (user_id uuid primary key references app_user(id) on delete cascade,country_code char(2) not null default 'IR' check(country_code='IR'),stage text not null check(stage in('primary_1','primary_2','secondary_1','secondary_2')),national_grade smallint not null check(national_grade between 1 and 12),local_year smallint not null check(local_year between 1 and 3),school_name text,school_year text not null,updated_at timestamptz not null default now(),check((stage='primary_1' and national_grade between 1 and 3 and local_year=national_grade)or(stage='primary_2' and national_grade between 4 and 6 and local_year=national_grade-3)or(stage='secondary_1' and national_grade between 7 and 9 and local_year=national_grade-6)or(stage='secondary_2' and national_grade between 10 and 12 and local_year=national_grade-9)));
888 +create table curriculum_subject (id uuid primary key default gen_random_uuid(),country_code char(2) not null default 'IR',school_year text not null,national_grade smallint not null check(national_grade between 1 and 12),code text not null,name_fa text not null,sort_order smallint not null default 0,unique(country_code,school_year,national_grade,code));
889 +create table textbook_catalog (id uuid primary key default gen_random_uuid(),curriculum_subject_id uuid not null references curriculum_subject(id) on delete cascade,title_fa text not null,publisher text not null default 'سازمان پژوهش و برنامه‌ریزی آموزشی',source_host text not null default 'chap.sch.ir' check(source_host in('chap.sch.ir','medu.gov.ir')),source_url text not null check(source_url~'^https://'),redistribution_status text not null default 'link_only' check(redistribution_status in('link_only','licensed_bundle')),unique(curriculum_subject_id,title_fa));
890 +create table iran_calendar_event (id uuid primary key default gen_random_uuid(),jalali_year smallint not null check(jalali_year between 1300 and 1600),jalali_month smallint not null check(jalali_month between 1 and 12),jalali_day smallint not null check(jalali_day between 1 and 31),title_fa text not null,is_official_holiday boolean not null default false,source_name text not null,source_url text not null check(source_url~'^https://'),unique(jalali_year,jalali_month,jalali_day,title_fa));
891 +alter table notification_preference add column if not exists in_app_banner boolean not null default true,add column if not exists push_enabled boolean not null default false,add column if not exists planner_reminders boolean not null default true,add column if not exists school_reminders boolean not null default true,add column if not exists calendar_reminders boolean not null default true,add column if not exists cycle_reminders boolean not null default false,add column if not exists sensitive_preview boolean not null default false;
892 +create table menstrual_cycle_entry (id uuid primary key default gen_random_uuid(),owner_user_id uuid not null references app_user(id) on delete cascade,starts_on date not null,ends_on date,predicted_next_on date,symptoms text[] not null default '{}',notes text,reminder_enabled boolean not null default false,created_at timestamptz not null default now(),updated_at timestamptz not null default now(),check(ends_on is null or ends_on>=starts_on),check(predicted_next_on is null or predicted_next_on>starts_on));
893 +create index menstrual_cycle_owner_date_idx on menstrual_cycle_entry(owner_user_id,starts_on desc);
894 +insert into curriculum_subject(school_year,national_grade,code,name_fa,sort_order) values ('1405-1406',7,'fa','فارسی',10),('1405-1406',7,'writing','نگارش',20),('1405-1406',7,'math','ریاضی',30),('1405-1406',7,'science','علوم تجربی',40),('1405-1406',7,'social','مطالعات اجتماعی',50),('1405-1406',7,'arabic','عربی',60),('1405-1406',7,'quran','قرآن',70),('1405-1406',7,'religion','پیام‌های آسمان',80),('1405-1406',7,'english','انگلیسی',90),('1405-1406',7,'worktech','کار و فناوری',100),('1405-1406',7,'thinking','تفکر و سبک زندگی',110),('1405-1406',7,'pe','تربیت بدنی و سلامت',120) on conflict do nothing;
895 +insert into textbook_catalog(curriculum_subject_id,title_fa,source_url) select id,name_fa,'https://chap.sch.ir/' from curriculum_subject where school_year='1405-1406' and national_grade=7 on conflict do nothing;
896 +insert into iran_calendar_event(jalali_year,jalali_month,jalali_day,title_fa,is_official_holiday,source_name,source_url) values (1405,1,1,'آغاز نوروز',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,1,2,'عید نوروز',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,1,3,'عید نوروز',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,1,4,'عید نوروز',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,1,12,'روز جمهوری اسلامی ایران',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,1,13,'روز طبیعت',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,3,14,'رحلت امام خمینی',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,3,15,'قیام ۱۵ خرداد',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,11,22,'پیروزی انقلاب اسلامی ایران',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,12,29,'روز ملی شدن صنعت نفت ایران',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/') on conflict do nothing;
897 +
898 +insert into lifeguide_qa.schema_migration(filename,sha256)
899 +values ('0005_iran_family_learning.sql',encode(digest(convert_to($qa_original_0005$begin;
900 +alter table profile add column if not exists household_persona text check (household_persona in ('mother','father','child','adult')), add column if not exists sex text check (sex in ('female','male','unspecified'));
901 +create table education_profile (user_id uuid primary key references app_user(id) on delete cascade,country_code char(2) not null default 'IR' check(country_code='IR'),stage text not null check(stage in('primary_1','primary_2','secondary_1','secondary_2')),national_grade smallint not null check(national_grade between 1 and 12),local_year smallint not null check(local_year between 1 and 3),school_name text,school_year text not null,updated_at timestamptz not null default now(),check((stage='primary_1' and national_grade between 1 and 3 and local_year=national_grade)or(stage='primary_2' and national_grade between 4 and 6 and local_year=national_grade-3)or(stage='secondary_1' and national_grade between 7 and 9 and local_year=national_grade-6)or(stage='secondary_2' and national_grade between 10 and 12 and local_year=national_grade-9)));
902 +create table curriculum_subject (id uuid primary key default gen_random_uuid(),country_code char(2) not null default 'IR',school_year text not null,national_grade smallint not null check(national_grade between 1 and 12),code text not null,name_fa text not null,sort_order smallint not null default 0,unique(country_code,school_year,national_grade,code));
903 +create table textbook_catalog (id uuid primary key default gen_random_uuid(),curriculum_subject_id uuid not null references curriculum_subject(id) on delete cascade,title_fa text not null,publisher text not null default 'سازمان پژوهش و برنامه‌ریزی آموزشی',source_host text not null default 'chap.sch.ir' check(source_host in('chap.sch.ir','medu.gov.ir')),source_url text not null check(source_url~'^https://'),redistribution_status text not null default 'link_only' check(redistribution_status in('link_only','licensed_bundle')),unique(curriculum_subject_id,title_fa));
904 +create table iran_calendar_event (id uuid primary key default gen_random_uuid(),jalali_year smallint not null check(jalali_year between 1300 and 1600),jalali_month smallint not null check(jalali_month between 1 and 12),jalali_day smallint not null check(jalali_day between 1 and 31),title_fa text not null,is_official_holiday boolean not null default false,source_name text not null,source_url text not null check(source_url~'^https://'),unique(jalali_year,jalali_month,jalali_day,title_fa));
905 +alter table notification_preference add column if not exists in_app_banner boolean not null default true,add column if not exists push_enabled boolean not null default false,add column if not exists planner_reminders boolean not null default true,add column if not exists school_reminders boolean not null default true,add column if not exists calendar_reminders boolean not null default true,add column if not exists cycle_reminders boolean not null default false,add column if not exists sensitive_preview boolean not null default false;
906 +create table menstrual_cycle_entry (id uuid primary key default gen_random_uuid(),owner_user_id uuid not null references app_user(id) on delete cascade,starts_on date not null,ends_on date,predicted_next_on date,symptoms text[] not null default '{}',notes text,reminder_enabled boolean not null default false,created_at timestamptz not null default now(),updated_at timestamptz not null default now(),check(ends_on is null or ends_on>=starts_on),check(predicted_next_on is null or predicted_next_on>starts_on));
907 +create index menstrual_cycle_owner_date_idx on menstrual_cycle_entry(owner_user_id,starts_on desc);
908 +insert into curriculum_subject(school_year,national_grade,code,name_fa,sort_order) values ('1405-1406',7,'fa','فارسی',10),('1405-1406',7,'writing','نگارش',20),('1405-1406',7,'math','ریاضی',30),('1405-1406',7,'science','علوم تجربی',40),('1405-1406',7,'social','مطالعات اجتماعی',50),('1405-1406',7,'arabic','عربی',60),('1405-1406',7,'quran','قرآن',70),('1405-1406',7,'religion','پیام‌های آسمان',80),('1405-1406',7,'english','انگلیسی',90),('1405-1406',7,'worktech','کار و فناوری',100),('1405-1406',7,'thinking','تفکر و سبک زندگی',110),('1405-1406',7,'pe','تربیت بدنی و سلامت',120) on conflict do nothing;
909 +insert into textbook_catalog(curriculum_subject_id,title_fa,source_url) select id,name_fa,'https://chap.sch.ir/' from curriculum_subject where school_year='1405-1406' and national_grade=7 on conflict do nothing;
910 +insert into iran_calendar_event(jalali_year,jalali_month,jalali_day,title_fa,is_official_holiday,source_name,source_url) values (1405,1,1,'آغاز نوروز',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,1,2,'عید نوروز',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,1,3,'عید نوروز',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,1,4,'عید نوروز',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,1,12,'روز جمهوری اسلامی ایران',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,1,13,'روز طبیعت',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,3,14,'رحلت امام خمینی',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,3,15,'قیام ۱۵ خرداد',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,11,22,'پیروزی انقلاب اسلامی ایران',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/'),(1405,12,29,'روز ملی شدن صنعت نفت ایران',true,'تقویم رسمی کشور ۱۴۰۵ — مرکز تقویم مؤسسه ژئوفیزیک دانشگاه تهران','https://calendar.ut.ac.ir/') on conflict do nothing;
911 +commit;$qa_original_0005$,'UTF8'),'sha256'),'hex'));
912 +-- Original LifeGuide migration 0006_iran_calendar_1405_holidays.sql
913 +
914 +insert into iran_calendar_event(jalali_year,jalali_month,jalali_day,title_fa,is_official_holiday,source_name,source_url) values
915 +(1405,1,1,'عید سعید فطر و آغاز نوروز',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
916 +(1405,1,2,'تعطیل عید سعید فطر و عید نوروز',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
917 +(1405,1,25,'شهادت امام جعفر صادق (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
918 +(1405,3,6,'عید سعید قربان',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
919 +(1405,3,14,'عید سعید غدیر خم و رحلت امام خمینی',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
920 +(1405,4,3,'تاسوعای حسینی',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
921 +(1405,4,4,'عاشورای حسینی',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
922 +(1405,5,13,'اربعین حسینی',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
923 +(1405,5,21,'رحلت حضرت رسول اکرم (ص) و شهادت امام حسن مجتبی (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
924 +(1405,5,22,'شهادت امام رضا (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
925 +(1405,5,30,'شهادت امام حسن عسکری (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
926 +(1405,6,8,'ولادت حضرت رسول اکرم (ص) و امام جعفر صادق (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
927 +(1405,8,22,'شهادت حضرت فاطمه زهرا (س)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
928 +(1405,10,2,'ولادت امام علی (ع) و روز پدر',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
929 +(1405,10,16,'مبعث حضرت رسول اکرم (ص)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
930 +(1405,11,4,'ولادت حضرت قائم (عج) و نیمه شعبان',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
931 +(1405,12,9,'شهادت حضرت علی (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
932 +(1405,12,19,'عید سعید فطر',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
933 +(1405,12,20,'تعطیل به مناسبت عید سعید فطر',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/')
934 +on conflict do nothing;
935 +
936 +insert into lifeguide_qa.schema_migration(filename,sha256)
937 +values ('0006_iran_calendar_1405_holidays.sql',encode(digest(convert_to($qa_original_0006$begin;
938 +insert into iran_calendar_event(jalali_year,jalali_month,jalali_day,title_fa,is_official_holiday,source_name,source_url) values
939 +(1405,1,1,'عید سعید فطر و آغاز نوروز',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
940 +(1405,1,2,'تعطیل عید سعید فطر و عید نوروز',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
941 +(1405,1,25,'شهادت امام جعفر صادق (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
942 +(1405,3,6,'عید سعید قربان',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
943 +(1405,3,14,'عید سعید غدیر خم و رحلت امام خمینی',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
944 +(1405,4,3,'تاسوعای حسینی',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
945 +(1405,4,4,'عاشورای حسینی',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
946 +(1405,5,13,'اربعین حسینی',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
947 +(1405,5,21,'رحلت حضرت رسول اکرم (ص) و شهادت امام حسن مجتبی (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
948 +(1405,5,22,'شهادت امام رضا (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
949 +(1405,5,30,'شهادت امام حسن عسکری (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
950 +(1405,6,8,'ولادت حضرت رسول اکرم (ص) و امام جعفر صادق (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
951 +(1405,8,22,'شهادت حضرت فاطمه زهرا (س)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
952 +(1405,10,2,'ولادت امام علی (ع) و روز پدر',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
953 +(1405,10,16,'مبعث حضرت رسول اکرم (ص)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
954 +(1405,11,4,'ولادت حضرت قائم (عج) و نیمه شعبان',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
955 +(1405,12,9,'شهادت حضرت علی (ع)',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
956 +(1405,12,19,'عید سعید فطر',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/'),
957 +(1405,12,20,'تعطیل به مناسبت عید سعید فطر',true,'تقویم رسمی کشور ۱۴۰۵','https://calendar.ut.ac.ir/')
958 +on conflict do nothing;
959 +commit;
960 +$qa_original_0006$,'UTF8'),'sha256'),'hex'));
961 +-- Original LifeGuide migration 0007_auth_contacts.sql
962 +
963 +
964 +alter table app_user alter column email_normalized drop not null;
965 +alter table app_user add column phone_normalized text unique;
966 +alter table app_user add column phone_verified_at timestamptz;
967 +alter table app_user add constraint app_user_phone_format
968 + check (phone_normalized is null or phone_normalized ~ '^\+[1-9][0-9]{7,14}$');
969 +alter table app_user add constraint app_user_contact_required
970 + check (email_normalized is not null or phone_normalized is not null);
971 +
972 +alter table family_invitation alter column invited_email_normalized drop not null;
973 +alter table family_invitation add column invited_phone_normalized text;
974 +alter table family_invitation add constraint family_invitation_contact_required
975 + check (num_nonnulls(invited_email_normalized,invited_phone_normalized)=1);
976 +alter table family_invitation add constraint family_invitation_phone_format
977 + check (invited_phone_normalized is null or invited_phone_normalized ~ '^\+[1-9][0-9]{7,14}$');
978 +
979 +create table auth_delivery_attempt (
980 + id uuid primary key default gen_random_uuid(),
981 + recipient_digest text not null check (recipient_digest ~ '^[a-f0-9]{64}$'),
982 + purpose text not null check (purpose in ('email_verification','password_reset','phone_otp')),
983 + user_id uuid references app_user(id) on delete set null,
984 + status text not null default 'pending'
985 + check (status in ('pending','accepted','failed','unconfigured','not_needed')),
986 + requested_at timestamptz not null default now(),
987 + updated_at timestamptz not null default now()
988 +);
989 +create index auth_delivery_recipient_window_idx
990 + on auth_delivery_attempt(recipient_digest,purpose,requested_at desc);
991 +
992 +create table auth_phone_challenge (
993 + id uuid primary key,
994 + user_id uuid references app_user(id) on delete cascade,
995 + purpose text not null check (purpose in ('verify','login','recovery')),
996 + code_digest text not null check (code_digest ~ '^[a-f0-9]{64}$'),
997 + attempts smallint not null default 0 check (attempts between 0 and 5),
998 + expires_at timestamptz not null,
999 + used_at timestamptz,
1000 + created_at timestamptz not null default now(),
1001 + check (expires_at > created_at)
1002 +);
1003 +create index auth_phone_challenge_owner_idx on auth_phone_challenge(user_id,created_at desc);
1004 +
1005 +
1006 +insert into lifeguide_qa.schema_migration(filename,sha256)
1007 +values ('0007_auth_contacts.sql',encode(digest(convert_to($qa_original_0007$begin;
1008 +
1009 +alter table app_user alter column email_normalized drop not null;
1010 +alter table app_user add column phone_normalized text unique;
1011 +alter table app_user add column phone_verified_at timestamptz;
1012 +alter table app_user add constraint app_user_phone_format
1013 + check (phone_normalized is null or phone_normalized ~ '^\+[1-9][0-9]{7,14}$');
1014 +alter table app_user add constraint app_user_contact_required
1015 + check (email_normalized is not null or phone_normalized is not null);
1016 +
1017 +alter table family_invitation alter column invited_email_normalized drop not null;
1018 +alter table family_invitation add column invited_phone_normalized text;
1019 +alter table family_invitation add constraint family_invitation_contact_required
1020 + check (num_nonnulls(invited_email_normalized,invited_phone_normalized)=1);
1021 +alter table family_invitation add constraint family_invitation_phone_format
1022 + check (invited_phone_normalized is null or invited_phone_normalized ~ '^\+[1-9][0-9]{7,14}$');
1023 +
1024 +create table auth_delivery_attempt (
1025 + id uuid primary key default gen_random_uuid(),
1026 + recipient_digest text not null check (recipient_digest ~ '^[a-f0-9]{64}$'),
1027 + purpose text not null check (purpose in ('email_verification','password_reset','phone_otp')),
1028 + user_id uuid references app_user(id) on delete set null,
1029 + status text not null default 'pending'
1030 + check (status in ('pending','accepted','failed','unconfigured','not_needed')),
1031 + requested_at timestamptz not null default now(),
1032 + updated_at timestamptz not null default now()
1033 +);
1034 +create index auth_delivery_recipient_window_idx
1035 + on auth_delivery_attempt(recipient_digest,purpose,requested_at desc);
1036 +
1037 +create table auth_phone_challenge (
1038 + id uuid primary key,
1039 + user_id uuid references app_user(id) on delete cascade,
1040 + purpose text not null check (purpose in ('verify','login','recovery')),
1041 + code_digest text not null check (code_digest ~ '^[a-f0-9]{64}$'),
1042 + attempts smallint not null default 0 check (attempts between 0 and 5),
1043 + expires_at timestamptz not null,
1044 + used_at timestamptz,
1045 + created_at timestamptz not null default now(),
1046 + check (expires_at > created_at)
1047 +);
1048 +create index auth_phone_challenge_owner_idx on auth_phone_challenge(user_id,created_at desc);
1049 +
1050 +commit;
1051 +$qa_original_0007$,'UTF8'),'sha256'),'hex'));
1052 +-- Original LifeGuide migration 0008_study_sessions.sql
1053 +
1054 +
1055 +-- Reuse the existing planner; its legacy status remains compatible.
1056 +alter table plan_item add column activity_version bigint not null default 0;
1057 +alter table plan_item add column if not exists version bigint not null default 0;
1058 +alter table plan_item add constraint plan_item_id_owner_unique unique(id,owner_user_id);
1059 +
1060 +create function plan_item_revision() returns trigger language plpgsql as $$
1061 +begin
1062 + new.version := old.version+1;
1063 + return new;
1064 +end $$;
1065 +create trigger plan_item_revision before update on plan_item
1066 +for each row execute function plan_item_revision();
1067 +
1068 +create table study_session (
1069 + id uuid primary key,
1070 + child_user_id uuid not null references app_user(id) on delete cascade,
1071 + plan_item_id uuid not null,
1072 + source text not null check(source in ('timer','self_reported')),
1073 + status text not null check(status in ('running','paused','completed','archived')),
1074 + started_at timestamptz not null,
1075 + ended_at timestamptz,
1076 + last_event_at timestamptz not null,
1077 + recorded_duration_seconds integer not null default 0 check(recorded_duration_seconds>=0),
1078 + version integer not null default 1 check(version>0),
1079 + last_sync_at timestamptz not null default now(),
1080 + created_at timestamptz not null default now(),
1081 + updated_at timestamptz not null default now(),
1082 + archived_at timestamptz,
1083 + foreign key(plan_item_id,child_user_id) references plan_item(id,owner_user_id) on delete cascade,
1084 + check(ended_at is null or ended_at>=started_at),
1085 + check(last_event_at>=started_at)
1086 +);
1087 +create index study_session_owner_idx on study_session(child_user_id,started_at desc);
1088 +create index study_session_plan_idx on study_session(plan_item_id) where archived_at is null;
1089 +
1090 +create table study_interval (
1091 + id bigint generated always as identity primary key,
1092 + session_id uuid not null references study_session(id) on delete cascade,
1093 + starts_at timestamptz not null,
1094 + ends_at timestamptz,
1095 + check(ends_at is null or ends_at>=starts_at)
1096 +);
1097 +create index study_interval_session_idx on study_interval(session_id,starts_at);
1098 +create unique index study_interval_one_running_idx on study_interval(session_id) where ends_at is null;
1099 +
1100 +create table activity_state_event (
1101 + id bigint generated always as identity primary key,
1102 + plan_item_id uuid not null references plan_item(id) on delete cascade,
1103 + actor_user_id uuid not null references app_user(id),
1104 + state text not null check(state in ('planned','started','paused','completed','verified')),
1105 + source text not null check(source in ('client_timer','self_reported','guardian_confirmation')),
1106 + occurred_at timestamptz not null,
1107 + accepted_at timestamptz not null default now(),
1108 + version bigint not null check(version>0),
1109 + confirmation text,
1110 + unique(plan_item_id,version),
1111 + check((state='verified' and source='guardian_confirmation' and char_length(confirmation) between 1 and 1000)
1112 + or (state<>'verified' and source<>'guardian_confirmation' and confirmation is null))
1113 +);
1114 +create index activity_state_latest_idx on activity_state_event(plan_item_id,version desc);
1115 +
1116 +-- A separate ledger avoids changing existing planner/offline sync protocol.
1117 +create table study_mutation (
1118 + user_id uuid not null references app_user(id) on delete cascade,
1119 + id uuid not null,
1120 + request_hash text not null,
1121 + response_body jsonb not null,
1122 + response_status integer not null,
1123 + accepted_at timestamptz not null default now(),
1124 + primary key(user_id,id)
1125 +);
1126 +
1127 +
1128 +insert into lifeguide_qa.schema_migration(filename,sha256)
1129 +values ('0008_study_sessions.sql',encode(digest(convert_to($qa_original_0008$begin;
1130 +
1131 +-- Reuse the existing planner; its legacy status remains compatible.
1132 +alter table plan_item add column activity_version bigint not null default 0;
1133 +alter table plan_item add column if not exists version bigint not null default 0;
1134 +alter table plan_item add constraint plan_item_id_owner_unique unique(id,owner_user_id);
1135 +
1136 +create function plan_item_revision() returns trigger language plpgsql as $$
1137 +begin
1138 + new.version := old.version+1;
1139 + return new;
1140 +end $$;
1141 +create trigger plan_item_revision before update on plan_item
1142 +for each row execute function plan_item_revision();
1143 +
1144 +create table study_session (
1145 + id uuid primary key,
1146 + child_user_id uuid not null references app_user(id) on delete cascade,
1147 + plan_item_id uuid not null,
1148 + source text not null check(source in ('timer','self_reported')),
1149 + status text not null check(status in ('running','paused','completed','archived')),
1150 + started_at timestamptz not null,
1151 + ended_at timestamptz,
1152 + last_event_at timestamptz not null,
1153 + recorded_duration_seconds integer not null default 0 check(recorded_duration_seconds>=0),
1154 + version integer not null default 1 check(version>0),
1155 + last_sync_at timestamptz not null default now(),
1156 + created_at timestamptz not null default now(),
1157 + updated_at timestamptz not null default now(),
1158 + archived_at timestamptz,
1159 + foreign key(plan_item_id,child_user_id) references plan_item(id,owner_user_id) on delete cascade,
1160 + check(ended_at is null or ended_at>=started_at),
1161 + check(last_event_at>=started_at)
1162 +);
1163 +create index study_session_owner_idx on study_session(child_user_id,started_at desc);
1164 +create index study_session_plan_idx on study_session(plan_item_id) where archived_at is null;
1165 +
1166 +create table study_interval (
1167 + id bigint generated always as identity primary key,
1168 + session_id uuid not null references study_session(id) on delete cascade,
1169 + starts_at timestamptz not null,
1170 + ends_at timestamptz,
1171 + check(ends_at is null or ends_at>=starts_at)
1172 +);
1173 +create index study_interval_session_idx on study_interval(session_id,starts_at);
1174 +create unique index study_interval_one_running_idx on study_interval(session_id) where ends_at is null;
1175 +
1176 +create table activity_state_event (
1177 + id bigint generated always as identity primary key,
1178 + plan_item_id uuid not null references plan_item(id) on delete cascade,
1179 + actor_user_id uuid not null references app_user(id),
1180 + state text not null check(state in ('planned','started','paused','completed','verified')),
1181 + source text not null check(source in ('client_timer','self_reported','guardian_confirmation')),
1182 + occurred_at timestamptz not null,
1183 + accepted_at timestamptz not null default now(),
1184 + version bigint not null check(version>0),
1185 + confirmation text,
1186 + unique(plan_item_id,version),
1187 + check((state='verified' and source='guardian_confirmation' and char_length(confirmation) between 1 and 1000)
1188 + or (state<>'verified' and source<>'guardian_confirmation' and confirmation is null))
1189 +);
1190 +create index activity_state_latest_idx on activity_state_event(plan_item_id,version desc);
1191 +
1192 +-- A separate ledger avoids changing existing planner/offline sync protocol.
1193 +create table study_mutation (
1194 + user_id uuid not null references app_user(id) on delete cascade,
1195 + id uuid not null,
1196 + request_hash text not null,
1197 + response_body jsonb not null,
1198 + response_status integer not null,
1199 + accepted_at timestamptz not null default now(),
1200 + primary key(user_id,id)
1201 +);
1202 +
1203 +commit;
1204 +$qa_original_0008$,'UTF8'),'sha256'),'hex'));
1205 +-- Original LifeGuide migration 0009_authorization_privacy.sql
1206 +
1207 +
1208 +create or replace function can_view_student_academic(p_viewer uuid, p_student uuid) returns boolean
1209 +language sql stable as $$
1210 + select p_viewer=p_student or exists(
1211 + select 1 from guardian_relationship g
1212 + where g.guardian_user_id=p_viewer
1213 + and g.minor_user_id=p_student
1214 + and is_active_guardian(g.family_id,p_viewer,p_student)
1215 + )
1216 +$$;
1217 +
1218 +create or replace function can_view_plan_item(p_viewer uuid, p_item uuid) returns boolean
1219 +language sql stable as $$
1220 + select exists(
1221 + select 1 from plan_item p
1222 + where p.id=p_item
1223 + and (
1224 + p.owner_user_id=p_viewer
1225 + or (
1226 + p.family_id is not null
1227 + and is_active_family_member(p.family_id,p.owner_user_id)
1228 + and is_active_family_member(p.family_id,p_viewer)
1229 + and (
1230 + p.visibility='family'
1231 + or (
1232 + p.visibility='parent_guardian'
1233 + and is_active_guardian(p.family_id,p_viewer,p.owner_user_id)
1234 + )
1235 + or (
1236 + p.visibility='selected_members'
1237 + and exists(
1238 + select 1 from sharing_grant sg
1239 + where sg.resource_type='plan_item'
1240 + and sg.resource_id=p.id
1241 + and sg.grantee_user_id=p_viewer
1242 + and sg.granted_by=p.owner_user_id
1243 + )
1244 + )
1245 + )
1246 + )
1247 + )
1248 + )
1249 +$$;
1250 +
1251 +-- Remove grants that are already invalid; later rejoining must not restore them.
1252 +delete from sharing_grant sg
1253 + where sg.resource_type='plan_item'
1254 + and not exists(
1255 + select 1 from plan_item p
1256 + where p.id=sg.resource_id
1257 + and p.visibility='selected_members'
1258 + and p.family_id is not null
1259 + and sg.granted_by=p.owner_user_id
1260 + and is_active_family_member(p.family_id,p.owner_user_id)
1261 + and is_active_family_member(p.family_id,sg.grantee_user_id)
1262 + );
1263 +
1264 +create function revoke_changed_plan_item_grants() returns trigger
1265 +language plpgsql as $$
1266 +begin
1267 + if new.visibility <> 'selected_members'
1268 + or new.family_id is distinct from old.family_id
1269 + or new.owner_user_id is distinct from old.owner_user_id then
1270 + delete from sharing_grant where resource_type='plan_item' and resource_id=new.id;
1271 + end if;
1272 + return new;
1273 +end
1274 +$$;
1275 +
1276 +create trigger plan_item_revoke_changed_grants
1277 +after update of visibility,family_id,owner_user_id on plan_item
1278 +for each row execute function revoke_changed_plan_item_grants();
1279 +
1280 +create function revoke_ended_membership_grants() returns trigger
1281 +language plpgsql as $$
1282 +begin
1283 + if tg_op='DELETE' or new.ended_at is not null then
1284 + delete from sharing_grant sg
1285 + using plan_item p
1286 + where sg.resource_type='plan_item'
1287 + and sg.resource_id=p.id
1288 + and p.family_id=old.family_id
1289 + and (p.owner_user_id=old.user_id or sg.grantee_user_id=old.user_id);
1290 + end if;
1291 + return null;
1292 +end
1293 +$$;
1294 +
1295 +create trigger family_membership_revoke_ended_grants
1296 +after update of ended_at or delete on family_membership
1297 +for each row execute function revoke_ended_membership_grants();
1298 +
1299 +
1300 +insert into lifeguide_qa.schema_migration(filename,sha256)
1301 +values ('0009_authorization_privacy.sql',encode(digest(convert_to($qa_original_0009$begin;
1302 +
1303 +create or replace function can_view_student_academic(p_viewer uuid, p_student uuid) returns boolean
1304 +language sql stable as $$
1305 + select p_viewer=p_student or exists(
1306 + select 1 from guardian_relationship g
1307 + where g.guardian_user_id=p_viewer
1308 + and g.minor_user_id=p_student
1309 + and is_active_guardian(g.family_id,p_viewer,p_student)
1310 + )
1311 +$$;
1312 +
1313 +create or replace function can_view_plan_item(p_viewer uuid, p_item uuid) returns boolean
1314 +language sql stable as $$
1315 + select exists(
1316 + select 1 from plan_item p
1317 + where p.id=p_item
1318 + and (
1319 + p.owner_user_id=p_viewer
1320 + or (
1321 + p.family_id is not null
1322 + and is_active_family_member(p.family_id,p.owner_user_id)
1323 + and is_active_family_member(p.family_id,p_viewer)
1324 + and (
1325 + p.visibility='family'
1326 + or (
1327 + p.visibility='parent_guardian'
1328 + and is_active_guardian(p.family_id,p_viewer,p.owner_user_id)
1329 + )
1330 + or (
1331 + p.visibility='selected_members'
1332 + and exists(
1333 + select 1 from sharing_grant sg
1334 + where sg.resource_type='plan_item'
1335 + and sg.resource_id=p.id
1336 + and sg.grantee_user_id=p_viewer
1337 + and sg.granted_by=p.owner_user_id
1338 + )
1339 + )
1340 + )
1341 + )
1342 + )
1343 + )
1344 +$$;
1345 +
1346 +-- Remove grants that are already invalid; later rejoining must not restore them.
1347 +delete from sharing_grant sg
1348 + where sg.resource_type='plan_item'
1349 + and not exists(
1350 + select 1 from plan_item p
1351 + where p.id=sg.resource_id
1352 + and p.visibility='selected_members'
1353 + and p.family_id is not null
1354 + and sg.granted_by=p.owner_user_id
1355 + and is_active_family_member(p.family_id,p.owner_user_id)
1356 + and is_active_family_member(p.family_id,sg.grantee_user_id)
1357 + );
1358 +
1359 +create function revoke_changed_plan_item_grants() returns trigger
1360 +language plpgsql as $$
1361 +begin
1362 + if new.visibility <> 'selected_members'
1363 + or new.family_id is distinct from old.family_id
1364 + or new.owner_user_id is distinct from old.owner_user_id then
1365 + delete from sharing_grant where resource_type='plan_item' and resource_id=new.id;
1366 + end if;
1367 + return new;
1368 +end
1369 +$$;
1370 +
1371 +create trigger plan_item_revoke_changed_grants
1372 +after update of visibility,family_id,owner_user_id on plan_item
1373 +for each row execute function revoke_changed_plan_item_grants();
1374 +
1375 +create function revoke_ended_membership_grants() returns trigger
1376 +language plpgsql as $$
1377 +begin
1378 + if tg_op='DELETE' or new.ended_at is not null then
1379 + delete from sharing_grant sg
1380 + using plan_item p
1381 + where sg.resource_type='plan_item'
1382 + and sg.resource_id=p.id
1383 + and p.family_id=old.family_id
1384 + and (p.owner_user_id=old.user_id or sg.grantee_user_id=old.user_id);
1385 + end if;
1386 + return null;
1387 +end
1388 +$$;
1389 +
1390 +create trigger family_membership_revoke_ended_grants
1391 +after update of ended_at or delete on family_membership
1392 +for each row execute function revoke_ended_membership_grants();
1393 +
1394 +commit;
1395 +$qa_original_0009$,'UTF8'),'sha256'),'hex'));
1396 +-- Original LifeGuide migration 0010_planner_sync.sql
1397 +
1398 +
1399 +alter table plan_item add column if not exists version bigint not null default 0;
1400 +alter table plan_item alter column version set default 1;
1401 +alter table plan_item add column planned_duration_seconds integer
1402 + check(planned_duration_seconds is null or planned_duration_seconds between 0 and 86400);
1403 +update plan_item set planned_duration_seconds=duration_minutes*60 where duration_minutes is not null;
1404 +
1405 +alter table sync_mutation drop constraint sync_mutation_pkey;
1406 +alter table sync_mutation add primary key(user_id,id);
1407 +alter table sync_mutation drop constraint sync_mutation_operation_check;
1408 +alter table sync_mutation add constraint sync_mutation_operation_check
1409 + check(operation in ('create','update','complete','reschedule','archive'));
1410 +alter table sync_mutation add column request_hash text;
1411 +alter table sync_mutation add column canonical_item jsonb;
1412 +
1413 +create or replace function is_active_family_member(p_family uuid,p_user uuid) returns boolean
1414 +language sql stable as $$
1415 + select exists(select 1 from family_membership m join family_workspace f on f.id=m.family_id
1416 + where m.family_id=p_family and m.user_id=p_user and m.ended_at is null and f.archived_at is null)
1417 +$$;
1418 +create or replace function is_active_guardian(p_family uuid,p_guardian uuid,p_minor uuid) returns boolean
1419 +language sql stable as $$
1420 + select exists(select 1 from guardian_relationship g
1421 + join family_workspace f on f.id=g.family_id and f.archived_at is null
1422 + join family_membership gm on gm.family_id=g.family_id and gm.user_id=g.guardian_user_id
1423 + and gm.ended_at is null and gm.role='parent_guardian'
1424 + join family_membership mm on mm.family_id=g.family_id and mm.user_id=g.minor_user_id
1425 + and mm.ended_at is null and mm.role='teen_minor'
1426 + where g.family_id=p_family and g.guardian_user_id=p_guardian and g.minor_user_id=p_minor and g.active)
1427 +$$;
1428 +create or replace function is_family_admin(p_family uuid,p_user uuid) returns boolean
1429 +language sql stable as $$
1430 + select exists(select 1 from family_membership m join family_workspace f on f.id=m.family_id
1431 + where m.family_id=p_family and m.user_id=p_user and m.ended_at is null and m.is_admin and f.archived_at is null)
1432 +$$;
1433 +
1434 +-- Legacy planner PATCH/sync writes still record explicit self-reported activity
1435 +-- transitions. Dedicated study/activity writes already advance activity_version.
1436 +create function plan_item_legacy_activity() returns trigger language plpgsql as $$
1437 +begin
1438 + if new.status is distinct from old.status and new.activity_version=old.activity_version
1439 + and new.status<>'cancelled' then
1440 + new.activity_version := old.activity_version+1;
1441 + insert into activity_state_event(plan_item_id,actor_user_id,state,source,occurred_at,version)
1442 + values(new.id,new.owner_user_id,
1443 + case new.status when 'completed' then 'completed' when 'in_progress' then 'started' else 'planned' end,
1444 + 'self_reported',coalesce(new.completed_at,new.updated_at),new.activity_version);
1445 + end if;
1446 + return new;
1447 +end $$;
1448 +create trigger plan_item_legacy_activity before update on plan_item
1449 +for each row execute function plan_item_legacy_activity();
1450 +
1451 +
1452 +insert into lifeguide_qa.schema_migration(filename,sha256)
1453 +values ('0010_planner_sync.sql',encode(digest(convert_to($qa_original_0010$begin;
1454 +
1455 +alter table plan_item add column if not exists version bigint not null default 0;
1456 +alter table plan_item alter column version set default 1;
1457 +alter table plan_item add column planned_duration_seconds integer
1458 + check(planned_duration_seconds is null or planned_duration_seconds between 0 and 86400);
1459 +update plan_item set planned_duration_seconds=duration_minutes*60 where duration_minutes is not null;
1460 +
1461 +alter table sync_mutation drop constraint sync_mutation_pkey;
1462 +alter table sync_mutation add primary key(user_id,id);
1463 +alter table sync_mutation drop constraint sync_mutation_operation_check;
1464 +alter table sync_mutation add constraint sync_mutation_operation_check
1465 + check(operation in ('create','update','complete','reschedule','archive'));
1466 +alter table sync_mutation add column request_hash text;
1467 +alter table sync_mutation add column canonical_item jsonb;
1468 +
1469 +create or replace function is_active_family_member(p_family uuid,p_user uuid) returns boolean
1470 +language sql stable as $$
1471 + select exists(select 1 from family_membership m join family_workspace f on f.id=m.family_id
1472 + where m.family_id=p_family and m.user_id=p_user and m.ended_at is null and f.archived_at is null)
1473 +$$;
1474 +create or replace function is_active_guardian(p_family uuid,p_guardian uuid,p_minor uuid) returns boolean
1475 +language sql stable as $$
1476 + select exists(select 1 from guardian_relationship g
1477 + join family_workspace f on f.id=g.family_id and f.archived_at is null
1478 + join family_membership gm on gm.family_id=g.family_id and gm.user_id=g.guardian_user_id
1479 + and gm.ended_at is null and gm.role='parent_guardian'
1480 + join family_membership mm on mm.family_id=g.family_id and mm.user_id=g.minor_user_id
1481 + and mm.ended_at is null and mm.role='teen_minor'
1482 + where g.family_id=p_family and g.guardian_user_id=p_guardian and g.minor_user_id=p_minor and g.active)
1483 +$$;
1484 +create or replace function is_family_admin(p_family uuid,p_user uuid) returns boolean
1485 +language sql stable as $$
1486 + select exists(select 1 from family_membership m join family_workspace f on f.id=m.family_id
1487 + where m.family_id=p_family and m.user_id=p_user and m.ended_at is null and m.is_admin and f.archived_at is null)
1488 +$$;
1489 +
1490 +-- Legacy planner PATCH/sync writes still record explicit self-reported activity
1491 +-- transitions. Dedicated study/activity writes already advance activity_version.
1492 +create function plan_item_legacy_activity() returns trigger language plpgsql as $$
1493 +begin
1494 + if new.status is distinct from old.status and new.activity_version=old.activity_version
1495 + and new.status<>'cancelled' then
1496 + new.activity_version := old.activity_version+1;
1497 + insert into activity_state_event(plan_item_id,actor_user_id,state,source,occurred_at,version)
1498 + values(new.id,new.owner_user_id,
1499 + case new.status when 'completed' then 'completed' when 'in_progress' then 'started' else 'planned' end,
1500 + 'self_reported',coalesce(new.completed_at,new.updated_at),new.activity_version);
1501 + end if;
1502 + return new;
1503 +end $$;
1504 +create trigger plan_item_legacy_activity before update on plan_item
1505 +for each row execute function plan_item_legacy_activity();
1506 +
1507 +commit;
1508 +$qa_original_0010$,'UTF8'),'sha256'),'hex'));
1509 +revoke all on schema lifeguide_qa from public,anon,authenticated,service_role;
1510 +revoke all on all tables in schema lifeguide_qa from public,anon,authenticated,service_role;
1511 +revoke all on all sequences in schema lifeguide_qa from public,anon,authenticated,service_role;
1512 +revoke all on all functions in schema lifeguide_qa from public,anon,authenticated,service_role;
1513 +do $lockdown$ declare rowrecord record; begin
1514 + for rowrecord in select c.relname from pg_class c join pg_namespace n on n.oid=c.relnamespace
1515 + where n.nspname='lifeguide_qa' and c.relkind in ('r','p') loop
1516 + execute format('alter table %I.%I enable row level security','lifeguide_qa',rowrecord.relname);
1517 + execute format('alter table %I.%I force row level security','lifeguide_qa',rowrecord.relname);
1518 + end loop;
1519 +end $lockdown$;
1520 +commit;
\ No newline at end of file