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:
33 files changed
+1348
-265
No files matched your search
@@ -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}`,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user