diff --git a/apps/api/src/routes/staff.ts b/apps/api/src/routes/staff.ts index 3316c45..3aa2f1a 100644 --- a/apps/api/src/routes/staff.ts +++ b/apps/api/src/routes/staff.ts @@ -15,7 +15,18 @@ 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"); + return c.json(staffRow); +}); staffRouter.get("/", async (c) => { const db = getDb(); @@ -45,11 +56,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 +157,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.js b/apps/web/src/pages/Book.js new file mode 100644 index 0000000..2aa1f73 --- /dev/null +++ b/apps/web/src/pages/Book.js @@ -0,0 +1,231 @@ +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +import { useEffect, useState } from "react"; +// ─── Helpers ───────────────────────────────────────────────────────────────── +function fmtPrice(cents) { + return `$${(cents / 100).toFixed(2)}`; +} +function fmtDuration(minutes) { + if (minutes < 60) + return `${minutes} min`; + const h = Math.floor(minutes / 60); + const m = minutes % 60; + return m > 0 ? `${h}h ${m}m` : `${h}h`; +} +function fmtTime(iso) { + return new Date(iso).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); +} +function fmtDateLong(isoDate) { + const d = new Date(isoDate + "T12:00:00Z"); + return d.toLocaleDateString([], { weekday: "long", year: "numeric", month: "long", day: "numeric" }); +} +function todayIso() { + return new Date().toISOString().slice(0, 10); +} +// ─── Sub-components ─────────────────────────────────────────────────────────── +function StepIndicator({ step }) { + const steps = ["Service", "Date & Time", "Your Info", "Confirm"]; + return (_jsx("div", { style: { display: "flex", gap: 0, marginBottom: "1.5rem" }, children: steps.map((label, i) => { + const idx = i + 1; + const active = idx === step; + const done = idx < step; + return (_jsxs("div", { style: { + flex: 1, + textAlign: "center", + padding: "0.5rem 0.25rem", + fontSize: 12, + fontWeight: active ? 700 : 400, + color: active ? "var(--color-primary)" : done ? "var(--color-primary)" : "#9ca3af", + borderBottom: `3px solid ${active ? "var(--color-primary)" : done ? "var(--color-primary)" : "#e5e7eb"}`, + }, children: [_jsx("span", { style: { + display: "inline-flex", + alignItems: "center", + justifyContent: "center", + width: 22, + height: 22, + borderRadius: "50%", + background: active ? "var(--color-primary)" : done ? "var(--color-primary)" : "#e5e7eb", + color: active || done ? "#fff" : "#6b7280", + fontSize: 12, + fontWeight: 700, + marginRight: 4, + }, children: done ? "✓" : idx }), label] }, label)); + }) })); +} +// ─── Main Component ─────────────────────────────────────────────────────────── +export function BookPage() { + const [step, setStep] = useState(1); + // Step 1 — service + const [services, setServices] = useState([]); + const [servicesLoading, setServicesLoading] = useState(true); + const [selectedService, setSelectedService] = useState(null); + // Step 2 — date & time + const [date, setDate] = useState(todayIso()); + const [dateError, setDateError] = useState(null); + const [slots, setSlots] = useState([]); + const [slotsLoading, setSlotsLoading] = useState(false); + const [selectedSlot, setSelectedSlot] = useState(null); + // Step 3 — contact info + const [form, setForm] = useState({ + serviceId: "", + startTime: "", + clientName: "", + clientEmail: "", + clientPhone: "", + petName: "", + petSpecies: "", + petBreed: "", + notes: "", + }); + const [formError, setFormError] = useState(null); + // Step 4 — result + const [submitting, setSubmitting] = useState(false); + const [result, setResult] = useState(null); + const [submitError, setSubmitError] = useState(null); + // Load services on mount + useEffect(() => { + fetch("/api/book/services") + .then((r) => r.json()) + .then(setServices) + .catch(() => setServices([])) + .finally(() => setServicesLoading(false)); + }, []); + // Load slots when service or date changes (step 2) + useEffect(() => { + if (!selectedService || !date) + return; + setSlotsLoading(true); + setSelectedSlot(null); + fetch(`/api/book/availability?serviceId=${encodeURIComponent(selectedService.id)}&date=${encodeURIComponent(date)}`) + .then((r) => r.json()) + .then(setSlots) + .catch(() => setSlots([])) + .finally(() => setSlotsLoading(false)); + }, [selectedService, date]); + function goToStep2(svc) { + setSelectedService(svc); + setForm((f) => ({ ...f, serviceId: svc.id })); + setDateError(null); + setStep(2); + } + function goToStep3() { + if (!selectedSlot) + return; + setForm((f) => ({ ...f, startTime: selectedSlot })); + setStep(3); + } + function goToStep4() { + if (!form.clientName.trim() || !form.clientEmail.trim() || !form.petName.trim() || !form.petSpecies.trim()) { + setFormError("Please fill in all required fields."); + return; + } + setFormError(null); + setStep(4); + } + async function submitBooking() { + setSubmitting(true); + setSubmitError(null); + try { + const res = await fetch("/api/book/appointments", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + serviceId: form.serviceId, + startTime: form.startTime, + clientName: form.clientName, + clientEmail: form.clientEmail, + clientPhone: form.clientPhone || undefined, + petName: form.petName, + petSpecies: form.petSpecies, + petBreed: form.petBreed || undefined, + notes: form.notes || undefined, + }), + }); + if (!res.ok) { + const body = (await res.json()); + throw new Error(body.error ?? `HTTP ${res.status}`); + } + const data = (await res.json()); + setResult(data); + setStep(5); + } + catch (e) { + setSubmitError(e instanceof Error ? e.message : "Something went wrong. Please try again."); + } + finally { + setSubmitting(false); + } + } + // ── Styles ── + const card = { + background: "#fff", + border: "1px solid #e5e7eb", + borderRadius: 8, + padding: "1rem", + cursor: "pointer", + }; + const selectedCard = { + ...card, + border: "2px solid var(--color-primary)", + background: "#f0faf5", + }; + const input = { + width: "100%", + padding: "0.5rem 0.75rem", + border: "1px solid #d1d5db", + borderRadius: 6, + fontSize: 14, + boxSizing: "border-box", + }; + const label = { + display: "block", + fontSize: 13, + fontWeight: 600, + color: "#374151", + marginBottom: 4, + }; + const btn = { + padding: "0.6rem 1.25rem", + borderRadius: 6, + border: "none", + cursor: "pointer", + fontSize: 14, + fontWeight: 600, + }; + const primaryBtn = { + ...btn, + background: "var(--color-primary)", + color: "#fff", + }; + const secondaryBtn = { + ...btn, + background: "#f3f4f6", + color: "#374151", + }; + return (_jsxs("div", { style: { maxWidth: 640, margin: "0 auto", padding: "1rem" }, children: [_jsxs("div", { style: { marginBottom: "1.5rem" }, children: [_jsx("h1", { style: { fontSize: 24, fontWeight: 700, color: "#1f2937", margin: 0 }, children: "Book an Appointment" }), _jsx("p", { style: { fontSize: 14, color: "#6b7280", marginTop: 4 }, children: "Schedule a grooming appointment for your pet in minutes." })] }), step < 5 && _jsx(StepIndicator, { step: step }), step === 1 && (_jsxs("div", { children: [_jsx("h2", { style: { fontSize: 16, fontWeight: 600, marginBottom: "0.75rem" }, children: "Choose a service" }), servicesLoading && _jsx("p", { style: { color: "#6b7280" }, children: "Loading services\u2026" }), !servicesLoading && services.length === 0 && (_jsx("p", { style: { color: "#ef4444" }, children: "No services available. Please contact us to book." })), _jsx("div", { style: { display: "flex", flexDirection: "column", gap: "0.75rem" }, children: services.map((svc) => (_jsx("div", { style: selectedService?.id === svc.id ? selectedCard : card, onClick: () => goToStep2(svc), role: "button", tabIndex: 0, onKeyDown: (e) => e.key === "Enter" && goToStep2(svc), children: _jsxs("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start" }, children: [_jsxs("div", { children: [_jsx("div", { style: { fontWeight: 600, fontSize: 15, color: "#1f2937" }, children: svc.name }), svc.description && (_jsx("div", { style: { fontSize: 13, color: "#6b7280", marginTop: 2 }, children: svc.description }))] }), _jsxs("div", { style: { textAlign: "right", flexShrink: 0, marginLeft: "1rem" }, children: [_jsx("div", { style: { fontWeight: 700, color: "var(--color-primary)", fontSize: 15 }, children: fmtPrice(svc.basePriceCents) }), _jsx("div", { style: { fontSize: 12, color: "#9ca3af" }, children: fmtDuration(svc.durationMinutes) })] })] }) }, svc.id))) })] })), step === 2 && selectedService && (_jsxs("div", { children: [_jsx("h2", { style: { fontSize: 16, fontWeight: 600, marginBottom: 4 }, children: "Choose a date and time" }), _jsxs("p", { style: { fontSize: 13, color: "#6b7280", marginBottom: "1rem" }, children: [selectedService.name, " \u2014 ", fmtDuration(selectedService.durationMinutes), " \u2014 ", fmtPrice(selectedService.basePriceCents)] }), _jsxs("div", { style: { marginBottom: "1rem" }, children: [_jsx("label", { style: label, children: "Date" }), _jsx("input", { type: "date", value: date, min: todayIso(), style: { ...input, width: "auto" }, onChange: (e) => { + const val = e.target.value; + if (val && !/^\d{4}-\d{2}-\d{2}$/.test(val)) { + setDateError("Please enter a date in YYYY-MM-DD format."); + return; + } + setDateError(null); + setDate(val); + } }), dateError && _jsx("p", { style: { color: "#ef4444", fontSize: 12, marginTop: 4 }, children: dateError })] }), _jsxs("div", { style: { marginBottom: "1.25rem" }, children: [_jsxs("label", { style: label, children: ["Available times on ", fmtDateLong(date)] }), slotsLoading && _jsx("p", { style: { color: "#6b7280", fontSize: 13 }, children: "Checking availability\u2026" }), !slotsLoading && slots.length === 0 && (_jsx("p", { style: { color: "#6b7280", fontSize: 13 }, children: "No available slots on this date. Please try another day." })), !slotsLoading && slots.length > 0 && (_jsx("div", { style: { display: "flex", flexWrap: "wrap", gap: "0.5rem", marginTop: "0.5rem" }, children: slots.map((slot) => (_jsx("button", { onClick: () => setSelectedSlot(slot), style: { + padding: "0.4rem 0.85rem", + borderRadius: 6, + border: `2px solid ${selectedSlot === slot ? "var(--color-primary)" : "#d1d5db"}`, + background: selectedSlot === slot ? "var(--color-primary)" : "#fff", + color: selectedSlot === slot ? "#fff" : "#374151", + fontSize: 13, + fontWeight: 500, + cursor: "pointer", + }, children: fmtTime(slot) }, slot))) }))] }), _jsxs("div", { style: { display: "flex", gap: "0.75rem" }, children: [_jsx("button", { style: secondaryBtn, onClick: () => setStep(1), children: "Back" }), _jsx("button", { style: { ...primaryBtn, opacity: selectedSlot ? 1 : 0.5 }, disabled: !selectedSlot, onClick: goToStep3, children: "Continue" })] })] })), step === 3 && (_jsxs("div", { children: [_jsx("h2", { style: { fontSize: 16, fontWeight: 600, marginBottom: "1rem" }, children: "Your information" }), _jsxs("div", { style: { display: "flex", flexDirection: "column", gap: "1rem" }, children: [_jsxs("fieldset", { style: { border: "1px solid #e5e7eb", borderRadius: 8, padding: "0.75rem 1rem" }, children: [_jsx("legend", { style: { fontSize: 13, fontWeight: 600, color: "#374151", padding: "0 0.25rem" }, children: "Contact details" }), _jsxs("div", { style: { display: "flex", flexDirection: "column", gap: "0.75rem" }, children: [_jsxs("div", { children: [_jsx("label", { style: label, children: "Full name *" }), _jsx("input", { style: input, value: form.clientName, onChange: (e) => setForm((f) => ({ ...f, clientName: e.target.value })), placeholder: "Jane Smith" })] }), _jsxs("div", { children: [_jsx("label", { style: label, children: "Email *" }), _jsx("input", { type: "email", style: input, value: form.clientEmail, onChange: (e) => setForm((f) => ({ ...f, clientEmail: e.target.value })), placeholder: "jane@example.com" })] }), _jsxs("div", { children: [_jsx("label", { style: label, children: "Phone" }), _jsx("input", { type: "tel", style: input, value: form.clientPhone, onChange: (e) => setForm((f) => ({ ...f, clientPhone: e.target.value })), placeholder: "(555) 000-1234" })] })] })] }), _jsxs("fieldset", { style: { border: "1px solid #e5e7eb", borderRadius: 8, padding: "0.75rem 1rem" }, children: [_jsx("legend", { style: { fontSize: 13, fontWeight: 600, color: "#374151", padding: "0 0.25rem" }, children: "Pet details" }), _jsxs("div", { style: { display: "flex", flexDirection: "column", gap: "0.75rem" }, children: [_jsxs("div", { children: [_jsx("label", { style: label, children: "Pet name *" }), _jsx("input", { style: input, value: form.petName, onChange: (e) => setForm((f) => ({ ...f, petName: e.target.value })), placeholder: "Buddy" })] }), _jsxs("div", { children: [_jsx("label", { style: label, children: "Species *" }), _jsxs("select", { style: input, value: form.petSpecies, onChange: (e) => setForm((f) => ({ ...f, petSpecies: e.target.value })), children: [_jsx("option", { value: "", children: "Select species\u2026" }), _jsx("option", { value: "dog", children: "Dog" }), _jsx("option", { value: "cat", children: "Cat" }), _jsx("option", { value: "rabbit", children: "Rabbit" }), _jsx("option", { value: "other", children: "Other" })] })] }), _jsxs("div", { children: [_jsx("label", { style: label, children: "Breed" }), _jsx("input", { style: input, value: form.petBreed, onChange: (e) => setForm((f) => ({ ...f, petBreed: e.target.value })), placeholder: "Golden Retriever" })] }), _jsxs("div", { children: [_jsx("label", { style: label, children: "Notes for groomer" }), _jsx("textarea", { style: { ...input, minHeight: 64, resize: "vertical", fontFamily: "inherit" }, value: form.notes, onChange: (e) => setForm((f) => ({ ...f, notes: e.target.value })), placeholder: "Any special requests or things we should know\u2026" })] })] })] })] }), formError && (_jsx("p", { style: { color: "#ef4444", fontSize: 13, marginTop: "0.75rem" }, children: formError })), _jsxs("div", { style: { display: "flex", gap: "0.75rem", marginTop: "1.25rem" }, children: [_jsx("button", { style: secondaryBtn, onClick: () => setStep(2), children: "Back" }), _jsx("button", { style: primaryBtn, onClick: goToStep4, children: "Review booking" })] })] })), step === 4 && selectedService && selectedSlot && (_jsxs("div", { children: [_jsx("h2", { style: { fontSize: 16, fontWeight: 600, marginBottom: "1rem" }, children: "Confirm your booking" }), _jsx("div", { style: { ...card, cursor: "default", marginBottom: "1.25rem" }, children: _jsxs("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.75rem", fontSize: 14 }, children: [_jsxs("div", { children: [_jsx("div", { style: { color: "#9ca3af", fontSize: 12, fontWeight: 600, textTransform: "uppercase" }, children: "Service" }), _jsx("div", { style: { fontWeight: 600 }, children: selectedService.name }), _jsxs("div", { style: { color: "#6b7280" }, children: [fmtPrice(selectedService.basePriceCents), " \u00B7 ", fmtDuration(selectedService.durationMinutes)] })] }), _jsxs("div", { children: [_jsx("div", { style: { color: "#9ca3af", fontSize: 12, fontWeight: 600, textTransform: "uppercase" }, children: "Date & Time" }), _jsx("div", { style: { fontWeight: 600 }, children: fmtDateLong(date) }), _jsx("div", { style: { color: "#6b7280" }, children: fmtTime(selectedSlot) })] }), _jsxs("div", { children: [_jsx("div", { style: { color: "#9ca3af", fontSize: 12, fontWeight: 600, textTransform: "uppercase" }, children: "Client" }), _jsx("div", { style: { fontWeight: 600 }, children: form.clientName }), _jsx("div", { style: { color: "#6b7280" }, children: form.clientEmail }), form.clientPhone && _jsx("div", { style: { color: "#6b7280" }, children: form.clientPhone })] }), _jsxs("div", { children: [_jsx("div", { style: { color: "#9ca3af", fontSize: 12, fontWeight: 600, textTransform: "uppercase" }, children: "Pet" }), _jsx("div", { style: { fontWeight: 600 }, children: form.petName }), _jsxs("div", { style: { color: "#6b7280", textTransform: "capitalize" }, children: [form.petSpecies, form.petBreed ? ` · ${form.petBreed}` : ""] })] }), form.notes && (_jsxs("div", { style: { gridColumn: "1 / -1" }, children: [_jsx("div", { style: { color: "#9ca3af", fontSize: 12, fontWeight: 600, textTransform: "uppercase" }, children: "Notes" }), _jsx("div", { style: { color: "#374151" }, children: form.notes })] }))] }) }), submitError && (_jsx("p", { style: { color: "#ef4444", fontSize: 13, marginBottom: "0.75rem" }, children: submitError })), _jsxs("div", { style: { display: "flex", gap: "0.75rem" }, children: [_jsx("button", { style: secondaryBtn, onClick: () => setStep(3), disabled: submitting, children: "Back" }), _jsx("button", { style: { ...primaryBtn, opacity: submitting ? 0.7 : 1 }, onClick: submitBooking, disabled: submitting, children: submitting ? "Booking…" : "Confirm booking" })] })] })), step === 5 && result && (_jsxs("div", { style: { textAlign: "center", padding: "2rem 1rem" }, children: [_jsx("div", { style: { fontSize: 48, marginBottom: "0.75rem" }, children: "\uD83D\uDC3E" }), _jsx("h2", { style: { fontSize: 20, fontWeight: 700, color: "#1f2937", marginBottom: "0.5rem" }, children: "Booking confirmed!" }), _jsxs("p", { style: { color: "#6b7280", fontSize: 14, marginBottom: "1.5rem" }, children: ["We've booked ", result.pet.name, " in for", " ", selectedService?.name, " on ", fmtDateLong(date), " at", " ", fmtTime(result.appointment.startTime), "."] }), _jsx("div", { style: { ...card, cursor: "default", textAlign: "left", marginBottom: "1.5rem" }, children: _jsxs("p", { style: { margin: 0, fontSize: 14, color: "#374151" }, children: ["A confirmation will be sent to ", _jsx("strong", { children: result.client.email }), ". If you need to reschedule or cancel, please contact us."] }) }), _jsx("button", { style: primaryBtn, onClick: () => { + setStep(1); + setSelectedService(null); + setSelectedSlot(null); + setResult(null); + setForm({ + serviceId: "", startTime: "", clientName: "", clientEmail: "", + clientPhone: "", petName: "", petSpecies: "", petBreed: "", notes: "", + }); + }, children: "Book another appointment" })] }))] })); +} diff --git a/apps/web/src/pages/Book.tsx b/apps/web/src/pages/Book.tsx index 0e0710d..dc58c9b 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 ─────────────────────────────────────────────────────────────────── @@ -107,6 +108,7 @@ export function BookPage() { // Step 2 — date & time const [date, setDate] = useState(todayIso()); + const [dateError, setDateError] = useState(null); const [slots, setSlots] = useState([]); const [slotsLoading, setSlotsLoading] = useState(false); const [selectedSlot, setSelectedSlot] = useState(null); @@ -125,6 +127,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); @@ -328,8 +352,21 @@ export function BookPage() { value={date} min={todayIso()} style={{ ...input, width: "auto" }} - onChange={(e) => setDate(e.target.value)} + onChange={(e) => { + const val = e.target.value; + // HTML5 date input enforces yyyy-MM-dd; empty value means invalid format + if (!val) { + setDateError("Please enter a valid date (YYYY-MM-DD)."); + setDate(""); + } else { + setDateError(null); + setDate(val); + } + }} /> + {dateError && ( +

