fix(gro-38): prod/demo auth and API-based seed (#117)
Closes GRO-38. Adds POST /api/admin/seed (manager-only, gated by SEED_KNOWN_USERS_ONLY) and separates dev vs prod seeding paths. Reviewed and approved by CTO and QA. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit was merged in pull request #117.
This commit is contained in:
committed by
GitHub
parent
d0b4baf5aa
commit
e3220af9ce
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Admin seed endpoint — populates minimal known-user seed data via the API.
|
||||
*
|
||||
* This is the canonical way to seed prod/demo data. The old approach (seed.ts
|
||||
* writing directly to the DB) bypasses API validation and audit trails.
|
||||
*
|
||||
* Security: This endpoint is manager-only (enforced via requireRole in index.ts).
|
||||
* It is disabled when AUTH_DISABLED=true — dev/test seeding should use the
|
||||
* direct-DB seed.ts in that mode.
|
||||
*/
|
||||
|
||||
import { Hono } from "hono";
|
||||
import { eq, getDb, staff, clients, pets, services } from "@groombook/db";
|
||||
|
||||
export const adminSeedRouter = new Hono();
|
||||
|
||||
const KNOWN_STAFF = {
|
||||
name: "Demo Manager",
|
||||
email: "demo-manager@groombook.dev",
|
||||
oidcSub: "demo-manager-001",
|
||||
role: "manager" as const,
|
||||
active: true,
|
||||
};
|
||||
|
||||
const KNOWN_CLIENT = {
|
||||
name: "Demo Client",
|
||||
email: "demo-client@example.com",
|
||||
phone: "555-0001",
|
||||
address: "1 Demo Street, Demo City, CA 90210",
|
||||
};
|
||||
|
||||
const DEMO_PET = {
|
||||
name: "Demo Dog",
|
||||
species: "Dog",
|
||||
breed: "Golden Retriever",
|
||||
weightKg: "30.00",
|
||||
};
|
||||
|
||||
const DEMO_SERVICES = [
|
||||
{ name: "Bath & Brush", description: "Full bath, blow-dry, brush out, and ear cleaning", basePriceCents: 4500, durationMinutes: 45 },
|
||||
{ name: "Full Groom — Small", description: "Complete grooming for dogs under 25 lbs", basePriceCents: 6500, durationMinutes: 60 },
|
||||
{ name: "Full Groom — Medium", description: "Complete grooming for dogs 25-50 lbs", basePriceCents: 8000, durationMinutes: 75 },
|
||||
{ name: "Nail Trim", description: "Nail clipping and filing", basePriceCents: 1500, durationMinutes: 15 },
|
||||
];
|
||||
|
||||
adminSeedRouter.post("/seed", async (c) => {
|
||||
// Refuse to run when AUTH_DISABLED — dev environments use direct-DB seeding
|
||||
if (process.env.AUTH_DISABLED === "true") {
|
||||
return c.json(
|
||||
{
|
||||
error:
|
||||
"Seed endpoint is not available when AUTH_DISABLED=true. Use direct DB seeding for dev/test environments.",
|
||||
},
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
const db = getDb();
|
||||
const results: string[] = [];
|
||||
|
||||
// ── Staff: Demo Manager ─────────────────────────────────────────────────────
|
||||
const [existingStaff] = await db
|
||||
.select()
|
||||
.from(staff)
|
||||
.where(eq(staff.email, KNOWN_STAFF.email));
|
||||
|
||||
if (existingStaff) {
|
||||
results.push(`Staff '${KNOWN_STAFF.name}' already exists (id: ${existingStaff.id})`);
|
||||
} else {
|
||||
const [created] = await db.insert(staff).values(KNOWN_STAFF).returning();
|
||||
results.push(`Created staff '${KNOWN_STAFF.name}' (id: ${created!.id}, oidcSub: ${KNOWN_STAFF.oidcSub})`);
|
||||
}
|
||||
|
||||
// ── Services: only seed if none exist ─────────────────────────────────────
|
||||
const existingServices = await db.select().from(services).limit(1);
|
||||
if (existingServices.length > 0) {
|
||||
results.push("Services already exist — skipping");
|
||||
} else {
|
||||
const created: { id: string; name: string }[] = [];
|
||||
for (const svc of DEMO_SERVICES) {
|
||||
const [row] = await db.insert(services).values({ ...svc, active: true }).returning();
|
||||
created.push(row!);
|
||||
}
|
||||
results.push(`Created ${created.length} services: ${created.map((s) => s.name).join(", ")}`);
|
||||
}
|
||||
|
||||
// ── Client: Demo Client ───────────────────────────────────────────────────
|
||||
const [existingClient] = await db
|
||||
.select()
|
||||
.from(clients)
|
||||
.where(eq(clients.email, KNOWN_CLIENT.email));
|
||||
|
||||
let clientId: string;
|
||||
if (existingClient) {
|
||||
clientId = existingClient.id;
|
||||
results.push(`Client '${KNOWN_CLIENT.name}' already exists (id: ${clientId})`);
|
||||
} else {
|
||||
const [created] = await db.insert(clients).values(KNOWN_CLIENT).returning();
|
||||
clientId = created!.id;
|
||||
results.push(`Created client '${KNOWN_CLIENT.name}' (id: ${clientId})`);
|
||||
}
|
||||
|
||||
// ── Pet: Demo Dog ──────────────────────────────────────────────────────────
|
||||
const existingPets = await db
|
||||
.select()
|
||||
.from(pets)
|
||||
.where(eq(pets.clientId, clientId));
|
||||
|
||||
const demoDog = existingPets.find(
|
||||
(p) => p.name === DEMO_PET.name && p.species === DEMO_PET.species
|
||||
);
|
||||
|
||||
if (demoDog) {
|
||||
results.push(`Pet '${DEMO_PET.name}' already exists for Demo Client (id: ${demoDog.id})`);
|
||||
} else {
|
||||
const [created] = await db
|
||||
.insert(pets)
|
||||
.values({
|
||||
clientId,
|
||||
name: DEMO_PET.name,
|
||||
species: DEMO_PET.species,
|
||||
breed: DEMO_PET.breed,
|
||||
weightKg: DEMO_PET.weightKg,
|
||||
dateOfBirth: new Date("2020-06-15T00:00:00Z"),
|
||||
})
|
||||
.returning();
|
||||
results.push(`Created pet '${DEMO_PET.name}' for Demo Client (id: ${created!.id})`);
|
||||
}
|
||||
|
||||
return c.json({
|
||||
message: "Seed complete",
|
||||
details: results,
|
||||
credentials: {
|
||||
note: "For dev-mode access, use X-Dev-User-Id: demo-manager-001 header",
|
||||
staffOidcSub: KNOWN_STAFF.oidcSub,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
staff,
|
||||
} from "@groombook/db";
|
||||
import { buildConfirmationEmail, sendEmail } from "../services/email.js";
|
||||
import { notifyWaitlistForAppointment } from "../services/waitlistNotify.js";
|
||||
|
||||
export const appointmentsRouter = new Hono();
|
||||
|
||||
@@ -510,16 +511,38 @@ appointmentsRouter.delete("/:id", async (c) => {
|
||||
.set({ status: "cancelled", updatedAt: new Date() })
|
||||
.where(eq(appointments.id, id));
|
||||
}
|
||||
|
||||
const apptDate = current.startTime.toISOString().slice(0, 10);
|
||||
const apptTime = current.startTime.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: true });
|
||||
notifyWaitlistForAppointment(id, apptDate, apptTime, current.serviceId).catch((err) => {
|
||||
console.error("[appointments] Failed to notify waitlist:", err);
|
||||
});
|
||||
|
||||
return c.json({ ok: true });
|
||||
}
|
||||
|
||||
// Single cancel (default)
|
||||
const [current] = await db
|
||||
.select()
|
||||
.from(appointments)
|
||||
.where(eq(appointments.id, id))
|
||||
.limit(1);
|
||||
if (!current) return c.json({ error: "Not found" }, 404);
|
||||
|
||||
const apptDate = current.startTime.toISOString().slice(0, 10);
|
||||
const apptTime = current.startTime.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: true });
|
||||
|
||||
const [row] = await db
|
||||
.update(appointments)
|
||||
.set({ status: "cancelled", updatedAt: new Date() })
|
||||
.where(eq(appointments.id, id))
|
||||
.returning();
|
||||
if (!row) return c.json({ error: "Not found" }, 404);
|
||||
|
||||
notifyWaitlistForAppointment(id, apptDate, apptTime, current.serviceId).catch((err) => {
|
||||
console.error("[appointments] Failed to notify waitlist:", err);
|
||||
});
|
||||
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Hono } from "hono";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { z } from "zod";
|
||||
import { and, eq, getDb, appointments, impersonationSessions } from "@groombook/db";
|
||||
import { and, eq, getDb, appointments, impersonationSessions, waitlistEntries } from "@groombook/db";
|
||||
import type { AppEnv } from "../middleware/rbac.js";
|
||||
|
||||
export const portalRouter = new Hono<AppEnv>();
|
||||
@@ -75,3 +75,159 @@ portalRouter.patch(
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
// ─── Client-facing waitlist routes ───────────────────────────────────────────
|
||||
|
||||
const createWaitlistEntrySchema = z.object({
|
||||
petId: z.string().uuid(),
|
||||
serviceId: z.string().uuid(),
|
||||
preferredDate: z.string(),
|
||||
preferredTime: z.string(),
|
||||
});
|
||||
|
||||
const updateWaitlistEntrySchema = z.object({
|
||||
status: z.literal("cancelled").optional(),
|
||||
preferredDate: z.string().optional(),
|
||||
preferredTime: z.string().optional(),
|
||||
});
|
||||
|
||||
portalRouter.post(
|
||||
"/waitlist",
|
||||
zValidator("json", createWaitlistEntrySchema),
|
||||
async (c) => {
|
||||
const db = getDb();
|
||||
const body = c.req.valid("json");
|
||||
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||
|
||||
let clientId: string | null = null;
|
||||
if (sessionId) {
|
||||
const [session] = await db
|
||||
.select()
|
||||
.from(impersonationSessions)
|
||||
.where(
|
||||
and(
|
||||
eq(impersonationSessions.id, sessionId),
|
||||
eq(impersonationSessions.status, "active")
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
if (session && session.expiresAt > new Date()) {
|
||||
clientId = session.clientId;
|
||||
}
|
||||
}
|
||||
|
||||
if (!clientId) {
|
||||
return c.json({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
|
||||
const [entry] = await db
|
||||
.insert(waitlistEntries)
|
||||
.values({
|
||||
clientId,
|
||||
petId: body.petId,
|
||||
serviceId: body.serviceId,
|
||||
preferredDate: body.preferredDate,
|
||||
preferredTime: body.preferredTime,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return c.json(entry, 201);
|
||||
}
|
||||
);
|
||||
|
||||
portalRouter.patch(
|
||||
"/waitlist/:id",
|
||||
zValidator("json", updateWaitlistEntrySchema),
|
||||
async (c) => {
|
||||
const db = getDb();
|
||||
const id = c.req.param("id");
|
||||
const body = c.req.valid("json");
|
||||
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||
|
||||
if (!sessionId) {
|
||||
return c.json({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
|
||||
const [session] = await db
|
||||
.select()
|
||||
.from(impersonationSessions)
|
||||
.where(
|
||||
and(
|
||||
eq(impersonationSessions.id, sessionId),
|
||||
eq(impersonationSessions.status, "active")
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!session || session.expiresAt <= new Date()) {
|
||||
return c.json({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
|
||||
const [existing] = await db
|
||||
.select()
|
||||
.from(waitlistEntries)
|
||||
.where(eq(waitlistEntries.id, id))
|
||||
.limit(1);
|
||||
|
||||
if (!existing) return c.json({ error: "Not found" }, 404);
|
||||
if (existing.clientId !== session.clientId) {
|
||||
return c.json({ error: "Forbidden" }, 403);
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = { updatedAt: new Date() };
|
||||
if (body.status !== undefined) updateData.status = body.status;
|
||||
if (body.preferredDate !== undefined) updateData.preferredDate = body.preferredDate;
|
||||
if (body.preferredTime !== undefined) updateData.preferredTime = body.preferredTime;
|
||||
|
||||
const [updated] = await db
|
||||
.update(waitlistEntries)
|
||||
.set(updateData)
|
||||
.where(eq(waitlistEntries.id, id))
|
||||
.returning();
|
||||
|
||||
return c.json(updated);
|
||||
}
|
||||
);
|
||||
|
||||
portalRouter.delete("/waitlist/:id", async (c) => {
|
||||
const db = getDb();
|
||||
const id = c.req.param("id");
|
||||
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||
|
||||
if (!sessionId) {
|
||||
return c.json({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
|
||||
const [session] = await db
|
||||
.select()
|
||||
.from(impersonationSessions)
|
||||
.where(
|
||||
and(
|
||||
eq(impersonationSessions.id, sessionId),
|
||||
eq(impersonationSessions.status, "active")
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!session || session.expiresAt <= new Date()) {
|
||||
return c.json({ error: "Unauthorized" }, 401);
|
||||
}
|
||||
|
||||
const [entry] = await db
|
||||
.select()
|
||||
.from(waitlistEntries)
|
||||
.where(eq(waitlistEntries.id, id))
|
||||
.limit(1);
|
||||
|
||||
if (!entry) return c.json({ error: "Not found" }, 404);
|
||||
if (entry.clientId !== session.clientId) {
|
||||
return c.json({ error: "Forbidden" }, 403);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(waitlistEntries)
|
||||
.where(eq(waitlistEntries.id, id))
|
||||
.returning();
|
||||
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Hono } from "hono";
|
||||
import {
|
||||
and,
|
||||
eq,
|
||||
lt,
|
||||
getDb,
|
||||
waitlistEntries,
|
||||
clients,
|
||||
pets,
|
||||
services,
|
||||
} from "@groombook/db";
|
||||
import type { AppEnv } from "../middleware/rbac.js";
|
||||
|
||||
export const waitlistRouter = new Hono<AppEnv>();
|
||||
|
||||
async function markExpiredEntries(db: ReturnType<typeof getDb>, rows: { status: string; preferredDate: string }[]) {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const hasExpired = rows.some((r) => r.status === "active" && r.preferredDate < today);
|
||||
if (hasExpired) {
|
||||
await db
|
||||
.update(waitlistEntries)
|
||||
.set({ status: "expired", updatedAt: new Date() })
|
||||
.where(and(eq(waitlistEntries.status, "active"), lt(waitlistEntries.preferredDate, today)));
|
||||
}
|
||||
}
|
||||
|
||||
waitlistRouter.get("/", async (c) => {
|
||||
const db = getDb();
|
||||
const date = c.req.query("date");
|
||||
|
||||
const conditions = [];
|
||||
if (date) {
|
||||
conditions.push(eq(waitlistEntries.preferredDate, date));
|
||||
}
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: waitlistEntries.id,
|
||||
clientId: waitlistEntries.clientId,
|
||||
petId: waitlistEntries.petId,
|
||||
serviceId: waitlistEntries.serviceId,
|
||||
preferredDate: waitlistEntries.preferredDate,
|
||||
preferredTime: waitlistEntries.preferredTime,
|
||||
status: waitlistEntries.status,
|
||||
notifiedAt: waitlistEntries.notifiedAt,
|
||||
expiresAt: waitlistEntries.expiresAt,
|
||||
createdAt: waitlistEntries.createdAt,
|
||||
updatedAt: waitlistEntries.updatedAt,
|
||||
clientName: clients.name,
|
||||
clientEmail: clients.email,
|
||||
petName: pets.name,
|
||||
serviceName: services.name,
|
||||
})
|
||||
.from(waitlistEntries)
|
||||
.leftJoin(clients, eq(waitlistEntries.clientId, clients.id))
|
||||
.leftJoin(pets, eq(waitlistEntries.petId, pets.id))
|
||||
.leftJoin(services, eq(waitlistEntries.serviceId, services.id))
|
||||
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
||||
.orderBy(waitlistEntries.createdAt);
|
||||
|
||||
await markExpiredEntries(db, rows);
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const enriched = rows.map((row) => ({
|
||||
...row,
|
||||
status: row.status === "active" && row.preferredDate < today ? "expired" : row.status,
|
||||
}));
|
||||
|
||||
return c.json(enriched);
|
||||
});
|
||||
|
||||
waitlistRouter.get("/:id", async (c) => {
|
||||
const db = getDb();
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(waitlistEntries)
|
||||
.where(eq(waitlistEntries.id, c.req.param("id")))
|
||||
.limit(1);
|
||||
if (!row) return c.json({ error: "Not found" }, 404);
|
||||
|
||||
await markExpiredEntries(db, [row]);
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const isExpired = row.status === "active" && row.preferredDate < today;
|
||||
return c.json({
|
||||
...row,
|
||||
status: isExpired ? "expired" : row.status,
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user