Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 23be6230ba | |||
| 40bd6dcfea | |||
| 4884961c8e | |||
| 93be4d8f72 | |||
| f67b96ddfe | |||
| d1a68d93de | |||
| e9f94a2bd7 | |||
| de16c50040 | |||
| fc6c6ef752 | |||
| 1a6a54cc84 |
@@ -166,6 +166,7 @@ Expected: one row, `role = 'groomer'`. If zero rows return, the request hit the
|
||||
| TC-API-3.26 | Verify 25-35% medicalAlerts distribution | GET /api/pets (first 30 pets), count how many have non-empty medicalAlerts | Ratio is 25-35% (seed uses rand() < 0.3 for ~30% distribution) |
|
||||
| TC-API-3.27 | Verify coat_type enum has all seed values | After UAT seed completes, inspect the coat_type enum on the UAT DB — it must contain: short, medium, long, double, wire, silky, curly, hairless | UAT seed jobs (`reset-demo-data`, `seed-test-data`) complete 1/1 with no `enum_in` error; coat_type includes all 8 values used by seed.ts `coatTypePool` |
|
||||
| TC-API-3.28 | Verify pet_size_category enum has all seed values | After UAT seed completes, inspect the pet_size_category enum on the UAT DB — it must contain: small, medium, large, extra_large | UAT seed jobs (`reset-demo-data`, `seed-test-data`) complete 1/1 with no `enum_in` error; pet_size_category includes all 4 values used by seed.ts `petSizeCategoryPool` (regression for GRO-1999, mirrors TC-API-3.27) |
|
||||
| TC-API-3.29 | Verify `reset-demo-data` CronJob does not fail with FK 23503 on `invoice_tip_splits` (GRO-2123) | Trigger the CronJob manually: `kubectl create job --from=cronjob/reset-demo-data verify-gro2123 -n groombook-uat`. Wait for pod to terminate. Inspect logs: `kubectl logs -n groombook-uat -l job-name=verify-gro2123` | Pod reaches `Completed` state; logs show `✓ Acquired seed advisory lock` and `✓ Released seed advisory lock` from `seed.ts`; no `PostgresError: … violates foreign key constraint "invoice_tip_splits_invoice_id_invoices_id_fk"` (code 23503); final counts unchanged (500 clients, ~4000 invoices) |
|
||||
|
||||
### 4.4 Appointment Scheduling
|
||||
|
||||
@@ -192,6 +193,33 @@ Expected: one row, `role = 'groomer'`. If zero rows return, the request hit the
|
||||
| TC-API-5.4 | Update service | PATCH /api/services/{id} with updated fields | 200 OK, service updated |
|
||||
| TC-API-5.5 | Delete service | DELETE /api/services/{id} | 200 OK, service deleted |
|
||||
|
||||
#### 4.5.1 Seed/Reset idempotency (GRO-2064)
|
||||
|
||||
Services seeding is now keyed on the deterministic `services.id` (not `name`) and
|
||||
the reset path now `TRUNCATE`s `services` alongside the other dynamic tables.
|
||||
This means:
|
||||
|
||||
- Running the seed Job twice in a row (no reset in between) converges to the
|
||||
same catalogue — no `services_pkey` collision.
|
||||
- A `pnpm reset` followed by `pnpm seed` (or a CronJob reset fire) leaves the
|
||||
catalogue exactly matching `servicesDef` (10 rows, ids `b0000001-…-001` …
|
||||
`…-00a`), regardless of any stale rows that were present beforehand.
|
||||
- Mixed `seedKnownUsers` + full `seed()` invocations are safe — the
|
||||
`demoSvcs` subset (Bath & Brush, Full Groom Small/Medium, Nail Trim) is
|
||||
keyed on ids `…-001`, `…-002`, `…-003`, `…-005` and the upsert target
|
||||
is `services.id`, so the same-id / different-name collision that broke
|
||||
GRO-2033 (id `…-004` = "Nail Trim" vs servicesDef `…-004` =
|
||||
"Full Groom — Large") cannot recur.
|
||||
|
||||
**UAT regression** (verify after a new image is rolled out):
|
||||
|
||||
| # | Scenario | Steps | Expected |
|
||||
|---|----------|-------|----------|
|
||||
| TC-SEED-1 | Reset → seed converges | `kubectl -n groombook exec deploy/api -- pnpm reset && pnpm seed` | Seed completes 1/1, `services` count = 10, all ids match `servicesDef` |
|
||||
| TC-SEED-2 | Idempotent re-seed | Re-run `pnpm seed` without reset | Seed completes 1/1, no `services_pkey` errors, `services` count still 10 |
|
||||
| TC-SEED-3 | Catalogue matches servicesDef | `psql -c "SELECT id, name FROM services ORDER BY id"` | Rows `…-001`…`…-00a` with names "Bath & Brush"…"Sanitary Trim" exactly as in `servicesDef` |
|
||||
| TC-SEED-4 | Demo subset coexists | Run `seedKnownUsers` then full `seed` | No collision, demo subset (4 services) ends up with the same rows the full seed would write |
|
||||
|
||||
### 4.6 Staff Management
|
||||
|
||||
| # | Scenario | Steps | Expected |
|
||||
@@ -231,6 +259,10 @@ Expected: one row, `role = 'groomer'`. If zero rows return, the request hit the
|
||||
| TC-API-8.9 | SSO bridge — no Better Auth session | POST /api/portal/session-from-auth without Better Auth session cookie | 401 Unauthorized |
|
||||
| TC-API-8.10 | SSO bridge — no matching client | POST /api/portal/session-from-auth with valid Better Auth session for a user with no client record | 404 Not Found, error "No client record found for this user" |
|
||||
| TC-API-8.11 | SSO bridge — returned session works on portal routes | After TC-API-8.8, use returned sessionId as `X-Impersonation-Session-Id` header on GET /api/portal/me | 200 OK, client profile returned |
|
||||
| TC-API-8.12 | Portal GET pets returns extended fields (GRO-2187) | Establish a portal session (TC-API-8.8), then `GET /api/portal/pets` with `X-Impersonation-Session-Id` | 200 OK; each pet includes `coatType`, `petSizeCategory`, `healthAlerts`, `preferredCuts`, `medicalAlerts` (in addition to id/name/breed/weight/birthDate/photoUrl/notes) |
|
||||
| TC-API-8.13 | Portal pet update — owner success + persistence (GRO-2187, fixes [GRO-1480](/GRO/issues/GRO-1480) §5.23) | With a portal session for the pet's owner, `PATCH /api/portal/pets/{petId}` with body `{ "name": "...", "breed": "...", "weightKg": 18.25, "healthAlerts": "...", "coatType": "double", "petSizeCategory": "xlarge", "preferredCuts": ["teddy bear"], "medicalAlerts": [{"type":"allergy","description":"oatmeal","severity":"medium"}] }` | 200 OK; response reflects the update with `petSizeCategory: "extra_large"` (web `xlarge` → DB `extra_large`). A follow-up `GET /api/portal/pets` shows the persisted values |
|
||||
| TC-API-8.14 | Portal pet update — non-owner blocked (GRO-2187) | `PATCH /api/portal/pets/{petId}` for a pet owned by a different client, using another client's portal session | 403 Forbidden (or 404 if pet id is unknown); no mutation persisted |
|
||||
| TC-API-8.15 | Portal pet update — invalid enum rejected (GRO-2187) | `PATCH /api/portal/pets/{petId}` with `coatType: "fluffy"` or `petSizeCategory: "gigantic"` | 422 Unprocessable Entity; pet unchanged |
|
||||
|
||||
### 4.9 Waitlist
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
"test": "vitest run",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate",
|
||||
"db:seed": "tsx src/db/seed.ts",
|
||||
"db:reset": "tsx src/db/reset.ts && drizzle-kit migrate && tsx src/db/seed.ts",
|
||||
"db:seed": "pnpm --filter @groombook/db seed",
|
||||
"db:reset": "pnpm --filter @groombook/db reset",
|
||||
"db:studio": "drizzle-kit studio"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,66 @@
|
||||
-- Migration: 0041_route_optimization.sql
|
||||
-- Route optimization schema: geocoding columns on clients, groomerRoutes +
|
||||
-- routeStops tables, and route settings on business_settings.
|
||||
-- Written idempotently so it is safe to re-run.
|
||||
|
||||
-- ─── Enums ────────────────────────────────────────────────────────────────────
|
||||
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE "route_status" AS ENUM ('draft', 'optimized', 'in_progress', 'completed');
|
||||
EXCEPTION WHEN duplicate_object THEN NULL;
|
||||
END $$;
|
||||
|
||||
-- ─── Clients: geocoding columns ───────────────────────────────────────────────
|
||||
|
||||
ALTER TABLE "clients" ADD COLUMN IF NOT EXISTS "latitude" double precision;
|
||||
ALTER TABLE "clients" ADD COLUMN IF NOT EXISTS "longitude" double precision;
|
||||
ALTER TABLE "clients" ADD COLUMN IF NOT EXISTS "geocoded_at" timestamp;
|
||||
|
||||
-- ─── Business settings: route optimization config ─────────────────────────────
|
||||
|
||||
ALTER TABLE "business_settings"
|
||||
ADD COLUMN IF NOT EXISTS "default_travel_buffer_mins" integer NOT NULL DEFAULT 15;
|
||||
ALTER TABLE "business_settings"
|
||||
ADD COLUMN IF NOT EXISTS "route_optimization_provider" text DEFAULT 'nominatim';
|
||||
-- Encrypted at rest at the application layer (AES-256-GCM).
|
||||
ALTER TABLE "business_settings"
|
||||
ADD COLUMN IF NOT EXISTS "google_maps_api_key" text;
|
||||
|
||||
-- ─── Groomer routes table ─────────────────────────────────────────────────────
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "groomer_routes" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
"staff_id" uuid NOT NULL REFERENCES "staff"("id") ON DELETE CASCADE,
|
||||
"route_date" date NOT NULL,
|
||||
"status" "route_status" NOT NULL DEFAULT 'draft',
|
||||
"total_travel_mins" integer,
|
||||
"total_distance_km" numeric(8, 2),
|
||||
"optimized_at" timestamp,
|
||||
"created_at" timestamp NOT NULL DEFAULT now(),
|
||||
"updated_at" timestamp NOT NULL DEFAULT now(),
|
||||
CONSTRAINT "uq_groomer_routes_staff_date" UNIQUE ("staff_id", "route_date")
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "idx_groomer_routes_staff_id"
|
||||
ON "groomer_routes"("staff_id");
|
||||
|
||||
-- ─── Route stops table ────────────────────────────────────────────────────────
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "route_stops" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
"route_id" uuid NOT NULL REFERENCES "groomer_routes"("id") ON DELETE CASCADE,
|
||||
"appointment_id" uuid NOT NULL REFERENCES "appointments"("id") ON DELETE CASCADE,
|
||||
"stop_order" integer NOT NULL,
|
||||
"latitude" double precision NOT NULL,
|
||||
"longitude" double precision NOT NULL,
|
||||
"travel_mins_from_prev" integer,
|
||||
"travel_distance_km_from_prev" numeric(8, 2),
|
||||
"buffer_mins" integer NOT NULL DEFAULT 15,
|
||||
"created_at" timestamp NOT NULL DEFAULT now(),
|
||||
"updated_at" timestamp NOT NULL DEFAULT now(),
|
||||
CONSTRAINT "uq_route_stops_route_appointment" UNIQUE ("route_id", "appointment_id"),
|
||||
CONSTRAINT "uq_route_stops_route_order" UNIQUE ("route_id", "stop_order")
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "idx_route_stops_route_id"
|
||||
ON "route_stops"("route_id");
|
||||
@@ -281,6 +281,13 @@
|
||||
"when": 1780000000002,
|
||||
"tag": "0040_register_missing_coat_type_values",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 41,
|
||||
"version": "7",
|
||||
"when": 1780000000003,
|
||||
"tag": "0041_route_optimization",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,9 @@ export function buildClient(overrides: Partial<ClientRow> = {}): ClientRow {
|
||||
stripeCustomerId: null,
|
||||
status: "active",
|
||||
disabledAt: null,
|
||||
latitude: null,
|
||||
longitude: null,
|
||||
geocodedAt: null,
|
||||
createdAt: new Date("2025-01-01T00:00:00Z"),
|
||||
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
||||
...overrides,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import {
|
||||
boolean,
|
||||
date,
|
||||
doublePrecision,
|
||||
index,
|
||||
integer,
|
||||
jsonb,
|
||||
@@ -140,6 +142,10 @@ export const clients = pgTable(
|
||||
stripeCustomerId: text("stripe_customer_id"),
|
||||
status: clientStatusEnum("status").notNull().default("active"),
|
||||
disabledAt: timestamp("disabled_at"),
|
||||
// Geocoded coordinates for route optimization; null until geocoded.
|
||||
latitude: doublePrecision("latitude"),
|
||||
longitude: doublePrecision("longitude"),
|
||||
geocodedAt: timestamp("geocoded_at"),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
},
|
||||
@@ -555,6 +561,16 @@ export const businessSettings = pgTable("business_settings", {
|
||||
accentColor: text("accent_color").notNull().default("#8b7355"),
|
||||
messagingPhoneNumber: text("messaging_phone_number"),
|
||||
telnyxMessagingProfileId: text("telnyx_messaging_profile_id"),
|
||||
// Route optimization settings.
|
||||
defaultTravelBufferMins: integer("default_travel_buffer_mins")
|
||||
.notNull()
|
||||
.default(15),
|
||||
routeOptimizationProvider: text("route_optimization_provider").default(
|
||||
"nominatim"
|
||||
),
|
||||
// Encrypted at rest at the application layer (AES-256-GCM), mirroring
|
||||
// the handling of authProviderConfigs.clientSecret.
|
||||
googleMapsApiKey: text("google_maps_api_key"),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
});
|
||||
@@ -658,3 +674,69 @@ export const bufferRules = pgTable(
|
||||
index("idx_buffer_rules_service_id").on(t.serviceId),
|
||||
]
|
||||
);
|
||||
|
||||
// ─── Route Optimization ───────────────────────────────────────────────────────
|
||||
|
||||
export const routeStatusEnum = pgEnum("route_status", [
|
||||
"draft",
|
||||
"optimized",
|
||||
"in_progress",
|
||||
"completed",
|
||||
]);
|
||||
|
||||
// A groomer's optimized route for a single day. One row per (staff, date).
|
||||
export const groomerRoutes = pgTable(
|
||||
"groomer_routes",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
staffId: uuid("staff_id")
|
||||
.notNull()
|
||||
.references(() => staff.id, { onDelete: "cascade" }),
|
||||
routeDate: date("route_date", { mode: "string" }).notNull(),
|
||||
status: routeStatusEnum("status").notNull().default("draft"),
|
||||
// Populated once the route is optimized.
|
||||
totalTravelMins: integer("total_travel_mins"),
|
||||
totalDistanceKm: numeric("total_distance_km", { precision: 8, scale: 2 }),
|
||||
optimizedAt: timestamp("optimized_at"),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
},
|
||||
(t) => [
|
||||
// One route per groomer per day.
|
||||
unique("uq_groomer_routes_staff_date").on(t.staffId, t.routeDate),
|
||||
index("idx_groomer_routes_staff_id").on(t.staffId),
|
||||
]
|
||||
);
|
||||
|
||||
// An ordered stop within a groomer's route, tied to an appointment.
|
||||
export const routeStops = pgTable(
|
||||
"route_stops",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
routeId: uuid("route_id")
|
||||
.notNull()
|
||||
.references(() => groomerRoutes.id, { onDelete: "cascade" }),
|
||||
appointmentId: uuid("appointment_id")
|
||||
.notNull()
|
||||
.references(() => appointments.id, { onDelete: "cascade" }),
|
||||
stopOrder: integer("stop_order").notNull(),
|
||||
latitude: doublePrecision("latitude").notNull(),
|
||||
longitude: doublePrecision("longitude").notNull(),
|
||||
// Null for the first stop in the route.
|
||||
travelMinsFromPrev: integer("travel_mins_from_prev"),
|
||||
travelDistanceKmFromPrev: numeric("travel_distance_km_from_prev", {
|
||||
precision: 8,
|
||||
scale: 2,
|
||||
}),
|
||||
bufferMins: integer("buffer_mins").notNull().default(15),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
},
|
||||
(t) => [
|
||||
// An appointment appears at most once per route.
|
||||
unique("uq_route_stops_route_appointment").on(t.routeId, t.appointmentId),
|
||||
// Stop order is unique within a route.
|
||||
unique("uq_route_stops_route_order").on(t.routeId, t.stopOrder),
|
||||
index("idx_route_stops_route_id").on(t.routeId),
|
||||
]
|
||||
);
|
||||
|
||||
+243
-17
@@ -401,7 +401,9 @@ const servicesDef = [
|
||||
*
|
||||
* In seedKnownUsers() this replaces the inline UAT-staff block.
|
||||
*/
|
||||
async function seedUatStaffAccounts(db: ReturnType<typeof drizzle>) {
|
||||
async function seedUatStaffAccounts(
|
||||
db: ReturnType<typeof drizzle>,
|
||||
): Promise<string | null> {
|
||||
// ── Staff: UAT Super User (oidcSub from SEED_UAT_SUPER_OIDC_SUB env var) ──
|
||||
const uatSuperOidcSub = process.env.SEED_UAT_SUPER_OIDC_SUB;
|
||||
if (uatSuperOidcSub) {
|
||||
@@ -668,6 +670,132 @@ async function seedUatStaffAccounts(db: ReturnType<typeof drizzle>) {
|
||||
console.log(`✓ Created UAT pet '${pet.name}' with extended fields`);
|
||||
}
|
||||
}
|
||||
|
||||
// ── GRO-2100: deterministic uat-groomer ↔ pet linkage ───────────────────────
|
||||
// The UAT groomer (`uat-groomer@groombook.dev`, staffId 00000000-0000-0000-0000-000000000004)
|
||||
// needs at least one linked pet/appointment or GRO-1987 TC-UAT-2/3 cannot run
|
||||
// (the pet profile-summary endpoint returns 404 instead of 200/403).
|
||||
//
|
||||
// We deterministically link the UAT groomer to the UAT customer's first pet
|
||||
// ("UAT Pup Alpha") and leave the second pet ("UAT Pup Beta") UNLINKED so
|
||||
// TC-UAT-2 (200) and TC-UAT-3 (403) can both hardcode the stable petIds.
|
||||
//
|
||||
// The linkage call itself is performed by the caller AFTER the `services`
|
||||
// catalogue has been seeded (this helper runs before services exist,
|
||||
// which previously caused the linkage to be silently skipped on every
|
||||
// reset). GRO-2100 follow-up.
|
||||
return uatCustomerClientId;
|
||||
}
|
||||
|
||||
/**
|
||||
* GRO-2100: create a deterministic completed appointment linking the UAT groomer
|
||||
* to "UAT Pup Alpha" (c0000001-0000-0000-0000-000000000002). "UAT Pup Beta"
|
||||
* (c0000001-0000-0000-0000-000000000003) is intentionally left UNLINKED so
|
||||
* GRO-1987 TC-UAT-3 can verify the 403 forbidden response.
|
||||
*
|
||||
* Idempotent: the deterministic appointment id (`a0000001-…-0001`) is the
|
||||
* upsert key, so re-running the seed on every reset-demo-data CronJob
|
||||
* (hourly per apps/overlays/uat/reset-cronjob.yaml) is safe.
|
||||
*/
|
||||
async function seedUatGroomerLinkage(
|
||||
db: ReturnType<typeof drizzle>,
|
||||
customerClientId: string | null,
|
||||
): Promise<void> {
|
||||
const uatGroomerEmail = "uat-groomer@groombook.dev";
|
||||
const LINKED_PET_ID = "c0000001-0000-0000-0000-000000000002"; // UAT Pup Alpha
|
||||
const APPT_ID = "a0000001-0000-0000-0000-000000000001";
|
||||
|
||||
// Skip silently if the UAT Customer client wasn't created (non-UAT seed
|
||||
// profile, e.g. seedKnownUsers() in an env without the UAT personas).
|
||||
if (!customerClientId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only run if the UAT groomer staff record actually exists — dev/test seeds
|
||||
// that don't set SEED_UAT_STAFF_OIDC_SUB should not crash.
|
||||
const [uatGroomerStaff] = await db
|
||||
.select({ id: schema.staff.id })
|
||||
.from(schema.staff)
|
||||
.where(eq(schema.staff.email, uatGroomerEmail))
|
||||
.limit(1);
|
||||
if (!uatGroomerStaff) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip if this exact appointment already exists (idempotent on re-seed).
|
||||
const [existing] = await db
|
||||
.select({ id: schema.appointments.id })
|
||||
.from(schema.appointments)
|
||||
.where(eq(schema.appointments.id, APPT_ID))
|
||||
.limit(1);
|
||||
if (existing) {
|
||||
console.log(`✓ GRO-2100: uat-groomer linkage appointment already exists — skipping`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip if the linked pet hasn't been seeded yet (defensive: caller should
|
||||
// ensure pets exist; if the helper is re-ordered later we don't want to
|
||||
// crash here).
|
||||
const [linkedPet] = await db
|
||||
.select({ id: schema.pets.id })
|
||||
.from(schema.pets)
|
||||
.where(eq(schema.pets.id, LINKED_PET_ID))
|
||||
.limit(1);
|
||||
if (!linkedPet) {
|
||||
console.warn(`⚠ GRO-2100: UAT Pup Alpha (${LINKED_PET_ID}) not found — skipping uat-groomer linkage`);
|
||||
return;
|
||||
}
|
||||
|
||||
// The "Bath & Brush" service id is stable across the reset; falls back to
|
||||
// any active service if it has not been seeded yet (e.g. seedKnownUsers
|
||||
// runs in isolation).
|
||||
const BATH_AND_BRUSH_ID = "b0000001-0000-0000-0000-000000000001";
|
||||
const [bathService] = await db
|
||||
.select({ id: schema.services.id })
|
||||
.from(schema.services)
|
||||
.where(eq(schema.services.id, BATH_AND_BRUSH_ID))
|
||||
.limit(1);
|
||||
|
||||
let serviceId: string;
|
||||
if (bathService) {
|
||||
serviceId = bathService.id;
|
||||
} else {
|
||||
const [fallback] = await db
|
||||
.select({ id: schema.services.id })
|
||||
.from(schema.services)
|
||||
.where(eq(schema.services.active, true))
|
||||
.limit(1);
|
||||
if (!fallback) {
|
||||
console.warn(`⚠ GRO-2100: no active services found — skipping uat-groomer linkage`);
|
||||
return;
|
||||
}
|
||||
serviceId = fallback.id;
|
||||
}
|
||||
|
||||
// Schedule the completed appointment 7 days ago so the profile-summary's
|
||||
// "recentGroomingHistory" window (last 10) reliably includes it.
|
||||
const startTime = new Date();
|
||||
startTime.setDate(startTime.getDate() - 7);
|
||||
startTime.setHours(10, 0, 0, 0);
|
||||
const endTime = new Date(startTime.getTime() + 45 * 60 * 1000);
|
||||
|
||||
await db.insert(schema.appointments).values({
|
||||
id: APPT_ID,
|
||||
clientId: customerClientId,
|
||||
petId: LINKED_PET_ID,
|
||||
serviceId,
|
||||
staffId: uatGroomerStaff.id,
|
||||
batherStaffId: null,
|
||||
status: "completed",
|
||||
startTime,
|
||||
endTime,
|
||||
notes: "GRO-2100: deterministic uat-groomer linkage for TC-UAT-2/3.",
|
||||
priceCents: null,
|
||||
confirmationStatus: "confirmed",
|
||||
});
|
||||
console.log(
|
||||
`✓ GRO-2100: linked uat-groomer (${uatGroomerStaff.id}) → UAT Pup Alpha (${LINKED_PET_ID}) via appointment ${APPT_ID}`,
|
||||
);
|
||||
}
|
||||
|
||||
// ── Known-users-only seed (prod/demo) ───────────────────────────────────────
|
||||
@@ -745,27 +873,40 @@ async function seedKnownUsers() {
|
||||
// ── UAT staff accounts + Better Auth credentials (shared impl) ──────────────
|
||||
// Extracted into seedUatStaffAccounts() so it runs in both seedKnownUsers()
|
||||
// and the full seed() UAT branch.
|
||||
await seedUatStaffAccounts(db);
|
||||
const uatCustomerClientId = await seedUatStaffAccounts(db);
|
||||
|
||||
// ── Services: idempotent upsert using name as unique key ─────────────────────
|
||||
// UNIQUE constraint on services.name (migration 0020) must exist first.
|
||||
// Uses b0000001-... IDs to match main seed servicesDef for same-named services.
|
||||
// ── Services: idempotent upsert keyed on `id` ─────────────────────────────
|
||||
// GRO-2064: previously keyed on `services.name` while writing a
|
||||
// deterministic `id`. If a stale row existed with the same `id` but a
|
||||
// different `name`, PostgreSQL raised `services_pkey` (id collision)
|
||||
// before the name-targeted ON CONFLICT could fire. Switch the conflict
|
||||
// target to `services.id` so deterministic ids always win; pair with
|
||||
// `TRUNCATE services … CASCADE` above so each reset rebuilds the
|
||||
// catalogue from `servicesDef` cleanly. GRO-2033 close-out.
|
||||
// Id↔name map MUST stay in sync with `servicesDef` (the canonical source
|
||||
// of truth in the main `seed()` function).
|
||||
const demoSvcs = [
|
||||
{ id: "b0000001-0000-0000-0000-000000000001", name: "Bath & Brush", description: "Full bath, blow-dry, brush out, and ear cleaning", basePriceCents: 4500, durationMinutes: 45 },
|
||||
{ id: "b0000001-0000-0000-0000-000000000002", name: "Full Groom — Small", description: "Complete grooming for dogs under 25 lbs", basePriceCents: 6500, durationMinutes: 60 },
|
||||
{ id: "b0000001-0000-0000-0000-000000000003", name: "Full Groom — Medium", description: "Complete grooming for dogs 25-50 lbs", basePriceCents: 8000, durationMinutes: 75 },
|
||||
{ id: "b0000001-0000-0000-0000-000000000004", name: "Nail Trim", description: "Nail clipping and filing", basePriceCents: 1500, durationMinutes: 15 },
|
||||
{ id: "b0000001-0000-0000-0000-000000000005", name: "Nail Trim", description: "Nail clipping and filing", basePriceCents: 1500, durationMinutes: 15 },
|
||||
];
|
||||
for (const svc of demoSvcs) {
|
||||
await db.insert(schema.services)
|
||||
.values({ ...svc, active: true })
|
||||
.onConflictDoUpdate({
|
||||
target: schema.services.name,
|
||||
set: { description: svc.description, basePriceCents: svc.basePriceCents, durationMinutes: svc.durationMinutes, active: true },
|
||||
target: schema.services.id,
|
||||
set: { name: svc.name, description: svc.description, basePriceCents: svc.basePriceCents, durationMinutes: svc.durationMinutes, active: true },
|
||||
});
|
||||
}
|
||||
console.log(`✓ Seeded ${demoSvcs.length} services`);
|
||||
|
||||
// GRO-2100: deterministic uat-groomer ↔ UAT Pup Alpha linkage. Must run
|
||||
// AFTER services are seeded (this helper looks up an active service id
|
||||
// to attach to the appointment; on a fresh reset there are none yet at
|
||||
// the time seedUatStaffAccounts() returns).
|
||||
await seedUatGroomerLinkage(db, uatCustomerClientId);
|
||||
|
||||
// ── Client: Demo Client ──
|
||||
const [existingClient] = await db
|
||||
.select()
|
||||
@@ -835,6 +976,63 @@ async function seedKnownUsers() {
|
||||
|
||||
// ── Main seed ────────────────────────────────────────────────────────────────
|
||||
|
||||
// ── GRO-2123: serialize reset+seed with a Postgres advisory lock ────────
|
||||
// The reset-demo-data CronJob runs on an hourly schedule. With
|
||||
// concurrencyPolicy=Replace, a new pod can start while the previous one
|
||||
// is still mid-seed; the new pod's TRUNCATE then deletes rows the old pod
|
||||
// is still inserting, producing FK 23503 errors non-deterministically
|
||||
// (see GRO-2123: invoice_tip_splits → invoices).
|
||||
//
|
||||
// We hold a session-level advisory lock for the full duration of the
|
||||
// seed so that overlapping invocations block then proceed in order —
|
||||
// not skip. The key is a stable 32-bit constant so it can be referenced
|
||||
// from runbooks without ambiguity and binds to the single-argument
|
||||
// `pg_advisory_lock(int)` form, which postgres-js serializes as a plain
|
||||
// number (no bigint type plumbing required).
|
||||
const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitrary, stable
|
||||
|
||||
/**
|
||||
* Reserve a dedicated connection from `pool`, take the seed advisory lock
|
||||
* on it, run `fn`, and release the lock + connection in a try/finally.
|
||||
*
|
||||
* CRITICAL: with postgres-js connection pooling, a session-level
|
||||
* `pg_advisory_lock(KEY)` acquired on one pooled connection and released
|
||||
* on a *different* one is a no-op (the lock is bound to the session /
|
||||
* pg-backend that took it). We therefore reserve a dedicated connection
|
||||
* for the lock and release it from the same reserved connection. The
|
||||
* seed work itself still runs on the pooled connections.
|
||||
*/
|
||||
async function withSeedAdvisoryLock<T>(
|
||||
pool: ReturnType<typeof postgres>,
|
||||
fn: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
const lockConnection = await pool.reserve();
|
||||
let lockHeld = false;
|
||||
try {
|
||||
await lockConnection`SELECT pg_advisory_lock(${SEED_ADVISORY_LOCK_KEY})`;
|
||||
lockHeld = true;
|
||||
console.log(`✓ Acquired seed advisory lock (key=${SEED_ADVISORY_LOCK_KEY})`);
|
||||
const result = await fn();
|
||||
await lockConnection`SELECT pg_advisory_unlock(${SEED_ADVISORY_LOCK_KEY})`;
|
||||
lockHeld = false;
|
||||
console.log(`✓ Released seed advisory lock`);
|
||||
return result;
|
||||
} finally {
|
||||
if (lockHeld) {
|
||||
try {
|
||||
await lockConnection`SELECT pg_advisory_unlock(${SEED_ADVISORY_LOCK_KEY})`;
|
||||
} catch (err) {
|
||||
console.error("Failed to release seed advisory lock during cleanup:", err);
|
||||
}
|
||||
}
|
||||
try {
|
||||
lockConnection.release();
|
||||
} catch (err) {
|
||||
console.error("Failed to release reserved lock connection:", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function seed() {
|
||||
const url = process.env.DATABASE_URL;
|
||||
if (!url) {
|
||||
@@ -852,6 +1050,22 @@ async function seed() {
|
||||
const client = postgres(url, { max: 5 });
|
||||
const db = drizzle(client, { schema });
|
||||
|
||||
// GRO-2123: hold the seed advisory lock for the full body of runSeedBody.
|
||||
// See the withSeedAdvisoryLock comment for why a reserved connection is
|
||||
// required (postgres-js pooling would silently drop the lock otherwise).
|
||||
await withSeedAdvisoryLock(client, async () => {
|
||||
return await runSeedBody(client, db, profile, cfg);
|
||||
});
|
||||
|
||||
await client.end();
|
||||
}
|
||||
|
||||
async function runSeedBody(
|
||||
client: ReturnType<typeof postgres>,
|
||||
db: ReturnType<typeof drizzle>,
|
||||
profile: SeedProfile,
|
||||
cfg: ProfileConfig,
|
||||
): Promise<void> {
|
||||
console.log(`Seeding Groom Book database (profile: ${profile})...\n`);
|
||||
|
||||
// ── Staff ──
|
||||
@@ -868,7 +1082,13 @@ async function seed() {
|
||||
({ id: uuid(), name: `Bather ${i + 1}`, email: `bather${i + 1}@groombook.dev`, role: "groomer" as const, isSuperUser: false })
|
||||
);
|
||||
|
||||
await db.execute(sql`TRUNCATE impersonation_sessions, impersonation_audit_logs, appointments, invoices, invoice_line_items, invoice_tip_splits, grooming_visit_logs CASCADE`);
|
||||
// GRO-2064: also TRUNCATE `services` so each reset rebuilds the catalogue
|
||||
// from `servicesDef` (deterministic IDs + UNIQUE(name)). Stale service rows
|
||||
// (e.g. a prior `seedKnownUsers` run that wrote a different `name` for the
|
||||
// same `id`) would otherwise cause the deterministic upsert to PK-collide
|
||||
// on `services.id` — see CTO review on infra PR #605 (rev #4230). TRUNCATE
|
||||
// CASCADE handles appointments/invoices FKs to services.id.
|
||||
await db.execute(sql`TRUNCATE services, impersonation_sessions, impersonation_audit_logs, appointments, invoices, invoice_line_items, invoice_tip_splits, grooming_visit_logs CASCADE`);
|
||||
|
||||
const allStaff = [...managerStaff, ...receptionistStaff, ...groomers, ...bathers];
|
||||
for (const s of allStaff) {
|
||||
@@ -916,12 +1136,14 @@ async function seed() {
|
||||
// ── UAT staff accounts + Better Auth credentials (shared impl) ──────────────
|
||||
// Seeds deterministic UAT staff with numeric OIDC subs and Better Auth credentials.
|
||||
// Must run AFTER random staff are created so upserts land correctly.
|
||||
await seedUatStaffAccounts(db);
|
||||
const uatCustomerClientId = await seedUatStaffAccounts(db);
|
||||
|
||||
// ── Services ──
|
||||
// Upsert services using name as unique key. With deterministic IDs in
|
||||
// servicesDef and TRUNCATE clearing downstream tables first, this is
|
||||
// idempotent: first run inserts, subsequent runs update existing rows.
|
||||
// GRO-2064: key the upsert on `services.id` (not `name`) so deterministic
|
||||
// ids always win, and rely on the TRUNCATE above to clear stale rows before
|
||||
// the catalogue is rebuilt. The previous name-targeted upsert failed with
|
||||
// `services_pkey` when a prior run had left a row with the same id but a
|
||||
// different name (CTO review on infra PR #605, rev #4230).
|
||||
const serviceIds: string[] = [];
|
||||
for (const s of servicesDef) {
|
||||
serviceIds.push(s.id);
|
||||
@@ -935,12 +1157,18 @@ async function seed() {
|
||||
active: true,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: schema.services.name,
|
||||
set: { description: s.desc, basePriceCents: s.price, durationMinutes: s.dur, active: true },
|
||||
target: schema.services.id,
|
||||
set: { name: s.name, description: s.desc, basePriceCents: s.price, durationMinutes: s.dur, active: true },
|
||||
});
|
||||
}
|
||||
console.log(`✓ Created ${servicesDef.length} services`);
|
||||
|
||||
// GRO-2100: deterministic uat-groomer ↔ UAT Pup Alpha linkage. Must run
|
||||
// AFTER services are seeded (this helper looks up an active service id
|
||||
// to attach to the appointment; on a fresh reset there are none yet at
|
||||
// the time seedUatStaffAccounts() returns).
|
||||
await seedUatGroomerLinkage(db, uatCustomerClientId);
|
||||
|
||||
// ── Clients & Pets ──
|
||||
const now = new Date();
|
||||
const appointmentsBackDate = new Date(now);
|
||||
@@ -1459,8 +1687,6 @@ async function seed() {
|
||||
}
|
||||
console.log(`✓ Created ${visitLogCount} grooming visit logs`);
|
||||
console.log("\nSeed complete!");
|
||||
|
||||
await client.end();
|
||||
}
|
||||
|
||||
seed().catch((err) => {
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { Hono } from "hono";
|
||||
|
||||
const CLIENT_ID = "550e8400-e29b-41d4-a716-446655440001";
|
||||
const OTHER_CLIENT_ID = "550e8400-e29b-41d4-a716-446655440099";
|
||||
const PET_ID = "880e8400-e29b-41d4-a716-446655440004";
|
||||
const SESSION_ID = "770e8400-e29b-41d4-a716-446655440003";
|
||||
|
||||
const futureDate = () => new Date(Date.now() + 30 * 60 * 1000);
|
||||
|
||||
const ACTIVE_SESSION = {
|
||||
id: SESSION_ID,
|
||||
clientId: CLIENT_ID,
|
||||
status: "active" as const,
|
||||
expiresAt: futureDate(),
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
// A persisted pet owned by CLIENT_ID. weightKg is a string because the column is
|
||||
// numeric (Drizzle serialises numeric to string).
|
||||
const PET = {
|
||||
id: PET_ID,
|
||||
clientId: CLIENT_ID,
|
||||
name: "Rex",
|
||||
species: "dog",
|
||||
breed: "Labrador",
|
||||
weightKg: "12.50",
|
||||
dateOfBirth: null,
|
||||
healthAlerts: null,
|
||||
groomingNotes: null,
|
||||
coatType: null,
|
||||
petSizeCategory: null,
|
||||
preferredCuts: [],
|
||||
medicalAlerts: [],
|
||||
photoKey: null,
|
||||
};
|
||||
|
||||
let selectSessionRow: Record<string, unknown> | null = null;
|
||||
let selectPetRow: Record<string, unknown> | null = null;
|
||||
let updatedValues: Record<string, unknown>[] = [];
|
||||
|
||||
function resetMock() {
|
||||
selectSessionRow = null;
|
||||
selectPetRow = null;
|
||||
updatedValues = [];
|
||||
}
|
||||
|
||||
vi.mock("@groombook/db", () => {
|
||||
function makeChainable(data: unknown[]): unknown {
|
||||
const arr = [...data];
|
||||
const chain = new Proxy(arr, {
|
||||
get(target, prop) {
|
||||
if (prop === "where" || prop === "orderBy" || prop === "limit") {
|
||||
return () => chain;
|
||||
}
|
||||
// @ts-expect-error proxy
|
||||
return target[prop];
|
||||
},
|
||||
});
|
||||
return chain;
|
||||
}
|
||||
|
||||
function tableProxy(name: string) {
|
||||
return new Proxy(
|
||||
{ _name: name },
|
||||
{ get: (t, p) => (p === "_name" ? name : { table: name, column: p }) }
|
||||
);
|
||||
}
|
||||
|
||||
const impersonationSessions = tableProxy("impersonationSessions");
|
||||
const pets = tableProxy("pets");
|
||||
|
||||
return {
|
||||
getDb: () => ({
|
||||
select: () => ({
|
||||
from: (table: { _name: string }) => {
|
||||
if (table._name === "impersonationSessions") {
|
||||
return makeChainable(selectSessionRow ? [selectSessionRow] : []);
|
||||
}
|
||||
if (table._name === "pets") {
|
||||
return makeChainable(selectPetRow ? [selectPetRow] : []);
|
||||
}
|
||||
return makeChainable([]);
|
||||
},
|
||||
}),
|
||||
update: () => ({
|
||||
set: (vals: Record<string, unknown>) => ({
|
||||
where: () => ({
|
||||
returning: () => {
|
||||
if (selectPetRow) {
|
||||
updatedValues.push(vals);
|
||||
return [{ ...selectPetRow, ...vals }];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
// portalAudit inserts an audit row after the handler; make it a no-op so
|
||||
// the middleware does not log a swallowed error during tests.
|
||||
insert: () => ({ values: () => ({ returning: () => [] }) }),
|
||||
}),
|
||||
impersonationSessions,
|
||||
pets,
|
||||
// Other tables imported by the portal router but unused in these tests.
|
||||
appointments: tableProxy("appointments"),
|
||||
waitlistEntries: tableProxy("waitlistEntries"),
|
||||
clients: tableProxy("clients"),
|
||||
services: tableProxy("services"),
|
||||
staff: tableProxy("staff"),
|
||||
invoices: tableProxy("invoices"),
|
||||
invoiceLineItems: tableProxy("invoiceLineItems"),
|
||||
impersonationAuditLogs: tableProxy("impersonationAuditLogs"),
|
||||
eq: vi.fn(),
|
||||
and: vi.fn(),
|
||||
inArray: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
const { portalRouter } = await import("../routes/portal.js");
|
||||
|
||||
const app = new Hono();
|
||||
app.route("/portal", portalRouter);
|
||||
|
||||
function jsonPatch(path: string, body: unknown, headers?: Record<string, string>) {
|
||||
return app.request(path, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...headers,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => resetMock());
|
||||
|
||||
describe("PATCH /portal/pets/:petId", () => {
|
||||
it("updates an owned pet and persists the mapped columns (200)", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectPetRow = PET;
|
||||
|
||||
// Mirrors the groombook/web PetForm payload: it spreads the GET-shaped pet
|
||||
// (weight, notes, birthDate, photoUrl) and adds the form's edited keys
|
||||
// (weightKg, healthAlerts, coatType, …). "xlarge" must map to "extra_large".
|
||||
const res = await jsonPatch(
|
||||
`/portal/pets/${PET_ID}`,
|
||||
{
|
||||
id: PET_ID,
|
||||
name: "Rex Updated",
|
||||
breed: "Golden Retriever",
|
||||
weight: "12.50",
|
||||
weightKg: 18.25,
|
||||
notes: "old grooming notes",
|
||||
healthAlerts: "Allergic to oatmeal shampoo",
|
||||
photoUrl: "pets/rex.jpg",
|
||||
coatType: "double",
|
||||
petSizeCategory: "xlarge",
|
||||
preferredCuts: ["teddy bear", "puppy cut"],
|
||||
medicalAlerts: [
|
||||
{ id: "a1", type: "allergy", description: "oatmeal", severity: "medium" },
|
||||
],
|
||||
},
|
||||
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.name).toBe("Rex Updated");
|
||||
expect(body.petSizeCategory).toBe("extra_large");
|
||||
expect(body.coatType).toBe("double");
|
||||
|
||||
const persisted = updatedValues[0]!;
|
||||
expect(persisted.name).toBe("Rex Updated");
|
||||
expect(persisted.breed).toBe("Golden Retriever");
|
||||
// weightKg (form key) wins over weight (GET key) and is stored as a string.
|
||||
expect(persisted.weightKg).toBe("18.25");
|
||||
expect(persisted.groomingNotes).toBe("old grooming notes");
|
||||
expect(persisted.healthAlerts).toBe("Allergic to oatmeal shampoo");
|
||||
expect(persisted.photoKey).toBe("pets/rex.jpg");
|
||||
expect(persisted.coatType).toBe("double");
|
||||
expect(persisted.petSizeCategory).toBe("extra_large");
|
||||
expect(persisted.preferredCuts).toEqual(["teddy bear", "puppy cut"]);
|
||||
expect(persisted.medicalAlerts).toEqual([
|
||||
{ id: "a1", type: "allergy", description: "oatmeal", severity: "medium" },
|
||||
]);
|
||||
expect(persisted.updatedAt).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it("falls back to the weight key when weightKg is absent", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectPetRow = PET;
|
||||
|
||||
const res = await jsonPatch(
|
||||
`/portal/pets/${PET_ID}`,
|
||||
{ weight: "9.75" },
|
||||
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(updatedValues[0]!.weightKg).toBe("9.75");
|
||||
});
|
||||
|
||||
it("returns 403 when the pet belongs to a different client", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectPetRow = { ...PET, clientId: OTHER_CLIENT_ID };
|
||||
|
||||
const res = await jsonPatch(
|
||||
`/portal/pets/${PET_ID}`,
|
||||
{ name: "Hacker" },
|
||||
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||
);
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(updatedValues).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns 404 when the pet does not exist", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectPetRow = null;
|
||||
|
||||
const res = await jsonPatch(
|
||||
`/portal/pets/${PET_ID}`,
|
||||
{ name: "Ghost" },
|
||||
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||
);
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns 422 for an invalid coatType", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectPetRow = PET;
|
||||
|
||||
const res = await jsonPatch(
|
||||
`/portal/pets/${PET_ID}`,
|
||||
{ coatType: "fluffy" },
|
||||
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||
);
|
||||
|
||||
expect(res.status).toBe(422);
|
||||
expect(updatedValues).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns 422 for an invalid petSizeCategory", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectPetRow = PET;
|
||||
|
||||
const res = await jsonPatch(
|
||||
`/portal/pets/${PET_ID}`,
|
||||
{ petSizeCategory: "gigantic" },
|
||||
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||
);
|
||||
|
||||
expect(res.status).toBe(422);
|
||||
expect(updatedValues).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns 401 without an impersonation session header", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectPetRow = PET;
|
||||
|
||||
const res = await jsonPatch(`/portal/pets/${PET_ID}`, { name: "NoAuth" });
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
+145
-1
@@ -225,9 +225,153 @@ portalRouter.get("/pets", async (c) => {
|
||||
const clientId = c.get("portalClientId");
|
||||
|
||||
const clientPets = await db.select().from(pets).where(eq(pets.clientId, clientId));
|
||||
return c.json(clientPets.map(p => ({ id: p.id, name: p.name, breed: p.breed, weight: p.weightKg, birthDate: p.dateOfBirth, photoUrl: p.photoKey, notes: p.groomingNotes })));
|
||||
return c.json(clientPets.map(p => ({
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
breed: p.breed,
|
||||
weight: p.weightKg,
|
||||
birthDate: p.dateOfBirth,
|
||||
photoUrl: p.photoKey,
|
||||
notes: p.groomingNotes,
|
||||
coatType: p.coatType,
|
||||
petSizeCategory: p.petSizeCategory,
|
||||
healthAlerts: p.healthAlerts,
|
||||
preferredCuts: p.preferredCuts,
|
||||
medicalAlerts: p.medicalAlerts,
|
||||
})));
|
||||
});
|
||||
|
||||
// ─── Customer-facing pet update ───────────────────────────────────────────────
|
||||
//
|
||||
// The customer portal pet-profile form (groombook/web) saves edits via
|
||||
// PATCH /api/portal/pets/:petId. The web payload mixes the keys returned by
|
||||
// GET /portal/pets (weight, birthDate, photoUrl, notes) with the form's own
|
||||
// edited keys (weightKg, healthAlerts, coatType, …), so we accept both spellings
|
||||
// and map each to its `pets` column. Ownership is enforced exactly like the
|
||||
// appointment-notes handler: 404 if the pet does not exist, 403 if it belongs to
|
||||
// another client.
|
||||
|
||||
// Allowed enum values mirror packages/db/src/schema.ts coatTypeEnum /
|
||||
// petSizeCategoryEnum. Kept as plain string lists so an invalid value can be
|
||||
// rejected with 422 in-handler (zValidator failures would surface as 400).
|
||||
const PORTAL_COAT_TYPES: readonly string[] = ["short", "medium", "long", "double", "wire", "silky", "curly", "hairless"];
|
||||
const PORTAL_PET_SIZES: readonly string[] = ["small", "medium", "large", "extra_large"];
|
||||
// The web size dropdown emits "xlarge"; the DB enum value is "extra_large".
|
||||
const PORTAL_PET_SIZE_ALIASES: Record<string, string> = { xlarge: "extra_large" };
|
||||
|
||||
const portalMedicalAlertSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
type: z.string(),
|
||||
description: z.string(),
|
||||
severity: z.enum(["low", "medium", "high"]),
|
||||
});
|
||||
|
||||
const portalPetUpdateSchema = z.object({
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
breed: z.string().max(200).nullable().optional(),
|
||||
// weightKg is the form's edited key; weight is the GET-shaped key. Accept both.
|
||||
weightKg: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
weight: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
birthDate: z.string().nullable().optional(),
|
||||
notes: z.string().max(2000).nullable().optional(),
|
||||
healthAlerts: z.string().max(2000).nullable().optional(),
|
||||
photoUrl: z.string().nullable().optional(),
|
||||
// coatType / petSizeCategory validated in-handler so bad values return 422.
|
||||
coatType: z.string().nullable().optional(),
|
||||
petSizeCategory: z.string().nullable().optional(),
|
||||
preferredCuts: z.array(z.string()).nullable().optional(),
|
||||
medicalAlerts: z.array(portalMedicalAlertSchema).nullable().optional(),
|
||||
});
|
||||
|
||||
portalRouter.patch(
|
||||
"/pets/:petId",
|
||||
zValidator("json", portalPetUpdateSchema),
|
||||
async (c) => {
|
||||
const db = getDb();
|
||||
const petId = c.req.param("petId");
|
||||
const body = c.req.valid("json");
|
||||
const clientId = c.get("portalClientId");
|
||||
|
||||
const [pet] = await db
|
||||
.select()
|
||||
.from(pets)
|
||||
.where(eq(pets.id, petId))
|
||||
.limit(1);
|
||||
|
||||
if (!pet) {
|
||||
return c.json({ error: "Not found" }, 404);
|
||||
}
|
||||
|
||||
if (pet.clientId !== clientId) {
|
||||
return c.json({ error: "Forbidden" }, 403);
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = { updatedAt: new Date() };
|
||||
|
||||
if (body.name !== undefined) updateData.name = body.name;
|
||||
if (body.breed !== undefined) updateData.breed = body.breed;
|
||||
|
||||
if (body.weightKg !== undefined || body.weight !== undefined) {
|
||||
const w = body.weightKg ?? body.weight;
|
||||
updateData.weightKg = w === null || w === undefined ? null : String(w);
|
||||
}
|
||||
|
||||
if (body.birthDate !== undefined) {
|
||||
updateData.dateOfBirth = body.birthDate ? new Date(body.birthDate) : null;
|
||||
}
|
||||
|
||||
if (body.notes !== undefined) updateData.groomingNotes = body.notes;
|
||||
if (body.healthAlerts !== undefined) updateData.healthAlerts = body.healthAlerts;
|
||||
if (body.photoUrl !== undefined) updateData.photoKey = body.photoUrl;
|
||||
|
||||
if (body.coatType !== undefined) {
|
||||
if (body.coatType !== null && !PORTAL_COAT_TYPES.includes(body.coatType)) {
|
||||
return c.json({ error: "Invalid coatType" }, 422);
|
||||
}
|
||||
updateData.coatType = body.coatType;
|
||||
}
|
||||
|
||||
if (body.petSizeCategory !== undefined) {
|
||||
let size: string | null = body.petSizeCategory;
|
||||
if (size !== null) {
|
||||
size = PORTAL_PET_SIZE_ALIASES[size] ?? size;
|
||||
if (!PORTAL_PET_SIZES.includes(size)) {
|
||||
return c.json({ error: "Invalid petSizeCategory" }, 422);
|
||||
}
|
||||
}
|
||||
updateData.petSizeCategory = size;
|
||||
}
|
||||
|
||||
if (body.preferredCuts !== undefined) updateData.preferredCuts = body.preferredCuts ?? [];
|
||||
if (body.medicalAlerts !== undefined) updateData.medicalAlerts = body.medicalAlerts ?? [];
|
||||
|
||||
const [updated] = await db
|
||||
.update(pets)
|
||||
.set(updateData)
|
||||
.where(eq(pets.id, petId))
|
||||
.returning();
|
||||
|
||||
if (!updated) {
|
||||
return c.json({ error: "Not found" }, 404);
|
||||
}
|
||||
|
||||
return c.json({
|
||||
id: updated.id,
|
||||
name: updated.name,
|
||||
breed: updated.breed,
|
||||
weight: updated.weightKg,
|
||||
birthDate: updated.dateOfBirth,
|
||||
photoUrl: updated.photoKey,
|
||||
notes: updated.groomingNotes,
|
||||
coatType: updated.coatType,
|
||||
petSizeCategory: updated.petSizeCategory,
|
||||
healthAlerts: updated.healthAlerts,
|
||||
preferredCuts: updated.preferredCuts,
|
||||
medicalAlerts: updated.medicalAlerts,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
portalRouter.get("/invoices", async (c) => {
|
||||
const db = getDb();
|
||||
const clientId = c.get("portalClientId");
|
||||
|
||||
Reference in New Issue
Block a user