Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 91af671c4e | |||
| 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
-160
@@ -32,10 +32,10 @@ jobs:
|
|||||||
run: pnpm install --frozen-lockfile
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
- name: Typecheck
|
- name: Typecheck
|
||||||
run: pnpm --filter @groombook/api typecheck
|
run: pnpm typecheck
|
||||||
|
|
||||||
- name: Lint
|
- name: Lint
|
||||||
run: pnpm --filter @groombook/api lint
|
run: pnpm lint
|
||||||
|
|
||||||
test:
|
test:
|
||||||
name: Test
|
name: Test
|
||||||
@@ -56,39 +56,16 @@ jobs:
|
|||||||
run: pnpm install --frozen-lockfile
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: pnpm --filter @groombook/api test
|
run: pnpm test
|
||||||
|
|
||||||
build:
|
|
||||||
name: Build
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [lint-typecheck]
|
|
||||||
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:
|
docker:
|
||||||
name: Build & Push Docker Images
|
name: Build & Push Docker Image
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [build]
|
needs: [lint-typecheck, test]
|
||||||
outputs:
|
|
||||||
tag: ${{ steps.version.outputs.tag }}
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
packages: write
|
packages: write
|
||||||
|
id-token: write
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
@@ -118,140 +95,9 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: Dockerfile
|
file: Dockerfile
|
||||||
target: runner
|
|
||||||
push: true
|
push: true
|
||||||
tags: |
|
tags: |
|
||||||
ghcr.io/groombook/api:${{ steps.version.outputs.tag }}
|
ghcr.io/groombook/api:${{ steps.version.outputs.tag }}
|
||||||
${{ github.ref == 'refs/heads/main' && 'ghcr.io/groombook/api:latest' || '' }}
|
${{ github.ref == 'refs/heads/main' && 'ghcr.io/groombook/api:latest' || '' }}
|
||||||
cache-from: type=gha
|
cache-from: type=gha
|
||||||
cache-to: type=gha,mode=max
|
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/groombook/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/groombook/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/groombook/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/groombook/overlays/dev/ apps/groombook/base/migrate-job.yaml apps/groombook/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/
|
|
||||||
|
|||||||
+25
-11
@@ -2,37 +2,51 @@ 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 ./
|
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/
|
||||||
|
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 ./
|
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
|
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -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.js";
|
* 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" });
|
||||||
@@ -406,6 +406,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 +525,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(),
|
||||||
});
|
});
|
||||||
@@ -95,6 +95,10 @@ function pick<T>(arr: T[]): T {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Return n distinct random elements from an array. */
|
/** 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;
|
||||||
@@ -879,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;
|
||||||
@@ -974,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,
|
||||||
@@ -1075,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;
|
||||||
@@ -1094,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"
|
||||||
|
}
|
||||||
@@ -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
-319
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,2 @@
|
|||||||
packages:
|
packages:
|
||||||
- "apps/*"
|
|
||||||
- "packages/*"
|
- "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, {
|
||||||
@@ -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, {
|
||||||
@@ -22,7 +22,7 @@ import { searchRouter } from "./routes/search.js";
|
|||||||
import { getObject } from "./lib/s3.js";
|
import { getObject } from "./lib/s3.js";
|
||||||
import { calendarRouter } from "./routes/calendar.js";
|
import { calendarRouter } from "./routes/calendar.js";
|
||||||
import { setupRouter } from "./routes/setup.js";
|
import { setupRouter } from "./routes/setup.js";
|
||||||
import { getDb, businessSettings, eq, staff } from "./db/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";
|
||||||
@@ -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;
|
||||||
@@ -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,7 +1,7 @@
|
|||||||
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, staffRoleEnum } from "@groombook/db";
|
||||||
|
|
||||||
export type StaffRole = "groomer" | "receptionist" | "manager";
|
type StaffRole = typeof staffRoleEnum.enumValues[number];
|
||||||
export type StaffRow = typeof staff.$inferSelect;
|
export type StaffRow = typeof staff.$inferSelect;
|
||||||
|
|
||||||
export interface AppEnv {
|
export interface AppEnv {
|
||||||
@@ -110,6 +110,27 @@ export const resolveStaffMiddleware: MiddlewareHandler<AppEnv> = async (
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Auto-create staff record for authenticated OAuth users with no existing staff record
|
||||||
|
// This allows new OAuth users to access the app (defaults to receptionist role)
|
||||||
|
if (jwt.email && jwt.name) {
|
||||||
|
const [newStaff] = await db
|
||||||
|
.insert(staff)
|
||||||
|
.values({
|
||||||
|
email: jwt.email,
|
||||||
|
name: jwt.name,
|
||||||
|
userId: jwt.sub,
|
||||||
|
role: "receptionist",
|
||||||
|
active: true,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
if (newStaff) {
|
||||||
|
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,
|
||||||
@@ -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();
|
||||||
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { and, eq, exists, getDb, or, clients, appointments } from "../db/index.js";
|
import { and, eq, exists, getDb, or, clients, appointments } from "@groombook/db";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const clientsRouter = new Hono<AppEnv>();
|
export const clientsRouter = new Hono<AppEnv>();
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { getDb, staff, clients, eq, sql } from "../db/index.js";
|
import { getDb, staff, clients, eq, sql } from "@groombook/db";
|
||||||
|
|
||||||
const devRouter = new Hono();
|
const devRouter = new Hono();
|
||||||
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { and, desc, eq, getDb, groomingVisitLogs, appointments, or } from "../db/index.js";
|
import { and, desc, eq, getDb, groomingVisitLogs, appointments, or } from "@groombook/db";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const groomingLogsRouter = new Hono<AppEnv>();
|
export const groomingLogsRouter = new Hono<AppEnv>();
|
||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
impersonationAuditLogs,
|
impersonationAuditLogs,
|
||||||
clients,
|
clients,
|
||||||
desc,
|
desc,
|
||||||
} from "../db/index.js";
|
} from "@groombook/db";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const impersonationRouter = new Hono<AppEnv>();
|
export const impersonationRouter = new Hono<AppEnv>();
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user