-- 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, -- Monotonic counter: a deleted version's number is never reused. last_version_number integer not null default 0 constraint anatomical_sheets_last_version_nonneg check (last_version_number >= 0), 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') -- Hostile or runaway documents stop here (2 MiB; the horse catalog is ~170 KiB). constraint anatomical_sheet_versions_content_size check (pg_column_size(content) <= 2097152), 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_range check (byte_size between 1 and 20971520), 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 security definer 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.id <> old.id or new.sheet_id <> old.sheet_id or new.version_number <> old.version_number then raise exception 'id, 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 security definer 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; $$; -- Uniqueness of the id-bearing collections. create or replace function private.sheet_document_duplicate_issues(p_doc jsonb) returns text[] language plpgsql immutable set search_path = '' as $$ declare v_issues text[] := '{}'; r record; begin for r in select * from (values ('views', 'id', 'view.id.duplicate'), ('annotations', 'id', 'annotation.id.duplicate'), ('categories', 'id', 'category.id.duplicate'), ('finding_zones', 'id', 'finding_zone.id.duplicate') ) as t(collection, key, code) loop if exists ( select 1 from jsonb_array_elements(coalesce(p_doc -> r.collection, '[]'::jsonb)) e group by e ->> r.key having count(*) > 1 ) then v_issues := private.append_issue(v_issues, r.code); end if; end loop; if exists ( select 1 from jsonb_array_elements(coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb)) g group by g ->> 'code' having count(*) > 1 ) then v_issues := private.append_issue(v_issues, 'region.code.duplicate'); end if; return v_issues; end; $$; -- View tree: one main view, parents exist, details reachable, something to draw. create or replace function private.sheet_document_view_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); r record; begin 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; for r in select v ->> 'id' as id, v ->> 'kind' as kind, v ->> 'parent_view_id' as parent, v ->> 'svg_asset_id' as asset, jsonb_typeof(v -> 'view_box') as view_box_type 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 coalesce(r.view_box_type, 'null') = '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; return v_issues; end; $$; -- Annotation references: view, category, trigger target, finding zone, region. create or replace function private.sheet_document_annotation_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_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 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(coalesce(p_doc -> 'annotations', '[]'::jsonb)) 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; $$; -- True when every id-bearing collection of the document is a JSON array. create or replace function private.sheet_document_has_shape(p_doc jsonb) returns boolean language sql immutable set search_path = '' as $$ select jsonb_typeof(p_doc) = 'object' and jsonb_typeof(coalesce(p_doc -> 'views', '[]'::jsonb)) = 'array' and jsonb_typeof(coalesce(p_doc -> 'annotations', '[]'::jsonb)) = 'array' and jsonb_typeof(coalesce(p_doc -> 'categories', '[]'::jsonb)) = 'array' and jsonb_typeof(coalesce(p_doc -> 'finding_zones', '[]'::jsonb)) = 'array' and jsonb_typeof(coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb)) = 'array'; $$; create or replace function private.sheet_document_issues(p_doc jsonb) returns text[] language sql immutable set search_path = '' as $$ select case when not private.sheet_document_has_shape(p_doc) then array['document.shape'] else private.sheet_document_view_issues(p_doc) || private.sheet_document_duplicate_issues(p_doc) || private.sheet_document_annotation_issues(p_doc) 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.'; -- Asset ids referenced by the views of a document (lower-cased uuid text). create or replace function private.sheet_document_asset_ids(p_doc jsonb) returns text[] language sql immutable set search_path = '' as $$ select coalesce(array_agg(distinct lower(v ->> 'svg_asset_id')), '{}') from jsonb_array_elements(coalesce(p_doc -> 'views', '[]'::jsonb)) v where v ->> 'svg_asset_id' is not null; $$; -- 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(ref), '{}') from unnest(private.sheet_document_asset_ids(p_doc)) as ref where not exists ( select 1 from public.anatomical_sheet_assets a where a.sheet_id = p_sheet_id and a.id::text = ref ); $$; -- --------------------------------------------------------------------------- -- 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; -- A staff-deactivated account keeps no write access (profiles.active). if not exists (select 1 from public.profiles p where p.id = v_actor and p.active) then raise exception 'account is not active' 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; $$; -- Same check through a version id; unknown and foreign versions get one answer. create or replace function private.require_version_editor(p_actor uuid, p_version_id uuid) returns void language plpgsql stable security definer set search_path = '' as $$ declare v_sheet uuid; begin select sheet_id into v_sheet from public.anatomical_sheet_versions where id = p_version_id; if v_sheet is null or not private.can_edit_sheet(p_actor, v_sheet) then raise exception 'version % is not editable by the caller', p_version_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 if jsonb_typeof(p_content -> 'schema_version') is distinct from 'number' then raise exception 'document.schema_version must be a number' using errcode = '23514'; end if; 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; update public.anatomical_sheets set last_version_number = last_version_number + 1 where id = p_sheet_id returning last_version_number into v_number; 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 a document references to another sheet; returns old id → new id. create or replace function private.copy_sheet_assets(p_actor uuid, p_from uuid, p_to uuid, p_doc jsonb) 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 and id::text = any (private.sheet_document_asset_ids(p_doc)) 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 ? lower(v ->> 'svg_asset_id') then jsonb_set(v, '{svg_asset_id}', to_jsonb(p_map ->> lower(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 perform private.require_version_editor(v_actor, version_id); select * into v_version from public.anatomical_sheet_versions where id = version_id for update; 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 if char_length(reason) > 500 then raise exception 'reason exceeds 500 characters' using errcode = '22023'; end if; perform private.require_version_editor(v_actor, version_id); select * into v_version from public.anatomical_sheet_versions where id = version_id for update; 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 perform private.require_version_editor(v_actor, version_id); select sheet_id, version_number into v_sheet, v_number from public.anatomical_sheet_versions where id = version_id; -- 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; -- One answer for "unknown", "not published" and "not usable": no existence oracle. if v_source.id is null or v_source.status <> 'published' or not private.can_use_sheet(v_actor, v_source.sheet_id) then raise exception 'version % is not available for copy', source_version_id using errcode = '42501'; 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, v_source.content); 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); -- Lock before the copies check so a concurrent fork cannot slip in. perform 1 from public.anatomical_sheets s where s.id = sheet_id for update; 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; $$; -- Sharing is sensitive state: audited, never a direct column write. create or replace function public.set_sheet_visibility(sheet_id uuid, visibility public.sheet_visibility) returns uuid language plpgsql security definer set search_path = '' as $$ declare v_actor uuid := private.require_actor(); begin perform private.require_sheet_editor(v_actor, sheet_id); update public.anatomical_sheets s set visibility = set_sheet_visibility.visibility where s.id = sheet_id and s.visibility <> set_sheet_visibility.visibility; if found then perform private.log_event( v_actor, 'anatomical_sheet.visibility_changed', 'anatomical_sheet', sheet_id, null, null, jsonb_build_object('visibility', visibility) ); end if; return sheet_id; 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 or not private.can_edit_sheet(v_actor, v_sheet) then raise exception 'asset % is not editable by the caller', asset_id using errcode = '42501'; end if; if exists ( select 1 from public.anatomical_sheet_versions v where v.sheet_id = v_sheet and asset_id::text = any (private.sheet_document_asset_ids(v.content)) ) 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.'; comment on function public.set_sheet_visibility(uuid, public.sheet_visibility) is 'private ↔ public. Audited; the only way to change sharing.'; -- --------------------------------------------------------------------------- -- Privileges + RLS -- --------------------------------------------------------------------------- -- PostgreSQL grants EXECUTE to PUBLIC on every new function and a per-schema -- ALTER DEFAULT PRIVILEGES cannot take that built-in default away: revoke it -- explicitly on every private function (the policies need only the two -- predicates granted above). revoke all on function private.check_sheet_version_document() from public; revoke all on function private.guard_sheet_version_update() from public; revoke all on function private.guard_sheet_version_delete() from public; revoke all on function private.sheet_version_dependents(uuid) from public; revoke all on function private.append_issue(text[], text) from public; revoke all on function private.sheet_document_duplicate_issues(jsonb) from public; revoke all on function private.sheet_document_view_issues(jsonb) from public; revoke all on function private.sheet_document_annotation_issues(jsonb) from public; revoke all on function private.sheet_document_has_shape(jsonb) from public; revoke all on function private.sheet_document_issues(jsonb) from public; revoke all on function private.sheet_document_asset_ids(jsonb) from public; revoke all on function private.sheet_document_unknown_assets(uuid, jsonb) from public; revoke all on function private.can_edit_sheet(uuid, uuid) from public; revoke all on function private.can_use_sheet(uuid, uuid) from public; revoke all on function private.require_actor() from public; revoke all on function private.require_sheet_editor(uuid, uuid) from public; revoke all on function private.require_version_editor(uuid, uuid) from public; revoke all on function private.insert_sheet_draft(uuid, uuid, jsonb, text) from public; revoke all on function private.copy_sheet_assets(uuid, uuid, uuid, jsonb) from public; revoke all on function private.remap_document_assets(jsonb, jsonb) from public; revoke all on function private.set_sheet_status(uuid, uuid, public.sheet_status, public.sheet_status, text) from public; 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.set_sheet_visibility(uuid, public.sheet_visibility) 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.set_sheet_visibility(uuid, public.sheet_visibility) 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; visibility, status, provenance, ownership go through RPCs. grant update (name, slug, description) 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 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_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) );