Compare commits

..

34 Commits

Author SHA1 Message Date
Flea Flicker e6c729be12 feat(GRO-2319): surface active waitlist entries on portal appointments + seed (#204)
CI / Test (pull_request) Successful in 29s
CI / Lint & Typecheck (pull_request) Successful in 38s
CI / Build & Push Docker Images (pull_request) Successful in 1m26s
2026-06-09 10:42:41 +00:00
Flea Flicker 807ccb455f dev → uat: GRO-2311 seed portal StatusBadge appointments (#201) (#202)
CI / Lint & Typecheck (push) Successful in 28s
CI / Test (push) Successful in 24s
CI / Build & Push Docker Images (push) Successful in 1m23s
2026-06-09 09:56:34 +00:00
Flea Flicker c4385617c6 dev → uat: GRO-2172 extended pet fields (#200)
CI / Test (push) Successful in 23s
CI / Lint & Typecheck (push) Successful in 24s
CI / Build & Push Docker Images (push) Successful in 39s
2026-06-09 09:22:12 +00:00
Flea Flicker 8cd5a2ef4d dev → uat: GRO-2299 redact googleMapsApiKey from PATCH /api/admin/settings (#196)
CI / Test (push) Failing after 10m55s
CI / Lint & Typecheck (push) Failing after 10m55s
CI / Build & Push Docker Images (push) Has been skipped
2026-06-09 06:58:39 +00:00
Flea Flicker 2566fb8f20 Promote GRO-2294 to UAT: Route Optimization security hardening (#194)
CI / Lint & Typecheck (push) Successful in 28s
CI / Test (push) Successful in 29s
CI / Build & Push Docker Images (push) Successful in 39s
CI / Test (pull_request) Successful in 25s
CI / Lint & Typecheck (pull_request) Successful in 37s
CI / Build & Push Docker Images (pull_request) Successful in 1m8s
2026-06-09 06:27:17 +00:00
Lint Roller 4868f18dfd Merge pull request 'Promote dev→uat: GRO-2225 + GRO-2235 + GRO-2157 (atomic)' (#188) from promote/dev-to-uat-gro-2225 into uat
CI / Test (push) Successful in 29s
CI / Lint & Typecheck (push) Successful in 36s
CI / Build & Push Docker Images (push) Successful in 41s
CI / Test (pull_request) Successful in 28s
CI / Lint & Typecheck (pull_request) Successful in 31s
CI / Build & Push Docker Images (pull_request) Successful in 1m17s
Promote dev→uat: GRO-2225 + GRO-2235 + GRO-2157 (atomic)

QA-approved on 37e42b3. CI green (Test, Lint & Typecheck, Build & Push).
2026-06-09 00:26:18 +00:00
Flea Flicker 37e42b3104 ci: re-trigger checks (transient pnpm/action-setup runner flake)
CI / Test (pull_request) Successful in 26s
CI / Lint & Typecheck (pull_request) Successful in 30s
CI / Build & Push Docker Images (pull_request) Successful in 27s
Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-06-09 00:21:03 +00:00
Flea Flicker d617c69571 Merge remote-tracking branch 'origin/dev' into promote/dev-to-uat-gro-2225
CI / Test (pull_request) Failing after 5s
CI / Lint & Typecheck (pull_request) Successful in 28s
CI / Build & Push Docker Images (pull_request) Has been skipped
2026-06-09 00:18:24 +00:00
Flea Flicker 76d9850464 Promote dev→uat: GRO-2225 UAT seed route cohort + receptionist credential
CI / Test (pull_request) Successful in 30s
CI / Lint & Typecheck (pull_request) Successful in 31s
CI / Build & Push Docker Images (pull_request) Failing after 15s
2026-06-08 23:16:51 +00:00
Flea Flicker 96dbb8c41d Merge pull request 'Promote dev → uat: GRO-2155/2156/2203/2211/2163 + GRO-2234 (cumulative batch)' (#182) from flea/dev-to-uat-gro-2156 into uat
CI / Test (push) Successful in 25s
CI / Lint & Typecheck (push) Successful in 30s
CI / Build & Push Docker Images (push) Successful in 1m24s
CI / Test (pull_request) Successful in 27s
CI / Lint & Typecheck (pull_request) Successful in 30s
CI / Build & Push Docker Images (pull_request) Successful in 1m11s
2026-06-08 19:42:25 +00:00
Flea Flicker 636fa713e1 Merge dev into uat: add GRO-2234 portal session sliding TTL + re-mint to dev→uat batch
CI / Test (pull_request) Successful in 28s
CI / Lint & Typecheck (pull_request) Successful in 28s
CI / Build & Push Docker Images (pull_request) Successful in 27s
2026-06-08 19:17:15 +00:00
Flea Flicker 6120b96c7c Merge dev into uat: promote GRO-2156 route travel buffer + reorder (Phase 2.2)
CI / Test (pull_request) Successful in 26s
CI / Lint & Typecheck (pull_request) Successful in 28s
CI / Build & Push Docker Images (pull_request) Successful in 1m2s
Resolves UAT_PLAYBOOK.md conflict by unioning uat-only TC-UAT-2/3 (GRO-2100)
with dev's §4.16 update + new §4.17. Code files taken from dev (superset).

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-06-08 18:11:05 +00:00
Flea Flicker eb92f99c4a dev → uat: GRO-2203 portal pet PATCH malformed-petId 500→404 (#178)
CI / Test (push) Successful in 27s
CI / Lint & Typecheck (push) Successful in 32s
CI / Build & Push Docker Images (push) Successful in 1m1s
CI / Test (pull_request) Successful in 27s
CI / Lint & Typecheck (pull_request) Successful in 31s
CI / Build & Push Docker Images (pull_request) Successful in 1m4s
2026-06-08 17:53:01 +00:00
Flea Flicker 587fd4ec95 dev → uat: GRO-2155 route optimization endpoints (carries GRO-2163) (#176)
CI / Test (push) Successful in 26s
CI / Lint & Typecheck (push) Successful in 27s
CI / Build & Push Docker Images (push) Successful in 25s
2026-06-08 16:45:44 +00:00
Flea Flicker 8cf72d926d dev → uat: portal photoKey S3 key-hijack fix (GRO-2187/GRO-2198) (#173)
CI / Test (push) Successful in 22s
CI / Lint & Typecheck (push) Successful in 27s
CI / Build & Push Docker Images (push) Successful in 43s
CI / Test (pull_request) Successful in 27s
CI / Lint & Typecheck (pull_request) Successful in 32s
CI / Build & Push Docker Images (pull_request) Successful in 39s
2026-06-08 12:39:52 +00:00
Flea Flicker 8721f0b63c dev → uat: GRO-2154 geocoding endpoints (Phase 1.3) (#171)
CI / Test (push) Successful in 24s
CI / Lint & Typecheck (push) Successful in 27s
CI / Build & Push Docker Images (push) Successful in 35s
2026-06-08 12:06:43 +00:00
Flea Flicker 027e012a58 Merge pull request 'dev → uat: GRO-2153 abstracted geocoding service' (#168) from dev-to-uat-gro-2153 into uat
CI / Test (push) Successful in 1m5s
CI / Lint & Typecheck (push) Successful in 43m29s
CI / Build & Push Docker Images (push) Successful in 1m7s
2026-06-08 10:51:17 +00:00
Flea Flicker b3db206588 Merge pull request 'dev → uat: GRO-2187 portal pet PATCH + GET enrichment (carries GRO-2152)' (#166) from dev-to-uat-gro-2187 into uat
CI / Test (push) Successful in 1m19s
CI / Lint & Typecheck (push) Successful in 1m25s
CI / Build & Push Docker Images (push) Successful in 3m58s
2026-06-08 10:02:17 +00:00
Flea Flicker 6538406db2 Merge pull request 'chore: delete stale apps/api/src/db/seed.ts duplicate (GRO-2129)' (#158) from dev into uat
CI / Test (push) Successful in 12s
CI / Lint & Typecheck (push) Successful in 18s
CI / Build & Push Docker Images (push) Successful in 38s
CI / Test (pull_request) Successful in 22s
CI / Lint & Typecheck (pull_request) Successful in 25s
CI / Build & Push Docker Images (pull_request) Successful in 38s
2026-06-04 12:45:24 +00:00
Flea Flicker e2eacbc9fe Merge pull request 'dev → uat: GRO-2123 seed advisory lock' (#156) from dev-to-uat-gro-2123 into uat
CI / Test (push) Successful in 16s
CI / Lint & Typecheck (push) Successful in 16s
CI / Build & Push Docker Images (push) Successful in 40s
CI / Test (pull_request) Successful in 12s
CI / Lint & Typecheck (pull_request) Successful in 15s
CI / Build & Push Docker Images (pull_request) Successful in 39s
2026-06-04 11:32:06 +00:00
Flea Flicker e639cc82d1 chore(uat): GRO-2100 promote uat-groomer seed-linkage ordering fix to uat (#154)
CI / Test (push) Successful in 16s
CI / Lint & Typecheck (push) Successful in 19s
CI / Build & Push Docker Images (push) Successful in 27s
Co-authored-by: Flea Flicker <flea@groombook.dev>
Co-committed-by: Flea Flicker <flea@groombook.dev>
2026-06-02 20:23:54 +00:00
Flea Flicker f2931d7be2 Merge pull request 'Promote dev→uat: GRO-2100 uat-groomer ↔ UAT Pup Alpha linkage' (#152) from promote/dev-to-uat-gro-2100 into uat
CI / Test (push) Successful in 13s
CI / Lint & Typecheck (push) Successful in 18s
CI / Build & Push Docker Images (push) Successful in 26s
Merge pull request #152 from groombook/promote/dev-to-uat-gro-2100

Promote dev→uat: GRO-2100 uat-groomer ↔ UAT Pup Alpha linkage
2026-06-02 19:11:46 +00:00
Paperclip d4a4ddce37 ci: retrigger GRO-2100 PR #152 Build & Push Docker Images (Reset image build failed — docker registry flake)
CI / Test (pull_request) Successful in 13s
CI / Lint & Typecheck (pull_request) Successful in 17s
CI / Build & Push Docker Images (pull_request) Successful in 40s
2026-06-02 18:28:17 +00:00
Paperclip bd384bdf5c docs(UAT_PLAYBOOK): add TC-UAT-2/3 for uat-groomer linked/unlinked pet profile-summary (GRO-2100)
CI / Lint & Typecheck (pull_request) Successful in 16s
CI / Test (pull_request) Successful in 2m20s
CI / Build & Push Docker Images (pull_request) Failing after 36s
Lint Roller review on PR #152 flagged that the GRO-2100 seed change produces
new observable UAT API behavior that the playbook must reflect. Add two
deterministic rows pinning the contract GRO-1987 TC-UAT-2/3 will exercise:

- TC-UAT-2: uat-groomer + linked pet c0000001-...-002 (UAT Pup Alpha) → 200
- TC-UAT-3: uat-groomer + unlinked pet c0000001-...-003 (UAT Pup Beta) → 403

The 403-vs-404 note in TC-UAT-3 mirrors the verification note in the
GRO-2100 issue body so the QA runner knows where to file if the API
returns 404 (a separate RBAC defect, not against the seed).
2026-06-02 18:24:40 +00:00
The Dogfather 411c42b2c4 Merge pull request 'Promote dev→uat: GRO-2033 services_pkey seed fix (fc6c6ef7)' (#149) from dev into uat
CI / Test (push) Successful in 14s
CI / Lint & Typecheck (push) Successful in 16s
CI / Build & Push Docker Images (push) Successful in 39s
CI / Test (pull_request) Successful in 12s
CI / Lint & Typecheck (pull_request) Successful in 16s
CI / Build & Push Docker Images (pull_request) Successful in 38s
2026-06-02 05:06:34 +00:00
The Dogfather bf97849324 promote(dev→uat): owner-bypass read audit row (GRO-2063) (#147)
CI / Test (push) Successful in 12s
CI / Lint & Typecheck (push) Successful in 17s
CI / Build & Push Docker Images (push) Successful in 41s
Promote GRO-2063 defense-in-depth audit row to uat. CI green. QA + CTO approved on dev PR #146.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-06-02 04:21:43 +00:00
The Dogfather 7181d41b24 Merge pull request 'Promote dev→uat: rbac Better-Auth auto-provision (GRO-2052)' (#144) from dev into uat
CI / Test (push) Successful in 13s
CI / Lint & Typecheck (push) Successful in 15s
CI / Build & Push Docker Images (push) Failing after 13s
CI / Test (pull_request) Successful in 12s
CI / Lint & Typecheck (pull_request) Successful in 15s
CI / Build & Push Docker Images (pull_request) Successful in 41s
Promote dev→uat: rbac Better-Auth auto-provision (GRO-2052)

Makes the pets.ts owner-bypass reachable for Better-Auth email/password customers by auto-provisioning a groomer staff row keyed on user.id. Unblocks GRO-2050 and GRO-2035.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 02:42:19 +00:00
The Dogfather 4e9c4c5e08 Merge pull request 'promote(uat): GRO-2013 owner-bypass + GRO-2033 idempotent migrations (dev→uat)' (#142) from dogfather/gro-2013-promote-uat into uat
CI / Test (push) Successful in 13s
CI / Lint & Typecheck (push) Successful in 18s
CI / Build & Push Docker Images (push) Successful in 39s
2026-06-01 20:14:14 +00:00
The Dogfather 16c959434b promote(uat): GRO-2013 owner-bypass + GRO-2033 idempotent migrations (dev→uat)
CI / Test (pull_request) Successful in 11s
CI / Lint & Typecheck (pull_request) Successful in 16s
CI / Build & Push Docker Images (pull_request) Successful in 41s
Merge dev into uat. Resolves test-file/playbook conflicts created by PR #138's
squash merge by taking dev's superset versions (verified: all GRO-2014 tests +
TC ids preserved, plus GRO-2013 additions). No-ff merge so dev becomes an
ancestor of uat, preventing future squash-divergence conflicts.

Carries:
- GRO-2013 deployed-tree owner-bypass (src/routes/pets.ts, reconciled 20-test file)
- GRO-2033 idempotent migrations 0039/0040

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-06-01 20:10:51 +00:00
The Dogfather 23484dc90a promote(uat): GRO-2014 profile-summary error-handling fix (dev→uat) (#138)
CI / Test (push) Successful in 10s
CI / Lint & Typecheck (push) Successful in 16s
CI / Build & Push Docker Images (push) Successful in 39s
2026-06-01 18:27:42 +00:00
The Dogfather 6a81a52a50 Merge pull request 'Promote dev → uat: UAT seed-password source-of-truth playbook (GRO-2000)' (#134) from dev into uat
CI / Test (push) Successful in 12s
CI / Lint & Typecheck (push) Successful in 15s
CI / Build & Push Docker Images (push) Successful in 27s
CI / Test (pull_request) Successful in 11s
CI / Lint & Typecheck (pull_request) Successful in 13s
CI / Build & Push Docker Images (pull_request) Successful in 1m10s
2026-06-01 17:41:47 +00:00
The Dogfather 5a4b9a98bd Merge pull request 'promote(docker): bake pnpm via npm to remove Corepack runtime downloads (GRO-1981)' (#133) from dev into uat
CI / Test (push) Successful in 12s
CI / Lint & Typecheck (push) Successful in 14s
CI / Build & Push Docker Images (push) Successful in 40s
Promote GRO-1985 (parent GRO-1981) dev->uat. cc @cpfarhood
2026-06-01 16:30:54 +00:00
The Dogfather f7f88156e1 Merge pull request 'promote(db): register extra_large via migration 0038 to UAT (GRO-2004)' (#131) from dev into uat
CI / Test (push) Successful in 11s
CI / Lint & Typecheck (push) Successful in 15s
CI / Build & Push Docker Images (push) Successful in 35s
2026-06-01 14:52:13 +00:00
The Dogfather 8af5a49d14 Merge pull request 'Promote dev→uat: GRO-1982 pet_size_category extra_large enum migration' (#126) from dev into uat
CI / Test (push) Successful in 13s
CI / Lint & Typecheck (push) Successful in 16s
CI / Build & Push Docker Images (push) Successful in 37s
Promote dev→uat: GRO-1983 seed-job pnpm fix + GRO-1982 extra_large enum migration

Carries the accumulated dev state into uat (PR #125 docker pnpm fix + 0037 migration).

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-06-01 12:44:20 +00:00
9 changed files with 49 additions and 518 deletions
-11
View File
@@ -1,11 +0,0 @@
{
"mcpServers": {
"gitea": {
"type": "http",
"url": "https://git-mcp.farh.net/mcp",
"headers": {
"Authorization": "Bearer ${GITEA_TOKEN}"
}
}
}
}
-1
View File
@@ -288,7 +288,6 @@ This means:
| 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
+1 -1
View File
@@ -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
View File
@@ -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) => {
+6 -8
View File
@@ -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) ──────────────────────────────────────────
/**
@@ -1402,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
@@ -1415,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> {
@@ -1473,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,
-57
View File
@@ -42,7 +42,6 @@ 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() {
@@ -51,7 +50,6 @@ function resetMock() {
selectWaitlistRows = [];
selectPetRows = [];
selectStaffRows = [];
selectServiceRows = [];
updatedValues = [];
}
@@ -85,7 +83,6 @@ vi.mock("@groombook/db", () => {
const waitlistEntries = mkTable("waitlistEntries");
const pets = mkTable("pets");
const staff = mkTable("staff");
const services = mkTable("services");
return {
getDb: () => ({
@@ -106,9 +103,6 @@ vi.mock("@groombook/db", () => {
if (table._name === "staff") {
return makeChainable(selectStaffRows);
}
if (table._name === "services") {
return makeChainable(selectServiceRows);
}
return makeChainable([]);
},
}),
@@ -132,7 +126,6 @@ vi.mock("@groombook/db", () => {
waitlistEntries,
pets,
staff,
services,
eq: vi.fn(),
and: vi.fn(),
inArray: vi.fn(),
@@ -205,56 +198,6 @@ describe("GET /portal/appointments (waitlist surfacing — GRO-2319)", () => {
});
});
// 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;
-201
View File
@@ -1,201 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Hono } from "hono";
import { getAuth } from "../lib/auth.js";
const NEW_USER_EMAIL = "new-sso-user@example.com";
const NEW_USER_NAME = "New SSO User";
const NEW_USER_ID = "11111111-2222-3333-4444-555555555555";
const BETTER_AUTH_SESSION = {
user: {
id: "auth-user-new",
email: NEW_USER_EMAIL,
name: NEW_USER_NAME,
},
session: {
id: "ba-session-new",
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
},
};
let mockGetAuth: ReturnType<typeof vi.fn>;
let mockGetSession: ReturnType<typeof vi.fn>;
let existingClientRow: Record<string, unknown> | null = null;
let insertedClientValues: Record<string, unknown> | null = null;
let insertShouldThrow: { code?: string } | null = null;
function makeChainable(data: unknown[]): unknown {
const arr = [...data];
return new Proxy(arr, {
get(target, prop) {
if (prop === "where" || prop === "orderBy" || prop === "limit") {
return () => makeChainable(target);
}
// @ts-expect-error proxy
return target[prop];
},
});
}
vi.mock("@groombook/db", () => {
const clients = new Proxy(
{ _name: "clients" },
{ get: (t, p) => (p === "_name" ? "clients" : { table: "clients", column: p }) }
);
return {
getDb: () => ({
select: () => ({
from: (table: { _name: string }) => {
if (table._name === "clients") {
return makeChainable(existingClientRow ? [existingClientRow] : []);
}
return makeChainable([]);
},
}),
insert: (table: { _name: string }) => ({
values: (vals: Record<string, unknown>) => {
if (insertShouldThrow) {
const err = new Error("unique violation") as Error & { code?: string };
err.code = insertShouldThrow.code;
throw err;
}
return {
returning: () => {
if (table._name === "clients") {
insertedClientValues = { id: NEW_USER_ID, ...vals };
return [insertedClientValues];
}
return [];
},
};
},
}),
}),
clients,
eq: vi.fn(),
and: vi.fn(),
inArray: vi.fn(),
};
});
vi.mock("../lib/auth.js", () => ({
getAuth: vi.fn(),
}));
const { portalRouter } = await import("../routes/portal.js");
const app = new Hono();
app.route("/portal", portalRouter);
describe("POST /portal/clients-from-auth (GRO-2359)", () => {
beforeEach(() => {
existingClientRow = null;
insertedClientValues = null;
insertShouldThrow = null;
mockGetSession = vi.fn();
mockGetAuth = vi.fn(() => ({
api: {
getSession: mockGetSession,
},
}));
vi.mocked(getAuth).mockImplementation(mockGetAuth);
});
it("returns 401 when no Better Auth session is present", async () => {
mockGetSession.mockResolvedValue(null);
const res = await app.request("/portal/clients-from-auth", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Test User" }),
});
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error).toBe("Unauthorized");
});
it("returns 400 when body fails zod validation (empty name)", async () => {
mockGetSession.mockResolvedValue(BETTER_AUTH_SESSION);
const res = await app.request("/portal/clients-from-auth", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "" }),
});
expect(res.status).toBe(400);
});
it("creates a new client row bound to the auth user's email and returns 201", async () => {
mockGetSession.mockResolvedValue(BETTER_AUTH_SESSION);
const res = await app.request("/portal/clients-from-auth", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: " New SSO User ",
phone: "555-1234",
address: "1 Main St",
notes: "test note",
}),
});
expect(res.status).toBe(201);
const body = await res.json();
expect(body).toMatchObject({
id: NEW_USER_ID,
name: "New SSO User",
email: NEW_USER_EMAIL,
});
// Trim must be applied to the persisted values.
expect(insertedClientValues).not.toBeNull();
expect((insertedClientValues as Record<string, unknown>).name).toBe("New SSO User");
expect((insertedClientValues as Record<string, unknown>).email).toBe(NEW_USER_EMAIL);
expect((insertedClientValues as Record<string, unknown>).phone).toBe("555-1234");
});
it("normalizes empty optional fields to null on insert", async () => {
mockGetSession.mockResolvedValue(BETTER_AUTH_SESSION);
await app.request("/portal/clients-from-auth", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Test", phone: "", address: " " }),
});
expect(insertedClientValues).not.toBeNull();
expect((insertedClientValues as Record<string, unknown>).phone).toBeNull();
expect((insertedClientValues as Record<string, unknown>).address).toBeNull();
});
it("returns 409 when a client row already exists for this email", async () => {
mockGetSession.mockResolvedValue(BETTER_AUTH_SESSION);
existingClientRow = { id: "existing-client-id", email: NEW_USER_EMAIL };
const res = await app.request("/portal/clients-from-auth", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Test" }),
});
expect(res.status).toBe(409);
const body = await res.json();
expect(body.error).toMatch(/already exists/i);
expect(insertedClientValues).toBeNull();
});
it("returns 409 on unique constraint race (23505)", async () => {
mockGetSession.mockResolvedValue(BETTER_AUTH_SESSION);
insertShouldThrow = { code: "23505" };
const res = await app.request("/portal/clients-from-auth", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Test" }),
});
expect(res.status).toBe(409);
});
it("returns 503 when auth is not configured", async () => {
mockGetAuth.mockImplementation(() => {
throw new Error("Auth not initialized");
});
const res = await app.request("/portal/clients-from-auth", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Test" }),
});
expect(res.status).toBe(503);
});
});
+3 -125
View File
@@ -147,114 +147,6 @@ portalRouter.post("/session-from-auth", async (c) => {
);
});
// GRO-2359 — register a brand-new SSO user. The post-auth handler in the
// web portal redirects here when `session-from-auth` returns 404, so the
// OOBE can complete a customer record for the new user. Auth is via the
// Better Auth session (same shape as `session-from-auth`), so this is
// registered BEFORE the `validatePortalSession` middleware.
//
// Contract:
// POST /api/portal/clients-from-auth
// Body: { name: string; phone?: string|null; address?: string|null; notes?: string|null }
// 201: { id, name, email }
// 400: invalid body (zod failure)
// 401: no Better Auth session
// 409: a `clients` row already exists for this email (portal selection case)
// 500: insert failed
//
// We do NOT auto-link the user's auth account to the new client row; the
// existing `session-from-auth` endpoint re-resolves the row by email on the
// next call, so the OOBE's success path just navigates the user back to
// `/` and lets the bridge mint a portal session.
const createClientFromAuthSchema = z.object({
name: z.string().min(1).max(200),
phone: z.string().max(50).nullish(),
address: z.string().max(500).nullish(),
notes: z.string().max(2000).nullish(),
});
portalRouter.post(
"/clients-from-auth",
zValidator("json", createClientFromAuthSchema),
async (c) => {
let auth;
try {
auth = getAuth();
} catch {
return c.json({ error: "Authentication not configured" }, 503);
}
const session = await auth.api.getSession({
headers: c.req.raw.headers,
});
if (!session) {
return c.json({ error: "Unauthorized" }, 401);
}
const body = c.req.valid("json");
const db = getDb();
// Pre-check: if a client already exists for this email, return 409 so
// the OOBE can render the "portal selection" message (the user needs
// to contact their groomer to link the new SSO identity to the
// pre-existing customer record). We don't return the existing row to
// avoid leaking PII about other accounts.
const [existing] = await db
.select({ id: clients.id })
.from(clients)
.where(eq(clients.email, session.user.email))
.limit(1);
if (existing) {
return c.json(
{ error: "A customer record with this email already exists" },
409,
);
}
let row;
try {
[row] = await db
.insert(clients)
.values({
name: body.name.trim(),
email: session.user.email,
phone: body.phone?.trim() || null,
address: body.address?.trim() || null,
notes: body.notes?.trim() || null,
})
.returning();
} catch (err) {
// Concurrent insert from a parallel OOBE submit — treat as 409.
if (
err instanceof Error &&
"code" in err &&
(err as { code?: string }).code === "23505"
) {
return c.json(
{ error: "A customer record with this email already exists" },
409,
);
}
throw err;
}
if (!row) {
return c.json({ error: "Failed to create client" }, 500);
}
return c.json(
{
id: row.id,
name: row.name,
email: row.email,
},
201,
);
},
);
// Apply middleware to all portal routes
portalRouter.use("/*", validatePortalSession, portalAudit);
@@ -327,22 +219,12 @@ portalRouter.get("/appointments", async (c) => {
...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,
@@ -353,17 +235,13 @@ 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, name: serviceMap[a.serviceId]?.name } : null,
service: a.serviceId ? { id: a.serviceId } : null,
staff: a.staffId ? { id: staffMap[a.staffId]?.id, name: staffMap[a.staffId]?.name } : null,
}));
// 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.
// yields a null startTime, which the portal tolerates).
const waitlistAppts = waitlistRows.map(w => {
const parsed = new Date(`${w.preferredDate}T${w.preferredTime}`);
const startTime = Number.isNaN(parsed.getTime()) ? null : parsed;
@@ -376,7 +254,7 @@ portalRouter.get("/appointments", async (c) => {
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,
service: { id: w.serviceId },
staff: null,
};
});
View File