Forms
formsForms with numbered versions (steps and show or skip logic), a JSON Schema 2020-12 per version that validates every submission, drafts, public links through share-links with a rate limit and a bot-check hook, handlers that turn a submission into a record, scoring against an answer key respondents can't read, and NPS rollups.
Content & filesReact hooksmanagedcustom
BIH1v12
Q4 launch planInstall
The command also installs updated-at, memberships, jsonb-schemas, permissions, the modules it needs.
npx better-supabase add formsConfigure
The blocks entries in your config, with the default mode.
import { defineConfig } from "better-supabase/config";
export default defineConfig({
blocks: {
// Required by forms; add installs them too.
"updated-at": {},
memberships: {},
"jsonb-schemas": {},
permissions: {},
// Modes: "managed", "custom". The default is "managed".
forms: { mode: "managed" },
},
});Migrations
The files
npx better-supabase add forms writes into your declarative schema with the default layout.11 files
supabase/schemas/900_better_supabase_086_forms.sqlschema1585 lines-- better-supabase module: forms
-- @bsb-block forms@2 managed
-- @bsb-hash sha256:4f7a2aed003de83d826271895510ce61ea1e17fecc674fb3b32624709785e459
-- Forms with numbered versions (steps and show or skip logic), a JSON Schema 2020-12 per version that validates every submission, drafts, public links through share-links with a rate limit and a bot-check hook, handlers that turn a submission into a record, scoring against an answer key respondents can't read, and NPS rollups.
-- Managed by `better-supabase add`; re-running it rewrites this file unless it was edited by hand.
-- Change it through `blocks` in better-supabase.config.ts and the module's SQL hooks.
create table "better_supabase"."forms" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"key" text not null constraint bsb_forms_key_check check ("key" ~ '^[a-z][a-z0-9_-]{0,62}$'),
"title" text not null constraint bsb_forms_title_check check (length("title") >= 1 and length("title") <= 200),
"description" text constraint bsb_forms_description_check check ("description" is null or length("description") <= 2000),
"status" text not null default 'draft' constraint bsb_forms_status_check check ("status" in ('draft', 'open', 'closed', 'archived')),
"current_version_id" uuid,
"created_by" uuid,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "key")
);
alter table "better_supabase"."forms" enable row level security;
revoke all on "better_supabase"."forms" from public, anon, authenticated;
grant select on "better_supabase"."forms" to authenticated;
grant all on "better_supabase"."forms" to service_role;
create policy bsb_forms_read on "better_supabase"."forms"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('forms.read')));
create table "better_supabase"."form_versions" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"form_id" uuid not null references "better_supabase"."forms" ("id") on delete cascade,
"number" integer not null constraint bsb_form_versions_number_check check ("number" > 0),
"definition" jsonb not null,
"schema" jsonb not null,
"created_by" uuid,
"created_at" timestamptz not null default now(),
unique ("form_id", "number")
);
alter table "better_supabase"."form_versions" enable row level security;
revoke all on "better_supabase"."form_versions" from public, anon, authenticated;
grant select on "better_supabase"."form_versions" to authenticated;
grant all on "better_supabase"."form_versions" to service_role;
create policy bsb_form_versions_read on "better_supabase"."form_versions"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('forms.read')));
create table "better_supabase"."form_submissions" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"form_id" uuid not null references "better_supabase"."forms" ("id") on delete cascade,
"version_id" uuid not null references "better_supabase"."form_versions" ("id") on delete cascade,
"subject_type" text,
"subject_id" text,
"respondent_id" uuid,
"answers" jsonb not null default '{}'::jsonb constraint bsb_form_submissions_answers_check check (jsonb_typeof("answers") = 'object' and octet_length("answers"::text) <= 1048576),
"status" text not null default 'submitted' constraint bsb_form_submissions_status_check check ("status" in ('draft', 'submitted', 'accepted', 'rejected')),
"source" text not null default 'member' constraint bsb_form_submissions_source_check check ("source" in ('member', 'public', 'service')),
"reviewed_by" uuid,
"reviewed_at" timestamptz,
"archived_at" timestamptz,
"created_at" timestamptz not null default now(),
"submitted_at" timestamptz,
"updated_at" timestamptz not null default now(),
constraint bsb_form_submissions_check check (("subject_type" is null) = ("subject_id" is null))
);
create index "form_submissions_form_idx" on "better_supabase"."form_submissions" ("form_id", "created_at" desc);
create index "form_submissions_tenant_idx" on "better_supabase"."form_submissions" ("tenant_id", "created_at" desc);
create index "form_submissions_version_idx" on "better_supabase"."form_submissions" ("version_id");
create index "form_submissions_respondent_idx" on "better_supabase"."form_submissions" ("respondent_id") where "respondent_id" is not null;
create index "form_submissions_subject_idx" on "better_supabase"."form_submissions" ("subject_type", "subject_id") where "subject_type" is not null;
alter table "better_supabase"."form_submissions" enable row level security;
revoke all on "better_supabase"."form_submissions" from public, anon, authenticated;
grant select on "better_supabase"."form_submissions" to authenticated;
grant all on "better_supabase"."form_submissions" to service_role;
create policy bsb_form_submissions_read on "better_supabase"."form_submissions"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('forms.review')) or "respondent_id" = (select auth.uid()));
alter table "better_supabase"."form_submissions" add column "score" numeric;
alter table "better_supabase"."form_submissions" add column "max_score" numeric;
alter table "better_supabase"."form_submissions" add column "passed" boolean;
-- The correct answers of a scored version, which only definer functions read.
create table "better_supabase"."form_answer_keys" (
"version_id" uuid primary key references "better_supabase"."form_versions" ("id") on delete cascade,
"tenant_id" uuid not null,
"answers" jsonb not null constraint bsb_form_answer_keys_answers_check check (jsonb_typeof("answers") = 'object'),
"created_at" timestamptz not null default now()
);
alter table "better_supabase"."form_answer_keys" enable row level security;
revoke all on "better_supabase"."form_answer_keys" from public, anon, authenticated;
grant all on "better_supabase"."form_answer_keys" to service_role;
-- The schema of one field's answer. Mirrors fieldSchema in
-- core/contracts/form-definition.ts.
create or replace function "better_supabase"."form_field_schema"(field jsonb)
returns jsonb
language plpgsql
immutable
set search_path = ''
as $$
declare
v_type text := field ->> 'type';
-- required only asks for the key, so an empty answer needs its own floor.
v_floor jsonb := case when field -> 'required' = 'true'::jsonb then '1'::jsonb end;
v_values jsonb;
v_out jsonb;
begin
select coalesce(jsonb_agg(o.value -> 'value' order by o.ord), '[]'::jsonb) into v_values
from jsonb_array_elements(coalesce(field -> 'options', '[]'::jsonb)) with ordinality as o(value, ord);
v_out := case v_type
when 'text' then jsonb_build_object('type', 'string', 'maxLength', coalesce(field -> 'maxLength', '500'::jsonb))
|| jsonb_strip_nulls(jsonb_build_object('minLength', coalesce(field -> 'minLength', v_floor), 'pattern', field -> 'pattern'))
when 'textarea' then jsonb_build_object('type', 'string', 'maxLength', coalesce(field -> 'maxLength', '10000'::jsonb))
|| jsonb_strip_nulls(jsonb_build_object('minLength', coalesce(field -> 'minLength', v_floor), 'pattern', field -> 'pattern'))
when 'email' then jsonb_build_object('type', 'string', 'format', 'email', 'maxLength', 320)
when 'url' then jsonb_build_object('type', 'string', 'format', 'uri', 'maxLength', 2000)
when 'number' then jsonb_build_object('type', 'number') || jsonb_strip_nulls(jsonb_build_object('minimum', field -> 'min', 'maximum', field -> 'max'))
when 'integer' then jsonb_build_object('type', 'integer') || jsonb_strip_nulls(jsonb_build_object('minimum', field -> 'min', 'maximum', field -> 'max'))
when 'date' then '{"type": "string", "format": "date"}'::jsonb
when 'bool' then '{"type": "boolean"}'::jsonb
when 'consent' then '{"type": "boolean", "const": true}'::jsonb
when 'option' then jsonb_build_object('type', 'string', 'enum', v_values)
when 'multi' then jsonb_build_object('type', 'array', 'items', jsonb_build_object('type', 'string', 'enum', v_values), 'uniqueItems', true)
|| jsonb_strip_nulls(jsonb_build_object('minItems', coalesce(field -> 'min', v_floor), 'maxItems', field -> 'max'))
when 'nps' then '{"type": "integer", "minimum": 0, "maximum": 10}'::jsonb
else '{}'::jsonb
end;
return v_out || jsonb_strip_nulls(jsonb_build_object('title', field -> 'label', 'description', field -> 'help'));
end;
$$;
revoke execute on function "better_supabase"."form_field_schema"(jsonb) from public, anon, authenticated;
-- The schema a showIf condition holds under, as an if.
create or replace function "better_supabase"."form_condition_schema"(condition jsonb)
returns jsonb
language sql
immutable
set search_path = ''
as $$
select jsonb_build_object(
'properties', jsonb_build_object(condition ->> 'field',
case
when condition ? 'equals' then jsonb_build_object('const', condition -> 'equals')
when condition ? 'in' then jsonb_build_object('enum', condition -> 'in')
else '{"not": {"enum": [null, "", []]}}'::jsonb
end),
'required', jsonb_build_array(condition ->> 'field'))
$$;
revoke execute on function "better_supabase"."form_condition_schema"(jsonb) from public, anon, authenticated;
-- The JSON Schema 2020-12 a version's answers validate against. Mirrors
-- formSchema in core/contracts/form-definition.ts: a required field with a
-- showIf (its own or its step's) is required only while the condition holds.
create or replace function "better_supabase"."form_schema"(definition jsonb)
returns jsonb
language plpgsql
immutable
set search_path = ''
as $$
declare
v_properties jsonb := '{}'::jsonb;
v_required jsonb := '[]'::jsonb;
v_conditional jsonb := '[]'::jsonb;
v_conditions jsonb;
v_step jsonb;
v_field jsonb;
begin
for v_step in select x from jsonb_array_elements(definition -> 'steps') x loop
for v_field in select x from jsonb_array_elements(v_step -> 'fields') x loop
v_properties := v_properties || jsonb_build_object(v_field ->> 'key', "better_supabase"."form_field_schema"(v_field));
continue when coalesce((v_field ->> 'required')::boolean, false) is false;
v_conditions := '[]'::jsonb;
if v_step ? 'showIf' then
v_conditions := v_conditions || jsonb_build_array("better_supabase"."form_condition_schema"(v_step -> 'showIf'));
end if;
if v_field ? 'showIf' then
v_conditions := v_conditions || jsonb_build_array("better_supabase"."form_condition_schema"(v_field -> 'showIf'));
end if;
if jsonb_array_length(v_conditions) = 0 then
v_required := v_required || jsonb_build_array(v_field ->> 'key');
else
v_conditional := v_conditional || jsonb_build_array(jsonb_build_object(
'if', case when jsonb_array_length(v_conditions) = 1 then v_conditions -> 0 else jsonb_build_object('allOf', v_conditions) end,
'then', jsonb_build_object('required', jsonb_build_array(v_field ->> 'key'))));
end if;
end loop;
end loop;
return jsonb_build_object('$schema', 'https://json-schema.org/draft/2020-12/schema', 'type', 'object', 'properties', v_properties, 'additionalProperties', false)
|| case when jsonb_array_length(v_required) > 0 then jsonb_build_object('required', v_required) else '{}'::jsonb end
|| case when jsonb_array_length(v_conditional) > 0 then jsonb_build_object('allOf', v_conditional) else '{}'::jsonb end;
end;
$$;
revoke execute on function "better_supabase"."form_schema"(jsonb) from public, anon, authenticated;
-- Checks a definition (its shape, then what the shape can't say, as
-- formDefinitionProblems does) and copies each customField's definition in.
create or replace function "better_supabase"."form_resolve"(tenant uuid, definition jsonb)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_errors text[];
v_problem text;
v_steps jsonb := '[]'::jsonb;
v_fields jsonb;
v_step jsonb;
v_field jsonb;
v_custom jsonb;
v_options jsonb;
v_step_keys text[] := '{}';
v_keys text[] := '{}';
v_scored boolean := false;
begin
v_errors := extensions.jsonschema_validation_errors('{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","required":["steps"],"additionalProperties":false,"properties":{"steps":{"type":"array","minItems":1,"maxItems":50,"items":{"type":"object","required":["key","fields"],"additionalProperties":false,"properties":{"key":{"type":"string","pattern":"^[a-z][a-zA-Z0-9_]{0,62}$"},"title":{"type":"string","maxLength":200},"description":{"type":"string","maxLength":2000},"showIf":{"type":"object","required":["field"],"minProperties":2,"maxProperties":2,"additionalProperties":false,"properties":{"field":{"type":"string","pattern":"^[a-z][a-zA-Z0-9_]{0,62}$"},"equals":{},"in":{"type":"array","minItems":1,"maxItems":500},"filled":{"const":true}}},"fields":{"type":"array","minItems":1,"maxItems":200,"items":{"type":"object","required":["key"],"additionalProperties":false,"properties":{"key":{"type":"string","pattern":"^[a-z][a-zA-Z0-9_]{0,62}$"},"label":{"type":"string","minLength":1,"maxLength":200},"type":{"enum":["text","textarea","email","url","number","integer","date","bool","consent","option","multi","json","nps"]},"required":{"type":"boolean"},"help":{"type":"string","maxLength":1000},"placeholder":{"type":"string","maxLength":200},"options":{"type":"array","minItems":1,"maxItems":500,"items":{"type":"object","required":["value","label"],"additionalProperties":false,"properties":{"value":{"type":"string","minLength":1,"maxLength":200},"label":{"type":"string","minLength":1,"maxLength":200}}}},"min":{"type":"number"},"max":{"type":"number"},"minLength":{"type":"integer","minimum":0},"maxLength":{"type":"integer","minimum":1},"pattern":{"type":"string","maxLength":500},"showIf":{"type":"object","required":["field"],"minProperties":2,"maxProperties":2,"additionalProperties":false,"properties":{"field":{"type":"string","pattern":"^[a-z][a-zA-Z0-9_]{0,62}$"},"equals":{},"in":{"type":"array","minItems":1,"maxItems":500},"filled":{"const":true}}},"customField":{"type":"string","pattern":"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},"correct":{},"points":{"type":"number","minimum":0,"maximum":10000},"meta":{"type":"object","maxProperties":20}}}}}}},"scoring":{"type":"object","additionalProperties":false,"properties":{"passMark":{"type":"number","minimum":0,"maximum":100}}}}}'::json, definition::json);
if cardinality(v_errors) > 0 then
raise exception 'the form definition is invalid: %', array_to_string(v_errors, '; ')
using errcode = '22023', detail = to_jsonb(v_errors)::text, hint = 'FORM_DEFINITION_INVALID';
end if;
<<steps>>
for v_step in select x from jsonb_array_elements(definition -> 'steps') x loop
if (v_step ->> 'key') = any (v_step_keys) then
v_problem := format('step %s is listed twice', v_step ->> 'key');
exit;
end if;
v_step_keys := v_step_keys || (v_step ->> 'key');
if v_step ? 'showIf' and not ((v_step -> 'showIf' ->> 'field') = any (v_keys)) then
v_problem := format('step %s: showIf names %s, which isn''t an earlier field', v_step ->> 'key', v_step -> 'showIf' ->> 'field');
exit;
end if;
v_fields := '[]'::jsonb;
for v_field in select x from jsonb_array_elements(v_step -> 'fields') x loop
if (v_field ->> 'key') = any (v_keys) then
v_problem := format('field %s is listed twice', v_field ->> 'key');
exit steps;
end if;
if v_field ? 'showIf' and not ((v_field -> 'showIf' ->> 'field') = any (v_keys)) then
v_problem := format('field %s: showIf names %s, which isn''t an earlier field', v_field ->> 'key', v_field -> 'showIf' ->> 'field');
exit steps;
end if;
v_keys := v_keys || (v_field ->> 'key');
v_custom := null;
if v_field ? 'customField' then
v_problem := format('field %s: customField needs the custom-fields module', v_field ->> 'key');
exit steps;
end if;
if not (v_field ? 'label' and v_field ? 'type') then
v_problem := format('field %s needs a label and a type, or a customField', v_field ->> 'key');
exit steps;
end if;
if (v_field ->> 'type') in ('option', 'multi') and coalesce(jsonb_array_length(v_field -> 'options'), 0) = 0 then
v_problem := format('field %s needs options', v_field ->> 'key');
exit steps;
end if;
if v_field ? 'pattern' then
begin
perform '' ~ (v_field ->> 'pattern');
exception when invalid_regular_expression then
v_problem := format('field %s: pattern is not a valid regular expression', v_field ->> 'key');
end;
exit steps when v_problem is not null;
end if;
if v_field ? 'correct' then
v_scored := true;
if v_field -> 'correct' = 'null'::jsonb then
v_problem := format('field %s: correct can''t be null', v_field ->> 'key');
exit steps;
end if;
if (v_field ->> 'type') in ('consent', 'json', 'nps') then
v_problem := format('field %s: a %s field can''t have a correct answer', v_field ->> 'key', v_field ->> 'type');
exit steps;
end if;
if not "better_supabase"."form_correct_fits"(v_field) then
v_problem := format('field %s: correct isn''t an answer the field takes', v_field ->> 'key');
exit steps;
end if;
elsif v_field ? 'points' then
v_problem := format('field %s: points need a correct answer', v_field ->> 'key');
exit steps;
end if;
v_fields := v_fields || jsonb_build_array(v_field);
end loop;
v_steps := v_steps || jsonb_build_array(jsonb_set(v_step, '{fields}', v_fields));
end loop;
if v_problem is null and definition ? 'scoring' and not v_scored then
v_problem := 'scoring needs a field with a correct answer';
end if;
if v_problem is not null then
v_errors := array[v_problem];
raise exception 'the form definition is invalid: %', array_to_string(v_errors, '; ')
using errcode = '22023', detail = to_jsonb(v_errors)::text, hint = 'FORM_DEFINITION_INVALID';
end if;
return jsonb_build_object('steps', v_steps)
|| case when definition ? 'scoring' then jsonb_build_object('scoring', definition -> 'scoring') else '{}'::jsonb end;
end;
$$;
revoke execute on function "better_supabase"."form_resolve"(uuid, jsonb) from public, anon, authenticated;
-- Whether a field's correct answer is one it takes. Mirrors correctFits in
-- core/contracts/form-definition.ts.
create or replace function "better_supabase"."form_correct_fits"(field jsonb)
returns boolean
language sql
immutable
set search_path = ''
as $$
select case field ->> 'type'
when 'text' then jsonb_typeof(field -> 'correct') = 'string'
when 'textarea' then jsonb_typeof(field -> 'correct') = 'string'
when 'email' then jsonb_typeof(field -> 'correct') = 'string'
when 'url' then jsonb_typeof(field -> 'correct') = 'string'
when 'date' then jsonb_typeof(field -> 'correct') = 'string'
when 'number' then jsonb_typeof(field -> 'correct') = 'number'
when 'integer' then case when jsonb_typeof(field -> 'correct') = 'number'
then (field ->> 'correct')::numeric = trunc((field ->> 'correct')::numeric) else false end
when 'bool' then jsonb_typeof(field -> 'correct') = 'boolean'
when 'option' then jsonb_typeof(field -> 'correct') = 'string'
and exists (select 1 from jsonb_array_elements(coalesce(field -> 'options', '[]'::jsonb)) o where o -> 'value' = field -> 'correct')
when 'multi' then jsonb_typeof(field -> 'correct') = 'array'
and jsonb_array_length(field -> 'correct') > 0
and not exists (
select 1 from jsonb_array_elements(field -> 'correct') v
where jsonb_typeof(v) <> 'string'
or not exists (select 1 from jsonb_array_elements(coalesce(field -> 'options', '[]'::jsonb)) o where o -> 'value' = v))
else false
end
$$;
revoke execute on function "better_supabase"."form_correct_fits"(jsonb) from public, anon, authenticated;
-- Whether a showIf condition holds for the answers. Mirrors conditionHolds in
-- blocks/forms/questionnaire.ts.
create or replace function "better_supabase"."form_condition_holds"(condition jsonb, answers jsonb)
returns boolean
language sql
immutable
set search_path = ''
as $$
select case
when not answers ? (condition ->> 'field') then false
when condition ? 'equals' then answers -> (condition ->> 'field') = condition -> 'equals'
when condition ? 'in' then exists (select 1 from jsonb_array_elements(condition -> 'in') x where x = answers -> (condition ->> 'field'))
else not (answers -> (condition ->> 'field') in ('null'::jsonb, '""'::jsonb, '[]'::jsonb))
end
$$;
revoke execute on function "better_supabase"."form_condition_holds"(jsonb, jsonb) from public, anon, authenticated;
-- Whether an answer earns a field's points: text without case and surrounding
-- spaces, a multi answer as a set, anything else as the same JSON value.
create or replace function "better_supabase"."form_answer_matches"(type text, answer jsonb, correct jsonb)
returns boolean
language sql
immutable
set search_path = ''
as $$
select case
when type in ('text', 'textarea', 'email', 'url') then jsonb_typeof(answer) = 'string' and jsonb_typeof(correct) = 'string'
and lower(btrim(answer #>> '{}', ' ')) = lower(btrim(correct #>> '{}', ' '))
when type = 'multi' then jsonb_typeof(answer) = 'array' and jsonb_typeof(correct) = 'array'
and answer @> correct and correct @> answer
else coalesce(answer = correct, false)
end
$$;
revoke execute on function "better_supabase"."form_answer_matches"(text, jsonb, jsonb) from public, anon, authenticated;
-- A submission's grade: { score, maxScore, passed } against the answer key
-- (field key to correct answer), or null for a form without one. A field its
-- showIf (or its step's) hides counts toward neither score; passed is null
-- without scoring.passMark. Mirrors formScore in blocks/forms/scoring.ts.
create or replace function "better_supabase"."form_score"(definition jsonb, answer_key jsonb, answers jsonb)
returns jsonb
language plpgsql
immutable
set search_path = ''
as $$
declare
v_step jsonb;
v_field jsonb;
v_points numeric;
v_score numeric := 0;
v_max numeric := 0;
v_pass numeric := (definition -> 'scoring' ->> 'passMark')::numeric;
begin
if answer_key is null or answer_key = '{}'::jsonb then
return null;
end if;
for v_step in select x from jsonb_array_elements(definition -> 'steps') x loop
continue when v_step ? 'showIf' and not "better_supabase"."form_condition_holds"(v_step -> 'showIf', answers);
for v_field in select x from jsonb_array_elements(v_step -> 'fields') x loop
continue when not answer_key ? (v_field ->> 'key');
continue when v_field ? 'showIf' and not "better_supabase"."form_condition_holds"(v_field -> 'showIf', answers);
v_points := coalesce((v_field ->> 'points')::numeric, 1);
v_max := v_max + v_points;
if answers ? (v_field ->> 'key')
and "better_supabase"."form_answer_matches"(v_field ->> 'type', answers -> (v_field ->> 'key'), answer_key -> (v_field ->> 'key')) then
v_score := v_score + v_points;
end if;
end loop;
end loop;
return jsonb_build_object('score', v_score, 'maxScore', v_max,
'passed', case when v_pass is null then null else v_score * 100 >= v_pass * v_max end);
end;
$$;
revoke execute on function "better_supabase"."form_score"(jsonb, jsonb, jsonb) from public, anon, authenticated;
-- The definition without its correct answers, and the answer key they make
-- (field key to correct answer), as { definition, key }.
create or replace function "better_supabase"."form_answer_split"(definition jsonb)
returns jsonb
language sql
immutable
set search_path = ''
as $$
select jsonb_build_object(
'definition', jsonb_set(definition, '{steps}', coalesce((
select jsonb_agg(jsonb_set(s.step, '{fields}', (
select jsonb_agg(f.field - 'correct' order by f.ord)
from jsonb_array_elements(s.step -> 'fields') with ordinality as f(field, ord))) order by s.ord)
from jsonb_array_elements(definition -> 'steps') with ordinality as s(step, ord)), '[]'::jsonb)),
'key', coalesce((
select jsonb_object_agg(f.field ->> 'key', f.field -> 'correct')
from jsonb_array_elements(definition -> 'steps') s(step)
cross join lateral jsonb_array_elements(s.step -> 'fields') f(field)
where f.field ? 'correct'), '{}'::jsonb))
$$;
revoke execute on function "better_supabase"."form_answer_split"(jsonb) from public, anon, authenticated;
-- A stored definition with its answer key put back, for the form's managers.
create or replace function "better_supabase"."form_answer_merge"(definition jsonb, answer_key jsonb)
returns jsonb
language sql
immutable
set search_path = ''
as $$
select case when answer_key is null or answer_key = '{}'::jsonb then definition
else jsonb_set(definition, '{steps}', coalesce((
select jsonb_agg(jsonb_set(s.step, '{fields}', (
select jsonb_agg(case when answer_key ? (f.field ->> 'key') then f.field || jsonb_build_object('correct', answer_key -> (f.field ->> 'key')) else f.field end order by f.ord)
from jsonb_array_elements(s.step -> 'fields') with ordinality as f(field, ord))) order by s.ord)
from jsonb_array_elements(definition -> 'steps') with ordinality as s(step, ord)), '[]'::jsonb))
end
$$;
revoke execute on function "better_supabase"."form_answer_merge"(jsonb, jsonb) from public, anon, authenticated;
-- Creates a draft form. fields sets the extra columns by name.
create or replace function "better_supabase"."create_form"(tenant uuid, key text, title text, description text default null, fields jsonb default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."forms"%rowtype;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', create_form.tenant, 'forms.manage'), false)) then
raise exception 'not allowed to manage forms' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
if create_form.key is null or create_form.key !~ '^[a-z][a-z0-9_-]{0,62}$' then
raise exception 'a form key is lowercase letters, digits, - and _, starting with a letter' using errcode = '22023', hint = 'FORM_KEY_INVALID';
end if;
if exists (select 1 from "better_supabase"."forms" x where x."tenant_id" = create_form.tenant and x."key" = create_form.key) then
raise exception 'a form with this key exists' using errcode = '23505', hint = 'FORM_KEY_TAKEN';
end if;
insert into "better_supabase"."forms" ("tenant_id", "key", "title", "description", "created_by")
values (create_form.tenant, create_form.key, create_form.title, create_form.description, auth.uid())
returning * into v_row;
null;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'key', v_row."key", 'title', v_row."title", 'description', v_row."description", 'status', v_row."status", 'currentVersionId', v_row."current_version_id", 'createdBy', v_row."created_by", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."create_form"(uuid, text, text, text, jsonb) from public, anon;
grant execute on function "better_supabase"."create_form"(uuid, text, text, text, jsonb) to authenticated, service_role;
-- Changes the title, description, status or the extra columns in fields.
-- A form opens for submissions once it has a published version.
create or replace function "better_supabase"."update_form"(form_id uuid, title text default null, description text default null, status text default null, fields jsonb default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."forms"%rowtype;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."forms" x where x."id" = update_form.form_id for update;
if not found then
raise exception 'form not found' using errcode = 'P0002', hint = 'FORM_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'forms.manage'), false)) then
raise exception 'not allowed to manage forms' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
if update_form.status is not null and update_form.status not in ('open', 'closed', 'archived') then
raise exception 'status is open, closed or archived' using errcode = '22023', hint = 'FORM_STATUS_INVALID';
end if;
if update_form.status = 'open' and v_row."current_version_id" is null then
raise exception 'publish a version before opening the form' using errcode = '55000', hint = 'FORM_NOT_PUBLISHED';
end if;
update "better_supabase"."forms" x set
"title" = coalesce(update_form.title, x."title"),
"description" = coalesce(update_form.description, x."description"),
"status" = coalesce(update_form.status, x."status"),
"updated_at" = now()
where x."id" = update_form.form_id
returning * into v_row;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'key', v_row."key", 'title', v_row."title", 'description', v_row."description", 'status', v_row."status", 'currentVersionId', v_row."current_version_id", 'createdBy', v_row."created_by", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."update_form"(uuid, text, text, text, jsonb) from public, anon;
grant execute on function "better_supabase"."update_form"(uuid, text, text, text, jsonb) to authenticated, service_role;
-- Publishes a new version: checks the definition, copies custom fields in,
-- builds the version's JSON Schema and makes it current. A draft form opens.
create or replace function "better_supabase"."publish_form_version"(form_id uuid, definition jsonb)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_form "better_supabase"."forms"%rowtype;
v_resolved jsonb;
v_split jsonb;
v_number integer;
v_row "better_supabase"."form_versions"%rowtype;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_form from "better_supabase"."forms" x where x."id" = publish_form_version.form_id for update;
if not found then
raise exception 'form not found' using errcode = 'P0002', hint = 'FORM_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_form."tenant_id", 'forms.manage'), false)) then
raise exception 'not allowed to manage forms' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_form_publish"(uuid, jsonb)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::jsonb)', v_hook::oid::regproc)
using publish_form_version.form_id, publish_form_version.definition;
end if;
end;
v_resolved := "better_supabase"."form_resolve"(v_form."tenant_id", publish_form_version.definition);
v_split := "better_supabase"."form_answer_split"(v_resolved);
if v_split -> 'key' <> '{}'::jsonb then
v_resolved := v_split -> 'definition';
end if;
select coalesce(max(x."number"), 0) + 1 into v_number from "better_supabase"."form_versions" x where x."form_id" = v_form."id";
insert into "better_supabase"."form_versions" ("tenant_id", "form_id", "number", "definition", "schema", "created_by")
values (v_form."tenant_id", v_form."id", v_number, v_resolved, "better_supabase"."form_schema"(v_resolved), auth.uid())
returning * into v_row;
if v_split -> 'key' <> '{}'::jsonb then
insert into "better_supabase"."form_answer_keys" ("version_id", "tenant_id", "answers")
values (v_row."id", v_row."tenant_id", v_split -> 'key');
end if;
update "better_supabase"."forms" x set
"current_version_id" = v_row."id",
"status" = case when x."status" = 'draft' then 'open' else x."status" end,
"updated_at" = now()
where x."id" = v_form."id";
null;
declare
v_hook regprocedure := to_regprocedure('"public"."after_form_publish"(uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid)', v_hook::oid::regproc)
using v_row."id";
end if;
end;
return jsonb_build_object('id', v_row."id", 'formId', v_row."form_id", 'number', v_row."number", 'definition', case when coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'forms.manage'), false)
then "better_supabase"."form_answer_merge"(v_row."definition", (select a."answers" from "better_supabase"."form_answer_keys" a where a."version_id" = v_row."id"))
else v_row."definition" end, 'schema', v_row."schema", 'createdBy', v_row."created_by", 'createdAt', v_row."created_at");
end;
$$;
revoke execute on function "better_supabase"."publish_form_version"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."publish_form_version"(uuid, jsonb) to authenticated, service_role;
create or replace function "better_supabase"."get_form"(form_id uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."forms"%rowtype;
v_version "better_supabase"."form_versions"%rowtype;
begin
select * into v_row from "better_supabase"."forms" x where x."id" = get_form.form_id;
if not found then
raise exception 'form not found' using errcode = 'P0002', hint = 'FORM_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'forms.read'), false)) then
raise exception 'not allowed to read this form' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
select * into v_version from "better_supabase"."form_versions" x where x."id" = v_row."current_version_id";
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'key', v_row."key", 'title', v_row."title", 'description', v_row."description", 'status', v_row."status", 'currentVersionId', v_row."current_version_id", 'createdBy', v_row."created_by", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at") || jsonb_build_object('version', case when v_version."id" is null then null else jsonb_build_object('id', v_version."id", 'formId', v_version."form_id", 'number', v_version."number", 'definition', case when coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_version."tenant_id", 'forms.manage'), false)
then "better_supabase"."form_answer_merge"(v_version."definition", (select a."answers" from "better_supabase"."form_answer_keys" a where a."version_id" = v_version."id"))
else v_version."definition" end, 'schema', v_version."schema", 'createdBy', v_version."created_by", 'createdAt', v_version."created_at") end);
end;
$$;
revoke execute on function "better_supabase"."get_form"(uuid) from public, anon;
grant execute on function "better_supabase"."get_form"(uuid) to authenticated, service_role;
create or replace function "better_supabase"."get_form_version"(version_id uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."form_versions"%rowtype;
begin
select * into v_row from "better_supabase"."form_versions" x where x."id" = get_form_version.version_id;
if not found then
raise exception 'form version not found' using errcode = 'P0002', hint = 'FORM_VERSION_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'forms.read'), false)) then
raise exception 'not allowed to read this form' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
return jsonb_build_object('id', v_row."id", 'formId', v_row."form_id", 'number', v_row."number", 'definition', case when coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'forms.manage'), false)
then "better_supabase"."form_answer_merge"(v_row."definition", (select a."answers" from "better_supabase"."form_answer_keys" a where a."version_id" = v_row."id"))
else v_row."definition" end, 'schema', v_row."schema", 'createdBy', v_row."created_by", 'createdAt', v_row."created_at");
end;
$$;
revoke execute on function "better_supabase"."get_form_version"(uuid) from public, anon;
grant execute on function "better_supabase"."get_form_version"(uuid) to authenticated, service_role;
-- Newest first. filters is { status (a value or a list), search, sort, direction,
-- facet, count, limit, after, offset, paged, total, totalCap } (ADR 0749).
create or replace function "better_supabase"."list_forms"(tenant uuid, filters jsonb default '{}')
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_filters jsonb := coalesce(list_forms.filters, '{}'::jsonb);
v_search text := case when nullif(trim(v_filters ->> 'search'), '') is null then null
else '%' || replace(replace(replace(trim(v_filters ->> 'search'), '\', '\\'), '%', '\%'), '_', '\_') || '%' end;
v_limit integer := least(greatest(coalesce((v_filters ->> 'limit')::integer, 200), 1), 500);
v_offset integer := greatest(coalesce((v_filters ->> 'offset')::integer, 0), 0);
v_after jsonb := v_filters -> 'after';
v_paged boolean := coalesce((v_filters ->> 'paged')::boolean, false);
v_total_cap integer := least(greatest(coalesce((v_filters ->> 'totalCap')::integer, 10000), 1), 100000);
v_items jsonb;
v_more boolean;
v_next jsonb;
v_total integer;
v_sort text := nullif(v_filters ->> 'sort', '');
v_dir text := nullif(v_filters ->> 'direction', '');
v_facet text := nullif(v_filters ->> 'facet', '');
v_count boolean := coalesce((v_filters ->> 'count')::boolean, false);
v_result jsonb;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', list_forms.tenant, 'forms.read'), false)) then
raise exception 'not allowed to read forms' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
if v_filters ? 'after' and v_filters ? 'offset' then
raise exception 'after and offset are two ways to page; pass one' using errcode = '22023', hint = 'FORM_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('status') then
raise exception 'facet is one of status' using errcode = '22023', hint = 'FORM_INVALID';
end if;
with s as (
select (case v_facet when 'status' then (x."status")::text end) as v
from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
limit v_total_cap + 1
)
select jsonb_build_object('facet', v_facet, 'values', coalesce(jsonb_agg(jsonb_build_object('value', g.v, 'count', jsonb_build_object('value', g.n, 'exact', g.exact)) order by g.n desc, g.v), '[]'::jsonb))
into v_result
from (
select s.v, count(*) as n, (select count(*) from s) <= v_total_cap as exact
from s where s.v is not null group by s.v order by n desc, s.v limit 100
) g;
return v_result;
end if;
if v_count then
select count(*) into v_total from (
select 1 from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
limit v_total_cap + 1
) c;
return jsonb_build_object('value', least(v_total, v_total_cap), 'exact', v_total <= v_total_cap);
end if;
if v_sort is not null and v_sort not in ('createdAt', 'title', 'key') then
raise exception 'sort is one of createdAt, title, key' using errcode = '22023', hint = 'FORM_INVALID';
end if;
if v_dir is not null and v_dir not in ('asc', 'desc') then
raise exception 'direction is asc or desc' using errcode = '22023', hint = 'FORM_INVALID';
end if;
if v_sort is null and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'key', x."key", 'title', x."title", 'description', x."description", 'status', x."status", 'currentVersionId', x."current_version_id", 'createdBy', x."created_by", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
and (v_after is null or (x."created_at" >= (v_after ->> 0)::timestamptz and ((x."created_at" > (v_after ->> 0)::timestamptz) or (x."created_at" = (v_after ->> 0)::timestamptz and x."id" < (v_after ->> 1)::uuid))))
order by x."created_at" asc, x."id" desc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'key', x."key", 'title', x."title", 'description', x."description", 'status', x."status", 'currentVersionId', x."current_version_id", 'createdBy', x."created_by", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
and (v_after is null or (x."created_at", x."id") < ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."created_at" desc, x."id" desc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'createdAt' and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'key', x."key", 'title', x."title", 'description', x."description", 'status', x."status", 'currentVersionId', x."current_version_id", 'createdBy', x."created_by", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
and (v_after is null or (x."created_at" >= (v_after ->> 0)::timestamptz and ((x."created_at" > (v_after ->> 0)::timestamptz) or (x."created_at" = (v_after ->> 0)::timestamptz and x."id" < (v_after ->> 1)::uuid))))
order by x."created_at" asc, x."id" desc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'createdAt' and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'key', x."key", 'title', x."title", 'description', x."description", 'status', x."status", 'currentVersionId', x."current_version_id", 'createdBy', x."created_by", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
and (v_after is null or (x."created_at", x."id") < ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."created_at" desc, x."id" desc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'title' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'key', x."key", 'title', x."title", 'description', x."description", 'status', x."status", 'currentVersionId', x."current_version_id", 'createdBy', x."created_by", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."title")::text, (x."id")::text) as k
from (
select * from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
and (v_after is null or (x."title", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."title" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'title' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'key', x."key", 'title', x."title", 'description', x."description", 'status', x."status", 'currentVersionId', x."current_version_id", 'createdBy', x."created_by", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."title")::text, (x."id")::text) as k
from (
select * from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
and (v_after is null or (x."title" <= (v_after ->> 0)::text and ((x."title" < (v_after ->> 0)::text) or (x."title" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."title" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'key' and coalesce(v_dir, 'asc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'key', x."key", 'title', x."title", 'description', x."description", 'status', x."status", 'currentVersionId', x."current_version_id", 'createdBy', x."created_by", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."key")::text, (x."id")::text) as k
from (
select * from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
and (v_after is null or (x."key", x."id") > ((v_after ->> 0)::text, (v_after ->> 1)::uuid))
order by x."key" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'key' and coalesce(v_dir, 'asc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'key', x."key", 'title', x."title", 'description', x."description", 'status', x."status", 'currentVersionId', x."current_version_id", 'createdBy', x."created_by", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."key")::text, (x."id")::text) as k
from (
select * from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
and (v_after is null or (x."key" <= (v_after ->> 0)::text and ((x."key" < (v_after ->> 0)::text) or (x."key" = (v_after ->> 0)::text and x."id" > (v_after ->> 1)::uuid))))
order by x."key" desc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
end if;
if not v_paged then
return v_items;
end if;
if coalesce((v_filters ->> 'total')::boolean, false) then
select count(*) into v_total from (
select 1 from "better_supabase"."forms" x
where x."tenant_id" = list_forms.tenant
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (v_search is null or x."title" ilike v_search or x."key" ilike v_search)
limit v_total_cap + 1
) c;
end if;
return jsonb_build_object('items', v_items, 'hasMore', v_more, 'nextCursor', case when v_more then v_next end)
|| case when v_total is null then '{}'::jsonb
else jsonb_build_object('total', least(v_total, v_total_cap), 'totalCapped', v_total > v_total_cap) end;
end;
$$;
revoke execute on function "better_supabase"."list_forms"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."list_forms"(uuid, jsonb) to authenticated, service_role;
-- Newest first. Reviewers see every submission; others see their own.
-- filters is { formId, status, respondentId (each a value or a list), includeArchived, search
-- (a text match in the answers), sort (createdAt, submittedAt), direction,
-- facet, count, limit, after, offset, paged, total, totalCap } (ADR 1077).
create or replace function "better_supabase"."page_form_submissions"(tenant uuid, filters jsonb default '{}')
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_variable
declare
v_filters jsonb := coalesce(page_form_submissions.filters, '{}'::jsonb);
v_search text := case when nullif(trim(v_filters ->> 'search'), '') is null then null
else '%' || replace(replace(replace(trim(v_filters ->> 'search'), '\', '\\'), '%', '\%'), '_', '\_') || '%' end;
v_all boolean := coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', page_form_submissions.tenant, 'forms.review'), false);
v_limit integer := least(greatest(coalesce((v_filters ->> 'limit')::integer, 50), 1), 200);
v_offset integer := greatest(coalesce((v_filters ->> 'offset')::integer, 0), 0);
v_after jsonb := v_filters -> 'after';
v_paged boolean := coalesce((v_filters ->> 'paged')::boolean, false);
v_total_cap integer := least(greatest(coalesce((v_filters ->> 'totalCap')::integer, 10000), 1), 100000);
v_items jsonb;
v_more boolean;
v_next jsonb;
v_total integer;
v_sort text := nullif(v_filters ->> 'sort', '');
v_dir text := nullif(v_filters ->> 'direction', '');
v_facet text := nullif(v_filters ->> 'facet', '');
v_count boolean := coalesce((v_filters ->> 'count')::boolean, false);
v_result jsonb;
begin
if v_filters ? 'after' and v_filters ? 'offset' then
raise exception 'after and offset are two ways to page; pass one' using errcode = '22023', hint = 'FORM_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('status', 'formId') then
raise exception 'facet is one of status, formId' using errcode = '22023', hint = 'FORM_INVALID';
end if;
with s as (
select (case v_facet when 'status' then (x."status")::text when 'formId' then (x."form_id"::text)::text end) as v
from "better_supabase"."form_submissions" x
where x."tenant_id" = page_form_submissions.tenant
and (not (v_filters -> 'formId' is not null and jsonb_typeof(v_filters -> 'formId') <> 'null' and not (jsonb_typeof(v_filters -> 'formId') = 'array' and jsonb_array_length(v_filters -> 'formId') = 0)) or x."form_id" = any((case when jsonb_typeof(v_filters -> 'formId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'formId')) else array[v_filters ->> 'formId'] end)::uuid[]))
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'respondentId' is not null and jsonb_typeof(v_filters -> 'respondentId') <> 'null' and not (jsonb_typeof(v_filters -> 'respondentId') = 'array' and jsonb_array_length(v_filters -> 'respondentId') = 0)) or x."respondent_id" = any((case when jsonb_typeof(v_filters -> 'respondentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'respondentId')) else array[v_filters ->> 'respondentId'] end)::uuid[]))
and (coalesce(nullif(coalesce(v_filters #>> '{includeArchived,0}', v_filters ->> 'includeArchived'), '') = 'true', false) or x."archived_at" is null)
and (v_search is null or x."answers"::text ilike v_search)
and (v_all or x."respondent_id" = auth.uid())
limit v_total_cap + 1
)
select jsonb_build_object('facet', v_facet, 'values', coalesce(jsonb_agg(jsonb_build_object('value', g.v, 'count', jsonb_build_object('value', g.n, 'exact', g.exact)) order by g.n desc, g.v), '[]'::jsonb))
into v_result
from (
select s.v, count(*) as n, (select count(*) from s) <= v_total_cap as exact
from s where s.v is not null group by s.v order by n desc, s.v limit 100
) g;
return v_result;
end if;
if v_count then
select count(*) into v_total from (
select 1 from "better_supabase"."form_submissions" x
where x."tenant_id" = page_form_submissions.tenant
and (not (v_filters -> 'formId' is not null and jsonb_typeof(v_filters -> 'formId') <> 'null' and not (jsonb_typeof(v_filters -> 'formId') = 'array' and jsonb_array_length(v_filters -> 'formId') = 0)) or x."form_id" = any((case when jsonb_typeof(v_filters -> 'formId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'formId')) else array[v_filters ->> 'formId'] end)::uuid[]))
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'respondentId' is not null and jsonb_typeof(v_filters -> 'respondentId') <> 'null' and not (jsonb_typeof(v_filters -> 'respondentId') = 'array' and jsonb_array_length(v_filters -> 'respondentId') = 0)) or x."respondent_id" = any((case when jsonb_typeof(v_filters -> 'respondentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'respondentId')) else array[v_filters ->> 'respondentId'] end)::uuid[]))
and (coalesce(nullif(coalesce(v_filters #>> '{includeArchived,0}', v_filters ->> 'includeArchived'), '') = 'true', false) or x."archived_at" is null)
and (v_search is null or x."answers"::text ilike v_search)
and (v_all or x."respondent_id" = auth.uid())
limit v_total_cap + 1
) c;
return jsonb_build_object('value', least(v_total, v_total_cap), 'exact', v_total <= v_total_cap);
end if;
if v_sort is not null and v_sort not in ('createdAt', 'submittedAt') then
raise exception 'sort is one of createdAt, submittedAt' using errcode = '22023', hint = 'FORM_INVALID';
end if;
if v_dir is not null and v_dir not in ('asc', 'desc') then
raise exception 'direction is asc or desc' using errcode = '22023', hint = 'FORM_INVALID';
end if;
if v_sort is null and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'formId', x."form_id", 'versionId', x."version_id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'respondentId', x."respondent_id", 'answers', x."answers", 'status', x."status", 'source', x."source", 'reviewedBy', x."reviewed_by", 'reviewedAt', x."reviewed_at", 'archivedAt', x."archived_at", 'createdAt', x."created_at", 'submittedAt', x."submitted_at", 'updatedAt', x."updated_at", 'score', x."score", 'maxScore', x."max_score", 'passed', x."passed") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."form_submissions" x
where x."tenant_id" = page_form_submissions.tenant
and (not (v_filters -> 'formId' is not null and jsonb_typeof(v_filters -> 'formId') <> 'null' and not (jsonb_typeof(v_filters -> 'formId') = 'array' and jsonb_array_length(v_filters -> 'formId') = 0)) or x."form_id" = any((case when jsonb_typeof(v_filters -> 'formId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'formId')) else array[v_filters ->> 'formId'] end)::uuid[]))
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'respondentId' is not null and jsonb_typeof(v_filters -> 'respondentId') <> 'null' and not (jsonb_typeof(v_filters -> 'respondentId') = 'array' and jsonb_array_length(v_filters -> 'respondentId') = 0)) or x."respondent_id" = any((case when jsonb_typeof(v_filters -> 'respondentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'respondentId')) else array[v_filters ->> 'respondentId'] end)::uuid[]))
and (coalesce(nullif(coalesce(v_filters #>> '{includeArchived,0}', v_filters ->> 'includeArchived'), '') = 'true', false) or x."archived_at" is null)
and (v_search is null or x."answers"::text ilike v_search)
and (v_all or x."respondent_id" = auth.uid())
and (v_after is null or (x."created_at" >= (v_after ->> 0)::timestamptz and ((x."created_at" > (v_after ->> 0)::timestamptz) or (x."created_at" = (v_after ->> 0)::timestamptz and x."id" < (v_after ->> 1)::uuid))))
order by x."created_at" asc, x."id" desc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'formId', x."form_id", 'versionId', x."version_id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'respondentId', x."respondent_id", 'answers', x."answers", 'status', x."status", 'source', x."source", 'reviewedBy', x."reviewed_by", 'reviewedAt', x."reviewed_at", 'archivedAt', x."archived_at", 'createdAt', x."created_at", 'submittedAt', x."submitted_at", 'updatedAt', x."updated_at", 'score', x."score", 'maxScore', x."max_score", 'passed', x."passed") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."form_submissions" x
where x."tenant_id" = page_form_submissions.tenant
and (not (v_filters -> 'formId' is not null and jsonb_typeof(v_filters -> 'formId') <> 'null' and not (jsonb_typeof(v_filters -> 'formId') = 'array' and jsonb_array_length(v_filters -> 'formId') = 0)) or x."form_id" = any((case when jsonb_typeof(v_filters -> 'formId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'formId')) else array[v_filters ->> 'formId'] end)::uuid[]))
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'respondentId' is not null and jsonb_typeof(v_filters -> 'respondentId') <> 'null' and not (jsonb_typeof(v_filters -> 'respondentId') = 'array' and jsonb_array_length(v_filters -> 'respondentId') = 0)) or x."respondent_id" = any((case when jsonb_typeof(v_filters -> 'respondentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'respondentId')) else array[v_filters ->> 'respondentId'] end)::uuid[]))
and (coalesce(nullif(coalesce(v_filters #>> '{includeArchived,0}', v_filters ->> 'includeArchived'), '') = 'true', false) or x."archived_at" is null)
and (v_search is null or x."answers"::text ilike v_search)
and (v_all or x."respondent_id" = auth.uid())
and (v_after is null or (x."created_at", x."id") < ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."created_at" desc, x."id" desc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'createdAt' and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'formId', x."form_id", 'versionId', x."version_id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'respondentId', x."respondent_id", 'answers', x."answers", 'status', x."status", 'source', x."source", 'reviewedBy', x."reviewed_by", 'reviewedAt', x."reviewed_at", 'archivedAt', x."archived_at", 'createdAt', x."created_at", 'submittedAt', x."submitted_at", 'updatedAt', x."updated_at", 'score', x."score", 'maxScore', x."max_score", 'passed', x."passed") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."form_submissions" x
where x."tenant_id" = page_form_submissions.tenant
and (not (v_filters -> 'formId' is not null and jsonb_typeof(v_filters -> 'formId') <> 'null' and not (jsonb_typeof(v_filters -> 'formId') = 'array' and jsonb_array_length(v_filters -> 'formId') = 0)) or x."form_id" = any((case when jsonb_typeof(v_filters -> 'formId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'formId')) else array[v_filters ->> 'formId'] end)::uuid[]))
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'respondentId' is not null and jsonb_typeof(v_filters -> 'respondentId') <> 'null' and not (jsonb_typeof(v_filters -> 'respondentId') = 'array' and jsonb_array_length(v_filters -> 'respondentId') = 0)) or x."respondent_id" = any((case when jsonb_typeof(v_filters -> 'respondentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'respondentId')) else array[v_filters ->> 'respondentId'] end)::uuid[]))
and (coalesce(nullif(coalesce(v_filters #>> '{includeArchived,0}', v_filters ->> 'includeArchived'), '') = 'true', false) or x."archived_at" is null)
and (v_search is null or x."answers"::text ilike v_search)
and (v_all or x."respondent_id" = auth.uid())
and (v_after is null or (x."created_at" >= (v_after ->> 0)::timestamptz and ((x."created_at" > (v_after ->> 0)::timestamptz) or (x."created_at" = (v_after ->> 0)::timestamptz and x."id" < (v_after ->> 1)::uuid))))
order by x."created_at" asc, x."id" desc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'createdAt' and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'formId', x."form_id", 'versionId', x."version_id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'respondentId', x."respondent_id", 'answers', x."answers", 'status', x."status", 'source', x."source", 'reviewedBy', x."reviewed_by", 'reviewedAt', x."reviewed_at", 'archivedAt', x."archived_at", 'createdAt', x."created_at", 'submittedAt', x."submitted_at", 'updatedAt', x."updated_at", 'score', x."score", 'maxScore', x."max_score", 'passed', x."passed") as j, jsonb_build_array((x."created_at")::text, (x."id")::text) as k
from (
select * from "better_supabase"."form_submissions" x
where x."tenant_id" = page_form_submissions.tenant
and (not (v_filters -> 'formId' is not null and jsonb_typeof(v_filters -> 'formId') <> 'null' and not (jsonb_typeof(v_filters -> 'formId') = 'array' and jsonb_array_length(v_filters -> 'formId') = 0)) or x."form_id" = any((case when jsonb_typeof(v_filters -> 'formId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'formId')) else array[v_filters ->> 'formId'] end)::uuid[]))
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'respondentId' is not null and jsonb_typeof(v_filters -> 'respondentId') <> 'null' and not (jsonb_typeof(v_filters -> 'respondentId') = 'array' and jsonb_array_length(v_filters -> 'respondentId') = 0)) or x."respondent_id" = any((case when jsonb_typeof(v_filters -> 'respondentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'respondentId')) else array[v_filters ->> 'respondentId'] end)::uuid[]))
and (coalesce(nullif(coalesce(v_filters #>> '{includeArchived,0}', v_filters ->> 'includeArchived'), '') = 'true', false) or x."archived_at" is null)
and (v_search is null or x."answers"::text ilike v_search)
and (v_all or x."respondent_id" = auth.uid())
and (v_after is null or (x."created_at", x."id") < ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by x."created_at" desc, x."id" desc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'submittedAt' and coalesce(v_dir, 'desc') = 'asc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'formId', x."form_id", 'versionId', x."version_id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'respondentId', x."respondent_id", 'answers', x."answers", 'status', x."status", 'source', x."source", 'reviewedBy', x."reviewed_by", 'reviewedAt', x."reviewed_at", 'archivedAt', x."archived_at", 'createdAt', x."created_at", 'submittedAt', x."submitted_at", 'updatedAt', x."updated_at", 'score', x."score", 'maxScore', x."max_score", 'passed', x."passed") as j, jsonb_build_array((coalesce(x."submitted_at", timestamptz '-infinity'))::text, (x."id")::text) as k
from (
select * from "better_supabase"."form_submissions" x
where x."tenant_id" = page_form_submissions.tenant
and (not (v_filters -> 'formId' is not null and jsonb_typeof(v_filters -> 'formId') <> 'null' and not (jsonb_typeof(v_filters -> 'formId') = 'array' and jsonb_array_length(v_filters -> 'formId') = 0)) or x."form_id" = any((case when jsonb_typeof(v_filters -> 'formId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'formId')) else array[v_filters ->> 'formId'] end)::uuid[]))
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'respondentId' is not null and jsonb_typeof(v_filters -> 'respondentId') <> 'null' and not (jsonb_typeof(v_filters -> 'respondentId') = 'array' and jsonb_array_length(v_filters -> 'respondentId') = 0)) or x."respondent_id" = any((case when jsonb_typeof(v_filters -> 'respondentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'respondentId')) else array[v_filters ->> 'respondentId'] end)::uuid[]))
and (coalesce(nullif(coalesce(v_filters #>> '{includeArchived,0}', v_filters ->> 'includeArchived'), '') = 'true', false) or x."archived_at" is null)
and (v_search is null or x."answers"::text ilike v_search)
and (v_all or x."respondent_id" = auth.uid())
and (v_after is null or (coalesce(x."submitted_at", timestamptz '-infinity') >= (v_after ->> 0)::timestamptz and ((coalesce(x."submitted_at", timestamptz '-infinity') > (v_after ->> 0)::timestamptz) or (coalesce(x."submitted_at", timestamptz '-infinity') = (v_after ->> 0)::timestamptz and x."id" < (v_after ->> 1)::uuid))))
order by coalesce(x."submitted_at", timestamptz '-infinity') asc, x."id" desc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'submittedAt' and coalesce(v_dir, 'desc') = 'desc' then
if v_after is not null and (jsonb_typeof(v_after) <> 'array' or jsonb_array_length(v_after) <> 2) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'FORM_INVALID';
end if;
select coalesce(jsonb_agg(p.j order by p.n) filter (where p.n <= v_limit), '[]'::jsonb),
count(*) > v_limit,
(array_agg(p.k order by p.n) filter (where p.n = v_limit))[1]
into v_items, v_more, v_next
from (
select row_number() over () as n, jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'formId', x."form_id", 'versionId', x."version_id", 'subjectType', x."subject_type", 'subjectId', x."subject_id", 'respondentId', x."respondent_id", 'answers', x."answers", 'status', x."status", 'source', x."source", 'reviewedBy', x."reviewed_by", 'reviewedAt', x."reviewed_at", 'archivedAt', x."archived_at", 'createdAt', x."created_at", 'submittedAt', x."submitted_at", 'updatedAt', x."updated_at", 'score', x."score", 'maxScore', x."max_score", 'passed', x."passed") as j, jsonb_build_array((coalesce(x."submitted_at", timestamptz '-infinity'))::text, (x."id")::text) as k
from (
select * from "better_supabase"."form_submissions" x
where x."tenant_id" = page_form_submissions.tenant
and (not (v_filters -> 'formId' is not null and jsonb_typeof(v_filters -> 'formId') <> 'null' and not (jsonb_typeof(v_filters -> 'formId') = 'array' and jsonb_array_length(v_filters -> 'formId') = 0)) or x."form_id" = any((case when jsonb_typeof(v_filters -> 'formId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'formId')) else array[v_filters ->> 'formId'] end)::uuid[]))
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'respondentId' is not null and jsonb_typeof(v_filters -> 'respondentId') <> 'null' and not (jsonb_typeof(v_filters -> 'respondentId') = 'array' and jsonb_array_length(v_filters -> 'respondentId') = 0)) or x."respondent_id" = any((case when jsonb_typeof(v_filters -> 'respondentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'respondentId')) else array[v_filters ->> 'respondentId'] end)::uuid[]))
and (coalesce(nullif(coalesce(v_filters #>> '{includeArchived,0}', v_filters ->> 'includeArchived'), '') = 'true', false) or x."archived_at" is null)
and (v_search is null or x."answers"::text ilike v_search)
and (v_all or x."respondent_id" = auth.uid())
and (v_after is null or (coalesce(x."submitted_at", timestamptz '-infinity'), x."id") < ((v_after ->> 0)::timestamptz, (v_after ->> 1)::uuid))
order by coalesce(x."submitted_at", timestamptz '-infinity') desc, x."id" desc
limit v_limit + 1 offset v_offset
) x
) p;
end if;
if not v_paged then
return v_items;
end if;
if coalesce((v_filters ->> 'total')::boolean, false) then
select count(*) into v_total from (
select 1 from "better_supabase"."form_submissions" x
where x."tenant_id" = page_form_submissions.tenant
and (not (v_filters -> 'formId' is not null and jsonb_typeof(v_filters -> 'formId') <> 'null' and not (jsonb_typeof(v_filters -> 'formId') = 'array' and jsonb_array_length(v_filters -> 'formId') = 0)) or x."form_id" = any((case when jsonb_typeof(v_filters -> 'formId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'formId')) else array[v_filters ->> 'formId'] end)::uuid[]))
and (not (v_filters -> 'status' is not null and jsonb_typeof(v_filters -> 'status') <> 'null' and not (jsonb_typeof(v_filters -> 'status') = 'array' and jsonb_array_length(v_filters -> 'status') = 0)) or x."status"::text = any((case when jsonb_typeof(v_filters -> 'status') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'status')) else array[v_filters ->> 'status'] end)::text[]))
and (not (v_filters -> 'respondentId' is not null and jsonb_typeof(v_filters -> 'respondentId') <> 'null' and not (jsonb_typeof(v_filters -> 'respondentId') = 'array' and jsonb_array_length(v_filters -> 'respondentId') = 0)) or x."respondent_id" = any((case when jsonb_typeof(v_filters -> 'respondentId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'respondentId')) else array[v_filters ->> 'respondentId'] end)::uuid[]))
and (coalesce(nullif(coalesce(v_filters #>> '{includeArchived,0}', v_filters ->> 'includeArchived'), '') = 'true', false) or x."archived_at" is null)
and (v_search is null or x."answers"::text ilike v_search)
and (v_all or x."respondent_id" = auth.uid())
limit v_total_cap + 1
) c;
end if;
return jsonb_build_object('items', v_items, 'hasMore', v_more, 'nextCursor', case when v_more then v_next end)
|| case when v_total is null then '{}'::jsonb
else jsonb_build_object('total', least(v_total, v_total_cap), 'totalCapped', v_total > v_total_cap) end;
end;
$$;
revoke execute on function "better_supabase"."page_form_submissions"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_form_submissions"(uuid, jsonb) to authenticated, service_role;
-- Writes a submission against the form's current version, validating the
-- answers unless it is a draft. Only definer functions of this module call it.
create or replace function "better_supabase"."form_submission_save"(form_id uuid, answers jsonb, subject_type text, subject_id text, respondent uuid, source text, draft boolean, submission_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_form "better_supabase"."forms"%rowtype;
v_schema jsonb;
v_definition jsonb;
v_grade jsonb;
v_errors text[];
v_row "better_supabase"."form_submissions"%rowtype;
v_link jsonb;
begin
select * into v_form from "better_supabase"."forms" x where x."id" = form_submission_save.form_id;
if not found then
raise exception 'form not found' using errcode = 'P0002', hint = 'FORM_NOT_FOUND';
end if;
if v_form."status" <> 'open' then
raise exception 'this form isn''t taking submissions' using errcode = '55000', hint = 'FORM_CLOSED';
end if;
if jsonb_typeof(form_submission_save.answers) is distinct from 'object' then
raise exception 'answers must be an object' using errcode = '22023', hint = 'FORM_ANSWERS_INVALID';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_form_submission"(uuid, jsonb)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::jsonb)', v_hook::oid::regproc)
using form_submission_save.form_id, form_submission_save.answers;
end if;
end;
if not form_submission_save.draft then
select x."schema", x."definition" into v_schema, v_definition from "better_supabase"."form_versions" x where x."id" = v_form."current_version_id";
v_errors := extensions.jsonschema_validation_errors(v_schema::json, form_submission_save.answers::json);
if cardinality(v_errors) > 0 then
raise exception '%.answers does not match its JSON Schema: %', 'form_submissions', array_to_string(v_errors, '; ')
using errcode = '23514', column = 'answers', detail = to_jsonb(v_errors)::text, hint = 'JSON_SCHEMA_INVALID';
end if;
v_grade := "better_supabase"."form_score"(v_definition, (select a."answers" from "better_supabase"."form_answer_keys" a where a."version_id" = v_form."current_version_id"), form_submission_save.answers);
end if;
if form_submission_save.submission_id is not null then
select * into v_row from "better_supabase"."form_submissions" x where x."id" = form_submission_save.submission_id for update;
if not found or v_row."form_id" <> form_submission_save.form_id or v_row."respondent_id" is distinct from form_submission_save.respondent then
raise exception 'submission not found' using errcode = 'P0002', hint = 'FORM_SUBMISSION_NOT_FOUND';
end if;
if v_row."status" <> 'draft' then
raise exception 'only a draft submission can change' using errcode = '55000', hint = 'FORM_SUBMISSION_LOCKED';
end if;
update "better_supabase"."form_submissions" x set
"version_id" = v_form."current_version_id",
"answers" = form_submission_save.answers,
"status" = case when form_submission_save.draft then 'draft' else 'submitted' end,
"submitted_at" = case when form_submission_save.draft then null else now() end,
"subject_type" = coalesce(form_submission_save.subject_type, x."subject_type"),
"subject_id" = coalesce(form_submission_save.subject_id, x."subject_id"),
"score" = (v_grade ->> 'score')::numeric,
"max_score" = (v_grade ->> 'maxScore')::numeric,
"passed" = (v_grade ->> 'passed')::boolean,
"updated_at" = now()
where x."id" = form_submission_save.submission_id
returning * into v_row;
else
insert into "better_supabase"."form_submissions" ("tenant_id", "form_id", "version_id", "subject_type", "subject_id", "respondent_id", "answers", "status", "source", "submitted_at", "score", "max_score", "passed")
values (v_form."tenant_id", v_form."id", v_form."current_version_id", form_submission_save.subject_type, form_submission_save.subject_id, form_submission_save.respondent, form_submission_save.answers,
case when form_submission_save.draft then 'draft' else 'submitted' end, form_submission_save.source,
case when form_submission_save.draft then null else now() end, (v_grade ->> 'score')::numeric, (v_grade ->> 'maxScore')::numeric, (v_grade ->> 'passed')::boolean)
returning * into v_row;
end if;
if not form_submission_save.draft then
null;
declare
v_hook regprocedure := to_regprocedure('"public"."after_form_submission"(uuid)');
begin
if v_hook is not null then
execute format('select %s($1::uuid)', v_hook::oid::regproc)
using v_row."id";
end if;
end;
end if;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'formId', v_row."form_id", 'versionId', v_row."version_id", 'subjectType', v_row."subject_type", 'subjectId', v_row."subject_id", 'respondentId', v_row."respondent_id", 'answers', v_row."answers", 'status', v_row."status", 'source', v_row."source", 'reviewedBy', v_row."reviewed_by", 'reviewedAt', v_row."reviewed_at", 'archivedAt', v_row."archived_at", 'createdAt', v_row."created_at", 'submittedAt', v_row."submitted_at", 'updatedAt', v_row."updated_at", 'score', v_row."score", 'maxScore', v_row."max_score", 'passed', v_row."passed");
end;
$$;
revoke execute on function "better_supabase"."form_submission_save"(uuid, jsonb, text, text, uuid, text, boolean, uuid) from public, anon, authenticated;
-- Submits answers as the caller, or saves them as a draft to finish later
-- (submission_id continues one). A subject links the submission to a record
-- the caller can read.
create or replace function "better_supabase"."submit_form"(form_id uuid, answers jsonb, subject_type text default null, subject_id text default null, submission_id uuid default null, draft boolean default false)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
begin
select x."tenant_id" into v_tenant from "better_supabase"."forms" x where x."id" = submit_form.form_id;
if not found then
raise exception 'form not found' using errcode = 'P0002', hint = 'FORM_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or (auth.uid() is not null and coalesce(better_supabase.can('tenant', v_tenant, 'forms.submit'), false))) then
raise exception 'not allowed to submit this form' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
if (submit_form.subject_type is null) <> (submit_form.subject_id is null) then
raise exception 'pass both subject_type and subject_id, or neither' using errcode = '22023', hint = 'FORM_SUBJECT_INVALID';
end if;
if submit_form.subject_type is not null and not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or true) then
raise exception 'not allowed to link this record' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
return "better_supabase"."form_submission_save"(submit_form.form_id, submit_form.answers, submit_form.subject_type, submit_form.subject_id, auth.uid(),
case when coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') then 'service' else 'member' end, coalesce(submit_form.draft, false), submit_form.submission_id);
end;
$$;
revoke execute on function "better_supabase"."submit_form"(uuid, jsonb, text, text, uuid, boolean) from public, anon;
grant execute on function "better_supabase"."submit_form"(uuid, jsonb, text, text, uuid, boolean) to authenticated, service_role;
create or replace function "better_supabase"."get_form_submission"(submission_id uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."form_submissions"%rowtype;
begin
select * into v_row from "better_supabase"."form_submissions" x where x."id" = get_form_submission.submission_id;
if not found then
raise exception 'submission not found' using errcode = 'P0002', hint = 'FORM_SUBMISSION_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."respondent_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'forms.review'), false)) then
raise exception 'submission not found' using errcode = 'P0002', hint = 'FORM_SUBMISSION_NOT_FOUND';
end if;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'formId', v_row."form_id", 'versionId', v_row."version_id", 'subjectType', v_row."subject_type", 'subjectId', v_row."subject_id", 'respondentId', v_row."respondent_id", 'answers', v_row."answers", 'status', v_row."status", 'source', v_row."source", 'reviewedBy', v_row."reviewed_by", 'reviewedAt', v_row."reviewed_at", 'archivedAt', v_row."archived_at", 'createdAt', v_row."created_at", 'submittedAt', v_row."submitted_at", 'updatedAt', v_row."updated_at", 'score', v_row."score", 'maxScore', v_row."max_score", 'passed', v_row."passed");
end;
$$;
revoke execute on function "better_supabase"."get_form_submission"(uuid) from public, anon;
grant execute on function "better_supabase"."get_form_submission"(uuid) to authenticated, service_role;
-- Newest first. Reviewers see every submission; others see their own.
-- Archived submissions stay out unless include_archived is true.
create or replace function "better_supabase"."list_form_submissions"(form_id uuid, status text default null, page_size integer default 50, before timestamptz default null, include_archived boolean default false)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_tenant uuid;
v_all boolean;
v_rows jsonb;
begin
select x."tenant_id" into v_tenant from "better_supabase"."forms" x where x."id" = list_form_submissions.form_id;
if not found then
raise exception 'form not found' using errcode = 'P0002', hint = 'FORM_NOT_FOUND';
end if;
v_all := coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_tenant, 'forms.review'), false);
select coalesce(jsonb_agg(jsonb_build_object('id', r."id", 'organizationId', r."tenant_id", 'formId', r."form_id", 'versionId', r."version_id", 'subjectType', r."subject_type", 'subjectId', r."subject_id", 'respondentId', r."respondent_id", 'answers', r."answers", 'status', r."status", 'source', r."source", 'reviewedBy', r."reviewed_by", 'reviewedAt', r."reviewed_at", 'archivedAt', r."archived_at", 'createdAt', r."created_at", 'submittedAt', r."submitted_at", 'updatedAt', r."updated_at", 'score', r."score", 'maxScore', r."max_score", 'passed', r."passed") order by r."created_at" desc), '[]'::jsonb) into v_rows
from (
select * from "better_supabase"."form_submissions" x
where x."form_id" = list_form_submissions.form_id
and (v_all or x."respondent_id" = auth.uid())
and (list_form_submissions.status is null or x."status"::text = list_form_submissions.status)
and (list_form_submissions.before is null or x."created_at" < list_form_submissions.before)
and (coalesce(list_form_submissions.include_archived, false) or x."archived_at" is null)
order by x."created_at" desc
limit least(greatest(coalesce(list_form_submissions.page_size, 50), 1), 200)
) r;
return v_rows;
end;
$$;
revoke execute on function "better_supabase"."list_form_submissions"(uuid, text, integer, timestamptz, boolean) from public, anon;
grant execute on function "better_supabase"."list_form_submissions"(uuid, text, integer, timestamptz, boolean) to authenticated, service_role;
-- The Net Promoter Score of an nps field (the current version's first one by
-- default) over the submitted and accepted answers between since and until,
-- with a row per day, week, month, quarter or year (UTC) when bucket is set.
create or replace function "better_supabase"."form_nps"(form_id uuid, field text default null, since timestamptz default null, until timestamptz default null, bucket text default null)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
v_form "better_supabase"."forms"%rowtype;
v_field text := form_nps.field;
v_total jsonb;
v_periods jsonb;
begin
select * into v_form from "better_supabase"."forms" x where x."id" = form_nps.form_id;
if not found then
raise exception 'form not found' using errcode = 'P0002', hint = 'FORM_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_form."tenant_id", 'forms.review'), false)) then
raise exception 'not allowed to read this form''s results' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
if form_nps.bucket is not null and form_nps.bucket not in ('day', 'week', 'month', 'quarter', 'year') then
raise exception 'bucket is day, week, month, quarter, year' using errcode = '22023', hint = 'FORM_NPS_BUCKET_INVALID';
end if;
if v_field is null then
select q.field ->> 'key' into v_field
from "better_supabase"."form_versions" x
cross join lateral jsonb_array_elements(x."definition" -> 'steps') with ordinality as p(step, step_ord)
cross join lateral jsonb_array_elements(p.step -> 'fields') with ordinality as q(field, field_ord)
where x."id" = v_form."current_version_id" and q.field ->> 'type' = 'nps'
order by p.step_ord, q.field_ord
limit 1;
if v_field is null then
raise exception 'the form has no nps field' using errcode = '22023', hint = 'FORM_NPS_FIELD_MISSING';
end if;
end if;
with answered as (
select r.answer, r.answered_at from (
select case when jsonb_typeof(x."answers" -> v_field) = 'number' then (x."answers" ->> v_field)::numeric end as answer,
x."submitted_at" as answered_at
from "better_supabase"."form_submissions" x
where x."form_id" = form_nps.form_id
and x."status" in ('submitted', 'accepted')
and x."archived_at" is null
and (form_nps.since is null or x."submitted_at" >= form_nps.since)
and (form_nps.until is null or x."submitted_at" < form_nps.until)
) r
where r.answer between 0 and 10
)
select jsonb_build_object('responses', count(*), 'promoters', count(*) filter (where a.answer >= 9), 'passives', count(*) filter (where a.answer >= 7 and a.answer < 9), 'detractors', count(*) filter (where a.answer < 7), 'score', case when count(*) = 0 then null else round((count(*) filter (where a.answer >= 9) - count(*) filter (where a.answer < 7)) * 100.0 / count(*), 1) end),
case when form_nps.bucket is null then '[]'::jsonb else coalesce((
select jsonb_agg(jsonb_build_object('start', g.start) || g.counts order by g.start)
from (
select date_trunc(form_nps.bucket, b.answered_at, 'UTC') as start, jsonb_build_object('responses', count(*), 'promoters', count(*) filter (where b.answer >= 9), 'passives', count(*) filter (where b.answer >= 7 and b.answer < 9), 'detractors', count(*) filter (where b.answer < 7), 'score', case when count(*) = 0 then null else round((count(*) filter (where b.answer >= 9) - count(*) filter (where b.answer < 7)) * 100.0 / count(*), 1) end) as counts
from answered b
group by 1
) g), '[]'::jsonb) end
into v_total, v_periods
from answered a;
return jsonb_build_object('field', v_field) || v_total || jsonb_build_object('periods', v_periods);
end;
$$;
revoke execute on function "better_supabase"."form_nps"(uuid, text, timestamptz, timestamptz, text) from public, anon;
grant execute on function "better_supabase"."form_nps"(uuid, text, timestamptz, timestamptz, text) to authenticated, service_role;
create or replace function "better_supabase"."review_form_submission"(submission_id uuid, status text)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."form_submissions"%rowtype;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."form_submissions" x where x."id" = review_form_submission.submission_id for update;
if not found then
raise exception 'submission not found' using errcode = 'P0002', hint = 'FORM_SUBMISSION_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'forms.review'), false)) then
raise exception 'not allowed to review submissions' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
if review_form_submission.status is null or review_form_submission.status not in ('submitted', 'accepted', 'rejected') then
raise exception 'status is submitted, accepted or rejected' using errcode = '22023', hint = 'FORM_STATUS_INVALID';
end if;
if v_row."status" = 'draft' then
raise exception 'a draft isn''t submitted yet' using errcode = '55000', hint = 'FORM_SUBMISSION_DRAFT';
end if;
update "better_supabase"."form_submissions" x set
"status" = review_form_submission.status,
"reviewed_by" = auth.uid(),
"reviewed_at" = now(),
"updated_at" = now()
where x."id" = review_form_submission.submission_id
returning * into v_row;
null;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'formId', v_row."form_id", 'versionId', v_row."version_id", 'subjectType', v_row."subject_type", 'subjectId', v_row."subject_id", 'respondentId', v_row."respondent_id", 'answers', v_row."answers", 'status', v_row."status", 'source', v_row."source", 'reviewedBy', v_row."reviewed_by", 'reviewedAt', v_row."reviewed_at", 'archivedAt', v_row."archived_at", 'createdAt', v_row."created_at", 'submittedAt', v_row."submitted_at", 'updatedAt', v_row."updated_at", 'score', v_row."score", 'maxScore', v_row."max_score", 'passed', v_row."passed");
end;
$$;
revoke execute on function "better_supabase"."review_form_submission"(uuid, text) from public, anon;
grant execute on function "better_supabase"."review_form_submission"(uuid, text) to authenticated, service_role;
-- Archives a submission: it leaves list_form_submissions and form_nps and keeps its answers, score and review.
create or replace function "better_supabase"."archive_form_submission"(submission_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."form_submissions"%rowtype;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."form_submissions" x where x."id" = archive_form_submission.submission_id for update;
if not found then
raise exception 'submission not found' using errcode = 'P0002', hint = 'FORM_SUBMISSION_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'forms.review'), false)) then
raise exception 'not allowed to archive submissions' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
if v_row."archived_at" is not null then
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'formId', v_row."form_id", 'versionId', v_row."version_id", 'subjectType', v_row."subject_type", 'subjectId', v_row."subject_id", 'respondentId', v_row."respondent_id", 'answers', v_row."answers", 'status', v_row."status", 'source', v_row."source", 'reviewedBy', v_row."reviewed_by", 'reviewedAt', v_row."reviewed_at", 'archivedAt', v_row."archived_at", 'createdAt', v_row."created_at", 'submittedAt', v_row."submitted_at", 'updatedAt', v_row."updated_at", 'score', v_row."score", 'maxScore', v_row."max_score", 'passed', v_row."passed");
end if;
if v_row."status" = 'draft' then
raise exception 'a draft isn''t submitted yet' using errcode = '55000', hint = 'FORM_SUBMISSION_DRAFT';
end if;
update "better_supabase"."form_submissions" x set
"archived_at" = now(),
"updated_at" = now()
where x."id" = v_row."id"
returning * into v_row;
null;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'formId', v_row."form_id", 'versionId', v_row."version_id", 'subjectType', v_row."subject_type", 'subjectId', v_row."subject_id", 'respondentId', v_row."respondent_id", 'answers', v_row."answers", 'status', v_row."status", 'source', v_row."source", 'reviewedBy', v_row."reviewed_by", 'reviewedAt', v_row."reviewed_at", 'archivedAt', v_row."archived_at", 'createdAt', v_row."created_at", 'submittedAt', v_row."submitted_at", 'updatedAt', v_row."updated_at", 'score', v_row."score", 'maxScore', v_row."max_score", 'passed', v_row."passed");
end;
$$;
revoke execute on function "better_supabase"."archive_form_submission"(uuid) from public, anon;
grant execute on function "better_supabase"."archive_form_submission"(uuid) to authenticated, service_role;
-- Restores an archived submission to the lists.
create or replace function "better_supabase"."restore_form_submission"(submission_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."form_submissions"%rowtype;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."form_submissions" x where x."id" = restore_form_submission.submission_id for update;
if not found then
raise exception 'submission not found' using errcode = 'P0002', hint = 'FORM_SUBMISSION_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'forms.review'), false)) then
raise exception 'not allowed to restore submissions' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
if v_row."archived_at" is null then
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'formId', v_row."form_id", 'versionId', v_row."version_id", 'subjectType', v_row."subject_type", 'subjectId', v_row."subject_id", 'respondentId', v_row."respondent_id", 'answers', v_row."answers", 'status', v_row."status", 'source', v_row."source", 'reviewedBy', v_row."reviewed_by", 'reviewedAt', v_row."reviewed_at", 'archivedAt', v_row."archived_at", 'createdAt', v_row."created_at", 'submittedAt', v_row."submitted_at", 'updatedAt', v_row."updated_at", 'score', v_row."score", 'maxScore', v_row."max_score", 'passed', v_row."passed");
end if;
update "better_supabase"."form_submissions" x set
"archived_at" = null,
"updated_at" = now()
where x."id" = v_row."id"
returning * into v_row;
null;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'formId', v_row."form_id", 'versionId', v_row."version_id", 'subjectType', v_row."subject_type", 'subjectId', v_row."subject_id", 'respondentId', v_row."respondent_id", 'answers', v_row."answers", 'status', v_row."status", 'source', v_row."source", 'reviewedBy', v_row."reviewed_by", 'reviewedAt', v_row."reviewed_at", 'archivedAt', v_row."archived_at", 'createdAt', v_row."created_at", 'submittedAt', v_row."submitted_at", 'updatedAt', v_row."updated_at", 'score', v_row."score", 'maxScore', v_row."max_score", 'passed', v_row."passed");
end;
$$;
revoke execute on function "better_supabase"."restore_form_submission"(uuid) from public, anon;
grant execute on function "better_supabase"."restore_form_submission"(uuid) to authenticated, service_role;
-- Removes a submission for good: a reviewer (or the key set as
-- permissions.purge) any submission, a respondent their own draft. Archive
-- keeps the row.
create or replace function "better_supabase"."purge_form_submission"(submission_id uuid)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."form_submissions"%rowtype;
begin
if not (better_supabase.actor_may_write()) then
raise exception 'This session is read-only' using errcode = '42501', hint = 'ACTOR_READ_ONLY';
end if;
select * into v_row from "better_supabase"."form_submissions" x where x."id" = purge_form_submission.submission_id for update;
if not found then
raise exception 'submission not found' using errcode = 'P0002', hint = 'FORM_SUBMISSION_NOT_FOUND';
end if;
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'forms.review'), false)
or (coalesce(v_row."respondent_id" = auth.uid(), false) and v_row."status" = 'draft')) then
raise exception 'not allowed to purge this submission' using errcode = '42501', hint = 'FORM_FORBIDDEN';
end if;
delete from "better_supabase"."form_submissions" x where x."id" = purge_form_submission.submission_id;
null;
return true;
end;
$$;
revoke execute on function "better_supabase"."purge_form_submission"(uuid) from public, anon;
grant execute on function "better_supabase"."purge_form_submission"(uuid) to authenticated, service_role;
-- Tenant isolation (ADR 0099): permissive policies combine with or, so one
-- the app adds would widen the block's. These restrictive policies keep each
-- table to the caller's organizations and what the block's policies grant.
create policy bsb_tenant_scope_select on "better_supabase"."forms" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('forms.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."forms" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."forms" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."forms" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."form_versions" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('forms.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."form_versions" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."form_versions" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."form_versions" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_select on "better_supabase"."form_submissions" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("tenant_id" in (select better_supabase.tenant_ids_with('forms.review')) or "respondent_id" = (select auth.uid()))
);
create policy bsb_tenant_scope_insert on "better_supabase"."form_submissions" as restrictive
for insert to public
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_update on "better_supabase"."form_submissions" as restrictive
for update to public
using ("tenant_id" in (select better_supabase.member_organization_ids()))
with check ("tenant_id" in (select better_supabase.member_organization_ids()));
create policy bsb_tenant_scope_delete on "better_supabase"."form_submissions" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
Client
The React hooks are the registry item @better-supabase/use-forms, which shadcn copies into your app. They return data and actions and render no UI, so you build the interface from your own components.
Events
With the outbox installed, the module writes these in the same transaction as the change.
- form.created
- form_submission.archived
- form_submission.purged
- form_submission.restored
- form_submission.reviewed
- form_submission.submitted
- form_version.published
Dependencies
- Required: the install command adds it too
- Works with: optional
Recipes
More in Content & files
Collaborative documentsdocuments Yjs documents attached to any subject: an update log, a compacted snapshot, a private realtime topic per document for updates and presence, suggestions that editors accept into the log, and named versions through the versions module. Drivedrive Folders and files on the attachments module: access granted to users, teams or roles and inherited down the tree, enforced by storage policies too; moves and renames with a name-conflict policy; revisions through versions, a bin through trash, starred and recent items through share-links' user state, and folder share links. Drive filesdrive-files The part of the drive module that needs attachments, versions, trash and share-links: file uploads and revisions with an optional usage quota, extracted text, storage policies, the bin, starred and recent items, folder share links and the purge event. Installed with drive. Signaturessignatures Simple electronic signatures on a frozen version of a record: drawn, typed or click signatures in parallel or in order, a hash that detects edits after signing, and an approval step a signer can decide. Templatestemplates Typed, versioned templates (system starters and tenant forks) that create records, with merge fields and workflows started on each record they create. Coursescourses Courses of modules and lessons ordered by rank keys, with quiz lessons graded by forms, per-lesson progress, completion and certificates. Each course runs as an enrollment program, so learners enroll through enrollments.