feat(staff): super user grant/revoke UI with last-user guardrail (GRO-206) #155

Closed
groombook-engineer[bot] wants to merge 7 commits from feat/gro-198-super-user-ui into main
7 changed files with 250 additions and 20 deletions
+114 -7
View File
@@ -15,7 +15,26 @@ const createStaffSchema = z.object({
active: z.boolean().default(true),
});
const updateStaffSchema = createStaffSchema.partial().omit({ email: true });
const updateStaffSchema = z.object({
name: z.string().min(1).max(200).optional(),
role: z.enum(["groomer", "receptionist", "manager"]).optional(),
active: z.boolean().optional(),
isSuperUser: z.boolean().optional(),
oidcSub: z.string().optional(),
});
staffRouter.get("/me", async (c) => {
const staffRow = c.get("staff");
if (!staffRow) {
return c.json({ error: "Staff record not found in context" }, 500);
}
try {
return c.json(staffRow);
} catch (err) {
console.error("[/api/staff/me] serialization error:", err, "staffRow:", staffRow);
return c.json({ error: "Serialization error", detail: String(err) }, 500);
}
});
staffRouter.get("/", async (c) => {
const db = getDb();
@@ -45,11 +64,76 @@ staffRouter.post("/", zValidator("json", createStaffSchema), async (c) => {
staffRouter.patch("/:id", zValidator("json", updateStaffSchema), async (c) => {
const db = getDb();
const currentStaff = c.get("staff");
const body = c.req.valid("json");
const targetId = c.req.param("id");
// Only super users can change isSuperUser
if (body.isSuperUser !== undefined && !currentStaff.isSuperUser) {
return c.json({ error: "Forbidden: super user privileges required to modify super user status" }, 403);
}
// Before revoking or deactivating the last super user, serialize access with a
// transaction + FOR UPDATE to prevent a race where two concurrent requests both
// pass the count check and leave zero super users.
const needsSuperUserGuard = body.isSuperUser === false || body.active === false;
if (needsSuperUserGuard) {
const [guardError, row] = await db.transaction(async (tx) => {
// Lock the target row so no other request can modify it concurrently
const [target] = await tx
.select({ isSuperUser: staff.isSuperUser })
.from(staff)
.where(eq(staff.id, targetId))
.limit(1)
.for("update");
if (!target) return ["Not found", null as (typeof staff.$inferSelect | null)];
// Only enforce guard if the target is actually a super user
const isRevokingSuperUser = body.isSuperUser === false && target.isSuperUser;
const isDeactivatingSuperUser = body.active === false && target.isSuperUser;
if (!isRevokingSuperUser && !isDeactivatingSuperUser) {
const [updated] = await tx
.update(staff)
.set({ ...body, updatedAt: new Date() })
.where(eq(staff.id, targetId))
.returning();
return [null, updated];
}
// Count active super users (excluding target — it will be changed)
const superUserCount = await tx
.select({ id: staff.id })
.from(staff)
.where(and(eq(staff.isSuperUser, true), eq(staff.active, true), ne(staff.id, targetId)))
.limit(2);
if (superUserCount.length <= 1) {
return [
body.isSuperUser === false
? "Cannot revoke the last super user. Assign another super user first."
: "Cannot deactivate the last super user. Assign another super user first.",
null,
];
}
const [updated] = await tx
.update(staff)
.set({ ...body, updatedAt: new Date() })
.where(eq(staff.id, targetId))
.returning();
return [null, updated];
});
if (guardError) return c.json({ error: guardError }, guardError === "Not found" ? 404 : 400);
if (!row) return c.json({ error: "Not found" }, 404);
return c.json(row);
}
const [row] = await db
.update(staff)
.set({ ...body, updatedAt: new Date() })
.where(eq(staff.id, c.req.param("id")))
.where(eq(staff.id, targetId))
.returning();
if (!row) return c.json({ error: "Not found" }, 404);
return c.json(row);
@@ -81,11 +165,34 @@ staffRouter.delete("/:id", async (c) => {
);
}
const [row] = await db
.delete(staff)
.where(eq(staff.id, id))
.returning();
if (!row) return c.json({ error: "Not found" }, 404);
// Prevent deleting the last super user — use transaction to avoid race
const [guardError] = await db.transaction(async (tx) => {
const [targetStaff] = await tx
.select({ isSuperUser: staff.isSuperUser })
.from(staff)
.where(eq(staff.id, id))
.limit(1)
.for("update");
if (!targetStaff) return ["Not found", null];
if (targetStaff.isSuperUser) {
const superUserCount = await tx
.select({ id: staff.id })
.from(staff)
.where(and(eq(staff.isSuperUser, true), eq(staff.active, true), ne(staff.id, id)))
.limit(2);
if (superUserCount.length <= 1) {
return ["Cannot delete the last super user. Assign another super user first.", null];
}
}
const [row] = await tx.delete(staff).where(eq(staff.id, id)).returning();
return [null, row];
});
if (guardError === "Not found") return c.json({ error: "Not found" }, 404);
if (guardError) return c.json({ error: guardError }, 400);
return c.json({ ok: true });
});
+23
View File
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import type { Service } from "@groombook/types";
// ─── Types ───────────────────────────────────────────────────────────────────
@@ -125,6 +126,28 @@ export function BookPage() {
});
const [formError, setFormError] = useState<string | null>(null);
// Pre-fill form from URL params (e.g., ?clientName=Jane&clientEmail=jane@example.com)
const [searchParams] = useSearchParams();
useEffect(() => {
const clientName = searchParams.get("clientName");
const clientEmail = searchParams.get("clientEmail");
const clientPhone = searchParams.get("clientPhone");
const petName = searchParams.get("petName");
const petSpecies = searchParams.get("petSpecies");
const petBreed = searchParams.get("petBreed");
if (clientName || clientEmail || clientPhone || petName || petSpecies || petBreed) {
setForm((f) => ({
...f,
...(clientName && { clientName }),
...(clientEmail && { clientEmail }),
...(clientPhone && { clientPhone }),
...(petName && { petName }),
...(petSpecies && { petSpecies }),
...(petBreed && { petBreed }),
}));
}
}, [searchParams]);
// Step 4 — result
const [submitting, setSubmitting] = useState(false);
const [result, setResult] = useState<BookingResult | null>(null);
+31 -1
View File
@@ -1,4 +1,4 @@
import { useState } from "react";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useBranding } from "../BrandingContext.js";
@@ -17,6 +17,21 @@ export function SetupWizard() {
const [businessName, setBusinessName] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [guardLoading, setGuardLoading] = useState(true);
// Guard: redirect if setup is not needed
useEffect(() => {
fetch("/api/setup/status")
.then((r) => r.json())
.then((data) => {
if (data.needsSetup === false) {
navigate("/admin", { replace: true });
} else {
setGuardLoading(false);
}
})
.catch(() => setGuardLoading(false));
}, [navigate]);
const current = STEPS[step];
const isLast = step === STEPS.length - 1;
@@ -61,6 +76,21 @@ export function SetupWizard() {
if (step > 0) setStep((s) => s - 1);
};
if (guardLoading) {
return (
<div style={{
minHeight: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
background: "#f0f2f5",
fontFamily: "system-ui, sans-serif",
}}>
<p style={{ color: "#6b7280" }}>Checking setup status</p>
</div>
);
}
return (
<div style={{
minHeight: "100vh",
+77 -3
View File
@@ -11,6 +11,7 @@ const EMPTY_FORM: StaffForm = { name: "", email: "", role: "groomer" };
export function StaffPage() {
const [staff, setStaff] = useState<Staff[]>([]);
const [me, setMe] = useState<Staff | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [editing, setEditing] = useState<Staff | null>(null);
@@ -18,6 +19,11 @@ export function StaffPage() {
const [form, setForm] = useState<StaffForm>(EMPTY_FORM);
const [formError, setFormError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [togglingSuperUser, setTogglingSuperUser] = useState<string | null>(null);
const [toggleError, setToggleError] = useState<string | null>(null);
const isCurrentUserSuperUser = me?.isSuperUser ?? false;
const activeSuperUserCount = staff.filter((s) => s.active && s.isSuperUser).length;
async function load() {
const r = await fetch("/api/staff?includeInactive=true");
@@ -25,8 +31,15 @@ export function StaffPage() {
setStaff((await r.json()) as Staff[]);
}
async function loadMe() {
const r = await fetch("/api/staff/me");
if (r.ok) {
setMe((await r.json()) as Staff);
}
}
useEffect(() => {
load()
Promise.all([load(), loadMe()])
.catch((e: unknown) => setError(e instanceof Error ? e.message : "Unknown error"))
.finally(() => setLoading(false));
}, []);
@@ -71,6 +84,27 @@ export function StaffPage() {
await load();
}
async function toggleSuperUser(s: Staff) {
setTogglingSuperUser(s.id);
setToggleError(null);
try {
const newValue = !s.isSuperUser;
const res = await fetch(`/api/staff/${s.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ isSuperUser: newValue }),
});
if (!res.ok) {
const err = (await res.json()) as { error?: string };
setToggleError(err.error ?? `HTTP ${res.status}`);
return;
}
await load();
} finally {
setTogglingSuperUser(null);
}
}
if (loading) return <p style={{ padding: "1rem" }}>Loading</p>;
if (error) return <p style={{ padding: "1rem", color: "red" }}>Error: {error}</p>;
@@ -83,6 +117,12 @@ export function StaffPage() {
</button>
</div>
{toggleError && (
<p style={{ color: "#dc2626", background: "#fef2f2", border: "1px solid #fecaca", borderRadius: 6, padding: "0.5rem 0.75rem", marginBottom: "0.75rem", fontSize: 13 }}>
{toggleError}
</p>
)}
{staff.length === 0 ? (
<p>No staff members yet.</p>
) : (
@@ -90,7 +130,7 @@ export function StaffPage() {
<table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
<thead>
<tr style={{ background: "#f8fafc" }}>
{["Name", "Email", "Role", "Status", ""].map((h) => (
{["Name", "Email", "Role", "Super User", "Status", ""].map((h) => (
<th key={h} style={{ textAlign: "left", padding: "0.55rem 0.75rem", borderBottom: "1px solid #e5e7eb", fontSize: 11, fontWeight: 600, color: "#6b7280", textTransform: "uppercase", letterSpacing: "0.04em" }}>{h}</th>
))}
</tr>
@@ -101,6 +141,33 @@ export function StaffPage() {
<td style={tdStyle}>{s.name}</td>
<td style={tdStyle}>{s.email}</td>
<td style={tdStyle}><span style={{ textTransform: "capitalize" }}>{s.role}</span></td>
<td style={tdStyle}>
{s.isSuperUser ? (
<>
<span style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "2px 8px", borderRadius: 12, fontSize: 11, fontWeight: 600, background: "#ede9fe", color: "#5b21b6" }}>
Super User
</span>
{isCurrentUserSuperUser && s.id !== me?.id && (
<button
onClick={() => toggleSuperUser(s)}
disabled={togglingSuperUser === s.id || activeSuperUserCount <= 1}
title={activeSuperUserCount <= 1 ? "Cannot revoke: last super user" : undefined}
style={{ ...btnStyle, padding: "0.2rem 0.6rem", fontSize: 11, background: "#f3f4f6", color: "#374151", borderColor: "#d1d5db", marginLeft: 4 }}
>
{togglingSuperUser === s.id ? "…" : "Revoke"}
</button>
)}
</>
) : isCurrentUserSuperUser ? (
<button
onClick={() => toggleSuperUser(s)}
disabled={togglingSuperUser === s.id}
style={{ ...btnStyle, padding: "0.2rem 0.6rem", fontSize: 11, background: "#f3f4f6", color: "#374151", borderColor: "#d1d5db" }}
>
{togglingSuperUser === s.id ? "…" : "+ Grant"}
</button>
) : null}
</td>
<td style={tdStyle}>
<span style={{ padding: "2px 8px", borderRadius: 12, fontSize: 11, fontWeight: 600, background: s.active ? "#d1fae5" : "#f3f4f6", color: s.active ? "#065f46" : "#6b7280" }}>
{s.active ? "Active" : "Inactive"}
@@ -108,7 +175,14 @@ export function StaffPage() {
</td>
<td style={{ ...tdStyle, whiteSpace: "nowrap" }}>
<button onClick={() => openEdit(s)} style={{ ...btnStyle, marginRight: "0.4rem" }}>Edit</button>
<button onClick={() => toggleActive(s)} style={btnStyle}>{s.active ? "Deactivate" : "Activate"}</button>
<button
onClick={() => toggleActive(s)}
disabled={s.isSuperUser && activeSuperUserCount <= 1 && s.active}
title={s.isSuperUser && activeSuperUserCount <= 1 && s.active ? "Cannot deactivate the last super user" : undefined}
style={{ ...btnStyle, opacity: s.isSuperUser && activeSuperUserCount <= 1 && s.active ? 0.5 : 1 }}
>
{s.active ? "Deactivate" : "Activate"}
</button>
</td>
</tr>
))}
+4 -7
View File
@@ -5,7 +5,7 @@ import {
Settings, LogOut, Shield,
} from "lucide-react";
import { Dashboard } from "./sections/Dashboard.js";
import { AppointmentsSection, RescheduleFlow } from "./sections/Appointments.js";
import { AppointmentsSection, RescheduleFlow, type Appointment } from "./sections/Appointments.js";
import { PetProfiles } from "./sections/PetProfiles.js";
import { ReportCards } from "./sections/ReportCards.js";
import { BillingPayments } from "./sections/BillingPayments.js";
@@ -33,7 +33,7 @@ export function CustomerPortal() {
const [mobileNavOpen, setMobileNavOpen] = useState(false);
const [showAuditLog, setShowAuditLog] = useState(false);
const [showReschedule, setShowReschedule] = useState(false);
const [rescheduleAppointment, setRescheduleAppointment] = useState<Record<string, unknown> | null>(null);
const [rescheduleAppointment, setRescheduleAppointment] = useState<{ id: string } | null>(null);
const [session, setSession] = useState<ImpersonationSession | null>(null);
const [sessionExtended, setSessionExtended] = useState(false);
const [clientName, setClientName] = useState<string>("");
@@ -115,9 +115,7 @@ export function CustomerPortal() {
};
const handleReschedule = useCallback((appointmentId: string) => {
// Look up the full appointment from Dashboard's displayed data
// The appointment was already fetched by Dashboard, so we use the ID to find it
setRescheduleAppointment({ id: appointmentId } as Record<string, unknown>);
setRescheduleAppointment({ id: appointmentId });
setShowReschedule(true);
}, []);
@@ -176,9 +174,8 @@ export function CustomerPortal() {
)}
{showReschedule && rescheduleAppointment && (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
<RescheduleFlow
appointment={rescheduleAppointment as any}
appointment={rescheduleAppointment as unknown as Appointment}
onClose={() => { setShowReschedule(false); setRescheduleAppointment(null); }}
sessionId={session?.id ?? null}
/>
@@ -225,7 +225,6 @@ function ManagePets({ sessionId, readOnly }: { sessionId: string | null; readOnl
<PetForm
// eslint-disable-next-line @typescript-eslint/no-explicit-any
pet={(editingPet ?? undefined) as any}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onSave={() => { setEditingPetId(null); setShowAddForm(false); }}
onCancel={() => { setEditingPetId(null); setShowAddForm(false); }}
/>
@@ -1,7 +1,7 @@
import React, { useState, useEffect } from 'react';
import { Calendar, Clock, Plus, ChevronRight, ChevronDown, Loader2 } from 'lucide-react';
interface Appointment {
export interface Appointment {
id: string;
petId: string;
serviceId: string;