{dateError}

+ )}
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; diff --git a/apps/web/src/portal/sections/ReportCards.js b/apps/web/src/portal/sections/ReportCards.js new file mode 100644 index 0000000..b85b183 --- /dev/null +++ b/apps/web/src/portal/sections/ReportCards.js @@ -0,0 +1,77 @@ +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +import { useState, useEffect } from "react"; +import { FileText, Share2, Calendar, Smile, Meh, ChevronRight, Loader2 } from "lucide-react"; +const MOOD_CONFIG = { + calm: { icon: Smile, label: "Calm & Relaxed", color: "text-green-700", bg: "bg-green-100" }, + cooperative: { icon: Smile, label: "Cooperative", color: "text-blue-700", bg: "bg-blue-100" }, + anxious: { icon: Meh, label: "Anxious", color: "text-amber-700", bg: "bg-amber-100" }, + wiggly: { icon: Meh, label: "Wiggly", color: "text-purple-700", bg: "bg-purple-100" }, +}; +export function ReportCards() { + const [appointments, setAppointments] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + const [selectedCard, setSelectedCard] = useState(null); + useEffect(() => { + const fetchReportCards = async () => { + try { + const response = await fetch("/api/portal/appointments"); + if (response.ok) { + const data = await response.json(); + const allAppointments = data.appointments || data || []; + const reportCardAppointments = allAppointments.filter((appt) => appt.reportCardId); + setAppointments(reportCardAppointments); + } + else { + setError("Failed to load report cards."); + } + } + catch { + setError("Failed to load report cards. Please try again."); + } + finally { + setIsLoading(false); + } + }; + fetchReportCards(); + }, []); + if (isLoading) { + return (_jsxs("div", { className: "flex items-center justify-center py-12", children: [_jsx(Loader2, { className: "animate-spin text-stone-400", size: 24 }), _jsx("span", { className: "ml-3 text-stone-500", children: "Loading report cards..." })] })); + } + if (error) { + return (_jsxs("div", { className: "text-center py-12", children: [_jsx("p", { className: "text-red-600 mb-4", children: error }), _jsx("button", { onClick: () => window.location.reload(), className: "px-4 py-2 bg-stone-100 text-stone-700 rounded-md hover:bg-stone-200", children: "Retry" })] })); + } + if (appointments.length === 0) { + return (_jsxs("div", { className: "text-center py-12", children: [_jsx("div", { className: "w-16 h-16 mx-auto mb-4 rounded-full bg-stone-100 flex items-center justify-center", children: _jsx(FileText, { size: 24, className: "text-stone-400" }) }), _jsx("h3", { className: "text-lg font-medium text-stone-800 mb-1", children: "No Report Cards Yet" }), _jsx("p", { className: "text-sm text-stone-500", children: "Report cards from your grooming visits will appear here after your appointments." })] })); + } + if (selectedCard) { + return _jsx(ReportCardDetail, { card: selectedCard, onBack: () => setSelectedCard(null) }); + } + return (_jsxs("div", { className: "space-y-6", children: [_jsx("p", { className: "text-sm text-stone-500", children: "Grooming report cards from your recent visits" }), _jsx("div", { className: "space-y-4", children: appointments.map((card) => { + const moodKey = "cooperative"; + const mood = MOOD_CONFIG[moodKey]; + const MoodIcon = mood.icon; + return (_jsx("button", { onClick: () => setSelectedCard(card), className: "w-full bg-white rounded-2xl border border-stone-200 p-5 shadow-sm text-left hover:border-stone-300 transition-colors", children: _jsxs("div", { className: "flex items-start gap-4", children: [_jsx("div", { className: "w-14 h-14 rounded-xl bg-(--color-accent-light) flex items-center justify-center text-(--color-accent)", children: _jsx(FileText, { size: 24 }) }), _jsxs("div", { className: "flex-1", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("h3", { className: "font-semibold text-stone-800", children: [card.petName || "Pet", "'s Report Card"] }), _jsx(ChevronRight, { size: 16, className: "text-stone-400" })] }), _jsxs("p", { className: "text-sm text-stone-500 mt-0.5", children: [card.serviceName || "Grooming", " with ", card.groomerName || "your groomer"] }), _jsxs("div", { className: "flex items-center gap-3 mt-2", children: [_jsxs("span", { className: "flex items-center gap-1 text-xs text-stone-400", children: [_jsx(Calendar, { size: 12 }), new Date(card.date).toLocaleDateString("en-US", { + month: "short", + day: "numeric", + year: "numeric", + })] }), _jsxs("span", { className: `flex items-center gap-1 text-xs px-2 py-0.5 rounded-full ${mood.bg} ${mood.color}`, children: [_jsx(MoodIcon, { size: 12 }), mood.label] })] })] })] }) }, card.id)); + }) })] })); +} +function ReportCardDetail({ card, onBack }) { + const moodKey = "cooperative"; + const mood = MOOD_CONFIG[moodKey]; + const MoodIcon = mood.icon; + return (_jsxs("div", { className: "space-y-6", children: [_jsx("button", { onClick: onBack, className: "text-sm text-(--color-accent-dark) font-medium hover:underline", children: "Back to Report Cards" }), _jsxs("div", { className: "bg-white rounded-2xl border border-stone-200 shadow-sm overflow-hidden", children: [_jsxs("div", { className: "bg-gradient-to-r from-(--color-accent-lighter) to-(--color-accent-light) p-6", children: [_jsxs("div", { className: "flex items-center justify-between mb-1", children: [_jsxs("h2", { className: "text-xl font-semibold text-stone-800", children: [card.petName || "Pet", "'s Grooming Report"] }), _jsxs("button", { className: "flex items-center gap-1.5 px-3 py-1.5 bg-white/80 text-stone-700 rounded-lg text-sm font-medium hover:bg-white", children: [_jsx(Share2, { size: 14 }), "Share"] })] }), _jsxs("p", { className: "text-sm text-stone-600", children: [new Date(card.date).toLocaleDateString("en-US", { + weekday: "long", + month: "long", + day: "numeric", + year: "numeric", + }), card.groomerName ? ` · Groomer: ${card.groomerName}` : ""] })] }), _jsxs("div", { className: "p-6 space-y-6", children: [_jsxs("div", { children: [_jsx("h3", { className: "font-medium text-stone-800 mb-3", children: "Before & After" }), _jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-4", children: [_jsxs("div", { className: "rounded-xl bg-stone-50 p-4", children: [_jsx("p", { className: "text-xs font-medium text-stone-400 uppercase mb-2", children: "Before" }), _jsx("div", { className: "w-full h-32 bg-stone-200 rounded-lg flex items-center justify-center text-stone-400 text-sm mb-2", children: "Photo placeholder" }), _jsx("p", { className: "text-sm text-stone-600", children: "Before photo description not available." })] }), _jsxs("div", { className: "rounded-xl bg-(--color-accent-lighter) p-4", children: [_jsx("p", { className: "text-xs font-medium text-(--color-accent) uppercase mb-2", children: "After" }), _jsx("div", { className: "w-full h-32 bg-(--color-accent-light) rounded-lg flex items-center justify-center text-(--color-accent) text-sm mb-2", children: "Photo placeholder" }), _jsx("p", { className: "text-sm text-stone-700", children: "After photo description not available." })] })] })] }), _jsxs("div", { children: [_jsx("h3", { className: "font-medium text-stone-800 mb-2", children: "Services Performed" }), _jsx("div", { className: "flex flex-wrap gap-2", children: _jsx("span", { className: "px-3 py-1 bg-stone-100 rounded-full text-sm text-stone-700", children: card.serviceName || "Grooming" }) })] }), _jsxs("div", { children: [_jsx("h3", { className: "font-medium text-stone-800 mb-2", children: "Behavior & Mood" }), _jsxs("div", { className: `inline-flex items-center gap-2 px-4 py-2 rounded-xl ${mood.bg}`, children: [_jsx(MoodIcon, { size: 20, className: mood.color }), _jsx("span", { className: `font-medium ${mood.color}`, children: mood.label })] })] }), _jsxs("div", { className: "bg-(--color-accent-lighter) rounded-xl p-4", children: [_jsxs("h3", { className: "font-medium text-stone-800 mb-2", children: ["A Note from ", card.groomerName || "Your Groomer"] }), _jsx("p", { className: "text-sm text-stone-700 italic leading-relaxed", children: "\"Report card details are not yet available. Please check back after your visit.\"" })] }), _jsxs("div", { className: "bg-white border border-stone-200 rounded-xl p-4 flex items-center justify-between", children: [_jsxs("div", { children: [_jsx("p", { className: "text-sm font-medium text-stone-800", children: "Book your next visit" }), _jsx("p", { className: "text-xs text-stone-500", children: "Schedule your next grooming appointment" })] }), _jsx("button", { onClick: () => { + // TODO: Pre-select the service from report card (serviceId/serviceName) once BookPage supports service pre-selection via URL param + const params = new URLSearchParams(); + if (card.petName) params.set("petName", card.petName); + if (card.serviceName) params.set("serviceName", card.serviceName); + window.location.href = `/admin/book${params.size > 0 ? `?${params.toString()}` : ""}`; + }, className: "px-4 py-2 bg-(--color-accent) text-white rounded-lg text-sm font-medium hover:bg-(--color-accent-hover)", children: "Rebook Now" })] })] })] })] })); +} \ No newline at end of file diff --git a/apps/web/src/portal/sections/ReportCards.tsx b/apps/web/src/portal/sections/ReportCards.tsx index f1136a3..a8d471b 100644 --- a/apps/web/src/portal/sections/ReportCards.tsx +++ b/apps/web/src/portal/sections/ReportCards.tsx @@ -241,8 +241,17 @@ function ReportCardDetail({ card, onBack }: { card: Appointment; onBack: () => v

Book your next visit

Schedule your next grooming appointment

-
{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() { - +