Employees
Employees with or without an account, a manager, team and status, an org chart, offboarding, and private details and contracts behind employees.view_sensitive.
employees keeps the people an organization employs. An employee has a name, an optional account (userId: contractors and interns often have none), a manager, a team, a job title, an employment type, a start and end date, and a status of preboarding, active, on_leave or offboarded. Managers form a tree: the database refuses a manager from another organization and a manager who reports to the employee. Private details and a contract history sit in their own tables, which only the employee and holders of employees.read_sensitive read.
Reading the directory needs employees.read, which members have. Creating, editing and offboarding needs employees.write, and the private details and contracts need employees.read_sensitive; admins have both. A manager without employees.read still reads the employees under them through reportsOf and orgChart, and every employee reads their own row, details and contracts.
Some actions take their own key when you set one, and fall back otherwise:
| Key | Gates | Without it |
|---|---|---|
permissions.create | create | the write key |
permissions.contractsRead | reading contracts | the readSensitive key |
permissions.contractsWrite | adding, changing and deleting contracts, on its own | the write and readSensitive keys together |
permissions.privateDetailsWrite | saving someone else's private details, with readSensitive | the readSensitive key alone |
better-supabase add employeesThe module needs memberships and access. With outbox it records events, with hiring it makes employees from hired applications, and with relations it links them to the application they came from.
Server code calls the employees instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useEmployees } = defineDataHooks(
"employees",
(db: AppDb) => db.employees,
);import { createEmployees } from "better-supabase/blocks/employees";
const mia = await db.employees
.create(organizationId, {
name: "Mia de Vries",
userId,
jobTitle: "Designer",
managerId: leadId,
startDate: Temporal.PlainDate.from("2026-11-01"),
})
.orThrow();"use client";
import { useEmployees } from "@/lib/supabase/hooks";
const rows = useEmployees({ limit: 50 });The status defaults to preboarding before the start date and active from it. employmentType is one of blocks.employees.options.employmentTypes (employee, contractor, intern and temporary by default), and the first one is the default. A userId must be a member of the organization (EMPLOYEE_USER_NOT_MEMBER) and an employee only once (EMPLOYEE_USER_TAKEN). Setting or changing userId also needs permissions.readSensitive and permissions.contractsRead (EMPLOYEE_LINK_FORBIDDEN), because the linked account reads that employee's own private details and contracts.
Installing the block registers employees as the employee subject, so comments, files, tags and search attach to them. Set the page a search result links to on the entity:
export default defineConfig({
blocks: { employees: { names: { employee: { url: "/people/{id}" } } } },
});Paging employees
page lists the organization's employees by name (ADR 1077) and needs employees.read. Sorts are name (the default) and startDate, newest first. Filters are status, employmentType, teamId, managerId and userId, each a list of values. q searches the name, email and job title. facets counts status, employmentType and teamId, count returns { value, exact }, and get reads one employee by id (also for the employee and their managers).
const first = await employees
.page({
organizationId,
filters: { status: ["active"] },
q: "ada",
limit: 50,
})
.orThrow();
const facets = await employees.facets({ organizationId }).orThrow();
const total = await employees
.count({ organizationId, filters: { teamId: [teamId] } })
.orThrow();
const one = await employees.get(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.
Editing
update(changes) applies a batch of { employeeId, field, value } cells, each on its own, as an editable grid sends them. A change that fails comes back in rejected with its hint and the others stay. The fields are name, email, userId, jobTitle, teamId, managerId, employmentType, status, startDate, endDate and the extra columns by name; null clears one. status takes preboarding, active or on_leave; setting it on an offboarded employee rehires them and clears the end date. An app status that a label maps to next to its first value, such as offboarding in values: { employees: { status: { active: ["active", "offboarding"] } } }, is accepted and written as it is, and counts as that label where the block checks the status.
const { accepted, rejected } = await employees
.update([
{ employeeId: mia.id, field: "jobTitle", value: "Lead designer" },
{ employeeId: leadId, field: "managerId", value: mia.id },
])
.orThrow();
// rejected[0].hint === "EMPLOYEE_MANAGER_CYCLE" when the lead manages MiaPass { atomic: true } as the second argument to apply the batch as one
unit: the first change that fails returns its error and no change stays. To
catch an edit made against a stale row, send the employee's updatedAt as
expectedUpdatedAt on the change. When another edit has changed the employee
since, the change fails with EMPLOYEE_STALE. A batch that edits one
employee more than once compares each change with the row as it was before
the batch. The check needs the updated_at column; on a table that maps it to
null, a change with expectedUpdatedAt fails with EMPLOYEE_CHANGES_INVALID.
await employees
.update(
[
{
employeeId: mia.id,
field: "jobTitle",
value: "Lead designer",
expectedUpdatedAt: mia.updatedAt,
},
],
{ atomic: true },
)
.orThrow();Columns you add to employees with alter table in your own schema files are fields of the block (details). Pass a Standard Schema as fields to type them, parse them on reads and validate them on writes:
const employees = createEmployees({
transport,
fields: z.object({ cost_center: z.string() }),
});Columns you add to the private details and contracts tables are fields. savePrivateDetails
and addContract take their values under fields (a column that is not null without a default is written in the insert), and the reads return
them with the row.
Time and leave
With time-entries or leave
installed, time entries and leave requests carry an employee_id column.
A trigger fills it from the employee with the row's account when the row is
written, and a trigger on employees fills or clears it when an employee
gets, changes or loses an account. Upgrading an app that has both blocks
fills the column for the rows it already has. A member who isn't an
employee keeps employee_id null.
Your own status values
An app status such as offboarding that values maps next to a label is accepted on create and typed. better-supabase gen writes the values of blocks.employees.values.employees.status into the generated entry as options.statuses, so createEmployees widens the status of create to the labels and your values. create refuses any app value that values maps to offboarded, as it does the label.
Org chart
orgChart(organizationId) returns the current employees under everyone without a manager, and orgChart(organizationId, rootId) the employees under one, each with its depth and number of directReports, in display order. reportsOf(managerId) returns the direct reports, and { indirect: true } everyone under the manager. Offboarded employees are left out.
Offboarding
offboard(employeeId, { endDate, reason }) sets the status to offboarded, the end date (today by default) and the reason, and moves the employee's reports to their manager. Offboarding again returns the employee unchanged. When enrollments is installed, onboardWithProgram({ organizationId, input, program, dates }) creates the employee, enrolls them in the program and sets the enrollment dates in one call and one transaction (onboard_with_program), and returns the employee and the enrollment. When enrollments and shifts are installed, offboardWithWork({ employeeId, endDate, reason, windowDays }) does the same and also cancels the employee's active enrollments and unassigns their open shifts in the next windowDays days (30 by default), in one call and one transaction (offboard_with_work). It returns the employee and the counts of enrollments and assignments it ended. Set options.offboarding: { reports: "keep" } to leave the reports with the offboarded employee, for an app that reassigns them itself.
Offboarding is how an employment is archived: the employee stays in the table
with the status offboarded, drops out of the org chart and reportsOf, and
keeps their history. A status can't move back from offboarded, so there is no
restore; a rehire is a new employee.
purge(employeeId) removes an employee that was created by mistake
(purge_employee in SQL). It needs permissions.purge, which falls back to
employees.write, moves the reports as offboarding does (with
reports: "keep" they get no manager), records employee.purged, and fails with EMPLOYEE_IN_USE while another row, such
as a time entry, still points at the employee. Offboard employees who
worked for the organization instead, so their history stays.
From a hired application
With the teams block, employees can
be team members with or without an account. teamId is the primary team:
setting it adds the employee to that team, and the team rows follow the
employee's account.
With the hiring module, fromApplication(applicationId) makes the employee for a hired application, in preboarding. The name comes from the candidate's title column in config.recordTypes, and the job title, team and employment type from the job (an employment type the job's column stores as an enum, or under another label through blocks.hiring.values, is compared by its block label, and a team or employment type the job's table has no column for is left empty); pass overrides such as { startDate } as the second argument. The employee's origin is the application, so calling it again returns the same employee, and with relations it gets a created_from relation to the application. Call it from an application.hired handler:
onBlockEvent(bsb, hiringEvents, "application.hired", async (event) => {
await employees.fromApplication(event.data.applicationId).orThrow();
});create takes an origin ({ type, id }) too, so other imports stay idempotent.
Private details
savePrivateDetails(employeeId, input) saves the national id, IBAN, birth date, personal email, phone, address and emergency contacts; the keys it leaves out keep their value. privateDetails(employeeId) reads them. The employee edits their own details, and offboarding stamps offboardedAt, so an anonymize rule can clear them a retention period later:
"data-lifecycle": {
options: {
anonymize: [
{
table: "better_supabase.employee_private_details",
after: "2 years",
from: "offboarded_at",
set: {
national_id: null,
iban: null,
address: null,
emergency_contacts: { sql: "'[]'::jsonb" },
},
markedBy: "anonymized_at",
},
],
},
},The three tables declare their tenant to data-lifecycle, so an organization export includes them and the purge deletes them. The employees row and the private details also declare the employee's user, so a user's own export includes them.
Contracts
addContract(employeeId, { startsOn, endsOn, hoursPerWeek, salary, salaryPeriod, note }) appends to the employee's contract history. salary is a Money value from commerce, such as money(5_400_000n, "EUR"), which carries its currency and is sent as text so it stays exact past 2^53, and salaryPeriod is hour, week, month or year. A new contract starts after the latest one (EMPLOYEE_CONTRACT_OVERLAP), which ends the day before; rows are never edited. contracts(employeeId) returns them, the newest first. Adding one needs employees.write and employees.read_sensitive.
With options.contracts: "editable", contracts can be changed and removed
too: updateContract(contractId, patch) sets the keys the patch names
(null clears endsOn, hoursPerWeek, salary, salaryPeriod or note;
clearing the salary clears the currency on the block's own table and keeps it on
an app's table)
and deleteContract(contractId) removes one (update_employee_contract and
delete_employee_contract in SQL). Both need the same keys as adding one,
record employee.updated with fields: ["contract"], and fail with
EMPLOYEE_CONTRACT_NOT_FOUND for a contract the caller can't change. With
options.contractOverlap: "allow" next to it, addContract skips the
overlap check and leaves the previous contract as it is, for apps that keep
contracts side by side. With options.contractOverlap: "deny", addContract
leaves the previous contract as it is too, and addContract and
updateContract fail with EMPLOYEE_CONTRACT_OVERLAP when the contract's
dates overlap another contract of the employee; end the previous contract
first. An
app's own salary period column maps its labels through
values, as in
values: { contracts: { salaryPeriod: { hour: "hourly", month: "monthly" } } }.
On the employee's own page, the block's record binding (employeeContractsBinding) loads the contracts with the employee as the subject ({ type: "employee", id }, or the renamed type) and reads again on employee.updated and employee.deleted. It needs the contracts read key and hides itself from a viewer without it. Its remove write calls deleteContract, so it works with options.contracts: "editable". Adding a contract takes dates and money, which a Server Action can't carry, so addContract stays a call on the client.
An app's own contracts table can map salary and currency to null, and
the module then reads and writes contracts without them. When its salary
column holds major units, such as a numeric of euros, set
options.salaryUnits: "major": the module divides by the currency's minor
units on write and multiplies on read, so salary stays minor units in the
API.
Adopting a table
An app's own employment type column, such as an enum, maps the labels of options.employmentTypes through values: values: { employees: { employmentType: { intern: "trainee" } } }, or {} when the enum uses the labels as they are.
An app with its own employees table keeps it: the module runs over it, maps its columns, and adds the columns it lacks unless you map them to null: email, jobTitle, team, employmentType, startDate, endDate, offboardReason, the origin columns and the timestamps are optional, and the module leaves out what needs them. privateDetails and contracts can be null as whole tables, and the private details' user and iban columns can be null.
First and last names
With options.name: "split", the module writes firstName and lastName
(first_name and last_name by default) instead of one name. create
takes firstName and lastName, or splits name at its first space;
update takes firstName, lastName and name (split the same way). The
full name is read from the name column when you map one, which the module
never writes, so make it a generated column:
full_name text generated always as (trim(first_name || coalesce(' ' || last_name, ''))) storedMap name to null when the table has no such column: reads, events and
the org chart order then join the two parts, and the record title and search
use firstName.
Flat private details
With options.privateDetails: "flat", the address and one emergency contact
live in plain columns: addressLine1, addressLine2, postalCode, city,
region, country, emergencyName, emergencyPhone and
emergencyRelation. Map the ones your table has and the rest, with address
and emergencyContacts, to null. savePrivateDetails takes either those
keys or the usual address object (line1, line2, postalCode, city,
region, country) and emergencyContacts list, whose first contact fills
the columns; reads return address and emergency_contacts built from them.
blocks: {
employees: {
tables: {
employees: "public.staff",
privateDetails: "public.staff_private",
contracts: "public.staff_contracts",
},
columns: {
employees: { name: "full_name", firstName: "first_name", lastName: "last_name" },
privateDetails: {
user: null, iban: null, address: null, emergencyContacts: null,
addressLine1: "home_line1", postalCode: "home_postal_code",
city: "home_city", country: "home_country",
addressLine2: null, region: null,
emergencyName: "emergency_name", emergencyPhone: "emergency_phone",
emergencyRelation: null,
},
contracts: { salaryPeriod: "pay_basis" },
},
values: { contracts: { salaryPeriod: { hour: "hourly", month: "monthly", year: "annual", week: null } } },
options: { name: "split", privateDetails: "flat", contracts: "editable" },
},
},Events
| Event | Data |
|---|---|
employee.created | organizationId, employeeId, subjectType, subjectId, name, userId, managerId, status |
employee.updated, employee.offboarded | the same without managerId and status, with fields (the changed fields, or contract) or endDate |
employee.manager_changed | the same, with fromManagerId and toManagerId; offboarding records one for each report that moves |
employee.purged | the same as employee.updated, without fields |
Every employee event carries userId, the employee's user account, or null
for an employee without one. A sink on employee.offboarded can use it to
hand over the user's files or end their sessions. The offboarding reason stays on the employee
(offboard_reason) and is not in the event, so it never reaches a webhook; a
consumer that needs it reads the employee.
Hooks
before_employee_create, after_employee_create, before_employee_update, after_employee_update, before_employee_offboard, after_employee_offboard, before_employee_purge and after_employee_purge run in the same transaction as the change. See extending blocks.
Errors
| Hint | Cause |
|---|---|
EMPLOYEE_FORBIDDEN | the caller lacks employees.write, or can't read the org chart |
EMPLOYEE_LINK_FORBIDDEN | setting userId without readSensitive and contractsRead |
EMPLOYEE_NOT_FOUND | no employee the caller can change or whose details they can see |
EMPLOYEE_ATTRS_INVALID | a missing name or a field with an invalid value |
EMPLOYEE_TYPE_INVALID | an employment type outside options.employmentTypes |
EMPLOYEE_STATUS_INVALID | a status other than preboarding, active or on_leave |
EMPLOYEE_USER_NOT_MEMBER | the user isn't a member of the organization |
EMPLOYEE_USER_TAKEN | the user is already an employee of the organization |
EMPLOYEE_MANAGER_NOT_FOUND | the manager isn't an employee of the organization |
EMPLOYEE_MANAGER_CYCLE | the manager reports to the employee |
EMPLOYEE_FIELD_UNKNOWN | a change names a field that can't be written |
EMPLOYEE_CHANGES_INVALID | changes isn't a list, or sends expectedUpdatedAt without updated_at |
EMPLOYEE_STALE | the employee changed since the expectedUpdatedAt the change sent |
EMPLOYEE_IN_USE | another row still points at the employee being deleted |
EMPLOYEE_ORIGIN_NOT_FOUND | no application the caller can turn into an employee |
EMPLOYEE_APPLICATION_NOT_HIRED | the application isn't hired |
EMPLOYEE_PRIVATE_INVALID | a private detail has an invalid value, such as a malformed IBAN |
EMPLOYEE_CONTRACT_INVALID | a contract without a start date, or with an invalid value |
EMPLOYEE_CONTRACT_OVERLAP | the contract starts on or before the latest one, or overlaps another with contractOverlap: "deny" |
EMPLOYEE_CONTRACT_NOT_FOUND | no contract the caller can change (editable contracts) |
Without the client
db.employees is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createEmployees } from "better-supabase/blocks/employees";
const employees = createEmployees({ transport });
const mia = await employees
.create(organizationId, {
name: "Mia de Vries",
userId,
jobTitle: "Designer",
managerId: leadId,
startDate: Temporal.PlainDate.from("2026-11-01"),
})
.orThrow();Last updated on
Hiring
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.
Qualifications
Certifications, licences and skills that members, companies and assets hold, with a validity, evidence, requirements, a gap report, the holders qualified on a date and expiry notifications.