Leave
leaveLeave types, requests that go through approvals, and a balance ledger per member and year with accruals, adjustments and a year-end carryover. With employees, requests carry the employee_id of their member, or belong to an employee with owner "employee". Balances can live in the app's own table of signed amounts instead of the ledger.
Peoplemanagedcustom
To do
Doing
Done
Install
The command also installs updated-at, memberships, permissions, approvals, ledger, housekeeping, the modules it needs.
npx better-supabase add leaveConfigure
The blocks entries in your config, with the default mode.
import { defineConfig } from "better-supabase/config";
export default defineConfig({
blocks: {
// Required by leave; add installs them too.
"updated-at": {},
memberships: {},
permissions: {},
approvals: {},
ledger: {},
housekeeping: {},
// Modes: "managed", "custom". The default is "managed".
leave: { mode: "managed" },
},
});Migrations
The files
npx better-supabase add leave writes into your declarative schema with the default layout.16 files
supabase/schemas/900_better_supabase_110_leave.sqlschema1421 lines-- better-supabase module: leave
-- @bsb-block leave@3 managed
-- @bsb-hash sha256:cf0b19d2e8ad5636df6fd3f084a9391a20a9887fc4570585a428390cdc534417
-- Leave types, requests that go through approvals, and a balance ledger per member and year with accruals, adjustments and a year-end carryover. With employees, requests carry the employee_id of their member, or belong to an employee with owner "employee". Balances can live in the app's own table of signed amounts instead of the ledger.
-- 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"."leave_types" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"key" text not null constraint bsb_leave_types_key_check check ("key" ~ '^[a-z][a-z0-9_-]{0,62}$'),
"name" text not null constraint bsb_leave_types_name_check check (length("name") >= 1 and length("name") <= 100),
"unit" text not null default 'days' constraint bsb_leave_types_unit_check check ("unit" in ('days', 'hours')),
"paid" boolean not null default true,
-- Untracked types (unpaid leave, say) book no ledger entries and skip the balance check.
"tracked" boolean not null default true,
-- What accrue_leave grants each member per period when it names no amount.
"allowance" numeric(8, 2) constraint bsb_leave_types_allowance_check check ("allowance" is null or "allowance" >= 0),
-- How much close_leave_year carries into the next period; null carries everything.
"carryover_max" numeric(8, 2) constraint bsb_leave_types_carryover_max_check check ("carryover_max" is null or "carryover_max" >= 0),
"color" text constraint bsb_leave_types_color_check check ("color" is null or "color" ~ '^#[0-9a-fA-F]{6}$'),
"auto_approve" boolean not null default false,
"archived_at" timestamptz,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
unique ("tenant_id", "key"),
unique ("tenant_id", "id")
);
alter table "better_supabase"."leave_types" enable row level security;
revoke all on "better_supabase"."leave_types" from public, anon, authenticated;
grant select on "better_supabase"."leave_types" to authenticated;
grant all on "better_supabase"."leave_types" to service_role;
create policy bsb_leave_types_read on "better_supabase"."leave_types"
for select to authenticated
using ("tenant_id" in (select better_supabase.tenant_ids_with('leave.request')) or "tenant_id" in (select better_supabase.tenant_ids_with('leave.read')));
create table "better_supabase"."leave_requests" (
"id" uuid primary key default gen_random_uuid(),
"tenant_id" uuid not null,
"user_id" uuid not null,
"type_id" uuid not null,
"starts_on" date not null,
"ends_on" date not null,
"partial" text not null default 'full' constraint bsb_leave_requests_partial_check check ("partial" in ('full', 'morning', 'afternoon', 'hours')),
-- Working days, or hours for an hours type, that the request books.
"amount" numeric(8, 2) not null constraint bsb_leave_requests_amount_check check ("amount" > 0),
"note" text constraint bsb_leave_requests_note_check check ("note" is null or length("note") <= 2000),
"approval_id" uuid references "better_supabase"."approval_requests" ("id") on delete set null,
"approved_at" timestamptz,
"rejected_at" timestamptz,
"decided_by" uuid,
"decision_note" text constraint bsb_leave_requests_decision_note_check check ("decision_note" is null or length("decision_note") <= 2000),
"cancelled_at" timestamptz,
"cancelled_by" uuid,
"created_at" timestamptz not null default now(),
"updated_at" timestamptz not null default now(),
constraint bsb_leave_requests_check check ("ends_on" >= "starts_on"),
foreign key ("tenant_id", "type_id") references "better_supabase"."leave_types" ("tenant_id", "id") on delete restrict
);
create index "leave_requests_user_idx" on "better_supabase"."leave_requests" ("tenant_id", "user_id", "starts_on" desc);
create index "leave_requests_dates_idx" on "better_supabase"."leave_requests" ("tenant_id", "starts_on", "ends_on");
create index "leave_requests_approval_idx" on "better_supabase"."leave_requests" ("approval_id") where "approval_id" is not null;
create index "leave_requests_type_idx" on "better_supabase"."leave_requests" ("tenant_id", "type_id");
alter table "better_supabase"."leave_requests" enable row level security;
revoke all on "better_supabase"."leave_requests" from public, anon, authenticated;
grant select on "better_supabase"."leave_requests" to authenticated;
grant all on "better_supabase"."leave_requests" to service_role;
create policy bsb_leave_requests_read on "better_supabase"."leave_requests"
for select to authenticated
using ("user_id" = (select auth.uid()) or "tenant_id" in (select better_supabase.tenant_ids_with('leave.read')));
-- Posts one leave movement to a member's account of a type and period:
-- against the type's taken account for taken leave, the member's account
-- of to_period for a carryover, else the type's pool. Returns the ledger
-- transaction; with a key a second post returns the first.
create or replace function "better_supabase"."leave_post"(tenant uuid, user_id uuid, type_id uuid, kind text, amount numeric, period integer, request_id uuid default null, note text default null, key text default null, to_period integer default null)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_unit text;
v_account uuid;
v_counter uuid;
v_amount bigint := round(leave_post.amount * 100);
begin
select t."unit" into v_unit from "better_supabase"."leave_types" t where t."id" = leave_post.type_id;
v_account := "better_supabase"."ledger_account_for"(leave_post.tenant, 'leave', 'leave:' || leave_post.type_id::text || ':' || leave_post.user_id::text || ':' || leave_post.period::text, 'Leave', v_unit, 2::smallint,
'leave-types', leave_post.type_id::text, leave_post.user_id, true, 'leave.read', 'leave',
jsonb_build_object('userId', leave_post.user_id, 'typeId', leave_post.type_id, 'period', leave_post.period));
v_counter := case
when leave_post.to_period is not null then
"better_supabase"."ledger_account_for"(leave_post.tenant, 'leave', 'leave:' || leave_post.type_id::text || ':' || leave_post.user_id::text || ':' || leave_post.to_period::text, 'Leave', v_unit, 2::smallint,
'leave-types', leave_post.type_id::text, leave_post.user_id, true, 'leave.read', 'leave',
jsonb_build_object('userId', leave_post.user_id, 'typeId', leave_post.type_id, 'period', leave_post.to_period))
else "better_supabase"."ledger_account_for"(leave_post.tenant, 'leave_pool',
'leave:' || leave_post.type_id::text || case when leave_post.kind = 'taken' then ':taken' else ':pool' end,
case when leave_post.kind = 'taken' then 'Leave taken' else 'Leave pool' end, v_unit, 2::smallint,
'leave-types', leave_post.type_id::text, null, true, 'leave.read', 'leave', null)
end;
return "better_supabase"."ledger_post"(leave_post.tenant, 'leave.' || leave_post.kind,
jsonb_build_array(
jsonb_build_object('account', v_account, 'amount', v_amount),
jsonb_build_object('account', v_counter, 'amount', -v_amount)),
case when leave_post.request_id is not null then 'leave-requests' end, leave_post.request_id::text,
nullif(trim(leave_post.note), ''),
case when leave_post.key is not null then 'leave:' || leave_post.user_id::text || ':' || leave_post.type_id::text || ':' || leave_post.key end,
null,
jsonb_build_object('userId', leave_post.user_id, 'typeId', leave_post.type_id, 'period', leave_post.period, 'kind', leave_post.kind));
end;
$$;
revoke execute on function "better_supabase"."leave_post"(uuid, uuid, uuid, text, numeric, integer, uuid, text, text, integer) from public, anon, authenticated;
-- Whether a member already has the leave movement with this key.
create or replace function "better_supabase"."leave_posted"(tenant uuid, user_id uuid, type_id uuid, key text)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (select 1 from "better_supabase"."ledger_transactions" r where r."tenant_id" = leave_posted.tenant
and r."idempotency_key" = 'leave:' || leave_posted.user_id::text || ':' || leave_posted.type_id::text || ':' || leave_posted.key)
$$;
revoke execute on function "better_supabase"."leave_posted"(uuid, uuid, uuid, text) from public, anon, authenticated;
-- A member's balance of one type for one period: the account's balance,
-- minus the requests still waiting for approval.
create or replace function "better_supabase"."leave_available"(tenant uuid, user_id uuid, type_id uuid, period integer)
returns numeric
language sql
stable
security definer
set search_path = ''
as $$
select coalesce((select b."balance"::numeric / 100 from "better_supabase"."ledger_accounts" x join "better_supabase"."ledger_balances" b on b."account_id" = x."id"
where x."tenant_id" = leave_available.tenant and x."code" = 'leave:' || leave_available.type_id::text || ':' || leave_available.user_id::text || ':' || leave_available.period::text), 0)
- coalesce((select sum(r."amount") from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id"
where r."tenant_id" = leave_available.tenant and r."user_id" = leave_available.user_id
and r."type_id" = leave_available.type_id and extract(year from r."starts_on")::integer = leave_available.period
and r."cancelled_at" is null and r."approved_at" is null and p."status" = 'pending'), 0)
$$;
revoke execute on function "better_supabase"."leave_available"(uuid, uuid, uuid, integer) from public, anon, authenticated;
-- A member's balance of each tracked type for one period (default this
-- year): granted, taken, pending and available.
create or replace function "better_supabase"."leave_balances"(tenant uuid, user_id uuid default null, period integer default null)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_user uuid := coalesce(leave_balances.user_id, auth.uid());
v_period integer := coalesce(leave_balances.period, extract(year from current_date)::integer);
v_rows 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', leave_balances.tenant, 'leave.read'), false)
or (coalesce(v_user = auth.uid(), false) and coalesce(better_supabase.can('tenant', leave_balances.tenant, 'leave.request'), false))) then
raise exception 'not allowed to read this member''s leave balance' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
if v_user is null then
raise exception 'name user_id' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
select coalesce(jsonb_agg(jsonb_build_object(
'typeId', t."id", 'key', t."key", 'name', t."name", 'unit', t."unit",
'userId', v_user, 'period', v_period,
'granted', (coalesce(b.granted, 0)::numeric / 100)::numeric(10, 2)::text,
'taken', (coalesce(b.taken, 0)::numeric / 100)::numeric(10, 2)::text,
'pending', w.pending::numeric(10, 2)::text,
'available', (coalesce(b.total, 0)::numeric / 100 - w.pending)::numeric(10, 2)::text
) order by t."name"), '[]'::jsonb) into v_rows
from "better_supabase"."leave_types" t
left join lateral (
select sum(y."amount") filter (where r."kind" <> 'leave.taken') as granted,
-sum(y."amount") filter (where r."kind" = 'leave.taken') as taken,
sum(y."amount") as total
from "better_supabase"."ledger_entries" y
join "better_supabase"."ledger_accounts" x on x."id" = y."account_id" and x."managed_by" = 'leave' and x."kind" = 'leave'
join "better_supabase"."ledger_transactions" r on r."id" = y."transaction_id"
where x."tenant_id" = leave_balances.tenant and x."code" = 'leave:' || t."id"::text || ':' || v_user::text || ':' || v_period::text
) b on true
cross join lateral (
select coalesce((select sum(r."amount") from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id"
where r."tenant_id" = leave_balances.tenant and r."user_id" = v_user
and r."type_id" = t."id" and extract(year from r."starts_on")::integer = v_period
and r."cancelled_at" is null and r."approved_at" is null and p."status" = 'pending'), 0) as pending
) w
where t."tenant_id" = leave_balances.tenant and t."tracked" and t."archived_at" is null;
return v_rows;
end;
$$;
revoke execute on function "better_supabase"."leave_balances"(uuid, uuid, integer) from public, anon;
grant execute on function "better_supabase"."leave_balances"(uuid, uuid, integer) to authenticated, service_role;
-- A member's ledger entries of one period, newest first.
create or replace function "better_supabase"."leave_ledger_entries"(tenant uuid, user_id uuid default null, period integer default null, type_id uuid default null)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_user uuid := coalesce(leave_ledger_entries.user_id, auth.uid());
v_rows 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', leave_ledger_entries.tenant, 'leave.read'), false)
or (coalesce(v_user = auth.uid(), false) and coalesce(better_supabase.can('tenant', leave_ledger_entries.tenant, 'leave.request'), false))) then
raise exception 'not allowed to read this member''s leave balance' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
select coalesce(jsonb_agg(jsonb_build_object('id', y."id", 'organizationId', x."tenant_id", 'userId', x."owner_id",
'typeId', (x."metadata" ->> 'typeId')::uuid, 'kind', substr(r."kind", 7), 'amount', (y."amount"::numeric / 100)::numeric(10, 2)::text,
'period', (x."metadata" ->> 'period')::integer,
'requestId', case when r."reference_type" = 'leave-requests' then r."reference_id"::uuid end,
'note', r."memo", 'createdAt', y."created_at") order by y."created_at" desc, y."id" desc), '[]'::jsonb) into v_rows
from "better_supabase"."ledger_entries" y
join "better_supabase"."ledger_accounts" x on x."id" = y."account_id" and x."managed_by" = 'leave' and x."kind" = 'leave'
join "better_supabase"."ledger_transactions" r on r."id" = y."transaction_id"
where x."tenant_id" = leave_ledger_entries.tenant and x."owner_id" = v_user
and (leave_ledger_entries.period is null or (x."metadata" ->> 'period')::integer = leave_ledger_entries.period)
and (leave_ledger_entries.type_id is null or x."holder_id" = leave_ledger_entries.type_id::text);
return v_rows;
end;
$$;
revoke execute on function "better_supabase"."leave_ledger_entries"(uuid, uuid, integer, uuid) from public, anon;
grant execute on function "better_supabase"."leave_ledger_entries"(uuid, uuid, integer, uuid) to authenticated, service_role;
-- Adds a grant or a manual adjustment (signed) to a member's balance.
create or replace function "better_supabase"."adjust_leave_balance"(tenant uuid, user_id uuid, type_id uuid, amount numeric, period integer default null, kind text default 'adjustment', note text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_period integer := coalesce(adjust_leave_balance.period, extract(year from current_date)::integer);
v_transaction uuid;
v_entry uuid;
v_row 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', adjust_leave_balance.tenant, 'leave.manage'), false)) then
raise exception 'not allowed to adjust leave balances' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
if coalesce(adjust_leave_balance.kind, 'adjustment') not in ('grant', 'adjustment') then
raise exception 'kind must be grant or adjustment' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if adjust_leave_balance.amount is null or adjust_leave_balance.amount = 0 then
raise exception 'amount must not be zero' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if not exists (select 1 from "better_supabase"."memberships" m where m."organization_id" = adjust_leave_balance.tenant and m."user_id" = adjust_leave_balance.user_id) then
raise exception 'the user is not a member of this organization' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if not exists (select 1 from "better_supabase"."leave_types" t where t."id" = adjust_leave_balance.type_id and t."tenant_id" = adjust_leave_balance.tenant) then
raise exception 'leave type not found' using errcode = 'P0002', hint = 'LEAVE_TYPE_NOT_FOUND';
end if;
v_transaction := "better_supabase"."leave_post"(adjust_leave_balance.tenant, adjust_leave_balance.user_id, adjust_leave_balance.type_id,
coalesce(adjust_leave_balance.kind, 'adjustment'), adjust_leave_balance.amount, v_period, null, adjust_leave_balance.note);
select y."id", jsonb_build_object('id', y."id", 'organizationId', x."tenant_id", 'userId', x."owner_id",
'typeId', (x."metadata" ->> 'typeId')::uuid, 'kind', substr(r."kind", 7), 'amount', (y."amount"::numeric / 100)::numeric(10, 2)::text,
'period', (x."metadata" ->> 'period')::integer,
'requestId', case when r."reference_type" = 'leave-requests' then r."reference_id"::uuid end,
'note', r."memo", 'createdAt', y."created_at") into v_entry, v_row
from "better_supabase"."ledger_entries" y
join "better_supabase"."ledger_accounts" x on x."id" = y."account_id" and x."managed_by" = 'leave' and x."kind" = 'leave'
join "better_supabase"."ledger_transactions" r on r."id" = y."transaction_id"
where y."transaction_id" = v_transaction and x."owner_id" = adjust_leave_balance.user_id;
null;
return v_row;
end;
$$;
revoke execute on function "better_supabase"."adjust_leave_balance"(uuid, uuid, uuid, numeric, integer, text, text) from public, anon;
grant execute on function "better_supabase"."adjust_leave_balance"(uuid, uuid, uuid, numeric, integer, text, text) to authenticated, service_role;
-- Grants every member (or user_ids) an accrual of one type: amount, or the
-- type's allowance. With idempotency_key a member gets it once, so a
-- scheduled job can run it again safely. Returns how many entries it wrote.
create or replace function "better_supabase"."accrue_leave"(tenant uuid, type_id uuid, amount numeric default null, period integer default null, user_ids uuid[] default null, idempotency_key text default null, note text default null)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_type "better_supabase"."leave_types"%rowtype;
v_amount numeric;
v_user uuid;
v_count integer := 0;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', accrue_leave.tenant, 'leave.manage'), false)) then
raise exception 'not allowed to accrue leave' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
select * into v_type from "better_supabase"."leave_types" t where t."id" = accrue_leave.type_id and t."tenant_id" = accrue_leave.tenant;
if not found then
raise exception 'leave type not found' using errcode = 'P0002', hint = 'LEAVE_TYPE_NOT_FOUND';
end if;
v_amount := coalesce(accrue_leave.amount, v_type."allowance");
if v_amount is null or v_amount <= 0 then
raise exception 'name an amount, or give the type an allowance' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
for v_user in
select m."user_id" from "better_supabase"."memberships" m
where m."organization_id" = accrue_leave.tenant
and (accrue_leave.user_ids is null or m."user_id" = any (accrue_leave.user_ids))
loop
continue when accrue_leave.idempotency_key is not null
and "better_supabase"."leave_posted"(accrue_leave.tenant, v_user, v_type."id", accrue_leave.idempotency_key);
perform "better_supabase"."leave_post"(accrue_leave.tenant, v_user, v_type."id", 'accrual', v_amount,
coalesce(accrue_leave.period, extract(year from current_date)::integer), null, accrue_leave.note, accrue_leave.idempotency_key);
v_count := v_count + 1;
end loop;
return v_count;
end;
$$;
revoke execute on function "better_supabase"."accrue_leave"(uuid, uuid, numeric, integer, uuid[], text, text) from public, anon;
grant execute on function "better_supabase"."accrue_leave"(uuid, uuid, numeric, integer, uuid[], text, text) to authenticated, service_role;
-- Closes a period: each member's positive balance of each tracked type
-- carries into the next period up to the type's carryover_max, and the rest
-- expires. Run once per period; a second run writes nothing. Returns how
-- many entries on members' accounts it wrote.
create or replace function "better_supabase"."close_leave_year"(tenant uuid, period integer)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_key text := 'close:' || close_leave_year.period::text;
v_row record;
v_written integer := 0;
begin
if not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', close_leave_year.tenant, 'leave.manage'), false)) then
raise exception 'not allowed to close leave periods' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
if close_leave_year.period is null then
raise exception 'name the period to close' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
for v_row in
select x."owner_id" as user_id, t."id" as type_id, b."balance"::numeric / 100 as balance,
least(b."balance"::numeric / 100, coalesce(t."carryover_max", b."balance"::numeric / 100)) as carry
from "better_supabase"."ledger_accounts" x
join "better_supabase"."ledger_balances" b on b."account_id" = x."id"
join "better_supabase"."leave_types" t on t."id" = better_supabase.try_column_type(x."holder_id", (null::"better_supabase"."leave_types")."id") and t."tracked"
where x."tenant_id" = close_leave_year.tenant and x."managed_by" = 'leave' and x."kind" = 'leave'
and (x."metadata" ->> 'period')::integer = close_leave_year.period and b."balance" > 0
loop
if v_row.carry <> 0 and not "better_supabase"."leave_posted"(close_leave_year.tenant, v_row.user_id, v_row.type_id, v_key || ':carryover:' || close_leave_year.period::text) then
perform "better_supabase"."leave_post"(close_leave_year.tenant, v_row.user_id, v_row.type_id, 'carryover', -v_row.carry, close_leave_year.period,
null, null, v_key || ':carryover:' || close_leave_year.period::text, close_leave_year.period + 1);
v_written := v_written + 2;
end if;
if v_row.balance - v_row.carry <> 0 and not "better_supabase"."leave_posted"(close_leave_year.tenant, v_row.user_id, v_row.type_id, v_key || ':expiry:' || close_leave_year.period::text) then
perform "better_supabase"."leave_post"(close_leave_year.tenant, v_row.user_id, v_row.type_id, 'expiry', -(v_row.balance - v_row.carry), close_leave_year.period,
null, null, v_key || ':expiry:' || close_leave_year.period::text);
v_written := v_written + 1;
end if;
end loop;
return v_written;
end;
$$;
revoke execute on function "better_supabase"."close_leave_year"(uuid, integer) from public, anon;
grant execute on function "better_supabase"."close_leave_year"(uuid, integer) to authenticated, service_role;
-- The working days (options.workingDays) from one date to another, inclusive.
create or replace function "better_supabase"."leave_working_days"(starts_on date, ends_on date)
returns integer
language sql
immutable
set search_path = ''
as $$
select count(*)::integer
from generate_series(leave_working_days.starts_on, leave_working_days.ends_on, interval '1 day') d
where extract(isodow from d)::integer = any (array[1, 2, 3, 4, 5])
$$;
revoke execute on function "better_supabase"."leave_working_days"(date, date) from public, anon;
grant execute on function "better_supabase"."leave_working_days"(date, date) to authenticated, service_role;
-- Creates or updates a leave type by key. Without a key column, key is the
-- id of the type to update, and any other key creates one. auto_approve:
-- its requests need no approval.
create or replace function "better_supabase"."upsert_leave_type"(tenant uuid, key text, name text, unit text default 'days', paid boolean default true, tracked boolean default true, allowance numeric default null, carryover_max numeric default null, color text default null, auto_approve boolean default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row "better_supabase"."leave_types"%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', upsert_leave_type.tenant, 'leave.manage'), false)) then
raise exception 'not allowed to manage leave types' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
insert into "better_supabase"."leave_types" ("tenant_id", "key", "name", "unit", "paid", "tracked", "allowance", "carryover_max", "color", "auto_approve")
values (upsert_leave_type.tenant, upsert_leave_type.key, upsert_leave_type.name, coalesce(upsert_leave_type.unit, 'days'), coalesce(upsert_leave_type.paid, true), coalesce(upsert_leave_type.tracked, true), upsert_leave_type.allowance, upsert_leave_type.carryover_max, upsert_leave_type.color, coalesce(upsert_leave_type.auto_approve, false))
on conflict ("tenant_id", "key") do update
set "name" = excluded."name", "unit" = excluded."unit", "paid" = excluded."paid",
"tracked" = excluded."tracked", "allowance" = excluded."allowance",
"carryover_max" = excluded."carryover_max", "color" = excluded."color", "auto_approve" = excluded."auto_approve",
"archived_at" = null, "updated_at" = now()
returning * into v_row;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'key', v_row."key", 'name', v_row."name", 'unit', v_row."unit", 'paid', v_row."paid", 'tracked', v_row."tracked", 'allowance', v_row."allowance"::text, 'carryoverMax', v_row."carryover_max"::text, 'color', v_row."color", 'autoApprove', v_row."auto_approve", 'archivedAt', v_row."archived_at", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."upsert_leave_type"(uuid, text, text, text, boolean, boolean, numeric, numeric, text, boolean) from public, anon;
grant execute on function "better_supabase"."upsert_leave_type"(uuid, text, text, text, boolean, boolean, numeric, numeric, text, boolean) to authenticated, service_role;
-- Hides a type from new requests; its requests and ledger stay.
create or replace function "better_supabase"."archive_leave_type"(type_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."leave_types"%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"."leave_types" x where x."id" = archive_leave_type.type_id for update;
if not found then
raise exception 'leave type not found' using errcode = 'P0002', hint = 'LEAVE_TYPE_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", 'leave.manage'), false)) then
raise exception 'not allowed to manage leave types' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
update "better_supabase"."leave_types" x set "archived_at" = coalesce(x."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", 'key', v_row."key", 'name', v_row."name", 'unit', v_row."unit", 'paid', v_row."paid", 'tracked', v_row."tracked", 'allowance', v_row."allowance"::text, 'carryoverMax', v_row."carryover_max"::text, 'color', v_row."color", 'autoApprove', v_row."auto_approve", 'archivedAt', v_row."archived_at", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."archive_leave_type"(uuid) from public, anon;
grant execute on function "better_supabase"."archive_leave_type"(uuid) to authenticated, service_role;
-- Makes an archived type available to new requests again.
create or replace function "better_supabase"."restore_leave_type"(type_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."leave_types"%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"."leave_types" x where x."id" = restore_leave_type.type_id for update;
if not found then
raise exception 'leave type not found' using errcode = 'P0002', hint = 'LEAVE_TYPE_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", 'leave.manage'), false)) then
raise exception 'not allowed to manage leave types' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
update "better_supabase"."leave_types" 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", 'key', v_row."key", 'name', v_row."name", 'unit', v_row."unit", 'paid', v_row."paid", 'tracked', v_row."tracked", 'allowance', v_row."allowance"::text, 'carryoverMax', v_row."carryover_max"::text, 'color', v_row."color", 'autoApprove', v_row."auto_approve", 'archivedAt', v_row."archived_at", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."restore_leave_type"(uuid) from public, anon;
grant execute on function "better_supabase"."restore_leave_type"(uuid) to authenticated, service_role;
create or replace function "better_supabase"."list_leave_types"(tenant uuid, archived boolean default false)
returns jsonb
language sql
stable
security invoker
set search_path = ''
as $$
select coalesce(jsonb_agg(jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'key', x."key", 'name', x."name", 'unit', x."unit", 'paid', x."paid", 'tracked', x."tracked", 'allowance', x."allowance"::text, 'carryoverMax', x."carryover_max"::text, 'color', x."color", 'autoApprove', x."auto_approve", 'archivedAt', x."archived_at", 'createdAt', x."created_at", 'updatedAt', x."updated_at") order by x."name"), '[]'::jsonb)
from "better_supabase"."leave_types" x
where x."tenant_id" = list_leave_types.tenant
and (coalesce(list_leave_types.archived, false) or x."archived_at" is null)
$$;
revoke execute on function "better_supabase"."list_leave_types"(uuid, boolean) from public, anon;
grant execute on function "better_supabase"."list_leave_types"(uuid, boolean) to authenticated, service_role;
-- Asks for leave and opens its approval. A day type books working days
-- (half a day for a morning or afternoon); an hours type books hours.
-- Without options.allowNegative the request can't exceed the balance of
-- the period it starts in. fields: the extra columns to set.
create or replace function "better_supabase"."request_leave"(tenant uuid, type_id uuid, starts_on date, ends_on date, partial text default 'full', hours numeric default null, note text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_me uuid := auth.uid();
v_type "better_supabase"."leave_types"%rowtype;
v_partial text := coalesce(request_leave.partial, 'full');
v_amount numeric;
v_row "better_supabase"."leave_requests"%rowtype;
v_approval "better_supabase"."approval_requests"%rowtype;
v_request jsonb;
v_at_once boolean;
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 v_me is null or not coalesce(better_supabase.can('tenant', request_leave.tenant, 'leave.request'), false) then
raise exception 'not allowed to request leave here' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
select * into v_type from "better_supabase"."leave_types" x
where x."id" = request_leave.type_id and x."tenant_id" = request_leave.tenant and x."archived_at" is null;
if not found then
raise exception 'leave type not found' using errcode = 'P0002', hint = 'LEAVE_TYPE_NOT_FOUND';
end if;
if request_leave.starts_on is null or request_leave.ends_on is null or request_leave.ends_on < request_leave.starts_on then
raise exception 'ends_on must be on or after starts_on' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if v_partial not in ('full', 'morning', 'afternoon', 'hours') then
raise exception 'partial must be full, morning, afternoon or hours' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if v_type."unit" = 'hours' then
if v_partial <> 'hours' and v_partial <> 'full' then
raise exception 'an hours type takes partial hours' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if request_leave.hours is null or request_leave.hours <= 0 then
raise exception 'an hours type needs hours greater than zero' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
v_partial := 'hours';
v_amount := request_leave.hours;
else
if v_partial = 'hours' then
raise exception 'a day type takes partial full, morning or afternoon' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if v_partial in ('morning', 'afternoon') and request_leave.starts_on <> request_leave.ends_on then
raise exception 'a half day starts and ends on the same date' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
v_amount := "better_supabase"."leave_working_days"(request_leave.starts_on, request_leave.ends_on)
* case when v_partial = 'full' then 1 else 0.5 end;
end if;
if v_amount <= 0 then
raise exception 'the request covers no working days' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
perform pg_advisory_xact_lock(hashtextextended('leave:' || request_leave.tenant::text || ':' || v_me::text, 0));
if exists (
select 1 from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id"
where r."tenant_id" = request_leave.tenant and r."user_id" = v_me
and r."cancelled_at" is null and (r."approved_at" is not null or p."status" = 'pending')
and daterange(r."starts_on", r."ends_on", '[]') && daterange(request_leave.starts_on, request_leave.ends_on, '[]')
and not (r."partial" = 'morning' and v_partial = 'afternoon')
and not (r."partial" = 'afternoon' and v_partial = 'morning')
) then
raise exception 'this overlaps another leave request' using errcode = '23P01', hint = 'LEAVE_OVERLAP';
end if;
if v_type."tracked" and "better_supabase"."leave_available"(request_leave.tenant, v_me, v_type."id", extract(year from request_leave.starts_on)::integer) < v_amount then
raise exception 'this request is more than the available balance' using errcode = '23514', hint = 'LEAVE_BALANCE_EXCEEDED';
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."before_leave_request"(uuid, uuid, date, date, numeric)');
begin
if v_hook is not null then
execute format('select %s($1::uuid, $2::uuid, $3::date, $4::date, $5::numeric)', v_hook::oid::regproc)
using request_leave.tenant, v_type."id", request_leave.starts_on, request_leave.ends_on, v_amount;
end if;
end;
insert into "better_supabase"."leave_requests" ("tenant_id", "user_id", "type_id", "starts_on", "ends_on", "partial", "amount", "note")
values (request_leave.tenant, v_me, v_type."id", request_leave.starts_on, request_leave.ends_on, v_partial, v_amount, nullif(trim(request_leave.note), ''))
returning * into v_row;
v_at_once := coalesce(v_type."auto_approve", false);
if not v_at_once then
v_request := "better_supabase"."open_approval"(
request_leave.tenant, 'leave_request', v_row."id"::text, 'approve',
'{"steps":[{"approvers":{"permission":"leave.approve"},"required":1}],"selfApproval":false,"expiresIn":null,"run":null}'::jsonb, v_row."note",
jsonb_build_object('userId', v_me, 'typeId', v_type."id", 'type', v_type."name", 'startsOn', v_row."starts_on", 'endsOn', v_row."ends_on", 'amount', v_amount::text, 'unit', v_type."unit")
);
update "better_supabase"."leave_requests" x set "approval_id" = (v_request ->> 'id')::uuid
where x."id" = v_row."id"
returning * into v_row;
select * into v_approval from "better_supabase"."approval_requests" x where x."id" = v_row."approval_id";
end if;
null;
if v_at_once then
perform "better_supabase"."approve_leave_request"(v_row."id");
select * into v_row from "better_supabase"."leave_requests" x where x."id" = v_row."id";
end if;
declare
v_hook regprocedure := to_regprocedure('"public"."after_leave_request"(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", 'organizationId', v_row."tenant_id", 'userId', v_row."user_id", 'typeId', v_row."type_id", 'startsOn', v_row."starts_on", 'endsOn', v_row."ends_on", 'partial', v_row."partial", 'amount', v_row."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.manage'), false)) then v_row."note" end, 'status', case when v_row."cancelled_at" is not null then 'cancelled' when v_row."approved_at" is not null then 'approved' when v_row."rejected_at" is not null then 'rejected' when v_approval."status" in ('rejected', 'expired') then 'rejected' when v_approval."status" = 'cancelled' then 'cancelled' else 'pending' end, 'approvalId', v_row."approval_id", 'approvedAt', v_row."approved_at", 'cancelledAt', v_row."cancelled_at", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."request_leave"(uuid, uuid, date, date, text, numeric, text) from public, anon;
grant execute on function "better_supabase"."request_leave"(uuid, uuid, date, date, text, numeric, text) to authenticated, service_role;
-- Books the leave once the approval is final: approved_at and, for a
-- tracked type, a taken entry. Approvals calls it; it isn't granted to anyone.
create or replace function "better_supabase"."approve_leave_request"(request_id uuid)
returns void
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."leave_requests"%rowtype;
begin
update "better_supabase"."leave_requests" x set "approved_at" = now(), "updated_at" = now()
where x."id" = approve_leave_request.request_id and x."approved_at" is null and x."cancelled_at" is null
returning * into v_row;
if not found then
return;
end if;
perform "better_supabase"."leave_post"(v_row."tenant_id", v_row."user_id", v_row."type_id", 'taken', -v_row."amount", extract(year from v_row."starts_on")::integer, v_row."id")
from "better_supabase"."leave_types" t where t."id" = v_row."type_id" and t."tracked";
null;
end;
$$;
revoke execute on function "better_supabase"."approve_leave_request"(uuid) from public, anon, authenticated;
-- Stamps the final decision of a request's approval on the request, as
-- decide_leave_request does without approvals: approved books the leave,
-- rejected and cancelled close it. Approvals calls it from its own definer
-- functions, so it runs as their owner; it isn't granted to anyone.
create or replace function "better_supabase"."leave_approval_decided"(request_id uuid, decision text, note text, decided_by uuid)
returns void
language plpgsql
security invoker
set search_path = ''
as $$
declare
v_row "better_supabase"."leave_requests"%rowtype;
begin
if leave_approval_decided.decision = 'approved' then
perform "better_supabase"."approve_leave_request"(leave_approval_decided.request_id);
update "better_supabase"."leave_requests" x set "updated_at" = now(), "decided_by" = leave_approval_decided.decided_by, "decision_note" = nullif(trim(leave_approval_decided.note), '')
where x."id" = leave_approval_decided.request_id and x."approved_at" is not null and x."cancelled_at" is null;
elsif leave_approval_decided.decision = 'rejected' then
update "better_supabase"."leave_requests" x set "updated_at" = now(), "rejected_at" = now(), "decided_by" = leave_approval_decided.decided_by, "decision_note" = nullif(trim(leave_approval_decided.note), '')
where x."id" = leave_approval_decided.request_id and x."approved_at" is null and x."cancelled_at" is null
returning * into v_row;
if found then
null;
end if;
elsif leave_approval_decided.decision = 'cancelled' then
update "better_supabase"."leave_requests" x set "cancelled_at" = now(), "cancelled_by" = leave_approval_decided.decided_by, "updated_at" = now()
where x."id" = leave_approval_decided.request_id and x."approved_at" is null and x."cancelled_at" is null
returning * into v_row;
if found then
null;
end if;
end if;
end;
$$;
revoke execute on function "better_supabase"."leave_approval_decided"(uuid, text, text, uuid) from public, anon, authenticated;
-- Cancels a request: the requester before it starts, or a manager any
-- time. A pending approval is cancelled with it; approved leave goes back
-- to the balance.
create or replace function "better_supabase"."cancel_leave_request"(request_id uuid)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_row "better_supabase"."leave_requests"%rowtype;
v_approval "better_supabase"."approval_requests"%rowtype;
v_manager boolean;
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"."leave_requests" x where x."id" = cancel_leave_request.request_id for update;
if not found then
raise exception 'leave request not found' using errcode = 'P0002', hint = 'LEAVE_REQUEST_NOT_FOUND';
end if;
v_manager := 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", 'leave.manage'), false);
if not (v_manager or coalesce(v_row."user_id" = auth.uid(), false)) then
raise exception 'not allowed to cancel this leave request' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
if v_row."cancelled_at" is not null then
raise exception 'this leave request is already cancelled' using errcode = 'PT409', hint = 'LEAVE_REQUEST_CLOSED';
end if;
if v_row."approved_at" is null and v_row."rejected_at" is not null then
raise exception 'this leave request was rejected' using errcode = 'PT409', hint = 'LEAVE_REQUEST_CLOSED';
end if;
if not v_manager and v_row."approved_at" is not null and v_row."starts_on" <= current_date then
raise exception 'leave that has started can only be cancelled by a manager' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
update "better_supabase"."approval_requests" p set "status" = 'cancelled', "decided_at" = now()
where p."id" = v_row."approval_id" and p."status" = 'pending';
if v_row."approved_at" is not null then
perform "better_supabase"."leave_post"(v_row."tenant_id", v_row."user_id", v_row."type_id", 'taken', v_row."amount", extract(year from v_row."starts_on")::integer, v_row."id", 'cancelled')
from "better_supabase"."leave_types" t where t."id" = v_row."type_id" and t."tracked";
end if;
update "better_supabase"."leave_requests" x set "cancelled_at" = now(), "cancelled_by" = auth.uid(), "updated_at" = now()
where x."id" = v_row."id"
returning * into v_row;
select * into v_approval from "better_supabase"."approval_requests" x where x."id" = v_row."approval_id";
null;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'userId', v_row."user_id", 'typeId', v_row."type_id", 'startsOn', v_row."starts_on", 'endsOn', v_row."ends_on", 'partial', v_row."partial", 'amount', v_row."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.manage'), false)) then v_row."note" end, 'status', case when v_row."cancelled_at" is not null then 'cancelled' when v_row."approved_at" is not null then 'approved' when v_row."rejected_at" is not null then 'rejected' when v_approval."status" in ('rejected', 'expired') then 'rejected' when v_approval."status" = 'cancelled' then 'cancelled' else 'pending' end, 'approvalId', v_row."approval_id", 'approvedAt', v_row."approved_at", 'cancelledAt', v_row."cancelled_at", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."cancel_leave_request"(uuid) from public, anon;
grant execute on function "better_supabase"."cancel_leave_request"(uuid) to authenticated, service_role;
-- Changes a pending or approved request: its dates, parts of the day,
-- hours, note or extra columns. What it leaves null keeps its value, and an
-- empty note clears it. The requester changes a pending request, which goes
-- back to approval; a manager also changes approved leave, which is booked
-- again for the new amount, so leave can be shortened.
create or replace function "better_supabase"."update_leave_request"(request_id uuid, starts_on date default null, ends_on date default null, partial text default null, hours numeric default null, note text default null)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_me uuid;
v_row "better_supabase"."leave_requests"%rowtype;
v_old "better_supabase"."leave_requests"%rowtype;
v_type "better_supabase"."leave_types"%rowtype;
v_partial text;
v_amount numeric;
v_manager boolean;
v_status text;
v_starts date;
v_ends date;
v_approval "better_supabase"."approval_requests"%rowtype;
v_request jsonb;
v_at_once boolean;
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"."leave_requests" x where x."id" = update_leave_request.request_id for update;
if not found then
raise exception 'leave request not found' using errcode = 'P0002', hint = 'LEAVE_REQUEST_NOT_FOUND';
end if;
select * into v_approval from "better_supabase"."approval_requests" x where x."id" = v_row."approval_id";
v_old := v_row;
v_manager := 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", 'leave.manage'), false);
if not (v_manager or coalesce(v_row."user_id" = auth.uid(), false)) then
raise exception 'not allowed to change this leave request' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
v_status := case when v_row."cancelled_at" is not null then 'cancelled' when v_row."approved_at" is not null then 'approved' when v_row."rejected_at" is not null then 'rejected' when v_approval."status" in ('rejected', 'expired') then 'rejected' when v_approval."status" = 'cancelled' then 'cancelled' else 'pending' end;
if v_status not in ('pending', 'approved') then
raise exception 'only a pending or approved leave request changes' using errcode = 'PT409', hint = 'LEAVE_REQUEST_CLOSED';
end if;
if v_status = 'approved' and not v_manager then
raise exception 'approved leave is changed by a manager' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
select * into v_type from "better_supabase"."leave_types" x where x."id" = v_row."type_id";
v_me := v_row."user_id";
v_starts := coalesce(update_leave_request.starts_on, v_row."starts_on");
v_ends := coalesce(update_leave_request.ends_on, v_row."ends_on");
if v_ends < v_starts then
raise exception 'ends_on must be on or after starts_on' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
v_partial := coalesce(update_leave_request.partial, (v_old."partial")::text);
if v_partial not in ('full', 'morning', 'afternoon', 'hours') then
raise exception 'partial must be full, morning, afternoon or hours' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if v_type."unit" = 'hours' then
if v_partial <> 'hours' and v_partial <> 'full' then
raise exception 'an hours type takes partial hours' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if coalesce(update_leave_request.hours, case when v_type."unit" = 'hours' then v_old."amount" end) is null or coalesce(update_leave_request.hours, case when v_type."unit" = 'hours' then v_old."amount" end) <= 0 then
raise exception 'an hours type needs hours greater than zero' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
v_partial := 'hours';
v_amount := coalesce(update_leave_request.hours, case when v_type."unit" = 'hours' then v_old."amount" end);
else
if v_partial = 'hours' then
raise exception 'a day type takes partial full, morning or afternoon' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if v_partial in ('morning', 'afternoon') and v_starts <> v_ends then
raise exception 'a half day starts and ends on the same date' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
v_amount := "better_supabase"."leave_working_days"(v_starts, v_ends)
* case when v_partial = 'full' then 1 else 0.5 end;
end if;
if v_amount <= 0 then
raise exception 'the request covers no working days' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
perform pg_advisory_xact_lock(hashtextextended('leave:' || v_row."tenant_id"::text || ':' || v_me::text, 0));
if exists (
select 1 from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id"
where r."tenant_id" = v_row."tenant_id" and r."user_id" = v_me
and r."cancelled_at" is null and r."id" <> v_row."id" and (r."approved_at" is not null or p."status" = 'pending')
and daterange(r."starts_on", r."ends_on", '[]') && daterange(v_starts, v_ends, '[]')
and not (r."partial" = 'morning' and v_partial = 'afternoon')
and not (r."partial" = 'afternoon' and v_partial = 'morning')
) then
raise exception 'this overlaps another leave request' using errcode = '23P01', hint = 'LEAVE_OVERLAP';
end if;
if v_type."tracked" and "better_supabase"."leave_available"(v_row."tenant_id", v_me, v_type."id", extract(year from v_starts)::integer)
+ (case when extract(year from v_old."starts_on") = extract(year from v_starts) then v_old."amount" else 0 end) < v_amount then
raise exception 'this request is more than the available balance' using errcode = '23514', hint = 'LEAVE_BALANCE_EXCEEDED';
end if;
if v_status = 'approved' then
perform "better_supabase"."leave_post"(v_old."tenant_id", v_old."user_id", v_old."type_id", 'taken', v_old."amount", extract(year from v_old."starts_on")::integer, v_old."id", 'changed')
from "better_supabase"."leave_types" t where t."id" = v_old."type_id" and t."tracked";
end if;
update "better_supabase"."leave_requests" x set "starts_on" = v_starts, "ends_on" = v_ends, "partial" = v_partial, "amount" = v_amount, "note" = case when update_leave_request.note is null then x."note" else nullif(trim(update_leave_request.note), '') end, "updated_at" = now()
where x."id" = v_row."id"
returning * into v_row;
if v_status = 'approved' then
perform "better_supabase"."leave_post"(v_row."tenant_id", v_row."user_id", v_row."type_id", 'taken', -v_row."amount", extract(year from v_row."starts_on")::integer, v_row."id")
from "better_supabase"."leave_types" t where t."id" = v_row."type_id" and t."tracked";
end if;
if v_status = 'pending' then
update "better_supabase"."approval_requests" p set "status" = 'cancelled', "decided_at" = now()
where p."id" = v_row."approval_id" and p."status" = 'pending';
v_at_once := coalesce(v_type."auto_approve", false);
if not v_at_once then
v_request := "better_supabase"."open_approval"(
v_row."tenant_id", 'leave_request', v_row."id"::text, 'approve',
'{"steps":[{"approvers":{"permission":"leave.approve"},"required":1}],"selfApproval":false,"expiresIn":null,"run":null}'::jsonb, v_row."note",
jsonb_build_object('userId', v_me, 'typeId', v_type."id", 'type', v_type."name", 'startsOn', v_row."starts_on", 'endsOn', v_row."ends_on", 'amount', v_amount::text, 'unit', v_type."unit")
);
update "better_supabase"."leave_requests" x set "approval_id" = (v_request ->> 'id')::uuid
where x."id" = v_row."id"
returning * into v_row;
select * into v_approval from "better_supabase"."approval_requests" x where x."id" = v_row."approval_id";
end if;
if v_at_once then
perform "better_supabase"."approve_leave_request"(v_row."id");
select * into v_row from "better_supabase"."leave_requests" x where x."id" = v_row."id";
end if;
end if;
null;
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'userId', v_row."user_id", 'typeId', v_row."type_id", 'startsOn', v_row."starts_on", 'endsOn', v_row."ends_on", 'partial', v_row."partial", 'amount', v_row."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.manage'), false)) then v_row."note" end, 'status', case when v_row."cancelled_at" is not null then 'cancelled' when v_row."approved_at" is not null then 'approved' when v_row."rejected_at" is not null then 'rejected' when v_approval."status" in ('rejected', 'expired') then 'rejected' when v_approval."status" = 'cancelled' then 'cancelled' else 'pending' end, 'approvalId', v_row."approval_id", 'approvedAt', v_row."approved_at", 'cancelledAt', v_row."cancelled_at", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."update_leave_request"(uuid, date, date, text, numeric, text) from public, anon;
grant execute on function "better_supabase"."update_leave_request"(uuid, date, date, text, numeric, text) to authenticated, service_role;
-- Takes a gap out of approved leave, such as sick days during a holiday:
-- the request ends before the gap and a new approved request takes the days
-- after it. Needs a manager.
create or replace function "better_supabase"."split_leave_request"(request_id uuid, gap_starts date, gap_ends date)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_old "better_supabase"."leave_requests"%rowtype;
v_row "better_supabase"."leave_requests"%rowtype;
v_type "better_supabase"."leave_types"%rowtype;
v_partial text := 'full';
v_amount numeric;
v_approval "better_supabase"."approval_requests"%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_old from "better_supabase"."leave_requests" x where x."id" = split_leave_request.request_id for update;
if not found then
raise exception 'leave request not found' using errcode = 'P0002', hint = 'LEAVE_REQUEST_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_old."tenant_id", 'leave.manage'), false)) then
raise exception 'approved leave is split by a manager' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
if v_old."approved_at" is null or v_old."cancelled_at" is not null then
raise exception 'only approved leave is split' using errcode = 'PT409', hint = 'LEAVE_REQUEST_CLOSED';
end if;
select * into v_type from "better_supabase"."leave_types" x where x."id" = v_old."type_id";
if v_type."unit" = 'hours' then
raise exception 'leave in hours isn''t split' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if split_leave_request.gap_starts is null or split_leave_request.gap_ends is null
or split_leave_request.gap_ends < split_leave_request.gap_starts
or split_leave_request.gap_starts <= v_old."starts_on" or split_leave_request.gap_ends >= v_old."ends_on" then
raise exception 'the gap lies inside the leave with days on both sides; shorten leave with update_leave_request' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if v_partial not in ('full', 'morning', 'afternoon', 'hours') then
raise exception 'partial must be full, morning, afternoon or hours' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if v_type."unit" = 'hours' then
if v_partial <> 'hours' and v_partial <> 'full' then
raise exception 'an hours type takes partial hours' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if null is null or null <= 0 then
raise exception 'an hours type needs hours greater than zero' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
v_partial := 'hours';
v_amount := null;
else
if v_partial = 'hours' then
raise exception 'a day type takes partial full, morning or afternoon' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
if v_partial in ('morning', 'afternoon') and (split_leave_request.gap_ends + 1) <> v_old."ends_on" then
raise exception 'a half day starts and ends on the same date' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
v_amount := "better_supabase"."leave_working_days"((split_leave_request.gap_ends + 1), v_old."ends_on")
* case when v_partial = 'full' then 1 else 0.5 end;
end if;
perform "better_supabase"."update_leave_request"(v_old."id", ends_on => split_leave_request.gap_starts - 1, partial => 'full');
insert into "better_supabase"."leave_requests" ("tenant_id", "user_id", "type_id", "starts_on", "ends_on", "partial", "amount", "note", "approval_id", "approved_at")
values (v_old."tenant_id", v_old."user_id", v_old."type_id", split_leave_request.gap_ends + 1, v_old."ends_on", v_partial, v_amount, v_old."note", v_old."approval_id", v_old."approved_at")
returning * into v_row;
perform "better_supabase"."leave_post"(v_row."tenant_id", v_row."user_id", v_row."type_id", 'taken', -v_row."amount", extract(year from v_row."starts_on")::integer, v_row."id")
from "better_supabase"."leave_types" t where t."id" = v_row."type_id" and t."tracked";
select * into v_approval from "better_supabase"."approval_requests" x where x."id" = v_row."approval_id";
null;
return jsonb_build_object(
'request', (select jsonb_build_object('id', x."id", 'organizationId', x."tenant_id", 'userId', x."user_id", 'typeId', x."type_id", 'startsOn', x."starts_on", 'endsOn', x."ends_on", 'partial', x."partial", 'amount', x."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false)) then x."note" end, 'status', case when x."cancelled_at" is not null then 'cancelled' when x."approved_at" is not null then 'approved' when x."rejected_at" is not null then 'rejected' when v_approval."status" in ('rejected', 'expired') then 'rejected' when v_approval."status" = 'cancelled' then 'cancelled' else 'pending' end, 'approvalId', x."approval_id", 'approvedAt', x."approved_at", 'cancelledAt', x."cancelled_at", 'createdAt', x."created_at", 'updatedAt', x."updated_at") from "better_supabase"."leave_requests" x where x."id" = v_old."id"),
'split', jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'userId', v_row."user_id", 'typeId', v_row."type_id", 'startsOn', v_row."starts_on", 'endsOn', v_row."ends_on", 'partial', v_row."partial", 'amount', v_row."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.manage'), false)) then v_row."note" end, 'status', case when v_row."cancelled_at" is not null then 'cancelled' when v_row."approved_at" is not null then 'approved' when v_row."rejected_at" is not null then 'rejected' when v_approval."status" in ('rejected', 'expired') then 'rejected' when v_approval."status" = 'cancelled' then 'cancelled' else 'pending' end, 'approvalId', v_row."approval_id", 'approvedAt', v_row."approved_at", 'cancelledAt', v_row."cancelled_at", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at")
);
end;
$$;
revoke execute on function "better_supabase"."split_leave_request"(uuid, date, date) from public, anon;
grant execute on function "better_supabase"."split_leave_request"(uuid, date, date) to authenticated, service_role;
-- Requests that overlap a date range, earliest first: the caller's, or
-- everyone's with the read permission.
create or replace function "better_supabase"."list_leave_requests"(tenant uuid, user_id uuid default null, status text default null, starts date default null, ends date default null, everyone boolean default false, page_size integer default 100)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_reader boolean := coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', list_leave_requests.tenant, 'leave.read'), false);
v_rows jsonb;
begin
if not (v_reader or coalesce(better_supabase.can('tenant', list_leave_requests.tenant, 'leave.request'), false)) then
raise exception 'not allowed to list leave requests' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
if not v_reader and (coalesce(list_leave_requests.everyone, false) or (list_leave_requests.user_id is not null and list_leave_requests.user_id is distinct from auth.uid())) then
raise exception 'not allowed to read another member''s leave' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
select coalesce(jsonb_agg(z.item order by z.starts, z.created), '[]'::jsonb) into v_rows
from (
select jsonb_build_object('id', r."id", 'organizationId', r."tenant_id", 'userId', r."user_id", 'typeId', r."type_id", 'startsOn', r."starts_on", 'endsOn', r."ends_on", 'partial', r."partial", 'amount', r."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(r."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', r."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', r."tenant_id", 'leave.manage'), false)) then r."note" end, 'status', case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end, 'approvalId', r."approval_id", 'approvedAt', r."approved_at", 'cancelledAt', r."cancelled_at", 'createdAt', r."created_at", 'updatedAt', r."updated_at") as item, r."starts_on" as starts, r."created_at" as created
from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id"
where r."tenant_id" = list_leave_requests.tenant
and (case
when coalesce(list_leave_requests.everyone, false) then true
when list_leave_requests.user_id is not null then r."user_id" = list_leave_requests.user_id
else r."user_id" = auth.uid()
end)
and (list_leave_requests.status is null or case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end = list_leave_requests.status)
and (list_leave_requests.starts is null or r."ends_on" >= list_leave_requests.starts)
and (list_leave_requests.ends is null or r."starts_on" <= list_leave_requests.ends)
order by r."starts_on", r."created_at"
limit least(greatest(coalesce(list_leave_requests.page_size, 100), 1), 500)
) z;
return v_rows;
end;
$$;
revoke execute on function "better_supabase"."list_leave_requests"(uuid, uuid, text, date, date, boolean, integer) from public, anon;
grant execute on function "better_supabase"."list_leave_requests"(uuid, uuid, text, date, date, boolean, integer) to authenticated, service_role;
-- The requests that overlap a date range as a keyset page, soonest first (ADR
-- 1077): the caller's, or everyone's with the read permission. filters is
-- { everyone, userId, employeeId, from, to (dates), status, typeId (each a value
-- or a list), search (note, type name), sort (startsOn, endsOn, createdAt),
-- direction, facet, count, limit, after, offset, paged, total, totalCap }.
create or replace function "better_supabase"."page_leave_requests"(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_leave_requests.filters, '{}'::jsonb);
v_reader boolean := coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(better_supabase.can('tenant', page_leave_requests.tenant, 'leave.read'), false);
v_everyone boolean := coalesce(nullif(coalesce(v_filters #>> '{everyone,0}', v_filters ->> 'everyone'), '')::boolean, false);
v_user_arg uuid := nullif(coalesce(v_filters #>> '{userId,0}', v_filters ->> 'userId'), '')::uuid;
v_employee_arg uuid := nullif(coalesce(v_filters #>> '{employeeId,0}', v_filters ->> 'employeeId'), '')::uuid;
v_from date := nullif(coalesce(v_filters #>> '{from,0}', v_filters ->> 'from'), '')::date;
v_to date := nullif(coalesce(v_filters #>> '{to,0}', v_filters ->> 'to'), '')::date;
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, 100), 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 (v_reader or coalesce(better_supabase.can('tenant', page_leave_requests.tenant, 'leave.request'), false)) then
raise exception 'not allowed to list leave requests' using errcode = '42501', hint = 'LEAVE_FORBIDDEN';
end if;
if not v_reader and (v_everyone or (v_user_arg is not null and v_user_arg is distinct from auth.uid())) then
raise exception 'not allowed to read another member''s leave' using errcode = '42501', hint = 'LEAVE_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 = 'LEAVE_INVALID';
end if;
if v_facet is not null then
if v_facet not in ('status', 'typeId') then
raise exception 'facet is one of status, typeId' using errcode = '22023', hint = 'LEAVE_INVALID';
end if;
with s as (
select (case v_facet when 'status' then (x.leave_status)::text when 'typeId' then (x."type_id"::text)::text end) as v
from (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" 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 (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" 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 ('startsOn', 'endsOn', 'createdAt') then
raise exception 'sort is one of startsOn, endsOn, createdAt' using errcode = '22023', hint = 'LEAVE_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 = 'LEAVE_INVALID';
end if;
if v_sort is null 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) <> 3) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'LEAVE_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", 'userId', x."user_id", 'typeId', x."type_id", 'startsOn', x."starts_on", 'endsOn', x."ends_on", 'partial', x."partial", 'amount', x."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false)) then x."note" end, 'status', x.leave_status, 'approvalId', x."approval_id", 'approvedAt', x."approved_at", 'cancelledAt', x."cancelled_at", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."starts_on")::text, (x."created_at")::text, (x."id")::text) as k
from (
select * from (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" ilike v_search))
and (v_after is null or (x."starts_on", x."created_at", x."id") > ((v_after ->> 0)::date, (v_after ->> 1)::timestamptz, (v_after ->> 2)::uuid))
order by x."starts_on" asc, x."created_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort is null 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) <> 3) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'LEAVE_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", 'userId', x."user_id", 'typeId', x."type_id", 'startsOn', x."starts_on", 'endsOn', x."ends_on", 'partial', x."partial", 'amount', x."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false)) then x."note" end, 'status', x.leave_status, 'approvalId', x."approval_id", 'approvedAt', x."approved_at", 'cancelledAt', x."cancelled_at", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."starts_on")::text, (x."created_at")::text, (x."id")::text) as k
from (
select * from (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" ilike v_search))
and (v_after is null or (x."starts_on" <= (v_after ->> 0)::date and ((x."starts_on" < (v_after ->> 0)::date) or (x."starts_on" = (v_after ->> 0)::date and x."created_at" > (v_after ->> 1)::timestamptz) or (x."starts_on" = (v_after ->> 0)::date and x."created_at" = (v_after ->> 1)::timestamptz and x."id" > (v_after ->> 2)::uuid))))
order by x."starts_on" desc, x."created_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'startsOn' 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) <> 3) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'LEAVE_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", 'userId', x."user_id", 'typeId', x."type_id", 'startsOn', x."starts_on", 'endsOn', x."ends_on", 'partial', x."partial", 'amount', x."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false)) then x."note" end, 'status', x.leave_status, 'approvalId', x."approval_id", 'approvedAt', x."approved_at", 'cancelledAt', x."cancelled_at", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."starts_on")::text, (x."created_at")::text, (x."id")::text) as k
from (
select * from (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" ilike v_search))
and (v_after is null or (x."starts_on", x."created_at", x."id") > ((v_after ->> 0)::date, (v_after ->> 1)::timestamptz, (v_after ->> 2)::uuid))
order by x."starts_on" asc, x."created_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'startsOn' 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) <> 3) then
raise exception 'after is the nextCursor of the previous page' using errcode = '22023', hint = 'LEAVE_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", 'userId', x."user_id", 'typeId', x."type_id", 'startsOn', x."starts_on", 'endsOn', x."ends_on", 'partial', x."partial", 'amount', x."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false)) then x."note" end, 'status', x.leave_status, 'approvalId', x."approval_id", 'approvedAt', x."approved_at", 'cancelledAt', x."cancelled_at", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."starts_on")::text, (x."created_at")::text, (x."id")::text) as k
from (
select * from (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" ilike v_search))
and (v_after is null or (x."starts_on" <= (v_after ->> 0)::date and ((x."starts_on" < (v_after ->> 0)::date) or (x."starts_on" = (v_after ->> 0)::date and x."created_at" > (v_after ->> 1)::timestamptz) or (x."starts_on" = (v_after ->> 0)::date and x."created_at" = (v_after ->> 1)::timestamptz and x."id" > (v_after ->> 2)::uuid))))
order by x."starts_on" desc, x."created_at" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'endsOn' 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 = 'LEAVE_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", 'userId', x."user_id", 'typeId', x."type_id", 'startsOn', x."starts_on", 'endsOn', x."ends_on", 'partial', x."partial", 'amount', x."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false)) then x."note" end, 'status', x.leave_status, 'approvalId', x."approval_id", 'approvedAt', x."approved_at", 'cancelledAt', x."cancelled_at", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."ends_on")::text, (x."id")::text) as k
from (
select * from (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" ilike v_search))
and (v_after is null or (x."ends_on", x."id") > ((v_after ->> 0)::date, (v_after ->> 1)::uuid))
order by x."ends_on" asc, x."id" asc
limit v_limit + 1 offset v_offset
) x
) p;
elsif v_sort = 'endsOn' 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 = 'LEAVE_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", 'userId', x."user_id", 'typeId', x."type_id", 'startsOn', x."starts_on", 'endsOn', x."ends_on", 'partial', x."partial", 'amount', x."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false)) then x."note" end, 'status', x.leave_status, 'approvalId', x."approval_id", 'approvedAt', x."approved_at", 'cancelledAt', x."cancelled_at", 'createdAt', x."created_at", 'updatedAt', x."updated_at") as j, jsonb_build_array((x."ends_on")::text, (x."id")::text) as k
from (
select * from (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" ilike v_search))
and (v_after is null or (x."ends_on" <= (v_after ->> 0)::date and ((x."ends_on" < (v_after ->> 0)::date) or (x."ends_on" = (v_after ->> 0)::date and x."id" > (v_after ->> 1)::uuid))))
order by x."ends_on" desc, x."id" asc
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 = 'LEAVE_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", 'userId', x."user_id", 'typeId', x."type_id", 'startsOn', x."starts_on", 'endsOn', x."ends_on", 'partial', x."partial", 'amount', x."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false)) then x."note" end, 'status', x.leave_status, 'approvalId', x."approval_id", 'approvedAt', x."approved_at", 'cancelledAt', x."cancelled_at", '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 (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" 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" asc, x."id" asc
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 = 'LEAVE_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", 'userId', x."user_id", 'typeId', x."type_id", 'startsOn', x."starts_on", 'endsOn', x."ends_on", 'partial', x."partial", 'amount', x."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false)) then x."note" end, 'status', x.leave_status, 'approvalId', x."approval_id", 'approvedAt', x."approved_at", 'cancelledAt', x."cancelled_at", '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 (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" 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" 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 (select r.*, case when r."cancelled_at" is not null then 'cancelled' when r."approved_at" is not null then 'approved' when r."rejected_at" is not null then 'rejected' when p."status" in ('rejected', 'expired') then 'rejected' when p."status" = 'cancelled' then 'cancelled' else 'pending' end as leave_status from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" p on p."id" = r."approval_id") x
where x."tenant_id" = page_leave_requests.tenant
and (case when v_everyone then true when v_user_arg is not null then x."user_id" = v_user_arg else x."user_id" = auth.uid() end)
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.leave_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 -> 'typeId' is not null and jsonb_typeof(v_filters -> 'typeId') <> 'null' and not (jsonb_typeof(v_filters -> 'typeId') = 'array' and jsonb_array_length(v_filters -> 'typeId') = 0)) or x."type_id"::text = any((case when jsonb_typeof(v_filters -> 'typeId') = 'array' then array(select jsonb_array_elements_text(v_filters -> 'typeId')) else array[v_filters ->> 'typeId'] end)::text[]))
and (v_from is null or x."ends_on" >= v_from)
and (v_to is null or x."starts_on" <= v_to)
and (v_search is null or (x."note" ilike v_search and (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(x."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', x."tenant_id", 'leave.manage'), false))) or exists (select 1 from "better_supabase"."leave_types" st where st."id" = better_supabase.try_column_type(x."type_id"::text, (null::"better_supabase"."leave_types")."id") and st."name" 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"."page_leave_requests"(uuid, jsonb) from public, anon;
grant execute on function "better_supabase"."page_leave_requests"(uuid, jsonb) to authenticated, service_role;
-- One request by id, when the caller may read it: their own, or any with the
-- read permission. It reads the table as its owner, so an app that revokes
-- the note column from authenticated still gets it here.
create or replace function "better_supabase"."get_leave_request"(request_id uuid)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
#variable_conflict use_column
declare
v_row "better_supabase"."leave_requests"%rowtype;
v_approval "better_supabase"."approval_requests"%rowtype;
begin
select * into v_row from "better_supabase"."leave_requests" x where x."id" = get_leave_request.request_id;
if not found or not (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."user_id" = auth.uid(), false) or (coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.read'), false))) then
raise exception 'leave request not found' using errcode = 'P0002', hint = 'LEAVE_REQUEST_NOT_FOUND';
end if;
select * into v_approval from "better_supabase"."approval_requests" x where x."id" = v_row."approval_id";
return jsonb_build_object('id', v_row."id", 'organizationId', v_row."tenant_id", 'userId', v_row."user_id", 'typeId', v_row."type_id", 'startsOn', v_row."starts_on", 'endsOn', v_row."ends_on", 'partial', v_row."partial", 'amount', v_row."amount"::text, 'note', case when (coalesce(nullif((select auth.jwt()) ->> 'role', ''), session_user::text) in ('service_role', 'postgres', 'supabase_admin') or coalesce(v_row."user_id" = auth.uid(), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.approve'), false) or coalesce(better_supabase.can('tenant', v_row."tenant_id", 'leave.manage'), false)) then v_row."note" end, 'status', case when v_row."cancelled_at" is not null then 'cancelled' when v_row."approved_at" is not null then 'approved' when v_row."rejected_at" is not null then 'rejected' when v_approval."status" in ('rejected', 'expired') then 'rejected' when v_approval."status" = 'cancelled' then 'cancelled' else 'pending' end, 'approvalId', v_row."approval_id", 'approvedAt', v_row."approved_at", 'cancelledAt', v_row."cancelled_at", 'createdAt', v_row."created_at", 'updatedAt', v_row."updated_at");
end;
$$;
revoke execute on function "better_supabase"."get_leave_request"(uuid) from public, anon;
grant execute on function "better_supabase"."get_leave_request"(uuid) to authenticated, service_role;
create or replace function "better_supabase"."leave_range_close_blockers"(tenant uuid, starts_on date, ends_on date)
returns text[]
language sql
stable
security definer
set search_path = ''
as $$
select case when exists (
select 1 from "better_supabase"."leave_requests" r
left join "better_supabase"."approval_requests" ap on ap."id" = r."approval_id"
where r."tenant_id" = leave_range_close_blockers.tenant
and r."starts_on" between leave_range_close_blockers.starts_on and leave_range_close_blockers.ends_on
and r."cancelled_at" is null and r."approved_at" is null and ap."status" = 'pending'
) then array['pending_requests']::text[] else '{}'::text[] end
$$;
revoke execute on function "better_supabase"."leave_range_close_blockers"(uuid, date, date) from public, anon, authenticated;
grant execute on function "better_supabase"."leave_range_close_blockers"(uuid, date, date) to service_role;
create or replace function "better_supabase"."leave_close_range"(tenant uuid, starts_on date, ends_on date)
returns void
language plpgsql
security definer
set search_path = ''
as $$
begin
perform "better_supabase"."close_leave_year"(leave_close_range.tenant, extract(year from leave_close_range.starts_on)::integer);
end;
$$;
revoke execute on function "better_supabase"."leave_close_range"(uuid, date, date) from public, anon, authenticated;
grant execute on function "better_supabase"."leave_close_range"(uuid, date, date) to service_role;
-- Seeds the rows every organization starts with for leave. Safe to run
-- again: a row whose key exists is kept. It is not an entry point.
create or replace function "better_supabase"."seed_leave_defaults"(p_tenant uuid, p_variant text default null, p_locale text default 'en')
returns void
language plpgsql
security definer
set search_path = ''
as $$
begin
insert into "better_supabase"."leave_types" ("tenant_id", "key", "name", "unit", "paid", "tracked", "allowance")
select p_tenant, 'annual', 'Annual leave', 'days', true, true, 20
where not exists (select 1 from "better_supabase"."leave_types" x where x."tenant_id" = p_tenant and x."key" is not distinct from 'annual');
insert into "better_supabase"."leave_types" ("tenant_id", "key", "name", "unit", "paid", "tracked")
select p_tenant, 'sick', 'Sick leave', 'days', true, false
where not exists (select 1 from "better_supabase"."leave_types" x where x."tenant_id" = p_tenant and x."key" is not distinct from 'sick');
insert into "better_supabase"."leave_types" ("tenant_id", "key", "name", "unit", "paid", "tracked")
select p_tenant, 'unpaid', 'Unpaid leave', 'days', false, false
where not exists (select 1 from "better_supabase"."leave_types" x where x."tenant_id" = p_tenant and x."key" is not distinct from 'unpaid');
end;
$$;
revoke execute on function "better_supabase"."seed_leave_defaults"(uuid, text, text) from public, anon, authenticated;
grant execute on function "better_supabase"."seed_leave_defaults"(uuid, text, text) to 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"."leave_types" 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('leave.request')) or "tenant_id" in (select better_supabase.tenant_ids_with('leave.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."leave_types" 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"."leave_types" 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"."leave_types" 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"."leave_requests" as restrictive
for select to public
using (
"tenant_id" in (select better_supabase.member_organization_ids())
or ("user_id" = (select auth.uid()) or "tenant_id" in (select better_supabase.tenant_ids_with('leave.read')))
);
create policy bsb_tenant_scope_insert on "better_supabase"."leave_requests" 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"."leave_requests" 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"."leave_requests" as restrictive
for delete to public
using ("tenant_id" in (select better_supabase.member_organization_ids()));
Client
This block has no React entry yet. Its TypeScript side is in better-supabase/blocks/leave, which runs on the server.
Events
With the outbox installed, the module writes these in the same transaction as the change.
- leave_balance.adjusted
- leave_request.approved
- leave_request.cancelled
- leave_request.rejected
- leave_request.requested
- leave_request.split
- leave_request.updated
- leave_type.archived
- leave_type.restored
Dependencies
- Required: the install command adds it too
- Works with: optional
Recipes
No UI recipe uses it yet. See all recipes.
More in People
Time trackingtime-entries Time entries with one running timer per member and no overlaps, on any record, billable with a rate. Weekly timesheets go through approvals, and a submitted or approved week is locked. Hiringhiring Jobs and applications on a pipeline per job, candidates from config.recordTypes, scorecards per stage, interviews, and hire, reject and withdraw events for the app to act on. Employeesemployees Employees with or without an account, a manager, team, job title, employment type and status, an org chart, offboarding, and private details and contracts behind employees.view_sensitive. With time-entries, time entries carry the employee_id of their member. Enrollmentsenrollments Programs of steps per organization, and enrollments of a party, a member or any subject in them with step progress and completion. Onboarding checklists run on it. Qualificationsqualifications Qualification types (certifications, licences, skills) with a validity in months and optional evidence, requirements naming who must hold them (a role, a team, a job title, an asset kind, a segment or one holder), holdings of members, companies and assets that expire, a gap report, the holders qualified on a date, expiry notifications, and holdings granted from course certificates. Shiftsshifts Shift templates that generate shifts on weekdays, shifts planned in draft and published per team and location, assignments checked for overlap, approved leave, required qualifications and rest time, open shift requests, swaps between members, availability, a roster, planned hours against contract hours, and time entries from worked shifts.