Multi-administrator support
CI / ci (push) Canceled after 0s

1. Summary of changes
The installer-created account is no longer special. "Owner" is now literally renamed Administrator and behaves exactly like the existing role/permission system already allowed — the codebase turned out to already define "administrator" structurally (a StaffProfile whose role holds MANAGE_STAFF), not as a name or a business.ownerId-style field, and last-administrator protection already existed. The real work was: closing the gap between that and a full admin-management UI, fixing two OTP-migration bugs the new spec's requirements exposed, and making the existing protection transactional.

Businesses can now have any number of Administrators, added via Invite Administrator (name + email → OTP-verified before access), promoted/demoted via the existing staff role dropdown (now intercepted with a confirmation dialog when it crosses the Administrator boundary), or removed via the existing deactivate flow.
Two real bugs found and fixed, both required for the spec's "unverified email must not get access":
Invitation acceptance (/invite/accept) never actually verified an OTP — it silently relied on a sign-in path that would have failed for every real invitee. It now sends and verifies a real code, reusing the shared OtpCodeStep UI.
A newly-invited (not-yet-accepted) account could sign in via plain email OTP before ever touching the invite link, because sign-in only checked "does a User row exist," not whether it was verified. Fixed in the shared OTP service, benefiting every invitation, not just administrators'.
Last-administrator protection (already existed) is now transactional — a SELECT ... FOR UPDATE lock on the business row closes the race where two concurrent removals of two different administrators could both succeed.
Administrators (any staff member, in fact) can now change their own email — new address must be OTP-verified before it replaces the login email.
No hidden installer privilege: confirmed via code audit and a live install → the account is a plain Administrator-role staff member, provable identically via the Team UI as any later-added one.
NextChair Manager and platform Super Administrator are untouched.
2. Prisma/database changes
No schema changes. One data-only migration: prisma/migrations/20260905214944_administrator_role_rename — UPDATE Role SET name = 'Administrator' WHERE name = 'Owner' AND isSystem = true. Runs through the normal migration-deploy process; not something to run by hand.

3. How Administrator roles are represented
A per-business Role row named "Administrator" (was "Owner"), isSystem: true, holding every Permission — created identically at install and in dev seed data. This is what "Invite"/"Make Administrator" assign.
Whether a StaffProfile currently counts as an Administrator is permission-based (holds MANAGE_STAFF), not a name check — the same definition the codebase already used for last-owner protection (isStaffAdministrator in staff.service.ts). This is deliberately reused rather than introduced, and stays correct if a business ever gets a custom role that also grants MANAGE_STAFF.
No Business.adminId-style field anywhere — confirmed none existed before this work either.
4. How administrator invitations work
Reuses the existing StaffInvitation model and createStaffProfile/createInvitation machinery verbatim — a new inviteAdministratorAction just pre-selects the Administrator role and uses a minimal Name+Email form (invite-administrator-form.tsx). Acceptance (accept-invitation.ts) now requires a real OTP code sent to the invited email before the account activates — expiry (7 days), resend, and revoke are all the pre-existing invitation mechanics (revoke = the existing deactivate action, relabeled "Revoke Invitation" while pending).

5. How last-administrator protection is enforced
Server-side only, inside staff.service.ts's updateStaffAsOwner (role change) and deactivateStaff (remove), each wrapped in prisma.$transaction that first locks the business row (SELECT ... FOR UPDATE), then counts other active Administrators before allowing the change. Verified with a genuine concurrency test (two simultaneous removals against a 2-admin business) and manually in-browser (see below).

6. Installation flow changes
Only the role name and one line of wizard copy changed ("This becomes the first Administrator..."). No structural UX change — still collects name/email, verifies via OTP, creates/activates the account, assigns the role, exactly as before.

7. Files changed
New: the migration; email-change.service.ts + change-email.ts action + change-email-section.tsx; invite-administrator-form.tsx + add-administrator/page.tsx; 3 new integration test files.

Modified — core: staff.service.ts (transactional protection, isStaffAdministrator), staff-invitation.service.ts, otp.service.ts (onlyIfUserExists fix, email-change purpose), default-permissions.ts, permissions.ts, auth.ts (JWT email-refresh, simplified finalize path).

Modified — actions/UI: owner/actions/staff.ts, staff-detail-panel.tsx, team/page.tsx, add-staff-form.tsx, accept-invitation.ts/form/page, otp-code-step.tsx, profile-form.tsx, installer files, seed.ts, plus a terminology sweep ("owner" → "administrator" copy in breaks.ts/time-off.ts/staff-emails.ts/profile page).

8. Manual testing steps
Sign in as the seeded owner → /owner/team shows an Administrator badge and an "Invite Administrator" icon next to "+". Invite someone, accept via /invite/accept?token=... printed to the terminal (code also prints there) — they land signed in with full Manage access. Promote/demote any staff member via the role dropdown on their detail page — crossing the Administrator boundary shows a confirmation dialog. With only one Administrator left, attempting to demote or deactivate them shows "You can't remove the only administrator. Add another administrator first." Change your own email from Profile settings — the new address must be OTP-verified before it replaces the old one.

9. Deployment steps on the VPS
None beyond the normal deploy process — the migration is a standard Prisma migration that prisma migrate deploy (whatever already runs it there) will pick up automatically. No new environment variables. No changes to NextChair Manager or its authentication.

Verification performed: tsc/lint/unit — all clean; full test:integration — 219 passed (up from 207, all new); full test:e2e — same 36/37 as before this work (the 1 failure is a pre-existing, auth-unrelated flake unrelated to any of this); a full live manual pass covering every scenario above, including the last-administrator block and the email-change JWT-refresh behavior.
This commit is contained in:
Stefan Lazic committed 2026-09-05 23:32:54 +01:00
1 parent 94aa1b2f26
commit 973187dcc7
33 files changed
+1348 -265

