Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(users): re-invite a deactivated employee instead of dead-ending (#1611)

BettrCallRaulaa8a0a7c6e02
diff --git a/.ai/lessons.md b/.ai/lessons.md
index e1cb383510..10278bb2f0 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3689,3 +3689,13 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Rule:** Keep one source for a fact. When a history exists, the current value is a row of it (here the open `workCenterLoad` row), not a second column to keep in step. Order writes against the history itself: refuse a write that is older than the newest boundary (any `loadedAt` or `unloadedAt`), and back it with constraints (a CHECK that an interval does not end before it starts, a partial unique index for one open row).
**Applies to:** `workCenterLoad` and its interceptors (`sync_load_work_center_operation`, `sync_unload_work_center_operation`), and any "current pointer + history" pair (statuses with a status log, assignments with an assignment history).
+
+## A unique index over a nullable column never deduplicated, and adding a real one breaks silent writers
+
+**Context:** Employee re-invite (2026-10-15). `membership` had `uq_membership ("groupId", "memberGroupId", "memberUserId")`, and every user membership has `memberGroupId` NULL.
+
+**Problem:** Under the default `NULLS DISTINCT`, rows with a NULL in the key never conflict, so the constraint that looked like it deduplicated user memberships never had. Writers inserted duplicates without error. A new unique index on `("groupId", "memberUserId")` made those same writers fail: the insert interceptors had no `ON CONFLICT`, and the employee-type change interceptor moved a membership onto a group the user was already in. Each would have failed the employee, customer-account or supplier-account write that fired it.
+
+**Rule:** Before adding a unique index, list every writer of the table, interceptors included, and give each one `ON CONFLICT … DO NOTHING` or a conflict-safe update in the same change. When a composite unique key includes a nullable column, assume it deduplicates nothing for rows where that column is NULL.
+
+**Applies to:** `membership` and its interceptors in `packages/database/src/event-system/handlers/`, and any unique key with a nullable column.
diff --git a/.claude/rules/user-employee-job-relationships.md b/.claude/rules/user-employee-job-relationships.md
index 32735a6eb0..814817575e 100644
--- a/.claude/rules/user-employee-job-relationships.md
+++ b/.claude/rules/user-employee-job-relationships.md
@@ -91,17 +91,68 @@ is the separate `job` table from `20240909194622_jobs.sql`).
- `userToCompany.role` (membership type) is distinct from `employeeType` (which permission set);
don't conflate "role" the enum with "role" the job title (`employeeJob.title`).
- Permission company-ID array `"0"` means "all companies" — don't string-match a literal company id only.
-- Deactivating an employee (`deactivateEmployee` in `users.server.ts`) removes the company from
- `userPermission.permissions`, deletes the `userToCompany` and `employeeJob` rows, sets
- `employee.active = false`, and invalidates the Redis claims cache. It does **not** clear
- `user.active` or scrub stored userId references (assignee columns, `workCenterEmployee`,
- notification-group settings arrays).
+- Deactivating an employee (`deactivateEmployee` in `packages/auth/src/services/users.server.ts`)
+ removes the company from `userPermission.permissions`, deletes the `userToCompany` row and every
+ `membership` in groups owned by that company, and sets `employee.active = false`.
+ It does **not** clear `user.active`, delete the `employee` or `employeeJob` rows, or scrub stored
+ userId references (assignee columns, `workCenterEmployee`, notification-group settings arrays).
+- **The claims cache is invalidated by the deactivate\* functions themselves**, not by their
+ callers. `deactivateEmployee`/`Customer`/`Supplier` each `redis.del(getPermissionCacheKey(userId))`
+ on success, and `deactivateUser` deletes it again after delegating. That matters because
+ `requirePermissions` reads the cache (1h TTL) before the database, and the `create*Account`
+ rollback paths in the ERP call the role-specific functions directly rather than going through
+ `deactivateUser` — a caller that skipped the invalidation would leave revoked grants live.
+ `employeeJob` is kept on purpose — it is org placement, not access — so title, start date,
+ department, shift, manager, location, tags and custom fields survive a deactivate/re-invite
+ round trip. Group memberships do not: acceptance restores only the employee-type group, so
+ a re-invited person must be added back to any custom group by hand. Because the row
+ survives, a reader of `employeeJob` that means "current staff" must also check
+ `employee.active` (`getScheduledEmployeesToday` does; `employeeJob` has no FK to `employee`
+ to embed).
- Planning stores more user ids the deactivation does not scrub: `itemPlanning.responsibleEmployee`,
`location.responsibleEmployee`, `companySettings.defaultResponsibleEmployee`,
`itemPostingGroupResponsibility.responsibleEmployee` and `planningAction.assignee` (all
`TEXT REFERENCES "user"("id")`, so the database accepts any user's id, including another
company's). A route saves one only after `isActiveCompanyEmployee(client, companyId, userId)`
(`apps/erp/app/modules/shared/shared.server.ts`), which fails closed on a read error.
+- Re-adding a deactivated person through Add Account (`createEmployeeAccount`) reuses the surviving
+ rows rather than failing: it refuses only when the existing `employee` row is `active`. A person
+ whose invite is still pending is re-added the same way, which issues a new code and invalidates
+ the link already emailed. The reuse path (`reinviteDeactivatedEmployee`) is one Kysely
+ transaction: it locks the `employee` row and re-checks `active` under the lock, updates
+ `employeeTypeId`, upserts `employeeJob` (only `locationId`, `updatedBy` and `updatedAt` on
+ conflict) and upserts the `invite` on `(email, companyId)` — so the invite's permissions and the
+ row's employee type cannot diverge, and a failed write leaves no redeemable invite. It never
+ inserts a first-time `employee` row; that stays under the caller's RLS client.
+- **The re-add writes outside RLS, so it checks what RLS would have.** The route requires only
+ `users_create`, but a first-time add inserts `employee` and `employeeJob` under the caller's
+ client, whose INSERT policies require `users_update` and `people_create`. Before the reuse
+ transaction, `createEmployeeAccount` reads the inviter's claims (`getUserClaims`) and refuses
+ unless both are held — otherwise a `users_create`-only admin could re-add someone they could
+ never have added. The writes stamp the inviter in `updatedBy` (`employeeJob`, `invite`) because
+ the Kysely connection has no `auth.uid()` for the audit log; `employee` has no audit columns.
+- **A re-used invite row restarts `createdAt`** (`insertInvite` and the reuse path both set it). The
+ controlled-environment expiry (`isControlledInviteExpired`) counts from it, and the reused row is
+ the person's original invite, so keeping it expired the new invite on arrival.
+- Re-activation happens on invite acceptance — `acceptInvite` (`apps/erp/app/modules/users/users.server.ts`) restores the
+ employee-type `membership` the deactivation removed (the `sync_add_employee_to_type_group` trigger
+ fires on INSERT only, so an UPDATE cannot rely on it), flips `active` back to true, and stamps
+ `acceptedAt` in one Kysely transaction, so a failed restore leaves the invite unaccepted and
+ retryable rather than an active employee outside their type's group. The `acceptedAt` update also
+ requires `revokedAt IS NULL`, so a revoke that commits after the invite was looked up still wins.
+ Before merging `userPermission`, the transaction locks the `user` row `FOR NO KEY UPDATE`
+ (`migrateUserToSso` does the same), so two first acceptances for one user in different companies
+ cannot drop each other's grants. The membership insert uses
+ `ON CONFLICT ("groupId", "memberUserId") DO NOTHING` against `membership_groupId_memberUserId_key`
+ (`20261015074817`), which is what makes it safe against the trigger racing the same insert.
+- **Every writer of a user membership must tolerate that index.** Before it, `uq_membership`
+ (`groupId, memberGroupId, memberUserId`) never deduped user memberships (`memberGroupId` is NULL
+ on all of them), so duplicates were silent. The insert interceptors
+ (`sync_add_employee_to_type_group`, `sync_add_customer_account_to_group`,
+ `sync_add_supplier_account_to_group`) use `ON CONFLICT … DO NOTHING`, and
+ `sync_update_employee_type_membership` drops the old membership instead of moving it when the
+ user is already in the new type's group (`20261015075112`). A new writer needs the same, or a
+ leftover membership fails the insert or update that fired it.
- Notification fan-out (`notify.ts` `resolve-recipients` in `packages/jobs`) filters resolved
recipients against `userToCompany` for the notification's company — a missing membership row
(i.e. a deactivated user) is dropped before any in-app/email/Slack delivery, regardless of how
diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.ts
index a724af369c..317104f57b 100644
--- a/apps/erp/app/modules/people/people.service.ts
+++ b/apps/erp/app/modules/people/people.service.ts
@@ -955,15 +955,25 @@ export async function getScheduledEmployeesToday(
client: SupabaseClient<Database>,
companyId: string
) {
- const { data } = await client
- .from("employeeJob")
- .select(
- "id, shiftId, shift:shift(id, name, startTime, endTime, sunday, monday, tuesday, wednesday, thursday, friday, saturday)"
- )
- .eq("companyId", companyId)
- .not("shiftId", "is", null);
+ // Deactivation keeps the employeeJob row (and its shift), so the roster is
+ // narrowed to active employees. employeeJob has no FK to employee to embed.
+ const [{ data }, { data: activeEmployees }] = await Promise.all([
+ client
+ .from("employeeJob")
+ .select(
+ "id, shiftId, shift:shift(id, name, startTime, endTime, sunday, monday, tuesday, wednesday, thursday, friday, saturday)"
+ )
+ .eq("companyId", companyId)
+ .not("shiftId", "is", null),
+ client
+ .from("employee")
+ .select("id")
+ .eq("companyId", companyId)
+ .eq("active", true)
+ ]);
- if (!data) return [];
+ if (!data || !activeEmployees) return [];
+ const activeIds = new Set(activeEmployees.map((e) => e.id));
const dayNames = [
"sunday",
@@ -981,7 +991,7 @@ export async function getScheduledEmployeesToday(
return data.filter((ej) => {
const shift = ej.shift as Record<string, unknown> | null;
- return shift && shift[dayName] === true;
+ return activeIds.has(ej.id) && shift && shift[dayName] === true;
});
}
diff --git a/apps/erp/app/modules/users/users.server.test.ts b/apps/erp/app/modules/users/users.server.test.ts
new file mode 100644
index 0000000000..fec7c97441
--- /dev/null
+++ b/apps/erp/app/modules/users/users.server.test.ts
@@ -0,0 +1,566 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { CompiledQuery, DatabaseConnection, Driver } from "kysely";
+import {
+ Kysely,
+ PostgresAdapter,
+ PostgresIntrospector,
+ PostgresQueryCompiler
+} from "kysely";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// users.server pulls in auth, SSO, Redis and two module barrels at import
+// time. Everything createEmployeeAccount and acceptInvite do not exercise is
+// stubbed; the parts they do are recorded so each test can assert on which
+// writes ran and through which client.
+const mocks = vi.hoisted(() => ({
+ deactivateEmployee: vi.fn(),
+ deleteAuthAccount: vi.fn(),
+ getDatabaseClient: vi.fn(),
+ getPermissionsByEmployeeType: vi.fn(),
+ getUserClaims: vi.fn(),
+ insertEmployeeJob: vi.fn(),
+ mergeInvitePermissions: vi.fn(() => ({})),
+ serviceRoleWrites: [] as { table: string; op: string; payload: unknown }[]
+}));
+
+// hasPermission stays real: the re-add path's permission check is under test.
+// It is read from its source file because the package root pulls in Lingui
+// macros that only run inside the app build.
+vi.mock("@carbon/auth", async () => ({
+ CONTROLLED_ENVIRONMENT: false,
+ error: vi.fn(),
+ success: vi.fn(),
+ hasPermission: (
+ await vi.importActual<
+ typeof import("../../../../../packages/auth/src/services/users")
+ >("../../../../../packages/auth/src/services/users")
+ ).hasPermission
+}));
+
+vi.mock("@carbon/auth/auth.server", () => ({
+ deleteAuthAccount: mocks.deleteAuthAccount
+}));
+
+vi.mock("@carbon/auth/auth-events.server", () => ({
+ logPermissionChange: vi.fn()
+}));
+
+vi.mock("@carbon/auth/client.server", () => ({
+ getCarbonServiceRole: () => ({
+ from: (table: string) => {
+ const chain: Record<string, unknown> = {
+ select: () => chain,
+ eq: () => chain,
+ single: () =>
+ Promise.resolve(
+ table === "user"
+ ? { data: { id: USER, email: EMAIL }, error: null }
+ : { data: null, error: null }
+ ),
+ // The employee type and location ownership checks: both belong to
+ // the company in every test here.
+ maybeSingle: () =>
+ Promise.resolve(
+ table === "employeeType" || table === "location"
+ ? { data: { id: table }, error: null }
+ : { data: null, error: null }
+ ),
+ upsert: (payload: unknown) => {
+ mocks.serviceRoleWrites.push({ table, op: "upsert", payload });
+ return chain;
+ }
+ };
+ return chain;
+ },
+ auth: {
+ admin: { getUserById: () => Promise.resolve({ error: null }) }
+ }
+ })
+}));
+
+vi.mock("@carbon/auth/session.server", () => ({
+ flash: vi.fn(),
+ requireAuthSession: vi.fn()
+}));
+
+vi.mock("@carbon/auth/users.server", () => ({
+ deactivateCustomer: vi.fn(),
+ deactivateEmployee: mocks.deactivateEmployee,
+ deactivateSupplier: vi.fn(),
+ getUserClaims: mocks.getUserClaims
+}));
+
+vi.mock("@carbon/kv", () => ({
+ redis: { del: vi.fn(), get: vi.fn(), set: vi.fn() }
+}));
+
+vi.mock("@carbon/ee/sso.server", () => ({
+ emailDomain: vi.fn(),
+ getSsoConnection: vi.fn(),
+ getSsoConnectionByDomain: vi.fn(),
+ isSsoEnabled: () => false,
+ mergeInvitePermissions: mocks.mergeInvitePermissions,
+ seedSsoIdentityForUser: vi.fn(),
+ uncoveredSsoDomainError: vi.fn()
+}));
+
+vi.mock("@carbon/logger", () => ({
+ getLogger: () => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn()
+ })
+}));
+
+vi.mock("~/modules/purchasing", () => ({ getSupplierContact: vi.fn() }));
+vi.mock("~/modules/sales", () => ({ getCustomerContact: vi.fn() }));
+vi.mock("~/modules/users", () => ({
+ getPermissionsByEmployeeType: mocks.getPermissionsByEmployeeType
+}));
+vi.mock("~/services/database.server", () => ({
+ getDatabaseClient: mocks.getDatabaseClient
+}));
+vi.mock("~/utils/path", () => ({ path: { to: {} } }));
+vi.mock("../people/people.service", () => ({
+ insertEmployeeJob: mocks.insertEmployeeJob
+}));
+
+const { acceptInvite, createEmployeeAccount } = await import("./users.server");
+
+const USER = "usr_1";
+const COMPANY = "cmp_1";
+const EMAIL = "[email protected]";
+const NEW_TYPE = "et_new";
+
+const ACCOUNT = {
+ email: EMAIL,
+ firstName: "Pat",
+ lastName: "Doe",
+ employeeType: NEW_TYPE,
+ locationId: "loc_1",
+ companyId: COMPANY,
+ createdBy: "usr_admin"
+};
+
+type Statement = { sql: string; parameters: readonly unknown[] };
+
+/**
+ * Drives Kysely's real Postgres compiler through a fake driver, so the tests
+ * see the SQL the transaction would send and whether it committed or rolled
+ * back. `respond` answers each statement, or throws to simulate a failed write.
+ * Nothing reaches a database: a rollback here proves Kysely issued one and
+ * stopped executing, not what Postgres did with it.
+ */
+function makeDb(respond: (statement: Statement) => unknown[]) {
+ const statements: Statement[] = [];
+ const transactions = { begin: 0, commit: 0, rollback: 0 };
+ const connection: DatabaseConnection = {
+ async executeQuery(query: CompiledQuery) {
+ const statement = { sql: query.sql, parameters: query.parameters };
+ statements.push(statement);
+ return { rows: respond(statement) } as never;
+ },
+ async *streamQuery() {}
+ };
+ const driver: Driver = {
+ async init() {},
+ async acquireConnection() {
+ return connection;
+ },
+ async beginTransaction() {
+ transactions.begin++;
+ },
+ async commitTransaction() {
+ transactions.commit++;
+ },
+ async rollbackTransaction() {
+ transactions.rollback++;
+ },
+ async releaseConnection() {},
+ async destroy() {}
+ };
+ const db = new Kysely<Record<string, never>>({
+ dialect: {
+ createAdapter: () => new PostgresAdapter(),
+ createDriver: () => driver,
+ createIntrospector: (kysely) => new PostgresIntrospector(kysely),
+ createQueryCompiler: () => new PostgresQueryCompiler()
+ }
+ });
+ return { db, statements, transactions };
+}
+
+/** The caller's RLS client: answers the pre-read and records inserts. */
+function makeClient(
+ existingEmployee: { id: string; active: boolean } | null,
+ readError: { message: string } | null = null
+) {
+ const writes: { table: string; op: string; payload: unknown }[] = [];
+ const client = {
+ from: (table: string) => {
+ const chain: Record<string, unknown> = {
+ select: () => chain,
+ eq: () => chain,
+ maybeSingle: () =>
+ Promise.resolve(
+ readError
+ ? { data: null, error: readError }
+ : { data: existingEmployee, error: null }
+ ),
+ single: () => Promise.resolve({ data: {}, error: null }),
+ insert: (payload: unknown) => {
+ writes.push({ table, op: "insert", payload });
+ return chain;
+ }
+ };
+ return chain;
+ }
+ };
+ return { client: client as never, writes };
+}
+
+const deactivated = { id: USER, active: false };
+
+function answer(lockedRow: { active: boolean } | null) {
+ return ({ sql }: Statement) =>
+ sql.startsWith('select "active" from "employee"') && lockedRow
+ ? [lockedRow]
+ : [];
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.serviceRoleWrites.length = 0;
+ mocks.getPermissionsByEmployeeType.mockResolvedValue({
+ data: [
+ {
+ module: "Sales",
+ view: [COMPANY],
+ create: [COMPANY],
+ update: [],
+ delete: []
+ }
+ ],
+ error: null
+ });
+ mocks.insertEmployeeJob.mockResolvedValue({ data: {}, error: null });
+ // The inviter may do everything a first-time add needs.
+ mocks.getUserClaims.mockResolvedValue({
+ role: "employee",
+ permissions: {
+ users: { view: [], create: [COMPANY], update: [COMPANY], delete: [] },
+ people: { view: [], create: [COMPANY], update: [], delete: [] }
+ }
+ });
+});
+
+describe("createEmployeeAccount — re-adding a deactivated employee", () => {
+ it("writes the employee type, placement and invite in one committed transaction", async () => {
+ const { db, statements, transactions } = makeDb(answer(deactivated));
+ mocks.getDatabaseClient.mockReturnValue(db);
+ const { client, writes } = makeClient(deactivated);
+
+ const result = await createEmployeeAccount(client, ACCOUNT);
+
+ expect(result).toMatchObject({ success: true, userId: USER });
+ if (!result.success) throw new Error(result.message);
+ expect(transactions).toEqual({ begin: 1, commit: 1, rollback: 0 });
+
+ const [lock, employee, job, invite] = statements;
+ expect(statements).toHaveLength(4);
+ expect(lock.sql).toMatch(/from "employee" .* for update$/);
+ expect(lock.parameters).toEqual([USER, COMPANY]);
+ expect(employee.sql).toMatch(/^update "employee" set "employeeTypeId" =/);
+ expect(employee.parameters).toEqual([NEW_TYPE, USER, COMPANY]);
+ expect(job.sql).toMatch(
+ /^insert into "employeeJob" .* on conflict \("id", "companyId"\) do update set "locationId" =/
+ );
+ expect(invite.sql).toMatch(
+ /^insert into "invite" .* on conflict \("email", "companyId"\) do update set/
+ );
+ expect(invite.sql).toMatch(/"acceptedAt" = \$\d+, "revokedAt" = \$\d+$/);
+
+ // The invite carries the permissions of the SAME type written to the
+ // employee row, under the code returned to the caller.
+ const permissions = JSON.parse(invite.parameters[1] as string);
+ expect(permissions).toEqual({
+ sales_view: [COMPANY],
+ sales_create: [COMPANY],
+ sales_update: [],
+ sales_delete: []
+ });
+ expect(invite.parameters).toContain(result.code);
+ expect(mocks.getPermissionsByEmployeeType).toHaveBeenCalledWith(
+ client,
+ NEW_TYPE
+ );
+
+ // Nothing went through the non-transactional clients.
+ expect(writes).toEqual([]);
+ expect(mocks.serviceRoleWrites).toEqual([]);
+ expect(mocks.insertEmployeeJob).not.toHaveBeenCalled();
+ });
+
+ it("rolls back and writes nothing further when the employee write fails", async () => {
+ const { db, statements, transactions } = makeDb((statement) => {
+ if (statement.sql.startsWith('update "employee"')) {
+ throw new Error("employee write failed");
+ }
+ return answer(deactivated)(statement);
+ });
+ mocks.getDatabaseClient.mockReturnValue(db);
+ const { client } = makeClient(deactivated);
+
+ const result = await createEmployeeAccount(client, ACCOUNT);
+
+ expect(result).toEqual({
+ success: false,
+ message: "employee write failed"
+ });
+ expect(transactions).toEqual({ begin: 1, commit: 0, rollback: 1 });
+ // No placement or invite statement ran after the failure, so no
+ // redeemable invite can outlive it.
+ expect(statements.map((s) => s.sql.split(" ")[0])).toEqual([
+ "select",
+ "update"
+ ]);
+ expect(mocks.serviceRoleWrites).toEqual([]);
+ // A rollback needs no compensation, and deactivating here would strip
+ // whatever this person still holds in the company.
+ expect(mocks.deactivateEmployee).not.toHaveBeenCalled();
+ expect(mocks.deleteAuthAccount).not.toHaveBeenCalled();
+ });
+
+ it("rolls back the employee and placement writes when the invite write fails", async () => {
+ const { db, statements, transactions } = makeDb((statement) => {
+ if (statement.sql.startsWith('insert into "invite"')) {
+ throw new Error("invite write failed");
+ }
+ return answer(deactivated)(statement);
+ });
+ mocks.getDatabaseClient.mockReturnValue(db);
+ const { client } = makeClient(deactivated);
+
+ const result = await createEmployeeAccount(client, ACCOUNT);
+
+ expect(result).toEqual({ success: false, message: "invite write failed" });
+ expect(statements).toHaveLength(4);
+ expect(transactions).toEqual({ begin: 1, commit: 0, rollback: 1 });
+ expect(mocks.deactivateEmployee).not.toHaveBeenCalled();
+ expect(mocks.deleteAuthAccount).not.toHaveBeenCalled();
+ });
+
+ it("refuses under the lock when the employee was activated since the pre-read", async () => {
+ const { db, statements, transactions } = makeDb(answer({ active: true }));
+ mocks.getDatabaseClient.mockReturnValue(db);
+ const { client } = makeClient(deactivated);
+
+ const result = await createEmployeeAccount(client, ACCOUNT);
+
+ expect(result).toEqual({
+ success: false,
+ message: "This user is already an employee in this company"
+ });
+ expect(statements).toHaveLength(1);
+ expect(transactions).toEqual({ begin: 1, commit: 0, rollback: 1 });
+ });
+
+ it("refuses rather than inserting when the row disappeared since the pre-read", async () => {
+ const { db, statements, transactions } = makeDb(answer(null));
+ mocks.getDatabaseClient.mockReturnValue(db);
+ const { client } = makeClient(deactivated);
+
+ const result = await createEmployeeAccount(client, ACCOUNT);
+
+ expect(result.success).toBe(false);
+ // Only the lock ran: a first-time employee insert never happens outside
+ // the caller's RLS client.
+ expect(statements).toHaveLength(1);
+ expect(transactions.rollback).toBe(1);
+ });
+});
+
+describe("createEmployeeAccount — re-add guards", () => {
+ it("restarts the reused invite's createdAt, which the controlled-environment expiry counts from", async () => {
+ const { db, statements } = makeDb(answer(deactivated));
+ mocks.getDatabaseClient.mockReturnValue(db);
+ const { client } = makeClient(deactivated);
+
+ const result = await createEmployeeAccount(client, ACCOUNT);
+
+ expect(result.success).toBe(true);
+ const invite = statements.find((s) =>
+ s.sql.startsWith('insert into "invite"')
+ );
+ const onConflict = invite?.sql.split(" do update set ")[1] ?? "";
+ // The reused row is the original invite, usually long since accepted.
+ expect(onConflict).toMatch(/"createdAt" = \$\d+/);
+ expect(onConflict).toMatch(/"updatedBy" = \$\d+/);
+ });
+
+ it("refuses an inviter who could not add the person the first time", async () => {
+ // users_create only: a first-time add's RLS inserts need users_update and
+ // people_create, so the RLS-bypassing re-add must not succeed either.
+ mocks.getUserClaims.mockResolvedValue({
+ role: "employee",
+ permissions: {
+ users: { view: [], create: [COMPANY], update: [], delete: [] },
+ people: { view: [], create: [COMPANY], update: [], delete: [] }
+ }
+ });
+ const { db, transactions } = makeDb(answer(deactivated));
+ mocks.getDatabaseClient.mockReturnValue(db);
+ const { client, writes } = makeClient(deactivated);
+
+ const result = await createEmployeeAccount(client, ACCOUNT);
+
+ expect(result).toEqual({
+ success: false,
+ message:
+ "Re-adding a deactivated employee requires the Users update and People create permissions"
+ });
+ expect(mocks.getUserClaims).toHaveBeenCalledWith(
+ ACCOUNT.createdBy,
+ COMPANY
+ );
+ expect(transactions.begin).toBe(0);
+ expect(writes).toEqual([]);
+ expect(mocks.serviceRoleWrites).toEqual([]);
+ });
+});
+
+describe("createEmployeeAccount — the existing-employee read fails", () => {
+ it("returns the error before any write path starts", async () => {
+ const { db, transactions } = makeDb(() => []);
+ mocks.getDatabaseClient.mockReturnValue(db);
+ const { client, writes } = makeClient(null, { message: "read failed" });
+
+ const result = await createEmployeeAccount(client, ACCOUNT);
+
+ expect(result).toEqual({ success: false, message: "read failed" });
+ // Neither the re-invite transaction nor the first-time writes ran, so no
+ // redeemable invite was written beside a failed employee insert.
+ expect(transactions.begin).toBe(0);
+ expect(writes).toEqual([]);
+ expect(mocks.serviceRoleWrites).toEqual([]);
+ expect(mocks.insertEmployeeJob).not.toHaveBeenCalled();
+ });
+});
+
+describe("createEmployeeAccount — first time in the company", () => {
+ it("keeps writing through the caller's RLS client, outside any transaction", async () => {
+ const { db, transactions } = makeDb(() => []);
+ mocks.getDatabaseClient.mockReturnValue(db);
+ const { client, writes } = makeClient(null);
+
+ const result = await createEmployeeAccount(client, ACCOUNT);
+
+ expect(result).toMatchObject({ success: true, userId: USER });
+ expect(transactions.begin).toBe(0);
+ expect(writes).toEqual([
+ {
+ table: "employee",
+ op: "insert",
+ payload: [
+ {
+ id: USER,
+ employeeTypeId: NEW_TYPE,
+ active: false,
+ companyId: COMPANY
+ }
+ ]
+ }
+ ]);
+ expect(mocks.insertEmployeeJob).toHaveBeenCalledWith(client, {
+ id: USER,
+ companyId: COMPANY,
+ locationId: "loc_1"
+ });
+ expect(mocks.serviceRoleWrites).toMatchObject([
+ { table: "invite", op: "upsert" }
+ ]);
+ });
+});
+
+describe("acceptInvite", () => {
+ const INVITE = {
+ id: "inv_1",
+ code: "code_1",
+ email: EMAIL,
+ companyId: COMPANY,
+ role: "employee",
+ permissions: {},
+ createdAt: "2026-10-01T00:00:00Z",
+ acceptedAt: null,
+ revokedAt: null
+ };
+
+ /** The service-role client acceptInvite looks the invite up with. */
+ function makeInviteLookup() {
+ const chain: Record<string, unknown> = {
+ select: () => chain,
+ eq: () => chain,
+ is: () => chain,
+ single: () => Promise.resolve({ data: INVITE, error: null })
+ };
+ return { from: () => chain } as never;
+ }
+
+ /** `acceptedRow` is what the guarded invite update returns: none = lost. */
+ function answerAccept(acceptedRow: typeof INVITE | null) {
+ return ({ sql }: Statement) => {
+ if (sql.startsWith('select "id", "employeeTypeId" from "employee"')) {
+ return [{ id: USER, employeeTypeId: "et_1" }];
+ }
+ if (sql.startsWith('select "id" from "user"')) return [{ id: USER }];
+ if (sql.startsWith('update "invite"')) {
+ return acceptedRow ? [acceptedRow] : [];
+ }
+ return [];
+ };
+ }
+
+ it("locks the user row before reading the permissions it merges into", async () => {
+ const { db, statements, transactions } = makeDb(answerAccept(INVITE));
+ mocks.getDatabaseClient.mockReturnValue(db);
+
+ const result = await acceptInvite(makeInviteLookup(), INVITE.code, EMAIL);
+
+ expect(result.error).toBeNull();
+ expect(transactions).toEqual({ begin: 1, commit: 1, rollback: 0 });
+ const lock = statements.findIndex((s) =>
+ /^select "id" from "user" where "id" = \$1 for no key update$/.test(s.sql)
+ );
+ const read = statements.findIndex((s) =>
+ s.sql.startsWith('select "permissions" from "userPermission"')
+ );
+ expect(lock).toBeGreaterThanOrEqual(0);
+ expect(statements[lock].parameters).toEqual([USER]);
+ expect(lock).toBeLessThan(read);
+ });
+
+ it("does not accept an invite revoked after it was looked up", async () => {
+ const { db, statements, transactions } = makeDb(answerAccept(null));
+ mocks.getDatabaseClient.mockReturnValue(db);
+
+ const result = await acceptInvite(makeInviteLookup(), INVITE.code, EMAIL);
+
+ expect(result).toEqual({
+ data: null,
+ error: {
+ message: "This invite has already been accepted or was revoked."
+ }
+ });
+ // The activation, membership and permission writes before the guard are
+ // rolled back with it.
+ expect(transactions).toEqual({ begin: 1, commit: 0, rollback: 1 });
+ const update = statements.find((s) => s.sql.startsWith('update "invite"'));
+ expect(update?.sql).toMatch(
+ /"companyId" = \$\d+ and "acceptedAt" is null and "revokedAt" is null/
+ );
+ });
+});
diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.ts
index f595090500..8e14f72b01 100644
--- a/apps/erp/app/modules/users/users.server.ts
+++ b/apps/erp/app/modules/users/users.server.ts
@@ -2,16 +2,18 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { CONTROLLED_ENVIRONMENT, error } from "@carbon/auth";
+import { CONTROLLED_ENVIRONMENT, error, hasPermission } from "@carbon/auth";
import { deleteAuthAccount } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash, requireAuthSession } from "@carbon/auth/session.server";
import {
deactivateCustomer,
deactivateEmployee,
- deactivateSupplier
+ deactivateSupplier,
+ getUserClaims
} from "@carbon/auth/users.server";
import type { Database } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { redis } from "@carbon/kv";
import { now, parseAbsolute } from "@internationalized/date";
@@ -25,11 +27,14 @@ import {
getSsoConnection,
getSsoConnectionByDomain,
isSsoEnabled,
+ // Shared with migrateUserToSso on purpose: both paths merge an invite's
+ // permissions into userPermission, and they must not drift.
+ mergeInvitePermissions,
seedSsoIdentityForUser,
uncoveredSsoDomainError
} from "@carbon/ee/sso.server";
import { getLogger } from "@carbon/logger";
-import { redirect } from "@carbon/utils";
+import { datetime, redirect } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { getSupplierContact } from "~/modules/purchasing";
import { getCustomerContact } from "~/modules/sales";
@@ -124,16 +129,7 @@ export async function acceptInvite(
const user = await getUserByEmail(invite.data.email);
if (user.error) return user;
- const activationFunction =
- invite.data.role === "employee"
- ? activateEmployee
- : invite.data.role === "customer"
- ? activateCustomer
- : invite.data.role === "supplier"
- ? activateSupplier
- : null;
-
- if (!activationFunction) {
+ if (!["employee", "customer", "supplier"].includes(invite.data.role)) {
return {
data: null,
error: {
@@ -142,145 +138,186 @@ export async function acceptInvite(
};
}
- const [activate, addUser, setPermissions] = await Promise.all([
- activationFunction(serviceRole, {
- userId: user.data.id,
- companyId: invite.data.companyId
- }),
- addUserToCompany(serviceRole, {
- userId: user.data.id,
- companyId: invite.data.companyId,
- role: invite.data.role
- }),
- setUserPermissions(
- serviceRole,
- user.data.id,
- invite.data.permissions as Record<string, string[]>
- )
- ]);
-
- if (activate.error) {
- logger.error("Failed to activate invite", { error: activate.error });
- await rollbackInvite(serviceRole, {
- userId: user.data.id,
- companyId: invite.data.companyId
- });
- return activate;
- }
-
- if (addUser.error) {
- logger.error("Failed to add user to company", { error: addUser.error });
- await rollbackInvite(serviceRole, {
- userId: user.data.id,
- companyId: invite.data.companyId
- });
- return addUser;
- }
-
- if (setPermissions.error) {
- logger.error("Failed to set user permissions", {
- error: setPermissions.error
- });
- await rollbackInvite(serviceRole, {
- userId: user.data.id,
- companyId: invite.data.companyId
- });
- return setPermissions;
- }
-
- return serviceRole
- .from("invite")
- .update({ acceptedAt: new Date().toISOString() })
- .eq("code", code)
- .select("*")
- .single();
-}
-
-async function activateCustomer(
- client: SupabaseClient<Database>,
- {
- userId,
- companyId
- }: {
- userId: string;
- companyId: string;
- }
-) {
- const result = await client
- .from("customerAccount")
- .update({ active: true })
- .eq("id", userId)
- .eq("companyId", companyId)
- .select("id");
-
- if (!result.error && (!result.data || result.data.length === 0)) {
- return {
- data: null,
- error: {
- message: `Customer account not found for user ${userId} in company ${companyId}. The account may have been deleted during deactivation.`
+ const userId = user.data.id;
+ const { companyId, role } = invite.data;
+
+ // Account activation, company membership, the permission merge and the
+ // acceptedAt stamp are one unit of work. They used to run as three
+ // concurrent writes followed by a compensating rollbackInvite, which could
+ // not undo what it had not yet written and silently mismatched the
+ // customer/supplier account keys. A transaction removes the half-states
+ // instead of trying to repair them: nothing is visible unless all of it
+ // commits. Mirrors migrateUserToSso, the SSO path that has to finish the
+ // same work.
+ const db = getDatabaseClient();
+
+ try {
+ const acceptedInvite = await db.transaction().execute(async (trx) => {
+ switch (role) {
+ case "employee": {
+ // Deactivation dropped this membership and the trigger that seeds it
+ // only fires on INSERT, so reactivation has to restore it. Done before
+ // the active flip and inside the transaction: an employee is never
+ // visible as active while outside their employee type's group.
+ const employee = await trx
+ .selectFrom("employee")
+ .select(["id", "employeeTypeId"])
+ .where("id", "=", userId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+
+ if (!employee) {
+ throw new Error(
+ `Employee record not found for user ${userId} in company ${companyId}. The record may have been deleted during deactivation.`
+ );
+ }
+
+ if (employee.employeeTypeId) {
+ await trx
+ .insertInto("membership")
+ .values({
+ groupId: employee.employeeTypeId,
+ memberUserId: userId
+ })
+ .onConflict((oc) =>
+ oc.columns(["groupId", "memberUserId"]).doNothing()
+ )
+ .execute();
+ }
+
+ await trx
+ .updateTable("employee")
+ .set({ active: true })
+ .where("id", "=", userId)
+ .where("companyId", "=", companyId)
+ .execute();
+ break;
+ }
+ case "customer": {
+ const customerAccount = await trx
+ .updateTable("customerAccount")
+ .set({ active: true })
+ .where("id", "=", userId)
+ .where("companyId", "=", companyId)
+ .returning("id")
+ .executeTakeFirst();
+
+ if (!customerAccount) {
+ throw new Error(
+ `Customer account not found for user ${userId} in company ${companyId}. The account may have been deleted during deactivation.`
+ );
+ }
+ break;
+ }
+ case "supplier": {
+ const supplierAccount = await trx
+ .updateTable("supplierAccount")
+ .set({ active: true })
+ .where("id", "=", userId)
+ .where("companyId", "=", companyId)
+ .returning("id")
+ .executeTakeFirst();
+
+ if (!supplierAccount) {
+ throw new Error(
+ `Supplier account not found for user ${userId} in company ${companyId}. The account may have been deleted during deactivation.`
+ );
+ }
+ break;
+ }
+ default: {
+ // A new "role" enum value fails typecheck here until it is handled,
+ // instead of being activated as a supplier.
+ const unhandled: never = role;
+ throw new Error(`Invalid invite role: ${unhandled}`);
+ }
}
- };
- }
- return result;
-}
-
-async function activateEmployee(
- client: SupabaseClient<Database>,
- {
- userId,
- companyId
- }: {
- userId: string;
- companyId: string;
- }
-) {
- const result = await client
- .from("employee")
- .update({ active: true })
- .eq("id", userId)
- .eq("companyId", companyId)
- .select("id");
+ await trx
+ .insertInto("userToCompany")
+ .values({ userId, companyId, role })
+ .onConflict((oc) => oc.columns(["userId", "companyId"]).doNothing())
+ .execute();
+
+ // Serialize on the user row before the read-merge-write below. The
+ // userPermission lock alone holds nothing while that row is absent, so
+ // two first acceptances for this user in different companies could both
+ // merge from {} and the later upsert would drop the earlier grant.
+ // NO KEY UPDATE, not UPDATE: foreign-key checks from rows that reference
+ // the user (createdBy and the like) are not blocked.
+ await trx
+ .selectFrom("user")
+ .select("id")
+ .where("id", "=", userId)
+ .forNoKeyUpdate()
+ .executeTakeFirstOrThrow();
+
+ // setUserPermissions semantics, but under a row lock so two concurrent
+ // grants cannot lose one another's writes.
+ const currentPermission = await trx
+ .selectFrom("userPermission")
+ .select("permissions")
+ .where("id", "=", userId)
+ .forUpdate()
+ .executeTakeFirst();
+
+ const mergedPermissions = JSON.stringify(
+ mergeInvitePermissions(
+ (currentPermission?.permissions ?? {}) as Record<string, string[]>,
+ (invite.data.permissions ?? {}) as Record<string, string[]>
+ )
+ );
- if (!result.error && (!result.data || result.data.length === 0)) {
- return {
- data: null,
- error: {
- message: `Employee record not found for user ${userId} in company ${companyId}. The record may have been deleted during deactivation.`
+ await trx
+ .insertInto("userPermission")
+ .values({ id: userId, permissions: mergedPermissions })
+ .onConflict((oc) =>
+ oc.column("id").doUpdateSet({ permissions: mergedPermissions })
+ )
+ .execute();
+
+ // Guarded so a concurrent acceptance can never apply twice, and so a
+ // revoke that committed after the lookup above still wins.
+ const accepted = await trx
+ .updateTable("invite")
+ .set({ acceptedAt: datetime.timestamp() })
+ .where("code", "=", code)
+ .where("companyId", "=", companyId)
+ .where("acceptedAt", "is", null)
+ .where("revokedAt", "is", null)
+ .returningAll()
+ .executeTakeFirst();
+
+ if (!accepted) {
+ throw new Error(
+ "This invite has already been accepted or was revoked."
+ );
}
- };
- }
- return result;
-}
+ return accepted;
+ });
-async function activateSupplier(
- client: SupabaseClient<Database>,
- {
- userId,
- companyId
- }: {
- userId: string;
- companyId: string;
- }
-) {
- const result = await client
- .from("supplierAccount")
- .update({ active: true })
- .eq("id", userId)
- .eq("companyId", companyId)
- .select("id");
+ // Post-commit and failure-tolerant: the grants just written are cached by
+ // requirePermissions, so a stale entry would outlive the acceptance.
+ try {
+ await redis.del(getPermissionCacheKey(userId));
+ } catch (err) {
+ logger.error(
+ "Failed to invalidate permission cache after invite accept",
+ { error: err, userId }
+ );
+ }
- if (!result.error && (!result.data || result.data.length === 0)) {
+ return { data: acceptedInvite, error: null };
+ } catch (err) {
+ logger.error("Failed to accept invite", { error: err, userId, companyId });
return {
data: null,
error: {
- message: `Supplier account not found for user ${userId} in company ${companyId}. The account may have been deleted during deactivation.`
+ message: err instanceof Error ? err.message : "Failed to accept invite"
}
};
}
-
- return result;
}
export async function addUserToCompany(
@@ -534,6 +571,7 @@ export async function createEmployeeAccount(
const user = await getUserByEmail(email);
let userId = "";
let isNewUser = false;
+ let isReactivation = false;
if (user.data) {
userId = user.data.id;
@@ -547,17 +585,37 @@ export async function createEmployeeAccount(
const existingEmployee = await client
.from("employee")
- .select("id")
+ .select("id, active")
.eq("id", userId)
.eq("companyId", companyId)
.maybeSingle();
- if (existingEmployee.data) {
+ // A failed read must not fall through to the first-time path: there the
+ // invite upsert can succeed beside a failing employee insert and leave a
+ // redeemable invite behind.
+ if (existingEmployee.error) {
+ logger.error("Failed to read the existing employee row", {
+ companyId,
+ userId,
+ error: existingEmployee.error
+ });
+ return { success: false, message: existingEmployee.error.message };
+ }
+
+ // Only an *active* employee is genuinely already a member. An inactive row
+ // is the residue of a deactivation or a revoked invite: deactivation keeps
+ // the "employee" row (and now the "employeeJob" row too), so refusing here
+ // dead-ended re-adding someone — the blocking record is also hidden by the
+ // employee list's default Active/Invited filter, leaving no way to act on
+ // the error. reinviteDeactivatedEmployee reuses those rows instead.
+ if (existingEmployee.data?.active) {
return {
success: false,
message: "This user is already an employee in this company"
};
}
+
+ isReactivation = Boolean(existingEmployee.data);
} else {
isNewUser = true;
const resolvedId = await resolveAuthUserId(email);
@@ -583,6 +641,78 @@ export async function createEmployeeAccount(
}
const code = crypto.randomUUID();
+ const invite = {
+ role: "employee",
+ permissions,
+ email,
+ companyId,
+ createdBy,
+ code,
+ attestedBy: attestedBy ?? null,
+ attestedAt: attestedAt ?? null
+ } satisfies InviteInsert;
+
+ if (isReactivation) {
+ // Reusing surviving rows is an UPDATE, which RLS would gate behind
+ // users_update / people_update, so this path writes outside RLS, scoped by
+ // id + companyId. It is one transaction because the three writes are only
+ // correct together (see the helper), and it needs no compensation: the
+ // auth user already existed, so a rollback leaves nothing behind.
+ //
+ // Writing outside RLS must not grant more than a first-time add, which
+ // inserts under the caller's client: the INSERT policies on "employee" and
+ // "employeeJob" require users_update and people_create. The route only
+ // requires users_create, so the same two are checked here.
+ const claims = await getUserClaims(createdBy, companyId).catch(
+ (err: unknown) => {
+ logger.error("Failed to read the inviter's permissions", {
+ companyId,
+ createdBy,
+ error: err
+ });
+ return null;
+ }
+ );
+ if (
+ !hasPermission(claims?.permissions, "users", "update", companyId) ||
+ !hasPermission(claims?.permissions, "people", "create", companyId)
+ ) {
+ logger.error("Re-adding a deactivated employee was refused", {
+ companyId,
+ userId,
+ createdBy
+ });
+ return {
+ success: false,
+ message:
+ "Re-adding a deactivated employee requires the Users update and People create permissions"
+ };
+ }
+
+ try {
+ await reinviteDeactivatedEmployee(getDatabaseClient(), {
+ userId,
+ companyId,
+ employeeTypeId: employeeType,
+ locationId,
+ invite
+ });
+ } catch (err) {
+ logger.error("Failed to re-invite employee", {
+ error: err,
+ userId,
+ companyId
+ });
+ return {
+ success: false,
+ message:
+ err instanceof Error ? err.message : "Failed to re-invite employee"
+ };
+ }
+
+ return { success: true, code, userId };
+ }
+
const [employeeInsert, jobInsert, inviteInsert] = await Promise.all([
insertEmployee(client, {
id: userId,
@@ -595,16 +725,7 @@ export async function createEmployeeAccount(
companyId,
locationId
}),
- insertInvite(serviceRole, {
- role: "employee",
- permissions,
- email,
- companyId,
- createdBy,
- code,
- attestedBy: attestedBy ?? null,
- attestedAt: attestedAt ?? null
- })
+ insertInvite(serviceRole, invite)
]);
if (employeeInsert.error) {
@@ -937,6 +1058,127 @@ export async function insertEmployee(
return client.from("employee").insert([employee]).select("*").single();
}
+/**
+ * Re-add someone whose "employee" row survived a deactivation or a revoked
+ * invite, writing the employee type, org placement and invite in one
+ * transaction. They are only correct together: acceptInvite restores the
+ * employee-type membership from employee.employeeTypeId, while the invite's
+ * permissions come from the type chosen on the form. Written separately, a
+ * failed employee write left a redeemable invite for the new type next to a row
+ * still naming the old one.
+ *
+ * The employee row is locked first. That re-checks the caller's "not active"
+ * read, so a concurrent acceptance cannot be flipped back to inactive, and it
+ * serialises two re-adds of the same person, so the later one overwrites all
+ * three rows rather than some of them. The row must still exist: this path
+ * only reuses rows, and a first-time employee insert stays under the caller's
+ * RLS client. Active stays false until the invite is accepted.
+ *
+ * "employeeJob" is upserted because deactivation keeps it (title, start date,
+ * department, shift, manager, tags and custom fields carry through), but an
+ * employee deactivated before that change has none. Only locationId is written
+ * on conflict. Kept here rather than in people.service.ts — every export there
+ * is also published as an MCP tool.
+ *
+ * The invite write mirrors insertInvite: upsert on (email, companyId), clearing
+ * acceptedAt and revokedAt so a spent invite row becomes redeemable again, and
+ * restarting createdAt so the controlled-environment expiry counts from now.
+ */
+async function reinviteDeactivatedEmployee(
+ db: Kysely<KyselyDatabase>,
+ {
+ userId,
+ companyId,
+ employeeTypeId,
+ locationId,
+ invite
+ }: {
+ userId: string;
+ companyId: string;
+ employeeTypeId: string;
+ locationId: string;
+ invite: Omit<InviteInsert, "permissions"> & {
+ permissions: Record<string, string[]>;
+ };
+ }
+) {
+ await db.transaction().execute(async (trx) => {
+ const employee = await trx
+ .selectFrom("employee")
+ .select("active")
+ .where("id", "=", userId)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .executeTakeFirst();
+
+ if (!employee) {
+ throw new Error(
+ `Employee record not found for user ${userId} in company ${companyId}. Try adding the employee again.`
+ );
+ }
+
+ if (employee.active) {
+ throw new Error("This user is already an employee in this company");
+ }
+
+ await trx
+ .updateTable("employee")
+ .set({ employeeTypeId })
+ .where("id", "=", userId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ // updatedBy names the inviter: this connection has no auth.uid(), and the
+ // audit log falls back to the row's own audit columns for the actor.
+ await trx
+ .insertInto("employeeJob")
+ .values({ id: userId, companyId, locationId })
+ .onConflict((oc) =>
+ oc.columns(["id", "companyId"]).doUpdateSet({
+ locationId,
+ updatedBy: invite.createdBy,
+ updatedAt: datetime.timestamp()
+ })
+ )
+ .execute();
+
+ const permissions = JSON.stringify(invite.permissions);
+
+ await trx
+ .insertInto("invite")
+ .values({
+ role: invite.role,
+ permissions,
+ email: invite.email,
+ companyId: invite.companyId,
+ createdBy: invite.createdBy,
+ code: invite.code,
+ attestedBy: invite.attestedBy ?? null,
+ attestedAt: invite.attestedAt ?? null,
+ acceptedAt: null,
+ revokedAt: null
+ })
+ .onConflict((oc) =>
+ oc.columns(["email", "companyId"]).doUpdateSet({
+ role: invite.role,
+ permissions,
+ createdBy: invite.createdBy,
+ updatedBy: invite.createdBy,
+ // The controlled-environment expiry counts from createdAt. The
+ // reused row is the original invite, usually long since accepted,
+ // so keeping its createdAt expired the new invite on arrival.
+ createdAt: datetime.timestamp(),
+ code: invite.code,
+ attestedBy: invite.attestedBy ?? null,
+ attestedAt: invite.attestedAt ?? null,
+ acceptedAt: null,
+ revokedAt: null
+ })
+ )
+ .execute();
+ });
+}
+
export async function insertInvite(
client: SupabaseClient<Database>,
invite: InviteInsert
@@ -948,10 +1190,22 @@ export async function insertInvite(
// onConflict upsert. Clear both terminal states so a previously revoked or
// accepted invite becomes redeemable again — otherwise the acceptance
// loader (invite.$code.tsx) rejects the row and it can never be accepted.
- .upsert([{ ...invite, acceptedAt: null, revokedAt: null }], {
- onConflict: "email, companyId",
- ignoreDuplicates: false
- })
+ // createdAt restarts too: the controlled-environment expiry counts from
+ // it, and the reused row's is the original invite's.
+ .upsert(
+ [
+ {
+ ...invite,
+ createdAt: datetime.timestamp(),
+ acceptedAt: null,
+ revokedAt: null
+ }
+ ],
+ {
+ onConflict: "email, companyId",
+ ignoreDuplicates: false
+ }
+ )
.select("*")
.single()
);
@@ -1313,65 +1567,3 @@ export async function resetPassword(userId: string, password: string) {
password
});
}
-
-async function rollbackInvite(
- serviceRole: SupabaseClient<Database>,
- { userId, companyId }: { userId: string; companyId: string }
-) {
- await Promise.all([
- serviceRole
- .from("employee")
- .update({ active: false })
- .eq("id", userId)
- .eq("companyId", companyId),
- serviceRole
- .from("userToCompany")
- .delete()
- .eq("userId", userId)
- .eq("companyId", companyId),
- serviceRole
- .from("customerAccount")
- .delete()
- .eq("id", userId)
- .eq("companyId", companyId),
- serviceRole
- .from("supplierAccount")
- .delete()
- .eq("id", userId)
- .eq("companyId", companyId)
- ]);
-}
-
-async function setUserPermissions(
- client: SupabaseClient<Database>,
- userId: string,
- permissions: Record<string, string[]>
-) {
- const user = await client
- .from("userPermission")
- .select("permissions")
- .eq("id", userId)
- .maybeSingle();
-
- const currentPermissions = (user.data?.permissions ?? {}) as Record<
- string,
- string[]
- >;
- const newPermissions = { ...currentPermissions };
-
- Object.entries(permissions).forEach(([key, value]) => {
- if (key in newPermissions) {
- newPermissions[key] = [...newPermissions[key], ...value];
- } else {
- newPermissions[key] = value;
- }
- });
-
- const result = await client
- .from("userPermission")
- .upsert({ id: userId, permissions: newPermissions });
-
- await redis.del(getPermissionCacheKey(userId));
-
- return result;
-}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index da390980ec..8eb71ac8f9 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -591,7 +591,7 @@
{"name":"people_getOpenClockEntry","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"48d1ac3381b4","injectAuth":"companyId","permission":"people:view","paginates":false},
{"name":"people_getPeople","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"5483e69d7515","injectAuth":"companyId","permission":"people:view","paginates":false,"defaults":"always"},
{"name":"people_getRecentTimecards","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"579660621675","injectAuth":"companyId","permission":"people:view","paginates":false},
- {"name":"people_getScheduledEmployeesToday","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c429622c953e","injectAuth":"companyId","permission":"people:view","paginates":false},
+ {"name":"people_getScheduledEmployeesToday","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c93c10ff0dbe","injectAuth":"companyId","permission":"people:view","paginates":false},
{"name":"people_getShift","classification":"READ","paramCount":1,"schema":"fbdb1fa56a88","response":"86e4039d95bd","injectAuth":"companyId","permission":"people:view","paginates":false},
{"name":"people_getShifts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"92fec9db1b7e","injectAuth":"companyId","permission":"people:view","paginates":true,"defaults":"always"},
{"name":"people_getShiftsList","classification":"READ","paramCount":1,"schema":"b76e1039273f","response":"ce08332e0ce6","injectAuth":"companyId","permission":"people:view","paginates":false},
diff --git a/apps/erp/app/routes/x+/users+/deactivate.tsx b/apps/erp/app/routes/x+/users+/deactivate.tsx
index 34c6f5998e..4bd9c47a83 100644
--- a/apps/erp/app/routes/x+/users+/deactivate.tsx
+++ b/apps/erp/app/routes/x+/users+/deactivate.tsx
@@ -4,6 +4,7 @@
import { error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { deactivateUser } from "@carbon/auth/users.server";
import { validationError, validator } from "@carbon/form";
@@ -13,7 +14,7 @@ import type { ActionFunctionArgs } from "react-router";
import { deactivateUsersValidator } from "~/modules/users";
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
delete: "users"
});
@@ -38,9 +39,12 @@ export async function action({ request }: ActionFunctionArgs) {
if (users.length === 1) {
const [targetUserId] = users;
- // deactivateUser() handles Stripe subscription quantity update internally
+ // deactivateUser() handles Stripe subscription quantity update internally.
+ // It needs the service role: "userPermission" has no UPDATE policy, so under
+ // the caller's client the permission strip matched no rows and the user
+ // kept every grant for this company.
const result = await deactivateUser(
- client,
+ getCarbonServiceRole(),
targetUserId,
companyId,
userId,
diff --git a/packages/auth/src/services/deactivate-employee.test.ts b/packages/auth/src/services/deactivate-employee.test.ts
new file mode 100644
index 0000000000..d5cb8cff2b
--- /dev/null
+++ b/packages/auth/src/services/deactivate-employee.test.ts
@@ -0,0 +1,151 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// Same simulation preamble as the sibling auth tests: @carbon/kv is wrapped in
+// withResilience(), and env is validated at import time, so both are stubbed
+// rather than requiring Redis and a full environment in the test run.
+const { redisDel } = vi.hoisted(() => ({
+ redisDel: vi.fn().mockResolvedValue(null)
+}));
+
+vi.mock("@carbon/kv", () => ({
+ redis: {
+ get: vi.fn().mockResolvedValue(null),
+ set: vi.fn().mockResolvedValue(null),
+ del: redisDel,
+ getdel: vi.fn().mockResolvedValue(null)
+ }
+}));
+
+vi.mock("../config/env", () => ({
+ RESEND_DOMAIN: "test.dev",
+ DOMAIN: "localhost",
+ ERP_URL: "http://localhost:3000",
+ MES_URL: "http://localhost:3001",
+ VERCEL_URL: "",
+ CarbonEdition: "Community",
+ REFRESH_ACCESS_TOKEN_THRESHOLD: 60,
+ SESSION_KEY: "auth",
+ SESSION_MAX_AGE: 60 * 60 * 24 * 7,
+ SESSION_SECRET: "test-session-secret",
+ SUPABASE_URL: "http://localhost:54321",
+ SUPABASE_INTERNAL_URL: "http://localhost:54321",
+ SUPABASE_ANON_KEY: "test-anon-key",
+ SUPABASE_SERVICE_ROLE_KEY: "test-service-role-key",
+ SUPABASE_JWT_SECRET: "test-jwt-secret"
+}));
+
+vi.mock("./auth-events.server", () => ({
+ logRoleChange: vi.fn(),
+ logPermissionChange: vi.fn()
+}));
+
+import { deactivateEmployee } from "./users.server";
+
+const USER = "usr_1";
+const COMPANY = "cmp_1";
+const OTHER_COMPANY = "cmp_2";
+
+type Op = { table: string; op: string; payload?: unknown };
+
+let ops: Op[];
+
+/**
+ * Minimal stand-in for the Supabase client: every builder method returns the
+ * same object so calls chain, and the object is awaitable so `Promise.all` over
+ * a list of builders resolves. Each terminal verb is recorded so a test can
+ * assert on which tables were written and how.
+ */
+function makeClient(reads: Record<string, unknown>) {
+ const builder = (table: string) => {
+ const record = (op: string, payload?: unknown) => {
+ ops.push({ table, op, payload });
+ return chain;
+ };
+
+ const chain: Record<string, unknown> = {
+ select: () => chain,
+ eq: () => chain,
+ in: () => chain,
+ update: (payload: unknown) => record("update", payload),
+ delete: () => record("delete"),
+ insert: (payload: unknown) => record("insert", payload),
+ upsert: (payload: unknown) => record("upsert", payload),
+ maybeSingle: () => Promise.resolve(reads[table] ?? { data: null }),
+ single: () => Promise.resolve(reads[table] ?? { data: null }),
+ then: (resolve: (value: unknown) => unknown) =>
+ resolve(reads[table] ?? { data: null, error: null })
+ };
+
+ return chain;
+ };
+
+ return { from: (table: string) => builder(table) };
+}
+
+beforeEach(() => {
+ ops = [];
+ redisDel.mockClear();
+});
+
+describe("deactivateEmployee", () => {
+ const client = () =>
+ makeClient({
+ userPermission: {
+ data: { permissions: { parts_view: [COMPANY, OTHER_COMPANY] } },
+ error: null
+ },
+ group: { data: [{ id: "grp_1" }], error: null }
+ }) as any;
+
+ it("keeps the employeeJob row so org placement survives", async () => {
+ await deactivateEmployee(client(), USER, COMPANY);
+
+ // Regression guard: deleting employeeJob here made deactivation lossy —
+ // title, start date, department, shift, manager, location, tags and custom
+ // fields cannot be reconstructed when the person is re-invited.
+ expect(ops.filter((o) => o.table === "employeeJob")).toEqual([]);
+ });
+
+ it("still removes everything that grants access", async () => {
+ const result = await deactivateEmployee(client(), USER, COMPANY);
+
+ expect(ops).toContainEqual(
+ expect.objectContaining({ table: "userToCompany", op: "delete" })
+ );
+ expect(ops).toContainEqual(
+ expect.objectContaining({
+ table: "employee",
+ op: "update",
+ payload: { active: false }
+ })
+ );
+ expect(ops).toContainEqual(
+ expect.objectContaining({ table: "membership", op: "delete" })
+ );
+ expect(result.success).toBe(true);
+ });
+
+ it("invalidates the cached claims itself, for callers that skip deactivateUser", async () => {
+ await deactivateEmployee(client(), USER, COMPANY);
+
+ // requirePermissions reads this cache (1h TTL) before the database, and the
+ // create*Account rollbacks call this function directly rather than through
+ // deactivateUser — so the invalidation has to live here.
+ expect(redisDel).toHaveBeenCalledWith(`permissions:${USER}`);
+ });
+
+ it("strips only the deactivating company from the permission map", async () => {
+ await deactivateEmployee(client(), USER, COMPANY);
+
+ const update = ops.find(
+ (o) => o.table === "userPermission" && o.op === "update"
+ );
+ expect(update?.payload).toEqual({
+ permissions: { parts_view: [OTHER_COMPANY] }
+ });
+ });
+});
diff --git a/packages/auth/src/services/users.server.ts b/packages/auth/src/services/users.server.ts
index 4a78ec1899..7103a7d45c 100644
--- a/packages/auth/src/services/users.server.ts
+++ b/packages/auth/src/services/users.server.ts
@@ -197,6 +197,11 @@ export async function deactivateCustomer(
reason: "deactivate"
});
+ // Same ownership as the employee path below: invalidate here so the
+ // create*Account rollbacks, which call this directly, cannot leave revoked
+ // grants readable from cache.
+ await redis.del(getPermissionCacheKey(userId));
+
return success("Sucessfully deactivated customer");
}
@@ -252,11 +257,13 @@ export async function deactivateEmployee(
.update({ active: false })
.eq("id", userId)
.eq("companyId", companyId),
- serviceRole
- .from("employeeJob")
- .delete()
- .eq("id", userId)
- .eq("companyId", companyId),
+ // "employeeJob" is deliberately left in place. It carries org placement —
+ // title, start date, department, shift, manager, location, tags, custom
+ // fields — none of which grants access; membership ("userToCompany"),
+ // permissions, and "employee".active are what gate it, and all three are
+ // cleared here. Deleting the row made deactivation lossy: nothing in the
+ // re-invite path can reconstruct it, so a revoked employee who was later
+ // re-invited came back with their placement silently blanked.
...(groupIds.length > 0
? [
serviceRole
@@ -295,6 +302,13 @@ export async function deactivateEmployee(
reason: "deactivate"
});
+ // The permissions this function just revoked are cached in Redis, and
+ // `requirePermissions` reads that cache before the database. Invalidating
+ // here rather than only in `deactivateUser` covers the callers that reach
+ // this function directly — the create*Account rollback paths — which
+ // otherwise left a deactivated user's grants live until the 1h TTL.
+ await redis.del(getPermissionCacheKey(userId));
+
return success("Sucessfully deactivated employee");
}
@@ -513,5 +527,8 @@ export async function deactivateSupplier(
reason: "deactivate"
});
+ // See deactivateEmployee: the direct callers own nothing, this function does.
+ await redis.del(getPermissionCacheKey(userId));
+
return success("Sucessfully deactivated supplier");
}
diff --git a/packages/database/src/event-system/handlers/sync_add_customer_account_to_group.sql b/packages/database/src/event-system/handlers/sync_add_customer_account_to_group.sql
index 30636eef93..9c8d5f3bb5 100644
--- a/packages/database/src/event-system/handlers/sync_add_customer_account_to_group.sql
+++ b/packages/database/src/event-system/handlers/sync_add_customer_account_to_group.sql
@@ -6,10 +6,13 @@ AS $function$
BEGIN
IF p_operation != 'INSERT' THEN RETURN; END IF;
+ -- A user is in a group once ("membership_groupId_memberUserId_key"). A
+ -- membership left behind for this pair must not fail the parent insert.
INSERT INTO "membership" ("groupId", "memberUserId")
VALUES (
p_new->>'customerId',
p_new->>'id'
- );
+ )
+ ON CONFLICT ("groupId", "memberUserId") DO NOTHING;
END;
$function$;
diff --git a/packages/database/src/event-system/handlers/sync_add_employee_to_type_group.sql b/packages/database/src/event-system/handlers/sync_add_employee_to_type_group.sql
index 43bfc0aed8..378e97bc80 100644
--- a/packages/database/src/event-system/handlers/sync_add_employee_to_type_group.sql
+++ b/packages/database/src/event-system/handlers/sync_add_employee_to_type_group.sql
@@ -6,10 +6,13 @@ AS $function$
BEGIN
IF p_operation != 'INSERT' THEN RETURN; END IF;
+ -- A user is in a group once ("membership_groupId_memberUserId_key"). A
+ -- membership left behind for this pair must not fail the parent insert.
INSERT INTO "membership" ("groupId", "memberUserId")
VALUES (
p_new->>'employeeTypeId',
p_new->>'id'
- );
+ )
+ ON CONFLICT ("groupId", "memberUserId") DO NOTHING;
END;
$function$;
diff --git a/packages/database/src/event-system/handlers/sync_add_supplier_account_to_group.sql b/packages/database/src/event-system/handlers/sync_add_supplier_account_to_group.sql
index eb63500c14..fd755b5271 100644
--- a/packages/database/src/event-system/handlers/sync_add_supplier_account_to_group.sql
+++ b/packages/database/src/event-system/handlers/sync_add_supplier_account_to_group.sql
@@ -6,10 +6,13 @@ AS $function$
BEGIN
IF p_operation != 'INSERT' THEN RETURN; END IF;
+ -- A user is in a group once ("membership_groupId_memberUserId_key"). A
+ -- membership left behind for this pair must not fail the parent insert.
INSERT INTO "membership" ("groupId", "memberUserId")
VALUES (
p_new->>'supplierId',
p_new->>'id'
- );
+ )
+ ON CONFLICT ("groupId", "memberUserId") DO NOTHING;
END;
$function$;
diff --git a/packages/database/src/event-system/handlers/sync_update_employee_type_membership.sql b/packages/database/src/event-system/handlers/sync_update_employee_type_membership.sql
index 6b49c54e67..0b963d34bb 100644
--- a/packages/database/src/event-system/handlers/sync_update_employee_type_membership.sql
+++ b/packages/database/src/event-system/handlers/sync_update_employee_type_membership.sql
@@ -5,9 +5,24 @@ CREATE OR REPLACE FUNCTION public.sync_update_employee_type_membership(p_table t
AS $function$
BEGIN
IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'employeeTypeId') IS NOT DISTINCT FROM (p_old->>'employeeTypeId') THEN
+ RETURN;
+ END IF;
+ -- Move the membership to the new type's group. When the user is already in
+ -- that group, moving it would break "membership_groupId_memberUserId_key",
+ -- so the old membership is dropped instead.
UPDATE "membership"
SET "groupId" = p_new->>'employeeTypeId'
+ WHERE "groupId" = p_old->>'employeeTypeId'
+ AND "memberUserId" = p_new->>'id'
+ AND NOT EXISTS (
+ SELECT 1 FROM "membership" m
+ WHERE m."groupId" = p_new->>'employeeTypeId'
+ AND m."memberUserId" = p_new->>'id'
+ );
+
+ DELETE FROM "membership"
WHERE "groupId" = p_old->>'employeeTypeId'
AND "memberUserId" = p_new->>'id';
END;
diff --git a/packages/database/supabase/migrations/20261015074817_membership-user-unique.sql b/packages/database/supabase/migrations/20261015074817_membership-user-unique.sql
new file mode 100644
index 0000000000..62164ae078
--- /dev/null
+++ b/packages/database/supabase/migrations/20261015074817_membership-user-unique.sql
@@ -0,0 +1,38 @@
+-- A user may belong to a group exactly once.
+--
+-- "uq_membership" spans ("groupId", "memberGroupId", "memberUserId"), and
+-- "memberGroupId" is NULL on every user membership. Under the default NULLS
+-- DISTINCT those rows never conflict with each other, so the constraint that
+-- looks like it dedupes user memberships has never done so: two concurrent
+-- writers — the sync_add_employee_to_type_group trigger and the invite
+-- acceptance path that restores the membership on reactivation — can both
+-- insert the same (groupId, memberUserId) pair.
+--
+-- A plain (not partial) unique index is deliberate: it gives ON CONFLICT an
+-- inferrable target, and group memberships keep "memberUserId" NULL, so they
+-- stay mutually distinct and are unaffected.
+
+-- Wrapped in an explicit transaction: the migration runner applies statements in
+-- autocommit, and `LOCK TABLE` requires a transaction block. Same pattern as
+-- 20260908021155_accounting_posting_corrections.sql.
+BEGIN;
+
+-- Hold writers off until the index exists. Without the lock, a membership insert
+-- committing between the DELETE and the index build reintroduces a duplicate and
+-- fails the migration. SHARE ROW EXCLUSIVE conflicts with INSERT/UPDATE/DELETE
+-- but still lets readers through.
+LOCK TABLE "membership" IN SHARE ROW EXCLUSIVE MODE;
+
+-- Collapse existing duplicates first, keeping the earliest row of each pair so
+-- any FK or audit reference to the surviving id stays valid.
+DELETE FROM "membership" m
+USING "membership" keeper
+WHERE m."memberUserId" IS NOT NULL
+ AND m."groupId" = keeper."groupId"
+ AND m."memberUserId" = keeper."memberUserId"
+ AND m."id" > keeper."id";
+
+CREATE UNIQUE INDEX IF NOT EXISTS "membership_groupId_memberUserId_key"
+ ON "membership" ("groupId", "memberUserId");
+
+COMMIT;
diff --git a/packages/database/supabase/migrations/20261015075112_membership-handlers-on-conflict.sql b/packages/database/supabase/migrations/20261015075112_membership-handlers-on-conflict.sql
new file mode 100644
index 0000000000..226f9b1858
--- /dev/null
+++ b/packages/database/supabase/migrations/20261015075112_membership-handlers-on-conflict.sql
@@ -0,0 +1,90 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.sync_add_customer_account_to_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF p_operation != 'INSERT' THEN RETURN; END IF;
+
+ -- A user is in a group once ("membership_groupId_memberUserId_key"). A
+ -- membership left behind for this pair must not fail the parent insert.
+ INSERT INTO "membership" ("groupId", "memberUserId")
+ VALUES (
+ p_new->>'customerId',
+ p_new->>'id'
+ )
+ ON CONFLICT ("groupId", "memberUserId") DO NOTHING;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.sync_add_employee_to_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF p_operation != 'INSERT' THEN RETURN; END IF;
+
+ -- A user is in a group once ("membership_groupId_memberUserId_key"). A
+ -- membership left behind for this pair must not fail the parent insert.
+ INSERT INTO "membership" ("groupId", "memberUserId")
+ VALUES (
+ p_new->>'employeeTypeId',
+ p_new->>'id'
+ )
+ ON CONFLICT ("groupId", "memberUserId") DO NOTHING;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.sync_add_supplier_account_to_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF p_operation != 'INSERT' THEN RETURN; END IF;
+
+ -- A user is in a group once ("membership_groupId_memberUserId_key"). A
+ -- membership left behind for this pair must not fail the parent insert.
+ INSERT INTO "membership" ("groupId", "memberUserId")
+ VALUES (
+ p_new->>'supplierId',
+ p_new->>'id'
+ )
+ ON CONFLICT ("groupId", "memberUserId") DO NOTHING;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.sync_update_employee_type_membership(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'employeeTypeId') IS NOT DISTINCT FROM (p_old->>'employeeTypeId') THEN
+ RETURN;
+ END IF;
+
+ -- Move the membership to the new type's group. When the user is already in
+ -- that group, moving it would break "membership_groupId_memberUserId_key",
+ -- so the old membership is dropped instead.
+ UPDATE "membership"
+ SET "groupId" = p_new->>'employeeTypeId'
+ WHERE "groupId" = p_old->>'employeeTypeId'
+ AND "memberUserId" = p_new->>'id'
+ AND NOT EXISTS (
+ SELECT 1 FROM "membership" m
+ WHERE m."groupId" = p_new->>'employeeTypeId'
+ AND m."memberUserId" = p_new->>'id'
+ );
+
+ DELETE FROM "membership"
+ WHERE "groupId" = p_old->>'employeeTypeId'
+ AND "memberUserId" = p_new->>'id';
+END;
+$function$;
diff --git a/packages/ee/src/sso/provisioning.server.test.ts b/packages/ee/src/sso/provisioning.server.test.ts
index baa21ec4bd..af0d7e6924 100644
--- a/packages/ee/src/sso/provisioning.server.test.ts
+++ b/packages/ee/src/sso/provisioning.server.test.ts
@@ -62,7 +62,7 @@ describe("buildArchivedEmail", () => {
});
describe("mergeInvitePermissions", () => {
- it("takes new keys as-is and concatenates existing keys (setUserPermissions semantics)", () => {
+ it("takes new keys as-is and unions existing keys", () => {
const merged = mergeInvitePermissions(
{ sales_view: ["c1"] },
{ sales_view: ["c2"], parts_view: ["c2"] }
@@ -79,10 +79,10 @@ describe("mergeInvitePermissions", () => {
expect(current).toEqual({ sales_view: ["c1"] });
});
- it("concatenates duplicates when the same grant is merged twice (matches setUserPermissions, which does not dedupe)", () => {
+ it("does not repeat a company id when the same grant is merged twice", () => {
const once = mergeInvitePermissions({}, { sales_view: ["c2"] });
const twice = mergeInvitePermissions(once, { sales_view: ["c2"] });
- expect(twice).toEqual({ sales_view: ["c2", "c2"] });
+ expect(twice).toEqual({ sales_view: ["c2"] });
});
it('keeps "0" wildcard entries untouched when merging', () => {
diff --git a/packages/ee/src/sso/provisioning.server.ts b/packages/ee/src/sso/provisioning.server.ts
index aadbcc0578..58d7fd50ff 100644
--- a/packages/ee/src/sso/provisioning.server.ts
+++ b/packages/ee/src/sso/provisioning.server.ts
@@ -321,9 +321,10 @@ export function buildArchivedEmail(oldUserId: string, email: string): string {
}
/**
- * Merge invite grants into a user's existing permission set — the same
- * semantics as `setUserPermissions` in the ERP users module (arrays are
- * concatenated per key; new keys are taken as-is).
+ * Merge invite grants into a user's existing permission set, used by both
+ * `acceptInvite` in the ERP users module and SSO migration. Arrays are
+ * unioned per key, so re-accepting an invite for a company the user still
+ * holds grants for does not repeat the company id.
*/
export function mergeInvitePermissions(
current: Record<string, string[]>,
@@ -331,8 +332,7 @@ export function mergeInvitePermissions(
): Record<string, string[]> {
const merged = { ...current };
Object.entries(granted).forEach(([key, value]) => {
- const existing = merged[key];
- merged[key] = existing ? [...existing, ...value] : value;
+ merged[key] = [...new Set([...(merged[key] ?? []), ...value])];
});
return merged;
}
@@ -538,6 +538,16 @@ export async function migrateUserToSso(
.onConflict((oc) => oc.columns(["userId", "companyId"]).doNothing())
.execute();
+ // Serialize on the user row before the read-merge-write below, as
+ // acceptInvite does: the userPermission lock holds nothing while that
+ // row is absent. NO KEY UPDATE leaves foreign-key checks unblocked.
+ await trx
+ .selectFrom("user")
+ .select("id")
+ .where("id", "=", newUserId)
+ .forNoKeyUpdate()
+ .executeTakeFirstOrThrow();
+
// Merge invite permissions into userPermission (setUserPermissions
// semantics), under lock so concurrent grants don't lose writes.
const currentPermission = await trx