From f4ceaf68f9a6dd62a54c71acf551171101df4940 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 23:42:43 +0200 Subject: [PATCH] feat(supabase): anatomical sheets, immutable versions, assets, lifecycle RPCs, RLS + pgTAP --- .../20261008110000_anatomical_sheets.sql | 1083 +++++++++++++++++ supabase/tests/005_anatomical_sheets.sql | 511 ++++++++ 2 files changed, 1594 insertions(+) create mode 100644 supabase/migrations/20261008110000_anatomical_sheets.sql create mode 100644 supabase/tests/005_anatomical_sheets.sql diff --git a/supabase/migrations/20261008110000_anatomical_sheets.sql b/supabase/migrations/20261008110000_anatomical_sheets.sql new file mode 100644 index 00000000..88ca7948 --- /dev/null +++ b/supabase/migrations/20261008110000_anatomical_sheets.sql @@ -0,0 +1,1083 @@ +-- Anatomical sheets: species reference, sheet identity, immutable published +-- versions, content-addressed assets, lifecycle RPCs. +-- Spec: docs/development/ANATOMICAL_SHEET_MODEL.md. Business architecture +-- §2.6–§2.9, §7, §16, §17.3. Forward-only: never edit once applied. +-- +-- The canonical document (views, annotations, finding tree) is JSONB in +-- anatomical_sheet_versions.content. Zod owns its shape; SQL owns what only +-- the database knows (species of the parent sheet, registered assets, +-- immutability, numbering) and re-checks the referential rules at +-- publication so a browser cannot publish a dangling document. + +-- --------------------------------------------------------------------------- +-- Species (reference data) +-- --------------------------------------------------------------------------- +create table public.species ( + id text primary key + constraint species_id_format check (id ~ '^[a-z0-9][a-z0-9_-]{0,63}$'), + name_fr text not null + constraint species_name_fr_length check (char_length(name_fr) between 1 and 80), + name_en text not null + constraint species_name_en_length check (char_length(name_en) between 1 and 80), + sort_order integer not null default 100, + active boolean not null default true, + created_at timestamptz not null default now() +); + +comment on table public.species is + 'Species a sheet can describe. Reference data seeded by migrations; no API write path.'; + +insert into public.species (id, name_fr, name_en, sort_order) +values ('equine', 'Cheval', 'Horse', 10) +on conflict (id) do nothing; + +-- --------------------------------------------------------------------------- +-- Enums +-- --------------------------------------------------------------------------- +create type public.sheet_visibility as enum ('private', 'public'); +create type public.sheet_status as enum ('active', 'archived', 'deleted'); +create type public.sheet_version_status as enum ('draft', 'published', 'deprecated'); + +-- --------------------------------------------------------------------------- +-- Sheets +-- --------------------------------------------------------------------------- +create table public.anatomical_sheets ( + id uuid primary key default gen_random_uuid(), + species_id text not null references public.species (id), + name text not null + constraint anatomical_sheets_name_length check (char_length(name) between 1 and 120), + slug text not null + constraint anatomical_sheets_slug_format check (slug ~ '^[a-z0-9][a-z0-9-]{1,79}$'), + description text not null default '' + constraint anatomical_sheets_description_length check (char_length(description) <= 2000), + -- null = platform-owned (official sheets, seeds). + creator_user_id uuid references public.profiles (id) on delete restrict, + is_official boolean not null default false, + visibility public.sheet_visibility not null default 'private', + status public.sheet_status not null default 'active', + -- Provenance of a copy. The copy survives the source (set null). + based_on_sheet_id uuid references public.anatomical_sheets (id) on delete set null, + based_on_version_id uuid, + current_version_id uuid, + archived_at timestamptz, + deleted_at timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint anatomical_sheets_owner check (is_official or creator_user_id is not null) +); + +comment on table public.anatomical_sheets is + 'Fiche anatomique identity: owner, visibility, status, provenance (based_on_*), current published version. Content lives in anatomical_sheet_versions.'; +comment on column public.anatomical_sheets.is_official is + 'Platform-owned sheet (creator null), created and edited by platform admins only.'; + +-- One slug per owner scope; platform-owned sheets share one scope. +create unique index anatomical_sheets_slug_owner_unique + on public.anatomical_sheets ( + coalesce(creator_user_id, '00000000-0000-0000-0000-000000000000'::uuid), slug + ) + where status <> 'deleted'; +create index anatomical_sheets_creator_idx + on public.anatomical_sheets (creator_user_id) where status <> 'deleted'; +create index anatomical_sheets_public_idx + on public.anatomical_sheets (species_id) where visibility = 'public' and status = 'active'; +create index anatomical_sheets_based_on_idx + on public.anatomical_sheets (based_on_version_id) where based_on_version_id is not null; + +create trigger anatomical_sheets_set_updated_at + before update on public.anatomical_sheets + for each row execute function private.set_updated_at(); + +-- --------------------------------------------------------------------------- +-- Versions +-- --------------------------------------------------------------------------- +create table public.anatomical_sheet_versions ( + id uuid primary key default gen_random_uuid(), + sheet_id uuid not null references public.anatomical_sheets (id) on delete cascade, + version_number integer not null + constraint anatomical_sheet_versions_number_positive check (version_number > 0), + status public.sheet_version_status not null default 'draft', + document_schema_version integer not null + constraint anatomical_sheet_versions_schema_known check (document_schema_version = 1), + content jsonb not null + constraint anatomical_sheet_versions_content_object check (jsonb_typeof(content) = 'object'), + change_note text not null default '' + constraint anatomical_sheet_versions_change_note_length check (char_length(change_note) <= 1000), + created_by uuid references public.profiles (id) on delete set null, + published_at timestamptz, + published_by uuid references public.profiles (id) on delete set null, + deprecated_at timestamptz, + deprecated_by uuid references public.profiles (id) on delete set null, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint anatomical_sheet_versions_number_unique unique (sheet_id, version_number), + -- The document declares its own schema version; both must agree. + constraint anatomical_sheet_versions_schema_matches + check ((content -> 'schema_version') = to_jsonb(document_schema_version)), + constraint anatomical_sheet_versions_published_stamped + check (status = 'draft' or published_at is not null), + constraint anatomical_sheet_versions_deprecated_stamped + check (status <> 'deprecated' or deprecated_at is not null) +); + +comment on table public.anatomical_sheet_versions is + 'Numbered versions of a sheet. content = canonical document (Zod schema in packages/domain). Published rows are immutable; drafts are editable by the sheet editors.'; + +-- At most one draft per sheet (OPEN_QUESTIONS C8). +create unique index anatomical_sheet_versions_one_draft + on public.anatomical_sheet_versions (sheet_id) where status = 'draft'; +create index anatomical_sheet_versions_published_idx + on public.anatomical_sheet_versions (sheet_id, version_number desc) where status = 'published'; + +alter table public.anatomical_sheets + add constraint anatomical_sheets_based_on_version_fkey + foreign key (based_on_version_id) references public.anatomical_sheet_versions (id) on delete set null, + add constraint anatomical_sheets_current_version_fkey + foreign key (current_version_id) references public.anatomical_sheet_versions (id) on delete restrict; + +create trigger anatomical_sheet_versions_set_updated_at + before update on public.anatomical_sheet_versions + for each row execute function private.set_updated_at(); + +-- --------------------------------------------------------------------------- +-- Assets (content-addressed SVG files, metadata only; bytes live in Storage +-- under anatomical-sheet-assets/.svg) +-- --------------------------------------------------------------------------- +create table public.anatomical_sheet_assets ( + id uuid primary key default gen_random_uuid(), + sheet_id uuid not null references public.anatomical_sheets (id) on delete cascade, + sha256 text not null + constraint anatomical_sheet_assets_sha256_format check (sha256 ~ '^[0-9a-f]{64}$'), + byte_size integer not null + constraint anatomical_sheet_assets_byte_size_positive check (byte_size > 0), + content_type text not null default 'image/svg+xml' + constraint anatomical_sheet_assets_content_type check (content_type in ('image/svg+xml')), + file_name text not null + constraint anatomical_sheet_assets_file_name_length check (char_length(file_name) between 1 and 255), + created_by uuid references public.profiles (id) on delete set null, + created_at timestamptz not null default now(), + constraint anatomical_sheet_assets_sheet_sha_unique unique (sheet_id, sha256) +); + +comment on table public.anatomical_sheet_assets is + 'SVG assets of a sheet, immutable and content-addressed (sha256). Referenced from the document views by id. Bytes in Storage, path derived from sha256.'; + +create index anatomical_sheet_assets_sheet_idx on public.anatomical_sheet_assets (sheet_id); + +-- --------------------------------------------------------------------------- +-- Guards (every role, table owner included) +-- --------------------------------------------------------------------------- + +-- Document ↔ row: the document must describe the sheet's species. +create or replace function private.check_sheet_version_document() +returns trigger +language plpgsql +set search_path = '' +as $$ +declare + v_species text; +begin + select species_id into v_species from public.anatomical_sheets where id = new.sheet_id; + if new.content ->> 'species_id' is distinct from v_species then + raise exception 'document species % does not match sheet species %', + new.content ->> 'species_id', v_species + using errcode = '23514'; + end if; + return new; +end; +$$; + +create trigger anatomical_sheet_versions_check_document + before insert or update of content, sheet_id on public.anatomical_sheet_versions + for each row execute function private.check_sheet_version_document(); + +-- Published rows are immutable: the only transition is published → deprecated +-- (status + deprecation stamps). Deprecated rows are frozen. A draft may +-- change content or become published, never deprecated directly. +create or replace function private.guard_sheet_version_update() +returns trigger +language plpgsql +set search_path = '' +as $$ +declare + v_same_core boolean; +begin + if new.sheet_id <> old.sheet_id or new.version_number <> old.version_number then + raise exception 'sheet_id and version_number are immutable' using errcode = '42501'; + end if; + + if old.status = 'deprecated' then + raise exception 'deprecated version % is frozen', old.id using errcode = '42501'; + end if; + + if old.status = 'published' then + v_same_core := + new.content = old.content + and new.document_schema_version = old.document_schema_version + and new.change_note = old.change_note + and new.created_by is not distinct from old.created_by + and new.published_at = old.published_at + and new.published_by is not distinct from old.published_by + and new.created_at = old.created_at; + if new.status = 'deprecated' and v_same_core then + return new; + end if; + raise exception 'published version % is immutable', old.id using errcode = '42501'; + end if; + + -- old.status = 'draft' + if new.status = 'deprecated' then + raise exception 'a draft cannot be deprecated; delete it' using errcode = '55000'; + end if; + return new; +end; +$$; + +create trigger anatomical_sheet_versions_guard_update + before update on public.anatomical_sheet_versions + for each row execute function private.guard_sheet_version_update(); + +-- Dependents that block a physical delete (business architecture §16). +-- Reports join this check when their table exists. +create or replace function private.sheet_version_dependents(p_version_id uuid) +returns text[] +language sql +stable +security definer +set search_path = '' +as $$ + select array_remove(array[ + case when exists ( + select 1 from public.anatomical_sheets s where s.current_version_id = p_version_id + ) then 'current_version' end, + case when exists ( + select 1 from public.anatomical_sheets s + where s.based_on_version_id = p_version_id and s.status <> 'deleted' + ) then 'active_fork' end + ], null); +$$; + +create or replace function private.guard_sheet_version_delete() +returns trigger +language plpgsql +set search_path = '' +as $$ +declare + v_dependents text[]; +begin + if old.status = 'published' then + raise exception 'published version % cannot be deleted; deprecate it first', old.id + using errcode = '55000'; + end if; + v_dependents := private.sheet_version_dependents(old.id); + if coalesce(array_length(v_dependents, 1), 0) > 0 then + raise exception 'version % still has dependents: %', old.id, v_dependents + using errcode = '55000'; + end if; + return old; +end; +$$; + +create trigger anatomical_sheet_versions_guard_delete + before delete on public.anatomical_sheet_versions + for each row execute function private.guard_sheet_version_delete(); + +-- --------------------------------------------------------------------------- +-- Document referential checks (publication gate). Mirrors the error-level +-- rules of packages/domain validateSheetDocument that need no recursion. +-- --------------------------------------------------------------------------- +create or replace function private.append_issue(p_issues text[], p_code text) +returns text[] +language sql +immutable +set search_path = '' +as $$ + select case when p_issues @> array[p_code] then p_issues else p_issues || p_code end; +$$; + +create or replace function private.sheet_document_issues(p_doc jsonb) +returns text[] +language plpgsql +immutable +set search_path = '' +as $$ +declare + v_issues text[] := '{}'; + v_views jsonb := coalesce(p_doc -> 'views', '[]'::jsonb); + v_anns jsonb := coalesce(p_doc -> 'annotations', '[]'::jsonb); + v_cats jsonb := coalesce(p_doc -> 'categories', '[]'::jsonb); + v_zones jsonb := coalesce(p_doc -> 'finding_zones', '[]'::jsonb); + v_regs jsonb := coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb); + r record; +begin + if jsonb_typeof(v_views) <> 'array' or jsonb_typeof(v_anns) <> 'array' + or jsonb_typeof(v_cats) <> 'array' or jsonb_typeof(v_zones) <> 'array' + or jsonb_typeof(v_regs) <> 'array' then + return array['document.shape']; + end if; + + if (select count(*) from jsonb_array_elements(v_views) v where v ->> 'kind' = 'main') <> 1 then + v_issues := private.append_issue(v_issues, 'view.main.count'); + end if; + if exists (select 1 from jsonb_array_elements(v_views) v group by v ->> 'id' having count(*) > 1) then + v_issues := private.append_issue(v_issues, 'view.id.duplicate'); + end if; + if exists (select 1 from jsonb_array_elements(v_anns) a group by a ->> 'id' having count(*) > 1) then + v_issues := private.append_issue(v_issues, 'annotation.id.duplicate'); + end if; + if exists (select 1 from jsonb_array_elements(v_cats) c group by c ->> 'id' having count(*) > 1) then + v_issues := private.append_issue(v_issues, 'category.id.duplicate'); + end if; + if exists (select 1 from jsonb_array_elements(v_zones) z group by z ->> 'id' having count(*) > 1) then + v_issues := private.append_issue(v_issues, 'finding_zone.id.duplicate'); + end if; + if exists (select 1 from jsonb_array_elements(v_regs) g group by g ->> 'code' having count(*) > 1) then + v_issues := private.append_issue(v_issues, 'region.code.duplicate'); + end if; + + for r in + select v ->> 'id' as id, v ->> 'kind' as kind, v ->> 'parent_view_id' as parent, + v ->> 'svg_asset_id' as asset, v -> 'view_box' as view_box + from jsonb_array_elements(v_views) v + loop + if r.kind = 'detail' then + if not exists (select 1 from jsonb_array_elements(v_views) p where p ->> 'id' = r.parent) then + v_issues := private.append_issue(v_issues, 'view.parent.missing'); + elsif not exists ( + select 1 from jsonb_array_elements(v_anns) a + where a ->> 'kind' = 'detail_trigger' + and a ->> 'opens_view_id' = r.id and a ->> 'view_id' = r.parent + ) then + v_issues := private.append_issue(v_issues, 'view.unreachable'); + end if; + if r.asset is null and (r.view_box is null or jsonb_typeof(r.view_box) = 'null') then + v_issues := private.append_issue(v_issues, 'view.asset.missing'); + end if; + elsif r.asset is null then + v_issues := private.append_issue(v_issues, 'view.asset.missing'); + end if; + end loop; + + for r in + select a ->> 'kind' as kind, a ->> 'view_id' as view_id, a ->> 'category_id' as category_id, + a ->> 'opens_view_id' as opens, a ->> 'finding_zone_id' as zone, + a ->> 'vertebral_region_code' as region + from jsonb_array_elements(v_anns) a + loop + if not exists (select 1 from jsonb_array_elements(v_views) v where v ->> 'id' = r.view_id) then + v_issues := private.append_issue(v_issues, 'annotation.view.missing'); + end if; + if not exists (select 1 from jsonb_array_elements(v_cats) c where c ->> 'id' = r.category_id) then + v_issues := private.append_issue(v_issues, 'annotation.category.missing'); + end if; + if r.kind = 'detail_trigger' and not exists ( + select 1 from jsonb_array_elements(v_views) v + where v ->> 'id' = r.opens and v ->> 'kind' = 'detail' and v ->> 'parent_view_id' = r.view_id + ) then + v_issues := private.append_issue(v_issues, 'annotation.opens_view.invalid'); + end if; + if r.zone is not null and not exists ( + select 1 from jsonb_array_elements(v_zones) z where z ->> 'id' = r.zone + ) then + v_issues := private.append_issue(v_issues, 'annotation.finding_zone.missing'); + end if; + if r.region is not null and not exists ( + select 1 from jsonb_array_elements(v_regs) g where g ->> 'code' = r.region + ) then + v_issues := private.append_issue(v_issues, 'annotation.region.missing'); + end if; + end loop; + + return v_issues; +end; +$$; + +comment on function private.sheet_document_issues(jsonb) is + 'Error-level referential rules of the canonical document (codes shared with packages/domain). Empty array = publishable as far as SQL can tell.'; + +-- Every svg_asset_id used by a view must be an asset registered for the sheet. +create or replace function private.sheet_document_unknown_assets(p_sheet_id uuid, p_doc jsonb) +returns text[] +language sql +stable +security definer +set search_path = '' +as $$ + select coalesce(array_agg(v ->> 'svg_asset_id'), '{}') + from jsonb_array_elements(coalesce(p_doc -> 'views', '[]'::jsonb)) v + where v ->> 'svg_asset_id' is not null + and not exists ( + select 1 from public.anatomical_sheet_assets a + where a.sheet_id = p_sheet_id and a.id::text = v ->> 'svg_asset_id' + ); +$$; + +-- --------------------------------------------------------------------------- +-- Access helpers (security definer, read the sheets bypassing their policies) +-- --------------------------------------------------------------------------- +create or replace function private.can_edit_sheet(p_user_id uuid, p_sheet_id uuid) +returns boolean +language sql +stable +security definer +set search_path = '' +as $$ + select exists ( + select 1 from public.anatomical_sheets s + where s.id = p_sheet_id + and s.status <> 'deleted' + and ( + (s.creator_user_id is not null and s.creator_user_id = p_user_id) + or (s.is_official and private.is_platform_admin(p_user_id)) + ) + ); +$$; + +-- Grants and follows (community step) will widen this predicate. +create or replace function private.can_use_sheet(p_user_id uuid, p_sheet_id uuid) +returns boolean +language sql +stable +security definer +set search_path = '' +as $$ + select exists ( + select 1 from public.anatomical_sheets s + where s.id = p_sheet_id + and s.status = 'active' + and (s.visibility = 'public' or private.can_edit_sheet(p_user_id, p_sheet_id)) + ); +$$; + +comment on function private.can_edit_sheet(uuid, uuid) is 'creator of a non-deleted sheet, or platform admin on an official sheet.'; +comment on function private.can_use_sheet(uuid, uuid) is 'active sheet that is public or editable by the user. Follows/grants plug in here later.'; + +grant execute on function private.can_edit_sheet(uuid, uuid) to authenticated; +grant execute on function private.can_use_sheet(uuid, uuid) to authenticated; + +-- --------------------------------------------------------------------------- +-- Internal helpers for the RPCs +-- --------------------------------------------------------------------------- +create or replace function private.require_actor() +returns uuid +language plpgsql +stable +set search_path = '' +as $$ +declare + v_actor uuid := auth.uid(); +begin + if v_actor is null then + raise exception 'authentication required' using errcode = '42501'; + end if; + return v_actor; +end; +$$; + +create or replace function private.require_sheet_editor(p_actor uuid, p_sheet_id uuid) +returns void +language plpgsql +stable +set search_path = '' +as $$ +begin + if not private.can_edit_sheet(p_actor, p_sheet_id) then + raise exception 'not an editor of sheet %', p_sheet_id using errcode = '42501'; + end if; +end; +$$; + +-- Inserts a draft with the next version number. The sheet row is locked so +-- two concurrent calls cannot pick the same number. +create or replace function private.insert_sheet_draft( + p_actor uuid, + p_sheet_id uuid, + p_content jsonb, + p_change_note text +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_number integer; + v_id uuid; +begin + perform 1 from public.anatomical_sheets where id = p_sheet_id for update; + if exists ( + select 1 from public.anatomical_sheet_versions + where sheet_id = p_sheet_id and status = 'draft' + ) then + raise exception 'sheet % already has a draft', p_sheet_id using errcode = '23505'; + end if; + select coalesce(max(version_number), 0) + 1 into v_number + from public.anatomical_sheet_versions where sheet_id = p_sheet_id; + + insert into public.anatomical_sheet_versions ( + sheet_id, version_number, status, document_schema_version, content, change_note, created_by + ) + values ( + p_sheet_id, v_number, 'draft', (p_content ->> 'schema_version')::integer, + p_content, coalesce(p_change_note, ''), p_actor + ) + returning id into v_id; + + perform private.log_event( + p_actor, 'anatomical_sheet_version.created', 'anatomical_sheet_version', v_id, null, null, + jsonb_build_object('sheet_id', p_sheet_id, 'version_number', v_number) + ); + return v_id; +end; +$$; + +-- Copies the asset rows of one sheet to another; returns old id → new id. +create or replace function private.copy_sheet_assets(p_actor uuid, p_from uuid, p_to uuid) +returns jsonb +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_map jsonb := '{}'::jsonb; + v_new uuid; + r record; +begin + for r in + select id, sha256, byte_size, content_type, file_name + from public.anatomical_sheet_assets where sheet_id = p_from + loop + insert into public.anatomical_sheet_assets ( + sheet_id, sha256, byte_size, content_type, file_name, created_by + ) + values (p_to, r.sha256, r.byte_size, r.content_type, r.file_name, p_actor) + returning id into v_new; + v_map := v_map || jsonb_build_object(r.id::text, v_new::text); + end loop; + return v_map; +end; +$$; + +-- Rewrites views[].svg_asset_id through an old → new map. +create or replace function private.remap_document_assets(p_doc jsonb, p_map jsonb) +returns jsonb +language sql +immutable +set search_path = '' +as $$ + select jsonb_set( + p_doc, + '{views}', + coalesce(( + select jsonb_agg( + case + when v ->> 'svg_asset_id' is not null and p_map ? (v ->> 'svg_asset_id') + then jsonb_set(v, '{svg_asset_id}', to_jsonb(p_map ->> (v ->> 'svg_asset_id'))) + else v + end + order by ord + ) + from jsonb_array_elements(coalesce(p_doc -> 'views', '[]'::jsonb)) with ordinality as t(v, ord) + ), '[]'::jsonb) + ); +$$; + +-- --------------------------------------------------------------------------- +-- RPCs (authenticated callers; every call audited) +-- --------------------------------------------------------------------------- +create or replace function public.create_anatomical_sheet( + species_id text, + name text, + slug text, + document jsonb, + description text default '', + visibility public.sheet_visibility default 'private', + official boolean default false +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_sheet uuid; +begin + if official and not private.is_platform_admin(v_actor) then + raise exception 'only platform admins create official sheets' using errcode = '42501'; + end if; + if not exists (select 1 from public.species s where s.id = species_id and s.active) then + raise exception 'unknown species %', species_id using errcode = 'P0002'; + end if; + + insert into public.anatomical_sheets ( + species_id, name, slug, description, creator_user_id, is_official, visibility + ) + values ( + species_id, name, slug, coalesce(description, ''), + case when official then null else v_actor end, official, visibility + ) + returning id into v_sheet; + + perform private.log_event( + v_actor, 'anatomical_sheet.created', 'anatomical_sheet', v_sheet, null, null, + jsonb_build_object('species_id', species_id, 'official', official, 'visibility', visibility) + ); + perform private.insert_sheet_draft(v_actor, v_sheet, document, 'Initial draft'); + return v_sheet; +end; +$$; + +create or replace function public.create_sheet_draft( + sheet_id uuid, + from_version_id uuid default null, + change_note text default '' +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_source uuid; + v_content jsonb; +begin + perform private.require_sheet_editor(v_actor, sheet_id); + select coalesce(from_version_id, s.current_version_id) into v_source + from public.anatomical_sheets s where s.id = sheet_id; + + select v.content into v_content + from public.anatomical_sheet_versions v + where v.id = v_source and v.sheet_id = create_sheet_draft.sheet_id and v.status <> 'draft'; + if v_content is null then + raise exception 'no published version to start from (sheet %)', sheet_id using errcode = 'P0002'; + end if; + return private.insert_sheet_draft(v_actor, sheet_id, v_content, change_note); +end; +$$; + +create or replace function public.publish_sheet_version(version_id uuid) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_version public.anatomical_sheet_versions%rowtype; + v_issues text[]; +begin + select * into v_version from public.anatomical_sheet_versions where id = version_id for update; + if v_version.id is null then + raise exception 'unknown version %', version_id using errcode = 'P0002'; + end if; + perform private.require_sheet_editor(v_actor, v_version.sheet_id); + if v_version.status <> 'draft' then + raise exception 'version % is not a draft', version_id using errcode = '55000'; + end if; + + v_issues := private.sheet_document_issues(v_version.content); + if coalesce(array_length(v_issues, 1), 0) > 0 then + raise exception 'document not publishable: %', array_to_string(v_issues, ', ') + using errcode = '23514'; + end if; + v_issues := private.sheet_document_unknown_assets(v_version.sheet_id, v_version.content); + if coalesce(array_length(v_issues, 1), 0) > 0 then + raise exception 'document not publishable: view.asset.unknown %', array_to_string(v_issues, ', ') + using errcode = '23514'; + end if; + + update public.anatomical_sheet_versions + set status = 'published', published_at = now(), published_by = v_actor + where id = version_id; + update public.anatomical_sheets + set current_version_id = version_id + where id = v_version.sheet_id; + + perform private.log_event( + v_actor, 'anatomical_sheet_version.published', 'anatomical_sheet_version', version_id, null, null, + jsonb_build_object('sheet_id', v_version.sheet_id, 'version_number', v_version.version_number) + ); + return version_id; +end; +$$; + +create or replace function public.deprecate_sheet_version(version_id uuid, reason text default null) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_version public.anatomical_sheet_versions%rowtype; + v_next uuid; +begin + select * into v_version from public.anatomical_sheet_versions where id = version_id for update; + if v_version.id is null then + raise exception 'unknown version %', version_id using errcode = 'P0002'; + end if; + perform private.require_sheet_editor(v_actor, v_version.sheet_id); + if v_version.status <> 'published' then + raise exception 'version % is not published', version_id using errcode = '55000'; + end if; + + update public.anatomical_sheet_versions + set status = 'deprecated', deprecated_at = now(), deprecated_by = v_actor + where id = version_id; + + -- The sheet's current version moves to the latest remaining published one. + select id into v_next from public.anatomical_sheet_versions + where sheet_id = v_version.sheet_id and status = 'published' + order by version_number desc limit 1; + update public.anatomical_sheets + set current_version_id = v_next + where id = v_version.sheet_id and current_version_id = version_id; + + perform private.log_event( + v_actor, 'anatomical_sheet_version.deprecated', 'anatomical_sheet_version', version_id, null, null, + jsonb_build_object('sheet_id', v_version.sheet_id, 'reason', reason) + ); + return version_id; +end; +$$; + +create or replace function public.delete_sheet_version(version_id uuid) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_sheet uuid; + v_number integer; +begin + select sheet_id, version_number into v_sheet, v_number + from public.anatomical_sheet_versions where id = version_id; + if v_sheet is null then + raise exception 'unknown version %', version_id using errcode = 'P0002'; + end if; + perform private.require_sheet_editor(v_actor, v_sheet); + + -- Preconditions (published, current, active fork) are raised by the delete guard. + delete from public.anatomical_sheet_versions where id = version_id; + + perform private.log_event( + v_actor, 'anatomical_sheet_version.deleted', 'anatomical_sheet_version', version_id, null, null, + jsonb_build_object('sheet_id', v_sheet, 'version_number', v_number) + ); + return version_id; +end; +$$; + +create or replace function public.fork_anatomical_sheet( + source_version_id uuid, + name text, + slug text, + visibility public.sheet_visibility default 'private' +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_source public.anatomical_sheet_versions%rowtype; + v_species text; + v_sheet uuid; + v_map jsonb; +begin + select * into v_source from public.anatomical_sheet_versions where id = source_version_id; + if v_source.id is null then + raise exception 'unknown version %', source_version_id using errcode = 'P0002'; + end if; + if not private.can_use_sheet(v_actor, v_source.sheet_id) then + raise exception 'sheet % is not usable by the caller', v_source.sheet_id using errcode = '42501'; + end if; + if v_source.status <> 'published' then + raise exception 'only a published version can be copied' using errcode = '55000'; + end if; + + select species_id into v_species from public.anatomical_sheets where id = v_source.sheet_id; + insert into public.anatomical_sheets ( + species_id, name, slug, creator_user_id, visibility, based_on_sheet_id, based_on_version_id + ) + values (v_species, name, slug, v_actor, visibility, v_source.sheet_id, source_version_id) + returning id into v_sheet; + + v_map := private.copy_sheet_assets(v_actor, v_source.sheet_id, v_sheet); + perform private.log_event( + v_actor, 'anatomical_sheet.forked', 'anatomical_sheet', v_sheet, null, null, + jsonb_build_object('source_sheet_id', v_source.sheet_id, 'source_version_id', source_version_id) + ); + perform private.insert_sheet_draft( + v_actor, v_sheet, private.remap_document_assets(v_source.content, v_map), + 'Copied from version ' || v_source.version_number + ); + return v_sheet; +end; +$$; + +create or replace function private.set_sheet_status( + p_actor uuid, + p_sheet uuid, + p_from public.sheet_status, + p_to public.sheet_status, + p_action text +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_status public.sheet_status; +begin + perform private.require_sheet_editor(p_actor, p_sheet); + select status into v_status from public.anatomical_sheets where id = p_sheet for update; + if v_status <> p_from then + raise exception 'sheet % is % (expected %)', p_sheet, v_status, p_from using errcode = '55000'; + end if; + update public.anatomical_sheets + set status = p_to, + archived_at = case when p_to = 'archived' then now() when p_to = 'active' then null else archived_at end, + deleted_at = case when p_to = 'deleted' then now() else deleted_at end + where id = p_sheet; + perform private.log_event(p_actor, p_action, 'anatomical_sheet', p_sheet); + return p_sheet; +end; +$$; + +create or replace function public.archive_anatomical_sheet(sheet_id uuid) +returns uuid +language sql +security definer +set search_path = '' +as $$ + select private.set_sheet_status( + private.require_actor(), sheet_id, 'active', 'archived', 'anatomical_sheet.archived' + ); +$$; + +create or replace function public.restore_anatomical_sheet(sheet_id uuid) +returns uuid +language sql +security definer +set search_path = '' +as $$ + select private.set_sheet_status( + private.require_actor(), sheet_id, 'archived', 'active', 'anatomical_sheet.restored' + ); +$$; + +-- Soft delete. Refused while another sheet still derives from one of its +-- versions (§16: no active fork). Published versions stay in place. +create or replace function public.delete_anatomical_sheet(sheet_id uuid) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_status public.sheet_status; +begin + perform private.require_sheet_editor(v_actor, sheet_id); + if exists ( + select 1 from public.anatomical_sheets f + where f.based_on_sheet_id = delete_anatomical_sheet.sheet_id and f.status <> 'deleted' + ) then + raise exception 'sheet % still has active copies; archive it instead', sheet_id + using errcode = '55000'; + end if; + select status into v_status from public.anatomical_sheets where id = sheet_id; + return private.set_sheet_status(v_actor, sheet_id, v_status, 'deleted', 'anatomical_sheet.deleted'); +end; +$$; + +create or replace function public.register_sheet_asset( + sheet_id uuid, + sha256 text, + byte_size integer, + file_name text +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_id uuid; +begin + perform private.require_sheet_editor(v_actor, sheet_id); + select id into v_id from public.anatomical_sheet_assets a + where a.sheet_id = register_sheet_asset.sheet_id and a.sha256 = register_sheet_asset.sha256; + if v_id is not null then + return v_id; + end if; + + insert into public.anatomical_sheet_assets (sheet_id, sha256, byte_size, file_name, created_by) + values (sheet_id, sha256, byte_size, file_name, v_actor) + returning id into v_id; + + perform private.log_event( + v_actor, 'anatomical_sheet_asset.registered', 'anatomical_sheet_asset', v_id, null, null, + jsonb_build_object('sheet_id', sheet_id, 'sha256', sha256, 'byte_size', byte_size) + ); + return v_id; +end; +$$; + +create or replace function public.delete_sheet_asset(asset_id uuid) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_sheet uuid; +begin + select sheet_id into v_sheet from public.anatomical_sheet_assets where id = asset_id; + if v_sheet is null then + raise exception 'unknown asset %', asset_id using errcode = 'P0002'; + end if; + perform private.require_sheet_editor(v_actor, v_sheet); + if exists ( + select 1 from public.anatomical_sheet_versions v, + jsonb_array_elements(coalesce(v.content -> 'views', '[]'::jsonb)) w + where v.sheet_id = v_sheet and w ->> 'svg_asset_id' = asset_id::text + ) then + raise exception 'asset % is referenced by a version', asset_id using errcode = '55000'; + end if; + + delete from public.anatomical_sheet_assets where id = asset_id; + perform private.log_event( + v_actor, 'anatomical_sheet_asset.deleted', 'anatomical_sheet_asset', asset_id, null, null, + jsonb_build_object('sheet_id', v_sheet) + ); + return asset_id; +end; +$$; + +comment on function public.create_anatomical_sheet(text, text, text, jsonb, text, public.sheet_visibility, boolean) is + 'Creates a sheet and its draft version 1 from a canonical document. official = true needs a platform admin.'; +comment on function public.create_sheet_draft(uuid, uuid, text) is + 'Opens the single draft of a sheet, copied from a published version (default: current). 23505 when a draft exists.'; +comment on function public.publish_sheet_version(uuid) is + 'Draft → published after the SQL referential checks; becomes the sheet current version. Earlier published versions stay published.'; +comment on function public.deprecate_sheet_version(uuid, text) is + 'Published → deprecated (still readable, not offered for new reports). Current version moves to the latest published one.'; +comment on function public.delete_sheet_version(uuid) is + 'Physical delete; refused (55000) for published rows, the current version, or a version with active copies.'; +comment on function public.fork_anatomical_sheet(uuid, text, text, public.sheet_visibility) is + 'Personal copy of a published version: new sheet with based_on_* provenance, assets copied, draft v1. The source is not modified.'; +comment on function public.delete_anatomical_sheet(uuid) is + 'Soft delete (status deleted); refused while active copies derive from the sheet.'; + +-- --------------------------------------------------------------------------- +-- Privileges + RLS +-- --------------------------------------------------------------------------- +revoke all on function public.create_anatomical_sheet(text, text, text, jsonb, text, public.sheet_visibility, boolean) from public, anon; +revoke all on function public.create_sheet_draft(uuid, uuid, text) from public, anon; +revoke all on function public.publish_sheet_version(uuid) from public, anon; +revoke all on function public.deprecate_sheet_version(uuid, text) from public, anon; +revoke all on function public.delete_sheet_version(uuid) from public, anon; +revoke all on function public.fork_anatomical_sheet(uuid, text, text, public.sheet_visibility) from public, anon; +revoke all on function public.archive_anatomical_sheet(uuid) from public, anon; +revoke all on function public.restore_anatomical_sheet(uuid) from public, anon; +revoke all on function public.delete_anatomical_sheet(uuid) from public, anon; +revoke all on function public.register_sheet_asset(uuid, text, integer, text) from public, anon; +revoke all on function public.delete_sheet_asset(uuid) from public, anon; + +grant execute on function public.create_anatomical_sheet(text, text, text, jsonb, text, public.sheet_visibility, boolean) to authenticated, service_role; +grant execute on function public.create_sheet_draft(uuid, uuid, text) to authenticated, service_role; +grant execute on function public.publish_sheet_version(uuid) to authenticated, service_role; +grant execute on function public.deprecate_sheet_version(uuid, text) to authenticated, service_role; +grant execute on function public.delete_sheet_version(uuid) to authenticated, service_role; +grant execute on function public.fork_anatomical_sheet(uuid, text, text, public.sheet_visibility) to authenticated, service_role; +grant execute on function public.archive_anatomical_sheet(uuid) to authenticated, service_role; +grant execute on function public.restore_anatomical_sheet(uuid) to authenticated, service_role; +grant execute on function public.delete_anatomical_sheet(uuid) to authenticated, service_role; +grant execute on function public.register_sheet_asset(uuid, text, integer, text) to authenticated, service_role; +grant execute on function public.delete_sheet_asset(uuid) to authenticated, service_role; + +revoke all on public.species from public, anon, authenticated; +revoke all on public.anatomical_sheets from public, anon, authenticated; +revoke all on public.anatomical_sheet_versions from public, anon, authenticated; +revoke all on public.anatomical_sheet_assets from public, anon, authenticated; + +grant select on public.species to authenticated; +grant select on public.anatomical_sheets to authenticated; +-- Editors change the identity columns in place; status, provenance, ownership go through RPCs. +grant update (name, slug, description, visibility) on public.anatomical_sheets to authenticated; +grant select on public.anatomical_sheet_versions to authenticated; +-- Draft autosave: editors patch content and change_note; the guards keep +-- published rows frozen whatever the grant says. +grant update (content, change_note) on public.anatomical_sheet_versions to authenticated; +grant delete on public.anatomical_sheet_versions to authenticated; +grant select on public.anatomical_sheet_assets to authenticated; + +alter table public.species enable row level security; +alter table public.anatomical_sheets enable row level security; +alter table public.anatomical_sheet_versions enable row level security; +alter table public.anatomical_sheet_assets enable row level security; + +create policy species_select_active + on public.species + for select + to authenticated + using (active); + +create policy anatomical_sheets_select_usable_or_editable + on public.anatomical_sheets + for select + to authenticated + using ( + private.can_use_sheet((select auth.uid()), id) + or private.can_edit_sheet((select auth.uid()), id) + ); + +create policy anatomical_sheets_update_editor + on public.anatomical_sheets + for update + to authenticated + using (private.can_edit_sheet((select auth.uid()), id)) + with check (private.can_edit_sheet((select auth.uid()), id)); + +-- Published and deprecated versions follow the sheet visibility; drafts are +-- visible to editors only. +create policy anatomical_sheet_versions_select + on public.anatomical_sheet_versions + for select + to authenticated + using ( + (status <> 'draft' and private.can_use_sheet((select auth.uid()), sheet_id)) + or private.can_edit_sheet((select auth.uid()), sheet_id) + ); + +create policy anatomical_sheet_versions_update_own_draft + on public.anatomical_sheet_versions + for update + to authenticated + using (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)) + with check (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)); + +create policy anatomical_sheet_versions_delete_own_draft + on public.anatomical_sheet_versions + for delete + to authenticated + using (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)); + +create policy anatomical_sheet_assets_select + on public.anatomical_sheet_assets + for select + to authenticated + using ( + private.can_use_sheet((select auth.uid()), sheet_id) + or private.can_edit_sheet((select auth.uid()), sheet_id) + ); diff --git a/supabase/tests/005_anatomical_sheets.sql b/supabase/tests/005_anatomical_sheets.sql new file mode 100644 index 00000000..b7151985 --- /dev/null +++ b/supabase/tests/005_anatomical_sheets.sql @@ -0,0 +1,511 @@ +-- Anatomical sheets: schema contract, lifecycle (allowed path), immutability, +-- copies with provenance, deletion preconditions, invalid documents, every +-- denied path (other user, anon, direct writes, official sheets). +-- Counts are scoped to fixture ids: the real stack also carries seed rows. +begin; +select plan(95); + +-- --------------------------------------------------------------------------- +-- Fixtures +-- --------------------------------------------------------------------------- +insert into auth.users (id, email) values + ('20000000-0000-0000-0000-000000000001', 'root-sheets@test.local'), + ('20000000-0000-0000-0000-00000000000a', 'alice-sheets@test.local'), + ('20000000-0000-0000-0000-00000000000b', 'bob-sheets@test.local'); +select private.assign_platform_role(null, '20000000-0000-0000-0000-000000000001', 'owner'); + +-- A small but complete document: two views (detail without its own asset), +-- a trigger, a bilateral joint, a spine zone, one finding zone. +create function pg_temp.sheet_doc(p_asset uuid) +returns jsonb +language sql +as $$ + select jsonb_build_object( + 'schema_version', 1, + 'species_id', 'equine', + 'name', jsonb_build_object('fr', 'Cheval test', 'en', 'Test horse'), + 'description', '{}'::jsonb, + 'scope_disclaimer', '{}'::jsonb, + 'attribution', jsonb_build_object('authors', '[]'::jsonb, 'license', null, 'notes', null), + 'vertebral_config', jsonb_build_object('regions', jsonb_build_array( + jsonb_build_object('code', 'C', 'name', jsonb_build_object('fr', 'Cervicales', 'en', 'Cervical'), 'count', 7) + )), + 'categories', jsonb_build_array( + jsonb_build_object('id', 'articulations', 'name', jsonb_build_object('fr', 'Articulations', 'en', 'Joints'), 'color', null) + ), + 'views', jsonb_build_array( + jsonb_build_object('id', 'view-main', 'kind', 'main', + 'name', jsonb_build_object('fr', 'Vue principale', 'en', 'Main view'), + 'svg_asset_id', p_asset, 'view_box', null), + jsonb_build_object('id', 'view-head', 'kind', 'detail', 'parent_view_id', 'view-main', + 'name', jsonb_build_object('fr', 'Tête', 'en', 'Head'), + 'svg_asset_id', null, + 'view_box', jsonb_build_object('min_x', 60, 'min_y', 100, 'width', 500, 'height', 380)) + ), + 'annotations', jsonb_build_array( + jsonb_build_object('id', 'hip', 'kind', 'point', 'view_id', 'view-main', 'category_id', 'articulations', + 'laterality', 'bilateral', 'geometry', null, + 'name', jsonb_build_object('fr', 'Hanche', 'en', 'Hip joint'), + 'finding_zone_id', 'hip', 'vertebral_region_code', null), + jsonb_build_object('id', 'cervical', 'kind', 'zone', 'view_id', 'view-main', 'category_id', 'articulations', + 'laterality', 'unpaired', 'geometry', null, + 'name', jsonb_build_object('fr', 'Vertèbres cervicales', 'en', 'Cervical vertebrae'), + 'finding_zone_id', null, 'vertebral_region_code', 'C'), + jsonb_build_object('id', 'head-trigger', 'kind', 'detail_trigger', 'view_id', 'view-main', + 'category_id', 'articulations', 'laterality', 'unpaired', 'geometry', null, + 'name', null, 'opens_view_id', 'view-head') + ), + 'finding_zones', jsonb_build_array( + jsonb_build_object('id', 'hip', 'name', jsonb_build_object('fr', 'Hanche', 'en', 'Hip'), + 'categories', jsonb_build_array( + jsonb_build_object('id', 'hip-dysfunctions', 'kind', 'dysfunction', + 'name', jsonb_build_object('fr', 'Dysfonctions', 'en', 'Dysfunctions'), + 'children', jsonb_build_array( + jsonb_build_object('id', 'articular', 'name', jsonb_build_object('fr', 'Articulaire', 'en', 'Articular')) + )) + )) + ) + ); +$$; + +create table pg_temp.ids (key text primary key, id uuid not null); +create function pg_temp.id(p_key text) returns uuid language sql stable +as $$ select id from pg_temp.ids where key = p_key $$; +-- The fixtures are read while impersonating the API roles. +grant all on pg_temp.ids to anon, authenticated; +grant execute on function pg_temp.id(text), pg_temp.sheet_doc(uuid) to anon, authenticated; + +-- --------------------------------------------------------------------------- +-- 1. Schema contract +-- --------------------------------------------------------------------------- +select has_table('public', 'species', 'table species exists'); +select has_table('public', 'anatomical_sheets', 'table anatomical_sheets exists'); +select has_table('public', 'anatomical_sheet_versions', 'table anatomical_sheet_versions exists'); +select has_table('public', 'anatomical_sheet_assets', 'table anatomical_sheet_assets exists'); +select enum_has_labels('public', 'sheet_visibility', array['private', 'public'], 'sheet_visibility labels'); +select enum_has_labels('public', 'sheet_status', array['active', 'archived', 'deleted'], 'sheet_status labels'); +select enum_has_labels('public', 'sheet_version_status', array['draft', 'published', 'deprecated'], 'sheet_version_status labels'); +select is( + (select count(*) from public.species where id = 'equine' and active), 1::bigint, + 'species equine is seeded by the migration' +); +select ok( + (select bool_and(relrowsecurity) from pg_class + where oid in ('public.species'::regclass, 'public.anatomical_sheets'::regclass, + 'public.anatomical_sheet_versions'::regclass, 'public.anatomical_sheet_assets'::regclass)), + 'RLS enabled on the four tables' +); +select ok(not has_table_privilege('anon', 'public.anatomical_sheets', 'select'), 'anon cannot select sheets'); +select ok(not has_table_privilege('anon', 'public.anatomical_sheet_versions', 'select'), 'anon cannot select versions'); +select ok(not has_table_privilege('anon', 'public.species', 'select'), 'anon cannot select species'); +select ok(not has_table_privilege('authenticated', 'public.anatomical_sheets', 'insert'), 'authenticated cannot insert sheets directly'); +select ok(not has_table_privilege('authenticated', 'public.anatomical_sheets', 'delete'), 'authenticated cannot delete sheets directly'); +select ok(not has_column_privilege('authenticated', 'public.anatomical_sheets', 'status', 'update'), 'authenticated cannot update sheets.status'); +select ok(not has_column_privilege('authenticated', 'public.anatomical_sheets', 'is_official', 'update'), 'authenticated cannot update sheets.is_official'); +select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_versions', 'insert'), 'authenticated cannot insert versions directly'); +select ok(not has_column_privilege('authenticated', 'public.anatomical_sheet_versions', 'status', 'update'), 'authenticated cannot update versions.status'); +select ok(has_column_privilege('authenticated', 'public.anatomical_sheet_versions', 'content', 'update'), 'authenticated may update versions.content (RLS: own draft)'); +select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_assets', 'insert'), 'authenticated cannot insert assets directly'); +select ok(not has_function_privilege('anon', 'public.publish_sheet_version(uuid)', 'execute'), 'anon cannot execute publish_sheet_version'); + +-- --------------------------------------------------------------------------- +-- 2. Alice creates a private sheet (draft v1), registers an asset, publishes +-- --------------------------------------------------------------------------- +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); + +insert into pg_temp.ids select 'sheet', public.create_anatomical_sheet( + 'equine', 'Mon cheval', 'mon-cheval', pg_temp.sheet_doc(null), 'perso' +); +select results_eq( + $$ select creator_user_id, status::text, visibility::text, current_version_id, is_official + from public.anatomical_sheets where id = pg_temp.id('sheet') $$, + $$ values ('20000000-0000-0000-0000-00000000000a'::uuid, 'active', 'private', null::uuid, false) $$, + 'created sheet: creator alice, active, private, no current version' +); +insert into pg_temp.ids select 'v1', id from public.anatomical_sheet_versions + where sheet_id = pg_temp.id('sheet') and version_number = 1; +select is( + (select status::text from public.anatomical_sheet_versions where id = pg_temp.id('v1')), + 'draft', 'version 1 is a draft' +); +select throws_ok( + $$ select public.create_anatomical_sheet('unicorn', 'x', 'x-x', pg_temp.sheet_doc(null)) $$, + 'P0002', null, 'unknown species is refused' +); +select throws_ok( + $$ select public.create_anatomical_sheet('equine', 'Dup', 'mon-cheval', pg_temp.sheet_doc(null)) $$, + '23505', null, 'slug is unique per owner' +); + +-- Publishing a draft whose main view has no asset is refused with the rule code +select throws_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + '23514', 'document not publishable: view.asset.missing', 'publish refuses a main view without asset' +); + +insert into pg_temp.ids select 'asset', public.register_sheet_asset( + pg_temp.id('sheet'), repeat('a', 64), 142400, 'Horse.svg' +); +select is( + public.register_sheet_asset(pg_temp.id('sheet'), repeat('a', 64), 142400, 'Horse.svg'), + pg_temp.id('asset'), 'registering the same sha256 again returns the same asset' +); + +-- Draft autosave: direct UPDATE of content through the policy +update public.anatomical_sheet_versions + set content = pg_temp.sheet_doc(pg_temp.id('asset')), change_note = 'asset wired' + where id = pg_temp.id('v1'); +select is( + (select content -> 'views' -> 0 ->> 'svg_asset_id' from public.anatomical_sheet_versions where id = pg_temp.id('v1')), + pg_temp.id('asset')::text, 'editor updated the draft content in place' +); + +-- Unknown asset uuid is refused at publish +update public.anatomical_sheet_versions + set content = pg_temp.sheet_doc('ffffffff-ffff-ffff-ffff-ffffffffffff') + where id = pg_temp.id('v1'); +select throws_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + '23514', null, 'publish refuses a view pointing at an asset not registered for the sheet' +); +update public.anatomical_sheet_versions + set content = pg_temp.sheet_doc(pg_temp.id('asset')) where id = pg_temp.id('v1'); + +-- Document species must match the sheet species (trigger) +select throws_ok( + $$ update public.anatomical_sheet_versions + set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{species_id}', '"canine"') + where id = pg_temp.id('v1') $$, + '23514', null, 'a document for another species is refused' +); +-- Dangling references are refused at publish +update public.anatomical_sheet_versions + set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,0,finding_zone_id}', '"nowhere"') + where id = pg_temp.id('v1'); +select throws_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + '23514', 'document not publishable: annotation.finding_zone.missing', + 'publish refuses an annotation pointing at a missing finding zone' +); +update public.anatomical_sheet_versions + set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,1,id}', '"hip"') + where id = pg_temp.id('v1'); +select throws_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + '23514', 'document not publishable: annotation.id.duplicate', + 'publish refuses duplicate annotation ids' +); +update public.anatomical_sheet_versions + set content = pg_temp.sheet_doc(pg_temp.id('asset')) where id = pg_temp.id('v1'); + +select lives_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + 'alice publishes version 1' +); +select results_eq( + $$ select status::text, published_by, published_at is not null + from public.anatomical_sheet_versions where id = pg_temp.id('v1') $$, + $$ values ('published', '20000000-0000-0000-0000-00000000000a'::uuid, true) $$, + 'version 1 is published by alice' +); +select is( + (select current_version_id from public.anatomical_sheets where id = pg_temp.id('sheet')), + pg_temp.id('v1'), 'sheet current version is v1' +); +select throws_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + '55000', null, 'publishing twice is refused' +); + +-- --------------------------------------------------------------------------- +-- 3. Published rows are immutable (editor, then table owner) +-- --------------------------------------------------------------------------- +-- Through the API role the policies hide published rows from UPDATE/DELETE: +-- the statement touches zero rows instead of raising. +update public.anatomical_sheet_versions set content = '{}'::jsonb where id = pg_temp.id('v1'); +select is( + (select content from public.anatomical_sheet_versions where id = pg_temp.id('v1')), + pg_temp.sheet_doc(pg_temp.id('asset')), 'editor UPDATE of published content touches no row' +); +update public.anatomical_sheet_versions set change_note = 'x' where id = pg_temp.id('v1'); +select is( + (select change_note from public.anatomical_sheet_versions where id = pg_temp.id('v1')), + 'asset wired', 'editor UPDATE of a published change note touches no row' +); +delete from public.anatomical_sheet_versions where id = pg_temp.id('v1'); +select is( + (select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v1')), + 1::bigint, 'editor DELETE of a published version touches no row' +); +reset role; +select throws_ok( + $$ update public.anatomical_sheet_versions + set content = pg_temp.sheet_doc(pg_temp.id('asset')) || '{"name":{"fr":"X","en":"X"}}' + where id = pg_temp.id('v1') $$, + '42501', null, 'even the table owner cannot change published content' +); +select throws_ok( + $$ update public.anatomical_sheet_versions set status = 'draft' where id = pg_temp.id('v1') $$, + '42501', null, 'a published version cannot go back to draft' +); +select throws_ok( + $$ update public.anatomical_sheet_versions set version_number = 9 where id = pg_temp.id('v1') $$, + '42501', null, 'version_number is immutable' +); +select throws_ok( + $$ delete from public.anatomical_sheet_versions where id = pg_temp.id('v1') $$, + '55000', null, 'owner role cannot delete a published version either' +); + +-- --------------------------------------------------------------------------- +-- 4. New version leaves the old one intact +-- --------------------------------------------------------------------------- +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +create table pg_temp.v1_snapshot as + select * from public.anatomical_sheet_versions where id = pg_temp.id('v1'); + +insert into pg_temp.ids select 'v2', public.create_sheet_draft(pg_temp.id('sheet'), null, 'second edition'); +select results_eq( + $$ select version_number, status::text, change_note, content = (select content from pg_temp.v1_snapshot) + from public.anatomical_sheet_versions where id = pg_temp.id('v2') $$, + $$ values (2, 'draft', 'second edition', true) $$, + 'draft v2 starts from the current version content' +); +select throws_ok( + $$ select public.create_sheet_draft(pg_temp.id('sheet')) $$, + '23505', null, 'one draft per sheet' +); +update public.anatomical_sheet_versions + set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{name,fr}', '"Cheval v2"') + where id = pg_temp.id('v2'); +select lives_ok($$ select public.publish_sheet_version(pg_temp.id('v2')) $$, 'alice publishes v2'); +select is( + (select current_version_id from public.anatomical_sheets where id = pg_temp.id('sheet')), + pg_temp.id('v2'), 'current version moved to v2' +); +select is( + (select count(*) from public.anatomical_sheet_versions v, pg_temp.v1_snapshot s + where v.id = s.id and v.content = s.content and v.status = s.status + and v.published_at = s.published_at and v.version_number = s.version_number + and v.change_note = s.change_note), + 1::bigint, 'v1 row is byte-identical after v2 was published' +); +select throws_ok( + $$ select public.delete_sheet_version(pg_temp.id('v2')) $$, + '55000', null, 'the current version cannot be deleted' +); +select throws_ok( + $$ select public.delete_sheet_version(pg_temp.id('v1')) $$, + '55000', null, 'a published version cannot be deleted before deprecation' +); + +-- --------------------------------------------------------------------------- +-- 5. Bob: private sheet invisible; public sheet usable; copy keeps provenance +-- --------------------------------------------------------------------------- +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 0::bigint, 'bob does not see the private sheet'); +select is((select count(*) from public.anatomical_sheet_versions where sheet_id = pg_temp.id('sheet')), 0::bigint, 'bob does not see its versions'); +select is((select count(*) from public.anatomical_sheet_assets where sheet_id = pg_temp.id('sheet')), 0::bigint, 'bob does not see its assets'); +select throws_ok( + $$ select public.fork_anatomical_sheet(pg_temp.id('v2'), 'Copie', 'copie-bob') $$, + '42501', null, 'bob cannot copy a private sheet' +); +select throws_ok( + $$ select public.create_sheet_draft(pg_temp.id('sheet')) $$, + '42501', null, 'bob cannot open a draft on alice sheet' +); +update public.anatomical_sheets set name = 'hijack' where id = pg_temp.id('sheet'); +select throws_ok( + $$ insert into public.anatomical_sheets (species_id, name, slug, creator_user_id) + values ('equine', 'direct', 'direct', '20000000-0000-0000-0000-00000000000b') $$, + '42501', null, 'bob cannot insert a sheet row directly' +); +select throws_ok( + $$ insert into public.anatomical_sheet_versions (sheet_id, version_number, document_schema_version, content) + values (pg_temp.id('sheet'), 9, 1, pg_temp.sheet_doc(null)) $$, + '42501', null, 'bob cannot insert a version row directly' +); + +-- alice makes the sheet public through the identity-column policy +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select is((select name from public.anatomical_sheets where id = pg_temp.id('sheet')), 'Mon cheval', 'bob update on alice sheet changed nothing'); +update public.anatomical_sheets set visibility = 'public' where id = pg_temp.id('sheet'); +insert into pg_temp.ids select 'v3', public.create_sheet_draft(pg_temp.id('sheet'), null, 'work in progress'); + +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 1::bigint, 'bob sees the public sheet'); +select results_eq( + $$ select version_number from public.anatomical_sheet_versions where sheet_id = pg_temp.id('sheet') order by 1 $$, + $$ values (1), (2) $$, + 'bob sees the published versions, not the draft' +); +select is( + (select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v3') and content = '{}'::jsonb), + 0::bigint, 'bob cannot read the draft' +); +update public.anatomical_sheet_versions set content = '{"schema_version":1}'::jsonb where id = pg_temp.id('v3'); +select throws_ok( + $$ select public.fork_anatomical_sheet(pg_temp.id('v3'), 'Copie', 'copie-bob') $$, + '55000', null, 'only a published version can be copied' +); + +create table pg_temp.source_snapshot as + select s.updated_at as sheet_updated_at, s.current_version_id, v.content, v.updated_at as version_updated_at, + (select count(*) from public.anatomical_sheet_assets where sheet_id = s.id) as asset_count + from public.anatomical_sheets s join public.anatomical_sheet_versions v on v.id = s.current_version_id + where s.id = pg_temp.id('sheet'); + +insert into pg_temp.ids select 'fork', public.fork_anatomical_sheet(pg_temp.id('v2'), 'Copie de Bob', 'copie-bob'); +select results_eq( + $$ select creator_user_id, based_on_sheet_id, based_on_version_id, species_id, visibility::text, is_official + from public.anatomical_sheets where id = pg_temp.id('fork') $$, + $$ values ('20000000-0000-0000-0000-00000000000b'::uuid, pg_temp.id('sheet'), pg_temp.id('v2'), 'equine', 'private', false) $$, + 'copy records provenance (source sheet + version) and belongs to bob' +); +insert into pg_temp.ids select 'fork-v1', id from public.anatomical_sheet_versions where sheet_id = pg_temp.id('fork'); +insert into pg_temp.ids select 'fork-asset', id from public.anatomical_sheet_assets where sheet_id = pg_temp.id('fork'); +select results_eq( + $$ select version_number, status::text, created_by from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1') $$, + $$ values (1, 'draft', '20000000-0000-0000-0000-00000000000b'::uuid) $$, + 'copy starts as draft v1 owned by bob' +); +select results_eq( + $$ select sha256, byte_size, id <> pg_temp.id('asset') from public.anatomical_sheet_assets where sheet_id = pg_temp.id('fork') $$, + $$ values (repeat('a', 64), 142400, true) $$, + 'asset rows are copied (same content, new id)' +); +select is( + (select content -> 'views' -> 0 ->> 'svg_asset_id' from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1')), + pg_temp.id('fork-asset')::text, 'copied document points at the copied asset' +); +select is( + (select content #- '{views,0,svg_asset_id}' from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1')), + (select content #- '{views,0,svg_asset_id}' from pg_temp.source_snapshot), + 'copied document is otherwise identical to the source' +); + +-- bob edits his copy; the source stays untouched +update public.anatomical_sheet_versions + set content = jsonb_set(content, '{name,fr}', '"Ma copie"') where id = pg_temp.id('fork-v1'); +select lives_ok($$ select public.publish_sheet_version(pg_temp.id('fork-v1')) $$, 'bob publishes his copy'); +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select is( + (select count(*) from public.anatomical_sheets s join public.anatomical_sheet_versions v on v.id = s.current_version_id, + pg_temp.source_snapshot snap + where s.id = pg_temp.id('sheet') and s.updated_at = snap.sheet_updated_at and s.current_version_id = snap.current_version_id + and v.content = snap.content and v.updated_at = snap.version_updated_at + and (select count(*) from public.anatomical_sheet_assets where sheet_id = s.id) = snap.asset_count), + 1::bigint, 'source sheet, version and assets are unchanged by the copy and its edits' +); + +-- --------------------------------------------------------------------------- +-- 6. Deprecation, deletion preconditions, archive, soft delete +-- --------------------------------------------------------------------------- +select lives_ok($$ select public.deprecate_sheet_version(pg_temp.id('v2'), 'superseded') $$, 'alice deprecates v2'); +select results_eq( + $$ select status::text, deprecated_by from public.anatomical_sheet_versions where id = pg_temp.id('v2') $$, + $$ values ('deprecated', '20000000-0000-0000-0000-00000000000a'::uuid) $$, + 'v2 is deprecated' +); +select is( + (select current_version_id from public.anatomical_sheets where id = pg_temp.id('sheet')), + pg_temp.id('v1'), 'current version falls back to the latest published one (v1)' +); +update public.anatomical_sheet_versions set content = '{}'::jsonb where id = pg_temp.id('v2'); +select is( + (select content ->> 'schema_version' from public.anatomical_sheet_versions where id = pg_temp.id('v2')), + '1', 'a deprecated version is hidden from editor UPDATE' +); +reset role; +select throws_ok( + $$ update public.anatomical_sheet_versions set change_note = 'late edit' where id = pg_temp.id('v2') $$, + '42501', null, 'a deprecated version is frozen for the table owner too' +); +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select throws_ok( + $$ select public.delete_sheet_version(pg_temp.id('v2')) $$, + '55000', null, 'v2 cannot be deleted while bob copy derives from it' +); +select throws_ok( + $$ select public.delete_anatomical_sheet(pg_temp.id('sheet')) $$, + '55000', null, 'the sheet cannot be deleted while a copy is active' +); +select lives_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice archives the sheet'); +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 0::bigint, 'an archived sheet is no longer usable by others'); +select throws_ok( + $$ select public.delete_sheet_version(pg_temp.id('fork-v1')) $$, + '55000', null, 'bob cannot delete the published version of his copy' +); +select lives_ok($$ select public.delete_anatomical_sheet(pg_temp.id('fork')) $$, 'bob soft-deletes his copy'); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('fork')), 0::bigint, 'a deleted sheet is invisible to its creator'); + +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select lives_ok($$ select public.restore_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice restores the sheet'); +select lives_ok($$ select public.delete_sheet_version(pg_temp.id('v2')) $$, 'deprecated v2 is deleted once no active copy depends on it'); +select is((select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v2')), 0::bigint, 'v2 row is gone'); +select lives_ok($$ delete from public.anatomical_sheet_versions where id = pg_temp.id('v3') $$, 'editor drops her own draft directly'); +select throws_ok( + $$ select public.delete_sheet_asset(pg_temp.id('asset')) $$, + '55000', null, 'an asset referenced by a version cannot be deleted' +); + +-- --------------------------------------------------------------------------- +-- 7. Official sheets: platform admins only +-- --------------------------------------------------------------------------- +select throws_ok( + $$ select public.create_anatomical_sheet('equine', 'Officielle', 'officielle', pg_temp.sheet_doc(null), '', 'public', true) $$, + '42501', null, 'a plain user cannot create an official sheet' +); +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-000000000001","role":"authenticated"}', true); +insert into pg_temp.ids select 'official', public.create_anatomical_sheet( + 'equine', 'Faunosteo / Cheval', 'faunosteo-cheval', pg_temp.sheet_doc(null), 'Fiche officielle', 'public', true +); +select results_eq( + $$ select creator_user_id, is_official, visibility::text from public.anatomical_sheets where id = pg_temp.id('official') $$, + $$ values (null::uuid, true, 'public') $$, + 'official sheet is platform-owned' +); +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('official')), 1::bigint, 'alice sees the public official sheet'); +select is( + (select count(*) from public.anatomical_sheet_versions where sheet_id = pg_temp.id('official')), + 0::bigint, 'alice does not see the official draft' +); +select throws_ok( + $$ select public.create_sheet_draft(pg_temp.id('official')) $$, + '42501', null, 'alice cannot edit the official sheet' +); + +-- --------------------------------------------------------------------------- +-- 8. Anonymous +-- --------------------------------------------------------------------------- +set local role anon; +select set_config('request.jwt.claims', '', true); +select throws_ok($$ select * from public.species $$, '42501', null, 'anon cannot read species'); +select throws_ok($$ select * from public.anatomical_sheets $$, '42501', null, 'anon cannot read sheets'); +select throws_ok( + $$ select public.create_anatomical_sheet('equine', 'x', 'x-x', '{}'::jsonb) $$, + '42501', null, 'anon cannot call create_anatomical_sheet' +); + +-- --------------------------------------------------------------------------- +-- 9. Audit trail +-- --------------------------------------------------------------------------- +reset role; +select results_eq( + $$ select action from audit.audit_logs + where resource_id in (pg_temp.id('sheet'), pg_temp.id('v1'), pg_temp.id('v2'), pg_temp.id('fork'), pg_temp.id('asset')) + group by action order by action collate "C" $$, + $$ values ('anatomical_sheet.archived'), ('anatomical_sheet.created'), ('anatomical_sheet.deleted'), + ('anatomical_sheet.forked'), ('anatomical_sheet.restored'), ('anatomical_sheet_asset.registered'), + ('anatomical_sheet_version.created'), ('anatomical_sheet_version.deleted'), + ('anatomical_sheet_version.deprecated'), ('anatomical_sheet_version.published') $$, + 'every lifecycle step left an audit event' +); + +select * from finish(); +rollback;