No files matched your search

@@ -13,10 +13,11 @@ export interface StaffInvitationEmailData {
export function renderStaffInvitationEmail(data: StaffInvitationEmailData): RenderedEmail {
const actionUrl = absoluteUrl(data.acceptInvitePath);
const article = data.roleName === "Administrator" ? "an" : "a";
const bodyHtml = [
paragraph(`Hi ${data.staffName},`),
paragraph(
`${data.invitedByName} has added you as ${data.roleName === "Owner" ? "an" : "a"} ${data.roleName} at ${data.business.name}. Set your password to get started.`,
`${data.invitedByName} has added you as ${article} ${data.roleName} at ${data.business.name}. Verify your email to get started — no password needed.`,
),
].join("");
@@ -27,7 +28,7 @@ export function renderStaffInvitationEmail(data: StaffInvitationEmailData): Rend
businessLogoUrl: data.business.logoUrl,
headline: "You've been invited",
bodyHtml,
actionLabel: "Set Your Password",
actionLabel: "Verify Your Email",
actionUrl,
footerNote: footerNoteHtml(data.business),
}),
@@ -37,9 +38,9 @@ export function renderStaffInvitationEmail(data: StaffInvitationEmailData): Rend
bodyLines: [
`Hi ${data.staffName},`,
"",
`${data.invitedByName} has added you as a ${data.roleName} at ${data.business.name}. Set your password to get started.`,
`${data.invitedByName} has added you as ${article} ${data.roleName} at ${data.business.name}. Verify your email to get started — no password needed.`,
],
actionLabel: "Set Your Password",
actionLabel: "Verify Your Email",
actionUrl,
footerNote: footerNoteText(data.business),
}),
@@ -0,0 +1,128 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { requestEmailChange, verifyEmailChange } from "../email-change.service";
import { MockEmailProvider } from "@/services/notifications/providers/mock-email-provider";
import {
cleanupTestBusiness,
createTestBusiness,
createTestStaff,
prisma,
} from "@/services/scheduling/__tests__/fixtures";
import type { TestBusiness } from "@/services/scheduling/__tests__/fixtures";
/**
* Real MySQL, real OTP verify/finalize — see otp.service.integration.test.ts
* for why a hand-rolled fake Prisma client would risk getting the
* verify/consume semantics subtly wrong. Uses the same
* request-then-extract-code-from-MockEmailProvider pattern established
* there and in installer.service.integration.test.ts.
*/
function uniqueEmail(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}@test.local`;
}
async function requestAndExtractCode(newEmail: string, currentEmail: string | null): Promise<string> {
const mockProvider = new MockEmailProvider();
const result = await requestEmailChange(prisma, { currentEmail, newEmail, emailProvider: mockProvider });
expect(result.valid).toBe(true);
const sent = mockProvider.sentEmails[0];
const code = /verification code is (\d{6})/.exec(sent?.text ?? "")?.[1];
if (!code) throw new Error("Test setup failed: couldn't extract the OTP code from the captured email.");
return code;
}
describe("email-change (integration)", () => {
let business: TestBusiness;
beforeEach(async () => {
business = await createTestBusiness();
});
afterEach(async () => {
await cleanupTestBusiness(business);
});
it("only replaces the login email after the code is verified", async () => {
const { userId } = await createTestStaff(business);
const user = await prisma.user.findUniqueOrThrow({ where: { id: userId } });
const newEmail = uniqueEmail("new-email");
const code = await requestAndExtractCode(newEmail, user.email);
// Requesting the code must not have touched the email yet.
const stillOld = await prisma.user.findUniqueOrThrow({ where: { id: userId } });
expect(stillOld.email).toBe(user.email);
const result = await verifyEmailChange(prisma, { userId, newEmail, code });
expect(result.valid).toBe(true);
const updated = await prisma.user.findUniqueOrThrow({ where: { id: userId } });
expect(updated.email).toBe(newEmail.toLowerCase());
expect(updated.emailVerified).not.toBeNull();
});
it("rejects an incorrect code and leaves the email unchanged", async () => {
const { userId } = await createTestStaff(business);
const user = await prisma.user.findUniqueOrThrow({ where: { id: userId } });
const newEmail = uniqueEmail("wrong-code");
await requestAndExtractCode(newEmail, user.email);
const result = await verifyEmailChange(prisma, { userId, newEmail, code: "000000" });
expect(result.valid).toBe(false);
expect(result.issues[0]?.code).toBe("INCORRECT_CODE");
const unchanged = await prisma.user.findUniqueOrThrow({ where: { id: userId } });
expect(unchanged.email).toBe(user.email);
});
it("rejects a new email already used by another account, at request time", async () => {
const { userId: firstUserId } = await createTestStaff(business);
const { userId: secondUserId } = await createTestStaff(business);
const firstUser = await prisma.user.findUniqueOrThrow({ where: { id: firstUserId } });
const secondUser = await prisma.user.findUniqueOrThrow({ where: { id: secondUserId } });
const mockProvider = new MockEmailProvider();
const result = await requestEmailChange(prisma, {
currentEmail: firstUser.email,
newEmail: secondUser.email!,
emailProvider: mockProvider,
});
expect(result.valid).toBe(false);
expect(result.issues[0]?.code).toBe("EMAIL_ALREADY_IN_USE");
expect(mockProvider.sentEmails).toHaveLength(0);
});
it("rejects a new email claimed by another account between request and verify", async () => {
const { userId: firstUserId } = await createTestStaff(business);
const firstUser = await prisma.user.findUniqueOrThrow({ where: { id: firstUserId } });
const newEmail = uniqueEmail("claimed-in-between");
const code = await requestAndExtractCode(newEmail, firstUser.email);
// Someone else grabs the exact same address after the code was sent
// but before it's verified.
const interloper = await prisma.user.create({ data: { email: newEmail.toLowerCase(), name: "Interloper" } });
business.createdUserIds.push(interloper.id);
const result = await verifyEmailChange(prisma, { userId: firstUserId, newEmail, code });
expect(result.valid).toBe(false);
expect(result.issues[0]?.code).toBe("EMAIL_ALREADY_IN_USE");
const unchanged = await prisma.user.findUniqueOrThrow({ where: { id: firstUserId } });
expect(unchanged.email).toBe(firstUser.email);
});
it("rejects changing to the current email address", async () => {
const { userId } = await createTestStaff(business);
const user = await prisma.user.findUniqueOrThrow({ where: { id: userId } });
const mockProvider = new MockEmailProvider();
const result = await requestEmailChange(prisma, {
currentEmail: user.email,
newEmail: user.email!,
emailProvider: mockProvider,
});
expect(result.valid).toBe(false);
expect(result.issues[0]?.code).toBe("SAME_EMAIL");
});
});
@@ -0,0 +1,122 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { requestOtp, verifyOtp } from "@/lib/auth/otp.service";
import { MockEmailProvider } from "@/services/notifications/providers/mock-email-provider";
import { acceptInvitation, createInvitation, validateInvitationToken } from "../staff-invitation.service";
import { createStaffProfile } from "../staff.service";
import {
cleanupTestBusiness,
createTestBusiness,
prisma,
} from "@/services/scheduling/__tests__/fixtures";
import type { TestBusiness } from "@/services/scheduling/__tests__/fixtures";
/**
* Covers the fix from this work: invitation acceptance now requires a real
* OTP verification (src/features/auth/actions/accept-invitation.ts,
* requestInvitationOtpAction/verifyInvitationOtpAction), not just
* possessing the invite link — and, just as importantly, a newly-invited
* account genuinely cannot sign in via plain OTP *before* that
* verification happens (requestOtp's `onlyIfUserExists` now also requires
* emailVerified, see otp.service.ts). Tests the service layer directly
* (same convention as every other *.integration.test.ts here) rather than
* the Server Actions, which need a Next.js request context for auth()/
* headers() that a plain Vitest run doesn't have.
*/
async function createRoleAndInviteStaff(business: TestBusiness): Promise<{ staffId: string; email: string; token: string }> {
const role = await prisma.role.create({ data: { businessId: business.businessId, name: "Barber" } });
const email = `invitee-${Date.now()}-${Math.random().toString(36).slice(2, 8)}@test.local`;
const result = await createStaffProfile(prisma, {
businessId: business.businessId,
input: { name: "New Invitee", email, roleId: role.id, serviceIds: [], isBookableOnline: true },
});
if (!result.success) throw new Error("Test setup failed: couldn't create the invited staff profile.");
business.createdUserIds.push(result.staff.userId);
const invitation = await createInvitation(prisma, { businessId: business.businessId, staffId: result.staff.id, email });
return { staffId: result.staff.id, email, token: invitation.token };
}
async function requestAndExtractCode(email: string): Promise<string> {
const mockProvider = new MockEmailProvider();
const result = await requestOtp(prisma, { email, purpose: "staff-invite", emailProvider: mockProvider });
expect(result.ok).toBe(true);
const sent = mockProvider.sentEmails[0];
const code = /verification code is (\d{6})/.exec(sent?.text ?? "")?.[1];
if (!code) throw new Error("Test setup failed: couldn't extract the OTP code from the captured email.");
return code;
}
describe("staff invitation OTP verification (integration)", () => {
let business: TestBusiness;
beforeEach(async () => {
business = await createTestBusiness();
});
afterEach(async () => {
await cleanupTestBusiness(business);
});
it("a newly-invited (unverified) account cannot sign in via plain OTP before accepting", async () => {
const { email } = await createRoleAndInviteStaff(business);
// createStaffProfile creates the User immediately, before any
// invitation is accepted — this is what onlyIfUserExists must not
// treat as "safe to sign this email in".
const user = await prisma.user.findUniqueOrThrow({ where: { email } });
expect(user.emailVerified).toBeNull();
const mockProvider = new MockEmailProvider();
const result = await requestOtp(prisma, { email, purpose: "login", onlyIfUserExists: true, emailProvider: mockProvider });
// Same generic {ok:true} either way — see onlyIfUserExists's own doc
// comment — but nothing should actually have been sent, and no
// EmailOtp row should exist to verify against.
expect(result.ok).toBe(true);
expect(mockProvider.sentEmails).toHaveLength(0);
expect(await prisma.emailOtp.findUnique({ where: { email } })).toBeNull();
});
it("verifying the invitation's OTP activates the account and grants sign-in access", async () => {
const { email, token } = await createRoleAndInviteStaff(business);
const code = await requestAndExtractCode(email);
const verified = await verifyOtp(prisma, email, code);
expect(verified.ok).toBe(true);
const result = await acceptInvitation(prisma, { token });
expect(result.success).toBe(true);
const user = await prisma.user.findUniqueOrThrow({ where: { email } });
expect(user.emailVerified).not.toBeNull();
// Now that emailVerified is set, onlyIfUserExists must treat this as a
// real, signable-in account.
const mockProvider = new MockEmailProvider();
const signInRequest = await requestOtp(prisma, { email, purpose: "login", onlyIfUserExists: true, emailProvider: mockProvider });
expect(signInRequest.ok).toBe(true);
expect(mockProvider.sentEmails).toHaveLength(1);
});
it("rejects an expired invitation token", async () => {
const { token } = await createRoleAndInviteStaff(business);
await prisma.staffInvitation.update({ where: { token }, data: { expiresAt: new Date(Date.now() - 1000) } });
const check = await validateInvitationToken(prisma, token);
expect(check.valid).toBe(false);
if (check.valid) throw new Error("unreachable");
expect(check.reason).toBe("EXPIRED");
});
it("rejects an already-accepted invitation token (cannot be replayed)", async () => {
const { email, token } = await createRoleAndInviteStaff(business);
const firstCode = await requestAndExtractCode(email);
expect((await verifyOtp(prisma, email, firstCode)).ok).toBe(true);
expect((await acceptInvitation(prisma, { token })).success).toBe(true);
const check = await validateInvitationToken(prisma, token);
expect(check.valid).toBe(false);
if (check.valid) throw new Error("unreachable");
expect(check.reason).toBe("ALREADY_ACCEPTED");
});
});
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
createStaffProfile,
deactivateStaff,
isStaffAdministrator,
reactivateStaff,
setStaffServiceEligibility,
updateStaffAsOwner,
@@ -16,15 +17,16 @@ import {
import type { TestBusiness } from "@/services/scheduling/__tests__/fixtures";
/**
* Covers the owner-only staff management additions from Phase 6:
* onboarding, deactivation/last-owner protection, and service-eligibility
* conflict review. Uses createTestStaff's auto-created role (no
* MANAGE_STAFF permission) as the "ordinary barber" role, and a
* hand-created role with MANAGE_STAFF as the "owner" role — mirroring how
* countOtherActiveManagers/staffCurrentlyManagesStaff actually define "is
* an owner" (see staff.service.ts).
* Covers owner/administrator staff management: onboarding, deactivation/
* last-administrator protection, role promote/demote, and
* service-eligibility conflict review. Uses createTestStaff's auto-created
* role (no MANAGE_STAFF permission) as the "ordinary barber" role, and a
* hand-created role with MANAGE_STAFF as the "administrator" role —
* mirroring how countOtherActiveAdministrators/isStaffAdministrator
* actually define "is an administrator" (see staff.service.ts):
* permission-based, never a check against the role's name.
*/
describe("StaffService — owner actions (integration)", () => {
describe("StaffService — owner/administrator actions (integration)", () => {
let business: TestBusiness;
beforeEach(async () => {
@@ -35,11 +37,11 @@ describe("StaffService — owner actions (integration)", () => {
await cleanupTestBusiness(business);
});
async function createOwnerRole() {
async function createAdministratorRole() {
return prisma.role.create({
data: {
businessId: business.businessId,
name: "Owner",
name: "Administrator",
permissions: { create: [{ permission: "MANAGE_STAFF" }] },
},
});
@@ -91,55 +93,100 @@ describe("StaffService — owner actions (integration)", () => {
});
});
describe("last-owner protection", () => {
it("blocks deactivating the only active owner", async () => {
const ownerRole = await createOwnerRole();
const { staffId: ownerStaffId, userId } = await createTestStaff(business);
await prisma.staffProfile.update({ where: { id: ownerStaffId }, data: { roleId: ownerRole.id } });
describe("last-administrator protection", () => {
it("blocks deactivating (removing) the only active administrator", async () => {
const administratorRole = await createAdministratorRole();
const { staffId: administratorStaffId, userId } = await createTestStaff(business);
await prisma.staffProfile.update({ where: { id: administratorStaffId }, data: { roleId: administratorRole.id } });
void userId;
const result = await deactivateStaff(prisma, { staffId: ownerStaffId, businessId: business.businessId });
const result = await deactivateStaff(prisma, { staffId: administratorStaffId, businessId: business.businessId });
expect(result.success).toBe(false);
if (result.success) throw new Error("unreachable");
expect(result.validation.issues[0]?.code).toBe("LAST_OWNER");
expect(result.validation.issues[0]?.code).toBe("LAST_ADMINISTRATOR");
expect(result.validation.issues[0]?.message).toBe(
"You can't remove the only administrator. Add another administrator first.",
);
const stillActive = await prisma.staffProfile.findUniqueOrThrow({ where: { id: ownerStaffId } });
const stillActive = await prisma.staffProfile.findUniqueOrThrow({ where: { id: administratorStaffId } });
expect(stillActive.status).toBe("ACTIVE");
});
it("allows deactivating an owner when another active owner remains", async () => {
const ownerRole = await createOwnerRole();
const { staffId: firstOwnerId } = await createTestStaff(business);
const { staffId: secondOwnerId } = await createTestStaff(business);
it("allows removing an administrator when another active administrator remains", async () => {
const administratorRole = await createAdministratorRole();
const { staffId: firstAdminId } = await createTestStaff(business);
const { staffId: secondAdminId } = await createTestStaff(business);
await prisma.staffProfile.updateMany({
where: { id: { in: [firstOwnerId, secondOwnerId] } },
data: { roleId: ownerRole.id },
where: { id: { in: [firstAdminId, secondAdminId] } },
data: { roleId: administratorRole.id },
});
const result = await deactivateStaff(prisma, { staffId: firstOwnerId, businessId: business.businessId });
const result = await deactivateStaff(prisma, { staffId: firstAdminId, businessId: business.businessId });
expect(result.success).toBe(true);
const deactivated = await prisma.staffProfile.findUniqueOrThrow({ where: { id: firstOwnerId } });
const deactivated = await prisma.staffProfile.findUniqueOrThrow({ where: { id: firstAdminId } });
expect(deactivated.status).toBe("INACTIVE");
});
it("blocks demoting the only active owner's role away from MANAGE_STAFF", async () => {
const ownerRole = await createOwnerRole();
it("blocks demoting the only active administrator's role away from MANAGE_STAFF", async () => {
const administratorRole = await createAdministratorRole();
const barberRole = await createBarberRole();
const { staffId: ownerStaffId } = await createTestStaff(business);
await prisma.staffProfile.update({ where: { id: ownerStaffId }, data: { roleId: ownerRole.id } });
const { staffId: administratorStaffId } = await createTestStaff(business);
await prisma.staffProfile.update({ where: { id: administratorStaffId }, data: { roleId: administratorRole.id } });
const result = await updateStaffAsOwner(prisma, {
staffId: ownerStaffId,
staffId: administratorStaffId,
businessId: business.businessId,
input: { roleId: barberRole.id },
});
expect(result.success).toBe(false);
if (result.success) throw new Error("unreachable");
expect(result.validation.issues[0]?.code).toBe("LAST_OWNER");
expect(result.validation.issues[0]?.code).toBe("LAST_ADMINISTRATOR");
expect(result.validation.issues[0]?.message).toBe(
"You can't remove the only administrator. Add another administrator first.",
);
const stillOwner = await prisma.staffProfile.findUniqueOrThrow({ where: { id: ownerStaffId } });
expect(stillOwner.roleId).toBe(ownerRole.id);
const stillAdministrator = await prisma.staffProfile.findUniqueOrThrow({ where: { id: administratorStaffId } });
expect(stillAdministrator.roleId).toBe(administratorRole.id);
});
it("promotes a barber to Administrator", async () => {
const administratorRole = await createAdministratorRole();
const barberRole = await createBarberRole();
const { staffId } = await createTestStaff(business);
await prisma.staffProfile.update({ where: { id: staffId }, data: { roleId: barberRole.id } });
const result = await updateStaffAsOwner(prisma, {
staffId,
businessId: business.businessId,
input: { roleId: administratorRole.id },
});
expect(result.success).toBe(true);
const promoted = await prisma.staffProfile.findUniqueOrThrow({ where: { id: staffId } });
expect(promoted.roleId).toBe(administratorRole.id);
expect(await isStaffAdministrator(prisma, staffId)).toBe(true);
});
it("demotes an Administrator to Barber when another Administrator remains", async () => {
const administratorRole = await createAdministratorRole();
const barberRole = await createBarberRole();
const { staffId: firstAdminId } = await createTestStaff(business);
const { staffId: secondAdminId } = await createTestStaff(business);
await prisma.staffProfile.updateMany({
where: { id: { in: [firstAdminId, secondAdminId] } },
data: { roleId: administratorRole.id },
});
const result = await updateStaffAsOwner(prisma, {
staffId: firstAdminId,
businessId: business.businessId,
input: { roleId: barberRole.id },
});
expect(result.success).toBe(true);
expect(await isStaffAdministrator(prisma, firstAdminId)).toBe(false);
expect(await isStaffAdministrator(prisma, secondAdminId)).toBe(true);
});
it("reactivating a deactivated staff member restores ACTIVE status", async () => {
@@ -152,6 +199,61 @@ describe("StaffService — owner actions (integration)", () => {
const staff = await prisma.staffProfile.findUniqueOrThrow({ where: { id: staffId } });
expect(staff.status).toBe("ACTIVE");
});
/**
* The concurrency scenario the brief explicitly calls out: a business
* with exactly two administrators, and two simultaneous requests each
* trying to remove a *different* one of them (one demoting, one
* deactivating). Without updateStaffAsOwner/deactivateStaff each
* locking the business row inside their own transaction (see
* staff.service.ts), both could read "the other one is still an
* administrator" before either commits, and both would succeed —
* leaving zero. Run repeatedly (not just once) since a race is
* probabilistic; this asserts the invariant holds regardless of which
* of the two operations happens to win.
*/
it("never leaves zero administrators when two are removed concurrently", async () => {
const administratorRole = await createAdministratorRole();
const barberRole = await createBarberRole();
const { staffId: firstAdminId } = await createTestStaff(business);
const { staffId: secondAdminId } = await createTestStaff(business);
await prisma.staffProfile.updateMany({
where: { id: { in: [firstAdminId, secondAdminId] } },
data: { roleId: administratorRole.id },
});
const [demoteResult, deactivateResult] = await Promise.all([
updateStaffAsOwner(prisma, {
staffId: firstAdminId,
businessId: business.businessId,
input: { roleId: barberRole.id },
}),
deactivateStaff(prisma, { staffId: secondAdminId, businessId: business.businessId }),
]);
// Exactly one of the two concurrent removals must have been rejected
// — never both succeeding (zero administrators) and, just as
// importantly, never both being rejected (a business with 2 real
// administrators must be able to remove one of them).
const results = [demoteResult, deactivateResult];
const succeeded = results.filter((r) => r.success);
const failed = results.filter((r) => !r.success);
expect(succeeded).toHaveLength(1);
expect(failed).toHaveLength(1);
if (!failed[0]!.success) {
expect(failed[0]!.validation.issues[0]?.code).toBe("LAST_ADMINISTRATOR");
}
const remainingAdministrators = await prisma.staffProfile.count({
where: {
businessId: business.businessId,
status: "ACTIVE",
id: { in: [firstAdminId, secondAdminId] },
role: { permissions: { some: { permission: "MANAGE_STAFF" } } },
},
});
expect(remainingAdministrators).toBeGreaterThanOrEqual(1);
});
});
describe("deactivation appointment conflicts", () => {
+117
View File
@@ -0,0 +1,117 @@
import type { Prisma, PrismaClient } from "@/generated/prisma/client";
import { finalizeOtp, requestOtp, verifyOtp } from "@/lib/auth/otp.service";
import type { EmailProvider } from "@/services/notifications/providers/email-provider";
import { fail, ok } from "@/lib/validation-result";
import type { ValidationResult } from "@/lib/validation-result";
/**
* The testable core of "change my login email" (see
* src/features/staff/actions/change-email.ts for the thin Server Action
* wrapper that resolves the caller's session/IP and calls these) — pulled
* into its own service, same split as every other staff-management action
* in this app (StaffService, StaffInvitationService), so this can be
* integration-tested directly without needing a Next.js request context
* for auth()/headers().
*
* Available to any staff member, Administrator or not — see
* change-email.ts's own header for why this deliberately isn't
* Administrator-gated.
*/
type Db = PrismaClient | Prisma.TransactionClient;
export type EmailChangeErrorCode =
| "INVALID_INPUT"
| "SAME_EMAIL"
| "EMAIL_ALREADY_IN_USE"
| "TOO_MANY_ATTEMPTS"
| "INCORRECT_CODE";
class EmailChangeConflictError extends Error {}
class EmailChangeNotVerifiedError extends Error {}
function normalizeEmail(email: string): string {
return email.trim().toLowerCase();
}
function isValidEmailFormat(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
/** Step 1 — send a code to the NEW address (never the current one). */
export async function requestEmailChange(
db: Db,
params: {
currentEmail: string | null;
newEmail: string;
ip?: string;
senderName?: string;
emailProvider: EmailProvider;
},
): Promise<ValidationResult<EmailChangeErrorCode>> {
const email = normalizeEmail(params.newEmail);
if (!isValidEmailFormat(email)) {
return fail({ code: "INVALID_INPUT", message: "Enter a valid email address." });
}
if (email === params.currentEmail?.toLowerCase()) {
return fail({ code: "SAME_EMAIL", message: "That's already your email address." });
}
const existing = await db.user.findUnique({ where: { email }, select: { id: true } });
if (existing) {
return fail({ code: "EMAIL_ALREADY_IN_USE", message: "That email is already in use." });
}
const result = await requestOtp(db, {
email,
purpose: "email-change",
ip: params.ip,
senderName: params.senderName,
emailProvider: params.emailProvider,
});
if (!result.ok) {
return fail({ code: "TOO_MANY_ATTEMPTS", message: "Too many attempts. Please try again later." });
}
return ok();
}
/**
* Step 2 — verifies the code, then re-checks the uniqueness conflict and
* finalizes the OTP together with the actual `User.email` write inside one
* transaction (closes the request-to-verify race: someone else could have
* claimed the address in between). The old email is untouched until this
* succeeds.
*/
export async function verifyEmailChange(
prisma: PrismaClient,
params: { userId: string; newEmail: string; code: string; ip?: string },
): Promise<ValidationResult<EmailChangeErrorCode>> {
const email = normalizeEmail(params.newEmail);
const verified = await verifyOtp(prisma, email, params.code, params.ip);
if (!verified.ok) {
return fail({ code: "INCORRECT_CODE", message: "Incorrect or expired code. Please try again." });
}
try {
await prisma.$transaction(async (tx) => {
const conflict = await tx.user.findUnique({ where: { email }, select: { id: true } });
if (conflict && conflict.id !== params.userId) {
throw new EmailChangeConflictError();
}
if (!(await finalizeOtp(tx, email))) {
throw new EmailChangeNotVerifiedError();
}
await tx.user.update({ where: { id: params.userId }, data: { email, emailVerified: new Date() } });
});
} catch (error) {
if (error instanceof EmailChangeConflictError) {
return fail({ code: "EMAIL_ALREADY_IN_USE", message: "That email is already in use." });
}
if (error instanceof EmailChangeNotVerifiedError) {
return fail({ code: "INCORRECT_CODE", message: "Incorrect or expired code. Please try again." });
}
throw error;
}
return ok();
}
+20 -12
View File
@@ -8,9 +8,14 @@ import { getOwnerUserIds } from "@/services/notifications/recipients";
* The "invite a new staff member" flow, deliberately split out of
* StaffService (see docs/phase-6-summary.md, "Domain services" — the
* brief's own instruction not to mix invitation delivery into StaffService).
* StaffService.createStaffProfile makes the User/StaffProfile usable
* immediately; this file only tracks the separate "has this person set
* their own password yet" signal via StaffInvitation.acceptedAt.
* StaffService.createStaffProfile creates the User/StaffProfile
* immediately, but requestOtp's `onlyIfUserExists` check (src/lib/auth/
* otp.service.ts) also requires `emailVerified` — so a newly-invited
* account genuinely cannot sign in until this file's acceptInvitation sets
* that, which itself only happens after the invitee verifies an OTP sent
* to this exact email (see src/features/auth/actions/accept-invitation.ts).
* This file tracks that "has this person verified their email yet" signal
* via StaffInvitation.acceptedAt.
*
* `token` is a plain opaque value (crypto-random, not HMAC-signed like the
* booking-draft cookie, because it's validated against a database row
@@ -58,7 +63,7 @@ export async function createInvitation(
type: NotificationType.STAFF_INVITATION_RECEIVED,
recipientUserId: staff.user.id,
subject: `You've been invited to join ${staff.business.name}`,
bodyText: `${invitedBy?.name ?? "The owner"} has added you as ${staff.role.name} at ${staff.business.name}. Set your password to get started.`,
bodyText: `${invitedBy?.name ?? "The business's administrator"} has added you as ${staff.role.name} at ${staff.business.name}. Verify your email to get started — no password needed.`,
deepLinkPath: `/invite/accept?token=${invitation.token}`,
idempotencyKey: `notify:staff-invitation-received:${invitation.id}`,
});
@@ -105,13 +110,16 @@ export async function validateInvitationToken(prisma: PrismaClient, token: strin
}
/**
* Activates the invited staff member's account — no password to set:
* possessing this exact token (delivered only to the invited email) is
* itself the proof of email ownership, same as it already was for
* `emailVerified` before this function ever checked a password (see this
* file's own header). The caller (acceptInvitationAction) signs the user
* in immediately after, via src/auth.ts's token-gated finalize path,
* reusing this same invitation token as the required secret.
* Activates the invited staff member's account — no password to set. The
* caller (verifyInvitationOtpAction, src/features/auth/actions/accept-
* invitation.ts) has already required the invitee to request and verify a
* one-time code sent to this exact email (via requestOtp/verifyOtp,
* purpose "staff-invite") before calling this — the token alone is no
* longer treated as sufficient proof of email ownership on its own. This
* function itself just does the actual account-activation bookkeeping
* (emailVerified + acceptedAt) once that verification has already
* succeeded, still re-validating the token/expiry/already-accepted state
* one more time for safety.
*/
export async function acceptInvitation(
prisma: PrismaClient,
@@ -138,7 +146,7 @@ export async function acceptInvitation(
type: NotificationType.OWNER_STAFF_INVITATION_ACCEPTED,
recipientUserId: ownerUserId,
subject: "Invitation accepted",
bodyText: `${check.invitation.staff.user.name ?? "A new team member"} has set their password and joined ${check.invitation.staff.business.name}.`,
bodyText: `${check.invitation.staff.user.name ?? "A new team member"} has verified their email and joined ${check.invitation.staff.business.name}.`,
deepLinkPath: `/owner/team/${check.invitation.staff.id}`,
idempotencyKey: `notify:owner-staff-invitation-accepted:${check.invitation.id}:${ownerUserId}`,
});
+128 -78
View File
@@ -1,4 +1,4 @@
import type { PrismaClient } from "@/generated/prisma/client";
import type { Prisma, PrismaClient } from "@/generated/prisma/client";
import { Weekday } from "@/generated/prisma/enums";
import {
calendarDateOf,
@@ -34,7 +34,7 @@ export type StaffServiceErrorCode =
| "PERMISSION_DENIED"
| "EMAIL_ALREADY_IN_USE"
| "ROLE_NOT_FOUND"
| "LAST_OWNER";
| "LAST_ADMINISTRATOR";
export class StaffPermissionDeniedError extends Error {
constructor(message = "You don't have permission to manage this staff member's schedule.") {
@@ -43,6 +43,19 @@ export class StaffPermissionDeniedError extends Error {
}
}
/** A Prisma client or an in-flight transaction client — same convention as src/lib/auth/otp.service.ts's `Db` alias, so the last-administrator count/update below can run atomically inside one `$transaction`. */
type Db = PrismaClient | Prisma.TransactionClient;
/** Thrown inside a `$transaction` callback below to carry a specific StaffServiceErrorCode back out through the surrounding try/catch — mirrors installer.service.ts's own InstallStepError pattern. */
class StaffOperationError extends Error {
constructor(
readonly code: StaffServiceErrorCode,
message: string,
) {
super(message);
}
}
/** Every mutation here takes the acting staff member's own id and asserts the resource belongs to them — a staff member manages only their own schedule this phase (see docs/phase-5-summary.md, "Permission model"). */
export function assertOwnsResource(resourceStaffId: string, actingStaffId: string): void {
if (resourceStaffId !== actingStaffId) {
@@ -696,12 +709,12 @@ export async function listRolesForBusiness(prisma: PrismaClient, businessId: str
});
}
/** A role holding MANAGE_STAFF is this app's definition of "an owner" — see docs/phase-6-summary.md, "Roles and permissions". */
async function countOtherActiveManagers(
prisma: PrismaClient,
/** A role holding MANAGE_STAFF is this app's definition of "an Administrator" — see docs/phase-6-summary.md, "Roles and permissions". Deliberately permission-based, not a check against the role's name — stays correct even if a business ever gets a custom role that also grants MANAGE_STAFF. */
async function countOtherActiveAdministrators(
db: Db,
params: { businessId: string; excludeStaffId: string },
) {
return prisma.staffProfile.count({
return db.staffProfile.count({
where: {
businessId: params.businessId,
status: "ACTIVE",
@@ -711,8 +724,9 @@ async function countOtherActiveManagers(
});
}
async function staffCurrentlyManagesStaff(prisma: PrismaClient, staffId: string): Promise<boolean> {
const staff = await prisma.staffProfile.findUnique({
/** Exported so the owner-actions layer can decide when a role change / deactivation crosses the Administrator boundary, for audit-log naming (ADMINISTRATOR_PROMOTED/DEMOTED/REMOVED vs. the generic STAFF_* actions). */
export async function isStaffAdministrator(db: Db, staffId: string): Promise<boolean> {
const staff = await db.staffProfile.findUnique({
where: { id: staffId },
select: { status: true, role: { select: { permissions: { select: { permission: true } } } } },
});
@@ -796,63 +810,87 @@ export interface UpdateStaffAsOwnerInput {
roleId?: string;
}
/**
* A role change is the only path here that can ever reduce the business's
* administrator count, so the last-administrator check and the actual
* write must happen atomically — otherwise two concurrent requests each
* demoting a *different* administrator could both read "someone else is
* still an administrator" before either commits, and both succeed,
* leaving zero. When a role change is requested, this acquires a
* `SELECT ... FOR UPDATE` lock on the business's own row first (same
* `$queryRaw` tagged-template pattern already used in
* src/app/api/health/route.ts) so a second concurrent call for the same
* business blocks until the first transaction commits — at which point its
* own count reflects the first call's already-applied change. Calls that
* don't touch `roleId` skip the lock entirely so ordinary concurrent
* profile edits for different staff members are never needlessly
* serialized against each other.
*/
export async function updateStaffAsOwner(
prisma: PrismaClient,
params: { staffId: string; businessId: string; input: UpdateStaffAsOwnerInput },
) {
const existing = await prisma.staffProfile.findFirst({
where: { id: params.staffId, businessId: params.businessId },
});
if (!existing) {
return { success: false as const, validation: fail({ code: "STAFF_NOT_FOUND", message: "Staff member not found." }) };
}
if (params.input.roleId && params.input.roleId !== existing.roleId) {
const role = await prisma.role.findFirst({ where: { id: params.input.roleId, businessId: params.businessId } });
if (!role) {
return { success: false as const, validation: fail({ code: "ROLE_NOT_FOUND", message: "Role not found." }) };
}
const wasManager = await staffCurrentlyManagesStaff(prisma, params.staffId);
const stillManagesAfter = !!(await prisma.rolePermission.findFirst({
where: { roleId: role.id, permission: "MANAGE_STAFF" },
}));
if (wasManager && !stillManagesAfter) {
const otherManagers = await countOtherActiveManagers(prisma, {
businessId: params.businessId,
excludeStaffId: params.staffId,
});
if (otherManagers === 0) {
return {
success: false as const,
validation: fail({
code: "LAST_OWNER",
message: "This is the only active owner — assign another owner first.",
}),
};
try {
await prisma.$transaction(async (tx) => {
if (params.input.roleId !== undefined) {
await tx.$queryRaw`SELECT id FROM Business WHERE id = ${params.businessId} FOR UPDATE`;
}
}
}
await prisma.$transaction([
prisma.user.update({
where: { id: existing.userId },
data: {
...(params.input.name !== undefined ? { name: params.input.name } : {}),
...(params.input.phone !== undefined ? { phone: params.input.phone || null } : {}),
...(params.input.image !== undefined ? { image: params.input.image || null } : {}),
},
}),
prisma.staffProfile.update({
where: { id: params.staffId },
data: {
...(params.input.bio !== undefined ? { bio: params.input.bio || null } : {}),
...(params.input.isBookableOnline !== undefined
? { isBookableOnline: params.input.isBookableOnline }
: {}),
...(params.input.roleId !== undefined ? { roleId: params.input.roleId } : {}),
},
}),
]);
const existing = await tx.staffProfile.findFirst({
where: { id: params.staffId, businessId: params.businessId },
});
if (!existing) {
throw new StaffOperationError("STAFF_NOT_FOUND", "Staff member not found.");
}
if (params.input.roleId && params.input.roleId !== existing.roleId) {
const role = await tx.role.findFirst({ where: { id: params.input.roleId, businessId: params.businessId } });
if (!role) {
throw new StaffOperationError("ROLE_NOT_FOUND", "Role not found.");
}
const wasAdministrator = await isStaffAdministrator(tx, params.staffId);
const stillAdministratorAfter = !!(await tx.rolePermission.findFirst({
where: { roleId: role.id, permission: "MANAGE_STAFF" },
}));
if (wasAdministrator && !stillAdministratorAfter) {
const otherAdministrators = await countOtherActiveAdministrators(tx, {
businessId: params.businessId,
excludeStaffId: params.staffId,
});
if (otherAdministrators === 0) {
throw new StaffOperationError(
"LAST_ADMINISTRATOR",
"You can't remove the only administrator. Add another administrator first.",
);
}
}
}
await tx.user.update({
where: { id: existing.userId },
data: {
...(params.input.name !== undefined ? { name: params.input.name } : {}),
...(params.input.phone !== undefined ? { phone: params.input.phone || null } : {}),
...(params.input.image !== undefined ? { image: params.input.image || null } : {}),
},
});
await tx.staffProfile.update({
where: { id: params.staffId },
data: {
...(params.input.bio !== undefined ? { bio: params.input.bio || null } : {}),
...(params.input.isBookableOnline !== undefined
? { isBookableOnline: params.input.isBookableOnline }
: {}),
...(params.input.roleId !== undefined ? { roleId: params.input.roleId } : {}),
},
});
});
} catch (error) {
if (error instanceof StaffOperationError) {
return { success: false as const, validation: fail({ code: error.code, message: error.message }) };
}
throw error;
}
return { success: true as const, validation: ok() };
}
@@ -888,24 +926,6 @@ export async function deactivateStaff(
};
}
const wasManager = await staffCurrentlyManagesStaff(prisma, params.staffId);
if (wasManager) {
const otherManagers = await countOtherActiveManagers(prisma, {
businessId: params.businessId,
excludeStaffId: params.staffId,
});
if (otherManagers === 0) {
return {
success: false as const,
validation: fail({
code: "LAST_OWNER",
message: "This is the only active owner — assign another owner first.",
}),
conflicts: [],
};
}
}
if (!params.acknowledgeConflicts) {
const conflicts = await findStaffDeactivationConflicts(prisma, { staffId: params.staffId });
if (conflicts.length > 0) {
@@ -920,7 +940,37 @@ export async function deactivateStaff(
}
}
await prisma.staffProfile.update({ where: { id: params.staffId }, data: { status: "INACTIVE" } });
// Last-administrator protection is checked fresh, inside the same
// transaction as the actual write, under a lock on the business row —
// see updateStaffAsOwner's own comment for why this needs to be atomic
// rather than the read-then-write this used to be.
try {
await prisma.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM Business WHERE id = ${params.businessId} FOR UPDATE`;
const wasAdministrator = await isStaffAdministrator(tx, params.staffId);
if (wasAdministrator) {
const otherAdministrators = await countOtherActiveAdministrators(tx, {
businessId: params.businessId,
excludeStaffId: params.staffId,
});
if (otherAdministrators === 0) {
throw new StaffOperationError(
"LAST_ADMINISTRATOR",
"You can't remove the only administrator. Add another administrator first.",
);
}
}
await tx.staffProfile.update({ where: { id: params.staffId }, data: { status: "INACTIVE" } });
});
} catch (error) {
if (error instanceof StaffOperationError) {
return { success: false as const, validation: fail({ code: error.code, message: error.message }), conflicts: [] };
}
throw error;
}
return { success: true as const, conflicts: [], validation: ok() };
}