Compare commits
14 Commits
pr-19
..
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
|
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
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: 20
|
||||||
|
cache: pnpm
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Typecheck
|
||||||
|
run: pnpm typecheck
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
run: pnpm 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: 20
|
||||||
|
cache: pnpm
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: pnpm test
|
||||||
|
|
||||||
|
docker:
|
||||||
|
name: Build & Push Docker Image
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [lint-typecheck, test]
|
||||||
|
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 Gitea Container Registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: git.farh.net
|
||||||
|
username: ${{ gitea.actor }}
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|
||||||
|
- name: Build and push API image
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: |
|
||||||
|
git.farh.net/groombook/api:${{ steps.version.outputs.tag }}
|
||||||
|
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/api:latest' || '' }}
|
||||||
|
cache-from: type=registry,ref=git.farh.net/groombook/cache:api
|
||||||
|
cache-to: type=registry,ref=git.farh.net/groombook/cache:api,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: 20
|
|
||||||
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: 20
|
|
||||||
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: 20
|
|
||||||
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/
|
|
||||||
|
|||||||
+26
-11
@@ -2,37 +2,52 @@ 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
|
||||||
|
|
||||||
|
# Runtime
|
||||||
FROM node:20-alpine AS runner
|
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
|
|
||||||
|
|||||||
+18
-1
@@ -28,7 +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 | Auto-provision on first OIDC login | First login as a Better-Auth user with no existing staff record | 200 OK, access granted; groomer staff record auto-created with name/email from user table |
|
| 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
|
||||||
|
|
||||||
@@ -178,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,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"
|
|
||||||
}
|
|
||||||
@@ -3,5 +3,40 @@
|
|||||||
"version": "0.0.1",
|
"version": "0.0.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"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"
|
||||||
|
},
|
||||||
|
"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"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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");
|
||||||
@@ -204,6 +204,20 @@
|
|||||||
"when": 1775741667192,
|
"when": 1775741667192,
|
||||||
"tag": "0028_sms_reminders",
|
"tag": "0028_sms_reminders",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 29,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1775784467192,
|
||||||
|
"tag": "0029_db_indexes_constraints",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 30,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1775828067192,
|
||||||
|
"tag": "0030_messaging",
|
||||||
|
"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" });
|
||||||
@@ -103,6 +103,8 @@ export function buildPet(overrides: Partial<PetRow> & { clientId: string }): Pet
|
|||||||
photoKey: null,
|
photoKey: null,
|
||||||
photoUploadedAt: null,
|
photoUploadedAt: null,
|
||||||
image: null,
|
image: null,
|
||||||
|
coatType: null,
|
||||||
|
petSizeCategory: null,
|
||||||
createdAt: new Date("2025-01-01T00:00:00Z"),
|
createdAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
};
|
};
|
||||||
@@ -117,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"),
|
||||||
@@ -48,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", {
|
||||||
@@ -142,6 +158,8 @@ 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"),
|
||||||
@@ -158,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(),
|
||||||
@@ -406,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"),
|
||||||
@@ -414,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,6 +39,12 @@ 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;
|
||||||
@@ -208,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, {
|
||||||
@@ -45,72 +45,40 @@ const GROOMER: StaffRow = {
|
|||||||
|
|
||||||
let staffLookupResult: StaffRow | null = null;
|
let staffLookupResult: StaffRow | null = null;
|
||||||
let managerFallbackResult: StaffRow | null = MANAGER;
|
let managerFallbackResult: StaffRow | null = MANAGER;
|
||||||
let userLookupResult: { id: string; name: string | null; email: string | null } | null = null;
|
|
||||||
let insertedStaff: StaffRow | null = null;
|
|
||||||
|
|
||||||
vi.mock("../db", () => {
|
vi.mock("@groombook/db", () => {
|
||||||
const makeTableProxy = (name: string) =>
|
const staff = new Proxy(
|
||||||
new Proxy(
|
{ _name: "staff" },
|
||||||
{ _name: name },
|
{
|
||||||
{
|
get(target, prop) {
|
||||||
get(target, prop) {
|
if (prop === "_name") return "staff";
|
||||||
if (prop === "_name") return name;
|
if (prop === "$inferSelect") return {};
|
||||||
if (prop === "$inferSelect") return {};
|
return { table: "staff", column: prop };
|
||||||
return { table: name, column: prop };
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
const staff = makeTableProxy("staff");
|
|
||||||
const user = makeTableProxy("user");
|
|
||||||
|
|
||||||
const buildQuery = (result: unknown, fallback: unknown) => ({
|
|
||||||
limit: () => ({
|
|
||||||
[Symbol.iterator]: function* () {
|
|
||||||
if (result) yield result;
|
|
||||||
},
|
},
|
||||||
0: result,
|
}
|
||||||
length: result ? 1 : 0,
|
);
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getDb: () => ({
|
getDb: () => ({
|
||||||
select: () => ({
|
select: () => ({
|
||||||
from: (table: unknown) => ({
|
from: () => ({
|
||||||
where: () => buildQuery(
|
where: () => ({
|
||||||
table === staff ? staffLookupResult : userLookupResult,
|
limit: () => {
|
||||||
table === staff ? managerFallbackResult : null
|
// dev mode fallback to first manager
|
||||||
),
|
return managerFallbackResult ? [managerFallbackResult] : [];
|
||||||
}),
|
},
|
||||||
}),
|
[Symbol.iterator]: function* () {
|
||||||
insert: (table: unknown) => ({
|
if (staffLookupResult) yield staffLookupResult;
|
||||||
values: (vals: Record<string, unknown>) => ({
|
},
|
||||||
returning: () => {
|
0: staffLookupResult,
|
||||||
const newStaff: StaffRow = {
|
length: staffLookupResult ? 1 : 0,
|
||||||
id: "new-staff-id",
|
}),
|
||||||
oidcSub: null,
|
|
||||||
userId: vals.userId as string,
|
|
||||||
role: vals.role as StaffRow["role"],
|
|
||||||
isSuperUser: false,
|
|
||||||
name: vals.name as string,
|
|
||||||
email: vals.email as string,
|
|
||||||
active: true,
|
|
||||||
icalToken: null,
|
|
||||||
createdAt: new Date(),
|
|
||||||
updatedAt: new Date(),
|
|
||||||
};
|
|
||||||
insertedStaff = newStaff;
|
|
||||||
return [newStaff];
|
|
||||||
},
|
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
staff,
|
staff,
|
||||||
user,
|
|
||||||
eq: vi.fn((_col: unknown, _val: unknown) => ({ col: _col, val: _val })),
|
eq: vi.fn((_col: unknown, _val: unknown) => ({ col: _col, val: _val })),
|
||||||
and: vi.fn((..._clauses: unknown[]) => ({})),
|
and: vi.fn((..._clauses: unknown[]) => ({})),
|
||||||
sql: vi.fn((..._args: unknown[]) => ({})),
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -119,8 +87,6 @@ vi.mock("../db", () => {
|
|||||||
function resetMocks() {
|
function resetMocks() {
|
||||||
staffLookupResult = null;
|
staffLookupResult = null;
|
||||||
managerFallbackResult = MANAGER;
|
managerFallbackResult = MANAGER;
|
||||||
userLookupResult = null;
|
|
||||||
insertedStaff = null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Build a minimal Hono app with jwtPayload pre-set, then apply a middleware. */
|
/** Build a minimal Hono app with jwtPayload pre-set, then apply a middleware. */
|
||||||
@@ -236,50 +202,6 @@ describe("resolveStaffMiddleware", () => {
|
|||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
expect(body.error).toMatch(/no staff records found/i);
|
expect(body.error).toMatch(/no staff records found/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("auto-provision: creates groomer staff record on first login when Better-Auth user exists", async () => {
|
|
||||||
staffLookupResult = null;
|
|
||||||
userLookupResult = { id: "ba-user-new", name: "New User", email: "newuser@example.com" };
|
|
||||||
let capturedStaff: StaffRow | null = null;
|
|
||||||
const app = buildApp(resolveStaffMiddleware, (c) => {
|
|
||||||
capturedStaff = c.get("staff");
|
|
||||||
return c.json({ ok: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await app.request("/test");
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(capturedStaff).not.toBeNull();
|
|
||||||
expect(capturedStaff!.role).toBe("groomer");
|
|
||||||
expect(capturedStaff!.userId).toBe("ba-user-new");
|
|
||||||
expect(capturedStaff!.name).toBe("New User");
|
|
||||||
expect(capturedStaff!.email).toBe("newuser@example.com");
|
|
||||||
expect(capturedStaff!.isSuperUser).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("auto-provision: falls back to email prefix when user has no name", async () => {
|
|
||||||
staffLookupResult = null;
|
|
||||||
userLookupResult = { id: "ba-user-noname", name: null, email: "firstlogin@example.com" };
|
|
||||||
let capturedStaff: StaffRow | null = null;
|
|
||||||
const app = buildApp(resolveStaffMiddleware, (c) => {
|
|
||||||
capturedStaff = c.get("staff");
|
|
||||||
return c.json({ ok: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await app.request("/test");
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(capturedStaff!.name).toBe("firstlogin");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("auto-provision: returns 403 when no staff record and no Better-Auth user exists", async () => {
|
|
||||||
staffLookupResult = null;
|
|
||||||
userLookupResult = null;
|
|
||||||
const app = buildApp(resolveStaffMiddleware);
|
|
||||||
|
|
||||||
const res = await app.request("/test");
|
|
||||||
expect(res.status).toBe(403);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.error).toMatch(/no staff record found for authenticated user/i);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ─── requireRole tests ────────────────────────────────────────────────────────
|
// ─── requireRole tests ────────────────────────────────────────────────────────
|
||||||
@@ -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, user } 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;
|
||||||
@@ -110,30 +110,6 @@ export const resolveStaffMiddleware: MiddlewareHandler<AppEnv> = async (
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Auto-provision: no staff record exists for this user at all, but a valid
|
|
||||||
// Better-Auth user session exists (jwt.sub = user.id from user table).
|
|
||||||
// Create a minimal groomer staff record on first login.
|
|
||||||
const [userRow] = await db
|
|
||||||
.select({ id: user.id, name: user.name, email: user.email })
|
|
||||||
.from(user)
|
|
||||||
.where(eq(user.id, jwt.sub))
|
|
||||||
.limit(1);
|
|
||||||
if (userRow) {
|
|
||||||
const [newStaff] = await db
|
|
||||||
.insert(staff)
|
|
||||||
.values({
|
|
||||||
name: userRow.name ?? jwt.email?.split("@")[0] ?? "Unknown",
|
|
||||||
email: userRow.email ?? jwt.email ?? "",
|
|
||||||
userId: jwt.sub,
|
|
||||||
role: "groomer",
|
|
||||||
isSuperUser: false,
|
|
||||||
active: true,
|
|
||||||
})
|
|
||||||
.returning();
|
|
||||||
c.set("staff", newStaff);
|
|
||||||
await next();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
return c.json(
|
return c.json(
|
||||||
{ error: "Forbidden: no staff record found for authenticated user" },
|
{ error: "Forbidden: no staff record found for authenticated user" },
|
||||||
403
|
403
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { eq, getDb, staff, clients, pets, services } from "../../db/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";
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ import {
|
|||||||
appointments,
|
appointments,
|
||||||
clients,
|
clients,
|
||||||
pets,
|
pets,
|
||||||
} from "../db/index.js";
|
} from "@groombook/db";
|
||||||
import {
|
import {
|
||||||
generateAvailableSlots,
|
generateAvailableSlots,
|
||||||
BUSINESS_START_HOUR,
|
BUSINESS_START_HOUR,
|
||||||
@@ -112,6 +112,8 @@ const bookingSchema = z.object({
|
|||||||
petName: z.string().min(1).max(200),
|
petName: z.string().min(1).max(200),
|
||||||
petSpecies: z.string().min(1).max(100),
|
petSpecies: z.string().min(1).max(100),
|
||||||
petBreed: z.string().max(100).optional(),
|
petBreed: z.string().max(100).optional(),
|
||||||
|
petSizeCategory: z.string().max(50).optional(),
|
||||||
|
petCoatType: z.string().max(50).optional(),
|
||||||
notes: z.string().max(2000).optional(),
|
notes: z.string().max(2000).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -191,6 +193,8 @@ bookRouter.post(
|
|||||||
name: body.petName,
|
name: body.petName,
|
||||||
species: body.petSpecies,
|
species: body.petSpecies,
|
||||||
breed: body.petBreed ?? null,
|
breed: body.petBreed ?? null,
|
||||||
|
coatType: (body.petCoatType ?? null) as "smooth" | "double" | "wire" | "curly" | "long" | "hairless" | null,
|
||||||
|
petSizeCategory: (body.petSizeCategory ?? null) as "small" | "medium" | "large" | "xlarge" | null,
|
||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
const pet = petInserted[0];
|
const pet = petInserted[0];
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import { Hono } from "hono";
|
||||||
|
import { zValidator } from "@hono/zod-validator";
|
||||||
|
import { z } from "zod/v3";
|
||||||
|
import {
|
||||||
|
and,
|
||||||
|
eq,
|
||||||
|
isNull,
|
||||||
|
getDb,
|
||||||
|
bufferRules,
|
||||||
|
services,
|
||||||
|
} from "@groombook/db";
|
||||||
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
import { requireRole } from "../middleware/rbac.js";
|
||||||
|
|
||||||
|
export const bufferRulesRouter = new Hono<AppEnv>();
|
||||||
|
|
||||||
|
// Apply manager role guard to all routes
|
||||||
|
bufferRulesRouter.use("*", requireRole("manager"));
|
||||||
|
|
||||||
|
const createBufferRuleSchema = z.object({
|
||||||
|
serviceId: z.string().uuid(),
|
||||||
|
sizeCategory: z.enum(["small", "medium", "large", "xlarge"]).optional(),
|
||||||
|
coatType: z.enum(["smooth", "double", "wire", "curly", "long", "hairless"]).optional(),
|
||||||
|
bufferMinutes: z.number().int().positive(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateBufferRuleSchema = z.object({
|
||||||
|
bufferMinutes: z.number().int().positive(),
|
||||||
|
});
|
||||||
|
|
||||||
|
bufferRulesRouter.get("/", async (c) => {
|
||||||
|
const db = getDb();
|
||||||
|
const serviceId = c.req.query("serviceId");
|
||||||
|
|
||||||
|
const conditions = [];
|
||||||
|
if (serviceId) conditions.push(eq(bufferRules.serviceId, serviceId));
|
||||||
|
|
||||||
|
const rows = await db
|
||||||
|
.select({
|
||||||
|
id: bufferRules.id,
|
||||||
|
serviceId: bufferRules.serviceId,
|
||||||
|
serviceName: services.name,
|
||||||
|
sizeCategory: bufferRules.sizeCategory,
|
||||||
|
coatType: bufferRules.coatType,
|
||||||
|
bufferMinutes: bufferRules.bufferMinutes,
|
||||||
|
createdAt: bufferRules.createdAt,
|
||||||
|
updatedAt: bufferRules.updatedAt,
|
||||||
|
})
|
||||||
|
.from(bufferRules)
|
||||||
|
.leftJoin(services, eq(bufferRules.serviceId, services.id))
|
||||||
|
.where(conditions.length > 0 ? and(...conditions) : undefined);
|
||||||
|
|
||||||
|
return c.json(rows);
|
||||||
|
});
|
||||||
|
|
||||||
|
bufferRulesRouter.post(
|
||||||
|
"/",
|
||||||
|
zValidator("json", createBufferRuleSchema),
|
||||||
|
async (c) => {
|
||||||
|
const db = getDb();
|
||||||
|
const body = c.req.valid("json");
|
||||||
|
|
||||||
|
// Validate serviceId exists
|
||||||
|
const [svc] = await db
|
||||||
|
.select({ id: services.id })
|
||||||
|
.from(services)
|
||||||
|
.where(eq(services.id, body.serviceId))
|
||||||
|
.limit(1);
|
||||||
|
if (!svc) return c.json({ error: "Service not found" }, 404);
|
||||||
|
|
||||||
|
// Check for duplicate — sizeCategory/coatType are nullable, use isNull for null check
|
||||||
|
const conditions = [eq(bufferRules.serviceId, body.serviceId)];
|
||||||
|
if (body.sizeCategory) {
|
||||||
|
conditions.push(eq(bufferRules.sizeCategory, body.sizeCategory));
|
||||||
|
} else {
|
||||||
|
conditions.push(isNull(bufferRules.sizeCategory));
|
||||||
|
}
|
||||||
|
if (body.coatType) {
|
||||||
|
conditions.push(eq(bufferRules.coatType, body.coatType));
|
||||||
|
} else {
|
||||||
|
conditions.push(isNull(bufferRules.coatType));
|
||||||
|
}
|
||||||
|
const [existing] = await db
|
||||||
|
.select({ id: bufferRules.id })
|
||||||
|
.from(bufferRules)
|
||||||
|
.where(and(...conditions))
|
||||||
|
.limit(1);
|
||||||
|
if (existing) return c.json({ error: "Duplicate rule for this service and attributes" }, 409);
|
||||||
|
|
||||||
|
const [row] = await db
|
||||||
|
.insert(bufferRules)
|
||||||
|
.values({
|
||||||
|
serviceId: body.serviceId,
|
||||||
|
sizeCategory: body.sizeCategory,
|
||||||
|
coatType: body.coatType,
|
||||||
|
bufferMinutes: body.bufferMinutes,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
return c.json(row, 201);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
bufferRulesRouter.patch(
|
||||||
|
"/:id",
|
||||||
|
zValidator("json", updateBufferRuleSchema),
|
||||||
|
async (c) => {
|
||||||
|
const db = getDb();
|
||||||
|
const body = c.req.valid("json");
|
||||||
|
const [row] = await db
|
||||||
|
.update(bufferRules)
|
||||||
|
.set({ bufferMinutes: body.bufferMinutes, updatedAt: new Date() })
|
||||||
|
.where(eq(bufferRules.id, c.req.param("id")))
|
||||||
|
.returning();
|
||||||
|
if (!row) return c.json({ error: "Not found" }, 404);
|
||||||
|
return c.json(row);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
bufferRulesRouter.delete("/:id", async (c) => {
|
||||||
|
const db = getDb();
|
||||||
|
const [row] = await db
|
||||||
|
.delete(bufferRules)
|
||||||
|
.where(eq(bufferRules.id, c.req.param("id")))
|
||||||
|
.returning();
|
||||||
|
if (!row) return c.json({ error: "Not found" }, 404);
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
@@ -10,7 +10,7 @@ import {
|
|||||||
pets,
|
pets,
|
||||||
services,
|
services,
|
||||||
staff,
|
staff,
|
||||||
} from "../db/index.js";
|
} from "@groombook/db";
|
||||||
|
|
||||||
export const calendarRouter = new Hono();
|
export const calendarRouter = new Hono();
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user