Compare commits
14 Commits
pr-44
..
7d27fb85c6
| Author | SHA1 | Date | |
|---|---|---|---|
| 7d27fb85c6 | |||
| 48d0e687b9 | |||
| 61db8eb661 | |||
| 7a5a99e106 | |||
| 9c5e470737 | |||
| f1258023ac | |||
| faf7def77d | |||
| 539ef21d89 | |||
| 4f981bbebd | |||
| d8f2135506 | |||
| d9ee14b17e | |||
| 9ed28f8bab | |||
| abac9dfe6c | |||
| 4d7baec939 |
@@ -1,11 +0,0 @@
|
|||||||
node_modules
|
|
||||||
.git
|
|
||||||
*.md
|
|
||||||
.github
|
|
||||||
apps/e2e
|
|
||||||
apps/web/dist
|
|
||||||
apps/api/dist
|
|
||||||
packages/db/dist
|
|
||||||
packages/types/dist
|
|
||||||
.turbo
|
|
||||||
screenshots/
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
root = true
|
|
||||||
|
|
||||||
[*]
|
|
||||||
indent_style = space
|
|
||||||
indent_size = 2
|
|
||||||
end_of_line = lf
|
|
||||||
charset = utf-8
|
|
||||||
trim_trailing_whitespace = true
|
|
||||||
insert_final_newline = true
|
|
||||||
|
|
||||||
[*.md]
|
|
||||||
trim_trailing_whitespace = false
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
# Groom Book — Environment Variables
|
|
||||||
# Copy this file to .env and adjust values for your deployment.
|
|
||||||
|
|
||||||
# ── Database ──────────────────────────────────────────────────────────────────
|
|
||||||
DATABASE_URL=postgres://groombook:groombook@postgres:5432/groombook
|
|
||||||
|
|
||||||
# ── Authentication ────────────────────────────────────────────────────────────
|
|
||||||
# Set AUTH_DISABLED=true to skip OIDC validation (useful for local dev/Docker).
|
|
||||||
# In production, configure an Authentik instance and set these values.
|
|
||||||
AUTH_DISABLED=false
|
|
||||||
OIDC_ISSUER=https://authentik.example.com
|
|
||||||
OIDC_AUDIENCE=groombook
|
|
||||||
|
|
||||||
# ── Setup Wizard ─────────────────────────────────────────────────────────────
|
|
||||||
# When SKIP_OOBE=true, the setup wizard is bypassed regardless of whether a
|
|
||||||
# super user exists in the database. Useful in dev/test environments where the
|
|
||||||
# database has data but the setup wizard would otherwise block access.
|
|
||||||
SKIP_OOBE=false
|
|
||||||
|
|
||||||
# ── API ───────────────────────────────────────────────────────────────────────
|
|
||||||
PORT=3000
|
|
||||||
CORS_ORIGIN=http://localhost:8080
|
|
||||||
|
|
||||||
# ── Email Reminders (optional) ────────────────────────────────────────────────
|
|
||||||
# Leave SMTP_HOST unset to disable email notifications entirely.
|
|
||||||
# When configured, appointment confirmation and reminder emails are sent via SMTP.
|
|
||||||
SMTP_HOST=smtp.example.com
|
|
||||||
SMTP_PORT=587
|
|
||||||
SMTP_SECURE=false
|
|
||||||
SMTP_USER=user@example.com
|
|
||||||
SMTP_PASS=password
|
|
||||||
SMTP_FROM="Groom Book <noreply@example.com>"
|
|
||||||
|
|
||||||
# Hours before appointment to send reminder emails (defaults: 24 and 2)
|
|
||||||
REMINDER_HOURS_EARLY=24
|
|
||||||
REMINDER_HOURS_LATE=2
|
|
||||||
+6
-68
@@ -25,7 +25,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 20
|
||||||
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: 22
|
node-version: 20
|
||||||
cache: pnpm
|
cache: pnpm
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
@@ -58,35 +58,13 @@ jobs:
|
|||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: pnpm test
|
run: pnpm test
|
||||||
|
|
||||||
build:
|
docker:
|
||||||
name: Build
|
name: Build & Push Docker Image
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [lint-typecheck, test]
|
needs: [lint-typecheck, test]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v4
|
|
||||||
with:
|
|
||||||
version: '9.15.4'
|
|
||||||
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: 22
|
|
||||||
cache: pnpm
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: pnpm install --frozen-lockfile
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
run: pnpm build
|
|
||||||
|
|
||||||
docker:
|
|
||||||
name: Build & Push Docker Images
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [build]
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Generate image tag
|
- name: Generate image tag
|
||||||
id: version
|
id: version
|
||||||
run: |
|
run: |
|
||||||
@@ -106,56 +84,16 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
registry: git.farh.net
|
registry: git.farh.net
|
||||||
username: ${{ gitea.actor }}
|
username: ${{ gitea.actor }}
|
||||||
password: ${{ gitea.token }}
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|
||||||
- name: Build and push API image
|
- name: Build and push API image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: Dockerfile
|
file: Dockerfile
|
||||||
target: runner
|
|
||||||
push: true
|
push: true
|
||||||
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
|
|
||||||
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
|
|
||||||
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
|
|
||||||
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
|
|
||||||
@@ -1,257 +0,0 @@
|
|||||||
name: CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main, dev]
|
|
||||||
pull_request:
|
|
||||||
branches: [main, dev]
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
ref:
|
|
||||||
description: "Branch or ref to run CI against"
|
|
||||||
required: false
|
|
||||||
default: "main"
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
lint-typecheck:
|
|
||||||
name: Lint & Typecheck
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v4
|
|
||||||
with:
|
|
||||||
version: '9.15.4'
|
|
||||||
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: 22
|
|
||||||
cache: pnpm
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: pnpm install --frozen-lockfile
|
|
||||||
|
|
||||||
- name: Typecheck
|
|
||||||
run: pnpm --filter @groombook/api typecheck
|
|
||||||
|
|
||||||
- name: Lint
|
|
||||||
run: pnpm --filter @groombook/api lint
|
|
||||||
|
|
||||||
test:
|
|
||||||
name: Test
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v4
|
|
||||||
with:
|
|
||||||
version: '9.15.4'
|
|
||||||
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: 22
|
|
||||||
cache: pnpm
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: pnpm install --frozen-lockfile
|
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
run: pnpm --filter @groombook/api test
|
|
||||||
|
|
||||||
build:
|
|
||||||
name: Build
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [lint-typecheck, test]
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v4
|
|
||||||
with:
|
|
||||||
version: '9.15.4'
|
|
||||||
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: 22
|
|
||||||
cache: pnpm
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: pnpm install --frozen-lockfile
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
run: pnpm --filter @groombook/api build
|
|
||||||
|
|
||||||
docker:
|
|
||||||
name: Build & Push Docker Images
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [build]
|
|
||||||
outputs:
|
|
||||||
tag: ${{ steps.version.outputs.tag }}
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
packages: write
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Generate image tag
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
|
||||||
TAG="pr-${{ github.event.pull_request.number }}-${GITHUB_SHA::7}"
|
|
||||||
else
|
|
||||||
TAG="$(date -u +%Y.%m.%d)-${GITHUB_SHA::7}"
|
|
||||||
fi
|
|
||||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "Image tag: $TAG"
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v3
|
|
||||||
|
|
||||||
- name: Log in to GitHub Container Registry
|
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{ github.actor }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Build and push API image
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: Dockerfile
|
|
||||||
target: runner
|
|
||||||
push: true
|
|
||||||
tags: |
|
|
||||||
ghcr.io/groombook/api:${{ steps.version.outputs.tag }}
|
|
||||||
${{ github.ref == 'refs/heads/main' && 'ghcr.io/groombook/api:latest' || '' }}
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
||||||
|
|
||||||
- name: Build and push Migrate image
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: Dockerfile
|
|
||||||
target: migrate
|
|
||||||
push: true
|
|
||||||
tags: |
|
|
||||||
ghcr.io/groombook/migrate:${{ steps.version.outputs.tag }}
|
|
||||||
${{ github.ref == 'refs/heads/main' && 'ghcr.io/groombook/migrate:latest' || '' }}
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
||||||
|
|
||||||
- name: Build and push Seed image
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: Dockerfile
|
|
||||||
target: seed
|
|
||||||
push: true
|
|
||||||
tags: |
|
|
||||||
ghcr.io/groombook/seed:${{ steps.version.outputs.tag }}
|
|
||||||
${{ github.ref == 'refs/heads/main' && 'ghcr.io/groombook/seed:latest' || '' }}
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
||||||
|
|
||||||
- name: Build and push Reset image
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: Dockerfile
|
|
||||||
target: reset
|
|
||||||
push: true
|
|
||||||
tags: |
|
|
||||||
ghcr.io/groombook/reset:${{ steps.version.outputs.tag }}
|
|
||||||
${{ github.ref == 'refs/heads/main' && 'ghcr.io/groombook/reset:latest' || '' }}
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
||||||
|
|
||||||
cd:
|
|
||||||
name: Update Infra Image Tags
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [docker]
|
|
||||||
if: (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dev') && github.event_name == 'push'
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
pull-requests: write
|
|
||||||
steps:
|
|
||||||
- name: Generate infra repo token
|
|
||||||
id: infra-token
|
|
||||||
uses: tibdex/github-app-token@v2
|
|
||||||
with:
|
|
||||||
app_id: ${{ vars.GH_APP_ID }}
|
|
||||||
private_key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
|
||||||
|
|
||||||
- name: Clone groombook/infra
|
|
||||||
run: |
|
|
||||||
git clone https://x-access-token:${{ steps.infra-token.outputs.token }}@github.com/groombook/infra.git /tmp/infra
|
|
||||||
|
|
||||||
- name: Install yq
|
|
||||||
run: |
|
|
||||||
sudo wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64
|
|
||||||
sudo chmod +x /usr/local/bin/yq
|
|
||||||
|
|
||||||
- name: Update dev overlay image tags
|
|
||||||
env:
|
|
||||||
TAG: ${{ needs.docker.outputs.tag }}
|
|
||||||
SHA: ${{ github.sha }}
|
|
||||||
run: |
|
|
||||||
if [ -z "$TAG" ]; then
|
|
||||||
TAG="$(date -u +%Y.%m.%d)-${SHA::7}"
|
|
||||||
fi
|
|
||||||
export SHORT_SHA="${SHA::7}"
|
|
||||||
echo "Updating dev overlay image tags to: $TAG"
|
|
||||||
echo "Updating migration/seed Job names with SHA: $SHORT_SHA"
|
|
||||||
cd /tmp/infra
|
|
||||||
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/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/reset")).newTag = env(TAG)' "$DEV_KUST"
|
|
||||||
|
|
||||||
MIGRATE_JOB="apps/base/migrate-job.yaml"
|
|
||||||
if [ -f "$MIGRATE_JOB" ]; then
|
|
||||||
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 '.spec.ttlSecondsAfterFinished = (.spec.ttlSecondsAfterFinished // 86400)' "$MIGRATE_JOB"
|
|
||||||
fi
|
|
||||||
|
|
||||||
SEED_JOB="apps/base/seed-job.yaml"
|
|
||||||
if [ -f "$SEED_JOB" ]; then
|
|
||||||
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 '.spec.ttlSecondsAfterFinished = (.spec.ttlSecondsAfterFinished // 86400)' "$SEED_JOB"
|
|
||||||
fi
|
|
||||||
|
|
||||||
git -C /tmp/infra diff --stat
|
|
||||||
|
|
||||||
- name: Create PR on groombook/infra
|
|
||||||
env:
|
|
||||||
TAG: ${{ needs.docker.outputs.tag }}
|
|
||||||
GH_TOKEN: ${{ steps.infra-token.outputs.token }}
|
|
||||||
run: |
|
|
||||||
if [ -z "$TAG" ]; then
|
|
||||||
TAG="$(date -u +%Y.%m.%d)-${GITHUB_SHA::7}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
cd /tmp/infra
|
|
||||||
git config user.name "groombook-engineer[bot]"
|
|
||||||
git config user.email "3141748+groombook-engineer[bot]@users.noreply.github.com"
|
|
||||||
git checkout -b "chore/update-image-tags-${TAG}"
|
|
||||||
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 push -u origin "chore/update-image-tags-${TAG}"
|
|
||||||
|
|
||||||
EXISTING_PR=$(gh pr list --repo groombook/infra --head "chore/update-image-tags-${TAG}" --state open --json number -q '.[0].number' || true)
|
|
||||||
if [ -n "$EXISTING_PR" ]; then
|
|
||||||
echo "PR #$EXISTING_PR already exists for this tag, merging existing PR"
|
|
||||||
gh pr merge "$EXISTING_PR" --repo groombook/infra --merge
|
|
||||||
else
|
|
||||||
PR_URL=$(gh pr create \
|
|
||||||
--repo groombook/infra \
|
|
||||||
--base main \
|
|
||||||
--head "chore/update-image-tags-${TAG}" \
|
|
||||||
--title "chore: deploy ${TAG} to dev" \
|
|
||||||
--body "[GRO-178](/GRO/issues/GRO-178) — automated image tag update from main merge")
|
|
||||||
gh pr merge "$PR_URL" --merge
|
|
||||||
fi
|
|
||||||
+2
-19
@@ -1,23 +1,6 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
dist/
|
dist/
|
||||||
.env
|
|
||||||
.env.local
|
|
||||||
*.local
|
|
||||||
.DS_Store
|
.DS_Store
|
||||||
*.log
|
*.log
|
||||||
.turbo/
|
.env
|
||||||
coverage/
|
.env.local
|
||||||
minimax-output/
|
|
||||||
|
|
||||||
# Agent runtime artifacts — never commit
|
|
||||||
.gh-token
|
|
||||||
*.gh-token
|
|
||||||
.config/gh/
|
|
||||||
**/.config/gh/
|
|
||||||
infra-repo
|
|
||||||
infra-repo/
|
|
||||||
**/instructions/.gh-token
|
|
||||||
**/AGENT_HOME/**
|
|
||||||
$AGENT_HOME/**
|
|
||||||
.claude/
|
|
||||||
.codex/
|
|
||||||
|
|||||||
+28
-13
@@ -1,38 +1,53 @@
|
|||||||
FROM node:22-alpine AS base
|
FROM node:20-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
|
||||||
|
|
||||||
|
# Install deps
|
||||||
FROM base AS deps
|
FROM base AS deps
|
||||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./
|
||||||
COPY apps/api/package.json apps/api/
|
COPY packages/db/package.json packages/db/
|
||||||
|
COPY packages/types/package.json packages/types/
|
||||||
RUN pnpm install --frozen-lockfile
|
RUN pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
# Build
|
||||||
FROM deps AS builder
|
FROM deps AS builder
|
||||||
RUN mkdir -p /home/node/.cache/node/corepack
|
RUN mkdir -p /home/node/.cache/node/corepack
|
||||||
COPY apps/api/ apps/api/
|
COPY packages/ packages/
|
||||||
RUN pnpm --filter @groombook/api build
|
COPY src/ src/
|
||||||
|
COPY tsconfig.json ./
|
||||||
|
RUN pnpm --filter @groombook/types build && \
|
||||||
|
pnpm --filter @groombook/db build && \
|
||||||
|
pnpm build
|
||||||
|
|
||||||
FROM node:22-alpine AS runner
|
# Runtime
|
||||||
|
FROM node:20-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
|
||||||
|
|
||||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./
|
||||||
COPY --from=builder /app/apps/api/package.json apps/api/
|
COPY --from=builder /app/package.json ./
|
||||||
COPY --from=builder /app/apps/api/dist apps/api/dist
|
COPY --from=builder /app/dist dist/
|
||||||
|
COPY --from=builder /app/packages/db/package.json packages/db/
|
||||||
|
COPY --from=builder /app/packages/db/dist packages/db/dist
|
||||||
|
COPY --from=builder /app/packages/types/package.json packages/types/
|
||||||
|
COPY --from=builder /app/packages/types/dist packages/types/dist
|
||||||
RUN pnpm install --frozen-lockfile --prod
|
RUN pnpm install --frozen-lockfile --prod
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
RUN apk add --no-cache curl
|
RUN apk add --no-cache curl
|
||||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||||
CMD curl -f http://localhost:3000/health || exit 1
|
CMD curl -f http://localhost:3000/health || exit 1
|
||||||
CMD ["node", "apps/api/dist/index.js"]
|
CMD ["node", "dist/index.js"]
|
||||||
|
|
||||||
|
# Migrate stage — runs drizzle-kit migrate against the database
|
||||||
FROM builder AS migrate
|
FROM builder AS migrate
|
||||||
CMD ["pnpm", "--filter", "@groombook/api", "db:migrate"]
|
CMD ["pnpm", "db:migrate"]
|
||||||
|
|
||||||
|
# Seed stage — populates the database with test data
|
||||||
FROM builder AS seed
|
FROM builder AS seed
|
||||||
CMD ["pnpm", "--filter", "@groombook/api", "db:seed"]
|
CMD ["pnpm", "db:seed"]
|
||||||
|
|
||||||
|
# Reset stage — drops all tables, re-runs migrations, and re-seeds
|
||||||
FROM builder AS reset
|
FROM builder AS reset
|
||||||
CMD ["pnpm", "--filter", "@groombook/api", "db:reset"]
|
CMD ["pnpm", "db:reset"]
|
||||||
@@ -1,38 +1,2 @@
|
|||||||
# GroomBook API
|
# api
|
||||||
|
GroomBook API service (extracted from groombook/app monorepo)
|
||||||
GroomBook API service — extracted from the [groombook/app](https://github.com/groombook/app) monorepo.
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
|
|
||||||
This repository contains the GroomBook API service, including:
|
|
||||||
- REST API endpoints
|
|
||||||
- Database schema and migrations (via Drizzle ORM)
|
|
||||||
- Authentication (via Better Auth)
|
|
||||||
- Background job handlers
|
|
||||||
|
|
||||||
## Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
apps/api/ # API service source
|
|
||||||
packages/db/ # Database schema, migrations, and utilities
|
|
||||||
packages/types/ # Shared TypeScript types
|
|
||||||
```
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pnpm install
|
|
||||||
cp .env.example .env # Fill in required environment variables
|
|
||||||
pnpm --filter @groombook/api dev
|
|
||||||
```
|
|
||||||
|
|
||||||
## Docker
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker build -t ghcr.io/groombook/api:latest .
|
|
||||||
docker run -p 3000:3000 ghcr.io/groombook/api:latest
|
|
||||||
```
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
AGPL-3.0-only
|
|
||||||
|
|||||||
@@ -28,6 +28,12 @@ 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 | Email+password login (UAT) | POST /api/auth/sign-in/email with uat-super@groombook.dev + SEED_UAT_SUPER_PASSWORD | 200 OK, session cookie returned |
|
||||||
|
| TC-API-1.5 | Email+password login — groomer | POST /api/auth/sign-in/email with uat-groomer@groombook.dev + SEED_UAT_GROOMER_PASSWORD | 200 OK, session cookie returned |
|
||||||
|
| TC-API-1.6 | Email+password login — customer | POST /api/auth/sign-in/email with uat-customer@groombook.dev + SEED_UAT_CUSTOMER_PASSWORD | 200 OK, session cookie returned |
|
||||||
|
| TC-API-1.7 | Email+password login — tester | POST /api/auth/sign-in/email with uat-tester@groombook.dev + SEED_UAT_TESTER_PASSWORD | 200 OK, session cookie returned |
|
||||||
|
| TC-API-1.8 | Email+password — invalid password | POST /api/auth/sign-in/email with wrong password | 400 Bad Request, error returned |
|
||||||
|
| TC-API-1.9 | Email+password — unknown user | POST /api/auth/sign-in/email with non-existent email | 400 Bad Request, error returned |
|
||||||
|
|
||||||
### 4.2 Client Management
|
### 4.2 Client Management
|
||||||
|
|
||||||
@@ -177,6 +183,18 @@ GroomBook API is a Hono-based REST service (TypeScript/Node.js) powering the pet
|
|||||||
| TC-API-14.4 | Update group notes | PATCH /api/appointment-groups/{id} with notes | 200 OK, notes updated |
|
| TC-API-14.4 | Update group notes | PATCH /api/appointment-groups/{id} with notes | 200 OK, notes updated |
|
||||||
| TC-API-14.5 | Cancel group | DELETE /api/appointment-groups/{id} | 200 OK, all appointments cancelled |
|
| TC-API-14.5 | Cancel group | DELETE /api/appointment-groups/{id} | 200 OK, all appointments cancelled |
|
||||||
|
|
||||||
|
### 4.15 Buffer Rules
|
||||||
|
|
||||||
|
| # | Scenario | Steps | Expected |
|
||||||
|
|---|----------|-------|----------|
|
||||||
|
| TC-API-15.1 | List buffer rules | GET /api/admin/buffer-rules | 200 OK, list of active buffer rules returned |
|
||||||
|
| TC-API-15.2 | Create buffer rule | POST /api/admin/buffer-rules with service, species, sizeCategory, bufferMinutes | 201 Created, buffer rule created |
|
||||||
|
| TC-API-15.3 | Update buffer rule | PATCH /api/admin/buffer-rules/{id} with updated bufferMinutes | 200 OK, buffer rule updated |
|
||||||
|
| TC-API-15.4 | Delete buffer rule | DELETE /api/admin/buffer-rules/{id} | 200 OK, buffer rule removed |
|
||||||
|
| TC-API-15.5 | Reject invalid bufferMinutes | POST /api/admin/buffer-rules with bufferMinutes: -5 | 400 Bad Request, invalid bufferMinutes rejected |
|
||||||
|
| TC-API-15.6 | Reject missing required fields | POST /api/admin/buffer-rules with service only | 400 Bad Request, species and sizeCategory required |
|
||||||
|
| TC-API-15.7 | Booking uses buffer | Book appointment for pet with sizeCategory; verify duration reflects buffer | 201 Created, appointment duration includes buffer time |
|
||||||
|
|
||||||
## Pass/Fail Criteria
|
## Pass/Fail Criteria
|
||||||
|
|
||||||
**Pass:**
|
**Pass:**
|
||||||
|
|||||||
@@ -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": {} }
|
|
||||||
}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "@groombook/api",
|
|
||||||
"version": "0.0.1",
|
|
||||||
"private": true,
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"dev": "tsx watch src/index.ts",
|
|
||||||
"build": "tsc",
|
|
||||||
"start": "node dist/index.js",
|
|
||||||
"lint": "eslint src --ext .ts",
|
|
||||||
"typecheck": "tsc --noEmit",
|
|
||||||
"test": "vitest run",
|
|
||||||
"db:generate": "drizzle-kit generate",
|
|
||||||
"db:migrate": "drizzle-kit migrate",
|
|
||||||
"db:seed": "tsx src/db/seed.ts",
|
|
||||||
"db:reset": "tsx src/db/reset.ts && drizzle-kit migrate && tsx src/db/seed.ts",
|
|
||||||
"db:studio": "drizzle-kit studio"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@aws-sdk/client-s3": "^3.800.0",
|
|
||||||
"@aws-sdk/s3-request-presigner": "^3.800.0",
|
|
||||||
"@hono/node-server": "^1.13.7",
|
|
||||||
"@hono/zod-validator": "^0.7.6",
|
|
||||||
"better-auth": "^1.5.6",
|
|
||||||
"drizzle-orm": "^0.38.4",
|
|
||||||
"hono": "^4.6.17",
|
|
||||||
"node-cron": "^3.0.3",
|
|
||||||
"nodemailer": "^6.9.16",
|
|
||||||
"postgres": "^3.4.5",
|
|
||||||
"stripe": "^22.0.0",
|
|
||||||
"telnyx": "^1.23.0",
|
|
||||||
"zod": "^4.3.6"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/node": "^22.10.7",
|
|
||||||
"@types/node-cron": "^3.0.11",
|
|
||||||
"@types/nodemailer": "^6.4.17",
|
|
||||||
"@vitest/coverage-v8": "^3.2.4",
|
|
||||||
"drizzle-kit": "^0.30.4",
|
|
||||||
"eslint": "^9.18.0",
|
|
||||||
"tsx": "^4.19.2",
|
|
||||||
"typescript": "^5.7.3",
|
|
||||||
"typescript-eslint": "^8.20.0",
|
|
||||||
"vitest": "^3.2.4"
|
|
||||||
},
|
|
||||||
"license": "AGPL-3.0-only"
|
|
||||||
}
|
|
||||||
@@ -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 = "550e8400-e29b-41d4-a716-446655440001";
|
|
||||||
const PET_ID = "660e8400-e29b-41d4-a716-446655440002";
|
|
||||||
|
|
||||||
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: vi.fn(),
|
|
||||||
eq: vi.fn(),
|
|
||||||
exists: vi.fn(),
|
|
||||||
or: vi.fn(),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// ─── 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"]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+35
-1
@@ -3,6 +3,40 @@
|
|||||||
"version": "0.0.1",
|
"version": "0.0.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"packageManager": "pnpm@9.15.4",
|
"scripts": {
|
||||||
|
"dev": "tsx watch src/index.ts",
|
||||||
|
"build": "tsc",
|
||||||
|
"start": "node dist/index.js",
|
||||||
|
"lint": "eslint src --ext .ts",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"test": "vitest run"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@aws-sdk/client-s3": "^3.800.0",
|
||||||
|
"@aws-sdk/s3-request-presigner": "^3.800.0",
|
||||||
|
"@groombook/db": "workspace:*",
|
||||||
|
"@groombook/types": "workspace:*",
|
||||||
|
"@hono/node-server": "^1.13.7",
|
||||||
|
"@hono/zod-validator": "^0.7.6",
|
||||||
|
"better-auth": "^1.5.6",
|
||||||
|
"hono": "^4.6.17",
|
||||||
|
"node-cron": "^3.0.3",
|
||||||
|
"nodemailer": "^6.9.16",
|
||||||
|
"stripe": "^22.0.0",
|
||||||
|
"telnyx": "^1.23.0",
|
||||||
|
|
||||||
|
"zod": "^4.3.6"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.10.7",
|
||||||
|
"@types/node-cron": "^3.0.11",
|
||||||
|
"@types/nodemailer": "^6.4.17",
|
||||||
|
"@vitest/coverage-v8": "^3.2.4",
|
||||||
|
"eslint": "^9.18.0",
|
||||||
|
"tsx": "^4.19.2",
|
||||||
|
"typescript": "^5.7.3",
|
||||||
|
"typescript-eslint": "^8.20.0",
|
||||||
|
"vitest": "^3.2.4"
|
||||||
|
},
|
||||||
"license": "AGPL-3.0-only"
|
"license": "AGPL-3.0-only"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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: {
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
-- Migration: 0030_messaging.sql
|
||||||
|
-- Messaging schema: conversations, messages, attachments, consent events + business messaging settings
|
||||||
|
|
||||||
|
-- ─── Enums ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CREATE TYPE "messaging_channel" AS ENUM ('sms', 'mms');
|
||||||
|
CREATE TYPE "message_direction" AS ENUM ('inbound', 'outbound');
|
||||||
|
CREATE TYPE "message_status" AS ENUM ('queued', 'sent', 'delivered', 'failed', 'received');
|
||||||
|
CREATE TYPE "message_consent_kind" AS ENUM ('opt_in', 'opt_out', 'help');
|
||||||
|
|
||||||
|
-- ─── Tables ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CREATE TABLE "conversations" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"business_id" uuid NOT NULL,
|
||||||
|
"client_id" uuid NOT NULL REFERENCES "clients"("id") ON DELETE CASCADE,
|
||||||
|
"channel" "messaging_channel" NOT NULL,
|
||||||
|
"external_number" text NOT NULL,
|
||||||
|
"business_number" text NOT NULL,
|
||||||
|
"last_message_at" timestamp,
|
||||||
|
"status" text NOT NULL DEFAULT 'active',
|
||||||
|
"created_at" timestamp NOT NULL DEFAULT now(),
|
||||||
|
"updated_at" timestamp NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "idx_conversations_business_id_last_message_at" ON "conversations"("business_id", "last_message_at" DESC);
|
||||||
|
CREATE UNIQUE INDEX "uq_conversations_business_client_number" ON "conversations"("business_id", "client_id", "business_number");
|
||||||
|
|
||||||
|
CREATE TABLE "messages" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"conversation_id" uuid NOT NULL REFERENCES "conversations"("id") ON DELETE CASCADE,
|
||||||
|
"direction" "message_direction" NOT NULL,
|
||||||
|
"body" text,
|
||||||
|
"status" "message_status" NOT NULL DEFAULT 'queued',
|
||||||
|
"provider_message_id" text,
|
||||||
|
"error_code" text,
|
||||||
|
"error_message" text,
|
||||||
|
"sent_by_staff_id" uuid REFERENCES "staff"("id") ON DELETE SET NULL,
|
||||||
|
"created_at" timestamp NOT NULL DEFAULT now(),
|
||||||
|
"delivered_at" timestamp,
|
||||||
|
"read_by_client_at" timestamp
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "idx_messages_conversation_id_created_at" ON "messages"("conversation_id", "created_at" DESC);
|
||||||
|
CREATE UNIQUE INDEX "uq_messages_provider_message_id" ON "messages"("provider_message_id");
|
||||||
|
|
||||||
|
CREATE TABLE "message_attachments" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"message_id" uuid NOT NULL REFERENCES "messages"("id") ON DELETE CASCADE,
|
||||||
|
"content_type" text NOT NULL,
|
||||||
|
"url" text NOT NULL,
|
||||||
|
"size" integer NOT NULL,
|
||||||
|
"provider_media_id" text
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "idx_message_attachments_message_id" ON "message_attachments"("message_id");
|
||||||
|
|
||||||
|
CREATE TABLE "message_consent_events" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"client_id" uuid NOT NULL REFERENCES "clients"("id") ON DELETE CASCADE,
|
||||||
|
"business_id" uuid NOT NULL,
|
||||||
|
"kind" "message_consent_kind" NOT NULL,
|
||||||
|
"source" text,
|
||||||
|
"created_at" timestamp NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "idx_message_consent_events_client_id" ON "message_consent_events"("client_id");
|
||||||
|
|
||||||
|
-- ─── Business Settings extensions ────────────────────────────────────────────
|
||||||
|
|
||||||
|
ALTER TABLE "business_settings" ADD COLUMN "messaging_phone_number" text;
|
||||||
|
ALTER TABLE "business_settings" ADD COLUMN "telnyx_messaging_profile_id" text;
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
-- Migration: 0031_buffer_rules.sql
|
||||||
|
-- Buffer rules CRUD: pet size/coat enums, bufferRules table, services.defaultBufferMinutes
|
||||||
|
|
||||||
|
-- ─── Enums ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CREATE TYPE "pet_size_category" AS ENUM ('small', 'medium', 'large', 'xlarge');
|
||||||
|
CREATE TYPE "coat_type" AS ENUM ('smooth', 'double', 'wire', 'curly', 'long', 'hairless');
|
||||||
|
|
||||||
|
-- ─── Alter pets columns to use new enums ─────────────────────────────────────
|
||||||
|
|
||||||
|
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";
|
||||||
|
|
||||||
|
-- ─── Services: add defaultBufferMinutes ───────────────────────────────────────
|
||||||
|
|
||||||
|
ALTER TABLE "services" ADD COLUMN "default_buffer_minutes" integer;
|
||||||
|
|
||||||
|
-- ─── Buffer Rules table ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CREATE TABLE "buffer_rules" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"service_id" uuid NOT NULL REFERENCES "services"("id") ON DELETE CASCADE,
|
||||||
|
"size_category" "pet_size_category",
|
||||||
|
"coat_type" "coat_type",
|
||||||
|
"buffer_minutes" integer NOT NULL,
|
||||||
|
"created_at" timestamp NOT NULL DEFAULT now(),
|
||||||
|
"updated_at" timestamp NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT "uq_buffer_rules_service_size_coat" UNIQUE ("service_id", "size_category", "coat_type")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "idx_buffer_rules_service_id" ON "buffer_rules"("service_id");
|
||||||
@@ -208,15 +208,15 @@
|
|||||||
{
|
{
|
||||||
"idx": 29,
|
"idx": 29,
|
||||||
"version": "7",
|
"version": "7",
|
||||||
"when": 1775828067192,
|
"when": 1775784467192,
|
||||||
"tag": "0029_db_indexes_constraints",
|
"tag": "0029_db_indexes_constraints",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"idx": 30,
|
"idx": 30,
|
||||||
"version": "7",
|
"version": "7",
|
||||||
"when": 1775914467192,
|
"when": 1775828067192,
|
||||||
"tag": "0030_extended_pet_profile",
|
"tag": "0030_messaging",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"name": "@groombook/db",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"main": "./dist/index.js",
|
||||||
|
"types": "./src/index.ts",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"default": "./dist/index.js",
|
||||||
|
"types": "./src/index.ts"
|
||||||
|
},
|
||||||
|
"./factories": {
|
||||||
|
"default": "./src/factories.ts",
|
||||||
|
"types": "./src/factories.ts"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc",
|
||||||
|
"generate": "drizzle-kit generate",
|
||||||
|
"migrate": "drizzle-kit migrate",
|
||||||
|
"seed": "tsx src/seed.ts",
|
||||||
|
"reset": "tsx src/reset.ts && drizzle-kit migrate && tsx src/seed.ts",
|
||||||
|
"studio": "drizzle-kit studio",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"drizzle-orm": "^0.38.4",
|
||||||
|
"postgres": "^3.4.5"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.10.7",
|
||||||
|
"drizzle-kit": "^0.30.4",
|
||||||
|
"tsx": "^4.19.0",
|
||||||
|
"typescript": "^5.7.3"
|
||||||
|
},
|
||||||
|
"license": "AGPL-3.0-only"
|
||||||
|
}
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
* readable values (e.g. "staff-1", "client-2") without needing crypto.
|
* readable values (e.g. "staff-1", "client-2") without needing crypto.
|
||||||
*
|
*
|
||||||
* Usage:
|
* Usage:
|
||||||
* import { buildStaff, buildClient, buildPet } from "./db/factories";
|
* import { buildStaff, buildClient, buildPet } from "@groombook/db/factories";
|
||||||
*
|
*
|
||||||
* const manager = buildStaff({ role: "manager" });
|
* const manager = buildStaff({ role: "manager" });
|
||||||
* const client = buildClient({ name: "Alice Smith" });
|
* const client = buildClient({ name: "Alice Smith" });
|
||||||
@@ -104,10 +104,7 @@ export function buildPet(overrides: Partial<PetRow> & { clientId: string }): Pet
|
|||||||
photoUploadedAt: null,
|
photoUploadedAt: null,
|
||||||
image: null,
|
image: null,
|
||||||
coatType: null,
|
coatType: null,
|
||||||
temperamentScore: null,
|
petSizeCategory: null,
|
||||||
temperamentFlags: [],
|
|
||||||
medicalAlerts: [],
|
|
||||||
preferredCuts: [],
|
|
||||||
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"),
|
||||||
};
|
};
|
||||||
@@ -122,6 +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,
|
||||||
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,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", [
|
||||||
@@ -58,6 +48,22 @@ 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", {
|
||||||
@@ -152,16 +158,12 @@ export const pets = pgTable(
|
|||||||
cutStyle: text("cut_style"),
|
cutStyle: text("cut_style"),
|
||||||
shampooPreference: text("shampoo_preference"),
|
shampooPreference: text("shampoo_preference"),
|
||||||
specialCareNotes: text("special_care_notes"),
|
specialCareNotes: text("special_care_notes"),
|
||||||
|
coatType: coatTypeEnum("coat_type"),
|
||||||
|
petSizeCategory: petSizeCategoryEnum("pet_size_category"),
|
||||||
customFields: jsonb("custom_fields").$type<Record<string, string>>().notNull().default({}),
|
customFields: jsonb("custom_fields").$type<Record<string, string>>().notNull().default({}),
|
||||||
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(),
|
||||||
},
|
},
|
||||||
@@ -174,11 +176,34 @@ 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),
|
||||||
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(),
|
||||||
@@ -422,6 +447,117 @@ export const impersonationAuditLogs = pgTable(
|
|||||||
(t) => [index("impersonation_audit_logs_session_id_idx").on(t.sessionId)]
|
(t) => [index("impersonation_audit_logs_session_id_idx").on(t.sessionId)]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ─── Messaging ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const messagingChannelEnum = pgEnum("messaging_channel", ["sms", "mms"]);
|
||||||
|
|
||||||
|
export const messageDirectionEnum = pgEnum("message_direction", [
|
||||||
|
"inbound",
|
||||||
|
"outbound",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const messageStatusEnum = pgEnum("message_status", [
|
||||||
|
"queued",
|
||||||
|
"sent",
|
||||||
|
"delivered",
|
||||||
|
"failed",
|
||||||
|
"received",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const messageConsentKindEnum = pgEnum("message_consent_kind", [
|
||||||
|
"opt_in",
|
||||||
|
"opt_out",
|
||||||
|
"help",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const conversations = pgTable(
|
||||||
|
"conversations",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
businessId: uuid("business_id").notNull(),
|
||||||
|
clientId: uuid("client_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => clients.id, { onDelete: "cascade" }),
|
||||||
|
channel: messagingChannelEnum("channel").notNull(),
|
||||||
|
externalNumber: text("external_number").notNull(),
|
||||||
|
businessNumber: text("business_number").notNull(),
|
||||||
|
lastMessageAt: timestamp("last_message_at"),
|
||||||
|
status: text("status").notNull().default("active"),
|
||||||
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(t) => [
|
||||||
|
index("idx_conversations_business_id_last_message_at").on(
|
||||||
|
t.businessId,
|
||||||
|
t.lastMessageAt.desc()
|
||||||
|
),
|
||||||
|
unique("uq_conversations_business_client_number").on(
|
||||||
|
t.businessId,
|
||||||
|
t.clientId,
|
||||||
|
t.businessNumber
|
||||||
|
),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
export const messages = pgTable(
|
||||||
|
"messages",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
conversationId: uuid("conversation_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => conversations.id, { onDelete: "cascade" }),
|
||||||
|
direction: messageDirectionEnum("direction").notNull(),
|
||||||
|
body: text("body"),
|
||||||
|
status: messageStatusEnum("status").notNull().default("queued"),
|
||||||
|
providerMessageId: text("provider_message_id"),
|
||||||
|
errorCode: text("error_code"),
|
||||||
|
errorMessage: text("error_message"),
|
||||||
|
sentByStaffId: uuid("sent_by_staff_id").references(() => staff.id, {
|
||||||
|
onDelete: "set null",
|
||||||
|
}),
|
||||||
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
|
deliveredAt: timestamp("delivered_at"),
|
||||||
|
readByClientAt: timestamp("read_by_client_at"),
|
||||||
|
},
|
||||||
|
(t) => [
|
||||||
|
index("idx_messages_conversation_id_created_at").on(
|
||||||
|
t.conversationId,
|
||||||
|
t.createdAt.desc()
|
||||||
|
),
|
||||||
|
unique("uq_messages_provider_message_id").on(t.providerMessageId),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
export const messageAttachments = pgTable(
|
||||||
|
"message_attachments",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
messageId: uuid("message_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => messages.id, { onDelete: "cascade" }),
|
||||||
|
contentType: text("content_type").notNull(),
|
||||||
|
url: text("url").notNull(),
|
||||||
|
size: integer("size").notNull(),
|
||||||
|
providerMediaId: text("provider_media_id"),
|
||||||
|
},
|
||||||
|
(t) => [index("idx_message_attachments_message_id").on(t.messageId)]
|
||||||
|
);
|
||||||
|
|
||||||
|
export const messageConsentEvents = pgTable(
|
||||||
|
"message_consent_events",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
clientId: uuid("client_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => clients.id, { onDelete: "cascade" }),
|
||||||
|
businessId: uuid("business_id").notNull(),
|
||||||
|
kind: messageConsentKindEnum("kind").notNull(),
|
||||||
|
source: text("source"),
|
||||||
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(t) => [index("idx_message_consent_events_client_id").on(t.clientId)]
|
||||||
|
);
|
||||||
|
|
||||||
export const businessSettings = pgTable("business_settings", {
|
export const businessSettings = pgTable("business_settings", {
|
||||||
id: uuid("id").primaryKey().defaultRandom(),
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
businessName: text("business_name").notNull().default("GroomBook"),
|
businessName: text("business_name").notNull().default("GroomBook"),
|
||||||
@@ -430,6 +566,8 @@ export const businessSettings = pgTable("business_settings", {
|
|||||||
logoKey: text("logo_key"),
|
logoKey: text("logo_key"),
|
||||||
primaryColor: text("primary_color").notNull().default("#4f8a6f"),
|
primaryColor: text("primary_color").notNull().default("#4f8a6f"),
|
||||||
accentColor: text("accent_color").notNull().default("#8b7355"),
|
accentColor: text("accent_color").notNull().default("#8b7355"),
|
||||||
|
messagingPhoneNumber: text("messaging_phone_number"),
|
||||||
|
telnyxMessagingProfileId: text("telnyx_messaging_profile_id"),
|
||||||
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,6 +94,11 @@ 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;
|
||||||
@@ -454,32 +459,6 @@ async function seedKnownUsers() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Staff: UAT Tester (oidcSub from SEED_UAT_TESTER_OIDC_SUB env var) ──
|
|
||||||
const uatTesterOidcSub = process.env.SEED_UAT_TESTER_OIDC_SUB;
|
|
||||||
if (uatTesterOidcSub) {
|
|
||||||
const UAT_TESTER_STAFF_ID = "00000000-0000-0000-0000-000000000007";
|
|
||||||
const [existingUatTester] = await db
|
|
||||||
.select()
|
|
||||||
.from(schema.staff)
|
|
||||||
.where(eq(schema.staff.email, "uat-tester@groombook.dev"))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (existingUatTester) {
|
|
||||||
console.log(`✓ Staff 'UAT Tester' already exists — skipping`);
|
|
||||||
} else {
|
|
||||||
await db.insert(schema.staff).values({
|
|
||||||
id: UAT_TESTER_STAFF_ID,
|
|
||||||
name: "UAT Tester",
|
|
||||||
email: "uat-tester@groombook.dev",
|
|
||||||
oidcSub: uatTesterOidcSub,
|
|
||||||
role: "groomer",
|
|
||||||
isSuperUser: false,
|
|
||||||
active: true,
|
|
||||||
});
|
|
||||||
console.log(`✓ Created staff 'UAT Tester' (oidcSub: ${uatTesterOidcSub})`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Staff: UAT Groomer Personas (SEED_UAT_GROOMER_EMAILS + SEED_UAT_GROOMER_NAMES) ──
|
// ── Staff: UAT Groomer Personas (SEED_UAT_GROOMER_EMAILS + SEED_UAT_GROOMER_NAMES) ──
|
||||||
const groomerEmails = process.env.SEED_UAT_GROOMER_EMAILS?.split(",").map((e) => e.trim()).filter(Boolean) ?? [];
|
const groomerEmails = process.env.SEED_UAT_GROOMER_EMAILS?.split(",").map((e) => e.trim()).filter(Boolean) ?? [];
|
||||||
const groomerNames = process.env.SEED_UAT_GROOMER_NAMES?.split(",").map((n) => n.trim()).filter(Boolean) ?? [];
|
const groomerNames = process.env.SEED_UAT_GROOMER_NAMES?.split(",").map((n) => n.trim()).filter(Boolean) ?? [];
|
||||||
@@ -904,7 +883,6 @@ async function seed() {
|
|||||||
let appointmentCount = 0;
|
let appointmentCount = 0;
|
||||||
let invoiceCount = 0;
|
let invoiceCount = 0;
|
||||||
let visitLogCount = 0;
|
let visitLogCount = 0;
|
||||||
let paidInvoiceCounter = 0;
|
|
||||||
|
|
||||||
// Process in batches per client to keep memory manageable
|
// Process in batches per client to keep memory manageable
|
||||||
const apptBatchSize = 100;
|
const apptBatchSize = 100;
|
||||||
@@ -999,11 +977,8 @@ async function seed() {
|
|||||||
|
|
||||||
const invoiceStatus = rand() < 0.95 ? "paid" as const : "pending" as const;
|
const invoiceStatus = rand() < 0.95 ? "paid" as const : "pending" as const;
|
||||||
const paidAt = invoiceStatus === "paid" ? new Date(endTime.getTime() + randInt(5, 30) * 60 * 1000) : null;
|
const paidAt = invoiceStatus === "paid" ? new Date(endTime.getTime() + randInt(5, 30) * 60 * 1000) : null;
|
||||||
paidInvoiceCounter++;
|
|
||||||
const stripePaymentIntentId = invoiceStatus === "paid"
|
|
||||||
? `pi_test_seed_${String(paidInvoiceCounter).padStart(6, "0")}`
|
|
||||||
: null;
|
|
||||||
|
|
||||||
|
const stripePaymentIntentId = invoiceStatus === "paid" && rand() < 0.2 ? `pi_test_${uuid().replace(/-/g, "").slice(0, 24)}` : null;
|
||||||
invoiceBatch.push({
|
invoiceBatch.push({
|
||||||
id: invoiceId,
|
id: invoiceId,
|
||||||
appointmentId: apptId,
|
appointmentId: apptId,
|
||||||
@@ -1100,7 +1075,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;
|
||||||
|
|
||||||
const startTime = randDate(appointmentsBackDate, now);
|
let 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;
|
||||||
@@ -1119,16 +1094,14 @@ async function seed() {
|
|||||||
const taxCents = Math.round(effectivePrice * 0.08);
|
const taxCents = Math.round(effectivePrice * 0.08);
|
||||||
const totalCents = effectivePrice + taxCents + tipCents;
|
const totalCents = effectivePrice + taxCents + tipCents;
|
||||||
const paidAt = new Date(endTime.getTime() + randInt(5, 30) * 60 * 1000);
|
const paidAt = new Date(endTime.getTime() + randInt(5, 30) * 60 * 1000);
|
||||||
paidInvoiceCounter++;
|
const stripePaymentIntentId = rand() < 0.2 ? `pi_test_${uuid().replace(/-/g, "").slice(0, 24)}` : null;
|
||||||
|
|
||||||
invoiceBatch.push({
|
invoiceBatch.push({
|
||||||
id: invoiceId, appointmentId: apptId, clientId,
|
id: invoiceId, appointmentId: apptId, clientId,
|
||||||
subtotalCents: effectivePrice, taxCents, tipCents, totalCents,
|
subtotalCents: effectivePrice, taxCents, tipCents, totalCents,
|
||||||
status: "paid" as const,
|
status: "paid" as const,
|
||||||
paymentMethod: pick(["cash", "card", "card", "card", "check"]) as "cash" | "card" | "check",
|
paymentMethod: pick(["cash", "card", "card", "card", "check"]) as "cash" | "card" | "check",
|
||||||
paidAt,
|
paidAt, stripePaymentIntentId, notes: null,
|
||||||
stripePaymentIntentId: `pi_test_seed_${String(paidInvoiceCounter).padStart(6, "0")}`,
|
|
||||||
notes: null,
|
|
||||||
});
|
});
|
||||||
lineItemBatch.push({
|
lineItemBatch.push({
|
||||||
id: uuid(), invoiceId, description: svc.name, quantity: 1,
|
id: uuid(), invoiceId, description: svc.name, quantity: 1,
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "@groombook/types",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"main": "./dist/index.js",
|
||||||
|
"types": "./src/index.ts",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"default": "./dist/index.js",
|
||||||
|
"types": "./src/index.ts"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc",
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"typescript": "^5.7.3"
|
||||||
|
},
|
||||||
|
"license": "AGPL-3.0-only"
|
||||||
|
}
|
||||||
@@ -39,26 +39,19 @@ export interface Pet {
|
|||||||
cutStyle: string | null;
|
cutStyle: string | null;
|
||||||
shampooPreference: string | null;
|
shampooPreference: string | null;
|
||||||
specialCareNotes: string | null;
|
specialCareNotes: string | null;
|
||||||
|
coatType: string | null;
|
||||||
|
petSizeCategory: string | null;
|
||||||
|
preferredCuts: string[];
|
||||||
|
medicalAlerts: MedicalAlert[];
|
||||||
|
temperamentScore?: number;
|
||||||
|
temperamentFlags?: string[];
|
||||||
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;
|
||||||
@@ -221,3 +214,14 @@ export interface PaginatedList<T> {
|
|||||||
page: number;
|
page: number;
|
||||||
pageSize: number;
|
pageSize: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type AlertSeverity = "low" | "medium" | "high";
|
||||||
|
|
||||||
|
export interface MedicalAlert {
|
||||||
|
id: string;
|
||||||
|
type: string;
|
||||||
|
description: string;
|
||||||
|
severity: AlertSeverity;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CoatType = "smooth" | "double" | "curly" | "wire" | "long" | "hairless";
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"strict": true,
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"rootDir": "./src"
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
Generated
+350
-332
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
packages:
|
packages:
|
||||||
- "apps/*"
|
- "packages/*"
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ let dbSelectResult: unknown[] = [];
|
|||||||
const mockEq = vi.fn((_col: unknown, _val: unknown) => ({ col: _col, val: _val }));
|
const mockEq = vi.fn((_col: unknown, _val: unknown) => ({ col: _col, val: _val }));
|
||||||
const mockDecryptSecret = vi.fn((s: string) => `decrypted:${s}`);
|
const mockDecryptSecret = vi.fn((s: string) => `decrypted:${s}`);
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
const authProviderConfig = new Proxy(
|
const authProviderConfig = new Proxy(
|
||||||
{ _name: "auth_provider_config" },
|
{ _name: "auth_provider_config" },
|
||||||
{
|
{
|
||||||
@@ -40,7 +40,7 @@ vi.mock("../db", () => {
|
|||||||
|
|
||||||
async function reimportAuth() {
|
async function reimportAuth() {
|
||||||
vi.resetModules();
|
vi.resetModules();
|
||||||
vi.doMock("./db", () => ({
|
vi.doMock("@groombook/db", () => ({
|
||||||
getDb: () => ({
|
getDb: () => ({
|
||||||
select: () => ({
|
select: () => ({
|
||||||
from: () => ({
|
from: () => ({
|
||||||
@@ -38,7 +38,7 @@ const mockGroomer: MockStaff = { id: "staff-3", role: "groomer", isSuperUser: fa
|
|||||||
|
|
||||||
// ─── Mock db module ───────────────────────────────────────────────────────────
|
// ─── Mock db module ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
const authProviderConfig = new Proxy(
|
const authProviderConfig = new Proxy(
|
||||||
{ _name: "auth_provider_config" },
|
{ _name: "auth_provider_config" },
|
||||||
{
|
{
|
||||||
@@ -40,7 +40,7 @@ function resetMock() {
|
|||||||
deletedId = null;
|
deletedId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
function makeChainable(data: unknown[]): unknown {
|
function makeChainable(data: unknown[]): unknown {
|
||||||
const arr = [...data];
|
const arr = [...data];
|
||||||
const chain = new Proxy(arr, {
|
const chain = new Proxy(arr, {
|
||||||
@@ -39,7 +39,7 @@ function resetMock() {
|
|||||||
lastUpdate = {};
|
lastUpdate = {};
|
||||||
}
|
}
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
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 }) }
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||||
import { encryptSecret, decryptSecret } from "../db/index.js";
|
import { encryptSecret, decryptSecret } from "@groombook/db";
|
||||||
|
|
||||||
describe("encryptSecret / decryptSecret", () => {
|
describe("encryptSecret / decryptSecret", () => {
|
||||||
const originalEnv = process.env.BETTER_AUTH_SECRET;
|
const originalEnv = process.env.BETTER_AUTH_SECRET;
|
||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
buildPet,
|
buildPet,
|
||||||
buildService,
|
buildService,
|
||||||
buildAppointment,
|
buildAppointment,
|
||||||
} from "../db/factories.js";
|
} from "@groombook/db/factories";
|
||||||
|
|
||||||
describe("resetFactoryCounters", () => {
|
describe("resetFactoryCounters", () => {
|
||||||
it("resets all counters so IDs restart from 1", () => {
|
it("resets all counters so IDs restart from 1", () => {
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import type { AppEnv, StaffRow } from "../middleware/rbac.js";
|
import type { AppEnv, StaffRow } from "../middleware/rbac.js";
|
||||||
import { buildStaff } from "../db/factories.js";
|
import { buildStaff } from "@groombook/db/factories";
|
||||||
|
|
||||||
// ─── Mock data (built with factories for schema-safe defaults) ────────────────
|
// ─── Mock data (built with factories for schema-safe defaults) ────────────────
|
||||||
|
|
||||||
@@ -76,7 +76,7 @@ function makeChainableResult(data: unknown[]): unknown {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
function makeTable(name: string) {
|
function makeTable(name: string) {
|
||||||
return new Proxy(
|
return new Proxy(
|
||||||
{ _name: name },
|
{ _name: name },
|
||||||
@@ -40,7 +40,7 @@ function resetDb() {
|
|||||||
|
|
||||||
// ─── Module mocks ─────────────────────────────────────────────────────────────
|
// ─── Module mocks ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
const pets = new Proxy(
|
const pets = new Proxy(
|
||||||
{ _name: "pets" },
|
{ _name: "pets" },
|
||||||
{ get(t, p) { return p === "_name" ? "pets" : {}; } }
|
{ get(t, p) { return p === "_name" ? "pets" : {}; } }
|
||||||
@@ -47,7 +47,7 @@ function resetMock() {
|
|||||||
updatedValues = [];
|
updatedValues = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
function makeChainable(data: unknown[]): unknown {
|
function makeChainable(data: unknown[]): unknown {
|
||||||
const arr = [...data];
|
const arr = [...data];
|
||||||
const chain = new Proxy(arr, {
|
const chain = new Proxy(arr, {
|
||||||
@@ -67,11 +67,6 @@ 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 }) }
|
||||||
@@ -104,12 +99,8 @@ vi.mock("../db", () => {
|
|||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
insert: () => ({
|
|
||||||
values: () => ({ returning: () => [{}] }),
|
|
||||||
}),
|
|
||||||
}),
|
}),
|
||||||
impersonationSessions,
|
impersonationSessions,
|
||||||
impersonationAuditLogs,
|
|
||||||
appointments,
|
appointments,
|
||||||
eq: vi.fn(),
|
eq: vi.fn(),
|
||||||
and: vi.fn(),
|
and: vi.fn(),
|
||||||
@@ -46,7 +46,7 @@ const GROOMER: StaffRow = {
|
|||||||
let staffLookupResult: StaffRow | null = null;
|
let staffLookupResult: StaffRow | null = null;
|
||||||
let managerFallbackResult: StaffRow | null = MANAGER;
|
let managerFallbackResult: StaffRow | null = MANAGER;
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
const staff = new Proxy(
|
const staff = new Proxy(
|
||||||
{ _name: "staff" },
|
{ _name: "staff" },
|
||||||
{
|
{
|
||||||
@@ -23,7 +23,7 @@ const PET_ROW = {
|
|||||||
let clientResults: typeof ACTIVE_CLIENT[] = [];
|
let clientResults: typeof ACTIVE_CLIENT[] = [];
|
||||||
let petResults: typeof PET_ROW[] = [];
|
let petResults: typeof PET_ROW[] = [];
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
// Proxy objects for table/column references — values don't matter for tests
|
// Proxy objects for table/column references — values don't matter for tests
|
||||||
const tableProxy = (name: string) =>
|
const tableProxy = (name: string) =>
|
||||||
new Proxy(
|
new Proxy(
|
||||||
@@ -39,7 +39,7 @@ function clearAuthEnv() {
|
|||||||
|
|
||||||
// ─── Mock db module ───────────────────────────────────────────────────────────
|
// ─── Mock db module ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
const authProviderConfig = new Proxy(
|
const authProviderConfig = new Proxy(
|
||||||
{ _name: "auth_provider_config" },
|
{ _name: "auth_provider_config" },
|
||||||
{
|
{
|
||||||
@@ -49,7 +49,7 @@ function resetMock() {
|
|||||||
updatedValues = [];
|
updatedValues = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
function makeChainable(data: unknown[]): unknown {
|
function makeChainable(data: unknown[]): unknown {
|
||||||
const arr = [...data];
|
const arr = [...data];
|
||||||
const chain = new Proxy(arr, {
|
const chain = new Proxy(arr, {
|
||||||
@@ -19,10 +19,11 @@ import { impersonationRouter } from "./routes/impersonation.js";
|
|||||||
import { settingsRouter } from "./routes/settings.js";
|
import { settingsRouter } from "./routes/settings.js";
|
||||||
import { authProviderRouter } from "./routes/authProvider.js";
|
import { authProviderRouter } from "./routes/authProvider.js";
|
||||||
import { searchRouter } from "./routes/search.js";
|
import { searchRouter } from "./routes/search.js";
|
||||||
|
import { bufferRulesRouter } from "./routes/buffer-rules.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/index.js";
|
import { getDb, businessSettings, eq, staff } from "@groombook/db";
|
||||||
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";
|
||||||
@@ -269,6 +270,7 @@ api.route("/admin/settings", settingsRouter);
|
|||||||
api.route("/admin/auth-provider", authProviderRouter);
|
api.route("/admin/auth-provider", authProviderRouter);
|
||||||
api.route("/admin/seed", adminSeedRouter);
|
api.route("/admin/seed", adminSeedRouter);
|
||||||
api.route("/search", searchRouter);
|
api.route("/search", searchRouter);
|
||||||
|
api.route("/buffer-rules", bufferRulesRouter);
|
||||||
|
|
||||||
const port = Number(process.env.PORT ?? 3000);
|
const port = Number(process.env.PORT ?? 3000);
|
||||||
await initAuth();
|
await initAuth();
|
||||||
@@ -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/index.js";
|
import { getDb, authProviderConfig, eq } from "@groombook/db";
|
||||||
import { decryptSecret } from "../db/index.js";
|
import { decryptSecret } from "@groombook/db";
|
||||||
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,9 +97,6 @@ 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,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -250,9 +247,6 @@ 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/index.js";
|
import { getDb, impersonationAuditLogs } from "@groombook/db";
|
||||||
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/index.js";
|
import { and, eq, getDb, impersonationSessions } from "@groombook/db";
|
||||||
|
|
||||||
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/index.js";
|
import { and, eq, getDb, sql, staff } from "@groombook/db";
|
||||||
|
|
||||||
export type StaffRole = "groomer" | "receptionist" | "manager";
|
export type StaffRole = "groomer" | "receptionist" | "manager";
|
||||||
export type StaffRow = typeof staff.$inferSelect;
|
export type StaffRow = typeof staff.$inferSelect;
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { eq, getDb, staff, clients, pets, services } from "../../db/index.js";
|
import { eq, getDb, staff, clients, pets, services } from "@groombook/db";
|
||||||
|
|
||||||
export const adminSeedRouter = new Hono();
|
export const adminSeedRouter = new Hono();
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ import {
|
|||||||
pets,
|
pets,
|
||||||
services,
|
services,
|
||||||
staff,
|
staff,
|
||||||
} from "../db/index.js";
|
} from "@groombook/db";
|
||||||
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/index.js";
|
} from "@groombook/db";
|
||||||
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/index.js";
|
import { eq, getDb, authProviderConfig, encryptSecret } from "@groombook/db";
|
||||||
import { requireSuperUser } from "../middleware/rbac.js";
|
import { requireSuperUser } from "../middleware/rbac.js";
|
||||||
import { reinitAuth } from "../lib/auth.js";
|
import { reinitAuth } from "../lib/auth.js";
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user