diff --git a/apps/api/src/routes/staff.ts b/apps/api/src/routes/staff.ts index 3316c45..845e15d 100644 --- a/apps/api/src/routes/staff.ts +++ b/apps/api/src/routes/staff.ts @@ -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 }); }); diff --git a/apps/web/src/pages/Book.tsx b/apps/web/src/pages/Book.tsx index 0e0710d..33df3a8 100644 --- a/apps/web/src/pages/Book.tsx +++ b/apps/web/src/pages/Book.tsx @@ -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(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(null); diff --git a/apps/web/src/pages/SetupWizard.jsx b/apps/web/src/pages/SetupWizard.jsx index 69ed08d..72fa949 100644 --- a/apps/web/src/pages/SetupWizard.jsx +++ b/apps/web/src/pages/SetupWizard.jsx @@ -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 ( +
+

Checking setup status…

+
+ ); + } + return (
([]); + const [me, setMe] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [editing, setEditing] = useState(null); @@ -18,6 +19,11 @@ export function StaffPage() { const [form, setForm] = useState(EMPTY_FORM); const [formError, setFormError] = useState(null); const [saving, setSaving] = useState(false); + const [togglingSuperUser, setTogglingSuperUser] = useState(null); + const [toggleError, setToggleError] = useState(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

Loading…

; if (error) return

Error: {error}

; @@ -83,6 +117,12 @@ export function StaffPage() {
+ {toggleError && ( +

+ {toggleError} +

+ )} + {staff.length === 0 ? (

No staff members yet.

) : ( @@ -90,7 +130,7 @@ export function StaffPage() { - {["Name", "Email", "Role", "Status", ""].map((h) => ( + {["Name", "Email", "Role", "Super User", "Status", ""].map((h) => ( ))} @@ -101,6 +141,33 @@ export function StaffPage() { + ))} diff --git a/apps/web/src/portal/CustomerPortal.tsx b/apps/web/src/portal/CustomerPortal.tsx index d8ba8bc..c03e323 100644 --- a/apps/web/src/portal/CustomerPortal.tsx +++ b/apps/web/src/portal/CustomerPortal.tsx @@ -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 | null>(null); + const [rescheduleAppointment, setRescheduleAppointment] = useState<{ id: string } | null>(null); const [session, setSession] = useState(null); const [sessionExtended, setSessionExtended] = useState(false); const [clientName, setClientName] = useState(""); @@ -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); + setRescheduleAppointment({ id: appointmentId }); setShowReschedule(true); }, []); @@ -176,9 +174,8 @@ export function CustomerPortal() { )} {showReschedule && rescheduleAppointment && ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any { setShowReschedule(false); setRescheduleAppointment(null); }} sessionId={session?.id ?? null} /> diff --git a/apps/web/src/portal/sections/AccountSettings.tsx b/apps/web/src/portal/sections/AccountSettings.tsx index 2fba3a6..8a5bc4e 100644 --- a/apps/web/src/portal/sections/AccountSettings.tsx +++ b/apps/web/src/portal/sections/AccountSettings.tsx @@ -225,7 +225,6 @@ function ManagePets({ sessionId, readOnly }: { sessionId: string | null; readOnl { setEditingPetId(null); setShowAddForm(false); }} onCancel={() => { setEditingPetId(null); setShowAddForm(false); }} /> diff --git a/apps/web/src/portal/sections/Appointments.tsx b/apps/web/src/portal/sections/Appointments.tsx index 03fcad1..ac25e82 100644 --- a/apps/web/src/portal/sections/Appointments.tsx +++ b/apps/web/src/portal/sections/Appointments.tsx @@ -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;
{h}
{s.name} {s.email} {s.role} + {s.isSuperUser ? ( + <> + + ★ Super User + + {isCurrentUserSuperUser && s.id !== me?.id && ( + + )} + + ) : isCurrentUserSuperUser ? ( + + ) : null} + {s.active ? "Active" : "Inactive"} @@ -108,7 +175,14 @@ export function StaffPage() { - +