Compare commits
48 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c737bfece9 | |||
| 47e2021cf4 | |||
| 31404befee | |||
| a9db0ca9ac | |||
| 4bbb0c9fc5 | |||
| 03f79a3701 | |||
| 2b92c2ab6c | |||
| e9ad92de01 | |||
| bfe1a29c08 | |||
| 1ad43ce701 | |||
| 96dbb8c41d | |||
| 636fa713e1 | |||
| 6120b96c7c | |||
| eb92f99c4a | |||
| 587fd4ec95 | |||
| 6e2e46daf8 | |||
| 8cf72d926d | |||
| 8721f0b63c | |||
| 027e012a58 | |||
| b3db206588 | |||
| fc072d51f4 | |||
| 6538406db2 | |||
| e2eacbc9fe | |||
| e639cc82d1 | |||
| f2931d7be2 | |||
| d4a4ddce37 | |||
| bd384bdf5c | |||
| c92fb2539d | |||
| 411c42b2c4 | |||
| bf97849324 | |||
| 2a6242d3de | |||
| 7181d41b24 | |||
| 4e9c4c5e08 | |||
| 16c959434b | |||
| 23484dc90a | |||
| 766728865e | |||
| 6a81a52a50 | |||
| 5a4b9a98bd | |||
| f7f88156e1 | |||
| 8af5a49d14 | |||
| 403634eb96 | |||
| 152abfc4d5 | |||
| c8bbb12edb | |||
| ba95088653 | |||
| dd83f29736 | |||
| 185fce8e17 | |||
| 081379c189 | |||
| e01c12a316 |
@@ -287,6 +287,8 @@ This means:
|
||||
| TC-API-8.16 | Portal pet update — malformed (non-UUID) petId returns 404 (GRO-2203) | With a valid portal session, `PATCH /api/portal/pets/not-a-uuid` with header `X-Impersonation-Session-Id` and body `{"coatType":"short"}` | 404 Not Found with body `{"error":"Not found"}` (was an unhandled 500 from the Postgres uuid cast in GRO-2203; mirrors the GRO-2014 guard). No mutation persisted |
|
||||
| TC-API-8.17 | SSO portal session slides on activity (GRO-2234) | Establish a portal session (TC-API-8.8). Note the returned `sessionId`. Make any authenticated portal call (e.g. `GET /api/portal/me`) several times spaced over ≥1 minute, each with `X-Impersonation-Session-Id: {sessionId}`. | Every call returns 200; the session's `expiresAt` is extended (slid forward to ~30 min from each request) so the session stays valid during continuous use — it does NOT lapse mid-session. SSO-bridge sessions mint with a 30-min idle TTL bounded by an 8h absolute cap from `startedAt`. |
|
||||
| TC-API-8.18 | Slow-wizard Book New submit succeeds (GRO-2234) | Establish a portal session (TC-API-8.8). Wait >2 minutes while making at least one intervening authenticated portal call (mimicking the multi-step Book New wizard: pet/service/groomer/date GETs). Then `POST /api/portal/waitlist` with a valid pet+service payload and the same `X-Impersonation-Session-Id`. | 201 Created — the deliberately-paced wizard no longer 401s on submit because activity slid the session forward. (Regression guard for the GRO-2234 "session TTL too short → 401" defect.) |
|
||||
| TC-API-8.19 | Portal appointments surface active waitlist entries (GRO-2319) | As `uat-customer@groombook.dev`, establish a portal session, then `GET /api/portal/appointments`. | 200 OK. In addition to the customer's appointments, the response includes the seeded ACTIVE waitlist entry as a synthetic card: `status: "waitlisted"`, `id` prefixed `waitlist:`, `confirmationStatus: null`, a non-null derived `startTime` (from the entry's preferred date/time), and the entry's `pet`. Cancelled/notified/expired waitlist entries are NOT surfaced. |
|
||||
| TC-API-8.20 | Portal waitlist card populates service {id, name} (GRO-2342) | As `uat-customer@groombook.dev`, establish a portal session, then `GET /api/portal/appointments`. | 200 OK. The synthetic `waitlisted` card returned for the active waitlist entry has `service: {id: "<serviceId>", name: "<serviceName>"}` (full service record, not just `{id}`), matching the shape the appointments join returns. The portal Upcoming list therefore renders the actual service name in place of the fallback "Service" label. |
|
||||
|
||||
### 4.9 Waitlist
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
"wait-for-db": "node ./scripts/wait-for-db.mjs",
|
||||
"migrate": "node ./scripts/wait-for-db.mjs && drizzle-kit migrate",
|
||||
"seed": "node ./scripts/wait-for-db.mjs && tsx src/seed.ts",
|
||||
"reset": "node ./scripts/wait-for-db.mjs && tsx src/reset.ts",
|
||||
"reset": "node ./scripts/wait-for-db.mjs && tsx src/reset.ts && drizzle-kit migrate && tsx src/seed.ts",
|
||||
"studio": "drizzle-kit studio",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
|
||||
+39
-114
@@ -1,52 +1,13 @@
|
||||
/**
|
||||
* reset.ts — Drop all application tables, re-run migrations, and re-seed.
|
||||
* reset.ts — Drop all application tables and re-run migrations + seed.
|
||||
*
|
||||
* Intended for local development only. Never run against production.
|
||||
*
|
||||
* Usage:
|
||||
* DATABASE_URL=postgres://... npx tsx packages/db/src/reset.ts
|
||||
*
|
||||
* GRO-2139: the entire drop→migrate→seed chain runs inside a single
|
||||
* Postgres advisory lock (SEED_ADVISORY_LOCK_KEY) so a concurrent
|
||||
* `seed.ts` (e.g. the dev `seed-test-data-*` Job being recreated at
|
||||
* the top of the hour) cannot interleave between `reset.ts` (DROP)
|
||||
* and `seed.ts` (TRUNCATE+insert) and collide on `invoices_pkey`.
|
||||
*
|
||||
* Why this matters: `seed.ts` derives every primary key from a single
|
||||
* shared Mulberry32 PRNG seeded with 42 (see `createPrng(42)` and
|
||||
* `uuid()` in seed.ts). Two concurrent same-profile seeders therefore
|
||||
* emit *identical* ids for the same logical row, and any moment
|
||||
* between a concurrent `seed.ts` TRUNCATE and INSERT is exactly the
|
||||
* window in which the second seeder's INSERT can hit a pkey already
|
||||
* taken by the first. Pre-GRO-2123 this raced unconditionally;
|
||||
* GRO-2123 added the advisory lock around `runSeedBody` but left
|
||||
* `reset.ts` and `drizzle-kit migrate` outside the lock. This script
|
||||
* now wraps the *whole* chain in the same lock: `withSeedAdvisoryLock`
|
||||
* pins the lock to one reserved session and the DROP → migrate → seed
|
||||
* work runs on the rest of the pool, so the lock guarantees mutual
|
||||
* exclusion against any concurrent seeder for the entire chain.
|
||||
*
|
||||
* See: groombook/infra `apps/base/reset-cronjob.yaml` (CronJob) and
|
||||
* `apps/base/seed-job.yaml` (one-shot Job) — both invoke the same
|
||||
* `seed.ts` code path on the same database in `groombook-dev`.
|
||||
*/
|
||||
import postgres from "postgres";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import { migrate } from "drizzle-orm/postgres-js/migrator";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import * as schema from "./schema.js";
|
||||
import {
|
||||
SEED_ADVISORY_LOCK_KEY,
|
||||
withSeedAdvisoryLock,
|
||||
getProfile,
|
||||
runSeedBody,
|
||||
profiles,
|
||||
} from "./seed.js";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const MIGRATIONS_FOLDER = resolve(__dirname, "../migrations");
|
||||
import postgres from "postgres";
|
||||
|
||||
async function reset() {
|
||||
const url = process.env.DATABASE_URL;
|
||||
@@ -55,88 +16,52 @@ async function reset() {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (
|
||||
process.env.NODE_ENV === "production" &&
|
||||
process.env.ALLOW_RESET !== "true"
|
||||
) {
|
||||
console.error(
|
||||
"[FATAL] db:reset must not be run in production without ALLOW_RESET=true.",
|
||||
);
|
||||
if (process.env.NODE_ENV === "production" && process.env.ALLOW_RESET !== "true") {
|
||||
console.error("[FATAL] db:reset must not be run in production without ALLOW_RESET=true.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Pool sizing is load-bearing here. `withSeedAdvisoryLock` does
|
||||
// `pool.reserve()` to pin the advisory lock to one dedicated session
|
||||
// (a session-level lock released on a *different* pooled connection is
|
||||
// a no-op), and the DROP / migrate / seed work then runs on the
|
||||
// *remaining* pooled connections. The lock provides mutual exclusion
|
||||
// across processes regardless of how many connections the work uses —
|
||||
// it does NOT require the work to share the lock's session.
|
||||
//
|
||||
// Therefore `max` must be ≥ 2: 1 reserved for the lock + ≥1 free for
|
||||
// the work. `max: 1` would let `reserve()` consume the only connection
|
||||
// and every query inside the callback would block forever waiting for
|
||||
// a connection that never frees (connection-starvation deadlock). We
|
||||
// use `max: 6` to match `seed()`'s headroom (1 reserved + 5 work).
|
||||
const client = postgres(url, { max: 6 });
|
||||
const db = drizzle(client, { schema });
|
||||
const client = postgres(url, { max: 1 });
|
||||
|
||||
try {
|
||||
await withSeedAdvisoryLock(client, async () => {
|
||||
console.log("Dropping all application tables...\n");
|
||||
console.log("Dropping all application tables...\n");
|
||||
|
||||
// Drop dependencies (tables) first
|
||||
await client`
|
||||
DO $$ DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
FOR r IN (
|
||||
SELECT tablename FROM pg_tables
|
||||
WHERE schemaname = 'public'
|
||||
) LOOP
|
||||
EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE';
|
||||
END LOOP;
|
||||
END $$;
|
||||
`;
|
||||
// Drop in dependency order (children before parents)
|
||||
await client`
|
||||
DO $$ DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
FOR r IN (
|
||||
SELECT tablename FROM pg_tables
|
||||
WHERE schemaname = 'public'
|
||||
) LOOP
|
||||
EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE';
|
||||
END LOOP;
|
||||
END $$;
|
||||
`;
|
||||
|
||||
// Drop custom enums
|
||||
await client`
|
||||
DO $$ DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
FOR r IN (
|
||||
SELECT typname FROM pg_type
|
||||
WHERE typtype = 'e' AND typnamespace = (
|
||||
SELECT oid FROM pg_namespace WHERE nspname = 'public'
|
||||
)
|
||||
) LOOP
|
||||
EXECUTE 'DROP TYPE IF EXISTS ' || quote_ident(r.typname) || ' CASCADE';
|
||||
END LOOP;
|
||||
END $$;
|
||||
`;
|
||||
// Drop custom enums
|
||||
await client`
|
||||
DO $$ DECLARE
|
||||
r RECORD;
|
||||
BEGIN
|
||||
FOR r IN (
|
||||
SELECT typname FROM pg_type
|
||||
WHERE typtype = 'e' AND typnamespace = (
|
||||
SELECT oid FROM pg_namespace WHERE nspname = 'public'
|
||||
)
|
||||
) LOOP
|
||||
EXECUTE 'DROP TYPE IF EXISTS ' || quote_ident(r.typname) || ' CASCADE';
|
||||
END LOOP;
|
||||
END $$;
|
||||
`;
|
||||
|
||||
// Drop the drizzle migrations tracking table
|
||||
await client`DROP TABLE IF EXISTS drizzle.__drizzle_migrations CASCADE`;
|
||||
await client`DROP SCHEMA IF EXISTS drizzle CASCADE`;
|
||||
// Drop the drizzle migrations tracking table
|
||||
await client`DROP TABLE IF EXISTS drizzle.__drizzle_migrations CASCADE`;
|
||||
await client`DROP SCHEMA IF EXISTS drizzle CASCADE`;
|
||||
|
||||
console.log("✓ All tables and enums dropped\n");
|
||||
console.log("✓ All tables and enums dropped\n");
|
||||
|
||||
console.log("Running migrations...");
|
||||
await migrate(db, { migrationsFolder: MIGRATIONS_FOLDER });
|
||||
console.log("✓ Migrations applied\n");
|
||||
|
||||
console.log("Seeding database...");
|
||||
const profile = getProfile();
|
||||
const cfg = profiles[profile];
|
||||
await runSeedBody(client, db, profile, cfg);
|
||||
});
|
||||
|
||||
console.log(
|
||||
`\n✓ Reset complete (advisory lock key=0x${SEED_ADVISORY_LOCK_KEY.toString(16)})`,
|
||||
);
|
||||
} finally {
|
||||
await client.end();
|
||||
}
|
||||
await client.end();
|
||||
}
|
||||
|
||||
reset().catch((err) => {
|
||||
|
||||
+216
-8
@@ -24,9 +24,9 @@ import type { MedicalAlert } from "@groombook/types";
|
||||
|
||||
// ── Seed profile configuration ─────────────────────────────────────────────
|
||||
|
||||
export type SeedProfile = "dev" | "uat" | "demo";
|
||||
type SeedProfile = "dev" | "uat" | "demo";
|
||||
|
||||
export interface ProfileConfig {
|
||||
interface ProfileConfig {
|
||||
staffCount: { manager: number; receptionist: number; groomer: number; bather: number };
|
||||
clientCount: number;
|
||||
appointmentsBackDays: number;
|
||||
@@ -35,7 +35,7 @@ export interface ProfileConfig {
|
||||
includeUatClients: boolean;
|
||||
}
|
||||
|
||||
export const profiles: Record<SeedProfile, ProfileConfig> = {
|
||||
const profiles: Record<SeedProfile, ProfileConfig> = {
|
||||
dev: {
|
||||
staffCount: { manager: 1, receptionist: 1, groomer: 2, bather: 0 },
|
||||
clientCount: 100,
|
||||
@@ -70,8 +70,6 @@ function getProfile(): SeedProfile {
|
||||
return "uat";
|
||||
}
|
||||
|
||||
export { getProfile };
|
||||
|
||||
// ── Deterministic PRNG (Mulberry32) ──────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -832,6 +830,208 @@ async function seedUatGroomerLinkage(
|
||||
);
|
||||
}
|
||||
|
||||
// ── GRO-2311 / GRO-2313: portal customer StatusBadge coverage ────────────────
|
||||
|
||||
/**
|
||||
* GRO-2311 / GRO-2313: give the UAT portal customer (`uat-customer@groombook.dev`)
|
||||
* a deterministic spread of appointments so the customer-portal StatusBadge
|
||||
* palette can be LIVE-observed (not just code-verified against the bundle).
|
||||
*
|
||||
* `appointment_status` enum is (`scheduled, confirmed, in_progress, completed,
|
||||
* cancelled, no_show`) — the portal's <StatusBadge> renders `appointment.status`
|
||||
* verbatim. `pending` and `waitlisted` are NOT valid appointment statuses, so
|
||||
* GRO-2319 derives them in the portal: `pending` from an upcoming appointment's
|
||||
* `confirmationStatus` (the `scheduled` row below carries `pending`), and
|
||||
* `waitlisted` from an ACTIVE `waitlist_entries` row (seeded at the end of this
|
||||
* function) which `GET /api/portal/appointments` surfaces as a synthetic card.
|
||||
* The `no_show`→`no-show` badge-key fix is the web side of GRO-2319.
|
||||
*
|
||||
* - confirmed → future startTime → renders as an Upcoming card (Confirmed badge)
|
||||
* - scheduled → future startTime → renders as an Upcoming card (Scheduled badge)
|
||||
* - cancelled → past startTime → Past tab (isUpcoming excludes cancelled)
|
||||
* - no_show → past startTime → Past tab (raw `no_show` label until GRO-2319)
|
||||
*
|
||||
* The existing GRO-2100 `completed` appointment (a0000001-…-0001) is left
|
||||
* untouched (AC #4), so Completed is also covered.
|
||||
*
|
||||
* Idempotent: each appointment uses a fixed UUID and is upserted with
|
||||
* onConflictDoNothing, so the hourly reset-demo-data CronJob (which TRUNCATEs
|
||||
* then re-seeds) and non-truncating dev re-seeds never dup-key
|
||||
* (see GRO-2033 for the dup-key class).
|
||||
*/
|
||||
async function seedUatCustomerPortalAppointments(
|
||||
db: ReturnType<typeof drizzle>,
|
||||
customerClientId: string | null,
|
||||
): Promise<void> {
|
||||
const LINKED_PET_ID = "c0000001-0000-0000-0000-000000000002"; // UAT Pup Alpha
|
||||
|
||||
// Skip silently outside the UAT persona profile (e.g. a dev/test seed that
|
||||
// never created the UAT Customer client).
|
||||
if (!customerClientId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The customer's pet must exist (pets are NOT truncated on reset, so this is
|
||||
// stable). Defensive: bail cleanly if the persona pet is absent.
|
||||
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-2311: UAT Pup Alpha (${LINKED_PET_ID}) not found — skipping portal appointment seed`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Stable "Bath & Brush" service; fall back to any active service.
|
||||
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-2311: no active services found — skipping portal appointment seed`);
|
||||
return;
|
||||
}
|
||||
serviceId = fallback.id;
|
||||
}
|
||||
|
||||
// Attach the UAT groomer when present (nicer "with <groomer>" card); else null
|
||||
// ("First Available"). Either way these are the customer's own appointments —
|
||||
// no new groomer↔pet linkage invariant is created (uses the already-linked
|
||||
// Pup Alpha), so GRO-1987 TC-UAT-3 (403 on the UNLINKED Pup Beta) is unaffected.
|
||||
const [uatGroomerStaff] = await db
|
||||
.select({ id: schema.staff.id })
|
||||
.from(schema.staff)
|
||||
.where(eq(schema.staff.email, "uat-groomer@groombook.dev"))
|
||||
.limit(1);
|
||||
const staffId = uatGroomerStaff?.id ?? null;
|
||||
|
||||
// Anchor all times to local wall-clock so future/past holds regardless of the
|
||||
// hourly reset cadence.
|
||||
const at = (deltaDays: number, hour: number): Date => {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() + deltaDays);
|
||||
d.setHours(hour, 0, 0, 0);
|
||||
return d;
|
||||
};
|
||||
const DURATION_MS = 45 * 60 * 1000;
|
||||
|
||||
const rows = [
|
||||
{
|
||||
id: "a0000001-0000-0000-0000-000000000002",
|
||||
status: "confirmed" as const,
|
||||
start: at(3, 10),
|
||||
confirmationStatus: "confirmed",
|
||||
confirmedAt: new Date(),
|
||||
cancelledAt: null as Date | null,
|
||||
notes: "GRO-2311: upcoming confirmed appointment for portal StatusBadge coverage.",
|
||||
},
|
||||
{
|
||||
id: "a0000001-0000-0000-0000-000000000003",
|
||||
status: "scheduled" as const,
|
||||
start: at(5, 14),
|
||||
confirmationStatus: "pending",
|
||||
confirmedAt: null as Date | null,
|
||||
cancelledAt: null as Date | null,
|
||||
notes: "GRO-2311: upcoming scheduled appointment for portal StatusBadge coverage.",
|
||||
},
|
||||
{
|
||||
id: "a0000001-0000-0000-0000-000000000004",
|
||||
status: "cancelled" as const,
|
||||
start: at(-3, 11),
|
||||
confirmationStatus: "cancelled",
|
||||
confirmedAt: null as Date | null,
|
||||
cancelledAt: new Date(),
|
||||
notes: "GRO-2311: cancelled appointment (Past tab) for portal StatusBadge coverage.",
|
||||
},
|
||||
{
|
||||
id: "a0000001-0000-0000-0000-000000000005",
|
||||
status: "no_show" as const,
|
||||
start: at(-10, 9),
|
||||
confirmationStatus: "confirmed",
|
||||
confirmedAt: null as Date | null,
|
||||
cancelledAt: null as Date | null,
|
||||
notes: "GRO-2311: no_show appointment (Past tab) for portal StatusBadge coverage.",
|
||||
},
|
||||
];
|
||||
|
||||
await db
|
||||
.insert(schema.appointments)
|
||||
.values(
|
||||
rows.map((r) => ({
|
||||
id: r.id,
|
||||
clientId: customerClientId,
|
||||
petId: LINKED_PET_ID,
|
||||
serviceId,
|
||||
staffId,
|
||||
batherStaffId: null,
|
||||
status: r.status,
|
||||
startTime: r.start,
|
||||
endTime: new Date(r.start.getTime() + DURATION_MS),
|
||||
notes: r.notes,
|
||||
priceCents: null,
|
||||
confirmationStatus: r.confirmationStatus,
|
||||
confirmedAt: r.confirmedAt,
|
||||
cancelledAt: r.cancelledAt,
|
||||
})),
|
||||
)
|
||||
.onConflictDoNothing({ target: schema.appointments.id });
|
||||
|
||||
console.log(
|
||||
`✓ GRO-2311: seeded ${rows.length} portal StatusBadge appointments (confirmed/scheduled/cancelled/no_show) for UAT customer`,
|
||||
);
|
||||
|
||||
// GRO-2319 item 2: seed one ACTIVE waitlist entry so the portal's `waitlisted`
|
||||
// card (surfaced by GET /api/portal/appointments) is live-observable. Unlike
|
||||
// appointments, `waitlist_entries` is NOT truncated on the hourly reset, so we
|
||||
// upsert by fixed id and REFRESH the preferred date to a future-relative value
|
||||
// each reset — otherwise the date would go stale and the card would drop out of
|
||||
// the Upcoming list. (The seeded `scheduled` appointment above already carries
|
||||
// `confirmationStatus: "pending"`, which drives the live Pending badge.)
|
||||
const WAITLIST_ENTRY_ID = "e0000001-0000-0000-0000-000000000001";
|
||||
const pad2 = (n: number): string => String(n).padStart(2, "0");
|
||||
const wlStart = at(7, 13); // 7 days out, 1pm — comfortably "upcoming"
|
||||
const wlPreferredDate = `${wlStart.getFullYear()}-${pad2(wlStart.getMonth() + 1)}-${pad2(wlStart.getDate())}`;
|
||||
const wlPreferredTime = `${pad2(wlStart.getHours())}:00:00`;
|
||||
|
||||
await db
|
||||
.insert(schema.waitlistEntries)
|
||||
.values({
|
||||
id: WAITLIST_ENTRY_ID,
|
||||
clientId: customerClientId,
|
||||
petId: LINKED_PET_ID,
|
||||
serviceId,
|
||||
preferredDate: wlPreferredDate,
|
||||
preferredTime: wlPreferredTime,
|
||||
status: "active",
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: schema.waitlistEntries.id,
|
||||
set: {
|
||||
preferredDate: wlPreferredDate,
|
||||
preferredTime: wlPreferredTime,
|
||||
status: "active",
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
console.log(
|
||||
`✓ GRO-2319: seeded 1 active waitlist entry (${wlPreferredDate} ${wlPreferredTime}) for UAT customer portal Waitlisted card`,
|
||||
);
|
||||
}
|
||||
|
||||
// ── GRO-2225: deterministic route-optimization cohort ────────────────────────
|
||||
|
||||
/**
|
||||
@@ -1113,6 +1313,10 @@ async function seedKnownUsers() {
|
||||
// to attach to the appointment; on a fresh reset there are none yet at
|
||||
// the time seedUatStaffAccounts() returns).
|
||||
await seedUatGroomerLinkage(db, uatCustomerClientId);
|
||||
// GRO-2311 / GRO-2313: portal customer StatusBadge palette coverage (reachable
|
||||
// appointment statuses only). Runs after the groomer linkage so the customer
|
||||
// client + Pup Alpha already exist.
|
||||
await seedUatCustomerPortalAppointments(db, uatCustomerClientId);
|
||||
|
||||
// ── Client: Demo Client ──
|
||||
const [existingClient] = await db
|
||||
@@ -1196,7 +1400,7 @@ async function seedKnownUsers() {
|
||||
// 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).
|
||||
export const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitrary, stable
|
||||
const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitrary, stable
|
||||
|
||||
/**
|
||||
* Reserve a dedicated connection from `pool`, take the seed advisory lock
|
||||
@@ -1209,7 +1413,7 @@ export const SEED_ADVISORY_LOCK_KEY = 0x47524f4f; // "GROO" in ASCII — arbitra
|
||||
* for the lock and release it from the same reserved connection. The
|
||||
* seed work itself still runs on the pooled connections.
|
||||
*/
|
||||
export async function withSeedAdvisoryLock<T>(
|
||||
async function withSeedAdvisoryLock<T>(
|
||||
pool: ReturnType<typeof postgres>,
|
||||
fn: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
@@ -1267,7 +1471,7 @@ async function seed() {
|
||||
await client.end();
|
||||
}
|
||||
|
||||
export async function runSeedBody(
|
||||
async function runSeedBody(
|
||||
client: ReturnType<typeof postgres>,
|
||||
db: ReturnType<typeof drizzle>,
|
||||
profile: SeedProfile,
|
||||
@@ -1375,6 +1579,10 @@ export async function runSeedBody(
|
||||
// to attach to the appointment; on a fresh reset there are none yet at
|
||||
// the time seedUatStaffAccounts() returns).
|
||||
await seedUatGroomerLinkage(db, uatCustomerClientId);
|
||||
// GRO-2311 / GRO-2313: portal customer StatusBadge palette coverage (reachable
|
||||
// appointment statuses only). Runs after the groomer linkage so the customer
|
||||
// client + Pup Alpha already exist.
|
||||
await seedUatCustomerPortalAppointments(db, uatCustomerClientId);
|
||||
|
||||
// GRO-2225: deterministic pre-geocoded route cohort + fixed-date appointments
|
||||
// for the UAT groomer. Must run AFTER services are seeded (it looks up a
|
||||
|
||||
@@ -39,11 +39,19 @@ const APPOINTMENT = {
|
||||
|
||||
let selectSessionRow: Record<string, unknown> | null = null;
|
||||
let selectAppointmentRow: Record<string, unknown> | null = null;
|
||||
let selectWaitlistRows: Record<string, unknown>[] = [];
|
||||
let selectPetRows: Record<string, unknown>[] = [];
|
||||
let selectStaffRows: Record<string, unknown>[] = [];
|
||||
let selectServiceRows: Record<string, unknown>[] = [];
|
||||
let updatedValues: Record<string, unknown>[] = [];
|
||||
|
||||
function resetMock() {
|
||||
selectSessionRow = null;
|
||||
selectAppointmentRow = null;
|
||||
selectWaitlistRows = [];
|
||||
selectPetRows = [];
|
||||
selectStaffRows = [];
|
||||
selectServiceRows = [];
|
||||
updatedValues = [];
|
||||
}
|
||||
|
||||
@@ -72,6 +80,13 @@ vi.mock("@groombook/db", () => {
|
||||
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
|
||||
);
|
||||
|
||||
const mkTable = (name: string) =>
|
||||
new Proxy({ _name: name }, { get: (t, p) => (p === "_name" ? name : { table: name, column: p }) });
|
||||
const waitlistEntries = mkTable("waitlistEntries");
|
||||
const pets = mkTable("pets");
|
||||
const staff = mkTable("staff");
|
||||
const services = mkTable("services");
|
||||
|
||||
return {
|
||||
getDb: () => ({
|
||||
select: () => ({
|
||||
@@ -82,6 +97,18 @@ vi.mock("@groombook/db", () => {
|
||||
if (table._name === "appointments") {
|
||||
return makeChainable(selectAppointmentRow ? [selectAppointmentRow] : []);
|
||||
}
|
||||
if (table._name === "waitlistEntries") {
|
||||
return makeChainable(selectWaitlistRows);
|
||||
}
|
||||
if (table._name === "pets") {
|
||||
return makeChainable(selectPetRows);
|
||||
}
|
||||
if (table._name === "staff") {
|
||||
return makeChainable(selectStaffRows);
|
||||
}
|
||||
if (table._name === "services") {
|
||||
return makeChainable(selectServiceRows);
|
||||
}
|
||||
return makeChainable([]);
|
||||
},
|
||||
}),
|
||||
@@ -102,8 +129,13 @@ vi.mock("@groombook/db", () => {
|
||||
}),
|
||||
impersonationSessions,
|
||||
appointments,
|
||||
waitlistEntries,
|
||||
pets,
|
||||
staff,
|
||||
services,
|
||||
eq: vi.fn(),
|
||||
and: vi.fn(),
|
||||
inArray: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -125,6 +157,104 @@ function jsonPatch(path: string, body: unknown, headers?: Record<string, string>
|
||||
|
||||
beforeEach(() => resetMock());
|
||||
|
||||
// GRO-2319 item 2: the portal Upcoming list renders active waitlist entries as
|
||||
// synthetic `waitlisted` cards, so GET /portal/appointments must surface them.
|
||||
describe("GET /portal/appointments (waitlist surfacing — GRO-2319)", () => {
|
||||
it("returns active waitlist entries as synthetic waitlisted cards", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectAppointmentRow = { ...APPOINTMENT };
|
||||
selectWaitlistRows = [
|
||||
{
|
||||
id: "11111111-1111-1111-1111-111111111111",
|
||||
petId: "pet-1",
|
||||
serviceId: "svc-1",
|
||||
preferredDate: "2099-01-01",
|
||||
preferredTime: "13:00:00",
|
||||
},
|
||||
];
|
||||
selectPetRows = [{ id: "pet-1", name: "Rex", photoKey: null }];
|
||||
|
||||
const res = await app.request("/portal/appointments", {
|
||||
headers: { "X-Impersonation-Session-Id": SESSION_ID },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
const waitlistCard = body.appointments.find(
|
||||
(a: { status: string }) => a.status === "waitlisted",
|
||||
);
|
||||
expect(waitlistCard).toBeTruthy();
|
||||
expect(waitlistCard.id).toBe("waitlist:11111111-1111-1111-1111-111111111111");
|
||||
expect(waitlistCard.pet.name).toBe("Rex");
|
||||
expect(waitlistCard.confirmationStatus).toBeNull();
|
||||
// startTime is derived from preferredDate + preferredTime so the card sorts
|
||||
// and classifies as Upcoming.
|
||||
expect(waitlistCard.startTime).toBeTruthy();
|
||||
});
|
||||
|
||||
it("omits the waitlist section when the client has no active entries", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectAppointmentRow = { ...APPOINTMENT };
|
||||
selectWaitlistRows = [];
|
||||
|
||||
const res = await app.request("/portal/appointments", {
|
||||
headers: { "X-Impersonation-Session-Id": SESSION_ID },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.appointments.some((a: { status: string }) => a.status === "waitlisted")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// GRO-2342: GET /portal/appointments must populate the synthetic waitlist
|
||||
// card's `service` object with the full service record (id + name) — same
|
||||
// shape the appointments join returns — so the portal renders the real
|
||||
// service name in place of the fallback "Service" label.
|
||||
describe("GET /portal/appointments (waitlist service name — GRO-2342)", () => {
|
||||
it("returns service {id, name} on the synthetic waitlist card", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectAppointmentRow = { ...APPOINTMENT };
|
||||
selectWaitlistRows = [
|
||||
{
|
||||
id: "22222222-2222-2222-2222-222222222222",
|
||||
petId: "pet-1",
|
||||
serviceId: "svc-1",
|
||||
preferredDate: "2099-01-01",
|
||||
preferredTime: "13:00:00",
|
||||
},
|
||||
];
|
||||
selectPetRows = [{ id: "pet-1", name: "Rex", photoKey: null }];
|
||||
selectServiceRows = [{ id: "svc-1", name: "Full Groom" }];
|
||||
|
||||
const res = await app.request("/portal/appointments", {
|
||||
headers: { "X-Impersonation-Session-Id": SESSION_ID },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
const waitlistCard = body.appointments.find(
|
||||
(a: { status: string }) => a.status === "waitlisted",
|
||||
);
|
||||
expect(waitlistCard).toBeTruthy();
|
||||
expect(waitlistCard.service).toEqual({ id: "svc-1", name: "Full Groom" });
|
||||
});
|
||||
|
||||
it("returns service {id, name} on the appointment card (same shape)", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
selectAppointmentRow = { ...APPOINTMENT, serviceId: "svc-appt" };
|
||||
selectServiceRows = [{ id: "svc-appt", name: "Bath & Brush" }];
|
||||
|
||||
const res = await app.request("/portal/appointments", {
|
||||
headers: { "X-Impersonation-Session-Id": SESSION_ID },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
const apptCard = body.appointments.find(
|
||||
(a: { status: string }) => a.status === "scheduled",
|
||||
);
|
||||
expect(apptCard).toBeTruthy();
|
||||
expect(apptCard.service).toEqual({ id: "svc-appt", name: "Bath & Brush" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("PATCH /portal/appointments/:id/notes", () => {
|
||||
it("returns updated appointment with safe fields only", async () => {
|
||||
selectSessionRow = ACTIVE_SESSION;
|
||||
|
||||
+60
-4
@@ -1,7 +1,7 @@
|
||||
import { Hono } from "hono";
|
||||
import { zValidator } from "@hono/zod-validator";
|
||||
import { z } from "zod/v3";
|
||||
import { eq, inArray } from "@groombook/db";
|
||||
import { and, eq, inArray } from "@groombook/db";
|
||||
import { getDb, appointments, impersonationSessions, waitlistEntries, clients, pets, services, staff, invoices, invoiceLineItems } from "@groombook/db";
|
||||
import { validatePortalSession, PORTAL_SESSION_IDLE_TTL_MS } from "../middleware/portalSession.js";
|
||||
import { portalAudit } from "../middleware/portalAudit.js";
|
||||
@@ -195,14 +195,46 @@ portalRouter.get("/appointments", async (c) => {
|
||||
.where(eq(appointments.clientId, clientId))
|
||||
.orderBy(appointments.startTime);
|
||||
|
||||
const petIds = allAppts.map(a => a.petId).filter((id): id is string => id !== null);
|
||||
// GRO-2319: surface the client's ACTIVE waitlist entries alongside their
|
||||
// appointments so the portal can render them as `waitlisted` cards in the
|
||||
// Upcoming list. The `appointment_status` enum cannot represent `waitlisted`,
|
||||
// so these are synthetic entries (status hard-set to `waitlisted`, id prefixed
|
||||
// `waitlist:`) derived from `waitlist_entries`.
|
||||
const waitlistRows = await db
|
||||
.select({
|
||||
id: waitlistEntries.id,
|
||||
petId: waitlistEntries.petId,
|
||||
serviceId: waitlistEntries.serviceId,
|
||||
preferredDate: waitlistEntries.preferredDate,
|
||||
preferredTime: waitlistEntries.preferredTime,
|
||||
})
|
||||
.from(waitlistEntries)
|
||||
.where(
|
||||
and(eq(waitlistEntries.clientId, clientId), eq(waitlistEntries.status, "active")),
|
||||
);
|
||||
|
||||
// Pet lookups must cover both appointment and waitlist pets.
|
||||
const petIds = [
|
||||
...allAppts.map(a => a.petId).filter((id): id is string => id !== null),
|
||||
...waitlistRows.map(w => w.petId),
|
||||
];
|
||||
const staffIds = allAppts.map(a => a.staffId).filter((id): id is string => id !== null);
|
||||
// GRO-2342: services must be looked up for both appointment and waitlist cards
|
||||
// so the portal can render `service.name` in place of the fallback "Service"
|
||||
// label (CMPO sign-off on the GRO-2319 waitlist card explicitly excluded the
|
||||
// service name; this follow-up closes the cosmetic gap).
|
||||
const serviceIds = [
|
||||
...allAppts.map(a => a.serviceId).filter((id): id is string => id !== null),
|
||||
...waitlistRows.map(w => w.serviceId).filter((id): id is string => id !== null),
|
||||
];
|
||||
|
||||
const petRows = petIds.length ? await db.select().from(pets).where(inArray(pets.id, petIds)) : [];
|
||||
const staffRows = staffIds.length ? await db.select().from(staff).where(inArray(staff.id, staffIds)) : [];
|
||||
const serviceRows = serviceIds.length ? await db.select().from(services).where(inArray(services.id, serviceIds)) : [];
|
||||
|
||||
const petMap = Object.fromEntries(petRows.map(p => [p.id, p]));
|
||||
const staffMap = Object.fromEntries(staffRows.map(s => [s.id, s]));
|
||||
const serviceMap = Object.fromEntries(serviceRows.map(s => [s.id, s]));
|
||||
|
||||
const appts = allAppts.map(a => ({
|
||||
id: a.id,
|
||||
@@ -213,11 +245,35 @@ portalRouter.get("/appointments", async (c) => {
|
||||
customerNotes: a.customerNotes,
|
||||
notes: a.notes,
|
||||
pet: a.petId ? { id: petMap[a.petId]?.id, name: petMap[a.petId]?.name, photo: petMap[a.petId]?.photoKey } : null,
|
||||
service: a.serviceId ? { id: a.serviceId } : null,
|
||||
service: a.serviceId ? { id: a.serviceId, name: serviceMap[a.serviceId]?.name } : null,
|
||||
staff: a.staffId ? { id: staffMap[a.staffId]?.id, name: staffMap[a.staffId]?.name } : null,
|
||||
}));
|
||||
|
||||
return c.json({ appointments: appts });
|
||||
// Derive a display `startTime` from the entry's preferred date/time so the
|
||||
// portal can sort/classify the synthetic card (an invalid combination simply
|
||||
// yields a null startTime, which the portal tolerates). GRO-2342: also
|
||||
// populate the synthetic card's `service` object with the full service
|
||||
// record (id + name) — same shape the appointments join returns — so the
|
||||
// portal renders the real service name in place of the fallback "Service"
|
||||
// label.
|
||||
const waitlistAppts = waitlistRows.map(w => {
|
||||
const parsed = new Date(`${w.preferredDate}T${w.preferredTime}`);
|
||||
const startTime = Number.isNaN(parsed.getTime()) ? null : parsed;
|
||||
return {
|
||||
id: `waitlist:${w.id}`,
|
||||
startTime,
|
||||
endTime: null,
|
||||
status: "waitlisted" as const,
|
||||
confirmationStatus: null,
|
||||
customerNotes: null,
|
||||
notes: null,
|
||||
pet: { id: petMap[w.petId]?.id, name: petMap[w.petId]?.name, photo: petMap[w.petId]?.photoKey },
|
||||
service: w.serviceId ? { id: w.serviceId, name: serviceMap[w.serviceId]?.name } : null,
|
||||
staff: null,
|
||||
};
|
||||
});
|
||||
|
||||
return c.json({ appointments: [...appts, ...waitlistAppts] });
|
||||
});
|
||||
|
||||
portalRouter.get("/pets", async (c) => {
|
||||
|
||||
Reference in New Issue
Block a user