Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1674a7df4a | |||
| 09187ca277 | |||
| 2c928ca4d7 | |||
| af75fecb66 | |||
| 2d4df6fe1e | |||
| db10320c8f | |||
| 40a4023c65 | |||
| d598511b75 |
@@ -202,20 +202,20 @@ jobs:
|
|||||||
echo "Updating dev overlay image tags to: $TAG"
|
echo "Updating dev overlay image tags to: $TAG"
|
||||||
echo "Updating migration/seed Job names with SHA: $SHORT_SHA"
|
echo "Updating migration/seed Job names with SHA: $SHORT_SHA"
|
||||||
cd /tmp/infra
|
cd /tmp/infra
|
||||||
DEV_KUST="apps/groombook/overlays/dev/kustomization.yaml"
|
DEV_KUST="apps/overlays/dev/kustomization.yaml"
|
||||||
yq -i '(.images[] | select(.name == "ghcr.io/groombook/api")).newTag = env(TAG)' "$DEV_KUST"
|
yq -i '(.images[] | select(.name == "ghcr.io/groombook/api")).newTag = env(TAG)' "$DEV_KUST"
|
||||||
yq -i '(.images[] | select(.name == "ghcr.io/groombook/migrate")).newTag = env(TAG)' "$DEV_KUST"
|
yq -i '(.images[] | select(.name == "ghcr.io/groombook/migrate")).newTag = env(TAG)' "$DEV_KUST"
|
||||||
yq -i '(.images[] | select(.name == "ghcr.io/groombook/seed")).newTag = env(TAG)' "$DEV_KUST"
|
yq -i '(.images[] | select(.name == "ghcr.io/groombook/seed")).newTag = env(TAG)' "$DEV_KUST"
|
||||||
yq -i '(.images[] | select(.name == "ghcr.io/groombook/reset")).newTag = env(TAG)' "$DEV_KUST"
|
yq -i '(.images[] | select(.name == "ghcr.io/groombook/reset")).newTag = env(TAG)' "$DEV_KUST"
|
||||||
|
|
||||||
MIGRATE_JOB="apps/groombook/base/migrate-job.yaml"
|
MIGRATE_JOB="apps/base/migrate-job.yaml"
|
||||||
if [ -f "$MIGRATE_JOB" ]; then
|
if [ -f "$MIGRATE_JOB" ]; then
|
||||||
yq -i '.metadata.name = "migrate-schema-" + env(SHORT_SHA)' "$MIGRATE_JOB"
|
yq -i '.metadata.name = "migrate-schema-" + env(SHORT_SHA)' "$MIGRATE_JOB"
|
||||||
yq -i '.metadata.annotations."groombook.app/deploy-version" = env(TAG)' "$MIGRATE_JOB"
|
yq -i '.metadata.annotations."groombook.app/deploy-version" = env(TAG)' "$MIGRATE_JOB"
|
||||||
yq -i '.spec.ttlSecondsAfterFinished = (.spec.ttlSecondsAfterFinished // 86400)' "$MIGRATE_JOB"
|
yq -i '.spec.ttlSecondsAfterFinished = (.spec.ttlSecondsAfterFinished // 86400)' "$MIGRATE_JOB"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
SEED_JOB="apps/groombook/base/seed-job.yaml"
|
SEED_JOB="apps/base/seed-job.yaml"
|
||||||
if [ -f "$SEED_JOB" ]; then
|
if [ -f "$SEED_JOB" ]; then
|
||||||
yq -i '.metadata.name = "seed-test-data-" + env(SHORT_SHA)' "$SEED_JOB"
|
yq -i '.metadata.name = "seed-test-data-" + env(SHORT_SHA)' "$SEED_JOB"
|
||||||
yq -i '.metadata.annotations."groombook.app/deploy-version" = env(TAG)' "$SEED_JOB"
|
yq -i '.metadata.annotations."groombook.app/deploy-version" = env(TAG)' "$SEED_JOB"
|
||||||
@@ -237,7 +237,7 @@ jobs:
|
|||||||
git config user.name "groombook-engineer[bot]"
|
git config user.name "groombook-engineer[bot]"
|
||||||
git config user.email "3141748+groombook-engineer[bot]@users.noreply.github.com"
|
git config user.email "3141748+groombook-engineer[bot]@users.noreply.github.com"
|
||||||
git checkout -b "chore/update-image-tags-${TAG}"
|
git checkout -b "chore/update-image-tags-${TAG}"
|
||||||
git add apps/groombook/overlays/dev/ apps/groombook/base/migrate-job.yaml apps/groombook/base/seed-job.yaml
|
git add apps/overlays/dev/ apps/base/migrate-job.yaml apps/base/seed-job.yaml
|
||||||
git commit -m "chore: update image tags and migration/seed Job names to ${TAG}"
|
git commit -m "chore: update image tags and migration/seed Job names to ${TAG}"
|
||||||
|
|
||||||
git push -u origin "chore/update-image-tags-${TAG}"
|
git push -u origin "chore/update-image-tags-${TAG}"
|
||||||
|
|||||||
+2
-2
@@ -3,7 +3,7 @@ RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
FROM base AS deps
|
FROM base AS deps
|
||||||
COPY package.json pnpm-lock.yaml ./
|
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||||
COPY apps/api/package.json apps/api/
|
COPY apps/api/package.json apps/api/
|
||||||
RUN pnpm install --frozen-lockfile
|
RUN pnpm install --frozen-lockfile
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ RUN corepack enable && corepack prepare pnpm@9.15.4 --activate
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
COPY package.json pnpm-lock.yaml ./
|
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||||
COPY --from=builder /app/apps/api/package.json apps/api/
|
COPY --from=builder /app/apps/api/package.json apps/api/
|
||||||
COPY --from=builder /app/apps/api/dist apps/api/dist
|
COPY --from=builder /app/apps/api/dist apps/api/dist
|
||||||
RUN pnpm install --frozen-lockfile --prod
|
RUN pnpm install --frozen-lockfile --prod
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ GroomBook API is a Hono-based REST service (TypeScript/Node.js) powering the pet
|
|||||||
| TC-API-1.1 | Login via OIDC | POST to OIDC provider callback, verify JWT token issued | 200 OK, JWT returned with valid claims |
|
| TC-API-1.1 | Login via OIDC | POST to OIDC provider callback, verify JWT token issued | 200 OK, JWT returned with valid claims |
|
||||||
| TC-API-1.2 | Session persistence | Make authenticated request, verify session token valid | 200 OK, request succeeds |
|
| TC-API-1.2 | Session persistence | Make authenticated request, verify session token valid | 200 OK, request succeeds |
|
||||||
| TC-API-1.3 | Logout | Call logout endpoint, verify token invalidated | 200 OK, subsequent requests return 401 |
|
| TC-API-1.3 | Logout | Call logout endpoint, verify token invalidated | 200 OK, subsequent requests return 401 |
|
||||||
|
| TC-API-1.4 | Auto-provision on first OIDC login | First login as a Better-Auth user with no existing staff record | 200 OK, access granted; groomer staff record auto-created with name/email from user table |
|
||||||
|
|
||||||
### 4.2 Client Management
|
### 4.2 Client Management
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { defineConfig } from "drizzle-kit";
|
import { defineConfig } from "drizzle-kit";
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
schema: "./src/db/schema.ts",
|
schema: "./src/schema.ts",
|
||||||
out: "./migrations",
|
out: "./migrations",
|
||||||
dialect: "postgresql",
|
dialect: "postgresql",
|
||||||
dbCredentials: {
|
dbCredentials: {
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
-- Migration: 0030_extended_pet_profile
|
|
||||||
-- Adds extended profile fields to the pets table
|
|
||||||
|
|
||||||
BEGIN;
|
|
||||||
|
|
||||||
ALTER TABLE pets ADD COLUMN coat_type text;
|
|
||||||
ALTER TABLE pets ADD COLUMN temperament_score integer;
|
|
||||||
ALTER TABLE pets ADD COLUMN temperament_flags jsonb DEFAULT '[]'::jsonb;
|
|
||||||
ALTER TABLE pets ADD COLUMN medical_alerts jsonb DEFAULT '[]'::jsonb;
|
|
||||||
ALTER TABLE pets ADD COLUMN preferred_cuts jsonb DEFAULT '[]'::jsonb;
|
|
||||||
|
|
||||||
COMMIT;
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
{
|
|
||||||
"id": "0030_extended_pet_profile",
|
|
||||||
"prevId": "0028_sms_reminders",
|
|
||||||
"version": "7",
|
|
||||||
"dialect": "postgresql",
|
|
||||||
"tables": {
|
|
||||||
"public.pets": {
|
|
||||||
"name": "pets",
|
|
||||||
"schema": "",
|
|
||||||
"columns": {
|
|
||||||
"id": { "name": "id", "type": "uuid", "primaryKey": true, "default": "gen_random_uuid()", "isNullable": false },
|
|
||||||
"client_id": { "name": "client_id", "type": "uuid", "isNullable": false },
|
|
||||||
"name": { "name": "name", "type": "text", "isNullable": false },
|
|
||||||
"species": { "name": "species", "type": "text", "isNullable": false },
|
|
||||||
"breed": { "name": "breed", "type": "text", "isNullable": true },
|
|
||||||
"weight_kg": { "name": "weight_kg", "type": "numeric(5, 2)", "isNullable": true },
|
|
||||||
"date_of_birth": { "name": "date_of_birth", "type": "timestamp", "isNullable": true },
|
|
||||||
"health_alerts": { "name": "health_alerts", "type": "text", "isNullable": true },
|
|
||||||
"grooming_notes": { "name": "grooming_notes", "type": "text", "isNullable": true },
|
|
||||||
"cut_style": { "name": "cut_style", "type": "text", "isNullable": true },
|
|
||||||
"shampoo_preference": { "name": "shampoo_preference", "type": "text", "isNullable": true },
|
|
||||||
"special_care_notes": { "name": "special_care_notes", "type": "text", "isNullable": true },
|
|
||||||
"custom_fields": { "name": "custom_fields", "type": "jsonb", "isNullable": false, "default": "'{}'::jsonb" },
|
|
||||||
"photo_key": { "name": "photo_key", "type": "text", "isNullable": true },
|
|
||||||
"photo_uploaded_at": { "name": "photo_uploaded_at", "type": "timestamp", "isNullable": true },
|
|
||||||
"image": { "name": "image", "type": "text", "isNullable": true },
|
|
||||||
"coat_type": { "name": "coat_type", "type": "text", "isNullable": true },
|
|
||||||
"temperament_score": { "name": "temperament_score", "type": "integer", "isNullable": true },
|
|
||||||
"temperament_flags": { "name": "temperament_flags", "type": "jsonb", "isNullable": true, "default": "'[]'::jsonb" },
|
|
||||||
"medical_alerts": { "name": "medical_alerts", "type": "jsonb", "isNullable": true, "default": "'[]'::jsonb" },
|
|
||||||
"preferred_cuts": { "name": "preferred_cuts", "type": "jsonb", "isNullable": true, "default": "'[]'::jsonb" },
|
|
||||||
"created_at": { "name": "created_at", "type": "timestamp", "isNullable": false, "default": "now()" },
|
|
||||||
"updated_at": { "name": "updated_at", "type": "timestamp", "isNullable": false, "default": "now()" }
|
|
||||||
},
|
|
||||||
"indexes": { "idx_pets_client_id": { "name": "idx_pets_client_id", "columns": [{ "expression": "client_id", "isExpression": false, "asc": true, "nulls": "last" }], "isUnique": false } },
|
|
||||||
"foreignKeys": { "pets_client_id_clients_id_fk": { "name": "pets_client_id_clients_id_fk", "tableFrom": "pets", "tableTo": "clients", "columnsFrom": ["client_id"], "columnsTo": ["id"], "onDelete": "cascade" } },
|
|
||||||
"compositePrimaryKeys": {},
|
|
||||||
"uniqueConstraints": {}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"enums": {},
|
|
||||||
"schemas": {},
|
|
||||||
"sequences": {},
|
|
||||||
"roles": {},
|
|
||||||
"policies": {},
|
|
||||||
"views": {},
|
|
||||||
"_meta": { "columns": {}, "schemas": {}, "tables": {} }
|
|
||||||
}
|
|
||||||
@@ -204,20 +204,6 @@
|
|||||||
"when": 1775741667192,
|
"when": 1775741667192,
|
||||||
"tag": "0028_sms_reminders",
|
"tag": "0028_sms_reminders",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
},
|
|
||||||
{
|
|
||||||
"idx": 29,
|
|
||||||
"version": "7",
|
|
||||||
"when": 1775828067192,
|
|
||||||
"tag": "0029_db_indexes_constraints",
|
|
||||||
"breakpoints": true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"idx": 30,
|
|
||||||
"version": "7",
|
|
||||||
"when": 1775914467192,
|
|
||||||
"tag": "0030_extended_pet_profile",
|
|
||||||
"breakpoints": true
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1,414 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
||||||
import { Hono } from "hono";
|
|
||||||
import type { AppEnv, StaffRow } from "../middleware/rbac.js";
|
|
||||||
import { petsRouter } from "../routes/pets.js";
|
|
||||||
|
|
||||||
// ─── Mock staff fixtures ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const MANAGER: StaffRow = {
|
|
||||||
id: "staff-manager-id",
|
|
||||||
oidcSub: "oidc-manager-sub",
|
|
||||||
userId: null,
|
|
||||||
role: "manager",
|
|
||||||
isSuperUser: true,
|
|
||||||
name: "Manager McManager",
|
|
||||||
email: "manager@example.com",
|
|
||||||
active: true,
|
|
||||||
icalToken: null,
|
|
||||||
createdAt: new Date(),
|
|
||||||
updatedAt: new Date(),
|
|
||||||
};
|
|
||||||
|
|
||||||
// ─── Mutable mock state ───────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const CLIENT_ID = "client-uuid-extended";
|
|
||||||
const PET_ID = "pet-uuid-extended";
|
|
||||||
|
|
||||||
let petRows: Record<string, unknown>[] = [];
|
|
||||||
let appointmentRows: Record<string, unknown>[] = [];
|
|
||||||
let insertedValues: Record<string, unknown>[] = [];
|
|
||||||
let updatedValues: Record<string, unknown>[] = [];
|
|
||||||
let deletedId: string | null = null;
|
|
||||||
|
|
||||||
function resetMock() {
|
|
||||||
petRows = [{
|
|
||||||
id: PET_ID,
|
|
||||||
clientId: CLIENT_ID,
|
|
||||||
name: "Biscuit",
|
|
||||||
species: "dog",
|
|
||||||
breed: "Golden Retriever",
|
|
||||||
weightKg: "30.00",
|
|
||||||
dateOfBirth: null,
|
|
||||||
healthAlerts: null,
|
|
||||||
groomingNotes: null,
|
|
||||||
cutStyle: null,
|
|
||||||
shampooPreference: null,
|
|
||||||
specialCareNotes: null,
|
|
||||||
customFields: {},
|
|
||||||
photoKey: null,
|
|
||||||
photoUploadedAt: null,
|
|
||||||
image: null,
|
|
||||||
coatType: null,
|
|
||||||
temperamentScore: null,
|
|
||||||
temperamentFlags: [],
|
|
||||||
medicalAlerts: [],
|
|
||||||
preferredCuts: [],
|
|
||||||
createdAt: new Date(),
|
|
||||||
updatedAt: new Date(),
|
|
||||||
}];
|
|
||||||
appointmentRows = [];
|
|
||||||
insertedValues = [];
|
|
||||||
updatedValues = [];
|
|
||||||
deletedId = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeSelectChainable(rows: unknown[]): unknown {
|
|
||||||
const chain = new Proxy([...rows], {
|
|
||||||
get(target, prop) {
|
|
||||||
if (prop === "where" || prop === "orderBy" || prop === "limit") {
|
|
||||||
return () => chain;
|
|
||||||
}
|
|
||||||
// @ts-expect-error proxy
|
|
||||||
return target[prop];
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return chain;
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeInsertChainable(): unknown {
|
|
||||||
let vals: Record<string, unknown> = {};
|
|
||||||
const chain = new Proxy({}, {
|
|
||||||
get(target, prop) {
|
|
||||||
if (prop === "values") {
|
|
||||||
return (v: Record<string, unknown>) => { vals = v; return chain; };
|
|
||||||
}
|
|
||||||
if (prop === "returning") {
|
|
||||||
return () => {
|
|
||||||
insertedValues.push(vals);
|
|
||||||
return [vals.id ? { ...vals, id: vals.id ?? PET_ID } : { ...vals, id: PET_ID }];
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return chain;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return chain;
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeUpdateChainable(): unknown {
|
|
||||||
let vals: Record<string, unknown> = {};
|
|
||||||
let whereId: string | null = null;
|
|
||||||
const chain = new Proxy({}, {
|
|
||||||
get(target, prop) {
|
|
||||||
if (prop === "set") {
|
|
||||||
return (v: Record<string, unknown>) => { vals = v; return chain; };
|
|
||||||
}
|
|
||||||
if (prop === "where") {
|
|
||||||
return (cond: unknown) => {
|
|
||||||
// Extract id from condition if it's an eq call
|
|
||||||
if (whereId) vals = { ...vals };
|
|
||||||
return chain;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (prop === "returning") {
|
|
||||||
return () => {
|
|
||||||
const merged = { ...petRows[0], ...vals };
|
|
||||||
updatedValues.push(vals);
|
|
||||||
return [merged];
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return chain;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return chain;
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeDeleteChainable(): unknown {
|
|
||||||
let whereId: string | null = null;
|
|
||||||
const chain = new Proxy({}, {
|
|
||||||
get(target, prop) {
|
|
||||||
if (prop === "where") {
|
|
||||||
return (cond: unknown) => {
|
|
||||||
whereId = PET_ID;
|
|
||||||
return chain;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (prop === "returning") {
|
|
||||||
return () => {
|
|
||||||
const row = petRows[0];
|
|
||||||
deletedId = row.id as string;
|
|
||||||
return [row];
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return chain;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return chain;
|
|
||||||
}
|
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
|
||||||
const pets = new Proxy({ _name: "pets" }, { get: (t, p) => p === "_name" ? "pets" : {} });
|
|
||||||
const appointments = new Proxy({ _name: "appointments" }, { get: (t, p) => p === "_name" ? "appointments" : {} });
|
|
||||||
return {
|
|
||||||
getDb: () => ({
|
|
||||||
select: () => ({
|
|
||||||
from: (table: unknown) => {
|
|
||||||
const name = (table as { _name?: string })._name;
|
|
||||||
if (name === "appointments") return makeSelectChainable(appointmentRows);
|
|
||||||
return makeSelectChainable(petRows);
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
insert: () => makeInsertChainable(),
|
|
||||||
update: () => makeUpdateChainable(),
|
|
||||||
delete: () => makeDeleteChainable(),
|
|
||||||
}),
|
|
||||||
pets,
|
|
||||||
appointments,
|
|
||||||
and,
|
|
||||||
eq,
|
|
||||||
exists,
|
|
||||||
or,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
function makeApp(staff: StaffRow = MANAGER) {
|
|
||||||
const app = new Hono<AppEnv>();
|
|
||||||
app.use("*", async (c, next) => {
|
|
||||||
c.set("staff", staff);
|
|
||||||
await next();
|
|
||||||
});
|
|
||||||
return app.route("/pets", petsRouter);
|
|
||||||
}
|
|
||||||
|
|
||||||
function createApp() {
|
|
||||||
const app = makeApp(MANAGER);
|
|
||||||
return app;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Tests ────────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
describe("Extended pet profile fields — validation", () => {
|
|
||||||
beforeEach(resetMock);
|
|
||||||
|
|
||||||
it("rejects temperamentScore of 0 (below min)", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ clientId: CLIENT_ID, name: "Test", species: "dog", temperamentScore: 0 }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.success).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects temperamentScore of 6 (above max)", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ clientId: CLIENT_ID, name: "Test", species: "dog", temperamentScore: 6 }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.success).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects non-integer temperamentScore", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ clientId: CLIENT_ID, name: "Test", species: "dog", temperamentScore: 3.5 }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects invalid medicalAlert severity", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
clientId: CLIENT_ID,
|
|
||||||
name: "Test",
|
|
||||||
species: "dog",
|
|
||||||
medicalAlerts: [{ type: "seizure", description: "xyz", severity: "critical" }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("accepts valid temperamentScore 1–5", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
for (const score of [1, 2, 3, 4, 5]) {
|
|
||||||
resetMock();
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ clientId: CLIENT_ID, name: "Test", species: "dog", temperamentScore: score }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(201);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("accepts all valid medicalAlert severity values", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
for (const severity of ["low", "medium", "high"] as const) {
|
|
||||||
resetMock();
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
clientId: CLIENT_ID,
|
|
||||||
name: "Test",
|
|
||||||
species: "dog",
|
|
||||||
medicalAlerts: [{ type: "allergy", description: "Sensitive to chicken", severity }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(201);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Extended pet profile fields — create", () => {
|
|
||||||
beforeEach(resetMock);
|
|
||||||
|
|
||||||
it("accepts all extended fields on create", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
clientId: CLIENT_ID,
|
|
||||||
name: "Biscuit",
|
|
||||||
species: "dog",
|
|
||||||
breed: "Golden Retriever",
|
|
||||||
coatType: "double",
|
|
||||||
temperamentScore: 4,
|
|
||||||
temperamentFlags: ["anxious_with_dryers", "gentle"],
|
|
||||||
medicalAlerts: [
|
|
||||||
{ type: "seizure", description: "Occasional episodes", severity: "medium" },
|
|
||||||
],
|
|
||||||
preferredCuts: ["puppy cut", "teddy bear"],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(201);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.coatType).toBe("double");
|
|
||||||
expect(body.temperamentScore).toBe(4);
|
|
||||||
expect(body.temperamentFlags).toEqual(["anxious_with_dryers", "gentle"]);
|
|
||||||
expect(body.medicalAlerts).toEqual([{ type: "seizure", description: "Occasional episodes", severity: "medium" }]);
|
|
||||||
expect(body.preferredCuts).toEqual(["puppy cut", "teddy bear"]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("create without extended fields works (all optional)", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ clientId: CLIENT_ID, name: "Basil", species: "cat" }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(201);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Extended pet profile fields — update", () => {
|
|
||||||
beforeEach(resetMock);
|
|
||||||
|
|
||||||
it("updates coatType", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request(`/pets/${PET_ID}`, {
|
|
||||||
method: "PATCH",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ coatType: "smooth" }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.coatType).toBe("smooth");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("updates temperamentScore", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request(`/pets/${PET_ID}`, {
|
|
||||||
method: "PATCH",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ temperamentScore: 2 }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.temperamentScore).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects temperamentScore 0 on update", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request(`/pets/${PET_ID}`, {
|
|
||||||
method: "PATCH",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ temperamentScore: 0 }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects invalid severity on update", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request(`/pets/${PET_ID}`, {
|
|
||||||
method: "PATCH",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
medicalAlerts: [{ type: "x", description: "y", severity: "urgent" }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects too many temperamentFlags (>20)", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const flags = Array.from({ length: 21 }, (_, i) => `flag_${i}`);
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ clientId: CLIENT_ID, name: "Test", species: "dog", temperamentFlags: flags }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects too many preferredCuts (>20)", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const cuts = Array.from({ length: 21 }, (_, i) => `cut_${i}`);
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ clientId: CLIENT_ID, name: "Test", species: "dog", preferredCuts: cuts }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects too many medicalAlerts (>50)", async () => {
|
|
||||||
const app = createApp();
|
|
||||||
const alerts = Array.from({ length: 51 }, (_, i) => ({
|
|
||||||
type: `type_${i}`,
|
|
||||||
description: `desc_${i}`,
|
|
||||||
severity: "low" as const,
|
|
||||||
}));
|
|
||||||
const res = await app.request("/pets", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ clientId: CLIENT_ID, name: "Test", species: "dog", medicalAlerts: alerts }),
|
|
||||||
});
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns extended fields in GET response", async () => {
|
|
||||||
petRows = [{ ...petRows[0], coatType: "wire", temperamentScore: 3, temperamentFlags: ["gentle"], medicalAlerts: [], preferredCuts: ["scissor cut"] }];
|
|
||||||
const app = createApp();
|
|
||||||
const res = await app.request(`/pets/${PET_ID}`);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.coatType).toBe("wire");
|
|
||||||
expect(body.temperamentScore).toBe(3);
|
|
||||||
expect(body.temperamentFlags).toEqual(["gentle"]);
|
|
||||||
expect(body.preferredCuts).toEqual(["scissor cut"]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -45,40 +45,72 @@ const GROOMER: StaffRow = {
|
|||||||
|
|
||||||
let staffLookupResult: StaffRow | null = null;
|
let staffLookupResult: StaffRow | null = null;
|
||||||
let managerFallbackResult: StaffRow | null = MANAGER;
|
let managerFallbackResult: StaffRow | null = MANAGER;
|
||||||
|
let userLookupResult: { id: string; name: string | null; email: string | null } | null = null;
|
||||||
|
let insertedStaff: StaffRow | null = null;
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("../db", () => {
|
||||||
const staff = new Proxy(
|
const makeTableProxy = (name: string) =>
|
||||||
{ _name: "staff" },
|
new Proxy(
|
||||||
{
|
{ _name: name },
|
||||||
get(target, prop) {
|
{
|
||||||
if (prop === "_name") return "staff";
|
get(target, prop) {
|
||||||
if (prop === "$inferSelect") return {};
|
if (prop === "_name") return name;
|
||||||
return { table: "staff", column: prop };
|
if (prop === "$inferSelect") return {};
|
||||||
|
return { table: name, column: prop };
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const staff = makeTableProxy("staff");
|
||||||
|
const user = makeTableProxy("user");
|
||||||
|
|
||||||
|
const buildQuery = (result: unknown, fallback: unknown) => ({
|
||||||
|
limit: () => ({
|
||||||
|
[Symbol.iterator]: function* () {
|
||||||
|
if (result) yield result;
|
||||||
},
|
},
|
||||||
}
|
0: result,
|
||||||
);
|
length: result ? 1 : 0,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getDb: () => ({
|
getDb: () => ({
|
||||||
select: () => ({
|
select: () => ({
|
||||||
from: () => ({
|
from: (table: unknown) => ({
|
||||||
where: () => ({
|
where: () => buildQuery(
|
||||||
limit: () => {
|
table === staff ? staffLookupResult : userLookupResult,
|
||||||
// dev mode fallback to first manager
|
table === staff ? managerFallbackResult : null
|
||||||
return managerFallbackResult ? [managerFallbackResult] : [];
|
),
|
||||||
},
|
}),
|
||||||
[Symbol.iterator]: function* () {
|
}),
|
||||||
if (staffLookupResult) yield staffLookupResult;
|
insert: (table: unknown) => ({
|
||||||
},
|
values: (vals: Record<string, unknown>) => ({
|
||||||
0: staffLookupResult,
|
returning: () => {
|
||||||
length: staffLookupResult ? 1 : 0,
|
const newStaff: StaffRow = {
|
||||||
}),
|
id: "new-staff-id",
|
||||||
|
oidcSub: null,
|
||||||
|
userId: vals.userId as string,
|
||||||
|
role: vals.role as StaffRow["role"],
|
||||||
|
isSuperUser: false,
|
||||||
|
name: vals.name as string,
|
||||||
|
email: vals.email as string,
|
||||||
|
active: true,
|
||||||
|
icalToken: null,
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
};
|
||||||
|
insertedStaff = newStaff;
|
||||||
|
return [newStaff];
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
staff,
|
staff,
|
||||||
|
user,
|
||||||
eq: vi.fn((_col: unknown, _val: unknown) => ({ col: _col, val: _val })),
|
eq: vi.fn((_col: unknown, _val: unknown) => ({ col: _col, val: _val })),
|
||||||
and: vi.fn((..._clauses: unknown[]) => ({})),
|
and: vi.fn((..._clauses: unknown[]) => ({})),
|
||||||
|
sql: vi.fn((..._args: unknown[]) => ({})),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -87,6 +119,8 @@ vi.mock("../db", () => {
|
|||||||
function resetMocks() {
|
function resetMocks() {
|
||||||
staffLookupResult = null;
|
staffLookupResult = null;
|
||||||
managerFallbackResult = MANAGER;
|
managerFallbackResult = MANAGER;
|
||||||
|
userLookupResult = null;
|
||||||
|
insertedStaff = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Build a minimal Hono app with jwtPayload pre-set, then apply a middleware. */
|
/** Build a minimal Hono app with jwtPayload pre-set, then apply a middleware. */
|
||||||
@@ -202,6 +236,50 @@ describe("resolveStaffMiddleware", () => {
|
|||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
expect(body.error).toMatch(/no staff records found/i);
|
expect(body.error).toMatch(/no staff records found/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("auto-provision: creates groomer staff record on first login when Better-Auth user exists", async () => {
|
||||||
|
staffLookupResult = null;
|
||||||
|
userLookupResult = { id: "ba-user-new", name: "New User", email: "newuser@example.com" };
|
||||||
|
let capturedStaff: StaffRow | null = null;
|
||||||
|
const app = buildApp(resolveStaffMiddleware, (c) => {
|
||||||
|
capturedStaff = c.get("staff");
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await app.request("/test");
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(capturedStaff).not.toBeNull();
|
||||||
|
expect(capturedStaff!.role).toBe("groomer");
|
||||||
|
expect(capturedStaff!.userId).toBe("ba-user-new");
|
||||||
|
expect(capturedStaff!.name).toBe("New User");
|
||||||
|
expect(capturedStaff!.email).toBe("newuser@example.com");
|
||||||
|
expect(capturedStaff!.isSuperUser).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("auto-provision: falls back to email prefix when user has no name", async () => {
|
||||||
|
staffLookupResult = null;
|
||||||
|
userLookupResult = { id: "ba-user-noname", name: null, email: "firstlogin@example.com" };
|
||||||
|
let capturedStaff: StaffRow | null = null;
|
||||||
|
const app = buildApp(resolveStaffMiddleware, (c) => {
|
||||||
|
capturedStaff = c.get("staff");
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await app.request("/test");
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(capturedStaff!.name).toBe("firstlogin");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("auto-provision: returns 403 when no staff record and no Better-Auth user exists", async () => {
|
||||||
|
staffLookupResult = null;
|
||||||
|
userLookupResult = null;
|
||||||
|
const app = buildApp(resolveStaffMiddleware);
|
||||||
|
|
||||||
|
const res = await app.request("/test");
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
const body = await res.json();
|
||||||
|
expect(body.error).toMatch(/no staff record found for authenticated user/i);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ─── requireRole tests ────────────────────────────────────────────────────────
|
// ─── requireRole tests ────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -12,16 +12,6 @@ import {
|
|||||||
uuid,
|
uuid,
|
||||||
} from "drizzle-orm/pg-core";
|
} from "drizzle-orm/pg-core";
|
||||||
|
|
||||||
// ─── Shared types ───────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export type MedicalAlertSeverity = "low" | "medium" | "high";
|
|
||||||
|
|
||||||
export interface MedicalAlert {
|
|
||||||
type: string;
|
|
||||||
description: string;
|
|
||||||
severity: MedicalAlertSeverity;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Enums ────────────────────────────────────────────────────────────────────
|
// ─── Enums ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const appointmentStatusEnum = pgEnum("appointment_status", [
|
export const appointmentStatusEnum = pgEnum("appointment_status", [
|
||||||
@@ -156,12 +146,6 @@ export const pets = pgTable(
|
|||||||
photoKey: text("photo_key"),
|
photoKey: text("photo_key"),
|
||||||
photoUploadedAt: timestamp("photo_uploaded_at"),
|
photoUploadedAt: timestamp("photo_uploaded_at"),
|
||||||
image: text("image"),
|
image: text("image"),
|
||||||
// Extended profile fields
|
|
||||||
coatType: text("coat_type"),
|
|
||||||
temperamentScore: integer("temperament_score"),
|
|
||||||
temperamentFlags: jsonb("temperament_flags").$type<string[]>().default([]),
|
|
||||||
medicalAlerts: jsonb("medical_alerts").$type<MedicalAlert[]>().default([]),
|
|
||||||
preferredCuts: jsonb("preferred_cuts").$type<string[]>().default([]),
|
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -94,11 +94,6 @@ function pick<T>(arr: T[]): T {
|
|||||||
return arr[Math.floor(rand() * arr.length)]!;
|
return arr[Math.floor(rand() * arr.length)]!;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Return n distinct random elements from an array. */
|
|
||||||
function pickN<T>(arr: T[], n: number): T[] {
|
|
||||||
const shuffled = [...arr].sort(() => rand() - 0.5);
|
|
||||||
return shuffled.slice(0, n);
|
|
||||||
}
|
|
||||||
|
|
||||||
function randInt(min: number, max: number): number {
|
function randInt(min: number, max: number): number {
|
||||||
return Math.floor(rand() * (max - min + 1)) + min;
|
return Math.floor(rand() * (max - min + 1)) + min;
|
||||||
@@ -1105,7 +1100,7 @@ async function seed() {
|
|||||||
const groomer = pick(groomers);
|
const groomer = pick(groomers);
|
||||||
const bather = bathers.length > 0 && rand() < 0.6 ? pick(bathers) : null;
|
const bather = bathers.length > 0 && rand() < 0.6 ? pick(bathers) : null;
|
||||||
|
|
||||||
let startTime = randDate(appointmentsBackDate, now);
|
const startTime = randDate(appointmentsBackDate, now);
|
||||||
startTime.setHours(randInt(8, 16), pick([0, 15, 30, 45]), 0, 0);
|
startTime.setHours(randInt(8, 16), pick([0, 15, 30, 45]), 0, 0);
|
||||||
const endTime = new Date(startTime.getTime() + svc.dur * 60 * 1000);
|
const endTime = new Date(startTime.getTime() + svc.dur * 60 * 1000);
|
||||||
const effectivePrice = svc.price;
|
const effectivePrice = svc.price;
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ import { searchRouter } from "./routes/search.js";
|
|||||||
import { getObject } from "./lib/s3.js";
|
import { getObject } from "./lib/s3.js";
|
||||||
import { calendarRouter } from "./routes/calendar.js";
|
import { calendarRouter } from "./routes/calendar.js";
|
||||||
import { setupRouter } from "./routes/setup.js";
|
import { setupRouter } from "./routes/setup.js";
|
||||||
import { getDb, businessSettings, eq, staff } from "./db";
|
import { getDb, businessSettings, eq, staff } from "./db/index.js";
|
||||||
import { authMiddleware } from "./middleware/auth.js";
|
import { authMiddleware } from "./middleware/auth.js";
|
||||||
import { resolveStaffMiddleware, requireRole, requireRoleOrSuperUser, requireSuperUser } from "./middleware/rbac.js";
|
import { resolveStaffMiddleware, requireRole, requireRoleOrSuperUser, requireSuperUser } from "./middleware/rbac.js";
|
||||||
import { devRouter } from "./routes/dev.js";
|
import { devRouter } from "./routes/dev.js";
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { betterAuth } from "better-auth";
|
import { betterAuth } from "better-auth";
|
||||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||||
import { genericOAuth } from "better-auth/plugins";
|
import { genericOAuth } from "better-auth/plugins";
|
||||||
import { getDb, authProviderConfig, eq } from "./db";
|
import { getDb, authProviderConfig, eq } from "../db/index.js";
|
||||||
import { decryptSecret } from "./db";
|
import { decryptSecret } from "../db/index.js";
|
||||||
import { sendEmail } from "../services/email.js";
|
import { sendEmail } from "../services/email.js";
|
||||||
|
|
||||||
const BETTER_AUTH_SECRET = process.env.BETTER_AUTH_SECRET;
|
const BETTER_AUTH_SECRET = process.env.BETTER_AUTH_SECRET;
|
||||||
@@ -97,6 +97,9 @@ export async function initAuth(): Promise<void> {
|
|||||||
window: 10,
|
window: 10,
|
||||||
storage: "memory",
|
storage: "memory",
|
||||||
customRules: {
|
customRules: {
|
||||||
|
"/sign-in/social": { max: 10, window: 60 },
|
||||||
|
"/sign-in/email": { max: 10, window: 60 },
|
||||||
|
"/sign-up/email": { max: 5, window: 60 },
|
||||||
"/get-session": false,
|
"/get-session": false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -247,6 +250,9 @@ export async function initAuth(): Promise<void> {
|
|||||||
window: 10,
|
window: 10,
|
||||||
storage: "memory",
|
storage: "memory",
|
||||||
customRules: {
|
customRules: {
|
||||||
|
"/sign-in/social": { max: 10, window: 60 },
|
||||||
|
"/sign-in/email": { max: 10, window: 60 },
|
||||||
|
"/sign-up/email": { max: 5, window: 60 },
|
||||||
"/get-session": false,
|
"/get-session": false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { MiddlewareHandler } from "hono";
|
import type { MiddlewareHandler } from "hono";
|
||||||
import { getDb, impersonationAuditLogs } from "../db";
|
import { getDb, impersonationAuditLogs } from "../db/index.js";
|
||||||
import type { PortalEnv } from "./portalSession.js";
|
import type { PortalEnv } from "./portalSession.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { MiddlewareHandler } from "hono";
|
import type { MiddlewareHandler } from "hono";
|
||||||
import { and, eq, getDb, impersonationSessions } from "../db";
|
import { and, eq, getDb, impersonationSessions } from "../db/index.js";
|
||||||
|
|
||||||
export interface PortalEnv {
|
export interface PortalEnv {
|
||||||
Variables: {
|
Variables: {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { MiddlewareHandler } from "hono";
|
import type { MiddlewareHandler } from "hono";
|
||||||
import { and, eq, getDb, sql, staff } from "../db";
|
import { and, eq, getDb, sql, staff, user } from "../db/index.js";
|
||||||
|
|
||||||
export type StaffRole = "groomer" | "receptionist" | "manager";
|
export type StaffRole = "groomer" | "receptionist" | "manager";
|
||||||
export type StaffRow = typeof staff.$inferSelect;
|
export type StaffRow = typeof staff.$inferSelect;
|
||||||
@@ -110,6 +110,30 @@ export const resolveStaffMiddleware: MiddlewareHandler<AppEnv> = async (
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Auto-provision: no staff record exists for this user at all, but a valid
|
||||||
|
// Better-Auth user session exists (jwt.sub = user.id from user table).
|
||||||
|
// Create a minimal groomer staff record on first login.
|
||||||
|
const [userRow] = await db
|
||||||
|
.select({ id: user.id, name: user.name, email: user.email })
|
||||||
|
.from(user)
|
||||||
|
.where(eq(user.id, jwt.sub))
|
||||||
|
.limit(1);
|
||||||
|
if (userRow) {
|
||||||
|
const [newStaff] = await db
|
||||||
|
.insert(staff)
|
||||||
|
.values({
|
||||||
|
name: userRow.name ?? jwt.email?.split("@")[0] ?? "Unknown",
|
||||||
|
email: userRow.email ?? jwt.email ?? "",
|
||||||
|
userId: jwt.sub,
|
||||||
|
role: "groomer",
|
||||||
|
isSuperUser: false,
|
||||||
|
active: true,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
c.set("staff", newStaff);
|
||||||
|
await next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
return c.json(
|
return c.json(
|
||||||
{ error: "Forbidden: no staff record found for authenticated user" },
|
{ error: "Forbidden: no staff record found for authenticated user" },
|
||||||
403
|
403
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { eq, getDb, staff, clients, pets, services } from "./db";
|
import { eq, getDb, staff, clients, pets, services } from "../../db/index.js";
|
||||||
|
|
||||||
export const adminSeedRouter = new Hono();
|
export const adminSeedRouter = new Hono();
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import {
|
|||||||
pets,
|
pets,
|
||||||
services,
|
services,
|
||||||
staff,
|
staff,
|
||||||
} from "../db";
|
} from "../db/index.js";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const appointmentGroupsRouter = new Hono<AppEnv>();
|
export const appointmentGroupsRouter = new Hono<AppEnv>();
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import {
|
|||||||
reminderLogs,
|
reminderLogs,
|
||||||
services,
|
services,
|
||||||
staff,
|
staff,
|
||||||
} from "../db";
|
} from "../db/index.js";
|
||||||
import { buildConfirmationEmail, sendEmail } from "../services/email.js";
|
import { buildConfirmationEmail, sendEmail } from "../services/email.js";
|
||||||
import { notifyWaitlistForAppointment } from "../services/waitlistNotify.js";
|
import { notifyWaitlistForAppointment } from "../services/waitlistNotify.js";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { eq, getDb, authProviderConfig, encryptSecret } from "../db";
|
import { eq, getDb, authProviderConfig, encryptSecret } from "../db/index.js";
|
||||||
import { requireSuperUser } from "../middleware/rbac.js";
|
import { requireSuperUser } from "../middleware/rbac.js";
|
||||||
import { reinitAuth } from "../lib/auth.js";
|
import { reinitAuth } from "../lib/auth.js";
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import {
|
|||||||
appointments,
|
appointments,
|
||||||
clients,
|
clients,
|
||||||
pets,
|
pets,
|
||||||
} from "../db";
|
} from "../db/index.js";
|
||||||
import {
|
import {
|
||||||
generateAvailableSlots,
|
generateAvailableSlots,
|
||||||
BUSINESS_START_HOUR,
|
BUSINESS_START_HOUR,
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import {
|
|||||||
pets,
|
pets,
|
||||||
services,
|
services,
|
||||||
staff,
|
staff,
|
||||||
} from "../db";
|
} from "../db/index.js";
|
||||||
|
|
||||||
export const calendarRouter = new Hono();
|
export const calendarRouter = new Hono();
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { and, eq, exists, getDb, or, clients, appointments } from "../db";
|
import { and, eq, exists, getDb, or, clients, appointments } from "../db/index.js";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const clientsRouter = new Hono<AppEnv>();
|
export const clientsRouter = new Hono<AppEnv>();
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { getDb, staff, clients, eq, sql } from "../db";
|
import { getDb, staff, clients, eq, sql } from "../db/index.js";
|
||||||
|
|
||||||
const devRouter = new Hono();
|
const devRouter = new Hono();
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { and, desc, eq, getDb, groomingVisitLogs, appointments, or } from "../db";
|
import { and, desc, eq, getDb, groomingVisitLogs, appointments, or } from "../db/index.js";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const groomingLogsRouter = new Hono<AppEnv>();
|
export const groomingLogsRouter = new Hono<AppEnv>();
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
impersonationAuditLogs,
|
impersonationAuditLogs,
|
||||||
clients,
|
clients,
|
||||||
desc,
|
desc,
|
||||||
} from "../db";
|
} from "../db/index.js";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const impersonationRouter = new Hono<AppEnv>();
|
export const impersonationRouter = new Hono<AppEnv>();
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
services,
|
services,
|
||||||
clients,
|
clients,
|
||||||
sql,
|
sql,
|
||||||
} from "../db";
|
} from "../db/index.js";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const invoicesRouter = new Hono<AppEnv>();
|
export const invoicesRouter = new Hono<AppEnv>();
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { and, eq, exists, getDb, or, pets, appointments } from "../db";
|
import { and, eq, exists, getDb, or, pets, appointments } from "../db/index.js";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
import {
|
import {
|
||||||
getPresignedUploadUrl,
|
getPresignedUploadUrl,
|
||||||
@@ -24,15 +24,6 @@ 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(),
|
||||||
coatType: z.string().max(100).optional(),
|
|
||||||
temperamentScore: z.number().int().min(1).max(5).optional(),
|
|
||||||
temperamentFlags: z.array(z.string().max(100)).max(20).optional(),
|
|
||||||
medicalAlerts: z.array(z.object({
|
|
||||||
type: z.string().max(100),
|
|
||||||
description: z.string().max(1000),
|
|
||||||
severity: z.enum(["low", "medium", "high"]),
|
|
||||||
})).max(50).optional(),
|
|
||||||
preferredCuts: z.array(z.string().max(200)).max(20).optional(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const updatePetSchema = createPetSchema.partial().omit({ clientId: true });
|
const updatePetSchema = createPetSchema.partial().omit({ clientId: true });
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { eq, inArray } from "../db";
|
import { eq, inArray } from "../db/index.js";
|
||||||
import { getDb, appointments, impersonationSessions, waitlistEntries, clients, pets, services, staff, invoices, invoiceLineItems } from "../db";
|
import { getDb, appointments, impersonationSessions, waitlistEntries, clients, pets, services, staff, invoices, invoiceLineItems } from "../db/index.js";
|
||||||
import { validatePortalSession } from "../middleware/portalSession.js";
|
import { validatePortalSession } from "../middleware/portalSession.js";
|
||||||
import { portalAudit } from "../middleware/portalAudit.js";
|
import { portalAudit } from "../middleware/portalAudit.js";
|
||||||
import type { PortalEnv } from "../middleware/portalSession.js";
|
import type { PortalEnv } from "../middleware/portalSession.js";
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
invoiceTipSplits,
|
invoiceTipSplits,
|
||||||
services,
|
services,
|
||||||
staff,
|
staff,
|
||||||
} from "../db";
|
} from "../db/index.js";
|
||||||
|
|
||||||
export const reportsRouter = new Hono();
|
export const reportsRouter = new Hono();
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { and, eq, getDb, clients, ilike, or, pets } from "../db";
|
import { and, eq, getDb, clients, ilike, or, pets } from "../db/index.js";
|
||||||
|
|
||||||
export const searchRouter = new Hono();
|
export const searchRouter = new Hono();
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { eq, getDb, services } from "../db";
|
import { eq, getDb, services } from "../db/index.js";
|
||||||
|
|
||||||
export const servicesRouter = new Hono();
|
export const servicesRouter = new Hono();
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { eq, getDb, businessSettings } from "../db";
|
import { eq, getDb, businessSettings } from "../db/index.js";
|
||||||
import { getPresignedUploadUrl, deleteObject, putObject, getObject } from "../lib/s3.js";
|
import { getPresignedUploadUrl, deleteObject, putObject, getObject } from "../lib/s3.js";
|
||||||
import { requireSuperUser } from "../middleware/rbac.js";
|
import { requireSuperUser } from "../middleware/rbac.js";
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { and, eq, getDb, sql, staff, businessSettings, authProviderConfig, encryptSecret } from "../db";
|
import { and, eq, getDb, sql, staff, businessSettings, authProviderConfig, encryptSecret } from "../db/index.js";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
const RATE_LIMIT_WINDOW_MS = 60_000;
|
const RATE_LIMIT_WINDOW_MS = 60_000;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { Hono } from "hono";
|
|||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { randomBytes } from "node:crypto";
|
import { randomBytes } from "node:crypto";
|
||||||
import { and, eq, getDb, ne, staff, appointments } from "../db";
|
import { and, eq, getDb, ne, staff, appointments } from "../db/index.js";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const staffRouter = new Hono<AppEnv>();
|
export const staffRouter = new Hono<AppEnv>();
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import Stripe from "stripe";
|
import Stripe from "stripe";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { eq, getDb, invoices } from "../db";
|
import { eq, getDb, invoices } from "../db/index.js";
|
||||||
import { getStripeClient } from "../services/payment.js";
|
import { getStripeClient } from "../services/payment.js";
|
||||||
|
|
||||||
export const webhooksRouter = new Hono();
|
export const webhooksRouter = new Hono();
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
clients,
|
clients,
|
||||||
pets,
|
pets,
|
||||||
services,
|
services,
|
||||||
} from "../db";
|
} from "../db/index.js";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const waitlistRouter = new Hono<AppEnv>();
|
export const waitlistRouter = new Hono<AppEnv>();
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import Stripe from "stripe";
|
import Stripe from "stripe";
|
||||||
import { getDb, clients, eq, inArray, invoices } from "../db";
|
import { getDb, clients, eq, inArray, invoices } from "../db/index.js";
|
||||||
|
|
||||||
let _stripe: Stripe | null | undefined;
|
let _stripe: Stripe | null | undefined;
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import {
|
|||||||
staff,
|
staff,
|
||||||
reminderLogs,
|
reminderLogs,
|
||||||
session,
|
session,
|
||||||
} from "../db";
|
} from "../db/index.js";
|
||||||
import {
|
import {
|
||||||
buildReminderEmail,
|
buildReminderEmail,
|
||||||
sendEmail,
|
sendEmail,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { and, eq, getDb, waitlistEntries, clients, pets, services } from "../db";
|
import { and, eq, getDb, waitlistEntries, clients, pets, services } from "../db/index.js";
|
||||||
import { buildWaitlistNotificationEmail, sendEmail } from "./email.js";
|
import { buildWaitlistNotificationEmail, sendEmail } from "./email.js";
|
||||||
|
|
||||||
export async function notifyWaitlistForAppointment(
|
export async function notifyWaitlistForAppointment(
|
||||||
|
|||||||
@@ -42,23 +42,10 @@ export interface Pet {
|
|||||||
customFields: Record<string, string>;
|
customFields: Record<string, string>;
|
||||||
photoKey?: string;
|
photoKey?: string;
|
||||||
photoUploadedAt?: string;
|
photoUploadedAt?: string;
|
||||||
coatType?: string | null;
|
|
||||||
temperamentScore?: number | null;
|
|
||||||
temperamentFlags?: string[];
|
|
||||||
medicalAlerts?: MedicalAlert[];
|
|
||||||
preferredCuts?: string[];
|
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type MedicalAlertSeverity = "low" | "medium" | "high";
|
|
||||||
|
|
||||||
export interface MedicalAlert {
|
|
||||||
type: string;
|
|
||||||
description: string;
|
|
||||||
severity: MedicalAlertSeverity;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GroomingVisitLog {
|
export interface GroomingVisitLog {
|
||||||
id: string;
|
id: string;
|
||||||
petId: string;
|
petId: string;
|
||||||
|
|||||||
@@ -1,3 +1,2 @@
|
|||||||
packages:
|
packages:
|
||||||
- "apps/*"
|
- "apps/*"
|
||||||
- "packages/*"
|
|
||||||
|
|||||||
Reference in New Issue
Block a user