Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cca83b18cf | |||
| 59cc1742cc | |||
| b486c44a82 | |||
| b5a08a2c7e | |||
| 06d72b5baf | |||
| 33aa63b10f | |||
| e26d960046 | |||
| 4e8c66f3ca | |||
| ea28095434 | |||
| 3b9c72c2c4 | |||
| 49f70eb74b | |||
| 62dfc7776b | |||
| 68df697cf3 | |||
| 174d1c667b | |||
| 9fe6e15012 | |||
| 002e6575ba | |||
| f9c679b392 | |||
| ce0739b3ba | |||
| 3609087980 | |||
| 7b2b533c16 | |||
| 55894c6ff2 | |||
| f55c74983f | |||
| 8bdab69288 | |||
| 8f7104c3a0 | |||
| dab9bfab71 | |||
| 70bc946a0d | |||
| 40422a14f0 | |||
| 9462915a66 | |||
| 46f134a294 | |||
| 4086b6f5c0 | |||
| d7d98791c7 | |||
| 3bec5d095a | |||
| 3fddf80fac | |||
| 1ea319e122 | |||
| da913d600f | |||
| ce9fcfb362 | |||
| 59893908e2 | |||
| 2b78fcf731 | |||
| c9e176f08c | |||
| 0cab1522cf | |||
| 2a27e8bee2 | |||
| d6f7ade7bd | |||
| 00dadac0a1 | |||
| 9692476202 | |||
| 9f2809e89b |
+52
-6
@@ -25,17 +25,17 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 20
|
node-version: 22
|
||||||
cache: pnpm
|
cache: pnpm
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pnpm install --frozen-lockfile
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
- name: Typecheck
|
- name: Typecheck
|
||||||
run: pnpm typecheck
|
run: pnpm --filter @groombook/api typecheck
|
||||||
|
|
||||||
- name: Lint
|
- name: Lint
|
||||||
run: pnpm lint
|
run: pnpm --filter @groombook/api lint
|
||||||
|
|
||||||
test:
|
test:
|
||||||
name: Test
|
name: Test
|
||||||
@@ -49,17 +49,17 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 20
|
node-version: 22
|
||||||
cache: pnpm
|
cache: pnpm
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pnpm install --frozen-lockfile
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: pnpm test
|
run: pnpm --filter @groombook/api test
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
name: Build & Push Docker Image
|
name: Build & Push Docker Images
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [lint-typecheck, test]
|
needs: [lint-typecheck, test]
|
||||||
steps:
|
steps:
|
||||||
@@ -78,6 +78,8 @@ jobs:
|
|||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
|
with:
|
||||||
|
driver-opts: network=host
|
||||||
|
|
||||||
- name: Log in to Gitea Container Registry
|
- name: Log in to Gitea Container Registry
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
@@ -91,9 +93,53 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: Dockerfile
|
file: Dockerfile
|
||||||
|
target: runner
|
||||||
push: true
|
push: true
|
||||||
|
provenance: false
|
||||||
tags: |
|
tags: |
|
||||||
git.farh.net/groombook/api:${{ steps.version.outputs.tag }}
|
git.farh.net/groombook/api:${{ steps.version.outputs.tag }}
|
||||||
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/api:latest' || '' }}
|
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/api:latest' || '' }}
|
||||||
cache-from: type=registry,ref=git.farh.net/groombook/cache:api
|
cache-from: type=registry,ref=git.farh.net/groombook/cache:api
|
||||||
cache-to: type=registry,ref=git.farh.net/groombook/cache:api,mode=max
|
cache-to: type=registry,ref=git.farh.net/groombook/cache:api,mode=max
|
||||||
|
|
||||||
|
- name: Build and push Migrate image
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: Dockerfile
|
||||||
|
target: migrate
|
||||||
|
push: true
|
||||||
|
provenance: false
|
||||||
|
tags: |
|
||||||
|
git.farh.net/groombook/migrate:${{ steps.version.outputs.tag }}
|
||||||
|
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/migrate:latest' || '' }}
|
||||||
|
cache-from: type=registry,ref=git.farh.net/groombook/cache:migrate
|
||||||
|
cache-to: type=registry,ref=git.farh.net/groombook/cache:migrate,mode=max
|
||||||
|
|
||||||
|
- name: Build and push Seed image
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: Dockerfile
|
||||||
|
target: seed
|
||||||
|
push: true
|
||||||
|
provenance: false
|
||||||
|
tags: |
|
||||||
|
git.farh.net/groombook/seed:${{ steps.version.outputs.tag }}
|
||||||
|
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/seed:latest' || '' }}
|
||||||
|
cache-from: type=registry,ref=git.farh.net/groombook/cache:seed
|
||||||
|
cache-to: type=registry,ref=git.farh.net/groombook/cache:seed,mode=max
|
||||||
|
|
||||||
|
- name: Build and push Reset image
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: Dockerfile
|
||||||
|
target: reset
|
||||||
|
push: true
|
||||||
|
provenance: false
|
||||||
|
tags: |
|
||||||
|
git.farh.net/groombook/reset:${{ steps.version.outputs.tag }}
|
||||||
|
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/reset:latest' || '' }}
|
||||||
|
cache-from: type=registry,ref=git.farh.net/groombook/cache:reset
|
||||||
|
cache-to: type=registry,ref=git.farh.net/groombook/cache:reset,mode=max
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 20
|
node-version: 22
|
||||||
cache: pnpm
|
cache: pnpm
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
@@ -49,7 +49,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 20
|
node-version: 22
|
||||||
cache: pnpm
|
cache: pnpm
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
@@ -71,7 +71,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 20
|
node-version: 22
|
||||||
cache: pnpm
|
cache: pnpm
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
|
|||||||
+6
-6
@@ -1,4 +1,4 @@
|
|||||||
FROM node:20-alpine AS base
|
FROM node:22-alpine AS base
|
||||||
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
|
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -17,10 +17,10 @@ COPY src/ src/
|
|||||||
COPY tsconfig.json ./
|
COPY tsconfig.json ./
|
||||||
RUN pnpm --filter @groombook/types build && \
|
RUN pnpm --filter @groombook/types build && \
|
||||||
pnpm --filter @groombook/db build && \
|
pnpm --filter @groombook/db build && \
|
||||||
pnpm --filter @groombook/api build
|
pnpm build
|
||||||
|
|
||||||
# Runtime
|
# Runtime
|
||||||
FROM node:20-alpine AS runner
|
FROM node:22-alpine AS runner
|
||||||
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
|
RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
@@ -42,12 +42,12 @@ CMD ["node", "dist/index.js"]
|
|||||||
|
|
||||||
# Migrate stage — runs drizzle-kit migrate against the database
|
# Migrate stage — runs drizzle-kit migrate against the database
|
||||||
FROM builder AS migrate
|
FROM builder AS migrate
|
||||||
CMD ["pnpm", "db:migrate"]
|
CMD ["pnpm", "--filter", "@groombook/db", "migrate"]
|
||||||
|
|
||||||
# Seed stage — populates the database with test data
|
# Seed stage — populates the database with test data
|
||||||
FROM builder AS seed
|
FROM builder AS seed
|
||||||
CMD ["pnpm", "db:seed"]
|
CMD ["pnpm", "--filter", "@groombook/db", "seed"]
|
||||||
|
|
||||||
# Reset stage — drops all tables, re-runs migrations, and re-seeds
|
# Reset stage — drops all tables, re-runs migrations, and re-seeds
|
||||||
FROM builder AS reset
|
FROM builder AS reset
|
||||||
CMD ["pnpm", "db:reset"]
|
CMD ["pnpm", "--filter", "@groombook/db", "reset"]
|
||||||
|
|||||||
@@ -21,6 +21,14 @@ GroomBook API is a Hono-based REST service (TypeScript/Node.js) powering the pet
|
|||||||
|
|
||||||
## Test Cases
|
## Test Cases
|
||||||
|
|
||||||
|
### 4.0 Health Check
|
||||||
|
|
||||||
|
| # | Scenario | Steps | Expected |
|
||||||
|
|---|----------|-------|----------|
|
||||||
|
| TC-API-0.1 | Unauthenticated health check | GET /api/health | 200 OK, `{"status":"ok"}` |
|
||||||
|
|
||||||
|
> **Note (GRO-1544):** Health endpoint registered on `api` basePath before auth middleware at `/api/health`. The old path `/health` was incorrect (routed to web pod via HTTPRoute `/*` rule).
|
||||||
|
|
||||||
### 4.1 Authentication
|
### 4.1 Authentication
|
||||||
|
|
||||||
| # | Scenario | Steps | Expected |
|
| # | Scenario | Steps | Expected |
|
||||||
@@ -38,6 +46,7 @@ GroomBook API is a Hono-based REST service (TypeScript/Node.js) powering the pet
|
|||||||
| TC-API-1.13 | Name fallback — user.name present | Auto-provision where Better-Auth user has name set | Staff name = user.name value from user table |
|
| TC-API-1.13 | Name fallback — user.name present | Auto-provision where Better-Auth user has name set | Staff name = user.name value from user table |
|
||||||
| TC-API-1.14 | Name fallback — no name, email present | Auto-provision where Better-Auth user has name = null, email = "test@example.com" | Staff name = "test" (email prefix before @) |
|
| TC-API-1.14 | Name fallback — no name, email present | Auto-provision where Better-Auth user has name = null, email = "test@example.com" | Staff name = "test" (email prefix before @) |
|
||||||
| TC-API-1.15 | Name fallback — no name, no email | Auto-provision where Better-Auth user has name = null, email = null | Staff name = "Unknown" |
|
| TC-API-1.15 | Name fallback — no name, no email | Auto-provision where Better-Auth user has name = null, email = null | Staff name = "Unknown" |
|
||||||
|
| TC-API-1.16 | OIDC login — Terraform-provisioned user | Initiate OIDC login as any UAT persona (uat-super, uat-groomer, uat-customer, uat-tester), complete authentik callback | 200 OK, session created — no account_not_linked error |
|
||||||
|
|
||||||
### 4.2 Client Management
|
### 4.2 Client Management
|
||||||
|
|
||||||
@@ -130,6 +139,9 @@ GroomBook API is a Hono-based REST service (TypeScript/Node.js) powering the pet
|
|||||||
| TC-API-8.5 | Add waitlist entry | POST /api/portal/waitlist with pet and service | 201 Created, waitlist entry created |
|
| TC-API-8.5 | Add waitlist entry | POST /api/portal/waitlist with pet and service | 201 Created, waitlist entry created |
|
||||||
| TC-API-8.6 | View portal invoices | GET /api/portal/invoices | 200 OK, list of client's invoices returned |
|
| TC-API-8.6 | View portal invoices | GET /api/portal/invoices | 200 OK, list of client's invoices returned |
|
||||||
| TC-API-8.7 | Pay multiple invoices | POST /api/portal/invoices/pay-multiple with invoice IDs | 200 OK, payment intent created |
|
| TC-API-8.7 | Pay multiple invoices | POST /api/portal/invoices/pay-multiple with invoice IDs | 200 OK, payment intent created |
|
||||||
|
| TC-API-8.8 | Update pet profile | PATCH /api/portal/pets/{id} with name, breed, groomingNotes | 200 OK, pet updated in portal shape |
|
||||||
|
| TC-API-8.9 | Update pet — ownership check | PATCH /api/portal/pets/{id} with session for different client | 403 Forbidden, pet belongs to another client |
|
||||||
|
| TC-API-8.10 | Update pet — not found | PATCH /api/portal/pets/{nonexistent-id} | 404 Not Found |
|
||||||
|
|
||||||
### 4.9 Waitlist
|
### 4.9 Waitlist
|
||||||
|
|
||||||
|
|||||||
@@ -135,7 +135,7 @@ function makeDeleteChainable(): unknown {
|
|||||||
}
|
}
|
||||||
if (prop === "returning") {
|
if (prop === "returning") {
|
||||||
return () => {
|
return () => {
|
||||||
const row = petRows[0];
|
const row = petRows[0]!;
|
||||||
deletedId = row.id as string;
|
deletedId = row.id as string;
|
||||||
return [row];
|
return [row];
|
||||||
};
|
};
|
||||||
@@ -165,10 +165,10 @@ vi.mock("../db", async (importOriginal) => {
|
|||||||
}),
|
}),
|
||||||
pets,
|
pets,
|
||||||
appointments,
|
appointments,
|
||||||
and: db.and,
|
and: vi.fn(),
|
||||||
eq: db.eq,
|
eq: vi.fn(),
|
||||||
exists: db.exists,
|
exists: vi.fn(),
|
||||||
or: db.or,
|
or: vi.fn(),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -67,6 +67,11 @@ vi.mock("../db", () => {
|
|||||||
{ get: (t, p) => (p === "_name" ? "impersonationSessions" : { table: "impersonationSessions", column: p }) }
|
{ get: (t, p) => (p === "_name" ? "impersonationSessions" : { table: "impersonationSessions", column: p }) }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const impersonationAuditLogs = new Proxy(
|
||||||
|
{ _name: "impersonationAuditLogs" },
|
||||||
|
{ get: (t, p) => (p === "_name" ? "impersonationAuditLogs" : { table: "impersonationAuditLogs", column: p }) }
|
||||||
|
);
|
||||||
|
|
||||||
const appointments = new Proxy(
|
const appointments = new Proxy(
|
||||||
{ _name: "appointments" },
|
{ _name: "appointments" },
|
||||||
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
|
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
|
||||||
@@ -99,8 +104,12 @@ vi.mock("../db", () => {
|
|||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
|
insert: () => ({
|
||||||
|
values: () => ({ returning: () => [{}] }),
|
||||||
|
}),
|
||||||
}),
|
}),
|
||||||
impersonationSessions,
|
impersonationSessions,
|
||||||
|
impersonationAuditLogs,
|
||||||
appointments,
|
appointments,
|
||||||
eq: vi.fn(),
|
eq: vi.fn(),
|
||||||
and: vi.fn(),
|
and: vi.fn(),
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
"version": "0.0.1",
|
"version": "0.0.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
"packageManager": "pnpm@9.15.4",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "tsx watch src/index.ts",
|
"dev": "tsx watch src/index.ts",
|
||||||
"build": "tsc --project .",
|
"build": "tsc --project .",
|
||||||
|
|||||||
@@ -6,8 +6,10 @@
|
|||||||
CREATE TYPE "pet_size_category" AS ENUM ('small', 'medium', 'large', 'xlarge');
|
CREATE TYPE "pet_size_category" AS ENUM ('small', 'medium', 'large', 'xlarge');
|
||||||
CREATE TYPE "coat_type" AS ENUM ('smooth', 'double', 'wire', 'curly', 'long', 'hairless');
|
CREATE TYPE "coat_type" AS ENUM ('smooth', 'double', 'wire', 'curly', 'long', 'hairless');
|
||||||
|
|
||||||
-- ─── Alter pets columns to use new enums ─────────────────────────────────────
|
-- ─── Add columns to pets if missing, then cast to enums ──────────────────────
|
||||||
|
|
||||||
|
ALTER TABLE "pets" ADD COLUMN IF NOT EXISTS "coat_type" text;
|
||||||
|
ALTER TABLE "pets" ADD COLUMN IF NOT EXISTS "pet_size_category" text;
|
||||||
ALTER TABLE "pets" ALTER COLUMN "coat_type" TYPE "coat_type" USING "coat_type"::text::"coat_type";
|
ALTER TABLE "pets" ALTER COLUMN "coat_type" TYPE "coat_type" USING "coat_type"::text::"coat_type";
|
||||||
ALTER TABLE "pets" ALTER COLUMN "pet_size_category" TYPE "pet_size_category" USING "pet_size_category"::text::"pet_size_category";
|
ALTER TABLE "pets" ALTER COLUMN "pet_size_category" TYPE "pet_size_category" USING "pet_size_category"::text::"pet_size_category";
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
-- no-op: journal entry exists but no schema change was needed
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-- Migration: 0033_add_services_default_buffer_minutes.sql
|
||||||
|
-- Adds missing default_buffer_minutes column to services table.
|
||||||
|
-- 0031_buffer_rules was applied to the DB but its journal entry was missing,
|
||||||
|
-- so this ensures idempotent column addition for fresh DB restores.
|
||||||
|
|
||||||
|
ALTER TABLE "services" ADD COLUMN IF NOT EXISTS "default_buffer_minutes" integer DEFAULT 0 NOT NULL;
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
{
|
||||||
|
"id": "0033_add_services_default_buffer_minutes",
|
||||||
|
"version": "7",
|
||||||
|
"dialect": "postgresql",
|
||||||
|
"tables": {
|
||||||
|
"authProviderConfig": {
|
||||||
|
"name": "auth_provider_config",
|
||||||
|
"columns": {
|
||||||
|
"id": { "name": "id", "type": "uuid", "primaryKey": true, "default": "gen_random_uuid()", "isNullable": false },
|
||||||
|
"providerId": { "name": "provider_id", "type": "text", "isNullable": false },
|
||||||
|
"displayName": { "name": "display_name", "type": "text", "isNullable": false },
|
||||||
|
"issuerUrl": { "name": "issuer_url", "type": "text", "isNullable": false },
|
||||||
|
"internalBaseUrl": { "name": "internal_base_url", "type": "text", "isNullable": true },
|
||||||
|
"clientId": { "name": "client_id", "type": "text", "isNullable": false },
|
||||||
|
"clientSecret": { "name": "client_secret", "type": "text", "isNullable": false },
|
||||||
|
"scopes": { "name": "scopes", "type": "text", "isNullable": false, "default": "'openid profile email'" },
|
||||||
|
"enabled": { "name": "enabled", "type": "boolean", "isNullable": false, "default": "true" },
|
||||||
|
"createdAt": { "name": "created_at", "type": "timestamp", "isNullable": false, "default": "now()" },
|
||||||
|
"updatedAt": { "name": "updated_at", "type": "timestamp", "isNullable": false, "default": "now()" }
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {}
|
||||||
|
},
|
||||||
|
"businessSettings": {
|
||||||
|
"name": "business_settings",
|
||||||
|
"columns": {
|
||||||
|
"id": { "name": "id", "type": "uuid", "primaryKey": true, "default": "gen_random_uuid()", "isNullable": false },
|
||||||
|
"businessName": { "name": "business_name", "type": "text", "isNullable": false, "default": "'GroomBook'" },
|
||||||
|
"logoBase64": { "name": "logo_base64", "type": "text", "isNullable": true },
|
||||||
|
"logoMimeType": { "name": "logo_mime_type", "type": "text", "isNullable": true },
|
||||||
|
"logoKey": { "name": "logo_key", "type": "text", "isNullable": true },
|
||||||
|
"primaryColor": { "name": "primary_color", "type": "text", "isNullable": false, "default": "'#4f8a6f'" },
|
||||||
|
"accentColor": { "name": "accent_color", "type": "text", "isNullable": false, "default": "'#8b7355'" },
|
||||||
|
"createdAt": { "name": "created_at", "type": "timestamp", "isNullable": false, "default": "now()" },
|
||||||
|
"updatedAt": { "name": "updated_at", "type": "timestamp", "isNullable": false, "default": "now()" }
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {}
|
||||||
|
},
|
||||||
|
"clients": {
|
||||||
|
"name": "clients",
|
||||||
|
"columns": {
|
||||||
|
"id": { "name": "id", "type": "uuid", "primaryKey": true, "default": "gen_random_uuid()", "isNullable": false },
|
||||||
|
"name": { "name": "name", "type": "text", "isNullable": false },
|
||||||
|
"email": { "name": "email", "type": "text", "isNullable": true },
|
||||||
|
"phone": { "name": "phone", "type": "text", "isNullable": true },
|
||||||
|
"address": { "name": "address", "type": "text", "isNullable": true },
|
||||||
|
"notes": { "name": "notes", "type": "text", "isNullable": true },
|
||||||
|
"emailOptOut": { "name": "email_opt_out", "type": "boolean", "isNullable": false, "default": "false" },
|
||||||
|
"smsOptIn": { "name": "sms_opt_in", "type": "boolean", "isNullable": false, "default": "false" },
|
||||||
|
"smsConsentDate": { "name": "sms_consent_date", "type": "timestamp", "isNullable": true },
|
||||||
|
"smsOptOutDate": { "name": "sms_opt_out_date", "type": "timestamp", "isNullable": true },
|
||||||
|
"smsConsentText": { "name": "sms_consent_text", "type": "text", "isNullable": true },
|
||||||
|
"stripeCustomerId": { "name": "stripe_customer_id", "type": "text", "isNullable": true },
|
||||||
|
"status": { "name": "status", "type": "client_status", "isNullable": false, "default": "'active'" },
|
||||||
|
"disabledAt": { "name": "disabled_at", "type": "timestamp", "isNullable": true },
|
||||||
|
"createdAt": { "name": "created_at", "type": "timestamp", "isNullable": false, "default": "now()" },
|
||||||
|
"updatedAt": { "name": "updated_at", "type": "timestamp", "isNullable": false, "default": "now()" }
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": { "idx_clients_stripe_customer_id": { "columns": ["stripe_customer_id"] } }
|
||||||
|
},
|
||||||
|
"invoices": {
|
||||||
|
"name": "invoices",
|
||||||
|
"columns": {
|
||||||
|
"id": { "name": "id", "type": "uuid", "primaryKey": true, "default": "gen_random_uuid()", "isNullable": false },
|
||||||
|
"appointmentId": { "name": "appointment_id", "type": "uuid", "isNullable": true },
|
||||||
|
"clientId": { "name": "client_id", "type": "uuid", "isNullable": false },
|
||||||
|
"subtotalCents": { "name": "subtotal_cents", "type": "integer", "isNullable": false },
|
||||||
|
"taxCents": { "name": "tax_cents", "type": "integer", "isNullable": false, "default": "0" },
|
||||||
|
"tipCents": { "name": "tip_cents", "type": "integer", "isNullable": false, "default": "0" },
|
||||||
|
"totalCents": { "name": "total_cents", "type": "integer", "isNullable": false },
|
||||||
|
"status": { "name": "status", "type": "invoice_status", "isNullable": false, "default": "'draft'" },
|
||||||
|
"paymentMethod": { "name": "payment_method", "type": "payment_method", "isNullable": true },
|
||||||
|
"paidAt": { "name": "paid_at", "type": "timestamp", "isNullable": true },
|
||||||
|
"stripePaymentIntentId": { "name": "stripe_payment_intent_id", "type": "text", "isNullable": true },
|
||||||
|
"stripeRefundId": { "name": "stripe_refund_id", "type": "text", "isNullable": true },
|
||||||
|
"paymentFailureReason": { "name": "payment_failure_reason", "type": "text", "isNullable": true },
|
||||||
|
"notes": { "name": "notes", "type": "text", "isNullable": true },
|
||||||
|
"createdAt": { "name": "created_at", "type": "timestamp", "isNullable": false, "default": "now()" },
|
||||||
|
"updatedAt": { "name": "updated_at", "type": "timestamp", "isNullable": false, "default": "now()" }
|
||||||
|
},
|
||||||
|
"indexes": { "idx_invoices_client_id": { "columns": ["client_id"] }, "idx_invoices_status": { "columns": ["status"] }, "idx_invoices_created_at": { "columns": ["created_at"] } },
|
||||||
|
"foreignKeys": { "invoices_appointment_id_fkey": { "columns": ["appointmentId"], "reference": { "table": "appointments", "columns": ["id"] } }, "invoices_client_id_fkey": { "columns": ["clientId"], "reference": { "table": "clients", "columns": ["id"] } } },
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": { "idx_invoices_stripe_payment_intent_id": { "columns": ["stripe_payment_intent_id"] } }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"enums": {
|
||||||
|
"appointment_status": { "name": "appointment_status", "values": ["scheduled", "confirmed", "in_progress", "completed", "cancelled", "no_show"] },
|
||||||
|
"client_status": { "name": "client_status", "values": ["active", "disabled"] },
|
||||||
|
"impersonation_session_status": { "name": "impersonation_session_status", "values": ["active", "ended", "expired"] },
|
||||||
|
"invoice_status": { "name": "invoice_status", "values": ["draft", "pending", "paid", "void"] },
|
||||||
|
"payment_method": { "name": "payment_method", "values": ["cash", "card", "check", "other"] },
|
||||||
|
"staff_role": { "name": "staff_role", "values": ["groomer", "receptionist", "manager"] },
|
||||||
|
"waitlist_status": { "name": "waitlist_status", "values": ["active", "notified", "expired", "cancelled"] }
|
||||||
|
},
|
||||||
|
"nativeEnums": {}
|
||||||
|
}
|
||||||
@@ -218,6 +218,27 @@
|
|||||||
"when": 1775828067192,
|
"when": 1775828067192,
|
||||||
"tag": "0030_messaging",
|
"tag": "0030_messaging",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 31,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1775860800000,
|
||||||
|
"tag": "0031_buffer_rules",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 32,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1775894400000,
|
||||||
|
"tag": "0032_staff_read_at",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 33,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1779500000000,
|
||||||
|
"tag": "0033_add_services_default_buffer_minutes",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -105,8 +105,6 @@ export function buildPet(overrides: Partial<PetRow> & { clientId: string }): Pet
|
|||||||
photoKey: null,
|
photoKey: null,
|
||||||
photoUploadedAt: null,
|
photoUploadedAt: null,
|
||||||
image: null,
|
image: null,
|
||||||
coatType: null,
|
|
||||||
petSizeCategory: null,
|
|
||||||
createdAt: new Date("2025-01-01T00:00:00Z"),
|
createdAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
};
|
};
|
||||||
@@ -121,7 +119,7 @@ export function buildService(overrides: Partial<ServiceRow> = {}): ServiceRow {
|
|||||||
description: "A grooming service",
|
description: "A grooming service",
|
||||||
basePriceCents: 6500,
|
basePriceCents: 6500,
|
||||||
durationMinutes: 60,
|
durationMinutes: 60,
|
||||||
defaultBufferMinutes: null,
|
defaultBufferMinutes: 0,
|
||||||
active: true,
|
active: true,
|
||||||
createdAt: new Date("2025-01-01T00:00:00Z"),
|
createdAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export function getDb() {
|
|||||||
if (_db) return _db;
|
if (_db) return _db;
|
||||||
const url = process.env.DATABASE_URL;
|
const url = process.env.DATABASE_URL;
|
||||||
if (!url) throw new Error("DATABASE_URL is not set");
|
if (!url) throw new Error("DATABASE_URL is not set");
|
||||||
const client = postgres(url, { max: 10 });
|
const client = postgres(url, { max: 10, connect_timeout: 5 });
|
||||||
_db = drizzle(client, { schema });
|
_db = drizzle(client, { schema });
|
||||||
return _db;
|
return _db;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,22 +48,6 @@ export const clientStatusEnum = pgEnum("client_status", [
|
|||||||
"disabled",
|
"disabled",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export const petSizeCategoryEnum = pgEnum("pet_size_category", [
|
|
||||||
"small",
|
|
||||||
"medium",
|
|
||||||
"large",
|
|
||||||
"xlarge",
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const coatTypeEnum = pgEnum("coat_type", [
|
|
||||||
"smooth",
|
|
||||||
"double",
|
|
||||||
"wire",
|
|
||||||
"curly",
|
|
||||||
"long",
|
|
||||||
"hairless",
|
|
||||||
]);
|
|
||||||
|
|
||||||
// ─── Better-Auth Tables ──────────────────────────────────────────────────────
|
// ─── Better-Auth Tables ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const user = pgTable("user", {
|
export const user = pgTable("user", {
|
||||||
@@ -196,35 +180,12 @@ export const services = pgTable("services", {
|
|||||||
description: text("description"),
|
description: text("description"),
|
||||||
basePriceCents: integer("base_price_cents").notNull(),
|
basePriceCents: integer("base_price_cents").notNull(),
|
||||||
durationMinutes: integer("duration_minutes").notNull(),
|
durationMinutes: integer("duration_minutes").notNull(),
|
||||||
defaultBufferMinutes: integer("default_buffer_minutes"),
|
|
||||||
active: boolean("active").notNull().default(true),
|
active: boolean("active").notNull().default(true),
|
||||||
defaultBufferMinutes: integer("default_buffer_minutes").notNull().default(0),
|
defaultBufferMinutes: integer("default_buffer_minutes").notNull().default(0),
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const bufferRules = pgTable(
|
|
||||||
"buffer_rules",
|
|
||||||
{
|
|
||||||
id: uuid("id").primaryKey().defaultRandom(),
|
|
||||||
serviceId: uuid("service_id")
|
|
||||||
.notNull()
|
|
||||||
.references(() => services.id, { onDelete: "cascade" }),
|
|
||||||
sizeCategory: petSizeCategoryEnum("size_category"),
|
|
||||||
coatType: coatTypeEnum("coat_type"),
|
|
||||||
bufferMinutes: integer("buffer_minutes").notNull(),
|
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
|
||||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
|
||||||
},
|
|
||||||
(t) => [
|
|
||||||
unique("uq_buffer_rules_service_size_coat").on(
|
|
||||||
t.serviceId,
|
|
||||||
t.sizeCategory,
|
|
||||||
t.coatType
|
|
||||||
),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
export const staff = pgTable("staff", {
|
export const staff = pgTable("staff", {
|
||||||
id: uuid("id").primaryKey().defaultRandom(),
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
name: text("name").notNull(),
|
name: text("name").notNull(),
|
||||||
|
|||||||
Generated
+6
-2
@@ -28,7 +28,7 @@ importers:
|
|||||||
version: 0.7.6(hono@4.12.18)(zod@4.4.3)
|
version: 0.7.6(hono@4.12.18)(zod@4.4.3)
|
||||||
better-auth:
|
better-auth:
|
||||||
specifier: ^1.5.6
|
specifier: ^1.5.6
|
||||||
version: 1.6.10(drizzle-orm@0.38.4(kysely@0.28.17)(postgres@3.4.9))(vitest@3.2.4(@types/node@22.19.18)(tsx@4.21.0))
|
version: 1.6.10(drizzle-kit@0.30.6)(drizzle-orm@0.38.4(kysely@0.28.17)(postgres@3.4.9))(vitest@3.2.4(@types/node@22.19.18)(tsx@4.21.0))
|
||||||
drizzle-orm:
|
drizzle-orm:
|
||||||
specifier: ^0.38.4
|
specifier: ^0.38.4
|
||||||
version: 0.38.4(kysely@0.28.17)(postgres@3.4.9)
|
version: 0.38.4(kysely@0.28.17)(postgres@3.4.9)
|
||||||
@@ -84,6 +84,9 @@ importers:
|
|||||||
|
|
||||||
packages/db:
|
packages/db:
|
||||||
dependencies:
|
dependencies:
|
||||||
|
better-auth:
|
||||||
|
specifier: ^1.5.6
|
||||||
|
version: 1.6.10(drizzle-kit@0.30.6)(drizzle-orm@0.38.4(kysely@0.28.17)(postgres@3.4.9))(vitest@3.2.4(@types/node@22.19.18)(tsx@4.21.0))
|
||||||
drizzle-orm:
|
drizzle-orm:
|
||||||
specifier: ^0.38.4
|
specifier: ^0.38.4
|
||||||
version: 0.38.4(kysely@0.28.17)(postgres@3.4.9)
|
version: 0.38.4(kysely@0.28.17)(postgres@3.4.9)
|
||||||
@@ -3927,7 +3930,7 @@ snapshots:
|
|||||||
|
|
||||||
balanced-match@4.0.4: {}
|
balanced-match@4.0.4: {}
|
||||||
|
|
||||||
better-auth@1.6.10(drizzle-orm@0.38.4(kysely@0.28.17)(postgres@3.4.9))(vitest@3.2.4(@types/node@22.19.18)(tsx@4.21.0)):
|
better-auth@1.6.10(drizzle-kit@0.30.6)(drizzle-orm@0.38.4(kysely@0.28.17)(postgres@3.4.9))(vitest@3.2.4(@types/node@22.19.18)(tsx@4.21.0)):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@better-auth/core': 1.6.10(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(better-call@1.3.5(zod@4.4.3))(jose@6.2.3)(kysely@0.28.17)(nanostores@1.3.0)
|
'@better-auth/core': 1.6.10(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(better-call@1.3.5(zod@4.4.3))(jose@6.2.3)(kysely@0.28.17)(nanostores@1.3.0)
|
||||||
'@better-auth/drizzle-adapter': 1.6.10(@better-auth/core@1.6.10(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(better-call@1.3.5(zod@4.4.3))(jose@6.2.3)(kysely@0.28.17)(nanostores@1.3.0))(@better-auth/utils@0.4.0)(drizzle-orm@0.38.4(kysely@0.28.17)(postgres@3.4.9))
|
'@better-auth/drizzle-adapter': 1.6.10(@better-auth/core@1.6.10(@better-auth/utils@0.4.0)(@better-fetch/fetch@1.1.21)(better-call@1.3.5(zod@4.4.3))(jose@6.2.3)(kysely@0.28.17)(nanostores@1.3.0))(@better-auth/utils@0.4.0)(drizzle-orm@0.38.4(kysely@0.28.17)(postgres@3.4.9))
|
||||||
@@ -3947,6 +3950,7 @@ snapshots:
|
|||||||
nanostores: 1.3.0
|
nanostores: 1.3.0
|
||||||
zod: 4.4.3
|
zod: 4.4.3
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
|
drizzle-kit: 0.30.6
|
||||||
drizzle-orm: 0.38.4(kysely@0.28.17)(postgres@3.4.9)
|
drizzle-orm: 0.38.4(kysely@0.28.17)(postgres@3.4.9)
|
||||||
vitest: 3.2.4(@types/node@22.19.18)(tsx@4.21.0)
|
vitest: 3.2.4(@types/node@22.19.18)(tsx@4.21.0)
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
|
|||||||
+145
-12
@@ -4,6 +4,7 @@ import { Hono } from "hono";
|
|||||||
const CLIENT_ID = "550e8400-e29b-41d4-a716-446655440001";
|
const CLIENT_ID = "550e8400-e29b-41d4-a716-446655440001";
|
||||||
const APPOINTMENT_ID = "660e8400-e29b-41d4-a716-446655440002";
|
const APPOINTMENT_ID = "660e8400-e29b-41d4-a716-446655440002";
|
||||||
const SESSION_ID = "770e8400-e29b-41d4-a716-446655440003";
|
const SESSION_ID = "770e8400-e29b-41d4-a716-446655440003";
|
||||||
|
const PET_ID = "880e8400-e29b-41d4-a716-446655440004";
|
||||||
|
|
||||||
const futureDate = () => new Date(Date.now() + 30 * 60 * 1000);
|
const futureDate = () => new Date(Date.now() + 30 * 60 * 1000);
|
||||||
const pastDate = () => new Date(Date.now() - 5 * 60 * 1000);
|
const pastDate = () => new Date(Date.now() - 5 * 60 * 1000);
|
||||||
@@ -37,13 +38,38 @@ const APPOINTMENT = {
|
|||||||
cancelledAt: null,
|
cancelledAt: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const PET = {
|
||||||
|
id: PET_ID,
|
||||||
|
clientId: CLIENT_ID,
|
||||||
|
name: "Fido",
|
||||||
|
species: "dog",
|
||||||
|
breed: "Labrador",
|
||||||
|
weightKg: "30.00",
|
||||||
|
dateOfBirth: null,
|
||||||
|
healthAlerts: null,
|
||||||
|
groomingNotes: null,
|
||||||
|
cutStyle: null,
|
||||||
|
shampooPreference: null,
|
||||||
|
specialCareNotes: null,
|
||||||
|
coatType: null,
|
||||||
|
petSizeCategory: null,
|
||||||
|
customFields: {},
|
||||||
|
photoKey: null,
|
||||||
|
photoUploadedAt: null,
|
||||||
|
image: null,
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
};
|
||||||
|
|
||||||
let selectSessionRow: Record<string, unknown> | null = null;
|
let selectSessionRow: Record<string, unknown> | null = null;
|
||||||
let selectAppointmentRow: Record<string, unknown> | null = null;
|
let selectAppointmentRow: Record<string, unknown> | null = null;
|
||||||
|
let selectPetRow: Record<string, unknown> | null = null;
|
||||||
let updatedValues: Record<string, unknown>[] = [];
|
let updatedValues: Record<string, unknown>[] = [];
|
||||||
|
|
||||||
function resetMock() {
|
function resetMock() {
|
||||||
selectSessionRow = null;
|
selectSessionRow = null;
|
||||||
selectAppointmentRow = null;
|
selectAppointmentRow = null;
|
||||||
|
selectPetRow = null;
|
||||||
updatedValues = [];
|
updatedValues = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,6 +88,8 @@ vi.mock("@groombook/db", () => {
|
|||||||
return chain;
|
return chain;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let activeUpdateTable: string | null = null;
|
||||||
|
|
||||||
const impersonationSessions = new Proxy(
|
const impersonationSessions = new Proxy(
|
||||||
{ _name: "impersonationSessions" },
|
{ _name: "impersonationSessions" },
|
||||||
{ get: (t, p) => (p === "_name" ? "impersonationSessions" : { table: "impersonationSessions", column: p }) }
|
{ get: (t, p) => (p === "_name" ? "impersonationSessions" : { table: "impersonationSessions", column: p }) }
|
||||||
@@ -72,6 +100,16 @@ vi.mock("@groombook/db", () => {
|
|||||||
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
|
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const pets = new Proxy(
|
||||||
|
{ _name: "pets" },
|
||||||
|
{ get: (t, p) => (p === "_name" ? "pets" : { table: "pets", column: p }) }
|
||||||
|
);
|
||||||
|
|
||||||
|
const impersonationAuditLogs = new Proxy(
|
||||||
|
{ _name: "impersonationAuditLogs" },
|
||||||
|
{ get: (t, p) => (p === "_name" ? "impersonationAuditLogs" : { table: "impersonationAuditLogs", column: p }) }
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getDb: () => ({
|
getDb: () => ({
|
||||||
select: () => ({
|
select: () => ({
|
||||||
@@ -82,26 +120,44 @@ vi.mock("@groombook/db", () => {
|
|||||||
if (table._name === "appointments") {
|
if (table._name === "appointments") {
|
||||||
return makeChainable(selectAppointmentRow ? [selectAppointmentRow] : []);
|
return makeChainable(selectAppointmentRow ? [selectAppointmentRow] : []);
|
||||||
}
|
}
|
||||||
|
if (table._name === "pets") {
|
||||||
|
return makeChainable(selectPetRow ? [selectPetRow] : []);
|
||||||
|
}
|
||||||
return makeChainable([]);
|
return makeChainable([]);
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
update: () => ({
|
insert: () => ({
|
||||||
set: (vals: Record<string, unknown>) => ({
|
values: () => ({
|
||||||
where: () => ({
|
returning: () => [{}],
|
||||||
returning: () => {
|
|
||||||
if (selectAppointmentRow) {
|
|
||||||
const updated = { ...selectAppointmentRow, ...vals };
|
|
||||||
updatedValues.push(vals);
|
|
||||||
return [updated];
|
|
||||||
}
|
|
||||||
return [];
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
|
update: (table: { _name: string }) => {
|
||||||
|
activeUpdateTable = table._name;
|
||||||
|
return {
|
||||||
|
set: (vals: Record<string, unknown>) => ({
|
||||||
|
where: () => ({
|
||||||
|
returning: () => {
|
||||||
|
if (activeUpdateTable === "appointments" && selectAppointmentRow) {
|
||||||
|
const updated = { ...selectAppointmentRow, ...vals };
|
||||||
|
updatedValues.push(vals);
|
||||||
|
return [updated];
|
||||||
|
}
|
||||||
|
if (activeUpdateTable === "pets" && selectPetRow) {
|
||||||
|
const updated = { ...selectPetRow, ...vals };
|
||||||
|
updatedValues.push(vals);
|
||||||
|
return [updated];
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
impersonationSessions,
|
impersonationSessions,
|
||||||
appointments,
|
appointments,
|
||||||
|
pets,
|
||||||
|
impersonationAuditLogs,
|
||||||
eq: vi.fn(),
|
eq: vi.fn(),
|
||||||
and: vi.fn(),
|
and: vi.fn(),
|
||||||
};
|
};
|
||||||
@@ -421,3 +477,80 @@ describe("POST /portal/appointments/:id/cancel", () => {
|
|||||||
expect(res.status).toBe(404);
|
expect(res.status).toBe(404);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ─── PATCH /portal/pets/:id ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function jsonPetPatch(path: string, body: unknown, headers?: Record<string, string>) {
|
||||||
|
return app.request(path, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
...headers,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("PATCH /portal/pets/:id", () => {
|
||||||
|
it("updates a pet and returns the updated pet in portal shape", async () => {
|
||||||
|
selectSessionRow = ACTIVE_SESSION;
|
||||||
|
selectPetRow = { ...PET, dateOfBirth: new Date("2020-01-15"), photoKey: "pets/test.jpg" };
|
||||||
|
const res = await jsonPetPatch(
|
||||||
|
`/portal/pets/${PET_ID}`,
|
||||||
|
{ name: "Fido Jr.", groomingNotes: "Needs extra brushing" },
|
||||||
|
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body).toHaveProperty("id");
|
||||||
|
expect(body).toHaveProperty("name", "Fido Jr.");
|
||||||
|
expect(body).toHaveProperty("notes", "Needs extra brushing");
|
||||||
|
expect(body).toHaveProperty("breed");
|
||||||
|
expect(body).toHaveProperty("photoUrl");
|
||||||
|
expect(body).not.toHaveProperty("clientId");
|
||||||
|
expect(body).not.toHaveProperty("customFields");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 401 without X-Impersonation-Session-Id header", async () => {
|
||||||
|
const res = await jsonPetPatch(`/portal/pets/${PET_ID}`, { name: "Test" });
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.error).toBe("Unauthorized");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 401 with expired session", async () => {
|
||||||
|
selectSessionRow = EXPIRED_SESSION;
|
||||||
|
const res = await jsonPetPatch(
|
||||||
|
`/portal/pets/${PET_ID}`,
|
||||||
|
{ name: "Test" },
|
||||||
|
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.error).toBe("Unauthorized");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 403 when pet belongs to a different client", async () => {
|
||||||
|
selectSessionRow = { ...ACTIVE_SESSION, clientId: "different-client-id" };
|
||||||
|
selectPetRow = { ...PET };
|
||||||
|
const res = await jsonPetPatch(
|
||||||
|
`/portal/pets/${PET_ID}`,
|
||||||
|
{ name: "Hacked" },
|
||||||
|
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.error).toBe("Forbidden");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 404 when pet not found", async () => {
|
||||||
|
selectSessionRow = ACTIVE_SESSION;
|
||||||
|
selectPetRow = null;
|
||||||
|
const res = await jsonPetPatch(
|
||||||
|
`/portal/pets/nonexistent-id`,
|
||||||
|
{ name: "Ghost" },
|
||||||
|
{ "X-Impersonation-Session-Id": SESSION_ID }
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
+10
-5
@@ -58,8 +58,11 @@ app.use(
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
// Health check (no auth required)
|
// Health check — no auth required, registered on app at full path before auth middleware
|
||||||
|
// /health: used by Dockerfile HEALTHCHECK and K8s readinessProbe/livenessProbe (port 3000 direct)
|
||||||
app.get("/health", (c) => c.json({ status: "ok" }));
|
app.get("/health", (c) => c.json({ status: "ok" }));
|
||||||
|
// /api/health: used by Gateway HTTPRoute (/api/* → API pod)
|
||||||
|
app.get("/api/health", (c) => c.json({ status: "ok" }));
|
||||||
|
|
||||||
// Public booking routes — no auth required, must be registered before auth middleware
|
// Public booking routes — no auth required, must be registered before auth middleware
|
||||||
app.route("/api/book", bookRouter);
|
app.route("/api/book", bookRouter);
|
||||||
@@ -282,14 +285,16 @@ startReminderScheduler();
|
|||||||
|
|
||||||
function shutdown() {
|
function shutdown() {
|
||||||
console.log("Shutting down gracefully...");
|
console.log("Shutting down gracefully...");
|
||||||
|
// SIGTERM/SIGINT → server.close() → callback → process.exit(0)
|
||||||
|
// If graceful close takes >8s, force-exit to avoid being killed undrained
|
||||||
|
setTimeout(() => {
|
||||||
|
console.error("Graceful close timeout — forcing exit");
|
||||||
|
process.exit(1);
|
||||||
|
}, 8_000);
|
||||||
server.close(() => {
|
server.close(() => {
|
||||||
console.log("HTTP server closed");
|
console.log("HTTP server closed");
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
setTimeout(() => {
|
|
||||||
console.error("Forced shutdown after timeout");
|
|
||||||
process.exit(1);
|
|
||||||
}, 10_000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
process.on("SIGTERM", shutdown);
|
process.on("SIGTERM", shutdown);
|
||||||
|
|||||||
+7
-1
@@ -186,7 +186,9 @@ export async function initAuth(): Promise<void> {
|
|||||||
const discoveryUrlStr = `${providerConfig.issuerUrl}/.well-known/openid-configuration`;
|
const discoveryUrlStr = `${providerConfig.issuerUrl}/.well-known/openid-configuration`;
|
||||||
let oidcConfig: Record<string, string> = {};
|
let oidcConfig: Record<string, string> = {};
|
||||||
try {
|
try {
|
||||||
const discoveryRes = await fetch(discoveryUrlStr);
|
const discoveryRes = await fetch(discoveryUrlStr, {
|
||||||
|
signal: AbortSignal.timeout(5000),
|
||||||
|
});
|
||||||
if (discoveryRes.ok) {
|
if (discoveryRes.ok) {
|
||||||
const discovery = await discoveryRes.json() as {
|
const discovery = await discoveryRes.json() as {
|
||||||
authorization_endpoint?: string;
|
authorization_endpoint?: string;
|
||||||
@@ -251,6 +253,10 @@ export async function initAuth(): Promise<void> {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
account: {
|
account: {
|
||||||
|
accountLinking: {
|
||||||
|
enabled: true,
|
||||||
|
trustedProviders: ["authentik"],
|
||||||
|
},
|
||||||
storeStateStrategy: "cookie" as const,
|
storeStateStrategy: "cookie" as const,
|
||||||
},
|
},
|
||||||
emailAndPassword: {
|
emailAndPassword: {
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ if (process.env.AUTH_DISABLED === "true") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
||||||
if (c.req.path.startsWith("/api/auth/")) {
|
if (c.req.path.startsWith("/api/auth/") || c.req.path === "/api/health") {
|
||||||
await next();
|
await next();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -193,8 +193,8 @@ bookRouter.post(
|
|||||||
name: body.petName,
|
name: body.petName,
|
||||||
species: body.petSpecies,
|
species: body.petSpecies,
|
||||||
breed: body.petBreed ?? null,
|
breed: body.petBreed ?? null,
|
||||||
coatType: (body.petCoatType ?? null) as "smooth" | "double" | "wire" | "curly" | "long" | "hairless" | null,
|
coatType: (body.petCoatType ?? null) as "short" | "medium" | "long" | "double" | "wire" | "silky" | "curly" | "hairless" | null,
|
||||||
petSizeCategory: (body.petSizeCategory ?? null) as "small" | "medium" | "large" | "xlarge" | null,
|
petSizeCategory: (body.petSizeCategory ?? null) as "small" | "medium" | "large" | "extra_large" | null,
|
||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
const pet = petInserted[0];
|
const pet = petInserted[0];
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ bufferRulesRouter.use("*", requireRole("manager"));
|
|||||||
|
|
||||||
const createBufferRuleSchema = z.object({
|
const createBufferRuleSchema = z.object({
|
||||||
serviceId: z.string().uuid(),
|
serviceId: z.string().uuid(),
|
||||||
sizeCategory: z.enum(["small", "medium", "large", "xlarge"]).optional(),
|
sizeCategory: z.enum(["small", "medium", "large", "extra_large"]).optional(),
|
||||||
coatType: z.enum(["smooth", "double", "wire", "curly", "long", "hairless"]).optional(),
|
coatType: z.enum(["short", "medium", "long", "double", "wire", "silky", "curly", "hairless"]).optional(),
|
||||||
bufferMinutes: z.number().int().positive(),
|
bufferMinutes: z.number().int().positive(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -24,8 +24,8 @@ const createPetSchema = z.object({
|
|||||||
shampooPreference: z.string().max(500).optional(),
|
shampooPreference: z.string().max(500).optional(),
|
||||||
specialCareNotes: z.string().max(2000).optional(),
|
specialCareNotes: z.string().max(2000).optional(),
|
||||||
customFields: z.record(z.string(), z.string()).optional(),
|
customFields: z.record(z.string(), z.string()).optional(),
|
||||||
sizeCategory: z.enum(["small", "medium", "large", "xlarge"]).optional(),
|
petSizeCategory: z.enum(["small", "medium", "large", "extra_large"]).optional(),
|
||||||
coatType: z.enum(["smooth", "double", "wire", "curly", "long", "hairless"]).optional(),
|
coatType: z.enum(["short", "medium", "long", "double", "wire", "silky", "curly", "hairless"]).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const updatePetSchema = createPetSchema.partial().omit({ clientId: true });
|
const updatePetSchema = createPetSchema.partial().omit({ clientId: true });
|
||||||
|
|||||||
@@ -152,6 +152,67 @@ portalRouter.get("/pets", async (c) => {
|
|||||||
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 })));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const portalUpdatePetSchema = z.object({
|
||||||
|
name: z.string().min(1).max(200).optional(),
|
||||||
|
species: z.string().min(1).max(100).optional(),
|
||||||
|
breed: z.string().max(200).optional(),
|
||||||
|
weightKg: z.number().positive().optional(),
|
||||||
|
dateOfBirth: z.string().datetime().optional(),
|
||||||
|
healthAlerts: z.string().max(2000).optional(),
|
||||||
|
groomingNotes: z.string().max(2000).optional(),
|
||||||
|
cutStyle: z.string().max(500).optional(),
|
||||||
|
shampooPreference: z.string().max(500).optional(),
|
||||||
|
specialCareNotes: z.string().max(2000).optional(),
|
||||||
|
customFields: z.record(z.string(), z.string()).optional(),
|
||||||
|
petSizeCategory: z.enum(["small", "medium", "large", "extra_large"]).optional(),
|
||||||
|
coatType: z.enum(["short", "medium", "long", "double", "wire", "silky", "curly", "hairless"]).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
portalRouter.patch(
|
||||||
|
"/pets/:id",
|
||||||
|
zValidator("json", portalUpdatePetSchema),
|
||||||
|
async (c) => {
|
||||||
|
const db = getDb();
|
||||||
|
const petId = c.req.param("id");
|
||||||
|
const clientId = c.get("portalClientId");
|
||||||
|
const body = c.req.valid("json");
|
||||||
|
|
||||||
|
const [existing] = await db
|
||||||
|
.select()
|
||||||
|
.from(pets)
|
||||||
|
.where(eq(pets.id, petId))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!existing) return c.json({ error: "Not found" }, 404);
|
||||||
|
if (existing.clientId !== clientId) return c.json({ error: "Forbidden" }, 403);
|
||||||
|
|
||||||
|
const { weightKg, dateOfBirth, customFields, ...rest } = body;
|
||||||
|
const [updated] = await db
|
||||||
|
.update(pets)
|
||||||
|
.set({
|
||||||
|
...rest,
|
||||||
|
weightKg: weightKg?.toString(),
|
||||||
|
dateOfBirth: dateOfBirth ? new Date(dateOfBirth) : undefined,
|
||||||
|
...(customFields !== undefined ? { customFields } : {}),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
})
|
||||||
|
.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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
portalRouter.get("/invoices", async (c) => {
|
portalRouter.get("/invoices", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const clientId = c.get("portalClientId");
|
const clientId = c.get("portalClientId");
|
||||||
|
|||||||
Reference in New Issue
Block a user