ad1f32eb8f
* feat(db): add Better-Auth schema tables (GRO-118) Add user, session, account, and verification tables required by Better-Auth's Drizzle adapter. Add nullable userId FK on staff to link business identity to auth identity. Fix test fixtures and factory to include the new column. Co-Authored-By: Paperclip <noreply@paperclip.ing> * feat(api): mount Better-Auth handler at /api/auth/** (GRO-118) - Import toNodeHandler from better-auth/node and auth from ./lib/auth.js - Mount Better-Auth HTTP handler before auth middleware block - Handles OAuth callbacks, sign-in/sign-out, session management - Supports GET/POST/PUT/PATCH/DELETE/OPTIONS methods Co-Authored-By: Paperclip <noreply@paperclip.ing> * feat(api): replace JWT auth with Better-Auth session validation (GRO-118) - Replace jose/jwtVerify with auth.api.getSession() - Session token validated via cookie/header, DB-backed - jwtPayload.sub now = Better-Auth user ID (not OIDC sub) - Dev mode bypass preserved; production guard against AUTH_DISABLED preserved - rbac.ts and tests updated in subsequent tasks Co-Authored-By: Paperclip <noreply@paperclip.ing> * feat(api): update resolveStaffMiddleware for Better-Auth userId (GRO-118) - Remove JwtPayload import; use inline type in AppEnv - Production and dev mode lookups now use staff.userId (not oidcSub) - Backward compat: jwtPayload.sub now = Better-Auth user ID Co-Authored-By: Paperclip <noreply@paperclip.ing> * chore(api): remove jose and openid-client deps (GRO-118) - Remove unused jose and openid-client packages - Regenerate pnpm lockfile - Pre-existing Zod type errors resolved (1 remaining: JwtPayload in test) Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(api): remove stale JwtPayload import from impersonation test (GRO-118) auth.ts no longer exports JwtPayload — replace with inline type. Co-Authored-By: Paperclip <noreply@paperclip.ing> * test(api): update RBAC tests for Better-Auth userId (GRO-128) - Add userId field to mock staff records (MANAGER, RECEPTIONIST, GROOMER) - Update jwtPayload.sub to use userId instead of oidcSub in test helpers - Update dev mode X-Dev-User-Id header to use userId Co-Authored-By: Paperclip <noreply@paperclip.ing> * chore(api): upgrade zod to v4 with v3 compat layer (GRO-131) - Bump zod from ^3.24.1 to ^4.3.6 - Bump @hono/zod-validator from ^0.4.3 to ^0.7.6 - Update all 12 route files to import from "zod/v3" compat layer Co-Authored-By: Paperclip <noreply@paperclip.ing> * feat(api): add Better-Auth configuration (GRO-118) Exports the better-auth() instance configured with: - Drizzle PG adapter - genericOAuth plugin for Authentik OIDC - 7-day session with 5-min cookie cache Co-Authored-By: Paperclip <noreply@paperclip.ing> * feat(web): install Better-Auth client and create config (GRO-118) - Add better-auth to apps/web/package.json dependencies - Create apps/web/src/lib/auth-client.ts with createAuthClient config - Export signIn, signOut, useSession from the client - Add vite-env.d.ts for Vite client types Co-Authored-By: Paperclip <noreply@paperclip.ing> * feat(web): use Better-Auth session state in App.tsx (GRO-126) Add useSession hook to check Better-Auth session for production auth. Redirect to Authentik sign-in when no session in production mode. Dev mode flow (DevLoginSelector) preserved. Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(web): scope devFetch interceptor to dev mode only (GRO-127) * fix(api): validate BETTER_AUTH_SECRET and fix lockfile specifier (GRO-118) - Add startup validation for BETTER_AUTH_SECRET when auth is enabled - Fix pnpm-lock.yaml typescript specifier mismatch (^5.9.3 → ^5.7.3) Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(web): mock authDisabled=true in App.test.tsx to fix CI failures App.test.tsx "App navigation" tests were failing because the beforeEach set authDisabled=false (production mode), which triggers the Better Auth useSession() path. Since useSession() was not mocked in tests, the component rendered null instead of the admin nav. Now uses authDisabled=true + dev user in localStorage for those tests, bypassing the Better Auth dependency while still testing the nav render. Also removes duplicate App.test.js (compiled artifact). Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(e2e): set authDisabled=true in fixtures to bypass Better Auth The App.tsx production auth path calls signIn.social() when authDisabled=false, causing E2E tests to render blank. The fixtures must mock authDisabled=true so the dev login selector is used instead. Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(e2e): add dev/config, dev/users, and branding mocks to navigation.spec.ts Playwright matches routes in last-registered-first-served order, so the catch-all /api/** handler was overwriting the authDisabled: true fixture. Added specific handlers before the catch-all to ensure auth config, user list, and branding responses are properly shaped. Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(web): gate DevLoginSelector on API authDisabled, not import.meta.env.DEV Move the DevLoginSelector rendering check from import.meta.env.DEV to the API-driven authDisabled state, after the loading guard. Simplify the redirect condition to remove the now-redundant pathname exception. Fixes E2E login tests that were failing because DevLoginSelector was never rendered in Docker production builds where import.meta.env.DEV is false. Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(db): add missing migration journal entries 0012-0017 Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(web): import App.tsx (not App.js) in App.test.tsx (#137) * fix(web): mock /api/auth/get-session in Dev login selector test The "redirects to /login when auth is disabled and no user selected" test fails because useSession() from better-auth/react calls /api/auth/get-session which wasn't mocked, causing sessionLoading to stay true indefinitely. Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(web): import App.tsx (not App.js) in test to get authDisabled bypass The Dev login selector test was importing the compiled App.js instead of the source App.tsx. App.js has different logic (uses import.meta.env.DEV instead of API-based authDisabled) and doesn't implement the sessionLoading bypass needed for tests to pass. Also applied the rawSession/rawSessionLoading refactor in App.tsx that bypasses useSession result when authDisabled=true. Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(web): use extensionless import for App in test The `.tsx` extension in the import path is not allowed without `allowImportingTsExtensions` (TS5097). Use extensionless `../App` which resolves correctly via moduleResolution: "bundler". Co-Authored-By: Paperclip <noreply@paperclip.ing> --------- Co-authored-by: Paperclip <noreply@paperclip.ing> * fix(auth): dev login resolve staff by id, not userId Co-Authored-By: Paperclip <noreply@paperclip.ing> * fix(rbac): fallback lookup for staff records predating Better-Auth userId (#140) GRO-153: /api/staff returned 403 for all staff because resolveStaffMiddleware looked up by staff.userId (Better-Auth ID) but dev login sent staff.id (PK), and existing staff records had userId=NULL. Changes: - resolveStaffMiddleware: try userId first, fall back to staff.id (dev mode) - resolveStaffMiddleware: try userId first, fall back to oidcSub (production) - GET /api/dev/users: include userId field for DevLoginSelector - DevLoginSelector: send userId (not staff.id) as X-Dev-User-Id - Migration 0018: backfill userId for known demo staff Co-authored-by: groombook-engineer[bot] <groombook-engineer@users.noreply.github.com> Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Barkley Trimsworth <barkley@groombook.farh.net> * fix(rbac): allow all staff roles to READ /api/staff GRO-156 follow-up: RBAC middleware was blocking groomer/receptionist from GET /api/staff. The QA review found 403 with "role groomer is not permitted" after PR #140 deployment. Fix: split the /staff/* guard — GET requests allow all roles (groomer, receptionist, manager); write operations remain manager-only. Co-Authored-By: Paperclip <noreply@paperclip.ing> --------- Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: groombook-engineer[bot] <269742240+groombook-engineer[bot]@users.noreply.github.com> Co-authored-by: Flea Flicker <flea-flicker@paperclip.ing> Co-authored-by: groombook-engineer[bot] <groombook-engineer@users.noreply.github.com> Co-authored-by: Barkley Trimsworth <barkley@groombook.farh.net>
278 lines
8.9 KiB
TypeScript
278 lines
8.9 KiB
TypeScript
import { Hono } from "hono";
|
|
import { zValidator } from "@hono/zod-validator";
|
|
import { z } from "zod/v3";
|
|
import {
|
|
and,
|
|
eq,
|
|
getDb,
|
|
gte,
|
|
lt,
|
|
lte,
|
|
ne,
|
|
appointmentGroups,
|
|
appointments,
|
|
clients,
|
|
pets,
|
|
services,
|
|
staff,
|
|
} from "@groombook/db";
|
|
|
|
export const appointmentGroupsRouter = new Hono();
|
|
|
|
// ─── Schemas ──────────────────────────────────────────────────────────────────
|
|
|
|
const petAppointmentSchema = z.object({
|
|
petId: z.string().uuid(),
|
|
serviceId: z.string().uuid(),
|
|
staffId: z.string().uuid().optional(),
|
|
// Each pet may have a different end time (e.g. small dog done faster)
|
|
endTime: z.string().datetime(),
|
|
priceCents: z.number().int().positive().optional(),
|
|
});
|
|
|
|
const createGroupSchema = z.object({
|
|
clientId: z.string().uuid(),
|
|
startTime: z.string().datetime(),
|
|
// One entry per pet
|
|
pets: z.array(petAppointmentSchema).min(2, "A group booking requires at least 2 pets"),
|
|
notes: z.string().max(2000).optional(),
|
|
});
|
|
|
|
const updateGroupSchema = z.object({
|
|
notes: z.string().max(2000).nullable().optional(),
|
|
});
|
|
|
|
// ─── List groups (compact, with appointment count and start time) ─────────────
|
|
|
|
appointmentGroupsRouter.get("/", async (c) => {
|
|
const db = getDb();
|
|
const clientId = c.req.query("clientId");
|
|
const from = c.req.query("from");
|
|
const to = c.req.query("to");
|
|
|
|
const groupConditions = clientId
|
|
? [eq(appointmentGroups.clientId, clientId)]
|
|
: [];
|
|
|
|
const groups = await db
|
|
.select()
|
|
.from(appointmentGroups)
|
|
.where(groupConditions.length > 0 ? and(...groupConditions) : undefined)
|
|
.orderBy(appointmentGroups.createdAt);
|
|
|
|
if (groups.length === 0) return c.json([]);
|
|
|
|
// Fetch appointments for all groups (filter by time range if provided)
|
|
const apptConditions = [];
|
|
if (from) apptConditions.push(gte(appointments.startTime, new Date(from)));
|
|
if (to) apptConditions.push(lte(appointments.startTime, new Date(to)));
|
|
|
|
const allAppts = await db
|
|
.select()
|
|
.from(appointments)
|
|
.where(apptConditions.length > 0 ? and(...apptConditions) : undefined);
|
|
|
|
const groupApptMap = new Map<string, typeof appointments.$inferSelect[]>();
|
|
for (const appt of allAppts) {
|
|
if (!appt.groupId) continue;
|
|
if (!groupApptMap.has(appt.groupId)) groupApptMap.set(appt.groupId, []);
|
|
groupApptMap.get(appt.groupId)!.push(appt);
|
|
}
|
|
|
|
const result = groups
|
|
.map((g) => ({
|
|
...g,
|
|
appointments: (groupApptMap.get(g.id) ?? []).sort(
|
|
(a, b) => a.startTime.getTime() - b.startTime.getTime()
|
|
),
|
|
}))
|
|
.filter((g) => !from || g.appointments.length > 0);
|
|
|
|
return c.json(result);
|
|
});
|
|
|
|
// ─── Get single group with its appointments ───────────────────────────────────
|
|
|
|
appointmentGroupsRouter.get("/:id", async (c) => {
|
|
const db = getDb();
|
|
const id = c.req.param("id");
|
|
|
|
const [group] = await db
|
|
.select()
|
|
.from(appointmentGroups)
|
|
.where(eq(appointmentGroups.id, id));
|
|
if (!group) return c.json({ error: "Not found" }, 404);
|
|
|
|
const groupAppts = await db
|
|
.select({
|
|
id: appointments.id,
|
|
petId: appointments.petId,
|
|
petName: pets.name,
|
|
serviceId: appointments.serviceId,
|
|
serviceName: services.name,
|
|
staffId: appointments.staffId,
|
|
staffName: staff.name,
|
|
status: appointments.status,
|
|
startTime: appointments.startTime,
|
|
endTime: appointments.endTime,
|
|
priceCents: appointments.priceCents,
|
|
notes: appointments.notes,
|
|
})
|
|
.from(appointments)
|
|
.leftJoin(pets, eq(appointments.petId, pets.id))
|
|
.leftJoin(services, eq(appointments.serviceId, services.id))
|
|
.leftJoin(staff, eq(appointments.staffId, staff.id))
|
|
.where(eq(appointments.groupId, id))
|
|
.orderBy(appointments.startTime);
|
|
|
|
const [client] = await db
|
|
.select({ name: clients.name, email: clients.email })
|
|
.from(clients)
|
|
.where(eq(clients.id, group.clientId));
|
|
|
|
return c.json({ ...group, client, appointments: groupAppts });
|
|
});
|
|
|
|
// ─── Create group booking ─────────────────────────────────────────────────────
|
|
|
|
appointmentGroupsRouter.post(
|
|
"/",
|
|
zValidator("json", createGroupSchema),
|
|
async (c) => {
|
|
const db = getDb();
|
|
const body = c.req.valid("json");
|
|
const startTime = new Date(body.startTime);
|
|
|
|
// Verify client exists
|
|
const [client] = await db
|
|
.select({ id: clients.id })
|
|
.from(clients)
|
|
.where(eq(clients.id, body.clientId));
|
|
if (!client) return c.json({ error: "Client not found" }, 404);
|
|
|
|
// Verify all pets belong to this client
|
|
const petIds = body.pets.map((p) => p.petId);
|
|
const petRows = await db
|
|
.select({ id: pets.id, clientId: pets.clientId })
|
|
.from(pets)
|
|
.where(eq(pets.clientId, body.clientId));
|
|
const ownedPetIds = new Set(petRows.map((p) => p.id));
|
|
const unauthorized = petIds.filter((id) => !ownedPetIds.has(id));
|
|
if (unauthorized.length > 0) {
|
|
return c.json({ error: `Pet(s) not found for this client: ${unauthorized.join(", ")}` }, 422);
|
|
}
|
|
|
|
// Deduplicate pets in a single booking
|
|
if (new Set(petIds).size !== petIds.length) {
|
|
return c.json({ error: "Each pet can only appear once per group booking" }, 422);
|
|
}
|
|
|
|
try {
|
|
const result = await db.transaction(async (tx) => {
|
|
// Check conflicts for each staff member
|
|
for (const pet of body.pets) {
|
|
if (!pet.staffId) continue;
|
|
const endTime = new Date(pet.endTime);
|
|
const conflicts = await tx
|
|
.select({ id: appointments.id })
|
|
.from(appointments)
|
|
.where(
|
|
and(
|
|
eq(appointments.staffId, pet.staffId),
|
|
lt(appointments.startTime, endTime),
|
|
gte(appointments.endTime, startTime),
|
|
ne(appointments.status, "cancelled"),
|
|
ne(appointments.status, "no_show"),
|
|
)
|
|
)
|
|
.limit(1);
|
|
if (conflicts.length > 0) {
|
|
throw Object.assign(
|
|
new Error(`Staff conflict for pet ${pet.petId}`),
|
|
{ statusCode: 409, petId: pet.petId, staffId: pet.staffId }
|
|
);
|
|
}
|
|
}
|
|
|
|
// Create the group record
|
|
const [group] = await tx
|
|
.insert(appointmentGroups)
|
|
.values({ clientId: body.clientId, notes: body.notes ?? null })
|
|
.returning();
|
|
if (!group) throw new Error("Failed to create appointment group");
|
|
|
|
// Create one appointment per pet
|
|
const createdAppts = [];
|
|
for (const pet of body.pets) {
|
|
const endTime = new Date(pet.endTime);
|
|
const [appt] = await tx
|
|
.insert(appointments)
|
|
.values({
|
|
clientId: body.clientId,
|
|
petId: pet.petId,
|
|
serviceId: pet.serviceId,
|
|
staffId: pet.staffId ?? null,
|
|
startTime,
|
|
endTime,
|
|
priceCents: pet.priceCents ?? null,
|
|
groupId: group.id,
|
|
})
|
|
.returning();
|
|
if (appt) createdAppts.push(appt);
|
|
}
|
|
|
|
return { group, appointments: createdAppts };
|
|
});
|
|
|
|
return c.json(result, 201);
|
|
} catch (err: unknown) {
|
|
const e = err as Error & { statusCode?: number };
|
|
if (e.statusCode === 409) {
|
|
return c.json({ error: "A staff member has a conflicting appointment at this time", detail: e.message }, 409);
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
);
|
|
|
|
// ─── Update group notes ───────────────────────────────────────────────────────
|
|
|
|
appointmentGroupsRouter.patch(
|
|
"/:id",
|
|
zValidator("json", updateGroupSchema),
|
|
async (c) => {
|
|
const db = getDb();
|
|
const id = c.req.param("id");
|
|
const body = c.req.valid("json");
|
|
|
|
const [updated] = await db
|
|
.update(appointmentGroups)
|
|
.set({ ...body, updatedAt: new Date() })
|
|
.where(eq(appointmentGroups.id, id))
|
|
.returning();
|
|
|
|
if (!updated) return c.json({ error: "Not found" }, 404);
|
|
return c.json(updated);
|
|
}
|
|
);
|
|
|
|
// ─── Cancel all appointments in a group ──────────────────────────────────────
|
|
|
|
appointmentGroupsRouter.delete("/:id", async (c) => {
|
|
const db = getDb();
|
|
const id = c.req.param("id");
|
|
|
|
const [group] = await db
|
|
.select({ id: appointmentGroups.id })
|
|
.from(appointmentGroups)
|
|
.where(eq(appointmentGroups.id, id));
|
|
if (!group) return c.json({ error: "Not found" }, 404);
|
|
|
|
await db
|
|
.update(appointments)
|
|
.set({ status: "cancelled", updatedAt: new Date() })
|
|
.where(eq(appointments.groupId, id));
|
|
|
|
return c.json({ ok: true });
|
|
});
|