Leave
Leave types in days or hours, requests approved through the approvals module, and balances on the ledger block per member and year with grants, accruals, adjustments and a year-end carryover.
leave keeps time off per organization: the types an organization offers (vacation, sick leave, a day off in lieu), the requests members file, and balances kept on the ledger. A request opens an approval request in the approvals module, and the final approval books it.
Requesting leave needs leave.request, reading other members' requests and balances needs leave.read, approving needs leave.approve (the default approval step), and managing types, adjusting balances and closing a year needs leave.manage. Admins get every permission and members get leave.request.
better-supabase add leaveThe module needs tenant, permissions and approvals.
Server code calls the leave instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useLeave } = defineDataHooks(
"leave",
(db: AppDb) => db.leave,
);import { createLeave } from "better-supabase/blocks/leave";
const vacation = await db.leave
.saveType(organizationId, {
key: "vacation",
name: "Vacation",
allowance: 25,
carryoverMax: 5,
})
.orThrow();
await db.leave
.accrue(organizationId, { typeId: vacation.id, period: 2026 })
.orThrow();
const request = await db.leave
.request(organizationId, {
typeId: vacation.id,
startsOn: Temporal.PlainDate.from("2026-10-19"),
endsOn: Temporal.PlainDate.from("2026-10-23"),
})
.orThrow();
// request.amount: 5 (working days), request.status: "pending""use client";
import { useLeave } from "@/lib/supabase/hooks";
const rows = useLeave({ limit: 50 });Types
saveType creates a type, or updates the one with the same key. A type counts in days (the default) or hours, is paid or not, and is tracked against a balance unless tracked: false (sick leave, for example, often isn't). allowance is what accrue grants when it names no amount, and carryoverMax caps what closePeriod carries into the next year. archiveType hides a type from new requests and keeps its history, restoreType makes it available again (both record leave_type.archived and leave_type.restored), and types lists the active ones (archived: true for all).
Requests
request books working days between startsOn and endsOn, inclusive: the days in workingDays (Monday to Friday by default), so a request over a weekend counts five days for a full week. partial: "morning" or "afternoon" books half a day and needs one date. An hours type takes hours instead.
A request can't overlap another pending or approved request of the member (LEAVE_OVERLAP). For a tracked type it can't exceed the available balance (LEAVE_BALANCE_EXCEEDED) unless allowNegative is on. A request counts toward the year it starts in.
| Status | Meaning |
|---|---|
pending | its approval request is open; it counts as pending |
approved | the final step approved it; the ledger has a taken entry |
rejected | the approval request was rejected or expired, or rejected_at is set |
cancelled | the requester or a manager cancelled it |
With the employees block installed, every request
has an employee_id column: the employee behind the requester, kept in step
by triggers like time entries' (see employees).
Approvers decide with the approvals client, where the request's subject type is leave_request:
import { createApprovals } from "better-supabase/blocks/approvals";
const approvals = createApprovals({ transport });
await approvals.approve(request.approvalId!).orThrow();update(requestId, change) changes a pending or approved request: its dates, partial or startPart and endPart, hours, note (an empty note clears it) or fields; what it leaves out keeps its value. The requester changes a pending request, which goes back to approval (the open approval request is cancelled and a new one opened). A member with leave.manage (or the employee's manager) also changes approved leave, which is booked again for the new amount, so a balance follows shortened or moved leave. split(requestId, { gapStarts, gapEnds }) takes a gap out of approved leave, such as sick days during a holiday: the request ends the day before gapStarts, and a new approved request (split) takes the days after gapEnds, each booked for its own working days. The gap needs leave on both sides; shorten with update otherwise.
A type with autoApprove: true needs no approval: its requests are approved when they are made, also by the requester, and booked at once. Sick leave is the common case. The block's own types table has the column; on your table map columns.types.autoApprove.
cancel(requestId) cancels a pending request, or an approved one before the leave starts, for its requester, and any request for a member with leave.manage. It cancels a pending approval request with it. Cancelling an approved request writes an entry that gives the days back. list returns the caller's requests, earliest first, and userId or everyone: true read other members' with leave.read; status, from and to narrow it.
workingDays({ from, to }) returns the working days between two Temporal.PlainDate values, inclusive, by the module's workingDays option. It is the number request charges a full-day request, so a form can show the cost before it submits. Half days are not counted.
const days = await leave.workingDays({ from, to }).orThrow();Paging requests
list stays as the capped convenience list. requestPage pages requests by keyset (ADR 1077). Sorts are startsOn (the default, soonest first), endsOn and createdAt. Filters are status and typeId (lists of values, a request matches any of them), userId, employeeId, from and to (one value each), and everyone: ["true"] for every member's requests, which needs leave.read. q searches the note and the type name, and facets are status and typeId. The organization comes from organizationId or the block's tenant option.
A request's note is private to the requester, their manager in the employees block, and members with leave.approve or leave.manage. Every other reader, including a colleague who lists everyone, gets note: null, and q matches only the notes the caller may read. get reads the same way. To close direct table reads as well, list the requests table in expose without the note columns, for example select(*, -note, -decision_note): the block then adds no table-wide select grant of its own, and its functions still return the note to those who may read it.
const first = await leave
.requestPage({
filters: { status: ["pending", "approved"], everyone: ["true"] },
q: "holiday",
limit: 50,
})
.orThrow();
const facets = await leave
.requestFacets({ filters: { everyone: ["true"] } })
.orThrow();
const total = await leave
.requestCount({ filters: { status: ["pending"] } })
.orThrow();
const one = await leave.getRequest(first.items[0].id).orThrow();A cursor belongs to the sort it came from, so start again from the first page when sort changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error. Block lists describes the options every block list shares.
Balances
Each member has a ledger account per type and year (amounts in hundredths of the type's unit), and every change to a balance is a ledger transaction of kind leave.grant, leave.accrual, leave.adjustment, leave.taken, leave.carryover or leave.expiry against the type's pool or taken account. A carryover moves the amount between the two years' accounts. balances(organizationId) returns the caller's balance of each tracked type this year (pass userId and period for others), with granted, taken, pending and available, which is the ledger total less pending requests. ledger lists the entries behind it.
adjust writes a grant or a correction for one member. accrue grants an amount, or the type's allowance, to every member or to userIds; give it an idempotencyKey and a member gets that accrual once, so a monthly cron can call it safely. closePeriod(organizationId, 2026) carries each member's remaining balance, up to carryoverMax, into 2027 and expires the rest. Running it twice writes nothing the second time.
With the periods block installed, request refuses a request that starts in a leave_year period the block locked or closed, with the hint LEAVE_PERIOD_CLOSED. A year without a period row stays open.
Configure
blocks: {
leave: {
options: {
workingDays: ["mon", "tue", "wed", "thu"],
policy: { steps: [{ approvers: { role: "admin" } }], expiresIn: "P14D" },
},
},
},policy is an approvals policy without run, since the final approval books the leave. Columns you add to the requests table are fields, typed with the client's fields schema.
Without the approvals block
options.approvals: false keeps the decision on the request, so leave runs without the approvals block (an approval column mapped to null does the same). A request stays pending until decide(requestId, { approved, note? }) approves or rejects it: the service role, or a member with leave.approve who didn't ask for it. Approval books the leave like a final approval; rejection sets rejected_at and records leave_request.rejected. The requests table takes optional rejectedAt, decidedBy and decisionNote columns; without rejectedAt a rejection fails with LEAVE_REJECTION_UNSUPPORTED. An app that decides elsewhere calls decide_leave_request from its own flow. The service role decides for a user with decidedBy (decided_by in SQL), which is kept in the decidedBy column instead of an empty value; a member passing someone else, or decidedBy naming the requester, fails with the forbidden error. With options.approver: "manager", the requester's manager in the employees block (or the request's employee's manager) may also decide, next to holders of leave.approve. That needs the employees block's tables; the default is "permission".
options.decider names an app function, "schema.function", that takes the request id and returns whether the caller may decide too. Use it for a rule the block doesn't know, such as every manager up the requester's reporting chain or a manager's stand-in. decide_leave_request calls it inside its own check, so the rule holds for every caller of the function, and it never lets the requester decide their own request. The function sees the caller through auth.uid(), and a null answer denies. With the approvals block, the function decides the policy steps whose approvers set decider: true. The default policy sets it next to leave.approve, and a policy of your own names it where it applies (steps: [{ approvers: { manager: true, decider: true } }]). The block files and closes the approval request itself with the real requester, so the app needs no service role to mirror decisions.
create function public.leave_chain_decides(request_id uuid)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select public.manages_in_chain(auth.uid(), r.employee_id)
from public.time_off_requests r
where r.id = request_id
$$;
revoke execute on function public.leave_chain_decides(uuid) from public, anon, authenticated;leave: { options: { approvals: false, decider: "public.leave_chain_decides" } }options.deciderMany is the set form of options.decider: an app function "schema.function", (ids uuid[]) returns uuid[], that returns the ids among ids the caller decides, the same answer decider gives for each. It needs decider. The approvals block's eligible set (approval_eligible_ids_in, which read policies call) asks it once per read for every request whose step sets decider: true, instead of calling decider once per pending request; the single-request checks keep calling decider.
A requester at the top of the reporting chain often has nobody to decide their leave. options.selfDecideWhenTopOfChain: true lets them decide it themselves through decide_leave_request, so the app doesn't need the service role for it. The database allows it only when the requester holds leave.approve in the request's organization and either has no active manager anywhere up their reporting chain or nobody else can decide the request. A manager up the chain counts only with an employee record that has a login, isn't offboarded and has no end date before today, so the person at the top of the chain decides their own leave even while other members hold leave.approve; those members can still decide it, and whoever acts first decides. Someone else can when they are an active member of the organization, other than the requester, and either hold leave.approve there or are the requester's manager the block lets decide: the direct manager under approver: "manager", or, with an options.decider, any manager up the reporting chain, since the block can't ask the decider about other users. A manager counts only with an employee record that has a login, isn't offboarded and has no end date before today, and only with a membership that isn't disabled. So an employee with an active manager can't approve their own leave while the owner holds leave.approve, and an owner whose manager left or has no account can still decide theirs. The check needs an access model that answers for other users: the roles and catalog models do, a custom model needs functions.canUser and a provider needs idsWithFor and isPlatformFor, or rendering the block fails. decide_leave_request checks the rule with leave_request_self_decides(request_id), which apps call too (requestSelfDecides(requestId) in TypeScript) to show whether the caller decides a request as its requester; leave_self_decides(tenant) (selfDecides(organizationId)) answers the same for the caller's next request in the organization. The decision is booked and recorded like any other, with the requester as decidedBy. With the approvals block, the same rule lets the requester decide their own approval request through decide_approval, each step in turn, and a manager step of the policy counts as someone else who can decide. The rule counts only holders of leave.approve, managers and a decider, so a policy that names a role, a team, users or another permission fails to render with it. The service role deciding for the requester through decidedBy still needs the policy's selfApproval. It needs the employees block's tables; the default is false.
leave: { options: { approvals: false, selfDecideWhenTopOfChain: true } }Your own tables without a key or part-of-day column
Over your own tables, columns.types.key and columns.requests.partial can map to null. Without a key column, a type's key is its id: saveType with an existing type's id updates it, and any other key creates a type. Without a partial column, a request takes whole days (LEAVE_PARTIAL_UNSUPPORTED for morning or afternoon) or, for an hours type, hours, and reads return full or hours.
Leave per employee
options.owner: "employee" keys requests and balances by an employee of the employees block instead of by a user, so an employee without an account has leave too. The requests table needs columns.requests.employee (employee_id), and columns.requests.user may map to null. request, list, balances, ledger and adjust take employeeId (the caller's employee by default), and accrue takes employeeIds. The employee's own account requests and reads their leave with leave.request; their manager (the employee's manager_id) or a member with leave.manage requests and cancels it for them, and leave.read reads everyone's. Reads return employeeId next to userId, which is missing for an employee without an account.
With the approvals block, the user who files a request is its approval's requester, and a manager step (approvers: { manager: true }) asks that user's manager. options.approvalOwner: "employee" makes the request's employee the requester instead, so a manager who books leave for a report decides it and the employee can't approve their own leave, and points the manager step at the employee's manager. For an employee without an account, the approval has no requester, so the member who filed it can decide it.
leave: {
options: {
owner: "employee",
approvalOwner: "employee",
policy: { steps: [{ approvers: { manager: true } }] },
},
},The decision on the request
options.approvalRequired names an app function (tenant, request_id uuid) returns boolean, such as a check of the leave type's settings. When it answers false, the request is approved at once and no approval request is filed, so a confidential type such as sick leave never reaches an approval payload. True or null files one as usual, and a type's autoApprove still approves at once too.
With the approvals block, the request's final decision is stamped on the request the same way decide_leave_request does without it. A final approval books the leave and sets decided_by to the last approver and decision_note to their comment. A rejection sets rejected_at, decided_by and decision_note and records leave_request.rejected. Cancelling the approval request (cancel_approval, by the requester or a manager) sets cancelled_at and cancelled_by and records leave_request.cancelled. Each column is left alone when you map it to null, and an expired request keeps its columns empty. A mapped rejected_at closes the request on its own, so a rejection from before an app switched to approvals mode, which has no approval request, stays rejected: update and cancel fail with LEAVE_REQUEST_CLOSED.
options.approvalSubject names the subject type the approvals are filed under, leave_request by default. Set it to keep a name your app already uses, such as time_off_request. The block's own policy is still options.policy; tenant policies (tenantPolicies) and requestColumns of the approvals block match the new name. Changing it on an install with pending requests leaves those under the old name, where the block no longer acts on their decisions, so rename them in the same migration: update better_supabase.approval_requests set subject_type = 'time_off_request' where subject_type = 'leave_request';.
leave: {
options: {
approvalSubject: "time_off_request";
}
}The part of the day a request starts and ends in
Over your own requests table, the columns start_part and end_part hold the part of the day a request starts and ends in: full, morning, afternoon or hours, which may be an enum. Declaring both turns the feature on, and columns.requests.startPart and endPart are only for columns with other names. Declaring one without the other is an error. request takes startPart and endPart: a request that starts in the afternoon begins halfway through its first day, and one that ends in the morning stops halfway through its last. A day type books the working days less half a day for each, and an hours type books hours with any parts. Two requests overlap only when their half days do, so a morning and an afternoon on the same date fit. partial still works and fills both parts.
Balances in your own table
tables.balances maps a table of yours that holds a balance as rows of signed amounts, instead of the ledger block, which leave then doesn't need. Each row has the owner (user or employee), the type, a kind (grant, accrual, taken, adjustment, carryover or expiry, which may be an enum), the amount in the type's unit, and the request a taken row belongs to; effectiveOn, expiresOn, note, key and createdBy are optional.
blocks: {
leave: {
tables: {
requests: "public.time_off_requests",
balances: "public.time_off_ledger",
},
columns: {
requests: {
user: null,
employee: "employee_id",
startPart: "start_part",
endPart: "end_part",
amount: "hours",
partial: null,
},
balances: { user: null, employee: "employee_id", amount: "hours", request: "time_off_request_id" },
},
options: { owner: "employee", approvals: false },
},
},The balance on a date is the sum of the rows effective by then, where a credit that has expired counts only as far as the debits used it: taken leave uses the credits that expire first. balances reads it at the end of period, or today for this year, and a request checks it on its start date. Approving a request adds a taken row dated on its start, and cancelling it deletes that row. adjust adds a row and takes expiresOn. closePeriod adds an expiry row on 31 December for the balance above carryoverMax; it needs effectiveOn. An idempotencyKey needs key.
adjust and accrue take an effectiveOn date, such as a backdated correction or an accrual on the first of the month. Without period the entry belongs to that date's year; without effectiveOn it counts from the first day of the period, as before. Without an effectiveOn column they refuse a date (LEAVE_EFFECTIVE_UNSUPPORTED).
await leave
.accrue(organizationId, {
typeId: vacation.id,
amount: 13.33,
effectiveOn: Temporal.PlainDate.from("2026-11-01"),
})
.orThrow();Confidential leave types
Every member with leave.read reads everyone's leave, which is right for a team calendar but not for sick leave. Over your own types table, declare a boolean confidential column (map columns.types.confidential when yours has another name), and leave of a confidential type stays with the people allowed to see it: the employee, their manager (with options.owner: "employee") and members with permissions.readConfidential (leave.manage when unset). list, balances, ledger and the feeds leave the others out, and so does the read policy of the block's own requests table.
blocks: {
leave: {
tables: { types: "public.time_off_types", requests: "public.time_off_requests" },
columns: { types: { confidential: "is_confidential" } },
permissions: { read: "time_off.read", readConfidential: "time_off.read_sickness" },
},
},A column derived from another one works too, such as is_confidential boolean generated always as (category = 'sick') stored. A feed shows confidential leave only while the link's creator holds the key.
Changes to approved leave go back to approval
By default only a manager changes approved leave, and it stays approved. With options.reapprove: true, the requester may change their own approved leave too, and the change goes back to approval: the taken leave returns to the balance, approvedAt (and without the approvals block decidedBy and decisionNote) is cleared, and the request is pending again, with a new approval request when the approvals block runs. A type with autoApprove is approved and booked again at once. permissions.reapprove names a key whose holders may change anyone's leave the same way, whether or not options.reapprove is set. A manager's change keeps the leave approved as before.
leave: {
options: { reapprove: true },
permissions: { reapprove: "timeOff.update" },
},A feed of approved leave
With share-links, the organization's approved leave can be shared as a feed, for example to subscribe in a calendar app. A member with leave.read creates a link of subject type leave_feed whose subject id is the organization's id, and feed(token) (or leave_feed(token), open to anon) returns the approved requests a year back and everything ahead. The link stops working when it is revoked or expires, and when its creator no longer holds leave.read. Turn the requests into iCalendar all-day events in your feed route.
const link = await shareLinks
.create({ type: "leave_feed", id: organizationId })
.orThrow();
const feed = await leave.feed(link.token).orThrow();Each entry has startPart and endPart. options.feed takes more:
| Option | Effect |
|---|---|
teams | with the teams block, a link of subject type leave_team_feed whose subject id is a team's id shares the leave of that team's members |
names | each entry carries the employee's name, or first and last name with the employees block's name: "split"; needs the employees block |
hideTypes | type keys whose type name the feed leaves out, such as ["sick"] |
typeKey | the types table column hideTypes matches, such as category, instead of the type key |
fields | each entry carries the request's extra columns, such as start and end times |
teamColumn | a column of the employees table that names an employee's team, such as department_team_id: a team feed shares the leave of the employees whose column holds the team's id, including employees without an account, instead of the team's members; needs teams and the employees block |
teamName | a team feed carries the team's teamName; needs teams |
organizationName | "schema.table.column" of the organization's name, matched on that table's id; the feed carries it as organizationName |
confidential | "busy" lists the confidential leave the link's creator can't see under busy, with who and when but without the type, amount or fields; "hide" (the default) leaves it out; needs columns.types.confidential |
leave: {
options: { feed: { teams: true, names: true, hideTypes: ["sick"], fields: true } },
}Errors
| Hint | Cause |
|---|---|
LEAVE_FORBIDDEN | the caller lacks the permission for this |
LEAVE_INVALID | dates out of order, a half day over several dates, missing hours, a zero amount, or no working days |
LEAVE_OVERLAP | the member has a pending or approved request on these dates |
LEAVE_BALANCE_EXCEEDED | the request is more than the available balance |
LEAVE_TYPE_NOT_FOUND | no active type has this id |
LEAVE_REQUEST_NOT_FOUND | no request the caller can see has this id |
LEAVE_REQUEST_CLOSED | the request is already cancelled or decided, or only approved leave is split |
LEAVE_EMPLOYEE_INVALID | no employee has this id, or the caller has no employee record |
LEAVE_PERIOD_CLOSED | the periods block locked or closed the leave year the request starts in |
On a record page
leaveBinding loads the leave requests of one owner, earliest first, through leave.forOwner({ subject, limit }). With a subject of type employee it filters by employee_id, which exists when the table has owner: "employee" or the employees block is installed. With any other type it filters by the member whose user id is the subject's id. On a table that keys requests by user only, an employee subject fails with a database error that says the employee_id argument is unknown, so bind such a page to the member instead. The organization comes from options.tenant; the owner, the owner's manager and anyone with leave.read see the requests. It shows at most limit requests (default 100, up to 500), goes stale on leave_request.* events and has no writes, because a request takes dates and an approval.
Events
The block records leave_request.requested, leave_request.approved, leave_request.rejected (without the approvals block), leave_request.cancelled, leave_request.updated and leave_request.split (the new request) with organizationId, id, userId, typeId, startsOn, endsOn, amount and approvalId, and leave_balance.adjusted with kind, amount and period for grants and adjustments. See events.
The block takes hooks around its methods; see extending blocks.
Without the client
db.leave is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createLeave } from "better-supabase/blocks/leave";
const leave = createLeave({ transport });
const vacation = await leave
.saveType(organizationId, {
key: "vacation",
name: "Vacation",
allowance: 25,
carryoverMax: 5,
})
.orThrow();
await leave
.accrue(organizationId, { typeId: vacation.id, period: 2026 })
.orThrow();
const request = await leave
.request(organizationId, {
typeId: vacation.id,
startsOn: Temporal.PlainDate.from("2026-10-19"),
endsOn: Temporal.PlainDate.from("2026-10-23"),
})
.orThrow();
// request.amount: 5 (working days), request.status: "pending"Decide and list pending
approve({ requestId, note }) and reject({ requestId, note }) call decide with the matching decision. pending({ organizationId, everyone }) lists the requests that wait for a decision.
await db.leave.approve({ requestId, note: "Enjoy" }).orThrow();
const waiting = await db.leave
.pending({ organizationId, everyone: true })
.orThrow();Last updated on
Care plans
Care plans for any client subject, with coded problems, goals with a measure, actions that start when the plan is published, evaluations over time, agreement through a signature and restrictive measures that start only once approved.
Shifts
Shift templates, shifts planned in draft and published per team and location, assignments checked for overlap, leave, qualifications and rest, open shift requests, swaps, availability, a roster and planned hours.