Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29b3d5d4e5 | ||
|
|
b3584e6c4d | ||
|
|
e203fb6c74 | ||
|
|
b51c1360e2 | ||
|
|
ef32d5a917 | ||
|
|
515707c9e4 | ||
|
|
a4945a87cf | ||
|
|
0b7f0a474e | ||
|
|
a70333f5e4 | ||
|
|
9cc330030b | ||
|
|
59acc32a46 | ||
|
|
183a2c99ed | ||
|
|
745af4184f | ||
|
|
279cd19308 | ||
|
|
02a12ee9e0 | ||
|
|
de791fd17d | ||
|
|
ed1d3a8c12 | ||
|
|
87bf9a6151 | ||
|
|
3f7b2d51db | ||
|
|
5970d707af | ||
|
|
e296e80e48 | ||
|
|
a0161a67d2 | ||
|
|
d06f80e572 | ||
|
|
be4dd5b47f | ||
|
|
e0f0b2f1e9 | ||
|
|
390e1dc0ea | ||
|
|
fa8686276d | ||
|
|
498d7d8a7d | ||
|
|
82857b5aa8 | ||
|
|
dafa3711f8 | ||
|
|
5b478c327d | ||
|
|
733d2459df | ||
|
|
4afa5d6fa0 | ||
|
|
617c884012 | ||
|
|
93476ac72a | ||
|
|
c4094630d9 | ||
|
|
6ec8b8400f | ||
|
|
9b2668f498 | ||
|
|
e38d14970d | ||
|
|
71c277045b | ||
|
|
c9a600b6d6 | ||
|
|
19461098a0 | ||
|
|
74dcc8e5ac | ||
|
|
bd1043a3f4 | ||
|
|
107cd9753e | ||
|
|
194604004e | ||
|
|
bb920ce6f0 | ||
|
|
c0315a705d | ||
|
|
fbc437a670 | ||
|
|
e0f0700398 | ||
|
|
defd9685e0 | ||
|
|
1ed62b0d3f | ||
|
|
91de6df04d | ||
|
|
a5d97d65e1 | ||
|
|
f0128f66b0 | ||
|
|
b33c68feb0 | ||
|
|
15655e3987 | ||
|
|
d8b3864411 | ||
|
|
194cbd6ca8 | ||
|
|
d5445c2282 | ||
|
|
dcfefc8371 | ||
|
|
b5f14335c4 | ||
|
|
d44ac949b5 | ||
|
|
a5e939221d | ||
|
|
833e3e5a9c | ||
|
|
ba1975dd6d | ||
|
|
3025ef3d21 | ||
|
|
8564f8af83 |
@@ -7,6 +7,7 @@ package-lock.json
|
|||||||
# Build outputs
|
# Build outputs
|
||||||
dist/
|
dist/
|
||||||
.next/
|
.next/
|
||||||
|
.next-build/
|
||||||
out/
|
out/
|
||||||
build/
|
build/
|
||||||
|
|
||||||
@@ -56,6 +57,10 @@ yarn-error.log*
|
|||||||
# Testing
|
# Testing
|
||||||
coverage/
|
coverage/
|
||||||
|
|
||||||
|
# Go photo-api service
|
||||||
|
photo-api/bin/
|
||||||
|
photo-api/data/
|
||||||
|
|
||||||
# Misc
|
# Misc
|
||||||
*.pem
|
*.pem
|
||||||
|
|
||||||
|
|||||||
@@ -4,17 +4,24 @@ A full-stack web app for organizing and managing language exchange events (Asunc
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Public site**: events, booking, contact, community, legal pages, bilingual (EN/ES)
|
- **Public site**: events, booking, contact, community, **photo galleries**, legal pages, bilingual (EN/ES)
|
||||||
- **User dashboard**: profile, tickets, payments, sessions/security
|
- Stable `/next` and `/featured` URLs that redirect to the current event
|
||||||
- **Admin** (`/admin`): events, tickets/check-in, users/roles, payments, email templates, media uploads
|
- Human-readable event URL slugs (with legacy-ID redirect support)
|
||||||
|
- **User dashboard**: overview tab, profile, tickets, payments, sessions/security
|
||||||
|
- Lightning invoice reuse and re-payment straight from the dashboard
|
||||||
|
- **Admin** (`/admin`): events, tickets/check-in, users/roles, payments, email templates, media uploads, **photo galleries**
|
||||||
|
- One unified ticket-creation modal with first-class payment status
|
||||||
|
- **Payments**: one automatic provider (**Lightning** via LNbits) plus manual providers (**TPago link**, bank transfer, card, cash), all defined in a central provider registry. Manual payments stay pending until an admin reconciles them (they are not auto-failed after the pending TTL).
|
||||||
|
- **Photo galleries** (standalone `photo-api` Go service): admins upload event photos, group them into galleries, and share them by visibility mode (public / private / share-link / ticket-holders). See [`photo-api/`](photo-api/README.md).
|
||||||
- **API**: Swagger UI at `/api-docs`, OpenAPI JSON at `/openapi.json`, health check at `/health`
|
- **API**: Swagger UI at `/api-docs`, OpenAPI JSON at `/openapi.json`, health check at `/health`
|
||||||
|
|
||||||
## Tech stack
|
## Tech stack
|
||||||
|
|
||||||
- **Backend**: Node.js + TypeScript, Hono, Drizzle ORM, SQLite (default) or PostgreSQL
|
- **Backend**: Node.js + TypeScript, Hono, Drizzle ORM, SQLite (default) or PostgreSQL
|
||||||
- **Auth**: JWT (via `jose`), **Argon2id** password hashing (with legacy bcrypt verification for older hashes)
|
- **Photo service**: standalone Go module (`photo-api/`), its own binary/deploy unit, sharing the backend database and `JWT_SECRET`
|
||||||
|
- **Auth**: [Better Auth](https://better-auth.com) — httpOnly cookie sessions (DB-validated on every request for instant revocation), **Argon2id** password hashing (with legacy bcrypt verification for older hashes), magic links, Google sign-in, admin ban/suspend
|
||||||
- **Email**: `nodemailer` (SMTP) with optional provider config
|
- **Email**: `nodemailer` (SMTP) with optional provider config
|
||||||
- **Frontend**: Next.js 14 (App Router), Tailwind CSS, Heroicons
|
- **Frontend**: Next.js (App Router), Tailwind CSS, Heroicons, skeleton loading states, custom error / global-error pages
|
||||||
|
|
||||||
## Local development
|
## Local development
|
||||||
|
|
||||||
@@ -22,6 +29,8 @@ A full-stack web app for organizing and managing language exchange events (Asunc
|
|||||||
|
|
||||||
- Node.js 18+
|
- Node.js 18+
|
||||||
- npm
|
- npm
|
||||||
|
- Go 1.26+ (for the `photo-api` service)
|
||||||
|
- Optional: `libvips-tools` (or `libheif-examples`) on the host to accept HEIC photo uploads
|
||||||
|
|
||||||
### Setup
|
### Setup
|
||||||
|
|
||||||
@@ -29,12 +38,14 @@ A full-stack web app for organizing and managing language exchange events (Asunc
|
|||||||
npm install
|
npm install
|
||||||
cp backend/.env.example backend/.env
|
cp backend/.env.example backend/.env
|
||||||
cp frontend/.env.example frontend/.env
|
cp frontend/.env.example frontend/.env
|
||||||
|
cp photo-api/.env.example photo-api/.env # set JWT_SECRET + DATABASE_URL to match backend/.env
|
||||||
```
|
```
|
||||||
|
|
||||||
### Initialize database (SQLite by default)
|
### Initialize database (SQLite by default)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run db:migrate
|
npm run db:migrate # backend (Drizzle) tables
|
||||||
|
npm run migrate:photos # photo-api owns only the photos_* tables via its own migrations
|
||||||
```
|
```
|
||||||
|
|
||||||
### Run
|
### Run
|
||||||
@@ -43,10 +54,13 @@ npm run db:migrate
|
|||||||
npm run dev
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`npm run dev` starts the backend, frontend, and photo-api together (via `concurrently`).
|
||||||
|
|
||||||
Default URLs:
|
Default URLs:
|
||||||
|
|
||||||
- Frontend: `http://localhost:3002`
|
- Frontend: `http://localhost:3002`
|
||||||
- Backend API: `http://localhost:3001`
|
- Backend API: `http://localhost:3001`
|
||||||
|
- Photo API: `http://localhost:3003` (the Next dev server rewrites `/api/photos/*` to it)
|
||||||
- API docs: `http://localhost:3001/api-docs`
|
- API docs: `http://localhost:3001/api-docs`
|
||||||
|
|
||||||
### First user becomes admin
|
### First user becomes admin
|
||||||
@@ -58,16 +72,37 @@ The first user to register becomes the **admin**. Register at `/register`.
|
|||||||
Run these from the repo root:
|
Run these from the repo root:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run dev
|
npm run dev # backend + frontend + photo-api
|
||||||
npm run build
|
npm run build # build all workspaces
|
||||||
npm run start
|
npm run start
|
||||||
npm run db:generate
|
npm run db:generate
|
||||||
npm run db:migrate
|
npm run db:migrate
|
||||||
npm run db:studio
|
npm run db:studio
|
||||||
npm run db:export # Backup database
|
npm run db:export # Backup database
|
||||||
npm run db:import # Restore from backup
|
npm run db:import # Restore from backup
|
||||||
|
|
||||||
|
# Photo service (Go)
|
||||||
|
npm run dev:photos # go run ./cmd/photo-api
|
||||||
|
npm run build:photos # go build -o bin/photo-api
|
||||||
|
npm run migrate:photos # apply photos_* migrations
|
||||||
|
npm run test:photos # go test ./...
|
||||||
|
|
||||||
|
# Move the photo library between storage backends (both must be configured
|
||||||
|
# in photo-api/.env; the source is left untouched, reruns skip what is there)
|
||||||
|
npm run sync:photos:to-s3 # local disk -> S3
|
||||||
|
npm run sync:photos:to-local # S3 -> local disk
|
||||||
|
npm run sync:photos -- to-s3 --dry-run # flags: --dry-run --overwrite
|
||||||
|
# --concurrency=N --gallery=<id>
|
||||||
|
|
||||||
|
# Uploads are deduplicated per gallery by content hash. Photos uploaded before
|
||||||
|
# that existed need hashing once (idempotent, deletes nothing):
|
||||||
|
npm run backfill:photos:checksums
|
||||||
```
|
```
|
||||||
|
|
||||||
|
After a sync, set `STORAGE_BACKEND=s3` (or `local`) in `photo-api/.env` and
|
||||||
|
restart the service to serve from the new backend. See
|
||||||
|
[`photo-api/README.md`](photo-api/README.md#move-the-library-between-backends).
|
||||||
|
|
||||||
You can also run per workspace:
|
You can also run per workspace:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -82,20 +117,34 @@ npm run dev --workspace=frontend
|
|||||||
Key settings (see `backend/.env.example` for the full list):
|
Key settings (see `backend/.env.example` for the full list):
|
||||||
|
|
||||||
- **DB**: `DB_TYPE=sqlite|postgres`, `DATABASE_URL=./data/spanglish.db` (or Postgres URL)
|
- **DB**: `DB_TYPE=sqlite|postgres`, `DATABASE_URL=./data/spanglish.db` (or Postgres URL)
|
||||||
- **Auth**: `JWT_SECRET` (change in production)
|
- **Auth**: `BETTER_AUTH_SECRET` (required in production, 32+ chars), `BETTER_AUTH_URL` (public site origin; falls back to `FRONTEND_URL`), optional `GOOGLE_CLIENT_ID`/`GOOGLE_CLIENT_SECRET`
|
||||||
|
- **Auth cookie scope**: `AUTH_COOKIE_DOMAIN` (optional, e.g. `.spanglishcommunity.com`) — set it only when the API is served from a different host than the site. The session cookie is host-only by default, so a cookie issued by `api.example.com` is invisible to the frontend's Next middleware on `example.com` and every `/dashboard`/`/admin` visit bounces back to `/login`. Leave empty in development.
|
||||||
- **URLs/ports**: `PORT`, `API_URL`, `FRONTEND_URL`
|
- **URLs/ports**: `PORT`, `API_URL`, `FRONTEND_URL`
|
||||||
- **Email**: `EMAIL_PROVIDER` (`console|smtp|resend`) and corresponding credentials
|
- **Email**: `EMAIL_PROVIDER` (`console|smtp|resend`) and corresponding credentials
|
||||||
- **Payments (optional)**: Stripe/MercadoPago/LNbits configuration
|
- **Payments (optional)**: LNbits (Lightning) configuration for the automatic provider. Manual providers (TPago link, bank transfer, card, cash) need no API keys — the TPago pay link is configured and sent via an email template.
|
||||||
- **Scaling (optional)**: `REDIS_URL`, `DB_POOL_MAX`, and `S3_*` (see "Horizontal scaling" below)
|
- **Scaling (optional)**: `REDIS_URL`, `DB_POOL_MAX`, and `S3_*` (see "Horizontal scaling" below)
|
||||||
|
|
||||||
|
### Photo service (`photo-api/.env`)
|
||||||
|
|
||||||
|
Key settings (see `photo-api/.env.example`):
|
||||||
|
|
||||||
|
- **Port**: `PORT=3003` (dev)
|
||||||
|
- **DB**: `DB_TYPE` and `DATABASE_URL` — point at the **same** database as the backend
|
||||||
|
- **Auth**: none needed for user auth — the service validates Better Auth session cookies against the shared database. `PHOTO_VIEW_SECRET` signs gallery image view tokens (falls back to `JWT_SECRET` during migration).
|
||||||
|
- **Storage**: `STORAGE_PATH` (local disk) or `S3_ENDPOINT` + `S3_BUCKET` (S3/Garage/MinIO); S3 downloads use short-lived presigned URLs
|
||||||
|
- **Storage switch**: `STORAGE_BACKEND=auto|local|s3` (`auto` = S3 when it is configured). Keep both sides configured and flip this one line to move between them; `npm run sync:photos:to-s3` / `:to-local` copies the existing library first
|
||||||
|
- **Uploads/worker**: `MAX_UPLOAD_MB`, `WORKER_CONCURRENCY` (a worker generates thumb/preview JPEG variants with EXIF stripped)
|
||||||
|
|
||||||
### Frontend (`frontend/.env`)
|
### Frontend (`frontend/.env`)
|
||||||
|
|
||||||
Key settings (see `frontend/.env.example`):
|
Key settings (see `frontend/.env.example`):
|
||||||
|
|
||||||
- **Server port**: `PORT=3002`
|
- **Server port**: `PORT=3002`
|
||||||
- **API base URL**: `NEXT_PUBLIC_API_URL` (optional)
|
- **API base URL**: `NEXT_PUBLIC_API_URL` (optional)
|
||||||
- Leave empty to use same-origin `/api` (recommended when running behind nginx)
|
- Leave empty to use same-origin `/api` (recommended when running behind nginx). Requests become relative paths, so nginx maps them to the backend port in production and the Next.js rewrites do it in dev — the browser never needs to know the port.
|
||||||
- In local dev, Next.js rewrites `/api/*` and `/uploads/*` to the backend
|
- Inlined at build time: changing it requires a rebuild, not just a restart.
|
||||||
|
- Pointing it at a separate API host (e.g. `https://api.example.com`) puts the session cookie on that host, where the Next middleware guarding `/admin` and `/dashboard` cannot read it. If you do that, set `AUTH_COOKIE_DOMAIN` on the backend as well.
|
||||||
|
- **Server-side API hosts**: `PHOTO_API_URL` (server-rendered `/photos` pages and the sitemap) and `BACKEND_URL` — server components cannot use relative URLs, so these are needed even when `NEXT_PUBLIC_API_URL` is empty. In production point them at loopback (`http://127.0.0.1:3020` / `http://127.0.0.1:3018`).
|
||||||
- **Social links (optional)**: `NEXT_PUBLIC_WHATSAPP`, `NEXT_PUBLIC_INSTAGRAM`, etc.
|
- **Social links (optional)**: `NEXT_PUBLIC_WHATSAPP`, `NEXT_PUBLIC_INSTAGRAM`, etc.
|
||||||
|
|
||||||
## Database
|
## Database
|
||||||
@@ -143,12 +192,13 @@ npm run db:import -- --yes ./data/backups/spanglish-2025-03-07.sql # Skip conf
|
|||||||
|
|
||||||
This repo includes example configs in `deploy/`:
|
This repo includes example configs in `deploy/`:
|
||||||
|
|
||||||
- **systemd**: `deploy/spanglish-backend.service`, `deploy/spanglish-frontend.service`
|
- **systemd**: `deploy/spanglish-backend.service`, `deploy/spanglish-frontend.service`, `deploy/spanglish-photos.service`
|
||||||
- Backend runs on **3018**, frontend on **3019** by default (see the unit files)
|
- Backend runs on **3018**, frontend on **3019**, photo-api on **3020** by default (see the unit files)
|
||||||
- Backend needs write access to `backend/data` and `backend/uploads`
|
- Backend needs write access to `backend/data` and `backend/uploads`
|
||||||
|
- The photo service runs its own migrations on start (`photo-api migrate`) and needs write access to its `STORAGE_PATH` (or S3 config)
|
||||||
- **nginx**:
|
- **nginx**:
|
||||||
- `deploy/spanglish_upstreams.conf` defines upstreams for ports 3018/3019
|
- `deploy/spanglish_upstreams.conf` defines upstreams for ports 3018/3019/3020
|
||||||
- `deploy/front-end_nginx.conf` proxies `/api` and `/uploads` to the backend and everything else to the frontend
|
- `deploy/front-end_nginx.conf` proxies `/api/photos` to the photo service, `/api` and `/uploads` to the backend, and everything else to the frontend
|
||||||
- `deploy/back-end_nginx.conf` is a dedicated API vhost example with CORS handling
|
- `deploy/back-end_nginx.conf` is a dedicated API vhost example with CORS handling
|
||||||
|
|
||||||
Typical production flow:
|
Typical production flow:
|
||||||
@@ -156,7 +206,9 @@ Typical production flow:
|
|||||||
```bash
|
```bash
|
||||||
npm ci
|
npm ci
|
||||||
npm run build
|
npm run build
|
||||||
|
npm run build:photos
|
||||||
npm run db:migrate
|
npm run db:migrate
|
||||||
|
npm run migrate:photos
|
||||||
```
|
```
|
||||||
|
|
||||||
Then install/enable the systemd services and nginx configs for your server.
|
Then install/enable the systemd services and nginx configs for your server.
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+40
-4
@@ -22,10 +22,18 @@ DATABASE_URL=./data/spanglish.db
|
|||||||
# Note: running more than one instance requires DB_TYPE=postgres. SQLite is a
|
# Note: running more than one instance requires DB_TYPE=postgres. SQLite is a
|
||||||
# single local file and cannot be shared safely across instances.
|
# single local file and cannot be shared safely across instances.
|
||||||
|
|
||||||
# Redis connection URL. When set, the cache, rate limiter, pub/sub (real-time
|
# Redis connection URL. When set, the cache, rate limiter, login lockout,
|
||||||
# payment events), distributed locks, and the email hourly cap are shared across
|
# pub/sub (real-time payment events), distributed locks, and the email hourly
|
||||||
# all instances. When unset, each instance uses in-memory equivalents.
|
# cap are shared across all instances. When unset, each instance uses in-memory
|
||||||
|
# equivalents.
|
||||||
|
#
|
||||||
|
# In production always set a password (requirepass on the server) and put it in
|
||||||
|
# the URL. Use the rediss:// scheme for TLS (handled natively by the client),
|
||||||
|
# and an optional /N path to select a DB index when sharing a Redis instance
|
||||||
|
# with other applications.
|
||||||
# REDIS_URL=redis://localhost:6379
|
# REDIS_URL=redis://localhost:6379
|
||||||
|
# REDIS_URL=redis://:your-redis-password@redis.internal:6379
|
||||||
|
# REDIS_URL=rediss://:your-redis-password@redis.example.com:6380/1
|
||||||
|
|
||||||
# Optional S3-compatible object storage for media uploads (e.g. Garage, MinIO,
|
# Optional S3-compatible object storage for media uploads (e.g. Garage, MinIO,
|
||||||
# AWS S3). When S3_ENDPOINT and S3_BUCKET are set, uploads go to the bucket and
|
# AWS S3). When S3_ENDPOINT and S3_BUCKET are set, uploads go to the bucket and
|
||||||
@@ -42,13 +50,41 @@ DATABASE_URL=./data/spanglish.db
|
|||||||
# Use path-style addressing (true for Garage/MinIO). Defaults to true.
|
# Use path-style addressing (true for Garage/MinIO). Defaults to true.
|
||||||
# S3_FORCE_PATH_STYLE=true
|
# S3_FORCE_PATH_STYLE=true
|
||||||
|
|
||||||
# JWT Secret (change in production!)
|
# Better Auth session secret. REQUIRED in production, 32+ characters.
|
||||||
|
# Generate one with: openssl rand -base64 48
|
||||||
|
# Rotating it signs everyone out (cookie signatures invalidate).
|
||||||
|
BETTER_AUTH_SECRET=
|
||||||
|
|
||||||
|
# Public site origin Better Auth builds its URLs against (falls back to
|
||||||
|
# FRONTEND_URL when unset). E.g. https://spanglishcommunity.com
|
||||||
|
BETTER_AUTH_URL=
|
||||||
|
|
||||||
|
# Session cookie domain, shared across subdomains. Set this when the API is served
|
||||||
|
# from a different host than the site (e.g. api.spanglishcommunity.com vs
|
||||||
|
# spanglishcommunity.com): without it the cookie is host-only and the frontend's
|
||||||
|
# Next middleware cannot see it, so /dashboard and /admin bounce back to /login.
|
||||||
|
# Must start with a dot. Leave EMPTY in development (localhost is single-host).
|
||||||
|
# E.g. .spanglishcommunity.com
|
||||||
|
AUTH_COOKIE_DOMAIN=
|
||||||
|
|
||||||
|
# Extra reverse-proxy IP prefixes allowed to set X-Real-IP / X-Forwarded-For
|
||||||
|
# (comma-separated, e.g. "172.20."). Loopback and RFC1918 ranges are always
|
||||||
|
# trusted; anything else is treated as a client and rate-limited by its
|
||||||
|
# actual socket address.
|
||||||
|
# TRUSTED_PROXIES=
|
||||||
|
|
||||||
|
# DEPRECATED: no longer used for API auth (Better Auth replaced the JWTs).
|
||||||
|
# Still read by photo-api as the fallback secret for gallery view tokens
|
||||||
|
# until PHOTO_VIEW_SECRET is set there; safe to remove after that.
|
||||||
JWT_SECRET=your-super-secret-key-change-in-production
|
JWT_SECRET=your-super-secret-key-change-in-production
|
||||||
|
|
||||||
# Google OAuth (optional - for Google Sign-In)
|
# Google OAuth (optional - for Google Sign-In)
|
||||||
# Get your Client ID from: https://console.cloud.google.com/apis/credentials
|
# Get your Client ID from: https://console.cloud.google.com/apis/credentials
|
||||||
# Note: The same Client ID should be used in frontend/.env
|
# Note: The same Client ID should be used in frontend/.env
|
||||||
GOOGLE_CLIENT_ID=
|
GOOGLE_CLIENT_ID=
|
||||||
|
# Only needed for the redirect OAuth flow; the Google Identity Services
|
||||||
|
# button (ID token sign-in) works with the Client ID alone.
|
||||||
|
GOOGLE_CLIENT_SECRET=
|
||||||
|
|
||||||
# Server Configuration
|
# Server Configuration
|
||||||
PORT=3001
|
PORT=3001
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 64 KiB |
@@ -5,6 +5,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "tsx watch src/index.ts",
|
"dev": "tsx watch src/index.ts",
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
|
"test": "vitest run",
|
||||||
"start": "NODE_ENV=production node dist/index.js",
|
"start": "NODE_ENV=production node dist/index.js",
|
||||||
"db:generate": "drizzle-kit generate",
|
"db:generate": "drizzle-kit generate",
|
||||||
"db:migrate": "tsx src/db/migrate.ts",
|
"db:migrate": "tsx src/db/migrate.ts",
|
||||||
@@ -19,9 +20,10 @@
|
|||||||
"@hono/zod-openapi": "^0.14.4",
|
"@hono/zod-openapi": "^0.14.4",
|
||||||
"argon2": "^0.44.0",
|
"argon2": "^0.44.0",
|
||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
"better-sqlite3": "^11.0.0",
|
"better-auth": "1.6.25",
|
||||||
|
"better-sqlite3": "^12.11.1",
|
||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
"drizzle-orm": "^0.31.2",
|
"drizzle-orm": "^0.45.2",
|
||||||
"hono": "^4.4.7",
|
"hono": "^4.4.7",
|
||||||
"ioredis": "^5.11.1",
|
"ioredis": "^5.11.1",
|
||||||
"jose": "^5.4.0",
|
"jose": "^5.4.0",
|
||||||
@@ -41,8 +43,10 @@
|
|||||||
"@types/pdfkit": "^0.17.4",
|
"@types/pdfkit": "^0.17.4",
|
||||||
"@types/pg": "^8.11.6",
|
"@types/pg": "^8.11.6",
|
||||||
"@types/qrcode": "^1.5.6",
|
"@types/qrcode": "^1.5.6",
|
||||||
"drizzle-kit": "^0.22.8",
|
"drizzle-kit": "^0.31.10",
|
||||||
|
"ioredis-mock": "^8.13.1",
|
||||||
"tsx": "^4.15.7",
|
"tsx": "^4.15.7",
|
||||||
"typescript": "^5.5.2"
|
"typescript": "^5.5.2",
|
||||||
|
"vitest": "^4.1.10"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,200 @@
|
|||||||
|
import { sqliteTable, text, integer, customType as sqliteCustomType } from 'drizzle-orm/sqlite-core';
|
||||||
|
import {
|
||||||
|
pgTable,
|
||||||
|
uuid,
|
||||||
|
varchar,
|
||||||
|
text as pgText,
|
||||||
|
timestamp,
|
||||||
|
boolean as pgBoolean,
|
||||||
|
bigint,
|
||||||
|
customType as pgCustomType,
|
||||||
|
} from 'drizzle-orm/pg-core';
|
||||||
|
|
||||||
|
// Better Auth table definitions for both dialects.
|
||||||
|
//
|
||||||
|
// The `user` model maps onto the EXISTING `users` table so user IDs (and every
|
||||||
|
// foreign key that references them) survive the auth migration untouched. Only
|
||||||
|
// the columns Better Auth reads/writes are declared here; legacy columns
|
||||||
|
// (password, google_id, token_version) stay physically present but invisible
|
||||||
|
// to Better Auth. The full application-facing definition lives in schema.ts —
|
||||||
|
// two Drizzle table objects can safely describe the same SQL table.
|
||||||
|
const dbType = process.env.DB_TYPE || 'sqlite';
|
||||||
|
|
||||||
|
// Better Auth hands the adapter JS Date objects, but the legacy sqlite `users`
|
||||||
|
// timestamps are ISO-8601 TEXT columns. Bridge the two representations.
|
||||||
|
const isoText = sqliteCustomType<{ data: Date; driverData: string }>({
|
||||||
|
dataType() {
|
||||||
|
return 'text';
|
||||||
|
},
|
||||||
|
toDriver(value: Date): string {
|
||||||
|
return (value instanceof Date ? value : new Date(value)).toISOString();
|
||||||
|
},
|
||||||
|
fromDriver(value: string): Date {
|
||||||
|
return new Date(value);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Legacy pg `users.is_claimed` is an INTEGER 0/1 column; expose it as boolean.
|
||||||
|
const pgIntBool = pgCustomType<{ data: boolean; driverData: number }>({
|
||||||
|
dataType() {
|
||||||
|
return 'integer';
|
||||||
|
},
|
||||||
|
toDriver(value: boolean): number {
|
||||||
|
return value ? 1 : 0;
|
||||||
|
},
|
||||||
|
fromDriver(value: number | boolean): boolean {
|
||||||
|
return Boolean(value);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== SQLite ====================
|
||||||
|
|
||||||
|
export const sqliteAuthUsers = sqliteTable('users', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
name: text('name').notNull(),
|
||||||
|
email: text('email').notNull().unique(),
|
||||||
|
emailVerified: integer('email_verified', { mode: 'boolean' }).notNull().default(false),
|
||||||
|
image: text('image'),
|
||||||
|
createdAt: isoText('created_at').notNull(),
|
||||||
|
updatedAt: isoText('updated_at').notNull(),
|
||||||
|
// admin plugin fields
|
||||||
|
role: text('role').notNull().default('user'),
|
||||||
|
banned: integer('banned', { mode: 'boolean' }).notNull().default(false),
|
||||||
|
banReason: text('ban_reason'),
|
||||||
|
banExpires: integer('ban_expires', { mode: 'timestamp_ms' }),
|
||||||
|
// application additionalFields
|
||||||
|
phone: text('phone'),
|
||||||
|
languagePreference: text('language_preference'),
|
||||||
|
rucNumber: text('ruc_number'),
|
||||||
|
isClaimed: integer('is_claimed', { mode: 'boolean' }).notNull().default(true),
|
||||||
|
accountStatus: text('account_status').notNull().default('active'),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteAuthSessions = sqliteTable('auth_sessions', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
userId: text('user_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => sqliteAuthUsers.id, { onDelete: 'cascade' }),
|
||||||
|
token: text('token').notNull().unique(),
|
||||||
|
expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
|
||||||
|
ipAddress: text('ip_address'),
|
||||||
|
userAgent: text('user_agent'),
|
||||||
|
// admin plugin (impersonation)
|
||||||
|
impersonatedBy: text('impersonated_by'),
|
||||||
|
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
|
||||||
|
updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteAuthAccounts = sqliteTable('auth_accounts', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
userId: text('user_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => sqliteAuthUsers.id, { onDelete: 'cascade' }),
|
||||||
|
accountId: text('account_id').notNull(),
|
||||||
|
providerId: text('provider_id').notNull(),
|
||||||
|
accessToken: text('access_token'),
|
||||||
|
refreshToken: text('refresh_token'),
|
||||||
|
idToken: text('id_token'),
|
||||||
|
accessTokenExpiresAt: integer('access_token_expires_at', { mode: 'timestamp_ms' }),
|
||||||
|
refreshTokenExpiresAt: integer('refresh_token_expires_at', { mode: 'timestamp_ms' }),
|
||||||
|
scope: text('scope'),
|
||||||
|
password: text('password'),
|
||||||
|
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
|
||||||
|
updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteAuthVerifications = sqliteTable('auth_verifications', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
identifier: text('identifier').notNull(),
|
||||||
|
value: text('value').notNull(),
|
||||||
|
expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
|
||||||
|
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
|
||||||
|
updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteAuthRateLimits = sqliteTable('auth_rate_limits', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
key: text('key'),
|
||||||
|
count: integer('count'),
|
||||||
|
lastRequest: integer('last_request'),
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== PostgreSQL ====================
|
||||||
|
|
||||||
|
export const pgAuthUsers = pgTable('users', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
name: varchar('name', { length: 255 }).notNull(),
|
||||||
|
email: varchar('email', { length: 255 }).notNull().unique(),
|
||||||
|
emailVerified: pgBoolean('email_verified').notNull().default(false),
|
||||||
|
image: pgText('image'),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
// admin plugin fields
|
||||||
|
role: varchar('role', { length: 20 }).notNull().default('user'),
|
||||||
|
banned: pgBoolean('banned').notNull().default(false),
|
||||||
|
banReason: pgText('ban_reason'),
|
||||||
|
banExpires: timestamp('ban_expires'),
|
||||||
|
// application additionalFields
|
||||||
|
phone: varchar('phone', { length: 50 }),
|
||||||
|
languagePreference: varchar('language_preference', { length: 10 }),
|
||||||
|
rucNumber: varchar('ruc_number', { length: 15 }),
|
||||||
|
isClaimed: pgIntBool('is_claimed').notNull(),
|
||||||
|
accountStatus: varchar('account_status', { length: 20 }).notNull().default('active'),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgAuthSessions = pgTable('auth_sessions', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
userId: uuid('user_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => pgAuthUsers.id, { onDelete: 'cascade' }),
|
||||||
|
token: varchar('token', { length: 255 }).notNull().unique(),
|
||||||
|
expiresAt: timestamp('expires_at').notNull(),
|
||||||
|
ipAddress: varchar('ip_address', { length: 45 }),
|
||||||
|
userAgent: pgText('user_agent'),
|
||||||
|
// admin plugin (impersonation)
|
||||||
|
impersonatedBy: uuid('impersonated_by'),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgAuthAccounts = pgTable('auth_accounts', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
userId: uuid('user_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => pgAuthUsers.id, { onDelete: 'cascade' }),
|
||||||
|
accountId: varchar('account_id', { length: 255 }).notNull(),
|
||||||
|
providerId: varchar('provider_id', { length: 100 }).notNull(),
|
||||||
|
accessToken: pgText('access_token'),
|
||||||
|
refreshToken: pgText('refresh_token'),
|
||||||
|
idToken: pgText('id_token'),
|
||||||
|
accessTokenExpiresAt: timestamp('access_token_expires_at'),
|
||||||
|
refreshTokenExpiresAt: timestamp('refresh_token_expires_at'),
|
||||||
|
scope: pgText('scope'),
|
||||||
|
password: pgText('password'),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgAuthVerifications = pgTable('auth_verifications', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
identifier: varchar('identifier', { length: 255 }).notNull(),
|
||||||
|
value: pgText('value').notNull(),
|
||||||
|
expiresAt: timestamp('expires_at').notNull(),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgAuthRateLimits = pgTable('auth_rate_limits', {
|
||||||
|
id: varchar('id', { length: 64 }).primaryKey(),
|
||||||
|
key: varchar('key', { length: 255 }),
|
||||||
|
count: bigint('count', { mode: 'number' }),
|
||||||
|
lastRequest: bigint('last_request', { mode: 'number' }),
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Runtime-switched exports ====================
|
||||||
|
|
||||||
|
export const authUsers = dbType === 'postgres' ? pgAuthUsers : sqliteAuthUsers;
|
||||||
|
export const authSessions = dbType === 'postgres' ? pgAuthSessions : sqliteAuthSessions;
|
||||||
|
export const authAccounts = dbType === 'postgres' ? pgAuthAccounts : sqliteAuthAccounts;
|
||||||
|
export const authVerifications = dbType === 'postgres' ? pgAuthVerifications : sqliteAuthVerifications;
|
||||||
|
export const authRateLimits = dbType === 'postgres' ? pgAuthRateLimits : sqliteAuthRateLimits;
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import { describe, it, expect, beforeAll } from 'vitest';
|
||||||
|
import { execFileSync } from 'child_process';
|
||||||
|
import { mkdtempSync } from 'fs';
|
||||||
|
import { tmpdir } from 'os';
|
||||||
|
import { join } from 'path';
|
||||||
|
import Database from 'better-sqlite3';
|
||||||
|
|
||||||
|
// Migration idempotency for the Better Auth backfill: seed legacy-shaped user
|
||||||
|
// rows, run migrate repeatedly, and assert the backfill is correct and never
|
||||||
|
// duplicates.
|
||||||
|
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'ba-migrate-test-'));
|
||||||
|
const dbPath = join(dir, 'migrate.db');
|
||||||
|
|
||||||
|
function runMigrate() {
|
||||||
|
execFileSync('npx', ['tsx', 'src/db/migrate.ts'], {
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
DB_TYPE: 'sqlite',
|
||||||
|
DATABASE_URL: dbPath,
|
||||||
|
REDIS_URL: '',
|
||||||
|
},
|
||||||
|
stdio: 'pipe',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let db: Database.Database;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
// First run creates the schema
|
||||||
|
runMigrate();
|
||||||
|
db = new Database(dbPath);
|
||||||
|
|
||||||
|
// Seed legacy-shaped users (pre-Better-Auth): password lives on users,
|
||||||
|
// google_id links Google, '' marks guest accounts, suspended via status.
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const insert = db.prepare(
|
||||||
|
`INSERT INTO users (id, email, password, name, role, is_claimed, google_id, account_status, token_version, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`
|
||||||
|
);
|
||||||
|
insert.run('legacy-argon', 'argon@old.py', '$argon2id$v=19$m=65536,t=3,p=4$fake', 'Argon', 'user', 1, null, 'active', now, now);
|
||||||
|
insert.run('legacy-bcrypt', 'bcrypt@old.py', '$2a$10$fakebcryptfakebcryptfakebc', 'Bcrypt', 'admin', 1, null, 'active', now, now);
|
||||||
|
insert.run('legacy-guest', 'guest@old.py', '', 'Guest', 'user', 1, null, 'active', now, now);
|
||||||
|
insert.run('legacy-google', 'google@old.py', null, 'Google', 'user', 1, 'google-sub-123', 'active', now, now);
|
||||||
|
insert.run('legacy-both', 'both@old.py', '$argon2id$v=19$m=65536,t=3,p=4$fake2', 'Both', 'user', 1, 'google-sub-456', 'active', now, now);
|
||||||
|
insert.run('legacy-suspended', 'suspended@old.py', '$argon2id$v=19$m=65536,t=3,p=4$fake3', 'Bad', 'user', 1, null, 'suspended', now, now);
|
||||||
|
|
||||||
|
// Second run performs the backfill against the seeded rows
|
||||||
|
runMigrate();
|
||||||
|
}, 240_000);
|
||||||
|
|
||||||
|
describe('Better Auth migration backfill', () => {
|
||||||
|
it('creates credential accounts for users with real passwords only', () => {
|
||||||
|
const rows = db
|
||||||
|
.prepare("SELECT user_id, password FROM auth_accounts WHERE provider_id = 'credential' ORDER BY user_id")
|
||||||
|
.all() as any[];
|
||||||
|
const byUser = new Map(rows.map((r) => [r.user_id, r.password]));
|
||||||
|
|
||||||
|
expect(byUser.get('legacy-argon')).toContain('$argon2id$');
|
||||||
|
expect(byUser.get('legacy-bcrypt')).toContain('$2a$');
|
||||||
|
expect(byUser.get('legacy-both')).toContain('$argon2id$');
|
||||||
|
expect(byUser.get('legacy-suspended')).toBeTruthy();
|
||||||
|
// Guests ('' password) and Google-only users get no credential account
|
||||||
|
expect(byUser.has('legacy-guest')).toBe(false);
|
||||||
|
expect(byUser.has('legacy-google')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates google accounts from google_id', () => {
|
||||||
|
const rows = db
|
||||||
|
.prepare("SELECT user_id, account_id FROM auth_accounts WHERE provider_id = 'google' ORDER BY user_id")
|
||||||
|
.all() as any[];
|
||||||
|
expect(rows).toEqual([
|
||||||
|
{ user_id: 'legacy-both', account_id: 'google-sub-456' },
|
||||||
|
{ user_id: 'legacy-google', account_id: 'google-sub-123' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks claimed legacy users email-verified, guests not', () => {
|
||||||
|
const verified = (email: string) =>
|
||||||
|
(db.prepare('SELECT email_verified FROM users WHERE email = ?').get(email) as any).email_verified;
|
||||||
|
expect(verified('argon@old.py')).toBe(1);
|
||||||
|
expect(verified('google@old.py')).toBe(1);
|
||||||
|
expect(verified('guest@old.py')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mirrors suspended accounts to banned', () => {
|
||||||
|
const row = db.prepare('SELECT banned, ban_reason FROM users WHERE email = ?').get('suspended@old.py') as any;
|
||||||
|
expect(row.banned).toBe(1);
|
||||||
|
expect(row.ban_reason).toContain('suspended');
|
||||||
|
const active = db.prepare('SELECT banned FROM users WHERE email = ?').get('argon@old.py') as any;
|
||||||
|
expect(active.banned).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is idempotent: a third run adds nothing', () => {
|
||||||
|
const count = () => (db.prepare('SELECT COUNT(*) AS n FROM auth_accounts').get() as any).n;
|
||||||
|
const before = count();
|
||||||
|
runMigrate();
|
||||||
|
expect(count()).toBe(before);
|
||||||
|
}, 60_000);
|
||||||
|
});
|
||||||
+634
-5
@@ -1,7 +1,8 @@
|
|||||||
import 'dotenv/config';
|
import 'dotenv/config';
|
||||||
import { db, dbAll, events } from './index.js';
|
import { db, dbAll, dbGet, events, users, expenseCategories } from './index.js';
|
||||||
import { sql, eq } from 'drizzle-orm';
|
import { sql, eq, ne } from 'drizzle-orm';
|
||||||
import { uniqueSlug } from '../lib/slugify.js';
|
import { uniqueSlug } from '../lib/slugify.js';
|
||||||
|
import { generateId, getNow } from '../lib/utils.js';
|
||||||
|
|
||||||
const dbType = process.env.DB_TYPE || 'sqlite';
|
const dbType = process.env.DB_TYPE || 'sqlite';
|
||||||
console.log(`Database type: ${dbType}`);
|
console.log(`Database type: ${dbType}`);
|
||||||
@@ -94,6 +95,8 @@ async function migrate() {
|
|||||||
banner_url TEXT,
|
banner_url TEXT,
|
||||||
external_booking_enabled INTEGER NOT NULL DEFAULT 0,
|
external_booking_enabled INTEGER NOT NULL DEFAULT 0,
|
||||||
external_booking_url TEXT,
|
external_booking_url TEXT,
|
||||||
|
presale_closure_enabled INTEGER,
|
||||||
|
presale_close_minutes_before INTEGER,
|
||||||
created_at TEXT NOT NULL,
|
created_at TEXT NOT NULL,
|
||||||
updated_at TEXT NOT NULL
|
updated_at TEXT NOT NULL
|
||||||
)
|
)
|
||||||
@@ -107,6 +110,19 @@ async function migrate() {
|
|||||||
await (db as any).run(sql`ALTER TABLE events ADD COLUMN external_booking_url TEXT`);
|
await (db as any).run(sql`ALTER TABLE events ADD COLUMN external_booking_url TEXT`);
|
||||||
} catch (e) { /* column may already exist */ }
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Pre-sale closure per-event overrides (NULL = inherit site_settings default)
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE events ADD COLUMN presale_closure_enabled INTEGER`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE events ADD COLUMN presale_close_minutes_before INTEGER`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Walk-in (door) price. NULL = fall back to price; 0 = free walk-in.
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE events ADD COLUMN walk_in_price REAL`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
// Add short description columns to events
|
// Add short description columns to events
|
||||||
try {
|
try {
|
||||||
await (db as any).run(sql`ALTER TABLE events ADD COLUMN short_description TEXT`);
|
await (db as any).run(sql`ALTER TABLE events ADD COLUMN short_description TEXT`);
|
||||||
@@ -133,17 +149,25 @@ async function migrate() {
|
|||||||
`);
|
`);
|
||||||
|
|
||||||
await (db as any).run(sql`
|
await (db as any).run(sql`
|
||||||
|
-- Matches db/schema.ts. The legacy attendee_name / NOT NULL email+phone
|
||||||
|
-- shape only survives in databases created before the split into
|
||||||
|
-- first/last name, where the ALTERs below relaxed it; a fresh database
|
||||||
|
-- must not recreate constraints the app no longer satisfies (door
|
||||||
|
-- walk-ins have neither an email nor a phone).
|
||||||
CREATE TABLE IF NOT EXISTS tickets (
|
CREATE TABLE IF NOT EXISTS tickets (
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
user_id TEXT NOT NULL REFERENCES users(id),
|
user_id TEXT NOT NULL REFERENCES users(id),
|
||||||
event_id TEXT NOT NULL REFERENCES events(id),
|
event_id TEXT NOT NULL REFERENCES events(id),
|
||||||
attendee_name TEXT NOT NULL,
|
attendee_first_name TEXT NOT NULL,
|
||||||
attendee_email TEXT NOT NULL,
|
attendee_last_name TEXT,
|
||||||
attendee_phone TEXT NOT NULL,
|
attendee_email TEXT,
|
||||||
|
attendee_phone TEXT,
|
||||||
|
attendee_ruc TEXT,
|
||||||
preferred_language TEXT,
|
preferred_language TEXT,
|
||||||
status TEXT NOT NULL DEFAULT 'pending',
|
status TEXT NOT NULL DEFAULT 'pending',
|
||||||
checkin_at TEXT,
|
checkin_at TEXT,
|
||||||
qr_code TEXT,
|
qr_code TEXT,
|
||||||
|
admin_note TEXT,
|
||||||
created_at TEXT NOT NULL
|
created_at TEXT NOT NULL
|
||||||
)
|
)
|
||||||
`);
|
`);
|
||||||
@@ -200,6 +224,18 @@ async function migrate() {
|
|||||||
await (db as any).run(sql`ALTER TABLE tickets ADD COLUMN is_guest INTEGER NOT NULL DEFAULT 0`);
|
await (db as any).run(sql`ALTER TABLE tickets ADD COLUMN is_guest INTEGER NOT NULL DEFAULT 0`);
|
||||||
} catch (e) { /* column may already exist */ }
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Migration: Add payment_status column to tickets (paid | unpaid | comp),
|
||||||
|
// backfilled from is_guest and the payments table on first run
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE tickets ADD COLUMN payment_status TEXT NOT NULL DEFAULT 'unpaid'`);
|
||||||
|
await (db as any).run(sql`UPDATE tickets SET payment_status = 'comp' WHERE is_guest = 1`);
|
||||||
|
await (db as any).run(sql`
|
||||||
|
UPDATE tickets SET payment_status = 'paid'
|
||||||
|
WHERE is_guest = 0
|
||||||
|
AND id IN (SELECT ticket_id FROM payments WHERE status = 'paid')
|
||||||
|
`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
// Make attendee_email and attendee_phone nullable (recreate table if needed or just allow nulls for new entries)
|
// Make attendee_email and attendee_phone nullable (recreate table if needed or just allow nulls for new entries)
|
||||||
// SQLite doesn't support altering column constraints, so we'll just ensure new entries work
|
// SQLite doesn't support altering column constraints, so we'll just ensure new entries work
|
||||||
|
|
||||||
@@ -247,6 +283,40 @@ async function migrate() {
|
|||||||
try {
|
try {
|
||||||
await (db as any).run(sql`ALTER TABLE payments ADD COLUMN lnbits_amount_sats INTEGER`);
|
await (db as any).run(sql`ALTER TABLE payments ADD COLUMN lnbits_amount_sats INTEGER`);
|
||||||
} catch (e) { /* column may already exist */ }
|
} catch (e) { /* column may already exist */ }
|
||||||
|
// Door check-in screen: split pre-sale vs door revenue and record the tender
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE payments ADD COLUMN source TEXT NOT NULL DEFAULT 'presale'`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE payments ADD COLUMN method TEXT`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Idempotency records for door check-in actions (retries / double taps)
|
||||||
|
await (db as any).run(sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
scope TEXT NOT NULL,
|
||||||
|
result TEXT NOT NULL,
|
||||||
|
undo_state TEXT,
|
||||||
|
undone_at TEXT,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Migration: tickets.booking_source (online | walk_in | admin). On first run,
|
||||||
|
// backfill walk-ins created on the door screen: each one left an idempotency
|
||||||
|
// record whose undo_state is {kind: 'created', ticketId}. Nothing else can be
|
||||||
|
// identified reliably, so all other existing tickets stay 'online'.
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE tickets ADD COLUMN booking_source TEXT NOT NULL DEFAULT 'online'`);
|
||||||
|
await (db as any).run(sql`
|
||||||
|
UPDATE tickets SET booking_source = 'walk_in'
|
||||||
|
WHERE id IN (
|
||||||
|
SELECT json_extract(undo_state, '$.ticketId') FROM idempotency_keys
|
||||||
|
WHERE scope = 'door-checkin' AND json_extract(undo_state, '$.kind') = 'created'
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
// Invoices table
|
// Invoices table
|
||||||
await (db as any).run(sql`
|
await (db as any).run(sql`
|
||||||
@@ -343,6 +413,14 @@ async function migrate() {
|
|||||||
} catch (e) { /* column may already exist */ }
|
} catch (e) { /* column may already exist */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// POS card terminal at the door: on globally by default, NULL override = inherit
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE payment_options ADD COLUMN pos_enabled INTEGER NOT NULL DEFAULT 1`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE event_payment_overrides ADD COLUMN pos_enabled INTEGER`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
await (db as any).run(sql`
|
await (db as any).run(sql`
|
||||||
CREATE TABLE IF NOT EXISTS contacts (
|
CREATE TABLE IF NOT EXISTS contacts (
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
@@ -471,6 +549,8 @@ async function migrate() {
|
|||||||
maintenance_mode INTEGER NOT NULL DEFAULT 0,
|
maintenance_mode INTEGER NOT NULL DEFAULT 0,
|
||||||
maintenance_message TEXT,
|
maintenance_message TEXT,
|
||||||
maintenance_message_es TEXT,
|
maintenance_message_es TEXT,
|
||||||
|
presale_closure_enabled INTEGER NOT NULL DEFAULT 1,
|
||||||
|
presale_close_minutes_before INTEGER NOT NULL DEFAULT 120,
|
||||||
updated_at TEXT NOT NULL,
|
updated_at TEXT NOT NULL,
|
||||||
updated_by TEXT REFERENCES users(id)
|
updated_by TEXT REFERENCES users(id)
|
||||||
)
|
)
|
||||||
@@ -481,6 +561,14 @@ async function migrate() {
|
|||||||
await (db as any).run(sql`ALTER TABLE site_settings ADD COLUMN featured_event_id TEXT REFERENCES events(id)`);
|
await (db as any).run(sql`ALTER TABLE site_settings ADD COLUMN featured_event_id TEXT REFERENCES events(id)`);
|
||||||
} catch (e) { /* column may already exist */ }
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Pre-sale closure site-wide defaults
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE site_settings ADD COLUMN presale_closure_enabled INTEGER NOT NULL DEFAULT 1`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE site_settings ADD COLUMN presale_close_minutes_before INTEGER NOT NULL DEFAULT 120`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
// Legal pages table for admin-editable legal content
|
// Legal pages table for admin-editable legal content
|
||||||
await (db as any).run(sql`
|
await (db as any).run(sql`
|
||||||
CREATE TABLE IF NOT EXISTS legal_pages (
|
CREATE TABLE IF NOT EXISTS legal_pages (
|
||||||
@@ -532,6 +620,81 @@ async function migrate() {
|
|||||||
updated_by TEXT REFERENCES users(id)
|
updated_by TEXT REFERENCES users(id)
|
||||||
)
|
)
|
||||||
`);
|
`);
|
||||||
|
|
||||||
|
// ==================== Better Auth ====================
|
||||||
|
// Better Auth core + admin plugin columns on the existing users table
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE users ADD COLUMN email_verified INTEGER NOT NULL DEFAULT 0`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE users ADD COLUMN image TEXT`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE users ADD COLUMN banned INTEGER NOT NULL DEFAULT 0`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE users ADD COLUMN ban_reason TEXT`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).run(sql`ALTER TABLE users ADD COLUMN ban_expires INTEGER`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Better Auth sessions (replaces the legacy user_sessions table).
|
||||||
|
// Timestamps are integer epoch-milliseconds (Drizzle timestamp_ms mode).
|
||||||
|
await (db as any).run(sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
token TEXT NOT NULL UNIQUE,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
ip_address TEXT,
|
||||||
|
user_agent TEXT,
|
||||||
|
impersonated_by TEXT,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Better Auth accounts: credential (password hash) and OAuth provider links
|
||||||
|
await (db as any).run(sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS auth_accounts (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
account_id TEXT NOT NULL,
|
||||||
|
provider_id TEXT NOT NULL,
|
||||||
|
access_token TEXT,
|
||||||
|
refresh_token TEXT,
|
||||||
|
id_token TEXT,
|
||||||
|
access_token_expires_at INTEGER,
|
||||||
|
refresh_token_expires_at INTEGER,
|
||||||
|
scope TEXT,
|
||||||
|
password TEXT,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Better Auth verification values (magic links, password reset tokens)
|
||||||
|
await (db as any).run(sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS auth_verifications (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
identifier TEXT NOT NULL,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Better Auth rate limiting (used when Redis is not configured)
|
||||||
|
await (db as any).run(sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS auth_rate_limits (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
key TEXT,
|
||||||
|
count INTEGER,
|
||||||
|
last_request INTEGER
|
||||||
|
)
|
||||||
|
`);
|
||||||
} else {
|
} else {
|
||||||
// PostgreSQL migrations
|
// PostgreSQL migrations
|
||||||
await (db as any).execute(sql`
|
await (db as any).execute(sql`
|
||||||
@@ -616,6 +779,8 @@ async function migrate() {
|
|||||||
banner_url VARCHAR(500),
|
banner_url VARCHAR(500),
|
||||||
external_booking_enabled INTEGER NOT NULL DEFAULT 0,
|
external_booking_enabled INTEGER NOT NULL DEFAULT 0,
|
||||||
external_booking_url VARCHAR(500),
|
external_booking_url VARCHAR(500),
|
||||||
|
presale_closure_enabled INTEGER,
|
||||||
|
presale_close_minutes_before INTEGER,
|
||||||
created_at TIMESTAMP NOT NULL,
|
created_at TIMESTAMP NOT NULL,
|
||||||
updated_at TIMESTAMP NOT NULL
|
updated_at TIMESTAMP NOT NULL
|
||||||
)
|
)
|
||||||
@@ -629,6 +794,19 @@ async function migrate() {
|
|||||||
await (db as any).execute(sql`ALTER TABLE events ADD COLUMN external_booking_url VARCHAR(500)`);
|
await (db as any).execute(sql`ALTER TABLE events ADD COLUMN external_booking_url VARCHAR(500)`);
|
||||||
} catch (e) { /* column may already exist */ }
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Pre-sale closure per-event overrides (NULL = inherit site_settings default)
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE events ADD COLUMN presale_closure_enabled INTEGER`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE events ADD COLUMN presale_close_minutes_before INTEGER`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Walk-in (door) price. NULL = fall back to price; 0 = free walk-in.
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE events ADD COLUMN walk_in_price DECIMAL(10, 2)`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
// Add short description columns to events
|
// Add short description columns to events
|
||||||
try {
|
try {
|
||||||
await (db as any).execute(sql`ALTER TABLE events ADD COLUMN short_description VARCHAR(300)`);
|
await (db as any).execute(sql`ALTER TABLE events ADD COLUMN short_description VARCHAR(300)`);
|
||||||
@@ -702,6 +880,18 @@ async function migrate() {
|
|||||||
await (db as any).execute(sql`ALTER TABLE tickets ADD COLUMN is_guest INTEGER NOT NULL DEFAULT 0`);
|
await (db as any).execute(sql`ALTER TABLE tickets ADD COLUMN is_guest INTEGER NOT NULL DEFAULT 0`);
|
||||||
} catch (e) { /* column may already exist */ }
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Migration: Add payment_status column to tickets (paid | unpaid | comp),
|
||||||
|
// backfilled from is_guest and the payments table on first run
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE tickets ADD COLUMN payment_status VARCHAR(10) NOT NULL DEFAULT 'unpaid'`);
|
||||||
|
await (db as any).execute(sql`UPDATE tickets SET payment_status = 'comp' WHERE is_guest = 1`);
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
UPDATE tickets SET payment_status = 'paid'
|
||||||
|
WHERE is_guest = 0
|
||||||
|
AND id IN (SELECT ticket_id FROM payments WHERE status = 'paid')
|
||||||
|
`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
await (db as any).execute(sql`
|
await (db as any).execute(sql`
|
||||||
CREATE TABLE IF NOT EXISTS payments (
|
CREATE TABLE IF NOT EXISTS payments (
|
||||||
id UUID PRIMARY KEY,
|
id UUID PRIMARY KEY,
|
||||||
@@ -737,6 +927,39 @@ async function migrate() {
|
|||||||
try {
|
try {
|
||||||
await (db as any).execute(sql`ALTER TABLE payments ADD COLUMN lnbits_amount_sats INTEGER`);
|
await (db as any).execute(sql`ALTER TABLE payments ADD COLUMN lnbits_amount_sats INTEGER`);
|
||||||
} catch (e) { /* column may already exist */ }
|
} catch (e) { /* column may already exist */ }
|
||||||
|
// Door check-in screen: split pre-sale vs door revenue and record the tender
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE payments ADD COLUMN source VARCHAR(20) NOT NULL DEFAULT 'presale'`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE payments ADD COLUMN method VARCHAR(20)`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Idempotency records for door check-in actions (retries / double taps)
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||||
|
key VARCHAR(128) PRIMARY KEY,
|
||||||
|
scope VARCHAR(64) NOT NULL,
|
||||||
|
result TEXT NOT NULL,
|
||||||
|
undo_state TEXT,
|
||||||
|
undone_at TIMESTAMP,
|
||||||
|
created_at TIMESTAMP NOT NULL
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Migration: tickets.booking_source (online | walk_in | admin), with the
|
||||||
|
// same one-time walk-in backfill as the sqlite branch.
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE tickets ADD COLUMN booking_source VARCHAR(20) NOT NULL DEFAULT 'online'`);
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
UPDATE tickets SET booking_source = 'walk_in'
|
||||||
|
WHERE id::text IN (
|
||||||
|
SELECT undo_state::json->>'ticketId' FROM idempotency_keys
|
||||||
|
WHERE scope = 'door-checkin' AND undo_state IS NOT NULL
|
||||||
|
AND undo_state::json->>'kind' = 'created'
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
// Invoices table
|
// Invoices table
|
||||||
await (db as any).execute(sql`
|
await (db as any).execute(sql`
|
||||||
@@ -831,6 +1054,14 @@ async function migrate() {
|
|||||||
} catch (e) { /* column may already exist */ }
|
} catch (e) { /* column may already exist */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// POS card terminal at the door: on globally by default, NULL override = inherit
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE payment_options ADD COLUMN pos_enabled INTEGER NOT NULL DEFAULT 1`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE event_payment_overrides ADD COLUMN pos_enabled INTEGER`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
await (db as any).execute(sql`
|
await (db as any).execute(sql`
|
||||||
CREATE TABLE IF NOT EXISTS contacts (
|
CREATE TABLE IF NOT EXISTS contacts (
|
||||||
id UUID PRIMARY KEY,
|
id UUID PRIMARY KEY,
|
||||||
@@ -959,6 +1190,8 @@ async function migrate() {
|
|||||||
maintenance_mode INTEGER NOT NULL DEFAULT 0,
|
maintenance_mode INTEGER NOT NULL DEFAULT 0,
|
||||||
maintenance_message TEXT,
|
maintenance_message TEXT,
|
||||||
maintenance_message_es TEXT,
|
maintenance_message_es TEXT,
|
||||||
|
presale_closure_enabled INTEGER NOT NULL DEFAULT 1,
|
||||||
|
presale_close_minutes_before INTEGER NOT NULL DEFAULT 120,
|
||||||
updated_at TIMESTAMP NOT NULL,
|
updated_at TIMESTAMP NOT NULL,
|
||||||
updated_by UUID REFERENCES users(id)
|
updated_by UUID REFERENCES users(id)
|
||||||
)
|
)
|
||||||
@@ -969,6 +1202,14 @@ async function migrate() {
|
|||||||
await (db as any).execute(sql`ALTER TABLE site_settings ADD COLUMN featured_event_id UUID REFERENCES events(id)`);
|
await (db as any).execute(sql`ALTER TABLE site_settings ADD COLUMN featured_event_id UUID REFERENCES events(id)`);
|
||||||
} catch (e) { /* column may already exist */ }
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Pre-sale closure site-wide defaults
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE site_settings ADD COLUMN presale_closure_enabled INTEGER NOT NULL DEFAULT 1`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE site_settings ADD COLUMN presale_close_minutes_before INTEGER NOT NULL DEFAULT 120`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
// Legal pages table for admin-editable legal content
|
// Legal pages table for admin-editable legal content
|
||||||
await (db as any).execute(sql`
|
await (db as any).execute(sql`
|
||||||
CREATE TABLE IF NOT EXISTS legal_pages (
|
CREATE TABLE IF NOT EXISTS legal_pages (
|
||||||
@@ -1020,6 +1261,252 @@ async function migrate() {
|
|||||||
updated_by UUID REFERENCES users(id)
|
updated_by UUID REFERENCES users(id)
|
||||||
)
|
)
|
||||||
`);
|
`);
|
||||||
|
|
||||||
|
// ==================== Better Auth ====================
|
||||||
|
// Better Auth core + admin plugin columns on the existing users table
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT FALSE`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS image TEXT`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS banned BOOLEAN NOT NULL DEFAULT FALSE`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS ban_reason TEXT`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
try {
|
||||||
|
await (db as any).execute(sql`ALTER TABLE users ADD COLUMN IF NOT EXISTS ban_expires TIMESTAMP`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
// Better Auth sessions (replaces the legacy user_sessions table)
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
token VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
expires_at TIMESTAMP NOT NULL,
|
||||||
|
ip_address VARCHAR(45),
|
||||||
|
user_agent TEXT,
|
||||||
|
impersonated_by UUID,
|
||||||
|
created_at TIMESTAMP NOT NULL,
|
||||||
|
updated_at TIMESTAMP NOT NULL
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Better Auth accounts: credential (password hash) and OAuth provider links
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS auth_accounts (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
account_id VARCHAR(255) NOT NULL,
|
||||||
|
provider_id VARCHAR(100) NOT NULL,
|
||||||
|
access_token TEXT,
|
||||||
|
refresh_token TEXT,
|
||||||
|
id_token TEXT,
|
||||||
|
access_token_expires_at TIMESTAMP,
|
||||||
|
refresh_token_expires_at TIMESTAMP,
|
||||||
|
scope TEXT,
|
||||||
|
password TEXT,
|
||||||
|
created_at TIMESTAMP NOT NULL,
|
||||||
|
updated_at TIMESTAMP NOT NULL
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Better Auth verification values (magic links, password reset tokens)
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS auth_verifications (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
identifier VARCHAR(255) NOT NULL,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
expires_at TIMESTAMP NOT NULL,
|
||||||
|
created_at TIMESTAMP NOT NULL,
|
||||||
|
updated_at TIMESTAMP NOT NULL
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Better Auth rate limiting (used when Redis is not configured)
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS auth_rate_limits (
|
||||||
|
id VARCHAR(64) PRIMARY KEY,
|
||||||
|
key VARCHAR(255),
|
||||||
|
count BIGINT,
|
||||||
|
last_request BIGINT
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Event finance, partners & team access ====================
|
||||||
|
// New tables only, so one engine-neutral block with a type map instead of a
|
||||||
|
// copy per branch. Money is whole PYG (INTEGER), percentages are basis points.
|
||||||
|
const T = dbType === 'sqlite'
|
||||||
|
? { id: 'TEXT', ts: 'TEXT', str: 'TEXT', text: 'TEXT' }
|
||||||
|
: { id: 'UUID', ts: 'TIMESTAMP', str: 'VARCHAR(300)', text: 'TEXT' };
|
||||||
|
const run = (stmt: string) =>
|
||||||
|
dbType === 'sqlite' ? (db as any).run(sql.raw(stmt)) : (db as any).execute(sql.raw(stmt));
|
||||||
|
|
||||||
|
try {
|
||||||
|
await run(`ALTER TABLE events ADD COLUMN series ${dbType === 'sqlite' ? 'TEXT' : 'VARCHAR(100)'}`);
|
||||||
|
} catch (e) { /* column may already exist */ }
|
||||||
|
|
||||||
|
const financeTables = [
|
||||||
|
`CREATE TABLE IF NOT EXISTS expense_categories (
|
||||||
|
id ${T.id} PRIMARY KEY,
|
||||||
|
name_en ${T.str} NOT NULL,
|
||||||
|
name_es ${T.str} NOT NULL,
|
||||||
|
color ${T.str} NOT NULL DEFAULT '#6B7280',
|
||||||
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||||
|
archived INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at ${T.ts} NOT NULL,
|
||||||
|
updated_at ${T.ts} NOT NULL
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS expense_templates (
|
||||||
|
id ${T.id} PRIMARY KEY,
|
||||||
|
name ${T.str} NOT NULL,
|
||||||
|
category_id ${T.id} REFERENCES expense_categories(id),
|
||||||
|
description ${T.text},
|
||||||
|
calc_type ${T.str} NOT NULL,
|
||||||
|
amount INTEGER NOT NULL DEFAULT 0,
|
||||||
|
percent_bp INTEGER NOT NULL DEFAULT 0,
|
||||||
|
minimum_amount INTEGER NOT NULL DEFAULT 0,
|
||||||
|
archived INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at ${T.ts} NOT NULL,
|
||||||
|
updated_at ${T.ts} NOT NULL
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS expense_template_packs (
|
||||||
|
id ${T.id} PRIMARY KEY,
|
||||||
|
name ${T.str} NOT NULL,
|
||||||
|
description ${T.text},
|
||||||
|
archived INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at ${T.ts} NOT NULL,
|
||||||
|
updated_at ${T.ts} NOT NULL
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS expense_template_pack_items (
|
||||||
|
id ${T.id} PRIMARY KEY,
|
||||||
|
pack_id ${T.id} NOT NULL REFERENCES expense_template_packs(id),
|
||||||
|
template_id ${T.id} NOT NULL REFERENCES expense_templates(id),
|
||||||
|
sort_order INTEGER NOT NULL DEFAULT 0
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS event_partners (
|
||||||
|
id ${T.id} PRIMARY KEY,
|
||||||
|
event_id ${T.id} NOT NULL REFERENCES events(id),
|
||||||
|
user_id ${T.id} REFERENCES users(id),
|
||||||
|
external_name ${T.str},
|
||||||
|
role_label ${T.str},
|
||||||
|
share_type ${T.str} NOT NULL,
|
||||||
|
percent_bp INTEGER NOT NULL DEFAULT 0,
|
||||||
|
fixed_amount INTEGER NOT NULL DEFAULT 0,
|
||||||
|
threshold_amount INTEGER NOT NULL DEFAULT 0,
|
||||||
|
loss_rule ${T.str} NOT NULL DEFAULT 'none',
|
||||||
|
loss_cap_amount INTEGER NOT NULL DEFAULT 0,
|
||||||
|
payout_status ${T.str} NOT NULL DEFAULT 'pending',
|
||||||
|
payout_date ${T.ts},
|
||||||
|
payout_method ${T.str},
|
||||||
|
payout_note ${T.text},
|
||||||
|
created_at ${T.ts} NOT NULL,
|
||||||
|
updated_at ${T.ts} NOT NULL
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS event_expenses (
|
||||||
|
id ${T.id} PRIMARY KEY,
|
||||||
|
event_id ${T.id} NOT NULL REFERENCES events(id),
|
||||||
|
category_id ${T.id} REFERENCES expense_categories(id),
|
||||||
|
template_id ${T.id} REFERENCES expense_templates(id),
|
||||||
|
description ${T.str} NOT NULL,
|
||||||
|
calc_type ${T.str} NOT NULL DEFAULT 'fixed',
|
||||||
|
quantity INTEGER NOT NULL DEFAULT 1,
|
||||||
|
unit_amount INTEGER NOT NULL DEFAULT 0,
|
||||||
|
percent_bp INTEGER NOT NULL DEFAULT 0,
|
||||||
|
minimum_amount INTEGER NOT NULL DEFAULT 0,
|
||||||
|
computed_amount INTEGER NOT NULL DEFAULT 0,
|
||||||
|
is_locked INTEGER NOT NULL DEFAULT 0,
|
||||||
|
status ${T.str} NOT NULL DEFAULT 'planned',
|
||||||
|
paid_by_partner_id ${T.id} REFERENCES event_partners(id),
|
||||||
|
receipt_url ${T.str},
|
||||||
|
expense_date ${T.ts},
|
||||||
|
created_by ${T.id} REFERENCES users(id),
|
||||||
|
updated_by ${T.id} REFERENCES users(id),
|
||||||
|
created_at ${T.ts} NOT NULL,
|
||||||
|
updated_at ${T.ts} NOT NULL
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS event_other_income (
|
||||||
|
id ${T.id} PRIMARY KEY,
|
||||||
|
event_id ${T.id} NOT NULL REFERENCES events(id),
|
||||||
|
description ${T.str} NOT NULL,
|
||||||
|
amount INTEGER NOT NULL,
|
||||||
|
created_by ${T.id} REFERENCES users(id),
|
||||||
|
created_at ${T.ts} NOT NULL,
|
||||||
|
updated_at ${T.ts} NOT NULL
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS payment_method_fees (
|
||||||
|
method ${T.str} PRIMARY KEY,
|
||||||
|
percent_bp INTEGER NOT NULL DEFAULT 0,
|
||||||
|
fixed_amount INTEGER NOT NULL DEFAULT 0,
|
||||||
|
updated_at ${T.ts} NOT NULL,
|
||||||
|
updated_by ${T.id} REFERENCES users(id)
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS event_finance_state (
|
||||||
|
event_id ${T.id} PRIMARY KEY REFERENCES events(id),
|
||||||
|
status ${T.str} NOT NULL DEFAULT 'open',
|
||||||
|
finalized_at ${T.ts},
|
||||||
|
finalized_by ${T.id} REFERENCES users(id),
|
||||||
|
snapshot_json ${T.text},
|
||||||
|
updated_at ${T.ts} NOT NULL
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS event_members (
|
||||||
|
id ${T.id} PRIMARY KEY,
|
||||||
|
event_id ${T.id} NOT NULL REFERENCES events(id),
|
||||||
|
user_id ${T.id} NOT NULL REFERENCES users(id),
|
||||||
|
role_preset ${T.str} NOT NULL,
|
||||||
|
permissions ${T.text} NOT NULL DEFAULT '{}',
|
||||||
|
created_by ${T.id} REFERENCES users(id),
|
||||||
|
created_at ${T.ts} NOT NULL,
|
||||||
|
updated_at ${T.ts} NOT NULL
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS finance_audit_log (
|
||||||
|
id ${T.id} PRIMARY KEY,
|
||||||
|
event_id ${T.id},
|
||||||
|
actor_user_id ${T.id} REFERENCES users(id),
|
||||||
|
entity_type ${T.str} NOT NULL,
|
||||||
|
entity_id ${T.str},
|
||||||
|
action ${T.str} NOT NULL,
|
||||||
|
before_json ${T.text},
|
||||||
|
after_json ${T.text},
|
||||||
|
created_at ${T.ts} NOT NULL
|
||||||
|
)`,
|
||||||
|
];
|
||||||
|
for (const stmt of financeTables) {
|
||||||
|
await run(stmt);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Defaults, only when the tables are still empty so archived/deleted rows stay gone.
|
||||||
|
const now = getNow();
|
||||||
|
const categoryCount = await dbGet<any>(
|
||||||
|
(db as any).select({ count: sql<number>`count(*)` }).from(sql`expense_categories`)
|
||||||
|
);
|
||||||
|
if (Number(categoryCount?.count || 0) === 0) {
|
||||||
|
const defaults: [string, string, string][] = [
|
||||||
|
['Venue', 'Lugar', '#2563EB'],
|
||||||
|
['Instructor / host', 'Instructor / anfitrión', '#7C3AED'],
|
||||||
|
['Food & drinks', 'Comida y bebidas', '#EA580C'],
|
||||||
|
['Staff', 'Personal', '#0D9488'],
|
||||||
|
['Marketing', 'Marketing', '#DB2777'],
|
||||||
|
['Supplies', 'Materiales', '#CA8A04'],
|
||||||
|
['Other', 'Otros', '#6B7280'],
|
||||||
|
];
|
||||||
|
for (const [i, [en, es, color]] of defaults.entries()) {
|
||||||
|
await (db as any).insert(expenseCategories).values({
|
||||||
|
id: generateId(), nameEn: en, nameEs: es, color, sortOrder: i, archived: dbType === 'sqlite' ? false : 0,
|
||||||
|
createdAt: now, updatedAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log('Seeded default expense categories.');
|
||||||
|
}
|
||||||
|
// One fee row per payments.provider in use; 0% until an admin sets them.
|
||||||
|
for (const method of ['tpago', 'bank_transfer', 'lightning', 'cash', 'pos']) {
|
||||||
|
await run(`INSERT INTO payment_method_fees (method, percent_bp, fixed_amount, updated_at)
|
||||||
|
VALUES ('${method}', 0, 0, ${dbType === 'sqlite' ? `'${new Date().toISOString()}'` : 'NOW()'})
|
||||||
|
ON CONFLICT (method) DO NOTHING`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Indexes on foreign-key / hot-filter columns (CREATE INDEX IF NOT EXISTS works on both engines)
|
// Indexes on foreign-key / hot-filter columns (CREATE INDEX IF NOT EXISTS works on both engines)
|
||||||
@@ -1030,8 +1517,24 @@ async function migrate() {
|
|||||||
`CREATE INDEX IF NOT EXISTS tickets_status_idx ON tickets(status)`,
|
`CREATE INDEX IF NOT EXISTS tickets_status_idx ON tickets(status)`,
|
||||||
`CREATE INDEX IF NOT EXISTS payments_ticket_id_idx ON payments(ticket_id)`,
|
`CREATE INDEX IF NOT EXISTS payments_ticket_id_idx ON payments(ticket_id)`,
|
||||||
`CREATE INDEX IF NOT EXISTS payments_status_idx ON payments(status)`,
|
`CREATE INDEX IF NOT EXISTS payments_status_idx ON payments(status)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS payments_source_idx ON payments(source)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS idempotency_keys_created_at_idx ON idempotency_keys(created_at)`,
|
||||||
`CREATE INDEX IF NOT EXISTS email_logs_event_id_idx ON email_logs(event_id)`,
|
`CREATE INDEX IF NOT EXISTS email_logs_event_id_idx ON email_logs(event_id)`,
|
||||||
`CREATE INDEX IF NOT EXISTS magic_link_tokens_token_idx ON magic_link_tokens(token)`,
|
`CREATE INDEX IF NOT EXISTS magic_link_tokens_token_idx ON magic_link_tokens(token)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS auth_sessions_user_id_idx ON auth_sessions(user_id)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS auth_accounts_user_id_idx ON auth_accounts(user_id)`,
|
||||||
|
`CREATE UNIQUE INDEX IF NOT EXISTS auth_accounts_provider_account_idx ON auth_accounts(provider_id, account_id)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS auth_verifications_identifier_idx ON auth_verifications(identifier)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS auth_rate_limits_key_idx ON auth_rate_limits(key)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS event_expenses_event_id_idx ON event_expenses(event_id)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS event_other_income_event_id_idx ON event_other_income(event_id)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS event_partners_event_id_idx ON event_partners(event_id)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS event_partners_user_id_idx ON event_partners(user_id)`,
|
||||||
|
`CREATE UNIQUE INDEX IF NOT EXISTS event_members_event_user_idx ON event_members(event_id, user_id)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS event_members_user_id_idx ON event_members(user_id)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS expense_template_pack_items_pack_id_idx ON expense_template_pack_items(pack_id)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS finance_audit_log_event_id_idx ON finance_audit_log(event_id, created_at)`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS events_series_idx ON events(series)`,
|
||||||
];
|
];
|
||||||
for (const stmt of indexStatements) {
|
for (const stmt of indexStatements) {
|
||||||
try {
|
try {
|
||||||
@@ -1043,6 +1546,132 @@ async function migrate() {
|
|||||||
} catch (e) { /* index may already exist */ }
|
} catch (e) { /* index may already exist */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==================== Better Auth data backfill ====================
|
||||||
|
// Idempotent: every statement is guarded so re-running migrate is safe, and
|
||||||
|
// legacy users are distinguished from Better-Auth-created users by having
|
||||||
|
// users.password / users.google_id set (Better Auth never writes either).
|
||||||
|
if (dbType === 'sqlite') {
|
||||||
|
// Legacy password hashes -> credential accounts (argon2 and bcrypt hashes
|
||||||
|
// both stay valid via the custom password verifier in lib/betterAuth.ts)
|
||||||
|
await (db as any).run(sql`
|
||||||
|
INSERT INTO auth_accounts (id, user_id, account_id, provider_id, password, created_at, updated_at)
|
||||||
|
SELECT lower(hex(randomblob(16))), u.id, u.id, 'credential', u.password,
|
||||||
|
CAST(strftime('%s','now') AS INTEGER) * 1000, CAST(strftime('%s','now') AS INTEGER) * 1000
|
||||||
|
FROM users u
|
||||||
|
WHERE u.password IS NOT NULL AND u.password != ''
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM auth_accounts a WHERE a.user_id = u.id AND a.provider_id = 'credential'
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Legacy Google links -> google provider accounts
|
||||||
|
await (db as any).run(sql`
|
||||||
|
INSERT INTO auth_accounts (id, user_id, account_id, provider_id, created_at, updated_at)
|
||||||
|
SELECT lower(hex(randomblob(16))), u.id, u.google_id, 'google',
|
||||||
|
CAST(strftime('%s','now') AS INTEGER) * 1000, CAST(strftime('%s','now') AS INTEGER) * 1000
|
||||||
|
FROM users u
|
||||||
|
WHERE u.google_id IS NOT NULL AND u.google_id != ''
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM auth_accounts a WHERE a.user_id = u.id AND a.provider_id = 'google'
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Claimed legacy accounts proved their email (register/claim link/Google)
|
||||||
|
await (db as any).run(sql`
|
||||||
|
UPDATE users SET email_verified = 1
|
||||||
|
WHERE email_verified = 0 AND is_claimed = 1
|
||||||
|
AND ((password IS NOT NULL AND password != '') OR google_id IS NOT NULL)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Suspended -> banned (admin plugin field); users.ts keeps them in sync
|
||||||
|
await (db as any).run(sql`
|
||||||
|
UPDATE users SET banned = 1, ban_reason = 'migrated: account suspended'
|
||||||
|
WHERE account_status = 'suspended' AND banned = 0
|
||||||
|
`);
|
||||||
|
} else {
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
INSERT INTO auth_accounts (id, user_id, account_id, provider_id, password, created_at, updated_at)
|
||||||
|
SELECT gen_random_uuid(), u.id, u.id::text, 'credential', u.password, NOW(), NOW()
|
||||||
|
FROM users u
|
||||||
|
WHERE u.password IS NOT NULL AND u.password != ''
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM auth_accounts a WHERE a.user_id = u.id AND a.provider_id = 'credential'
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
INSERT INTO auth_accounts (id, user_id, account_id, provider_id, created_at, updated_at)
|
||||||
|
SELECT gen_random_uuid(), u.id, u.google_id, 'google', NOW(), NOW()
|
||||||
|
FROM users u
|
||||||
|
WHERE u.google_id IS NOT NULL AND u.google_id != ''
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM auth_accounts a WHERE a.user_id = u.id AND a.provider_id = 'google'
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
UPDATE users SET email_verified = TRUE
|
||||||
|
WHERE email_verified = FALSE AND is_claimed = 1
|
||||||
|
AND ((password IS NOT NULL AND password != '') OR google_id IS NOT NULL)
|
||||||
|
`);
|
||||||
|
|
||||||
|
await (db as any).execute(sql`
|
||||||
|
UPDATE users SET banned = TRUE, ban_reason = 'migrated: account suspended'
|
||||||
|
WHERE account_status = 'suspended' AND banned = FALSE
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== users.email normalization ====================
|
||||||
|
// Better Auth lowercases the address on every lookup and write it performs,
|
||||||
|
// but the users.email unique index is case-sensitive on both dialects. Rows
|
||||||
|
// written outside Better Auth (guest bookings, door sales, admin-added
|
||||||
|
// tickets) used to keep the address exactly as typed, so a buyer who entered
|
||||||
|
// "John@Gmail.com" was invisible to sign-in and to Google account linking:
|
||||||
|
// signing in with Google minted a SECOND user row and left their tickets
|
||||||
|
// stranded on the first. lib/utils.ts normalizeEmail() fixes new writes; this
|
||||||
|
// fixes the rows already in the table.
|
||||||
|
//
|
||||||
|
// Idempotent, and deliberately conservative: a row is only lowercased when
|
||||||
|
// nothing already occupies the lowercase address. A genuine collision means
|
||||||
|
// two user rows for the same person, each with its own tickets, invoices and
|
||||||
|
// payments — merging those is a judgement call, not a migration, so they are
|
||||||
|
// reported for manual review instead.
|
||||||
|
const lowercaseEmailsSql = `
|
||||||
|
UPDATE users SET email = LOWER(email)
|
||||||
|
WHERE email <> LOWER(email)
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM users u2 WHERE u2.id <> users.id AND u2.email = LOWER(users.email)
|
||||||
|
)
|
||||||
|
`;
|
||||||
|
if (dbType === 'sqlite') {
|
||||||
|
await (db as any).run(sql.raw(lowercaseEmailsSql));
|
||||||
|
} else {
|
||||||
|
await (db as any).execute(sql.raw(lowercaseEmailsSql));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Whatever still differs from its own lowercase form is exactly the set the
|
||||||
|
// UPDATE refused to touch, i.e. the collisions.
|
||||||
|
const collisions = await dbAll<{ id: string; email: string }>(
|
||||||
|
(db as any)
|
||||||
|
.select({ id: (users as any).id, email: (users as any).email })
|
||||||
|
.from(users)
|
||||||
|
.where(ne((users as any).email, sql`LOWER(${(users as any).email})`))
|
||||||
|
);
|
||||||
|
if (collisions.length > 0) {
|
||||||
|
console.warn(
|
||||||
|
`WARNING: ${collisions.length} users row(s) keep a mixed-case email because the ` +
|
||||||
|
`lowercase address is already taken. Sign-in and Google linking only ever reach ` +
|
||||||
|
`the lowercase row, so these need a manual merge:`
|
||||||
|
);
|
||||||
|
for (const row of collisions) {
|
||||||
|
const canonical = row.email.toLowerCase();
|
||||||
|
const existing = await dbGet<{ id: string }>(
|
||||||
|
(db as any).select({ id: (users as any).id }).from(users).where(eq((users as any).email, canonical))
|
||||||
|
);
|
||||||
|
console.warn(` ${row.id} (${row.email}) -> keeps losing to ${existing?.id} (${canonical})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Backfill slugs for any events that don't have one yet (shared across DB types).
|
// Backfill slugs for any events that don't have one yet (shared across DB types).
|
||||||
// Ordered by creation so duplicate titles get deterministic -2, -3 suffixes.
|
// Ordered by creation so duplicate titles get deterministic -2, -3 suffixes.
|
||||||
const allEvents = await dbAll<{ id: string; title: string; slug: string | null }>(
|
const allEvents = await dbAll<{ id: string; title: string; slug: string | null }>(
|
||||||
|
|||||||
+392
-2
@@ -1,5 +1,5 @@
|
|||||||
import { sqliteTable, text, integer, real } from 'drizzle-orm/sqlite-core';
|
import { sqliteTable, text, integer, real } from 'drizzle-orm/sqlite-core';
|
||||||
import { pgTable, uuid, varchar, text as pgText, timestamp, decimal, integer as pgInteger } from 'drizzle-orm/pg-core';
|
import { pgTable, uuid, varchar, text as pgText, timestamp, decimal, integer as pgInteger, boolean as pgBoolean } from 'drizzle-orm/pg-core';
|
||||||
|
|
||||||
// Type to determine which schema to use
|
// Type to determine which schema to use
|
||||||
const dbType = process.env.DB_TYPE || 'sqlite';
|
const dbType = process.env.DB_TYPE || 'sqlite';
|
||||||
@@ -20,6 +20,12 @@ export const sqliteUsers = sqliteTable('users', {
|
|||||||
accountStatus: text('account_status', { enum: ['active', 'unclaimed', 'suspended'] }).notNull().default('active'),
|
accountStatus: text('account_status', { enum: ['active', 'unclaimed', 'suspended'] }).notNull().default('active'),
|
||||||
// Incremented to invalidate previously issued JWTs (logout-everywhere, password change/reset)
|
// Incremented to invalidate previously issued JWTs (logout-everywhere, password change/reset)
|
||||||
tokenVersion: integer('token_version').notNull().default(0),
|
tokenVersion: integer('token_version').notNull().default(0),
|
||||||
|
// Better Auth core + admin plugin fields (auth-schema.ts maps the same columns)
|
||||||
|
emailVerified: integer('email_verified', { mode: 'boolean' }).notNull().default(false),
|
||||||
|
image: text('image'),
|
||||||
|
banned: integer('banned', { mode: 'boolean' }).notNull().default(false),
|
||||||
|
banReason: text('ban_reason'),
|
||||||
|
banExpires: integer('ban_expires', { mode: 'timestamp_ms' }),
|
||||||
createdAt: text('created_at').notNull(),
|
createdAt: text('created_at').notNull(),
|
||||||
updatedAt: text('updated_at').notNull(),
|
updatedAt: text('updated_at').notNull(),
|
||||||
});
|
});
|
||||||
@@ -76,12 +82,20 @@ export const sqliteEvents = sqliteTable('events', {
|
|||||||
location: text('location').notNull(),
|
location: text('location').notNull(),
|
||||||
locationUrl: text('location_url'),
|
locationUrl: text('location_url'),
|
||||||
price: real('price').notNull().default(0),
|
price: real('price').notNull().default(0),
|
||||||
|
// Charged for walk-ins at the door (Scanner). Null = fall back to price; 0 = free.
|
||||||
|
// Admin/staff only: never serialized to public event responses.
|
||||||
|
walkInPrice: real('walk_in_price'),
|
||||||
currency: text('currency').notNull().default('PYG'),
|
currency: text('currency').notNull().default('PYG'),
|
||||||
capacity: integer('capacity').notNull().default(50),
|
capacity: integer('capacity').notNull().default(50),
|
||||||
status: text('status', { enum: ['draft', 'published', 'unlisted', 'cancelled', 'completed', 'archived'] }).notNull().default('draft'),
|
status: text('status', { enum: ['draft', 'published', 'unlisted', 'cancelled', 'completed', 'archived'] }).notNull().default('draft'),
|
||||||
bannerUrl: text('banner_url'),
|
bannerUrl: text('banner_url'),
|
||||||
externalBookingEnabled: integer('external_booking_enabled', { mode: 'boolean' }).notNull().default(false),
|
externalBookingEnabled: integer('external_booking_enabled', { mode: 'boolean' }).notNull().default(false),
|
||||||
externalBookingUrl: text('external_booking_url'),
|
externalBookingUrl: text('external_booking_url'),
|
||||||
|
// Pre-sale closure: null = inherit the site_settings default
|
||||||
|
presaleClosureEnabled: integer('presale_closure_enabled', { mode: 'boolean' }),
|
||||||
|
presaleCloseMinutesBefore: integer('presale_close_minutes_before'),
|
||||||
|
// Groups recurring events (e.g. "Morning Club") for the cross-event finance overview
|
||||||
|
series: text('series'),
|
||||||
createdAt: text('created_at').notNull(),
|
createdAt: text('created_at').notNull(),
|
||||||
updatedAt: text('updated_at').notNull(),
|
updatedAt: text('updated_at').notNull(),
|
||||||
});
|
});
|
||||||
@@ -110,13 +124,18 @@ export const sqliteTickets = sqliteTable('tickets', {
|
|||||||
qrCode: text('qr_code'),
|
qrCode: text('qr_code'),
|
||||||
adminNote: text('admin_note'),
|
adminNote: text('admin_note'),
|
||||||
isGuest: integer('is_guest', { mode: 'boolean' }).notNull().default(false),
|
isGuest: integer('is_guest', { mode: 'boolean' }).notNull().default(false),
|
||||||
|
// Paid: revenue counted; Unpaid: balance due (collect at door); Comp: free guest, no revenue
|
||||||
|
paymentStatus: text('payment_status', { enum: ['paid', 'unpaid', 'comp'] }).notNull().default('unpaid'),
|
||||||
|
// How the booking was made: public checkout, a walk-in on the door screen, or
|
||||||
|
// added by an admin. Distinct from payments.source, which is where money was taken.
|
||||||
|
bookingSource: text('booking_source', { enum: ['online', 'walk_in', 'admin'] }).notNull().default('online'),
|
||||||
createdAt: text('created_at').notNull(),
|
createdAt: text('created_at').notNull(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const sqlitePayments = sqliteTable('payments', {
|
export const sqlitePayments = sqliteTable('payments', {
|
||||||
id: text('id').primaryKey(),
|
id: text('id').primaryKey(),
|
||||||
ticketId: text('ticket_id').notNull().references(() => sqliteTickets.id),
|
ticketId: text('ticket_id').notNull().references(() => sqliteTickets.id),
|
||||||
provider: text('provider', { enum: ['bancard', 'lightning', 'cash', 'bank_transfer', 'tpago'] }).notNull(),
|
provider: text('provider', { enum: ['bancard', 'lightning', 'cash', 'bank_transfer', 'tpago', 'pos'] }).notNull(),
|
||||||
amount: real('amount').notNull(),
|
amount: real('amount').notNull(),
|
||||||
currency: text('currency').notNull().default('PYG'),
|
currency: text('currency').notNull().default('PYG'),
|
||||||
status: text('status', { enum: ['pending', 'pending_approval', 'paid', 'refunded', 'failed', 'cancelled', 'on_hold'] }).notNull().default('pending'),
|
status: text('status', { enum: ['pending', 'pending_approval', 'paid', 'refunded', 'failed', 'cancelled', 'on_hold'] }).notNull().default('pending'),
|
||||||
@@ -130,10 +149,32 @@ export const sqlitePayments = sqliteTable('payments', {
|
|||||||
paidByAdminId: text('paid_by_admin_id'),
|
paidByAdminId: text('paid_by_admin_id'),
|
||||||
adminNote: text('admin_note'), // Internal admin notes
|
adminNote: text('admin_note'), // Internal admin notes
|
||||||
reminderSentAt: text('reminder_sent_at'), // When payment reminder email was sent
|
reminderSentAt: text('reminder_sent_at'), // When payment reminder email was sent
|
||||||
|
// Where the money was taken: 'presale' (online/admin, the default) or 'door'
|
||||||
|
// (recorded by staff on the door check-in screen). Splits pre-sale vs door revenue.
|
||||||
|
source: text('source', { enum: ['presale', 'door'] }).notNull().default('presale'),
|
||||||
|
// Door tender used, for the end-of-night cash-up. Null for pre-sale payments.
|
||||||
|
// 'guest' is a zero-amount comp entry and carries no revenue.
|
||||||
|
method: text('method', { enum: ['cash', 'bitcoin', 'transfer', 'pos', 'guest'] }),
|
||||||
createdAt: text('created_at').notNull(),
|
createdAt: text('created_at').notNull(),
|
||||||
updatedAt: text('updated_at').notNull(),
|
updatedAt: text('updated_at').notNull(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Idempotency records for door check-in actions.
|
||||||
|
//
|
||||||
|
// The door screen fires check-ins / walk-in creations optimistically and retries
|
||||||
|
// on flaky venue wifi, so every action carries a client-generated key. The first
|
||||||
|
// request stores its response here; replays return that stored response instead
|
||||||
|
// of creating a second ticket, payment or check-in. `undoState` holds exactly
|
||||||
|
// what the action changed so the 10-second Undo can reverse it precisely.
|
||||||
|
export const sqliteIdempotencyKeys = sqliteTable('idempotency_keys', {
|
||||||
|
key: text('key').primaryKey(),
|
||||||
|
scope: text('scope').notNull(),
|
||||||
|
result: text('result').notNull(), // JSON response body of the original request
|
||||||
|
undoState: text('undo_state'), // JSON describing how to reverse the action
|
||||||
|
undoneAt: text('undone_at'),
|
||||||
|
createdAt: text('created_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
// Payment Options Configuration Table (global settings)
|
// Payment Options Configuration Table (global settings)
|
||||||
export const sqlitePaymentOptions = sqliteTable('payment_options', {
|
export const sqlitePaymentOptions = sqliteTable('payment_options', {
|
||||||
id: text('id').primaryKey(),
|
id: text('id').primaryKey(),
|
||||||
@@ -161,6 +202,8 @@ export const sqlitePaymentOptions = sqliteTable('payment_options', {
|
|||||||
cashEnabled: integer('cash_enabled', { mode: 'boolean' }).notNull().default(true),
|
cashEnabled: integer('cash_enabled', { mode: 'boolean' }).notNull().default(true),
|
||||||
cashInstructions: text('cash_instructions'),
|
cashInstructions: text('cash_instructions'),
|
||||||
cashInstructionsEs: text('cash_instructions_es'),
|
cashInstructionsEs: text('cash_instructions_es'),
|
||||||
|
// POS card terminal at the door (Scanner only, never offered at online checkout)
|
||||||
|
posEnabled: integer('pos_enabled', { mode: 'boolean' }).notNull().default(true),
|
||||||
// Booking settings
|
// Booking settings
|
||||||
allowDuplicateBookings: integer('allow_duplicate_bookings', { mode: 'boolean' }).notNull().default(false),
|
allowDuplicateBookings: integer('allow_duplicate_bookings', { mode: 'boolean' }).notNull().default(false),
|
||||||
// Metadata
|
// Metadata
|
||||||
@@ -193,6 +236,7 @@ export const sqliteEventPaymentOverrides = sqliteTable('event_payment_overrides'
|
|||||||
cashEnabled: integer('cash_enabled', { mode: 'boolean' }),
|
cashEnabled: integer('cash_enabled', { mode: 'boolean' }),
|
||||||
cashInstructions: text('cash_instructions'),
|
cashInstructions: text('cash_instructions'),
|
||||||
cashInstructionsEs: text('cash_instructions_es'),
|
cashInstructionsEs: text('cash_instructions_es'),
|
||||||
|
posEnabled: integer('pos_enabled', { mode: 'boolean' }),
|
||||||
// Metadata
|
// Metadata
|
||||||
createdAt: text('created_at').notNull(),
|
createdAt: text('created_at').notNull(),
|
||||||
updatedAt: text('updated_at').notNull(),
|
updatedAt: text('updated_at').notNull(),
|
||||||
@@ -357,11 +401,160 @@ export const sqliteSiteSettings = sqliteTable('site_settings', {
|
|||||||
maintenanceMode: integer('maintenance_mode', { mode: 'boolean' }).notNull().default(false),
|
maintenanceMode: integer('maintenance_mode', { mode: 'boolean' }).notNull().default(false),
|
||||||
maintenanceMessage: text('maintenance_message'),
|
maintenanceMessage: text('maintenance_message'),
|
||||||
maintenanceMessageEs: text('maintenance_message_es'),
|
maintenanceMessageEs: text('maintenance_message_es'),
|
||||||
|
// Pre-sale closure defaults (events inherit these unless they override)
|
||||||
|
presaleClosureEnabled: integer('presale_closure_enabled', { mode: 'boolean' }).notNull().default(true),
|
||||||
|
presaleCloseMinutesBefore: integer('presale_close_minutes_before').notNull().default(120),
|
||||||
// Metadata
|
// Metadata
|
||||||
updatedAt: text('updated_at').notNull(),
|
updatedAt: text('updated_at').notNull(),
|
||||||
updatedBy: text('updated_by').references(() => sqliteUsers.id),
|
updatedBy: text('updated_by').references(() => sqliteUsers.id),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ==================== Event finance (SQLite) ====================
|
||||||
|
// All money columns are whole PYG (integer). Percentages are stored in basis
|
||||||
|
// points (hundredths of a percent): 290 = 2.90%. JSON columns are text.
|
||||||
|
|
||||||
|
export const sqliteExpenseCategories = sqliteTable('expense_categories', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
nameEn: text('name_en').notNull(),
|
||||||
|
nameEs: text('name_es').notNull(),
|
||||||
|
color: text('color').notNull().default('#6B7280'),
|
||||||
|
sortOrder: integer('sort_order').notNull().default(0),
|
||||||
|
archived: integer('archived', { mode: 'boolean' }).notNull().default(false),
|
||||||
|
createdAt: text('created_at').notNull(),
|
||||||
|
updatedAt: text('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteExpenseTemplates = sqliteTable('expense_templates', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
name: text('name').notNull(),
|
||||||
|
categoryId: text('category_id').references(() => sqliteExpenseCategories.id),
|
||||||
|
description: text('description'),
|
||||||
|
// fixed | per_ticket_sold | per_checked_in | percent_of_revenue | minimum_spend
|
||||||
|
calcType: text('calc_type').notNull(),
|
||||||
|
amount: integer('amount').notNull().default(0),
|
||||||
|
percentBp: integer('percent_bp').notNull().default(0),
|
||||||
|
minimumAmount: integer('minimum_amount').notNull().default(0),
|
||||||
|
archived: integer('archived', { mode: 'boolean' }).notNull().default(false),
|
||||||
|
createdAt: text('created_at').notNull(),
|
||||||
|
updatedAt: text('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteExpenseTemplatePacks = sqliteTable('expense_template_packs', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
name: text('name').notNull(),
|
||||||
|
description: text('description'),
|
||||||
|
archived: integer('archived', { mode: 'boolean' }).notNull().default(false),
|
||||||
|
createdAt: text('created_at').notNull(),
|
||||||
|
updatedAt: text('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteExpenseTemplatePackItems = sqliteTable('expense_template_pack_items', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
packId: text('pack_id').notNull().references(() => sqliteExpenseTemplatePacks.id),
|
||||||
|
templateId: text('template_id').notNull().references(() => sqliteExpenseTemplates.id),
|
||||||
|
sortOrder: integer('sort_order').notNull().default(0),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteEventPartners = sqliteTable('event_partners', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
eventId: text('event_id').notNull().references(() => sqliteEvents.id),
|
||||||
|
userId: text('user_id').references(() => sqliteUsers.id),
|
||||||
|
externalName: text('external_name'),
|
||||||
|
roleLabel: text('role_label'),
|
||||||
|
// percent_profit | percent_revenue | fixed | fixed_plus_percent_above_threshold
|
||||||
|
shareType: text('share_type').notNull(),
|
||||||
|
percentBp: integer('percent_bp').notNull().default(0),
|
||||||
|
fixedAmount: integer('fixed_amount').notNull().default(0),
|
||||||
|
thresholdAmount: integer('threshold_amount').notNull().default(0),
|
||||||
|
// proportional | none | capped
|
||||||
|
lossRule: text('loss_rule').notNull().default('none'),
|
||||||
|
lossCapAmount: integer('loss_cap_amount').notNull().default(0),
|
||||||
|
payoutStatus: text('payout_status').notNull().default('pending'),
|
||||||
|
payoutDate: text('payout_date'),
|
||||||
|
payoutMethod: text('payout_method'),
|
||||||
|
payoutNote: text('payout_note'),
|
||||||
|
createdAt: text('created_at').notNull(),
|
||||||
|
updatedAt: text('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteEventExpenses = sqliteTable('event_expenses', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
eventId: text('event_id').notNull().references(() => sqliteEvents.id),
|
||||||
|
categoryId: text('category_id').references(() => sqliteExpenseCategories.id),
|
||||||
|
templateId: text('template_id').references(() => sqliteExpenseTemplates.id),
|
||||||
|
description: text('description').notNull(),
|
||||||
|
calcType: text('calc_type').notNull().default('fixed'),
|
||||||
|
// fixed: units bought; auto types: the count used at the last calculation
|
||||||
|
quantity: integer('quantity').notNull().default(1),
|
||||||
|
unitAmount: integer('unit_amount').notNull().default(0),
|
||||||
|
percentBp: integer('percent_bp').notNull().default(0),
|
||||||
|
minimumAmount: integer('minimum_amount').notNull().default(0),
|
||||||
|
computedAmount: integer('computed_amount').notNull().default(0),
|
||||||
|
// Locked rows keep computed_amount instead of following ticket counts
|
||||||
|
isLocked: integer('is_locked', { mode: 'boolean' }).notNull().default(false),
|
||||||
|
status: text('status').notNull().default('planned'), // planned | paid
|
||||||
|
// NULL = the organization paid; otherwise the partner who fronted it
|
||||||
|
paidByPartnerId: text('paid_by_partner_id').references(() => sqliteEventPartners.id),
|
||||||
|
receiptUrl: text('receipt_url'),
|
||||||
|
expenseDate: text('expense_date'),
|
||||||
|
createdBy: text('created_by').references(() => sqliteUsers.id),
|
||||||
|
updatedBy: text('updated_by').references(() => sqliteUsers.id),
|
||||||
|
createdAt: text('created_at').notNull(),
|
||||||
|
updatedAt: text('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteEventOtherIncome = sqliteTable('event_other_income', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
eventId: text('event_id').notNull().references(() => sqliteEvents.id),
|
||||||
|
description: text('description').notNull(),
|
||||||
|
amount: integer('amount').notNull(),
|
||||||
|
createdBy: text('created_by').references(() => sqliteUsers.id),
|
||||||
|
createdAt: text('created_at').notNull(),
|
||||||
|
updatedAt: text('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Keyed by payments.provider (door payments carry the legacy provider too)
|
||||||
|
export const sqlitePaymentMethodFees = sqliteTable('payment_method_fees', {
|
||||||
|
method: text('method').primaryKey(),
|
||||||
|
percentBp: integer('percent_bp').notNull().default(0),
|
||||||
|
fixedAmount: integer('fixed_amount').notNull().default(0),
|
||||||
|
updatedAt: text('updated_at').notNull(),
|
||||||
|
updatedBy: text('updated_by').references(() => sqliteUsers.id),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteEventFinanceState = sqliteTable('event_finance_state', {
|
||||||
|
eventId: text('event_id').primaryKey().references(() => sqliteEvents.id),
|
||||||
|
status: text('status').notNull().default('open'), // open | finalized | paid_out
|
||||||
|
finalizedAt: text('finalized_at'),
|
||||||
|
finalizedBy: text('finalized_by').references(() => sqliteUsers.id),
|
||||||
|
snapshotJson: text('snapshot_json'),
|
||||||
|
updatedAt: text('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteEventMembers = sqliteTable('event_members', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
eventId: text('event_id').notNull().references(() => sqliteEvents.id),
|
||||||
|
userId: text('user_id').notNull().references(() => sqliteUsers.id),
|
||||||
|
rolePreset: text('role_preset').notNull(), // staff | collaborator | co_manager
|
||||||
|
// JSON {permissionKey: boolean} applied on top of the preset
|
||||||
|
permissions: text('permissions').notNull().default('{}'),
|
||||||
|
createdBy: text('created_by').references(() => sqliteUsers.id),
|
||||||
|
createdAt: text('created_at').notNull(),
|
||||||
|
updatedAt: text('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sqliteFinanceAuditLog = sqliteTable('finance_audit_log', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
eventId: text('event_id'), // NULL for global finance settings
|
||||||
|
actorUserId: text('actor_user_id').references(() => sqliteUsers.id),
|
||||||
|
entityType: text('entity_type').notNull(),
|
||||||
|
entityId: text('entity_id'),
|
||||||
|
action: text('action').notNull(),
|
||||||
|
beforeJson: text('before_json'),
|
||||||
|
afterJson: text('after_json'),
|
||||||
|
createdAt: text('created_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
// ==================== PostgreSQL Schema ====================
|
// ==================== PostgreSQL Schema ====================
|
||||||
export const pgUsers = pgTable('users', {
|
export const pgUsers = pgTable('users', {
|
||||||
id: uuid('id').primaryKey(),
|
id: uuid('id').primaryKey(),
|
||||||
@@ -378,6 +571,12 @@ export const pgUsers = pgTable('users', {
|
|||||||
accountStatus: varchar('account_status', { length: 20 }).notNull().default('active'),
|
accountStatus: varchar('account_status', { length: 20 }).notNull().default('active'),
|
||||||
// Incremented to invalidate previously issued JWTs (logout-everywhere, password change/reset)
|
// Incremented to invalidate previously issued JWTs (logout-everywhere, password change/reset)
|
||||||
tokenVersion: pgInteger('token_version').notNull().default(0),
|
tokenVersion: pgInteger('token_version').notNull().default(0),
|
||||||
|
// Better Auth core + admin plugin fields (auth-schema.ts maps the same columns)
|
||||||
|
emailVerified: pgBoolean('email_verified').notNull().default(false),
|
||||||
|
image: pgText('image'),
|
||||||
|
banned: pgBoolean('banned').notNull().default(false),
|
||||||
|
banReason: pgText('ban_reason'),
|
||||||
|
banExpires: timestamp('ban_expires'),
|
||||||
createdAt: timestamp('created_at').notNull(),
|
createdAt: timestamp('created_at').notNull(),
|
||||||
updatedAt: timestamp('updated_at').notNull(),
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
});
|
});
|
||||||
@@ -434,12 +633,19 @@ export const pgEvents = pgTable('events', {
|
|||||||
location: varchar('location', { length: 500 }).notNull(),
|
location: varchar('location', { length: 500 }).notNull(),
|
||||||
locationUrl: varchar('location_url', { length: 500 }),
|
locationUrl: varchar('location_url', { length: 500 }),
|
||||||
price: decimal('price', { precision: 10, scale: 2 }).notNull().default('0'),
|
price: decimal('price', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
// Charged for walk-ins at the door (Scanner). Null = fall back to price; 0 = free.
|
||||||
|
// Admin/staff only: never serialized to public event responses.
|
||||||
|
walkInPrice: decimal('walk_in_price', { precision: 10, scale: 2 }),
|
||||||
currency: varchar('currency', { length: 10 }).notNull().default('PYG'),
|
currency: varchar('currency', { length: 10 }).notNull().default('PYG'),
|
||||||
capacity: pgInteger('capacity').notNull().default(50),
|
capacity: pgInteger('capacity').notNull().default(50),
|
||||||
status: varchar('status', { length: 20 }).notNull().default('draft'),
|
status: varchar('status', { length: 20 }).notNull().default('draft'),
|
||||||
bannerUrl: varchar('banner_url', { length: 500 }),
|
bannerUrl: varchar('banner_url', { length: 500 }),
|
||||||
externalBookingEnabled: pgInteger('external_booking_enabled').notNull().default(0),
|
externalBookingEnabled: pgInteger('external_booking_enabled').notNull().default(0),
|
||||||
externalBookingUrl: varchar('external_booking_url', { length: 500 }),
|
externalBookingUrl: varchar('external_booking_url', { length: 500 }),
|
||||||
|
// Pre-sale closure: null = inherit the site_settings default
|
||||||
|
presaleClosureEnabled: pgInteger('presale_closure_enabled'),
|
||||||
|
presaleCloseMinutesBefore: pgInteger('presale_close_minutes_before'),
|
||||||
|
series: varchar('series', { length: 100 }),
|
||||||
createdAt: timestamp('created_at').notNull(),
|
createdAt: timestamp('created_at').notNull(),
|
||||||
updatedAt: timestamp('updated_at').notNull(),
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
});
|
});
|
||||||
@@ -468,6 +674,10 @@ export const pgTickets = pgTable('tickets', {
|
|||||||
qrCode: varchar('qr_code', { length: 255 }),
|
qrCode: varchar('qr_code', { length: 255 }),
|
||||||
adminNote: pgText('admin_note'),
|
adminNote: pgText('admin_note'),
|
||||||
isGuest: pgInteger('is_guest').notNull().default(0),
|
isGuest: pgInteger('is_guest').notNull().default(0),
|
||||||
|
// Paid: revenue counted; Unpaid: balance due (collect at door); Comp: free guest, no revenue
|
||||||
|
paymentStatus: varchar('payment_status', { length: 10 }).notNull().default('unpaid'),
|
||||||
|
// online | walk_in | admin — see sqliteTickets.bookingSource
|
||||||
|
bookingSource: varchar('booking_source', { length: 20 }).notNull().default('online'),
|
||||||
createdAt: timestamp('created_at').notNull(),
|
createdAt: timestamp('created_at').notNull(),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -488,10 +698,26 @@ export const pgPayments = pgTable('payments', {
|
|||||||
paidByAdminId: uuid('paid_by_admin_id'),
|
paidByAdminId: uuid('paid_by_admin_id'),
|
||||||
adminNote: pgText('admin_note'),
|
adminNote: pgText('admin_note'),
|
||||||
reminderSentAt: timestamp('reminder_sent_at'), // When payment reminder email was sent
|
reminderSentAt: timestamp('reminder_sent_at'), // When payment reminder email was sent
|
||||||
|
// Where the money was taken: 'presale' (online/admin, the default) or 'door'
|
||||||
|
// (recorded by staff on the door check-in screen). Splits pre-sale vs door revenue.
|
||||||
|
source: varchar('source', { length: 20 }).notNull().default('presale'),
|
||||||
|
// Door tender used, for the end-of-night cash-up. Null for pre-sale payments.
|
||||||
|
// 'guest' is a zero-amount comp entry and carries no revenue.
|
||||||
|
method: varchar('method', { length: 20 }),
|
||||||
createdAt: timestamp('created_at').notNull(),
|
createdAt: timestamp('created_at').notNull(),
|
||||||
updatedAt: timestamp('updated_at').notNull(),
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Idempotency records for door check-in actions (see sqliteIdempotencyKeys).
|
||||||
|
export const pgIdempotencyKeys = pgTable('idempotency_keys', {
|
||||||
|
key: varchar('key', { length: 128 }).primaryKey(),
|
||||||
|
scope: varchar('scope', { length: 64 }).notNull(),
|
||||||
|
result: pgText('result').notNull(),
|
||||||
|
undoState: pgText('undo_state'),
|
||||||
|
undoneAt: timestamp('undone_at'),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
// Payment Options Configuration Table (global settings)
|
// Payment Options Configuration Table (global settings)
|
||||||
export const pgPaymentOptions = pgTable('payment_options', {
|
export const pgPaymentOptions = pgTable('payment_options', {
|
||||||
id: uuid('id').primaryKey(),
|
id: uuid('id').primaryKey(),
|
||||||
@@ -515,6 +741,7 @@ export const pgPaymentOptions = pgTable('payment_options', {
|
|||||||
cashEnabled: pgInteger('cash_enabled').notNull().default(1),
|
cashEnabled: pgInteger('cash_enabled').notNull().default(1),
|
||||||
cashInstructions: pgText('cash_instructions'),
|
cashInstructions: pgText('cash_instructions'),
|
||||||
cashInstructionsEs: pgText('cash_instructions_es'),
|
cashInstructionsEs: pgText('cash_instructions_es'),
|
||||||
|
posEnabled: pgInteger('pos_enabled').notNull().default(1),
|
||||||
allowDuplicateBookings: pgInteger('allow_duplicate_bookings').notNull().default(0),
|
allowDuplicateBookings: pgInteger('allow_duplicate_bookings').notNull().default(0),
|
||||||
updatedAt: timestamp('updated_at').notNull(),
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
updatedBy: uuid('updated_by').references(() => pgUsers.id),
|
updatedBy: uuid('updated_by').references(() => pgUsers.id),
|
||||||
@@ -544,6 +771,7 @@ export const pgEventPaymentOverrides = pgTable('event_payment_overrides', {
|
|||||||
cashEnabled: pgInteger('cash_enabled'),
|
cashEnabled: pgInteger('cash_enabled'),
|
||||||
cashInstructions: pgText('cash_instructions'),
|
cashInstructions: pgText('cash_instructions'),
|
||||||
cashInstructionsEs: pgText('cash_instructions_es'),
|
cashInstructionsEs: pgText('cash_instructions_es'),
|
||||||
|
posEnabled: pgInteger('pos_enabled'),
|
||||||
createdAt: timestamp('created_at').notNull(),
|
createdAt: timestamp('created_at').notNull(),
|
||||||
updatedAt: timestamp('updated_at').notNull(),
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
});
|
});
|
||||||
@@ -707,17 +935,159 @@ export const pgSiteSettings = pgTable('site_settings', {
|
|||||||
maintenanceMode: pgInteger('maintenance_mode').notNull().default(0),
|
maintenanceMode: pgInteger('maintenance_mode').notNull().default(0),
|
||||||
maintenanceMessage: pgText('maintenance_message'),
|
maintenanceMessage: pgText('maintenance_message'),
|
||||||
maintenanceMessageEs: pgText('maintenance_message_es'),
|
maintenanceMessageEs: pgText('maintenance_message_es'),
|
||||||
|
// Pre-sale closure defaults (events inherit these unless they override)
|
||||||
|
presaleClosureEnabled: pgInteger('presale_closure_enabled').notNull().default(1),
|
||||||
|
presaleCloseMinutesBefore: pgInteger('presale_close_minutes_before').notNull().default(120),
|
||||||
// Metadata
|
// Metadata
|
||||||
updatedAt: timestamp('updated_at').notNull(),
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
updatedBy: uuid('updated_by').references(() => pgUsers.id),
|
updatedBy: uuid('updated_by').references(() => pgUsers.id),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ==================== Event finance (PostgreSQL) ====================
|
||||||
|
// See the SQLite block: integer PYG, basis-point percentages, JSON as text.
|
||||||
|
|
||||||
|
export const pgExpenseCategories = pgTable('expense_categories', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
nameEn: varchar('name_en', { length: 100 }).notNull(),
|
||||||
|
nameEs: varchar('name_es', { length: 100 }).notNull(),
|
||||||
|
color: varchar('color', { length: 20 }).notNull().default('#6B7280'),
|
||||||
|
sortOrder: pgInteger('sort_order').notNull().default(0),
|
||||||
|
archived: pgInteger('archived').notNull().default(0),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgExpenseTemplates = pgTable('expense_templates', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
name: varchar('name', { length: 200 }).notNull(),
|
||||||
|
categoryId: uuid('category_id').references(() => pgExpenseCategories.id),
|
||||||
|
description: pgText('description'),
|
||||||
|
calcType: varchar('calc_type', { length: 40 }).notNull(),
|
||||||
|
amount: pgInteger('amount').notNull().default(0),
|
||||||
|
percentBp: pgInteger('percent_bp').notNull().default(0),
|
||||||
|
minimumAmount: pgInteger('minimum_amount').notNull().default(0),
|
||||||
|
archived: pgInteger('archived').notNull().default(0),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgExpenseTemplatePacks = pgTable('expense_template_packs', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
name: varchar('name', { length: 200 }).notNull(),
|
||||||
|
description: pgText('description'),
|
||||||
|
archived: pgInteger('archived').notNull().default(0),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgExpenseTemplatePackItems = pgTable('expense_template_pack_items', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
packId: uuid('pack_id').notNull().references(() => pgExpenseTemplatePacks.id),
|
||||||
|
templateId: uuid('template_id').notNull().references(() => pgExpenseTemplates.id),
|
||||||
|
sortOrder: pgInteger('sort_order').notNull().default(0),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgEventPartners = pgTable('event_partners', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
eventId: uuid('event_id').notNull().references(() => pgEvents.id),
|
||||||
|
userId: uuid('user_id').references(() => pgUsers.id),
|
||||||
|
externalName: varchar('external_name', { length: 200 }),
|
||||||
|
roleLabel: varchar('role_label', { length: 100 }),
|
||||||
|
shareType: varchar('share_type', { length: 40 }).notNull(),
|
||||||
|
percentBp: pgInteger('percent_bp').notNull().default(0),
|
||||||
|
fixedAmount: pgInteger('fixed_amount').notNull().default(0),
|
||||||
|
thresholdAmount: pgInteger('threshold_amount').notNull().default(0),
|
||||||
|
lossRule: varchar('loss_rule', { length: 20 }).notNull().default('none'),
|
||||||
|
lossCapAmount: pgInteger('loss_cap_amount').notNull().default(0),
|
||||||
|
payoutStatus: varchar('payout_status', { length: 20 }).notNull().default('pending'),
|
||||||
|
payoutDate: timestamp('payout_date'),
|
||||||
|
payoutMethod: varchar('payout_method', { length: 50 }),
|
||||||
|
payoutNote: pgText('payout_note'),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgEventExpenses = pgTable('event_expenses', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
eventId: uuid('event_id').notNull().references(() => pgEvents.id),
|
||||||
|
categoryId: uuid('category_id').references(() => pgExpenseCategories.id),
|
||||||
|
templateId: uuid('template_id').references(() => pgExpenseTemplates.id),
|
||||||
|
description: varchar('description', { length: 300 }).notNull(),
|
||||||
|
calcType: varchar('calc_type', { length: 40 }).notNull().default('fixed'),
|
||||||
|
quantity: pgInteger('quantity').notNull().default(1),
|
||||||
|
unitAmount: pgInteger('unit_amount').notNull().default(0),
|
||||||
|
percentBp: pgInteger('percent_bp').notNull().default(0),
|
||||||
|
minimumAmount: pgInteger('minimum_amount').notNull().default(0),
|
||||||
|
computedAmount: pgInteger('computed_amount').notNull().default(0),
|
||||||
|
isLocked: pgInteger('is_locked').notNull().default(0),
|
||||||
|
status: varchar('status', { length: 20 }).notNull().default('planned'),
|
||||||
|
paidByPartnerId: uuid('paid_by_partner_id').references(() => pgEventPartners.id),
|
||||||
|
receiptUrl: varchar('receipt_url', { length: 500 }),
|
||||||
|
expenseDate: timestamp('expense_date'),
|
||||||
|
createdBy: uuid('created_by').references(() => pgUsers.id),
|
||||||
|
updatedBy: uuid('updated_by').references(() => pgUsers.id),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgEventOtherIncome = pgTable('event_other_income', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
eventId: uuid('event_id').notNull().references(() => pgEvents.id),
|
||||||
|
description: varchar('description', { length: 300 }).notNull(),
|
||||||
|
amount: pgInteger('amount').notNull(),
|
||||||
|
createdBy: uuid('created_by').references(() => pgUsers.id),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgPaymentMethodFees = pgTable('payment_method_fees', {
|
||||||
|
method: varchar('method', { length: 50 }).primaryKey(),
|
||||||
|
percentBp: pgInteger('percent_bp').notNull().default(0),
|
||||||
|
fixedAmount: pgInteger('fixed_amount').notNull().default(0),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
updatedBy: uuid('updated_by').references(() => pgUsers.id),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgEventFinanceState = pgTable('event_finance_state', {
|
||||||
|
eventId: uuid('event_id').primaryKey().references(() => pgEvents.id),
|
||||||
|
status: varchar('status', { length: 20 }).notNull().default('open'),
|
||||||
|
finalizedAt: timestamp('finalized_at'),
|
||||||
|
finalizedBy: uuid('finalized_by').references(() => pgUsers.id),
|
||||||
|
snapshotJson: pgText('snapshot_json'),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgEventMembers = pgTable('event_members', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
eventId: uuid('event_id').notNull().references(() => pgEvents.id),
|
||||||
|
userId: uuid('user_id').notNull().references(() => pgUsers.id),
|
||||||
|
rolePreset: varchar('role_preset', { length: 20 }).notNull(),
|
||||||
|
permissions: pgText('permissions').notNull().default('{}'),
|
||||||
|
createdBy: uuid('created_by').references(() => pgUsers.id),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pgFinanceAuditLog = pgTable('finance_audit_log', {
|
||||||
|
id: uuid('id').primaryKey(),
|
||||||
|
eventId: uuid('event_id'),
|
||||||
|
actorUserId: uuid('actor_user_id').references(() => pgUsers.id),
|
||||||
|
entityType: varchar('entity_type', { length: 50 }).notNull(),
|
||||||
|
// Text, not uuid: settings rows are keyed by method name
|
||||||
|
entityId: varchar('entity_id', { length: 100 }),
|
||||||
|
action: varchar('action', { length: 50 }).notNull(),
|
||||||
|
beforeJson: pgText('before_json'),
|
||||||
|
afterJson: pgText('after_json'),
|
||||||
|
createdAt: timestamp('created_at').notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
// Export the appropriate schema based on DB_TYPE
|
// Export the appropriate schema based on DB_TYPE
|
||||||
export const users = dbType === 'postgres' ? pgUsers : sqliteUsers;
|
export const users = dbType === 'postgres' ? pgUsers : sqliteUsers;
|
||||||
export const events = dbType === 'postgres' ? pgEvents : sqliteEvents;
|
export const events = dbType === 'postgres' ? pgEvents : sqliteEvents;
|
||||||
export const eventSlugAliases = dbType === 'postgres' ? pgEventSlugAliases : sqliteEventSlugAliases;
|
export const eventSlugAliases = dbType === 'postgres' ? pgEventSlugAliases : sqliteEventSlugAliases;
|
||||||
export const tickets = dbType === 'postgres' ? pgTickets : sqliteTickets;
|
export const tickets = dbType === 'postgres' ? pgTickets : sqliteTickets;
|
||||||
export const payments = dbType === 'postgres' ? pgPayments : sqlitePayments;
|
export const payments = dbType === 'postgres' ? pgPayments : sqlitePayments;
|
||||||
|
export const idempotencyKeys = dbType === 'postgres' ? pgIdempotencyKeys : sqliteIdempotencyKeys;
|
||||||
export const contacts = dbType === 'postgres' ? pgContacts : sqliteContacts;
|
export const contacts = dbType === 'postgres' ? pgContacts : sqliteContacts;
|
||||||
export const emailSubscribers = dbType === 'postgres' ? pgEmailSubscribers : sqliteEmailSubscribers;
|
export const emailSubscribers = dbType === 'postgres' ? pgEmailSubscribers : sqliteEmailSubscribers;
|
||||||
export const media = dbType === 'postgres' ? pgMedia : sqliteMedia;
|
export const media = dbType === 'postgres' ? pgMedia : sqliteMedia;
|
||||||
@@ -735,6 +1105,17 @@ export const legalSettings = dbType === 'postgres' ? pgLegalSettings : sqliteLeg
|
|||||||
export const siteSettings = dbType === 'postgres' ? pgSiteSettings : sqliteSiteSettings;
|
export const siteSettings = dbType === 'postgres' ? pgSiteSettings : sqliteSiteSettings;
|
||||||
export const legalPages = dbType === 'postgres' ? pgLegalPages : sqliteLegalPages;
|
export const legalPages = dbType === 'postgres' ? pgLegalPages : sqliteLegalPages;
|
||||||
export const faqQuestions = dbType === 'postgres' ? pgFaqQuestions : sqliteFaqQuestions;
|
export const faqQuestions = dbType === 'postgres' ? pgFaqQuestions : sqliteFaqQuestions;
|
||||||
|
export const expenseCategories = dbType === 'postgres' ? pgExpenseCategories : sqliteExpenseCategories;
|
||||||
|
export const expenseTemplates = dbType === 'postgres' ? pgExpenseTemplates : sqliteExpenseTemplates;
|
||||||
|
export const expenseTemplatePacks = dbType === 'postgres' ? pgExpenseTemplatePacks : sqliteExpenseTemplatePacks;
|
||||||
|
export const expenseTemplatePackItems = dbType === 'postgres' ? pgExpenseTemplatePackItems : sqliteExpenseTemplatePackItems;
|
||||||
|
export const eventPartners = dbType === 'postgres' ? pgEventPartners : sqliteEventPartners;
|
||||||
|
export const eventExpenses = dbType === 'postgres' ? pgEventExpenses : sqliteEventExpenses;
|
||||||
|
export const eventOtherIncome = dbType === 'postgres' ? pgEventOtherIncome : sqliteEventOtherIncome;
|
||||||
|
export const paymentMethodFees = dbType === 'postgres' ? pgPaymentMethodFees : sqlitePaymentMethodFees;
|
||||||
|
export const eventFinanceState = dbType === 'postgres' ? pgEventFinanceState : sqliteEventFinanceState;
|
||||||
|
export const eventMembers = dbType === 'postgres' ? pgEventMembers : sqliteEventMembers;
|
||||||
|
export const financeAuditLog = dbType === 'postgres' ? pgFinanceAuditLog : sqliteFinanceAuditLog;
|
||||||
|
|
||||||
// Type exports
|
// Type exports
|
||||||
export type User = typeof sqliteUsers.$inferSelect;
|
export type User = typeof sqliteUsers.$inferSelect;
|
||||||
@@ -769,3 +1150,12 @@ export type FaqQuestion = typeof sqliteFaqQuestions.$inferSelect;
|
|||||||
export type NewFaqQuestion = typeof sqliteFaqQuestions.$inferInsert;
|
export type NewFaqQuestion = typeof sqliteFaqQuestions.$inferInsert;
|
||||||
export type LegalSettings = typeof sqliteLegalSettings.$inferSelect;
|
export type LegalSettings = typeof sqliteLegalSettings.$inferSelect;
|
||||||
export type NewLegalSettings = typeof sqliteLegalSettings.$inferInsert;
|
export type NewLegalSettings = typeof sqliteLegalSettings.$inferInsert;
|
||||||
|
export type ExpenseCategory = typeof sqliteExpenseCategories.$inferSelect;
|
||||||
|
export type ExpenseTemplate = typeof sqliteExpenseTemplates.$inferSelect;
|
||||||
|
export type ExpenseTemplatePack = typeof sqliteExpenseTemplatePacks.$inferSelect;
|
||||||
|
export type EventPartner = typeof sqliteEventPartners.$inferSelect;
|
||||||
|
export type EventExpense = typeof sqliteEventExpenses.$inferSelect;
|
||||||
|
export type EventOtherIncome = typeof sqliteEventOtherIncome.$inferSelect;
|
||||||
|
export type PaymentMethodFee = typeof sqlitePaymentMethodFees.$inferSelect;
|
||||||
|
export type EventFinanceState = typeof sqliteEventFinanceState.$inferSelect;
|
||||||
|
export type EventMember = typeof sqliteEventMembers.$inferSelect;
|
||||||
|
|||||||
+300
-130
@@ -7,9 +7,14 @@ import { logger } from 'hono/logger';
|
|||||||
import { swaggerUI } from '@hono/swagger-ui';
|
import { swaggerUI } from '@hono/swagger-ui';
|
||||||
|
|
||||||
import { serveStatic } from '@hono/node-server/serve-static';
|
import { serveStatic } from '@hono/node-server/serve-static';
|
||||||
import authRoutes from './routes/auth.js';
|
import { auth } from './lib/betterAuth.js';
|
||||||
|
import authExtRoutes from './routes/authExt.js';
|
||||||
|
import { getClientIp } from './lib/rateLimit.js';
|
||||||
import eventsRoutes from './routes/events.js';
|
import eventsRoutes from './routes/events.js';
|
||||||
import ticketsRoutes from './routes/tickets.js';
|
import ticketsRoutes from './routes/tickets.js';
|
||||||
|
import doorRoutes from './routes/door.js';
|
||||||
|
import eventFinanceRoutes from './routes/eventFinance.js';
|
||||||
|
import financeRoutes from './routes/finance.js';
|
||||||
import usersRoutes from './routes/users.js';
|
import usersRoutes from './routes/users.js';
|
||||||
import contactsRoutes from './routes/contacts.js';
|
import contactsRoutes from './routes/contacts.js';
|
||||||
import paymentsRoutes from './routes/payments.js';
|
import paymentsRoutes from './routes/payments.js';
|
||||||
@@ -24,10 +29,11 @@ import legalPagesRoutes from './routes/legal-pages.js';
|
|||||||
import legalSettingsRoutes from './routes/legal-settings.js';
|
import legalSettingsRoutes from './routes/legal-settings.js';
|
||||||
import faqRoutes from './routes/faq.js';
|
import faqRoutes from './routes/faq.js';
|
||||||
import emailService from './lib/email.js';
|
import emailService from './lib/email.js';
|
||||||
import { initEmailQueue } from './lib/emailQueue.js';
|
import { initEmailQueue, stopQueue } from './lib/emailQueue.js';
|
||||||
import { startBookingCleanup } from './lib/bookingCleanup.js';
|
import { startBookingCleanup, stopBookingCleanup } from './lib/bookingCleanup.js';
|
||||||
import { startHoldSweep } from './lib/holdSweep.js';
|
import { startHoldSweep, stopHoldSweep } from './lib/holdSweep.js';
|
||||||
import { startEventEndSweep } from './lib/eventEndSweep.js';
|
import { startEventEndSweep, stopEventEndSweep } from './lib/eventEndSweep.js';
|
||||||
|
import { closeRedis } from './lib/redis.js';
|
||||||
import { getLock } from './lib/stores/lock.js';
|
import { getLock } from './lib/stores/lock.js';
|
||||||
import { describeBackends, describeRedis, logSelectedBackends } from './lib/backends.js';
|
import { describeBackends, describeRedis, logSelectedBackends } from './lib/backends.js';
|
||||||
|
|
||||||
@@ -56,7 +62,7 @@ app.use(
|
|||||||
if (!origin) return frontendUrl;
|
if (!origin) return frontendUrl;
|
||||||
return allowedOrigins.has(origin) ? origin : null;
|
return allowedOrigins.has(origin) ? origin : null;
|
||||||
},
|
},
|
||||||
// We use bearer tokens, but keeping credentials=true matches nginx config.
|
// Session cookies must be allowed on cross-origin API calls (api.* vhost).
|
||||||
credentials: true,
|
credentials: true,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@@ -109,11 +115,15 @@ const openApiSpec = {
|
|||||||
],
|
],
|
||||||
paths: {
|
paths: {
|
||||||
// ==================== Auth Endpoints ====================
|
// ==================== Auth Endpoints ====================
|
||||||
'/api/auth/register': {
|
// Authentication is handled by Better Auth, mounted at /api/auth/*.
|
||||||
|
// Sessions are httpOnly cookies (spanglish.session_token); the endpoints
|
||||||
|
// below are the subset the frontend uses. See https://better-auth.com/docs
|
||||||
|
// for the full endpoint reference.
|
||||||
|
'/api/auth/sign-up/email': {
|
||||||
post: {
|
post: {
|
||||||
tags: ['Auth'],
|
tags: ['Auth'],
|
||||||
summary: 'Register a new user',
|
summary: 'Register a new user (Better Auth)',
|
||||||
description: 'Create a new user account. First registered user becomes admin. Password must be at least 10 characters.',
|
description: 'Create a user account and start a cookie session. First registered user becomes admin. Password policy: 10-128 chars, upper+lower+digit-or-symbol, common passwords rejected.',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
content: {
|
content: {
|
||||||
@@ -123,8 +133,8 @@ const openApiSpec = {
|
|||||||
required: ['email', 'password', 'name'],
|
required: ['email', 'password', 'name'],
|
||||||
properties: {
|
properties: {
|
||||||
email: { type: 'string', format: 'email' },
|
email: { type: 'string', format: 'email' },
|
||||||
password: { type: 'string', minLength: 10, description: 'Minimum 10 characters' },
|
password: { type: 'string', minLength: 10 },
|
||||||
name: { type: 'string', minLength: 2 },
|
name: { type: 'string' },
|
||||||
phone: { type: 'string' },
|
phone: { type: 'string' },
|
||||||
languagePreference: { type: 'string', enum: ['en', 'es'] },
|
languagePreference: { type: 'string', enum: ['en', 'es'] },
|
||||||
},
|
},
|
||||||
@@ -133,16 +143,17 @@ const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
responses: {
|
responses: {
|
||||||
201: { description: 'User created successfully' },
|
200: { description: 'User created; session cookie set' },
|
||||||
400: { description: 'Email already registered or validation error' },
|
422: { description: 'Email already registered' },
|
||||||
|
400: { description: 'Validation error' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'/api/auth/login': {
|
'/api/auth/sign-in/email': {
|
||||||
post: {
|
post: {
|
||||||
tags: ['Auth'],
|
tags: ['Auth'],
|
||||||
summary: 'Login with email and password',
|
summary: 'Login with email and password (Better Auth)',
|
||||||
description: 'Authenticate user with email and password. Rate limited to 5 attempts per 15 minutes.',
|
description: 'Starts a cookie session. Per-email lockout: 5 failures / 15 min. Per-IP rate limited.',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
content: {
|
content: {
|
||||||
@@ -159,42 +170,46 @@ const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
responses: {
|
responses: {
|
||||||
200: { description: 'Login successful, returns JWT token' },
|
200: { description: 'Login successful; session cookie set' },
|
||||||
401: { description: 'Invalid credentials' },
|
401: { description: 'Invalid credentials' },
|
||||||
429: { description: 'Too many login attempts' },
|
429: { description: 'Too many attempts' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'/api/auth/google': {
|
'/api/auth/sign-in/social': {
|
||||||
post: {
|
post: {
|
||||||
tags: ['Auth'],
|
tags: ['Auth'],
|
||||||
summary: 'Login or register with Google',
|
summary: 'Login or register with Google (Better Auth)',
|
||||||
description: 'Authenticate using Google OAuth. Creates account if user does not exist.',
|
description: 'Sign in with a Google ID token (Google Identity Services credential). Links to an existing account by verified email.',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: {
|
schema: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
required: ['credential'],
|
required: ['provider'],
|
||||||
properties: {
|
properties: {
|
||||||
credential: { type: 'string', description: 'Google ID token' },
|
provider: { type: 'string', enum: ['google'] },
|
||||||
|
idToken: {
|
||||||
|
type: 'object',
|
||||||
|
properties: { token: { type: 'string', description: 'Google ID token' } },
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
responses: {
|
responses: {
|
||||||
200: { description: 'Login successful' },
|
200: { description: 'Login successful; session cookie set' },
|
||||||
400: { description: 'Invalid Google token' },
|
401: { description: 'Invalid Google token' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'/api/auth/magic-link/request': {
|
'/api/auth/sign-in/magic-link': {
|
||||||
post: {
|
post: {
|
||||||
tags: ['Auth'],
|
tags: ['Auth'],
|
||||||
summary: 'Request magic link login',
|
summary: 'Request magic link login (Better Auth)',
|
||||||
description: 'Send a one-time login link to email. Link expires in 10 minutes.',
|
description: 'Emails a one-time login link (10 min TTL, single use, hashed at rest). Does not create accounts.',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
content: {
|
content: {
|
||||||
@@ -204,46 +219,33 @@ const openApiSpec = {
|
|||||||
required: ['email'],
|
required: ['email'],
|
||||||
properties: {
|
properties: {
|
||||||
email: { type: 'string', format: 'email' },
|
email: { type: 'string', format: 'email' },
|
||||||
|
callbackURL: { type: 'string' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
responses: {
|
responses: { 200: { description: 'Magic link sent (if account exists)' } },
|
||||||
200: { description: 'Magic link sent (if account exists)' },
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'/api/auth/magic-link/verify': {
|
'/api/auth/magic-link/verify': {
|
||||||
post: {
|
get: {
|
||||||
tags: ['Auth'],
|
tags: ['Auth'],
|
||||||
summary: 'Verify magic link token',
|
summary: 'Verify magic link token (Better Auth)',
|
||||||
description: 'Verify the magic link token and login user.',
|
parameters: [
|
||||||
requestBody: {
|
{ name: 'token', in: 'query', required: true, schema: { type: 'string' } },
|
||||||
required: true,
|
],
|
||||||
content: {
|
|
||||||
'application/json': {
|
|
||||||
schema: {
|
|
||||||
type: 'object',
|
|
||||||
required: ['token'],
|
|
||||||
properties: {
|
|
||||||
token: { type: 'string' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
responses: {
|
responses: {
|
||||||
200: { description: 'Login successful' },
|
200: { description: 'Login successful; session cookie set' },
|
||||||
400: { description: 'Invalid or expired token' },
|
400: { description: 'Invalid or expired token' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'/api/auth/password-reset/request': {
|
'/api/auth/request-password-reset': {
|
||||||
post: {
|
post: {
|
||||||
tags: ['Auth'],
|
tags: ['Auth'],
|
||||||
summary: 'Request password reset',
|
summary: 'Request password reset (Better Auth)',
|
||||||
description: 'Send a password reset link to email. Link expires in 30 minutes.',
|
description: 'Emails a reset link. Token expires in 30 minutes.',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
content: {
|
content: {
|
||||||
@@ -253,31 +255,30 @@ const openApiSpec = {
|
|||||||
required: ['email'],
|
required: ['email'],
|
||||||
properties: {
|
properties: {
|
||||||
email: { type: 'string', format: 'email' },
|
email: { type: 'string', format: 'email' },
|
||||||
|
redirectTo: { type: 'string' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
responses: {
|
responses: { 200: { description: 'Reset link sent (if account exists)' } },
|
||||||
200: { description: 'Reset link sent (if account exists)' },
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
'/api/auth/reset-password': {
|
||||||
'/api/auth/password-reset/confirm': {
|
|
||||||
post: {
|
post: {
|
||||||
tags: ['Auth'],
|
tags: ['Auth'],
|
||||||
summary: 'Confirm password reset',
|
summary: 'Reset password with token (Better Auth)',
|
||||||
description: 'Reset password using the token from email.',
|
description: 'Sets a new password and revokes all existing sessions.',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: {
|
schema: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
required: ['token', 'password'],
|
required: ['newPassword', 'token'],
|
||||||
properties: {
|
properties: {
|
||||||
|
newPassword: { type: 'string', minLength: 10 },
|
||||||
token: { type: 'string' },
|
token: { type: 'string' },
|
||||||
password: { type: 'string', minLength: 10 },
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -289,62 +290,10 @@ const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'/api/auth/claim-account/request': {
|
|
||||||
post: {
|
|
||||||
tags: ['Auth'],
|
|
||||||
summary: 'Request account claim link',
|
|
||||||
description: 'For unclaimed accounts created during booking. Link expires in 24 hours.',
|
|
||||||
requestBody: {
|
|
||||||
required: true,
|
|
||||||
content: {
|
|
||||||
'application/json': {
|
|
||||||
schema: {
|
|
||||||
type: 'object',
|
|
||||||
required: ['email'],
|
|
||||||
properties: {
|
|
||||||
email: { type: 'string', format: 'email' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
responses: {
|
|
||||||
200: { description: 'Claim link sent (if unclaimed account exists)' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
'/api/auth/claim-account/confirm': {
|
|
||||||
post: {
|
|
||||||
tags: ['Auth'],
|
|
||||||
summary: 'Confirm account claim',
|
|
||||||
description: 'Claim an unclaimed account by setting password or linking Google.',
|
|
||||||
requestBody: {
|
|
||||||
required: true,
|
|
||||||
content: {
|
|
||||||
'application/json': {
|
|
||||||
schema: {
|
|
||||||
type: 'object',
|
|
||||||
required: ['token'],
|
|
||||||
properties: {
|
|
||||||
token: { type: 'string' },
|
|
||||||
password: { type: 'string', minLength: 10, description: 'Required if not linking Google' },
|
|
||||||
googleId: { type: 'string', description: 'Google ID for OAuth linking' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
responses: {
|
|
||||||
200: { description: 'Account claimed successfully' },
|
|
||||||
400: { description: 'Invalid token or missing credentials' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
'/api/auth/change-password': {
|
'/api/auth/change-password': {
|
||||||
post: {
|
post: {
|
||||||
tags: ['Auth'],
|
tags: ['Auth'],
|
||||||
summary: 'Change password',
|
summary: 'Change password (Better Auth)',
|
||||||
description: 'Change password for authenticated user.',
|
|
||||||
security: [{ bearerAuth: [] }],
|
security: [{ bearerAuth: [] }],
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
@@ -356,6 +305,7 @@ const openApiSpec = {
|
|||||||
properties: {
|
properties: {
|
||||||
currentPassword: { type: 'string' },
|
currentPassword: { type: 'string' },
|
||||||
newPassword: { type: 'string', minLength: 10 },
|
newPassword: { type: 'string', minLength: 10 },
|
||||||
|
revokeOtherSessions: { type: 'boolean' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -368,27 +318,67 @@ const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'/api/auth/me': {
|
'/api/auth/get-session': {
|
||||||
get: {
|
get: {
|
||||||
tags: ['Auth'],
|
tags: ['Auth'],
|
||||||
summary: 'Get current user',
|
summary: 'Get current session and user (Better Auth)',
|
||||||
description: 'Get the currently authenticated user profile.',
|
|
||||||
security: [{ bearerAuth: [] }],
|
security: [{ bearerAuth: [] }],
|
||||||
responses: {
|
responses: {
|
||||||
200: { description: 'Current user data' },
|
200: { description: '{ session, user } or null when not authenticated' },
|
||||||
401: { description: 'Unauthorized' },
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'/api/auth/logout': {
|
'/api/auth/sign-out': {
|
||||||
post: {
|
post: {
|
||||||
tags: ['Auth'],
|
tags: ['Auth'],
|
||||||
summary: 'Logout',
|
summary: 'Logout (Better Auth)',
|
||||||
description: 'Logout current user (client-side token removal).',
|
description: 'Revokes the current session and clears the session cookie.',
|
||||||
responses: {
|
security: [{ bearerAuth: [] }],
|
||||||
200: { description: 'Logged out' },
|
responses: { 200: { description: 'Logged out' } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
'/api/auth/list-sessions': {
|
||||||
|
get: {
|
||||||
|
tags: ['Auth'],
|
||||||
|
summary: 'List active sessions (Better Auth)',
|
||||||
|
security: [{ bearerAuth: [] }],
|
||||||
|
responses: { 200: { description: 'Active sessions for the current user' } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'/api/auth-ext/claim-account': {
|
||||||
|
post: {
|
||||||
|
tags: ['Auth'],
|
||||||
|
summary: 'Claim a guest-created account',
|
||||||
|
description: 'Completes the progressive-account claim: requires a session established via the claim magic link, sets the password, and activates the account.',
|
||||||
|
security: [{ bearerAuth: [] }],
|
||||||
|
requestBody: {
|
||||||
|
required: true,
|
||||||
|
content: {
|
||||||
|
'application/json': {
|
||||||
|
schema: {
|
||||||
|
type: 'object',
|
||||||
|
required: ['password'],
|
||||||
|
properties: { password: { type: 'string', minLength: 10 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
responses: {
|
||||||
|
200: { description: 'Account claimed successfully' },
|
||||||
|
400: { description: 'Already claimed or validation error' },
|
||||||
|
401: { description: 'No session (claim link required)' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'/api/auth-ext/claim-eligibility': {
|
||||||
|
get: {
|
||||||
|
tags: ['Auth'],
|
||||||
|
summary: 'Check whether an email has an unclaimed account',
|
||||||
|
parameters: [
|
||||||
|
{ name: 'email', in: 'query', required: true, schema: { type: 'string', format: 'email' } },
|
||||||
|
],
|
||||||
|
responses: { 200: { description: '{ canClaim: boolean }' } },
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
// ==================== User Dashboard Endpoints ====================
|
// ==================== User Dashboard Endpoints ====================
|
||||||
@@ -780,6 +770,119 @@ const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
// ==================== Door Check-in Screen ====================
|
||||||
|
'/api/events/{eventId}/door-attendees': {
|
||||||
|
get: {
|
||||||
|
tags: ['Tickets'],
|
||||||
|
summary: 'Full attendee list for the door check-in screen',
|
||||||
|
description: 'One payload the door screen searches entirely client-side. Includes cancelled tickets so staff can see and reactivate them.',
|
||||||
|
security: [{ bearerAuth: [] }],
|
||||||
|
parameters: [
|
||||||
|
{ name: 'eventId', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
|
],
|
||||||
|
responses: {
|
||||||
|
200: { description: 'Event, attendees and check-in stats' },
|
||||||
|
404: { description: 'Event not found' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'/api/events/{eventId}/door-checkin': {
|
||||||
|
post: {
|
||||||
|
tags: ['Tickets'],
|
||||||
|
summary: 'Check in, settle payment, or create a walk-in (atomic)',
|
||||||
|
description: 'Pass ticketId to check in an existing attendee, or attendee to create a walk-in born confirmed, paid and checked in. The server prices the charge from the event: walk-ins pay the walk-in price (or the ticket price when none is set) x quantity, existing tickets the ticket price x quantity. Idempotent on idempotencyKey: replays return the original response instead of writing again.',
|
||||||
|
security: [{ bearerAuth: [] }],
|
||||||
|
parameters: [
|
||||||
|
{ name: 'eventId', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
|
],
|
||||||
|
requestBody: {
|
||||||
|
required: true,
|
||||||
|
content: {
|
||||||
|
'application/json': {
|
||||||
|
schema: {
|
||||||
|
type: 'object',
|
||||||
|
required: ['idempotencyKey'],
|
||||||
|
properties: {
|
||||||
|
ticketId: { type: 'string' },
|
||||||
|
attendee: {
|
||||||
|
type: 'object',
|
||||||
|
required: ['firstName'],
|
||||||
|
properties: {
|
||||||
|
firstName: { type: 'string' },
|
||||||
|
lastName: { type: 'string' },
|
||||||
|
phone: { type: 'string' },
|
||||||
|
email: { type: 'string', format: 'email' },
|
||||||
|
ruc: { type: 'string' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
payment: {
|
||||||
|
type: 'object',
|
||||||
|
required: ['method'],
|
||||||
|
properties: {
|
||||||
|
method: { type: 'string', enum: ['cash', 'bitcoin', 'transfer', 'pos', 'guest'] },
|
||||||
|
quantity: { type: 'integer', minimum: 1, maximum: 50, description: 'Tickets paid for in one go (defaults to 1). The server multiplies it by the resolved unit price.' },
|
||||||
|
amount: { type: 'number', description: 'Ignored unless amountOverride is true.' },
|
||||||
|
amountOverride: { type: 'boolean', description: 'Charge `amount` instead of the computed price. Admin/organizer only; written to audit_logs.' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
entryMethod: { type: 'string', enum: ['scan', 'search', 'walkin'] },
|
||||||
|
idempotencyKey: { type: 'string' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
responses: {
|
||||||
|
201: { description: 'Attendee checked in; warnings may contain at_capacity' },
|
||||||
|
200: { description: 'Replay of an already-processed idempotencyKey' },
|
||||||
|
400: { description: 'Ticket belongs to a different event, or the payment method is not enabled for this event' },
|
||||||
|
403: { description: 'amountOverride sent by a role that may not override the door amount' },
|
||||||
|
404: { description: 'Event or ticket not found' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'/api/events/{eventId}/door-checkin/undo': {
|
||||||
|
post: {
|
||||||
|
tags: ['Tickets'],
|
||||||
|
summary: 'Reverse one door check-in action',
|
||||||
|
description: 'Reverts exactly what the keyed action did: restores the previous check-in and payment state, or cancels a ticket that was created at the door.',
|
||||||
|
security: [{ bearerAuth: [] }],
|
||||||
|
parameters: [
|
||||||
|
{ name: 'eventId', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
|
],
|
||||||
|
requestBody: {
|
||||||
|
required: true,
|
||||||
|
content: {
|
||||||
|
'application/json': {
|
||||||
|
schema: {
|
||||||
|
type: 'object',
|
||||||
|
required: ['idempotencyKey'],
|
||||||
|
properties: { idempotencyKey: { type: 'string' } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
responses: {
|
||||||
|
200: { description: 'Action reversed (or already undone)' },
|
||||||
|
404: { description: 'No action recorded for this key' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'/api/events/{eventId}/door-summary': {
|
||||||
|
get: {
|
||||||
|
tags: ['Payments'],
|
||||||
|
summary: 'Door cash-up and pre-sale/door revenue split',
|
||||||
|
description: 'Totals per door tender (cash, bitcoin, transfer, guest) for end-of-night reconciliation, plus the pre-sale versus door revenue split shown on the event dashboard.',
|
||||||
|
security: [{ bearerAuth: [] }],
|
||||||
|
parameters: [
|
||||||
|
{ name: 'eventId', in: 'path', required: true, schema: { type: 'string' } },
|
||||||
|
],
|
||||||
|
responses: {
|
||||||
|
200: { description: 'Door totals by method, door lines, and pre-sale totals' },
|
||||||
|
404: { description: 'Event not found' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
'/api/tickets/{id}/checkin': {
|
'/api/tickets/{id}/checkin': {
|
||||||
post: {
|
post: {
|
||||||
tags: ['Tickets'],
|
tags: ['Tickets'],
|
||||||
@@ -1761,10 +1864,10 @@ const openApiSpec = {
|
|||||||
components: {
|
components: {
|
||||||
securitySchemes: {
|
securitySchemes: {
|
||||||
bearerAuth: {
|
bearerAuth: {
|
||||||
type: 'http',
|
type: 'apiKey',
|
||||||
scheme: 'bearer',
|
in: 'cookie',
|
||||||
bearerFormat: 'JWT',
|
name: 'spanglish.session_token',
|
||||||
description: 'JWT token obtained from login endpoint',
|
description: 'Better Auth httpOnly session cookie (set by sign-in; __Secure- prefixed in production)',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
schemas: {
|
schemas: {
|
||||||
@@ -1898,7 +2001,34 @@ app.get('/health', (c) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// API Routes
|
// API Routes
|
||||||
app.route('/api/auth', authRoutes);
|
// Better Auth handles all /api/auth/* endpoints (sign-in/up/out, magic link,
|
||||||
|
// password reset, Google, session management). CORS above runs first.
|
||||||
|
//
|
||||||
|
// Better Auth only sees the Request (no TCP peer address), so its per-IP rate
|
||||||
|
// limiting is fed the socket-anchored client IP resolved by getClientIp via a
|
||||||
|
// private header. The inbound value is always discarded — a client cannot
|
||||||
|
// choose its own rate-limit bucket.
|
||||||
|
app.on(['POST', 'GET'], '/api/auth/*', (c) => {
|
||||||
|
const headers = new Headers(c.req.raw.headers);
|
||||||
|
headers.delete('x-client-ip');
|
||||||
|
const clientIp = getClientIp(c);
|
||||||
|
if (clientIp && clientIp !== 'unknown') {
|
||||||
|
headers.set('x-client-ip', clientIp);
|
||||||
|
}
|
||||||
|
return auth.handler(
|
||||||
|
new Request(c.req.raw, {
|
||||||
|
headers,
|
||||||
|
// Node's fetch requires duplex for requests carrying a body stream
|
||||||
|
...(c.req.raw.body ? { duplex: 'half' as const } : {}),
|
||||||
|
} as RequestInit)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
app.route('/api/auth-ext', authExtRoutes);
|
||||||
|
// Door check-in screen endpoints live under /api/events/:eventId/door-*.
|
||||||
|
// Mounted first so the generic /:id routes below can never shadow them.
|
||||||
|
app.route('/api/events', doorRoutes);
|
||||||
|
// Per-event finance, partners and team access (/api/events/:id/finance, /expenses, /members, ...)
|
||||||
|
app.route('/api/events', eventFinanceRoutes);
|
||||||
app.route('/api/events', eventsRoutes);
|
app.route('/api/events', eventsRoutes);
|
||||||
app.route('/api/tickets', ticketsRoutes);
|
app.route('/api/tickets', ticketsRoutes);
|
||||||
app.route('/api/users', usersRoutes);
|
app.route('/api/users', usersRoutes);
|
||||||
@@ -1914,6 +2044,7 @@ app.route('/api/site-settings', siteSettingsRoutes);
|
|||||||
app.route('/api/legal-pages', legalPagesRoutes);
|
app.route('/api/legal-pages', legalPagesRoutes);
|
||||||
app.route('/api/legal-settings', legalSettingsRoutes);
|
app.route('/api/legal-settings', legalSettingsRoutes);
|
||||||
app.route('/api/faq', faqRoutes);
|
app.route('/api/faq', faqRoutes);
|
||||||
|
app.route('/api/finance', financeRoutes);
|
||||||
|
|
||||||
// 404 handler
|
// 404 handler
|
||||||
app.notFound((c) => {
|
app.notFound((c) => {
|
||||||
@@ -1943,8 +2074,11 @@ startEventEndSweep();
|
|||||||
// Initialize email templates on startup.
|
// Initialize email templates on startup.
|
||||||
// Guarded by a distributed lock so that, when running multiple replicas, only
|
// Guarded by a distributed lock so that, when running multiple replicas, only
|
||||||
// one instance seeds/updates templates per boot instead of all of them racing.
|
// one instance seeds/updates templates per boot instead of all of them racing.
|
||||||
|
// onUnavailable 'run': at boot the Redis connection may not be ready yet, and
|
||||||
|
// seeding is upsert-idempotent, so racing replicas are safe — never skipping
|
||||||
|
// beats never seeding on a first boot during a Redis blip.
|
||||||
getLock()
|
getLock()
|
||||||
.withLock('seed-templates', 30_000, () => emailService.seedDefaultTemplates())
|
.withLock('seed-templates', 30_000, () => emailService.seedDefaultTemplates(), { onUnavailable: 'run' })
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
if (result === null) {
|
if (result === null) {
|
||||||
console.log('[Email] Template seeding skipped (another instance holds the lock)');
|
console.log('[Email] Template seeding skipped (another instance holds the lock)');
|
||||||
@@ -1961,7 +2095,43 @@ console.log(`📋 OpenAPI spec at http://localhost:${port}/openapi.json`);
|
|||||||
// Log which backend (memory/redis, local/s3) each subsystem selected.
|
// Log which backend (memory/redis, local/s3) each subsystem selected.
|
||||||
logSelectedBackends();
|
logSelectedBackends();
|
||||||
|
|
||||||
serve({
|
const server = serve({
|
||||||
fetch: app.fetch,
|
fetch: app.fetch,
|
||||||
port,
|
port,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Graceful shutdown: stop the periodic jobs, stop accepting connections, then
|
||||||
|
// close Redis and exit. Open SSE payment streams hold sockets forever, so
|
||||||
|
// server.close() alone never completes — force-close remaining connections
|
||||||
|
// after a short grace period, with a hard exit as the final backstop.
|
||||||
|
let shuttingDown = false;
|
||||||
|
function shutdown(signal: string): void {
|
||||||
|
if (shuttingDown) return;
|
||||||
|
shuttingDown = true;
|
||||||
|
console.log(`[shutdown] ${signal} received, draining...`);
|
||||||
|
|
||||||
|
stopBookingCleanup();
|
||||||
|
stopHoldSweep();
|
||||||
|
stopEventEndSweep();
|
||||||
|
stopQueue();
|
||||||
|
|
||||||
|
server.close(() => {
|
||||||
|
console.log('[shutdown] server closed, closing redis');
|
||||||
|
closeRedis().finally(() => process.exit(0));
|
||||||
|
});
|
||||||
|
|
||||||
|
const forceClose = setTimeout(() => {
|
||||||
|
console.warn('[shutdown] force-closing remaining connections (SSE streams)');
|
||||||
|
(server as any).closeAllConnections?.();
|
||||||
|
}, 5_000);
|
||||||
|
forceClose.unref();
|
||||||
|
|
||||||
|
const forceExit = setTimeout(() => {
|
||||||
|
console.warn('[shutdown] drain timed out, forcing exit');
|
||||||
|
process.exit(1);
|
||||||
|
}, 10_000);
|
||||||
|
forceExit.unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||||
|
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||||
|
|||||||
+82
-321
@@ -1,332 +1,76 @@
|
|||||||
import * as jose from 'jose';
|
|
||||||
import * as argon2 from 'argon2';
|
|
||||||
import bcrypt from 'bcryptjs';
|
|
||||||
import crypto from 'crypto';
|
|
||||||
import { Context } from 'hono';
|
import { Context } from 'hono';
|
||||||
import { db, dbGet, dbAll, users, magicLinkTokens, userSessions } from '../db/index.js';
|
import { and, eq } from 'drizzle-orm';
|
||||||
import { eq, and, gt, sql, isNull } from 'drizzle-orm';
|
import { auth } from './betterAuth.js';
|
||||||
import { generateId, getNow, toDbDate } from './utils.js';
|
import { db, dbGet } from '../db/index.js';
|
||||||
|
import { authAccounts } from '../db/auth-schema.js';
|
||||||
|
|
||||||
const DEFAULT_DEV_JWT_SECRET = 'your-super-secret-key-change-in-production';
|
// Auth is provided by Better Auth (lib/betterAuth.ts): httpOnly cookie
|
||||||
const rawJwtSecret = process.env.JWT_SECRET;
|
// sessions validated against the auth_sessions table on every request, so
|
||||||
|
// revocation (ban/suspend/password reset) applies instantly. This module keeps
|
||||||
|
// the request-side helpers that the route files use.
|
||||||
|
|
||||||
// Never allow the insecure default in production: forgeable tokens = full account takeover.
|
// Re-exported for routes that hash/validate passwords outside Better Auth
|
||||||
if (process.env.NODE_ENV === 'production' && (!rawJwtSecret || rawJwtSecret === DEFAULT_DEV_JWT_SECRET)) {
|
export { hashPassword, verifyPassword, validatePassword } from './passwordPolicy.js';
|
||||||
throw new Error('JWT_SECRET must be set to a strong, unique value in production. Refusing to start with the default secret.');
|
|
||||||
}
|
|
||||||
if (!rawJwtSecret) {
|
|
||||||
console.warn('[auth] JWT_SECRET is not set; using an insecure development default. Set JWT_SECRET in production.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const JWT_SECRET = new TextEncoder().encode(rawJwtSecret || DEFAULT_DEV_JWT_SECRET);
|
export interface AuthUser {
|
||||||
const JWT_ISSUER = 'spanglish';
|
id: string;
|
||||||
const JWT_AUDIENCE = 'spanglish-app';
|
|
||||||
|
|
||||||
export interface JWTPayload {
|
|
||||||
sub: string;
|
|
||||||
email: string;
|
email: string;
|
||||||
|
name: string;
|
||||||
|
phone: string | null;
|
||||||
role: string;
|
role: string;
|
||||||
tokenVersion?: number;
|
languagePreference: string | null;
|
||||||
iat: number;
|
isClaimed: boolean;
|
||||||
exp: number;
|
rucNumber: string | null;
|
||||||
|
accountStatus: string;
|
||||||
|
emailVerified: boolean;
|
||||||
|
image: string | null;
|
||||||
|
createdAt: Date | string;
|
||||||
|
updatedAt: Date | string;
|
||||||
|
/** ID of the Better Auth session backing this request. */
|
||||||
|
sessionId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Password hashing with Argon2 (spec requirement)
|
/**
|
||||||
export async function hashPassword(password: string): Promise<string> {
|
* Resolve the authenticated user for a request from its Better Auth session
|
||||||
return argon2.hash(password, {
|
* cookie, or null when there is no valid session. Suspended/unclaimed/banned
|
||||||
type: argon2.argon2id,
|
* accounts never get API access even with a live session cookie.
|
||||||
memoryCost: 65536, // 64 MB
|
*/
|
||||||
timeCost: 3,
|
export async function getAuthUser(c: Context): Promise<AuthUser | null> {
|
||||||
parallelism: 4,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function verifyPassword(password: string, hash: string): Promise<boolean> {
|
|
||||||
// Support both bcrypt (legacy) and argon2 hashes for migration
|
|
||||||
if (hash.startsWith('$argon2')) {
|
|
||||||
return argon2.verify(hash, password);
|
|
||||||
}
|
|
||||||
// Legacy bcrypt support
|
|
||||||
return bcrypt.compare(password, hash);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate secure random token for magic links
|
|
||||||
export function generateSecureToken(): string {
|
|
||||||
return crypto.randomBytes(32).toString('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create magic link token
|
|
||||||
export async function createMagicLinkToken(
|
|
||||||
userId: string,
|
|
||||||
type: 'login' | 'reset_password' | 'claim_account' | 'email_verification',
|
|
||||||
expiresInMinutes: number = 10
|
|
||||||
): Promise<string> {
|
|
||||||
const token = generateSecureToken();
|
|
||||||
const now = getNow();
|
|
||||||
const expiresAt = toDbDate(new Date(Date.now() + expiresInMinutes * 60 * 1000));
|
|
||||||
|
|
||||||
await (db as any).insert(magicLinkTokens).values({
|
|
||||||
id: generateId(),
|
|
||||||
userId,
|
|
||||||
token,
|
|
||||||
type,
|
|
||||||
expiresAt,
|
|
||||||
createdAt: now,
|
|
||||||
});
|
|
||||||
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify and consume magic link token
|
|
||||||
export async function verifyMagicLinkToken(
|
|
||||||
token: string,
|
|
||||||
type: 'login' | 'reset_password' | 'claim_account' | 'email_verification'
|
|
||||||
): Promise<{ valid: boolean; userId?: string; error?: string }> {
|
|
||||||
const now = getNow();
|
|
||||||
|
|
||||||
const tokenRecord = await dbGet<any>(
|
|
||||||
(db as any)
|
|
||||||
.select()
|
|
||||||
.from(magicLinkTokens)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq((magicLinkTokens as any).token, token),
|
|
||||||
eq((magicLinkTokens as any).type, type)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
// Use a single generic error for all invalid states to avoid leaking token state
|
|
||||||
const genericError = 'Invalid or expired token';
|
|
||||||
|
|
||||||
if (!tokenRecord) {
|
|
||||||
return { valid: false, error: genericError };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tokenRecord.usedAt) {
|
|
||||||
return { valid: false, error: genericError };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (new Date(tokenRecord.expiresAt) < new Date()) {
|
|
||||||
return { valid: false, error: genericError };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Atomically consume the token: only the request that flips used_at from NULL wins.
|
|
||||||
// This prevents a double-spend race where two concurrent requests both pass the
|
|
||||||
// read-time "not used" check above.
|
|
||||||
const result: any = await (db as any)
|
|
||||||
.update(magicLinkTokens)
|
|
||||||
.set({ usedAt: now })
|
|
||||||
.where(and(
|
|
||||||
eq((magicLinkTokens as any).id, tokenRecord.id),
|
|
||||||
isNull((magicLinkTokens as any).usedAt)
|
|
||||||
));
|
|
||||||
|
|
||||||
const affected = result?.changes ?? result?.rowCount ?? 0;
|
|
||||||
if (affected === 0) {
|
|
||||||
return { valid: false, error: genericError };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { valid: true, userId: tokenRecord.userId };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create user session
|
|
||||||
export async function createUserSession(
|
|
||||||
userId: string,
|
|
||||||
userAgent?: string,
|
|
||||||
ipAddress?: string
|
|
||||||
): Promise<string> {
|
|
||||||
const sessionToken = generateSecureToken();
|
|
||||||
const now = getNow();
|
|
||||||
const expiresAt = toDbDate(new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)); // 30 days
|
|
||||||
|
|
||||||
await (db as any).insert(userSessions).values({
|
|
||||||
id: generateId(),
|
|
||||||
userId,
|
|
||||||
token: sessionToken,
|
|
||||||
userAgent: userAgent || null,
|
|
||||||
ipAddress: ipAddress || null,
|
|
||||||
lastActiveAt: now,
|
|
||||||
expiresAt,
|
|
||||||
createdAt: now,
|
|
||||||
});
|
|
||||||
|
|
||||||
return sessionToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get user's active sessions
|
|
||||||
export async function getUserSessions(userId: string) {
|
|
||||||
const now = getNow();
|
|
||||||
|
|
||||||
return dbAll(
|
|
||||||
(db as any)
|
|
||||||
.select()
|
|
||||||
.from(userSessions)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq((userSessions as any).userId, userId),
|
|
||||||
gt((userSessions as any).expiresAt, now)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Invalidate a specific session
|
|
||||||
export async function invalidateSession(sessionId: string, userId: string): Promise<boolean> {
|
|
||||||
const result = await (db as any)
|
|
||||||
.delete(userSessions)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq((userSessions as any).id, sessionId),
|
|
||||||
eq((userSessions as any).userId, userId)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Invalidate all user sessions (logout everywhere)
|
|
||||||
export async function invalidateAllUserSessions(userId: string): Promise<void> {
|
|
||||||
await (db as any)
|
|
||||||
.delete(userSessions)
|
|
||||||
.where(eq((userSessions as any).userId, userId));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Small blocklist of common/weak passwords (and obvious app-specific ones).
|
|
||||||
// Compared case-insensitively after stripping non-alphanumerics so that e.g.
|
|
||||||
// "P@ssw0rd!" still matches "password".
|
|
||||||
const COMMON_PASSWORDS = new Set([
|
|
||||||
'password', 'passw0rd', '123456', '1234567', '12345678', '123456789', '1234567890',
|
|
||||||
'qwerty', 'qwertyuiop', 'letmein', 'welcome', 'admin', 'administrator', 'iloveyou',
|
|
||||||
'monkey', 'dragon', 'sunshine', 'princess', 'football', 'baseball', 'abc123',
|
|
||||||
'spanglish', 'changeme', 'secret', 'master', 'login', 'access',
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Password policy: 10-128 chars, requires a mix of character types, and rejects
|
|
||||||
// common/weak passwords. Centralized so register/reset/change all share it.
|
|
||||||
export function validatePassword(password: string): { valid: boolean; error?: string } {
|
|
||||||
if (password.length < 10) {
|
|
||||||
return { valid: false, error: 'Password must be at least 10 characters long' };
|
|
||||||
}
|
|
||||||
if (password.length > 128) {
|
|
||||||
return { valid: false, error: 'Password must be at most 128 characters long' };
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasLower = /[a-z]/.test(password);
|
|
||||||
const hasUpper = /[A-Z]/.test(password);
|
|
||||||
const hasDigit = /\d/.test(password);
|
|
||||||
const hasSymbol = /[^A-Za-z0-9]/.test(password);
|
|
||||||
|
|
||||||
// Require lowercase, uppercase, and at least one digit or symbol.
|
|
||||||
if (!hasLower || !hasUpper || !(hasDigit || hasSymbol)) {
|
|
||||||
return {
|
|
||||||
valid: false,
|
|
||||||
error: 'Password must include uppercase and lowercase letters and at least one number or symbol',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const normalized = password.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
||||||
if (COMMON_PASSWORDS.has(normalized)) {
|
|
||||||
return { valid: false, error: 'Password is too common. Please choose a less guessable password.' };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { valid: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createToken(userId: string, email: string, role: string, tokenVersion: number = 0): Promise<string> {
|
|
||||||
const token = await new jose.SignJWT({ sub: userId, email, role, tokenVersion })
|
|
||||||
.setProtectedHeader({ alg: 'HS256' })
|
|
||||||
.setIssuedAt()
|
|
||||||
.setIssuer(JWT_ISSUER)
|
|
||||||
.setAudience(JWT_AUDIENCE)
|
|
||||||
.setExpirationTime('1d')
|
|
||||||
.sign(JWT_SECRET);
|
|
||||||
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Invalidate all previously issued JWTs for a user (logout-everywhere, password change/reset).
|
|
||||||
export async function bumpTokenVersion(userId: string): Promise<void> {
|
|
||||||
await (db as any)
|
|
||||||
.update(users)
|
|
||||||
.set({ tokenVersion: sql`${(users as any).tokenVersion} + 1` })
|
|
||||||
.where(eq((users as any).id, userId));
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createRefreshToken(userId: string): Promise<string> {
|
|
||||||
const token = await new jose.SignJWT({ sub: userId, type: 'refresh' })
|
|
||||||
.setProtectedHeader({ alg: 'HS256' })
|
|
||||||
.setIssuedAt()
|
|
||||||
.setIssuer(JWT_ISSUER)
|
|
||||||
.setExpirationTime('30d')
|
|
||||||
.sign(JWT_SECRET);
|
|
||||||
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function verifyToken(token: string): Promise<JWTPayload | null> {
|
|
||||||
try {
|
try {
|
||||||
const { payload } = await jose.jwtVerify(token, JWT_SECRET, {
|
const session = await auth.api.getSession({ headers: c.req.raw.headers });
|
||||||
issuer: JWT_ISSUER,
|
if (!session?.user) {
|
||||||
audience: JWT_AUDIENCE,
|
|
||||||
});
|
|
||||||
return payload as unknown as JWTPayload;
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAuthUser(c: Context): Promise<any | null> {
|
|
||||||
const authHeader = c.req.header('Authorization');
|
|
||||||
if (!authHeader?.startsWith('Bearer ')) {
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = authHeader.slice(7);
|
const user = session.user as any;
|
||||||
const payload = await verifyToken(token);
|
|
||||||
|
|
||||||
if (!payload) {
|
// Suspended (banned) or unclaimed accounts must not retain API access
|
||||||
|
if (user.banned) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Never load the password hash into request context — it is only needed for
|
|
||||||
// explicit password-verification routes that query it separately.
|
|
||||||
const user = await dbGet<any>(
|
|
||||||
(db as any)
|
|
||||||
.select({
|
|
||||||
id: (users as any).id,
|
|
||||||
email: (users as any).email,
|
|
||||||
name: (users as any).name,
|
|
||||||
phone: (users as any).phone,
|
|
||||||
role: (users as any).role,
|
|
||||||
languagePreference: (users as any).languagePreference,
|
|
||||||
isClaimed: (users as any).isClaimed,
|
|
||||||
googleId: (users as any).googleId,
|
|
||||||
rucNumber: (users as any).rucNumber,
|
|
||||||
accountStatus: (users as any).accountStatus,
|
|
||||||
tokenVersion: (users as any).tokenVersion,
|
|
||||||
createdAt: (users as any).createdAt,
|
|
||||||
updatedAt: (users as any).updatedAt,
|
|
||||||
})
|
|
||||||
.from(users)
|
|
||||||
.where(eq((users as any).id, payload.sub))
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reject tokens issued before a logout-everywhere / password change
|
|
||||||
if ((payload.tokenVersion ?? 0) !== (user.tokenVersion ?? 0)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Suspended/unclaimed accounts must not retain API access via an old JWT
|
|
||||||
if (user.accountStatus && user.accountStatus !== 'active') {
|
if (user.accountStatus && user.accountStatus !== 'active') {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return user;
|
return {
|
||||||
|
id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
name: user.name,
|
||||||
|
phone: user.phone ?? null,
|
||||||
|
role: user.role ?? 'user',
|
||||||
|
languagePreference: user.languagePreference ?? null,
|
||||||
|
isClaimed: Boolean(user.isClaimed),
|
||||||
|
rucNumber: user.rucNumber ?? null,
|
||||||
|
accountStatus: user.accountStatus ?? 'active',
|
||||||
|
emailVerified: Boolean(user.emailVerified),
|
||||||
|
image: user.image ?? null,
|
||||||
|
createdAt: user.createdAt,
|
||||||
|
updatedAt: user.updatedAt,
|
||||||
|
sessionId: session.session.id,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function requireAuth(roles?: string[]) {
|
export function requireAuth(roles?: string[]) {
|
||||||
@@ -346,21 +90,38 @@ export function requireAuth(roles?: string[]) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function isFirstUser(): Promise<boolean> {
|
/**
|
||||||
const result = await dbAll(
|
* Fetch only the credential password hash (never exposed via getAuthUser).
|
||||||
(db as any).select().from(users).limit(1)
|
* Returns null when the user has no password set (Google-only or unclaimed).
|
||||||
);
|
*/
|
||||||
return !result || result.length === 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Fetch only the password hash column (never expose via getAuthUser). */
|
|
||||||
export async function getUserPasswordHash(userId: string): Promise<string | null> {
|
export async function getUserPasswordHash(userId: string): Promise<string | null> {
|
||||||
const row = await dbGet<any>(
|
const row = await dbGet<any>(
|
||||||
(db as any)
|
(db as any)
|
||||||
.select({ password: (users as any).password })
|
.select({ password: (authAccounts as any).password })
|
||||||
.from(users)
|
.from(authAccounts)
|
||||||
.where(eq((users as any).id, userId))
|
.where(
|
||||||
|
and(
|
||||||
|
eq((authAccounts as any).userId, userId),
|
||||||
|
eq((authAccounts as any).providerId, 'credential')
|
||||||
|
)
|
||||||
|
)
|
||||||
);
|
);
|
||||||
const hash = row?.password;
|
const hash = row?.password;
|
||||||
return hash && String(hash).length > 0 ? String(hash) : null;
|
return hash && String(hash).length > 0 ? String(hash) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Whether the user has a linked Google account. */
|
||||||
|
export async function hasGoogleAccount(userId: string): Promise<boolean> {
|
||||||
|
const row = await dbGet<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({ id: (authAccounts as any).id })
|
||||||
|
.from(authAccounts)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq((authAccounts as any).userId, userId),
|
||||||
|
eq((authAccounts as any).providerId, 'google')
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return !!row;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
// Reports which backend each scalable subsystem is using, for the health
|
// Reports which backend each scalable subsystem is using, for the health
|
||||||
// endpoint and startup logging.
|
// endpoint and startup logging.
|
||||||
|
|
||||||
import { isRedisEnabled, isRedisHealthy } from './redis.js';
|
import { isRedisEnabled, isRedisHealthy, getRedisHealthDetail } from './redis.js';
|
||||||
import { getRateLimiter } from './stores/rateLimiter.js';
|
import { getRateLimiter } from './stores/rateLimiter.js';
|
||||||
import { getPubSub } from './stores/pubsub.js';
|
import { getPubSub } from './stores/pubsub.js';
|
||||||
import { getCache } from './stores/cache.js';
|
import { getCache } from './stores/cache.js';
|
||||||
import { getLock } from './stores/lock.js';
|
import { getLock } from './stores/lock.js';
|
||||||
|
import { getLoginLockout } from './stores/loginLockout.js';
|
||||||
import { getStorage } from './storage.js';
|
import { getStorage } from './storage.js';
|
||||||
|
|
||||||
export function describeBackends() {
|
export function describeBackends() {
|
||||||
@@ -14,12 +15,13 @@ export function describeBackends() {
|
|||||||
rateLimiter: getRateLimiter().backend,
|
rateLimiter: getRateLimiter().backend,
|
||||||
pubsub: getPubSub().backend,
|
pubsub: getPubSub().backend,
|
||||||
lock: getLock().backend,
|
lock: getLock().backend,
|
||||||
|
loginLockout: getLoginLockout().backend,
|
||||||
storage: getStorage().backend,
|
storage: getStorage().backend,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function describeRedis() {
|
export function describeRedis() {
|
||||||
return { enabled: isRedisEnabled(), healthy: isRedisHealthy() };
|
return { enabled: isRedisEnabled(), healthy: isRedisHealthy(), ...getRedisHealthDetail() };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Log one line per subsystem at startup so the active backend is obvious. */
|
/** Log one line per subsystem at startup so the active backend is obvious. */
|
||||||
@@ -32,5 +34,6 @@ export function logSelectedBackends(): void {
|
|||||||
console.log(` rate limiter: ${b.rateLimiter}`);
|
console.log(` rate limiter: ${b.rateLimiter}`);
|
||||||
console.log(` pub/sub: ${b.pubsub}`);
|
console.log(` pub/sub: ${b.pubsub}`);
|
||||||
console.log(` lock: ${b.lock}`);
|
console.log(` lock: ${b.lock}`);
|
||||||
|
console.log(` login lockout:${b.loginLockout}`);
|
||||||
console.log(` storage: ${b.storage}`);
|
console.log(` storage: ${b.storage}`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,519 @@
|
|||||||
|
import { describe, it, expect, beforeAll, vi } from 'vitest';
|
||||||
|
import { execFileSync } from 'child_process';
|
||||||
|
import { mkdtempSync } from 'fs';
|
||||||
|
import { tmpdir } from 'os';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { exportJWK, generateKeyPair, SignJWT } from 'jose';
|
||||||
|
import { normalizeEmail } from './utils.js';
|
||||||
|
|
||||||
|
// Environment must be pinned BEFORE the db/betterAuth singletons are imported
|
||||||
|
// (dotenv never overrides pre-set values).
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'ba-test-'));
|
||||||
|
const dbPath = join(dir, 'test.db');
|
||||||
|
process.env.DB_TYPE = 'sqlite';
|
||||||
|
process.env.DATABASE_URL = dbPath;
|
||||||
|
process.env.FRONTEND_URL = 'http://localhost:3002';
|
||||||
|
process.env.BETTER_AUTH_SECRET = 'integration-test-secret-0123456789abcdef';
|
||||||
|
delete process.env.REDIS_URL; // memory lockout/rate-limit backends
|
||||||
|
|
||||||
|
// Google IS configured here: account linking is the whole point of the tests at
|
||||||
|
// the bottom of this file, and betterAuth.ts omits `socialProviders` entirely
|
||||||
|
// when this is unset. No real credentials are involved — the id tokens are
|
||||||
|
// signed with a throwaway keypair and Google's JWKS endpoint is stubbed below.
|
||||||
|
const GOOGLE_CLIENT_ID = 'spanglish-test.apps.googleusercontent.com';
|
||||||
|
process.env.GOOGLE_CLIENT_ID = GOOGLE_CLIENT_ID;
|
||||||
|
|
||||||
|
// Capture outgoing auth emails (magic links, password resets)
|
||||||
|
const sentEmails: Array<{ to: string; subject: string; html: string }> = [];
|
||||||
|
vi.mock('./email.js', () => ({
|
||||||
|
sendEmail: vi.fn(async (opts: any) => {
|
||||||
|
sentEmails.push(opts);
|
||||||
|
}),
|
||||||
|
emailService: {},
|
||||||
|
default: {},
|
||||||
|
}));
|
||||||
|
|
||||||
|
let auth: (typeof import('./betterAuth.js'))['auth'];
|
||||||
|
let db: any;
|
||||||
|
let sqlite: any;
|
||||||
|
|
||||||
|
function lastEmailTo(email: string) {
|
||||||
|
const found = [...sentEmails].reverse().find((e) => e.to === email);
|
||||||
|
expect(found, `expected an email sent to ${email}`).toBeTruthy();
|
||||||
|
return found!;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractToken(html: string, param = 'token'): string {
|
||||||
|
const match = html.match(new RegExp(`[?&]${param}=([^"&\\s]+)`));
|
||||||
|
expect(match, `expected a ${param} in the email link`).toBeTruthy();
|
||||||
|
return decodeURIComponent(match![1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Google Identity Services stub -------------------------------------
|
||||||
|
// verifyGoogleIdToken() checks signature, issuer, audience and max age against
|
||||||
|
// Google's published JWKS; its only network call is that JWKS fetch. Signing
|
||||||
|
// with our own key and serving our own JWKS exercises the real verification
|
||||||
|
// path without touching the network or needing OAuth credentials.
|
||||||
|
const GOOGLE_KID = 'spanglish-test-key';
|
||||||
|
let googlePrivateKey: CryptoKey;
|
||||||
|
|
||||||
|
async function installGoogleStub() {
|
||||||
|
const { publicKey, privateKey } = await generateKeyPair('RS256', { extractable: true });
|
||||||
|
googlePrivateKey = privateKey as CryptoKey;
|
||||||
|
const jwk = { ...(await exportJWK(publicKey)), kid: GOOGLE_KID, alg: 'RS256', use: 'sig' };
|
||||||
|
|
||||||
|
const realFetch = globalThis.fetch;
|
||||||
|
globalThis.fetch = (async (input: any, init?: any) => {
|
||||||
|
const url = typeof input === 'string' ? input : (input?.url ?? String(input));
|
||||||
|
if (url.startsWith('https://www.googleapis.com/oauth2/v3/certs')) {
|
||||||
|
return new Response(JSON.stringify({ keys: [jwk] }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return realFetch(input, init);
|
||||||
|
}) as typeof fetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
function googleIdToken(opts: { email: string; sub: string; name?: string; emailVerified?: boolean }) {
|
||||||
|
return new SignJWT({
|
||||||
|
email: opts.email,
|
||||||
|
email_verified: opts.emailVerified ?? true,
|
||||||
|
name: opts.name ?? 'Google User',
|
||||||
|
picture: 'https://example.test/avatar.png',
|
||||||
|
})
|
||||||
|
.setProtectedHeader({ alg: 'RS256', kid: GOOGLE_KID })
|
||||||
|
.setIssuer('https://accounts.google.com')
|
||||||
|
.setAudience(GOOGLE_CLIENT_ID)
|
||||||
|
.setSubject(opts.sub)
|
||||||
|
.setIssuedAt()
|
||||||
|
.setExpirationTime('10m')
|
||||||
|
.sign(googlePrivateKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signInWithGoogle(
|
||||||
|
opts: Parameters<typeof googleIdToken>[0],
|
||||||
|
returnHeaders = false
|
||||||
|
): Promise<any> {
|
||||||
|
const token = await googleIdToken(opts);
|
||||||
|
return auth.api.signInSocial({
|
||||||
|
body: { provider: 'google', idToken: { token } },
|
||||||
|
headers: new Headers(),
|
||||||
|
...(returnHeaders ? { returnHeaders: true } : {}),
|
||||||
|
} as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Insert a user the way a guest booking does (routes/tickets.ts, routes/door.ts):
|
||||||
|
* unclaimed, unverified, and with no auth_accounts row at all. */
|
||||||
|
function insertBookingUser(id: string, email: string, name = 'Ticket Buyer') {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO users (id, email, password, name, role, is_claimed, account_status, email_verified, created_at, updated_at)
|
||||||
|
VALUES (?, ?, NULL, ?, 'user', 0, 'unclaimed', 0, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(id, email, name, now, now);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function userRow(email: string) {
|
||||||
|
return sqlite
|
||||||
|
.prepare('SELECT id, email, is_claimed, account_status, email_verified FROM users WHERE email = ?')
|
||||||
|
.get(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
function googleAccountsFor(userId: string) {
|
||||||
|
return sqlite
|
||||||
|
.prepare("SELECT id, account_id FROM auth_accounts WHERE user_id = ? AND provider_id = 'google'")
|
||||||
|
.all(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cookieHeaders(setCookie: string | null): Headers {
|
||||||
|
const sessionPart = (setCookie || '')
|
||||||
|
.split(/,(?=[^ ;]+=)/)
|
||||||
|
.map((c) => c.split(';')[0].trim())
|
||||||
|
.filter((c) => c.includes('session_token'))
|
||||||
|
.join('; ');
|
||||||
|
return new Headers({ cookie: sessionPart });
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
execFileSync('npx', ['tsx', 'src/db/migrate.ts'], {
|
||||||
|
env: { ...process.env },
|
||||||
|
stdio: 'pipe',
|
||||||
|
});
|
||||||
|
return (async () => {
|
||||||
|
({ auth } = await import('./betterAuth.js'));
|
||||||
|
({ db } = await import('../db/index.js'));
|
||||||
|
const Database = (await import('better-sqlite3')).default;
|
||||||
|
sqlite = new Database(dbPath);
|
||||||
|
await installGoogleStub();
|
||||||
|
})();
|
||||||
|
}, 120_000);
|
||||||
|
|
||||||
|
describe('Better Auth integration', () => {
|
||||||
|
it('makes the first registered user an admin, later users regular', async () => {
|
||||||
|
const first = await auth.api.signUpEmail({
|
||||||
|
body: { email: 'admin@test.py', password: 'FirstAdmin1!x', name: 'Admin' },
|
||||||
|
});
|
||||||
|
expect((first.user as any).id).toBeTruthy();
|
||||||
|
|
||||||
|
const row = sqlite.prepare('SELECT role, is_claimed, account_status FROM users WHERE email = ?').get('admin@test.py');
|
||||||
|
expect(row.role).toBe('admin');
|
||||||
|
expect(row.account_status).toBe('active');
|
||||||
|
|
||||||
|
await auth.api.signUpEmail({
|
||||||
|
body: { email: 'user@test.py', password: 'SecondUser1!x', name: 'User' },
|
||||||
|
});
|
||||||
|
const row2 = sqlite.prepare('SELECT role FROM users WHERE email = ?').get('user@test.py');
|
||||||
|
expect(row2.role).toBe('user');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores credential passwords as argon2id in auth_accounts, not users', async () => {
|
||||||
|
const acct = sqlite
|
||||||
|
.prepare("SELECT a.password FROM auth_accounts a JOIN users u ON u.id = a.user_id WHERE u.email = ? AND a.provider_id = 'credential'")
|
||||||
|
.get('admin@test.py');
|
||||||
|
expect(acct.password.startsWith('$argon2id$')).toBe(true);
|
||||||
|
const user = sqlite.prepare('SELECT password FROM users WHERE email = ?').get('admin@test.py');
|
||||||
|
expect(user.password).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects passwords that violate the policy', async () => {
|
||||||
|
// Too short
|
||||||
|
await expect(
|
||||||
|
auth.api.signUpEmail({ body: { email: 'weak1@test.py', password: 'Short1!', name: 'W' } })
|
||||||
|
).rejects.toThrow(/at least 10 characters/);
|
||||||
|
|
||||||
|
// Long enough but no character mix (app policy hook)
|
||||||
|
await expect(
|
||||||
|
auth.api.signUpEmail({ body: { email: 'weak2@test.py', password: 'alllowercasepw', name: 'W' } })
|
||||||
|
).rejects.toThrow(/uppercase and lowercase/);
|
||||||
|
|
||||||
|
// Common password normalized (policy blocklist)
|
||||||
|
await expect(
|
||||||
|
auth.api.signUpEmail({ body: { email: 'weak3@test.py', password: 'Spanglish!', name: 'W' } })
|
||||||
|
).rejects.toThrow(/too common/);
|
||||||
|
|
||||||
|
expect(sqlite.prepare("SELECT COUNT(*) AS n FROM users WHERE email LIKE 'weak%'").get().n).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('locks an email after 5 failed sign-ins', async () => {
|
||||||
|
await auth.api.signUpEmail({
|
||||||
|
body: { email: 'lockout@test.py', password: 'LockoutPass1!', name: 'L' },
|
||||||
|
});
|
||||||
|
for (let i = 0; i < 5; i++) {
|
||||||
|
await expect(
|
||||||
|
auth.api.signInEmail({ body: { email: 'lockout@test.py', password: 'WrongPass1!x' } })
|
||||||
|
).rejects.toThrow();
|
||||||
|
}
|
||||||
|
// Correct password now also refused: locked
|
||||||
|
await expect(
|
||||||
|
auth.api.signInEmail({ body: { email: 'lockout@test.py', password: 'LockoutPass1!' } })
|
||||||
|
).rejects.toThrow(/Too many login attempts/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses sign-in for banned (suspended) users and kills nothing else', async () => {
|
||||||
|
await auth.api.signUpEmail({
|
||||||
|
body: { email: 'banned@test.py', password: 'BannedPass1!x', name: 'B' },
|
||||||
|
});
|
||||||
|
sqlite.prepare("UPDATE users SET banned = 1, account_status = 'suspended' WHERE email = ?").run('banned@test.py');
|
||||||
|
await expect(
|
||||||
|
auth.api.signInEmail({ body: { email: 'banned@test.py', password: 'BannedPass1!x' } })
|
||||||
|
).rejects.toThrow(/suspended|banned/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('verifies legacy bcrypt hashes and upgrades them to argon2 on sign-in', async () => {
|
||||||
|
const bcrypt = (await import('bcryptjs')).default;
|
||||||
|
const legacyHash = bcrypt.hashSync('LegacyBcrypt1!', 10);
|
||||||
|
const su = await auth.api.signUpEmail({
|
||||||
|
body: { email: 'legacy@test.py', password: 'TempPass123!x', name: 'Legacy' },
|
||||||
|
});
|
||||||
|
sqlite
|
||||||
|
.prepare("UPDATE auth_accounts SET password = ? WHERE user_id = ? AND provider_id = 'credential'")
|
||||||
|
.run(legacyHash, (su.user as any).id);
|
||||||
|
|
||||||
|
const si = await auth.api.signInEmail({
|
||||||
|
body: { email: 'legacy@test.py', password: 'LegacyBcrypt1!' },
|
||||||
|
});
|
||||||
|
expect(si.user.email).toBe('legacy@test.py');
|
||||||
|
|
||||||
|
// Upgrade happens in the after-hook; poll briefly for it
|
||||||
|
let upgraded = '';
|
||||||
|
for (let i = 0; i < 20 && !upgraded.startsWith('$argon2'); i++) {
|
||||||
|
await new Promise((r) => setTimeout(r, 100));
|
||||||
|
upgraded = sqlite
|
||||||
|
.prepare("SELECT password FROM auth_accounts WHERE user_id = ? AND provider_id = 'credential'")
|
||||||
|
.get((su.user as any).id).password;
|
||||||
|
}
|
||||||
|
expect(upgraded.startsWith('$argon2id$')).toBe(true);
|
||||||
|
|
||||||
|
// And the upgraded hash still verifies
|
||||||
|
const again = await auth.api.signInEmail({
|
||||||
|
body: { email: 'legacy@test.py', password: 'LegacyBcrypt1!' },
|
||||||
|
});
|
||||||
|
expect(again.user.email).toBe('legacy@test.py');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('magic link signs in existing users but never creates accounts', async () => {
|
||||||
|
await auth.api.signUpEmail({
|
||||||
|
body: { email: 'magic@test.py', password: 'MagicPass12!x', name: 'M' },
|
||||||
|
});
|
||||||
|
await auth.api.signInMagicLink({
|
||||||
|
body: { email: 'magic@test.py', callbackURL: '/dashboard' },
|
||||||
|
headers: new Headers(),
|
||||||
|
});
|
||||||
|
const email = lastEmailTo('magic@test.py');
|
||||||
|
// Emails link to the frontend page, not the raw API endpoint
|
||||||
|
expect(email.html).toContain('http://localhost:3002/auth/magic-link?token=');
|
||||||
|
const token = extractToken(email.html);
|
||||||
|
|
||||||
|
const verified = await auth.api.magicLinkVerify({
|
||||||
|
query: { token },
|
||||||
|
headers: new Headers(),
|
||||||
|
});
|
||||||
|
expect((verified as any).user?.email ?? (verified as any).session?.userId).toBeTruthy();
|
||||||
|
|
||||||
|
// Unknown email: enumeration-safe success (an email may still go out),
|
||||||
|
// but verification can never create an account (disableSignUp)
|
||||||
|
const ghost = await auth.api.signInMagicLink({
|
||||||
|
body: { email: 'ghost@test.py' },
|
||||||
|
headers: new Headers(),
|
||||||
|
});
|
||||||
|
expect((ghost as any).status).toBe(true);
|
||||||
|
const ghostEmail = sentEmails.filter((e) => e.to === 'ghost@test.py').pop();
|
||||||
|
if (ghostEmail) {
|
||||||
|
const ghostToken = extractToken(ghostEmail.html);
|
||||||
|
await expect(
|
||||||
|
auth.api.magicLinkVerify({ query: { token: ghostToken }, headers: new Headers() })
|
||||||
|
).rejects.toThrow();
|
||||||
|
}
|
||||||
|
expect(sqlite.prepare('SELECT COUNT(*) AS n FROM users WHERE email = ?').get('ghost@test.py').n).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('completes the guest claim path: magic link session + setPassword', async () => {
|
||||||
|
// Simulate tickets.ts guest creation: user row, no credential account
|
||||||
|
const guestId = 'guest-claim-user-000001';
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO users (id, email, password, name, role, is_claimed, account_status, email_verified, banned, token_version, created_at, updated_at)
|
||||||
|
VALUES (?, ?, NULL, 'Guest', 'user', 0, 'unclaimed', 0, 0, 0, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(guestId, 'guest@test.py', now, now);
|
||||||
|
|
||||||
|
await auth.api.signInMagicLink({
|
||||||
|
body: { email: 'guest@test.py', callbackURL: '/auth/claim-account' },
|
||||||
|
headers: new Headers(),
|
||||||
|
});
|
||||||
|
const token = extractToken(lastEmailTo('guest@test.py').html);
|
||||||
|
const verified = await auth.api.magicLinkVerify({
|
||||||
|
query: { token },
|
||||||
|
returnHeaders: true,
|
||||||
|
headers: new Headers(),
|
||||||
|
});
|
||||||
|
const headers = cookieHeaders(verified.headers.get('set-cookie'));
|
||||||
|
|
||||||
|
// The session works even while unclaimed (the claim endpoint depends on this)
|
||||||
|
const session = await auth.api.getSession({ headers });
|
||||||
|
expect((session?.user as any)?.accountStatus).toBe('unclaimed');
|
||||||
|
|
||||||
|
// Set the password (what /api/auth-ext/claim-account does)
|
||||||
|
await auth.api.setPassword({ body: { newPassword: 'ClaimedPass1!x' }, headers });
|
||||||
|
const acct = sqlite
|
||||||
|
.prepare("SELECT password FROM auth_accounts WHERE user_id = ? AND provider_id = 'credential'")
|
||||||
|
.get(guestId);
|
||||||
|
expect(acct.password.startsWith('$argon2id$')).toBe(true);
|
||||||
|
|
||||||
|
// The claim email uses the claim template with the frontend link
|
||||||
|
const claimEmail = lastEmailTo('guest@test.py');
|
||||||
|
expect(claimEmail.subject).toContain('Claim');
|
||||||
|
expect(claimEmail.html).toContain('callbackURL=%2Fauth%2Fclaim-account');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('password reset revokes existing sessions and applies the new password', async () => {
|
||||||
|
const su = await auth.api.signUpEmail({
|
||||||
|
body: { email: 'reset@test.py', password: 'BeforeReset1!x', name: 'R' },
|
||||||
|
});
|
||||||
|
const userId = (su.user as any).id;
|
||||||
|
// A live session from sign-in
|
||||||
|
await auth.api.signInEmail({ body: { email: 'reset@test.py', password: 'BeforeReset1!x' } });
|
||||||
|
expect(
|
||||||
|
sqlite.prepare('SELECT COUNT(*) AS n FROM auth_sessions WHERE user_id = ?').get(userId).n
|
||||||
|
).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
await auth.api.requestPasswordReset({
|
||||||
|
body: { email: 'reset@test.py', redirectTo: '/auth/reset-password' },
|
||||||
|
});
|
||||||
|
const email = lastEmailTo('reset@test.py');
|
||||||
|
// Reset URLs are either .../reset-password/{token}?... or ...?token={token}
|
||||||
|
const html = email.html;
|
||||||
|
const pathMatch = html.match(/reset-password\/([^?"&\s]+)/);
|
||||||
|
const token = pathMatch ? decodeURIComponent(pathMatch[1]) : extractToken(html);
|
||||||
|
|
||||||
|
await auth.api.resetPassword({ body: { newPassword: 'AfterReset1!x', token } });
|
||||||
|
|
||||||
|
// revokeSessionsOnPasswordReset: true
|
||||||
|
expect(
|
||||||
|
sqlite.prepare('SELECT COUNT(*) AS n FROM auth_sessions WHERE user_id = ?').get(userId).n
|
||||||
|
).toBe(0);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
auth.api.signInEmail({ body: { email: 'reset@test.py', password: 'BeforeReset1!x' } })
|
||||||
|
).rejects.toThrow();
|
||||||
|
const after = await auth.api.signInEmail({
|
||||||
|
body: { email: 'reset@test.py', password: 'AfterReset1!x' },
|
||||||
|
});
|
||||||
|
expect(after.user.email).toBe('reset@test.py');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sessions are stored in auth_sessions with 7-day expiry', async () => {
|
||||||
|
const si = await auth.api.signInEmail({
|
||||||
|
body: { email: 'admin@test.py', password: 'FirstAdmin1!x' },
|
||||||
|
});
|
||||||
|
const row = sqlite
|
||||||
|
.prepare('SELECT expires_at FROM auth_sessions WHERE token = ?')
|
||||||
|
.get((si as any).token);
|
||||||
|
expect(row).toBeTruthy();
|
||||||
|
const days = (row.expires_at - Date.now()) / (1000 * 60 * 60 * 24);
|
||||||
|
expect(days).toBeGreaterThan(6.5);
|
||||||
|
expect(days).toBeLessThan(7.5);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
describe('Google sign-in and account linking', () => {
|
||||||
|
it('links Google onto a guest-booking user instead of failing with "account not linked"', async () => {
|
||||||
|
const id = insertBookingUser('booking-user-1', 'buyer@test.py');
|
||||||
|
expect(userRow('buyer@test.py').email_verified).toBe(0);
|
||||||
|
|
||||||
|
const res = await signInWithGoogle({ email: 'buyer@test.py', sub: 'google-sub-buyer' });
|
||||||
|
|
||||||
|
expect(res.user.id).toBe(id);
|
||||||
|
expect(googleAccountsFor(id)).toHaveLength(1);
|
||||||
|
expect(sqlite.prepare('SELECT COUNT(*) AS n FROM users WHERE email = ?').get('buyer@test.py').n).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('claims the booking account so the resulting session is actually accepted', async () => {
|
||||||
|
// getAuthUser() (lib/auth.ts) rejects any session whose user is not
|
||||||
|
// 'active', so linking alone would leave the user looking logged out.
|
||||||
|
const id = insertBookingUser('booking-user-2', 'buyer2@test.py');
|
||||||
|
|
||||||
|
const { headers, response } = await signInWithGoogle(
|
||||||
|
{ email: 'buyer2@test.py', sub: 'google-sub-buyer2' },
|
||||||
|
true
|
||||||
|
);
|
||||||
|
expect(response.user.id).toBe(id);
|
||||||
|
|
||||||
|
const row = userRow('buyer2@test.py');
|
||||||
|
expect(row.account_status).toBe('active');
|
||||||
|
expect(row.is_claimed).toBe(1);
|
||||||
|
expect(row.email_verified).toBe(1);
|
||||||
|
|
||||||
|
const session = await auth.api.getSession({
|
||||||
|
headers: cookieHeaders(headers.get('set-cookie')),
|
||||||
|
});
|
||||||
|
expect(session?.user.id).toBe(id);
|
||||||
|
expect((session?.user as any).accountStatus).toBe('active');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never reactivates a suspended account through a Google link', async () => {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO users (id, email, name, role, is_claimed, account_status, email_verified, banned, created_at, updated_at)
|
||||||
|
VALUES (?, ?, 'Suspended', 'user', 1, 'suspended', 1, 1, ?, ?)`
|
||||||
|
)
|
||||||
|
.run('suspended-google', 'suspended-google@test.py', now, now);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
signInWithGoogle({ email: 'suspended-google@test.py', sub: 'google-sub-suspended' })
|
||||||
|
).rejects.toThrow();
|
||||||
|
expect(userRow('suspended-google@test.py').account_status).toBe('suspended');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('links Google onto an email/password account created after the Better Auth migration', async () => {
|
||||||
|
// Better Auth writes email_verified = 0 on sign-up (requireEmailVerification
|
||||||
|
// is off), which used to be enough to block linking on its own.
|
||||||
|
await auth.api.signUpEmail({
|
||||||
|
body: { email: 'pwuser@test.py', password: 'PwUserPass1!x', name: 'Pw User' },
|
||||||
|
});
|
||||||
|
expect(userRow('pwuser@test.py').email_verified).toBe(0);
|
||||||
|
const id = userRow('pwuser@test.py').id;
|
||||||
|
|
||||||
|
const res = await signInWithGoogle({ email: 'pwuser@test.py', sub: 'google-sub-pwuser' });
|
||||||
|
|
||||||
|
expect(res.user.id).toBe(id);
|
||||||
|
expect(googleAccountsFor(id)).toHaveLength(1);
|
||||||
|
// The credential account survives: they can still sign in with a password.
|
||||||
|
const after = await auth.api.signInEmail({
|
||||||
|
body: { email: 'pwuser@test.py', password: 'PwUserPass1!x' },
|
||||||
|
});
|
||||||
|
expect(after.user.id).toBe(id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates exactly one user for a brand-new Google address and reuses it on the next sign-in', async () => {
|
||||||
|
const first = await signInWithGoogle({ email: 'fresh@test.py', sub: 'google-sub-fresh' });
|
||||||
|
const row = userRow('fresh@test.py');
|
||||||
|
expect(row.id).toBe(first.user.id);
|
||||||
|
expect(row.email_verified).toBe(1);
|
||||||
|
expect(row.account_status).toBe('active');
|
||||||
|
|
||||||
|
const second = await signInWithGoogle({ email: 'fresh@test.py', sub: 'google-sub-fresh' });
|
||||||
|
expect(second.user.id).toBe(first.user.id);
|
||||||
|
expect(sqlite.prepare('SELECT COUNT(*) AS n FROM users WHERE email = ?').get('fresh@test.py').n).toBe(1);
|
||||||
|
expect(googleAccountsFor(first.user.id)).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an id token minted for a different client id', async () => {
|
||||||
|
const token = await new SignJWT({ email: 'forged@test.py', email_verified: true, name: 'F' })
|
||||||
|
.setProtectedHeader({ alg: 'RS256', kid: GOOGLE_KID })
|
||||||
|
.setIssuer('https://accounts.google.com')
|
||||||
|
.setAudience('some-other-app.apps.googleusercontent.com')
|
||||||
|
.setSubject('google-sub-forged')
|
||||||
|
.setIssuedAt()
|
||||||
|
.setExpirationTime('10m')
|
||||||
|
.sign(googlePrivateKey);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
auth.api.signInSocial({
|
||||||
|
body: { provider: 'google', idToken: { token } },
|
||||||
|
headers: new Headers(),
|
||||||
|
} as any)
|
||||||
|
).rejects.toThrow();
|
||||||
|
expect(userRow('forged@test.py')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('users.email normalization', () => {
|
||||||
|
it('normalizes an address to its canonical stored form', () => {
|
||||||
|
expect(normalizeEmail(' John@Example.COM ')).toBe('john@example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lowercases legacy mixed-case rows on migrate, and reports collisions instead of merging', async () => {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const insert = (id: string, email: string, status = 'unclaimed') =>
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO users (id, email, name, role, is_claimed, account_status, email_verified, created_at, updated_at)
|
||||||
|
VALUES (?, ?, 'Legacy', 'user', 0, ?, 0, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(id, email, status, now, now);
|
||||||
|
|
||||||
|
insert('legacy-mixed', 'John@Example.com');
|
||||||
|
// A pair that genuinely collides: the migration must leave both alone.
|
||||||
|
insert('legacy-dup-lower', 'dup@example.com');
|
||||||
|
insert('legacy-dup-mixed', 'Dup@Example.com');
|
||||||
|
|
||||||
|
// The backfill lives in migrate.ts and is idempotent, so just re-run it.
|
||||||
|
execFileSync('npx', ['tsx', 'src/db/migrate.ts'], { env: { ...process.env }, stdio: 'pipe' });
|
||||||
|
|
||||||
|
expect(userRow('john@example.com').id).toBe('legacy-mixed');
|
||||||
|
expect(userRow('John@Example.com')).toBeUndefined();
|
||||||
|
expect(userRow('Dup@Example.com').id).toBe('legacy-dup-mixed');
|
||||||
|
expect(userRow('dup@example.com').id).toBe('legacy-dup-lower');
|
||||||
|
|
||||||
|
// ...and the lowercased row is now reachable by Google sign-in.
|
||||||
|
const res = await signInWithGoogle({ email: 'john@example.com', sub: 'google-sub-legacy' });
|
||||||
|
expect(res.user.id).toBe('legacy-mixed');
|
||||||
|
}, 120_000);
|
||||||
|
});
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
import { betterAuth } from 'better-auth';
|
||||||
|
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
|
||||||
|
import { magicLink, admin } from 'better-auth/plugins';
|
||||||
|
import { APIError, createAuthMiddleware } from 'better-auth/api';
|
||||||
|
import { eq, and } from 'drizzle-orm';
|
||||||
|
import { db, dbGet, dbAll, isPostgres } from '../db/index.js';
|
||||||
|
import {
|
||||||
|
authUsers,
|
||||||
|
authSessions,
|
||||||
|
authAccounts,
|
||||||
|
authVerifications,
|
||||||
|
authRateLimits,
|
||||||
|
} from '../db/auth-schema.js';
|
||||||
|
import { generateId } from './utils.js';
|
||||||
|
import { hashPassword, verifyPassword, validatePassword } from './passwordPolicy.js';
|
||||||
|
import { sendEmail } from './email.js';
|
||||||
|
import { getLoginLockout } from './stores/loginLockout.js';
|
||||||
|
|
||||||
|
const isProduction = process.env.NODE_ENV === 'production';
|
||||||
|
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3002';
|
||||||
|
|
||||||
|
// Cookie domain shared across subdomains (e.g. ".spanglishcommunity.com") so a session
|
||||||
|
// issued by api.* is also sent to the site origin, where the frontend's Next middleware
|
||||||
|
// reads it to gate /admin and /dashboard. Leave unset in dev: localhost is single-host
|
||||||
|
// and needs a host-only cookie.
|
||||||
|
const cookieDomain = process.env.AUTH_COOKIE_DOMAIN?.trim();
|
||||||
|
|
||||||
|
const DEFAULT_DEV_SECRET = 'spanglish-dev-only-better-auth-secret';
|
||||||
|
const rawSecret = process.env.BETTER_AUTH_SECRET;
|
||||||
|
|
||||||
|
// Never allow a weak/default secret in production: the secret signs session
|
||||||
|
// cookies, so a guessable value means forgeable sessions = account takeover.
|
||||||
|
if (isProduction && (!rawSecret || rawSecret.length < 32 || rawSecret === DEFAULT_DEV_SECRET)) {
|
||||||
|
throw new Error(
|
||||||
|
'BETTER_AUTH_SECRET must be set to a strong value (32+ characters) in production. Refusing to start.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!rawSecret) {
|
||||||
|
console.warn('[auth] BETTER_AUTH_SECRET is not set; using an insecure development default.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// The site origin plus its www/non-www alias, mirroring the CORS allowlist in
|
||||||
|
// index.ts. Requests whose Origin is not listed here are rejected by Better
|
||||||
|
// Auth's CSRF origin check.
|
||||||
|
function computeTrustedOrigins(): string[] {
|
||||||
|
const origins = new Set<string>([frontendUrl]);
|
||||||
|
try {
|
||||||
|
const url = new URL(frontendUrl);
|
||||||
|
const alias = url.hostname.startsWith('www.')
|
||||||
|
? url.hostname.slice(4)
|
||||||
|
: `www.${url.hostname}`;
|
||||||
|
origins.add(`${url.protocol}//${alias}${url.port ? `:${url.port}` : ''}`);
|
||||||
|
} catch {
|
||||||
|
/* keep frontendUrl as-is */
|
||||||
|
}
|
||||||
|
if (process.env.API_URL) origins.add(process.env.API_URL);
|
||||||
|
if (!isProduction) {
|
||||||
|
// Dev is frequently reached through a forwarded or proxied port (SSH tunnel, editor
|
||||||
|
// port forwarding), so the browser's Origin is http://localhost:<random> and every
|
||||||
|
// POST would fail the CSRF origin check. Trust any loopback port rather than pinning
|
||||||
|
// FRONTEND_URL to a port that changes between sessions. Wildcard patterns are matched
|
||||||
|
// per better-auth's trusted-origins helper; production stays on the exact allowlist.
|
||||||
|
origins.add('http://localhost:*');
|
||||||
|
origins.add('http://127.0.0.1:*');
|
||||||
|
}
|
||||||
|
return [...origins];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paths whose request body carries a new password that must satisfy the policy
|
||||||
|
// (Better Auth's minPasswordLength alone is weaker than the app's policy).
|
||||||
|
const PASSWORD_SETTING_PATHS = new Set([
|
||||||
|
'/sign-up/email',
|
||||||
|
'/reset-password',
|
||||||
|
'/change-password',
|
||||||
|
'/set-password',
|
||||||
|
]);
|
||||||
|
|
||||||
|
async function getCredentialAccount(userId: string): Promise<any | null> {
|
||||||
|
return dbGet<any>(
|
||||||
|
(db as any)
|
||||||
|
.select()
|
||||||
|
.from(authAccounts)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq((authAccounts as any).userId, userId),
|
||||||
|
eq((authAccounts as any).providerId, 'credential')
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const auth = betterAuth({
|
||||||
|
appName: 'Spanglish',
|
||||||
|
baseURL: process.env.BETTER_AUTH_URL || frontendUrl,
|
||||||
|
basePath: '/api/auth',
|
||||||
|
secret: rawSecret || DEFAULT_DEV_SECRET,
|
||||||
|
trustedOrigins: computeTrustedOrigins(),
|
||||||
|
telemetry: { enabled: false },
|
||||||
|
|
||||||
|
database: drizzleAdapter(db as any, {
|
||||||
|
provider: isPostgres() ? 'pg' : 'sqlite',
|
||||||
|
schema: {
|
||||||
|
user: authUsers,
|
||||||
|
session: authSessions,
|
||||||
|
account: authAccounts,
|
||||||
|
verification: authVerifications,
|
||||||
|
rateLimit: authRateLimits,
|
||||||
|
},
|
||||||
|
// better-sqlite3 cannot run Drizzle's async transactions; operations run
|
||||||
|
// sequentially instead (also the adapter default).
|
||||||
|
transaction: false,
|
||||||
|
}),
|
||||||
|
|
||||||
|
advanced: {
|
||||||
|
cookiePrefix: 'spanglish',
|
||||||
|
useSecureCookies: isProduction,
|
||||||
|
// Only adds a `Domain=` attribute — name, sameSite, secure and path are unchanged,
|
||||||
|
// so the cookie names hardcoded in the frontend middleware and the Go photo-api
|
||||||
|
// stay valid.
|
||||||
|
...(cookieDomain
|
||||||
|
? { crossSubDomainCookies: { enabled: true, domain: cookieDomain } }
|
||||||
|
: {}),
|
||||||
|
ipAddress: {
|
||||||
|
// Set by the /api/auth/* mount in index.ts from getClientIp(), which
|
||||||
|
// anchors trust in the TCP peer address (only our own proxies may speak
|
||||||
|
// for the client via X-Real-IP / X-Forwarded-For). Never read the raw
|
||||||
|
// forwarded headers here: without the socket they are spoofable, and
|
||||||
|
// Better Auth would fall back to one shared rate-limit bucket.
|
||||||
|
ipAddressHeaders: ['x-client-ip'],
|
||||||
|
},
|
||||||
|
database: {
|
||||||
|
// Match the app's existing ID convention (uuid on pg, nanoid on sqlite)
|
||||||
|
// so Better Auth rows are indistinguishable from legacy rows.
|
||||||
|
generateId: () => generateId(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
user: {
|
||||||
|
additionalFields: {
|
||||||
|
// `role`, `banned`, `banReason`, `banExpires` come from the admin plugin.
|
||||||
|
phone: { type: 'string', required: false, input: true },
|
||||||
|
languagePreference: { type: 'string', required: false, input: true },
|
||||||
|
rucNumber: { type: 'string', required: false, input: false },
|
||||||
|
isClaimed: { type: 'boolean', required: false, input: false, defaultValue: true },
|
||||||
|
accountStatus: { type: 'string', required: false, input: false, defaultValue: 'active' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
session: {
|
||||||
|
expiresIn: 60 * 60 * 24 * 7, // 7 days, rolling
|
||||||
|
updateAge: 60 * 60 * 24, // refresh expiry at most once a day
|
||||||
|
freshAge: 60 * 60 * 24, // sensitive operations require a session younger than this
|
||||||
|
// Disabled deliberately: every request validates against the session table,
|
||||||
|
// so ban/suspend/password-reset revocations apply instantly — and the Go
|
||||||
|
// photo-api (which reads the same table) can never disagree with us.
|
||||||
|
cookieCache: { enabled: false },
|
||||||
|
storeSessionInDatabase: true,
|
||||||
|
},
|
||||||
|
|
||||||
|
emailAndPassword: {
|
||||||
|
enabled: true,
|
||||||
|
minPasswordLength: 10,
|
||||||
|
maxPasswordLength: 128,
|
||||||
|
autoSignIn: true,
|
||||||
|
requireEmailVerification: false,
|
||||||
|
revokeSessionsOnPasswordReset: true,
|
||||||
|
resetPasswordTokenExpiresIn: 60 * 30, // 30 minutes, matches the legacy flow
|
||||||
|
sendResetPassword: async ({ user, url }) => {
|
||||||
|
try {
|
||||||
|
await sendEmail({
|
||||||
|
to: user.email,
|
||||||
|
subject: 'Reset Your Spanglish Password',
|
||||||
|
html: `
|
||||||
|
<h2>Reset Your Password</h2>
|
||||||
|
<p>Click the link below to reset your password. This link expires in 30 minutes.</p>
|
||||||
|
<p><a href="${url}" style="background-color: #3B82F6; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;">Reset Password</a></p>
|
||||||
|
<p>Or copy this link: ${url}</p>
|
||||||
|
<p>If you didn't request this, you can safely ignore this email.</p>
|
||||||
|
`,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to send password reset email:', error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
password: {
|
||||||
|
// Keep the existing argon2id parameters; legacy bcrypt hashes (migrated
|
||||||
|
// into auth_accounts) still verify and are upgraded on login below.
|
||||||
|
hash: (password) => hashPassword(password),
|
||||||
|
verify: ({ hash, password }) => verifyPassword(password, hash),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
...(process.env.GOOGLE_CLIENT_ID
|
||||||
|
? {
|
||||||
|
socialProviders: {
|
||||||
|
google: {
|
||||||
|
clientId: process.env.GOOGLE_CLIENT_ID,
|
||||||
|
// Not required for ID-token (Google Identity Services) sign-in,
|
||||||
|
// only for the redirect OAuth flow.
|
||||||
|
clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
|
||||||
|
account: {
|
||||||
|
accountLinking: {
|
||||||
|
enabled: true,
|
||||||
|
// Google verifies email ownership, so linking by email is safe — this
|
||||||
|
// matches the legacy /api/auth/google auto-link behavior.
|
||||||
|
trustedProviders: ['google'],
|
||||||
|
// `trustedProviders` alone is NOT enough: better-auth ORs a second,
|
||||||
|
// independent gate — `requireLocalEmailVerified` (default true) — which
|
||||||
|
// refuses the link whenever the LOCAL users.email_verified is false.
|
||||||
|
// That is the state of every guest-booking user (routes/tickets.ts,
|
||||||
|
// routes/door.ts insert email_verified = false) and of every
|
||||||
|
// email/password signup made after the Better Auth migration, so Google
|
||||||
|
// sign-in failed for them with "account not linked".
|
||||||
|
//
|
||||||
|
// The local flag adds nothing here: the Google ID token is signature-
|
||||||
|
// verified against Google's JWKS with issuer/audience/max-age checks and
|
||||||
|
// carries its own `email_verified`, so Google — not our column — is what
|
||||||
|
// proves ownership of the address.
|
||||||
|
//
|
||||||
|
// NOTE: upstream marks this option deprecated ("the gate will become
|
||||||
|
// unconditional"). better-auth is pinned exactly at 1.6.25 in both
|
||||||
|
// workspaces, and betterAuth.integration.test.ts covers this path, so an
|
||||||
|
// upgrade that drops the option fails CI rather than silently locking
|
||||||
|
// ticket buyers out again.
|
||||||
|
requireLocalEmailVerified: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
rateLimit: {
|
||||||
|
// Explicitly enabled so dev behaves like production (off in dev by default).
|
||||||
|
enabled: true,
|
||||||
|
window: 60,
|
||||||
|
max: 100,
|
||||||
|
// DB-backed rather than Redis: our Redis layer is fail-open by design,
|
||||||
|
// which is the wrong default for auth rate limiting. The per-email login
|
||||||
|
// lockout below is already Redis-shared across replicas.
|
||||||
|
storage: 'database',
|
||||||
|
modelName: 'rateLimit',
|
||||||
|
customRules: {
|
||||||
|
'/sign-in/email': { window: 900, max: 10 },
|
||||||
|
'/sign-up/email': { window: 900, max: 10 },
|
||||||
|
'/sign-in/magic-link': { window: 900, max: 5 },
|
||||||
|
'/magic-link/verify': { window: 900, max: 30 },
|
||||||
|
'/request-password-reset': { window: 900, max: 5 },
|
||||||
|
'/reset-password': { window: 900, max: 10 },
|
||||||
|
'/sign-in/social': { window: 900, max: 20 },
|
||||||
|
'/change-password': { window: 900, max: 10 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
databaseHooks: {
|
||||||
|
user: {
|
||||||
|
create: {
|
||||||
|
before: async (user) => {
|
||||||
|
// First user to register becomes admin (replaces isFirstUser())
|
||||||
|
const existing = await dbAll<any>((db as any).select().from(authUsers).limit(1));
|
||||||
|
if (!existing || existing.length === 0) {
|
||||||
|
return { data: { ...user, role: 'admin' } };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
account: {
|
||||||
|
create: {
|
||||||
|
// Fires for both branches of the OAuth path: createOAuthUser (new user)
|
||||||
|
// and linkAccount (existing user), since both go through the adapter's
|
||||||
|
// createWithHooks(..., 'account').
|
||||||
|
after: async (account) => {
|
||||||
|
if (account.providerId !== 'google') return;
|
||||||
|
// Attaching a Google account proves ownership of the address, so a
|
||||||
|
// row created during guest booking is now a real, claimed account.
|
||||||
|
// Without this, getAuthUser() (lib/auth.ts) rejects the brand-new
|
||||||
|
// session because accountStatus is still 'unclaimed' — the user gets
|
||||||
|
// a cookie and still looks logged out. Mirrors the tail of the
|
||||||
|
// magic-link claim flow in routes/authExt.ts.
|
||||||
|
//
|
||||||
|
// Scoped to 'unclaimed' in the WHERE clause so a suspended account is
|
||||||
|
// never silently reactivated by linking Google to it.
|
||||||
|
try {
|
||||||
|
await (db as any)
|
||||||
|
.update(authUsers)
|
||||||
|
// `emailVerified` is deliberately left alone: better-auth's link
|
||||||
|
// branch sets it right after this hook, but only when Google's
|
||||||
|
// id_token actually asserted email_verified.
|
||||||
|
.set({
|
||||||
|
isClaimed: true,
|
||||||
|
accountStatus: 'active',
|
||||||
|
updatedAt: new Date(),
|
||||||
|
})
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq((authUsers as any).id, account.userId),
|
||||||
|
eq((authUsers as any).accountStatus, 'unclaimed')
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('[auth] Failed to claim account on Google link:', err?.message || err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
hooks: {
|
||||||
|
before: createAuthMiddleware(async (ctx) => {
|
||||||
|
// Enforce the full password policy (character classes + blocklist) on
|
||||||
|
// every password-setting path, for both client and server-side calls.
|
||||||
|
if (PASSWORD_SETTING_PATHS.has(ctx.path)) {
|
||||||
|
const password = ctx.body?.password ?? ctx.body?.newPassword;
|
||||||
|
if (typeof password === 'string') {
|
||||||
|
const result = validatePassword(password);
|
||||||
|
if (!result.valid) {
|
||||||
|
throw new APIError('BAD_REQUEST', { message: result.error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per-email lockout: 5 failures / 15 min, Redis-shared when configured.
|
||||||
|
// Kept as defense-in-depth on top of Better Auth's per-IP rate limits.
|
||||||
|
if (ctx.path === '/sign-in/email' && typeof ctx.body?.email === 'string') {
|
||||||
|
const lockout = await getLoginLockout().isLocked(ctx.body.email);
|
||||||
|
if (lockout.locked) {
|
||||||
|
throw new APIError('TOO_MANY_REQUESTS', {
|
||||||
|
message: 'Too many login attempts. Please try again later.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
after: createAuthMiddleware(async (ctx) => {
|
||||||
|
if (ctx.path !== '/sign-in/email' || typeof ctx.body?.email !== 'string') return;
|
||||||
|
const email = ctx.body.email as string;
|
||||||
|
|
||||||
|
if (ctx.context.returned instanceof APIError) {
|
||||||
|
// Failed sign-in attempt counts toward the per-email lockout
|
||||||
|
await getLoginLockout().recordFailure(email);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await getLoginLockout().clear(email);
|
||||||
|
|
||||||
|
// Transparently upgrade legacy bcrypt hashes to argon2 now that we have
|
||||||
|
// the verified plaintext. Best-effort: never block the login.
|
||||||
|
try {
|
||||||
|
const password = ctx.body?.password;
|
||||||
|
const userId = (ctx.context.newSession?.user as any)?.id;
|
||||||
|
if (typeof password === 'string' && userId) {
|
||||||
|
const account = await getCredentialAccount(userId);
|
||||||
|
if (account?.password && !String(account.password).startsWith('$argon2')) {
|
||||||
|
const upgraded = await hashPassword(password);
|
||||||
|
await (db as any)
|
||||||
|
.update(authAccounts)
|
||||||
|
.set({ password: upgraded, updatedAt: new Date() })
|
||||||
|
.where(eq((authAccounts as any).id, account.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('[auth] Failed to upgrade legacy password hash:', err?.message || err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
|
||||||
|
plugins: [
|
||||||
|
magicLink({
|
||||||
|
expiresIn: 60 * 10, // 10 minutes, matches the legacy flow
|
||||||
|
// Magic links never create accounts (parity with the legacy behavior;
|
||||||
|
// account creation is register / Google / guest booking only).
|
||||||
|
disableSignUp: true,
|
||||||
|
// Hashed at rest: a leaked verification table cannot be replayed.
|
||||||
|
storeToken: 'hashed',
|
||||||
|
sendMagicLink: async ({ email, url, token }) => {
|
||||||
|
// Email a frontend URL (not the raw API verify URL) so the login
|
||||||
|
// completes on the site, preserving the legacy UX. The page calls
|
||||||
|
// authClient.magicLink.verify with the token.
|
||||||
|
let callbackURL = '/';
|
||||||
|
try {
|
||||||
|
callbackURL = new URL(url).searchParams.get('callbackURL') || '/';
|
||||||
|
} catch {
|
||||||
|
/* default */
|
||||||
|
}
|
||||||
|
const link = `${frontendUrl}/auth/magic-link?token=${encodeURIComponent(token)}&callbackURL=${encodeURIComponent(callbackURL)}`;
|
||||||
|
const isClaim = callbackURL.startsWith('/auth/claim-account');
|
||||||
|
try {
|
||||||
|
await sendEmail({
|
||||||
|
to: email,
|
||||||
|
subject: isClaim ? 'Claim Your Spanglish Account' : 'Your Spanglish Login Link',
|
||||||
|
html: isClaim
|
||||||
|
? `
|
||||||
|
<h2>Claim Your Account</h2>
|
||||||
|
<p>An account was created for you during booking. Click below to set up your login credentials. This link expires in 10 minutes.</p>
|
||||||
|
<p><a href="${link}" style="background-color: #3B82F6; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;">Claim Account</a></p>
|
||||||
|
<p>Or copy this link: ${link}</p>
|
||||||
|
<p>If you didn't request this, you can safely ignore this email.</p>
|
||||||
|
`
|
||||||
|
: `
|
||||||
|
<h2>Login to Spanglish</h2>
|
||||||
|
<p>Click the link below to log in. This link expires in 10 minutes.</p>
|
||||||
|
<p><a href="${link}" style="background-color: #3B82F6; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;">Log In</a></p>
|
||||||
|
<p>Or copy this link: ${link}</p>
|
||||||
|
<p>If you didn't request this, you can safely ignore this email.</p>
|
||||||
|
`,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to send magic link email:', error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
admin({
|
||||||
|
defaultRole: 'user',
|
||||||
|
adminRoles: ['admin'],
|
||||||
|
bannedUserMessage: 'Account is suspended. Please contact support.',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
export type Auth = typeof auth;
|
||||||
@@ -18,7 +18,7 @@ import { and, eq, lt, inArray, notInArray } from 'drizzle-orm';
|
|||||||
import { db, dbAll, tickets, payments } from '../db/index.js';
|
import { db, dbAll, tickets, payments } from '../db/index.js';
|
||||||
import { getNow, toDbDate } from './utils.js';
|
import { getNow, toDbDate } from './utils.js';
|
||||||
import { getLock } from './stores/lock.js';
|
import { getLock } from './stores/lock.js';
|
||||||
import { MANUAL_PAYMENT_PROVIDERS } from './manualProviders.js';
|
import { MANUAL_PAYMENT_PROVIDERS } from './paymentProviders.js';
|
||||||
|
|
||||||
function getTtlMs(): number {
|
function getTtlMs(): number {
|
||||||
const minutes = parseInt(process.env.PENDING_BOOKING_TTL_MINUTES || '30', 10);
|
const minutes = parseInt(process.env.PENDING_BOOKING_TTL_MINUTES || '30', 10);
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
// Single source of truth for event seat accounting.
|
||||||
|
//
|
||||||
|
// A seat is held by a booking the moment the money is real or claimed to be:
|
||||||
|
// - ticket 'confirmed' or 'checked_in' (paid), or
|
||||||
|
// - ticket 'pending' whose payment is 'pending_approval' (customer clicked
|
||||||
|
// "I've paid" and is waiting for admin verification).
|
||||||
|
//
|
||||||
|
// A bare 'pending' payment — an opened checkout that was never paid nor claimed,
|
||||||
|
// on any provider — holds NO seat, so abandoned bookings can never block sales.
|
||||||
|
// The accepted trade-off is a small oversell window when several people book the
|
||||||
|
// last seats and all later pay/claim; admin approval is the backstop and may
|
||||||
|
// knowingly approve over capacity (see routes/payments.ts).
|
||||||
|
//
|
||||||
|
// 'pending_approval' is a payment status (the ticket row stays 'pending'), so
|
||||||
|
// every capacity count joins tickets to payments. There is exactly one payment
|
||||||
|
// row per ticket (created together in routes/tickets.ts).
|
||||||
|
//
|
||||||
|
// Every place that counts seats — booking creation, public availability,
|
||||||
|
// hold recovery, admin dashboards — must go through these builders so the
|
||||||
|
// formula cannot diverge between surfaces.
|
||||||
|
|
||||||
|
import { sql, and, eq, inArray } from 'drizzle-orm';
|
||||||
|
import { tickets, payments } from '../db/index.js';
|
||||||
|
|
||||||
|
// COALESCE keeps the predicate two-valued under the LEFT JOIN (a ticket with no
|
||||||
|
// payment row must count as "not holding" — NULL would poison NOT ...).
|
||||||
|
export const seatHoldingSql = sql`(${(tickets as any).status} IN ('confirmed', 'checked_in') OR (${(tickets as any).status} = 'pending' AND COALESCE(${(payments as any).status}, '') = 'pending_approval'))`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query: number of seats currently held for an event.
|
||||||
|
* `executor` is the db, or a transaction (sync sqlite tx: finish with `.get()`;
|
||||||
|
* async pg tx / plain db: await via dbGet).
|
||||||
|
*/
|
||||||
|
export function seatHolderCountQuery(executor: any, eventId: string) {
|
||||||
|
return executor
|
||||||
|
.select({ count: sql<number>`count(distinct ${(tickets as any).id})` })
|
||||||
|
.from(tickets)
|
||||||
|
.leftJoin(payments, eq((payments as any).ticketId, (tickets as any).id))
|
||||||
|
.where(and(eq((tickets as any).eventId, eventId), seatHoldingSql));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query: how many of the given tickets do NOT currently hold a seat (and so
|
||||||
|
* would need fresh capacity if promoted to a seat-holding state).
|
||||||
|
*/
|
||||||
|
export function unseatedTicketCountQuery(executor: any, ticketIds: string[]) {
|
||||||
|
return executor
|
||||||
|
.select({ count: sql<number>`count(distinct ${(tickets as any).id})` })
|
||||||
|
.from(tickets)
|
||||||
|
.leftJoin(payments, eq((payments as any).ticketId, (tickets as any).id))
|
||||||
|
.where(and(inArray((tickets as any).id, ticketIds), sql`NOT ${seatHoldingSql}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query: per-event breakdown of paid vs claimed seats, grouped by event.
|
||||||
|
* paidCount = confirmed + checked_in; claimedCount = pending_approval-held.
|
||||||
|
* Pass `eventId` to restrict to one event (still returns a grouped row), or an
|
||||||
|
* array of ids to restrict to those events (e.g. one page of a listing). Callers
|
||||||
|
* must skip the query for an empty array.
|
||||||
|
*/
|
||||||
|
export function eventSeatBreakdownQuery(executor: any, eventId?: string | string[]) {
|
||||||
|
const query = executor
|
||||||
|
.select({
|
||||||
|
eventId: (tickets as any).eventId,
|
||||||
|
paidCount: sql<number>`sum(case when ${(tickets as any).status} IN ('confirmed', 'checked_in') then 1 else 0 end)`,
|
||||||
|
claimedCount: sql<number>`sum(case when ${(tickets as any).status} = 'pending' AND COALESCE(${(payments as any).status}, '') = 'pending_approval' then 1 else 0 end)`,
|
||||||
|
})
|
||||||
|
.from(tickets)
|
||||||
|
.leftJoin(payments, eq((payments as any).ticketId, (tickets as any).id));
|
||||||
|
const scoped = Array.isArray(eventId)
|
||||||
|
? query.where(inArray((tickets as any).eventId, eventId))
|
||||||
|
: eventId ? query.where(eq((tickets as any).eventId, eventId)) : query;
|
||||||
|
return scoped.groupBy((tickets as any).eventId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
// Door payment tenders.
|
||||||
|
//
|
||||||
|
// The door check-in screen offers five tenders. Each maps onto an
|
||||||
|
// existing payments.provider so the rest of the app (capacity, sweeps, admin
|
||||||
|
// payment lists, receipts) keeps working unchanged, while payments.method
|
||||||
|
// records which tender was actually used for the end-of-night cash-up.
|
||||||
|
//
|
||||||
|
// Bitcoin currently maps to the 'lightning' provider but records the payment as
|
||||||
|
// already made — the same trust model as cash, no invoice generated. When a real
|
||||||
|
// Lightning flow lands it slots in here: the tender keeps its name and provider,
|
||||||
|
// only the settlement path in routes/door.ts changes.
|
||||||
|
//
|
||||||
|
// POS is the physical card terminal. Staff open the POS step, which shows the
|
||||||
|
// amount to key into the terminal, charge the card, then confirm "Mark as paid";
|
||||||
|
// only that confirmation reaches this API, recorded like any other tender. A
|
||||||
|
// future automatic amount push to the terminal belongs in the POS step itself
|
||||||
|
// (frontend PosChargePanel) plus a 'terminal' settlement here — nothing talks to
|
||||||
|
// the terminal today.
|
||||||
|
|
||||||
|
import { eq } from 'drizzle-orm';
|
||||||
|
import { db, dbGet, paymentOptions, eventPaymentOverrides } from '../db/index.js';
|
||||||
|
|
||||||
|
export const DOOR_PAYMENT_METHODS = ['cash', 'bitcoin', 'transfer', 'pos', 'guest'] as const;
|
||||||
|
|
||||||
|
export type DoorPaymentMethod = (typeof DOOR_PAYMENT_METHODS)[number];
|
||||||
|
|
||||||
|
interface DoorTender {
|
||||||
|
/** Existing payments.provider this tender is stored as. */
|
||||||
|
provider: 'cash' | 'lightning' | 'bank_transfer' | 'pos';
|
||||||
|
/** Human label used in payment references and toasts. */
|
||||||
|
label: string;
|
||||||
|
/** Comp tenders carry no revenue and always record a zero amount. */
|
||||||
|
isComp: boolean;
|
||||||
|
/**
|
||||||
|
* How the money is confirmed before the door screen records it:
|
||||||
|
* 'on_tap' staff already hold the money when they tap (cash, …)
|
||||||
|
* 'staff_confirm' staff charge an external device first, then confirm
|
||||||
|
*/
|
||||||
|
confirmation: 'on_tap' | 'staff_confirm';
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DOOR_TENDERS: Record<DoorPaymentMethod, DoorTender> = {
|
||||||
|
cash: { provider: 'cash', label: 'cash', isComp: false, confirmation: 'on_tap' },
|
||||||
|
bitcoin: { provider: 'lightning', label: 'bitcoin', isComp: false, confirmation: 'on_tap' },
|
||||||
|
transfer: { provider: 'bank_transfer', label: 'transfer', isComp: false, confirmation: 'on_tap' },
|
||||||
|
pos: { provider: 'pos', label: 'POS', isComp: false, confirmation: 'staff_confirm' },
|
||||||
|
guest: { provider: 'cash', label: 'guest', isComp: true, confirmation: 'on_tap' },
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tenders that can be switched off per event through payment options. Only POS
|
||||||
|
* is configurable: the other door tenders are always available to staff.
|
||||||
|
*/
|
||||||
|
export function enabledDoorMethods(opts: { posEnabled: boolean }): DoorPaymentMethod[] {
|
||||||
|
return DOOR_PAYMENT_METHODS.filter((m) => m !== 'pos' || opts.posEnabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Door tenders available for this event (POS can be switched off per event). */
|
||||||
|
export async function loadDoorMethods(eventId: string): Promise<DoorPaymentMethod[]> {
|
||||||
|
const [globalOptions, overrides] = await Promise.all([
|
||||||
|
dbGet<any>((db as any).select().from(paymentOptions)),
|
||||||
|
dbGet<any>(
|
||||||
|
(db as any).select().from(eventPaymentOverrides).where(eq((eventPaymentOverrides as any).eventId, eventId))
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
// Override wins when set; POS defaults to on when nothing is configured.
|
||||||
|
const posEnabled = overrides?.posEnabled ?? globalOptions?.posEnabled ?? true;
|
||||||
|
return enabledDoorMethods({ posEnabled: posEnabled === true || posEnabled === 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDoorPaymentMethod(value: unknown): value is DoorPaymentMethod {
|
||||||
|
return typeof value === 'string' && (DOOR_PAYMENT_METHODS as readonly string[]).includes(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ticket paymentStatus a tender settles to: comps are 'comp', everything else 'paid'. */
|
||||||
|
export function paymentStatusForMethod(method: DoorPaymentMethod): 'paid' | 'comp' {
|
||||||
|
return DOOR_TENDERS[method].isComp ? 'comp' : 'paid';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Amount actually recorded: comps are always zero regardless of what was requested. */
|
||||||
|
export function amountForMethod(method: DoorPaymentMethod, requested: number): number {
|
||||||
|
return DOOR_TENDERS[method].isComp ? 0 : Math.max(0, requested);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function doorReference(method: DoorPaymentMethod): string {
|
||||||
|
return DOOR_TENDERS[method].isComp
|
||||||
|
? 'Door — guest (comp)'
|
||||||
|
: `Door — paid by ${DOOR_TENDERS[method].label}`;
|
||||||
|
}
|
||||||
@@ -74,8 +74,8 @@ export async function sendPaymentReceipt(paymentId: string): Promise<{ success:
|
|||||||
const eventTitle = locale === 'es' && event.titleEs ? event.titleEs : event.title;
|
const eventTitle = locale === 'es' && event.titleEs ? event.titleEs : event.title;
|
||||||
|
|
||||||
const paymentMethodNames: Record<string, Record<string, string>> = {
|
const paymentMethodNames: Record<string, Record<string, string>> = {
|
||||||
en: { bancard: 'Card', lightning: 'Lightning (Bitcoin)', cash: 'Cash', bank_transfer: 'Bank Transfer', tpago: 'TPago' },
|
en: { bancard: 'Card', lightning: 'Lightning (Bitcoin)', cash: 'Cash', bank_transfer: 'Bank Transfer', tpago: 'TPago', pos: 'POS' },
|
||||||
es: { bancard: 'Tarjeta', lightning: 'Lightning (Bitcoin)', cash: 'Efectivo', bank_transfer: 'Transferencia Bancaria', tpago: 'TPago' },
|
es: { bancard: 'Tarjeta', lightning: 'Lightning (Bitcoin)', cash: 'Efectivo', bank_transfer: 'Transferencia Bancaria', tpago: 'TPago', pos: 'POS' },
|
||||||
};
|
};
|
||||||
|
|
||||||
const receiptFullName = `${ticket.attendeeFirstName} ${ticket.attendeeLastName || ''}`.trim();
|
const receiptFullName = `${ticket.attendeeFirstName} ${ticket.attendeeLastName || ''}`.trim();
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
// Per-event access control.
|
||||||
|
//
|
||||||
|
// Global roles still work exactly as before: every route passes the roles it
|
||||||
|
// always allowed (`globalRoles`). On top of that, a user linked to one event
|
||||||
|
// through event_members gets the permissions of their role preset, adjusted by
|
||||||
|
// per-member overrides — for that event only. A collaborator with role 'user'
|
||||||
|
// therefore reaches the routes of their own events and gets 403 everywhere
|
||||||
|
// else.
|
||||||
|
//
|
||||||
|
// Finance and team management are deliberately NOT part of any global role
|
||||||
|
// except admin: organizers only see them on events where an admin granted it.
|
||||||
|
|
||||||
|
import type { Context } from 'hono';
|
||||||
|
import { and, eq } from 'drizzle-orm';
|
||||||
|
import { db, dbGet, eventMembers, tickets, payments } from '../db/index.js';
|
||||||
|
import { getAuthUser, type AuthUser } from './auth.js';
|
||||||
|
|
||||||
|
export const EVENT_PERMISSIONS = [
|
||||||
|
'view_overview',
|
||||||
|
'check_in',
|
||||||
|
'view_attendees_names',
|
||||||
|
'view_attendees_pii',
|
||||||
|
'email_attendees',
|
||||||
|
'view_payments',
|
||||||
|
'view_finance',
|
||||||
|
'edit_expenses',
|
||||||
|
'edit_own_expenses_only',
|
||||||
|
'view_full_split',
|
||||||
|
'edit_event',
|
||||||
|
'manage_team',
|
||||||
|
] as const;
|
||||||
|
export type EventPermission = (typeof EVENT_PERMISSIONS)[number];
|
||||||
|
|
||||||
|
export const ROLE_PRESETS = ['staff', 'collaborator', 'co_manager'] as const;
|
||||||
|
export type RolePreset = (typeof ROLE_PRESETS)[number];
|
||||||
|
|
||||||
|
export const PRESET_PERMISSIONS: Record<RolePreset, readonly EventPermission[]> = {
|
||||||
|
staff: ['view_overview', 'check_in', 'view_attendees_names'],
|
||||||
|
// Sees the event's P&L and only their own share, not the full split.
|
||||||
|
collaborator: ['view_overview', 'view_finance'],
|
||||||
|
co_manager: EVENT_PERMISSIONS.filter((p) => p !== 'manage_team'),
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a global role can already do on every event, mirroring the existing
|
||||||
|
* route allowlists. Used for the UI (which tabs to show) and for new routes.
|
||||||
|
*/
|
||||||
|
export const GLOBAL_ROLE_PERMISSIONS: Record<string, readonly EventPermission[]> = {
|
||||||
|
admin: EVENT_PERMISSIONS,
|
||||||
|
organizer: ['view_overview', 'check_in', 'view_attendees_names', 'view_attendees_pii', 'email_attendees', 'view_payments', 'edit_event'],
|
||||||
|
staff: ['view_overview', 'check_in', 'view_attendees_names', 'view_attendees_pii'],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function isEventPermission(key: string): key is EventPermission {
|
||||||
|
return (EVENT_PERMISSIONS as readonly string[]).includes(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseOverrides(raw: unknown): Partial<Record<EventPermission, boolean>> {
|
||||||
|
let obj: any = raw;
|
||||||
|
if (typeof raw === 'string') {
|
||||||
|
try { obj = JSON.parse(raw); } catch { obj = {}; }
|
||||||
|
}
|
||||||
|
const out: Partial<Record<EventPermission, boolean>> = {};
|
||||||
|
if (obj && typeof obj === 'object') {
|
||||||
|
for (const [k, v] of Object.entries(obj)) {
|
||||||
|
if (isEventPermission(k) && typeof v === 'boolean') out[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Preset permissions with the member's overrides applied in either direction. */
|
||||||
|
export function resolveMemberPermissions(preset: string, overrides: unknown): Set<EventPermission> {
|
||||||
|
const base = PRESET_PERMISSIONS[preset as RolePreset] || [];
|
||||||
|
const set = new Set<EventPermission>(base);
|
||||||
|
for (const [k, v] of Object.entries(parseOverrides(overrides))) {
|
||||||
|
if (v) set.add(k as EventPermission); else set.delete(k as EventPermission);
|
||||||
|
}
|
||||||
|
return set;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EventAccess {
|
||||||
|
eventId: string | null;
|
||||||
|
/** True when the user's global role passed the route's allowlist. */
|
||||||
|
global: boolean;
|
||||||
|
role: string;
|
||||||
|
permissions: Set<EventPermission>;
|
||||||
|
membership: { id: string; rolePreset: RolePreset } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMembership(userId: string, eventId: string) {
|
||||||
|
return dbGet<any>(
|
||||||
|
(db as any)
|
||||||
|
.select()
|
||||||
|
.from(eventMembers)
|
||||||
|
.where(and(eq((eventMembers as any).eventId, eventId), eq((eventMembers as any).userId, userId)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Union of what the user's global role and their membership (if any) grant on this event. */
|
||||||
|
export async function getEffectivePermissions(user: Pick<AuthUser, 'id' | 'role'>, eventId: string): Promise<EventAccess> {
|
||||||
|
const permissions = new Set<EventPermission>(GLOBAL_ROLE_PERMISSIONS[user.role] || []);
|
||||||
|
const member = await getMembership(user.id, eventId);
|
||||||
|
if (member) {
|
||||||
|
for (const p of resolveMemberPermissions(member.rolePreset, member.permissions)) permissions.add(p);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
eventId,
|
||||||
|
global: user.role === 'admin',
|
||||||
|
role: user.role,
|
||||||
|
permissions,
|
||||||
|
membership: member ? { id: member.id, rolePreset: member.rolePreset } : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function canUnfinalize(access: EventAccess): boolean {
|
||||||
|
return access.role === 'admin' || access.membership?.rolePreset === 'co_manager';
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Event id resolvers ====================
|
||||||
|
|
||||||
|
type EventIdResolver = (c: Context) => Promise<string | null> | string | null;
|
||||||
|
|
||||||
|
export const eventFromParam = (name = 'id'): EventIdResolver => (c) => c.req.param(name) || null;
|
||||||
|
|
||||||
|
export const eventFromQuery = (name = 'eventId'): EventIdResolver => (c) => c.req.query(name) || null;
|
||||||
|
|
||||||
|
/** Reads eventId from a JSON body. Hono caches the parsed body, so validators can read it again. */
|
||||||
|
export const eventFromBody = (name = 'eventId'): EventIdResolver => async (c) => {
|
||||||
|
try {
|
||||||
|
const body = await c.req.json();
|
||||||
|
return typeof body?.[name] === 'string' ? body[name] : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Query string first, then the JSON body (routes that accept both). */
|
||||||
|
export const eventFromQueryOrBody = (name = 'eventId'): EventIdResolver => async (c) =>
|
||||||
|
eventFromQuery(name)(c) || (c.req.method === 'GET' ? null : await eventFromBody(name)(c));
|
||||||
|
|
||||||
|
export const eventFromTicketParam = (name = 'id'): EventIdResolver => async (c) => {
|
||||||
|
const id = c.req.param(name);
|
||||||
|
if (!id) return null;
|
||||||
|
const row = await dbGet<any>(
|
||||||
|
(db as any).select({ eventId: (tickets as any).eventId }).from(tickets).where(eq((tickets as any).id, id))
|
||||||
|
);
|
||||||
|
return row?.eventId ?? null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const eventFromPaymentParam = (name = 'id'): EventIdResolver => async (c) => {
|
||||||
|
const id = c.req.param(name);
|
||||||
|
if (!id) return null;
|
||||||
|
const row = await dbGet<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({ eventId: (tickets as any).eventId })
|
||||||
|
.from(payments)
|
||||||
|
.innerJoin(tickets, eq((payments as any).ticketId, (tickets as any).id))
|
||||||
|
.where(eq((payments as any).id, id))
|
||||||
|
);
|
||||||
|
return row?.eventId ?? null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ==================== Middleware ====================
|
||||||
|
|
||||||
|
export interface RequireEventPermissionOptions {
|
||||||
|
/** Global roles that pass on every event (the route's existing allowlist). Default: admin only. */
|
||||||
|
globalRoles?: readonly string[];
|
||||||
|
/** Where the event id comes from. Default: the :id path param. */
|
||||||
|
eventId?: EventIdResolver;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allow the request when the user's global role is in `globalRoles`, or when
|
||||||
|
* their membership on the resolved event grants any of `keys`. Sets
|
||||||
|
* c.get('user') like requireAuth, and c.get('eventAccess') for handlers that
|
||||||
|
* shape their response (e.g. hide attendee contact details).
|
||||||
|
*/
|
||||||
|
export function requireEventPermission(
|
||||||
|
keys: EventPermission | readonly EventPermission[],
|
||||||
|
opts: RequireEventPermissionOptions = {},
|
||||||
|
) {
|
||||||
|
const wanted = (Array.isArray(keys) ? keys : [keys]) as readonly EventPermission[];
|
||||||
|
const globalRoles = opts.globalRoles || ['admin'];
|
||||||
|
const resolve = opts.eventId || eventFromParam('id');
|
||||||
|
|
||||||
|
return async (c: Context, next: () => Promise<void>) => {
|
||||||
|
const user = await getAuthUser(c);
|
||||||
|
if (!user) {
|
||||||
|
return c.json({ error: 'Unauthorized' }, 401);
|
||||||
|
}
|
||||||
|
c.set('user', user);
|
||||||
|
|
||||||
|
if (globalRoles.includes(user.role)) {
|
||||||
|
const eventId = await resolve(c);
|
||||||
|
c.set('eventAccess', {
|
||||||
|
eventId,
|
||||||
|
global: true,
|
||||||
|
role: user.role,
|
||||||
|
permissions: new Set(GLOBAL_ROLE_PERMISSIONS[user.role] || EVENT_PERMISSIONS),
|
||||||
|
membership: null,
|
||||||
|
} satisfies EventAccess);
|
||||||
|
await next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const eventId = await resolve(c);
|
||||||
|
if (!eventId) {
|
||||||
|
return c.json({ error: 'Forbidden' }, 403);
|
||||||
|
}
|
||||||
|
const access = await getEffectivePermissions(user, eventId);
|
||||||
|
if (!wanted.some((k) => access.permissions.has(k))) {
|
||||||
|
return c.json({ error: 'Forbidden', code: 'EVENT_PERMISSION', permission: wanted[0] }, 403);
|
||||||
|
}
|
||||||
|
c.set('eventAccess', access);
|
||||||
|
await next();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getEventAccess(c: Context): EventAccess | null {
|
||||||
|
return ((c as any).get('eventAccess') as EventAccess | undefined) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when the request may see attendee contact details (email, phone, RUC). */
|
||||||
|
export function canSeeAttendeePii(c: Context): boolean {
|
||||||
|
const access = getEventAccess(c);
|
||||||
|
return !access || access.global || access.permissions.has('view_attendees_pii');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop attendee contact details for members without view_attendees_pii. */
|
||||||
|
export function redactAttendee<T extends Record<string, any>>(t: T): T {
|
||||||
|
const { attendeeEmail, attendeePhone, attendeeRuc, ...rest } = t as any;
|
||||||
|
return { ...rest, attendeeEmail: null, attendeePhone: null, attendeeRuc: null } as T;
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
// finance_audit_log rows. Returned as TxOps so every change and its audit row
|
||||||
|
// commit (or roll back) together.
|
||||||
|
|
||||||
|
import { financeAuditLog } from '../../db/index.js';
|
||||||
|
import { generateId, getNow } from '../utils.js';
|
||||||
|
import { insertOp, type TxOp } from '../txOps.js';
|
||||||
|
|
||||||
|
export type FinanceEntity =
|
||||||
|
| 'expense' | 'other_income' | 'partner' | 'finance_state' | 'member'
|
||||||
|
| 'expense_category' | 'expense_template' | 'expense_template_pack' | 'payment_fee';
|
||||||
|
|
||||||
|
export function financeAuditOp(entry: {
|
||||||
|
eventId: string | null;
|
||||||
|
actorUserId: string;
|
||||||
|
entityType: FinanceEntity;
|
||||||
|
entityId: string | null;
|
||||||
|
action: string;
|
||||||
|
before?: unknown;
|
||||||
|
after?: unknown;
|
||||||
|
}): TxOp {
|
||||||
|
return insertOp(financeAuditLog, {
|
||||||
|
id: generateId(),
|
||||||
|
eventId: entry.eventId,
|
||||||
|
actorUserId: entry.actorUserId,
|
||||||
|
entityType: entry.entityType,
|
||||||
|
entityId: entry.entityId,
|
||||||
|
action: entry.action,
|
||||||
|
beforeJson: entry.before === undefined || entry.before === null ? null : JSON.stringify(entry.before),
|
||||||
|
afterJson: entry.after === undefined || entry.after === null ? null : JSON.stringify(entry.after),
|
||||||
|
createdAt: getNow(),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,397 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import {
|
||||||
|
calculateEventFinance,
|
||||||
|
expenseAmount,
|
||||||
|
paymentFee,
|
||||||
|
roundPyg,
|
||||||
|
type FinanceExpense,
|
||||||
|
type FinanceInput,
|
||||||
|
type FinancePartner,
|
||||||
|
type FinancePayment,
|
||||||
|
} from './calculate.js';
|
||||||
|
|
||||||
|
let seq = 0;
|
||||||
|
const pay = (amount: number, over: Partial<FinancePayment> = {}): FinancePayment => ({
|
||||||
|
id: `p${++seq}`, amount, provider: 'tpago', source: 'presale', status: 'paid', paidAt: '2026-09-01T12:00:00Z', ...over,
|
||||||
|
});
|
||||||
|
const expense = (over: Partial<FinanceExpense> = {}): FinanceExpense => ({
|
||||||
|
id: `e${++seq}`, description: 'x', categoryId: null, calcType: 'fixed', quantity: 1, unitAmount: 0, percentBp: 0,
|
||||||
|
minimumAmount: 0, computedAmount: 0, isLocked: false, status: 'planned', paidByPartnerId: null, ...over,
|
||||||
|
});
|
||||||
|
const partner = (over: Partial<FinancePartner> = {}): FinancePartner => ({
|
||||||
|
id: `pt${++seq}`, name: 'Partner', shareType: 'percent_profit', percentBp: 5000, fixedAmount: 0, thresholdAmount: 0,
|
||||||
|
lossRule: 'none', lossCapAmount: 0, ...over,
|
||||||
|
});
|
||||||
|
const input = (over: Partial<FinanceInput> = {}): FinanceInput => ({
|
||||||
|
ticketPrice: 100000, ticketsSold: 0, checkedIn: 0, payments: [], expenses: [], otherIncome: [], fees: [], partners: [], ...over,
|
||||||
|
});
|
||||||
|
const sumShares = (r: ReturnType<typeof calculateEventFinance>) =>
|
||||||
|
r.split.partners.reduce((s, p) => s + p.share, 0) + r.split.organization;
|
||||||
|
|
||||||
|
describe('calculateEventFinance: profit case', () => {
|
||||||
|
const studio = partner({ name: 'Studio', percentBp: 3000 });
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
ticketsSold: 20,
|
||||||
|
checkedIn: 18,
|
||||||
|
payments: [
|
||||||
|
...Array.from({ length: 15 }, () => pay(100000)),
|
||||||
|
...Array.from({ length: 3 }, () => pay(100000, { provider: 'lightning' })),
|
||||||
|
pay(120000, { provider: 'cash', source: 'door', paidAt: '2026-09-05T20:00:00Z' }),
|
||||||
|
pay(120000, { provider: 'pos', source: 'door', paidAt: '2026-09-05T20:10:00Z' }),
|
||||||
|
],
|
||||||
|
fees: [
|
||||||
|
{ method: 'tpago', percentBp: 350, fixedAmount: 0 }, // 3.5%
|
||||||
|
{ method: 'pos', percentBp: 290, fixedAmount: 500 },
|
||||||
|
],
|
||||||
|
otherIncome: [{ id: 'i1', description: 'Sponsor', amount: 150000 }],
|
||||||
|
expenses: [expense({ unitAmount: 800000, status: 'paid' }), expense({ calcType: 'per_checked_in', unitAmount: 15000 })],
|
||||||
|
partners: [studio],
|
||||||
|
}));
|
||||||
|
|
||||||
|
it('splits gross into pre-sale and door and by method', () => {
|
||||||
|
expect(r.revenue.gross).toBe(2040000);
|
||||||
|
expect(r.revenue.presale).toBe(1800000);
|
||||||
|
expect(r.revenue.door).toBe(240000);
|
||||||
|
expect(r.revenue.byMethod.map((m) => [m.method, m.gross])).toEqual([
|
||||||
|
['tpago', 1500000], ['lightning', 300000], ['cash', 120000], ['pos', 120000],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('charges fees per payment from the method rules', () => {
|
||||||
|
// tpago: 15 x 3500; pos: 3480 + 500; lightning and cash have no rule
|
||||||
|
expect(r.revenue.fees).toBe(15 * 3500 + 3980);
|
||||||
|
expect(r.revenue.byMethod.find((m) => m.method === 'pos')!.fees).toBe(3980);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds other income into net revenue and subtracts expenses', () => {
|
||||||
|
expect(r.revenue.net).toBe(2040000 - 56480 + 150000);
|
||||||
|
expect(r.expenses.total).toBe(800000 + 18 * 15000);
|
||||||
|
expect(r.expenses.paid).toBe(800000);
|
||||||
|
expect(r.expenses.planned).toBe(270000);
|
||||||
|
expect(r.profit).toBe(2133520 - 1070000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives the partner its percentage of profit and the organization the rest', () => {
|
||||||
|
expect(r.split.partners[0].share).toBe(roundPyg(1063520 * 0.3));
|
||||||
|
expect(r.split.organization).toBe(1063520 - roundPyg(1063520 * 0.3));
|
||||||
|
expect(sumShares(r)).toBe(r.profit);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds a cumulative sales timeline and a waterfall ending in the split', () => {
|
||||||
|
expect(r.salesTimeline).toEqual([
|
||||||
|
{ date: '2026-09-01', tickets: 18, revenue: 1800000 },
|
||||||
|
{ date: '2026-09-05', tickets: 20, revenue: 2040000 },
|
||||||
|
]);
|
||||||
|
expect(r.waterfall.map((w) => w.key)).toEqual([
|
||||||
|
'gross', 'refunds', 'fees', 'otherIncome', 'net', 'expenses', 'profit', `partner:${studio.id}`, 'organization',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('calculateEventFinance: refunds', () => {
|
||||||
|
it('subtracts refunded payments and charges no fee on them', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
payments: [pay(100000), pay(100000), pay(100000, { status: 'refunded' })],
|
||||||
|
fees: [{ method: 'tpago', percentBp: 1000, fixedAmount: 0 }],
|
||||||
|
}));
|
||||||
|
expect(r.revenue.gross).toBe(300000);
|
||||||
|
expect(r.revenue.refunds).toBe(100000);
|
||||||
|
expect(r.revenue.sales).toBe(200000);
|
||||||
|
expect(r.revenue.fees).toBe(20000);
|
||||||
|
expect(r.revenue.net).toBe(180000);
|
||||||
|
expect(r.salesTimeline.at(-1)).toEqual({ date: '2026-09-01', tickets: 2, revenue: 200000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses sales after refunds as the base for revenue percentages', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
payments: [pay(100000), pay(100000, { status: 'refunded' })],
|
||||||
|
expenses: [expense({ calcType: 'percent_of_revenue', percentBp: 1000 })],
|
||||||
|
}));
|
||||||
|
expect(r.expenses.total).toBe(10000);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('expense calc types', () => {
|
||||||
|
const ctx = { ticketsSold: 30, checkedIn: 25, sales: 3000000 };
|
||||||
|
|
||||||
|
it('fixed multiplies units by the unit amount', () => {
|
||||||
|
expect(expenseAmount(expense({ quantity: 3, unitAmount: 50000 }), ctx)).toEqual({ quantity: 3, amount: 150000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('per_ticket_sold follows tickets sold', () => {
|
||||||
|
expect(expenseAmount(expense({ calcType: 'per_ticket_sold', unitAmount: 10000 }), ctx)).toEqual({ quantity: 30, amount: 300000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('per_checked_in follows check-ins', () => {
|
||||||
|
expect(expenseAmount(expense({ calcType: 'per_checked_in', unitAmount: 10000 }), ctx)).toEqual({ quantity: 25, amount: 250000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('percent_of_revenue takes basis points of sales, rounded to the guaraní', () => {
|
||||||
|
expect(expenseAmount(expense({ calcType: 'percent_of_revenue', percentBp: 1250 }), ctx).amount).toBe(375000);
|
||||||
|
expect(expenseAmount(expense({ calcType: 'percent_of_revenue', percentBp: 333 }), { ...ctx, sales: 1001 }).amount).toBe(33);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('minimum_spend charges the minimum until per-head spend passes it', () => {
|
||||||
|
const e = expense({ calcType: 'minimum_spend', unitAmount: 40000, minimumAmount: 1500000 });
|
||||||
|
expect(expenseAmount(e, { ...ctx, checkedIn: 20 }).amount).toBe(1500000); // 800k < minimum
|
||||||
|
expect(expenseAmount(e, { ...ctx, checkedIn: 50 }).amount).toBe(2000000); // 2.0M > minimum
|
||||||
|
expect(expenseAmount(e, { ...ctx, checkedIn: 0 }).amount).toBe(1500000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('locked rows keep their stored amount regardless of counts', () => {
|
||||||
|
const e = expense({ calcType: 'per_checked_in', unitAmount: 10000, isLocked: true, computedAmount: 123000, quantity: 12 });
|
||||||
|
expect(expenseAmount(e, ctx)).toEqual({ quantity: 12, amount: 123000 });
|
||||||
|
const r = calculateEventFinance(input({ checkedIn: 99, expenses: [e] }));
|
||||||
|
expect(r.expenses.lines[0]).toMatchObject({ amount: 123000, auto: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks unlocked non-fixed rows as auto-calculated', () => {
|
||||||
|
const r = calculateEventFinance(input({ expenses: [expense(), expense({ calcType: 'per_ticket_sold' })] }));
|
||||||
|
expect(r.expenses.lines.map((l) => l.auto)).toEqual([false, true]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('calculateEventFinance: loss rules', () => {
|
||||||
|
// Net revenue 500k, expenses 1.5M => profit -1,000,000
|
||||||
|
const lossInput = (p: FinancePartner) => input({
|
||||||
|
payments: [pay(500000)],
|
||||||
|
expenses: [expense({ unitAmount: 1500000 })],
|
||||||
|
partners: [p],
|
||||||
|
});
|
||||||
|
|
||||||
|
it('proportional: the partner carries its percentage of the loss', () => {
|
||||||
|
const r = calculateEventFinance(lossInput(partner({ percentBp: 4000, lossRule: 'proportional' })));
|
||||||
|
expect(r.profit).toBe(-1000000);
|
||||||
|
expect(r.split.partners[0].share).toBe(-400000);
|
||||||
|
expect(r.split.organization).toBe(-600000);
|
||||||
|
expect(sumShares(r)).toBe(r.profit);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('none: the organization carries the whole loss', () => {
|
||||||
|
const r = calculateEventFinance(lossInput(partner({ percentBp: 4000, lossRule: 'none' })));
|
||||||
|
expect(r.split.partners[0].share).toBe(0);
|
||||||
|
expect(r.split.organization).toBe(-1000000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('capped: the partner carries its percentage up to the cap', () => {
|
||||||
|
const capped = calculateEventFinance(lossInput(partner({ percentBp: 4000, lossRule: 'capped', lossCapAmount: 250000 })));
|
||||||
|
expect(capped.split.partners[0].share).toBe(-250000);
|
||||||
|
expect(capped.split.organization).toBe(-750000);
|
||||||
|
// A cap larger than the proportional share does not increase it
|
||||||
|
const loose = calculateEventFinance(lossInput(partner({ percentBp: 4000, lossRule: 'capped', lossCapAmount: 900000 })));
|
||||||
|
expect(loose.split.partners[0].share).toBe(-400000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('loss rules do not change a profitable split', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
payments: [pay(1000000)],
|
||||||
|
partners: [partner({ percentBp: 4000, lossRule: 'capped', lossCapAmount: 1 })],
|
||||||
|
}));
|
||||||
|
expect(r.split.partners[0].share).toBe(400000);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('calculateEventFinance: reimbursements', () => {
|
||||||
|
it('adds paid costs a partner fronted to their payout without counting them twice', () => {
|
||||||
|
const host = partner({ name: 'Host', percentBp: 5000 });
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
payments: [pay(1000000)],
|
||||||
|
expenses: [
|
||||||
|
expense({ unitAmount: 200000, status: 'paid', paidByPartnerId: host.id }),
|
||||||
|
expense({ unitAmount: 100000, status: 'planned', paidByPartnerId: host.id }), // not fronted yet
|
||||||
|
expense({ unitAmount: 100000, status: 'paid' }),
|
||||||
|
],
|
||||||
|
partners: [host],
|
||||||
|
}));
|
||||||
|
expect(r.profit).toBe(600000);
|
||||||
|
const h = r.split.partners[0];
|
||||||
|
expect(h.reimbursement).toBe(200000);
|
||||||
|
expect(h.share).toBe(300000);
|
||||||
|
expect(h.payout).toBe(500000);
|
||||||
|
expect(r.split.organization).toBe(300000);
|
||||||
|
expect(sumShares(r)).toBe(r.profit);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('nets a loss share against a reimbursement', () => {
|
||||||
|
const host = partner({ percentBp: 5000, lossRule: 'proportional' });
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
payments: [pay(100000)],
|
||||||
|
expenses: [expense({ unitAmount: 300000, status: 'paid', paidByPartnerId: host.id })],
|
||||||
|
partners: [host],
|
||||||
|
}));
|
||||||
|
expect(r.profit).toBe(-200000);
|
||||||
|
expect(r.split.partners[0]).toMatchObject({ share: -100000, reimbursement: 300000, payout: 200000 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('calculateEventFinance: partner share types', () => {
|
||||||
|
it('percent_revenue is paid on sales after refunds, before profit shares', () => {
|
||||||
|
const venue = partner({ name: 'Venue', shareType: 'percent_revenue', percentBp: 2000 });
|
||||||
|
const cohost = partner({ name: 'Co-host', shareType: 'percent_profit', percentBp: 5000 });
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
payments: [pay(600000), pay(400000), pay(100000, { status: 'refunded' })],
|
||||||
|
expenses: [expense({ unitAmount: 300000 })],
|
||||||
|
partners: [venue, cohost],
|
||||||
|
}));
|
||||||
|
expect(r.profit).toBe(700000);
|
||||||
|
expect(r.split.partners[0].share).toBe(200000); // 20% of 1,000,000
|
||||||
|
expect(r.split.distributable).toBe(500000);
|
||||||
|
expect(r.split.partners[1].share).toBe(250000);
|
||||||
|
expect(r.split.organization).toBe(250000);
|
||||||
|
expect(sumShares(r)).toBe(r.profit);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('percent_revenue is still owed when the event loses money', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
payments: [pay(500000)],
|
||||||
|
expenses: [expense({ unitAmount: 800000 })],
|
||||||
|
partners: [partner({ shareType: 'percent_revenue', percentBp: 1000 })],
|
||||||
|
}));
|
||||||
|
expect(r.split.partners[0].share).toBe(50000);
|
||||||
|
expect(r.split.organization).toBe(-350000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fixed is owed regardless of profit', () => {
|
||||||
|
const r = calculateEventFinance(input({ partners: [partner({ shareType: 'fixed', fixedAmount: 300000 })] }));
|
||||||
|
expect(r.split.partners[0].share).toBe(300000);
|
||||||
|
expect(r.split.organization).toBe(-300000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fixed_plus_percent_above_threshold pays the fixed part plus a percentage above the threshold', () => {
|
||||||
|
const p = partner({ shareType: 'fixed_plus_percent_above_threshold', fixedAmount: 100000, percentBp: 1000, thresholdAmount: 500000 });
|
||||||
|
const high = calculateEventFinance(input({ payments: [pay(1600000)], partners: [p] }));
|
||||||
|
// distributable = 1.6M - 100k fixed = 1.5M; 10% of (1.5M - 500k) = 100k
|
||||||
|
expect(high.split.partners[0].share).toBe(200000);
|
||||||
|
expect(sumShares(high)).toBe(high.profit);
|
||||||
|
const low = calculateEventFinance(input({ payments: [pay(400000)], partners: [p] }));
|
||||||
|
expect(low.split.partners[0].share).toBe(100000);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('calculateEventFinance: break-even', () => {
|
||||||
|
it('finds the smallest ticket count that covers all expenses', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
ticketPrice: 100000,
|
||||||
|
ticketsSold: 4,
|
||||||
|
expenses: [expense({ unitAmount: 1000000 }), expense({ calcType: 'per_ticket_sold', unitAmount: 20000 })],
|
||||||
|
}));
|
||||||
|
// 80k contribution per ticket => ceil(1,000,000 / 80,000) = 13
|
||||||
|
expect(r.breakEven).toEqual({ tickets: 13, ticketPrice: 100000, remaining: 9 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accounts for minimum spend, other income and fees', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
ticketPrice: 100000,
|
||||||
|
fees: [{ method: 'tpago', percentBp: 1000, fixedAmount: 0 }],
|
||||||
|
otherIncome: [{ id: 'i', description: 's', amount: 90000 }],
|
||||||
|
expenses: [expense({ calcType: 'minimum_spend', unitAmount: 30000, minimumAmount: 900000 })],
|
||||||
|
}));
|
||||||
|
// 90k net per ticket, 90k income: 9 tickets => 810k + 90k = 900k = minimum
|
||||||
|
expect(r.breakEven.tickets).toBe(9);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is null when a ticket cannot cover its own variable cost, or the price is 0', () => {
|
||||||
|
expect(calculateEventFinance(input({ expenses: [expense({ calcType: 'per_ticket_sold', unitAmount: 150000 }), expense({ unitAmount: 1 })] })).breakEven.tickets).toBeNull();
|
||||||
|
expect(calculateEventFinance(input({ ticketPrice: 0, expenses: [expense({ unitAmount: 1 })] })).breakEven.tickets).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is 0 when there is nothing to cover', () => {
|
||||||
|
expect(calculateEventFinance(input()).breakEven.tickets).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('paymentFee', () => {
|
||||||
|
it('adds the fixed part and skips free payments', () => {
|
||||||
|
expect(paymentFee(100000, { method: 'pos', percentBp: 290, fixedAmount: 500 })).toBe(3400);
|
||||||
|
expect(paymentFee(0, { method: 'pos', percentBp: 290, fixedAmount: 500 })).toBe(0);
|
||||||
|
expect(paymentFee(100000, undefined)).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Regression scenarios pinned while reworking the Finance tab UI: the UI now
|
||||||
|
// derives its waterfall, break-even and lifecycle from these results, so the
|
||||||
|
// numbers themselves must not move.
|
||||||
|
describe('calculateEventFinance: pinned scenarios', () => {
|
||||||
|
const tpagoFee = { method: 'tpago', percentBp: 290, fixedAmount: 0 };
|
||||||
|
|
||||||
|
it('no expenses: profit is revenue after fees and break-even is 0', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
ticketPrice: 50000, ticketsSold: 4, checkedIn: 4,
|
||||||
|
payments: [pay(50000), pay(50000), pay(50000), pay(50000)],
|
||||||
|
fees: [tpagoFee],
|
||||||
|
}));
|
||||||
|
expect(r.revenue).toMatchObject({ gross: 200000, presale: 200000, door: 0, fees: 5800, sales: 200000, net: 194200 });
|
||||||
|
expect(r.expenses.total).toBe(0);
|
||||||
|
expect(r.profit).toBe(194200);
|
||||||
|
expect(r.breakEven).toEqual({ tickets: 0, ticketPrice: 50000, remaining: 0 });
|
||||||
|
expect(r.split).toEqual({ distributable: 194200, partners: [], organization: 194200 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a loss: planned and paid costs above revenue, break-even beyond sales', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
ticketPrice: 50000, ticketsSold: 4, checkedIn: 4,
|
||||||
|
payments: [pay(50000), pay(50000), pay(50000), pay(50000, { provider: 'cash', source: 'door' })],
|
||||||
|
fees: [tpagoFee],
|
||||||
|
expenses: [
|
||||||
|
expense({ calcType: 'fixed', quantity: 1, unitAmount: 300000, status: 'paid' }),
|
||||||
|
expense({ calcType: 'per_checked_in', unitAmount: 10000, status: 'planned' }),
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
expect(r.revenue).toMatchObject({ gross: 200000, presale: 150000, door: 50000, fees: 4350, net: 195650 });
|
||||||
|
expect(r.expenses).toMatchObject({ total: 340000, paid: 300000, planned: 40000 });
|
||||||
|
expect(r.profit).toBe(-144350);
|
||||||
|
// 218 bp fee mix: each extra ticket adds 50000 - 1090 - 10000 = 38910 against 300000 fixed.
|
||||||
|
expect(r.breakEven).toEqual({ tickets: 8, ticketPrice: 50000, remaining: 4 });
|
||||||
|
expect(r.split.organization).toBe(-144350);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('partners: fixed deal first, then percent of what is left, reimbursement on top', () => {
|
||||||
|
const ana = partner({ name: 'Ana', shareType: 'percent_profit', percentBp: 3000 });
|
||||||
|
const venue = partner({ name: 'Venue Co', shareType: 'fixed', fixedAmount: 100000 });
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
ticketPrice: 100000, ticketsSold: 10, checkedIn: 9,
|
||||||
|
payments: Array.from({ length: 10 }, () => pay(100000, { provider: 'bank_transfer' })),
|
||||||
|
otherIncome: [{ id: 'i1', description: 'Sponsor', amount: 50000 }],
|
||||||
|
expenses: [
|
||||||
|
expense({ calcType: 'fixed', quantity: 1, unitAmount: 200000, status: 'paid' }),
|
||||||
|
expense({ calcType: 'fixed', quantity: 1, unitAmount: 150000, status: 'paid', paidByPartnerId: ana.id }),
|
||||||
|
],
|
||||||
|
partners: [ana, venue],
|
||||||
|
}));
|
||||||
|
expect(r.revenue).toMatchObject({ gross: 1000000, fees: 0, otherIncome: 50000, net: 1050000 });
|
||||||
|
expect(r.profit).toBe(700000);
|
||||||
|
expect(r.split.distributable).toBe(600000);
|
||||||
|
const byName = Object.fromEntries(r.split.partners.map((p) => [p.name, p]));
|
||||||
|
expect(byName.Ana).toMatchObject({ share: 180000, reimbursement: 150000, payout: 330000 });
|
||||||
|
expect(byName['Venue Co']).toMatchObject({ share: 100000, reimbursement: 0, payout: 100000 });
|
||||||
|
expect(r.split.organization).toBe(420000);
|
||||||
|
expect(r.breakEven).toEqual({ tickets: 3, ticketPrice: 100000, remaining: 0 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('calculateEventFinance: break-even edges', () => {
|
||||||
|
it('lands exactly on the ticket where profit reaches 0', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
ticketPrice: 100000, ticketsSold: 1,
|
||||||
|
expenses: [expense({ calcType: 'fixed', quantity: 1, unitAmount: 300000 })],
|
||||||
|
}));
|
||||||
|
expect(r.breakEven).toEqual({ tickets: 3, ticketPrice: 100000, remaining: 2 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports 0 remaining once sales pass break-even', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
ticketPrice: 100000, ticketsSold: 5,
|
||||||
|
expenses: [expense({ calcType: 'fixed', quantity: 1, unitAmount: 250000 })],
|
||||||
|
}));
|
||||||
|
expect(r.breakEven).toEqual({ tickets: 3, ticketPrice: 100000, remaining: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('other income can cover costs before any ticket', () => {
|
||||||
|
const r = calculateEventFinance(input({
|
||||||
|
ticketPrice: 100000,
|
||||||
|
otherIncome: [{ id: 'i', description: 'Sponsor', amount: 500000 }],
|
||||||
|
expenses: [expense({ calcType: 'fixed', quantity: 1, unitAmount: 300000 })],
|
||||||
|
}));
|
||||||
|
expect(r.breakEven.tickets).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,395 @@
|
|||||||
|
/**
|
||||||
|
* Event P&L: a pure function from an event's money facts to the numbers the
|
||||||
|
* Finance tab, the partner statements and the finalize snapshot show.
|
||||||
|
*
|
||||||
|
* Everything is whole PYG. Percentages arrive in basis points (290 = 2.90%)
|
||||||
|
* and every percentage product is rounded to the nearest guaraní once, at the
|
||||||
|
* line it applies to, so totals always equal the sum of the lines shown.
|
||||||
|
*
|
||||||
|
* The waterfall:
|
||||||
|
* gross (paid + later-refunded payments)
|
||||||
|
* - refunds
|
||||||
|
* - payment fees (per payment, from payment_method_fees by provider)
|
||||||
|
* + other income
|
||||||
|
* = net revenue
|
||||||
|
* - expenses (planned and paid; auto rows follow the current counts unless locked)
|
||||||
|
* = profit / loss
|
||||||
|
* then the split:
|
||||||
|
* 1. fixed amounts and revenue shares are owed regardless of profit, so they
|
||||||
|
* come off first and leave the distributable profit;
|
||||||
|
* 2. profit shares are taken from the distributable profit, applying each
|
||||||
|
* partner's loss rule when it is negative;
|
||||||
|
* 3. the organization keeps the remainder.
|
||||||
|
* Reimbursements for costs a partner fronted are already inside expenses (so
|
||||||
|
* they are not deducted twice); they are added to that partner's payout.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const CALC_TYPES = ['fixed', 'per_ticket_sold', 'per_checked_in', 'percent_of_revenue', 'minimum_spend'] as const;
|
||||||
|
export type CalcType = (typeof CALC_TYPES)[number];
|
||||||
|
|
||||||
|
export const SHARE_TYPES = ['percent_profit', 'percent_revenue', 'fixed', 'fixed_plus_percent_above_threshold'] as const;
|
||||||
|
export type ShareType = (typeof SHARE_TYPES)[number];
|
||||||
|
|
||||||
|
export const LOSS_RULES = ['proportional', 'none', 'capped'] as const;
|
||||||
|
export type LossRule = (typeof LOSS_RULES)[number];
|
||||||
|
|
||||||
|
export interface FinancePayment {
|
||||||
|
id: string;
|
||||||
|
/** PYG recorded at payment time (Lightning included). */
|
||||||
|
amount: number;
|
||||||
|
/** payments.provider: tpago | bank_transfer | lightning | cash | pos | bancard */
|
||||||
|
provider: string;
|
||||||
|
source: 'presale' | 'door';
|
||||||
|
status: 'paid' | 'refunded';
|
||||||
|
paidAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FinanceExpense {
|
||||||
|
id: string;
|
||||||
|
description: string;
|
||||||
|
categoryId: string | null;
|
||||||
|
calcType: CalcType;
|
||||||
|
quantity: number;
|
||||||
|
unitAmount: number;
|
||||||
|
percentBp: number;
|
||||||
|
minimumAmount: number;
|
||||||
|
/** Stored amount; authoritative for locked rows. */
|
||||||
|
computedAmount: number;
|
||||||
|
isLocked: boolean;
|
||||||
|
status: 'planned' | 'paid';
|
||||||
|
/** null = paid by the organization. */
|
||||||
|
paidByPartnerId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FinanceOtherIncome {
|
||||||
|
id: string;
|
||||||
|
description: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FeeRule {
|
||||||
|
method: string;
|
||||||
|
percentBp: number;
|
||||||
|
fixedAmount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FinancePartner {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
shareType: ShareType;
|
||||||
|
percentBp: number;
|
||||||
|
fixedAmount: number;
|
||||||
|
thresholdAmount: number;
|
||||||
|
lossRule: LossRule;
|
||||||
|
lossCapAmount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FinanceInput {
|
||||||
|
/** Current online ticket price, used for break-even. */
|
||||||
|
ticketPrice: number;
|
||||||
|
/** Paid, non-cancelled tickets (comps excluded). */
|
||||||
|
ticketsSold: number;
|
||||||
|
/** Checked-in tickets, comps included (they still eat and drink). */
|
||||||
|
checkedIn: number;
|
||||||
|
payments: FinancePayment[];
|
||||||
|
expenses: FinanceExpense[];
|
||||||
|
otherIncome: FinanceOtherIncome[];
|
||||||
|
fees: FeeRule[];
|
||||||
|
partners: FinancePartner[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExpenseLine {
|
||||||
|
id: string;
|
||||||
|
/** Count the amount was derived from (units, tickets or check-ins). */
|
||||||
|
quantity: number;
|
||||||
|
amount: number;
|
||||||
|
/** True when the amount follows ticket counts / revenue. */
|
||||||
|
auto: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MethodTotals {
|
||||||
|
method: string;
|
||||||
|
count: number;
|
||||||
|
gross: number;
|
||||||
|
refunds: number;
|
||||||
|
fees: number;
|
||||||
|
net: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PartnerResult {
|
||||||
|
partnerId: string;
|
||||||
|
name: string;
|
||||||
|
shareType: ShareType;
|
||||||
|
/** What the base amount was for the percentage part (profit or revenue). */
|
||||||
|
basis: number;
|
||||||
|
/** Positive = paid to the partner; negative = the partner carries part of a loss. */
|
||||||
|
share: number;
|
||||||
|
reimbursement: number;
|
||||||
|
/** share + reimbursement. Negative means the partner owes the organization. */
|
||||||
|
payout: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FinanceResult {
|
||||||
|
counts: { ticketsSold: number; checkedIn: number; payments: number };
|
||||||
|
revenue: {
|
||||||
|
gross: number;
|
||||||
|
presale: number;
|
||||||
|
door: number;
|
||||||
|
refunds: number;
|
||||||
|
fees: number;
|
||||||
|
otherIncome: number;
|
||||||
|
/** gross - refunds: the base for revenue percentages. */
|
||||||
|
sales: number;
|
||||||
|
net: number;
|
||||||
|
byMethod: MethodTotals[];
|
||||||
|
};
|
||||||
|
expenses: {
|
||||||
|
lines: ExpenseLine[];
|
||||||
|
total: number;
|
||||||
|
planned: number;
|
||||||
|
paid: number;
|
||||||
|
byCategory: { categoryId: string | null; planned: number; paid: number; total: number }[];
|
||||||
|
};
|
||||||
|
profit: number;
|
||||||
|
breakEven: {
|
||||||
|
/** Tickets needed at ticketPrice for profit >= 0; null when unreachable. */
|
||||||
|
tickets: number | null;
|
||||||
|
ticketPrice: number;
|
||||||
|
/** Tickets still needed beyond those already sold. */
|
||||||
|
remaining: number | null;
|
||||||
|
};
|
||||||
|
split: {
|
||||||
|
/** Profit left after fixed amounts and revenue shares. */
|
||||||
|
distributable: number;
|
||||||
|
partners: PartnerResult[];
|
||||||
|
organization: number;
|
||||||
|
};
|
||||||
|
waterfall: { key: string; label?: string; amount: number }[];
|
||||||
|
/** Cumulative paid sales per day (YYYY-MM-DD, UTC). */
|
||||||
|
salesTimeline: { date: string; tickets: number; revenue: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Round half away from zero so a loss and a profit of the same size split symmetrically. */
|
||||||
|
export function roundPyg(value: number): number {
|
||||||
|
return Math.sign(value) * Math.round(Math.abs(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyBp(base: number, bp: number): number {
|
||||||
|
return roundPyg((base * bp) / 10000);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function paymentFee(amount: number, rule: FeeRule | undefined): number {
|
||||||
|
if (!rule || amount <= 0) return 0;
|
||||||
|
return applyBp(amount, rule.percentBp) + rule.fixedAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Amount for one expense row at the given counts. Locked rows keep their stored amount. */
|
||||||
|
export function expenseAmount(
|
||||||
|
e: Pick<FinanceExpense, 'calcType' | 'quantity' | 'unitAmount' | 'percentBp' | 'minimumAmount' | 'computedAmount' | 'isLocked'>,
|
||||||
|
ctx: { ticketsSold: number; checkedIn: number; sales: number },
|
||||||
|
): { quantity: number; amount: number } {
|
||||||
|
if (e.isLocked) return { quantity: e.quantity, amount: e.computedAmount };
|
||||||
|
switch (e.calcType) {
|
||||||
|
case 'per_ticket_sold':
|
||||||
|
return { quantity: ctx.ticketsSold, amount: e.unitAmount * ctx.ticketsSold };
|
||||||
|
case 'per_checked_in':
|
||||||
|
return { quantity: ctx.checkedIn, amount: e.unitAmount * ctx.checkedIn };
|
||||||
|
case 'percent_of_revenue':
|
||||||
|
return { quantity: 1, amount: applyBp(Math.max(0, ctx.sales), e.percentBp) };
|
||||||
|
case 'minimum_spend':
|
||||||
|
return { quantity: ctx.checkedIn, amount: Math.max(e.minimumAmount, e.unitAmount * ctx.checkedIn) };
|
||||||
|
case 'fixed':
|
||||||
|
default:
|
||||||
|
return { quantity: e.quantity, amount: e.unitAmount * e.quantity };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isAutoCalc(calcType: CalcType): boolean {
|
||||||
|
return calcType !== 'fixed';
|
||||||
|
}
|
||||||
|
|
||||||
|
function computePartners(profit: number, sales: number, partners: FinancePartner[], reimbursements: Map<string, number>) {
|
||||||
|
// Pass 1: amounts owed regardless of profit.
|
||||||
|
const upfront = new Map<string, number>();
|
||||||
|
for (const p of partners) {
|
||||||
|
let owed = 0;
|
||||||
|
if (p.shareType === 'fixed' || p.shareType === 'fixed_plus_percent_above_threshold') owed = p.fixedAmount;
|
||||||
|
else if (p.shareType === 'percent_revenue') owed = applyBp(Math.max(0, sales), p.percentBp);
|
||||||
|
upfront.set(p.id, owed);
|
||||||
|
}
|
||||||
|
const distributable = profit - [...upfront.values()].reduce((a, b) => a + b, 0);
|
||||||
|
|
||||||
|
// Pass 2: profit-based parts, taken from the distributable profit.
|
||||||
|
let profitParts = 0;
|
||||||
|
const results: PartnerResult[] = partners.map((p) => {
|
||||||
|
let basis = p.shareType === 'percent_revenue' ? sales : distributable;
|
||||||
|
let profitPart = 0;
|
||||||
|
if (p.shareType === 'percent_profit') {
|
||||||
|
const raw = applyBp(distributable, p.percentBp);
|
||||||
|
if (distributable >= 0 || p.lossRule === 'proportional') profitPart = raw;
|
||||||
|
else if (p.lossRule === 'capped') profitPart = Math.max(raw, -Math.abs(p.lossCapAmount));
|
||||||
|
} else if (p.shareType === 'fixed_plus_percent_above_threshold') {
|
||||||
|
basis = Math.max(0, distributable - p.thresholdAmount);
|
||||||
|
profitPart = applyBp(basis, p.percentBp);
|
||||||
|
}
|
||||||
|
profitParts += profitPart;
|
||||||
|
const share = (upfront.get(p.id) || 0) + profitPart;
|
||||||
|
const reimbursement = reimbursements.get(p.id) || 0;
|
||||||
|
return { partnerId: p.id, name: p.name, shareType: p.shareType, basis, share, reimbursement, payout: share + reimbursement };
|
||||||
|
});
|
||||||
|
|
||||||
|
return { distributable, partners: results, organization: distributable - profitParts };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Profit at a hypothetical ticket count, for break-even. Assumes every sold ticket checks in. */
|
||||||
|
function projectedProfit(n: number, input: FinanceInput, feeRate: { bp: number; fixed: number }, otherIncome: number): number {
|
||||||
|
const sales = n * input.ticketPrice;
|
||||||
|
const fees = n > 0 && input.ticketPrice > 0 ? n * (applyBp(input.ticketPrice, feeRate.bp) + feeRate.fixed) : 0;
|
||||||
|
const ctx = { ticketsSold: n, checkedIn: n, sales };
|
||||||
|
const expenses = input.expenses.reduce((sum, e) => sum + expenseAmount(e, ctx).amount, 0);
|
||||||
|
return sales - fees + otherIncome - expenses;
|
||||||
|
}
|
||||||
|
|
||||||
|
const BREAK_EVEN_SEARCH_LIMIT = 100000;
|
||||||
|
|
||||||
|
export function calculateEventFinance(input: FinanceInput): FinanceResult {
|
||||||
|
const feeByMethod = new Map(input.fees.map((f) => [f.method, f]));
|
||||||
|
|
||||||
|
// ---- Revenue
|
||||||
|
const methods = new Map<string, MethodTotals>();
|
||||||
|
let gross = 0, presale = 0, door = 0, refunds = 0, fees = 0;
|
||||||
|
for (const p of input.payments) {
|
||||||
|
const m = methods.get(p.provider) || { method: p.provider, count: 0, gross: 0, refunds: 0, fees: 0, net: 0 };
|
||||||
|
const fee = p.status === 'paid' ? paymentFee(p.amount, feeByMethod.get(p.provider)) : 0;
|
||||||
|
m.count += 1;
|
||||||
|
m.gross += p.amount;
|
||||||
|
gross += p.amount;
|
||||||
|
if (p.source === 'door') door += p.amount; else presale += p.amount;
|
||||||
|
if (p.status === 'refunded') {
|
||||||
|
// Refunds are whole-payment; the processor fee on a refunded payment is
|
||||||
|
// not tracked, so it is treated as returned too.
|
||||||
|
m.refunds += p.amount;
|
||||||
|
refunds += p.amount;
|
||||||
|
}
|
||||||
|
m.fees += fee;
|
||||||
|
fees += fee;
|
||||||
|
m.net = m.gross - m.refunds - m.fees;
|
||||||
|
methods.set(p.provider, m);
|
||||||
|
}
|
||||||
|
const otherIncome = input.otherIncome.reduce((sum, i) => sum + i.amount, 0);
|
||||||
|
const sales = gross - refunds;
|
||||||
|
const net = sales - fees + otherIncome;
|
||||||
|
|
||||||
|
// ---- Expenses
|
||||||
|
const ctx = { ticketsSold: input.ticketsSold, checkedIn: input.checkedIn, sales };
|
||||||
|
const lines: ExpenseLine[] = [];
|
||||||
|
const byCategory = new Map<string | null, { categoryId: string | null; planned: number; paid: number; total: number }>();
|
||||||
|
const reimbursements = new Map<string, number>();
|
||||||
|
let planned = 0, paid = 0;
|
||||||
|
for (const e of input.expenses) {
|
||||||
|
const { quantity, amount } = expenseAmount(e, ctx);
|
||||||
|
lines.push({ id: e.id, quantity, amount, auto: isAutoCalc(e.calcType) && !e.isLocked });
|
||||||
|
const cat = byCategory.get(e.categoryId) || { categoryId: e.categoryId, planned: 0, paid: 0, total: 0 };
|
||||||
|
if (e.status === 'paid') {
|
||||||
|
paid += amount;
|
||||||
|
cat.paid += amount;
|
||||||
|
if (e.paidByPartnerId) reimbursements.set(e.paidByPartnerId, (reimbursements.get(e.paidByPartnerId) || 0) + amount);
|
||||||
|
} else {
|
||||||
|
planned += amount;
|
||||||
|
cat.planned += amount;
|
||||||
|
}
|
||||||
|
cat.total += amount;
|
||||||
|
byCategory.set(e.categoryId, cat);
|
||||||
|
}
|
||||||
|
const expenseTotal = planned + paid;
|
||||||
|
const profit = net - expenseTotal;
|
||||||
|
|
||||||
|
// ---- Break-even at the current price, using the fee mix seen so far
|
||||||
|
// (or the most expensive configured method before any sales).
|
||||||
|
const paidPayments = input.payments.filter((p) => p.status === 'paid' && p.amount > 0);
|
||||||
|
const feeRate = paidPayments.length > 0 && gross > 0
|
||||||
|
? { bp: Math.round((fees / Math.max(1, sales)) * 10000), fixed: 0 }
|
||||||
|
: input.fees.reduce((worst, f) => (f.percentBp > worst.bp ? { bp: f.percentBp, fixed: f.fixedAmount } : worst), { bp: 0, fixed: 0 });
|
||||||
|
const profitAt = (n: number) => projectedProfit(n, input, feeRate, otherIncome);
|
||||||
|
let breakEvenTickets: number | null = null;
|
||||||
|
if (input.ticketPrice > 0) {
|
||||||
|
// Profit is non-decreasing in n for every calc type, so a doubling search
|
||||||
|
// followed by bisection finds the smallest n with profit >= 0.
|
||||||
|
if (profitAt(0) >= 0) {
|
||||||
|
breakEvenTickets = 0;
|
||||||
|
} else {
|
||||||
|
let lo = 0; // profitAt(lo) < 0
|
||||||
|
let hi = 1;
|
||||||
|
while (hi < BREAK_EVEN_SEARCH_LIMIT && profitAt(hi) < 0) {
|
||||||
|
lo = hi;
|
||||||
|
hi = Math.min(hi * 2, BREAK_EVEN_SEARCH_LIMIT);
|
||||||
|
}
|
||||||
|
if (profitAt(hi) >= 0) {
|
||||||
|
while (lo + 1 < hi) {
|
||||||
|
const mid = Math.floor((lo + hi) / 2);
|
||||||
|
if (profitAt(mid) >= 0) hi = mid; else lo = mid;
|
||||||
|
}
|
||||||
|
breakEvenTickets = hi;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Split
|
||||||
|
const split = computePartners(profit, sales, input.partners, reimbursements);
|
||||||
|
|
||||||
|
// ---- Waterfall (signed amounts, in display order)
|
||||||
|
const waterfall: FinanceResult['waterfall'] = [
|
||||||
|
{ key: 'gross', amount: gross },
|
||||||
|
{ key: 'refunds', amount: -refunds },
|
||||||
|
{ key: 'fees', amount: -fees },
|
||||||
|
{ key: 'otherIncome', amount: otherIncome },
|
||||||
|
{ key: 'net', amount: net },
|
||||||
|
{ key: 'expenses', amount: -expenseTotal },
|
||||||
|
{ key: 'profit', amount: profit },
|
||||||
|
...split.partners.map((p) => ({ key: `partner:${p.partnerId}`, label: p.name, amount: -p.share })),
|
||||||
|
{ key: 'organization', amount: split.organization },
|
||||||
|
];
|
||||||
|
|
||||||
|
// ---- Cumulative sales per day
|
||||||
|
const byDay = new Map<string, { tickets: number; revenue: number }>();
|
||||||
|
for (const p of input.payments) {
|
||||||
|
if (p.status !== 'paid' || !p.paidAt) continue;
|
||||||
|
const day = new Date(p.paidAt).toISOString().slice(0, 10);
|
||||||
|
const d = byDay.get(day) || { tickets: 0, revenue: 0 };
|
||||||
|
d.tickets += 1;
|
||||||
|
d.revenue += p.amount;
|
||||||
|
byDay.set(day, d);
|
||||||
|
}
|
||||||
|
let runTickets = 0, runRevenue = 0;
|
||||||
|
const salesTimeline = [...byDay.entries()]
|
||||||
|
.sort(([a], [b]) => a.localeCompare(b))
|
||||||
|
.map(([date, d]) => {
|
||||||
|
runTickets += d.tickets;
|
||||||
|
runRevenue += d.revenue;
|
||||||
|
return { date, tickets: runTickets, revenue: runRevenue };
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
counts: { ticketsSold: input.ticketsSold, checkedIn: input.checkedIn, payments: input.payments.length },
|
||||||
|
revenue: {
|
||||||
|
gross, presale, door, refunds, fees, otherIncome, sales, net,
|
||||||
|
byMethod: [...methods.values()].sort((a, b) => b.gross - a.gross),
|
||||||
|
},
|
||||||
|
expenses: {
|
||||||
|
lines,
|
||||||
|
total: expenseTotal,
|
||||||
|
planned,
|
||||||
|
paid,
|
||||||
|
byCategory: [...byCategory.values()].sort((a, b) => b.total - a.total),
|
||||||
|
},
|
||||||
|
profit,
|
||||||
|
breakEven: {
|
||||||
|
tickets: breakEvenTickets,
|
||||||
|
ticketPrice: input.ticketPrice,
|
||||||
|
remaining: breakEvenTickets === null ? null : Math.max(0, breakEvenTickets - input.ticketsSold),
|
||||||
|
},
|
||||||
|
split,
|
||||||
|
waterfall,
|
||||||
|
salesTimeline,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
// Reads an event's money facts from the database and runs calculateEventFinance.
|
||||||
|
// Once an event is finalized, the frozen snapshot is returned instead so the
|
||||||
|
// numbers partners were paid on never drift with later ticket changes.
|
||||||
|
|
||||||
|
import { and, eq, inArray, sql } from 'drizzle-orm';
|
||||||
|
import {
|
||||||
|
db, dbAll, dbGet, events, tickets, payments, eventExpenses, eventOtherIncome, eventPartners,
|
||||||
|
paymentMethodFees, eventFinanceState, users,
|
||||||
|
} from '../../db/index.js';
|
||||||
|
import { calculateEventFinance, type FinanceInput, type FinanceResult, type CalcType, type ShareType, type LossRule } from './calculate.js';
|
||||||
|
|
||||||
|
export const num = (v: any): number => {
|
||||||
|
const n = typeof v === 'string' ? parseFloat(v) : Number(v);
|
||||||
|
return Number.isFinite(n) ? n : 0;
|
||||||
|
};
|
||||||
|
export const pyg = (v: any): number => Math.round(num(v));
|
||||||
|
export const iso = (v: any): string | null => {
|
||||||
|
if (!v) return null;
|
||||||
|
const d = v instanceof Date ? v : new Date(v);
|
||||||
|
return Number.isNaN(d.getTime()) ? null : d.toISOString();
|
||||||
|
};
|
||||||
|
export const bool = (v: any): boolean => v === true || v === 1 || v === '1';
|
||||||
|
|
||||||
|
export type FinanceStatus = 'open' | 'finalized' | 'paid_out';
|
||||||
|
|
||||||
|
export interface FinanceSnapshot {
|
||||||
|
version: 1;
|
||||||
|
computedAt: string;
|
||||||
|
result: FinanceResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeExpense(e: any) {
|
||||||
|
return {
|
||||||
|
id: e.id,
|
||||||
|
eventId: e.eventId,
|
||||||
|
categoryId: e.categoryId ?? null,
|
||||||
|
templateId: e.templateId ?? null,
|
||||||
|
description: e.description,
|
||||||
|
calcType: e.calcType as CalcType,
|
||||||
|
quantity: pyg(e.quantity),
|
||||||
|
unitAmount: pyg(e.unitAmount),
|
||||||
|
percentBp: pyg(e.percentBp),
|
||||||
|
minimumAmount: pyg(e.minimumAmount),
|
||||||
|
computedAmount: pyg(e.computedAmount),
|
||||||
|
isLocked: bool(e.isLocked),
|
||||||
|
status: e.status as 'planned' | 'paid',
|
||||||
|
paidByPartnerId: e.paidByPartnerId ?? null,
|
||||||
|
receiptUrl: e.receiptUrl ?? null,
|
||||||
|
expenseDate: iso(e.expenseDate),
|
||||||
|
createdBy: e.createdBy ?? null,
|
||||||
|
updatedBy: e.updatedBy ?? null,
|
||||||
|
createdAt: iso(e.createdAt),
|
||||||
|
updatedAt: iso(e.updatedAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializePartner(p: any, userName?: string | null) {
|
||||||
|
return {
|
||||||
|
id: p.id,
|
||||||
|
eventId: p.eventId,
|
||||||
|
userId: p.userId ?? null,
|
||||||
|
externalName: p.externalName ?? null,
|
||||||
|
name: p.externalName || userName || 'Partner',
|
||||||
|
roleLabel: p.roleLabel ?? null,
|
||||||
|
shareType: p.shareType as ShareType,
|
||||||
|
percentBp: pyg(p.percentBp),
|
||||||
|
fixedAmount: pyg(p.fixedAmount),
|
||||||
|
thresholdAmount: pyg(p.thresholdAmount),
|
||||||
|
lossRule: p.lossRule as LossRule,
|
||||||
|
lossCapAmount: pyg(p.lossCapAmount),
|
||||||
|
payoutStatus: p.payoutStatus as 'pending' | 'paid',
|
||||||
|
payoutDate: iso(p.payoutDate),
|
||||||
|
payoutMethod: p.payoutMethod ?? null,
|
||||||
|
payoutNote: p.payoutNote ?? null,
|
||||||
|
createdAt: iso(p.createdAt),
|
||||||
|
updatedAt: iso(p.updatedAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeIncome(i: any) {
|
||||||
|
return {
|
||||||
|
id: i.id,
|
||||||
|
eventId: i.eventId,
|
||||||
|
description: i.description,
|
||||||
|
amount: pyg(i.amount),
|
||||||
|
createdBy: i.createdBy ?? null,
|
||||||
|
createdAt: iso(i.createdAt),
|
||||||
|
updatedAt: iso(i.updatedAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SerializedExpense = ReturnType<typeof serializeExpense>;
|
||||||
|
export type SerializedPartner = ReturnType<typeof serializePartner>;
|
||||||
|
export type SerializedIncome = ReturnType<typeof serializeIncome>;
|
||||||
|
|
||||||
|
export async function getFinanceState(eventId: string) {
|
||||||
|
const row = await dbGet<any>((db as any).select().from(eventFinanceState).where(eq((eventFinanceState as any).eventId, eventId)));
|
||||||
|
let snapshot: FinanceSnapshot | null = null;
|
||||||
|
if (row?.snapshotJson) {
|
||||||
|
try { snapshot = JSON.parse(row.snapshotJson); } catch { snapshot = null; }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
exists: !!row,
|
||||||
|
status: (row?.status || 'open') as FinanceStatus,
|
||||||
|
finalizedAt: iso(row?.finalizedAt),
|
||||||
|
finalizedBy: row?.finalizedBy ?? null,
|
||||||
|
snapshot,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadPartners(eventId: string): Promise<SerializedPartner[]> {
|
||||||
|
const rows = await dbAll<any>((db as any).select().from(eventPartners).where(eq((eventPartners as any).eventId, eventId)));
|
||||||
|
const userIds = [...new Set(rows.map((r: any) => r.userId).filter(Boolean))] as string[];
|
||||||
|
const names = new Map<string, string>();
|
||||||
|
if (userIds.length > 0) {
|
||||||
|
const us = await dbAll<any>(
|
||||||
|
(db as any).select({ id: (users as any).id, name: (users as any).name }).from(users).where(inArray((users as any).id, userIds))
|
||||||
|
);
|
||||||
|
for (const u of us) names.set(u.id, u.name);
|
||||||
|
}
|
||||||
|
return rows
|
||||||
|
.map((r: any) => serializePartner(r, r.userId ? names.get(r.userId) : null))
|
||||||
|
.sort((a, b) => (a.createdAt || '').localeCompare(b.createdAt || ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadExpenses(eventId: string): Promise<SerializedExpense[]> {
|
||||||
|
const rows = await dbAll<any>((db as any).select().from(eventExpenses).where(eq((eventExpenses as any).eventId, eventId)));
|
||||||
|
return rows
|
||||||
|
.map(serializeExpense)
|
||||||
|
.sort((a, b) => (a.createdAt || '').localeCompare(b.createdAt || ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadOtherIncome(eventId: string): Promise<SerializedIncome[]> {
|
||||||
|
const rows = await dbAll<any>((db as any).select().from(eventOtherIncome).where(eq((eventOtherIncome as any).eventId, eventId)));
|
||||||
|
return rows
|
||||||
|
.map(serializeIncome)
|
||||||
|
.sort((a, b) => (a.createdAt || '').localeCompare(b.createdAt || ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadFeeRules() {
|
||||||
|
const rows = await dbAll<any>((db as any).select().from(paymentMethodFees));
|
||||||
|
return rows.map((r: any) => ({
|
||||||
|
method: r.method as string,
|
||||||
|
percentBp: pyg(r.percentBp),
|
||||||
|
fixedAmount: pyg(r.fixedAmount),
|
||||||
|
updatedAt: iso(r.updatedAt),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ticket counts the auto-calculated expenses follow. */
|
||||||
|
export async function loadTicketCounts(eventId: string) {
|
||||||
|
const row = await dbGet<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({
|
||||||
|
sold: sql<number>`sum(case when ${(tickets as any).status} in ('confirmed', 'checked_in') and ${(tickets as any).paymentStatus} = 'paid' then 1 else 0 end)`,
|
||||||
|
checkedIn: sql<number>`sum(case when ${(tickets as any).status} = 'checked_in' then 1 else 0 end)`,
|
||||||
|
})
|
||||||
|
.from(tickets)
|
||||||
|
.where(eq((tickets as any).eventId, eventId))
|
||||||
|
);
|
||||||
|
return { ticketsSold: Number(row?.sold || 0), checkedIn: Number(row?.checkedIn || 0) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function buildFinanceInput(eventId: string, event: any) {
|
||||||
|
const [counts, payRows, expenses, otherIncome, partners, fees] = await Promise.all([
|
||||||
|
loadTicketCounts(eventId),
|
||||||
|
dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({
|
||||||
|
id: (payments as any).id,
|
||||||
|
amount: (payments as any).amount,
|
||||||
|
provider: (payments as any).provider,
|
||||||
|
source: (payments as any).source,
|
||||||
|
status: (payments as any).status,
|
||||||
|
paidAt: (payments as any).paidAt,
|
||||||
|
createdAt: (payments as any).createdAt,
|
||||||
|
})
|
||||||
|
.from(payments)
|
||||||
|
.innerJoin(tickets, eq((payments as any).ticketId, (tickets as any).id))
|
||||||
|
.where(and(
|
||||||
|
eq((tickets as any).eventId, eventId),
|
||||||
|
inArray((payments as any).status, ['paid', 'refunded'])
|
||||||
|
))
|
||||||
|
),
|
||||||
|
loadExpenses(eventId),
|
||||||
|
loadOtherIncome(eventId),
|
||||||
|
loadPartners(eventId),
|
||||||
|
loadFeeRules(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const input: FinanceInput = {
|
||||||
|
ticketPrice: pyg(event.price),
|
||||||
|
ticketsSold: counts.ticketsSold,
|
||||||
|
checkedIn: counts.checkedIn,
|
||||||
|
payments: payRows
|
||||||
|
.map((p: any) => ({
|
||||||
|
id: p.id,
|
||||||
|
amount: pyg(p.amount),
|
||||||
|
provider: p.provider,
|
||||||
|
source: p.source === 'door' ? 'door' as const : 'presale' as const,
|
||||||
|
status: p.status as 'paid' | 'refunded',
|
||||||
|
paidAt: iso(p.paidAt) || iso(p.createdAt),
|
||||||
|
}))
|
||||||
|
// Comps are recorded as 0 PYG payments; they are not sales.
|
||||||
|
.filter((p) => p.amount > 0),
|
||||||
|
expenses: expenses.map((e) => ({
|
||||||
|
id: e.id, description: e.description, categoryId: e.categoryId, calcType: e.calcType, quantity: e.quantity,
|
||||||
|
unitAmount: e.unitAmount, percentBp: e.percentBp, minimumAmount: e.minimumAmount, computedAmount: e.computedAmount,
|
||||||
|
isLocked: e.isLocked, status: e.status, paidByPartnerId: e.paidByPartnerId,
|
||||||
|
})),
|
||||||
|
otherIncome: otherIncome.map((i) => ({ id: i.id, description: i.description, amount: i.amount })),
|
||||||
|
fees,
|
||||||
|
partners: partners.map((p) => ({
|
||||||
|
id: p.id, name: p.name, shareType: p.shareType, percentBp: p.percentBp, fixedAmount: p.fixedAmount,
|
||||||
|
thresholdAmount: p.thresholdAmount, lossRule: p.lossRule, lossCapAmount: p.lossCapAmount,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
return { input, expenses, otherIncome, partners, counts };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getEvent(eventId: string) {
|
||||||
|
return dbGet<any>((db as any).select().from(events).where(eq((events as any).id, eventId)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The event's finance numbers plus the rows behind them. Uses the finalize
|
||||||
|
* snapshot when there is one; otherwise calculates live.
|
||||||
|
*/
|
||||||
|
export async function getEventFinance(eventId: string, event?: any) {
|
||||||
|
const ev = event || await getEvent(eventId);
|
||||||
|
if (!ev) return null;
|
||||||
|
const [state, built] = await Promise.all([getFinanceState(eventId), buildFinanceInput(eventId, ev)]);
|
||||||
|
const frozen = state.status !== 'open' && state.snapshot;
|
||||||
|
const result = frozen ? state.snapshot!.result : calculateEventFinance(built.input);
|
||||||
|
return {
|
||||||
|
event: ev,
|
||||||
|
state,
|
||||||
|
live: !frozen,
|
||||||
|
computedAt: frozen ? state.snapshot!.computedAt : new Date().toISOString(),
|
||||||
|
result,
|
||||||
|
expenses: built.expenses,
|
||||||
|
otherIncome: built.otherIncome,
|
||||||
|
partners: built.partners,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
// Partner statement PDF: the event P&L summary, the partner's deal, what they
|
||||||
|
// fronted, and the resulting payout. Uses the ticket PDF's brand helpers.
|
||||||
|
|
||||||
|
import {
|
||||||
|
COLORS, PAGE_W, PAGE_H, MARGIN, CONTENT_W, ACCENT_H, FOOTER_H, LOGO_RATIO,
|
||||||
|
getLogo, drawLabel, drawDivider, createDoc, collect, siteUrl,
|
||||||
|
} from '../pdf.js';
|
||||||
|
import type { FinanceResult, PartnerResult } from './calculate.js';
|
||||||
|
import type { SerializedExpense, SerializedPartner } from './load.js';
|
||||||
|
|
||||||
|
export function formatPygAmount(amount: number): string {
|
||||||
|
const sign = amount < 0 ? '-' : '';
|
||||||
|
return `${sign}${Math.abs(Math.round(amount)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.')} PYG`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pct = (bp: number) => `${(bp / 100).toLocaleString('es-PY', { maximumFractionDigits: 2 })}%`;
|
||||||
|
|
||||||
|
const STRINGS = {
|
||||||
|
en: {
|
||||||
|
title: 'Partner statement',
|
||||||
|
draft: 'DRAFT: the event is not finalized, numbers may still change.',
|
||||||
|
event: 'Event',
|
||||||
|
partner: 'Partner',
|
||||||
|
summary: 'Event summary',
|
||||||
|
gross: 'Gross ticket revenue',
|
||||||
|
refunds: 'Refunds',
|
||||||
|
fees: 'Payment fees',
|
||||||
|
otherIncome: 'Other income',
|
||||||
|
net: 'Net revenue',
|
||||||
|
expenses: 'Expenses',
|
||||||
|
profit: 'Profit / loss',
|
||||||
|
deal: 'Agreement',
|
||||||
|
share: 'Share',
|
||||||
|
reimbursements: 'Reimbursements (costs you paid)',
|
||||||
|
none: 'None',
|
||||||
|
payout: 'Total payout',
|
||||||
|
owes: 'Amount owed to the organization',
|
||||||
|
status: 'Payout status',
|
||||||
|
paid: 'Paid',
|
||||||
|
pending: 'Pending',
|
||||||
|
generated: 'Generated',
|
||||||
|
lossNote: { proportional: 'shares losses proportionally', none: 'does not share losses', capped: 'shares losses up to' },
|
||||||
|
shareTypes: {
|
||||||
|
percent_profit: (p: SerializedPartner) => `${pct(p.percentBp)} of profit`,
|
||||||
|
percent_revenue: (p: SerializedPartner) => `${pct(p.percentBp)} of ticket revenue`,
|
||||||
|
fixed: (p: SerializedPartner) => `Fixed ${formatPygAmount(p.fixedAmount)}`,
|
||||||
|
fixed_plus_percent_above_threshold: (p: SerializedPartner) =>
|
||||||
|
`${formatPygAmount(p.fixedAmount)} + ${pct(p.percentBp)} of profit above ${formatPygAmount(p.thresholdAmount)}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
es: {
|
||||||
|
title: 'Liquidación de socio',
|
||||||
|
draft: 'BORRADOR: el evento no está cerrado, los números pueden cambiar.',
|
||||||
|
event: 'Evento',
|
||||||
|
partner: 'Socio',
|
||||||
|
summary: 'Resumen del evento',
|
||||||
|
gross: 'Ingresos brutos por entradas',
|
||||||
|
refunds: 'Reembolsos',
|
||||||
|
fees: 'Comisiones de pago',
|
||||||
|
otherIncome: 'Otros ingresos',
|
||||||
|
net: 'Ingresos netos',
|
||||||
|
expenses: 'Gastos',
|
||||||
|
profit: 'Ganancia / pérdida',
|
||||||
|
deal: 'Acuerdo',
|
||||||
|
share: 'Participación',
|
||||||
|
reimbursements: 'Reembolsos (gastos que pagaste)',
|
||||||
|
none: 'Ninguno',
|
||||||
|
payout: 'Total a pagar',
|
||||||
|
owes: 'Monto adeudado a la organización',
|
||||||
|
status: 'Estado del pago',
|
||||||
|
paid: 'Pagado',
|
||||||
|
pending: 'Pendiente',
|
||||||
|
generated: 'Generado',
|
||||||
|
lossNote: { proportional: 'comparte pérdidas proporcionalmente', none: 'no comparte pérdidas', capped: 'comparte pérdidas hasta' },
|
||||||
|
shareTypes: {
|
||||||
|
percent_profit: (p: SerializedPartner) => `${pct(p.percentBp)} de la ganancia`,
|
||||||
|
percent_revenue: (p: SerializedPartner) => `${pct(p.percentBp)} de los ingresos por entradas`,
|
||||||
|
fixed: (p: SerializedPartner) => `Fijo ${formatPygAmount(p.fixedAmount)}`,
|
||||||
|
fixed_plus_percent_above_threshold: (p: SerializedPartner) =>
|
||||||
|
`${formatPygAmount(p.fixedAmount)} + ${pct(p.percentBp)} de la ganancia sobre ${formatPygAmount(p.thresholdAmount)}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export interface StatementData {
|
||||||
|
locale: 'en' | 'es';
|
||||||
|
event: { title: string; startDatetime: string | Date; location: string };
|
||||||
|
finalized: boolean;
|
||||||
|
timezone?: string;
|
||||||
|
result: FinanceResult;
|
||||||
|
partner: SerializedPartner;
|
||||||
|
line: PartnerResult | undefined;
|
||||||
|
frontedExpenses: SerializedExpense[];
|
||||||
|
/** Amount per expense id, from the same result. */
|
||||||
|
expenseAmounts: Map<string, number>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generatePartnerStatementPDF(data: StatementData): Promise<Buffer> {
|
||||||
|
const t = STRINGS[data.locale];
|
||||||
|
const doc = createDoc();
|
||||||
|
const done = collect(doc);
|
||||||
|
const tz = data.timezone || 'America/Asuncion';
|
||||||
|
const dateFmt = new Intl.DateTimeFormat(data.locale === 'es' ? 'es-PY' : 'en-US', { dateStyle: 'long', timeZone: tz });
|
||||||
|
|
||||||
|
doc.rect(0, 0, PAGE_W, PAGE_H).fill(COLORS.cream);
|
||||||
|
doc.rect(0, 0, PAGE_W, ACCENT_H).fill(COLORS.orange);
|
||||||
|
|
||||||
|
let y = MARGIN + 6;
|
||||||
|
const logo = getLogo();
|
||||||
|
if (logo) {
|
||||||
|
const w = 120;
|
||||||
|
doc.image(logo, MARGIN, y, { width: w });
|
||||||
|
y += w / LOGO_RATIO + 16;
|
||||||
|
} else {
|
||||||
|
doc.font('Helvetica-Bold').fontSize(18).fillColor(COLORS.navy).text('spanglish social', MARGIN, y);
|
||||||
|
y += 32;
|
||||||
|
}
|
||||||
|
|
||||||
|
doc.font('Helvetica-Bold').fontSize(22).fillColor(COLORS.navy).text(t.title, MARGIN, y, { width: CONTENT_W });
|
||||||
|
y += 32;
|
||||||
|
|
||||||
|
if (!data.finalized) {
|
||||||
|
doc.font('Helvetica-Bold').fontSize(9).fillColor(COLORS.orange).text(t.draft, MARGIN, y, { width: CONTENT_W });
|
||||||
|
y += 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
const col = CONTENT_W / 2;
|
||||||
|
drawLabel(doc, t.event, y, col - 12);
|
||||||
|
drawLabel(doc, t.partner, y, col, MARGIN + col);
|
||||||
|
y += 14;
|
||||||
|
doc.font('Helvetica-Bold').fontSize(12).fillColor(COLORS.navy);
|
||||||
|
doc.text(data.event.title, MARGIN, y, { width: col - 12 });
|
||||||
|
doc.text(data.partner.name, MARGIN + col, y, { width: col });
|
||||||
|
y += 16;
|
||||||
|
doc.font('Helvetica').fontSize(10).fillColor(COLORS.muted);
|
||||||
|
doc.text(`${dateFmt.format(new Date(data.event.startDatetime))} · ${data.event.location}`, MARGIN, y, { width: col - 12 });
|
||||||
|
if (data.partner.roleLabel) doc.text(data.partner.roleLabel, MARGIN + col, y, { width: col });
|
||||||
|
y += 34;
|
||||||
|
|
||||||
|
const row = (label: string, amount: number, opts: { bold?: boolean } = {}) => {
|
||||||
|
doc.font(opts.bold ? 'Helvetica-Bold' : 'Helvetica').fontSize(opts.bold ? 12 : 10.5).fillColor(COLORS.navy);
|
||||||
|
doc.text(label, MARGIN, y, { width: CONTENT_W - 160 });
|
||||||
|
doc.text(formatPygAmount(amount), MARGIN + CONTENT_W - 160, y, { width: 160, align: 'right' });
|
||||||
|
y += opts.bold ? 20 : 17;
|
||||||
|
};
|
||||||
|
|
||||||
|
drawLabel(doc, t.summary, y);
|
||||||
|
y += 16;
|
||||||
|
const r = data.result;
|
||||||
|
row(t.gross, r.revenue.gross);
|
||||||
|
if (r.revenue.refunds) row(t.refunds, -r.revenue.refunds);
|
||||||
|
row(t.fees, -r.revenue.fees);
|
||||||
|
if (r.revenue.otherIncome) row(t.otherIncome, r.revenue.otherIncome);
|
||||||
|
drawDivider(doc, y); y += 8;
|
||||||
|
row(t.net, r.revenue.net, { bold: true });
|
||||||
|
row(t.expenses, -r.expenses.total);
|
||||||
|
drawDivider(doc, y); y += 8;
|
||||||
|
row(t.profit, r.profit, { bold: true });
|
||||||
|
y += 18;
|
||||||
|
|
||||||
|
drawLabel(doc, t.deal, y);
|
||||||
|
y += 16;
|
||||||
|
let deal = t.shareTypes[data.partner.shareType](data.partner);
|
||||||
|
if (data.partner.shareType === 'percent_profit') {
|
||||||
|
deal += data.partner.lossRule === 'capped'
|
||||||
|
? ` · ${t.lossNote.capped} ${formatPygAmount(data.partner.lossCapAmount)}`
|
||||||
|
: ` · ${t.lossNote[data.partner.lossRule]}`;
|
||||||
|
}
|
||||||
|
doc.font('Helvetica').fontSize(10.5).fillColor(COLORS.navy).text(deal, MARGIN, y, { width: CONTENT_W });
|
||||||
|
y += 26;
|
||||||
|
|
||||||
|
const share = data.line?.share ?? 0;
|
||||||
|
const reimbursement = data.line?.reimbursement ?? 0;
|
||||||
|
const payout = data.line?.payout ?? 0;
|
||||||
|
row(t.share, share);
|
||||||
|
|
||||||
|
drawLabel(doc, t.reimbursements, y + 4);
|
||||||
|
y += 20;
|
||||||
|
if (data.frontedExpenses.length === 0) {
|
||||||
|
doc.font('Helvetica').fontSize(10).fillColor(COLORS.muted).text(t.none, MARGIN, y);
|
||||||
|
y += 16;
|
||||||
|
} else {
|
||||||
|
for (const e of data.frontedExpenses) {
|
||||||
|
doc.font('Helvetica').fontSize(10).fillColor(COLORS.muted);
|
||||||
|
doc.text(e.description, MARGIN + 10, y, { width: CONTENT_W - 170 });
|
||||||
|
doc.text(formatPygAmount(data.expenseAmounts.get(e.id) ?? e.computedAmount), MARGIN + CONTENT_W - 160, y, { width: 160, align: 'right' });
|
||||||
|
y += 15;
|
||||||
|
}
|
||||||
|
row(t.reimbursements, reimbursement);
|
||||||
|
}
|
||||||
|
y += 6;
|
||||||
|
drawDivider(doc, y); y += 10;
|
||||||
|
row(payout < 0 ? t.owes : t.payout, Math.abs(payout), { bold: true });
|
||||||
|
y += 6;
|
||||||
|
|
||||||
|
doc.font('Helvetica').fontSize(10).fillColor(COLORS.muted);
|
||||||
|
const status = data.partner.payoutStatus === 'paid'
|
||||||
|
? `${t.paid}${data.partner.payoutDate ? ` · ${dateFmt.format(new Date(data.partner.payoutDate))}` : ''}${data.partner.payoutMethod ? ` · ${data.partner.payoutMethod}` : ''}`
|
||||||
|
: t.pending;
|
||||||
|
doc.text(`${t.status}: ${status}`, MARGIN, y, { width: CONTENT_W });
|
||||||
|
if (data.partner.payoutNote) {
|
||||||
|
y += 15;
|
||||||
|
doc.text(data.partner.payoutNote, MARGIN, y, { width: CONTENT_W });
|
||||||
|
}
|
||||||
|
|
||||||
|
const footerY = PAGE_H - FOOTER_H;
|
||||||
|
doc.rect(0, footerY, PAGE_W, FOOTER_H).fill(COLORS.navy);
|
||||||
|
doc.font('Helvetica').fontSize(9).fillColor(COLORS.footerMuted)
|
||||||
|
.text(`${t.generated} ${dateFmt.format(new Date())}`, MARGIN, footerY + FOOTER_H / 2 - 5, { width: CONTENT_W / 2 });
|
||||||
|
doc.font('Helvetica-Bold').fontSize(10).fillColor('#FFFFFF')
|
||||||
|
.text(siteUrl().domain, MARGIN, footerY + FOOTER_H / 2 - 5.5, { width: CONTENT_W, align: 'right' });
|
||||||
|
|
||||||
|
doc.end();
|
||||||
|
return done;
|
||||||
|
}
|
||||||
@@ -1,19 +1,22 @@
|
|||||||
// Shared capacity-checked recovery for released bookings.
|
// Shared capacity-checked recovery for bookings that don't currently hold a seat.
|
||||||
//
|
//
|
||||||
// When a booking is put on hold (or failed/cancelled), its ticket(s) drop out of the
|
// Under the seat-holding rule (lib/capacity.ts) a seat is held by paid/checked-in
|
||||||
// capacity-counting statuses ('pending', 'confirmed', 'checked_in'), releasing the seat.
|
// tickets and by 'pending_approval' payments. Promoting a booking INTO one of those
|
||||||
// Recovering such a booking (user "I've paid" again, or an admin reactivating / marking
|
// states — user clicking "I've paid", an admin approving/reactivating a payment —
|
||||||
// it paid / reopening a failed payment) must atomically re-check that the event still has
|
// must atomically re-check that the event still has room, exactly like the original
|
||||||
// room before re-reserving the seat, exactly like the original booking-creation flow in
|
// booking-creation flow in routes/tickets.ts. Demoting back to bare 'pending'
|
||||||
// routes/tickets.ts.
|
// (e.g. reopening a failed payment) claims no seat and skips the check.
|
||||||
//
|
//
|
||||||
// Callers choose which ticket statuses are eligible to be re-reserved via
|
// Callers choose which ticket statuses are eligible to be flipped via
|
||||||
// `options.fromTicketStatuses` (default ['on_hold']); tickets not in that list — and
|
// `options.fromTicketStatuses` (default ['on_hold']); tickets not in that list are
|
||||||
// tickets that already hold a seat — are left untouched and don't consume capacity.
|
// left untouched. Tickets that already hold a seat cost no new capacity.
|
||||||
|
// `options.skipCapacityCheck` lets an admin knowingly approve over capacity —
|
||||||
|
// the UI warns first (routes/payments.ts /approve with allowOverCapacity).
|
||||||
|
|
||||||
import { eq, and, inArray, sql } from 'drizzle-orm';
|
import { eq, and, inArray } from 'drizzle-orm';
|
||||||
import { db, dbGet, tickets, payments, events, isSqlite } from '../db/index.js';
|
import { db, dbGet, tickets, payments, events, isSqlite } from '../db/index.js';
|
||||||
import { getNow, calculateAvailableSeats, isEventSoldOut } from './utils.js';
|
import { getNow, calculateAvailableSeats, isEventSoldOut } from './utils.js';
|
||||||
|
import { seatHolderCountQuery, unseatedTicketCountQuery } from './capacity.js';
|
||||||
|
|
||||||
export class HoldCapacityError extends Error {
|
export class HoldCapacityError extends Error {
|
||||||
constructor(public available: number) {
|
constructor(public available: number) {
|
||||||
@@ -26,6 +29,8 @@ interface ReserveOptions {
|
|||||||
extraPaymentFields?: Record<string, any>;
|
extraPaymentFields?: Record<string, any>;
|
||||||
/** Ticket statuses eligible to be flipped to targetTicketStatus. Default: ['on_hold']. */
|
/** Ticket statuses eligible to be flipped to targetTicketStatus. Default: ['on_hold']. */
|
||||||
fromTicketStatuses?: Array<'on_hold' | 'cancelled' | 'pending'>;
|
fromTicketStatuses?: Array<'on_hold' | 'cancelled' | 'pending'>;
|
||||||
|
/** Admin override: reserve even when it puts the event over capacity. */
|
||||||
|
skipCapacityCheck?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -34,7 +39,8 @@ interface ReserveOptions {
|
|||||||
* Only tickets whose current status is in `fromTicketStatuses` are flipped.
|
* Only tickets whose current status is in `fromTicketStatuses` are flipped.
|
||||||
* Capacity is asserted against the number of those tickets that don't already
|
* Capacity is asserted against the number of those tickets that don't already
|
||||||
* hold a seat, so re-reserving tickets that are already seated is a no-op.
|
* hold a seat, so re-reserving tickets that are already seated is a no-op.
|
||||||
* Throws HoldCapacityError if the event no longer has room.
|
* Throws HoldCapacityError if the event no longer has room (unless the target
|
||||||
|
* state holds no seat, or skipCapacityCheck is set).
|
||||||
*/
|
*/
|
||||||
export async function reserveOnHoldBooking(
|
export async function reserveOnHoldBooking(
|
||||||
eventId: string,
|
eventId: string,
|
||||||
@@ -46,6 +52,10 @@ export async function reserveOnHoldBooking(
|
|||||||
if (ticketIds.length === 0) return;
|
if (ticketIds.length === 0) return;
|
||||||
|
|
||||||
const fromTicketStatuses = options.fromTicketStatuses ?? ['on_hold'];
|
const fromTicketStatuses = options.fromTicketStatuses ?? ['on_hold'];
|
||||||
|
// Bare 'pending' payments hold no seat, so moving a booking back to 'pending'
|
||||||
|
// consumes no capacity and needs no check.
|
||||||
|
const targetHoldsSeat = targetPaymentStatus !== 'pending' || targetTicketStatus === 'confirmed';
|
||||||
|
const checkCapacity = targetHoldsSeat && !options.skipCapacityCheck;
|
||||||
|
|
||||||
const event = await dbGet<any>(
|
const event = await dbGet<any>(
|
||||||
(db as any).select().from(events).where(eq((events as any).id, eventId))
|
(db as any).select().from(events).where(eq((events as any).id, eventId))
|
||||||
@@ -65,8 +75,14 @@ export async function reserveOnHoldBooking(
|
|||||||
if (options.paidByAdminId) paymentUpdate.paidByAdminId = options.paidByAdminId;
|
if (options.paidByAdminId) paymentUpdate.paidByAdminId = options.paidByAdminId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Keep the ticket-level payment flag in sync when the payment settles
|
||||||
|
const ticketUpdate: Record<string, any> = { status: targetTicketStatus };
|
||||||
|
if (targetPaymentStatus === 'paid') {
|
||||||
|
ticketUpdate.paymentStatus = 'paid';
|
||||||
|
}
|
||||||
|
|
||||||
// `needed` is how many of these tickets don't currently hold a seat and so must
|
// `needed` is how many of these tickets don't currently hold a seat and so must
|
||||||
// be found new capacity; tickets already in a seat-holding status cost nothing.
|
// be found new capacity; tickets already in a seat-holding state cost nothing.
|
||||||
const assertCapacity = (reserved: number, needed: number) => {
|
const assertCapacity = (reserved: number, needed: number) => {
|
||||||
if (needed <= 0) return;
|
if (needed <= 0) return;
|
||||||
if (isEventSoldOut(event.capacity, reserved)) {
|
if (isEventSoldOut(event.capacity, reserved)) {
|
||||||
@@ -80,26 +96,14 @@ export async function reserveOnHoldBooking(
|
|||||||
|
|
||||||
if (isSqlite()) {
|
if (isSqlite()) {
|
||||||
(db as any).transaction((tx: any) => {
|
(db as any).transaction((tx: any) => {
|
||||||
const countRow = tx
|
if (checkCapacity) {
|
||||||
.select({ count: sql<number>`count(*)` })
|
const countRow = seatHolderCountQuery(tx, eventId).get();
|
||||||
.from(tickets)
|
const neededRow = unseatedTicketCountQuery(tx, ticketIds).get();
|
||||||
.where(and(
|
|
||||||
eq((tickets as any).eventId, eventId),
|
|
||||||
sql`${(tickets as any).status} IN ('pending', 'confirmed', 'checked_in')`
|
|
||||||
))
|
|
||||||
.get();
|
|
||||||
const neededRow = tx
|
|
||||||
.select({ count: sql<number>`count(*)` })
|
|
||||||
.from(tickets)
|
|
||||||
.where(and(
|
|
||||||
inArray((tickets as any).id, ticketIds),
|
|
||||||
sql`${(tickets as any).status} NOT IN ('pending', 'confirmed', 'checked_in')`
|
|
||||||
))
|
|
||||||
.get();
|
|
||||||
assertCapacity(Number(countRow?.count || 0), Number(neededRow?.count || 0));
|
assertCapacity(Number(countRow?.count || 0), Number(neededRow?.count || 0));
|
||||||
|
}
|
||||||
|
|
||||||
tx.update(tickets)
|
tx.update(tickets)
|
||||||
.set({ status: targetTicketStatus })
|
.set(ticketUpdate)
|
||||||
.where(and(
|
.where(and(
|
||||||
inArray((tickets as any).id, ticketIds),
|
inArray((tickets as any).id, ticketIds),
|
||||||
inArray((tickets as any).status, fromTicketStatuses)
|
inArray((tickets as any).status, fromTicketStatuses)
|
||||||
@@ -113,28 +117,14 @@ export async function reserveOnHoldBooking(
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
await (db as any).transaction(async (tx: any) => {
|
await (db as any).transaction(async (tx: any) => {
|
||||||
const countRow = await dbGet<any>(
|
if (checkCapacity) {
|
||||||
tx
|
const countRow = await dbGet<any>(seatHolderCountQuery(tx, eventId));
|
||||||
.select({ count: sql<number>`count(*)` })
|
const neededRow = await dbGet<any>(unseatedTicketCountQuery(tx, ticketIds));
|
||||||
.from(tickets)
|
|
||||||
.where(and(
|
|
||||||
eq((tickets as any).eventId, eventId),
|
|
||||||
sql`${(tickets as any).status} IN ('pending', 'confirmed', 'checked_in')`
|
|
||||||
))
|
|
||||||
);
|
|
||||||
const neededRow = await dbGet<any>(
|
|
||||||
tx
|
|
||||||
.select({ count: sql<number>`count(*)` })
|
|
||||||
.from(tickets)
|
|
||||||
.where(and(
|
|
||||||
inArray((tickets as any).id, ticketIds),
|
|
||||||
sql`${(tickets as any).status} NOT IN ('pending', 'confirmed', 'checked_in')`
|
|
||||||
))
|
|
||||||
);
|
|
||||||
assertCapacity(Number(countRow?.count || 0), Number(neededRow?.count || 0));
|
assertCapacity(Number(countRow?.count || 0), Number(neededRow?.count || 0));
|
||||||
|
}
|
||||||
|
|
||||||
await tx.update(tickets)
|
await tx.update(tickets)
|
||||||
.set({ status: targetTicketStatus })
|
.set(ticketUpdate)
|
||||||
.where(and(
|
.where(and(
|
||||||
inArray((tickets as any).id, ticketIds),
|
inArray((tickets as any).id, ticketIds),
|
||||||
inArray((tickets as any).status, fromTicketStatuses)
|
inArray((tickets as any).status, fromTicketStatuses)
|
||||||
|
|||||||
@@ -1,23 +1,24 @@
|
|||||||
// Auto-hold stale manual-payment bookings.
|
// Auto-hold stale unsettled manual-payment bookings.
|
||||||
//
|
//
|
||||||
// This job releases the seat held by an abandoned manual-payment booking (bank
|
// This job moves abandoned manual-payment bookings (bank transfer / TPago / cash)
|
||||||
// transfer / TPago / cash) after HOLD_THRESHOLD_HOURS. It covers two states, both of
|
// to 'on_hold' after HOLD_THRESHOLD_HOURS — bookings still in bare 'pending', i.e.
|
||||||
// which keep a seat reserved while awaiting a human:
|
// the customer never clicked "I've paid" and no admin settled them. These are exempt
|
||||||
// - 'pending_approval': the user clicked "I've paid" and is waiting for an admin.
|
// from the 30-min auto-fail in bookingCleanup.ts, and under the capacity rule in
|
||||||
// - 'pending' on a manual provider (see MANUAL_PAYMENT_PROVIDERS): the booking was
|
// lib/capacity.ts they hold no seat, so this sweep is pure list hygiene: it keeps
|
||||||
// never settled (these are exempt from the 30-min auto-fail in bookingCleanup.ts,
|
// dead checkouts out of the admin's pending queues.
|
||||||
// so this is their only seat-release path).
|
//
|
||||||
// In either case the payment (and its ticket) is silently moved to 'on_hold', which
|
// 'pending_approval' (customer claims they paid) is deliberately NOT swept: a
|
||||||
// drops it out of the capacity-counting statuses ('pending', 'confirmed', 'checked_in')
|
// claimed payment keeps its seat until an admin approves or rejects it — the admin
|
||||||
// and so releases the seat back to the event. The user receives no notification — they
|
// UI surfaces aging claims instead of silently releasing them.
|
||||||
// can recover via "I've paid" again, and an admin can reactivate or mark it paid
|
//
|
||||||
// directly, both re-checking capacity.
|
// The user receives no notification — they can recover via "I've paid", and an
|
||||||
|
// admin can approve/reactivate directly; every recovery path re-checks capacity.
|
||||||
|
|
||||||
import { and, or, eq, lt, inArray } from 'drizzle-orm';
|
import { and, eq, lt, inArray } from 'drizzle-orm';
|
||||||
import { db, dbAll, tickets, payments } from '../db/index.js';
|
import { db, dbAll, tickets, payments } from '../db/index.js';
|
||||||
import { getNow, toDbDate } from './utils.js';
|
import { getNow, toDbDate } from './utils.js';
|
||||||
import { getLock } from './stores/lock.js';
|
import { getLock } from './stores/lock.js';
|
||||||
import { MANUAL_PAYMENT_PROVIDERS } from './manualProviders.js';
|
import { MANUAL_PAYMENT_PROVIDERS } from './paymentProviders.js';
|
||||||
|
|
||||||
function getThresholdMs(): number {
|
function getThresholdMs(): number {
|
||||||
const hours = parseInt(process.env.HOLD_THRESHOLD_HOURS || '72', 10);
|
const hours = parseInt(process.env.HOLD_THRESHOLD_HOURS || '72', 10);
|
||||||
@@ -25,9 +26,9 @@ function getThresholdMs(): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Move stale awaiting-verification payments (and their tickets) to 'on_hold'.
|
* Move stale unsettled manual payments (and their tickets) to 'on_hold'.
|
||||||
* Covers 'pending_approval' payments and 'pending' payments on manual providers.
|
* Covers only bare 'pending' payments on manual providers; 'pending_approval'
|
||||||
* Returns the number of payments put on hold.
|
* is never swept. Returns the number of payments put on hold.
|
||||||
*/
|
*/
|
||||||
export async function sweepStaleApprovals(): Promise<number> {
|
export async function sweepStaleApprovals(): Promise<number> {
|
||||||
const cutoff = toDbDate(new Date(Date.now() - getThresholdMs()));
|
const cutoff = toDbDate(new Date(Date.now() - getThresholdMs()));
|
||||||
@@ -40,13 +41,8 @@ export async function sweepStaleApprovals(): Promise<number> {
|
|||||||
})
|
})
|
||||||
.from(payments)
|
.from(payments)
|
||||||
.where(and(
|
.where(and(
|
||||||
or(
|
|
||||||
eq((payments as any).status, 'pending_approval'),
|
|
||||||
and(
|
|
||||||
eq((payments as any).status, 'pending'),
|
eq((payments as any).status, 'pending'),
|
||||||
inArray((payments as any).provider, [...MANUAL_PAYMENT_PROVIDERS])
|
inArray((payments as any).provider, [...MANUAL_PAYMENT_PROVIDERS]),
|
||||||
)
|
|
||||||
),
|
|
||||||
lt((payments as any).createdAt, cutoff)
|
lt((payments as any).createdAt, cutoff)
|
||||||
))
|
))
|
||||||
);
|
);
|
||||||
@@ -72,7 +68,7 @@ export async function sweepStaleApprovals(): Promise<number> {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`[HoldSweep] Put ${stale.length} stale awaiting-verification payment(s) on hold.`);
|
console.log(`[HoldSweep] Put ${stale.length} stale unsettled manual payment(s) on hold.`);
|
||||||
return stale.length;
|
return stale.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
// Payment providers that require a human to verify the money arrived.
|
|
||||||
//
|
|
||||||
// These methods (bank transfer / TPago / cash) are never auto-confirmed and —
|
|
||||||
// crucially — are never auto-failed by the stale-booking cleanup: an admin settles
|
|
||||||
// them by hand. Note this is broader than the set of methods that expose an online
|
|
||||||
// "I've paid" step (bank transfer / TPago only); cash is settled at the door.
|
|
||||||
export const MANUAL_PAYMENT_PROVIDERS = ['bank_transfer', 'tpago', 'cash'] as const;
|
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import * as argon2 from 'argon2';
|
||||||
|
import bcrypt from 'bcryptjs';
|
||||||
|
|
||||||
|
// Password hashing with Argon2 (spec requirement)
|
||||||
|
export async function hashPassword(password: string): Promise<string> {
|
||||||
|
return argon2.hash(password, {
|
||||||
|
type: argon2.argon2id,
|
||||||
|
memoryCost: 65536, // 64 MB
|
||||||
|
timeCost: 3,
|
||||||
|
parallelism: 4,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyPassword(password: string, hash: string): Promise<boolean> {
|
||||||
|
// Support both bcrypt (legacy) and argon2 hashes for migration
|
||||||
|
if (hash.startsWith('$argon2')) {
|
||||||
|
return argon2.verify(hash, password);
|
||||||
|
}
|
||||||
|
// Legacy bcrypt support
|
||||||
|
return bcrypt.compare(password, hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Small blocklist of common/weak passwords (and obvious app-specific ones).
|
||||||
|
// Compared case-insensitively after stripping non-alphanumerics so that e.g.
|
||||||
|
// "P@ssw0rd!" still matches "password".
|
||||||
|
const COMMON_PASSWORDS = new Set([
|
||||||
|
'password', 'passw0rd', '123456', '1234567', '12345678', '123456789', '1234567890',
|
||||||
|
'qwerty', 'qwertyuiop', 'letmein', 'welcome', 'admin', 'administrator', 'iloveyou',
|
||||||
|
'monkey', 'dragon', 'sunshine', 'princess', 'football', 'baseball', 'abc123',
|
||||||
|
'spanglish', 'changeme', 'secret', 'master', 'login', 'access',
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Password policy: 10-128 chars, requires a mix of character types, and rejects
|
||||||
|
// common/weak passwords. Centralized so register/reset/change all share it.
|
||||||
|
export function validatePassword(password: string): { valid: boolean; error?: string } {
|
||||||
|
if (password.length < 10) {
|
||||||
|
return { valid: false, error: 'Password must be at least 10 characters long' };
|
||||||
|
}
|
||||||
|
if (password.length > 128) {
|
||||||
|
return { valid: false, error: 'Password must be at most 128 characters long' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasLower = /[a-z]/.test(password);
|
||||||
|
const hasUpper = /[A-Z]/.test(password);
|
||||||
|
const hasDigit = /\d/.test(password);
|
||||||
|
const hasSymbol = /[^A-Za-z0-9]/.test(password);
|
||||||
|
|
||||||
|
// Require lowercase, uppercase, and at least one digit or symbol.
|
||||||
|
if (!hasLower || !hasUpper || !(hasDigit || hasSymbol)) {
|
||||||
|
return {
|
||||||
|
valid: false,
|
||||||
|
error: 'Password must include uppercase and lowercase letters and at least one number or symbol',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalized = password.toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||||
|
if (COMMON_PASSWORDS.has(normalized)) {
|
||||||
|
return { valid: false, error: 'Password is too common. Please choose a less guessable password.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true };
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// Payment provider registry.
|
||||||
|
//
|
||||||
|
// Every provider is either:
|
||||||
|
// - 'automatic': the gateway itself confirms the payment (webhook/invoice
|
||||||
|
// settlement) and the booking is auto-approved on success. No admin involved.
|
||||||
|
// Currently Lightning; future online gateways (e.g. Stripe) go here.
|
||||||
|
// - 'manual': a human must verify the money arrived (TPago, bank transfer,
|
||||||
|
// card handled offline, cash or the POS terminal at the door). These are
|
||||||
|
// never auto-confirmed and never auto-failed; an admin settles them by hand. Bank transfer and
|
||||||
|
// TPago additionally expose an online "I've paid" step that moves the
|
||||||
|
// payment to 'pending_approval'.
|
||||||
|
//
|
||||||
|
// Capacity note (see lib/capacity.ts): only paid/checked-in tickets and
|
||||||
|
// 'pending_approval' payments hold a seat. A bare 'pending' payment — of either
|
||||||
|
// kind — holds no seat, so an abandoned checkout can never block sales.
|
||||||
|
|
||||||
|
export type PaymentProviderKind = 'automatic' | 'manual';
|
||||||
|
|
||||||
|
export const PAYMENT_PROVIDERS: Record<string, { kind: PaymentProviderKind }> = {
|
||||||
|
lightning: { kind: 'automatic' },
|
||||||
|
tpago: { kind: 'manual' },
|
||||||
|
bank_transfer: { kind: 'manual' },
|
||||||
|
card: { kind: 'manual' },
|
||||||
|
cash: { kind: 'manual' },
|
||||||
|
// Card on the physical POS terminal at the door; staff confirm it by hand
|
||||||
|
pos: { kind: 'manual' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const MANUAL_PAYMENT_PROVIDERS = Object.keys(PAYMENT_PROVIDERS).filter(
|
||||||
|
(p) => PAYMENT_PROVIDERS[p].kind === 'manual'
|
||||||
|
);
|
||||||
|
|
||||||
|
export function isManualProvider(provider: string): boolean {
|
||||||
|
return PAYMENT_PROVIDERS[provider]?.kind === 'manual';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isAutomaticProvider(provider: string): boolean {
|
||||||
|
return PAYMENT_PROVIDERS[provider]?.kind === 'automatic';
|
||||||
|
}
|
||||||
+350
-193
@@ -1,6 +1,8 @@
|
|||||||
// PDF Ticket Generation Service
|
// PDF Ticket Generation Service
|
||||||
import PDFDocument from 'pdfkit';
|
import PDFDocument from 'pdfkit';
|
||||||
import QRCode from 'qrcode';
|
import QRCode from 'qrcode';
|
||||||
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
interface TicketData {
|
interface TicketData {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -15,235 +17,390 @@ interface TicketData {
|
|||||||
locationUrl?: string;
|
locationUrl?: string;
|
||||||
};
|
};
|
||||||
timezone?: string;
|
timezone?: string;
|
||||||
|
/** 'en' | 'es' - drives the labels and the date/time format on the ticket */
|
||||||
|
locale?: string;
|
||||||
|
/** Optional perk line shown under the ticket holder (falls back to the terms line) */
|
||||||
|
note?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Brand ====================
|
||||||
|
|
||||||
|
export const COLORS = {
|
||||||
|
navy: '#002F44',
|
||||||
|
orange: '#F5821F',
|
||||||
|
cream: '#FDF8F0',
|
||||||
|
card: '#FFFFFF',
|
||||||
|
cardBorder: '#EFE6D8',
|
||||||
|
divider: '#E7DFD1',
|
||||||
|
label: '#9AA3AC',
|
||||||
|
muted: '#6B7580',
|
||||||
|
footerMuted: '#7FA3B5',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const PAGE_W = 595.28;
|
||||||
|
export const PAGE_H = 841.89;
|
||||||
|
export const MARGIN = 48;
|
||||||
|
export const CONTENT_W = PAGE_W - MARGIN * 2;
|
||||||
|
export const ACCENT_H = 10;
|
||||||
|
export const FOOTER_H = 48;
|
||||||
|
|
||||||
|
export const LOGO_RATIO = 1158 / 324;
|
||||||
|
|
||||||
|
const STRINGS = {
|
||||||
|
en: {
|
||||||
|
scan: 'SCAN AT THE ENTRANCE',
|
||||||
|
venue: 'VENUE',
|
||||||
|
holder: 'TICKET HOLDER',
|
||||||
|
terms: 'This ticket is non-transferable. One scan per entry.',
|
||||||
|
},
|
||||||
|
es: {
|
||||||
|
scan: 'ESCANEÁ AL INGRESAR',
|
||||||
|
venue: 'LUGAR',
|
||||||
|
holder: 'TITULAR',
|
||||||
|
terms: 'Esta entrada es personal e intransferible. Un escaneo por ingreso.',
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
function strings(locale?: string) {
|
||||||
|
return locale === 'es' ? STRINGS.es : STRINGS.en;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate a QR code as a data URL
|
* Locate the logo. `../../assets` resolves to backend/assets from both
|
||||||
|
* src/lib (tsx) and dist/lib (compiled), with the frontend copy as a fallback.
|
||||||
|
*/
|
||||||
|
function loadLogo(): Buffer | null {
|
||||||
|
const candidates = [
|
||||||
|
new URL('../../assets/logo-spanglish.png', import.meta.url),
|
||||||
|
new URL('../../../frontend/public/images/logo-spanglish.png', import.meta.url),
|
||||||
|
].map((u) => fileURLToPath(u));
|
||||||
|
|
||||||
|
for (const path of candidates) {
|
||||||
|
if (existsSync(path)) return readFileSync(path);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
let logoCache: Buffer | null | undefined;
|
||||||
|
export function getLogo(): Buffer | null {
|
||||||
|
if (logoCache === undefined) logoCache = loadLogo();
|
||||||
|
return logoCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a QR code as a PNG buffer
|
||||||
*/
|
*/
|
||||||
async function generateQRCode(data: string): Promise<Buffer> {
|
async function generateQRCode(data: string): Promise<Buffer> {
|
||||||
return QRCode.toBuffer(data, {
|
return QRCode.toBuffer(data, {
|
||||||
type: 'png',
|
type: 'png',
|
||||||
width: 200,
|
width: 600,
|
||||||
margin: 2,
|
margin: 1,
|
||||||
errorCorrectionLevel: 'M',
|
errorCorrectionLevel: 'M',
|
||||||
|
color: { dark: '#000000', light: '#FFFFFF' },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Format date for display using site timezone
|
* Short date + time as shown in the ticket header:
|
||||||
|
* en -> "JUL 25 · 4:30 PM" es -> "25 JUL · 16:30"
|
||||||
*/
|
*/
|
||||||
function formatDate(dateStr: string, timezone: string = 'America/Asuncion'): string {
|
function formatWhen(
|
||||||
const date = new Date(dateStr);
|
startStr: string,
|
||||||
return date.toLocaleDateString('en-US', {
|
endStr: string | undefined,
|
||||||
weekday: 'long',
|
timezone: string,
|
||||||
year: 'numeric',
|
locale: string
|
||||||
month: 'long',
|
): string {
|
||||||
day: 'numeric',
|
const isEs = locale === 'es';
|
||||||
timeZone: timezone,
|
const start = new Date(startStr);
|
||||||
});
|
const tag = isEs ? 'es-ES' : 'en-US';
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
const day = start.toLocaleDateString(tag, { day: 'numeric', timeZone: timezone });
|
||||||
* Format time for display using site timezone
|
const month = start
|
||||||
*/
|
.toLocaleDateString(tag, { month: 'short', timeZone: timezone })
|
||||||
function formatTime(dateStr: string, timezone: string = 'America/Asuncion'): string {
|
.replace(/\.$/, '')
|
||||||
const date = new Date(dateStr);
|
.toUpperCase();
|
||||||
return date.toLocaleTimeString('en-US', {
|
|
||||||
hour: '2-digit',
|
const time = (d: Date) =>
|
||||||
|
d
|
||||||
|
.toLocaleTimeString(tag, {
|
||||||
|
hour: isEs ? '2-digit' : 'numeric',
|
||||||
minute: '2-digit',
|
minute: '2-digit',
|
||||||
hour12: true,
|
hour12: !isEs,
|
||||||
timeZone: timezone,
|
timeZone: timezone,
|
||||||
|
})
|
||||||
|
.toUpperCase();
|
||||||
|
|
||||||
|
const date = isEs ? `${day} ${month}` : `${month} ${day}`;
|
||||||
|
const end = endStr ? new Date(endStr) : null;
|
||||||
|
const when = end ? `${time(start)} – ${time(end)}` : time(start);
|
||||||
|
|
||||||
|
return `${date} · ${when}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Events store the venue as a single string; the part before the first comma
|
||||||
|
* reads as the venue name and the remainder as its address.
|
||||||
|
*/
|
||||||
|
function splitLocation(location: string): { name: string; address?: string } {
|
||||||
|
const idx = location.indexOf(',');
|
||||||
|
if (idx === -1) return { name: location.trim() };
|
||||||
|
return {
|
||||||
|
name: location.slice(0, idx).trim(),
|
||||||
|
address: location.slice(idx + 1).trim() || undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Drawing helpers ====================
|
||||||
|
|
||||||
|
export function drawLabel(doc: PDFKit.PDFDocument, text: string, y: number, width = CONTENT_W, x = MARGIN) {
|
||||||
|
doc
|
||||||
|
.font('Helvetica-Bold')
|
||||||
|
.fontSize(8)
|
||||||
|
.fillColor(COLORS.label)
|
||||||
|
.text(text.toUpperCase(), x, y, { width, characterSpacing: 1.6 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function drawDivider(doc: PDFKit.PDFDocument, y: number) {
|
||||||
|
doc
|
||||||
|
.moveTo(MARGIN, y)
|
||||||
|
.lineTo(PAGE_W - MARGIN, y)
|
||||||
|
.lineWidth(1)
|
||||||
|
.strokeColor(COLORS.divider)
|
||||||
|
.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Centered text with letter spacing: pdfkit also spaces the last glyph, so nudge it back. */
|
||||||
|
function drawSpacedCentered(
|
||||||
|
doc: PDFKit.PDFDocument,
|
||||||
|
text: string,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
width: number,
|
||||||
|
spacing: number
|
||||||
|
) {
|
||||||
|
doc.text(text, x - spacing / 2, y, { width, align: 'center', characterSpacing: spacing });
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DetailBlock {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
sub?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Draw (or, with `measureOnly`, just measure) the venue / ticket holder / note
|
||||||
|
* block. Returns its total height so the caller can anchor it above the footer.
|
||||||
|
*/
|
||||||
|
function renderDetails(
|
||||||
|
doc: PDFKit.PDFDocument,
|
||||||
|
blocks: DetailBlock[],
|
||||||
|
note: string,
|
||||||
|
yStart: number,
|
||||||
|
measureOnly: boolean
|
||||||
|
): number {
|
||||||
|
let y = yStart;
|
||||||
|
|
||||||
|
blocks.forEach((block, i) => {
|
||||||
|
if (i > 0) {
|
||||||
|
y += 14;
|
||||||
|
if (!measureOnly) drawDivider(doc, y);
|
||||||
|
y += 18;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!measureOnly) drawLabel(doc, block.label, y);
|
||||||
|
y += 15;
|
||||||
|
|
||||||
|
doc.font('Helvetica-Bold').fontSize(13);
|
||||||
|
if (!measureOnly) doc.fillColor(COLORS.navy).text(block.value, MARGIN, y, { width: CONTENT_W });
|
||||||
|
y += doc.heightOfString(block.value, { width: CONTENT_W }) + 3;
|
||||||
|
|
||||||
|
if (block.sub) {
|
||||||
|
doc.font('Helvetica').fontSize(10.5);
|
||||||
|
if (!measureOnly) doc.fillColor(COLORS.muted).text(block.sub, MARGIN, y, { width: CONTENT_W });
|
||||||
|
y += doc.heightOfString(block.sub, { width: CONTENT_W }) + 3;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
y += 16;
|
||||||
|
doc.font('Helvetica').fontSize(10.5);
|
||||||
|
if (!measureOnly) doc.fillColor(COLORS.muted).text(note, MARGIN, y, { width: CONTENT_W });
|
||||||
|
y += doc.heightOfString(note, { width: CONTENT_W });
|
||||||
|
|
||||||
|
return y - yStart;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render one full-page ticket. Assumes the page is already added.
|
||||||
|
*/
|
||||||
|
function renderTicketPage(
|
||||||
|
doc: PDFKit.PDFDocument,
|
||||||
|
ticket: TicketData,
|
||||||
|
qrBuffer: Buffer,
|
||||||
|
siteDomain: string,
|
||||||
|
index = 0,
|
||||||
|
total = 1
|
||||||
|
) {
|
||||||
|
const locale = ticket.locale === 'es' ? 'es' : 'en';
|
||||||
|
const t = strings(locale);
|
||||||
|
const tz = ticket.timezone || 'America/Asuncion';
|
||||||
|
const footerY = PAGE_H - FOOTER_H;
|
||||||
|
|
||||||
|
// ==================== Background ====================
|
||||||
|
doc.rect(0, 0, PAGE_W, PAGE_H).fill(COLORS.cream);
|
||||||
|
doc.rect(0, 0, PAGE_W, ACCENT_H).fill(COLORS.orange);
|
||||||
|
|
||||||
|
// ==================== Logo ====================
|
||||||
|
const logo = getLogo();
|
||||||
|
let headerY = MARGIN + 6;
|
||||||
|
|
||||||
|
if (logo) {
|
||||||
|
const logoW = 158;
|
||||||
|
doc.image(logo, MARGIN, headerY, { width: logoW });
|
||||||
|
headerY += logoW / LOGO_RATIO;
|
||||||
|
} else {
|
||||||
|
doc.font('Helvetica-Bold').fontSize(21).fillColor(COLORS.navy).text('spanglish social', MARGIN, headerY);
|
||||||
|
headerY += 26;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Title + date ====================
|
||||||
|
const titleY = headerY + 30;
|
||||||
|
const when = formatWhen(ticket.event.startDatetime, ticket.event.endDatetime, tz, locale);
|
||||||
|
|
||||||
|
doc.font('Helvetica-Bold').fontSize(11.5);
|
||||||
|
const whenW = Math.min(doc.widthOfString(when) + 2, CONTENT_W * 0.5);
|
||||||
|
const titleW = CONTENT_W - whenW - 20;
|
||||||
|
|
||||||
|
doc.font('Helvetica-Bold').fontSize(26);
|
||||||
|
if (doc.widthOfString(ticket.event.title) > titleW) doc.fontSize(20);
|
||||||
|
doc.fillColor(COLORS.navy).text(ticket.event.title, MARGIN, titleY, { width: titleW });
|
||||||
|
const titleBottom = doc.y;
|
||||||
|
|
||||||
|
doc
|
||||||
|
.font('Helvetica-Bold')
|
||||||
|
.fontSize(11.5)
|
||||||
|
.fillColor(COLORS.orange)
|
||||||
|
.text(when, PAGE_W - MARGIN - whenW, titleY + 9, { width: whenW, align: 'right' });
|
||||||
|
|
||||||
|
// ==================== Layout: card fills what the detail block leaves ====================
|
||||||
|
const venue = splitLocation(ticket.event.location);
|
||||||
|
const note = ticket.note || t.terms;
|
||||||
|
const blocks: DetailBlock[] = [
|
||||||
|
{ label: t.venue, value: venue.name, sub: venue.address },
|
||||||
|
{ label: t.holder, value: ticket.attendeeName, sub: ticket.attendeeEmail },
|
||||||
|
];
|
||||||
|
|
||||||
|
const detailsH = renderDetails(doc, blocks, note, 0, true);
|
||||||
|
const detailsY = footerY - 46 - detailsH;
|
||||||
|
|
||||||
|
const cardY = Math.max(titleBottom, titleY + 36) + 24;
|
||||||
|
const cardX = MARGIN;
|
||||||
|
const cardW = CONTENT_W;
|
||||||
|
const cardH = Math.max(300, Math.min(detailsY - 32 - cardY, 430));
|
||||||
|
|
||||||
|
doc
|
||||||
|
.roundedRect(cardX, cardY, cardW, cardH, 14)
|
||||||
|
.lineWidth(1)
|
||||||
|
.fillAndStroke(COLORS.card, COLORS.cardBorder);
|
||||||
|
|
||||||
|
// ==================== QR card contents ====================
|
||||||
|
const labelH = 12;
|
||||||
|
const codeH = 24;
|
||||||
|
const qrSize = Math.min(236, cardH - (labelH + 20 + 22 + codeH + 44));
|
||||||
|
const stackH = labelH + 20 + qrSize + 22 + codeH;
|
||||||
|
let inner = cardY + (cardH - stackH) / 2;
|
||||||
|
|
||||||
|
doc.font('Helvetica-Bold').fontSize(8.5).fillColor(COLORS.label);
|
||||||
|
drawSpacedCentered(doc, t.scan, cardX, inner, cardW, 2);
|
||||||
|
|
||||||
|
if (total > 1) {
|
||||||
|
doc
|
||||||
|
.font('Helvetica-Bold')
|
||||||
|
.fontSize(8.5)
|
||||||
|
.fillColor(COLORS.label)
|
||||||
|
.text(`${index + 1} / ${total}`, cardX, inner, { width: cardW - 22, align: 'right', characterSpacing: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
inner += labelH + 20;
|
||||||
|
doc.image(qrBuffer, (PAGE_W - qrSize) / 2, inner, { width: qrSize, height: qrSize });
|
||||||
|
inner += qrSize + 22;
|
||||||
|
|
||||||
|
const code = ticket.qrCode || ticket.id.slice(0, 8).toUpperCase();
|
||||||
|
doc.font('Courier-Bold').fontSize(19).fillColor(COLORS.navy);
|
||||||
|
drawSpacedCentered(doc, code, cardX, inner, cardW, 3);
|
||||||
|
|
||||||
|
// ==================== Venue / ticket holder / note ====================
|
||||||
|
renderDetails(doc, blocks, note, detailsY, false);
|
||||||
|
|
||||||
|
// ==================== Footer ====================
|
||||||
|
doc.rect(0, footerY, PAGE_W, FOOTER_H).fill(COLORS.navy);
|
||||||
|
|
||||||
|
doc
|
||||||
|
.font('Courier')
|
||||||
|
.fontSize(7.5)
|
||||||
|
.fillColor(COLORS.footerMuted)
|
||||||
|
.text(ticket.id, MARGIN, footerY + FOOTER_H / 2 - 4, { width: CONTENT_W * 0.6, lineBreak: false });
|
||||||
|
|
||||||
|
doc
|
||||||
|
.font('Helvetica')
|
||||||
|
.fontSize(10)
|
||||||
|
.fillColor('#FFFFFF')
|
||||||
|
.text(siteDomain, MARGIN, footerY + FOOTER_H / 2 - 5.5, { width: CONTENT_W, align: 'right' });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createDoc(): PDFKit.PDFDocument {
|
||||||
|
return new PDFDocument({ size: 'A4', margin: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function collect(doc: PDFKit.PDFDocument): Promise<Buffer> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
doc.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||||
|
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||||
|
doc.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function siteUrl(): { base: string; domain: string } {
|
||||||
|
const base = process.env.FRONTEND_URL || 'https://spanglishcommunity.com';
|
||||||
|
let domain = base;
|
||||||
|
try {
|
||||||
|
domain = new URL(base).host.replace(/^www\./, '');
|
||||||
|
} catch {
|
||||||
|
domain = base.replace(/^https?:\/\//, '').replace(/^www\./, '').replace(/\/$/, '');
|
||||||
|
}
|
||||||
|
return { base, domain };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate a PDF ticket for a single ticket
|
* Generate a PDF ticket for a single ticket
|
||||||
*/
|
*/
|
||||||
export async function generateTicketPDF(ticket: TicketData): Promise<Buffer> {
|
export async function generateTicketPDF(ticket: TicketData): Promise<Buffer> {
|
||||||
return new Promise(async (resolve, reject) => {
|
return generateCombinedTicketsPDF([ticket]);
|
||||||
try {
|
|
||||||
const doc = new PDFDocument({
|
|
||||||
size: 'A4',
|
|
||||||
margin: 50,
|
|
||||||
});
|
|
||||||
|
|
||||||
const chunks: Buffer[] = [];
|
|
||||||
doc.on('data', (chunk: Buffer) => chunks.push(chunk));
|
|
||||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
|
||||||
doc.on('error', reject);
|
|
||||||
|
|
||||||
const frontendUrl = process.env.FRONTEND_URL || 'https://spanglishcommunity.com';
|
|
||||||
|
|
||||||
// Generate QR code with ticket URL
|
|
||||||
const qrUrl = `${frontendUrl}/ticket/${ticket.id}`;
|
|
||||||
const qrBuffer = await generateQRCode(qrUrl);
|
|
||||||
|
|
||||||
// ==================== Header ====================
|
|
||||||
doc.fontSize(28).fillColor('#1a1a1a').text('Spanglish', { align: 'center' });
|
|
||||||
doc.moveDown(0.5);
|
|
||||||
doc.fontSize(12).fillColor('#666').text('Language Exchange Community', { align: 'center' });
|
|
||||||
|
|
||||||
// Divider line
|
|
||||||
doc.moveDown(1);
|
|
||||||
doc.moveTo(50, doc.y).lineTo(545, doc.y).strokeColor('#e0e0e0').stroke();
|
|
||||||
doc.moveDown(1);
|
|
||||||
|
|
||||||
// ==================== Event Info ====================
|
|
||||||
doc.fontSize(22).fillColor('#1a1a1a').text(ticket.event.title, { align: 'center' });
|
|
||||||
doc.moveDown(0.5);
|
|
||||||
|
|
||||||
// Date and time (using site timezone)
|
|
||||||
const tz = ticket.timezone || 'America/Asuncion';
|
|
||||||
doc.fontSize(14).fillColor('#333');
|
|
||||||
doc.text(formatDate(ticket.event.startDatetime, tz), { align: 'center' });
|
|
||||||
|
|
||||||
const startTime = formatTime(ticket.event.startDatetime, tz);
|
|
||||||
const endTime = ticket.event.endDatetime ? formatTime(ticket.event.endDatetime, tz) : null;
|
|
||||||
const timeRange = endTime ? `${startTime} - ${endTime}` : startTime;
|
|
||||||
doc.text(timeRange, { align: 'center' });
|
|
||||||
|
|
||||||
doc.moveDown(0.5);
|
|
||||||
doc.fontSize(12).fillColor('#666').text(ticket.event.location, { align: 'center' });
|
|
||||||
|
|
||||||
// ==================== QR Code ====================
|
|
||||||
doc.moveDown(2);
|
|
||||||
|
|
||||||
// Center the QR code
|
|
||||||
const qrSize = 180;
|
|
||||||
const pageWidth = 595; // A4 width in points
|
|
||||||
const qrX = (pageWidth - qrSize) / 2;
|
|
||||||
|
|
||||||
doc.image(qrBuffer, qrX, doc.y, { width: qrSize, height: qrSize });
|
|
||||||
doc.y += qrSize + 10;
|
|
||||||
|
|
||||||
// ==================== Attendee Info ====================
|
|
||||||
doc.moveDown(1);
|
|
||||||
doc.fontSize(16).fillColor('#1a1a1a').text(ticket.attendeeName, { align: 'center' });
|
|
||||||
|
|
||||||
if (ticket.attendeeEmail) {
|
|
||||||
doc.fontSize(10).fillColor('#888').text(ticket.attendeeEmail, { align: 'center' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==================== Ticket ID ====================
|
|
||||||
doc.moveDown(1);
|
|
||||||
doc.fontSize(9).fillColor('#aaa').text(`Ticket ID: ${ticket.id}`, { align: 'center' });
|
|
||||||
doc.text(`Code: ${ticket.qrCode}`, { align: 'center' });
|
|
||||||
|
|
||||||
// ==================== Footer ====================
|
|
||||||
doc.moveDown(2);
|
|
||||||
doc.moveTo(50, doc.y).lineTo(545, doc.y).strokeColor('#e0e0e0').stroke();
|
|
||||||
doc.moveDown(0.5);
|
|
||||||
|
|
||||||
doc.fontSize(10).fillColor('#888').text('Scan this QR code at the entrance', { align: 'center' });
|
|
||||||
doc.moveDown(0.3);
|
|
||||||
doc.fontSize(8).fillColor('#aaa').text('This ticket is non-transferable. One scan per entry.', { align: 'center' });
|
|
||||||
|
|
||||||
doc.end();
|
|
||||||
} catch (error) {
|
|
||||||
reject(error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate a combined PDF with multiple tickets
|
* Generate a combined PDF with multiple tickets (one page each)
|
||||||
*/
|
*/
|
||||||
export async function generateCombinedTicketsPDF(tickets: TicketData[]): Promise<Buffer> {
|
export async function generateCombinedTicketsPDF(tickets: TicketData[]): Promise<Buffer> {
|
||||||
return new Promise(async (resolve, reject) => {
|
const doc = createDoc();
|
||||||
|
const done = collect(doc);
|
||||||
|
const { base, domain } = siteUrl();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const doc = new PDFDocument({
|
|
||||||
size: 'A4',
|
|
||||||
margin: 50,
|
|
||||||
});
|
|
||||||
|
|
||||||
const chunks: Buffer[] = [];
|
|
||||||
doc.on('data', (chunk: Buffer) => chunks.push(chunk));
|
|
||||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
|
||||||
doc.on('error', reject);
|
|
||||||
|
|
||||||
const frontendUrl = process.env.FRONTEND_URL || 'https://spanglishcommunity.com';
|
|
||||||
|
|
||||||
for (let i = 0; i < tickets.length; i++) {
|
for (let i = 0; i < tickets.length; i++) {
|
||||||
const ticket = tickets[i];
|
const ticket = tickets[i];
|
||||||
|
if (i > 0) doc.addPage();
|
||||||
|
|
||||||
if (i > 0) {
|
const qrBuffer = await generateQRCode(`${base}/ticket/${ticket.id}`);
|
||||||
doc.addPage();
|
renderTicketPage(doc, ticket, qrBuffer, domain, i, tickets.length);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate QR code
|
|
||||||
const qrUrl = `${frontendUrl}/ticket/${ticket.id}`;
|
|
||||||
const qrBuffer = await generateQRCode(qrUrl);
|
|
||||||
|
|
||||||
// ==================== Header ====================
|
|
||||||
doc.fontSize(28).fillColor('#1a1a1a').text('Spanglish', { align: 'center' });
|
|
||||||
doc.moveDown(0.5);
|
|
||||||
doc.fontSize(12).fillColor('#666').text('Language Exchange Community', { align: 'center' });
|
|
||||||
|
|
||||||
// Divider line
|
|
||||||
doc.moveDown(1);
|
|
||||||
doc.moveTo(50, doc.y).lineTo(545, doc.y).strokeColor('#e0e0e0').stroke();
|
|
||||||
doc.moveDown(1);
|
|
||||||
|
|
||||||
// ==================== Event Info ====================
|
|
||||||
doc.fontSize(22).fillColor('#1a1a1a').text(ticket.event.title, { align: 'center' });
|
|
||||||
doc.moveDown(0.5);
|
|
||||||
|
|
||||||
// Date and time (using site timezone)
|
|
||||||
const tz = ticket.timezone || 'America/Asuncion';
|
|
||||||
doc.fontSize(14).fillColor('#333');
|
|
||||||
doc.text(formatDate(ticket.event.startDatetime, tz), { align: 'center' });
|
|
||||||
|
|
||||||
const startTime = formatTime(ticket.event.startDatetime, tz);
|
|
||||||
const endTime = ticket.event.endDatetime ? formatTime(ticket.event.endDatetime, tz) : null;
|
|
||||||
const timeRange = endTime ? `${startTime} - ${endTime}` : startTime;
|
|
||||||
doc.text(timeRange, { align: 'center' });
|
|
||||||
|
|
||||||
doc.moveDown(0.5);
|
|
||||||
doc.fontSize(12).fillColor('#666').text(ticket.event.location, { align: 'center' });
|
|
||||||
|
|
||||||
// ==================== QR Code ====================
|
|
||||||
doc.moveDown(2);
|
|
||||||
|
|
||||||
const qrSize = 180;
|
|
||||||
const pageWidth = 595;
|
|
||||||
const qrX = (pageWidth - qrSize) / 2;
|
|
||||||
|
|
||||||
doc.image(qrBuffer, qrX, doc.y, { width: qrSize, height: qrSize });
|
|
||||||
doc.y += qrSize + 10;
|
|
||||||
|
|
||||||
// ==================== Attendee Info ====================
|
|
||||||
doc.moveDown(1);
|
|
||||||
doc.fontSize(16).fillColor('#1a1a1a').text(ticket.attendeeName, { align: 'center' });
|
|
||||||
|
|
||||||
if (ticket.attendeeEmail) {
|
|
||||||
doc.fontSize(10).fillColor('#888').text(ticket.attendeeEmail, { align: 'center' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==================== Ticket ID ====================
|
|
||||||
doc.moveDown(1);
|
|
||||||
doc.fontSize(9).fillColor('#aaa').text(`Ticket ID: ${ticket.id}`, { align: 'center' });
|
|
||||||
doc.text(`Code: ${ticket.qrCode}`, { align: 'center' });
|
|
||||||
|
|
||||||
// Ticket number for multi-ticket bookings
|
|
||||||
if (tickets.length > 1) {
|
|
||||||
doc.text(`Ticket ${i + 1} of ${tickets.length}`, { align: 'center' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==================== Footer ====================
|
|
||||||
doc.moveDown(2);
|
|
||||||
doc.moveTo(50, doc.y).lineTo(545, doc.y).strokeColor('#e0e0e0').stroke();
|
|
||||||
doc.moveDown(0.5);
|
|
||||||
|
|
||||||
doc.fontSize(10).fillColor('#888').text('Scan this QR code at the entrance', { align: 'center' });
|
|
||||||
doc.moveDown(0.3);
|
|
||||||
doc.fontSize(8).fillColor('#aaa').text('This ticket is non-transferable. One scan per entry.', { align: 'center' });
|
|
||||||
}
|
|
||||||
|
|
||||||
doc.end();
|
doc.end();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
reject(error);
|
doc.end();
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
return done;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import {
|
||||||
|
resolvePresaleClosure,
|
||||||
|
isPresaleClosed,
|
||||||
|
DEFAULT_PRESALE_CLOSE_MINUTES,
|
||||||
|
} from './presale.js';
|
||||||
|
|
||||||
|
const START = '2030-01-01T20:00:00.000Z';
|
||||||
|
const startMs = new Date(START).getTime();
|
||||||
|
const minutes = (n: number) => n * 60_000;
|
||||||
|
|
||||||
|
describe('resolvePresaleClosure', () => {
|
||||||
|
it('falls back to the built-in defaults when neither event nor settings specify anything', () => {
|
||||||
|
const r = resolvePresaleClosure({ startDatetime: START }, null);
|
||||||
|
expect(r.enabled).toBe(true);
|
||||||
|
expect(r.minutesBefore).toBe(DEFAULT_PRESALE_CLOSE_MINUTES);
|
||||||
|
expect(r.closesAt?.getTime()).toBe(startMs - minutes(DEFAULT_PRESALE_CLOSE_MINUTES));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('inherits from site settings when the event has null overrides', () => {
|
||||||
|
const r = resolvePresaleClosure(
|
||||||
|
{ startDatetime: START, presaleClosureEnabled: null, presaleCloseMinutesBefore: null },
|
||||||
|
{ presaleClosureEnabled: true, presaleCloseMinutesBefore: 30 }
|
||||||
|
);
|
||||||
|
expect(r.minutesBefore).toBe(30);
|
||||||
|
expect(r.closesAt?.getTime()).toBe(startMs - minutes(30));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets the event override the site settings', () => {
|
||||||
|
const r = resolvePresaleClosure(
|
||||||
|
{ startDatetime: START, presaleClosureEnabled: true, presaleCloseMinutesBefore: 1440 },
|
||||||
|
{ presaleClosureEnabled: false, presaleCloseMinutesBefore: 30 }
|
||||||
|
);
|
||||||
|
expect(r.enabled).toBe(true);
|
||||||
|
expect(r.closesAt?.getTime()).toBe(startMs - minutes(1440));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns closesAt null when closure is disabled (site-wide or per event)', () => {
|
||||||
|
expect(resolvePresaleClosure({ startDatetime: START }, { presaleClosureEnabled: false }).closesAt).toBeNull();
|
||||||
|
expect(
|
||||||
|
resolvePresaleClosure({ startDatetime: START, presaleClosureEnabled: false }, { presaleClosureEnabled: true }).closesAt
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts PostgreSQL 0/1 integers and string minutes', () => {
|
||||||
|
const r = resolvePresaleClosure(
|
||||||
|
{ startDatetime: new Date(START), presaleClosureEnabled: 1, presaleCloseMinutesBefore: '45' },
|
||||||
|
{ presaleClosureEnabled: 0, presaleCloseMinutesBefore: 10 }
|
||||||
|
);
|
||||||
|
expect(r.enabled).toBe(true);
|
||||||
|
expect(r.minutesBefore).toBe(45);
|
||||||
|
const off = resolvePresaleClosure({ startDatetime: START, presaleClosureEnabled: 0 }, { presaleClosureEnabled: 1 });
|
||||||
|
expect(off.enabled).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closes at the event start when minutes is 0', () => {
|
||||||
|
const r = resolvePresaleClosure({ startDatetime: START, presaleCloseMinutesBefore: 0 }, null);
|
||||||
|
expect(r.closesAt?.getTime()).toBe(startMs);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isPresaleClosed', () => {
|
||||||
|
const event = { startDatetime: START, presaleClosureEnabled: true, presaleCloseMinutesBefore: 60 };
|
||||||
|
|
||||||
|
it('is open before the cutoff and closed from the cutoff onwards', () => {
|
||||||
|
const cutoff = startMs - minutes(60);
|
||||||
|
expect(isPresaleClosed(event, null, cutoff - 1)).toBe(false);
|
||||||
|
expect(isPresaleClosed(event, null, cutoff)).toBe(true);
|
||||||
|
expect(isPresaleClosed(event, null, startMs + minutes(5))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never closes when closure is disabled', () => {
|
||||||
|
expect(isPresaleClosed({ ...event, presaleClosureEnabled: false }, null, startMs + minutes(60))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
/**
|
||||||
|
* Pre-sale closure: online registration for an event closes a configurable
|
||||||
|
* number of minutes before the event starts.
|
||||||
|
*
|
||||||
|
* Each event may override the site-wide default; a `null`/`undefined` value on
|
||||||
|
* the event means "inherit from site_settings". Values arrive as booleans on
|
||||||
|
* SQLite and as 0/1 integers on PostgreSQL, so both are accepted here.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const DEFAULT_PRESALE_CLOSURE_ENABLED = true;
|
||||||
|
export const DEFAULT_PRESALE_CLOSE_MINUTES = 120;
|
||||||
|
|
||||||
|
export interface PresaleEventLike {
|
||||||
|
startDatetime: string | Date;
|
||||||
|
presaleClosureEnabled?: boolean | number | null;
|
||||||
|
presaleCloseMinutesBefore?: number | string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PresaleSettingsLike {
|
||||||
|
presaleClosureEnabled?: boolean | number | null;
|
||||||
|
presaleCloseMinutesBefore?: number | string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResolvedPresaleClosure {
|
||||||
|
enabled: boolean;
|
||||||
|
minutesBefore: number;
|
||||||
|
/** When online registration closes, or null when closure is disabled. */
|
||||||
|
closesAt: Date | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBool(value: boolean | number | null | undefined): boolean | null {
|
||||||
|
if (value === null || value === undefined) return null;
|
||||||
|
return typeof value === 'number' ? value !== 0 : Boolean(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toMinutes(value: number | string | null | undefined): number | null {
|
||||||
|
if (value === null || value === undefined) return null;
|
||||||
|
const n = typeof value === 'string' ? parseInt(value, 10) : value;
|
||||||
|
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolvePresaleClosure(
|
||||||
|
event: PresaleEventLike,
|
||||||
|
settings?: PresaleSettingsLike | null
|
||||||
|
): ResolvedPresaleClosure {
|
||||||
|
const enabled =
|
||||||
|
toBool(event.presaleClosureEnabled) ??
|
||||||
|
toBool(settings?.presaleClosureEnabled) ??
|
||||||
|
DEFAULT_PRESALE_CLOSURE_ENABLED;
|
||||||
|
const minutesBefore =
|
||||||
|
toMinutes(event.presaleCloseMinutesBefore) ??
|
||||||
|
toMinutes(settings?.presaleCloseMinutesBefore) ??
|
||||||
|
DEFAULT_PRESALE_CLOSE_MINUTES;
|
||||||
|
|
||||||
|
if (!enabled) return { enabled, minutesBefore, closesAt: null };
|
||||||
|
|
||||||
|
const startMs = new Date(event.startDatetime).getTime();
|
||||||
|
if (!Number.isFinite(startMs)) return { enabled, minutesBefore, closesAt: null };
|
||||||
|
|
||||||
|
return { enabled, minutesBefore, closesAt: new Date(startMs - minutesBefore * 60_000) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isPresaleClosed(
|
||||||
|
event: PresaleEventLike,
|
||||||
|
settings?: PresaleSettingsLike | null,
|
||||||
|
nowMs: number = Date.now()
|
||||||
|
): boolean {
|
||||||
|
const { closesAt } = resolvePresaleClosure(event, settings);
|
||||||
|
return closesAt !== null && closesAt.getTime() <= nowMs;
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { getClientIp, isTrustedProxyIp } from './rateLimit.js';
|
||||||
|
|
||||||
|
// Minimal Hono-Context stand-in: headers + the node-server env with the
|
||||||
|
// socket peer address.
|
||||||
|
function fakeContext(opts: { peer?: string; headers?: Record<string, string> }) {
|
||||||
|
const headers = new Map(
|
||||||
|
Object.entries(opts.headers || {}).map(([k, v]) => [k.toLowerCase(), v])
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
req: { header: (name: string) => headers.get(name.toLowerCase()) },
|
||||||
|
env: opts.peer ? { incoming: { socket: { remoteAddress: opts.peer } } } : {},
|
||||||
|
} as any;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('isTrustedProxyIp', () => {
|
||||||
|
it('trusts loopback and private ranges, including IPv4-mapped IPv6', () => {
|
||||||
|
expect(isTrustedProxyIp('127.0.0.1')).toBe(true);
|
||||||
|
expect(isTrustedProxyIp('::1')).toBe(true);
|
||||||
|
expect(isTrustedProxyIp('::ffff:127.0.0.1')).toBe(true);
|
||||||
|
expect(isTrustedProxyIp('10.1.2.3')).toBe(true);
|
||||||
|
expect(isTrustedProxyIp('172.18.0.5')).toBe(true);
|
||||||
|
expect(isTrustedProxyIp('192.168.1.1')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not trust public addresses or near-miss ranges', () => {
|
||||||
|
expect(isTrustedProxyIp('203.0.113.7')).toBe(false);
|
||||||
|
expect(isTrustedProxyIp('172.15.0.1')).toBe(false); // outside 172.16/12
|
||||||
|
expect(isTrustedProxyIp('172.32.0.1')).toBe(false);
|
||||||
|
expect(isTrustedProxyIp('1270.0.0.1')).toBe(false);
|
||||||
|
expect(isTrustedProxyIp('')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getClientIp', () => {
|
||||||
|
it('prefers X-Real-IP when the peer is a trusted proxy', () => {
|
||||||
|
const c = fakeContext({
|
||||||
|
peer: '127.0.0.1',
|
||||||
|
headers: { 'x-real-ip': '203.0.113.7', 'x-forwarded-for': '9.9.9.9' },
|
||||||
|
});
|
||||||
|
expect(getClientIp(c)).toBe('203.0.113.7');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('walks X-Forwarded-For from the right past our own proxy hops', () => {
|
||||||
|
// spoofed prefix, then the real client appended by nginx, then the Next
|
||||||
|
// proxy hop — the rightmost untrusted entry wins
|
||||||
|
const c = fakeContext({
|
||||||
|
peer: '127.0.0.1',
|
||||||
|
headers: { 'x-forwarded-for': '9.9.9.9, 203.0.113.7, 127.0.0.1' },
|
||||||
|
});
|
||||||
|
expect(getClientIp(c)).toBe('203.0.113.7');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores forwarded headers entirely when the peer is untrusted', () => {
|
||||||
|
// A client hitting the API directly cannot pick its own bucket
|
||||||
|
const c = fakeContext({
|
||||||
|
peer: '198.51.100.4',
|
||||||
|
headers: { 'x-forwarded-for': '9.9.9.9', 'x-real-ip': '8.8.8.8' },
|
||||||
|
});
|
||||||
|
expect(getClientIp(c)).toBe('198.51.100.4');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to the socket address for local traffic with no headers', () => {
|
||||||
|
expect(getClientIp(fakeContext({ peer: '127.0.0.1' }))).toBe('127.0.0.1');
|
||||||
|
expect(getClientIp(fakeContext({ peer: '::ffff:127.0.0.1' }))).toBe('127.0.0.1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to the socket address when every forwarded hop is internal', () => {
|
||||||
|
const c = fakeContext({
|
||||||
|
peer: '127.0.0.1',
|
||||||
|
headers: { 'x-forwarded-for': '127.0.0.1' },
|
||||||
|
});
|
||||||
|
expect(getClientIp(c)).toBe('127.0.0.1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects junk header values instead of using them as bucket keys', () => {
|
||||||
|
const c = fakeContext({
|
||||||
|
peer: '127.0.0.1',
|
||||||
|
headers: { 'x-forwarded-for': 'not-an-ip; DROP TABLE users' },
|
||||||
|
});
|
||||||
|
expect(getClientIp(c)).toBe('127.0.0.1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns "unknown" without a socket address or trusted headers', () => {
|
||||||
|
expect(getClientIp(fakeContext({}))).toBe('unknown');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -10,11 +10,68 @@ import { getRateLimiter } from './stores/rateLimiter.js';
|
|||||||
* (horizontal scaling). See lib/stores/rateLimiter.ts.
|
* (horizontal scaling). See lib/stores/rateLimiter.ts.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** Best-effort client IP extraction (honours common reverse-proxy headers). */
|
// Peers allowed to speak for the client via X-Real-IP / X-Forwarded-For:
|
||||||
|
// loopback (nginx on the same host, the Next.js proxy) and RFC1918 ranges
|
||||||
|
// (the docker-compose scale deployment, where nginx is another container).
|
||||||
|
// Extend with TRUSTED_PROXIES (comma-separated IP prefixes, e.g. "172.20.").
|
||||||
|
const DEFAULT_TRUSTED_PROXY_PREFIXES = ['127.', '10.', '192.168.', '::1'];
|
||||||
|
|
||||||
|
function trustedProxyPrefixes(): string[] {
|
||||||
|
const extra = (process.env.TRUSTED_PROXIES || '')
|
||||||
|
.split(',')
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
return [...DEFAULT_TRUSTED_PROXY_PREFIXES, ...extra];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Strip the IPv4-mapped IPv6 prefix so "::ffff:127.0.0.1" matches "127.". */
|
||||||
|
function normalizeIp(ip: string | undefined | null): string {
|
||||||
|
const trimmed = (ip || '').trim();
|
||||||
|
return trimmed.toLowerCase().startsWith('::ffff:') ? trimmed.slice(7) : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isTrustedProxyIp(ip: string): boolean {
|
||||||
|
const normalized = normalizeIp(ip);
|
||||||
|
if (!normalized) return false;
|
||||||
|
if (/^172\.(1[6-9]|2[0-9]|3[01])\./.test(normalized)) return true; // 172.16.0.0/12
|
||||||
|
return trustedProxyPrefixes().some((prefix) => normalized === prefix || normalized.startsWith(prefix));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rough shape check so a junk header value can't become a rate-limit key.
|
||||||
|
function looksLikeIp(value: string): boolean {
|
||||||
|
return value.length > 0 && value.length <= 45 && /^[0-9a-fA-F.:]+$/.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Spoof-resistant client IP resolution.
|
||||||
|
*
|
||||||
|
* The TCP peer address (via @hono/node-server's env.incoming) anchors the
|
||||||
|
* trust decision: forwarded headers are only honoured when the direct peer is
|
||||||
|
* one of our own proxies. X-Real-IP is preferred because nginx overwrites it
|
||||||
|
* at the edge (deploy/*.conf); X-Forwarded-For is append-only, so it is
|
||||||
|
* walked from the right past our proxy hops — the leftmost entries are
|
||||||
|
* client-controlled and never trusted on their own.
|
||||||
|
*/
|
||||||
export function getClientIp(c: Context): string {
|
export function getClientIp(c: Context): string {
|
||||||
|
const socketAddr = normalizeIp((c.env as any)?.incoming?.socket?.remoteAddress);
|
||||||
|
|
||||||
|
if (socketAddr && isTrustedProxyIp(socketAddr)) {
|
||||||
|
const realIp = normalizeIp(c.req.header('x-real-ip'));
|
||||||
|
if (realIp && looksLikeIp(realIp)) return realIp;
|
||||||
|
|
||||||
const forwarded = c.req.header('x-forwarded-for');
|
const forwarded = c.req.header('x-forwarded-for');
|
||||||
if (forwarded) return forwarded.split(',')[0].trim();
|
if (forwarded) {
|
||||||
return c.req.header('x-real-ip') || 'unknown';
|
const chain = forwarded.split(',').map((s) => normalizeIp(s)).filter(Boolean);
|
||||||
|
for (let i = chain.length - 1; i >= 0; i--) {
|
||||||
|
if (!isTrustedProxyIp(chain[i])) {
|
||||||
|
return looksLikeIp(chain[i]) ? chain[i] : socketAddr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Every hop is one of ours: a genuinely local/internal client.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return socketAddr || 'unknown';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+80
-10
@@ -4,7 +4,15 @@
|
|||||||
// before with in-memory backends. When set, this module owns a single shared
|
// before with in-memory backends. When set, this module owns a single shared
|
||||||
// command connection plus a dedicated subscriber connection (a connection in
|
// command connection plus a dedicated subscriber connection (a connection in
|
||||||
// subscribe mode cannot run normal commands), with auto-reconnect, capped
|
// subscribe mode cannot run normal commands), with auto-reconnect, capped
|
||||||
// backoff, and a health flag that callers and the health endpoint can read.
|
// backoff, an active PING probe, and a health flag that callers and the health
|
||||||
|
// endpoint can read.
|
||||||
|
//
|
||||||
|
// TLS: use a rediss:// URL — ioredis enables TLS from the scheme. A /N path
|
||||||
|
// selects a DB index (e.g. redis://host:6379/1) when sharing an instance.
|
||||||
|
// We deliberately do not use ioredis's keyPrefix option: all keys are already
|
||||||
|
// namespaced per subsystem (cache:, rl:, lock:, lockout:), and keyPrefix has a
|
||||||
|
// pub/sub asymmetry (SUBSCRIBE channels get prefixed, PUBLISH channels do not)
|
||||||
|
// that would silently break the payment SSE channel.
|
||||||
|
|
||||||
import Redis from 'ioredis';
|
import Redis from 'ioredis';
|
||||||
|
|
||||||
@@ -12,6 +20,14 @@ let client: Redis | null = null;
|
|||||||
let subscriber: Redis | null = null;
|
let subscriber: Redis | null = null;
|
||||||
let healthy = false;
|
let healthy = false;
|
||||||
let initialized = false;
|
let initialized = false;
|
||||||
|
let pingTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let lastPingOkAt: string | null = null;
|
||||||
|
let lastPingMs: number | null = null;
|
||||||
|
|
||||||
|
// Debounce repeated error logs during a sustained outage: transitions are
|
||||||
|
// always logged, repeated per-retry errors at most once per LOG_EVERY_MS.
|
||||||
|
const ERROR_LOG_EVERY_MS = 30_000;
|
||||||
|
let lastErrorLogAt = 0;
|
||||||
|
|
||||||
/** Whether Redis is configured via REDIS_URL. */
|
/** Whether Redis is configured via REDIS_URL. */
|
||||||
export function isRedisEnabled(): boolean {
|
export function isRedisEnabled(): boolean {
|
||||||
@@ -23,14 +39,41 @@ export function isRedisHealthy(): boolean {
|
|||||||
return isRedisEnabled() && healthy;
|
return isRedisEnabled() && healthy;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Detail for the health endpoint: when the last successful PING happened. */
|
||||||
|
export function getRedisHealthDetail(): { lastPingOkAt: string | null; lastPingMs: number | null } {
|
||||||
|
return { lastPingOkAt, lastPingMs };
|
||||||
|
}
|
||||||
|
|
||||||
|
function setHealthy(next: boolean, context: string): void {
|
||||||
|
if (next !== healthy) {
|
||||||
|
if (next) {
|
||||||
|
console.log(`[redis] healthy (${context})`);
|
||||||
|
} else {
|
||||||
|
console.warn(`[redis] unhealthy (${context})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
healthy = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function logErrorDebounced(label: string, err: unknown): void {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - lastErrorLogAt >= ERROR_LOG_EVERY_MS) {
|
||||||
|
lastErrorLogAt = now;
|
||||||
|
console.error(`[redis] (${label}) error:`, (err as any)?.message || err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function buildClient(label: string): Redis {
|
function buildClient(label: string): Redis {
|
||||||
const url = process.env.REDIS_URL as string;
|
const url = process.env.REDIS_URL as string;
|
||||||
const instance = new Redis(url, {
|
const instance = new Redis(url, {
|
||||||
// Keep the process responsive: fail fast on a per-command basis and let the
|
// Keep the process responsive: fail fast on a per-command basis and let the
|
||||||
// callers degrade to their in-memory fallback rather than hanging.
|
// callers degrade to their in-memory fallback rather than hanging. Do not
|
||||||
|
// queue commands while disconnected — with fail-open callers everywhere a
|
||||||
|
// growing offline queue would only add latency and memory pressure.
|
||||||
maxRetriesPerRequest: 1,
|
maxRetriesPerRequest: 1,
|
||||||
enableOfflineQueue: false,
|
enableOfflineQueue: false,
|
||||||
lazyConnect: false,
|
lazyConnect: false,
|
||||||
|
connectTimeout: 5000,
|
||||||
retryStrategy(times) {
|
retryStrategy(times) {
|
||||||
// Capped exponential backoff for reconnects: 200ms, 400ms ... max 5s.
|
// Capped exponential backoff for reconnects: 200ms, 400ms ... max 5s.
|
||||||
const delay = Math.min(times * 200, 5000);
|
const delay = Math.min(times * 200, 5000);
|
||||||
@@ -42,30 +85,53 @@ function buildClient(label: string): Redis {
|
|||||||
console.log(`[redis] (${label}) connecting`);
|
console.log(`[redis] (${label}) connecting`);
|
||||||
});
|
});
|
||||||
instance.on('ready', () => {
|
instance.on('ready', () => {
|
||||||
healthy = true;
|
setHealthy(true, `${label} ready`);
|
||||||
console.log(`[redis] (${label}) ready`);
|
|
||||||
});
|
});
|
||||||
instance.on('error', (err) => {
|
instance.on('error', (err) => {
|
||||||
healthy = false;
|
setHealthy(false, `${label} error`);
|
||||||
console.error(`[redis] (${label}) error:`, err?.message || err);
|
logErrorDebounced(label, err);
|
||||||
});
|
});
|
||||||
instance.on('reconnecting', () => {
|
instance.on('reconnecting', () => {
|
||||||
healthy = false;
|
setHealthy(false, `${label} reconnecting`);
|
||||||
console.warn(`[redis] (${label}) reconnecting`);
|
|
||||||
});
|
});
|
||||||
instance.on('end', () => {
|
instance.on('end', () => {
|
||||||
healthy = false;
|
setHealthy(false, `${label} connection closed`);
|
||||||
console.warn(`[redis] (${label}) connection closed`);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Actively probe the command connection. The event-driven flag alone misses a
|
||||||
|
// silently hung connection; a periodic PING with a hard timeout catches it.
|
||||||
|
async function pingOnce(): Promise<void> {
|
||||||
|
if (!client) return;
|
||||||
|
const started = Date.now();
|
||||||
|
try {
|
||||||
|
await Promise.race([
|
||||||
|
client.ping(),
|
||||||
|
new Promise((_, reject) => {
|
||||||
|
const t = setTimeout(() => reject(new Error('ping timeout')), 2000);
|
||||||
|
(t as any).unref?.();
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
lastPingMs = Date.now() - started;
|
||||||
|
lastPingOkAt = new Date().toISOString();
|
||||||
|
setHealthy(true, 'ping ok');
|
||||||
|
} catch (err) {
|
||||||
|
setHealthy(false, 'ping failed');
|
||||||
|
logErrorDebounced('ping', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function ensureInit(): void {
|
function ensureInit(): void {
|
||||||
if (initialized || !isRedisEnabled()) return;
|
if (initialized || !isRedisEnabled()) return;
|
||||||
initialized = true;
|
initialized = true;
|
||||||
client = buildClient('commands');
|
client = buildClient('commands');
|
||||||
subscriber = buildClient('subscriber');
|
subscriber = buildClient('subscriber');
|
||||||
|
pingTimer = setInterval(() => {
|
||||||
|
void pingOnce();
|
||||||
|
}, 10_000);
|
||||||
|
(pingTimer as any).unref?.();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Shared command connection, or null when Redis is not configured. */
|
/** Shared command connection, or null when Redis is not configured. */
|
||||||
@@ -82,6 +148,10 @@ export function getSubscriber(): Redis | null {
|
|||||||
|
|
||||||
/** Close connections (used for graceful shutdown). */
|
/** Close connections (used for graceful shutdown). */
|
||||||
export async function closeRedis(): Promise<void> {
|
export async function closeRedis(): Promise<void> {
|
||||||
|
if (pingTimer) {
|
||||||
|
clearInterval(pingTimer);
|
||||||
|
pingTimer = null;
|
||||||
|
}
|
||||||
const tasks: Promise<unknown>[] = [];
|
const tasks: Promise<unknown>[] = [];
|
||||||
if (client) tasks.push(client.quit().catch(() => undefined));
|
if (client) tasks.push(client.quit().catch(() => undefined));
|
||||||
if (subscriber) tasks.push(subscriber.quit().catch(() => undefined));
|
if (subscriber) tasks.push(subscriber.quit().catch(() => undefined));
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { resolveSalesState, publicSalesFields, isOnlineSalesClosed } from './salesState.js';
|
||||||
|
|
||||||
|
const START = '2030-01-01T23:00:00.000Z'; // 20:00 in Asunción
|
||||||
|
const END = '2030-01-02T02:00:00.000Z';
|
||||||
|
const startMs = new Date(START).getTime();
|
||||||
|
const minutes = (n: number) => n * 60_000;
|
||||||
|
|
||||||
|
// Pre-sale closes 120 minutes before the start (the site default).
|
||||||
|
const event = {
|
||||||
|
status: 'published',
|
||||||
|
startDatetime: START,
|
||||||
|
endDatetime: END,
|
||||||
|
externalBookingEnabled: false,
|
||||||
|
price: 21000,
|
||||||
|
walkInPrice: 30000 as number | null,
|
||||||
|
};
|
||||||
|
const settings = { presaleClosureEnabled: true, presaleCloseMinutesBefore: 120 };
|
||||||
|
const beforeClose = startMs - minutes(121);
|
||||||
|
const afterClose = startMs - minutes(60);
|
||||||
|
|
||||||
|
describe('resolveSalesState', () => {
|
||||||
|
it('is online while pre-sale is open and seats are left', () => {
|
||||||
|
expect(resolveSalesState(event, settings, 10, beforeClose)).toBe('online');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is door after pre-sale closes, until the event ends', () => {
|
||||||
|
expect(resolveSalesState(event, settings, 10, afterClose)).toBe('door');
|
||||||
|
expect(resolveSalesState(event, settings, 10, startMs + minutes(30))).toBe('door');
|
||||||
|
expect(resolveSalesState(event, settings, 10, new Date(END).getTime() - 1)).toBe('door');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is sold_out with no seats left, online or at the door', () => {
|
||||||
|
expect(resolveSalesState(event, settings, 0, beforeClose)).toBe('sold_out');
|
||||||
|
expect(resolveSalesState(event, settings, 0, afterClose)).toBe('sold_out');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is ended once the end time passes, or the start time when there is no end', () => {
|
||||||
|
expect(resolveSalesState(event, settings, 10, new Date(END).getTime())).toBe('ended');
|
||||||
|
expect(resolveSalesState(event, settings, 0, new Date(END).getTime())).toBe('ended');
|
||||||
|
expect(resolveSalesState({ ...event, endDatetime: null }, settings, 10, startMs)).toBe('ended');
|
||||||
|
expect(resolveSalesState({ ...event, status: 'completed' }, settings, 10, beforeClose)).toBe('ended');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is external for external booking events, with no door state', () => {
|
||||||
|
const external = { ...event, externalBookingEnabled: true };
|
||||||
|
expect(resolveSalesState(external, settings, 10, beforeClose)).toBe('external');
|
||||||
|
expect(resolveSalesState(external, settings, 10, afterClose)).toBe('external');
|
||||||
|
expect(resolveSalesState({ ...event, externalBookingEnabled: 1 }, settings, 10, afterClose)).toBe('external');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps cancelled events cancelled', () => {
|
||||||
|
expect(resolveSalesState({ ...event, status: 'cancelled' }, settings, 10, afterClose)).toBe('cancelled');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closes online sales at the start when pre-sale closure is off', () => {
|
||||||
|
const noClosure = { ...event, presaleClosureEnabled: false };
|
||||||
|
expect(resolveSalesState(noClosure, settings, 10, startMs - 1)).toBe('online');
|
||||||
|
expect(resolveSalesState(noClosure, settings, 10, startMs)).toBe('door');
|
||||||
|
expect(isOnlineSalesClosed(noClosure, settings, startMs - 1)).toBe(false);
|
||||||
|
expect(isOnlineSalesClosed(noClosure, settings, startMs)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('publicSalesFields', () => {
|
||||||
|
it('door with walk_in_price set: doorPrice is the walk-in price', () => {
|
||||||
|
expect(publicSalesFields(event, settings, 48, afterClose)).toEqual({ salesState: 'door', doorPrice: 30000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('door with walk_in_price null: doorPrice falls back to the ticket price', () => {
|
||||||
|
expect(publicSalesFields({ ...event, walkInPrice: null }, settings, 48, afterClose))
|
||||||
|
.toEqual({ salesState: 'door', doorPrice: 21000 });
|
||||||
|
// Postgres decimals arrive as strings
|
||||||
|
expect(publicSalesFields({ ...event, price: '21000.00', walkInPrice: null }, settings, 48, afterClose).doorPrice)
|
||||||
|
.toBe(21000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('door with a free walk-in keeps 0, not the ticket price', () => {
|
||||||
|
expect(publicSalesFields({ ...event, walkInPrice: 0 }, settings, 48, afterClose).doorPrice).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits doorPrice in every other state', () => {
|
||||||
|
const cases: Array<[number, number, any]> = [
|
||||||
|
[10, beforeClose, event], // online
|
||||||
|
[0, afterClose, event], // sold_out
|
||||||
|
[10, new Date(END).getTime(), event], // ended
|
||||||
|
[10, afterClose, { ...event, externalBookingEnabled: true }], // external
|
||||||
|
[10, afterClose, { ...event, status: 'cancelled' }], // cancelled
|
||||||
|
];
|
||||||
|
for (const [spots, now, e] of cases) {
|
||||||
|
const fields = publicSalesFields(e, settings, spots, now);
|
||||||
|
expect(fields.salesState).not.toBe('door');
|
||||||
|
expect(fields).not.toHaveProperty('doorPrice');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
// Public sales state of an event: what the event page offers a visitor right now.
|
||||||
|
//
|
||||||
|
// online pre-sale open and seats left (book online)
|
||||||
|
// door online sales closed, the event has not ended and seats are left:
|
||||||
|
// people can still come and pay at the door until the event ends
|
||||||
|
// sold_out no seats left, online or at the door
|
||||||
|
// ended the event is over (end time passed, or status completed/archived)
|
||||||
|
// external bookings happen on an external site; no door state
|
||||||
|
// cancelled the event was cancelled
|
||||||
|
//
|
||||||
|
// This is the single source of truth for the public page, listings and JSON-LD.
|
||||||
|
// Online sales close at the pre-sale cutoff (lib/presale.ts) or, when pre-sale
|
||||||
|
// closure is off, when the event starts — the booking API enforces the same rule
|
||||||
|
// through isOnlineSalesClosed. The state flips on the clock without any edit to
|
||||||
|
// the event, so cached copies must be refreshed around presaleClosesAt.
|
||||||
|
|
||||||
|
import { isPresaleClosed, type PresaleEventLike, type PresaleSettingsLike } from './presale.js';
|
||||||
|
import { resolveWalkInPrice } from './walkInPrice.js';
|
||||||
|
|
||||||
|
export type SalesState = 'online' | 'door' | 'sold_out' | 'ended' | 'external' | 'cancelled';
|
||||||
|
|
||||||
|
export interface SalesStateEventLike extends PresaleEventLike {
|
||||||
|
status: string;
|
||||||
|
endDatetime?: string | Date | null;
|
||||||
|
externalBookingEnabled?: boolean | number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** When the event ends: its end time, or its start time when no end is set (as in eventEndSweep). */
|
||||||
|
export function eventEndMs(event: { startDatetime: string | Date; endDatetime?: string | Date | null }): number {
|
||||||
|
return new Date(event.endDatetime || event.startDatetime).getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True once online booking is closed: pre-sale cutoff passed, or the event has started. */
|
||||||
|
export function isOnlineSalesClosed(
|
||||||
|
event: PresaleEventLike,
|
||||||
|
settings?: PresaleSettingsLike | null,
|
||||||
|
nowMs: number = Date.now()
|
||||||
|
): boolean {
|
||||||
|
return isPresaleClosed(event, settings, nowMs) || new Date(event.startDatetime).getTime() <= nowMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveSalesState(
|
||||||
|
event: SalesStateEventLike,
|
||||||
|
settings: PresaleSettingsLike | null | undefined,
|
||||||
|
spotsLeft: number,
|
||||||
|
nowMs: number = Date.now()
|
||||||
|
): SalesState {
|
||||||
|
if (event.status === 'cancelled') return 'cancelled';
|
||||||
|
if (event.status === 'completed' || event.status === 'archived') return 'ended';
|
||||||
|
if (Boolean(event.externalBookingEnabled)) return 'external';
|
||||||
|
if (eventEndMs(event) <= nowMs) return 'ended';
|
||||||
|
if (spotsLeft <= 0) return 'sold_out';
|
||||||
|
if (isOnlineSalesClosed(event, settings, nowMs)) return 'door';
|
||||||
|
return 'online';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sales fields for a public event response. `doorPrice` (the resolved walk-in
|
||||||
|
* price: walk_in_price, else the ticket price) is present only in the `door`
|
||||||
|
* state, so the internal walk-in price never leaks while online sales are open.
|
||||||
|
* `event` is the raw row (it still carries walkInPrice).
|
||||||
|
*/
|
||||||
|
export function publicSalesFields(
|
||||||
|
event: SalesStateEventLike & { price: unknown; walkInPrice?: unknown },
|
||||||
|
settings: PresaleSettingsLike | null | undefined,
|
||||||
|
spotsLeft: number,
|
||||||
|
nowMs: number = Date.now()
|
||||||
|
): { salesState: SalesState; doorPrice?: number } {
|
||||||
|
const salesState = resolveSalesState(event, settings, spotsLeft, nowMs);
|
||||||
|
if (salesState !== 'door') return { salesState };
|
||||||
|
return { salesState, doorPrice: resolveWalkInPrice(event).unitPrice };
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import RedisMock from 'ioredis-mock';
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({ redis: null as any }));
|
||||||
|
|
||||||
|
vi.mock('../redis.js', () => ({
|
||||||
|
isRedisEnabled: () => true,
|
||||||
|
getRedis: () => mocks.redis,
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { MemoryLock, RedisLock, LockUnavailableError } from './lock.js';
|
||||||
|
|
||||||
|
describe('MemoryLock', () => {
|
||||||
|
it('grants the lock, blocks contenders, and frees on release', async () => {
|
||||||
|
const lock = new MemoryLock();
|
||||||
|
const token = await lock.acquire('a', 60_000);
|
||||||
|
expect(token).toBeTruthy();
|
||||||
|
expect(await lock.acquire('a', 60_000)).toBeNull();
|
||||||
|
await lock.release('a', token!);
|
||||||
|
expect(await lock.acquire('a', 60_000)).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores release with the wrong token', async () => {
|
||||||
|
const lock = new MemoryLock();
|
||||||
|
const token = await lock.acquire('a', 60_000);
|
||||||
|
await lock.release('a', 'not-the-token');
|
||||||
|
expect(await lock.acquire('a', 60_000)).toBeNull();
|
||||||
|
await lock.release('a', token!);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('withLock runs fn while held and returns null under contention', async () => {
|
||||||
|
const lock = new MemoryLock();
|
||||||
|
const held = await lock.acquire('a', 60_000);
|
||||||
|
expect(await lock.withLock('a', 60_000, async () => 'ran')).toBeNull();
|
||||||
|
await lock.release('a', held!);
|
||||||
|
expect(await lock.withLock('a', 60_000, async () => 'ran')).toBe('ran');
|
||||||
|
// Released after withLock completes.
|
||||||
|
expect(await lock.acquire('a', 60_000)).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RedisLock', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
mocks.redis = new RedisMock();
|
||||||
|
// ioredis-mock shares data between instances by connection string.
|
||||||
|
await mocks.redis.flushall();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('grants the lock and blocks contenders', async () => {
|
||||||
|
const lock = new RedisLock();
|
||||||
|
const token = await lock.acquire('a', 60_000);
|
||||||
|
expect(token).toBeTruthy();
|
||||||
|
expect(await lock.acquire('a', 60_000)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('release is compare-and-delete: wrong token does not free the lock', async () => {
|
||||||
|
const lock = new RedisLock();
|
||||||
|
const token = await lock.acquire('a', 60_000);
|
||||||
|
await lock.release('a', 'not-the-token');
|
||||||
|
expect(await lock.acquire('a', 60_000)).toBeNull();
|
||||||
|
await lock.release('a', token!);
|
||||||
|
expect(await lock.acquire('a', 60_000)).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws LockUnavailableError when the client is not initialized', async () => {
|
||||||
|
mocks.redis = null;
|
||||||
|
const lock = new RedisLock();
|
||||||
|
await expect(lock.acquire('a', 60_000)).rejects.toBeInstanceOf(LockUnavailableError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws LockUnavailableError when the backend errors', async () => {
|
||||||
|
mocks.redis = { set: () => Promise.reject(new Error('connection refused')) };
|
||||||
|
const lock = new RedisLock();
|
||||||
|
await expect(lock.acquire('a', 60_000)).rejects.toBeInstanceOf(LockUnavailableError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('withLock skips (returns null, fn not called) when unavailable by default', async () => {
|
||||||
|
mocks.redis = null;
|
||||||
|
const lock = new RedisLock();
|
||||||
|
const fn = vi.fn(async () => 'ran');
|
||||||
|
expect(await lock.withLock('a', 60_000, fn)).toBeNull();
|
||||||
|
expect(fn).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('withLock runs fn without the lock when onUnavailable is "run"', async () => {
|
||||||
|
mocks.redis = null;
|
||||||
|
const lock = new RedisLock();
|
||||||
|
const fn = vi.fn(async () => 'ran');
|
||||||
|
expect(await lock.withLock('a', 60_000, fn, { onUnavailable: 'run' })).toBe('ran');
|
||||||
|
expect(fn).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('withLock returns fn result and releases the lock afterwards', async () => {
|
||||||
|
const lock = new RedisLock();
|
||||||
|
expect(await lock.withLock('a', 60_000, async () => 42)).toBe(42);
|
||||||
|
expect(await lock.acquire('a', 60_000)).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -5,22 +5,45 @@
|
|||||||
//
|
//
|
||||||
// Use acquire/release for long-lived ownership (e.g. a background poller) and
|
// Use acquire/release for long-lived ownership (e.g. a background poller) and
|
||||||
// withLock for a one-shot critical section. Selection is based on REDIS_URL.
|
// withLock for a one-shot critical section. Selection is based on REDIS_URL.
|
||||||
|
//
|
||||||
|
// There is deliberately no auto-renewal/watchdog: every guarded section (sweep
|
||||||
|
// jobs, template seeding) is a handful of status-conditional bulk UPDATEs that
|
||||||
|
// finish far below the lock TTL, and a rare TTL overrun only risks one
|
||||||
|
// idempotent overlapping run. Keep TTLs generous instead of adding renewal.
|
||||||
|
|
||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
import { getRedis, isRedisEnabled } from '../redis.js';
|
import { getRedis, isRedisEnabled } from '../redis.js';
|
||||||
|
|
||||||
|
// Thrown when Redis is configured but the lock backend cannot be reached.
|
||||||
|
// This is distinct from contention (acquire resolves null): the caller must
|
||||||
|
// decide whether its critical section is safe to run without mutual exclusion.
|
||||||
|
export class LockUnavailableError extends Error {
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'LockUnavailableError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WithLockOptions {
|
||||||
|
// What withLock should do when the lock backend is unavailable (not mere
|
||||||
|
// contention): 'skip' (default) returns null as if the lock were held
|
||||||
|
// elsewhere; 'run' executes fn without mutual exclusion.
|
||||||
|
onUnavailable?: 'skip' | 'run';
|
||||||
|
}
|
||||||
|
|
||||||
export interface Lock {
|
export interface Lock {
|
||||||
readonly backend: 'memory' | 'redis';
|
readonly backend: 'memory' | 'redis';
|
||||||
// Returns a token when the lock was acquired, or null when already held.
|
// Returns a token when the lock was acquired, or null when already held.
|
||||||
|
// Throws LockUnavailableError when the backend is configured but erroring.
|
||||||
acquire(key: string, ttlMs: number): Promise<string | null>;
|
acquire(key: string, ttlMs: number): Promise<string | null>;
|
||||||
release(key: string, token: string): Promise<void>;
|
release(key: string, token: string): Promise<void>;
|
||||||
// Runs fn while holding the lock; returns fn's result, or null if not acquired.
|
// Runs fn while holding the lock; returns fn's result, or null if not acquired.
|
||||||
withLock<T>(key: string, ttlMs: number, fn: () => Promise<T>): Promise<T | null>;
|
withLock<T>(key: string, ttlMs: number, fn: () => Promise<T>, opts?: WithLockOptions): Promise<T | null>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==================== Memory implementation ====================
|
// ==================== Memory implementation ====================
|
||||||
|
|
||||||
class MemoryLock implements Lock {
|
export class MemoryLock implements Lock {
|
||||||
readonly backend = 'memory' as const;
|
readonly backend = 'memory' as const;
|
||||||
private held = new Map<string, { token: string; expiresAt: number }>();
|
private held = new Map<string, { token: string; expiresAt: number }>();
|
||||||
|
|
||||||
@@ -58,23 +81,23 @@ class MemoryLock implements Lock {
|
|||||||
const RELEASE_SCRIPT =
|
const RELEASE_SCRIPT =
|
||||||
'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
|
'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
|
||||||
|
|
||||||
class RedisLock implements Lock {
|
export class RedisLock implements Lock {
|
||||||
readonly backend = 'redis' as const;
|
readonly backend = 'redis' as const;
|
||||||
|
|
||||||
async acquire(key: string, ttlMs: number): Promise<string | null> {
|
async acquire(key: string, ttlMs: number): Promise<string | null> {
|
||||||
const redis = getRedis();
|
const redis = getRedis();
|
||||||
if (!redis) {
|
if (!redis) {
|
||||||
// Redis configured but unavailable: do not block critical sections.
|
throw new LockUnavailableError('redis client not initialized');
|
||||||
return randomUUID();
|
|
||||||
}
|
}
|
||||||
const token = randomUUID();
|
const token = randomUUID();
|
||||||
try {
|
try {
|
||||||
const result = await redis.set(`lock:${key}`, token, 'PX', ttlMs, 'NX');
|
const result = await redis.set(`lock:${key}`, token, 'PX', ttlMs, 'NX');
|
||||||
return result === 'OK' ? token : null;
|
return result === 'OK' ? token : null;
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.error('[lock] redis acquire error, proceeding without lock:', err?.message || err);
|
// Do NOT fabricate a token here: during an outage every replica would
|
||||||
// Fail open so a Redis outage does not deadlock startup or jobs.
|
// "acquire" every lock and run the guarded sections concurrently. Let the
|
||||||
return randomUUID();
|
// caller choose between skipping the run and running unlocked.
|
||||||
|
throw new LockUnavailableError(err?.message || String(err));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,8 +111,19 @@ class RedisLock implements Lock {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async withLock<T>(key: string, ttlMs: number, fn: () => Promise<T>): Promise<T | null> {
|
async withLock<T>(key: string, ttlMs: number, fn: () => Promise<T>, opts?: WithLockOptions): Promise<T | null> {
|
||||||
const token = await this.acquire(key, ttlMs);
|
let token: string | null;
|
||||||
|
try {
|
||||||
|
token = await this.acquire(key, ttlMs);
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof LockUnavailableError)) throw err;
|
||||||
|
if (opts?.onUnavailable === 'run') {
|
||||||
|
console.warn(`[lock] backend unavailable, running "${key}" WITHOUT mutual exclusion:`, err.message);
|
||||||
|
return fn();
|
||||||
|
}
|
||||||
|
console.warn(`[lock] backend unavailable, skipping "${key}" this run:`, err.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
if (!token) return null;
|
if (!token) return null;
|
||||||
try {
|
try {
|
||||||
return await fn();
|
return await fn();
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import RedisMock from 'ioredis-mock';
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({ redis: null as any }));
|
||||||
|
|
||||||
|
vi.mock('../redis.js', () => ({
|
||||||
|
isRedisEnabled: () => true,
|
||||||
|
getRedis: () => mocks.redis,
|
||||||
|
}));
|
||||||
|
|
||||||
|
import {
|
||||||
|
MemoryLoginLockout,
|
||||||
|
RedisLoginLockout,
|
||||||
|
MAX_LOGIN_ATTEMPTS,
|
||||||
|
} from './loginLockout.js';
|
||||||
|
|
||||||
|
describe('MemoryLoginLockout', () => {
|
||||||
|
it('locks after MAX_LOGIN_ATTEMPTS failures with retryAfter', async () => {
|
||||||
|
const lockout = new MemoryLoginLockout();
|
||||||
|
for (let i = 0; i < MAX_LOGIN_ATTEMPTS - 1; i++) {
|
||||||
|
await lockout.recordFailure('user@example.com');
|
||||||
|
expect((await lockout.isLocked('user@example.com')).locked).toBe(false);
|
||||||
|
}
|
||||||
|
await lockout.recordFailure('user@example.com');
|
||||||
|
const status = await lockout.isLocked('user@example.com');
|
||||||
|
expect(status.locked).toBe(true);
|
||||||
|
expect(status.retryAfter).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clear removes the lockout', async () => {
|
||||||
|
const lockout = new MemoryLoginLockout();
|
||||||
|
for (let i = 0; i < MAX_LOGIN_ATTEMPTS; i++) {
|
||||||
|
await lockout.recordFailure('user@example.com');
|
||||||
|
}
|
||||||
|
await lockout.clear('user@example.com');
|
||||||
|
expect((await lockout.isLocked('user@example.com')).locked).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats emails case-insensitively', async () => {
|
||||||
|
const lockout = new MemoryLoginLockout();
|
||||||
|
for (let i = 0; i < MAX_LOGIN_ATTEMPTS; i++) {
|
||||||
|
await lockout.recordFailure('User@Example.com');
|
||||||
|
}
|
||||||
|
expect((await lockout.isLocked('user@example.com')).locked).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('expires after the lockout window', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
try {
|
||||||
|
const lockout = new MemoryLoginLockout();
|
||||||
|
for (let i = 0; i < MAX_LOGIN_ATTEMPTS; i++) {
|
||||||
|
await lockout.recordFailure('user@example.com');
|
||||||
|
}
|
||||||
|
expect((await lockout.isLocked('user@example.com')).locked).toBe(true);
|
||||||
|
vi.advanceTimersByTime(16 * 60 * 1000);
|
||||||
|
expect((await lockout.isLocked('user@example.com')).locked).toBe(false);
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RedisLoginLockout', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
mocks.redis = new RedisMock();
|
||||||
|
// ioredis-mock shares data between instances by connection string.
|
||||||
|
await mocks.redis.flushall();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('locks after MAX_LOGIN_ATTEMPTS failures shared via redis', async () => {
|
||||||
|
const lockout = new RedisLoginLockout();
|
||||||
|
for (let i = 0; i < MAX_LOGIN_ATTEMPTS - 1; i++) {
|
||||||
|
await lockout.recordFailure('user@example.com');
|
||||||
|
expect((await lockout.isLocked('user@example.com')).locked).toBe(false);
|
||||||
|
}
|
||||||
|
await lockout.recordFailure('user@example.com');
|
||||||
|
const status = await lockout.isLocked('user@example.com');
|
||||||
|
expect(status.locked).toBe(true);
|
||||||
|
expect(status.retryAfter).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets the lockout window TTL on the first failure', async () => {
|
||||||
|
const lockout = new RedisLoginLockout();
|
||||||
|
await lockout.recordFailure('user@example.com');
|
||||||
|
const ttl = await mocks.redis.pttl('lockout:user@example.com');
|
||||||
|
expect(ttl).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clear removes the lockout', async () => {
|
||||||
|
const lockout = new RedisLoginLockout();
|
||||||
|
for (let i = 0; i < MAX_LOGIN_ATTEMPTS; i++) {
|
||||||
|
await lockout.recordFailure('user@example.com');
|
||||||
|
}
|
||||||
|
await lockout.clear('user@example.com');
|
||||||
|
expect((await lockout.isLocked('user@example.com')).locked).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats emails case-insensitively', async () => {
|
||||||
|
const lockout = new RedisLoginLockout();
|
||||||
|
for (let i = 0; i < MAX_LOGIN_ATTEMPTS; i++) {
|
||||||
|
await lockout.recordFailure('User@Example.com');
|
||||||
|
}
|
||||||
|
expect((await lockout.isLocked('user@example.com')).locked).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails open when the client is not initialized', async () => {
|
||||||
|
mocks.redis = null;
|
||||||
|
const lockout = new RedisLoginLockout();
|
||||||
|
await expect(lockout.recordFailure('user@example.com')).resolves.toBeUndefined();
|
||||||
|
expect((await lockout.isLocked('user@example.com')).locked).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails open when the backend errors', async () => {
|
||||||
|
mocks.redis = {
|
||||||
|
get: () => Promise.reject(new Error('connection refused')),
|
||||||
|
pttl: () => Promise.reject(new Error('connection refused')),
|
||||||
|
del: () => Promise.reject(new Error('connection refused')),
|
||||||
|
lockoutRecordFailure: () => Promise.reject(new Error('connection refused')),
|
||||||
|
};
|
||||||
|
const lockout = new RedisLoginLockout();
|
||||||
|
await expect(lockout.recordFailure('user@example.com')).resolves.toBeUndefined();
|
||||||
|
expect((await lockout.isLocked('user@example.com')).locked).toBe(false);
|
||||||
|
await expect(lockout.clear('user@example.com')).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
// Per-email login lockout abstraction with two implementations:
|
||||||
|
// - memory: per-process Map (the original routes/auth.ts behavior)
|
||||||
|
// - redis: shared counter across all instances so the lockout cannot be
|
||||||
|
// bypassed by round-robining replicas
|
||||||
|
//
|
||||||
|
// Semantics: recordFailure starts a window on the first failure; once the
|
||||||
|
// failure count reaches the max the email is locked until the window expires;
|
||||||
|
// clear removes the counter on successful login. Selection is based on
|
||||||
|
// REDIS_URL. The redis implementation fails open (never locked, failures not
|
||||||
|
// recorded) — the per-IP auth rate limit remains as a backstop during a
|
||||||
|
// Redis outage.
|
||||||
|
|
||||||
|
import type Redis from 'ioredis';
|
||||||
|
import { getRedis, isRedisEnabled } from '../redis.js';
|
||||||
|
|
||||||
|
export const MAX_LOGIN_ATTEMPTS = 5;
|
||||||
|
export const LOCKOUT_DURATION_MS = 15 * 60 * 1000; // 15 minutes
|
||||||
|
|
||||||
|
export interface LockoutStatus {
|
||||||
|
locked: boolean;
|
||||||
|
// Seconds until the lockout lifts; only set when locked.
|
||||||
|
retryAfter?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginLockout {
|
||||||
|
readonly backend: 'memory' | 'redis';
|
||||||
|
isLocked(email: string): Promise<LockoutStatus>;
|
||||||
|
recordFailure(email: string): Promise<void>;
|
||||||
|
clear(email: string): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Emails are compared case-insensitively so "User@x.com" and "user@x.com"
|
||||||
|
// share one counter.
|
||||||
|
function normalize(email: string): string {
|
||||||
|
return email.trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Memory implementation ====================
|
||||||
|
|
||||||
|
export class MemoryLoginLockout implements LoginLockout {
|
||||||
|
readonly backend = 'memory' as const;
|
||||||
|
private attempts = new Map<string, { count: number; resetAt: number }>();
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
// Periodically drop expired entries so the Map does not grow unbounded.
|
||||||
|
const cleanup = setInterval(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [key, entry] of this.attempts) {
|
||||||
|
if (now > entry.resetAt) this.attempts.delete(key);
|
||||||
|
}
|
||||||
|
}, 60_000);
|
||||||
|
(cleanup as any).unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
async isLocked(email: string): Promise<LockoutStatus> {
|
||||||
|
const entry = this.attempts.get(normalize(email));
|
||||||
|
const now = Date.now();
|
||||||
|
if (!entry || now > entry.resetAt) return { locked: false };
|
||||||
|
if (entry.count >= MAX_LOGIN_ATTEMPTS) {
|
||||||
|
return { locked: true, retryAfter: Math.ceil((entry.resetAt - now) / 1000) };
|
||||||
|
}
|
||||||
|
return { locked: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
async recordFailure(email: string): Promise<void> {
|
||||||
|
const key = normalize(email);
|
||||||
|
const now = Date.now();
|
||||||
|
const entry = this.attempts.get(key);
|
||||||
|
if (!entry || now > entry.resetAt) {
|
||||||
|
this.attempts.set(key, { count: 1, resetAt: now + LOCKOUT_DURATION_MS });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
entry.count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
async clear(email: string): Promise<void> {
|
||||||
|
this.attempts.delete(normalize(email));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Redis implementation ====================
|
||||||
|
|
||||||
|
// Same atomic INCR+PEXPIRE shape as the rate limiter's consume script: the
|
||||||
|
// window starts at the first failure and any TTL-less counter is repaired.
|
||||||
|
const RECORD_FAILURE_SCRIPT = `
|
||||||
|
local count = redis.call('INCR', KEYS[1])
|
||||||
|
if count == 1 then
|
||||||
|
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
||||||
|
end
|
||||||
|
if redis.call('PTTL', KEYS[1]) < 0 then
|
||||||
|
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
||||||
|
end
|
||||||
|
return count
|
||||||
|
`;
|
||||||
|
|
||||||
|
type RedisWithLockout = Redis & {
|
||||||
|
lockoutRecordFailure(key: string, windowMs: number): Promise<number>;
|
||||||
|
};
|
||||||
|
|
||||||
|
function withLockoutCommand(redis: Redis): RedisWithLockout {
|
||||||
|
if (typeof (redis as any).lockoutRecordFailure !== 'function') {
|
||||||
|
redis.defineCommand('lockoutRecordFailure', { numberOfKeys: 1, lua: RECORD_FAILURE_SCRIPT });
|
||||||
|
}
|
||||||
|
return redis as RedisWithLockout;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RedisLoginLockout implements LoginLockout {
|
||||||
|
readonly backend = 'redis' as const;
|
||||||
|
|
||||||
|
private key(email: string): string {
|
||||||
|
return `lockout:${normalize(email)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async isLocked(email: string): Promise<LockoutStatus> {
|
||||||
|
const redis = getRedis();
|
||||||
|
if (!redis) return { locked: false };
|
||||||
|
try {
|
||||||
|
const [count, ttl] = await Promise.all([
|
||||||
|
redis.get(this.key(email)),
|
||||||
|
redis.pttl(this.key(email)),
|
||||||
|
]);
|
||||||
|
if (count !== null && parseInt(count, 10) >= MAX_LOGIN_ATTEMPTS) {
|
||||||
|
const retryAfter = ttl > 0 ? Math.ceil(ttl / 1000) : Math.ceil(LOCKOUT_DURATION_MS / 1000);
|
||||||
|
return { locked: true, retryAfter };
|
||||||
|
}
|
||||||
|
return { locked: false };
|
||||||
|
} catch (err: any) {
|
||||||
|
// Fail open: the per-IP auth rate limit still applies.
|
||||||
|
console.error('[loginLockout] redis error, treating as unlocked:', err?.message || err);
|
||||||
|
return { locked: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async recordFailure(email: string): Promise<void> {
|
||||||
|
const redis = getRedis();
|
||||||
|
if (!redis) return;
|
||||||
|
try {
|
||||||
|
await withLockoutCommand(redis).lockoutRecordFailure(this.key(email), LOCKOUT_DURATION_MS);
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('[loginLockout] redis error recording failure:', err?.message || err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async clear(email: string): Promise<void> {
|
||||||
|
const redis = getRedis();
|
||||||
|
if (!redis) return;
|
||||||
|
try {
|
||||||
|
await redis.del(this.key(email));
|
||||||
|
} catch (err: any) {
|
||||||
|
console.error('[loginLockout] redis error clearing failures:', err?.message || err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Selection ====================
|
||||||
|
|
||||||
|
let instance: LoginLockout | null = null;
|
||||||
|
|
||||||
|
export function getLoginLockout(): LoginLockout {
|
||||||
|
if (!instance) {
|
||||||
|
instance = isRedisEnabled() ? new RedisLoginLockout() : new MemoryLoginLockout();
|
||||||
|
}
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import RedisMock from 'ioredis-mock';
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({ redis: null as any }));
|
||||||
|
|
||||||
|
vi.mock('../redis.js', () => ({
|
||||||
|
isRedisEnabled: () => true,
|
||||||
|
getRedis: () => mocks.redis,
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { MemoryRateLimiter, RedisRateLimiter } from './rateLimiter.js';
|
||||||
|
|
||||||
|
describe('MemoryRateLimiter', () => {
|
||||||
|
it('allows up to max within the window, then blocks with retryAfter', async () => {
|
||||||
|
const limiter = new MemoryRateLimiter();
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
expect((await limiter.consume('k', 3, 60_000)).allowed).toBe(true);
|
||||||
|
}
|
||||||
|
const blocked = await limiter.consume('k', 3, 60_000);
|
||||||
|
expect(blocked.allowed).toBe(false);
|
||||||
|
expect(blocked.retryAfter).toBeGreaterThan(0);
|
||||||
|
expect(blocked.retryAfter).toBeLessThanOrEqual(60);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resets after the window elapses', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
try {
|
||||||
|
const limiter = new MemoryRateLimiter();
|
||||||
|
expect((await limiter.consume('k', 1, 1_000)).allowed).toBe(true);
|
||||||
|
expect((await limiter.consume('k', 1, 1_000)).allowed).toBe(false);
|
||||||
|
vi.advanceTimersByTime(1_500);
|
||||||
|
expect((await limiter.consume('k', 1, 1_000)).allowed).toBe(true);
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RedisRateLimiter', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
mocks.redis = new RedisMock();
|
||||||
|
// ioredis-mock shares data between instances by connection string.
|
||||||
|
await mocks.redis.flushall();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets the window TTL atomically on the first hit', async () => {
|
||||||
|
const limiter = new RedisRateLimiter();
|
||||||
|
expect((await limiter.consume('k', 5, 60_000)).allowed).toBe(true);
|
||||||
|
const ttl = await mocks.redis.pttl('rl:k');
|
||||||
|
expect(ttl).toBeGreaterThan(0);
|
||||||
|
expect(ttl).toBeLessThanOrEqual(60_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('blocks over the limit with a sane retryAfter', async () => {
|
||||||
|
const limiter = new RedisRateLimiter();
|
||||||
|
for (let i = 0; i < 2; i++) {
|
||||||
|
expect((await limiter.consume('k', 2, 60_000)).allowed).toBe(true);
|
||||||
|
}
|
||||||
|
const blocked = await limiter.consume('k', 2, 60_000);
|
||||||
|
expect(blocked.allowed).toBe(false);
|
||||||
|
expect(blocked.retryAfter).toBeGreaterThan(0);
|
||||||
|
expect(blocked.retryAfter).toBeLessThanOrEqual(60);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('self-heals a counter stranded without a TTL', async () => {
|
||||||
|
await mocks.redis.set('rl:k', '3');
|
||||||
|
expect(await mocks.redis.pttl('rl:k')).toBeLessThan(0);
|
||||||
|
const limiter = new RedisRateLimiter();
|
||||||
|
await limiter.consume('k', 10, 60_000);
|
||||||
|
expect(await mocks.redis.pttl('rl:k')).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails open when the backend errors', async () => {
|
||||||
|
mocks.redis = { rlConsume: () => Promise.reject(new Error('connection refused')) };
|
||||||
|
const limiter = new RedisRateLimiter();
|
||||||
|
expect((await limiter.consume('k', 1, 60_000)).allowed).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails open when the client is not initialized', async () => {
|
||||||
|
mocks.redis = null;
|
||||||
|
const limiter = new RedisRateLimiter();
|
||||||
|
expect((await limiter.consume('k', 1, 60_000)).allowed).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
// Rate limiter abstraction with two implementations:
|
// Rate limiter abstraction with two implementations:
|
||||||
// - memory: per-process fixed window (the original behavior)
|
// - memory: per-process fixed window (the original behavior)
|
||||||
// - redis: shared fixed window across all instances (INCR + PEXPIRE)
|
// - redis: shared fixed window across all instances, implemented as a single
|
||||||
|
// Lua script so INCR and PEXPIRE are atomic (a crash between separate calls
|
||||||
|
// would otherwise strand a counter with no expiry)
|
||||||
//
|
//
|
||||||
// Selection happens once based on REDIS_URL. On any Redis error the limiter
|
// Selection happens once based on REDIS_URL. On any Redis error the limiter
|
||||||
// fails open (allows the request) so a Redis blip never takes the API down.
|
// fails open (allows the request) so a Redis blip never takes the API down.
|
||||||
|
|
||||||
|
import type Redis from 'ioredis';
|
||||||
import { getRedis, isRedisEnabled } from '../redis.js';
|
import { getRedis, isRedisEnabled } from '../redis.js';
|
||||||
|
|
||||||
export interface RateLimitResult {
|
export interface RateLimitResult {
|
||||||
@@ -24,7 +27,7 @@ interface Bucket {
|
|||||||
resetAt: number;
|
resetAt: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
class MemoryRateLimiter implements RateLimiter {
|
export class MemoryRateLimiter implements RateLimiter {
|
||||||
readonly backend = 'memory' as const;
|
readonly backend = 'memory' as const;
|
||||||
private buckets = new Map<string, Bucket>();
|
private buckets = new Map<string, Bucket>();
|
||||||
|
|
||||||
@@ -58,22 +61,44 @@ class MemoryRateLimiter implements RateLimiter {
|
|||||||
|
|
||||||
// ==================== Redis implementation ====================
|
// ==================== Redis implementation ====================
|
||||||
|
|
||||||
class RedisRateLimiter implements RateLimiter {
|
// Atomically increments the window counter, sets the expiry on the first hit,
|
||||||
|
// and repairs any counter left without a TTL (self-heals keys stranded by the
|
||||||
|
// pre-Lua implementation or a lost PEXPIRE). Returns {count, ttlMs}.
|
||||||
|
export const CONSUME_SCRIPT = `
|
||||||
|
local count = redis.call('INCR', KEYS[1])
|
||||||
|
if count == 1 then
|
||||||
|
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
||||||
|
end
|
||||||
|
local ttl = redis.call('PTTL', KEYS[1])
|
||||||
|
if ttl < 0 then
|
||||||
|
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
||||||
|
ttl = tonumber(ARGV[1])
|
||||||
|
end
|
||||||
|
return {count, ttl}
|
||||||
|
`;
|
||||||
|
|
||||||
|
type RedisWithConsume = Redis & {
|
||||||
|
rlConsume(key: string, windowMs: number): Promise<[number, number]>;
|
||||||
|
};
|
||||||
|
|
||||||
|
function withConsumeCommand(redis: Redis): RedisWithConsume {
|
||||||
|
if (typeof (redis as any).rlConsume !== 'function') {
|
||||||
|
// ioredis caches the script SHA and transparently handles NOSCRIPT.
|
||||||
|
redis.defineCommand('rlConsume', { numberOfKeys: 1, lua: CONSUME_SCRIPT });
|
||||||
|
}
|
||||||
|
return redis as RedisWithConsume;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RedisRateLimiter implements RateLimiter {
|
||||||
readonly backend = 'redis' as const;
|
readonly backend = 'redis' as const;
|
||||||
|
|
||||||
async consume(key: string, max: number, windowMs: number): Promise<RateLimitResult> {
|
async consume(key: string, max: number, windowMs: number): Promise<RateLimitResult> {
|
||||||
const redis = getRedis();
|
const redis = getRedis();
|
||||||
if (!redis) return { allowed: true };
|
if (!redis) return { allowed: true };
|
||||||
|
|
||||||
const redisKey = `rl:${key}`;
|
|
||||||
try {
|
try {
|
||||||
const count = await redis.incr(redisKey);
|
const [count, ttl] = await withConsumeCommand(redis).rlConsume(`rl:${key}`, windowMs);
|
||||||
if (count === 1) {
|
|
||||||
// First hit in this window: set the expiry that defines the window.
|
|
||||||
await redis.pexpire(redisKey, windowMs);
|
|
||||||
}
|
|
||||||
if (count > max) {
|
if (count > max) {
|
||||||
const ttl = await redis.pttl(redisKey);
|
|
||||||
const retryAfter = ttl > 0 ? Math.ceil(ttl / 1000) : Math.ceil(windowMs / 1000);
|
const retryAfter = ttl > 0 ? Math.ceil(ttl / 1000) : Math.ceil(windowMs / 1000);
|
||||||
return { allowed: false, retryAfter };
|
return { allowed: false, retryAfter };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// Engine-neutral transactional writes.
|
||||||
|
//
|
||||||
|
// better-sqlite3 transactions take a *synchronous* callback (awaiting inside one
|
||||||
|
// silently breaks atomicity), while node-postgres takes an async one. Rather than
|
||||||
|
// fork every multi-write route into two near-identical branches, callers build a
|
||||||
|
// plain list of operations and hand it here: the business logic stays in one
|
||||||
|
// place and only the six lines below know which driver is underneath.
|
||||||
|
|
||||||
|
import { db, isSqlite } from '../db/index.js';
|
||||||
|
|
||||||
|
export type TxOp =
|
||||||
|
| { kind: 'insert'; table: any; values: any }
|
||||||
|
| { kind: 'update'; table: any; values: any; where: any }
|
||||||
|
| { kind: 'delete'; table: any; where: any };
|
||||||
|
|
||||||
|
export const insertOp = (table: any, values: any): TxOp => ({ kind: 'insert', table, values });
|
||||||
|
export const updateOp = (table: any, values: any, where: any): TxOp => ({ kind: 'update', table, values, where });
|
||||||
|
export const deleteOp = (table: any, where: any): TxOp => ({ kind: 'delete', table, where });
|
||||||
|
|
||||||
|
/** Apply every op inside a single transaction; any throw rolls back all of them. */
|
||||||
|
export async function runOps(ops: TxOp[]): Promise<void> {
|
||||||
|
if (ops.length === 0) return;
|
||||||
|
|
||||||
|
if (isSqlite()) {
|
||||||
|
(db as any).transaction((tx: any) => {
|
||||||
|
for (const op of ops) {
|
||||||
|
if (op.kind === 'insert') tx.insert(op.table).values(op.values).run();
|
||||||
|
else if (op.kind === 'update') tx.update(op.table).set(op.values).where(op.where).run();
|
||||||
|
else tx.delete(op.table).where(op.where).run();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await (db as any).transaction(async (tx: any) => {
|
||||||
|
for (const op of ops) {
|
||||||
|
if (op.kind === 'insert') await tx.insert(op.table).values(op.values);
|
||||||
|
else if (op.kind === 'update') await tx.update(op.table).set(op.values).where(op.where);
|
||||||
|
else await tx.delete(op.table).where(op.where);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -22,6 +22,19 @@ export function generateTicketCode(): string {
|
|||||||
return `TKT-${nanoid(8).toUpperCase()}`;
|
return `TKT-${nanoid(8).toUpperCase()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Canonical form for `users.email`.
|
||||||
|
*
|
||||||
|
* Better Auth lowercases the address on every lookup and write it performs,
|
||||||
|
* but the `users.email` unique index is case-sensitive on both dialects. Any
|
||||||
|
* row written outside Better Auth (guest bookings, door sales, admin-added
|
||||||
|
* tickets) must therefore be normalized the same way, or the row becomes
|
||||||
|
* invisible to sign-in / Google linking and a duplicate person gets created.
|
||||||
|
*/
|
||||||
|
export function normalizeEmail(email: string): string {
|
||||||
|
return email.trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get current timestamp in the format appropriate for the database type.
|
* Get current timestamp in the format appropriate for the database type.
|
||||||
* - SQLite: returns ISO string
|
* - SQLite: returns ISO string
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { resolveWalkInPrice, omitWalkInPrice, parseWalkInPrice, canSeeWalkInPrice } from './walkInPrice.js';
|
||||||
|
|
||||||
|
describe('resolveWalkInPrice', () => {
|
||||||
|
it('falls back to the ticket price when no walk-in price is set', () => {
|
||||||
|
expect(resolveWalkInPrice({ price: 21000, walkInPrice: null })).toEqual({ unitPrice: 21000, source: 'ticket' });
|
||||||
|
expect(resolveWalkInPrice({ price: 21000 })).toEqual({ unitPrice: 21000, source: 'ticket' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats 0 as a free walk-in, not as unset', () => {
|
||||||
|
expect(resolveWalkInPrice({ price: 21000, walkInPrice: 0 })).toEqual({ unitPrice: 0, source: 'walk_in' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses a set walk-in price', () => {
|
||||||
|
expect(resolveWalkInPrice({ price: 21000, walkInPrice: 25000 })).toEqual({ unitPrice: 25000, source: 'walk_in' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads Postgres decimal strings', () => {
|
||||||
|
expect(resolveWalkInPrice({ price: '21000.00', walkInPrice: '25000.00' })).toEqual({ unitPrice: 25000, source: 'walk_in' });
|
||||||
|
expect(resolveWalkInPrice({ price: '21000.00', walkInPrice: null })).toEqual({ unitPrice: 21000, source: 'ticket' });
|
||||||
|
expect(parseWalkInPrice('0.00')).toBe(0);
|
||||||
|
expect(parseWalkInPrice('')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('omitWalkInPrice', () => {
|
||||||
|
it('drops the walk-in price and keeps everything else', () => {
|
||||||
|
const event = { id: 'e1', price: 21000, walkInPrice: 25000, currency: 'PYG' };
|
||||||
|
const result = omitWalkInPrice(event);
|
||||||
|
expect(result).not.toHaveProperty('walkInPrice');
|
||||||
|
expect(result).toEqual({ id: 'e1', price: 21000, currency: 'PYG' });
|
||||||
|
expect(event.walkInPrice).toBe(25000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes null through', () => {
|
||||||
|
expect(omitWalkInPrice(null)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('canSeeWalkInPrice', () => {
|
||||||
|
it('is limited to event managers and door staff', () => {
|
||||||
|
expect(canSeeWalkInPrice('admin')).toBe(true);
|
||||||
|
expect(canSeeWalkInPrice('organizer')).toBe(true);
|
||||||
|
expect(canSeeWalkInPrice('staff')).toBe(true);
|
||||||
|
expect(canSeeWalkInPrice('marketing')).toBe(false);
|
||||||
|
expect(canSeeWalkInPrice('user')).toBe(false);
|
||||||
|
expect(canSeeWalkInPrice(null)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// Walk-in (door) pricing.
|
||||||
|
//
|
||||||
|
// An event may set a separate price for people who buy at the door. It is an
|
||||||
|
// internal number: staff charge it on the door screen, but it never appears on
|
||||||
|
// the public event page, listings or JSON-LD, so every public serializer must
|
||||||
|
// drop it (see omitWalkInPrice).
|
||||||
|
//
|
||||||
|
// walkInPrice null -> not set, walk-ins pay the regular ticket price
|
||||||
|
// walkInPrice 0 -> free walk-in (a real value, distinct from null)
|
||||||
|
// walkInPrice n -> walk-ins pay n, in the event's currency
|
||||||
|
|
||||||
|
export type WalkInPriceSource = 'walk_in' | 'ticket';
|
||||||
|
|
||||||
|
/** Roles that may see an event's walk-in price: event managers and door staff. */
|
||||||
|
export const WALK_IN_PRICE_ROLES = ['admin', 'organizer', 'staff'] as const;
|
||||||
|
|
||||||
|
export function canSeeWalkInPrice(role: string | null | undefined): boolean {
|
||||||
|
return !!role && (WALK_IN_PRICE_ROLES as readonly string[]).includes(role);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Postgres decimals arrive as strings; null/undefined/garbage stay null. */
|
||||||
|
export function parseWalkInPrice(value: unknown): number | null {
|
||||||
|
if (value === null || value === undefined || value === '') return null;
|
||||||
|
const n = typeof value === 'string' ? parseFloat(value) : Number(value);
|
||||||
|
return Number.isFinite(n) ? n : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The per-ticket price a walk-in is charged, and where it came from. */
|
||||||
|
export function resolveWalkInPrice(event: { price: unknown; walkInPrice?: unknown }): {
|
||||||
|
unitPrice: number;
|
||||||
|
source: WalkInPriceSource;
|
||||||
|
} {
|
||||||
|
const walkIn = parseWalkInPrice(event.walkInPrice);
|
||||||
|
if (walkIn !== null) return { unitPrice: walkIn, source: 'walk_in' };
|
||||||
|
const price = typeof event.price === 'string' ? parseFloat(event.price) : Number(event.price);
|
||||||
|
return { unitPrice: Number.isFinite(price) ? price : 0, source: 'ticket' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Copy of an event row without its walk-in price, for anything a non-staff caller can read. */
|
||||||
|
export function omitWalkInPrice<T extends Record<string, any> | null | undefined>(event: T): T {
|
||||||
|
if (!event) return event;
|
||||||
|
const { walkInPrice: _omitted, ...rest } = event as Record<string, any>;
|
||||||
|
return rest as T;
|
||||||
|
}
|
||||||
@@ -2,7 +2,9 @@ import { Hono } from 'hono';
|
|||||||
import { db, dbGet, dbAll, users, events, tickets, payments, contacts, emailSubscribers } from '../db/index.js';
|
import { db, dbGet, dbAll, users, events, tickets, payments, contacts, emailSubscribers } from '../db/index.js';
|
||||||
import { eq, and, ne, gte, sql, desc, inArray } from 'drizzle-orm';
|
import { eq, and, ne, gte, sql, desc, inArray } from 'drizzle-orm';
|
||||||
import { requireAuth } from '../lib/auth.js';
|
import { requireAuth } from '../lib/auth.js';
|
||||||
|
import { requireEventPermission, eventFromParam } from '../lib/eventPermissions.js';
|
||||||
import { getNow } from '../lib/utils.js';
|
import { getNow } from '../lib/utils.js';
|
||||||
|
import { eventSeatBreakdownQuery } from '../lib/capacity.js';
|
||||||
|
|
||||||
const adminRouter = new Hono();
|
const adminRouter = new Hono();
|
||||||
|
|
||||||
@@ -20,8 +22,9 @@ const csvEscape = (value: string) => {
|
|||||||
adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) => {
|
adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) => {
|
||||||
const now = getNow();
|
const now = getNow();
|
||||||
|
|
||||||
// Get upcoming events
|
// Get upcoming events with seat counts (paid + claimed, per lib/capacity.ts)
|
||||||
const upcomingEvents = await dbAll(
|
// so the dashboard's capacity alerts reflect real availability.
|
||||||
|
const upcomingEventsRaw = await dbAll<any>(
|
||||||
(db as any)
|
(db as any)
|
||||||
.select()
|
.select()
|
||||||
.from(events)
|
.from(events)
|
||||||
@@ -35,6 +38,24 @@ adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) =>
|
|||||||
.limit(5)
|
.limit(5)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const seatRows = await dbAll<any>(eventSeatBreakdownQuery(db));
|
||||||
|
const seatsByEvent = new Map<string, { paid: number; claimed: number }>();
|
||||||
|
for (const row of seatRows) {
|
||||||
|
seatsByEvent.set(row.eventId, {
|
||||||
|
paid: Number(row.paidCount) || 0,
|
||||||
|
claimed: Number(row.claimedCount) || 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const upcomingEvents = upcomingEventsRaw.map((event: any) => {
|
||||||
|
const counts = seatsByEvent.get(event.id) || { paid: 0, claimed: 0 };
|
||||||
|
return {
|
||||||
|
...event,
|
||||||
|
bookedCount: counts.paid,
|
||||||
|
claimedCount: counts.claimed,
|
||||||
|
availableSeats: Math.max(0, (event.capacity || 0) - counts.paid - counts.claimed),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
// Get recent tickets
|
// Get recent tickets
|
||||||
const recentTickets = await dbAll(
|
const recentTickets = await dbAll(
|
||||||
(db as any)
|
(db as any)
|
||||||
@@ -70,6 +91,8 @@ adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) =>
|
|||||||
.where(eq((tickets as any).status, 'confirmed'))
|
.where(eq((tickets as any).status, 'confirmed'))
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// 'pending' = checkout opened, nothing paid or claimed (informational);
|
||||||
|
// 'pending_approval' = customer says they paid, needs admin verification (actionable).
|
||||||
const pendingPayments = await dbGet<any>(
|
const pendingPayments = await dbGet<any>(
|
||||||
(db as any)
|
(db as any)
|
||||||
.select({ count: sql<number>`count(*)` })
|
.select({ count: sql<number>`count(*)` })
|
||||||
@@ -77,6 +100,13 @@ adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) =>
|
|||||||
.where(eq((payments as any).status, 'pending'))
|
.where(eq((payments as any).status, 'pending'))
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const awaitingApprovalPayments = await dbGet<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({ count: sql<number>`count(*)` })
|
||||||
|
.from(payments)
|
||||||
|
.where(eq((payments as any).status, 'pending_approval'))
|
||||||
|
);
|
||||||
|
|
||||||
const onHoldPayments = await dbGet<any>(
|
const onHoldPayments = await dbGet<any>(
|
||||||
(db as any)
|
(db as any)
|
||||||
.select({ count: sql<number>`count(*)` })
|
.select({ count: sql<number>`count(*)` })
|
||||||
@@ -115,6 +145,7 @@ adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) =>
|
|||||||
totalTickets: totalTickets?.count || 0,
|
totalTickets: totalTickets?.count || 0,
|
||||||
confirmedTickets: confirmedTickets?.count || 0,
|
confirmedTickets: confirmedTickets?.count || 0,
|
||||||
pendingPayments: pendingPayments?.count || 0,
|
pendingPayments: pendingPayments?.count || 0,
|
||||||
|
awaitingApprovalPayments: awaitingApprovalPayments?.count || 0,
|
||||||
onHoldPayments: onHoldPayments?.count || 0,
|
onHoldPayments: onHoldPayments?.count || 0,
|
||||||
totalRevenue,
|
totalRevenue,
|
||||||
newContacts: newContacts?.count || 0,
|
newContacts: newContacts?.count || 0,
|
||||||
@@ -152,6 +183,17 @@ adminRouter.get('/analytics', requireAuth(['admin']), async (c) => {
|
|||||||
.groupBy((tickets as any).eventId)
|
.groupBy((tickets as any).eventId)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Revenue is what was actually paid, not tickets × the current event price
|
||||||
|
// (which an admin can change after tickets have been sold).
|
||||||
|
const revenueRows = await dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({ eventId: (tickets as any).eventId, count: sql<number>`coalesce(sum(${(payments as any).amount}), 0)` })
|
||||||
|
.from(payments)
|
||||||
|
.innerJoin(tickets, eq((payments as any).ticketId, (tickets as any).id))
|
||||||
|
.where(eq((payments as any).status, 'paid'))
|
||||||
|
.groupBy((tickets as any).eventId)
|
||||||
|
);
|
||||||
|
|
||||||
const toMap = (rows: any[]) => {
|
const toMap = (rows: any[]) => {
|
||||||
const m = new Map<string, number>();
|
const m = new Map<string, number>();
|
||||||
for (const r of rows) m.set(r.eventId, Number(r.count) || 0);
|
for (const r of rows) m.set(r.eventId, Number(r.count) || 0);
|
||||||
@@ -160,6 +202,7 @@ adminRouter.get('/analytics', requireAuth(['admin']), async (c) => {
|
|||||||
const totalMap = toMap(totalRows);
|
const totalMap = toMap(totalRows);
|
||||||
const confirmedMap = toMap(confirmedRows);
|
const confirmedMap = toMap(confirmedRows);
|
||||||
const checkedInMap = toMap(checkedInRows);
|
const checkedInMap = toMap(checkedInRows);
|
||||||
|
const revenueMap = toMap(revenueRows);
|
||||||
|
|
||||||
const eventStats = allEvents.map((event: any) => {
|
const eventStats = allEvents.map((event: any) => {
|
||||||
const confirmedBookings = confirmedMap.get(event.id) || 0;
|
const confirmedBookings = confirmedMap.get(event.id) || 0;
|
||||||
@@ -171,7 +214,7 @@ adminRouter.get('/analytics', requireAuth(['admin']), async (c) => {
|
|||||||
totalBookings: totalMap.get(event.id) || 0,
|
totalBookings: totalMap.get(event.id) || 0,
|
||||||
confirmedBookings,
|
confirmedBookings,
|
||||||
checkedIn: checkedInMap.get(event.id) || 0,
|
checkedIn: checkedInMap.get(event.id) || 0,
|
||||||
revenue: confirmedBookings * event.price,
|
revenue: revenueMap.get(event.id) || 0,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -234,7 +277,7 @@ adminRouter.get('/export/tickets', requireAuth(['admin']), async (c) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Export attendees for a specific event (admin) — CSV download
|
// Export attendees for a specific event (admin) — CSV download
|
||||||
adminRouter.get('/events/:eventId/attendees/export', requireAuth(['admin']), async (c) => {
|
adminRouter.get('/events/:eventId/attendees/export', requireEventPermission('view_attendees_pii', { globalRoles: ['admin'], eventId: eventFromParam('eventId') }), async (c) => {
|
||||||
const eventId = c.req.param('eventId');
|
const eventId = c.req.param('eventId');
|
||||||
const status = c.req.query('status') || 'all'; // confirmed | checked_in | confirmed_pending | all
|
const status = c.req.query('status') || 'all'; // confirmed | checked_in | confirmed_pending | all
|
||||||
const q = c.req.query('q') || '';
|
const q = c.req.query('q') || '';
|
||||||
@@ -338,14 +381,14 @@ adminRouter.get('/events/:eventId/attendees/export', requireAuth(['admin']), asy
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Legacy alias — keep old path working
|
// Legacy alias — keep old path working
|
||||||
adminRouter.get('/events/:eventId/export', requireAuth(['admin']), async (c) => {
|
adminRouter.get('/events/:eventId/export', requireEventPermission('view_attendees_pii', { globalRoles: ['admin'], eventId: eventFromParam('eventId') }), async (c) => {
|
||||||
const newUrl = new URL(c.req.url);
|
const newUrl = new URL(c.req.url);
|
||||||
newUrl.pathname = newUrl.pathname.replace('/export', '/attendees/export');
|
newUrl.pathname = newUrl.pathname.replace('/export', '/attendees/export');
|
||||||
return c.redirect(newUrl.toString(), 301);
|
return c.redirect(newUrl.toString(), 301);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Export tickets for a specific event (admin) — CSV download (confirmed/checked_in only)
|
// Export tickets for a specific event (admin) — CSV download (confirmed/checked_in only)
|
||||||
adminRouter.get('/events/:eventId/tickets/export', requireAuth(['admin']), async (c) => {
|
adminRouter.get('/events/:eventId/tickets/export', requireEventPermission('view_attendees_pii', { globalRoles: ['admin'], eventId: eventFromParam('eventId') }), async (c) => {
|
||||||
const eventId = c.req.param('eventId');
|
const eventId = c.req.param('eventId');
|
||||||
const status = c.req.query('status') || 'all'; // confirmed | checked_in | all
|
const status = c.req.query('status') || 'all'; // confirmed | checked_in | all
|
||||||
const q = c.req.query('q') || '';
|
const q = c.req.query('q') || '';
|
||||||
@@ -489,6 +532,7 @@ adminRouter.get('/export/financial', requireAuth(['admin']), async (c) => {
|
|||||||
bancard: filteredPayments.filter((p: any) => p.provider === 'bancard' && p.status === 'paid').reduce((sum: number, p: any) => sum + p.amount, 0),
|
bancard: filteredPayments.filter((p: any) => p.provider === 'bancard' && p.status === 'paid').reduce((sum: number, p: any) => sum + p.amount, 0),
|
||||||
lightning: filteredPayments.filter((p: any) => p.provider === 'lightning' && p.status === 'paid').reduce((sum: number, p: any) => sum + p.amount, 0),
|
lightning: filteredPayments.filter((p: any) => p.provider === 'lightning' && p.status === 'paid').reduce((sum: number, p: any) => sum + p.amount, 0),
|
||||||
cash: filteredPayments.filter((p: any) => p.provider === 'cash' && p.status === 'paid').reduce((sum: number, p: any) => sum + p.amount, 0),
|
cash: filteredPayments.filter((p: any) => p.provider === 'cash' && p.status === 'paid').reduce((sum: number, p: any) => sum + p.amount, 0),
|
||||||
|
pos: filteredPayments.filter((p: any) => p.provider === 'pos' && p.status === 'paid').reduce((sum: number, p: any) => sum + p.amount, 0),
|
||||||
},
|
},
|
||||||
paidCount: filteredPayments.filter((p: any) => p.status === 'paid').length,
|
paidCount: filteredPayments.filter((p: any) => p.status === 'paid').length,
|
||||||
pendingCount: filteredPayments.filter((p: any) => p.status === 'pending').length,
|
pendingCount: filteredPayments.filter((p: any) => p.status === 'pending').length,
|
||||||
|
|||||||
@@ -1,719 +0,0 @@
|
|||||||
import { Hono } from 'hono';
|
|
||||||
import { zValidator } from '@hono/zod-validator';
|
|
||||||
import { z } from 'zod';
|
|
||||||
import { db, dbGet, users, magicLinkTokens, User } from '../db/index.js';
|
|
||||||
import { eq } from 'drizzle-orm';
|
|
||||||
import {
|
|
||||||
hashPassword,
|
|
||||||
verifyPassword,
|
|
||||||
createToken,
|
|
||||||
createRefreshToken,
|
|
||||||
isFirstUser,
|
|
||||||
getAuthUser,
|
|
||||||
validatePassword,
|
|
||||||
createMagicLinkToken,
|
|
||||||
verifyMagicLinkToken,
|
|
||||||
invalidateAllUserSessions,
|
|
||||||
bumpTokenVersion,
|
|
||||||
requireAuth,
|
|
||||||
getUserPasswordHash,
|
|
||||||
} from '../lib/auth.js';
|
|
||||||
import { generateId, getNow, toDbBool } from '../lib/utils.js';
|
|
||||||
import { sendEmail } from '../lib/email.js';
|
|
||||||
import { rateLimitMiddleware } from '../lib/rateLimit.js';
|
|
||||||
|
|
||||||
// Per-IP rate limit for sensitive auth endpoints (registration, login, and all
|
|
||||||
// email-dispatching flows) to curb credential stuffing and email flooding.
|
|
||||||
const authRateLimit = rateLimitMiddleware({ max: 20, windowMs: 15 * 60 * 1000, prefix: 'auth' });
|
|
||||||
|
|
||||||
// User type that includes all fields (some added in schema updates)
|
|
||||||
type AuthUser = User & {
|
|
||||||
isClaimed: boolean;
|
|
||||||
googleId: string | null;
|
|
||||||
rucNumber: string | null;
|
|
||||||
accountStatus: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const auth = new Hono();
|
|
||||||
|
|
||||||
// Rate limiting store (in production, use Redis)
|
|
||||||
const loginAttempts = new Map<string, { count: number; resetAt: number }>();
|
|
||||||
const MAX_LOGIN_ATTEMPTS = 5;
|
|
||||||
const LOCKOUT_DURATION = 15 * 60 * 1000; // 15 minutes
|
|
||||||
|
|
||||||
function checkRateLimit(email: string): { allowed: boolean; retryAfter?: number } {
|
|
||||||
const now = Date.now();
|
|
||||||
const attempts = loginAttempts.get(email);
|
|
||||||
|
|
||||||
if (!attempts) {
|
|
||||||
return { allowed: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (now > attempts.resetAt) {
|
|
||||||
loginAttempts.delete(email);
|
|
||||||
return { allowed: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (attempts.count >= MAX_LOGIN_ATTEMPTS) {
|
|
||||||
return { allowed: false, retryAfter: Math.ceil((attempts.resetAt - now) / 1000) };
|
|
||||||
}
|
|
||||||
|
|
||||||
return { allowed: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
function recordFailedAttempt(email: string): void {
|
|
||||||
const now = Date.now();
|
|
||||||
const attempts = loginAttempts.get(email) || { count: 0, resetAt: now + LOCKOUT_DURATION };
|
|
||||||
attempts.count++;
|
|
||||||
loginAttempts.set(email, attempts);
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearFailedAttempts(email: string): void {
|
|
||||||
loginAttempts.delete(email);
|
|
||||||
}
|
|
||||||
|
|
||||||
const registerSchema = z.object({
|
|
||||||
email: z.string().email(),
|
|
||||||
password: z.string().min(10, 'Password must be at least 10 characters'),
|
|
||||||
name: z.string().min(2),
|
|
||||||
phone: z.string().optional(),
|
|
||||||
languagePreference: z.enum(['en', 'es']).optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const loginSchema = z.object({
|
|
||||||
email: z.string().email(),
|
|
||||||
password: z.string(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const magicLinkRequestSchema = z.object({
|
|
||||||
email: z.string().email(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const magicLinkVerifySchema = z.object({
|
|
||||||
token: z.string(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const passwordResetRequestSchema = z.object({
|
|
||||||
email: z.string().email(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const passwordResetSchema = z.object({
|
|
||||||
token: z.string(),
|
|
||||||
password: z.string().min(10, 'Password must be at least 10 characters'),
|
|
||||||
});
|
|
||||||
|
|
||||||
const claimAccountSchema = z.object({
|
|
||||||
token: z.string(),
|
|
||||||
password: z.string().min(10, 'Password must be at least 10 characters'),
|
|
||||||
});
|
|
||||||
|
|
||||||
const changePasswordSchema = z.object({
|
|
||||||
currentPassword: z.string(),
|
|
||||||
newPassword: z.string().min(10, 'Password must be at least 10 characters'),
|
|
||||||
});
|
|
||||||
|
|
||||||
const googleAuthSchema = z.object({
|
|
||||||
credential: z.string(), // Google ID token
|
|
||||||
});
|
|
||||||
|
|
||||||
// Register
|
|
||||||
auth.post('/register', authRateLimit, zValidator('json', registerSchema), async (c) => {
|
|
||||||
const data = c.req.valid('json');
|
|
||||||
|
|
||||||
// Validate password strength
|
|
||||||
const passwordValidation = validatePassword(data.password);
|
|
||||||
if (!passwordValidation.valid) {
|
|
||||||
return c.json({ error: passwordValidation.error }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if email exists
|
|
||||||
const existing = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).email, data.email))
|
|
||||||
);
|
|
||||||
if (existing) {
|
|
||||||
// If user exists but is unclaimed, allow claiming
|
|
||||||
if (!existing.isClaimed || existing.accountStatus === 'unclaimed') {
|
|
||||||
return c.json({
|
|
||||||
error: 'Email already registered',
|
|
||||||
canClaim: true,
|
|
||||||
message: 'This email has an unclaimed account. Please check your email for the claim link or request a new one.'
|
|
||||||
}, 400);
|
|
||||||
}
|
|
||||||
return c.json({ error: 'Email already registered' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if first user (becomes admin)
|
|
||||||
const firstUser = await isFirstUser();
|
|
||||||
|
|
||||||
const hashedPassword = await hashPassword(data.password);
|
|
||||||
const now = getNow();
|
|
||||||
const id = generateId();
|
|
||||||
|
|
||||||
const newUser = {
|
|
||||||
id,
|
|
||||||
email: data.email,
|
|
||||||
password: hashedPassword,
|
|
||||||
name: data.name,
|
|
||||||
phone: data.phone || null,
|
|
||||||
role: firstUser ? 'admin' : 'user',
|
|
||||||
languagePreference: data.languagePreference || null,
|
|
||||||
isClaimed: toDbBool(true),
|
|
||||||
googleId: null,
|
|
||||||
rucNumber: null,
|
|
||||||
accountStatus: 'active',
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
};
|
|
||||||
|
|
||||||
await (db as any).insert(users).values(newUser);
|
|
||||||
|
|
||||||
const token = await createToken(id, data.email, newUser.role, 0);
|
|
||||||
const refreshToken = await createRefreshToken(id);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
user: {
|
|
||||||
id,
|
|
||||||
email: data.email,
|
|
||||||
name: data.name,
|
|
||||||
role: newUser.role,
|
|
||||||
isClaimed: true,
|
|
||||||
},
|
|
||||||
token,
|
|
||||||
refreshToken,
|
|
||||||
message: firstUser ? 'Admin account created successfully' : 'Account created successfully',
|
|
||||||
}, 201);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Login with email/password
|
|
||||||
auth.post('/login', authRateLimit, zValidator('json', loginSchema), async (c) => {
|
|
||||||
const data = c.req.valid('json');
|
|
||||||
|
|
||||||
// Check rate limit
|
|
||||||
const rateLimit = checkRateLimit(data.email);
|
|
||||||
if (!rateLimit.allowed) {
|
|
||||||
return c.json({
|
|
||||||
error: 'Too many login attempts. Please try again later.',
|
|
||||||
retryAfter: rateLimit.retryAfter
|
|
||||||
}, 429);
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).email, data.email))
|
|
||||||
);
|
|
||||||
if (!user) {
|
|
||||||
recordFailedAttempt(data.email);
|
|
||||||
return c.json({ error: 'Invalid credentials' }, 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if account is suspended
|
|
||||||
if (user.accountStatus === 'suspended') {
|
|
||||||
return c.json({ error: 'Account is suspended. Please contact support.' }, 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if user has a password set
|
|
||||||
if (!user.password) {
|
|
||||||
return c.json({
|
|
||||||
error: 'No password set for this account',
|
|
||||||
needsClaim: !user.isClaimed,
|
|
||||||
message: user.isClaimed
|
|
||||||
? 'Please use Google login or request a password reset.'
|
|
||||||
: 'Please claim your account first.'
|
|
||||||
}, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const validPassword = await verifyPassword(data.password, user.password);
|
|
||||||
if (!validPassword) {
|
|
||||||
recordFailedAttempt(data.email);
|
|
||||||
return c.json({ error: 'Invalid credentials' }, 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clear failed attempts on successful login
|
|
||||||
clearFailedAttempts(data.email);
|
|
||||||
|
|
||||||
// Transparently upgrade legacy bcrypt hashes to argon2 now that we have the
|
|
||||||
// plaintext and have verified it. Best-effort: a failure here must not block
|
|
||||||
// the login.
|
|
||||||
if (!String(user.password).startsWith('$argon2')) {
|
|
||||||
try {
|
|
||||||
const upgradedHash = await hashPassword(data.password);
|
|
||||||
await (db as any)
|
|
||||||
.update(users)
|
|
||||||
.set({ password: upgradedHash })
|
|
||||||
.where(eq((users as any).id, user.id));
|
|
||||||
} catch (err: any) {
|
|
||||||
console.error('[auth] Failed to upgrade legacy password hash:', err?.message || err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = await createToken(user.id, user.email, user.role, user.tokenVersion ?? 0);
|
|
||||||
const refreshToken = await createRefreshToken(user.id);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
user: {
|
|
||||||
id: user.id,
|
|
||||||
email: user.email,
|
|
||||||
name: user.name,
|
|
||||||
role: user.role,
|
|
||||||
isClaimed: user.isClaimed,
|
|
||||||
phone: user.phone,
|
|
||||||
rucNumber: user.rucNumber,
|
|
||||||
languagePreference: user.languagePreference,
|
|
||||||
},
|
|
||||||
token,
|
|
||||||
refreshToken,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Request magic link login
|
|
||||||
auth.post('/magic-link/request', authRateLimit, zValidator('json', magicLinkRequestSchema), async (c) => {
|
|
||||||
const { email } = c.req.valid('json');
|
|
||||||
|
|
||||||
const user = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).email, email))
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
// Don't reveal if email exists
|
|
||||||
return c.json({ message: 'If an account exists with this email, a login link has been sent.' });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (user.accountStatus === 'suspended') {
|
|
||||||
return c.json({ message: 'If an account exists with this email, a login link has been sent.' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create magic link token (expires in 10 minutes)
|
|
||||||
const token = await createMagicLinkToken(user.id, 'login', 10);
|
|
||||||
const magicLink = `${process.env.FRONTEND_URL || 'http://localhost:3000'}/auth/magic-link?token=${token}`;
|
|
||||||
|
|
||||||
// Send email
|
|
||||||
try {
|
|
||||||
await sendEmail({
|
|
||||||
to: email,
|
|
||||||
subject: 'Your Spanglish Login Link',
|
|
||||||
html: `
|
|
||||||
<h2>Login to Spanglish</h2>
|
|
||||||
<p>Click the link below to log in. This link expires in 10 minutes.</p>
|
|
||||||
<p><a href="${magicLink}" style="background-color: #3B82F6; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;">Log In</a></p>
|
|
||||||
<p>Or copy this link: ${magicLink}</p>
|
|
||||||
<p>If you didn't request this, you can safely ignore this email.</p>
|
|
||||||
`,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to send magic link email:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({ message: 'If an account exists with this email, a login link has been sent.' });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Verify magic link and login
|
|
||||||
auth.post('/magic-link/verify', authRateLimit, zValidator('json', magicLinkVerifySchema), async (c) => {
|
|
||||||
const { token } = c.req.valid('json');
|
|
||||||
|
|
||||||
const verification = await verifyMagicLinkToken(token, 'login');
|
|
||||||
|
|
||||||
if (!verification.valid) {
|
|
||||||
return c.json({ error: verification.error }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).id, verification.userId))
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!user || user.accountStatus === 'suspended') {
|
|
||||||
return c.json({ error: 'Invalid token' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const authToken = await createToken(user.id, user.email, user.role, user.tokenVersion ?? 0);
|
|
||||||
const refreshToken = await createRefreshToken(user.id);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
user: {
|
|
||||||
id: user.id,
|
|
||||||
email: user.email,
|
|
||||||
name: user.name,
|
|
||||||
role: user.role,
|
|
||||||
isClaimed: user.isClaimed,
|
|
||||||
phone: user.phone,
|
|
||||||
rucNumber: user.rucNumber,
|
|
||||||
languagePreference: user.languagePreference,
|
|
||||||
},
|
|
||||||
token: authToken,
|
|
||||||
refreshToken,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Request password reset
|
|
||||||
auth.post('/password-reset/request', authRateLimit, zValidator('json', passwordResetRequestSchema), async (c) => {
|
|
||||||
const { email } = c.req.valid('json');
|
|
||||||
|
|
||||||
const user = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).email, email))
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
// Don't reveal if email exists
|
|
||||||
return c.json({ message: 'If an account exists with this email, a password reset link has been sent.' });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (user.accountStatus === 'suspended') {
|
|
||||||
return c.json({ message: 'If an account exists with this email, a password reset link has been sent.' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create reset token (expires in 30 minutes)
|
|
||||||
const token = await createMagicLinkToken(user.id, 'reset_password', 30);
|
|
||||||
const resetLink = `${process.env.FRONTEND_URL || 'http://localhost:3000'}/auth/reset-password?token=${token}`;
|
|
||||||
|
|
||||||
// Send email
|
|
||||||
try {
|
|
||||||
await sendEmail({
|
|
||||||
to: email,
|
|
||||||
subject: 'Reset Your Spanglish Password',
|
|
||||||
html: `
|
|
||||||
<h2>Reset Your Password</h2>
|
|
||||||
<p>Click the link below to reset your password. This link expires in 30 minutes.</p>
|
|
||||||
<p><a href="${resetLink}" style="background-color: #3B82F6; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;">Reset Password</a></p>
|
|
||||||
<p>Or copy this link: ${resetLink}</p>
|
|
||||||
<p>If you didn't request this, you can safely ignore this email.</p>
|
|
||||||
`,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to send password reset email:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({ message: 'If an account exists with this email, a password reset link has been sent.' });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Reset password
|
|
||||||
auth.post('/password-reset/confirm', authRateLimit, zValidator('json', passwordResetSchema), async (c) => {
|
|
||||||
const { token, password } = c.req.valid('json');
|
|
||||||
|
|
||||||
// Validate password strength
|
|
||||||
const passwordValidation = validatePassword(password);
|
|
||||||
if (!passwordValidation.valid) {
|
|
||||||
return c.json({ error: passwordValidation.error }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const verification = await verifyMagicLinkToken(token, 'reset_password');
|
|
||||||
|
|
||||||
if (!verification.valid) {
|
|
||||||
return c.json({ error: verification.error }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const hashedPassword = await hashPassword(password);
|
|
||||||
const now = getNow();
|
|
||||||
|
|
||||||
await (db as any)
|
|
||||||
.update(users)
|
|
||||||
.set({
|
|
||||||
password: hashedPassword,
|
|
||||||
updatedAt: now,
|
|
||||||
})
|
|
||||||
.where(eq((users as any).id, verification.userId));
|
|
||||||
|
|
||||||
// Invalidate all existing sessions/JWTs for security
|
|
||||||
await invalidateAllUserSessions(verification.userId!);
|
|
||||||
await bumpTokenVersion(verification.userId!);
|
|
||||||
|
|
||||||
return c.json({ message: 'Password reset successfully. Please log in with your new password.' });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Claim unclaimed account
|
|
||||||
auth.post('/claim-account/request', authRateLimit, zValidator('json', magicLinkRequestSchema), async (c) => {
|
|
||||||
const { email } = c.req.valid('json');
|
|
||||||
|
|
||||||
const user = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).email, email))
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return c.json({ message: 'If an unclaimed account exists with this email, a claim link has been sent.' });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (user.isClaimed && user.accountStatus !== 'unclaimed') {
|
|
||||||
return c.json({ error: 'Account is already claimed' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create claim token (expires in 1 hour)
|
|
||||||
const token = await createMagicLinkToken(user.id, 'claim_account', 60);
|
|
||||||
const claimLink = `${process.env.FRONTEND_URL || 'http://localhost:3000'}/auth/claim-account?token=${token}`;
|
|
||||||
|
|
||||||
// Send email
|
|
||||||
try {
|
|
||||||
await sendEmail({
|
|
||||||
to: email,
|
|
||||||
subject: 'Claim Your Spanglish Account',
|
|
||||||
html: `
|
|
||||||
<h2>Claim Your Account</h2>
|
|
||||||
<p>An account was created for you during booking. Click below to set up your login credentials.</p>
|
|
||||||
<p><a href="${claimLink}" style="background-color: #3B82F6; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;">Claim Account</a></p>
|
|
||||||
<p>Or copy this link: ${claimLink}</p>
|
|
||||||
<p>This link expires in 1 hour.</p>
|
|
||||||
`,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to send claim account email:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({ message: 'If an unclaimed account exists with this email, a claim link has been sent.' });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Complete account claim
|
|
||||||
auth.post('/claim-account/confirm', authRateLimit, zValidator('json', claimAccountSchema), async (c) => {
|
|
||||||
const { token, password } = c.req.valid('json');
|
|
||||||
|
|
||||||
const verification = await verifyMagicLinkToken(token, 'claim_account');
|
|
||||||
|
|
||||||
if (!verification.valid) {
|
|
||||||
return c.json({ error: verification.error }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const passwordValidation = validatePassword(password);
|
|
||||||
if (!passwordValidation.valid) {
|
|
||||||
return c.json({ error: passwordValidation.error }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = getNow();
|
|
||||||
// Only set a password here. Linking a Google account requires a verified Google
|
|
||||||
// ID token via /google; we never trust a client-supplied googleId.
|
|
||||||
const updates: Record<string, any> = {
|
|
||||||
isClaimed: toDbBool(true),
|
|
||||||
accountStatus: 'active',
|
|
||||||
password: await hashPassword(password),
|
|
||||||
updatedAt: now,
|
|
||||||
};
|
|
||||||
|
|
||||||
await (db as any)
|
|
||||||
.update(users)
|
|
||||||
.set(updates)
|
|
||||||
.where(eq((users as any).id, verification.userId));
|
|
||||||
|
|
||||||
const user = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).id, verification.userId))
|
|
||||||
);
|
|
||||||
|
|
||||||
const authToken = await createToken(user.id, user.email, user.role, user.tokenVersion ?? 0);
|
|
||||||
const refreshToken = await createRefreshToken(user.id);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
user: {
|
|
||||||
id: user.id,
|
|
||||||
email: user.email,
|
|
||||||
name: user.name,
|
|
||||||
role: user.role,
|
|
||||||
isClaimed: user.isClaimed,
|
|
||||||
phone: user.phone,
|
|
||||||
rucNumber: user.rucNumber,
|
|
||||||
languagePreference: user.languagePreference,
|
|
||||||
},
|
|
||||||
token: authToken,
|
|
||||||
refreshToken,
|
|
||||||
message: 'Account claimed successfully!',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Google OAuth login/register
|
|
||||||
auth.post('/google', authRateLimit, zValidator('json', googleAuthSchema), async (c) => {
|
|
||||||
const { credential } = c.req.valid('json');
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Verify the Google ID token. Google's tokeninfo endpoint validates the
|
|
||||||
// signature and expiry server-side; we additionally enforce the audience so a
|
|
||||||
// token minted for a different OAuth client cannot be replayed against us.
|
|
||||||
const response = await fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${encodeURIComponent(credential)}`);
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
return c.json({ error: 'Invalid Google token' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const googleData = await response.json() as {
|
|
||||||
sub: string;
|
|
||||||
email: string;
|
|
||||||
name: string;
|
|
||||||
email_verified: string;
|
|
||||||
aud?: string;
|
|
||||||
exp?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
// email_verified can be returned as boolean true or string "true"
|
|
||||||
if (String(googleData.email_verified) !== 'true') {
|
|
||||||
return c.json({ error: 'Google email not verified' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enforce audience when a client ID is configured (closes token-confusion attacks)
|
|
||||||
const expectedAud = process.env.GOOGLE_CLIENT_ID;
|
|
||||||
if (expectedAud) {
|
|
||||||
if (googleData.aud !== expectedAud) {
|
|
||||||
return c.json({ error: 'Invalid Google token audience' }, 400);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.warn('[auth] GOOGLE_CLIENT_ID is not set; skipping audience verification for Google login.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reject expired tokens (defense-in-depth; tokeninfo also rejects them)
|
|
||||||
if (googleData.exp && Number(googleData.exp) * 1000 < Date.now()) {
|
|
||||||
return c.json({ error: 'Google token expired' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const { sub: googleId, email, name } = googleData;
|
|
||||||
|
|
||||||
// Check if user exists by email or google_id
|
|
||||||
let user = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).email, email))
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
// Check by google_id
|
|
||||||
user = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).googleId, googleId))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = getNow();
|
|
||||||
|
|
||||||
if (user) {
|
|
||||||
// User exists - link Google account if not already linked
|
|
||||||
if (user.accountStatus === 'suspended') {
|
|
||||||
return c.json({ error: 'Account is suspended. Please contact support.' }, 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!user.googleId) {
|
|
||||||
await (db as any)
|
|
||||||
.update(users)
|
|
||||||
.set({
|
|
||||||
googleId,
|
|
||||||
isClaimed: toDbBool(true),
|
|
||||||
accountStatus: 'active',
|
|
||||||
updatedAt: now,
|
|
||||||
})
|
|
||||||
.where(eq((users as any).id, user.id));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Refresh user data
|
|
||||||
user = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).id, user.id))
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
// Create new user
|
|
||||||
const firstUser = await isFirstUser();
|
|
||||||
const id = generateId();
|
|
||||||
|
|
||||||
const newUser = {
|
|
||||||
id,
|
|
||||||
email,
|
|
||||||
password: null,
|
|
||||||
name,
|
|
||||||
phone: null,
|
|
||||||
role: firstUser ? 'admin' : 'user',
|
|
||||||
languagePreference: null,
|
|
||||||
isClaimed: toDbBool(true),
|
|
||||||
googleId,
|
|
||||||
rucNumber: null,
|
|
||||||
accountStatus: 'active',
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
};
|
|
||||||
|
|
||||||
await (db as any).insert(users).values(newUser);
|
|
||||||
user = newUser;
|
|
||||||
}
|
|
||||||
|
|
||||||
const authToken = await createToken(user.id, user.email, user.role, user.tokenVersion ?? 0);
|
|
||||||
const refreshToken = await createRefreshToken(user.id);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
user: {
|
|
||||||
id: user.id,
|
|
||||||
email: user.email,
|
|
||||||
name: user.name,
|
|
||||||
role: user.role,
|
|
||||||
isClaimed: user.isClaimed,
|
|
||||||
phone: user.phone,
|
|
||||||
rucNumber: user.rucNumber,
|
|
||||||
languagePreference: user.languagePreference,
|
|
||||||
},
|
|
||||||
token: authToken,
|
|
||||||
refreshToken,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Google auth error:', error);
|
|
||||||
return c.json({ error: 'Failed to authenticate with Google' }, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get current user
|
|
||||||
auth.get('/me', async (c) => {
|
|
||||||
const user = await getAuthUser(c);
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return c.json({ error: 'Unauthorized' }, 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
user: {
|
|
||||||
id: user.id,
|
|
||||||
email: user.email,
|
|
||||||
name: user.name,
|
|
||||||
role: user.role,
|
|
||||||
phone: user.phone,
|
|
||||||
isClaimed: user.isClaimed,
|
|
||||||
rucNumber: user.rucNumber,
|
|
||||||
languagePreference: user.languagePreference,
|
|
||||||
accountStatus: user.accountStatus,
|
|
||||||
createdAt: user.createdAt,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Change password (authenticated users)
|
|
||||||
auth.post('/change-password', requireAuth(), zValidator('json', changePasswordSchema), async (c) => {
|
|
||||||
const user = (c as any).get('user') as AuthUser;
|
|
||||||
const { currentPassword, newPassword } = c.req.valid('json');
|
|
||||||
|
|
||||||
// Validate new password
|
|
||||||
const passwordValidation = validatePassword(newPassword);
|
|
||||||
if (!passwordValidation.valid) {
|
|
||||||
return c.json({ error: passwordValidation.error }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify current password if user has one
|
|
||||||
const existingHash = await getUserPasswordHash(user.id);
|
|
||||||
if (existingHash) {
|
|
||||||
const validPassword = await verifyPassword(currentPassword, existingHash);
|
|
||||||
if (!validPassword) {
|
|
||||||
return c.json({ error: 'Current password is incorrect' }, 400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const hashedPassword = await hashPassword(newPassword);
|
|
||||||
const now = getNow();
|
|
||||||
|
|
||||||
await (db as any)
|
|
||||||
.update(users)
|
|
||||||
.set({
|
|
||||||
password: hashedPassword,
|
|
||||||
updatedAt: now,
|
|
||||||
})
|
|
||||||
.where(eq((users as any).id, user.id));
|
|
||||||
|
|
||||||
// Invalidate all previously issued JWTs so a stolen old token can't outlive the change,
|
|
||||||
// then hand the current client a fresh token so it stays logged in on this device.
|
|
||||||
await bumpTokenVersion(user.id);
|
|
||||||
const refreshedUser = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).id, user.id))
|
|
||||||
);
|
|
||||||
const newToken = await createToken(user.id, user.email, user.role, refreshedUser?.tokenVersion ?? 0);
|
|
||||||
|
|
||||||
return c.json({ message: 'Password changed successfully', token: newToken });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Logout - invalidate all previously issued JWTs for this user (logout everywhere)
|
|
||||||
auth.post('/logout', async (c) => {
|
|
||||||
const user = await getAuthUser(c);
|
|
||||||
if (user) {
|
|
||||||
await invalidateAllUserSessions(user.id);
|
|
||||||
await bumpTokenVersion(user.id);
|
|
||||||
}
|
|
||||||
return c.json({ message: 'Logged out successfully' });
|
|
||||||
});
|
|
||||||
|
|
||||||
export default auth;
|
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { zValidator } from '@hono/zod-validator';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { eq } from 'drizzle-orm';
|
||||||
|
import { auth } from '../lib/betterAuth.js';
|
||||||
|
import { validatePassword } from '../lib/passwordPolicy.js';
|
||||||
|
import { db, dbGet, users } from '../db/index.js';
|
||||||
|
import { getNow, toDbBool, normalizeEmail } from '../lib/utils.js';
|
||||||
|
import { rateLimitMiddleware } from '../lib/rateLimit.js';
|
||||||
|
|
||||||
|
// Custom auth flows that Better Auth doesn't provide out of the box. Mounted
|
||||||
|
// at /api/auth-ext to avoid colliding with Better Auth's /api/auth/* handler.
|
||||||
|
const authExtRateLimit = rateLimitMiddleware({ max: 20, windowMs: 15 * 60 * 1000, prefix: 'auth-ext' });
|
||||||
|
|
||||||
|
const authExt = new Hono();
|
||||||
|
|
||||||
|
const claimAccountSchema = z.object({
|
||||||
|
password: z.string().min(10, 'Password must be at least 10 characters'),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Complete a progressive-account claim. The user arrives here already holding
|
||||||
|
// a session established by the claim magic link; this endpoint deliberately
|
||||||
|
// accepts accountStatus 'unclaimed' sessions (requireAuth would reject them)
|
||||||
|
// and is the ONLY endpoint that does.
|
||||||
|
authExt.post('/claim-account', authExtRateLimit, zValidator('json', claimAccountSchema), async (c) => {
|
||||||
|
const session = await auth.api.getSession({ headers: c.req.raw.headers });
|
||||||
|
if (!session?.user) {
|
||||||
|
return c.json({ error: 'Unauthorized. Please use the claim link from your email.' }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = session.user as any;
|
||||||
|
if (user.banned || user.accountStatus === 'suspended') {
|
||||||
|
return c.json({ error: 'Account is suspended. Please contact support.' }, 403);
|
||||||
|
}
|
||||||
|
if (user.isClaimed && user.accountStatus === 'active') {
|
||||||
|
return c.json({ error: 'Account is already claimed' }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { password } = c.req.valid('json');
|
||||||
|
const passwordValidation = validatePassword(password);
|
||||||
|
if (!passwordValidation.valid) {
|
||||||
|
return c.json({ error: passwordValidation.error }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creates the credential account with the argon2id hash from lib/betterAuth.ts
|
||||||
|
await auth.api.setPassword({
|
||||||
|
body: { newPassword: password },
|
||||||
|
headers: c.req.raw.headers,
|
||||||
|
});
|
||||||
|
|
||||||
|
// The magic link click proved email ownership
|
||||||
|
await (db as any)
|
||||||
|
.update(users)
|
||||||
|
.set({
|
||||||
|
isClaimed: toDbBool(true),
|
||||||
|
accountStatus: 'active',
|
||||||
|
emailVerified: true,
|
||||||
|
updatedAt: getNow(),
|
||||||
|
})
|
||||||
|
.where(eq((users as any).id, user.id));
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
message: 'Account claimed successfully!',
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
name: user.name,
|
||||||
|
role: user.role,
|
||||||
|
isClaimed: true,
|
||||||
|
phone: user.phone ?? null,
|
||||||
|
rucNumber: user.rucNumber ?? null,
|
||||||
|
languagePreference: user.languagePreference ?? null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Whether an email belongs to an unclaimed account. Deliberate, rate-limited
|
||||||
|
// exception to enumeration-safety, matching the legacy register/login UX that
|
||||||
|
// surfaced "this account can be claimed".
|
||||||
|
authExt.get('/claim-eligibility', authExtRateLimit, async (c) => {
|
||||||
|
const email = c.req.query('email');
|
||||||
|
if (!email || !z.string().email().safeParse(email).success) {
|
||||||
|
return c.json({ canClaim: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalized to match how the row is stored (see lib/utils.ts normalizeEmail)
|
||||||
|
const user = await dbGet<any>(
|
||||||
|
(db as any).select().from(users).where(eq((users as any).email, normalizeEmail(email)))
|
||||||
|
);
|
||||||
|
|
||||||
|
const canClaim = !!user && !user.banned && user.accountStatus !== 'suspended'
|
||||||
|
&& (!user.isClaimed || user.accountStatus === 'unclaimed');
|
||||||
|
|
||||||
|
return c.json({ canClaim });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default authExt;
|
||||||
+108
-46
@@ -1,24 +1,54 @@
|
|||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import { zValidator } from '@hono/zod-validator';
|
import { zValidator } from '@hono/zod-validator';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { db, dbGet, dbAll, users, tickets, payments, events, invoices, User } from '../db/index.js';
|
import { db, dbGet, dbAll, users, tickets, payments, events, invoices, eventMembers } from '../db/index.js';
|
||||||
import { eq, desc, and, gt, sql, inArray } from 'drizzle-orm';
|
import { eq, desc, and, gt, sql, inArray } from 'drizzle-orm';
|
||||||
import { requireAuth, getUserSessions, invalidateSession, invalidateAllUserSessions, bumpTokenVersion, createToken, hashPassword, validatePassword, getUserPasswordHash } from '../lib/auth.js';
|
import { requireAuth, getUserPasswordHash, hasGoogleAccount, validatePassword, type AuthUser } from '../lib/auth.js';
|
||||||
import { generateId, getNow } from '../lib/utils.js';
|
import { auth } from '../lib/betterAuth.js';
|
||||||
|
import { authSessions, authAccounts } from '../db/auth-schema.js';
|
||||||
// User type that includes all fields (some added in schema updates)
|
import { getNow } from '../lib/utils.js';
|
||||||
type AuthUser = User & {
|
import { omitWalkInPrice } from '../lib/walkInPrice.js';
|
||||||
isClaimed: boolean;
|
import { resolveMemberPermissions, EVENT_PERMISSIONS } from '../lib/eventPermissions.js';
|
||||||
googleId: string | null;
|
|
||||||
rucNumber: string | null;
|
|
||||||
accountStatus: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const dashboard = new Hono();
|
const dashboard = new Hono();
|
||||||
|
|
||||||
// Apply authentication to all routes
|
// Apply authentication to all routes
|
||||||
dashboard.use('*', requireAuth());
|
dashboard.use('*', requireAuth());
|
||||||
|
|
||||||
|
// ==================== My Events (team memberships) ====================
|
||||||
|
|
||||||
|
// Events the user was added to as staff / collaborator / co-manager, with what
|
||||||
|
// they may do on each. Opens the scoped event page at /dashboard/events/:id.
|
||||||
|
dashboard.get('/my-events', async (c) => {
|
||||||
|
const user = (c as any).get('user') as AuthUser;
|
||||||
|
const rows = await dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({ m: eventMembers, e: events })
|
||||||
|
.from(eventMembers)
|
||||||
|
.innerJoin(events, eq((eventMembers as any).eventId, (events as any).id))
|
||||||
|
.where(eq((eventMembers as any).userId, user.id))
|
||||||
|
);
|
||||||
|
const toIso = (v: any) => (v instanceof Date ? v.toISOString() : v);
|
||||||
|
return c.json({
|
||||||
|
events: rows
|
||||||
|
.map((r: any) => ({
|
||||||
|
event: {
|
||||||
|
id: r.e.id,
|
||||||
|
slug: r.e.slug,
|
||||||
|
title: r.e.title,
|
||||||
|
titleEs: r.e.titleEs,
|
||||||
|
startDatetime: toIso(r.e.startDatetime),
|
||||||
|
location: r.e.location,
|
||||||
|
status: r.e.status,
|
||||||
|
bannerUrl: r.e.bannerUrl,
|
||||||
|
},
|
||||||
|
rolePreset: r.m.rolePreset,
|
||||||
|
permissions: EVENT_PERMISSIONS.filter((p) => resolveMemberPermissions(r.m.rolePreset, r.m.permissions).has(p)),
|
||||||
|
}))
|
||||||
|
.sort((a: any, b: any) => String(b.event.startDatetime).localeCompare(String(a.event.startDatetime))),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// ==================== Profile Routes ====================
|
// ==================== Profile Routes ====================
|
||||||
|
|
||||||
const updateProfileSchema = z.object({
|
const updateProfileSchema = z.object({
|
||||||
@@ -50,7 +80,7 @@ dashboard.get('/profile', async (c) => {
|
|||||||
isClaimed: user.isClaimed,
|
isClaimed: user.isClaimed,
|
||||||
accountStatus: user.accountStatus,
|
accountStatus: user.accountStatus,
|
||||||
hasPassword,
|
hasPassword,
|
||||||
hasGoogleLinked: !!user.googleId,
|
hasGoogleLinked: await hasGoogleAccount(user.id),
|
||||||
memberSince: user.createdAt,
|
memberSince: user.createdAt,
|
||||||
membershipDays,
|
membershipDays,
|
||||||
createdAt: user.createdAt,
|
createdAt: user.createdAt,
|
||||||
@@ -214,7 +244,7 @@ dashboard.get('/tickets/:id', async (c) => {
|
|||||||
return c.json({
|
return c.json({
|
||||||
ticket: {
|
ticket: {
|
||||||
...ticket,
|
...ticket,
|
||||||
event,
|
event: omitWalkInPrice(event as any),
|
||||||
payment,
|
payment,
|
||||||
invoice,
|
invoice,
|
||||||
},
|
},
|
||||||
@@ -278,7 +308,7 @@ dashboard.get('/next-event', async (c) => {
|
|||||||
|
|
||||||
return c.json({
|
return c.json({
|
||||||
nextEvent: {
|
nextEvent: {
|
||||||
event: nextEvent,
|
event: omitWalkInPrice(nextEvent),
|
||||||
ticket: nextTicket,
|
ticket: nextTicket,
|
||||||
payment: nextPayment,
|
payment: nextPayment,
|
||||||
},
|
},
|
||||||
@@ -423,49 +453,77 @@ dashboard.get('/invoices', async (c) => {
|
|||||||
|
|
||||||
// ==================== Security Routes ====================
|
// ==================== Security Routes ====================
|
||||||
|
|
||||||
// Get active sessions
|
// Get active sessions (Better Auth session table; validated per-request so
|
||||||
|
// this list is always live). Session tokens are never exposed to the client.
|
||||||
dashboard.get('/sessions', async (c) => {
|
dashboard.get('/sessions', async (c) => {
|
||||||
const user = (c as any).get('user') as AuthUser;
|
const user = (c as any).get('user') as AuthUser;
|
||||||
|
|
||||||
const sessions = await getUserSessions(user.id);
|
const sessions = await dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({
|
||||||
|
id: (authSessions as any).id,
|
||||||
|
userAgent: (authSessions as any).userAgent,
|
||||||
|
ipAddress: (authSessions as any).ipAddress,
|
||||||
|
createdAt: (authSessions as any).createdAt,
|
||||||
|
updatedAt: (authSessions as any).updatedAt,
|
||||||
|
expiresAt: (authSessions as any).expiresAt,
|
||||||
|
})
|
||||||
|
.from(authSessions)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq((authSessions as any).userId, user.id),
|
||||||
|
gt((authSessions as any).expiresAt, new Date())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.orderBy(desc((authSessions as any).updatedAt))
|
||||||
|
);
|
||||||
|
|
||||||
return c.json({
|
return c.json({
|
||||||
sessions: sessions.map((s: any) => ({
|
sessions: sessions.map((s: any) => ({
|
||||||
id: s.id,
|
id: s.id,
|
||||||
userAgent: s.userAgent,
|
userAgent: s.userAgent,
|
||||||
ipAddress: s.ipAddress,
|
ipAddress: s.ipAddress,
|
||||||
lastActiveAt: s.lastActiveAt,
|
lastActiveAt: s.updatedAt,
|
||||||
createdAt: s.createdAt,
|
createdAt: s.createdAt,
|
||||||
|
expiresAt: s.expiresAt,
|
||||||
|
current: s.id === user.sessionId,
|
||||||
})),
|
})),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Revoke a specific session
|
// Revoke a specific session. Deleting the row is immediately effective:
|
||||||
|
// sessions are validated against the table on every request (no cookie cache).
|
||||||
dashboard.delete('/sessions/:id', async (c) => {
|
dashboard.delete('/sessions/:id', async (c) => {
|
||||||
const user = (c as any).get('user') as AuthUser;
|
const user = (c as any).get('user') as AuthUser;
|
||||||
const sessionId = c.req.param('id');
|
const sessionId = c.req.param('id');
|
||||||
|
|
||||||
await invalidateSession(sessionId, user.id);
|
await (db as any)
|
||||||
|
.delete(authSessions)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq((authSessions as any).id, sessionId),
|
||||||
|
eq((authSessions as any).userId, user.id)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
return c.json({ message: 'Session revoked' });
|
return c.json({ message: 'Session revoked' });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Revoke all sessions (logout everywhere). Bumping the token version invalidates
|
// Revoke all other sessions (logout everywhere else); the current session
|
||||||
// every previously issued JWT for this user, which is the actual enforcement
|
// stays valid so this device remains signed in.
|
||||||
// mechanism (auth is stateless JWT, not DB-session based).
|
|
||||||
dashboard.post('/sessions/revoke-all', async (c) => {
|
dashboard.post('/sessions/revoke-all', async (c) => {
|
||||||
const user = (c as any).get('user') as AuthUser;
|
const user = (c as any).get('user') as AuthUser;
|
||||||
|
|
||||||
await invalidateAllUserSessions(user.id);
|
await (db as any)
|
||||||
await bumpTokenVersion(user.id);
|
.delete(authSessions)
|
||||||
|
.where(
|
||||||
// Issue a fresh token so the current device stays signed in
|
and(
|
||||||
const refreshed = await dbGet<any>(
|
eq((authSessions as any).userId, user.id),
|
||||||
(db as any).select().from(users).where(eq((users as any).id, user.id))
|
sql`${(authSessions as any).id} != ${user.sessionId}`
|
||||||
|
)
|
||||||
);
|
);
|
||||||
const token = await createToken(user.id, user.email, user.role, refreshed?.tokenVersion ?? 0);
|
|
||||||
|
|
||||||
return c.json({ message: 'All other sessions revoked.', token });
|
return c.json({ message: 'All other sessions revoked.' });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Set password (for users without one)
|
// Set password (for users without one)
|
||||||
@@ -482,21 +540,21 @@ dashboard.post('/set-password', zValidator('json', setPasswordSchema), async (c)
|
|||||||
return c.json({ error: 'Password already set. Use change password instead.' }, 400);
|
return c.json({ error: 'Password already set. Use change password instead.' }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// setPassword is a server-only Better Auth endpoint, so the HTTP-layer
|
||||||
|
// policy hook does not cover it — validate explicitly.
|
||||||
const passwordValidation = validatePassword(password);
|
const passwordValidation = validatePassword(password);
|
||||||
if (!passwordValidation.valid) {
|
if (!passwordValidation.valid) {
|
||||||
return c.json({ error: passwordValidation.error }, 400);
|
return c.json({ error: passwordValidation.error }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
const hashedPassword = await hashPassword(password);
|
try {
|
||||||
const now = getNow();
|
await auth.api.setPassword({
|
||||||
|
body: { newPassword: password },
|
||||||
await (db as any)
|
headers: c.req.raw.headers,
|
||||||
.update(users)
|
});
|
||||||
.set({
|
} catch (err: any) {
|
||||||
password: hashedPassword,
|
return c.json({ error: err?.body?.message || 'Failed to set password' }, 400);
|
||||||
updatedAt: now,
|
}
|
||||||
})
|
|
||||||
.where(eq((users as any).id, user.id));
|
|
||||||
|
|
||||||
return c.json({ message: 'Password set successfully' });
|
return c.json({ message: 'Password set successfully' });
|
||||||
});
|
});
|
||||||
@@ -505,7 +563,7 @@ dashboard.post('/set-password', zValidator('json', setPasswordSchema), async (c)
|
|||||||
dashboard.post('/unlink-google', async (c) => {
|
dashboard.post('/unlink-google', async (c) => {
|
||||||
const user = (c as any).get('user') as AuthUser;
|
const user = (c as any).get('user') as AuthUser;
|
||||||
|
|
||||||
if (!user.googleId) {
|
if (!(await hasGoogleAccount(user.id))) {
|
||||||
return c.json({ error: 'Google account not linked' }, 400);
|
return c.json({ error: 'Google account not linked' }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -513,14 +571,18 @@ dashboard.post('/unlink-google', async (c) => {
|
|||||||
return c.json({ error: 'Cannot unlink Google without a password set' }, 400);
|
return c.json({ error: 'Cannot unlink Google without a password set' }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
const now = getNow();
|
await (db as any)
|
||||||
|
.delete(authAccounts)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq((authAccounts as any).userId, user.id),
|
||||||
|
eq((authAccounts as any).providerId, 'google')
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
await (db as any)
|
await (db as any)
|
||||||
.update(users)
|
.update(users)
|
||||||
.set({
|
.set({ updatedAt: getNow() })
|
||||||
googleId: null,
|
|
||||||
updatedAt: now,
|
|
||||||
})
|
|
||||||
.where(eq((users as any).id, user.id));
|
.where(eq((users as any).id, user.id));
|
||||||
|
|
||||||
return c.json({ message: 'Google account unlinked' });
|
return c.json({ message: 'Google account unlinked' });
|
||||||
|
|||||||
@@ -0,0 +1,691 @@
|
|||||||
|
import { describe, it, expect, beforeAll, vi } from 'vitest';
|
||||||
|
import { execFileSync } from 'child_process';
|
||||||
|
import { mkdtempSync } from 'fs';
|
||||||
|
import { tmpdir } from 'os';
|
||||||
|
import { join } from 'path';
|
||||||
|
|
||||||
|
// Env must be pinned before the db singleton is imported (dotenv never overrides).
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'door-test-'));
|
||||||
|
const dbPath = join(dir, 'test.db');
|
||||||
|
process.env.DB_TYPE = 'sqlite';
|
||||||
|
process.env.DATABASE_URL = dbPath;
|
||||||
|
process.env.FRONTEND_URL = 'http://localhost:3002';
|
||||||
|
process.env.BETTER_AUTH_SECRET = 'door-test-secret-0123456789abcdef';
|
||||||
|
delete process.env.REDIS_URL;
|
||||||
|
|
||||||
|
const STAFF = { id: 'staff-user-id', name: 'Door Staff', role: 'staff' };
|
||||||
|
const ADMIN = { id: 'admin-user-id', name: 'The Admin', role: 'admin' };
|
||||||
|
const ORGANIZER = { id: 'organizer-user-id', name: 'The Organizer', role: 'organizer' };
|
||||||
|
|
||||||
|
// Who the next request is from. Session auth itself is Better Auth's concern and
|
||||||
|
// has its own integration suite; this mock keeps the *role* check real so the
|
||||||
|
// tests can prove which endpoints door staff may reach.
|
||||||
|
let currentUser: { id: string; name: string; role: string } = STAFF;
|
||||||
|
|
||||||
|
vi.mock('../lib/auth.js', () => ({
|
||||||
|
requireAuth: (roles?: string[]) => async (c: any, next: any) => {
|
||||||
|
if (roles && !roles.includes(currentUser.role)) {
|
||||||
|
return c.json({ error: 'Forbidden' }, 403);
|
||||||
|
}
|
||||||
|
c.set('user', currentUser);
|
||||||
|
await next();
|
||||||
|
},
|
||||||
|
getAuthUser: async () => currentUser,
|
||||||
|
}));
|
||||||
|
|
||||||
|
/** Run one request as a given role, always restoring the default afterwards. */
|
||||||
|
async function as<T>(user: typeof STAFF, fn: () => Promise<T>): Promise<T> {
|
||||||
|
const previous = currentUser;
|
||||||
|
currentUser = user;
|
||||||
|
try {
|
||||||
|
return await fn();
|
||||||
|
} finally {
|
||||||
|
currentUser = previous;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Walk-ins with an email trigger a confirmation send; keep it out of the test.
|
||||||
|
vi.mock('../lib/email.js', () => ({
|
||||||
|
default: { sendBookingConfirmation: vi.fn(async () => ({ success: true })) },
|
||||||
|
}));
|
||||||
|
|
||||||
|
let app: any;
|
||||||
|
let sqlite: any;
|
||||||
|
|
||||||
|
const EVENT_ID = 'evt-door-1';
|
||||||
|
const PRICE = 60000;
|
||||||
|
|
||||||
|
/** POST helper that mirrors how the door screen calls the API. */
|
||||||
|
async function post(path: string, body: unknown) {
|
||||||
|
const res = await app.request(path, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
return { status: res.status, body: await res.json() };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function get(path: string) {
|
||||||
|
const res = await app.request(path);
|
||||||
|
return { status: res.status, body: await res.json() };
|
||||||
|
}
|
||||||
|
|
||||||
|
function seedTicket(row: {
|
||||||
|
id: string;
|
||||||
|
first: string;
|
||||||
|
last?: string | null;
|
||||||
|
status: string;
|
||||||
|
paymentStatus: string;
|
||||||
|
phone?: string | null;
|
||||||
|
bookingId?: string | null;
|
||||||
|
qr?: string;
|
||||||
|
/** Seed the pre-sale payment a paid ticket was bought with, at this amount. */
|
||||||
|
paidAmount?: number;
|
||||||
|
}) {
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO tickets (id, booking_id, user_id, event_id, attendee_first_name, attendee_last_name,
|
||||||
|
attendee_email, attendee_phone, status, payment_status, is_guest, qr_code, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(
|
||||||
|
row.id,
|
||||||
|
row.bookingId ?? null,
|
||||||
|
'seed-user',
|
||||||
|
EVENT_ID,
|
||||||
|
row.first,
|
||||||
|
row.last ?? null,
|
||||||
|
`${row.id}@test.py`,
|
||||||
|
row.phone ?? null,
|
||||||
|
row.status,
|
||||||
|
row.paymentStatus,
|
||||||
|
row.qr ?? `QR-${row.id}`,
|
||||||
|
new Date().toISOString()
|
||||||
|
);
|
||||||
|
if (row.paidAmount !== undefined) seedPayment(row.id, row.paidAmount, 'paid');
|
||||||
|
}
|
||||||
|
|
||||||
|
function seedPayment(ticketId: string, amount: number, status: string, provider = 'bancard') {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO payments (id, ticket_id, provider, amount, currency, status, paid_at, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, 'PYG', ?, ?, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(`pay-${ticketId}`, ticketId, provider, amount, status, status === 'paid' ? now : null, now, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
execFileSync('npx', ['tsx', 'src/db/migrate.ts'], { env: { ...process.env }, stdio: 'pipe' });
|
||||||
|
|
||||||
|
return (async () => {
|
||||||
|
const { Hono } = await import('hono');
|
||||||
|
const doorRoutes = (await import('./door.js')).default;
|
||||||
|
app = new Hono();
|
||||||
|
app.route('/api/events', doorRoutes);
|
||||||
|
|
||||||
|
const Database = (await import('better-sqlite3')).default;
|
||||||
|
sqlite = new Database(dbPath);
|
||||||
|
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO users (id, email, name, role, is_claimed, account_status, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, 'user', 0, 'unclaimed', ?, ?)`
|
||||||
|
)
|
||||||
|
.run('seed-user', 'seed@test.py', 'Seed User', now, now);
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO users (id, email, name, role, is_claimed, account_status, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, 'staff', 1, 'active', ?, ?)`
|
||||||
|
)
|
||||||
|
.run(STAFF.id, 'staff@test.py', STAFF.name, now, now);
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO events (id, title, description, start_datetime, location, price, currency, capacity, status, created_at, updated_at)
|
||||||
|
VALUES (?, 'Door Night', 'desc', ?, 'Asuncion', ?, 'PYG', 2, 'published', ?, ?)`
|
||||||
|
)
|
||||||
|
.run(EVENT_ID, now, PRICE, now, now);
|
||||||
|
|
||||||
|
seedTicket({ id: 'tkt-paid', first: 'José', last: 'Núñez', status: 'confirmed', paymentStatus: 'paid', phone: '+595 981 234 567', paidAmount: PRICE });
|
||||||
|
seedTicket({ id: 'tkt-unpaid', first: 'Ana', last: 'Group', status: 'confirmed', paymentStatus: 'unpaid', bookingId: 'bk-1' });
|
||||||
|
seedTicket({ id: 'tkt-unpaid-2', first: 'Beto', last: 'Group', status: 'confirmed', paymentStatus: 'unpaid', bookingId: 'bk-1' });
|
||||||
|
seedTicket({ id: 'tkt-cancelled', first: 'Carla', last: 'Gone', status: 'cancelled', paymentStatus: 'unpaid' });
|
||||||
|
})();
|
||||||
|
}, 120_000);
|
||||||
|
|
||||||
|
describe('door-attendees', () => {
|
||||||
|
it('returns everyone including cancelled, with group bookings flagged', async () => {
|
||||||
|
const { status, body } = await get(`/api/events/${EVENT_ID}/door-attendees`);
|
||||||
|
expect(status).toBe(200);
|
||||||
|
expect(body.event.price).toBe(PRICE);
|
||||||
|
expect(body.attendees).toHaveLength(4);
|
||||||
|
|
||||||
|
const cancelled = body.attendees.find((a: any) => a.ticketId === 'tkt-cancelled');
|
||||||
|
expect(cancelled.status).toBe('cancelled');
|
||||||
|
|
||||||
|
const grouped = body.attendees.find((a: any) => a.ticketId === 'tkt-unpaid');
|
||||||
|
expect(grouped.isGroupBooking).toBe(true);
|
||||||
|
expect(grouped.amountDue).toBe(PRICE);
|
||||||
|
|
||||||
|
const solo = body.attendees.find((a: any) => a.ticketId === 'tkt-paid');
|
||||||
|
expect(solo.isGroupBooking).toBe(false);
|
||||||
|
expect(solo.amountDue).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is sorted alphabetically so an empty search is scrollable', async () => {
|
||||||
|
const { body } = await get(`/api/events/${EVENT_ID}/door-attendees`);
|
||||||
|
const names = body.attendees.map((a: any) => a.fullName);
|
||||||
|
expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('door-checkin: existing ticket', () => {
|
||||||
|
it('checks in a paid attendee with no payment record touched', async () => {
|
||||||
|
const { status, body } = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
ticketId: 'tkt-paid',
|
||||||
|
entryMethod: 'search',
|
||||||
|
idempotencyKey: 'key-paid-checkin',
|
||||||
|
});
|
||||||
|
expect(status).toBe(201);
|
||||||
|
expect(body.attendee.checkedIn).toBe(true);
|
||||||
|
expect(body.attendee.checkinAt).toBeTruthy();
|
||||||
|
expect(body.attendee.checkedInBy).toBe(STAFF.name);
|
||||||
|
expect(body.payment).toBeNull();
|
||||||
|
|
||||||
|
const row = sqlite.prepare('SELECT status, checked_in_by_admin_id FROM tickets WHERE id = ?').get('tkt-paid');
|
||||||
|
expect(row.status).toBe('checked_in');
|
||||||
|
expect(row.checked_in_by_admin_id).toBe(STAFF.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('replays an already-processed key instead of checking in twice', async () => {
|
||||||
|
const before = sqlite.prepare('SELECT checkin_at FROM tickets WHERE id = ?').get('tkt-paid').checkin_at;
|
||||||
|
|
||||||
|
const { status, body } = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
ticketId: 'tkt-paid',
|
||||||
|
idempotencyKey: 'key-paid-checkin',
|
||||||
|
});
|
||||||
|
expect(status).toBe(200);
|
||||||
|
expect(body.replayed).toBe(true);
|
||||||
|
|
||||||
|
const after = sqlite.prepare('SELECT checkin_at FROM tickets WHERE id = ?').get('tkt-paid').checkin_at;
|
||||||
|
expect(after).toBe(before);
|
||||||
|
expect(sqlite.prepare("SELECT COUNT(*) n FROM payments WHERE ticket_id = ? AND source = 'door'").get('tkt-paid').n).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('settles an unpaid group-booking ticket in cash and checks in, in one call', async () => {
|
||||||
|
const { status, body } = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
ticketId: 'tkt-unpaid',
|
||||||
|
payment: { method: 'cash', amount: PRICE },
|
||||||
|
entryMethod: 'search',
|
||||||
|
idempotencyKey: 'key-unpaid-cash',
|
||||||
|
});
|
||||||
|
expect(status).toBe(201);
|
||||||
|
expect(body.attendee.paymentStatus).toBe('paid');
|
||||||
|
expect(body.attendee.checkedIn).toBe(true);
|
||||||
|
expect(body.payment).toMatchObject({ method: 'cash', amount: PRICE });
|
||||||
|
|
||||||
|
const payment = sqlite.prepare('SELECT * FROM payments WHERE ticket_id = ?').get('tkt-unpaid');
|
||||||
|
expect(payment.source).toBe('door');
|
||||||
|
expect(payment.method).toBe('cash');
|
||||||
|
expect(payment.provider).toBe('cash');
|
||||||
|
expect(payment.status).toBe('paid');
|
||||||
|
expect(payment.paid_by_admin_id).toBe(STAFF.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('takes a group payment at a multiple of the ticket price', async () => {
|
||||||
|
const { body } = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
ticketId: 'tkt-unpaid-2',
|
||||||
|
payment: { method: 'transfer', quantity: 2 },
|
||||||
|
idempotencyKey: 'key-unpaid-2-transfer',
|
||||||
|
});
|
||||||
|
expect(body.payment.amount).toBe(PRICE * 2);
|
||||||
|
const payment = sqlite.prepare('SELECT * FROM payments WHERE ticket_id = ?').get('tkt-unpaid-2');
|
||||||
|
expect(payment.provider).toBe('bank_transfer');
|
||||||
|
expect(payment.method).toBe('transfer');
|
||||||
|
expect(payment.amount).toBe(PRICE * 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reactivates a cancelled ticket through the same payment flow', async () => {
|
||||||
|
const { body } = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
ticketId: 'tkt-cancelled',
|
||||||
|
payment: { method: 'bitcoin' },
|
||||||
|
idempotencyKey: 'key-cancelled-reactivate',
|
||||||
|
});
|
||||||
|
expect(body.attendee.status).toBe('checked_in');
|
||||||
|
expect(body.attendee.paymentStatus).toBe('paid');
|
||||||
|
const payment = sqlite.prepare('SELECT * FROM payments WHERE ticket_id = ?').get('tkt-cancelled');
|
||||||
|
// Bitcoin is recorded as already-paid Lightning: same trust model as cash,
|
||||||
|
// no invoice generated (see lib/doorPayments.ts).
|
||||||
|
expect(payment.provider).toBe('lightning');
|
||||||
|
expect(payment.method).toBe('bitcoin');
|
||||||
|
expect(payment.amount).toBe(PRICE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a ticket from another event', async () => {
|
||||||
|
const { status, body } = await post('/api/events/other-event/door-checkin', {
|
||||||
|
ticketId: 'tkt-paid',
|
||||||
|
idempotencyKey: 'key-wrong-event',
|
||||||
|
});
|
||||||
|
expect(status).toBe(404);
|
||||||
|
expect(body.error).toMatch(/Event not found/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('door-checkin: walk-ins', () => {
|
||||||
|
it('creates a cash walk-in confirmed, paid and checked in with no email', async () => {
|
||||||
|
const { status, body } = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Walk' },
|
||||||
|
payment: { method: 'cash' },
|
||||||
|
entryMethod: 'walkin',
|
||||||
|
idempotencyKey: 'key-walkin-cash',
|
||||||
|
});
|
||||||
|
expect(status).toBe(201);
|
||||||
|
expect(body.action).toBe('walkin');
|
||||||
|
expect(body.attendee.fullName).toBe('Walk');
|
||||||
|
expect(body.attendee.checkedIn).toBe(true);
|
||||||
|
expect(body.attendee.paymentStatus).toBe('paid');
|
||||||
|
expect(body.attendee.email).toBeNull();
|
||||||
|
|
||||||
|
const ticket = sqlite.prepare('SELECT * FROM tickets WHERE id = ?').get(body.attendee.ticketId);
|
||||||
|
expect(ticket.status).toBe('checked_in');
|
||||||
|
expect(ticket.qr_code).toBeTruthy();
|
||||||
|
// A placeholder account keeps users.email unique without mailing anyone.
|
||||||
|
const account = sqlite.prepare('SELECT email FROM users WHERE id = ?').get(ticket.user_id);
|
||||||
|
expect(account.email).toMatch(/@doorentry\.local$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records a guest walk-in as a zero-amount comp', async () => {
|
||||||
|
const { body } = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Free', lastName: 'Guest' },
|
||||||
|
payment: { method: 'guest', amount: PRICE },
|
||||||
|
entryMethod: 'walkin',
|
||||||
|
idempotencyKey: 'key-walkin-guest',
|
||||||
|
});
|
||||||
|
expect(body.attendee.paymentStatus).toBe('comp');
|
||||||
|
expect(body.attendee.isGuest).toBe(true);
|
||||||
|
expect(body.payment.amount).toBe(0);
|
||||||
|
const payment = sqlite.prepare('SELECT * FROM payments WHERE ticket_id = ?').get(body.attendee.ticketId);
|
||||||
|
expect(payment.amount).toBe(0);
|
||||||
|
expect(payment.method).toBe('guest');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not create a second ticket when the same walk-in key is retried', async () => {
|
||||||
|
const before = sqlite.prepare('SELECT COUNT(*) n FROM tickets').get().n;
|
||||||
|
const { status, body } = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Walk' },
|
||||||
|
payment: { method: 'cash' },
|
||||||
|
idempotencyKey: 'key-walkin-cash',
|
||||||
|
});
|
||||||
|
expect(status).toBe(200);
|
||||||
|
expect(body.replayed).toBe(true);
|
||||||
|
expect(sqlite.prepare('SELECT COUNT(*) n FROM tickets').get().n).toBe(before);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('warns rather than blocks once the event is over capacity', async () => {
|
||||||
|
// Capacity is 2 and several tickets already hold seats.
|
||||||
|
const { body } = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Overflow' },
|
||||||
|
payment: { method: 'cash' },
|
||||||
|
idempotencyKey: 'key-walkin-overflow',
|
||||||
|
});
|
||||||
|
expect(body.ok).toBe(true);
|
||||||
|
expect(body.warnings).toContain('at_capacity');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('undo', () => {
|
||||||
|
it('reverts a plain check-in to its previous state', async () => {
|
||||||
|
seedTicket({ id: 'tkt-undo', first: 'Undo', last: 'Me', status: 'confirmed', paymentStatus: 'paid', paidAmount: PRICE });
|
||||||
|
await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
ticketId: 'tkt-undo',
|
||||||
|
idempotencyKey: 'key-undo-checkin',
|
||||||
|
});
|
||||||
|
expect(sqlite.prepare('SELECT status FROM tickets WHERE id = ?').get('tkt-undo').status).toBe('checked_in');
|
||||||
|
|
||||||
|
const { status, body } = await post(`/api/events/${EVENT_ID}/door-checkin/undo`, {
|
||||||
|
idempotencyKey: 'key-undo-checkin',
|
||||||
|
});
|
||||||
|
expect(status).toBe(200);
|
||||||
|
expect(body.reverted).toBe('existing');
|
||||||
|
|
||||||
|
const row = sqlite.prepare('SELECT status, checkin_at FROM tickets WHERE id = ?').get('tkt-undo');
|
||||||
|
expect(row.status).toBe('confirmed');
|
||||||
|
expect(row.checkin_at).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes the payment it created and restores the unpaid balance', async () => {
|
||||||
|
seedTicket({ id: 'tkt-undo-pay', first: 'Undo', last: 'Pay', status: 'confirmed', paymentStatus: 'unpaid' });
|
||||||
|
await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
ticketId: 'tkt-undo-pay',
|
||||||
|
payment: { method: 'cash' },
|
||||||
|
idempotencyKey: 'key-undo-pay',
|
||||||
|
});
|
||||||
|
expect(sqlite.prepare('SELECT COUNT(*) n FROM payments WHERE ticket_id = ?').get('tkt-undo-pay').n).toBe(1);
|
||||||
|
|
||||||
|
await post(`/api/events/${EVENT_ID}/door-checkin/undo`, { idempotencyKey: 'key-undo-pay' });
|
||||||
|
|
||||||
|
const row = sqlite.prepare('SELECT status, payment_status FROM tickets WHERE id = ?').get('tkt-undo-pay');
|
||||||
|
expect(row.status).toBe('confirmed');
|
||||||
|
expect(row.payment_status).toBe('unpaid');
|
||||||
|
expect(sqlite.prepare('SELECT COUNT(*) n FROM payments WHERE ticket_id = ?').get('tkt-undo-pay').n).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cancels a walk-in it created', async () => {
|
||||||
|
const { body } = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Mistake' },
|
||||||
|
payment: { method: 'cash' },
|
||||||
|
idempotencyKey: 'key-undo-walkin',
|
||||||
|
});
|
||||||
|
await post(`/api/events/${EVENT_ID}/door-checkin/undo`, { idempotencyKey: 'key-undo-walkin' });
|
||||||
|
|
||||||
|
const ticket = sqlite.prepare('SELECT status FROM tickets WHERE id = ?').get(body.attendee.ticketId);
|
||||||
|
expect(ticket.status).toBe('cancelled');
|
||||||
|
const payment = sqlite.prepare('SELECT status FROM payments WHERE ticket_id = ?').get(body.attendee.ticketId);
|
||||||
|
expect(payment.status).toBe('cancelled');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is safe to call twice and rejects an unknown key', async () => {
|
||||||
|
const repeat = await post(`/api/events/${EVENT_ID}/door-checkin/undo`, { idempotencyKey: 'key-undo-walkin' });
|
||||||
|
expect(repeat.body.alreadyUndone).toBe(true);
|
||||||
|
|
||||||
|
const unknown = await post(`/api/events/${EVENT_ID}/door-checkin/undo`, { idempotencyKey: 'never-happened' });
|
||||||
|
expect(unknown.status).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('door-summary access', () => {
|
||||||
|
it('is hidden from door staff — whole-event takings are not door information', async () => {
|
||||||
|
const { status, body } = await get(`/api/events/${EVENT_ID}/door-summary`);
|
||||||
|
expect(status).toBe(403);
|
||||||
|
// The numbers must not leak in the body either: hiding the section in the UI
|
||||||
|
// alone would still expose them to anyone reading the network response.
|
||||||
|
expect(body).not.toHaveProperty('door');
|
||||||
|
expect(body).not.toHaveProperty('presale');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is available to admin and organizer', async () => {
|
||||||
|
for (const role of [ADMIN, ORGANIZER]) {
|
||||||
|
const { status } = await as(role, () => get(`/api/events/${EVENT_ID}/door-summary`));
|
||||||
|
expect(status, `${role.role} should see door takings`).toBe(200);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still lets door staff do their job — list, check in and undo', async () => {
|
||||||
|
expect((await get(`/api/events/${EVENT_ID}/door-attendees`)).status).toBe(200);
|
||||||
|
|
||||||
|
// Comp, so this ticket stays out of the revenue totals asserted below and
|
||||||
|
// the two tests cannot drift into each other through the shared database.
|
||||||
|
seedTicket({ id: 'tkt-role', first: 'Role', last: 'Check', status: 'confirmed', paymentStatus: 'comp' });
|
||||||
|
const checkin = await post(`/api/events/${EVENT_ID}/door-checkin`, {
|
||||||
|
ticketId: 'tkt-role',
|
||||||
|
idempotencyKey: 'key-role-check',
|
||||||
|
});
|
||||||
|
expect(checkin.status).toBe(201);
|
||||||
|
|
||||||
|
const undo = await post(`/api/events/${EVENT_ID}/door-checkin/undo`, {
|
||||||
|
idempotencyKey: 'key-role-check',
|
||||||
|
});
|
||||||
|
expect(undo.status).toBe(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('door-summary', () => {
|
||||||
|
it('totals door takings by tender and splits them from pre-sale', async () => {
|
||||||
|
const { status, body } = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/door-summary`));
|
||||||
|
expect(status).toBe(200);
|
||||||
|
|
||||||
|
// Cash: tkt-unpaid + the 'Walk' and 'Overflow' walk-ins (the undone ones are
|
||||||
|
// cancelled and no longer count).
|
||||||
|
expect(body.door.byMethod.cash.count).toBe(3);
|
||||||
|
expect(body.door.byMethod.cash.total).toBe(PRICE * 3);
|
||||||
|
expect(body.door.byMethod.transfer).toEqual({ count: 1, total: PRICE * 2 });
|
||||||
|
expect(body.door.byMethod.bitcoin).toEqual({ count: 1, total: PRICE });
|
||||||
|
expect(body.door.byMethod.guest).toEqual({ count: 1, total: 0 });
|
||||||
|
expect(body.door.total).toBe(PRICE * 6);
|
||||||
|
|
||||||
|
// Settled tickets with no door payment against them: tkt-paid, plus tkt-undo,
|
||||||
|
// whose door check-in was undone and which is a pre-paid ticket again.
|
||||||
|
expect(body.presale.count).toBe(2);
|
||||||
|
expect(body.presale.total).toBe(PRICE * 2);
|
||||||
|
expect(body.total).toBe(PRICE * 8);
|
||||||
|
|
||||||
|
expect(body.door.lines.length).toBe(body.door.count);
|
||||||
|
expect(body.door.lines[0]).toHaveProperty('name');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps pre-sale revenue at what was paid when the ticket price changes', async () => {
|
||||||
|
sqlite.prepare('UPDATE events SET price = ? WHERE id = ?').run(99000, EVENT_ID);
|
||||||
|
try {
|
||||||
|
const { body } = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/door-summary`));
|
||||||
|
expect(body.presale).toEqual({ count: 2, total: PRICE * 2 });
|
||||||
|
expect(body.door.total).toBe(PRICE * 6);
|
||||||
|
} finally {
|
||||||
|
sqlite.prepare('UPDATE events SET price = ? WHERE id = ?').run(PRICE, EVENT_ID);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Walk-in price & POS ====================
|
||||||
|
// Separate events so these cannot drift into the door-summary totals above.
|
||||||
|
|
||||||
|
const WALKIN_EVENT_ID = 'evt-door-walkin';
|
||||||
|
const WALKIN_PRICE = 25000;
|
||||||
|
const WALKIN_TICKET_PRICE = 21000;
|
||||||
|
const FREE_WALKIN_EVENT_ID = 'evt-door-free-walkin';
|
||||||
|
const NO_POS_EVENT_ID = 'evt-door-no-pos';
|
||||||
|
|
||||||
|
describe('walk-in pricing', () => {
|
||||||
|
beforeAll(() => {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const insertEvent = sqlite.prepare(
|
||||||
|
`INSERT INTO events (id, title, description, start_datetime, location, price, walk_in_price, currency, capacity, status, created_at, updated_at)
|
||||||
|
VALUES (?, ?, 'desc', ?, 'Asuncion', ?, ?, 'PYG', 100, 'published', ?, ?)`
|
||||||
|
);
|
||||||
|
insertEvent.run(WALKIN_EVENT_ID, 'Walk-in Night', now, WALKIN_TICKET_PRICE, WALKIN_PRICE, now, now);
|
||||||
|
insertEvent.run(FREE_WALKIN_EVENT_ID, 'Free Door Night', now, WALKIN_TICKET_PRICE, 0, now, now);
|
||||||
|
insertEvent.run(NO_POS_EVENT_ID, 'No POS Night', now, WALKIN_TICKET_PRICE, null, now, now);
|
||||||
|
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO users (id, email, name, role, is_claimed, account_status, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, 'admin', 1, 'active', ?, ?)`
|
||||||
|
)
|
||||||
|
.run(ADMIN.id, 'admin@test.py', ADMIN.name, now, now);
|
||||||
|
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO event_payment_overrides (id, event_id, pos_enabled, created_at, updated_at)
|
||||||
|
VALUES ('ovr-no-pos', ?, 0, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(NO_POS_EVENT_ID, now, now);
|
||||||
|
|
||||||
|
sqlite
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO tickets (id, user_id, event_id, attendee_first_name, status, payment_status, is_guest, qr_code, created_at)
|
||||||
|
VALUES ('tkt-walkin-event-unpaid', 'seed-user', ?, 'Pre', 'confirmed', 'unpaid', 0, 'QR-walkin-unpaid', ?)`
|
||||||
|
)
|
||||||
|
.run(WALKIN_EVENT_ID, now);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves the walk-in unit price on the server for the door screen', async () => {
|
||||||
|
const withPrice = await get(`/api/events/${WALKIN_EVENT_ID}/door-attendees`);
|
||||||
|
expect(withPrice.body.event).toMatchObject({
|
||||||
|
price: WALKIN_TICKET_PRICE,
|
||||||
|
walkInPrice: WALKIN_PRICE,
|
||||||
|
walkInUnitPrice: WALKIN_PRICE,
|
||||||
|
walkInPriceSource: 'walk_in',
|
||||||
|
});
|
||||||
|
|
||||||
|
const fallback = await get(`/api/events/${EVENT_ID}/door-attendees`);
|
||||||
|
expect(fallback.body.event).toMatchObject({
|
||||||
|
walkInPrice: null,
|
||||||
|
walkInUnitPrice: PRICE,
|
||||||
|
walkInPriceSource: 'ticket',
|
||||||
|
});
|
||||||
|
|
||||||
|
const free = await get(`/api/events/${FREE_WALKIN_EVENT_ID}/door-attendees`);
|
||||||
|
expect(free.body.event).toMatchObject({ walkInPrice: 0, walkInUnitPrice: 0, walkInPriceSource: 'walk_in' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('charges walk-ins the walk-in price and marks them as walk-in bookings', async () => {
|
||||||
|
const { status, body } = await post(`/api/events/${WALKIN_EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Door', lastName: 'Buyer' },
|
||||||
|
payment: { method: 'cash' },
|
||||||
|
entryMethod: 'walkin',
|
||||||
|
idempotencyKey: 'key-walkin-price-cash',
|
||||||
|
});
|
||||||
|
expect(status).toBe(201);
|
||||||
|
expect(body.payment).toMatchObject({ method: 'cash', amount: WALKIN_PRICE, currency: 'PYG', amountOverridden: false });
|
||||||
|
|
||||||
|
const ticket = sqlite.prepare('SELECT booking_source FROM tickets WHERE id = ?').get(body.attendee.ticketId);
|
||||||
|
expect(ticket.booking_source).toBe('walk_in');
|
||||||
|
const payment = sqlite.prepare('SELECT amount, currency, source FROM payments WHERE ticket_id = ?').get(body.attendee.ticketId);
|
||||||
|
expect(payment).toMatchObject({ amount: WALKIN_PRICE, currency: 'PYG', source: 'door' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats a walk-in price of 0 as a free walk-in, not as "unset"', async () => {
|
||||||
|
const { body } = await post(`/api/events/${FREE_WALKIN_EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Free' },
|
||||||
|
payment: { method: 'cash' },
|
||||||
|
idempotencyKey: 'key-walkin-free',
|
||||||
|
});
|
||||||
|
expect(body.payment.amount).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('multiplies the resolved price by quantity', async () => {
|
||||||
|
const { body } = await post(`/api/events/${WALKIN_EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Group' },
|
||||||
|
payment: { method: 'cash', quantity: 3 },
|
||||||
|
idempotencyKey: 'key-walkin-price-group',
|
||||||
|
});
|
||||||
|
expect(body.payment.amount).toBe(WALKIN_PRICE * 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores a client-sent amount without the override flag', async () => {
|
||||||
|
const { status, body } = await post(`/api/events/${WALKIN_EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Cheap' },
|
||||||
|
payment: { method: 'cash', amount: 1 },
|
||||||
|
idempotencyKey: 'key-walkin-client-amount',
|
||||||
|
});
|
||||||
|
expect(status).toBe(201);
|
||||||
|
expect(body.payment.amount).toBe(WALKIN_PRICE);
|
||||||
|
const payment = sqlite.prepare('SELECT amount FROM payments WHERE ticket_id = ?').get(body.attendee.ticketId);
|
||||||
|
expect(payment.amount).toBe(WALKIN_PRICE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses an amount override from door staff and writes nothing', async () => {
|
||||||
|
const before = sqlite.prepare('SELECT COUNT(*) n FROM tickets').get().n;
|
||||||
|
const { status, body } = await post(`/api/events/${WALKIN_EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Discount' },
|
||||||
|
payment: { method: 'cash', amount: 1000, amountOverride: true },
|
||||||
|
idempotencyKey: 'key-walkin-staff-override',
|
||||||
|
});
|
||||||
|
expect(status).toBe(403);
|
||||||
|
expect(body.code).toBe('OVERRIDE_FORBIDDEN');
|
||||||
|
expect(sqlite.prepare('SELECT COUNT(*) n FROM tickets').get().n).toBe(before);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets an admin override the amount and records it in the audit log', async () => {
|
||||||
|
const { status, body } = await as(ADMIN, () => post(`/api/events/${WALKIN_EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Friend' },
|
||||||
|
payment: { method: 'cash', amount: 10000, amountOverride: true },
|
||||||
|
idempotencyKey: 'key-walkin-admin-override',
|
||||||
|
}));
|
||||||
|
expect(status).toBe(201);
|
||||||
|
expect(body.payment).toMatchObject({ amount: 10000, amountOverridden: true });
|
||||||
|
|
||||||
|
const log = sqlite
|
||||||
|
.prepare(`SELECT * FROM audit_logs WHERE action = 'door_amount_override' AND target_id = ?`)
|
||||||
|
.get(body.payment.id);
|
||||||
|
expect(log.user_id).toBe(ADMIN.id);
|
||||||
|
expect(JSON.parse(log.details)).toMatchObject({
|
||||||
|
eventId: WALKIN_EVENT_ID,
|
||||||
|
computedAmount: WALKIN_PRICE,
|
||||||
|
chargedAmount: 10000,
|
||||||
|
currency: 'PYG',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('settles an existing unpaid ticket at the ticket price, not the walk-in price', async () => {
|
||||||
|
const { body } = await post(`/api/events/${WALKIN_EVENT_ID}/door-checkin`, {
|
||||||
|
ticketId: 'tkt-walkin-event-unpaid',
|
||||||
|
payment: { method: 'cash' },
|
||||||
|
idempotencyKey: 'key-walkin-event-existing',
|
||||||
|
});
|
||||||
|
expect(body.payment.amount).toBe(WALKIN_TICKET_PRICE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the charged amount when the walk-in price is edited afterwards', async () => {
|
||||||
|
const { body } = await post(`/api/events/${WALKIN_EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Snapshot' },
|
||||||
|
payment: { method: 'cash' },
|
||||||
|
idempotencyKey: 'key-walkin-snapshot',
|
||||||
|
});
|
||||||
|
sqlite.prepare('UPDATE events SET walk_in_price = ? WHERE id = ?').run(99000, WALKIN_EVENT_ID);
|
||||||
|
try {
|
||||||
|
const payment = sqlite.prepare('SELECT amount FROM payments WHERE ticket_id = ?').get(body.attendee.ticketId);
|
||||||
|
expect(payment.amount).toBe(WALKIN_PRICE);
|
||||||
|
} finally {
|
||||||
|
sqlite.prepare('UPDATE events SET walk_in_price = ? WHERE id = ?').run(WALKIN_PRICE, WALKIN_EVENT_ID);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POS tender', () => {
|
||||||
|
it('is offered on the door screen unless switched off for the event', async () => {
|
||||||
|
expect((await get(`/api/events/${WALKIN_EVENT_ID}/door-attendees`)).body.doorMethods)
|
||||||
|
.toEqual(['cash', 'bitcoin', 'transfer', 'pos', 'guest']);
|
||||||
|
expect((await get(`/api/events/${NO_POS_EVENT_ID}/door-attendees`)).body.doorMethods)
|
||||||
|
.toEqual(['cash', 'bitcoin', 'transfer', 'guest']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records a confirmed POS walk-in as a paid door payment at the walk-in price', async () => {
|
||||||
|
const { status, body } = await post(`/api/events/${WALKIN_EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Card', lastName: 'Payer' },
|
||||||
|
payment: { method: 'pos' },
|
||||||
|
entryMethod: 'walkin',
|
||||||
|
idempotencyKey: 'key-walkin-pos',
|
||||||
|
});
|
||||||
|
expect(status).toBe(201);
|
||||||
|
expect(body.attendee).toMatchObject({ checkedIn: true, paymentStatus: 'paid', doorMethod: 'pos' });
|
||||||
|
expect(body.payment).toMatchObject({ method: 'pos', amount: WALKIN_PRICE });
|
||||||
|
|
||||||
|
const payment = sqlite.prepare('SELECT * FROM payments WHERE ticket_id = ?').get(body.attendee.ticketId);
|
||||||
|
expect(payment).toMatchObject({
|
||||||
|
provider: 'pos',
|
||||||
|
method: 'pos',
|
||||||
|
source: 'door',
|
||||||
|
status: 'paid',
|
||||||
|
amount: WALKIN_PRICE,
|
||||||
|
paid_by_admin_id: STAFF.id,
|
||||||
|
reference: 'Door — paid by POS',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows POS takings in the door summary', async () => {
|
||||||
|
const { body } = await as(ADMIN, () => get(`/api/events/${WALKIN_EVENT_ID}/door-summary`));
|
||||||
|
expect(body.door.byMethod.pos).toEqual({ count: 1, total: WALKIN_PRICE });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('can be undone like any other walk-in', async () => {
|
||||||
|
const { body } = await post(`/api/events/${WALKIN_EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Declined' },
|
||||||
|
payment: { method: 'pos' },
|
||||||
|
idempotencyKey: 'key-walkin-pos-undo',
|
||||||
|
});
|
||||||
|
await post(`/api/events/${WALKIN_EVENT_ID}/door-checkin/undo`, { idempotencyKey: 'key-walkin-pos-undo' });
|
||||||
|
const payment = sqlite.prepare('SELECT status FROM payments WHERE ticket_id = ?').get(body.attendee.ticketId);
|
||||||
|
expect(payment.status).toBe('cancelled');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is rejected when POS is disabled for the event', async () => {
|
||||||
|
const { status, body } = await post(`/api/events/${NO_POS_EVENT_ID}/door-checkin`, {
|
||||||
|
attendee: { firstName: 'Nope' },
|
||||||
|
payment: { method: 'pos' },
|
||||||
|
idempotencyKey: 'key-walkin-pos-disabled',
|
||||||
|
});
|
||||||
|
expect(status).toBe(400);
|
||||||
|
expect(body.code).toBe('METHOD_DISABLED');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,746 @@
|
|||||||
|
// Door check-in screen (admin/scanner) API.
|
||||||
|
//
|
||||||
|
// At the door, check-in and ticket creation are the same action, so everything
|
||||||
|
// here is written for one-tap speed on a phone with unreliable venue wifi:
|
||||||
|
//
|
||||||
|
// GET /:eventId/door-attendees full attendee list, fetched once and searched
|
||||||
|
// client-side so typing never hits the network
|
||||||
|
// POST /:eventId/door-checkin the single write endpoint — checks in, settles
|
||||||
|
// payment, or creates a walk-in, atomically
|
||||||
|
// POST /:eventId/door-checkin/undo reverses exactly what one keyed action did
|
||||||
|
// GET /:eventId/door-summary end-of-night cash-up + pre-sale/door revenue
|
||||||
|
// split (admin/organizer only)
|
||||||
|
//
|
||||||
|
// Every write carries a client-generated idempotencyKey. The key is inserted in
|
||||||
|
// the same transaction as the writes, so a double tap or a retry after a timeout
|
||||||
|
// can never produce a second ticket, a second payment or a double check-in — the
|
||||||
|
// replay returns the original response instead.
|
||||||
|
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { zValidator } from '@hono/zod-validator';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { eq, and, inArray, sql } from 'drizzle-orm';
|
||||||
|
import {
|
||||||
|
db, dbGet, dbAll, tickets, events, users, payments, idempotencyKeys, auditLogs,
|
||||||
|
} from '../db/index.js';
|
||||||
|
import { requireEventPermission, eventFromParam, canSeeAttendeePii } from '../lib/eventPermissions.js';
|
||||||
|
import { generateId, generateTicketCode, getNow, toDbBool, toDbDate, normalizeEmail } from '../lib/utils.js';
|
||||||
|
import { runOps, insertOp, updateOp, deleteOp, type TxOp } from '../lib/txOps.js';
|
||||||
|
import { seatHolderCountQuery } from '../lib/capacity.js';
|
||||||
|
import {
|
||||||
|
DOOR_PAYMENT_METHODS, DOOR_TENDERS, amountForMethod, doorReference,
|
||||||
|
paymentStatusForMethod, loadDoorMethods, type DoorPaymentMethod,
|
||||||
|
} from '../lib/doorPayments.js';
|
||||||
|
import { parseWalkInPrice, resolveWalkInPrice } from '../lib/walkInPrice.js';
|
||||||
|
import emailService from '../lib/email.js';
|
||||||
|
|
||||||
|
const doorRouter = new Hono();
|
||||||
|
|
||||||
|
const STAFF_ROLES = ['admin', 'organizer', 'staff'] as const;
|
||||||
|
// Whole-event money is management information, not door information: door staff
|
||||||
|
// reconcile their own shift from the session feed the client keeps locally, and
|
||||||
|
// never see what the event took overall. Matches the existing convention for
|
||||||
|
// revenue aggregates (admin/export/financial, admin/analytics).
|
||||||
|
const REVENUE_ROLES = ['admin', 'organizer'] as const;
|
||||||
|
// The server prices every door charge from the event record. Only the roles the
|
||||||
|
// app treats as administrators may override that with a typed amount, and every
|
||||||
|
// override is written to audit_logs.
|
||||||
|
const AMOUNT_OVERRIDE_ROLES = ['admin', 'organizer'] as const;
|
||||||
|
const MAX_DOOR_QUANTITY = 50;
|
||||||
|
const IDEMPOTENCY_SCOPE = 'door-checkin';
|
||||||
|
|
||||||
|
// ==================== Shared helpers ====================
|
||||||
|
|
||||||
|
const num = (v: any): number => {
|
||||||
|
const n = typeof v === 'string' ? parseFloat(v) : Number(v);
|
||||||
|
return Number.isFinite(n) ? n : 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const iso = (v: any): string | null => {
|
||||||
|
if (!v) return null;
|
||||||
|
return v instanceof Date ? v.toISOString() : String(v);
|
||||||
|
};
|
||||||
|
|
||||||
|
function fullName(ticket: any): string {
|
||||||
|
return `${ticket.attendeeFirstName} ${ticket.attendeeLastName || ''}`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The row shape the door screen renders. Returned both by the preload list and
|
||||||
|
* by every write, so the client can splice an updated attendee straight back
|
||||||
|
* into its in-memory list without a refetch.
|
||||||
|
*/
|
||||||
|
function toDoorAttendee(
|
||||||
|
ticket: any,
|
||||||
|
opts: { price: number; groupBookingIds: Set<string>; adminNames: Map<string, string>; doorMethod?: string | null } ,
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
ticketId: ticket.id,
|
||||||
|
firstName: ticket.attendeeFirstName,
|
||||||
|
lastName: ticket.attendeeLastName || null,
|
||||||
|
fullName: fullName(ticket),
|
||||||
|
email: ticket.attendeeEmail || null,
|
||||||
|
phone: ticket.attendeePhone || null,
|
||||||
|
status: ticket.status,
|
||||||
|
paymentStatus: ticket.paymentStatus,
|
||||||
|
isGuest: !!ticket.isGuest,
|
||||||
|
checkedIn: ticket.status === 'checked_in',
|
||||||
|
checkinAt: iso(ticket.checkinAt),
|
||||||
|
checkedInBy: ticket.checkedInByAdminId ? opts.adminNames.get(ticket.checkedInByAdminId) || null : null,
|
||||||
|
bookingId: ticket.bookingId || null,
|
||||||
|
isGroupBooking: !!(ticket.bookingId && opts.groupBookingIds.has(ticket.bookingId)),
|
||||||
|
amountDue: ticket.paymentStatus === 'unpaid' ? opts.price : 0,
|
||||||
|
doorMethod: opts.doorMethod ?? null,
|
||||||
|
qrCode: ticket.qrCode || null,
|
||||||
|
createdAt: iso(ticket.createdAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadEvent(eventId: string | undefined) {
|
||||||
|
if (!eventId) return null;
|
||||||
|
const event = await dbGet<any>(
|
||||||
|
(db as any).select().from(events).where(eq((events as any).id, eventId))
|
||||||
|
);
|
||||||
|
if (!event) return null;
|
||||||
|
return {
|
||||||
|
...event,
|
||||||
|
price: num(event.price),
|
||||||
|
walkInPrice: parseWalkInPrice(event.walkInPrice),
|
||||||
|
capacity: Number(event.capacity),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Names of the admins/staff referenced by the given check-in rows, in one query. */
|
||||||
|
async function loadAdminNames(adminIds: string[]): Promise<Map<string, string>> {
|
||||||
|
const unique = [...new Set(adminIds.filter(Boolean))];
|
||||||
|
if (unique.length === 0) return new Map();
|
||||||
|
const rows = await dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({ id: (users as any).id, name: (users as any).name })
|
||||||
|
.from(users)
|
||||||
|
.where(inArray((users as any).id, unique))
|
||||||
|
);
|
||||||
|
return new Map(rows.map((r: any) => [r.id, r.name]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Seats currently held for an event, used only to warn (never to block) at the door. */
|
||||||
|
async function seatsHeld(eventId: string): Promise<number> {
|
||||||
|
const row = await dbGet<any>(seatHolderCountQuery(db, eventId));
|
||||||
|
return Number(row?.count || 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== GET /:eventId/door-attendees ====================
|
||||||
|
// One payload, fetched on load and refreshed every ~30s by the client. Cancelled
|
||||||
|
// tickets are included on purpose: staff must be able to see and reactivate them.
|
||||||
|
|
||||||
|
doorRouter.get('/:eventId/door-attendees', requireEventPermission('check_in', { globalRoles: STAFF_ROLES, eventId: eventFromParam('eventId') }), async (c) => {
|
||||||
|
const eventId = c.req.param('eventId');
|
||||||
|
|
||||||
|
const event = await loadEvent(eventId);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
|
||||||
|
const rows = await dbAll<any>(
|
||||||
|
(db as any).select().from(tickets).where(eq((tickets as any).eventId, eventId))
|
||||||
|
);
|
||||||
|
|
||||||
|
// A booking id shared by more than one ticket marks a group booking, which is
|
||||||
|
// the usual reason an otherwise-confirmed attendee still shows as unpaid.
|
||||||
|
const bookingCounts = new Map<string, number>();
|
||||||
|
for (const t of rows) {
|
||||||
|
if (t.bookingId) bookingCounts.set(t.bookingId, (bookingCounts.get(t.bookingId) || 0) + 1);
|
||||||
|
}
|
||||||
|
const groupBookingIds = new Set(
|
||||||
|
[...bookingCounts.entries()].filter(([, n]) => n > 1).map(([id]) => id)
|
||||||
|
);
|
||||||
|
|
||||||
|
const adminNames = await loadAdminNames(rows.map((t: any) => t.checkedInByAdminId));
|
||||||
|
|
||||||
|
// Door tender per ticket, so a row already settled at the door shows how.
|
||||||
|
// Joined on the event rather than on a list of ticket ids: the id list would
|
||||||
|
// grow with the guest list and eventually blow the statement parameter limit.
|
||||||
|
const doorMethods = new Map<string, string>();
|
||||||
|
const doorPayments = await dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({ ticketId: (payments as any).ticketId, method: (payments as any).method })
|
||||||
|
.from(payments)
|
||||||
|
.innerJoin(tickets, eq((payments as any).ticketId, (tickets as any).id))
|
||||||
|
.where(and(
|
||||||
|
eq((tickets as any).eventId, eventId),
|
||||||
|
eq((payments as any).source, 'door')
|
||||||
|
))
|
||||||
|
);
|
||||||
|
for (const p of doorPayments) if (p.method) doorMethods.set(p.ticketId, p.method);
|
||||||
|
|
||||||
|
const enabledMethods = await loadDoorMethods(event.id);
|
||||||
|
const walkIn = resolveWalkInPrice(event);
|
||||||
|
|
||||||
|
const attendees = rows
|
||||||
|
.map((t: any) => toDoorAttendee(t, {
|
||||||
|
price: event.price,
|
||||||
|
groupBookingIds,
|
||||||
|
adminNames,
|
||||||
|
doorMethod: doorMethods.get(t.id) || null,
|
||||||
|
}))
|
||||||
|
.map((a) => (canSeeAttendeePii(c) ? a : { ...a, email: null, phone: null }))
|
||||||
|
.sort((a, b) => a.fullName.localeCompare(b.fullName, undefined, { sensitivity: 'base' }));
|
||||||
|
|
||||||
|
const checkedIn = attendees.filter((a) => a.checkedIn).length;
|
||||||
|
const totalActive = attendees.filter((a) => a.status === 'confirmed' || a.status === 'checked_in').length;
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
event: {
|
||||||
|
id: event.id,
|
||||||
|
title: event.title,
|
||||||
|
price: event.price,
|
||||||
|
// What one walk-in ticket costs, resolved server-side (walk-in price, or
|
||||||
|
// the ticket price when none is set) so the screen shows what will be charged.
|
||||||
|
walkInPrice: event.walkInPrice,
|
||||||
|
walkInUnitPrice: walkIn.unitPrice,
|
||||||
|
walkInPriceSource: walkIn.source,
|
||||||
|
currency: event.currency,
|
||||||
|
capacity: event.capacity,
|
||||||
|
},
|
||||||
|
doorMethods: enabledMethods,
|
||||||
|
attendees,
|
||||||
|
stats: { checkedIn, totalActive, capacity: event.capacity },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== POST /:eventId/door-checkin ====================
|
||||||
|
|
||||||
|
const doorCheckinSchema = z.object({
|
||||||
|
// Existing ticket to check in (and optionally settle), or…
|
||||||
|
ticketId: z.string().optional(),
|
||||||
|
// …a walk-in to create. Only a first name is ever required.
|
||||||
|
attendee: z.object({
|
||||||
|
firstName: z.string().trim().min(1).max(255),
|
||||||
|
lastName: z.string().trim().max(255).optional().or(z.literal('')),
|
||||||
|
phone: z.string().trim().max(50).optional().or(z.literal('')),
|
||||||
|
email: z.string().trim().email().optional().or(z.literal('')),
|
||||||
|
ruc: z.string().trim().max(15).optional().or(z.literal('')),
|
||||||
|
}).optional(),
|
||||||
|
payment: z.object({
|
||||||
|
method: z.enum(DOOR_PAYMENT_METHODS),
|
||||||
|
// How many tickets' worth is being paid (someone paying for their group).
|
||||||
|
// The server prices it: walk-in price for walk-ins, ticket price otherwise.
|
||||||
|
quantity: z.number().int().min(1).max(MAX_DOOR_QUANTITY).optional(),
|
||||||
|
// A typed amount is ignored unless amountOverride is set, which only
|
||||||
|
// admin/organizer may do.
|
||||||
|
amount: z.number().min(0).optional(),
|
||||||
|
amountOverride: z.boolean().optional(),
|
||||||
|
}).refine((p) => !p.amountOverride || typeof p.amount === 'number', {
|
||||||
|
message: 'amount is required when amountOverride is set',
|
||||||
|
path: ['amount'],
|
||||||
|
}).optional(),
|
||||||
|
// How the attendee reached this action, for the session feed.
|
||||||
|
entryMethod: z.enum(['scan', 'search', 'walkin']).optional(),
|
||||||
|
idempotencyKey: z.string().min(8).max(128),
|
||||||
|
}).refine((d) => !!d.ticketId || !!d.attendee, {
|
||||||
|
message: 'Either ticketId or attendee is required',
|
||||||
|
path: ['ticketId'],
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Undo instructions recorded alongside each processed idempotency key. */
|
||||||
|
type UndoState =
|
||||||
|
| {
|
||||||
|
kind: 'created';
|
||||||
|
ticketId: string;
|
||||||
|
paymentId: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
kind: 'existing';
|
||||||
|
ticketId: string;
|
||||||
|
prevTicket: { status: string; checkinAt: string | null; checkedInByAdminId: string | null; paymentStatus: string; isGuest: boolean };
|
||||||
|
createdPaymentId?: string;
|
||||||
|
prevPayment?: {
|
||||||
|
id: string; provider: string; amount: number; status: string; reference: string | null;
|
||||||
|
paidAt: string | null; paidByAdminId: string | null; source: string; method: string | null;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A replay of a key we already processed returns the original response verbatim. */
|
||||||
|
async function findProcessedKey(key: string) {
|
||||||
|
return dbGet<any>(
|
||||||
|
(db as any).select().from(idempotencyKeys).where(eq((idempotencyKeys as any).key, key))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
doorRouter.post(
|
||||||
|
'/:eventId/door-checkin',
|
||||||
|
requireEventPermission('check_in', { globalRoles: STAFF_ROLES, eventId: eventFromParam('eventId') }),
|
||||||
|
zValidator('json', doorCheckinSchema),
|
||||||
|
async (c) => {
|
||||||
|
const eventId = c.req.param('eventId');
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const adminUser = (c as any).get('user');
|
||||||
|
|
||||||
|
const existingKey = await findProcessedKey(data.idempotencyKey);
|
||||||
|
if (existingKey) {
|
||||||
|
return c.json({ ...JSON.parse(existingKey.result), replayed: true, undone: !!existingKey.undoneAt });
|
||||||
|
}
|
||||||
|
|
||||||
|
const amountOverride = !!data.payment?.amountOverride;
|
||||||
|
if (amountOverride && !(AMOUNT_OVERRIDE_ROLES as readonly string[]).includes(adminUser?.role)) {
|
||||||
|
return c.json({ error: 'Only an admin can override the door amount', code: 'OVERRIDE_FORBIDDEN' }, 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
const event = await loadEvent(eventId);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
|
||||||
|
const method = data.payment?.method as DoorPaymentMethod | undefined;
|
||||||
|
if (method && !(await loadDoorMethods(event.id)).includes(method)) {
|
||||||
|
return c.json({ error: `${DOOR_TENDERS[method].label} is not enabled for this event`, code: 'METHOD_DISABLED' }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = getNow();
|
||||||
|
const nowIso = new Date().toISOString();
|
||||||
|
const quantity = data.payment?.quantity ?? 1;
|
||||||
|
// Walk-ins pay the walk-in price (falling back to the ticket price); an
|
||||||
|
// existing unpaid ticket settles at the current ticket price (its pending
|
||||||
|
// payment is repriced whenever the event price changes).
|
||||||
|
const unitPrice = data.ticketId ? event.price : resolveWalkInPrice(event).unitPrice;
|
||||||
|
const computedAmount = unitPrice * quantity;
|
||||||
|
const requestedAmount = amountOverride ? data.payment!.amount! : computedAmount;
|
||||||
|
|
||||||
|
const ops: TxOp[] = [];
|
||||||
|
let undoState: UndoState;
|
||||||
|
let action: 'checkin' | 'walkin';
|
||||||
|
let ticketRow: any;
|
||||||
|
let paymentSummary: {
|
||||||
|
id: string; method: DoorPaymentMethod; amount: number; currency: string; amountOverridden: boolean;
|
||||||
|
} | null = null;
|
||||||
|
let emailTicketId: string | null = null;
|
||||||
|
|
||||||
|
if (data.ticketId) {
|
||||||
|
// ---- Existing ticket: settle (optionally) and check in ----
|
||||||
|
const ticket = await dbGet<any>(
|
||||||
|
(db as any).select().from(tickets).where(eq((tickets as any).id, data.ticketId))
|
||||||
|
);
|
||||||
|
if (!ticket) return c.json({ error: 'Ticket not found' }, 404);
|
||||||
|
if (ticket.eventId !== eventId) {
|
||||||
|
return c.json({ error: 'Ticket belongs to a different event', code: 'WRONG_EVENT' }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
action = 'checkin';
|
||||||
|
const prevTicket = {
|
||||||
|
status: ticket.status,
|
||||||
|
checkinAt: iso(ticket.checkinAt),
|
||||||
|
checkedInByAdminId: ticket.checkedInByAdminId || null,
|
||||||
|
paymentStatus: ticket.paymentStatus,
|
||||||
|
isGuest: !!ticket.isGuest,
|
||||||
|
};
|
||||||
|
const undo: UndoState = { kind: 'existing', ticketId: ticket.id, prevTicket };
|
||||||
|
|
||||||
|
const ticketUpdate: Record<string, any> = {};
|
||||||
|
|
||||||
|
if (method) {
|
||||||
|
const amount = amountForMethod(method, requestedAmount);
|
||||||
|
const tender = DOOR_TENDERS[method];
|
||||||
|
ticketUpdate.paymentStatus = paymentStatusForMethod(method);
|
||||||
|
if (method === 'guest') ticketUpdate.isGuest = toDbBool(true);
|
||||||
|
|
||||||
|
const existingPayment = await dbGet<any>(
|
||||||
|
(db as any).select().from(payments).where(eq((payments as any).ticketId, ticket.id))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (existingPayment) {
|
||||||
|
undo.prevPayment = {
|
||||||
|
id: existingPayment.id,
|
||||||
|
provider: existingPayment.provider,
|
||||||
|
amount: num(existingPayment.amount),
|
||||||
|
status: existingPayment.status,
|
||||||
|
reference: existingPayment.reference || null,
|
||||||
|
paidAt: iso(existingPayment.paidAt),
|
||||||
|
paidByAdminId: existingPayment.paidByAdminId || null,
|
||||||
|
source: existingPayment.source || 'presale',
|
||||||
|
method: existingPayment.method || null,
|
||||||
|
};
|
||||||
|
ops.push(updateOp(payments, {
|
||||||
|
provider: tender.provider,
|
||||||
|
amount,
|
||||||
|
currency: event.currency,
|
||||||
|
status: 'paid',
|
||||||
|
reference: doorReference(method),
|
||||||
|
paidAt: now,
|
||||||
|
paidByAdminId: adminUser?.id || null,
|
||||||
|
source: 'door',
|
||||||
|
method,
|
||||||
|
updatedAt: now,
|
||||||
|
}, eq((payments as any).id, existingPayment.id)));
|
||||||
|
paymentSummary = { id: existingPayment.id, method, amount, currency: event.currency, amountOverridden: amountOverride && !tender.isComp };
|
||||||
|
} else {
|
||||||
|
const paymentId = generateId();
|
||||||
|
undo.createdPaymentId = paymentId;
|
||||||
|
ops.push(insertOp(payments, {
|
||||||
|
id: paymentId,
|
||||||
|
ticketId: ticket.id,
|
||||||
|
provider: tender.provider,
|
||||||
|
amount,
|
||||||
|
currency: event.currency,
|
||||||
|
status: 'paid',
|
||||||
|
reference: doorReference(method),
|
||||||
|
paidAt: now,
|
||||||
|
paidByAdminId: adminUser?.id || null,
|
||||||
|
source: 'door',
|
||||||
|
method,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
}));
|
||||||
|
paymentSummary = { id: paymentId, method, amount, currency: event.currency, amountOverridden: amountOverride && !tender.isComp };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check in. An already-checked-in ticket keeps its original timestamp so
|
||||||
|
// staff can still tell the person when they actually entered.
|
||||||
|
if (ticket.status !== 'checked_in') {
|
||||||
|
ticketUpdate.status = 'checked_in';
|
||||||
|
ticketUpdate.checkinAt = now;
|
||||||
|
ticketUpdate.checkedInByAdminId = adminUser?.id || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(ticketUpdate).length > 0) {
|
||||||
|
ops.push(updateOp(tickets, ticketUpdate, eq((tickets as any).id, ticket.id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
undoState = undo;
|
||||||
|
ticketRow = { ...ticket, ...ticketUpdate, checkinAt: ticketUpdate.checkinAt ?? ticket.checkinAt };
|
||||||
|
} else {
|
||||||
|
// ---- Walk-in: born confirmed, settled and checked in, in one write ----
|
||||||
|
const attendee = data.attendee!;
|
||||||
|
action = 'walkin';
|
||||||
|
const tenderMethod: DoorPaymentMethod = method || 'cash';
|
||||||
|
const tender = DOOR_TENDERS[tenderMethod];
|
||||||
|
const amount = amountForMethod(tenderMethod, requestedAmount);
|
||||||
|
const hasEmail = !!(attendee.email && attendee.email.trim());
|
||||||
|
const firstNameValue = attendee.firstName.trim();
|
||||||
|
const lastNameValue = attendee.lastName?.trim() || null;
|
||||||
|
const displayName = lastNameValue ? `${firstNameValue} ${lastNameValue}` : firstNameValue;
|
||||||
|
|
||||||
|
// No email is the fast path; a placeholder keeps the users.email unique
|
||||||
|
// constraint satisfied without ever mailing anyone.
|
||||||
|
// Normalized: Better Auth lowercases every lookup it makes, and the
|
||||||
|
// users.email unique index is case-sensitive, so a mixed-case address
|
||||||
|
// written here would be invisible to sign-in and Google linking.
|
||||||
|
const accountEmail = normalizeEmail(
|
||||||
|
hasEmail
|
||||||
|
? attendee.email!
|
||||||
|
: `${tenderMethod === 'guest' ? 'guest' : 'door'}-${generateId()}@doorentry.local`
|
||||||
|
);
|
||||||
|
|
||||||
|
let user = hasEmail
|
||||||
|
? await dbGet<any>((db as any).select().from(users).where(eq((users as any).email, accountEmail)))
|
||||||
|
: null;
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
const userId = generateId();
|
||||||
|
user = { id: userId, email: accountEmail };
|
||||||
|
ops.push(insertOp(users, {
|
||||||
|
id: userId,
|
||||||
|
email: accountEmail,
|
||||||
|
password: null,
|
||||||
|
name: displayName,
|
||||||
|
phone: attendee.phone?.trim() || null,
|
||||||
|
role: 'user',
|
||||||
|
languagePreference: null,
|
||||||
|
isClaimed: toDbBool(false),
|
||||||
|
accountStatus: 'unclaimed',
|
||||||
|
emailVerified: false,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
const ticketId = generateId();
|
||||||
|
const paymentId = generateId();
|
||||||
|
const newTicket = {
|
||||||
|
id: ticketId,
|
||||||
|
bookingId: null,
|
||||||
|
userId: user.id,
|
||||||
|
eventId,
|
||||||
|
attendeeFirstName: firstNameValue,
|
||||||
|
attendeeLastName: lastNameValue,
|
||||||
|
attendeeEmail: hasEmail ? attendee.email!.trim() : null,
|
||||||
|
attendeePhone: attendee.phone?.trim() || null,
|
||||||
|
attendeeRuc: attendee.ruc?.trim() || null,
|
||||||
|
preferredLanguage: null,
|
||||||
|
status: 'checked_in',
|
||||||
|
paymentStatus: paymentStatusForMethod(tenderMethod),
|
||||||
|
isGuest: toDbBool(tenderMethod === 'guest'),
|
||||||
|
qrCode: generateTicketCode(),
|
||||||
|
checkinAt: now,
|
||||||
|
checkedInByAdminId: adminUser?.id || null,
|
||||||
|
adminNote: null,
|
||||||
|
bookingSource: 'walk_in',
|
||||||
|
createdAt: now,
|
||||||
|
};
|
||||||
|
ops.push(insertOp(tickets, newTicket));
|
||||||
|
ops.push(insertOp(payments, {
|
||||||
|
id: paymentId,
|
||||||
|
ticketId,
|
||||||
|
provider: tender.provider,
|
||||||
|
amount,
|
||||||
|
currency: event.currency,
|
||||||
|
status: 'paid',
|
||||||
|
reference: doorReference(tenderMethod),
|
||||||
|
paidAt: now,
|
||||||
|
paidByAdminId: adminUser?.id || null,
|
||||||
|
source: 'door',
|
||||||
|
method: tenderMethod,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
}));
|
||||||
|
|
||||||
|
paymentSummary = { id: paymentId, method: tenderMethod, amount, currency: event.currency, amountOverridden: amountOverride && !tender.isComp };
|
||||||
|
undoState = { kind: 'created', ticketId, paymentId };
|
||||||
|
ticketRow = newTicket;
|
||||||
|
// Only mail people who actually gave an address; no QR for the rest.
|
||||||
|
if (hasEmail) emailTicketId = ticketId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Written in the same transaction as the payment, so the log can never
|
||||||
|
// disagree with what was recorded.
|
||||||
|
if (paymentSummary?.amountOverridden) {
|
||||||
|
ops.push(insertOp(auditLogs, {
|
||||||
|
id: generateId(),
|
||||||
|
userId: adminUser?.id || null,
|
||||||
|
action: 'door_amount_override',
|
||||||
|
target: 'payment',
|
||||||
|
targetId: paymentSummary.id,
|
||||||
|
details: JSON.stringify({
|
||||||
|
eventId,
|
||||||
|
ticketId: ticketRow.id,
|
||||||
|
method: paymentSummary.method,
|
||||||
|
quantity,
|
||||||
|
computedAmount,
|
||||||
|
chargedAmount: paymentSummary.amount,
|
||||||
|
currency: event.currency,
|
||||||
|
}),
|
||||||
|
timestamp: now,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Staff at the door is the authority: a full event is a warning, never a block.
|
||||||
|
const held = await seatsHeld(eventId);
|
||||||
|
const atCapacity = event.capacity > 0 && held >= event.capacity;
|
||||||
|
|
||||||
|
const adminNames = await loadAdminNames([ticketRow.checkedInByAdminId]);
|
||||||
|
const responseBody = {
|
||||||
|
ok: true,
|
||||||
|
action,
|
||||||
|
attendee: toDoorAttendee(ticketRow, {
|
||||||
|
price: event.price,
|
||||||
|
groupBookingIds: new Set(ticketRow.bookingId ? [ticketRow.bookingId] : []),
|
||||||
|
adminNames,
|
||||||
|
doorMethod: paymentSummary?.method || null,
|
||||||
|
}),
|
||||||
|
payment: paymentSummary,
|
||||||
|
warnings: atCapacity ? ['at_capacity'] : [],
|
||||||
|
idempotencyKey: data.idempotencyKey,
|
||||||
|
processedAt: nowIso,
|
||||||
|
};
|
||||||
|
|
||||||
|
// The key row goes in with the writes, so two concurrent replays of the same
|
||||||
|
// key cannot both commit — the loser hits the primary-key conflict below.
|
||||||
|
ops.unshift(insertOp(idempotencyKeys, {
|
||||||
|
key: data.idempotencyKey,
|
||||||
|
scope: IDEMPOTENCY_SCOPE,
|
||||||
|
result: JSON.stringify(responseBody),
|
||||||
|
undoState: JSON.stringify(undoState),
|
||||||
|
undoneAt: null,
|
||||||
|
createdAt: now,
|
||||||
|
}));
|
||||||
|
|
||||||
|
try {
|
||||||
|
await runOps(ops);
|
||||||
|
} catch (err: any) {
|
||||||
|
const replay = await findProcessedKey(data.idempotencyKey);
|
||||||
|
if (replay) {
|
||||||
|
return c.json({ ...JSON.parse(replay.result), replayed: true, undone: !!replay.undoneAt });
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (paymentSummary?.amountOverridden) {
|
||||||
|
console.info(
|
||||||
|
`[Door] Amount override by ${adminUser?.id} (${adminUser?.role}) on event ${eventId}: ` +
|
||||||
|
`${paymentSummary.amount} ${event.currency} instead of ${computedAmount} (${paymentSummary.method})`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (emailTicketId) {
|
||||||
|
emailService.sendBookingConfirmation(emailTicketId).catch((err) => {
|
||||||
|
console.error('[Email] Failed to send door walk-in confirmation:', err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.json(responseBody, 201);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// ==================== POST /:eventId/door-checkin/undo ====================
|
||||||
|
// Reverses exactly what the keyed action did — nothing more. This is what makes
|
||||||
|
// the door screen safe to run without a single confirm dialog.
|
||||||
|
|
||||||
|
doorRouter.post(
|
||||||
|
'/:eventId/door-checkin/undo',
|
||||||
|
requireEventPermission('check_in', { globalRoles: STAFF_ROLES, eventId: eventFromParam('eventId') }),
|
||||||
|
zValidator('json', z.object({ idempotencyKey: z.string().min(8).max(128) })),
|
||||||
|
async (c) => {
|
||||||
|
const { idempotencyKey } = c.req.valid('json');
|
||||||
|
|
||||||
|
const record = await findProcessedKey(idempotencyKey);
|
||||||
|
if (!record) return c.json({ error: 'Nothing to undo for this action' }, 404);
|
||||||
|
if (record.undoneAt) return c.json({ ok: true, alreadyUndone: true });
|
||||||
|
|
||||||
|
const undo = JSON.parse(record.undoState || 'null') as UndoState | null;
|
||||||
|
if (!undo) return c.json({ error: 'This action cannot be undone' }, 400);
|
||||||
|
|
||||||
|
const now = getNow();
|
||||||
|
const ops: TxOp[] = [];
|
||||||
|
|
||||||
|
if (undo.kind === 'created') {
|
||||||
|
// Walk-ins created here are cancelled, not deleted: the row stays as an
|
||||||
|
// audit trail and can be reactivated from the same screen.
|
||||||
|
ops.push(updateOp(tickets, {
|
||||||
|
status: 'cancelled',
|
||||||
|
checkinAt: null,
|
||||||
|
checkedInByAdminId: null,
|
||||||
|
}, eq((tickets as any).id, undo.ticketId)));
|
||||||
|
ops.push(updateOp(payments, {
|
||||||
|
status: 'cancelled',
|
||||||
|
paidAt: null,
|
||||||
|
updatedAt: now,
|
||||||
|
}, eq((payments as any).id, undo.paymentId)));
|
||||||
|
} else {
|
||||||
|
ops.push(updateOp(tickets, {
|
||||||
|
status: undo.prevTicket.status,
|
||||||
|
checkinAt: undo.prevTicket.checkinAt ? toDbDate(undo.prevTicket.checkinAt) : null,
|
||||||
|
checkedInByAdminId: undo.prevTicket.checkedInByAdminId,
|
||||||
|
paymentStatus: undo.prevTicket.paymentStatus,
|
||||||
|
isGuest: toDbBool(undo.prevTicket.isGuest),
|
||||||
|
}, eq((tickets as any).id, undo.ticketId)));
|
||||||
|
|
||||||
|
if (undo.createdPaymentId) {
|
||||||
|
ops.push(deleteOp(payments, eq((payments as any).id, undo.createdPaymentId)));
|
||||||
|
} else if (undo.prevPayment) {
|
||||||
|
const prev = undo.prevPayment;
|
||||||
|
ops.push(updateOp(payments, {
|
||||||
|
provider: prev.provider,
|
||||||
|
amount: prev.amount,
|
||||||
|
status: prev.status,
|
||||||
|
reference: prev.reference,
|
||||||
|
paidAt: prev.paidAt ? toDbDate(prev.paidAt) : null,
|
||||||
|
paidByAdminId: prev.paidByAdminId,
|
||||||
|
source: prev.source,
|
||||||
|
method: prev.method,
|
||||||
|
updatedAt: now,
|
||||||
|
}, eq((payments as any).id, prev.id)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ops.push(updateOp(idempotencyKeys, { undoneAt: now }, eq((idempotencyKeys as any).key, idempotencyKey)));
|
||||||
|
|
||||||
|
await runOps(ops);
|
||||||
|
|
||||||
|
return c.json({ ok: true, ticketId: undo.ticketId, reverted: undo.kind });
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// ==================== GET /:eventId/door-summary ====================
|
||||||
|
// End-of-night reconciliation: what was taken at the door, by tender, plus the
|
||||||
|
// pre-sale/door split the event dashboard shows.
|
||||||
|
|
||||||
|
doorRouter.get('/:eventId/door-summary', requireEventPermission('view_payments', { globalRoles: REVENUE_ROLES, eventId: eventFromParam('eventId') }), async (c) => {
|
||||||
|
const eventId = c.req.param('eventId');
|
||||||
|
|
||||||
|
const event = await loadEvent(eventId);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
|
||||||
|
// Door payments settled for this event, with the attendee attached so the
|
||||||
|
// session feed can show who each line belongs to.
|
||||||
|
const rows = await dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({
|
||||||
|
paymentId: (payments as any).id,
|
||||||
|
ticketId: (tickets as any).id,
|
||||||
|
method: (payments as any).method,
|
||||||
|
amount: (payments as any).amount,
|
||||||
|
paidAt: (payments as any).paidAt,
|
||||||
|
firstName: (tickets as any).attendeeFirstName,
|
||||||
|
lastName: (tickets as any).attendeeLastName,
|
||||||
|
ticketStatus: (tickets as any).status,
|
||||||
|
})
|
||||||
|
.from(payments)
|
||||||
|
.innerJoin(tickets, eq((payments as any).ticketId, (tickets as any).id))
|
||||||
|
.where(and(
|
||||||
|
eq((tickets as any).eventId, eventId),
|
||||||
|
eq((payments as any).source, 'door'),
|
||||||
|
eq((payments as any).status, 'paid')
|
||||||
|
))
|
||||||
|
);
|
||||||
|
|
||||||
|
const byMethod: Record<string, { count: number; total: number }> = {};
|
||||||
|
for (const m of DOOR_PAYMENT_METHODS) byMethod[m] = { count: 0, total: 0 };
|
||||||
|
|
||||||
|
let doorTotal = 0;
|
||||||
|
for (const r of rows) {
|
||||||
|
const key = (r.method && byMethod[r.method]) ? r.method : 'cash';
|
||||||
|
const amount = num(r.amount);
|
||||||
|
byMethod[key].count += 1;
|
||||||
|
byMethod[key].total += amount;
|
||||||
|
doorTotal += amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pre-sale revenue: settled tickets that weren't taken at the door, at the
|
||||||
|
// amount actually paid — never the current event price, which an admin can
|
||||||
|
// change after tickets have been sold.
|
||||||
|
const doorTicketIds = new Set(rows.map((r: any) => r.ticketId));
|
||||||
|
const settled = await dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({ id: (tickets as any).id, amount: (payments as any).amount })
|
||||||
|
.from(tickets)
|
||||||
|
.leftJoin(payments, and(
|
||||||
|
eq((payments as any).ticketId, (tickets as any).id),
|
||||||
|
eq((payments as any).status, 'paid')
|
||||||
|
))
|
||||||
|
.where(and(
|
||||||
|
eq((tickets as any).eventId, eventId),
|
||||||
|
eq((tickets as any).paymentStatus, 'paid'),
|
||||||
|
sql`${(tickets as any).status} IN ('confirmed', 'checked_in')`
|
||||||
|
))
|
||||||
|
);
|
||||||
|
const presaleIds = new Set<string>();
|
||||||
|
let presaleTotal = 0;
|
||||||
|
for (const t of settled) {
|
||||||
|
if (doorTicketIds.has(t.id)) continue;
|
||||||
|
presaleIds.add(t.id);
|
||||||
|
presaleTotal += num(t.amount);
|
||||||
|
}
|
||||||
|
const presaleCount = presaleIds.size;
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
eventId,
|
||||||
|
currency: event.currency,
|
||||||
|
price: event.price,
|
||||||
|
door: {
|
||||||
|
count: rows.length,
|
||||||
|
total: doorTotal,
|
||||||
|
byMethod,
|
||||||
|
lines: rows
|
||||||
|
.map((r: any) => ({
|
||||||
|
paymentId: r.paymentId,
|
||||||
|
ticketId: r.ticketId,
|
||||||
|
name: `${r.firstName} ${r.lastName || ''}`.trim(),
|
||||||
|
method: r.method || 'cash',
|
||||||
|
amount: num(r.amount),
|
||||||
|
paidAt: iso(r.paidAt),
|
||||||
|
}))
|
||||||
|
.sort((a: any, b: any) => (b.paidAt || '').localeCompare(a.paidAt || '')),
|
||||||
|
},
|
||||||
|
presale: { count: presaleCount, total: presaleTotal },
|
||||||
|
total: presaleTotal + doorTotal,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
export default doorRouter;
|
||||||
@@ -4,6 +4,7 @@ import { z } from 'zod';
|
|||||||
import { db, dbGet, dbAll, emailTemplates, emailLogs, events, tickets } from '../db/index.js';
|
import { db, dbGet, dbAll, emailTemplates, emailLogs, events, tickets } from '../db/index.js';
|
||||||
import { eq, desc, and, or, sql } from 'drizzle-orm';
|
import { eq, desc, and, or, sql } from 'drizzle-orm';
|
||||||
import { requireAuth } from '../lib/auth.js';
|
import { requireAuth } from '../lib/auth.js';
|
||||||
|
import { requireEventPermission, eventFromParam, eventFromQuery } from '../lib/eventPermissions.js';
|
||||||
import { getNow, generateId } from '../lib/utils.js';
|
import { getNow, generateId } from '../lib/utils.js';
|
||||||
import emailService from '../lib/email.js';
|
import emailService from '../lib/email.js';
|
||||||
import { getTemplateVariables, defaultTemplates } from '../lib/emailTemplates.js';
|
import { getTemplateVariables, defaultTemplates } from '../lib/emailTemplates.js';
|
||||||
@@ -58,7 +59,7 @@ function safeParseVariables(raw: any): any[] {
|
|||||||
// ==================== Template Routes ====================
|
// ==================== Template Routes ====================
|
||||||
|
|
||||||
// Get all email templates
|
// Get all email templates
|
||||||
emailsRouter.get('/templates', requireAuth(['admin', 'organizer']), async (c) => {
|
emailsRouter.get('/templates', requireEventPermission('email_attendees', { globalRoles: ['admin', 'organizer'], eventId: eventFromQuery() }), async (c) => {
|
||||||
const templates = await dbAll<any>(
|
const templates = await dbAll<any>(
|
||||||
(db as any).select().from(emailTemplates).orderBy(desc((emailTemplates as any).createdAt))
|
(db as any).select().from(emailTemplates).orderBy(desc((emailTemplates as any).createdAt))
|
||||||
);
|
);
|
||||||
@@ -239,7 +240,7 @@ emailsRouter.get('/templates/:slug/variables', requireAuth(['admin', 'organizer'
|
|||||||
// ==================== Email Sending Routes ====================
|
// ==================== Email Sending Routes ====================
|
||||||
|
|
||||||
// Send email using template to event attendees (non-blocking, queued)
|
// Send email using template to event attendees (non-blocking, queued)
|
||||||
emailsRouter.post('/send/event/:eventId', requireAuth(['admin', 'organizer']), async (c) => {
|
emailsRouter.post('/send/event/:eventId', requireEventPermission('email_attendees', { globalRoles: ['admin', 'organizer'], eventId: eventFromParam('eventId') }), async (c) => {
|
||||||
const { eventId } = c.req.param();
|
const { eventId } = c.req.param();
|
||||||
const user = (c as any).get('user');
|
const user = (c as any).get('user');
|
||||||
const body = await c.req.json();
|
const body = await c.req.json();
|
||||||
@@ -286,7 +287,7 @@ emailsRouter.post('/send/custom', requireAuth(['admin', 'organizer']), zValidato
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Preview email (render template without sending)
|
// Preview email (render template without sending)
|
||||||
emailsRouter.post('/preview', requireAuth(['admin', 'organizer']), async (c) => {
|
emailsRouter.post('/preview', requireEventPermission('email_attendees', { globalRoles: ['admin', 'organizer'], eventId: eventFromQuery() }), async (c) => {
|
||||||
const body = await c.req.json();
|
const body = await c.req.json();
|
||||||
const { templateSlug, variables, locale } = body;
|
const { templateSlug, variables, locale } = body;
|
||||||
|
|
||||||
@@ -327,7 +328,7 @@ emailsRouter.post('/preview', requireAuth(['admin', 'organizer']), async (c) =>
|
|||||||
// ==================== Email Logs Routes ====================
|
// ==================== Email Logs Routes ====================
|
||||||
|
|
||||||
// Get email logs
|
// Get email logs
|
||||||
emailsRouter.get('/logs', requireAuth(['admin', 'organizer']), async (c) => {
|
emailsRouter.get('/logs', requireEventPermission('email_attendees', { globalRoles: ['admin', 'organizer'], eventId: eventFromQuery() }), async (c) => {
|
||||||
const eventId = c.req.query('eventId');
|
const eventId = c.req.query('eventId');
|
||||||
const status = c.req.query('status');
|
const status = c.req.query('status');
|
||||||
const search = c.req.query('search');
|
const search = c.req.query('search');
|
||||||
@@ -420,7 +421,7 @@ emailsRouter.post('/logs/:id/resend', requireAuth(['admin', 'organizer']), async
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Get email stats
|
// Get email stats
|
||||||
emailsRouter.get('/stats', requireAuth(['admin', 'organizer']), async (c) => {
|
emailsRouter.get('/stats', requireEventPermission('email_attendees', { globalRoles: ['admin', 'organizer'], eventId: eventFromQuery() }), async (c) => {
|
||||||
const eventId = c.req.query('eventId');
|
const eventId = c.req.query('eventId');
|
||||||
|
|
||||||
let baseCondition = eventId ? eq((emailLogs as any).eventId, eventId) : undefined;
|
let baseCondition = eventId ? eq((emailLogs as any).eventId, eventId) : undefined;
|
||||||
|
|||||||
@@ -0,0 +1,387 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||||
|
import { execFileSync } from 'child_process';
|
||||||
|
import { mkdtempSync } from 'fs';
|
||||||
|
import { tmpdir } from 'os';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
|
||||||
|
// Env must be pinned before the db singleton is imported (dotenv never overrides).
|
||||||
|
// Runs on a temp SQLite file by default. Set FINANCE_TEST_PG_URL to a Postgres
|
||||||
|
// URL to run the same suite in a throwaway schema (dropped afterwards).
|
||||||
|
const PG_URL = process.env.FINANCE_TEST_PG_URL;
|
||||||
|
const PG_SCHEMA = `fintest_${Date.now()}`;
|
||||||
|
if (PG_URL) {
|
||||||
|
process.env.DB_TYPE = 'postgres';
|
||||||
|
process.env.DATABASE_URL = `${PG_URL}${PG_URL.includes('?') ? '&' : '?'}options=-c%20search_path%3D${PG_SCHEMA}`;
|
||||||
|
} else {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'finance-test-'));
|
||||||
|
process.env.DB_TYPE = 'sqlite';
|
||||||
|
process.env.DATABASE_URL = join(dir, 'test.db');
|
||||||
|
}
|
||||||
|
process.env.FRONTEND_URL = 'http://localhost:3002';
|
||||||
|
process.env.BETTER_AUTH_SECRET = 'finance-test-secret-0123456789abcdef';
|
||||||
|
delete process.env.REDIS_URL;
|
||||||
|
|
||||||
|
type TestUser = { id: string; name: string; role: string; languagePreference?: string | null };
|
||||||
|
const ADMIN: TestUser = { id: randomUUID(), name: 'The Admin', role: 'admin' };
|
||||||
|
const ORGANIZER: TestUser = { id: randomUUID(), name: 'The Organizer', role: 'organizer' };
|
||||||
|
const COLLAB: TestUser = { id: randomUUID(), name: 'Pilates Studio', role: 'user' };
|
||||||
|
const COMANAGER: TestUser = { id: randomUUID(), name: 'Co Manager', role: 'user' };
|
||||||
|
const DOOR: TestUser = { id: randomUUID(), name: 'Door Helper', role: 'user' };
|
||||||
|
const STRANGER: TestUser = { id: randomUUID(), name: 'Stranger', role: 'user' };
|
||||||
|
|
||||||
|
// Session auth is Better Auth's concern and has its own suite; this keeps the
|
||||||
|
// role and membership checks real.
|
||||||
|
let currentUser: TestUser = ADMIN;
|
||||||
|
vi.mock('../lib/auth.js', () => ({
|
||||||
|
requireAuth: (roles?: string[]) => async (c: any, next: any) => {
|
||||||
|
if (roles && !roles.includes(currentUser.role)) return c.json({ error: 'Forbidden' }, 403);
|
||||||
|
c.set('user', currentUser);
|
||||||
|
await next();
|
||||||
|
},
|
||||||
|
getAuthUser: async () => currentUser,
|
||||||
|
}));
|
||||||
|
vi.mock('../lib/email.js', () => ({ default: {} }));
|
||||||
|
|
||||||
|
async function as<T>(user: TestUser, fn: () => Promise<T>): Promise<T> {
|
||||||
|
const previous = currentUser;
|
||||||
|
currentUser = user;
|
||||||
|
try {
|
||||||
|
return await fn();
|
||||||
|
} finally {
|
||||||
|
currentUser = previous;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let app: any;
|
||||||
|
let dbm: any;
|
||||||
|
|
||||||
|
const EVENT_ID = randomUUID();
|
||||||
|
const OTHER_EVENT_ID = randomUUID();
|
||||||
|
const SEED_USER_ID = randomUUID();
|
||||||
|
const PRICE = 100000;
|
||||||
|
|
||||||
|
async function call(method: string, path: string, body?: unknown) {
|
||||||
|
const res = await app.request(path, {
|
||||||
|
method,
|
||||||
|
headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
});
|
||||||
|
const type = res.headers.get('content-type') || '';
|
||||||
|
return { status: res.status, type, body: type.includes('json') ? await res.json() : Buffer.from(await res.arrayBuffer()) };
|
||||||
|
}
|
||||||
|
const get = (p: string) => call('GET', p);
|
||||||
|
const post = (p: string, b: unknown = {}) => call('POST', p, b);
|
||||||
|
const put = (p: string, b: unknown) => call('PUT', p, b);
|
||||||
|
|
||||||
|
// Seeded through drizzle so the same rows work on both engines.
|
||||||
|
async function seedTicket(label: string, eventId: string, opts: { status: string; paymentStatus: string; pay?: { amount: number; provider: string; source?: string; status?: string } }) {
|
||||||
|
const { db, tickets, payments } = dbm;
|
||||||
|
const now = dbm.getNow();
|
||||||
|
const id = randomUUID();
|
||||||
|
await db.insert(tickets).values({
|
||||||
|
id, userId: SEED_USER_ID, eventId, attendeeFirstName: `Guest ${label}`, attendeeLastName: 'Test',
|
||||||
|
attendeeEmail: `${label}@test.py`, attendeePhone: '+595 981 000 000', status: opts.status,
|
||||||
|
paymentStatus: opts.paymentStatus, isGuest: dbm.toDbBool(false), qrCode: `QR-${label}`, createdAt: now,
|
||||||
|
});
|
||||||
|
if (opts.pay) {
|
||||||
|
await db.insert(payments).values({
|
||||||
|
id: randomUUID(), ticketId: id, provider: opts.pay.provider, amount: opts.pay.amount, currency: 'PYG',
|
||||||
|
status: opts.pay.status || 'paid', source: opts.pay.source || 'presale', paidAt: now, createdAt: now, updatedAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
if (PG_URL) execFileSync('psql', [PG_URL, '-qc', `CREATE SCHEMA ${PG_SCHEMA}`], { stdio: 'pipe' });
|
||||||
|
execFileSync('npx', ['tsx', 'src/db/migrate.ts'], { env: { ...process.env }, stdio: 'pipe' });
|
||||||
|
|
||||||
|
return (async () => {
|
||||||
|
const { Hono } = await import('hono');
|
||||||
|
app = new Hono();
|
||||||
|
app.route('/api/events', (await import('./door.js')).default);
|
||||||
|
app.route('/api/events', (await import('./eventFinance.js')).default);
|
||||||
|
app.route('/api/events', (await import('./events.js')).default);
|
||||||
|
app.route('/api/finance', (await import('./finance.js')).default);
|
||||||
|
app.route('/api/dashboard', (await import('./dashboard.js')).default);
|
||||||
|
|
||||||
|
dbm = { ...(await import('../db/index.js')), ...(await import('../lib/utils.js')) };
|
||||||
|
const { db, users, events } = dbm;
|
||||||
|
const now = dbm.getNow();
|
||||||
|
for (const u of [ADMIN, ORGANIZER, COLLAB, COMANAGER, DOOR, STRANGER, { id: SEED_USER_ID, name: 'Seed', role: 'user' }]) {
|
||||||
|
await db.insert(users).values({
|
||||||
|
id: u.id, email: `${u.name.toLowerCase().replace(/ /g, '.')}@test.py`, name: u.name, role: u.role,
|
||||||
|
isClaimed: dbm.toDbBool(true), accountStatus: 'active', createdAt: now, updatedAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (const [id, title] of [[EVENT_ID, 'Morning Club: Pilates Edition'], [OTHER_EVENT_ID, 'Some Other Event']]) {
|
||||||
|
await db.insert(events).values({
|
||||||
|
id, title, description: 'desc', startDatetime: now, location: 'Studio Uno', price: PRICE, currency: 'PYG',
|
||||||
|
capacity: 40, status: 'published', externalBookingEnabled: dbm.toDbBool(false), createdAt: now, updatedAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 10 pre-sale TPago tickets (8 checked in), 2 cash walk-ins at the door, 1 refund.
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
await seedTicket(`t${i}`, EVENT_ID, { status: i < 8 ? 'checked_in' : 'confirmed', paymentStatus: 'paid', pay: { amount: PRICE, provider: 'tpago' } });
|
||||||
|
}
|
||||||
|
await seedTicket('door1', EVENT_ID, { status: 'checked_in', paymentStatus: 'paid', pay: { amount: 120000, provider: 'cash', source: 'door' } });
|
||||||
|
await seedTicket('door2', EVENT_ID, { status: 'checked_in', paymentStatus: 'paid', pay: { amount: 120000, provider: 'cash', source: 'door' } });
|
||||||
|
await seedTicket('refunded', EVENT_ID, { status: 'cancelled', paymentStatus: 'paid', pay: { amount: PRICE, provider: 'tpago', status: 'refunded' } });
|
||||||
|
await seedTicket('other1', OTHER_EVENT_ID, { status: 'confirmed', paymentStatus: 'paid', pay: { amount: PRICE, provider: 'tpago' } });
|
||||||
|
})();
|
||||||
|
}, 120_000);
|
||||||
|
|
||||||
|
afterAll(() => {
|
||||||
|
if (PG_URL) execFileSync('psql', [PG_URL, '-qc', `DROP SCHEMA ${PG_SCHEMA} CASCADE`], { stdio: 'pipe' });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('event finance access', () => {
|
||||||
|
it('lets admins in and keeps organizers out until they are granted access', async () => {
|
||||||
|
expect((await as(ADMIN, () => get(`/api/events/${EVENT_ID}/finance`))).status).toBe(200);
|
||||||
|
expect((await as(ORGANIZER, () => get(`/api/events/${EVENT_ID}/finance`))).status).toBe(403);
|
||||||
|
expect((await as(ORGANIZER, () => get(`/api/events/${EVENT_ID}/members`))).status).toBe(403);
|
||||||
|
const perms = await as(ORGANIZER, () => get(`/api/events/${EVENT_ID}/my-permissions`));
|
||||||
|
expect(perms.body.permissions).toContain('view_payments');
|
||||||
|
expect(perms.body.permissions).not.toContain('view_finance');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets an admin add team members, and writes the audit log', async () => {
|
||||||
|
const add = (userId: string, rolePreset: string, permissions?: Record<string, boolean>) =>
|
||||||
|
as(ADMIN, () => post(`/api/events/${EVENT_ID}/members`, { userId, rolePreset, permissions }));
|
||||||
|
expect((await add(COLLAB.id, 'collaborator')).status).toBe(201);
|
||||||
|
expect((await add(COMANAGER.id, 'co_manager')).status).toBe(201);
|
||||||
|
expect((await add(DOOR.id, 'staff')).status).toBe(201);
|
||||||
|
expect((await add(COLLAB.id, 'staff')).status).toBe(409);
|
||||||
|
|
||||||
|
const candidates = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/members/candidates?q=stran`));
|
||||||
|
expect(candidates.body.users.map((u: any) => u.id)).toEqual([STRANGER.id]);
|
||||||
|
|
||||||
|
const log = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/audit-log`));
|
||||||
|
expect(log.body.entries.filter((e: any) => e.entityType === 'member' && e.action === 'create')).toHaveLength(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives a collaborator only their events and permitted routes', async () => {
|
||||||
|
const mine = await as(COLLAB, () => get('/api/dashboard/my-events'));
|
||||||
|
expect(mine.status).toBe(200);
|
||||||
|
expect(mine.body.events.map((e: any) => e.event.id)).toEqual([EVENT_ID]);
|
||||||
|
expect(mine.body.events[0].permissions).toEqual(['view_overview', 'view_finance']);
|
||||||
|
|
||||||
|
expect((await as(COLLAB, () => get(`/api/events/${EVENT_ID}/finance`))).status).toBe(200);
|
||||||
|
// Other events' data
|
||||||
|
expect((await as(COLLAB, () => get(`/api/events/${OTHER_EVENT_ID}/finance`))).status).toBe(403);
|
||||||
|
expect((await as(COLLAB, () => get(`/api/events/${OTHER_EVENT_ID}/attendees`))).status).toBe(403);
|
||||||
|
// Routes on their own event that the preset does not grant
|
||||||
|
expect((await as(COLLAB, () => get(`/api/events/${EVENT_ID}/attendees`))).status).toBe(403);
|
||||||
|
expect((await as(COLLAB, () => get(`/api/events/${EVENT_ID}/door-attendees`))).status).toBe(403);
|
||||||
|
expect((await as(COLLAB, () => get(`/api/events/${EVENT_ID}/door-summary`))).status).toBe(403);
|
||||||
|
expect((await as(COLLAB, () => get(`/api/events/${EVENT_ID}/members`))).status).toBe(403);
|
||||||
|
expect((await as(COLLAB, () => get(`/api/events/${EVENT_ID}/audit-log`))).status).toBe(403);
|
||||||
|
expect((await as(COLLAB, () => post(`/api/events/${EVENT_ID}/expenses`, { description: 'x', unitAmount: 1 }))).status).toBe(403);
|
||||||
|
expect((await as(COLLAB, () => put(`/api/events/${EVENT_ID}`, { title: 'Hacked' }))).status).toBe(403);
|
||||||
|
expect((await as(COLLAB, () => get('/api/finance/overview'))).status).toBe(403);
|
||||||
|
expect((await as(COLLAB, () => get('/api/finance/settings/expense-templates'))).status).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows staff members attendee names without contact details', async () => {
|
||||||
|
const res = await as(DOOR, () => get(`/api/events/${EVENT_ID}/attendees`));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.attendees.length).toBeGreaterThan(0);
|
||||||
|
expect(res.body.attendees.every((a: any) => a.attendeeEmail === null && a.attendeePhone === null)).toBe(true);
|
||||||
|
const door = await as(DOOR, () => get(`/api/events/${EVENT_ID}/door-attendees`));
|
||||||
|
expect(door.status).toBe(200);
|
||||||
|
expect(door.body.attendees.every((a: any) => a.email === null)).toBe(true);
|
||||||
|
// Admins still get everything
|
||||||
|
const full = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/attendees`));
|
||||||
|
expect(full.body.attendees.some((a: any) => a.attendeeEmail)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies per-member overrides in both directions', async () => {
|
||||||
|
const list = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/members`));
|
||||||
|
const door = list.body.members.find((m: any) => m.userId === DOOR.id);
|
||||||
|
await as(ADMIN, () => put(`/api/events/${EVENT_ID}/members/${door.id}`, { permissions: { view_attendees_pii: true, check_in: false } }));
|
||||||
|
expect((await as(DOOR, () => get(`/api/events/${EVENT_ID}/door-attendees`))).status).toBe(403);
|
||||||
|
const res = await as(DOOR, () => get(`/api/events/${EVENT_ID}/attendees`));
|
||||||
|
expect(res.body.attendees.some((a: any) => a.attendeeEmail)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Morning Club: Pilates Edition finance flow', () => {
|
||||||
|
let packId = '';
|
||||||
|
let partnerId = '';
|
||||||
|
|
||||||
|
it('builds a template pack in settings', async () => {
|
||||||
|
const cats = await as(ADMIN, () => get('/api/finance/settings/expense-categories'));
|
||||||
|
const venue = cats.body.categories.find((c: any) => c.nameEn === 'Venue');
|
||||||
|
const make = (body: any) => as(ADMIN, () => post('/api/finance/settings/expense-templates', body));
|
||||||
|
const studio = await make({ name: 'Studio minimum spend', categoryId: venue.id, calcType: 'minimum_spend', amount: 30000, minimumAmount: 500000 });
|
||||||
|
const mats = await make({ name: 'Mat rental', calcType: 'per_checked_in', amount: 5000 });
|
||||||
|
const instructor = await make({ name: 'Instructor', calcType: 'fixed', amount: 300000 });
|
||||||
|
const promo = await make({ name: 'Promo share', calcType: 'percent_of_revenue', percentBp: 500 });
|
||||||
|
expect([studio, mats, instructor, promo].map((r) => r.status)).toEqual([201, 201, 201, 201]);
|
||||||
|
|
||||||
|
const pack = await as(ADMIN, () => post('/api/finance/settings/expense-template-packs', {
|
||||||
|
name: 'Morning Club pack', templateIds: [studio.body.template.id, mats.body.template.id, instructor.body.template.id, promo.body.template.id],
|
||||||
|
}));
|
||||||
|
expect(pack.status).toBe(201);
|
||||||
|
packId = pack.body.pack.id;
|
||||||
|
expect(pack.body.pack.templateIds).toHaveLength(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies the pack to the event with amounts from current counts', async () => {
|
||||||
|
const res = await as(ADMIN, () => post(`/api/events/${EVENT_ID}/expenses/apply-template`, { packId }));
|
||||||
|
expect(res.status).toBe(201);
|
||||||
|
expect(res.body.expenses.map((e: any) => [e.description, e.computedAmount])).toEqual([
|
||||||
|
['Studio minimum spend', 500000], // 10 checked in x 30k = 300k < 500k minimum
|
||||||
|
['Mat rental', 50000],
|
||||||
|
['Instructor', 300000],
|
||||||
|
['Promo share', 62000], // 5% of 1,240,000 sales after the refund
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds a partner at a percent of profit and computes the split', async () => {
|
||||||
|
const res = await as(ADMIN, () => post(`/api/events/${EVENT_ID}/partners`, {
|
||||||
|
userId: COLLAB.id, roleLabel: 'Studio', shareType: 'percent_profit', percentBp: 3000, lossRule: 'proportional',
|
||||||
|
}));
|
||||||
|
expect(res.status).toBe(201);
|
||||||
|
partnerId = res.body.partner.id;
|
||||||
|
|
||||||
|
const fin = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/finance`));
|
||||||
|
const s = fin.body.summary;
|
||||||
|
expect(s.revenue.gross).toBe(1340000);
|
||||||
|
expect(s.revenue.refunds).toBe(100000);
|
||||||
|
expect(s.revenue.presale).toBe(1100000);
|
||||||
|
expect(s.revenue.door).toBe(240000);
|
||||||
|
expect(s.expenses.total).toBe(912000);
|
||||||
|
expect(s.profit).toBe(1240000 - 912000);
|
||||||
|
expect(s.split.partners[0].share).toBe(Math.round(328000 * 0.3));
|
||||||
|
expect(s.split.organization).toBe(328000 - 98400);
|
||||||
|
expect(s.breakEven.tickets).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the collaborator their own share but not the full split', async () => {
|
||||||
|
const fin = await as(COLLAB, () => get(`/api/events/${EVENT_ID}/finance`));
|
||||||
|
expect(fin.body.viewer.fullSplit).toBe(false);
|
||||||
|
expect(fin.body.summary.split.organization).toBeNull();
|
||||||
|
expect(fin.body.summary.split.partners.map((p: any) => p.partnerId)).toEqual([partnerId]);
|
||||||
|
expect(fin.body.summary.waterfall.some((w: any) => w.key === 'organization')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lets an organizer in once they are granted finance on this event', async () => {
|
||||||
|
await as(ADMIN, () => post(`/api/events/${EVENT_ID}/members`, { userId: ORGANIZER.id, rolePreset: 'collaborator', permissions: { view_full_split: true } }));
|
||||||
|
const fin = await as(ORGANIZER, () => get(`/api/events/${EVENT_ID}/finance`));
|
||||||
|
expect(fin.status).toBe(200);
|
||||||
|
expect(fin.body.viewer.fullSplit).toBe(true);
|
||||||
|
expect((await as(ORGANIZER, () => get(`/api/events/${OTHER_EVENT_ID}/finance`))).status).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('finalizes, freezes the numbers and blocks edits', async () => {
|
||||||
|
expect((await as(COLLAB, () => post(`/api/events/${EVENT_ID}/finance/finalize`))).status).toBe(403);
|
||||||
|
const res = await as(ADMIN, () => post(`/api/events/${EVENT_ID}/finance/finalize`));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
|
// A late walk-in no longer moves the finalized numbers
|
||||||
|
await seedTicket('late', EVENT_ID, { status: 'checked_in', paymentStatus: 'paid', pay: { amount: 120000, provider: 'cash', source: 'door' } });
|
||||||
|
const fin = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/finance`));
|
||||||
|
expect(fin.body.status).toBe('finalized');
|
||||||
|
expect(fin.body.live).toBe(false);
|
||||||
|
expect(fin.body.summary.revenue.gross).toBe(1340000);
|
||||||
|
|
||||||
|
const blocked = await as(ADMIN, () => post(`/api/events/${EVENT_ID}/expenses`, { description: 'Late cost', unitAmount: 1000 }));
|
||||||
|
expect(blocked.status).toBe(409);
|
||||||
|
expect(blocked.body.code).toBe('FINANCE_FINALIZED');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('exports the partner statement to the partner and not to others', async () => {
|
||||||
|
const pdf = await as(COLLAB, () => get(`/api/events/${EVENT_ID}/partners/${partnerId}/statement?locale=es`));
|
||||||
|
expect(pdf.status).toBe(200);
|
||||||
|
expect(pdf.type).toBe('application/pdf');
|
||||||
|
expect((pdf.body as Buffer).subarray(0, 4).toString()).toBe('%PDF');
|
||||||
|
|
||||||
|
const other = await as(ADMIN, () => post(`/api/events/${EVENT_ID}/partners`, { externalName: 'Someone', shareType: 'fixed', fixedAmount: 1 }));
|
||||||
|
expect(other.status).toBe(409); // finalized
|
||||||
|
expect((await as(DOOR, () => get(`/api/events/${EVENT_ID}/partners/${partnerId}/statement`))).status).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks the payout and moves the event to paid out', async () => {
|
||||||
|
const res = await as(ADMIN, () => post(`/api/events/${EVENT_ID}/partners/${partnerId}/mark-paid`, { paid: true, payoutMethod: 'transfer' }));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.status).toBe('paid_out');
|
||||||
|
expect(res.body.partner.payoutStatus).toBe('paid');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('only lets admins and co-managers unfinalize, and logs it', async () => {
|
||||||
|
expect((await as(ORGANIZER, () => post(`/api/events/${EVENT_ID}/finance/unfinalize`))).status).toBe(403);
|
||||||
|
expect((await as(COMANAGER, () => post(`/api/events/${EVENT_ID}/finance/unfinalize`))).status).toBe(200);
|
||||||
|
const fin = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/finance`));
|
||||||
|
expect(fin.body.status).toBe('open');
|
||||||
|
expect(fin.body.summary.revenue.gross).toBe(1460000); // the late walk-in now counts
|
||||||
|
const log = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/audit-log`));
|
||||||
|
const actions = log.body.entries.filter((e: any) => e.entityType === 'finance_state').map((e: any) => e.action);
|
||||||
|
expect(actions).toEqual(expect.arrayContaining(['finalize', 'paid_out', 'unfinalize']));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('limits edit_own_expenses_only members to their own rows', async () => {
|
||||||
|
const list = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/members`));
|
||||||
|
const collab = list.body.members.find((m: any) => m.userId === COLLAB.id);
|
||||||
|
await as(ADMIN, () => put(`/api/events/${EVENT_ID}/members/${collab.id}`, { permissions: { edit_own_expenses_only: true } }));
|
||||||
|
const own = await as(COLLAB, () => post(`/api/events/${EVENT_ID}/expenses`, { description: 'Flowers', unitAmount: 40000, status: 'paid', paidByPartnerId: partnerId }));
|
||||||
|
expect(own.status).toBe(201);
|
||||||
|
expect((await as(COLLAB, () => put(`/api/events/${EVENT_ID}/expenses/${own.body.expense.id}`, { unitAmount: 45000 }))).status).toBe(200);
|
||||||
|
const fin = await as(ADMIN, () => get(`/api/events/${EVENT_ID}/finance`));
|
||||||
|
const adminRow = fin.body.expenses.find((e: any) => e.createdBy === ADMIN.id);
|
||||||
|
expect((await as(COLLAB, () => put(`/api/events/${EVENT_ID}/expenses/${adminRow.id}`, { unitAmount: 1 }))).status).toBe(403);
|
||||||
|
// The reimbursement shows up on the partner line
|
||||||
|
expect(fin.body.summary.split.partners[0].reimbursement).toBe(45000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes the event in the cross-event overview', async () => {
|
||||||
|
await as(ADMIN, () => put(`/api/events/${EVENT_ID}`, { series: 'Morning Club' }));
|
||||||
|
const res = await as(ADMIN, () => get('/api/finance/overview?series=Morning%20Club'));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.events.map((e: any) => e.id)).toEqual([EVENT_ID]);
|
||||||
|
expect(res.body.bySeries[0].series).toBe('Morning Club');
|
||||||
|
expect(res.body.byPartner[0].name).toBe('Pilates Studio');
|
||||||
|
expect(res.body.filters.series).toEqual(['Morning Club']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cross-event overview: ready to close', () => {
|
||||||
|
const PAST_QUIET = 'evt-past-quiet';
|
||||||
|
const FUTURE = 'evt-future';
|
||||||
|
const PAST_DRAFT = 'evt-past-draft';
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const { db, events } = dbm;
|
||||||
|
const now = dbm.getNow();
|
||||||
|
const at = (iso: string) => dbm.toDbDate(iso);
|
||||||
|
for (const [id, title, start, status] of [
|
||||||
|
[PAST_QUIET, 'Quiet past event', '2026-01-10T20:00:00Z', 'published'],
|
||||||
|
[FUTURE, 'Future event', '2099-01-10T20:00:00Z', 'published'],
|
||||||
|
[PAST_DRAFT, 'Past draft', '2026-01-11T20:00:00Z', 'draft'],
|
||||||
|
] as const) {
|
||||||
|
await db.insert(events).values({
|
||||||
|
id, title, description: 'desc', startDatetime: at(start), location: 'Studio Uno', price: PRICE, currency: 'PYG',
|
||||||
|
capacity: 40, status, externalBookingEnabled: dbm.toDbBool(false), createdAt: now, updatedAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists past events with open books even with no money, and keeps them out of the totals', async () => {
|
||||||
|
const res = await as(ADMIN, () => get('/api/finance/overview'));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const ready = res.body.readyToClose.map((e: any) => e.id);
|
||||||
|
expect(ready).toContain(PAST_QUIET);
|
||||||
|
expect(ready).not.toContain(FUTURE);
|
||||||
|
expect(ready).not.toContain(PAST_DRAFT);
|
||||||
|
expect(res.body.events.map((e: any) => e.id)).not.toContain(PAST_QUIET);
|
||||||
|
// Longest-waiting first
|
||||||
|
const starts = res.body.readyToClose.map((e: any) => e.startDatetime);
|
||||||
|
expect([...starts].sort()).toEqual(starts);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('respects the venue filter', async () => {
|
||||||
|
const res = await as(ADMIN, () => get('/api/finance/overview?venue=Nowhere'));
|
||||||
|
expect(res.body.readyToClose).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,936 @@
|
|||||||
|
// Event finance, partners and team access, all scoped to one event and
|
||||||
|
// mounted under /api/events:
|
||||||
|
//
|
||||||
|
// GET /:id/my-permissions what the current user may do here
|
||||||
|
// GET /:id/finance P&L summary, chart data and the rows behind it
|
||||||
|
// POST /:id/finance/finalize | unfinalize freeze / reopen the numbers
|
||||||
|
// CRUD /:id/expenses (+ /apply-template) costs, manual or from templates / packs
|
||||||
|
// CRUD /:id/other-income sponsors, venue kickbacks, ...
|
||||||
|
// CRUD /:id/partners (+ /:pid/mark-paid, /:pid/statement PDF)
|
||||||
|
// CRUD /:id/members (+ /candidates) per-event team access
|
||||||
|
// GET /:id/audit-log
|
||||||
|
//
|
||||||
|
// Every route is guarded by requireEventPermission; only global admins pass on
|
||||||
|
// every event. Every write commits together with its finance_audit_log row.
|
||||||
|
|
||||||
|
import { Hono, type Context } from 'hono';
|
||||||
|
import { zValidator } from '@hono/zod-validator';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { and, desc, eq, inArray, notInArray, or, sql } from 'drizzle-orm';
|
||||||
|
import {
|
||||||
|
db, dbAll, dbGet, users, eventExpenses, eventOtherIncome, eventPartners, eventFinanceState, eventMembers,
|
||||||
|
expenseCategories, expenseTemplates, expenseTemplatePackItems, financeAuditLog,
|
||||||
|
} from '../db/index.js';
|
||||||
|
import { requireAuth, type AuthUser } from '../lib/auth.js';
|
||||||
|
import {
|
||||||
|
requireEventPermission, getEventAccess, getEffectivePermissions, canUnfinalize, resolveMemberPermissions,
|
||||||
|
parseOverrides, EVENT_PERMISSIONS, ROLE_PRESETS, type EventPermission,
|
||||||
|
} from '../lib/eventPermissions.js';
|
||||||
|
import { generateId, getNow, toDbBool, toDbDate } from '../lib/utils.js';
|
||||||
|
import { runOps, insertOp, updateOp, deleteOp, type TxOp } from '../lib/txOps.js';
|
||||||
|
import { financeAuditOp } from '../lib/finance/audit.js';
|
||||||
|
import {
|
||||||
|
getEventFinance, getEvent, getFinanceState, serializeExpense, serializeIncome, serializePartner, iso, pyg, bool,
|
||||||
|
loadPartners, type SerializedExpense,
|
||||||
|
} from '../lib/finance/load.js';
|
||||||
|
import { expenseAmount, isAutoCalc, CALC_TYPES, SHARE_TYPES, LOSS_RULES } from '../lib/finance/calculate.js';
|
||||||
|
import { generatePartnerStatementPDF } from '../lib/finance/statementPdf.js';
|
||||||
|
import { omitWalkInPrice } from '../lib/walkInPrice.js';
|
||||||
|
|
||||||
|
const financeRouter = new Hono();
|
||||||
|
|
||||||
|
const validationHook = (result: any, c: any) => {
|
||||||
|
if (!result.success) {
|
||||||
|
const errors = result.error.issues.map((i: any) => `${i.path.join('.')}: ${i.message}`).join(', ');
|
||||||
|
return c.json({ error: errors }, 400);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const MAX_PYG = 2_000_000_000;
|
||||||
|
const money = z.number().int().min(0).max(MAX_PYG);
|
||||||
|
const bp = z.number().int().min(0).max(10000);
|
||||||
|
// Receipts come from the media upload (/uploads/...) or an external link; never javascript: etc.
|
||||||
|
const receiptUrl = z.string().max(500).regex(/^(https?:\/\/|\/uploads\/)/, 'must be an http(s) or /uploads/ URL');
|
||||||
|
|
||||||
|
const currentUser = (c: Context) => (c as any).get('user') as AuthUser;
|
||||||
|
const can = (c: Context, key: EventPermission) => !!getEventAccess(c)?.permissions.has(key);
|
||||||
|
|
||||||
|
async function requireEvent(c: Context) {
|
||||||
|
const event = await getEvent(c.req.param('id')!);
|
||||||
|
return event || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 409 while the numbers are frozen. */
|
||||||
|
async function assertOpen(c: Context, eventId: string) {
|
||||||
|
const state = await getFinanceState(eventId);
|
||||||
|
if (state.status !== 'open') {
|
||||||
|
return c.json({ error: 'Finance is finalized for this event. Unfinalize it to make changes.', code: 'FINANCE_FINALIZED' }, 409);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Counts and sales the auto-calculated expenses follow right now. */
|
||||||
|
async function liveContext(eventId: string, event: any) {
|
||||||
|
const fin = await getEventFinance(eventId, event);
|
||||||
|
return {
|
||||||
|
ticketsSold: fin!.result.counts.ticketsSold,
|
||||||
|
checkedIn: fin!.result.counts.checkedIn,
|
||||||
|
sales: fin!.result.revenue.sales,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function partnerBelongsToEvent(partnerId: string, eventId: string) {
|
||||||
|
const row = await dbGet<any>(
|
||||||
|
(db as any).select({ id: (eventPartners as any).id }).from(eventPartners)
|
||||||
|
.where(and(eq((eventPartners as any).id, partnerId), eq((eventPartners as any).eventId, eventId)))
|
||||||
|
);
|
||||||
|
return !!row;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function categoryExists(categoryId: string) {
|
||||||
|
const row = await dbGet<any>((db as any).select({ id: (expenseCategories as any).id }).from(expenseCategories).where(eq((expenseCategories as any).id, categoryId)));
|
||||||
|
return !!row;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== Permissions for the UI ====================
|
||||||
|
|
||||||
|
financeRouter.get('/:id/my-permissions', requireAuth(), async (c) => {
|
||||||
|
const event = await requireEvent(c);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
const access = await getEffectivePermissions(currentUser(c), event.id);
|
||||||
|
return c.json({
|
||||||
|
eventId: event.id,
|
||||||
|
global: access.global,
|
||||||
|
role: access.role,
|
||||||
|
rolePreset: access.membership?.rolePreset ?? null,
|
||||||
|
permissions: EVENT_PERMISSIONS.filter((p) => access.permissions.has(p)),
|
||||||
|
canUnfinalize: canUnfinalize(access),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Summary ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collaborators without view_full_split see the event's P&L and their own
|
||||||
|
* partner line only: other partners and the organization's remainder are removed.
|
||||||
|
*/
|
||||||
|
function scopeToOwnShare<T extends NonNullable<Awaited<ReturnType<typeof getEventFinance>>>>(fin: T, userId: string) {
|
||||||
|
const own = new Set(fin.partners.filter((p) => p.userId === userId).map((p) => p.id));
|
||||||
|
return {
|
||||||
|
...fin,
|
||||||
|
partners: fin.partners.filter((p) => own.has(p.id)),
|
||||||
|
expenses: fin.expenses.map((e) => (e.paidByPartnerId && !own.has(e.paidByPartnerId) ? { ...e, paidByPartnerId: 'other' } : e)),
|
||||||
|
result: {
|
||||||
|
...fin.result,
|
||||||
|
split: {
|
||||||
|
distributable: null,
|
||||||
|
organization: null,
|
||||||
|
partners: fin.result.split.partners.filter((p) => own.has(p.partnerId)),
|
||||||
|
},
|
||||||
|
waterfall: fin.result.waterfall.filter((w) =>
|
||||||
|
w.key === 'organization' ? false : w.key.startsWith('partner:') ? own.has(w.key.slice(8)) : true),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
financeRouter.get('/:id/finance', requireEventPermission('view_finance'), async (c) => {
|
||||||
|
const event = await requireEvent(c);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
const fin = await getEventFinance(event.id, event);
|
||||||
|
if (!fin) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
|
||||||
|
const lines = new Map(fin.result.expenses.lines.map((l) => [l.id, l]));
|
||||||
|
const withAmounts = {
|
||||||
|
...fin,
|
||||||
|
expenses: fin.expenses.map((e) => ({
|
||||||
|
...e,
|
||||||
|
amount: lines.get(e.id)?.amount ?? e.computedAmount,
|
||||||
|
liveQuantity: lines.get(e.id)?.quantity ?? e.quantity,
|
||||||
|
auto: lines.get(e.id)?.auto ?? false,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
const fullSplit = can(c, 'view_full_split');
|
||||||
|
const scoped = fullSplit ? withAmounts : scopeToOwnShare(withAmounts, currentUser(c).id);
|
||||||
|
|
||||||
|
const categories = await dbAll<any>((db as any).select().from(expenseCategories));
|
||||||
|
const access = getEventAccess(c)!;
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
event: omitWalkInPrice({
|
||||||
|
id: event.id, title: event.title, titleEs: event.titleEs, startDatetime: iso(event.startDatetime),
|
||||||
|
endDatetime: event.endDatetime ? iso(event.endDatetime) : null,
|
||||||
|
location: event.location, series: event.series ?? null, price: pyg(event.price), currency: event.currency,
|
||||||
|
capacity: event.capacity,
|
||||||
|
}),
|
||||||
|
status: fin.state.status,
|
||||||
|
finalizedAt: fin.state.finalizedAt,
|
||||||
|
live: fin.live,
|
||||||
|
computedAt: fin.computedAt,
|
||||||
|
summary: scoped.result,
|
||||||
|
expenses: scoped.expenses,
|
||||||
|
otherIncome: scoped.otherIncome,
|
||||||
|
partners: scoped.partners,
|
||||||
|
categories: categories
|
||||||
|
.map((cat: any) => ({ id: cat.id, nameEn: cat.nameEn, nameEs: cat.nameEs, color: cat.color, sortOrder: pyg(cat.sortOrder), archived: bool(cat.archived) }))
|
||||||
|
.sort((a: any, b: any) => a.sortOrder - b.sortOrder),
|
||||||
|
viewer: {
|
||||||
|
fullSplit,
|
||||||
|
canEditExpenses: access.permissions.has('edit_expenses'),
|
||||||
|
canEditOwnExpenses: access.permissions.has('edit_own_expenses_only'),
|
||||||
|
canManageSplit: fullSplit && access.permissions.has('edit_expenses'),
|
||||||
|
canUnfinalize: canUnfinalize(access),
|
||||||
|
userId: currentUser(c).id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Expenses ====================
|
||||||
|
|
||||||
|
const expenseFields = {
|
||||||
|
description: z.string().trim().min(1).max(300),
|
||||||
|
categoryId: z.string().nullable().optional(),
|
||||||
|
calcType: z.enum(CALC_TYPES),
|
||||||
|
quantity: z.number().int().min(0).max(1_000_000),
|
||||||
|
unitAmount: money,
|
||||||
|
percentBp: bp,
|
||||||
|
minimumAmount: money,
|
||||||
|
computedAmount: money.optional(),
|
||||||
|
isLocked: z.boolean(),
|
||||||
|
status: z.enum(['planned', 'paid']),
|
||||||
|
paidByPartnerId: z.string().nullable().optional(),
|
||||||
|
receiptUrl: receiptUrl.nullable().optional(),
|
||||||
|
expenseDate: z.string().nullable().optional(),
|
||||||
|
};
|
||||||
|
const createExpenseSchema = z.object({
|
||||||
|
...expenseFields,
|
||||||
|
calcType: expenseFields.calcType.default('fixed'),
|
||||||
|
quantity: expenseFields.quantity.default(1),
|
||||||
|
unitAmount: money.default(0),
|
||||||
|
percentBp: bp.default(0),
|
||||||
|
minimumAmount: money.default(0),
|
||||||
|
isLocked: z.boolean().default(false),
|
||||||
|
status: expenseFields.status.default('planned'),
|
||||||
|
});
|
||||||
|
const updateExpenseSchema = z.object(expenseFields).partial();
|
||||||
|
|
||||||
|
const EXPENSE_EDITORS = ['edit_expenses', 'edit_own_expenses_only'] as const;
|
||||||
|
|
||||||
|
/** Members limited to their own expenses may only touch rows they created. */
|
||||||
|
function canEditRow(c: Context, row: any) {
|
||||||
|
return can(c, 'edit_expenses') || row.createdBy === currentUser(c).id;
|
||||||
|
}
|
||||||
|
|
||||||
|
type LiveContext = { ticketsSold: number; checkedIn: number; sales: number };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quantity and amount to store for a row. Unlocked rows follow the live counts.
|
||||||
|
* A locked row keeps its frozen amount; locking freezes the amount it shows at
|
||||||
|
* that moment unless one is typed in (`typed`).
|
||||||
|
*/
|
||||||
|
function storedAmount(row: any, ctx: LiveContext, opts: { typed?: number; wasLocked?: boolean; frozen?: { quantity: number; amount: number } } = {}) {
|
||||||
|
const live = expenseAmount({ ...row, isLocked: false }, ctx);
|
||||||
|
const quantity = isAutoCalc(row.calcType) ? live.quantity : row.quantity;
|
||||||
|
if (!row.isLocked) return { quantity, computedAmount: live.amount };
|
||||||
|
if (opts.typed !== undefined) return { quantity, computedAmount: opts.typed };
|
||||||
|
if (opts.wasLocked && opts.frozen) return { quantity: opts.frozen.quantity, computedAmount: opts.frozen.amount };
|
||||||
|
return { quantity, computedAmount: live.amount };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function validateExpenseRefs(c: Context, eventId: string, data: { categoryId?: string | null; paidByPartnerId?: string | null }) {
|
||||||
|
if (data.categoryId && !(await categoryExists(data.categoryId))) {
|
||||||
|
return c.json({ error: 'Unknown expense category' }, 400);
|
||||||
|
}
|
||||||
|
if (data.paidByPartnerId && !(await partnerBelongsToEvent(data.paidByPartnerId, eventId))) {
|
||||||
|
return c.json({ error: 'paidByPartnerId must be a partner of this event' }, 400);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
financeRouter.post('/:id/expenses', requireEventPermission(EXPENSE_EDITORS), zValidator('json', createExpenseSchema, validationHook), async (c) => {
|
||||||
|
const event = await requireEvent(c);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
const closed = await assertOpen(c, event.id);
|
||||||
|
if (closed) return closed;
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const bad = await validateExpenseRefs(c, event.id, data);
|
||||||
|
if (bad) return bad;
|
||||||
|
|
||||||
|
const user = currentUser(c);
|
||||||
|
const now = getNow();
|
||||||
|
const ctx = await liveContext(event.id, event);
|
||||||
|
const amounts = storedAmount(data, ctx, { typed: data.computedAmount });
|
||||||
|
const values = {
|
||||||
|
id: generateId(),
|
||||||
|
eventId: event.id,
|
||||||
|
categoryId: data.categoryId || null,
|
||||||
|
templateId: null,
|
||||||
|
description: data.description,
|
||||||
|
calcType: data.calcType,
|
||||||
|
quantity: amounts.quantity,
|
||||||
|
unitAmount: data.unitAmount,
|
||||||
|
percentBp: data.percentBp,
|
||||||
|
minimumAmount: data.minimumAmount,
|
||||||
|
computedAmount: amounts.computedAmount,
|
||||||
|
isLocked: toDbBool(data.isLocked),
|
||||||
|
status: data.status,
|
||||||
|
paidByPartnerId: data.paidByPartnerId || null,
|
||||||
|
receiptUrl: data.receiptUrl || null,
|
||||||
|
expenseDate: data.expenseDate ? toDbDate(data.expenseDate) : null,
|
||||||
|
createdBy: user.id,
|
||||||
|
updatedBy: user.id,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
await runOps([
|
||||||
|
insertOp(eventExpenses, values),
|
||||||
|
financeAuditOp({ eventId: event.id, actorUserId: user.id, entityType: 'expense', entityId: values.id, action: 'create', after: serializeExpense(values) }),
|
||||||
|
]);
|
||||||
|
return c.json({ expense: serializeExpense(values) }, 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.put('/:id/expenses/:expenseId', requireEventPermission(EXPENSE_EDITORS), zValidator('json', updateExpenseSchema, validationHook), async (c) => {
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const event = await getEvent(eventId);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
const closed = await assertOpen(c, eventId);
|
||||||
|
if (closed) return closed;
|
||||||
|
const existing = await dbGet<any>(
|
||||||
|
(db as any).select().from(eventExpenses)
|
||||||
|
.where(and(eq((eventExpenses as any).id, c.req.param('expenseId')), eq((eventExpenses as any).eventId, eventId)))
|
||||||
|
);
|
||||||
|
if (!existing) return c.json({ error: 'Expense not found' }, 404);
|
||||||
|
if (!canEditRow(c, existing)) return c.json({ error: 'You can only edit expenses you added', code: 'EVENT_PERMISSION' }, 403);
|
||||||
|
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const bad = await validateExpenseRefs(c, eventId, data);
|
||||||
|
if (bad) return bad;
|
||||||
|
|
||||||
|
const before = serializeExpense(existing);
|
||||||
|
const merged = { ...before, ...Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined)) } as any;
|
||||||
|
const ctx = await liveContext(eventId, event);
|
||||||
|
const amounts = storedAmount(merged, ctx, {
|
||||||
|
typed: data.computedAmount,
|
||||||
|
wasLocked: before.isLocked,
|
||||||
|
frozen: { quantity: before.quantity, amount: before.computedAmount },
|
||||||
|
});
|
||||||
|
const user = currentUser(c);
|
||||||
|
const updates: Record<string, any> = {
|
||||||
|
description: merged.description,
|
||||||
|
categoryId: merged.categoryId || null,
|
||||||
|
calcType: merged.calcType,
|
||||||
|
quantity: amounts.quantity,
|
||||||
|
unitAmount: merged.unitAmount,
|
||||||
|
percentBp: merged.percentBp,
|
||||||
|
minimumAmount: merged.minimumAmount,
|
||||||
|
computedAmount: amounts.computedAmount,
|
||||||
|
isLocked: toDbBool(!!merged.isLocked),
|
||||||
|
status: merged.status,
|
||||||
|
paidByPartnerId: merged.paidByPartnerId || null,
|
||||||
|
receiptUrl: merged.receiptUrl || null,
|
||||||
|
expenseDate: merged.expenseDate ? toDbDate(merged.expenseDate) : null,
|
||||||
|
updatedBy: user.id,
|
||||||
|
updatedAt: getNow(),
|
||||||
|
};
|
||||||
|
const after = serializeExpense({ ...existing, ...updates });
|
||||||
|
await runOps([
|
||||||
|
updateOp(eventExpenses, updates, eq((eventExpenses as any).id, existing.id)),
|
||||||
|
financeAuditOp({ eventId, actorUserId: user.id, entityType: 'expense', entityId: existing.id, action: 'update', before, after }),
|
||||||
|
]);
|
||||||
|
return c.json({ expense: after });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.delete('/:id/expenses/:expenseId', requireEventPermission(EXPENSE_EDITORS), async (c) => {
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const closed = await assertOpen(c, eventId);
|
||||||
|
if (closed) return closed;
|
||||||
|
const existing = await dbGet<any>(
|
||||||
|
(db as any).select().from(eventExpenses)
|
||||||
|
.where(and(eq((eventExpenses as any).id, c.req.param('expenseId')), eq((eventExpenses as any).eventId, eventId)))
|
||||||
|
);
|
||||||
|
if (!existing) return c.json({ error: 'Expense not found' }, 404);
|
||||||
|
if (!canEditRow(c, existing)) return c.json({ error: 'You can only delete expenses you added', code: 'EVENT_PERMISSION' }, 403);
|
||||||
|
const user = currentUser(c);
|
||||||
|
await runOps([
|
||||||
|
deleteOp(eventExpenses, eq((eventExpenses as any).id, existing.id)),
|
||||||
|
financeAuditOp({ eventId, actorUserId: user.id, entityType: 'expense', entityId: existing.id, action: 'delete', before: serializeExpense(existing) }),
|
||||||
|
]);
|
||||||
|
return c.json({ message: 'Expense deleted' });
|
||||||
|
});
|
||||||
|
|
||||||
|
const applyTemplateSchema = z.object({
|
||||||
|
templateId: z.string().optional(),
|
||||||
|
packId: z.string().optional(),
|
||||||
|
}).refine((d) => !!d.templateId !== !!d.packId, { message: 'Provide exactly one of templateId or packId' });
|
||||||
|
|
||||||
|
financeRouter.post('/:id/expenses/apply-template', requireEventPermission(EXPENSE_EDITORS), zValidator('json', applyTemplateSchema, validationHook), async (c) => {
|
||||||
|
const event = await requireEvent(c);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
const closed = await assertOpen(c, event.id);
|
||||||
|
if (closed) return closed;
|
||||||
|
const { templateId, packId } = c.req.valid('json');
|
||||||
|
|
||||||
|
let templateIds: string[];
|
||||||
|
if (packId) {
|
||||||
|
const items = await dbAll<any>((db as any).select().from(expenseTemplatePackItems).where(eq((expenseTemplatePackItems as any).packId, packId)));
|
||||||
|
if (items.length === 0) return c.json({ error: 'Template pack not found or empty' }, 404);
|
||||||
|
templateIds = items.sort((a: any, b: any) => pyg(a.sortOrder) - pyg(b.sortOrder)).map((i: any) => i.templateId);
|
||||||
|
} else {
|
||||||
|
templateIds = [templateId!];
|
||||||
|
}
|
||||||
|
const templates = await dbAll<any>((db as any).select().from(expenseTemplates).where(inArray((expenseTemplates as any).id, templateIds)));
|
||||||
|
const byId = new Map(templates.filter((t: any) => !bool(t.archived)).map((t: any) => [t.id, t]));
|
||||||
|
const ordered = templateIds.map((id) => byId.get(id)).filter(Boolean) as any[];
|
||||||
|
if (ordered.length === 0) return c.json({ error: 'Template not found' }, 404);
|
||||||
|
|
||||||
|
const user = currentUser(c);
|
||||||
|
const now = getNow();
|
||||||
|
const ctx = await liveContext(event.id, event);
|
||||||
|
const ops: TxOp[] = [];
|
||||||
|
const created: SerializedExpense[] = [];
|
||||||
|
for (const t of ordered) {
|
||||||
|
const row: any = {
|
||||||
|
id: generateId(),
|
||||||
|
eventId: event.id,
|
||||||
|
categoryId: t.categoryId || null,
|
||||||
|
templateId: t.id,
|
||||||
|
description: t.name,
|
||||||
|
calcType: t.calcType,
|
||||||
|
quantity: 1,
|
||||||
|
unitAmount: pyg(t.amount),
|
||||||
|
percentBp: pyg(t.percentBp),
|
||||||
|
minimumAmount: pyg(t.minimumAmount),
|
||||||
|
computedAmount: 0,
|
||||||
|
isLocked: toDbBool(false),
|
||||||
|
status: 'planned',
|
||||||
|
paidByPartnerId: null,
|
||||||
|
receiptUrl: null,
|
||||||
|
expenseDate: null,
|
||||||
|
createdBy: user.id,
|
||||||
|
updatedBy: user.id,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
const amounts = storedAmount(row, ctx);
|
||||||
|
row.quantity = amounts.quantity;
|
||||||
|
row.computedAmount = amounts.computedAmount;
|
||||||
|
ops.push(insertOp(eventExpenses, row));
|
||||||
|
const serialized = serializeExpense(row);
|
||||||
|
created.push(serialized);
|
||||||
|
ops.push(financeAuditOp({
|
||||||
|
eventId: event.id, actorUserId: user.id, entityType: 'expense', entityId: row.id,
|
||||||
|
action: packId ? 'apply_pack' : 'apply_template', after: { ...serialized, packId: packId ?? null },
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
await runOps(ops);
|
||||||
|
return c.json({ expenses: created }, 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Other income ====================
|
||||||
|
|
||||||
|
const incomeSchema = z.object({ description: z.string().trim().min(1).max(300), amount: money });
|
||||||
|
|
||||||
|
financeRouter.post('/:id/other-income', requireEventPermission('edit_expenses'), zValidator('json', incomeSchema, validationHook), async (c) => {
|
||||||
|
const event = await requireEvent(c);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
const closed = await assertOpen(c, event.id);
|
||||||
|
if (closed) return closed;
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const user = currentUser(c);
|
||||||
|
const now = getNow();
|
||||||
|
const values = { id: generateId(), eventId: event.id, description: data.description, amount: data.amount, createdBy: user.id, createdAt: now, updatedAt: now };
|
||||||
|
await runOps([
|
||||||
|
insertOp(eventOtherIncome, values),
|
||||||
|
financeAuditOp({ eventId: event.id, actorUserId: user.id, entityType: 'other_income', entityId: values.id, action: 'create', after: serializeIncome(values) }),
|
||||||
|
]);
|
||||||
|
return c.json({ income: serializeIncome(values) }, 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.put('/:id/other-income/:incomeId', requireEventPermission('edit_expenses'), zValidator('json', incomeSchema.partial(), validationHook), async (c) => {
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const closed = await assertOpen(c, eventId);
|
||||||
|
if (closed) return closed;
|
||||||
|
const existing = await dbGet<any>(
|
||||||
|
(db as any).select().from(eventOtherIncome)
|
||||||
|
.where(and(eq((eventOtherIncome as any).id, c.req.param('incomeId')), eq((eventOtherIncome as any).eventId, eventId)))
|
||||||
|
);
|
||||||
|
if (!existing) return c.json({ error: 'Income not found' }, 404);
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const updates: Record<string, any> = { updatedAt: getNow() };
|
||||||
|
if (data.description !== undefined) updates.description = data.description;
|
||||||
|
if (data.amount !== undefined) updates.amount = data.amount;
|
||||||
|
const user = currentUser(c);
|
||||||
|
const after = serializeIncome({ ...existing, ...updates });
|
||||||
|
await runOps([
|
||||||
|
updateOp(eventOtherIncome, updates, eq((eventOtherIncome as any).id, existing.id)),
|
||||||
|
financeAuditOp({ eventId, actorUserId: user.id, entityType: 'other_income', entityId: existing.id, action: 'update', before: serializeIncome(existing), after }),
|
||||||
|
]);
|
||||||
|
return c.json({ income: after });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.delete('/:id/other-income/:incomeId', requireEventPermission('edit_expenses'), async (c) => {
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const closed = await assertOpen(c, eventId);
|
||||||
|
if (closed) return closed;
|
||||||
|
const existing = await dbGet<any>(
|
||||||
|
(db as any).select().from(eventOtherIncome)
|
||||||
|
.where(and(eq((eventOtherIncome as any).id, c.req.param('incomeId')), eq((eventOtherIncome as any).eventId, eventId)))
|
||||||
|
);
|
||||||
|
if (!existing) return c.json({ error: 'Income not found' }, 404);
|
||||||
|
const user = currentUser(c);
|
||||||
|
await runOps([
|
||||||
|
deleteOp(eventOtherIncome, eq((eventOtherIncome as any).id, existing.id)),
|
||||||
|
financeAuditOp({ eventId, actorUserId: user.id, entityType: 'other_income', entityId: existing.id, action: 'delete', before: serializeIncome(existing) }),
|
||||||
|
]);
|
||||||
|
return c.json({ message: 'Income deleted' });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Partners ====================
|
||||||
|
|
||||||
|
const partnerFields = {
|
||||||
|
userId: z.string().nullable().optional(),
|
||||||
|
externalName: z.string().trim().max(200).nullable().optional(),
|
||||||
|
roleLabel: z.string().trim().max(100).nullable().optional(),
|
||||||
|
shareType: z.enum(SHARE_TYPES),
|
||||||
|
percentBp: bp,
|
||||||
|
fixedAmount: money,
|
||||||
|
thresholdAmount: money,
|
||||||
|
lossRule: z.enum(LOSS_RULES),
|
||||||
|
lossCapAmount: money,
|
||||||
|
};
|
||||||
|
const createPartnerSchema = z.object({
|
||||||
|
...partnerFields,
|
||||||
|
percentBp: bp.default(0),
|
||||||
|
fixedAmount: money.default(0),
|
||||||
|
thresholdAmount: money.default(0),
|
||||||
|
lossRule: partnerFields.lossRule.default('none'),
|
||||||
|
lossCapAmount: money.default(0),
|
||||||
|
}).refine((d) => !!d.userId || !!d.externalName, { message: 'A partner needs a linked user or a name' });
|
||||||
|
const updatePartnerSchema = z.object(partnerFields).partial();
|
||||||
|
|
||||||
|
/** Editing the split needs both the expense editor and the full-split view. */
|
||||||
|
function canManageSplit(c: Context) {
|
||||||
|
return can(c, 'edit_expenses') && can(c, 'view_full_split');
|
||||||
|
}
|
||||||
|
const splitForbidden = (c: Context) =>
|
||||||
|
c.json({ error: 'Forbidden', code: 'EVENT_PERMISSION', permission: 'view_full_split' }, 403);
|
||||||
|
|
||||||
|
async function userExists(userId: string) {
|
||||||
|
return !!(await dbGet<any>((db as any).select({ id: (users as any).id }).from(users).where(eq((users as any).id, userId))));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPartner(eventId: string, partnerId: string) {
|
||||||
|
return dbGet<any>(
|
||||||
|
(db as any).select().from(eventPartners)
|
||||||
|
.where(and(eq((eventPartners as any).id, partnerId), eq((eventPartners as any).eventId, eventId)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Users that can be linked to a partner (so the partner can log in and see their statement).
|
||||||
|
financeRouter.get('/:id/partners/candidates', requireEventPermission('edit_expenses'), async (c) => {
|
||||||
|
if (!canManageSplit(c)) return splitForbidden(c);
|
||||||
|
const q = (c.req.query('q') || '').trim().toLowerCase();
|
||||||
|
if (q.length < 2) return c.json({ users: [] });
|
||||||
|
return c.json({ users: await searchUsers(q, []) });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.post('/:id/partners', requireEventPermission('edit_expenses'), zValidator('json', createPartnerSchema, validationHook), async (c) => {
|
||||||
|
if (!canManageSplit(c)) return splitForbidden(c);
|
||||||
|
const event = await requireEvent(c);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
const closed = await assertOpen(c, event.id);
|
||||||
|
if (closed) return closed;
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
if (data.userId && !(await userExists(data.userId))) return c.json({ error: 'User not found' }, 400);
|
||||||
|
const user = currentUser(c);
|
||||||
|
const now = getNow();
|
||||||
|
const values = {
|
||||||
|
id: generateId(),
|
||||||
|
eventId: event.id,
|
||||||
|
userId: data.userId || null,
|
||||||
|
externalName: data.externalName || null,
|
||||||
|
roleLabel: data.roleLabel || null,
|
||||||
|
shareType: data.shareType,
|
||||||
|
percentBp: data.percentBp,
|
||||||
|
fixedAmount: data.fixedAmount,
|
||||||
|
thresholdAmount: data.thresholdAmount,
|
||||||
|
lossRule: data.lossRule,
|
||||||
|
lossCapAmount: data.lossCapAmount,
|
||||||
|
payoutStatus: 'pending',
|
||||||
|
payoutDate: null,
|
||||||
|
payoutMethod: null,
|
||||||
|
payoutNote: null,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
await runOps([
|
||||||
|
insertOp(eventPartners, values),
|
||||||
|
financeAuditOp({ eventId: event.id, actorUserId: user.id, entityType: 'partner', entityId: values.id, action: 'create', after: serializePartner(values) }),
|
||||||
|
]);
|
||||||
|
const partner = (await loadPartners(event.id)).find((p) => p.id === values.id);
|
||||||
|
return c.json({ partner }, 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.put('/:id/partners/:partnerId', requireEventPermission('edit_expenses'), zValidator('json', updatePartnerSchema, validationHook), async (c) => {
|
||||||
|
if (!canManageSplit(c)) return splitForbidden(c);
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const closed = await assertOpen(c, eventId);
|
||||||
|
if (closed) return closed;
|
||||||
|
const existing = await loadPartner(eventId, c.req.param('partnerId'));
|
||||||
|
if (!existing) return c.json({ error: 'Partner not found' }, 404);
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
if (data.userId && !(await userExists(data.userId))) return c.json({ error: 'User not found' }, 400);
|
||||||
|
const updates: Record<string, any> = { updatedAt: getNow() };
|
||||||
|
for (const [k, v] of Object.entries(data)) if (v !== undefined) updates[k] = v === '' ? null : v;
|
||||||
|
const merged = { ...existing, ...updates };
|
||||||
|
if (!merged.userId && !merged.externalName) return c.json({ error: 'A partner needs a linked user or a name' }, 400);
|
||||||
|
const user = currentUser(c);
|
||||||
|
await runOps([
|
||||||
|
updateOp(eventPartners, updates, eq((eventPartners as any).id, existing.id)),
|
||||||
|
financeAuditOp({ eventId, actorUserId: user.id, entityType: 'partner', entityId: existing.id, action: 'update', before: serializePartner(existing), after: serializePartner(merged) }),
|
||||||
|
]);
|
||||||
|
const partner = (await loadPartners(eventId)).find((p) => p.id === existing.id);
|
||||||
|
return c.json({ partner });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.delete('/:id/partners/:partnerId', requireEventPermission('edit_expenses'), async (c) => {
|
||||||
|
if (!canManageSplit(c)) return splitForbidden(c);
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const closed = await assertOpen(c, eventId);
|
||||||
|
if (closed) return closed;
|
||||||
|
const existing = await loadPartner(eventId, c.req.param('partnerId'));
|
||||||
|
if (!existing) return c.json({ error: 'Partner not found' }, 404);
|
||||||
|
const fronted = await dbGet<any>(
|
||||||
|
(db as any).select({ id: (eventExpenses as any).id }).from(eventExpenses).where(eq((eventExpenses as any).paidByPartnerId, existing.id))
|
||||||
|
);
|
||||||
|
if (fronted) {
|
||||||
|
return c.json({ error: 'This partner paid for expenses. Change who paid those expenses first.', code: 'PARTNER_HAS_EXPENSES' }, 409);
|
||||||
|
}
|
||||||
|
const user = currentUser(c);
|
||||||
|
await runOps([
|
||||||
|
deleteOp(eventPartners, eq((eventPartners as any).id, existing.id)),
|
||||||
|
financeAuditOp({ eventId, actorUserId: user.id, entityType: 'partner', entityId: existing.id, action: 'delete', before: serializePartner(existing) }),
|
||||||
|
]);
|
||||||
|
return c.json({ message: 'Partner removed' });
|
||||||
|
});
|
||||||
|
|
||||||
|
const markPaidSchema = z.object({
|
||||||
|
paid: z.boolean().default(true),
|
||||||
|
payoutDate: z.string().nullable().optional(),
|
||||||
|
payoutMethod: z.string().trim().max(50).nullable().optional(),
|
||||||
|
payoutNote: z.string().trim().max(1000).nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.post('/:id/partners/:partnerId/mark-paid', requireEventPermission('edit_expenses'), zValidator('json', markPaidSchema, validationHook), async (c) => {
|
||||||
|
if (!canManageSplit(c)) return splitForbidden(c);
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const existing = await loadPartner(eventId, c.req.param('partnerId'));
|
||||||
|
if (!existing) return c.json({ error: 'Partner not found' }, 404);
|
||||||
|
const state = await getFinanceState(eventId);
|
||||||
|
if (state.status === 'open') {
|
||||||
|
return c.json({ error: 'Finalize the event before recording payouts, so they match the frozen numbers.', code: 'FINANCE_NOT_FINALIZED' }, 409);
|
||||||
|
}
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const now = getNow();
|
||||||
|
const updates = data.paid
|
||||||
|
? {
|
||||||
|
payoutStatus: 'paid',
|
||||||
|
payoutDate: data.payoutDate ? toDbDate(data.payoutDate) : now,
|
||||||
|
payoutMethod: data.payoutMethod || null,
|
||||||
|
payoutNote: data.payoutNote || null,
|
||||||
|
updatedAt: now,
|
||||||
|
}
|
||||||
|
: { payoutStatus: 'pending', payoutDate: null, payoutMethod: null, payoutNote: data.payoutNote ?? existing.payoutNote ?? null, updatedAt: now };
|
||||||
|
|
||||||
|
const user = currentUser(c);
|
||||||
|
const ops: TxOp[] = [
|
||||||
|
updateOp(eventPartners, updates, eq((eventPartners as any).id, existing.id)),
|
||||||
|
financeAuditOp({
|
||||||
|
eventId, actorUserId: user.id, entityType: 'partner', entityId: existing.id, action: data.paid ? 'mark_paid' : 'mark_unpaid',
|
||||||
|
before: serializePartner(existing), after: serializePartner({ ...existing, ...updates }),
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
// The event is paid out once every partner is.
|
||||||
|
const all = await loadPartners(eventId);
|
||||||
|
const allPaid = all.every((p) => (p.id === existing.id ? data.paid : p.payoutStatus === 'paid'));
|
||||||
|
const nextStatus = allPaid ? 'paid_out' : 'finalized';
|
||||||
|
if (nextStatus !== state.status) {
|
||||||
|
ops.push(updateOp(eventFinanceState, { status: nextStatus, updatedAt: now }, eq((eventFinanceState as any).eventId, eventId)));
|
||||||
|
ops.push(financeAuditOp({ eventId, actorUserId: user.id, entityType: 'finance_state', entityId: eventId, action: nextStatus, before: { status: state.status }, after: { status: nextStatus } }));
|
||||||
|
}
|
||||||
|
await runOps(ops);
|
||||||
|
const partner = (await loadPartners(eventId)).find((p) => p.id === existing.id);
|
||||||
|
return c.json({ partner, status: nextStatus });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.get('/:id/partners/:partnerId/statement', requireEventPermission('view_finance'), async (c) => {
|
||||||
|
const event = await requireEvent(c);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
const fin = await getEventFinance(event.id, event);
|
||||||
|
const partner = fin!.partners.find((p) => p.id === c.req.param('partnerId'));
|
||||||
|
if (!partner) return c.json({ error: 'Partner not found' }, 404);
|
||||||
|
if (!can(c, 'view_full_split') && partner.userId !== currentUser(c).id) {
|
||||||
|
return c.json({ error: 'Forbidden', code: 'EVENT_PERMISSION', permission: 'view_full_split' }, 403);
|
||||||
|
}
|
||||||
|
const localeParam = c.req.query('locale');
|
||||||
|
const locale = localeParam === 'es' || (!localeParam && currentUser(c).languagePreference === 'es') ? 'es' : 'en';
|
||||||
|
const amounts = new Map(fin!.result.expenses.lines.map((l) => [l.id, l.amount]));
|
||||||
|
const pdf = await generatePartnerStatementPDF({
|
||||||
|
locale,
|
||||||
|
event: { title: (locale === 'es' && event.titleEs) || event.title, startDatetime: event.startDatetime, location: event.location },
|
||||||
|
finalized: fin!.state.status !== 'open',
|
||||||
|
result: fin!.result,
|
||||||
|
partner,
|
||||||
|
line: fin!.result.split.partners.find((p) => p.partnerId === partner.id),
|
||||||
|
frontedExpenses: fin!.expenses.filter((e) => e.paidByPartnerId === partner.id && e.status === 'paid'),
|
||||||
|
expenseAmounts: amounts,
|
||||||
|
});
|
||||||
|
const safeName = partner.name.replace(/[^a-zA-Z0-9-_]+/g, '-').replace(/^-+|-+$/g, '') || 'partner';
|
||||||
|
const slug = (event.slug || event.id).replace(/[^a-zA-Z0-9-_]+/g, '-');
|
||||||
|
return new Response(new Uint8Array(pdf), {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/pdf',
|
||||||
|
'Content-Disposition': `attachment; filename="statement-${slug}-${safeName}.pdf"`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Finalize ====================
|
||||||
|
|
||||||
|
financeRouter.post('/:id/finance/finalize', requireEventPermission('edit_expenses'), async (c) => {
|
||||||
|
if (!canManageSplit(c)) return splitForbidden(c);
|
||||||
|
const event = await requireEvent(c);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
const fin = await getEventFinance(event.id, event);
|
||||||
|
if (fin!.state.status !== 'open') return c.json({ error: 'Already finalized', code: 'FINANCE_FINALIZED' }, 409);
|
||||||
|
|
||||||
|
const user = currentUser(c);
|
||||||
|
const now = getNow();
|
||||||
|
const snapshot = { version: 1 as const, computedAt: new Date().toISOString(), result: fin!.result };
|
||||||
|
const ops: TxOp[] = [];
|
||||||
|
// Persist the amounts auto rows had at finalize, so the rows read the same as the snapshot.
|
||||||
|
const lines = new Map(fin!.result.expenses.lines.map((l) => [l.id, l]));
|
||||||
|
for (const e of fin!.expenses) {
|
||||||
|
const line = lines.get(e.id);
|
||||||
|
if (line && (line.amount !== e.computedAmount || line.quantity !== e.quantity)) {
|
||||||
|
ops.push(updateOp(eventExpenses, { computedAmount: line.amount, quantity: line.quantity }, eq((eventExpenses as any).id, e.id)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const stateValues = { status: 'finalized', finalizedAt: now, finalizedBy: user.id, snapshotJson: JSON.stringify(snapshot), updatedAt: now };
|
||||||
|
ops.push(fin!.state.exists
|
||||||
|
? updateOp(eventFinanceState, stateValues, eq((eventFinanceState as any).eventId, event.id))
|
||||||
|
: insertOp(eventFinanceState, { eventId: event.id, ...stateValues }));
|
||||||
|
ops.push(financeAuditOp({
|
||||||
|
eventId: event.id, actorUserId: user.id, entityType: 'finance_state', entityId: event.id, action: 'finalize',
|
||||||
|
before: { status: 'open' }, after: { status: 'finalized', profit: snapshot.result.profit, split: snapshot.result.split },
|
||||||
|
}));
|
||||||
|
await runOps(ops);
|
||||||
|
return c.json({ status: 'finalized', finalizedAt: iso(now) });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.post('/:id/finance/unfinalize', requireEventPermission('view_finance'), async (c) => {
|
||||||
|
const access = getEventAccess(c)!;
|
||||||
|
if (!canUnfinalize(access)) {
|
||||||
|
return c.json({ error: 'Only admins and co-managers can unfinalize', code: 'EVENT_PERMISSION' }, 403);
|
||||||
|
}
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const state = await getFinanceState(eventId);
|
||||||
|
if (state.status === 'open') return c.json({ error: 'Not finalized' }, 409);
|
||||||
|
const user = currentUser(c);
|
||||||
|
const now = getNow();
|
||||||
|
await runOps([
|
||||||
|
updateOp(eventFinanceState, { status: 'open', finalizedAt: null, finalizedBy: null, snapshotJson: null, updatedAt: now }, eq((eventFinanceState as any).eventId, eventId)),
|
||||||
|
financeAuditOp({
|
||||||
|
eventId, actorUserId: user.id, entityType: 'finance_state', entityId: eventId, action: 'unfinalize',
|
||||||
|
before: { status: state.status, finalizedAt: state.finalizedAt, finalizedBy: state.finalizedBy, snapshot: state.snapshot },
|
||||||
|
after: { status: 'open' },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
return c.json({ status: 'open' });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Audit log ====================
|
||||||
|
|
||||||
|
financeRouter.get('/:id/audit-log', requireEventPermission('view_full_split'), async (c) => {
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const limit = Math.min(200, Math.max(1, parseInt(c.req.query('limit') || '100', 10) || 100));
|
||||||
|
const offset = Math.max(0, parseInt(c.req.query('offset') || '0', 10) || 0);
|
||||||
|
const rows = await dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({
|
||||||
|
id: (financeAuditLog as any).id,
|
||||||
|
actorUserId: (financeAuditLog as any).actorUserId,
|
||||||
|
actorName: (users as any).name,
|
||||||
|
entityType: (financeAuditLog as any).entityType,
|
||||||
|
entityId: (financeAuditLog as any).entityId,
|
||||||
|
action: (financeAuditLog as any).action,
|
||||||
|
beforeJson: (financeAuditLog as any).beforeJson,
|
||||||
|
afterJson: (financeAuditLog as any).afterJson,
|
||||||
|
createdAt: (financeAuditLog as any).createdAt,
|
||||||
|
})
|
||||||
|
.from(financeAuditLog)
|
||||||
|
.leftJoin(users, eq((financeAuditLog as any).actorUserId, (users as any).id))
|
||||||
|
.where(eq((financeAuditLog as any).eventId, eventId))
|
||||||
|
.orderBy(desc((financeAuditLog as any).createdAt))
|
||||||
|
.limit(limit)
|
||||||
|
.offset(offset)
|
||||||
|
);
|
||||||
|
const parse = (s: string | null) => { if (!s) return null; try { return JSON.parse(s); } catch { return null; } };
|
||||||
|
return c.json({
|
||||||
|
entries: rows.map((r: any) => ({
|
||||||
|
id: r.id, actorUserId: r.actorUserId, actorName: r.actorName ?? null, entityType: r.entityType, entityId: r.entityId,
|
||||||
|
action: r.action, before: parse(r.beforeJson), after: parse(r.afterJson), createdAt: iso(r.createdAt),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Team members ====================
|
||||||
|
|
||||||
|
const permissionOverrides = z.record(z.enum(EVENT_PERMISSIONS), z.boolean());
|
||||||
|
const createMemberSchema = z.object({
|
||||||
|
userId: z.string().min(1),
|
||||||
|
rolePreset: z.enum(ROLE_PRESETS),
|
||||||
|
permissions: permissionOverrides.optional(),
|
||||||
|
});
|
||||||
|
const updateMemberSchema = z.object({
|
||||||
|
rolePreset: z.enum(ROLE_PRESETS).optional(),
|
||||||
|
permissions: permissionOverrides.optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
function serializeMember(m: any, u: any) {
|
||||||
|
const overrides = parseOverrides(m.permissions);
|
||||||
|
return {
|
||||||
|
id: m.id,
|
||||||
|
eventId: m.eventId,
|
||||||
|
userId: m.userId,
|
||||||
|
name: u?.name ?? null,
|
||||||
|
email: u?.email ?? null,
|
||||||
|
globalRole: u?.role ?? null,
|
||||||
|
rolePreset: m.rolePreset,
|
||||||
|
permissions: overrides,
|
||||||
|
effective: EVENT_PERMISSIONS.filter((p) => resolveMemberPermissions(m.rolePreset, overrides).has(p)),
|
||||||
|
createdAt: iso(m.createdAt),
|
||||||
|
updatedAt: iso(m.updatedAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadMember(eventId: string, memberId: string) {
|
||||||
|
return dbGet<any>(
|
||||||
|
(db as any).select().from(eventMembers)
|
||||||
|
.where(and(eq((eventMembers as any).id, memberId), eq((eventMembers as any).eventId, eventId)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadUser(userId: string) {
|
||||||
|
return dbGet<any>(
|
||||||
|
(db as any).select({ id: (users as any).id, name: (users as any).name, email: (users as any).email, role: (users as any).role })
|
||||||
|
.from(users).where(eq((users as any).id, userId))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
financeRouter.get('/:id/members', requireEventPermission('manage_team'), async (c) => {
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const rows = await dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({ m: eventMembers, name: (users as any).name, email: (users as any).email, role: (users as any).role })
|
||||||
|
.from(eventMembers)
|
||||||
|
.leftJoin(users, eq((eventMembers as any).userId, (users as any).id))
|
||||||
|
.where(eq((eventMembers as any).eventId, eventId))
|
||||||
|
);
|
||||||
|
return c.json({
|
||||||
|
members: rows
|
||||||
|
.map((r: any) => serializeMember(r.m, { name: r.name, email: r.email, role: r.role }))
|
||||||
|
.sort((a, b) => (a.name || '').localeCompare(b.name || '')),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Active users matching q by name or email, excluding some ids. */
|
||||||
|
async function searchUsers(q: string, excludeIds: string[]) {
|
||||||
|
const like = `%${q.replace(/[%_]/g, '')}%`;
|
||||||
|
const conditions: any[] = [
|
||||||
|
or(sql`lower(${(users as any).name}) like ${like}`, sql`lower(${(users as any).email}) like ${like}`),
|
||||||
|
eq((users as any).accountStatus, 'active'),
|
||||||
|
];
|
||||||
|
if (excludeIds.length > 0) conditions.push(notInArray((users as any).id, excludeIds));
|
||||||
|
return dbAll<any>(
|
||||||
|
(db as any)
|
||||||
|
.select({ id: (users as any).id, name: (users as any).name, email: (users as any).email, role: (users as any).role })
|
||||||
|
.from(users)
|
||||||
|
.where(and(...conditions))
|
||||||
|
.limit(10)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
financeRouter.get('/:id/members/candidates', requireEventPermission('manage_team'), async (c) => {
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const q = (c.req.query('q') || '').trim().toLowerCase();
|
||||||
|
if (q.length < 2) return c.json({ users: [] });
|
||||||
|
const existing = await dbAll<any>(
|
||||||
|
(db as any).select({ userId: (eventMembers as any).userId }).from(eventMembers).where(eq((eventMembers as any).eventId, eventId))
|
||||||
|
);
|
||||||
|
return c.json({ users: await searchUsers(q, existing.map((e: any) => e.userId)) });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.post('/:id/members', requireEventPermission('manage_team'), zValidator('json', createMemberSchema, validationHook), async (c) => {
|
||||||
|
const event = await requireEvent(c);
|
||||||
|
if (!event) return c.json({ error: 'Event not found' }, 404);
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const target = await loadUser(data.userId);
|
||||||
|
if (!target) return c.json({ error: 'User not found' }, 400);
|
||||||
|
const dupe = await dbGet<any>(
|
||||||
|
(db as any).select({ id: (eventMembers as any).id }).from(eventMembers)
|
||||||
|
.where(and(eq((eventMembers as any).eventId, event.id), eq((eventMembers as any).userId, data.userId)))
|
||||||
|
);
|
||||||
|
if (dupe) return c.json({ error: 'This user is already on the team', code: 'ALREADY_MEMBER' }, 409);
|
||||||
|
const user = currentUser(c);
|
||||||
|
const now = getNow();
|
||||||
|
const values = {
|
||||||
|
id: generateId(),
|
||||||
|
eventId: event.id,
|
||||||
|
userId: data.userId,
|
||||||
|
rolePreset: data.rolePreset,
|
||||||
|
permissions: JSON.stringify(data.permissions || {}),
|
||||||
|
createdBy: user.id,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
const member = serializeMember(values, target);
|
||||||
|
await runOps([
|
||||||
|
insertOp(eventMembers, values),
|
||||||
|
financeAuditOp({ eventId: event.id, actorUserId: user.id, entityType: 'member', entityId: values.id, action: 'create', after: member }),
|
||||||
|
]);
|
||||||
|
return c.json({ member }, 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.put('/:id/members/:memberId', requireEventPermission('manage_team'), zValidator('json', updateMemberSchema, validationHook), async (c) => {
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const existing = await loadMember(eventId, c.req.param('memberId'));
|
||||||
|
if (!existing) return c.json({ error: 'Member not found' }, 404);
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const updates: Record<string, any> = { updatedAt: getNow() };
|
||||||
|
if (data.rolePreset) updates.rolePreset = data.rolePreset;
|
||||||
|
if (data.permissions) updates.permissions = JSON.stringify(data.permissions);
|
||||||
|
const target = await loadUser(existing.userId);
|
||||||
|
const before = serializeMember(existing, target);
|
||||||
|
const after = serializeMember({ ...existing, ...updates }, target);
|
||||||
|
const user = currentUser(c);
|
||||||
|
await runOps([
|
||||||
|
updateOp(eventMembers, updates, eq((eventMembers as any).id, existing.id)),
|
||||||
|
financeAuditOp({ eventId, actorUserId: user.id, entityType: 'member', entityId: existing.id, action: 'update', before, after }),
|
||||||
|
]);
|
||||||
|
return c.json({ member: after });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeRouter.delete('/:id/members/:memberId', requireEventPermission('manage_team'), async (c) => {
|
||||||
|
const eventId = c.req.param('id');
|
||||||
|
const existing = await loadMember(eventId, c.req.param('memberId'));
|
||||||
|
if (!existing) return c.json({ error: 'Member not found' }, 404);
|
||||||
|
const user = currentUser(c);
|
||||||
|
const target = await loadUser(existing.userId);
|
||||||
|
await runOps([
|
||||||
|
deleteOp(eventMembers, eq((eventMembers as any).id, existing.id)),
|
||||||
|
financeAuditOp({ eventId, actorUserId: user.id, entityType: 'member', entityId: existing.id, action: 'delete', before: serializeMember(existing, target) }),
|
||||||
|
]);
|
||||||
|
return c.json({ message: 'Member removed' });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default financeRouter;
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||||
|
import { execFileSync } from 'child_process';
|
||||||
|
import { mkdtempSync } from 'fs';
|
||||||
|
import { tmpdir } from 'os';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
|
||||||
|
// Changing an event's ticket price must never rewrite what was already paid,
|
||||||
|
// but anyone who booked and hasn't paid yet owes the new price. These tests pin
|
||||||
|
// which payments follow a price change and which keep their amount.
|
||||||
|
|
||||||
|
// Runs on a temp SQLite file by default. Set FINANCE_TEST_PG_URL to a Postgres
|
||||||
|
// URL to run the same suite in a throwaway schema (dropped afterwards).
|
||||||
|
const PG_URL = process.env.FINANCE_TEST_PG_URL;
|
||||||
|
const PG_SCHEMA = `pricetest_${Date.now()}`;
|
||||||
|
if (PG_URL) {
|
||||||
|
process.env.DB_TYPE = 'postgres';
|
||||||
|
process.env.DATABASE_URL = `${PG_URL}${PG_URL.includes('?') ? '&' : '?'}options=-c%20search_path%3D${PG_SCHEMA}`;
|
||||||
|
} else {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'events-price-test-'));
|
||||||
|
process.env.DB_TYPE = 'sqlite';
|
||||||
|
process.env.DATABASE_URL = join(dir, 'test.db');
|
||||||
|
}
|
||||||
|
process.env.FRONTEND_URL = 'http://localhost:3002';
|
||||||
|
process.env.BETTER_AUTH_SECRET = 'events-price-secret-0123456789abcdef';
|
||||||
|
delete process.env.REDIS_URL;
|
||||||
|
delete process.env.REVALIDATE_SECRET;
|
||||||
|
|
||||||
|
const ADMIN = { id: randomUUID(), name: 'The Admin', role: 'admin' };
|
||||||
|
|
||||||
|
vi.mock('../lib/auth.js', () => ({
|
||||||
|
requireAuth: (roles?: string[]) => async (c: any, next: any) => {
|
||||||
|
if (roles && !roles.includes(ADMIN.role)) return c.json({ error: 'Forbidden' }, 403);
|
||||||
|
c.set('user', ADMIN);
|
||||||
|
await next();
|
||||||
|
},
|
||||||
|
getAuthUser: async () => ADMIN,
|
||||||
|
}));
|
||||||
|
|
||||||
|
let app: any;
|
||||||
|
let dbm: any;
|
||||||
|
|
||||||
|
const SEED_USER_ID = randomUUID();
|
||||||
|
const EVENT_ID = randomUUID();
|
||||||
|
const OTHER_EVENT_ID = randomUUID();
|
||||||
|
const OLD_PRICE = 50000;
|
||||||
|
const NEW_PRICE = 70000;
|
||||||
|
// Ticket id by label, so assertions read by name.
|
||||||
|
const ticketIds: Record<string, string> = {};
|
||||||
|
|
||||||
|
async function put(path: string, body: unknown) {
|
||||||
|
const res = await app.request(path, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
return { status: res.status, body: await res.json() };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One ticket with its payment row, the way a booking leaves them. Seeded through drizzle so it works on both engines. */
|
||||||
|
async function seedBooking(label: string, eventId: string, paymentStatus: string, provider = 'bancard') {
|
||||||
|
const { db, tickets, payments } = dbm;
|
||||||
|
const now = dbm.getNow();
|
||||||
|
const id = randomUUID();
|
||||||
|
ticketIds[label] = id;
|
||||||
|
const paid = paymentStatus === 'paid';
|
||||||
|
await db.insert(tickets).values({
|
||||||
|
id, userId: SEED_USER_ID, eventId, attendeeFirstName: label, status: paid ? 'confirmed' : 'pending',
|
||||||
|
paymentStatus: paid ? 'paid' : 'unpaid', isGuest: dbm.toDbBool(false), qrCode: `QR-${label}`, createdAt: now,
|
||||||
|
});
|
||||||
|
await db.insert(payments).values({
|
||||||
|
id: randomUUID(), ticketId: id, provider, amount: OLD_PRICE, currency: 'PYG',
|
||||||
|
status: paymentStatus, paidAt: paid ? now : null, createdAt: now, updatedAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function amountOf(label: string): Promise<number> {
|
||||||
|
const { db, dbGet, payments, eq } = dbm;
|
||||||
|
const row = await dbGet(db.select({ amount: payments.amount }).from(payments).where(eq(payments.ticketId, ticketIds[label])));
|
||||||
|
return Number(row.amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
if (PG_URL) execFileSync('psql', [PG_URL, '-qc', `CREATE SCHEMA ${PG_SCHEMA}`], { stdio: 'pipe' });
|
||||||
|
execFileSync('npx', ['tsx', 'src/db/migrate.ts'], { env: { ...process.env }, stdio: 'pipe' });
|
||||||
|
|
||||||
|
return (async () => {
|
||||||
|
const { Hono } = await import('hono');
|
||||||
|
app = new Hono();
|
||||||
|
app.route('/api/events', (await import('./events.js')).default);
|
||||||
|
|
||||||
|
dbm = { ...(await import('../db/index.js')), ...(await import('../lib/utils.js')), ...(await import('drizzle-orm')) };
|
||||||
|
const { db, users, events } = dbm;
|
||||||
|
const now = dbm.getNow();
|
||||||
|
await db.insert(users).values({
|
||||||
|
id: SEED_USER_ID, email: 'seed@test.py', name: 'Seed', role: 'user',
|
||||||
|
isClaimed: dbm.toDbBool(false), accountStatus: 'unclaimed', createdAt: now, updatedAt: now,
|
||||||
|
});
|
||||||
|
for (const id of [EVENT_ID, OTHER_EVENT_ID]) {
|
||||||
|
await db.insert(events).values({
|
||||||
|
id, title: `Event ${id}`, description: 'desc', startDatetime: now, location: 'Asuncion', price: OLD_PRICE,
|
||||||
|
currency: 'PYG', capacity: 40, status: 'published', externalBookingEnabled: dbm.toDbBool(false), createdAt: now, updatedAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await seedBooking('paid', EVENT_ID, 'paid');
|
||||||
|
await seedBooking('refunded', EVENT_ID, 'refunded');
|
||||||
|
await seedBooking('pending', EVENT_ID, 'pending');
|
||||||
|
await seedBooking('pending-tpago', EVENT_ID, 'pending', 'tpago');
|
||||||
|
await seedBooking('claimed', EVENT_ID, 'pending_approval', 'bank_transfer');
|
||||||
|
await seedBooking('on-hold', EVENT_ID, 'on_hold');
|
||||||
|
await seedBooking('lightning', EVENT_ID, 'pending', 'lightning');
|
||||||
|
await seedBooking('other-event', OTHER_EVENT_ID, 'pending');
|
||||||
|
})();
|
||||||
|
}, 120_000);
|
||||||
|
|
||||||
|
afterAll(() => {
|
||||||
|
if (PG_URL) execFileSync('psql', [PG_URL, '-qc', `DROP SCHEMA ${PG_SCHEMA} CASCADE`], { stdio: 'pipe' });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('changing the ticket price', () => {
|
||||||
|
it('leaves every payment alone when the price is not part of the edit', async () => {
|
||||||
|
const { status } = await put(`/api/events/${EVENT_ID}`, { location: 'Encarnación' });
|
||||||
|
expect(status).toBe(200);
|
||||||
|
expect(await amountOf('pending')).toBe(OLD_PRICE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves every payment alone when the price is resent unchanged', async () => {
|
||||||
|
const { status } = await put(`/api/events/${EVENT_ID}`, { price: OLD_PRICE, currency: 'PYG' });
|
||||||
|
expect(status).toBe(200);
|
||||||
|
expect(await amountOf('pending')).toBe(OLD_PRICE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reprices open payments and keeps what was already paid', async () => {
|
||||||
|
const { status, body } = await put(`/api/events/${EVENT_ID}`, { price: NEW_PRICE });
|
||||||
|
expect(status).toBe(200);
|
||||||
|
expect(body.event.price).toBe(NEW_PRICE);
|
||||||
|
|
||||||
|
// Not yet paid: owe the current price.
|
||||||
|
expect(await amountOf('pending')).toBe(NEW_PRICE);
|
||||||
|
expect(await amountOf('pending-tpago')).toBe(NEW_PRICE);
|
||||||
|
|
||||||
|
// History stays as it happened.
|
||||||
|
expect(await amountOf('paid')).toBe(OLD_PRICE);
|
||||||
|
expect(await amountOf('refunded')).toBe(OLD_PRICE);
|
||||||
|
// The customer already sent the old amount / an admin is reviewing it.
|
||||||
|
expect(await amountOf('claimed')).toBe(OLD_PRICE);
|
||||||
|
expect(await amountOf('on-hold')).toBe(OLD_PRICE);
|
||||||
|
// The Lightning invoice was issued for a fixed amount.
|
||||||
|
expect(await amountOf('lightning')).toBe(OLD_PRICE);
|
||||||
|
// Other events are untouched.
|
||||||
|
expect(await amountOf('other-event')).toBe(OLD_PRICE);
|
||||||
|
});
|
||||||
|
});
|
||||||
+236
-95
@@ -2,11 +2,18 @@ import { Hono } from 'hono';
|
|||||||
import { zValidator } from '@hono/zod-validator';
|
import { zValidator } from '@hono/zod-validator';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { db, dbGet, dbAll, events, eventSlugAliases, tickets, payments, eventPaymentOverrides, emailLogs, invoices, siteSettings, isPostgres } from '../db/index.js';
|
import { db, dbGet, dbAll, events, eventSlugAliases, tickets, payments, eventPaymentOverrides, emailLogs, invoices, siteSettings, isPostgres } from '../db/index.js';
|
||||||
import { eq, desc, and, gte, sql } from 'drizzle-orm';
|
import { eq, ne, desc, and, gte, inArray, sql } from 'drizzle-orm';
|
||||||
import { requireAuth, getAuthUser } from '../lib/auth.js';
|
import { requireAuth, getAuthUser } from '../lib/auth.js';
|
||||||
|
import { requireEventPermission, canSeeAttendeePii, redactAttendee } from '../lib/eventPermissions.js';
|
||||||
import { generateId, getNow, convertBooleansForDb, toDbDate, toDbDateTz, calculateAvailableSeats } from '../lib/utils.js';
|
import { generateId, getNow, convertBooleansForDb, toDbDate, toDbDateTz, calculateAvailableSeats } from '../lib/utils.js';
|
||||||
import { slugify, uniqueSlug } from '../lib/slugify.js';
|
import { slugify, uniqueSlug } from '../lib/slugify.js';
|
||||||
import { revalidateFrontendCache } from '../lib/revalidate.js';
|
import { revalidateFrontendCache } from '../lib/revalidate.js';
|
||||||
|
import { eventSeatBreakdownQuery } from '../lib/capacity.js';
|
||||||
|
import { resolvePresaleClosure } from '../lib/presale.js';
|
||||||
|
import { canSeeWalkInPrice, parseWalkInPrice } from '../lib/walkInPrice.js';
|
||||||
|
import { publicSalesFields } from '../lib/salesState.js';
|
||||||
|
import { loadDoorMethods } from '../lib/doorPayments.js';
|
||||||
|
import { runOps, updateOp, type TxOp } from '../lib/txOps.js';
|
||||||
|
|
||||||
interface UserContext {
|
interface UserContext {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -18,17 +25,52 @@ interface UserContext {
|
|||||||
const eventsRouter = new Hono<{ Variables: { user: UserContext } }>();
|
const eventsRouter = new Hono<{ Variables: { user: UserContext } }>();
|
||||||
|
|
||||||
// Helper to normalize event data for API response
|
// Helper to normalize event data for API response
|
||||||
// PostgreSQL decimal returns strings, booleans are stored as integers
|
// PostgreSQL decimal returns strings, booleans are stored as integers.
|
||||||
function normalizeEvent(event: any) {
|
// `settings` is the site_settings row; when given, the effective pre-sale
|
||||||
|
// cutoff (`presaleClosesAt`, ISO or null) is computed so the frontend and the
|
||||||
|
// booking API agree on when registration closes.
|
||||||
|
// The walk-in (door) price is internal: it is dropped unless the caller is
|
||||||
|
// admin/organizer/staff and `includeWalkInPrice` is set.
|
||||||
|
function normalizeEvent(event: any, settings?: any, opts: { includeWalkInPrice?: boolean } = {}) {
|
||||||
if (!event) return event;
|
if (!event) return event;
|
||||||
return {
|
const { walkInPrice, ...publicFields } = event;
|
||||||
...event,
|
const normalized = {
|
||||||
|
...publicFields,
|
||||||
|
...(opts.includeWalkInPrice ? { walkInPrice: parseWalkInPrice(walkInPrice) } : {}),
|
||||||
// Convert price from string/decimal to clean number
|
// Convert price from string/decimal to clean number
|
||||||
price: typeof event.price === 'string' ? parseFloat(event.price) : Number(event.price),
|
price: typeof event.price === 'string' ? parseFloat(event.price) : Number(event.price),
|
||||||
// Convert capacity from string to number if needed
|
// Convert capacity from string to number if needed
|
||||||
capacity: typeof event.capacity === 'string' ? parseInt(event.capacity, 10) : Number(event.capacity),
|
capacity: typeof event.capacity === 'string' ? parseInt(event.capacity, 10) : Number(event.capacity),
|
||||||
// Convert boolean integers to actual booleans for frontend
|
// Convert boolean integers to actual booleans for frontend
|
||||||
externalBookingEnabled: Boolean(event.externalBookingEnabled),
|
externalBookingEnabled: Boolean(event.externalBookingEnabled),
|
||||||
|
// Pre-sale overrides: null means "inherit the site default"
|
||||||
|
presaleClosureEnabled: event.presaleClosureEnabled == null ? null : Boolean(event.presaleClosureEnabled),
|
||||||
|
presaleCloseMinutesBefore: event.presaleCloseMinutesBefore == null ? null : Number(event.presaleCloseMinutesBefore),
|
||||||
|
};
|
||||||
|
if (settings !== undefined) {
|
||||||
|
const { closesAt } = resolvePresaleClosure(normalized, settings);
|
||||||
|
return { ...normalized, presaleClosesAt: closesAt ? closesAt.toISOString() : null };
|
||||||
|
}
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seat counts plus the public sales state for a normalized event. `raw` is the
|
||||||
|
// DB row: doorPrice is resolved from its walk-in price, and only in the `door`
|
||||||
|
// state (see lib/salesState.ts).
|
||||||
|
function withSeatsAndSales(
|
||||||
|
raw: any,
|
||||||
|
normalized: any,
|
||||||
|
settings: any,
|
||||||
|
counts: { paid: number; claimed: number },
|
||||||
|
nowMs: number = Date.now()
|
||||||
|
) {
|
||||||
|
const availableSeats = calculateAvailableSeats(normalized.capacity, counts.paid + counts.claimed);
|
||||||
|
return {
|
||||||
|
...normalized,
|
||||||
|
bookedCount: counts.paid,
|
||||||
|
claimedCount: counts.claimed,
|
||||||
|
availableSeats,
|
||||||
|
...publicSalesFields(raw, settings, availableSeats, nowMs),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,6 +143,29 @@ const parsePrice = (val: unknown): number => {
|
|||||||
return 0;
|
return 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Walk-in price: empty/null means "not set" (fall back to price) and must stay
|
||||||
|
// null, never 0 — 0 is a real value meaning a free walk-in. Unparseable input
|
||||||
|
// fails validation instead of silently becoming 0 the way parsePrice does.
|
||||||
|
const walkInPriceSchema = z.union([z.number(), z.string(), z.null()])
|
||||||
|
.transform((val) => {
|
||||||
|
if (val === null) return null;
|
||||||
|
if (typeof val === 'number') return val;
|
||||||
|
const trimmed = val.trim();
|
||||||
|
if (trimmed === '') return null;
|
||||||
|
return Number(trimmed.replace(',', '.'));
|
||||||
|
})
|
||||||
|
.pipe(z.number().min(0, 'Walk-in price cannot be negative').nullable())
|
||||||
|
.optional();
|
||||||
|
|
||||||
|
// PYG has no minor unit, so a PYG walk-in price must be a whole number.
|
||||||
|
function walkInPriceError(walkInPrice: number | null | undefined, currency: string | null | undefined): string | null {
|
||||||
|
if (walkInPrice == null) return null;
|
||||||
|
if ((currency || 'PYG') === 'PYG' && !Number.isInteger(walkInPrice)) {
|
||||||
|
return 'walkInPrice: Walk-in price must be a whole number for PYG';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
// Helper to normalize boolean (handles true/false and 0/1)
|
// Helper to normalize boolean (handles true/false and 0/1)
|
||||||
const normalizeBoolean = (val: unknown): boolean => {
|
const normalizeBoolean = (val: unknown): boolean => {
|
||||||
if (typeof val === 'boolean') return val;
|
if (typeof val === 'boolean') return val;
|
||||||
@@ -124,6 +189,9 @@ const baseEventSchema = z.object({
|
|||||||
locationUrl: z.string().url().optional().nullable().or(z.literal('')),
|
locationUrl: z.string().url().optional().nullable().or(z.literal('')),
|
||||||
// Accept price as number or string (handles "45000" and "41,44" formats)
|
// Accept price as number or string (handles "45000" and "41,44" formats)
|
||||||
price: z.union([z.number(), z.string()]).transform(parsePrice).pipe(z.number().min(0)).default(0),
|
price: z.union([z.number(), z.string()]).transform(parsePrice).pipe(z.number().min(0)).default(0),
|
||||||
|
walkInPrice: walkInPriceSchema,
|
||||||
|
// Groups recurring events for the finance overview ("" clears it)
|
||||||
|
series: z.preprocess((v) => (typeof v === 'string' && v.trim() === '' ? null : v), z.string().trim().max(100).nullable()).optional(),
|
||||||
currency: z.string().default('PYG'),
|
currency: z.string().default('PYG'),
|
||||||
capacity: z.union([z.number(), z.string()]).transform((val) => typeof val === 'string' ? parseInt(val, 10) || 50 : val).pipe(z.number().min(1)).default(50),
|
capacity: z.union([z.number(), z.string()]).transform((val) => typeof val === 'string' ? parseInt(val, 10) || 50 : val).pipe(z.number().min(1)).default(50),
|
||||||
status: z.enum(['draft', 'published', 'unlisted', 'cancelled', 'completed', 'archived']).default('draft'),
|
status: z.enum(['draft', 'published', 'unlisted', 'cancelled', 'completed', 'archived']).default('draft'),
|
||||||
@@ -137,8 +205,30 @@ const baseEventSchema = z.object({
|
|||||||
// External booking support - accept boolean or number (0/1 from DB)
|
// External booking support - accept boolean or number (0/1 from DB)
|
||||||
externalBookingEnabled: z.union([z.boolean(), z.number()]).transform(normalizeBoolean).default(false),
|
externalBookingEnabled: z.union([z.boolean(), z.number()]).transform(normalizeBoolean).default(false),
|
||||||
externalBookingUrl: z.string().url().optional().nullable().or(z.literal('')),
|
externalBookingUrl: z.string().url().optional().nullable().or(z.literal('')),
|
||||||
|
// Pre-sale closure overrides - null/omitted means "inherit the site default"
|
||||||
|
presaleClosureEnabled: z.union([z.boolean(), z.number(), z.null()])
|
||||||
|
.transform((v) => (v === null ? null : normalizeBoolean(v)))
|
||||||
|
.optional(),
|
||||||
|
presaleCloseMinutesBefore: z.union([z.number(), z.string(), z.null()])
|
||||||
|
.transform((v) => {
|
||||||
|
if (v === null) return null;
|
||||||
|
const n = typeof v === 'string' ? parseInt(v, 10) : v;
|
||||||
|
return Number.isFinite(n) ? Math.floor(n) : NaN;
|
||||||
|
})
|
||||||
|
.pipe(z.number().int().min(0, 'Pre-sale closure time cannot be negative').nullable())
|
||||||
|
.optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// When pre-sale closure is explicitly enabled on an event, the cutoff must be set too.
|
||||||
|
const presaleRefine = {
|
||||||
|
check: (data: { presaleClosureEnabled?: boolean | null; presaleCloseMinutesBefore?: number | null }) =>
|
||||||
|
data.presaleClosureEnabled !== true || typeof data.presaleCloseMinutesBefore === 'number',
|
||||||
|
options: {
|
||||||
|
message: 'Pre-sale closure time is required when pre-sale closure is enabled',
|
||||||
|
path: ['presaleCloseMinutesBefore'],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
const createEventSchema = baseEventSchema.refine(
|
const createEventSchema = baseEventSchema.refine(
|
||||||
(data) => {
|
(data) => {
|
||||||
// If external booking is enabled, URL must be provided and must start with https://
|
// If external booking is enabled, URL must be provided and must start with https://
|
||||||
@@ -151,7 +241,7 @@ const createEventSchema = baseEventSchema.refine(
|
|||||||
message: 'External booking URL is required and must be a valid HTTPS link when external booking is enabled',
|
message: 'External booking URL is required and must be a valid HTTPS link when external booking is enabled',
|
||||||
path: ['externalBookingUrl'],
|
path: ['externalBookingUrl'],
|
||||||
}
|
}
|
||||||
);
|
).refine(presaleRefine.check, presaleRefine.options);
|
||||||
|
|
||||||
const updateEventSchema = baseEventSchema.partial().refine(
|
const updateEventSchema = baseEventSchema.partial().refine(
|
||||||
(data) => {
|
(data) => {
|
||||||
@@ -165,18 +255,26 @@ const updateEventSchema = baseEventSchema.partial().refine(
|
|||||||
message: 'External booking URL is required and must be a valid HTTPS link when external booking is enabled',
|
message: 'External booking URL is required and must be a valid HTTPS link when external booking is enabled',
|
||||||
path: ['externalBookingUrl'],
|
path: ['externalBookingUrl'],
|
||||||
}
|
}
|
||||||
);
|
).refine(presaleRefine.check, presaleRefine.options);
|
||||||
|
|
||||||
// Get all events (public)
|
// Get all events (public)
|
||||||
eventsRouter.get('/', async (c) => {
|
eventsRouter.get('/', async (c) => {
|
||||||
const status = c.req.query('status');
|
const status = c.req.query('status');
|
||||||
const upcoming = c.req.query('upcoming');
|
const upcoming = c.req.query('upcoming');
|
||||||
|
// Pagination is opt-in: callers that pass neither page nor pageSize (public
|
||||||
|
// pages, admin filter dropdowns) still get the full list.
|
||||||
|
const pageParam = c.req.query('page');
|
||||||
|
const pageSizeParam = c.req.query('pageSize');
|
||||||
|
const paginated = pageParam !== undefined || pageSizeParam !== undefined;
|
||||||
|
const page = Math.max(parseInt(pageParam || '1', 10) || 1, 1);
|
||||||
|
const pageSize = Math.min(Math.max(parseInt(pageSizeParam || '25', 10) || 25, 1), 200);
|
||||||
|
|
||||||
// Only privileged users may see non-public events (drafts, archived, etc.).
|
// Only privileged users may see non-public events (drafts, archived, etc.).
|
||||||
// Anonymous/regular callers are restricted to published events regardless of
|
// Anonymous/regular callers are restricted to published events regardless of
|
||||||
// any client-supplied status filter, so drafts cannot leak.
|
// any client-supplied status filter, so drafts cannot leak.
|
||||||
const authUser: any = await getAuthUser(c);
|
const authUser: any = await getAuthUser(c);
|
||||||
const isPrivileged = !!authUser && ['admin', 'organizer', 'staff', 'marketing'].includes(authUser.role);
|
const isPrivileged = !!authUser && ['admin', 'organizer', 'staff', 'marketing'].includes(authUser.role);
|
||||||
|
const includeWalkInPrice = canSeeWalkInPrice(authUser?.role);
|
||||||
|
|
||||||
const conditions: any[] = [];
|
const conditions: any[] = [];
|
||||||
|
|
||||||
@@ -194,38 +292,58 @@ eventsRouter.get('/', async (c) => {
|
|||||||
conditions.push(eq((events as any).status, 'published'));
|
conditions.push(eq((events as any).status, 'published'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const whereClause = conditions.length === 0
|
||||||
|
? undefined
|
||||||
|
: conditions.length === 1 ? conditions[0] : and(...conditions);
|
||||||
|
|
||||||
let query = (db as any).select().from(events);
|
let query = (db as any).select().from(events);
|
||||||
if (conditions.length > 0) {
|
if (whereClause) query = query.where(whereClause);
|
||||||
query = query.where(conditions.length === 1 ? conditions[0] : and(...conditions));
|
query = query.orderBy(desc((events as any).startDatetime));
|
||||||
|
|
||||||
|
let total: number | undefined;
|
||||||
|
if (paginated) {
|
||||||
|
let countQuery = (db as any).select({ count: sql`count(*)` }).from(events);
|
||||||
|
if (whereClause) countQuery = countQuery.where(whereClause);
|
||||||
|
const totalRow = await dbGet<any>(countQuery);
|
||||||
|
total = Number(totalRow?.count || 0);
|
||||||
|
query = query.limit(pageSize).offset((page - 1) * pageSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await dbAll<any>(query.orderBy(desc((events as any).startDatetime)));
|
const result = await dbAll<any>(query);
|
||||||
|
|
||||||
// Single grouped query for booked counts across all events (avoids N+1: previously
|
// Single grouped query for seat counts across all events (avoids N+1: previously
|
||||||
// this ran one COUNT query per event).
|
// this ran one COUNT query per event). bookedCount = paid (confirmed/checked_in);
|
||||||
const countRows = await dbAll<any>(
|
// claimedCount = "I've paid" claims awaiting admin verification. Both hold seats,
|
||||||
(db as any)
|
// so availableSeats subtracts them together — the same formula the booking-creation
|
||||||
.select({ eventId: (tickets as any).eventId, count: sql<number>`count(*)` })
|
// capacity check enforces (lib/capacity.ts).
|
||||||
.from(tickets)
|
// Scoped to the returned events so a page of 25 does not scan every ticket.
|
||||||
.where(sql`${(tickets as any).status} IN ('confirmed', 'checked_in')`)
|
const eventIds = result.map((event: any) => event.id);
|
||||||
.groupBy((tickets as any).eventId)
|
const countRows = eventIds.length > 0
|
||||||
);
|
? await dbAll<any>(eventSeatBreakdownQuery(db, eventIds))
|
||||||
const countByEvent = new Map<string, number>();
|
: [];
|
||||||
|
const countByEvent = new Map<string, { paid: number; claimed: number }>();
|
||||||
for (const row of countRows) {
|
for (const row of countRows) {
|
||||||
countByEvent.set(row.eventId, Number(row.count) || 0);
|
countByEvent.set(row.eventId, {
|
||||||
|
paid: Number(row.paidCount) || 0,
|
||||||
|
claimed: Number(row.claimedCount) || 0,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const eventsWithCounts = result.map((event: any) => {
|
const siteSettingsRow = await getSiteSettingsRow();
|
||||||
const normalized = normalizeEvent(event);
|
const nowMs = Date.now();
|
||||||
const bookedCount = countByEvent.get(event.id) || 0;
|
const eventsWithCounts = result.map((event: any) =>
|
||||||
return {
|
withSeatsAndSales(
|
||||||
...normalized,
|
event,
|
||||||
bookedCount,
|
normalizeEvent(event, siteSettingsRow, { includeWalkInPrice }),
|
||||||
availableSeats: calculateAvailableSeats(normalized.capacity, bookedCount),
|
siteSettingsRow,
|
||||||
};
|
countByEvent.get(event.id) || { paid: 0, claimed: 0 },
|
||||||
});
|
nowMs,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
return c.json({ events: eventsWithCounts });
|
return paginated
|
||||||
|
? c.json({ events: eventsWithCounts, total, page, pageSize })
|
||||||
|
: c.json({ events: eventsWithCounts });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get single event (public) - resolves by id, canonical slug, or historical alias
|
// Get single event (public) - resolves by id, canonical slug, or historical alias
|
||||||
@@ -237,61 +355,54 @@ eventsRouter.get('/:id', async (c) => {
|
|||||||
return c.json({ error: 'Event not found' }, 404);
|
return c.json({ error: 'Event not found' }, 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const authUser: any = await getAuthUser(c);
|
||||||
|
|
||||||
// Draft events are only visible to privileged users (admin preview); hide from public.
|
// Draft events are only visible to privileged users (admin preview); hide from public.
|
||||||
if ((event as any).status === 'draft') {
|
if ((event as any).status === 'draft') {
|
||||||
const authUser: any = await getAuthUser(c);
|
|
||||||
const isPrivileged = !!authUser && ['admin', 'organizer', 'staff', 'marketing'].includes(authUser.role);
|
const isPrivileged = !!authUser && ['admin', 'organizer', 'staff', 'marketing'].includes(authUser.role);
|
||||||
if (!isPrivileged) {
|
if (!isPrivileged) {
|
||||||
return c.json({ error: 'Event not found' }, 404);
|
return c.json({ error: 'Event not found' }, 404);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Count confirmed AND checked_in tickets (checked_in were previously confirmed)
|
const settings = await getSiteSettingsRow();
|
||||||
// This ensures check-in doesn't affect capacity/spots_left
|
const normalized = normalizeEvent(event, settings, {
|
||||||
const ticketCount = await dbGet<any>(
|
includeWalkInPrice: canSeeWalkInPrice(authUser?.role),
|
||||||
(db as any)
|
});
|
||||||
.select({ count: sql<number>`count(*)` })
|
const counts = await getEventSeatCounts(event.id);
|
||||||
.from(tickets)
|
const publicEvent = withSeatsAndSales(event, normalized, settings, counts);
|
||||||
.where(
|
// Door tenders (never the comp "guest" one) for the page's "pay at the door" line.
|
||||||
and(
|
const doorPaymentMethods = publicEvent.salesState === 'door'
|
||||||
eq((tickets as any).eventId, event.id),
|
? (await loadDoorMethods(event.id)).filter((m) => m !== 'guest')
|
||||||
sql`${(tickets as any).status} IN ('confirmed', 'checked_in')`
|
: undefined;
|
||||||
)
|
// serverTime lets the page schedule its refresh at presaleClosesAt even when
|
||||||
)
|
// the visitor's clock is off.
|
||||||
);
|
|
||||||
|
|
||||||
const normalized = normalizeEvent(event);
|
|
||||||
const bookedCount = ticketCount?.count || 0;
|
|
||||||
return c.json({
|
return c.json({
|
||||||
event: {
|
event: { ...publicEvent, ...(doorPaymentMethods ? { doorPaymentMethods } : {}) },
|
||||||
...normalized,
|
serverTime: new Date().toISOString(),
|
||||||
bookedCount,
|
|
||||||
availableSeats: calculateAvailableSeats(normalized.capacity, bookedCount),
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
async function getSiteTimezone(): Promise<string> {
|
// Single site_settings row (or null when none has been created yet)
|
||||||
|
async function getSiteSettingsRow(): Promise<any | null> {
|
||||||
const settings = await dbGet<any>(
|
const settings = await dbGet<any>(
|
||||||
(db as any).select().from(siteSettings).limit(1)
|
(db as any).select().from(siteSettings).limit(1)
|
||||||
);
|
);
|
||||||
|
return settings || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function siteTimezoneOf(settings: any | null): string {
|
||||||
return settings?.timezone || 'America/Asuncion';
|
return settings?.timezone || 'America/Asuncion';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to get ticket count for an event
|
// Helper: paid (confirmed/checked_in) and claimed (pending_approval-held) seat
|
||||||
async function getEventTicketCount(eventId: string): Promise<number> {
|
// counts for one event — see lib/capacity.ts for the seat-holding rule.
|
||||||
const ticketCount = await dbGet<any>(
|
async function getEventSeatCounts(eventId: string): Promise<{ paid: number; claimed: number }> {
|
||||||
(db as any)
|
const row = await dbGet<any>(eventSeatBreakdownQuery(db, eventId));
|
||||||
.select({ count: sql<number>`count(*)` })
|
return {
|
||||||
.from(tickets)
|
paid: Number(row?.paidCount) || 0,
|
||||||
.where(
|
claimed: Number(row?.claimedCount) || 0,
|
||||||
and(
|
};
|
||||||
eq((tickets as any).eventId, eventId),
|
|
||||||
sql`${(tickets as any).status} IN ('confirmed', 'checked_in')`
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
return ticketCount?.count || 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the earliest upcoming published event with ticket counts (ignores featured promotion)
|
// Get the earliest upcoming published event with ticket counts (ignores featured promotion)
|
||||||
@@ -315,13 +426,9 @@ async function getNextChronologicalUpcoming(): Promise<any | null> {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bookedCount = await getEventTicketCount(event.id);
|
const counts = await getEventSeatCounts(event.id);
|
||||||
const normalized = normalizeEvent(event);
|
const settings = await getSiteSettingsRow();
|
||||||
return {
|
return withSeatsAndSales(event, normalizeEvent(event, settings), settings, counts);
|
||||||
...normalized,
|
|
||||||
bookedCount,
|
|
||||||
availableSeats: calculateAvailableSeats(normalized.capacity, bookedCount),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get next upcoming event (public) - earliest upcoming published event, ignores featured promotion
|
// Get next upcoming event (public) - earliest upcoming published event, ignores featured promotion
|
||||||
@@ -383,13 +490,10 @@ eventsRouter.get('/next/upcoming', async (c) => {
|
|||||||
|
|
||||||
// If we have a valid featured event, return it
|
// If we have a valid featured event, return it
|
||||||
if (featuredEvent) {
|
if (featuredEvent) {
|
||||||
const bookedCount = await getEventTicketCount(featuredEvent.id);
|
const counts = await getEventSeatCounts(featuredEvent.id);
|
||||||
const normalized = normalizeEvent(featuredEvent);
|
|
||||||
return c.json({
|
return c.json({
|
||||||
event: {
|
event: {
|
||||||
...normalized,
|
...withSeatsAndSales(featuredEvent, normalizeEvent(featuredEvent, settings), settings, counts),
|
||||||
bookedCount,
|
|
||||||
availableSeats: calculateAvailableSeats(normalized.capacity, bookedCount),
|
|
||||||
isFeatured: true,
|
isFeatured: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -411,7 +515,11 @@ eventsRouter.post('/', requireAuth(['admin', 'organizer']), zValidator('json', c
|
|||||||
const user = c.get('user');
|
const user = c.get('user');
|
||||||
const now = getNow();
|
const now = getNow();
|
||||||
const id = generateId();
|
const id = generateId();
|
||||||
const tz = await getSiteTimezone();
|
const siteSettingsRow = await getSiteSettingsRow();
|
||||||
|
const tz = siteTimezoneOf(siteSettingsRow);
|
||||||
|
|
||||||
|
const walkInError = walkInPriceError(data.walkInPrice, data.currency);
|
||||||
|
if (walkInError) return c.json({ error: walkInError }, 400);
|
||||||
|
|
||||||
// Convert data for database compatibility
|
// Convert data for database compatibility
|
||||||
const dbData = convertBooleansForDb(data);
|
const dbData = convertBooleansForDb(data);
|
||||||
@@ -436,11 +544,11 @@ eventsRouter.post('/', requireAuth(['admin', 'organizer']), zValidator('json', c
|
|||||||
revalidateFrontendCache();
|
revalidateFrontendCache();
|
||||||
|
|
||||||
// Return normalized event data
|
// Return normalized event data
|
||||||
return c.json({ event: normalizeEvent(newEvent) }, 201);
|
return c.json({ event: normalizeEvent(newEvent, siteSettingsRow, { includeWalkInPrice: true }) }, 201);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Update event (admin/organizer only)
|
// Update event (admin/organizer only)
|
||||||
eventsRouter.put('/:id', requireAuth(['admin', 'organizer']), zValidator('json', updateEventSchema, validationHook), async (c) => {
|
eventsRouter.put('/:id', requireEventPermission('edit_event', { globalRoles: ['admin', 'organizer'] }), zValidator('json', updateEventSchema, validationHook), async (c) => {
|
||||||
const id = c.req.param('id');
|
const id = c.req.param('id');
|
||||||
const data = c.req.valid('json');
|
const data = c.req.valid('json');
|
||||||
|
|
||||||
@@ -451,8 +559,17 @@ eventsRouter.put('/:id', requireAuth(['admin', 'organizer']), zValidator('json',
|
|||||||
return c.json({ error: 'Event not found' }, 404);
|
return c.json({ error: 'Event not found' }, 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (data.walkInPrice !== undefined || data.currency !== undefined) {
|
||||||
|
const walkInError = walkInPriceError(
|
||||||
|
data.walkInPrice !== undefined ? data.walkInPrice : parseWalkInPrice(existing.walkInPrice),
|
||||||
|
data.currency ?? existing.currency,
|
||||||
|
);
|
||||||
|
if (walkInError) return c.json({ error: walkInError }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
const now = getNow();
|
const now = getNow();
|
||||||
const tz = await getSiteTimezone();
|
const siteSettingsRow = await getSiteSettingsRow();
|
||||||
|
const tz = siteTimezoneOf(siteSettingsRow);
|
||||||
// Convert data for database compatibility
|
// Convert data for database compatibility
|
||||||
const updateData: Record<string, any> = { ...convertBooleansForDb(data), updatedAt: now };
|
const updateData: Record<string, any> = { ...convertBooleansForDb(data), updatedAt: now };
|
||||||
// Slug changes are handled explicitly below to manage aliases
|
// Slug changes are handled explicitly below to manage aliases
|
||||||
@@ -499,10 +616,30 @@ eventsRouter.put('/:id', requireAuth(['admin', 'organizer']), zValidator('json',
|
|||||||
updateData.slug = newSlug;
|
updateData.slug = newSlug;
|
||||||
}
|
}
|
||||||
|
|
||||||
await (db as any)
|
const ops: TxOp[] = [updateOp(events, updateData, eq((events as any).id, id))];
|
||||||
.update(events)
|
|
||||||
.set(updateData)
|
// Anyone who booked but hasn't paid yet owes the current price, so open
|
||||||
.where(eq((events as any).id, id));
|
// payments follow a price/currency change. Settled payments keep what was
|
||||||
|
// actually paid. Excluded: pending_approval (the customer already sent the
|
||||||
|
// old amount), on_hold (under review) and Lightning (the invoice is fixed).
|
||||||
|
const newPrice = data.price !== undefined ? data.price : Number(existing.price);
|
||||||
|
const newCurrency = data.currency ?? existing.currency;
|
||||||
|
if (newPrice !== Number(existing.price) || newCurrency !== existing.currency) {
|
||||||
|
ops.push(updateOp(
|
||||||
|
payments,
|
||||||
|
{ amount: newPrice, currency: newCurrency, updatedAt: now },
|
||||||
|
and(
|
||||||
|
eq((payments as any).status, 'pending'),
|
||||||
|
ne((payments as any).provider, 'lightning'),
|
||||||
|
inArray(
|
||||||
|
(payments as any).ticketId,
|
||||||
|
(db as any).select({ id: (tickets as any).id }).from(tickets).where(eq((tickets as any).eventId, id))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
await runOps(ops);
|
||||||
|
|
||||||
const updated = await dbGet(
|
const updated = await dbGet(
|
||||||
(db as any).select().from(events).where(eq((events as any).id, id))
|
(db as any).select().from(events).where(eq((events as any).id, id))
|
||||||
@@ -511,7 +648,7 @@ eventsRouter.put('/:id', requireAuth(['admin', 'organizer']), zValidator('json',
|
|||||||
// Revalidate sitemap when an event is updated (status/dates may have changed)
|
// Revalidate sitemap when an event is updated (status/dates may have changed)
|
||||||
revalidateFrontendCache();
|
revalidateFrontendCache();
|
||||||
|
|
||||||
return c.json({ event: normalizeEvent(updated) });
|
return c.json({ event: normalizeEvent(updated, siteSettingsRow, { includeWalkInPrice: true }) });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Delete event (admin only)
|
// Delete event (admin only)
|
||||||
@@ -577,17 +714,17 @@ eventsRouter.delete('/:id', requireAuth(['admin']), async (c) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Get event attendees (admin/organizer only)
|
// Get event attendees (admin/organizer only)
|
||||||
eventsRouter.get('/:id/attendees', requireAuth(['admin', 'organizer', 'staff']), async (c) => {
|
eventsRouter.get('/:id/attendees', requireEventPermission('view_attendees_names', { globalRoles: ['admin', 'organizer', 'staff'] }), async (c) => {
|
||||||
const id = c.req.param('id');
|
const id = c.req.param('id');
|
||||||
|
|
||||||
const attendees = await dbAll(
|
const attendees = await dbAll<any>(
|
||||||
(db as any)
|
(db as any)
|
||||||
.select()
|
.select()
|
||||||
.from(tickets)
|
.from(tickets)
|
||||||
.where(eq((tickets as any).eventId, id))
|
.where(eq((tickets as any).eventId, id))
|
||||||
);
|
);
|
||||||
|
|
||||||
return c.json({ attendees });
|
return c.json({ attendees: canSeeAttendeePii(c) ? attendees : attendees.map(redactAttendee) });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Duplicate event (admin/organizer only)
|
// Duplicate event (admin/organizer only)
|
||||||
@@ -622,23 +759,27 @@ eventsRouter.post('/:id/duplicate', requireAuth(['admin', 'organizer']), async (
|
|||||||
location: existing.location,
|
location: existing.location,
|
||||||
locationUrl: existing.locationUrl,
|
locationUrl: existing.locationUrl,
|
||||||
price: existing.price,
|
price: existing.price,
|
||||||
|
walkInPrice: existing.walkInPrice ?? null,
|
||||||
currency: existing.currency,
|
currency: existing.currency,
|
||||||
capacity: existing.capacity,
|
capacity: existing.capacity,
|
||||||
status: 'draft',
|
status: 'draft',
|
||||||
bannerUrl: existing.bannerUrl,
|
bannerUrl: existing.bannerUrl,
|
||||||
externalBookingEnabled: existing.externalBookingEnabled ?? 0, // Already in DB format (0/1)
|
externalBookingEnabled: existing.externalBookingEnabled ?? 0, // Already in DB format (0/1)
|
||||||
externalBookingUrl: existing.externalBookingUrl,
|
externalBookingUrl: existing.externalBookingUrl,
|
||||||
|
presaleClosureEnabled: existing.presaleClosureEnabled ?? null, // Already in DB format (0/1/null)
|
||||||
|
presaleCloseMinutesBefore: existing.presaleCloseMinutesBefore ?? null,
|
||||||
|
series: existing.series ?? null,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
};
|
};
|
||||||
|
|
||||||
await (db as any).insert(events).values(duplicatedEvent);
|
await (db as any).insert(events).values(duplicatedEvent);
|
||||||
|
|
||||||
return c.json({ event: normalizeEvent(duplicatedEvent), message: 'Event duplicated successfully' }, 201);
|
return c.json({ event: normalizeEvent(duplicatedEvent, undefined, { includeWalkInPrice: true }), message: 'Event duplicated successfully' }, 201);
|
||||||
});
|
});
|
||||||
|
|
||||||
// List slug aliases for an event (admin/organizer only)
|
// List slug aliases for an event (admin/organizer only)
|
||||||
eventsRouter.get('/:id/slug-aliases', requireAuth(['admin', 'organizer']), async (c) => {
|
eventsRouter.get('/:id/slug-aliases', requireEventPermission('edit_event', { globalRoles: ['admin', 'organizer'] }), async (c) => {
|
||||||
const id = c.req.param('id');
|
const id = c.req.param('id');
|
||||||
|
|
||||||
const existing = await dbGet<any>(
|
const existing = await dbGet<any>(
|
||||||
@@ -659,7 +800,7 @@ eventsRouter.get('/:id/slug-aliases', requireAuth(['admin', 'organizer']), async
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Remove a slug alias from an event (admin/organizer only)
|
// Remove a slug alias from an event (admin/organizer only)
|
||||||
eventsRouter.delete('/:id/slug-aliases/:slug', requireAuth(['admin', 'organizer']), async (c) => {
|
eventsRouter.delete('/:id/slug-aliases/:slug', requireEventPermission('edit_event', { globalRoles: ['admin', 'organizer'] }), async (c) => {
|
||||||
const id = c.req.param('id');
|
const id = c.req.param('id');
|
||||||
const slug = c.req.param('slug');
|
const slug = c.req.param('slug');
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,245 @@
|
|||||||
|
import { describe, it, expect, beforeAll, vi } from 'vitest';
|
||||||
|
import { execFileSync } from 'child_process';
|
||||||
|
import { mkdtempSync } from 'fs';
|
||||||
|
import { tmpdir } from 'os';
|
||||||
|
import { join } from 'path';
|
||||||
|
|
||||||
|
// The walk-in price is internal: admins set it, door staff charge it, and no
|
||||||
|
// public event response may carry it. These tests pin both halves.
|
||||||
|
|
||||||
|
// Env must be pinned before the db singleton is imported (dotenv never overrides).
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'events-walkin-test-'));
|
||||||
|
const dbPath = join(dir, 'test.db');
|
||||||
|
process.env.DB_TYPE = 'sqlite';
|
||||||
|
process.env.DATABASE_URL = dbPath;
|
||||||
|
process.env.FRONTEND_URL = 'http://localhost:3002';
|
||||||
|
process.env.BETTER_AUTH_SECRET = 'events-test-secret-0123456789abcdef';
|
||||||
|
delete process.env.REDIS_URL;
|
||||||
|
delete process.env.REVALIDATE_SECRET;
|
||||||
|
|
||||||
|
type TestUser = { id: string; name: string; role: string } | null;
|
||||||
|
const ADMIN = { id: 'admin-user-id', name: 'The Admin', role: 'admin' };
|
||||||
|
const STAFF = { id: 'staff-user-id', name: 'Door Staff', role: 'staff' };
|
||||||
|
const MEMBER = { id: 'member-user-id', name: 'Member', role: 'user' };
|
||||||
|
|
||||||
|
// Anonymous by default, like the public site and its server-side fetches.
|
||||||
|
let currentUser: TestUser = null;
|
||||||
|
|
||||||
|
vi.mock('../lib/auth.js', () => ({
|
||||||
|
requireAuth: (roles?: string[]) => async (c: any, next: any) => {
|
||||||
|
if (!currentUser) return c.json({ error: 'Unauthorized' }, 401);
|
||||||
|
if (roles && !roles.includes(currentUser.role)) return c.json({ error: 'Forbidden' }, 403);
|
||||||
|
c.set('user', currentUser);
|
||||||
|
await next();
|
||||||
|
},
|
||||||
|
getAuthUser: async () => currentUser,
|
||||||
|
}));
|
||||||
|
|
||||||
|
async function as<T>(user: TestUser, fn: () => Promise<T>): Promise<T> {
|
||||||
|
const previous = currentUser;
|
||||||
|
currentUser = user;
|
||||||
|
try {
|
||||||
|
return await fn();
|
||||||
|
} finally {
|
||||||
|
currentUser = previous;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let app: any;
|
||||||
|
let sqlite: any;
|
||||||
|
|
||||||
|
async function request(method: string, path: string, body?: unknown) {
|
||||||
|
const res = await app.request(path, {
|
||||||
|
method,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
});
|
||||||
|
return { status: res.status, body: await res.json() };
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseEvent = {
|
||||||
|
title: 'Walk-in Test',
|
||||||
|
description: 'desc',
|
||||||
|
startDatetime: '2099-01-10T20:00',
|
||||||
|
location: 'Asuncion',
|
||||||
|
price: 21000,
|
||||||
|
currency: 'PYG',
|
||||||
|
capacity: 40,
|
||||||
|
status: 'published',
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
execFileSync('npx', ['tsx', 'src/db/migrate.ts'], { env: { ...process.env }, stdio: 'pipe' });
|
||||||
|
|
||||||
|
return (async () => {
|
||||||
|
const { Hono } = await import('hono');
|
||||||
|
const eventsRoutes = (await import('./events.js')).default;
|
||||||
|
app = new Hono();
|
||||||
|
app.route('/api/events', eventsRoutes);
|
||||||
|
|
||||||
|
const Database = (await import('better-sqlite3')).default;
|
||||||
|
sqlite = new Database(dbPath);
|
||||||
|
})();
|
||||||
|
}, 120_000);
|
||||||
|
|
||||||
|
describe('admin event form: walk-in price', () => {
|
||||||
|
it('saves an empty walk-in price as null, not 0', async () => {
|
||||||
|
const { status, body } = await as(ADMIN, () =>
|
||||||
|
request('POST', '/api/events', { ...baseEvent, title: 'Empty walk-in', walkInPrice: '' })
|
||||||
|
);
|
||||||
|
expect(status).toBe(201);
|
||||||
|
expect(body.event.walkInPrice).toBeNull();
|
||||||
|
expect(sqlite.prepare('SELECT walk_in_price FROM events WHERE id = ?').get(body.event.id).walk_in_price).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('saves 0 as a free walk-in and a number as-is', async () => {
|
||||||
|
const free = await as(ADMIN, () =>
|
||||||
|
request('POST', '/api/events', { ...baseEvent, title: 'Free walk-in', walkInPrice: 0 })
|
||||||
|
);
|
||||||
|
expect(free.body.event.walkInPrice).toBe(0);
|
||||||
|
|
||||||
|
const priced = await as(ADMIN, () =>
|
||||||
|
request('POST', '/api/events', { ...baseEvent, title: 'Priced walk-in', walkInPrice: '25000' })
|
||||||
|
);
|
||||||
|
expect(priced.body.event.walkInPrice).toBe(25000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects negative, non-numeric and fractional PYG walk-in prices', async () => {
|
||||||
|
for (const walkInPrice of [-1, 'abc', 25000.5]) {
|
||||||
|
const { status } = await as(ADMIN, () =>
|
||||||
|
request('POST', '/api/events', { ...baseEvent, title: 'Bad walk-in', walkInPrice })
|
||||||
|
);
|
||||||
|
expect(status, `walkInPrice ${walkInPrice}`).toBe(400);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updates and clears the walk-in price, and duplicates carry it over', async () => {
|
||||||
|
const created = await as(ADMIN, () =>
|
||||||
|
request('POST', '/api/events', { ...baseEvent, title: 'Editable walk-in', walkInPrice: 25000 })
|
||||||
|
);
|
||||||
|
const id = created.body.event.id;
|
||||||
|
|
||||||
|
const updated = await as(ADMIN, () => request('PUT', `/api/events/${id}`, { walkInPrice: 30000 }));
|
||||||
|
expect(updated.body.event.walkInPrice).toBe(30000);
|
||||||
|
|
||||||
|
const copy = await as(ADMIN, () => request('POST', `/api/events/${id}/duplicate`));
|
||||||
|
expect(copy.status).toBe(201);
|
||||||
|
expect(copy.body.event.walkInPrice).toBe(30000);
|
||||||
|
|
||||||
|
const cleared = await as(ADMIN, () => request('PUT', `/api/events/${id}`, { walkInPrice: null }));
|
||||||
|
expect(cleared.body.event.walkInPrice).toBeNull();
|
||||||
|
|
||||||
|
// Omitting the field leaves it untouched.
|
||||||
|
await as(ADMIN, () => request('PUT', `/api/events/${id}`, { walkInPrice: 0 }));
|
||||||
|
const untouched = await as(ADMIN, () => request('PUT', `/api/events/${id}`, { capacity: 45 }));
|
||||||
|
expect(untouched.body.event.walkInPrice).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('public event responses', () => {
|
||||||
|
let slug: string;
|
||||||
|
let id: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const { body } = await as(ADMIN, () =>
|
||||||
|
request('POST', '/api/events', { ...baseEvent, title: 'Secret Door Price', walkInPrice: 25000 })
|
||||||
|
);
|
||||||
|
slug = body.event.slug;
|
||||||
|
id = body.event.id;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never include the walk-in price for anonymous or regular users', async () => {
|
||||||
|
for (const user of [null, MEMBER]) {
|
||||||
|
await as(user, async () => {
|
||||||
|
const single = await request('GET', `/api/events/${slug}`);
|
||||||
|
expect(single.status).toBe(200);
|
||||||
|
expect(single.body.event).not.toHaveProperty('walkInPrice');
|
||||||
|
expect(single.body.event.price).toBe(21000);
|
||||||
|
|
||||||
|
const list = await request('GET', '/api/events');
|
||||||
|
const listed = list.body.events.find((e: any) => e.id === id);
|
||||||
|
expect(listed).toBeTruthy();
|
||||||
|
expect(listed).not.toHaveProperty('walkInPrice');
|
||||||
|
|
||||||
|
const next = await request('GET', '/api/events/next/upcoming');
|
||||||
|
expect(next.body.event).not.toHaveProperty('walkInPrice');
|
||||||
|
|
||||||
|
// Belt and braces: the value must not appear anywhere in the payload.
|
||||||
|
expect(JSON.stringify(single.body)).not.toContain('25000');
|
||||||
|
expect(JSON.stringify(list.body)).not.toContain('25000');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes it for admin and door staff', async () => {
|
||||||
|
for (const user of [ADMIN, STAFF]) {
|
||||||
|
const single = await as(user, () => request('GET', `/api/events/${id}`));
|
||||||
|
expect(single.body.event.walkInPrice).toBe(25000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('public sales state and door price', () => {
|
||||||
|
const hours = (n: number) => new Date(Date.now() + n * 3_600_000).toISOString();
|
||||||
|
|
||||||
|
async function createEvent(fields: Record<string, unknown>) {
|
||||||
|
const { status, body } = await as(ADMIN, () =>
|
||||||
|
request('POST', '/api/events', { ...baseEvent, ...fields })
|
||||||
|
);
|
||||||
|
expect(status).toBe(201);
|
||||||
|
return body.event as { id: string; slug: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
it('adds doorPrice only in the door state and never exposes the raw walk-in price', async () => {
|
||||||
|
// Starts in 1h, pre-sale closed 2h before start (site default): door state.
|
||||||
|
const door = await createEvent({
|
||||||
|
title: 'Door State', walkInPrice: 31000, startDatetime: hours(1), endDatetime: hours(4),
|
||||||
|
});
|
||||||
|
// Starts in 3 days: still online.
|
||||||
|
const online = await createEvent({
|
||||||
|
title: 'Online State', walkInPrice: 31000, startDatetime: hours(72), endDatetime: hours(75),
|
||||||
|
});
|
||||||
|
// Already over.
|
||||||
|
const ended = await createEvent({
|
||||||
|
title: 'Ended State', walkInPrice: 31000, startDatetime: hours(-4), endDatetime: hours(-1),
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const user of [null, MEMBER]) {
|
||||||
|
await as(user, async () => {
|
||||||
|
const single = await request('GET', `/api/events/${door.slug}`);
|
||||||
|
expect(single.body.event.salesState).toBe('door');
|
||||||
|
expect(single.body.event.doorPrice).toBe(31000);
|
||||||
|
expect(single.body.event.presaleClosesAt).toEqual(expect.any(String));
|
||||||
|
expect(single.body.event.availableSeats).toBe(40);
|
||||||
|
expect(single.body.event.doorPaymentMethods).toEqual(['cash', 'bitcoin', 'transfer', 'pos']);
|
||||||
|
expect(single.body.event).not.toHaveProperty('walkInPrice');
|
||||||
|
expect(typeof single.body.serverTime).toBe('string');
|
||||||
|
|
||||||
|
for (const other of [online, ended]) {
|
||||||
|
const res = await request('GET', `/api/events/${other.slug}`);
|
||||||
|
expect(res.body.event.salesState).toBe(other === online ? 'online' : 'ended');
|
||||||
|
expect(res.body.event).not.toHaveProperty('doorPrice');
|
||||||
|
expect(res.body.event).not.toHaveProperty('doorPaymentMethods');
|
||||||
|
expect(res.body.event).not.toHaveProperty('walkInPrice');
|
||||||
|
expect(JSON.stringify(res.body)).not.toContain('31000');
|
||||||
|
}
|
||||||
|
|
||||||
|
const list = await request('GET', '/api/events');
|
||||||
|
const byId = new Map(list.body.events.map((e: any) => [e.id, e]));
|
||||||
|
expect((byId.get(door.id) as any).salesState).toBe('door');
|
||||||
|
expect((byId.get(door.id) as any).doorPrice).toBe(31000);
|
||||||
|
expect((byId.get(online.id) as any)).not.toHaveProperty('doorPrice');
|
||||||
|
for (const e of list.body.events) expect(e).not.toHaveProperty('walkInPrice');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to the ticket price when no walk-in price is set', async () => {
|
||||||
|
const door = await createEvent({
|
||||||
|
title: 'Door Fallback', walkInPrice: null, startDatetime: hours(1), endDatetime: hours(4),
|
||||||
|
});
|
||||||
|
const res = await request('GET', `/api/events/${door.slug}`);
|
||||||
|
expect(res.body.event.salesState).toBe('door');
|
||||||
|
expect(res.body.event.doorPrice).toBe(21000);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,407 @@
|
|||||||
|
// Global finance: expense categories, templates, template packs, payment
|
||||||
|
// method fees (Site Settings → Expense Templates) and the cross-event overview.
|
||||||
|
// Mounted at /api/finance.
|
||||||
|
//
|
||||||
|
// Writes are admin only. The read endpoints for categories/templates/packs are
|
||||||
|
// also open to members who can add expenses on the event given as ?eventId=,
|
||||||
|
// so the "Apply template" pickers work for them.
|
||||||
|
|
||||||
|
import { Hono, type Context } from 'hono';
|
||||||
|
import { zValidator } from '@hono/zod-validator';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { and, eq, gte, inArray, lte } from 'drizzle-orm';
|
||||||
|
import {
|
||||||
|
db, dbAll, dbGet, events, expenseCategories, expenseTemplates, expenseTemplatePacks, expenseTemplatePackItems,
|
||||||
|
eventExpenses, paymentMethodFees,
|
||||||
|
} from '../db/index.js';
|
||||||
|
import { requireAuth, type AuthUser } from '../lib/auth.js';
|
||||||
|
import { requireEventPermission, eventFromQuery } from '../lib/eventPermissions.js';
|
||||||
|
import { generateId, getNow, toDbBool, toDbDate } from '../lib/utils.js';
|
||||||
|
import { runOps, insertOp, updateOp, deleteOp, type TxOp } from '../lib/txOps.js';
|
||||||
|
import { financeAuditOp } from '../lib/finance/audit.js';
|
||||||
|
import { getEventFinance, iso, pyg, bool, loadFeeRules } from '../lib/finance/load.js';
|
||||||
|
import { CALC_TYPES } from '../lib/finance/calculate.js';
|
||||||
|
|
||||||
|
const financeGlobalRouter = new Hono();
|
||||||
|
|
||||||
|
const validationHook = (result: any, c: any) => {
|
||||||
|
if (!result.success) {
|
||||||
|
const errors = result.error.issues.map((i: any) => `${i.path.join('.')}: ${i.message}`).join(', ');
|
||||||
|
return c.json({ error: errors }, 400);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const money = z.number().int().min(0).max(2_000_000_000);
|
||||||
|
const bp = z.number().int().min(0).max(10000);
|
||||||
|
const currentUser = (c: Context) => (c as any).get('user') as AuthUser;
|
||||||
|
const ADMIN = requireAuth(['admin']);
|
||||||
|
const TEMPLATE_READERS = requireEventPermission(['edit_expenses', 'edit_own_expenses_only'], { eventId: eventFromQuery() });
|
||||||
|
|
||||||
|
// ==================== Categories ====================
|
||||||
|
|
||||||
|
const serializeCategory = (r: any) => ({
|
||||||
|
id: r.id, nameEn: r.nameEn, nameEs: r.nameEs, color: r.color, sortOrder: pyg(r.sortOrder), archived: bool(r.archived),
|
||||||
|
createdAt: iso(r.createdAt), updatedAt: iso(r.updatedAt),
|
||||||
|
});
|
||||||
|
|
||||||
|
const categorySchema = z.object({
|
||||||
|
nameEn: z.string().trim().min(1).max(100),
|
||||||
|
nameEs: z.string().trim().min(1).max(100),
|
||||||
|
color: z.string().regex(/^#[0-9a-fA-F]{6}$/).default('#6B7280'),
|
||||||
|
sortOrder: z.number().int().min(0).max(10000).default(0),
|
||||||
|
archived: z.boolean().default(false),
|
||||||
|
});
|
||||||
|
|
||||||
|
financeGlobalRouter.get('/settings/expense-categories', TEMPLATE_READERS, async (c) => {
|
||||||
|
const rows = await dbAll<any>((db as any).select().from(expenseCategories));
|
||||||
|
return c.json({ categories: rows.map(serializeCategory).sort((a, b) => a.sortOrder - b.sortOrder) });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeGlobalRouter.post('/settings/expense-categories', ADMIN, zValidator('json', categorySchema, validationHook), async (c) => {
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const now = getNow();
|
||||||
|
const values = { id: generateId(), ...data, archived: toDbBool(data.archived), createdAt: now, updatedAt: now };
|
||||||
|
await runOps([
|
||||||
|
insertOp(expenseCategories, values),
|
||||||
|
financeAuditOp({ eventId: null, actorUserId: currentUser(c).id, entityType: 'expense_category', entityId: values.id, action: 'create', after: serializeCategory(values) }),
|
||||||
|
]);
|
||||||
|
return c.json({ category: serializeCategory(values) }, 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
financeGlobalRouter.put('/settings/expense-categories/:id', ADMIN, zValidator('json', categorySchema.partial(), validationHook), async (c) => {
|
||||||
|
const existing = await dbGet<any>((db as any).select().from(expenseCategories).where(eq((expenseCategories as any).id, c.req.param('id'))));
|
||||||
|
if (!existing) return c.json({ error: 'Category not found' }, 404);
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const updates: Record<string, any> = { ...data, updatedAt: getNow() };
|
||||||
|
if (data.archived !== undefined) updates.archived = toDbBool(data.archived);
|
||||||
|
const after = serializeCategory({ ...existing, ...updates });
|
||||||
|
await runOps([
|
||||||
|
updateOp(expenseCategories, updates, eq((expenseCategories as any).id, existing.id)),
|
||||||
|
financeAuditOp({ eventId: null, actorUserId: currentUser(c).id, entityType: 'expense_category', entityId: existing.id, action: 'update', before: serializeCategory(existing), after }),
|
||||||
|
]);
|
||||||
|
return c.json({ category: after });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeGlobalRouter.delete('/settings/expense-categories/:id', ADMIN, async (c) => {
|
||||||
|
const id = c.req.param('id');
|
||||||
|
const existing = await dbGet<any>((db as any).select().from(expenseCategories).where(eq((expenseCategories as any).id, id)));
|
||||||
|
if (!existing) return c.json({ error: 'Category not found' }, 404);
|
||||||
|
const [usedByExpense, usedByTemplate] = await Promise.all([
|
||||||
|
dbGet<any>((db as any).select({ id: (eventExpenses as any).id }).from(eventExpenses).where(eq((eventExpenses as any).categoryId, id))),
|
||||||
|
dbGet<any>((db as any).select({ id: (expenseTemplates as any).id }).from(expenseTemplates).where(eq((expenseTemplates as any).categoryId, id))),
|
||||||
|
]);
|
||||||
|
if (usedByExpense || usedByTemplate) {
|
||||||
|
return c.json({ error: 'This category is in use. Archive it instead.', code: 'IN_USE' }, 409);
|
||||||
|
}
|
||||||
|
await runOps([
|
||||||
|
deleteOp(expenseCategories, eq((expenseCategories as any).id, id)),
|
||||||
|
financeAuditOp({ eventId: null, actorUserId: currentUser(c).id, entityType: 'expense_category', entityId: id, action: 'delete', before: serializeCategory(existing) }),
|
||||||
|
]);
|
||||||
|
return c.json({ message: 'Category deleted' });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Templates ====================
|
||||||
|
|
||||||
|
const serializeTemplate = (r: any) => ({
|
||||||
|
id: r.id, name: r.name, categoryId: r.categoryId ?? null, description: r.description ?? null, calcType: r.calcType,
|
||||||
|
amount: pyg(r.amount), percentBp: pyg(r.percentBp), minimumAmount: pyg(r.minimumAmount), archived: bool(r.archived),
|
||||||
|
createdAt: iso(r.createdAt), updatedAt: iso(r.updatedAt),
|
||||||
|
});
|
||||||
|
|
||||||
|
const templateSchema = z.object({
|
||||||
|
name: z.string().trim().min(1).max(200),
|
||||||
|
categoryId: z.string().nullable().optional(),
|
||||||
|
description: z.string().trim().max(1000).nullable().optional(),
|
||||||
|
calcType: z.enum(CALC_TYPES),
|
||||||
|
amount: money.default(0),
|
||||||
|
percentBp: bp.default(0),
|
||||||
|
minimumAmount: money.default(0),
|
||||||
|
archived: z.boolean().default(false),
|
||||||
|
});
|
||||||
|
|
||||||
|
async function validCategory(categoryId: string | null | undefined) {
|
||||||
|
if (!categoryId) return true;
|
||||||
|
return !!(await dbGet<any>((db as any).select({ id: (expenseCategories as any).id }).from(expenseCategories).where(eq((expenseCategories as any).id, categoryId))));
|
||||||
|
}
|
||||||
|
|
||||||
|
financeGlobalRouter.get('/settings/expense-templates', TEMPLATE_READERS, async (c) => {
|
||||||
|
const rows = await dbAll<any>((db as any).select().from(expenseTemplates));
|
||||||
|
return c.json({ templates: rows.map(serializeTemplate).sort((a, b) => a.name.localeCompare(b.name)) });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeGlobalRouter.post('/settings/expense-templates', ADMIN, zValidator('json', templateSchema, validationHook), async (c) => {
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
if (!(await validCategory(data.categoryId))) return c.json({ error: 'Unknown expense category' }, 400);
|
||||||
|
const now = getNow();
|
||||||
|
const values = {
|
||||||
|
id: generateId(), ...data, categoryId: data.categoryId || null, description: data.description || null,
|
||||||
|
archived: toDbBool(data.archived), createdAt: now, updatedAt: now,
|
||||||
|
};
|
||||||
|
await runOps([
|
||||||
|
insertOp(expenseTemplates, values),
|
||||||
|
financeAuditOp({ eventId: null, actorUserId: currentUser(c).id, entityType: 'expense_template', entityId: values.id, action: 'create', after: serializeTemplate(values) }),
|
||||||
|
]);
|
||||||
|
return c.json({ template: serializeTemplate(values) }, 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
financeGlobalRouter.put('/settings/expense-templates/:id', ADMIN, zValidator('json', templateSchema.partial(), validationHook), async (c) => {
|
||||||
|
const existing = await dbGet<any>((db as any).select().from(expenseTemplates).where(eq((expenseTemplates as any).id, c.req.param('id'))));
|
||||||
|
if (!existing) return c.json({ error: 'Template not found' }, 404);
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
if (!(await validCategory(data.categoryId))) return c.json({ error: 'Unknown expense category' }, 400);
|
||||||
|
const updates: Record<string, any> = { ...data, updatedAt: getNow() };
|
||||||
|
if (data.archived !== undefined) updates.archived = toDbBool(data.archived);
|
||||||
|
if (data.categoryId === '') updates.categoryId = null;
|
||||||
|
const after = serializeTemplate({ ...existing, ...updates });
|
||||||
|
await runOps([
|
||||||
|
updateOp(expenseTemplates, updates, eq((expenseTemplates as any).id, existing.id)),
|
||||||
|
financeAuditOp({ eventId: null, actorUserId: currentUser(c).id, entityType: 'expense_template', entityId: existing.id, action: 'update', before: serializeTemplate(existing), after }),
|
||||||
|
]);
|
||||||
|
return c.json({ template: after });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeGlobalRouter.delete('/settings/expense-templates/:id', ADMIN, async (c) => {
|
||||||
|
const id = c.req.param('id');
|
||||||
|
const existing = await dbGet<any>((db as any).select().from(expenseTemplates).where(eq((expenseTemplates as any).id, id)));
|
||||||
|
if (!existing) return c.json({ error: 'Template not found' }, 404);
|
||||||
|
const [usedByExpense, usedByPack] = await Promise.all([
|
||||||
|
dbGet<any>((db as any).select({ id: (eventExpenses as any).id }).from(eventExpenses).where(eq((eventExpenses as any).templateId, id))),
|
||||||
|
dbGet<any>((db as any).select({ id: (expenseTemplatePackItems as any).id }).from(expenseTemplatePackItems).where(eq((expenseTemplatePackItems as any).templateId, id))),
|
||||||
|
]);
|
||||||
|
if (usedByExpense || usedByPack) {
|
||||||
|
return c.json({ error: 'This template has been used or is in a pack. Archive it instead.', code: 'IN_USE' }, 409);
|
||||||
|
}
|
||||||
|
await runOps([
|
||||||
|
deleteOp(expenseTemplates, eq((expenseTemplates as any).id, id)),
|
||||||
|
financeAuditOp({ eventId: null, actorUserId: currentUser(c).id, entityType: 'expense_template', entityId: id, action: 'delete', before: serializeTemplate(existing) }),
|
||||||
|
]);
|
||||||
|
return c.json({ message: 'Template deleted' });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Template packs ====================
|
||||||
|
|
||||||
|
const packSchema = z.object({
|
||||||
|
name: z.string().trim().min(1).max(200),
|
||||||
|
description: z.string().trim().max(1000).nullable().optional(),
|
||||||
|
archived: z.boolean().default(false),
|
||||||
|
templateIds: z.array(z.string()).max(50).default([]),
|
||||||
|
});
|
||||||
|
|
||||||
|
async function loadPacks() {
|
||||||
|
const [packs, items] = await Promise.all([
|
||||||
|
dbAll<any>((db as any).select().from(expenseTemplatePacks)),
|
||||||
|
dbAll<any>((db as any).select().from(expenseTemplatePackItems)),
|
||||||
|
]);
|
||||||
|
return packs
|
||||||
|
.map((p: any) => ({
|
||||||
|
id: p.id, name: p.name, description: p.description ?? null, archived: bool(p.archived),
|
||||||
|
templateIds: items.filter((i: any) => i.packId === p.id).sort((a: any, b: any) => pyg(a.sortOrder) - pyg(b.sortOrder)).map((i: any) => i.templateId),
|
||||||
|
createdAt: iso(p.createdAt), updatedAt: iso(p.updatedAt),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function validTemplates(ids: string[]) {
|
||||||
|
if (ids.length === 0) return true;
|
||||||
|
const rows = await dbAll<any>((db as any).select({ id: (expenseTemplates as any).id }).from(expenseTemplates).where(inArray((expenseTemplates as any).id, ids)));
|
||||||
|
return rows.length === new Set(ids).size;
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemOps = (packId: string, templateIds: string[]): TxOp[] =>
|
||||||
|
[...new Set(templateIds)].map((templateId, i) => insertOp(expenseTemplatePackItems, { id: generateId(), packId, templateId, sortOrder: i }));
|
||||||
|
|
||||||
|
financeGlobalRouter.get('/settings/expense-template-packs', TEMPLATE_READERS, async (c) => {
|
||||||
|
return c.json({ packs: await loadPacks() });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeGlobalRouter.post('/settings/expense-template-packs', ADMIN, zValidator('json', packSchema, validationHook), async (c) => {
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
if (!(await validTemplates(data.templateIds))) return c.json({ error: 'Unknown template in pack' }, 400);
|
||||||
|
const now = getNow();
|
||||||
|
const values = { id: generateId(), name: data.name, description: data.description || null, archived: toDbBool(data.archived), createdAt: now, updatedAt: now };
|
||||||
|
await runOps([
|
||||||
|
insertOp(expenseTemplatePacks, values),
|
||||||
|
...itemOps(values.id, data.templateIds),
|
||||||
|
financeAuditOp({ eventId: null, actorUserId: currentUser(c).id, entityType: 'expense_template_pack', entityId: values.id, action: 'create', after: { ...data } }),
|
||||||
|
]);
|
||||||
|
const pack = (await loadPacks()).find((p) => p.id === values.id);
|
||||||
|
return c.json({ pack }, 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
financeGlobalRouter.put('/settings/expense-template-packs/:id', ADMIN, zValidator('json', packSchema.partial(), validationHook), async (c) => {
|
||||||
|
const id = c.req.param('id');
|
||||||
|
const before = (await loadPacks()).find((p) => p.id === id);
|
||||||
|
if (!before) return c.json({ error: 'Pack not found' }, 404);
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
if (data.templateIds && !(await validTemplates(data.templateIds))) return c.json({ error: 'Unknown template in pack' }, 400);
|
||||||
|
const updates: Record<string, any> = { updatedAt: getNow() };
|
||||||
|
if (data.name !== undefined) updates.name = data.name;
|
||||||
|
if (data.description !== undefined) updates.description = data.description || null;
|
||||||
|
if (data.archived !== undefined) updates.archived = toDbBool(data.archived);
|
||||||
|
const ops: TxOp[] = [updateOp(expenseTemplatePacks, updates, eq((expenseTemplatePacks as any).id, id))];
|
||||||
|
if (data.templateIds) {
|
||||||
|
ops.push(deleteOp(expenseTemplatePackItems, eq((expenseTemplatePackItems as any).packId, id)));
|
||||||
|
ops.push(...itemOps(id, data.templateIds));
|
||||||
|
}
|
||||||
|
ops.push(financeAuditOp({ eventId: null, actorUserId: currentUser(c).id, entityType: 'expense_template_pack', entityId: id, action: 'update', before, after: { ...before, ...data } }));
|
||||||
|
await runOps(ops);
|
||||||
|
const pack = (await loadPacks()).find((p) => p.id === id);
|
||||||
|
return c.json({ pack });
|
||||||
|
});
|
||||||
|
|
||||||
|
financeGlobalRouter.delete('/settings/expense-template-packs/:id', ADMIN, async (c) => {
|
||||||
|
const id = c.req.param('id');
|
||||||
|
const before = (await loadPacks()).find((p) => p.id === id);
|
||||||
|
if (!before) return c.json({ error: 'Pack not found' }, 404);
|
||||||
|
await runOps([
|
||||||
|
deleteOp(expenseTemplatePackItems, eq((expenseTemplatePackItems as any).packId, id)),
|
||||||
|
deleteOp(expenseTemplatePacks, eq((expenseTemplatePacks as any).id, id)),
|
||||||
|
financeAuditOp({ eventId: null, actorUserId: currentUser(c).id, entityType: 'expense_template_pack', entityId: id, action: 'delete', before }),
|
||||||
|
]);
|
||||||
|
return c.json({ message: 'Pack deleted' });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Payment method fees ====================
|
||||||
|
|
||||||
|
financeGlobalRouter.get('/settings/payment-fees', ADMIN, async (c) => {
|
||||||
|
return c.json({ fees: await loadFeeRules() });
|
||||||
|
});
|
||||||
|
|
||||||
|
const feeSchema = z.object({ percentBp: bp, fixedAmount: money });
|
||||||
|
const FEE_METHODS = ['tpago', 'bank_transfer', 'lightning', 'cash', 'pos', 'bancard'] as const;
|
||||||
|
|
||||||
|
financeGlobalRouter.put('/settings/payment-fees/:method', ADMIN, zValidator('json', feeSchema, validationHook), async (c) => {
|
||||||
|
const method = c.req.param('method');
|
||||||
|
if (!(FEE_METHODS as readonly string[]).includes(method)) return c.json({ error: 'Unknown payment method' }, 400);
|
||||||
|
const data = c.req.valid('json');
|
||||||
|
const existing = await dbGet<any>((db as any).select().from(paymentMethodFees).where(eq((paymentMethodFees as any).method, method)));
|
||||||
|
const user = currentUser(c);
|
||||||
|
const values = { percentBp: data.percentBp, fixedAmount: data.fixedAmount, updatedAt: getNow(), updatedBy: user.id };
|
||||||
|
await runOps([
|
||||||
|
existing
|
||||||
|
? updateOp(paymentMethodFees, values, eq((paymentMethodFees as any).method, method))
|
||||||
|
: insertOp(paymentMethodFees, { method, ...values }),
|
||||||
|
financeAuditOp({
|
||||||
|
eventId: null, actorUserId: user.id, entityType: 'payment_fee', entityId: method, action: existing ? 'update' : 'create',
|
||||||
|
before: existing ? { percentBp: pyg(existing.percentBp), fixedAmount: pyg(existing.fixedAmount) } : null, after: data,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
return c.json({ fee: { method, ...data } });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==================== Cross-event overview ====================
|
||||||
|
|
||||||
|
type Totals = { events: number; gross: number; fees: number; net: number; expenses: number; profit: number };
|
||||||
|
const emptyTotals = (): Totals => ({ events: 0, gross: 0, fees: 0, net: 0, expenses: 0, profit: 0 });
|
||||||
|
const addTo = (t: Totals, row: Omit<Totals, 'events'>) => {
|
||||||
|
t.events += 1; t.gross += row.gross; t.fees += row.fees; t.net += row.net; t.expenses += row.expenses; t.profit += row.profit;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Profit per event, per series, per venue and payouts per partner. Finalized
|
||||||
|
* events use their snapshot. `readyToClose` lists past events whose books are
|
||||||
|
* still open (with or without any money recorded), longest-waiting first. Filters: from / to (ISO dates on the event start),
|
||||||
|
* series, venue (exact location text), partner (user id or external name).
|
||||||
|
*/
|
||||||
|
financeGlobalRouter.get('/overview', ADMIN, async (c) => {
|
||||||
|
const isDate = (v?: string) => (v && /^\d{4}-\d{2}-\d{2}$/.test(v) ? v : undefined);
|
||||||
|
const from = isDate(c.req.query('from'));
|
||||||
|
const to = isDate(c.req.query('to'));
|
||||||
|
const seriesFilter = c.req.query('series');
|
||||||
|
const venueFilter = c.req.query('venue');
|
||||||
|
const partnerFilter = c.req.query('partner');
|
||||||
|
|
||||||
|
const conditions: any[] = [];
|
||||||
|
if (from) conditions.push(gte((events as any).startDatetime, toDbDate(from)));
|
||||||
|
if (to) conditions.push(lte((events as any).startDatetime, toDbDate(`${to}T23:59:59.999Z`)));
|
||||||
|
const allEvents = await dbAll<any>(
|
||||||
|
(db as any).select().from(events).where(conditions.length ? and(...conditions) : undefined)
|
||||||
|
);
|
||||||
|
|
||||||
|
const rows: any[] = [];
|
||||||
|
const seriesOptions = new Set<string>();
|
||||||
|
const venueOptions = new Set<string>();
|
||||||
|
const partnerOptions = new Map<string, string>();
|
||||||
|
const bySeries = new Map<string, Totals>();
|
||||||
|
const byVenue = new Map<string, Totals>();
|
||||||
|
const byPartner = new Map<string, { key: string; name: string; userId: string | null; events: number; share: number; reimbursement: number; payout: number; paid: number; pending: number }>();
|
||||||
|
const totals = emptyTotals();
|
||||||
|
// Past events whose books are still open, including ones with no money in
|
||||||
|
// or out yet (those are left out of `events` and the totals).
|
||||||
|
const readyToClose: any[] = [];
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
for (const ev of allEvents) {
|
||||||
|
if (ev.status === 'draft') continue;
|
||||||
|
const fin = await getEventFinance(ev.id, ev);
|
||||||
|
if (!fin) continue;
|
||||||
|
const r = fin.result;
|
||||||
|
const hasMoney = !(r.revenue.gross === 0 && r.expenses.total === 0 && r.revenue.otherIncome === 0 && fin.partners.length === 0);
|
||||||
|
const ended = new Date(ev.endDatetime || ev.startDatetime).getTime() <= now;
|
||||||
|
const ready = fin.state.status === 'open' && ended;
|
||||||
|
// Nothing to report for events with no money in or out, unless they still need closing.
|
||||||
|
if (!hasMoney && !ready) continue;
|
||||||
|
|
||||||
|
const series = ev.series || null;
|
||||||
|
const venue = (ev.location || '').trim();
|
||||||
|
const partnerKeys = fin.partners.map((p) => p.userId || `name:${p.name}`);
|
||||||
|
if (hasMoney) {
|
||||||
|
if (series) seriesOptions.add(series);
|
||||||
|
if (venue) venueOptions.add(venue);
|
||||||
|
fin.partners.forEach((p, i) => partnerOptions.set(partnerKeys[i], p.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (seriesFilter && (seriesFilter === '__none__' ? series !== null : series !== seriesFilter)) continue;
|
||||||
|
if (venueFilter && venue !== venueFilter) continue;
|
||||||
|
if (partnerFilter && !partnerKeys.includes(partnerFilter)) continue;
|
||||||
|
|
||||||
|
const row = { gross: r.revenue.gross, fees: r.revenue.fees, net: r.revenue.net, expenses: r.expenses.total, profit: r.profit };
|
||||||
|
const eventRow = {
|
||||||
|
id: ev.id, title: ev.title, titleEs: ev.titleEs ?? null, startDatetime: iso(ev.startDatetime),
|
||||||
|
endDatetime: ev.endDatetime ? iso(ev.endDatetime) : null, series, location: venue,
|
||||||
|
status: ev.status, financeStatus: fin.state.status, ticketsSold: r.counts.ticketsSold, ...row,
|
||||||
|
organization: r.split.organization,
|
||||||
|
};
|
||||||
|
if (ready) readyToClose.push(eventRow);
|
||||||
|
if (!hasMoney) continue;
|
||||||
|
rows.push(eventRow);
|
||||||
|
addTo(totals, row);
|
||||||
|
const sKey = series || '';
|
||||||
|
if (!bySeries.has(sKey)) bySeries.set(sKey, emptyTotals());
|
||||||
|
addTo(bySeries.get(sKey)!, row);
|
||||||
|
if (!byVenue.has(venue)) byVenue.set(venue, emptyTotals());
|
||||||
|
addTo(byVenue.get(venue)!, row);
|
||||||
|
|
||||||
|
fin.partners.forEach((p, i) => {
|
||||||
|
const key = partnerKeys[i];
|
||||||
|
const line = r.split.partners.find((x) => x.partnerId === p.id);
|
||||||
|
const agg = byPartner.get(key) || { key, name: p.name, userId: p.userId, events: 0, share: 0, reimbursement: 0, payout: 0, paid: 0, pending: 0 };
|
||||||
|
agg.events += 1;
|
||||||
|
agg.share += line?.share ?? 0;
|
||||||
|
agg.reimbursement += line?.reimbursement ?? 0;
|
||||||
|
agg.payout += line?.payout ?? 0;
|
||||||
|
if (p.payoutStatus === 'paid') agg.paid += line?.payout ?? 0; else agg.pending += line?.payout ?? 0;
|
||||||
|
byPartner.set(key, agg);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
rows.sort((a, b) => (b.startDatetime || '').localeCompare(a.startDatetime || ''));
|
||||||
|
// Longest-waiting first.
|
||||||
|
readyToClose.sort((a, b) => (a.startDatetime || '').localeCompare(b.startDatetime || ''));
|
||||||
|
const sortByProfit = <T extends { profit: number }>(xs: T[]) => xs.sort((a, b) => b.profit - a.profit);
|
||||||
|
return c.json({
|
||||||
|
totals,
|
||||||
|
events: rows,
|
||||||
|
readyToClose,
|
||||||
|
bySeries: sortByProfit([...bySeries.entries()].map(([series, t]) => ({ series: series || null, ...t }))),
|
||||||
|
byVenue: sortByProfit([...byVenue.entries()].map(([venue, t]) => ({ venue, ...t }))),
|
||||||
|
byPartner: [...byPartner.values()].sort((a, b) => b.payout - a.payout),
|
||||||
|
filters: {
|
||||||
|
series: [...seriesOptions].sort(),
|
||||||
|
venues: [...venueOptions].sort(),
|
||||||
|
partners: [...partnerOptions.entries()].map(([key, name]) => ({ key, name })).sort((a, b) => a.name.localeCompare(b.name)),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
export default financeGlobalRouter;
|
||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
} from '../lib/lnbits.js';
|
} from '../lib/lnbits.js';
|
||||||
import emailService from '../lib/email.js';
|
import emailService from '../lib/email.js';
|
||||||
import { getPubSub } from '../lib/stores/pubsub.js';
|
import { getPubSub } from '../lib/stores/pubsub.js';
|
||||||
import { getLock } from '../lib/stores/lock.js';
|
import { getLock, LockUnavailableError } from '../lib/stores/lock.js';
|
||||||
|
|
||||||
const lnbitsRouter = new Hono();
|
const lnbitsRouter = new Hono();
|
||||||
|
|
||||||
@@ -106,12 +106,26 @@ async function startBackgroundChecker(ticketId: string, paymentHash: string, exp
|
|||||||
|
|
||||||
const expiryMs = expirySeconds * 1000;
|
const expiryMs = expirySeconds * 1000;
|
||||||
|
|
||||||
const lockToken = await getLock().acquire(`checker:${ticketId}`, expiryMs);
|
let lockToken: string | null = null;
|
||||||
if (!lockToken) {
|
let lockUnavailable = false;
|
||||||
|
try {
|
||||||
|
lockToken = await getLock().acquire(`checker:${ticketId}`, expiryMs);
|
||||||
|
} catch (err) {
|
||||||
|
if (!(err instanceof LockUnavailableError)) throw err;
|
||||||
|
// Fail open: in webhook-less deployments this poller is the only way a
|
||||||
|
// Lightning payment gets confirmed, so a Redis outage must not stop it.
|
||||||
|
// Duplicate pollers across replicas are harmless because
|
||||||
|
// handlePaymentComplete only acts on rows it actually transitions.
|
||||||
|
console.warn(`[lnbits] lock backend unavailable, polling ticket ${ticketId} without lock:`, err.message);
|
||||||
|
lockUnavailable = true;
|
||||||
|
}
|
||||||
|
if (!lockToken && !lockUnavailable) {
|
||||||
// Another instance is already polling this ticket.
|
// Another instance is already polling this ticket.
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (lockToken) {
|
||||||
checkerLockTokens.set(ticketId, lockToken);
|
checkerLockTokens.set(ticketId, lockToken);
|
||||||
|
}
|
||||||
|
|
||||||
const startTime = Date.now();
|
const startTime = Date.now();
|
||||||
let checkCount = 0;
|
let checkCount = 0;
|
||||||
@@ -270,11 +284,13 @@ async function handlePaymentComplete(ticketId: string, paymentHash: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Confirm all tickets in the booking (idempotent: only flip pending -> confirmed)
|
// Confirm all tickets in the booking (idempotent: only flip pending -> confirmed)
|
||||||
|
let transitioned = 0;
|
||||||
for (const ticket of ticketsToConfirm) {
|
for (const ticket of ticketsToConfirm) {
|
||||||
await (db as any)
|
const result: any = await (db as any)
|
||||||
.update(tickets)
|
.update(tickets)
|
||||||
.set({ status: 'confirmed' })
|
.set({ status: 'confirmed', paymentStatus: 'paid' })
|
||||||
.where(and(eq((tickets as any).id, ticket.id), eq((tickets as any).status, 'pending')));
|
.where(and(eq((tickets as any).id, ticket.id), eq((tickets as any).status, 'pending')));
|
||||||
|
transitioned += result?.changes ?? result?.rowCount ?? 0;
|
||||||
|
|
||||||
await (db as any)
|
await (db as any)
|
||||||
.update(payments)
|
.update(payments)
|
||||||
@@ -289,6 +305,14 @@ async function handlePaymentComplete(ticketId: string, paymentHash: string) {
|
|||||||
console.log(`Ticket ${ticket.id} confirmed via Lightning payment (hash: ${paymentHash})`);
|
console.log(`Ticket ${ticket.id} confirmed via Lightning payment (hash: ${paymentHash})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Only the caller that actually flipped rows sends the emails. The webhook
|
||||||
|
// and the background poller (and pollers on multiple replicas during a Redis
|
||||||
|
// outage) can all land here; without this guard they would each email.
|
||||||
|
if (transitioned === 0) {
|
||||||
|
console.log(`Ticket ${ticketId} was already confirmed by a concurrent caller, skipping emails`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Get primary payment for sending receipt
|
// Get primary payment for sending receipt
|
||||||
const payment = await dbGet<any>(
|
const payment = await dbGet<any>(
|
||||||
(db as any)
|
(db as any)
|
||||||
@@ -372,8 +396,7 @@ lnbitsRouter.get('/stream/:ticketId', async (c) => {
|
|||||||
}
|
}
|
||||||
}, 15000);
|
}, 15000);
|
||||||
|
|
||||||
// Clean up on disconnect
|
const cleanup = () => {
|
||||||
stream.onAbort(() => {
|
|
||||||
clearInterval(heartbeat);
|
clearInterval(heartbeat);
|
||||||
const connections = activeConnections.get(ticketId);
|
const connections = activeConnections.get(ticketId);
|
||||||
if (connections) {
|
if (connections) {
|
||||||
@@ -388,11 +411,28 @@ lnbitsRouter.get('/stream/:ticketId', async (c) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
|
|
||||||
// Keep the stream open
|
// Clean up on disconnect
|
||||||
|
stream.onAbort(cleanup);
|
||||||
|
|
||||||
|
// Keep the stream open, and every 15s fall back to reading the ticket
|
||||||
|
// status from the DB. Pub/sub is best-effort: a message published while the
|
||||||
|
// subscriber connection was reconnecting is lost, and without this check
|
||||||
|
// the client would wait forever on a payment that already confirmed.
|
||||||
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
await stream.sleep(30000);
|
await stream.sleep(15000);
|
||||||
|
const current = await dbGet<any>(
|
||||||
|
(db as any).select().from(tickets).where(eq((tickets as any).id, ticketId))
|
||||||
|
);
|
||||||
|
if (current?.status === 'confirmed') {
|
||||||
|
await sendEvent({ type: 'paid', ticketId });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
cleanup();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { z } from 'zod';
|
|||||||
import { db, dbGet, paymentOptions, eventPaymentOverrides, events, tickets } from '../db/index.js';
|
import { db, dbGet, paymentOptions, eventPaymentOverrides, events, tickets } from '../db/index.js';
|
||||||
import { eq } from 'drizzle-orm';
|
import { eq } from 'drizzle-orm';
|
||||||
import { requireAuth, getAuthUser } from '../lib/auth.js';
|
import { requireAuth, getAuthUser } from '../lib/auth.js';
|
||||||
|
import { requireEventPermission, eventFromParam } from '../lib/eventPermissions.js';
|
||||||
import { generateId, getNow, convertBooleansForDb } from '../lib/utils.js';
|
import { generateId, getNow, convertBooleansForDb } from '../lib/utils.js';
|
||||||
|
|
||||||
const paymentOptionsRouter = new Hono();
|
const paymentOptionsRouter = new Hono();
|
||||||
@@ -36,6 +37,8 @@ const updatePaymentOptionsSchema = z.object({
|
|||||||
cashEnabled: booleanOrNumber.optional(),
|
cashEnabled: booleanOrNumber.optional(),
|
||||||
cashInstructions: z.string().optional().nullable(),
|
cashInstructions: z.string().optional().nullable(),
|
||||||
cashInstructionsEs: z.string().optional().nullable(),
|
cashInstructionsEs: z.string().optional().nullable(),
|
||||||
|
// POS terminal on the door screen
|
||||||
|
posEnabled: booleanOrNumber.optional(),
|
||||||
// Booking settings
|
// Booking settings
|
||||||
allowDuplicateBookings: booleanOrNumber.optional(),
|
allowDuplicateBookings: booleanOrNumber.optional(),
|
||||||
});
|
});
|
||||||
@@ -79,6 +82,7 @@ const updateEventOverridesSchema = z.object({
|
|||||||
cashEnabled: booleanOrNumber.optional().nullable(),
|
cashEnabled: booleanOrNumber.optional().nullable(),
|
||||||
cashInstructions: z.string().optional().nullable(),
|
cashInstructions: z.string().optional().nullable(),
|
||||||
cashInstructionsEs: z.string().optional().nullable(),
|
cashInstructionsEs: z.string().optional().nullable(),
|
||||||
|
posEnabled: booleanOrNumber.optional().nullable(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get global payment options
|
// Get global payment options
|
||||||
@@ -111,6 +115,7 @@ paymentOptionsRouter.get('/', requireAuth(['admin']), async (c) => {
|
|||||||
cashEnabled: true,
|
cashEnabled: true,
|
||||||
cashInstructions: null,
|
cashInstructions: null,
|
||||||
cashInstructionsEs: null,
|
cashInstructionsEs: null,
|
||||||
|
posEnabled: true,
|
||||||
allowDuplicateBookings: false,
|
allowDuplicateBookings: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -219,6 +224,7 @@ paymentOptionsRouter.get('/event/:eventId', async (c) => {
|
|||||||
cashEnabled: true,
|
cashEnabled: true,
|
||||||
cashInstructions: null,
|
cashInstructions: null,
|
||||||
cashInstructionsEs: null,
|
cashInstructionsEs: null,
|
||||||
|
posEnabled: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
const global = globalOptions || defaults;
|
const global = globalOptions || defaults;
|
||||||
@@ -245,6 +251,7 @@ paymentOptionsRouter.get('/event/:eventId', async (c) => {
|
|||||||
cashEnabled: overrides?.cashEnabled ?? global.cashEnabled,
|
cashEnabled: overrides?.cashEnabled ?? global.cashEnabled,
|
||||||
cashInstructions: overrides?.cashInstructions ?? global.cashInstructions,
|
cashInstructions: overrides?.cashInstructions ?? global.cashInstructions,
|
||||||
cashInstructionsEs: overrides?.cashInstructionsEs ?? global.cashInstructionsEs,
|
cashInstructionsEs: overrides?.cashInstructionsEs ?? global.cashInstructionsEs,
|
||||||
|
posEnabled: overrides?.posEnabled ?? global.posEnabled ?? true,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Full bank/TPago credentials are only returned when the caller proves they hold
|
// Full bank/TPago credentials are only returned when the caller proves they hold
|
||||||
@@ -270,7 +277,7 @@ paymentOptionsRouter.get('/event/:eventId', async (c) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Get event payment overrides (admin only)
|
// Get event payment overrides (admin only)
|
||||||
paymentOptionsRouter.get('/event/:eventId/overrides', requireAuth(['admin', 'organizer']), async (c) => {
|
paymentOptionsRouter.get('/event/:eventId/overrides', requireEventPermission('view_payments', { globalRoles: ['admin', 'organizer'], eventId: eventFromParam('eventId') }), async (c) => {
|
||||||
const eventId = c.req.param('eventId');
|
const eventId = c.req.param('eventId');
|
||||||
|
|
||||||
const overrides = await dbGet<any>(
|
const overrides = await dbGet<any>(
|
||||||
@@ -281,7 +288,7 @@ paymentOptionsRouter.get('/event/:eventId/overrides', requireAuth(['admin', 'org
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Update event payment overrides
|
// Update event payment overrides
|
||||||
paymentOptionsRouter.put('/event/:eventId/overrides', requireAuth(['admin', 'organizer']), zValidator('json', updateEventOverridesSchema), async (c) => {
|
paymentOptionsRouter.put('/event/:eventId/overrides', requireEventPermission('edit_event', { globalRoles: ['admin', 'organizer'], eventId: eventFromParam('eventId') }), zValidator('json', updateEventOverridesSchema), async (c) => {
|
||||||
const eventId = c.req.param('eventId');
|
const eventId = c.req.param('eventId');
|
||||||
const data = c.req.valid('json');
|
const data = c.req.valid('json');
|
||||||
const now = getNow();
|
const now = getNow();
|
||||||
@@ -333,7 +340,7 @@ paymentOptionsRouter.put('/event/:eventId/overrides', requireAuth(['admin', 'org
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Delete event payment overrides (revert to global)
|
// Delete event payment overrides (revert to global)
|
||||||
paymentOptionsRouter.delete('/event/:eventId/overrides', requireAuth(['admin', 'organizer']), async (c) => {
|
paymentOptionsRouter.delete('/event/:eventId/overrides', requireEventPermission('edit_event', { globalRoles: ['admin', 'organizer'], eventId: eventFromParam('eventId') }), async (c) => {
|
||||||
const eventId = c.req.param('eventId');
|
const eventId = c.req.param('eventId');
|
||||||
|
|
||||||
await (db as any)
|
await (db as any)
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ const updatePaymentSchema = z.object({
|
|||||||
const approvePaymentSchema = z.object({
|
const approvePaymentSchema = z.object({
|
||||||
adminNote: z.string().optional(),
|
adminNote: z.string().optional(),
|
||||||
sendEmail: z.boolean().optional().default(true),
|
sendEmail: z.boolean().optional().default(true),
|
||||||
|
// Admin override: confirm the booking even when it puts the event over
|
||||||
|
// capacity. The UI asks for explicit confirmation before sending this.
|
||||||
|
allowOverCapacity: z.boolean().optional().default(false),
|
||||||
});
|
});
|
||||||
|
|
||||||
const rejectPaymentSchema = z.object({
|
const rejectPaymentSchema = z.object({
|
||||||
@@ -285,7 +288,7 @@ paymentsRouter.put('/:id', requireAuth(['admin', 'organizer']), zValidator('json
|
|||||||
|
|
||||||
await (db as any)
|
await (db as any)
|
||||||
.update(tickets)
|
.update(tickets)
|
||||||
.set({ status: 'confirmed' })
|
.set({ status: 'confirmed', paymentStatus: 'paid' })
|
||||||
.where(eq((tickets as any).id, (t as any).id));
|
.where(eq((tickets as any).id, (t as any).id));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -317,7 +320,7 @@ paymentsRouter.put('/:id', requireAuth(['admin', 'organizer']), zValidator('json
|
|||||||
// Approve payment (admin) - specifically for pending_approval payments
|
// Approve payment (admin) - specifically for pending_approval payments
|
||||||
paymentsRouter.post('/:id/approve', requireAuth(['admin', 'organizer']), zValidator('json', approvePaymentSchema), async (c) => {
|
paymentsRouter.post('/:id/approve', requireAuth(['admin', 'organizer']), zValidator('json', approvePaymentSchema), async (c) => {
|
||||||
const id = c.req.param('id');
|
const id = c.req.param('id');
|
||||||
const { adminNote, sendEmail } = c.req.valid('json');
|
const { adminNote, sendEmail, allowOverCapacity } = c.req.valid('json');
|
||||||
const user = (c as any).get('user');
|
const user = (c as any).get('user');
|
||||||
|
|
||||||
const payment = await dbGet<any>(
|
const payment = await dbGet<any>(
|
||||||
@@ -334,12 +337,11 @@ paymentsRouter.post('/:id/approve', requireAuth(['admin', 'organizer']), zValida
|
|||||||
// Can approve pending, pending_approval, on_hold, or failed payments.
|
// Can approve pending, pending_approval, on_hold, or failed payments.
|
||||||
// 'failed' covers an admin confirming a payment that was auto-failed or rejected
|
// 'failed' covers an admin confirming a payment that was auto-failed or rejected
|
||||||
// in error; its tickets are cancelled, so recovery re-checks capacity below.
|
// in error; its tickets are cancelled, so recovery re-checks capacity below.
|
||||||
|
// Bare 'pending' covers customers who paid but never clicked "I've paid".
|
||||||
if (!['pending', 'pending_approval', 'on_hold', 'failed'].includes(payment.status)) {
|
if (!['pending', 'pending_approval', 'on_hold', 'failed'].includes(payment.status)) {
|
||||||
return c.json({ error: 'Payment cannot be approved in its current state' }, 400);
|
return c.json({ error: 'Payment cannot be approved in its current state' }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
const now = getNow();
|
|
||||||
|
|
||||||
// Get the ticket associated with this payment
|
// Get the ticket associated with this payment
|
||||||
const ticket = await dbGet<any>(
|
const ticket = await dbGet<any>(
|
||||||
(db as any)
|
(db as any)
|
||||||
@@ -381,9 +383,11 @@ paymentsRouter.post('/:id/approve', requireAuth(['admin', 'organizer']), zValida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payment.status === 'on_hold' || payment.status === 'failed') {
|
// Confirm the booking through the shared capacity-checked reservation.
|
||||||
// The seat was released when this booking went on hold or failed - re-check
|
// Tickets that already hold a seat ('pending_approval' claims) cost no new
|
||||||
// capacity before confirming it directly.
|
// capacity; unseated ones (bare 'pending', on_hold, failed/cancelled) do.
|
||||||
|
// When the event is full, the admin gets a structured over-capacity error and
|
||||||
|
// may retry with allowOverCapacity to knowingly overbook.
|
||||||
try {
|
try {
|
||||||
await reserveOnHoldBooking(
|
await reserveOnHoldBooking(
|
||||||
ticket.eventId,
|
ticket.eventId,
|
||||||
@@ -393,44 +397,22 @@ paymentsRouter.post('/:id/approve', requireAuth(['admin', 'organizer']), zValida
|
|||||||
{
|
{
|
||||||
paidByAdminId: user.id,
|
paidByAdminId: user.id,
|
||||||
fromTicketStatuses:
|
fromTicketStatuses:
|
||||||
payment.status === 'failed' ? ['cancelled', 'on_hold', 'pending'] : ['on_hold'],
|
payment.status === 'failed' ? ['cancelled', 'on_hold', 'pending'] : ['on_hold', 'pending'],
|
||||||
|
skipCapacityCheck: allowOverCapacity,
|
||||||
|
...(adminNote ? { extraPaymentFields: { adminNote } } : {}),
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof HoldCapacityError) {
|
if (err instanceof HoldCapacityError) {
|
||||||
return c.json({
|
return c.json({
|
||||||
error: 'This event is now full. Your spot was released after the payment deadline passed.',
|
error: 'Approving this payment puts the event over capacity.',
|
||||||
}, 400);
|
code: 'EVENT_OVER_CAPACITY',
|
||||||
|
availableSeats: err.available,
|
||||||
|
requestedSeats: ticketsToConfirm.length,
|
||||||
|
}, 409);
|
||||||
}
|
}
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
if (adminNote) {
|
|
||||||
await (db as any)
|
|
||||||
.update(payments)
|
|
||||||
.set({ adminNote })
|
|
||||||
.where(inArray((payments as any).ticketId, ticketsToConfirm.map((t: any) => t.id)));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Update all payments in the booking to paid
|
|
||||||
for (const t of ticketsToConfirm) {
|
|
||||||
await (db as any)
|
|
||||||
.update(payments)
|
|
||||||
.set({
|
|
||||||
status: 'paid',
|
|
||||||
paidAt: now,
|
|
||||||
paidByAdminId: user.id,
|
|
||||||
adminNote: adminNote || payment.adminNote,
|
|
||||||
updatedAt: now,
|
|
||||||
})
|
|
||||||
.where(eq((payments as any).ticketId, (t as any).id));
|
|
||||||
|
|
||||||
// Update ticket status to confirmed
|
|
||||||
await (db as any)
|
|
||||||
.update(tickets)
|
|
||||||
.set({ status: 'confirmed' })
|
|
||||||
.where(eq((tickets as any).id, (t as any).id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send confirmation emails asynchronously (if sendEmail is true, which is the default)
|
// Send confirmation emails asynchronously (if sendEmail is true, which is the default)
|
||||||
if (sendEmail !== false) {
|
if (sendEmail !== false) {
|
||||||
@@ -685,7 +667,7 @@ paymentsRouter.post('/:id/send-reminder', requireAuth(['admin', 'organizer']), a
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await emailService.sendPaymentReminder(id);
|
const result = await emailService.sendPaymentReminder(payment.id);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
const now = getNow();
|
const now = getNow();
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { eq, and, gte } from 'drizzle-orm';
|
|||||||
import { requireAuth } from '../lib/auth.js';
|
import { requireAuth } from '../lib/auth.js';
|
||||||
import { generateId, getNow, toDbBool } from '../lib/utils.js';
|
import { generateId, getNow, toDbBool } from '../lib/utils.js';
|
||||||
import { revalidateFrontendCache } from '../lib/revalidate.js';
|
import { revalidateFrontendCache } from '../lib/revalidate.js';
|
||||||
|
import { DEFAULT_PRESALE_CLOSURE_ENABLED, DEFAULT_PRESALE_CLOSE_MINUTES } from '../lib/presale.js';
|
||||||
|
|
||||||
interface UserContext {
|
interface UserContext {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -43,8 +44,26 @@ const updateSiteSettingsSchema = z.object({
|
|||||||
maintenanceMode: z.boolean().optional(),
|
maintenanceMode: z.boolean().optional(),
|
||||||
maintenanceMessage: z.string().optional().nullable(),
|
maintenanceMessage: z.string().optional().nullable(),
|
||||||
maintenanceMessageEs: z.string().optional().nullable(),
|
maintenanceMessageEs: z.string().optional().nullable(),
|
||||||
|
// Pre-sale closure defaults inherited by events that don't override them
|
||||||
|
presaleClosureEnabled: z.boolean().optional(),
|
||||||
|
presaleCloseMinutesBefore: z.number().int().min(0).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Booleans are stored as 0/1 integers on PostgreSQL; hand the frontend real booleans.
|
||||||
|
function normalizeSettings(row: any) {
|
||||||
|
if (!row) return row;
|
||||||
|
return {
|
||||||
|
...row,
|
||||||
|
maintenanceMode: Boolean(row.maintenanceMode),
|
||||||
|
presaleClosureEnabled: row.presaleClosureEnabled == null
|
||||||
|
? DEFAULT_PRESALE_CLOSURE_ENABLED
|
||||||
|
: Boolean(row.presaleClosureEnabled),
|
||||||
|
presaleCloseMinutesBefore: row.presaleCloseMinutesBefore == null
|
||||||
|
? DEFAULT_PRESALE_CLOSE_MINUTES
|
||||||
|
: Number(row.presaleCloseMinutesBefore),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Get site settings (public - needed for frontend timezone)
|
// Get site settings (public - needed for frontend timezone)
|
||||||
siteSettingsRouter.get('/', async (c) => {
|
siteSettingsRouter.get('/', async (c) => {
|
||||||
const settings = await dbGet(
|
const settings = await dbGet(
|
||||||
@@ -69,11 +88,13 @@ siteSettingsRouter.get('/', async (c) => {
|
|||||||
maintenanceMode: false,
|
maintenanceMode: false,
|
||||||
maintenanceMessage: null,
|
maintenanceMessage: null,
|
||||||
maintenanceMessageEs: null,
|
maintenanceMessageEs: null,
|
||||||
|
presaleClosureEnabled: DEFAULT_PRESALE_CLOSURE_ENABLED,
|
||||||
|
presaleCloseMinutesBefore: DEFAULT_PRESALE_CLOSE_MINUTES,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.json({ settings });
|
return c.json({ settings: normalizeSettings(settings) });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get available timezones
|
// Get available timezones
|
||||||
@@ -145,13 +166,15 @@ siteSettingsRouter.put('/', requireAuth(['admin']), zValidator('json', updateSit
|
|||||||
maintenanceMode: toDbBool(data.maintenanceMode || false),
|
maintenanceMode: toDbBool(data.maintenanceMode || false),
|
||||||
maintenanceMessage: data.maintenanceMessage || null,
|
maintenanceMessage: data.maintenanceMessage || null,
|
||||||
maintenanceMessageEs: data.maintenanceMessageEs || null,
|
maintenanceMessageEs: data.maintenanceMessageEs || null,
|
||||||
|
presaleClosureEnabled: toDbBool(data.presaleClosureEnabled ?? DEFAULT_PRESALE_CLOSURE_ENABLED),
|
||||||
|
presaleCloseMinutesBefore: data.presaleCloseMinutesBefore ?? DEFAULT_PRESALE_CLOSE_MINUTES,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
updatedBy: user.id,
|
updatedBy: user.id,
|
||||||
};
|
};
|
||||||
|
|
||||||
await (db as any).insert(siteSettings).values(newSettings);
|
await (db as any).insert(siteSettings).values(newSettings);
|
||||||
|
|
||||||
return c.json({ settings: newSettings, message: 'Settings created successfully' }, 201);
|
return c.json({ settings: normalizeSettings(newSettings), message: 'Settings created successfully' }, 201);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate featured event if provided
|
// Validate featured event if provided
|
||||||
@@ -174,6 +197,9 @@ siteSettingsRouter.put('/', requireAuth(['admin']), zValidator('json', updateSit
|
|||||||
if (typeof data.maintenanceMode === 'boolean') {
|
if (typeof data.maintenanceMode === 'boolean') {
|
||||||
updateData.maintenanceMode = toDbBool(data.maintenanceMode);
|
updateData.maintenanceMode = toDbBool(data.maintenanceMode);
|
||||||
}
|
}
|
||||||
|
if (typeof data.presaleClosureEnabled === 'boolean') {
|
||||||
|
updateData.presaleClosureEnabled = toDbBool(data.presaleClosureEnabled);
|
||||||
|
}
|
||||||
|
|
||||||
await (db as any)
|
await (db as any)
|
||||||
.update(siteSettings)
|
.update(siteSettings)
|
||||||
@@ -184,12 +210,17 @@ siteSettingsRouter.put('/', requireAuth(['admin']), zValidator('json', updateSit
|
|||||||
(db as any).select().from(siteSettings).where(eq((siteSettings as any).id, existing.id))
|
(db as any).select().from(siteSettings).where(eq((siteSettings as any).id, existing.id))
|
||||||
);
|
);
|
||||||
|
|
||||||
// Revalidate frontend cache if featured event changed
|
// Revalidate frontend cache if featured event changed or the pre-sale
|
||||||
if (data.featuredEventId !== undefined) {
|
// defaults changed (public event pages embed the computed cutoff).
|
||||||
|
if (
|
||||||
|
data.featuredEventId !== undefined ||
|
||||||
|
data.presaleClosureEnabled !== undefined ||
|
||||||
|
data.presaleCloseMinutesBefore !== undefined
|
||||||
|
) {
|
||||||
revalidateFrontendCache();
|
revalidateFrontendCache();
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.json({ settings: updated, message: 'Settings updated successfully' });
|
return c.json({ settings: normalizeSettings(updated), message: 'Settings updated successfully' });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Set featured event (admin only) - convenience endpoint for event editor
|
// Set featured event (admin only) - convenience endpoint for event editor
|
||||||
|
|||||||
+179
-229
@@ -4,12 +4,17 @@ import { z } from 'zod';
|
|||||||
import { db, dbGet, dbAll, tickets, events, users, payments, paymentOptions, eventPaymentOverrides, siteSettings, isSqlite } from '../db/index.js';
|
import { db, dbGet, dbAll, tickets, events, users, payments, paymentOptions, eventPaymentOverrides, siteSettings, isSqlite } from '../db/index.js';
|
||||||
import { eq, and, or, sql, inArray } from 'drizzle-orm';
|
import { eq, and, or, sql, inArray } from 'drizzle-orm';
|
||||||
import { requireAuth, getAuthUser } from '../lib/auth.js';
|
import { requireAuth, getAuthUser } from '../lib/auth.js';
|
||||||
import { generateId, generateTicketCode, getNow, toDbDate, calculateAvailableSeats, isEventSoldOut } from '../lib/utils.js';
|
import {
|
||||||
|
requireEventPermission, eventFromQuery, eventFromBody, eventFromTicketParam, canSeeAttendeePii, redactAttendee,
|
||||||
|
} from '../lib/eventPermissions.js';
|
||||||
|
import { generateId, generateTicketCode, getNow, toDbDate, toDbBool, normalizeEmail, calculateAvailableSeats, isEventSoldOut } from '../lib/utils.js';
|
||||||
import { createInvoice, isLNbitsConfigured, LNBITS_INVOICE_EXPIRY_SECONDS } from '../lib/lnbits.js';
|
import { createInvoice, isLNbitsConfigured, LNBITS_INVOICE_EXPIRY_SECONDS } from '../lib/lnbits.js';
|
||||||
import { rateLimitMiddleware } from '../lib/rateLimit.js';
|
import { rateLimitMiddleware } from '../lib/rateLimit.js';
|
||||||
import emailService from '../lib/email.js';
|
import emailService from '../lib/email.js';
|
||||||
import { generateTicketPDF, generateCombinedTicketsPDF } from '../lib/pdf.js';
|
import { generateTicketPDF, generateCombinedTicketsPDF } from '../lib/pdf.js';
|
||||||
import { reserveOnHoldBooking, HoldCapacityError } from '../lib/holdRecovery.js';
|
import { reserveOnHoldBooking, HoldCapacityError } from '../lib/holdRecovery.js';
|
||||||
|
import { seatHolderCountQuery } from '../lib/capacity.js';
|
||||||
|
import { isOnlineSalesClosed } from '../lib/salesState.js';
|
||||||
|
|
||||||
const ticketsRouter = new Hono();
|
const ticketsRouter = new Hono();
|
||||||
|
|
||||||
@@ -110,6 +115,17 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
|||||||
return c.json({ error: 'Event is not available for booking' }, 400);
|
return c.json({ error: 'Event is not available for booking' }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pre-sale closure: online registration stops N minutes before the event
|
||||||
|
// starts (per-event override, else the site-wide default), and at the latest
|
||||||
|
// when it starts — the same rule as the public salesState (lib/salesState.ts).
|
||||||
|
// Staff/door and admin ticket creation use separate endpoints and are not gated.
|
||||||
|
const siteSettingsRow = await dbGet<any>(
|
||||||
|
(db as any).select().from(siteSettings).limit(1)
|
||||||
|
);
|
||||||
|
if (isOnlineSalesClosed(event, siteSettingsRow)) {
|
||||||
|
return c.json({ error: 'Registration for this event is closed' }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
// Validate the requested payment method is actually enabled for this event
|
// Validate the requested payment method is actually enabled for this event
|
||||||
// (merge global options with any event-level overrides; override wins when not null)
|
// (merge global options with any event-level overrides; override wins when not null)
|
||||||
const globalPaymentOptions = await dbGet<any>(
|
const globalPaymentOptions = await dbGet<any>(
|
||||||
@@ -128,19 +144,10 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
|||||||
return c.json({ error: 'Selected payment method is not available for this event' }, 400);
|
return c.json({ error: 'Selected payment method is not available for this event' }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check capacity - count pending, confirmed AND checked_in tickets.
|
// Check capacity against held seats (paid/checked-in tickets plus claimed
|
||||||
// Pending reservations must hold seats to prevent overselling via unpaid bookings
|
// manual payments) — see lib/capacity.ts. Bare pending bookings hold no seat.
|
||||||
// (cancelled/failed tickets are excluded so abandoned/rejected bookings free their seats).
|
|
||||||
const existingTicketCount = await dbGet<any>(
|
const existingTicketCount = await dbGet<any>(
|
||||||
(db as any)
|
seatHolderCountQuery(db, data.eventId)
|
||||||
.select({ count: sql<number>`count(*)` })
|
|
||||||
.from(tickets)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq((tickets as any).eventId, data.eventId),
|
|
||||||
sql`${(tickets as any).status} IN ('pending', 'confirmed', 'checked_in')`
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const confirmedCount = existingTicketCount?.count || 0;
|
const confirmedCount = existingTicketCount?.count || 0;
|
||||||
@@ -156,9 +163,12 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
|||||||
}, 400);
|
}, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find or create user
|
// Find or create user. The account row is keyed on the normalized address so
|
||||||
|
// it stays reachable from Better Auth (which lowercases every lookup) —
|
||||||
|
// tickets.attendeeEmail below keeps the address exactly as the buyer typed it.
|
||||||
|
const accountEmail = normalizeEmail(data.email);
|
||||||
let user = await dbGet<any>(
|
let user = await dbGet<any>(
|
||||||
(db as any).select().from(users).where(eq((users as any).email, data.email))
|
(db as any).select().from(users).where(eq((users as any).email, accountEmail))
|
||||||
);
|
);
|
||||||
|
|
||||||
const now = getNow();
|
const now = getNow();
|
||||||
@@ -171,13 +181,16 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
|||||||
const userId = generateId();
|
const userId = generateId();
|
||||||
user = {
|
user = {
|
||||||
id: userId,
|
id: userId,
|
||||||
email: data.email,
|
email: accountEmail,
|
||||||
password: '', // No password for guest bookings
|
password: null, // No password for guest bookings; set on claim (Better Auth credential account)
|
||||||
name: fullName,
|
name: fullName,
|
||||||
phone: data.phone || null,
|
phone: data.phone || null,
|
||||||
role: 'user',
|
role: 'user',
|
||||||
languagePreference: null,
|
languagePreference: null,
|
||||||
rucNumber,
|
rucNumber,
|
||||||
|
isClaimed: toDbBool(false),
|
||||||
|
accountStatus: 'unclaimed',
|
||||||
|
emailVerified: false,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
};
|
};
|
||||||
@@ -230,16 +243,7 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
|||||||
try {
|
try {
|
||||||
if (isSqlite()) {
|
if (isSqlite()) {
|
||||||
(db as any).transaction((tx: any) => {
|
(db as any).transaction((tx: any) => {
|
||||||
const countRow = tx
|
const countRow = seatHolderCountQuery(tx, data.eventId).get();
|
||||||
.select({ count: sql<number>`count(*)` })
|
|
||||||
.from(tickets)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq((tickets as any).eventId, data.eventId),
|
|
||||||
sql`${(tickets as any).status} IN ('pending', 'confirmed', 'checked_in')`
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.get();
|
|
||||||
const reserved = Number(countRow?.count || 0);
|
const reserved = Number(countRow?.count || 0);
|
||||||
if (isEventSoldOut(event.capacity, reserved)) {
|
if (isEventSoldOut(event.capacity, reserved)) {
|
||||||
throw new BookingCapacityError('SOLD_OUT');
|
throw new BookingCapacityError('SOLD_OUT');
|
||||||
@@ -290,17 +294,7 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
await (db as any).transaction(async (tx: any) => {
|
await (db as any).transaction(async (tx: any) => {
|
||||||
const countRow = await dbGet<any>(
|
const countRow = await dbGet<any>(seatHolderCountQuery(tx, data.eventId));
|
||||||
tx
|
|
||||||
.select({ count: sql<number>`count(*)` })
|
|
||||||
.from(tickets)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq((tickets as any).eventId, data.eventId),
|
|
||||||
sql`${(tickets as any).status} IN ('pending', 'confirmed', 'checked_in')`
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
const reserved = Number(countRow?.count || 0);
|
const reserved = Number(countRow?.count || 0);
|
||||||
if (isEventSoldOut(event.capacity, reserved)) {
|
if (isEventSoldOut(event.capacity, reserved)) {
|
||||||
throw new BookingCapacityError('SOLD_OUT');
|
throw new BookingCapacityError('SOLD_OUT');
|
||||||
@@ -388,7 +382,7 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
|||||||
for (const t of createdTickets) {
|
for (const t of createdTickets) {
|
||||||
await (db as any)
|
await (db as any)
|
||||||
.update(tickets)
|
.update(tickets)
|
||||||
.set({ status: 'confirmed' })
|
.set({ status: 'confirmed', paymentStatus: 'paid' })
|
||||||
.where(and(eq((tickets as any).id, t.id), eq((tickets as any).status, 'pending')));
|
.where(and(eq((tickets as any).id, t.id), eq((tickets as any).status, 'pending')));
|
||||||
await (db as any)
|
await (db as any)
|
||||||
.update(payments)
|
.update(payments)
|
||||||
@@ -572,20 +566,24 @@ ticketsRouter.get('/booking/:bookingId/pdf', async (c) => {
|
|||||||
);
|
);
|
||||||
const timezone = settings?.timezone || 'America/Asuncion';
|
const timezone = settings?.timezone || 'America/Asuncion';
|
||||||
|
|
||||||
const ticketsData = confirmedTickets.map((ticket: any) => ({
|
const ticketsData = confirmedTickets.map((ticket: any) => {
|
||||||
|
const locale = ticket.preferredLanguage === 'es' ? 'es' : 'en';
|
||||||
|
return {
|
||||||
id: ticket.id,
|
id: ticket.id,
|
||||||
qrCode: ticket.qrCode,
|
qrCode: ticket.qrCode,
|
||||||
attendeeName: `${ticket.attendeeFirstName} ${ticket.attendeeLastName || ''}`.trim(),
|
attendeeName: `${ticket.attendeeFirstName} ${ticket.attendeeLastName || ''}`.trim(),
|
||||||
attendeeEmail: ticket.attendeeEmail,
|
attendeeEmail: ticket.attendeeEmail,
|
||||||
event: {
|
event: {
|
||||||
title: event.title,
|
title: locale === 'es' && event.titleEs ? event.titleEs : event.title,
|
||||||
startDatetime: event.startDatetime,
|
startDatetime: event.startDatetime,
|
||||||
endDatetime: event.endDatetime,
|
endDatetime: event.endDatetime,
|
||||||
location: event.location,
|
location: event.location,
|
||||||
locationUrl: event.locationUrl,
|
locationUrl: event.locationUrl,
|
||||||
},
|
},
|
||||||
timezone,
|
timezone,
|
||||||
}));
|
locale,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
const pdfBuffer = await generateCombinedTicketsPDF(ticketsData);
|
const pdfBuffer = await generateCombinedTicketsPDF(ticketsData);
|
||||||
|
|
||||||
@@ -649,19 +647,22 @@ ticketsRouter.get('/:id/pdf', async (c) => {
|
|||||||
);
|
);
|
||||||
const timezone = settings?.timezone || 'America/Asuncion';
|
const timezone = settings?.timezone || 'America/Asuncion';
|
||||||
|
|
||||||
|
const locale = ticket.preferredLanguage === 'es' ? 'es' : 'en';
|
||||||
|
|
||||||
const pdfBuffer = await generateTicketPDF({
|
const pdfBuffer = await generateTicketPDF({
|
||||||
id: ticket.id,
|
id: ticket.id,
|
||||||
qrCode: ticket.qrCode,
|
qrCode: ticket.qrCode,
|
||||||
attendeeName: `${ticket.attendeeFirstName} ${ticket.attendeeLastName || ''}`.trim(),
|
attendeeName: `${ticket.attendeeFirstName} ${ticket.attendeeLastName || ''}`.trim(),
|
||||||
attendeeEmail: ticket.attendeeEmail,
|
attendeeEmail: ticket.attendeeEmail,
|
||||||
event: {
|
event: {
|
||||||
title: event.title,
|
title: locale === 'es' && event.titleEs ? event.titleEs : event.title,
|
||||||
startDatetime: event.startDatetime,
|
startDatetime: event.startDatetime,
|
||||||
endDatetime: event.endDatetime,
|
endDatetime: event.endDatetime,
|
||||||
location: event.location,
|
location: event.location,
|
||||||
locationUrl: event.locationUrl,
|
locationUrl: event.locationUrl,
|
||||||
},
|
},
|
||||||
timezone,
|
timezone,
|
||||||
|
locale,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Set response headers for PDF download
|
// Set response headers for PDF download
|
||||||
@@ -678,7 +679,7 @@ ticketsRouter.get('/:id/pdf', async (c) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Get event check-in stats for scanner (lightweight endpoint for staff)
|
// Get event check-in stats for scanner (lightweight endpoint for staff)
|
||||||
ticketsRouter.get('/stats/checkin', requireAuth(['admin', 'organizer', 'staff']), async (c) => {
|
ticketsRouter.get('/stats/checkin', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromQuery() }), async (c) => {
|
||||||
const eventId = c.req.query('eventId');
|
const eventId = c.req.query('eventId');
|
||||||
|
|
||||||
if (!eventId) {
|
if (!eventId) {
|
||||||
@@ -729,7 +730,7 @@ ticketsRouter.get('/stats/checkin', requireAuth(['admin', 'organizer', 'staff'])
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Live search tickets (GET - for scanner live search)
|
// Live search tickets (GET - for scanner live search)
|
||||||
ticketsRouter.get('/search', requireAuth(['admin', 'organizer', 'staff']), async (c) => {
|
ticketsRouter.get('/search', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromQuery() }), async (c) => {
|
||||||
const q = c.req.query('q')?.trim() || '';
|
const q = c.req.query('q')?.trim() || '';
|
||||||
const eventId = c.req.query('eventId');
|
const eventId = c.req.query('eventId');
|
||||||
|
|
||||||
@@ -848,7 +849,7 @@ ticketsRouter.get('/:id', async (c) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Update ticket status (admin/organizer)
|
// Update ticket status (admin/organizer)
|
||||||
ticketsRouter.put('/:id', requireAuth(['admin', 'organizer', 'staff']), zValidator('json', updateTicketSchema), async (c) => {
|
ticketsRouter.put('/:id', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromTicketParam() }), zValidator('json', updateTicketSchema), async (c) => {
|
||||||
const id = c.req.param('id');
|
const id = c.req.param('id');
|
||||||
const data = c.req.valid('json');
|
const data = c.req.valid('json');
|
||||||
|
|
||||||
@@ -881,7 +882,7 @@ ticketsRouter.put('/:id', requireAuth(['admin', 'organizer', 'staff']), zValidat
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Search tickets by name/email (for scanner manual search)
|
// Search tickets by name/email (for scanner manual search)
|
||||||
ticketsRouter.post('/search', requireAuth(['admin', 'organizer', 'staff']), async (c) => {
|
ticketsRouter.post('/search', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromBody() }), async (c) => {
|
||||||
const body = await c.req.json().catch(() => ({}));
|
const body = await c.req.json().catch(() => ({}));
|
||||||
const { query, eventId } = body;
|
const { query, eventId } = body;
|
||||||
|
|
||||||
@@ -940,7 +941,7 @@ ticketsRouter.post('/search', requireAuth(['admin', 'organizer', 'staff']), asyn
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Validate ticket by QR code (for scanner)
|
// Validate ticket by QR code (for scanner)
|
||||||
ticketsRouter.post('/validate', requireAuth(['admin', 'organizer', 'staff']), async (c) => {
|
ticketsRouter.post('/validate', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromBody() }), async (c) => {
|
||||||
const body = await c.req.json().catch(() => ({}));
|
const body = await c.req.json().catch(() => ({}));
|
||||||
const { code, eventId } = body;
|
const { code, eventId } = body;
|
||||||
|
|
||||||
@@ -1029,6 +1030,9 @@ ticketsRouter.post('/validate', requireAuth(['admin', 'organizer', 'staff']), as
|
|||||||
attendeeEmail: ticket.attendeeEmail,
|
attendeeEmail: ticket.attendeeEmail,
|
||||||
attendeePhone: ticket.attendeePhone,
|
attendeePhone: ticket.attendeePhone,
|
||||||
status: ticket.status,
|
status: ticket.status,
|
||||||
|
paymentStatus: ticket.paymentStatus,
|
||||||
|
// Balance to collect at the door for unpaid tickets
|
||||||
|
amountDue: ticket.paymentStatus === 'unpaid' && event ? event.price : 0,
|
||||||
checkinAt: ticket.checkinAt,
|
checkinAt: ticket.checkinAt,
|
||||||
checkedInBy,
|
checkedInBy,
|
||||||
},
|
},
|
||||||
@@ -1042,7 +1046,7 @@ ticketsRouter.post('/validate', requireAuth(['admin', 'organizer', 'staff']), as
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Check-in ticket
|
// Check-in ticket
|
||||||
ticketsRouter.post('/:id/checkin', requireAuth(['admin', 'organizer', 'staff']), async (c) => {
|
ticketsRouter.post('/:id/checkin', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromTicketParam() }), async (c) => {
|
||||||
const id = c.req.param('id');
|
const id = c.req.param('id');
|
||||||
const adminUser = (c as any).get('user');
|
const adminUser = (c as any).get('user');
|
||||||
|
|
||||||
@@ -1097,7 +1101,7 @@ ticketsRouter.post('/:id/checkin', requireAuth(['admin', 'organizer', 'staff']),
|
|||||||
|
|
||||||
// Mark payment as received (for cash payments - admin only)
|
// Mark payment as received (for cash payments - admin only)
|
||||||
// Supports multi-ticket bookings - confirms all tickets in the booking
|
// Supports multi-ticket bookings - confirms all tickets in the booking
|
||||||
ticketsRouter.post('/:id/mark-paid', requireAuth(['admin', 'organizer', 'staff']), async (c) => {
|
ticketsRouter.post('/:id/mark-paid', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromTicketParam() }), async (c) => {
|
||||||
const id = c.req.param('id');
|
const id = c.req.param('id');
|
||||||
const user = (c as any).get('user');
|
const user = (c as any).get('user');
|
||||||
|
|
||||||
@@ -1109,7 +1113,9 @@ ticketsRouter.post('/:id/mark-paid', requireAuth(['admin', 'organizer', 'staff']
|
|||||||
return c.json({ error: 'Ticket not found' }, 404);
|
return c.json({ error: 'Ticket not found' }, 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ticket.status === 'confirmed') {
|
// Confirmed/checked-in tickets can still be marked paid when they carry an
|
||||||
|
// unpaid balance (admin-added unpaid tickets collected at the door)
|
||||||
|
if (['confirmed', 'checked_in'].includes(ticket.status) && ticket.paymentStatus !== 'unpaid') {
|
||||||
return c.json({ error: 'Ticket already confirmed' }, 400);
|
return c.json({ error: 'Ticket already confirmed' }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1152,12 +1158,12 @@ ticketsRouter.post('/:id/mark-paid', requireAuth(['admin', 'organizer', 'staff']
|
|||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Confirm all tickets in the booking
|
// Confirm all tickets in the booking (checked-in tickets keep their status)
|
||||||
for (const t of ticketsToConfirm) {
|
for (const t of ticketsToConfirm) {
|
||||||
// Update ticket status
|
// Update ticket status
|
||||||
await (db as any)
|
await (db as any)
|
||||||
.update(tickets)
|
.update(tickets)
|
||||||
.set({ status: 'confirmed' })
|
.set({ status: t.status === 'checked_in' ? 'checked_in' : 'confirmed', paymentStatus: 'paid' })
|
||||||
.where(eq((tickets as any).id, t.id));
|
.where(eq((tickets as any).id, t.id));
|
||||||
|
|
||||||
// Update payment status
|
// Update payment status
|
||||||
@@ -1183,7 +1189,7 @@ ticketsRouter.post('/:id/mark-paid', requireAuth(['admin', 'organizer', 'staff']
|
|||||||
|
|
||||||
// Send confirmation emails asynchronously (don't block the response)
|
// Send confirmation emails asynchronously (don't block the response)
|
||||||
Promise.all([
|
Promise.all([
|
||||||
emailService.sendBookingConfirmation(id),
|
emailService.sendBookingConfirmation(ticket.id),
|
||||||
payment ? emailService.sendPaymentReceipt(payment.id) : Promise.resolve(),
|
payment ? emailService.sendPaymentReceipt(payment.id) : Promise.resolve(),
|
||||||
]).catch(err => {
|
]).catch(err => {
|
||||||
console.error('[Email] Failed to send confirmation emails:', err);
|
console.error('[Email] Failed to send confirmation emails:', err);
|
||||||
@@ -1364,7 +1370,7 @@ ticketsRouter.post('/:id/cancel', async (c) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Remove check-in (reset to confirmed)
|
// Remove check-in (reset to confirmed)
|
||||||
ticketsRouter.post('/:id/remove-checkin', requireAuth(['admin', 'organizer', 'staff']), async (c) => {
|
ticketsRouter.post('/:id/remove-checkin', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromTicketParam() }), async (c) => {
|
||||||
const id = c.req.param('id');
|
const id = c.req.param('id');
|
||||||
|
|
||||||
const ticket = await dbGet<any>(
|
const ticket = await dbGet<any>(
|
||||||
@@ -1392,7 +1398,7 @@ ticketsRouter.post('/:id/remove-checkin', requireAuth(['admin', 'organizer', 'st
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Update admin note
|
// Update admin note
|
||||||
ticketsRouter.post('/:id/note', requireAuth(['admin', 'organizer', 'staff']), zValidator('json', updateNoteSchema), async (c) => {
|
ticketsRouter.post('/:id/note', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromTicketParam() }), zValidator('json', updateNoteSchema), async (c) => {
|
||||||
const id = c.req.param('id');
|
const id = c.req.param('id');
|
||||||
const { note } = c.req.valid('json');
|
const { note } = c.req.valid('json');
|
||||||
|
|
||||||
@@ -1417,7 +1423,7 @@ ticketsRouter.post('/:id/note', requireAuth(['admin', 'organizer', 'staff']), zV
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Admin create ticket (at the door)
|
// Admin create ticket (at the door)
|
||||||
ticketsRouter.post('/admin/create', requireAuth(['admin', 'organizer', 'staff']), zValidator('json', adminCreateTicketSchema), async (c) => {
|
ticketsRouter.post('/admin/create', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromBody() }), zValidator('json', adminCreateTicketSchema), async (c) => {
|
||||||
const data = c.req.valid('json');
|
const data = c.req.valid('json');
|
||||||
|
|
||||||
// Get event
|
// Get event
|
||||||
@@ -1437,9 +1443,10 @@ ticketsRouter.post('/admin/create', requireAuth(['admin', 'organizer', 'staff'])
|
|||||||
? data.email.trim()
|
? data.email.trim()
|
||||||
: `door-${generateId()}@doorentry.local`;
|
: `door-${generateId()}@doorentry.local`;
|
||||||
|
|
||||||
// Find or create user
|
// Find or create user (see the note on `accountEmail` in the booking route)
|
||||||
|
const accountEmail = normalizeEmail(attendeeEmail);
|
||||||
let user = await dbGet<any>(
|
let user = await dbGet<any>(
|
||||||
(db as any).select().from(users).where(eq((users as any).email, attendeeEmail))
|
(db as any).select().from(users).where(eq((users as any).email, accountEmail))
|
||||||
);
|
);
|
||||||
|
|
||||||
const adminFullName = data.lastName && data.lastName.trim()
|
const adminFullName = data.lastName && data.lastName.trim()
|
||||||
@@ -1450,12 +1457,15 @@ ticketsRouter.post('/admin/create', requireAuth(['admin', 'organizer', 'staff'])
|
|||||||
const userId = generateId();
|
const userId = generateId();
|
||||||
user = {
|
user = {
|
||||||
id: userId,
|
id: userId,
|
||||||
email: attendeeEmail,
|
email: accountEmail,
|
||||||
password: '',
|
password: null,
|
||||||
name: adminFullName,
|
name: adminFullName,
|
||||||
phone: data.phone || null,
|
phone: data.phone || null,
|
||||||
role: 'user',
|
role: 'user',
|
||||||
languagePreference: null,
|
languagePreference: null,
|
||||||
|
isClaimed: toDbBool(false),
|
||||||
|
accountStatus: 'unclaimed',
|
||||||
|
emailVerified: false,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
};
|
};
|
||||||
@@ -1498,9 +1508,11 @@ ticketsRouter.post('/admin/create', requireAuth(['admin', 'organizer', 'staff'])
|
|||||||
attendeePhone: data.phone && data.phone.trim() ? data.phone.trim() : null,
|
attendeePhone: data.phone && data.phone.trim() ? data.phone.trim() : null,
|
||||||
preferredLanguage: data.preferredLanguage || null,
|
preferredLanguage: data.preferredLanguage || null,
|
||||||
status: ticketStatus,
|
status: ticketStatus,
|
||||||
|
paymentStatus: 'paid',
|
||||||
qrCode,
|
qrCode,
|
||||||
checkinAt: data.autoCheckin ? now : null,
|
checkinAt: data.autoCheckin ? now : null,
|
||||||
adminNote: data.adminNote || null,
|
adminNote: data.adminNote || null,
|
||||||
|
bookingSource: 'admin',
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1541,148 +1553,33 @@ ticketsRouter.post('/admin/create', requireAuth(['admin', 'organizer', 'staff'])
|
|||||||
}, 201);
|
}, 201);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Admin create manual ticket (sends confirmation email + ticket to attendee)
|
// Unified admin add-attendee endpoint backing the single Add Ticket modal.
|
||||||
ticketsRouter.post('/admin/manual', requireAuth(['admin', 'organizer', 'staff']), zValidator('json', z.object({
|
// type drives payment handling:
|
||||||
|
// paid — email required; paid cash payment; confirmation email + QR sent
|
||||||
|
// door — paid in cash at the door; all fields optional; counts toward revenue;
|
||||||
|
// confirmation email only when an email is provided
|
||||||
|
// unpaid — QR issued with balance due (collect at door); pending tpago payment;
|
||||||
|
// pay-link (Bancard/TPago) email sent when an email is provided
|
||||||
|
// guest — free comp ticket, not counted in revenue; confirmation email only
|
||||||
|
// when an email is provided
|
||||||
|
ticketsRouter.post('/admin/add', requireEventPermission('check_in', { globalRoles: ['admin', 'organizer', 'staff'], eventId: eventFromBody() }), zValidator('json', z.object({
|
||||||
eventId: z.string(),
|
eventId: z.string(),
|
||||||
firstName: z.string().min(2),
|
type: z.enum(['paid', 'door', 'unpaid', 'guest']),
|
||||||
lastName: z.string().optional().or(z.literal('')),
|
// Door walk-ins can be logged with nothing filled in, so firstName is only
|
||||||
email: z.string().email('Valid email is required for manual tickets'),
|
// required for the other types
|
||||||
phone: z.string().optional().or(z.literal('')),
|
firstName: z.string().optional().or(z.literal('')),
|
||||||
preferredLanguage: z.enum(['en', 'es']).optional(),
|
|
||||||
adminNote: z.string().max(1000).optional(),
|
|
||||||
})), async (c) => {
|
|
||||||
const data = c.req.valid('json');
|
|
||||||
|
|
||||||
// Get event
|
|
||||||
const event = await dbGet<any>(
|
|
||||||
(db as any).select().from(events).where(eq((events as any).id, data.eventId))
|
|
||||||
);
|
|
||||||
if (!event) {
|
|
||||||
return c.json({ error: 'Event not found' }, 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Admin manual ticket: bypass capacity check (allow over-capacity for admin-created tickets)
|
|
||||||
|
|
||||||
const now = getNow();
|
|
||||||
const attendeeEmail = data.email.trim();
|
|
||||||
|
|
||||||
// Find or create user
|
|
||||||
let user = await dbGet<any>(
|
|
||||||
(db as any).select().from(users).where(eq((users as any).email, attendeeEmail))
|
|
||||||
);
|
|
||||||
|
|
||||||
const fullName = data.lastName && data.lastName.trim()
|
|
||||||
? `${data.firstName} ${data.lastName}`.trim()
|
|
||||||
: data.firstName;
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
const userId = generateId();
|
|
||||||
user = {
|
|
||||||
id: userId,
|
|
||||||
email: attendeeEmail,
|
|
||||||
password: '',
|
|
||||||
name: fullName,
|
|
||||||
phone: data.phone || null,
|
|
||||||
role: 'user',
|
|
||||||
languagePreference: null,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
};
|
|
||||||
await (db as any).insert(users).values(user);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for existing active ticket for this user and event
|
|
||||||
const existingTicket = await dbGet<any>(
|
|
||||||
(db as any)
|
|
||||||
.select()
|
|
||||||
.from(tickets)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq((tickets as any).userId, user.id),
|
|
||||||
eq((tickets as any).eventId, data.eventId)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (existingTicket && existingTicket.status !== 'cancelled') {
|
|
||||||
return c.json({ error: 'This person already has a ticket for this event' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create ticket as confirmed
|
|
||||||
const ticketId = generateId();
|
|
||||||
const qrCode = generateTicketCode();
|
|
||||||
|
|
||||||
const newTicket = {
|
|
||||||
id: ticketId,
|
|
||||||
userId: user.id,
|
|
||||||
eventId: data.eventId,
|
|
||||||
attendeeFirstName: data.firstName,
|
|
||||||
attendeeLastName: data.lastName && data.lastName.trim() ? data.lastName.trim() : null,
|
|
||||||
attendeeEmail: attendeeEmail,
|
|
||||||
attendeePhone: data.phone && data.phone.trim() ? data.phone.trim() : null,
|
|
||||||
preferredLanguage: data.preferredLanguage || null,
|
|
||||||
status: 'confirmed',
|
|
||||||
qrCode,
|
|
||||||
checkinAt: null,
|
|
||||||
adminNote: data.adminNote || null,
|
|
||||||
createdAt: now,
|
|
||||||
};
|
|
||||||
|
|
||||||
await (db as any).insert(tickets).values(newTicket);
|
|
||||||
|
|
||||||
// Create payment record (marked as paid - manual entry)
|
|
||||||
const paymentId = generateId();
|
|
||||||
const adminUser = (c as any).get('user');
|
|
||||||
const newPayment = {
|
|
||||||
id: paymentId,
|
|
||||||
ticketId,
|
|
||||||
provider: 'cash',
|
|
||||||
amount: event.price,
|
|
||||||
currency: event.currency,
|
|
||||||
status: 'paid',
|
|
||||||
reference: 'Manual ticket',
|
|
||||||
paidAt: now,
|
|
||||||
paidByAdminId: adminUser?.id || null,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
};
|
|
||||||
|
|
||||||
await (db as any).insert(payments).values(newPayment);
|
|
||||||
|
|
||||||
// Send booking confirmation email + ticket (asynchronously)
|
|
||||||
emailService.sendBookingConfirmation(ticketId).then(result => {
|
|
||||||
if (result.success) {
|
|
||||||
console.log(`[Email] Booking confirmation sent for manual ticket ${ticketId}`);
|
|
||||||
} else {
|
|
||||||
console.error(`[Email] Failed to send booking confirmation for manual ticket ${ticketId}:`, result.error);
|
|
||||||
}
|
|
||||||
}).catch(err => {
|
|
||||||
console.error('[Email] Exception sending booking confirmation for manual ticket:', err);
|
|
||||||
});
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
ticket: {
|
|
||||||
...newTicket,
|
|
||||||
event: {
|
|
||||||
title: event.title,
|
|
||||||
startDatetime: event.startDatetime,
|
|
||||||
location: event.location,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payment: newPayment,
|
|
||||||
message: 'Manual ticket created and confirmation email sent',
|
|
||||||
}, 201);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Admin invite guest ticket (free, confirmed, not counted in revenue)
|
|
||||||
ticketsRouter.post('/admin/guest', requireAuth(['admin', 'organizer', 'staff']), zValidator('json', z.object({
|
|
||||||
eventId: z.string(),
|
|
||||||
firstName: z.string().min(1),
|
|
||||||
lastName: z.string().optional().or(z.literal('')),
|
lastName: z.string().optional().or(z.literal('')),
|
||||||
email: z.string().email().optional().or(z.literal('')),
|
email: z.string().email().optional().or(z.literal('')),
|
||||||
phone: z.string().optional().or(z.literal('')),
|
phone: z.string().optional().or(z.literal('')),
|
||||||
preferredLanguage: z.enum(['en', 'es']).optional(),
|
preferredLanguage: z.enum(['en', 'es']).optional(),
|
||||||
|
checkinNow: z.boolean().optional().default(false),
|
||||||
adminNote: z.string().max(1000).optional(),
|
adminNote: z.string().max(1000).optional(),
|
||||||
|
}).refine((d) => d.type !== 'paid' || !!(d.email && d.email.trim()), {
|
||||||
|
message: 'Email is required for paid tickets',
|
||||||
|
path: ['email'],
|
||||||
|
}).refine((d) => d.type === 'door' || !!(d.firstName && d.firstName.trim()), {
|
||||||
|
message: 'First name is required',
|
||||||
|
path: ['firstName'],
|
||||||
})), async (c) => {
|
})), async (c) => {
|
||||||
const data = c.req.valid('json');
|
const data = c.req.valid('json');
|
||||||
|
|
||||||
@@ -1693,40 +1590,48 @@ ticketsRouter.post('/admin/guest', requireAuth(['admin', 'organizer', 'staff']),
|
|||||||
return c.json({ error: 'Event not found' }, 404);
|
return c.json({ error: 'Event not found' }, 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Admin-added tickets bypass the capacity check (intentional over-capacity)
|
||||||
|
|
||||||
const now = getNow();
|
const now = getNow();
|
||||||
const adminUser = (c as any).get('user');
|
const adminUser = (c as any).get('user');
|
||||||
|
const hasEmail = !!(data.email && data.email.trim());
|
||||||
|
const attendeeEmail = hasEmail
|
||||||
|
? data.email!.trim()
|
||||||
|
: `${data.type === 'guest' ? 'guest' : 'door'}-${generateId()}@${data.type === 'guest' ? 'guestinvite' : 'doorentry'}.local`;
|
||||||
|
|
||||||
// Find or create user (use placeholder email if none provided)
|
// Nameless door walk-ins still need a display name on the ticket
|
||||||
const attendeeEmail = data.email && data.email.trim()
|
const firstName = (data.firstName && data.firstName.trim()) || 'Walk-in';
|
||||||
? data.email.trim()
|
|
||||||
: `guest-${generateId()}@guestinvite.local`;
|
|
||||||
|
|
||||||
const fullName = data.lastName && data.lastName.trim()
|
const fullName = data.lastName && data.lastName.trim()
|
||||||
? `${data.firstName} ${data.lastName}`.trim()
|
? `${firstName} ${data.lastName.trim()}`
|
||||||
: data.firstName;
|
: firstName;
|
||||||
|
|
||||||
|
// Find or create user (see the note on `accountEmail` in the booking route)
|
||||||
|
const accountEmail = normalizeEmail(attendeeEmail);
|
||||||
let user = await dbGet<any>(
|
let user = await dbGet<any>(
|
||||||
(db as any).select().from(users).where(eq((users as any).email, attendeeEmail))
|
(db as any).select().from(users).where(eq((users as any).email, accountEmail))
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
const userId = generateId();
|
const userId = generateId();
|
||||||
user = {
|
user = {
|
||||||
id: userId,
|
id: userId,
|
||||||
email: attendeeEmail,
|
email: accountEmail,
|
||||||
password: '',
|
password: null,
|
||||||
name: fullName,
|
name: fullName,
|
||||||
phone: data.phone || null,
|
phone: data.phone || null,
|
||||||
role: 'user',
|
role: 'user',
|
||||||
languagePreference: null,
|
languagePreference: null,
|
||||||
|
isClaimed: toDbBool(false),
|
||||||
|
accountStatus: 'unclaimed',
|
||||||
|
emailVerified: false,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
};
|
};
|
||||||
await (db as any).insert(users).values(user);
|
await (db as any).insert(users).values(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for existing active ticket (only for real emails, not placeholder)
|
// Check for existing active ticket (only when a real email was provided)
|
||||||
if (data.email && data.email.trim()) {
|
if (hasEmail) {
|
||||||
const existingTicket = await dbGet<any>(
|
const existingTicket = await dbGet<any>(
|
||||||
(db as any)
|
(db as any)
|
||||||
.select()
|
.select()
|
||||||
@@ -1745,36 +1650,58 @@ ticketsRouter.post('/admin/guest', requireAuth(['admin', 'organizer', 'staff']),
|
|||||||
|
|
||||||
const ticketId = generateId();
|
const ticketId = generateId();
|
||||||
const qrCode = generateTicketCode();
|
const qrCode = generateTicketCode();
|
||||||
|
const paymentStatus = data.type === 'guest' ? 'comp' : data.type === 'unpaid' ? 'unpaid' : 'paid';
|
||||||
|
|
||||||
const newTicket = {
|
const newTicket = {
|
||||||
id: ticketId,
|
id: ticketId,
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
eventId: data.eventId,
|
eventId: data.eventId,
|
||||||
attendeeFirstName: data.firstName,
|
attendeeFirstName: firstName,
|
||||||
attendeeLastName: data.lastName && data.lastName.trim() ? data.lastName.trim() : null,
|
attendeeLastName: data.lastName && data.lastName.trim() ? data.lastName.trim() : null,
|
||||||
attendeeEmail: data.email && data.email.trim() ? data.email.trim() : null,
|
attendeeEmail: hasEmail ? data.email!.trim() : null,
|
||||||
attendeePhone: data.phone && data.phone.trim() ? data.phone.trim() : null,
|
attendeePhone: data.phone && data.phone.trim() ? data.phone.trim() : null,
|
||||||
preferredLanguage: data.preferredLanguage || null,
|
preferredLanguage: data.preferredLanguage || null,
|
||||||
status: 'confirmed',
|
status: data.checkinNow ? 'checked_in' : 'confirmed',
|
||||||
isGuest: 1,
|
isGuest: data.type === 'guest' ? 1 : 0,
|
||||||
|
paymentStatus,
|
||||||
qrCode,
|
qrCode,
|
||||||
checkinAt: null,
|
checkinAt: data.checkinNow ? now : null,
|
||||||
|
checkedInByAdminId: data.checkinNow ? adminUser?.id || null : null,
|
||||||
adminNote: data.adminNote || null,
|
adminNote: data.adminNote || null,
|
||||||
|
bookingSource: 'admin',
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
};
|
};
|
||||||
|
|
||||||
await (db as any).insert(tickets).values(newTicket);
|
await (db as any).insert(tickets).values(newTicket);
|
||||||
|
|
||||||
// Create a $0 payment record to track the invite
|
// Payment record: paid cash for paid/door/guest ($0 for guest), pending tpago for unpaid
|
||||||
const paymentId = generateId();
|
const paymentId = generateId();
|
||||||
const newPayment = {
|
const newPayment = data.type === 'unpaid'
|
||||||
|
? {
|
||||||
|
id: paymentId,
|
||||||
|
ticketId,
|
||||||
|
provider: 'tpago',
|
||||||
|
amount: event.price,
|
||||||
|
currency: event.currency,
|
||||||
|
status: 'pending',
|
||||||
|
reference: 'Unpaid ticket — collect at door',
|
||||||
|
paidAt: null,
|
||||||
|
paidByAdminId: null,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
}
|
||||||
|
: {
|
||||||
id: paymentId,
|
id: paymentId,
|
||||||
ticketId,
|
ticketId,
|
||||||
provider: 'cash',
|
provider: 'cash',
|
||||||
amount: 0,
|
amount: data.type === 'guest' ? 0 : event.price,
|
||||||
currency: event.currency,
|
currency: event.currency,
|
||||||
status: 'paid',
|
status: 'paid',
|
||||||
reference: 'Guest invite',
|
reference: data.type === 'guest'
|
||||||
|
? 'Guest invite'
|
||||||
|
: data.type === 'door'
|
||||||
|
? 'Paid at door'
|
||||||
|
: 'Manual ticket',
|
||||||
paidAt: now,
|
paidAt: now,
|
||||||
paidByAdminId: adminUser?.id || null,
|
paidByAdminId: adminUser?.id || null,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
@@ -1783,18 +1710,40 @@ ticketsRouter.post('/admin/guest', requireAuth(['admin', 'organizer', 'staff']),
|
|||||||
|
|
||||||
await (db as any).insert(payments).values(newPayment);
|
await (db as any).insert(payments).values(newPayment);
|
||||||
|
|
||||||
// Send booking confirmation email if a real email was provided
|
// Emails (asynchronous): paid always confirms; door/guest confirm only when an
|
||||||
if (data.email && data.email.trim()) {
|
// email exists; unpaid sends the TPago (Bancard) pay-link instructions instead
|
||||||
emailService.sendBookingConfirmation(ticketId).then(result => {
|
if (data.type === 'unpaid') {
|
||||||
if (result.success) {
|
if (hasEmail) {
|
||||||
console.log(`[Email] Booking confirmation sent for guest ticket ${ticketId}`);
|
emailService.sendPaymentInstructions(ticketId).then(result => {
|
||||||
} else {
|
if (!result.success) {
|
||||||
console.error(`[Email] Failed to send booking confirmation for guest ticket ${ticketId}:`, result.error);
|
console.error(`[Email] Failed to send pay link for unpaid ticket ${ticketId}:`, result.error);
|
||||||
}
|
}
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
console.error('[Email] Exception sending booking confirmation for guest ticket:', err);
|
console.error('[Email] Exception sending pay link for unpaid ticket:', err);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
} else if (data.type === 'paid' || hasEmail) {
|
||||||
|
emailService.sendBookingConfirmation(ticketId).then(result => {
|
||||||
|
if (!result.success) {
|
||||||
|
console.error(`[Email] Failed to send booking confirmation for ${data.type} ticket ${ticketId}:`, result.error);
|
||||||
|
}
|
||||||
|
}).catch(err => {
|
||||||
|
console.error(`[Email] Exception sending booking confirmation for ${data.type} ticket:`, err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const messages: Record<string, string> = {
|
||||||
|
paid: 'Ticket created — confirmation email sent',
|
||||||
|
door: hasEmail
|
||||||
|
? 'Ticket created — paid at the door, confirmation email sent'
|
||||||
|
: 'Ticket created — paid at the door',
|
||||||
|
unpaid: hasEmail
|
||||||
|
? 'Unpaid ticket created — payment link sent'
|
||||||
|
: 'Unpaid ticket created — collect payment at the door',
|
||||||
|
guest: hasEmail
|
||||||
|
? 'Guest invited — confirmation email sent'
|
||||||
|
: 'Guest invited',
|
||||||
|
};
|
||||||
|
|
||||||
return c.json({
|
return c.json({
|
||||||
ticket: {
|
ticket: {
|
||||||
@@ -1806,12 +1755,12 @@ ticketsRouter.post('/admin/guest', requireAuth(['admin', 'organizer', 'staff']),
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
payment: newPayment,
|
payment: newPayment,
|
||||||
message: 'Guest ticket created successfully',
|
message: data.checkinNow ? `${messages[data.type]} · checked in` : messages[data.type],
|
||||||
}, 201);
|
}, 201);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get all tickets (admin) - includes payment for each ticket
|
// Get all tickets (admin) - includes payment for each ticket
|
||||||
ticketsRouter.get('/', requireAuth(['admin', 'organizer']), async (c) => {
|
ticketsRouter.get('/', requireEventPermission('view_attendees_names', { globalRoles: ['admin', 'organizer'], eventId: eventFromQuery() }), async (c) => {
|
||||||
const eventId = c.req.query('eventId');
|
const eventId = c.req.query('eventId');
|
||||||
const status = c.req.query('status');
|
const status = c.req.query('status');
|
||||||
|
|
||||||
@@ -1842,8 +1791,9 @@ ticketsRouter.get('/', requireAuth(['admin', 'organizer']), async (c) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const showPii = canSeeAttendeePii(c);
|
||||||
const ticketsWithPayment = ticketsList.map((t: any) => ({
|
const ticketsWithPayment = ticketsList.map((t: any) => ({
|
||||||
...t,
|
...(showPii ? t : redactAttendee(t)),
|
||||||
payment: paymentByTicketId[t.id] || null,
|
payment: paymentByTicketId[t.id] || null,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import { z } from 'zod';
|
|||||||
import { db, dbGet, dbAll, users, tickets, events, payments, magicLinkTokens, userSessions, invoices, auditLogs, emailLogs, paymentOptions, legalPages, siteSettings } from '../db/index.js';
|
import { db, dbGet, dbAll, users, tickets, events, payments, magicLinkTokens, userSessions, invoices, auditLogs, emailLogs, paymentOptions, legalPages, siteSettings } from '../db/index.js';
|
||||||
import { eq, desc, sql, and, gte, lte } from 'drizzle-orm';
|
import { eq, desc, sql, and, gte, lte } from 'drizzle-orm';
|
||||||
import { requireAuth } from '../lib/auth.js';
|
import { requireAuth } from '../lib/auth.js';
|
||||||
|
import { authSessions } from '../db/auth-schema.js';
|
||||||
import { getNow, toDbDate } from '../lib/utils.js';
|
import { getNow, toDbDate } from '../lib/utils.js';
|
||||||
|
import { omitWalkInPrice } from '../lib/walkInPrice.js';
|
||||||
|
|
||||||
interface UserContext {
|
interface UserContext {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -175,11 +177,28 @@ usersRouter.put('/:id', requireAuth(['admin', 'organizer', 'staff', 'marketing',
|
|||||||
return c.json({ error: 'User not found' }, 404);
|
return c.json({ error: 'User not found' }, 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Keep the Better Auth admin `banned` flag in sync with accountStatus so
|
||||||
|
// sign-in is blocked at the auth layer too, and kill live sessions on
|
||||||
|
// suspension so it takes effect immediately (sessions are DB-validated on
|
||||||
|
// every request by both the backend and the photo API).
|
||||||
|
const statusMirror: Record<string, any> = {};
|
||||||
|
if (data.accountStatus === 'suspended') {
|
||||||
|
statusMirror.banned = true;
|
||||||
|
statusMirror.banReason = 'Suspended by admin';
|
||||||
|
} else if (data.accountStatus) {
|
||||||
|
statusMirror.banned = false;
|
||||||
|
statusMirror.banReason = null;
|
||||||
|
}
|
||||||
|
|
||||||
await (db as any)
|
await (db as any)
|
||||||
.update(users)
|
.update(users)
|
||||||
.set({ ...data, updatedAt: getNow() })
|
.set({ ...data, ...statusMirror, updatedAt: getNow() })
|
||||||
.where(eq((users as any).id, id));
|
.where(eq((users as any).id, id));
|
||||||
|
|
||||||
|
if (data.accountStatus === 'suspended') {
|
||||||
|
await (db as any).delete(authSessions).where(eq((authSessions as any).userId, id));
|
||||||
|
}
|
||||||
|
|
||||||
const updated = await dbGet(
|
const updated = await dbGet(
|
||||||
(db as any)
|
(db as any)
|
||||||
.select({
|
.select({
|
||||||
@@ -231,7 +250,7 @@ usersRouter.get('/:id/history', requireAuth(['admin', 'organizer', 'staff', 'mar
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
...ticket,
|
...ticket,
|
||||||
event,
|
event: omitWalkInPrice(event as any),
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -8,9 +8,9 @@
|
|||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"outDir": "./dist",
|
"outDir": "./dist",
|
||||||
"rootDir": "./src",
|
"rootDir": "./src",
|
||||||
"declaration": true,
|
"declaration": false,
|
||||||
"resolveJsonModule": true
|
"resolveJsonModule": true
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"],
|
"include": ["src/**/*"],
|
||||||
"exclude": ["node_modules", "dist"]
|
"exclude": ["node_modules", "dist", "src/**/*.test.ts"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { defineConfig } from 'vitest/config';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
include: ['src/**/*.test.ts'],
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -63,6 +63,29 @@ server {
|
|||||||
return 413 '{"error":"Payload too large (413). Please upload a smaller file."}';
|
return 413 '{"error":"Payload too large (413). Please upload a smaller file."}';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Photo gallery service (photo-api, port 3020). ^~ wins over the /
|
||||||
|
# prefix below; bigger body cap and unbuffered uploads for photo batches.
|
||||||
|
location ^~ /api/photos/ {
|
||||||
|
limit_req zone=spanglish_api_limit burst=50 nodelay;
|
||||||
|
|
||||||
|
proxy_pass http://spanglish_photos;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
# Strip CORS headers from the service (nginx handles CORS here)
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Origin';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Methods';
|
||||||
|
|
||||||
|
client_max_body_size 100m;
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 300s;
|
||||||
|
}
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
limit_req zone=spanglish_api_limit burst=50 nodelay;
|
limit_req zone=spanglish_api_limit burst=50 nodelay;
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,20 @@ services:
|
|||||||
|
|
||||||
redis:
|
redis:
|
||||||
image: redis:7-alpine
|
image: redis:7-alpine
|
||||||
command: ["redis-server", "--appendonly", "yes"]
|
# noeviction is deliberate: rate-limit, lock, and lockout keys must never
|
||||||
|
# be evicted for correctness. The cache workload is a single short-TTL key,
|
||||||
|
# so memory pressure is negligible; if caching ever grows, revisit this or
|
||||||
|
# move the cache to its own DB index.
|
||||||
|
command:
|
||||||
|
[
|
||||||
|
"redis-server",
|
||||||
|
"--appendonly", "yes",
|
||||||
|
"--requirepass", "${REDIS_PASSWORD:-change-me-redis-password}",
|
||||||
|
"--maxmemory", "256mb",
|
||||||
|
"--maxmemory-policy", "noeviction",
|
||||||
|
]
|
||||||
|
environment:
|
||||||
|
REDISCLI_AUTH: "${REDIS_PASSWORD:-change-me-redis-password}"
|
||||||
volumes:
|
volumes:
|
||||||
- redisdata:/data
|
- redisdata:/data
|
||||||
healthcheck:
|
healthcheck:
|
||||||
@@ -46,7 +59,7 @@ services:
|
|||||||
DB_TYPE: postgres
|
DB_TYPE: postgres
|
||||||
DATABASE_URL: postgresql://spanglish:spanglish@postgres:5432/spanglish
|
DATABASE_URL: postgresql://spanglish:spanglish@postgres:5432/spanglish
|
||||||
DB_POOL_MAX: "15"
|
DB_POOL_MAX: "15"
|
||||||
REDIS_URL: redis://redis:6379
|
REDIS_URL: "redis://:${REDIS_PASSWORD:-change-me-redis-password}@redis:6379"
|
||||||
JWT_SECRET: change-me-to-a-strong-secret
|
JWT_SECRET: change-me-to-a-strong-secret
|
||||||
FRONTEND_URL: http://localhost:8080
|
FRONTEND_URL: http://localhost:8080
|
||||||
# Optional S3-compatible storage so uploads are shared across replicas.
|
# Optional S3-compatible storage so uploads are shared across replicas.
|
||||||
|
|||||||
@@ -79,6 +79,24 @@ server {
|
|||||||
proxy_connect_timeout 300s;
|
proxy_connect_timeout 300s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Photo gallery service (photo-api, port 3020). ^~ wins over the /api
|
||||||
|
# prefix below. Batch photo uploads are large and slow, so the body cap
|
||||||
|
# is raised and request buffering is off for this location only.
|
||||||
|
location ^~ /api/photos/ {
|
||||||
|
proxy_pass http://spanglish_photos;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
client_max_body_size 100m;
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 300s;
|
||||||
|
}
|
||||||
|
|
||||||
# Proxy /api to backend
|
# Proxy /api to backend
|
||||||
location /api {
|
location /api {
|
||||||
proxy_pass http://spanglish_backend;
|
proxy_pass http://spanglish_backend;
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# ============================================================
|
||||||
|
# Spanglish Community - Photo Gallery API
|
||||||
|
# photos.spanglishcommunity.com
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name photos.spanglishcommunity.com;
|
||||||
|
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/html;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
return 301 https://photos.spanglishcommunity.com$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
http2 on;
|
||||||
|
|
||||||
|
server_name photos.spanglishcommunity.com;
|
||||||
|
|
||||||
|
# Photos can be larger than typical JSON payloads
|
||||||
|
client_max_body_size 25m;
|
||||||
|
|
||||||
|
# SSL
|
||||||
|
ssl_certificate /etc/letsencrypt/live/photos.spanglishcommunity.com/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/photos.spanglishcommunity.com/privkey.pem;
|
||||||
|
|
||||||
|
include /etc/letsencrypt/options-ssl-nginx.conf;
|
||||||
|
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
|
||||||
|
|
||||||
|
# Security
|
||||||
|
add_header X-Frame-Options "DENY" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
access_log /var/log/nginx/spanglish_photo_access.log;
|
||||||
|
error_log /var/log/nginx/spanglish_photo_error.log;
|
||||||
|
|
||||||
|
# CORS Configuration
|
||||||
|
set $cors_origin "";
|
||||||
|
if ($http_origin ~* "^https://(www\.)?spanglishcommunity\.com$") {
|
||||||
|
set $cors_origin $http_origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
add_header 'Access-Control-Allow-Origin' $cors_origin always;
|
||||||
|
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, OPTIONS' always;
|
||||||
|
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
|
||||||
|
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||||
|
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
|
||||||
|
|
||||||
|
# Ensure 413 returns JSON + CORS
|
||||||
|
error_page 413 = @payload_too_large;
|
||||||
|
location @payload_too_large {
|
||||||
|
default_type application/json;
|
||||||
|
return 413 '{"error":"Payload too large (413). Please upload a smaller file."}';
|
||||||
|
}
|
||||||
|
|
||||||
|
# Ensure 429 (rate limited) returns JSON + CORS
|
||||||
|
error_page 429 = @rate_limited;
|
||||||
|
location @rate_limited {
|
||||||
|
default_type application/json;
|
||||||
|
add_header 'Access-Control-Allow-Origin' $cors_origin always;
|
||||||
|
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||||
|
return 429 '{"error":"Too many requests. Please slow down."}';
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
limit_req zone=spanglish_photo_limit burst=40 nodelay;
|
||||||
|
|
||||||
|
# Preflight
|
||||||
|
if ($request_method = 'OPTIONS') {
|
||||||
|
add_header 'Access-Control-Allow-Origin' $cors_origin always;
|
||||||
|
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, OPTIONS' always;
|
||||||
|
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
|
||||||
|
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||||
|
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
|
||||||
|
add_header 'Access-Control-Max-Age' 86400 always;
|
||||||
|
add_header 'Content-Type' 'text/plain; charset=utf-8';
|
||||||
|
add_header 'Content-Length' 0;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy_pass http://spanglish_photo_api;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Origin';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Methods';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Headers';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Credentials';
|
||||||
|
proxy_hide_header 'Access-Control-Expose-Headers';
|
||||||
|
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 300s;
|
||||||
|
|
||||||
|
# Buffer large image uploads to disk rather than memory
|
||||||
|
proxy_request_buffering on;
|
||||||
|
proxy_max_temp_file_size 1024m;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
# ============================================================
|
||||||
|
# Spanglish Community - Backend API
|
||||||
|
# api.spanglishcommunity.com
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name api.spanglishcommunity.com;
|
||||||
|
|
||||||
|
# ACME
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Force HTTPS
|
||||||
|
location / {
|
||||||
|
return 301 https://api.spanglishcommunity.com$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
http2 on;
|
||||||
|
|
||||||
|
server_name api.spanglishcommunity.com;
|
||||||
|
|
||||||
|
# Upload size limit (avoid nginx 413 on media uploads)
|
||||||
|
# Keep this >= backend MEDIA_MAX_UPLOAD_MB (default 10MB).
|
||||||
|
client_max_body_size 20m;
|
||||||
|
|
||||||
|
# SSL
|
||||||
|
ssl_certificate /etc/letsencrypt/live/spanglishcommunity.com/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/spanglishcommunity.com/privkey.pem;
|
||||||
|
|
||||||
|
include /etc/letsencrypt/options-ssl-nginx.conf;
|
||||||
|
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
|
||||||
|
|
||||||
|
# Security (API)
|
||||||
|
add_header X-Frame-Options "DENY" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
access_log /var/log/nginx/spanglish_api_access.log;
|
||||||
|
error_log /var/log/nginx/spanglish_api_error.log;
|
||||||
|
|
||||||
|
# CORS Configuration (set once, used everywhere)
|
||||||
|
set $cors_origin "";
|
||||||
|
if ($http_origin ~* "^https://(www\.)?spanglishcommunity\.com$") {
|
||||||
|
set $cors_origin $http_origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Add CORS headers to all responses (including nginx-generated errors)
|
||||||
|
add_header 'Access-Control-Allow-Origin' $cors_origin always;
|
||||||
|
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, OPTIONS' always;
|
||||||
|
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
|
||||||
|
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||||
|
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
|
||||||
|
|
||||||
|
# Ensure 413 returns JSON + CORS (browser otherwise reports "CORS blocked")
|
||||||
|
error_page 413 = @payload_too_large;
|
||||||
|
location @payload_too_large {
|
||||||
|
default_type application/json;
|
||||||
|
return 413 '{"error":"Payload too large (413). Please upload a smaller file."}';
|
||||||
|
}
|
||||||
|
|
||||||
|
# Photo gallery service (photo-api, port 3003). ^~ wins over the "/"
|
||||||
|
# prefix below, so /api/photos/* reaches the Go photo-api instead of the
|
||||||
|
# Node backend (which has no photo routes and would 404). The admin UI
|
||||||
|
# calls this cross-origin via NEXT_PUBLIC_API_URL, so preflight + CORS
|
||||||
|
# must be handled here just like location / below.
|
||||||
|
location ^~ /api/photos/ {
|
||||||
|
limit_req zone=spanglish_api_limit burst=50 nodelay;
|
||||||
|
|
||||||
|
# Handle preflight OPTIONS requests (add_header inside if{} does NOT
|
||||||
|
# inherit server-level headers, so repeat all CORS headers here).
|
||||||
|
if ($request_method = 'OPTIONS') {
|
||||||
|
add_header 'Access-Control-Allow-Origin' $cors_origin always;
|
||||||
|
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, OPTIONS' always;
|
||||||
|
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
|
||||||
|
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||||
|
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
|
||||||
|
add_header 'Access-Control-Max-Age' 86400 always;
|
||||||
|
add_header 'Content-Type' 'text/plain; charset=utf-8';
|
||||||
|
add_header 'Content-Length' 0;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy_pass http://spanglish_photo_api;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
# Strip CORS headers from the service (nginx handles CORS here)
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Origin';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Methods';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Headers';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Credentials';
|
||||||
|
proxy_hide_header 'Access-Control-Expose-Headers';
|
||||||
|
|
||||||
|
# Photo batches can be large; allow bigger bodies + unbuffered upload.
|
||||||
|
client_max_body_size 100m;
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 300s;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
limit_req zone=spanglish_api_limit burst=50 nodelay;
|
||||||
|
|
||||||
|
# Handle preflight OPTIONS requests
|
||||||
|
# NOTE: add_header inside if{} does NOT inherit server-level headers,
|
||||||
|
# so we must repeat all CORS headers here.
|
||||||
|
if ($request_method = 'OPTIONS') {
|
||||||
|
add_header 'Access-Control-Allow-Origin' $cors_origin always;
|
||||||
|
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, OPTIONS' always;
|
||||||
|
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
|
||||||
|
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||||
|
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
|
||||||
|
add_header 'Access-Control-Max-Age' 86400 always;
|
||||||
|
add_header 'Content-Type' 'text/plain; charset=utf-8';
|
||||||
|
add_header 'Content-Length' 0;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy_pass http://spanglish_backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
# Strip CORS headers from backend (nginx handles CORS at server level)
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Origin';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Methods';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Headers';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Credentials';
|
||||||
|
proxy_hide_header 'Access-Control-Expose-Headers';
|
||||||
|
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 300s;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
# ============================================================
|
||||||
|
# Spanglish Community - Frontend
|
||||||
|
# spanglishcommunity.com / www
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name spanglishcommunity.com www.spanglishcommunity.com;
|
||||||
|
|
||||||
|
# ACME
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Force HTTPS
|
||||||
|
location / {
|
||||||
|
return 301 https://spanglishcommunity.com$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
http2 on;
|
||||||
|
|
||||||
|
server_name spanglishcommunity.com www.spanglishcommunity.com;
|
||||||
|
|
||||||
|
# Upload size limit (covers same-origin /api uploads via this vhost)
|
||||||
|
client_max_body_size 20m;
|
||||||
|
|
||||||
|
# SSL
|
||||||
|
ssl_certificate /etc/letsencrypt/live/spanglishcommunity.com/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/spanglishcommunity.com/privkey.pem;
|
||||||
|
|
||||||
|
include /etc/letsencrypt/options-ssl-nginx.conf;
|
||||||
|
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
|
||||||
|
|
||||||
|
# Security
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
access_log /var/log/nginx/spanglish_frontend_access.log;
|
||||||
|
error_log /var/log/nginx/spanglish_frontend_error.log;
|
||||||
|
|
||||||
|
# Proxy /api/photos to the photo-api (Go service, port 3003). ^~ wins over
|
||||||
|
# the /api prefix below so same-origin image/gallery requests reach the
|
||||||
|
# photo-api instead of the Node backend (which has no photo routes -> 404).
|
||||||
|
location ^~ /api/photos/ {
|
||||||
|
proxy_pass http://spanglish_photo_api;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
# Photo uploads/batches can be large; allow bigger bodies.
|
||||||
|
client_max_body_size 100m;
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 300s;
|
||||||
|
|
||||||
|
# Let the photo-api set Cache-Control per image visibility (public vs.
|
||||||
|
# token-gated) rather than forcing a cache policy here.
|
||||||
|
}
|
||||||
|
|
||||||
|
# Proxy /api to backend
|
||||||
|
location /api {
|
||||||
|
proxy_pass http://spanglish_backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 300s;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Proxy /uploads to backend
|
||||||
|
location /uploads {
|
||||||
|
proxy_pass http://spanglish_backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
# Cache static files
|
||||||
|
proxy_cache_valid 200 1d;
|
||||||
|
expires 1d;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Frontend App
|
||||||
|
location / {
|
||||||
|
proxy_pass http://spanglish_frontend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
# WebSocket / HMR
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
|
||||||
|
proxy_read_timeout 60s;
|
||||||
|
proxy_connect_timeout 60s;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# ============================================================
|
||||||
|
# Spanglish Community - Photo Gallery API
|
||||||
|
# photos.spanglishcommunity.com
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name photos.spanglishcommunity.com;
|
||||||
|
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
return 301 https://photos.spanglishcommunity.com$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
http2 on;
|
||||||
|
|
||||||
|
server_name photos.spanglishcommunity.com;
|
||||||
|
|
||||||
|
# Photos can be larger than typical JSON payloads
|
||||||
|
client_max_body_size 25m;
|
||||||
|
|
||||||
|
# SSL
|
||||||
|
ssl_certificate /etc/letsencrypt/live/photos.spanglishcommunity.com/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/photos.spanglishcommunity.com/privkey.pem;
|
||||||
|
|
||||||
|
include /etc/letsencrypt/options-ssl-nginx.conf;
|
||||||
|
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
|
||||||
|
|
||||||
|
# Security
|
||||||
|
add_header X-Frame-Options "DENY" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
access_log /var/log/nginx/spanglish_photo_access.log;
|
||||||
|
error_log /var/log/nginx/spanglish_photo_error.log;
|
||||||
|
|
||||||
|
# CORS Configuration
|
||||||
|
set $cors_origin "";
|
||||||
|
if ($http_origin ~* "^https://(www\.)?spanglishcommunity\.com$") {
|
||||||
|
set $cors_origin $http_origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
add_header 'Access-Control-Allow-Origin' $cors_origin always;
|
||||||
|
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, OPTIONS' always;
|
||||||
|
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
|
||||||
|
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||||
|
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
|
||||||
|
|
||||||
|
# Ensure 413 returns JSON + CORS
|
||||||
|
error_page 413 = @payload_too_large;
|
||||||
|
location @payload_too_large {
|
||||||
|
default_type application/json;
|
||||||
|
return 413 '{"error":"Payload too large (413). Please upload a smaller file."}';
|
||||||
|
}
|
||||||
|
|
||||||
|
# Ensure 429 (rate limited) returns JSON + CORS
|
||||||
|
error_page 429 = @rate_limited;
|
||||||
|
location @rate_limited {
|
||||||
|
default_type application/json;
|
||||||
|
add_header 'Access-Control-Allow-Origin' $cors_origin always;
|
||||||
|
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||||
|
return 429 '{"error":"Too many requests. Please slow down."}';
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
limit_req zone=spanglish_photo_limit burst=40 nodelay;
|
||||||
|
|
||||||
|
# Preflight
|
||||||
|
if ($request_method = 'OPTIONS') {
|
||||||
|
add_header 'Access-Control-Allow-Origin' $cors_origin always;
|
||||||
|
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, OPTIONS' always;
|
||||||
|
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
|
||||||
|
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||||
|
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
|
||||||
|
add_header 'Access-Control-Max-Age' 86400 always;
|
||||||
|
add_header 'Content-Type' 'text/plain; charset=utf-8';
|
||||||
|
add_header 'Content-Length' 0;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy_pass http://spanglish_photo_api;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Origin';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Methods';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Headers';
|
||||||
|
proxy_hide_header 'Access-Control-Allow-Credentials';
|
||||||
|
proxy_hide_header 'Access-Control-Expose-Headers';
|
||||||
|
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 300s;
|
||||||
|
|
||||||
|
# Buffer large image uploads to disk rather than memory
|
||||||
|
proxy_request_buffering on;
|
||||||
|
proxy_max_temp_file_size 1024m;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
upstream spanglish_frontend {
|
||||||
|
server 127.0.0.1:3019;
|
||||||
|
}
|
||||||
|
upstream spanglish_backend {
|
||||||
|
server 127.0.0.1:3018;
|
||||||
|
}
|
||||||
|
upstream spanglish_photo_api {
|
||||||
|
server 127.0.0.1:3003;
|
||||||
|
}
|
||||||
|
|
||||||
|
limit_req_zone $binary_remote_addr zone=spanglish_photo_limit:10m rate=20r/s;
|
||||||
|
limit_req_zone $binary_remote_addr zone=spanglish_api_limit:10m rate=30r/s;
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Spanglish Photo Gallery API
|
||||||
|
Documentation=https://git.azzamo.net/Michilis/Spanglish
|
||||||
|
After=network.target spanglish-backend.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=spanglish
|
||||||
|
Group=spanglish
|
||||||
|
WorkingDirectory=/home/spanglish/Spanglish/photo-api
|
||||||
|
EnvironmentFile=/home/spanglish/Spanglish/photo-api/.env
|
||||||
|
Environment=PORT=3020
|
||||||
|
# Apply pending photos_* migrations before serving (idempotent, advisory-locked)
|
||||||
|
ExecStartPre=/home/spanglish/Spanglish/photo-api/bin/photo-api migrate
|
||||||
|
ExecStart=/home/spanglish/Spanglish/photo-api/bin/photo-api
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=10
|
||||||
|
StandardOutput=syslog
|
||||||
|
StandardError=syslog
|
||||||
|
SyslogIdentifier=spanglish-photos
|
||||||
|
|
||||||
|
# Security hardening (mirrors spanglish-backend.service)
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=read-only
|
||||||
|
ReadWritePaths=/home/spanglish/Spanglish/photo-api/data
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -5,3 +5,7 @@ upstream spanglish_frontend {
|
|||||||
upstream spanglish_backend {
|
upstream spanglish_backend {
|
||||||
server 127.0.0.1:3018;
|
server 127.0.0.1:3018;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
upstream spanglish_photos {
|
||||||
|
server 127.0.0.1:3020;
|
||||||
|
}
|
||||||
@@ -7,6 +7,11 @@ NEXT_PUBLIC_SITE_URL=https://spanglishcommunity.com
|
|||||||
# API URL (leave empty for same-origin proxy)
|
# API URL (leave empty for same-origin proxy)
|
||||||
NEXT_PUBLIC_API_URL=
|
NEXT_PUBLIC_API_URL=
|
||||||
|
|
||||||
|
# Photo gallery service (photo-api) origin, used by the /api/photos rewrite
|
||||||
|
# and server-side rendering of /photos pages.
|
||||||
|
# Dev default: http://localhost:3003 — production: http://127.0.0.1:3020
|
||||||
|
PHOTO_API_URL=
|
||||||
|
|
||||||
# Google OAuth (optional - leave empty to hide Google Sign-In button)
|
# Google OAuth (optional - leave empty to hide Google Sign-In button)
|
||||||
# Get your Client ID from: https://console.cloud.google.com/apis/credentials
|
# Get your Client ID from: https://console.cloud.google.com/apis/credentials
|
||||||
# 1. Create a new OAuth 2.0 Client ID (Web application)
|
# 1. Create a new OAuth 2.0 Client ID (Web application)
|
||||||
|
|||||||
@@ -4,6 +4,10 @@
|
|||||||
// being hardcoded to localhost.
|
// being hardcoded to localhost.
|
||||||
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3001';
|
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3001';
|
||||||
|
|
||||||
|
// The standalone photo gallery service (photo-api/). Must be rewritten
|
||||||
|
// before the generic /api rule below — Next rewrites are order-sensitive.
|
||||||
|
const PHOTO_API_URL = process.env.PHOTO_API_URL || 'http://localhost:3003';
|
||||||
|
|
||||||
// Extra image hosts can be allowed via a comma-separated env var (e.g. a CDN).
|
// Extra image hosts can be allowed via a comma-separated env var (e.g. a CDN).
|
||||||
const extraImageHosts = (process.env.NEXT_PUBLIC_IMAGE_HOSTS || '')
|
const extraImageHosts = (process.env.NEXT_PUBLIC_IMAGE_HOSTS || '')
|
||||||
.split(',')
|
.split(',')
|
||||||
@@ -20,6 +24,9 @@ const securityHeaders = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
const nextConfig = {
|
const nextConfig = {
|
||||||
|
// Overridable so a production build can run while `next dev` holds .next
|
||||||
|
// (e.g. NEXT_DIST_DIR=.next-build npm run build).
|
||||||
|
distDir: process.env.NEXT_DIST_DIR || '.next',
|
||||||
images: {
|
images: {
|
||||||
// Restrict remote image sources to a known allowlist instead of allowing any
|
// Restrict remote image sources to a known allowlist instead of allowing any
|
||||||
// https host (which let the Next image optimizer be used as an open proxy).
|
// https host (which let the Next image optimizer be used as an open proxy).
|
||||||
@@ -39,6 +46,10 @@ const nextConfig = {
|
|||||||
},
|
},
|
||||||
async rewrites() {
|
async rewrites() {
|
||||||
return [
|
return [
|
||||||
|
{
|
||||||
|
source: '/api/photos/:path*',
|
||||||
|
destination: `${PHOTO_API_URL}/api/photos/:path*`,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
source: '/api/:path*',
|
source: '/api/:path*',
|
||||||
destination: `${BACKEND_URL}/api/:path*`,
|
destination: `${BACKEND_URL}/api/:path*`,
|
||||||
|
|||||||
@@ -6,7 +6,8 @@
|
|||||||
"dev": "dotenv -e .env -- next dev",
|
"dev": "dotenv -e .env -- next dev",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "dotenv -e .env -- next start",
|
"start": "dotenv -e .env -- next start",
|
||||||
"lint": "next lint"
|
"lint": "next lint",
|
||||||
|
"test": "vitest run"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@heroicons/react": "^2.1.4",
|
"@heroicons/react": "^2.1.4",
|
||||||
@@ -14,6 +15,7 @@
|
|||||||
"@tiptap/pm": "^3.18.0",
|
"@tiptap/pm": "^3.18.0",
|
||||||
"@tiptap/react": "^3.18.0",
|
"@tiptap/react": "^3.18.0",
|
||||||
"@tiptap/starter-kit": "^3.18.0",
|
"@tiptap/starter-kit": "^3.18.0",
|
||||||
|
"better-auth": "1.6.25",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"html5-qrcode": "^2.3.8",
|
"html5-qrcode": "^2.3.8",
|
||||||
"next": "^14.2.4",
|
"next": "^14.2.4",
|
||||||
@@ -22,6 +24,7 @@
|
|||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-hot-toast": "^2.4.1",
|
"react-hot-toast": "^2.4.1",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
|
"recharts": "^2.15.4",
|
||||||
"remark-gfm": "^4.0.1"
|
"remark-gfm": "^4.0.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -32,6 +35,7 @@
|
|||||||
"dotenv-cli": "^11.0.0",
|
"dotenv-cli": "^11.0.0",
|
||||||
"postcss": "^8.4.38",
|
"postcss": "^8.4.38",
|
||||||
"tailwindcss": "^3.4.4",
|
"tailwindcss": "^3.4.4",
|
||||||
"typescript": "^5.5.2"
|
"typescript": "^5.5.2",
|
||||||
|
"vitest": "^4.1.10"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, Suspense } from 'react';
|
import { useEffect, useState, Suspense } from 'react';
|
||||||
import { useRouter, useSearchParams } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { useLanguage } from '@/context/LanguageContext';
|
import { useLanguage } from '@/context/LanguageContext';
|
||||||
import { useAuth } from '@/context/AuthContext';
|
import { useAuth } from '@/context/AuthContext';
|
||||||
@@ -9,29 +9,48 @@ import Card from '@/components/ui/Card';
|
|||||||
import Button from '@/components/ui/Button';
|
import Button from '@/components/ui/Button';
|
||||||
import Input from '@/components/ui/Input';
|
import Input from '@/components/ui/Input';
|
||||||
import { authApi } from '@/lib/api';
|
import { authApi } from '@/lib/api';
|
||||||
|
import { authClient } from '@/lib/auth-client';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Progressive-account claim. The claim email contains a magic link that signs
|
||||||
|
* the user in (via /auth/magic-link) and redirects here; this page then asks
|
||||||
|
* for a password and completes the claim against /api/auth-ext/claim-account.
|
||||||
|
*/
|
||||||
function ClaimAccountContent() {
|
function ClaimAccountContent() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const searchParams = useSearchParams();
|
|
||||||
const { locale: language } = useLanguage();
|
const { locale: language } = useLanguage();
|
||||||
const { setAuthData } = useAuth();
|
const { refreshUser } = useAuth();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [checking, setChecking] = useState(true);
|
||||||
|
const [hasSession, setHasSession] = useState(false);
|
||||||
|
const [alreadyClaimed, setAlreadyClaimed] = useState(false);
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
password: '',
|
password: '',
|
||||||
confirmPassword: '',
|
confirmPassword: '',
|
||||||
});
|
});
|
||||||
|
|
||||||
const token = searchParams.get('token');
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
authClient
|
||||||
|
.getSession()
|
||||||
|
.then(({ data }) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
const user: any = data?.user;
|
||||||
|
setHasSession(!!user);
|
||||||
|
setAlreadyClaimed(!!user && user.isClaimed && user.accountStatus === 'active');
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!cancelled) setChecking(false);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
if (!token) {
|
|
||||||
toast.error(language === 'es' ? 'Token no válido' : 'Invalid token');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (formData.password !== formData.confirmPassword) {
|
if (formData.password !== formData.confirmPassword) {
|
||||||
toast.error(language === 'es' ? 'Las contraseñas no coinciden' : 'Passwords do not match');
|
toast.error(language === 'es' ? 'Las contraseñas no coinciden' : 'Passwords do not match');
|
||||||
return;
|
return;
|
||||||
@@ -49,8 +68,8 @@ function ClaimAccountContent() {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await authApi.confirmClaimAccount(token, { password: formData.password });
|
await authApi.confirmClaimAccount(formData.password);
|
||||||
setAuthData({ user: result.user, token: result.token });
|
await refreshUser();
|
||||||
toast.success(language === 'es' ? '¡Cuenta activada!' : 'Account activated!');
|
toast.success(language === 'es' ? '¡Cuenta activada!' : 'Account activated!');
|
||||||
router.push('/dashboard');
|
router.push('/dashboard');
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
@@ -60,7 +79,21 @@ function ClaimAccountContent() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!token) {
|
if (checking) {
|
||||||
|
return (
|
||||||
|
<div className="section-padding min-h-[70vh] flex items-center justify-center">
|
||||||
|
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-secondary-blue"></div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (alreadyClaimed) {
|
||||||
|
// Signed-in and already active: nothing to claim
|
||||||
|
router.push('/dashboard');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasSession) {
|
||||||
return (
|
return (
|
||||||
<div className="section-padding min-h-[70vh] flex items-center">
|
<div className="section-padding min-h-[70vh] flex items-center">
|
||||||
<div className="container-page">
|
<div className="container-page">
|
||||||
@@ -76,8 +109,8 @@ function ClaimAccountContent() {
|
|||||||
</h2>
|
</h2>
|
||||||
<p className="text-gray-600 mb-6">
|
<p className="text-gray-600 mb-6">
|
||||||
{language === 'es'
|
{language === 'es'
|
||||||
? 'Este enlace de activación no es válido o ha expirado.'
|
? 'Este enlace de activación no es válido o ha expirado. Solicita uno nuevo con "Enlace por Email" en la página de inicio de sesión.'
|
||||||
: 'This activation link is invalid or has expired.'}
|
: 'This activation link is invalid or has expired. Request a new one using "Email Link" on the login page.'}
|
||||||
</p>
|
</p>
|
||||||
<Link href="/login">
|
<Link href="/login">
|
||||||
<Button>
|
<Button>
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { useLanguage } from '@/context/LanguageContext';
|
|||||||
import { useAuth } from '@/context/AuthContext';
|
import { useAuth } from '@/context/AuthContext';
|
||||||
import Card from '@/components/ui/Card';
|
import Card from '@/components/ui/Card';
|
||||||
import Button from '@/components/ui/Button';
|
import Button from '@/components/ui/Button';
|
||||||
|
import { safeInternalPath } from '@/lib/safeRedirect';
|
||||||
|
import { redirectAfterAuth } from '@/lib/authRedirect';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
|
|
||||||
function MagicLinkContent() {
|
function MagicLinkContent() {
|
||||||
@@ -18,6 +20,7 @@ function MagicLinkContent() {
|
|||||||
const verificationAttempted = useRef(false);
|
const verificationAttempted = useRef(false);
|
||||||
|
|
||||||
const token = searchParams.get('token');
|
const token = searchParams.get('token');
|
||||||
|
const callbackURL = safeInternalPath(searchParams.get('callbackURL'), '/dashboard');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Prevent duplicate verification attempts (React StrictMode double-invokes effects)
|
// Prevent duplicate verification attempts (React StrictMode double-invokes effects)
|
||||||
@@ -34,11 +37,17 @@ function MagicLinkContent() {
|
|||||||
|
|
||||||
const verifyToken = async () => {
|
const verifyToken = async () => {
|
||||||
try {
|
try {
|
||||||
await loginWithMagicLink(token!);
|
const user = await loginWithMagicLink(token!);
|
||||||
setStatus('success');
|
setStatus('success');
|
||||||
toast.success(language === 'es' ? '¡Bienvenido!' : 'Welcome!');
|
toast.success(language === 'es' ? '¡Bienvenido!' : 'Welcome!');
|
||||||
|
// Unclaimed accounts must finish the claim (set a password) before the
|
||||||
|
// rest of the API will accept their session.
|
||||||
|
const destination =
|
||||||
|
user && (user.isClaimed === false || user.accountStatus === 'unclaimed')
|
||||||
|
? '/auth/claim-account'
|
||||||
|
: callbackURL;
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
router.push('/dashboard');
|
redirectAfterAuth(destination);
|
||||||
}, 1500);
|
}, 1500);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
setStatus('error');
|
setStatus('error');
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { useParams, useRouter, useSearchParams } from 'next/navigation';
|
|||||||
import { useLanguage } from '@/context/LanguageContext';
|
import { useLanguage } from '@/context/LanguageContext';
|
||||||
import { useAuth } from '@/context/AuthContext';
|
import { useAuth } from '@/context/AuthContext';
|
||||||
import { eventsApi, ticketsApi, paymentOptionsApi, Event, PaymentOptionsConfig } from '@/lib/api';
|
import { eventsApi, ticketsApi, paymentOptionsApi, Event, PaymentOptionsConfig } from '@/lib/api';
|
||||||
import { formatDateLong, formatTime, formatRucDisplay } from '@/lib/utils';
|
import { formatDateLong, formatTime, formatRucDisplay, eventSpotsLeft, isEventSoldOut, isPresaleClosed } from '@/lib/utils';
|
||||||
import { isSafeExternalUrl } from '@/lib/safeRedirect';
|
import { isSafeExternalUrl } from '@/lib/safeRedirect';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
import type {
|
import type {
|
||||||
@@ -108,16 +108,23 @@ export default function BookingPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bookedCount = eventRes.event.bookedCount ?? 0;
|
// Pre-sale closure: the booking API rejects after the cutoff, so
|
||||||
const capacity = eventRes.event.capacity ?? 0;
|
// bounce back to the event page instead of showing a dead form.
|
||||||
const soldOut = bookedCount >= capacity;
|
if (isPresaleClosed(eventRes.event)) {
|
||||||
if (soldOut) {
|
toast.error(t('events.details.registrationClosed'));
|
||||||
|
router.push(`/events/${eventRes.event.slug}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server-authoritative availability — same formula the booking API
|
||||||
|
// enforces, so a sold-out event is caught here, not at submit time.
|
||||||
|
if (isEventSoldOut(eventRes.event)) {
|
||||||
toast.error(t('events.details.soldOut'));
|
toast.error(t('events.details.soldOut'));
|
||||||
router.push(`/events/${eventRes.event.slug}`);
|
router.push(`/events/${eventRes.event.slug}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const spotsLeft = Math.max(0, capacity - bookedCount);
|
const spotsLeft = eventSpotsLeft(eventRes.event);
|
||||||
setEvent(eventRes.event);
|
setEvent(eventRes.event);
|
||||||
// Cap quantity by available spots (never allow requesting more than spotsLeft)
|
// Cap quantity by available spots (never allow requesting more than spotsLeft)
|
||||||
setTicketQuantity((q) => Math.min(q, Math.max(1, spotsLeft)));
|
setTicketQuantity((q) => Math.min(q, Math.max(1, spotsLeft)));
|
||||||
@@ -365,7 +372,31 @@ export default function BookingPage() {
|
|||||||
toast.success(t('booking.success.message'));
|
toast.success(t('booking.success.message'));
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
|
const message = String(error?.message || '');
|
||||||
|
// Pre-sale closed while the form was open: send the user back to the
|
||||||
|
// event page, which now shows the "Registration Closed" state.
|
||||||
|
if (/registration .*closed/i.test(message)) {
|
||||||
|
toast.error(t('events.details.registrationClosed'));
|
||||||
|
if (event?.slug) router.push(`/events/${event.slug}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
toast.error(error.message || t('booking.form.errors.bookingFailed'));
|
toast.error(error.message || t('booking.form.errors.bookingFailed'));
|
||||||
|
// Capacity race on the last seats: refresh availability so the page
|
||||||
|
// reflects reality (sold-out block / lower quantity cap) instead of the
|
||||||
|
// stale counts loaded when the form was opened.
|
||||||
|
if (/sold out|seats available/i.test(message)) {
|
||||||
|
try {
|
||||||
|
const { event: freshEvent } = await eventsApi.getById(params.eventId as string);
|
||||||
|
setEvent(freshEvent);
|
||||||
|
const freshSpots = eventSpotsLeft(freshEvent);
|
||||||
|
if (freshSpots > 0) {
|
||||||
|
setTicketQuantity((q) => Math.min(q, freshSpots));
|
||||||
|
setAttendees((prev) => prev.slice(0, Math.max(0, freshSpots - 1)));
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Keep the stale event state if the refresh fails
|
||||||
|
}
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false);
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
@@ -388,8 +419,8 @@ export default function BookingPage() {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const spotsLeft = Math.max(0, event.capacity - (event.bookedCount ?? 0));
|
const spotsLeft = eventSpotsLeft(event);
|
||||||
const isSoldOut = (event.bookedCount ?? 0) >= event.capacity;
|
const isSoldOut = isEventSoldOut(event);
|
||||||
|
|
||||||
// Paying step - waiting for Lightning payment (compact design)
|
// Paying step - waiting for Lightning payment (compact design)
|
||||||
if (step === 'paying' && bookingResult && bookingResult.lightningInvoice) {
|
if (step === 'paying' && bookingResult && bookingResult.lightningInvoice) {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ interface AccountTabProps {
|
|||||||
*/
|
*/
|
||||||
export default function AccountTab({ onUpdate }: AccountTabProps) {
|
export default function AccountTab({ onUpdate }: AccountTabProps) {
|
||||||
const { locale } = useLanguage();
|
const { locale } = useLanguage();
|
||||||
const { user, updateUser, logout } = useAuth();
|
const { user, updateUser } = useAuth();
|
||||||
|
|
||||||
const [profile, setProfile] = useState<UserProfile | null>(null);
|
const [profile, setProfile] = useState<UserProfile | null>(null);
|
||||||
const [sessions, setSessions] = useState<UserSession[]>([]);
|
const [sessions, setSessions] = useState<UserSession[]>([]);
|
||||||
@@ -187,15 +187,17 @@ export default function AccountTab({ onUpdate }: AccountTabProps) {
|
|||||||
if (
|
if (
|
||||||
!confirm(
|
!confirm(
|
||||||
locale === 'es'
|
locale === 'es'
|
||||||
? '¿Cerrar todas las sesiones? Serás desconectado.'
|
? '¿Cerrar todas las otras sesiones? Esta sesión permanecerá activa.'
|
||||||
: 'Log out of all sessions? You will be logged out.'
|
: 'Log out of all other sessions? This session stays signed in.'
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return;
|
return;
|
||||||
try {
|
try {
|
||||||
await dashboardApi.revokeAllSessions();
|
await dashboardApi.revokeAllSessions();
|
||||||
toast.success(locale === 'es' ? 'Todas las sesiones cerradas' : 'All sessions revoked');
|
toast.success(
|
||||||
logout();
|
locale === 'es' ? 'Todas las otras sesiones cerradas' : 'All other sessions revoked'
|
||||||
|
);
|
||||||
|
loadData();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.error(locale === 'es' ? 'Error' : 'Failed');
|
toast.error(locale === 'es' ? 'Error' : 'Failed');
|
||||||
}
|
}
|
||||||
@@ -477,7 +479,7 @@ export default function AccountTab({ onUpdate }: AccountTabProps) {
|
|||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{sessions.map((session, index) => (
|
{sessions.map((session) => (
|
||||||
<div
|
<div
|
||||||
key={session.id}
|
key={session.id}
|
||||||
className="flex items-center justify-between rounded-card bg-secondary-gray p-3"
|
className="flex items-center justify-between rounded-card bg-secondary-gray p-3"
|
||||||
@@ -494,7 +496,7 @@ export default function AccountTab({ onUpdate }: AccountTabProps) {
|
|||||||
{session.ipAddress && ` • ${session.ipAddress}`}
|
{session.ipAddress && ` • ${session.ipAddress}`}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{index === 0 ? (
|
{session.current ? (
|
||||||
<span className="ml-3 whitespace-nowrap text-xs font-medium text-green-600">
|
<span className="ml-3 whitespace-nowrap text-xs font-medium text-green-600">
|
||||||
{locale === 'es' ? 'Esta sesión' : 'This session'}
|
{locale === 'es' ? 'Esta sesión' : 'This session'}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { CalendarIcon, MapPinIcon, ChevronRightIcon } from '@heroicons/react/24/outline';
|
||||||
|
import { useLanguage } from '@/context/LanguageContext';
|
||||||
|
import type { MyEvent } from '@/lib/api';
|
||||||
|
|
||||||
|
/** Events the user was added to as staff, collaborator or co-manager. */
|
||||||
|
export default function MyEventsTab({ events }: { events: MyEvent[] }) {
|
||||||
|
const { t, locale } = useLanguage();
|
||||||
|
if (events.length === 0) {
|
||||||
|
return <p className="text-sm text-gray-500 py-8 text-center">{t('dashboard.myEvents.empty')}</p>;
|
||||||
|
}
|
||||||
|
const fmt = (iso: string) =>
|
||||||
|
new Date(iso).toLocaleDateString(locale === 'es' ? 'es-PY' : 'en-US', { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className="space-y-3">
|
||||||
|
{events.map(({ event, rolePreset }) => (
|
||||||
|
<li key={event.id}>
|
||||||
|
<Link
|
||||||
|
href={`/dashboard/events/${event.id}`}
|
||||||
|
className="flex items-center gap-4 rounded-card bg-white p-4 shadow-card transition-shadow hover:shadow-card-hover"
|
||||||
|
>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="font-semibold text-primary-dark truncate">{(locale === 'es' && event.titleEs) || event.title}</p>
|
||||||
|
<p className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500">
|
||||||
|
<span className="inline-flex items-center gap-1"><CalendarIcon className="h-3.5 w-3.5" />{fmt(event.startDatetime)}</span>
|
||||||
|
<span className="inline-flex items-center gap-1 min-w-0"><MapPinIcon className="h-3.5 w-3.5 flex-shrink-0" /><span className="truncate">{event.location}</span></span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span className="rounded-full bg-yellow-100 px-2 py-0.5 text-xs font-medium text-yellow-800 whitespace-nowrap">
|
||||||
|
{t(`admin.rolePresets.${rolePreset}`)}
|
||||||
|
</span>
|
||||||
|
<ChevronRightIcon className="h-5 w-5 flex-shrink-0 text-gray-400" />
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -44,6 +44,7 @@ export default function PaymentsTab({ payments, language: locale, onChange }: Pa
|
|||||||
lightning: { en: 'Lightning (Bitcoin)', es: 'Lightning (Bitcoin)' },
|
lightning: { en: 'Lightning (Bitcoin)', es: 'Lightning (Bitcoin)' },
|
||||||
cash: { en: 'Cash', es: 'Efectivo' },
|
cash: { en: 'Cash', es: 'Efectivo' },
|
||||||
bancard: { en: 'Card', es: 'Tarjeta' },
|
bancard: { en: 'Card', es: 'Tarjeta' },
|
||||||
|
pos: { en: 'POS', es: 'POS' },
|
||||||
};
|
};
|
||||||
return labels[provider]?.[locale === 'es' ? 'es' : 'en'] || provider;
|
return labels[provider]?.[locale === 'es' ? 'es' : 'en'] || provider;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useParams } from 'next/navigation';
|
||||||
|
import { PrivacyProvider } from '@/context/PrivacyContext';
|
||||||
|
import { EventDetailView } from '@/app/admin/events/[id]/_components/EventDetailView';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The single event page for team members (staff / collaborators / co-managers
|
||||||
|
* added in the event's Team tab). Same view as the admin page; tabs and data
|
||||||
|
* follow the member's permissions on this event only.
|
||||||
|
*/
|
||||||
|
export default function MemberEventPage() {
|
||||||
|
const params = useParams();
|
||||||
|
return (
|
||||||
|
<PrivacyProvider>
|
||||||
|
<div className="section-padding min-h-[70vh]">
|
||||||
|
<div className="container-page">
|
||||||
|
<EventDetailView eventId={params.id as string} backHref="/dashboard?tab=events" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PrivacyProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,9 +6,11 @@ import { useLanguage } from '@/context/LanguageContext';
|
|||||||
import { useAuth } from '@/context/AuthContext';
|
import { useAuth } from '@/context/AuthContext';
|
||||||
import {
|
import {
|
||||||
dashboardApi,
|
dashboardApi,
|
||||||
|
financeApi,
|
||||||
NextEventInfo,
|
NextEventInfo,
|
||||||
UserTicket,
|
UserTicket,
|
||||||
UserPayment,
|
UserPayment,
|
||||||
|
type MyEvent,
|
||||||
} from '@/lib/api';
|
} from '@/lib/api';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
import { CardListSkeleton } from '@/components/ui/Skeleton';
|
import { CardListSkeleton } from '@/components/ui/Skeleton';
|
||||||
@@ -17,42 +19,55 @@ import OverviewTab from './components/OverviewTab';
|
|||||||
import TicketsTab from './components/TicketsTab';
|
import TicketsTab from './components/TicketsTab';
|
||||||
import PaymentsTab from './components/PaymentsTab';
|
import PaymentsTab from './components/PaymentsTab';
|
||||||
import AccountTab from './components/AccountTab';
|
import AccountTab from './components/AccountTab';
|
||||||
|
import MyEventsTab from './components/MyEventsTab';
|
||||||
|
|
||||||
type Tab = 'overview' | 'tickets' | 'payments' | 'account';
|
type Tab = 'overview' | 'tickets' | 'payments' | 'events' | 'account';
|
||||||
|
|
||||||
export default function DashboardPage() {
|
export default function DashboardPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { locale } = useLanguage();
|
const { locale, t } = useLanguage();
|
||||||
const { user, isLoading: authLoading, token } = useAuth();
|
const { user, isLoading: authLoading } = useAuth();
|
||||||
|
|
||||||
const [activeTab, setActiveTab] = useState<Tab>('overview');
|
const [activeTab, setActiveTab] = useState<Tab>('overview');
|
||||||
const [nextEvent, setNextEvent] = useState<NextEventInfo | null>(null);
|
const [nextEvent, setNextEvent] = useState<NextEventInfo | null>(null);
|
||||||
const [tickets, setTickets] = useState<UserTicket[]>([]);
|
const [tickets, setTickets] = useState<UserTicket[]>([]);
|
||||||
const [payments, setPayments] = useState<UserPayment[]>([]);
|
const [payments, setPayments] = useState<UserPayment[]>([]);
|
||||||
|
const [myEvents, setMyEvents] = useState<MyEvent[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
// ?tab=events (the back link from a team event page) opens My Events.
|
||||||
|
useEffect(() => {
|
||||||
|
const tab = new URLSearchParams(window.location.search).get('tab');
|
||||||
|
if (tab === 'events') setActiveTab('events');
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!authLoading && !user) {
|
if (!authLoading && !user) {
|
||||||
router.push('/login');
|
router.push('/login');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (user && token) {
|
// Auth rides on the httpOnly session cookie; once the user has resolved
|
||||||
|
// the API calls are authenticated automatically.
|
||||||
|
if (user) {
|
||||||
loadDashboardData();
|
loadDashboardData();
|
||||||
}
|
}
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [user, authLoading, token]);
|
}, [user, authLoading]);
|
||||||
|
|
||||||
const loadDashboardData = async () => {
|
const loadDashboardData = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const [nextEventRes, ticketsRes, paymentsRes] = await Promise.all([
|
const [nextEventRes, ticketsRes, paymentsRes, myEventsRes] = await Promise.all([
|
||||||
dashboardApi.getNextEvent(),
|
dashboardApi.getNextEvent(),
|
||||||
dashboardApi.getTickets(),
|
dashboardApi.getTickets(),
|
||||||
dashboardApi.getPayments(),
|
dashboardApi.getPayments(),
|
||||||
|
// Team memberships are optional extra; never fail the dashboard over them.
|
||||||
|
financeApi.myEvents().catch(() => ({ events: [] as MyEvent[] })),
|
||||||
]);
|
]);
|
||||||
setNextEvent(nextEventRes.nextEvent);
|
setNextEvent(nextEventRes.nextEvent);
|
||||||
setTickets(ticketsRes.tickets);
|
setTickets(ticketsRes.tickets);
|
||||||
setPayments(paymentsRes.payments);
|
setPayments(paymentsRes.payments);
|
||||||
|
setMyEvents(myEventsRes.events);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load dashboard:', error);
|
console.error('Failed to load dashboard:', error);
|
||||||
toast.error(locale === 'es' ? 'Error al cargar el panel' : 'Failed to load dashboard data');
|
toast.error(locale === 'es' ? 'Error al cargar el panel' : 'Failed to load dashboard data');
|
||||||
@@ -65,6 +80,8 @@ export default function DashboardPage() {
|
|||||||
{ id: 'overview', label: { en: 'Overview', es: 'Resumen' } },
|
{ id: 'overview', label: { en: 'Overview', es: 'Resumen' } },
|
||||||
{ id: 'tickets', label: { en: 'Tickets', es: 'Entradas' } },
|
{ id: 'tickets', label: { en: 'Tickets', es: 'Entradas' } },
|
||||||
{ id: 'payments', label: { en: 'Payments', es: 'Pagos' } },
|
{ id: 'payments', label: { en: 'Payments', es: 'Pagos' } },
|
||||||
|
// Only for people on at least one event team
|
||||||
|
...(myEvents.length > 0 ? [{ id: 'events' as Tab, label: { en: t('dashboard.myEvents.tab'), es: t('dashboard.myEvents.tab') } }] : []),
|
||||||
{ id: 'account', label: { en: 'Account', es: 'Cuenta' } },
|
{ id: 'account', label: { en: 'Account', es: 'Cuenta' } },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -123,6 +140,7 @@ export default function DashboardPage() {
|
|||||||
{activeTab === 'payments' && (
|
{activeTab === 'payments' && (
|
||||||
<PaymentsTab payments={payments} language={locale} onChange={loadDashboardData} />
|
<PaymentsTab payments={payments} language={locale} onChange={loadDashboardData} />
|
||||||
)}
|
)}
|
||||||
|
{activeTab === 'events' && <MyEventsTab events={myEvents} />}
|
||||||
{activeTab === 'account' && <AccountTab onUpdate={loadDashboardData} />}
|
{activeTab === 'account' && <AccountTab onUpdate={loadDashboardData} />}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -18,11 +18,14 @@ export default function EventsClient({ initialEvents }: { initialEvents: Event[]
|
|||||||
const [filter, setFilter] = useState<'upcoming' | 'past'>('upcoming');
|
const [filter, setFilter] = useState<'upcoming' | 'past'>('upcoming');
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
|
// An event that has started but still sells at the door stays under Upcoming.
|
||||||
|
const isUpcoming = (e: Event) =>
|
||||||
|
new Date(e.startDatetime) >= now || e.salesState === 'door';
|
||||||
const upcomingEvents = initialEvents.filter(e =>
|
const upcomingEvents = initialEvents.filter(e =>
|
||||||
e.status === 'published' && new Date(e.startDatetime) >= now
|
e.status === 'published' && isUpcoming(e)
|
||||||
);
|
);
|
||||||
const pastEvents = initialEvents.filter(e =>
|
const pastEvents = initialEvents.filter(e =>
|
||||||
e.status === 'completed' || (e.status === 'published' && new Date(e.startDatetime) < now)
|
e.status === 'completed' || (e.status === 'published' && !isUpcoming(e))
|
||||||
);
|
);
|
||||||
|
|
||||||
const displayedEvents = filter === 'upcoming' ? upcomingEvents : pastEvents;
|
const displayedEvents = filter === 'upcoming' ? upcomingEvents : pastEvents;
|
||||||
@@ -34,9 +37,16 @@ export default function EventsClient({ initialEvents }: { initialEvents: Event[]
|
|||||||
if (event.status === 'cancelled') {
|
if (event.status === 'cancelled') {
|
||||||
return <span className="badge badge-danger">{t('events.details.cancelled')}</span>;
|
return <span className="badge badge-danger">{t('events.details.cancelled')}</span>;
|
||||||
}
|
}
|
||||||
if (event.availableSeats === 0) {
|
if (event.salesState === 'sold_out' || event.availableSeats === 0) {
|
||||||
return <span className="badge badge-warning">{t('events.details.soldOut')}</span>;
|
return <span className="badge badge-warning">{t('events.details.soldOut')}</span>;
|
||||||
}
|
}
|
||||||
|
if (event.salesState === 'door') {
|
||||||
|
return (
|
||||||
|
<span className="badge bg-primary-yellow/20 text-primary-dark whitespace-nowrap">
|
||||||
|
{t('events.door.badge')}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
import { useLanguage } from '@/context/LanguageContext';
|
import { useLanguage } from '@/context/LanguageContext';
|
||||||
import { eventsApi, Event } from '@/lib/api';
|
import { eventsApi, Event } from '@/lib/api';
|
||||||
import { formatPrice, formatDateLong, formatTime } from '@/lib/utils';
|
import { formatPrice, formatDateLong, formatTime, eventSpotsLeft, isEventSoldOut, isPresaleClosed, parseDate, formatDurationWords, nextSalesStateChangeMs } from '@/lib/utils';
|
||||||
import Card from '@/components/ui/Card';
|
import Card from '@/components/ui/Card';
|
||||||
import Button from '@/components/ui/Button';
|
import Button from '@/components/ui/Button';
|
||||||
import ShareButtons from '@/components/ShareButtons';
|
import ShareButtons from '@/components/ShareButtons';
|
||||||
@@ -24,6 +24,10 @@ interface EventDetailClientProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const MAX_TICKETS_PER_PERSON = 5;
|
const MAX_TICKETS_PER_PERSON = 5;
|
||||||
|
// setTimeout overflows past ~24.8 days; farther flips are caught on a later visit.
|
||||||
|
const MAX_TIMER_MS = 2_147_483_647;
|
||||||
|
// Display order of door tenders ("card" is the POS terminal; never a provider name).
|
||||||
|
const DOOR_METHOD_ORDER = ['cash', 'pos', 'bitcoin', 'transfer'] as const;
|
||||||
|
|
||||||
export default function EventDetailClient({ eventId, initialEvent }: EventDetailClientProps) {
|
export default function EventDetailClient({ eventId, initialEvent }: EventDetailClientProps) {
|
||||||
const { t, locale } = useLanguage();
|
const { t, locale } = useLanguage();
|
||||||
@@ -36,16 +40,54 @@ export default function EventDetailClient({ eventId, initialEvent }: EventDetail
|
|||||||
setMounted(true);
|
setMounted(true);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Refresh event data on client for real-time availability
|
// Server clock minus ours, so the refresh below fires on the server's schedule.
|
||||||
useEffect(() => {
|
const [clockOffsetMs, setClockOffsetMs] = useState(0);
|
||||||
|
|
||||||
|
const refreshEvent = useCallback(() => {
|
||||||
|
const sentAt = Date.now();
|
||||||
eventsApi.getById(eventId)
|
eventsApi.getById(eventId)
|
||||||
.then(({ event }) => setEvent(event))
|
.then(({ event, serverTime }) => {
|
||||||
|
setEvent(event);
|
||||||
|
if (serverTime) {
|
||||||
|
const receivedAt = Date.now();
|
||||||
|
setClockOffsetMs(parseDate(serverTime).getTime() - (sentAt + receivedAt) / 2);
|
||||||
|
}
|
||||||
|
})
|
||||||
.catch(console.error);
|
.catch(console.error);
|
||||||
}, [eventId]);
|
}, [eventId]);
|
||||||
|
|
||||||
// Spots left: never negative; sold out when confirmed >= capacity
|
// Refresh event data on client for real-time availability. The server-rendered
|
||||||
const spotsLeft = Math.max(0, event.capacity - (event.bookedCount ?? 0));
|
// copy can be up to a minute old (fetch revalidate), so this also corrects a
|
||||||
const isSoldOut = (event.bookedCount ?? 0) >= event.capacity;
|
// stale sales state right after load.
|
||||||
|
useEffect(() => {
|
||||||
|
refreshEvent();
|
||||||
|
}, [refreshEvent]);
|
||||||
|
|
||||||
|
// salesState flips on the clock (online → door at presaleClosesAt, door →
|
||||||
|
// ended at the end time) without any edit to the event: refetch at that moment
|
||||||
|
// so an open page stops offering online booking. Overdue flips retry after 3s.
|
||||||
|
useEffect(() => {
|
||||||
|
const changeAt = nextSalesStateChangeMs(event);
|
||||||
|
if (changeAt === null) return;
|
||||||
|
const delay = Math.max(changeAt - (Date.now() + clockOffsetMs) + 1000, 3000);
|
||||||
|
if (delay > MAX_TIMER_MS) return;
|
||||||
|
const timer = setTimeout(refreshEvent, delay);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [event, clockOffsetMs, refreshEvent]);
|
||||||
|
|
||||||
|
// Phones suspend timers in background tabs; catch up when the page is shown again.
|
||||||
|
useEffect(() => {
|
||||||
|
const onVisible = () => {
|
||||||
|
if (document.visibilityState === 'visible') refreshEvent();
|
||||||
|
};
|
||||||
|
document.addEventListener('visibilitychange', onVisible);
|
||||||
|
return () => document.removeEventListener('visibilitychange', onVisible);
|
||||||
|
}, [refreshEvent]);
|
||||||
|
|
||||||
|
// Server-authoritative availability (paid + claimed seats count; abandoned
|
||||||
|
// pending bookings don't) — matches the booking API's sold-out check exactly.
|
||||||
|
const spotsLeft = eventSpotsLeft(event);
|
||||||
|
const isSoldOut = isEventSoldOut(event);
|
||||||
const maxTickets = isSoldOut ? 0 : Math.min(MAX_TICKETS_PER_PERSON, Math.max(1, spotsLeft));
|
const maxTickets = isSoldOut ? 0 : Math.min(MAX_TICKETS_PER_PERSON, Math.max(1, spotsLeft));
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -66,12 +108,78 @@ export default function EventDetailClient({ eventId, initialEvent }: EventDetail
|
|||||||
const fmtTime = (dateStr: string) => formatTime(dateStr, locale as 'en' | 'es');
|
const fmtTime = (dateStr: string) => formatTime(dateStr, locale as 'en' | 'es');
|
||||||
|
|
||||||
const isCancelled = event.status === 'cancelled';
|
const isCancelled = event.status === 'cancelled';
|
||||||
|
// Server-computed sales state (backend lib/salesState.ts). External booking
|
||||||
|
// events, and any cached copy from before salesState existed, keep the
|
||||||
|
// original client-side rules below.
|
||||||
|
const salesState = event.salesState;
|
||||||
|
const legacyRules = !salesState || salesState === 'external';
|
||||||
|
const isDoorSales = salesState === 'door' && typeof event.doorPrice === 'number';
|
||||||
|
const hasEnded = salesState === 'ended';
|
||||||
// Only calculate isPastEvent after mount to avoid hydration mismatch
|
// Only calculate isPastEvent after mount to avoid hydration mismatch
|
||||||
const isPastEvent = mounted ? new Date(event.startDatetime) < new Date() : false;
|
const isPastEvent = legacyRules ? (mounted ? new Date(event.startDatetime) < new Date() : false) : hasEnded;
|
||||||
const canBook = !isSoldOut && !isCancelled && !isPastEvent && (event.status === 'published' || event.status === 'unlisted');
|
// Pre-sale closure (server-computed cutoff); same mount guard as isPastEvent
|
||||||
|
const presaleClosed = legacyRules ? (mounted ? isPresaleClosed(event) : false) : salesState === 'door';
|
||||||
|
const canBook = legacyRules
|
||||||
|
? !isSoldOut && !isCancelled && !isPastEvent && !presaleClosed && (event.status === 'published' || event.status === 'unlisted')
|
||||||
|
: salesState === 'online';
|
||||||
|
// Effective lead time (event override or site default), derived from the server cutoff
|
||||||
|
const presaleLeadMinutes = event.presaleClosesAt
|
||||||
|
? Math.max(0, Math.round((parseDate(event.startDatetime).getTime() - parseDate(event.presaleClosesAt).getTime()) / 60_000))
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const spotsLeftText = spotsLeft === 1
|
||||||
|
? t('events.door.spotsLeftOne')
|
||||||
|
: t('events.door.spotsLeft', { n: spotsLeft });
|
||||||
|
const doorMethodsText = DOOR_METHOD_ORDER
|
||||||
|
.filter((method) => event.doorPaymentMethods?.includes(method))
|
||||||
|
.map((method) => t(`events.door.methods.${method}`))
|
||||||
|
.join(', ');
|
||||||
|
|
||||||
|
// Online sales closed but seats left: people can still come and pay at the
|
||||||
|
// door. Informational only — there is nothing to click.
|
||||||
|
const DoorSalesBlock = () => {
|
||||||
|
const doorPrice = event.doorPrice ?? event.price;
|
||||||
|
return (
|
||||||
|
<div className="rounded-card bg-primary-yellow/15 border border-primary-yellow/40 px-5 py-6 text-center">
|
||||||
|
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
|
||||||
|
{t('events.door.onlineClosed')}
|
||||||
|
</p>
|
||||||
|
<p className="mt-1 text-lg font-semibold text-primary-dark">
|
||||||
|
{t('events.door.headline')}
|
||||||
|
</p>
|
||||||
|
<p className="mt-4 text-4xl font-bold text-primary-dark">
|
||||||
|
{doorPrice === 0 ? t('events.details.free') : formatPrice(doorPrice, event.currency)}
|
||||||
|
</p>
|
||||||
|
{doorPrice > 0 && (
|
||||||
|
<p className="text-xs text-gray-500 mt-1">{t('events.door.perPerson')}</p>
|
||||||
|
)}
|
||||||
|
{doorPrice > event.price && event.price > 0 && (
|
||||||
|
<p className="mt-2 text-sm text-gray-500">
|
||||||
|
{t('events.door.onlinePriceWas', { price: formatPrice(event.price, event.currency) })}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="mt-4 text-sm font-medium text-primary-dark">{spotsLeftText}</p>
|
||||||
|
{doorMethodsText && (
|
||||||
|
<p className="mt-1 text-xs text-gray-500">{t('events.door.accepts', { methods: doorMethodsText })}</p>
|
||||||
|
)}
|
||||||
|
<p className="mt-1 text-xs text-gray-500" suppressHydrationWarning>
|
||||||
|
{t('events.door.doorsOpen', { time: fmtTime(event.startDatetime) })}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
// Booking card content - reused for mobile and desktop positions
|
// Booking card content - reused for mobile and desktop positions
|
||||||
const BookingCardContent = () => (
|
const BookingCardContent = () => {
|
||||||
|
if (isDoorSales) return <DoorSalesBlock />;
|
||||||
|
if (hasEnded) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-card bg-secondary-gray px-5 py-6 text-center">
|
||||||
|
<p className="text-lg font-semibold text-primary-dark">{t('events.details.eventHasEnded')}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="text-center mb-4">
|
<div className="text-center mb-4">
|
||||||
<p className="text-sm text-gray-500">{t('events.details.price')}</p>
|
<p className="text-sm text-gray-500">{t('events.details.price')}</p>
|
||||||
@@ -142,12 +250,24 @@ export default function EventDetailClient({ eventId, initialEvent }: EventDetail
|
|||||||
<Button className="w-full" size="lg" disabled>
|
<Button className="w-full" size="lg" disabled>
|
||||||
{isPastEvent
|
{isPastEvent
|
||||||
? t('events.details.eventEnded')
|
? t('events.details.eventEnded')
|
||||||
|
: presaleClosed
|
||||||
|
? t('events.details.registrationClosed')
|
||||||
: isSoldOut
|
: isSoldOut
|
||||||
? t('events.details.soldOut')
|
? t('events.details.soldOut')
|
||||||
: t('events.details.cancelled')}
|
: t('events.details.cancelled')}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{canBook && !event.externalBookingEnabled && presaleLeadMinutes !== null && (
|
||||||
|
<p className="mt-3 text-center text-xs text-gray-400">
|
||||||
|
{presaleLeadMinutes > 0
|
||||||
|
? t('events.details.presaleClosesBefore', {
|
||||||
|
duration: formatDurationWords(presaleLeadMinutes, locale as 'en' | 'es'),
|
||||||
|
})
|
||||||
|
: t('events.details.presaleClosesAtStart')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
{!event.externalBookingEnabled && (
|
{!event.externalBookingEnabled && (
|
||||||
<p className="mt-4 text-center text-sm text-gray-500">
|
<p className="mt-4 text-center text-sm text-gray-500">
|
||||||
{spotsLeft} / {event.capacity} {t('events.details.spotsLeft')}
|
{spotsLeft} / {event.capacity} {t('events.details.spotsLeft')}
|
||||||
@@ -155,6 +275,7 @@ export default function EventDetailClient({ eventId, initialEvent }: EventDetail
|
|||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="section-padding">
|
<div className="section-padding">
|
||||||
@@ -253,7 +374,9 @@ export default function EventDetailClient({ eventId, initialEvent }: EventDetail
|
|||||||
<div>
|
<div>
|
||||||
<p className="font-medium text-sm">{t('events.details.capacity')}</p>
|
<p className="font-medium text-sm">{t('events.details.capacity')}</p>
|
||||||
<p className="text-gray-600">
|
<p className="text-gray-600">
|
||||||
{spotsLeft} / {event.capacity} {t('events.details.spotsLeft')}
|
{isDoorSales
|
||||||
|
? t('events.door.spotsLeftAtDoor', { n: spotsLeft })
|
||||||
|
: `${spotsLeft} / ${event.capacity} ${t('events.details.spotsLeft')}`}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import GallerySkeleton from '@/components/gallery/GallerySkeleton';
|
||||||
|
|
||||||
|
// Shown while the server component fetches the event gallery.
|
||||||
|
export default function Loading() {
|
||||||
|
return <GallerySkeleton />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import type { Metadata } from 'next';
|
||||||
|
import { Suspense } from 'react';
|
||||||
|
import type { PhotoGallery, Photo } from '@/lib/api';
|
||||||
|
import GalleryClient from '@/app/(public)/photos/[slug]/GalleryClient';
|
||||||
|
|
||||||
|
const photoApiUrl = process.env.PHOTO_API_URL || 'http://localhost:3003';
|
||||||
|
|
||||||
|
interface PageProps {
|
||||||
|
params: { id: string }; // event slug, same param name as the parent route
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public event galleries render server-side; link/ticket galleries return
|
||||||
|
// null here and are fetched client-side with the viewer's token.
|
||||||
|
async function getEventGallery(
|
||||||
|
eventSlug: string
|
||||||
|
): Promise<{ gallery: PhotoGallery; photos: Photo[] } | null> {
|
||||||
|
try {
|
||||||
|
const res = await fetch(
|
||||||
|
`${photoApiUrl}/api/photos/public/events/${encodeURIComponent(eventSlug)}/gallery`,
|
||||||
|
{ next: { revalidate: 300 } }
|
||||||
|
);
|
||||||
|
if (!res.ok) return null;
|
||||||
|
return await res.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
|
||||||
|
const data = await getEventGallery(params.id);
|
||||||
|
if (!data) {
|
||||||
|
return { title: 'Event Photos', robots: { index: false } };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
title: `${data.gallery.title} – Photos`,
|
||||||
|
description:
|
||||||
|
data.gallery.description ||
|
||||||
|
`Photos from ${data.gallery.title}, a Spanglish language exchange event in Asunción.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function EventGalleryPage({ params }: PageProps) {
|
||||||
|
const initial = await getEventGallery(params.id);
|
||||||
|
return (
|
||||||
|
// Suspense boundary required by useSearchParams() in the client child.
|
||||||
|
<Suspense>
|
||||||
|
<GalleryClient eventSlug={params.id} initial={initial} />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { Metadata } from 'next';
|
import type { Metadata } from 'next';
|
||||||
import { notFound, permanentRedirect } from 'next/navigation';
|
import { notFound, permanentRedirect } from 'next/navigation';
|
||||||
import EventDetailClient from './EventDetailClient';
|
import EventDetailClient from './EventDetailClient';
|
||||||
|
import type { EventSalesState } from '@/lib/api';
|
||||||
|
|
||||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://spanglish.com.py';
|
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://spanglish.com.py';
|
||||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
||||||
@@ -25,6 +26,8 @@ interface Event {
|
|||||||
bannerUrl?: string;
|
bannerUrl?: string;
|
||||||
availableSeats?: number;
|
availableSeats?: number;
|
||||||
bookedCount?: number;
|
bookedCount?: number;
|
||||||
|
presaleClosesAt?: string | null;
|
||||||
|
salesState?: EventSalesState;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
@@ -113,15 +116,23 @@ function generateEventJsonLd(event: Event) {
|
|||||||
name: 'Spanglish',
|
name: 'Spanglish',
|
||||||
url: siteUrl,
|
url: siteUrl,
|
||||||
},
|
},
|
||||||
|
// The offer is always the online price; the door price is never published
|
||||||
|
// here. In the `door` state seats can still be bought (at the door), so it
|
||||||
|
// stays InStock and drops the pre-sale validThrough, which is in the past.
|
||||||
offers: {
|
offers: {
|
||||||
'@type': 'Offer',
|
'@type': 'Offer',
|
||||||
price: event.price,
|
price: event.price,
|
||||||
priceCurrency: event.currency,
|
priceCurrency: event.currency,
|
||||||
availability: Math.max(0, (event.capacity ?? 0) - (event.bookedCount ?? 0)) > 0
|
availability:
|
||||||
? 'https://schema.org/InStock'
|
event.salesState === 'sold_out' ||
|
||||||
: 'https://schema.org/SoldOut',
|
(typeof event.availableSeats === 'number'
|
||||||
|
? event.availableSeats
|
||||||
|
: Math.max(0, (event.capacity ?? 0) - (event.bookedCount ?? 0))) <= 0
|
||||||
|
? 'https://schema.org/SoldOut'
|
||||||
|
: 'https://schema.org/InStock',
|
||||||
url: `${siteUrl}/events/${event.slug}`,
|
url: `${siteUrl}/events/${event.slug}`,
|
||||||
validFrom: new Date().toISOString(),
|
validFrom: new Date().toISOString(),
|
||||||
|
...(event.presaleClosesAt && event.salesState !== 'door' ? { validThrough: event.presaleClosesAt } : {}),
|
||||||
},
|
},
|
||||||
image: event.bannerUrl
|
image: event.bannerUrl
|
||||||
? (event.bannerUrl.startsWith('http') ? event.bannerUrl : `${siteUrl}${event.bannerUrl}`)
|
? (event.bannerUrl.startsWith('http') ? event.bannerUrl : `${siteUrl}${event.bannerUrl}`)
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, Suspense } from 'react';
|
import { useState, useEffect, Suspense } from 'react';
|
||||||
import { useRouter, useSearchParams } from 'next/navigation';
|
import { useSearchParams } from 'next/navigation';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { useLanguage } from '@/context/LanguageContext';
|
import { useLanguage } from '@/context/LanguageContext';
|
||||||
import { useAuth } from '@/context/AuthContext';
|
import { useAuth } from '@/context/AuthContext';
|
||||||
@@ -11,14 +11,20 @@ import Input from '@/components/ui/Input';
|
|||||||
import GoogleSignInButton from '@/components/GoogleSignInButton';
|
import GoogleSignInButton from '@/components/GoogleSignInButton';
|
||||||
import { authApi } from '@/lib/api';
|
import { authApi } from '@/lib/api';
|
||||||
import { safeInternalPath } from '@/lib/safeRedirect';
|
import { safeInternalPath } from '@/lib/safeRedirect';
|
||||||
|
import {
|
||||||
|
clearRedirectAttempt,
|
||||||
|
didRedirectBounce,
|
||||||
|
redirectAfterAuth,
|
||||||
|
} from '@/lib/authRedirect';
|
||||||
import toast from 'react-hot-toast';
|
import toast from 'react-hot-toast';
|
||||||
|
|
||||||
function LoginContent() {
|
function LoginContent() {
|
||||||
const router = useRouter();
|
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const { t, locale: language } = useLanguage();
|
const { t, locale: language } = useLanguage();
|
||||||
const { login } = useAuth();
|
const { login, user, isLoading: authLoading } = useAuth();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [redirecting, setRedirecting] = useState(false);
|
||||||
|
const [bounced, setBounced] = useState(false);
|
||||||
const [loginMode, setLoginMode] = useState<'password' | 'magic-link'>('password');
|
const [loginMode, setLoginMode] = useState<'password' | 'magic-link'>('password');
|
||||||
const [magicLinkSent, setMagicLinkSent] = useState(false);
|
const [magicLinkSent, setMagicLinkSent] = useState(false);
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
@@ -29,6 +35,27 @@ function LoginContent() {
|
|||||||
// Check for redirect after login (only same-origin relative paths are honoured)
|
// Check for redirect after login (only same-origin relative paths are honoured)
|
||||||
const redirectTo = safeInternalPath(searchParams.get('redirect'), '/dashboard');
|
const redirectTo = safeInternalPath(searchParams.get('redirect'), '/dashboard');
|
||||||
|
|
||||||
|
// Send an already-signed-in visitor on to their destination — and detect the case
|
||||||
|
// where that destination bounced them back here, which otherwise looks like the
|
||||||
|
// login page silently ignoring a successful sign-in.
|
||||||
|
useEffect(() => {
|
||||||
|
if (authLoading || redirecting) return;
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
// Signed out on the login page is a clean slate.
|
||||||
|
clearRedirectAttempt();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (didRedirectBounce(redirectTo)) {
|
||||||
|
setBounced(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setRedirecting(true);
|
||||||
|
redirectAfterAuth(redirectTo);
|
||||||
|
}, [authLoading, redirecting, user, redirectTo]);
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -36,10 +63,12 @@ function LoginContent() {
|
|||||||
try {
|
try {
|
||||||
await login(formData.email, formData.password);
|
await login(formData.email, formData.password);
|
||||||
toast.success(language === 'es' ? '¡Bienvenido!' : 'Welcome back!');
|
toast.success(language === 'es' ? '¡Bienvenido!' : 'Welcome back!');
|
||||||
router.push(redirectTo);
|
// Deliberately leaves `loading` set: the button must stay disabled until the
|
||||||
|
// browser replaces this page.
|
||||||
|
setRedirecting(true);
|
||||||
|
redirectAfterAuth(redirectTo);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
toast.error(error.message || t('auth.errors.invalidCredentials'));
|
toast.error(error.message || t('auth.errors.invalidCredentials'));
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -67,6 +96,38 @@ function LoginContent() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// The destination sent us back here even though the session is valid. Say so, rather
|
||||||
|
// than re-showing a form that appears to do nothing. The retry link is a plain <a> so
|
||||||
|
// it is a full page load, like every other navigation out of this page.
|
||||||
|
if (bounced) {
|
||||||
|
return (
|
||||||
|
<div className="section-padding min-h-[70vh] flex items-center">
|
||||||
|
<div className="container-page">
|
||||||
|
<div className="max-w-md mx-auto">
|
||||||
|
<Card className="p-8 text-center">
|
||||||
|
<h1 className="text-2xl font-bold">{t('auth.login.redirectBlocked')}</h1>
|
||||||
|
{user && <p className="mt-2 text-sm text-gray-600">{user.email}</p>}
|
||||||
|
<p className="mt-4 text-sm text-gray-600">
|
||||||
|
<code className="px-1.5 py-0.5 bg-gray-100 rounded">{redirectTo}</code>
|
||||||
|
</p>
|
||||||
|
<a href={redirectTo} className="mt-6 block">
|
||||||
|
<Button className="w-full" size="lg">
|
||||||
|
{t('auth.login.redirectRetry')}
|
||||||
|
</Button>
|
||||||
|
</a>
|
||||||
|
<Link
|
||||||
|
href="/"
|
||||||
|
className="mt-3 inline-block text-sm text-secondary-blue hover:underline"
|
||||||
|
>
|
||||||
|
{t('nav.home')}
|
||||||
|
</Link>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="section-padding min-h-[70vh] flex items-center">
|
<div className="section-padding min-h-[70vh] flex items-center">
|
||||||
<div className="container-page">
|
<div className="container-page">
|
||||||
@@ -151,9 +212,25 @@ function LoginContent() {
|
|||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button type="submit" className="w-full" size="lg" isLoading={loading}>
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="w-full"
|
||||||
|
size="lg"
|
||||||
|
isLoading={loading || redirecting}
|
||||||
|
loadingText={redirecting ? t('auth.login.redirecting') : t('common.loading')}
|
||||||
|
>
|
||||||
{t('auth.login.submit')}
|
{t('auth.login.submit')}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{redirecting && (
|
||||||
|
<p
|
||||||
|
className="text-center text-sm text-gray-600"
|
||||||
|
role="status"
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
{t('auth.login.redirecting')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</form>
|
</form>
|
||||||
) : magicLinkSent ? (
|
) : magicLinkSent ? (
|
||||||
<div className="text-center py-8">
|
<div className="text-center py-8">
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { useLanguage } from '@/context/LanguageContext';
|
||||||
|
import type { PhotoGallery } from '@/lib/api';
|
||||||
|
import Card from '@/components/ui/Card';
|
||||||
|
import { CameraIcon } from '@heroicons/react/24/outline';
|
||||||
|
|
||||||
|
export default function PhotosIndexClient({ galleries }: { galleries: PhotoGallery[] }) {
|
||||||
|
const { locale } = useLanguage();
|
||||||
|
const es = locale === 'es';
|
||||||
|
|
||||||
|
const formatDate = (iso?: string) => {
|
||||||
|
if (!iso) return null;
|
||||||
|
return new Date(iso).toLocaleDateString(es ? 'es-ES' : 'en-US', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
timeZone: 'America/Asuncion',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="section-padding">
|
||||||
|
<div className="container-page">
|
||||||
|
<h1 className="section-title text-center mb-2">
|
||||||
|
{es ? 'Galerías de Fotos' : 'Photo Galleries'}
|
||||||
|
</h1>
|
||||||
|
<p className="text-center text-gray-600 mb-10">
|
||||||
|
{es
|
||||||
|
? 'Recuerdos de nuestros intercambios de idiomas en Asunción'
|
||||||
|
: 'Memories from our language exchanges in Asunción'}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{galleries.length === 0 ? (
|
||||||
|
<div className="text-center py-16">
|
||||||
|
<CameraIcon className="w-16 h-16 mx-auto text-gray-300 mb-4" />
|
||||||
|
<p className="text-gray-600">
|
||||||
|
{es ? 'Aún no hay galerías publicadas.' : 'No galleries published yet.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
|
{galleries.map((g) => (
|
||||||
|
// Event-linked galleries live under the event's URL.
|
||||||
|
<Link key={g.id} href={g.event ? `/events/${g.event.slug}/gallery` : `/photos/${g.slug}`}>
|
||||||
|
<Card variant="elevated" className="overflow-hidden hover:shadow-card-hover transition-shadow h-full">
|
||||||
|
<div className="aspect-video bg-gray-100 flex items-center justify-center">
|
||||||
|
{g.coverUrl ? (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
<img src={g.coverUrl} alt="" className="w-full h-full object-cover" loading="lazy" />
|
||||||
|
) : (
|
||||||
|
<CameraIcon className="w-12 h-12 text-gray-300" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
<h2 className="font-heading font-semibold text-lg text-primary-dark">
|
||||||
|
{es && g.titleEs ? g.titleEs : g.title}
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm text-gray-600 mt-1">
|
||||||
|
{g.photoCount} {es ? 'fotos' : 'photos'}
|
||||||
|
{g.event?.startDatetime && <> · {formatDate(g.event.startDatetime)}</>}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,445 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { useSearchParams } from 'next/navigation';
|
||||||
|
import { useLanguage } from '@/context/LanguageContext';
|
||||||
|
import { useAuth } from '@/context/AuthContext';
|
||||||
|
import { photosApi, PhotoGallery, Photo } from '@/lib/api';
|
||||||
|
import Button from '@/components/ui/Button';
|
||||||
|
import GallerySkeleton from '@/components/gallery/GallerySkeleton';
|
||||||
|
import PhotoTile from '@/components/gallery/PhotoTile';
|
||||||
|
import {
|
||||||
|
GalleryContainer,
|
||||||
|
GalleryHeroFrame,
|
||||||
|
MasonryGrid,
|
||||||
|
} from '@/components/gallery/GalleryLayout';
|
||||||
|
import { useDownloads } from '@/components/gallery/useDownloads';
|
||||||
|
import SaveSheet, { SavePhoto, useMobileSave } from '@/components/gallery/SaveSheet';
|
||||||
|
import Lightbox from '@/components/Lightbox';
|
||||||
|
import LoginModal from '@/components/LoginModal';
|
||||||
|
import {
|
||||||
|
CalendarIcon,
|
||||||
|
CameraIcon,
|
||||||
|
LinkIcon,
|
||||||
|
LockClosedIcon,
|
||||||
|
TicketIcon,
|
||||||
|
} from '@heroicons/react/24/outline';
|
||||||
|
|
||||||
|
interface GalleryClientProps {
|
||||||
|
/** Fetch by gallery slug (standalone galleries at /photos/[slug]) … */
|
||||||
|
slug?: string;
|
||||||
|
/** … or by event slug (event galleries at /events/[slug]/gallery). */
|
||||||
|
eventSlug?: string;
|
||||||
|
initial: { gallery: PhotoGallery; photos: Photo[] } | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeniedState = 'login' | 'ticket' | 'private' | 'link' | 'notfound' | null;
|
||||||
|
|
||||||
|
export default function GalleryClient({ slug, eventSlug, initial }: GalleryClientProps) {
|
||||||
|
const { locale } = useLanguage();
|
||||||
|
const es = locale === 'es';
|
||||||
|
const { user, isLoading: authLoading } = useAuth();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const shareToken = searchParams.get('token') || undefined;
|
||||||
|
|
||||||
|
const [gallery, setGallery] = useState<PhotoGallery | null>(initial?.gallery ?? null);
|
||||||
|
const [photos, setPhotos] = useState<Photo[]>(initial?.photos ?? []);
|
||||||
|
const [loading, setLoading] = useState(!initial);
|
||||||
|
const [denied, setDenied] = useState<DeniedState>(null);
|
||||||
|
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
|
||||||
|
const [loginOpen, setLoginOpen] = useState(false);
|
||||||
|
const downloads = useDownloads(es);
|
||||||
|
const downloadLabels = {
|
||||||
|
download: es ? 'Descargar' : 'Download',
|
||||||
|
downloading: es ? 'Descargando…' : 'Downloading…',
|
||||||
|
};
|
||||||
|
|
||||||
|
// On a phone a download cannot reach the photo library, so the button
|
||||||
|
// opens a sheet offering the shareable preview instead (SaveSheet).
|
||||||
|
// Desktop keeps downloading the original straight away.
|
||||||
|
const mobileSave = useMobileSave();
|
||||||
|
const [savePhoto, setSavePhoto] = useState<SavePhoto | null>(null);
|
||||||
|
|
||||||
|
const downloadPhoto = (photo: Photo) => {
|
||||||
|
if (mobileSave) {
|
||||||
|
setSavePhoto({
|
||||||
|
id: photo.id,
|
||||||
|
previewUrl: photo.urls.download || photo.urls.preview || photo.urls.original,
|
||||||
|
originalUrl: photo.urls.downloadOriginal || photo.urls.original,
|
||||||
|
previewSize: photo.previewSizeBytes,
|
||||||
|
originalSize: photo.sizeBytes,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
downloads.start({
|
||||||
|
id: photo.id,
|
||||||
|
url: photo.urls.original,
|
||||||
|
filename: photo.originalFilename,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Server-rendered public galleries need no client fetch. Everything else
|
||||||
|
// (link/ticket/private) is fetched here with the share token and/or the
|
||||||
|
// viewer's own auth token attached.
|
||||||
|
useEffect(() => {
|
||||||
|
if (initial) return;
|
||||||
|
if (authLoading) return; // wait until the session state has resolved
|
||||||
|
let cancelled = false;
|
||||||
|
setLoading(true);
|
||||||
|
const fetcher = eventSlug
|
||||||
|
? photosApi.getEventGallery(eventSlug, shareToken)
|
||||||
|
: photosApi.getPublicGallery(slug || '', shareToken);
|
||||||
|
fetcher
|
||||||
|
.then((data) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
setGallery(data.gallery);
|
||||||
|
setPhotos(data.photos);
|
||||||
|
setDenied(null);
|
||||||
|
})
|
||||||
|
.catch((err: Error) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
// The photo-api returns a distinct message per visibility mode so
|
||||||
|
// each gets its own gate page (see accessDenial in access.go).
|
||||||
|
const msg = err.message || '';
|
||||||
|
if (msg.includes('Authentication required')) setDenied('login');
|
||||||
|
else if (msg.includes('attendees')) setDenied('ticket');
|
||||||
|
else if (msg.includes('private')) setDenied('private');
|
||||||
|
else if (msg.includes('share link')) setDenied('link');
|
||||||
|
else setDenied('notfound');
|
||||||
|
})
|
||||||
|
.finally(() => !cancelled && setLoading(false));
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [slug, eventSlug, shareToken, initial, authLoading, user?.id]);
|
||||||
|
|
||||||
|
// Mirrors the hero + masonry layout below, so the real page drops straight
|
||||||
|
// into the placeholder's geometry instead of replacing it.
|
||||||
|
if (loading || (authLoading && !initial)) {
|
||||||
|
return <GallerySkeleton count={gallery?.photoCount || undefined} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gate pages for restricted galleries. After a successful login in the
|
||||||
|
// pop-up, AuthContext's user changes, which re-runs the fetch effect —
|
||||||
|
// the gate resolves by itself when access is granted.
|
||||||
|
const loginModal = (
|
||||||
|
<LoginModal
|
||||||
|
open={loginOpen}
|
||||||
|
onClose={() => setLoginOpen(false)}
|
||||||
|
message={
|
||||||
|
es
|
||||||
|
? 'Inicia sesión para ver esta galería.'
|
||||||
|
: 'Log in to view this gallery.'
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (denied === 'login') {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<GateMessage
|
||||||
|
icon={TicketIcon}
|
||||||
|
title={es ? 'Solo para asistentes' : 'Attendees only'}
|
||||||
|
body={
|
||||||
|
es
|
||||||
|
? 'Esta galería es para asistentes del evento. Inicia sesión con la cuenta que usaste para reservar.'
|
||||||
|
: 'This gallery is for event attendees. Log in with the account you used to book.'
|
||||||
|
}
|
||||||
|
action={
|
||||||
|
<Button onClick={() => setLoginOpen(true)}>{es ? 'Iniciar sesión' : 'Log in'}</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{loginModal}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (denied === 'ticket') {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<GateMessage
|
||||||
|
icon={TicketIcon}
|
||||||
|
title={es ? 'Solo para asistentes' : 'Attendees only'}
|
||||||
|
body={
|
||||||
|
es
|
||||||
|
? 'Esta galería es para quienes asistieron al evento con una entrada confirmada. ¿Reservaste con otra cuenta?'
|
||||||
|
: 'This gallery is only available to people who attended the event with a confirmed ticket. Booked with a different account?'
|
||||||
|
}
|
||||||
|
action={
|
||||||
|
<div className="flex flex-wrap justify-center gap-3">
|
||||||
|
{(eventSlug || gallery?.event) && (
|
||||||
|
<Link href={`/events/${eventSlug || gallery?.event?.slug}`}>
|
||||||
|
<Button variant="outline">{es ? 'Ver el evento' : 'View the event'}</Button>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
<Button onClick={() => setLoginOpen(true)}>
|
||||||
|
{es ? 'Cambiar de cuenta' : 'Switch account'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{loginModal}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (denied === 'private') {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<GateMessage
|
||||||
|
icon={LockClosedIcon}
|
||||||
|
title={es ? 'Esta galería es privada' : 'This gallery is private'}
|
||||||
|
body={
|
||||||
|
es
|
||||||
|
? 'Solo los organizadores pueden verla. Si eres parte del equipo, inicia sesión.'
|
||||||
|
: 'Only the organizers can see it. If that’s you, log in.'
|
||||||
|
}
|
||||||
|
action={
|
||||||
|
<div className="flex flex-wrap justify-center gap-3">
|
||||||
|
<Link href="/photos">
|
||||||
|
<Button variant="outline">{es ? 'Ver galerías públicas' : 'Browse public galleries'}</Button>
|
||||||
|
</Link>
|
||||||
|
<Button onClick={() => setLoginOpen(true)}>{es ? 'Iniciar sesión' : 'Log in'}</Button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{loginModal}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (denied === 'link') {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<GateMessage
|
||||||
|
icon={LinkIcon}
|
||||||
|
title={es ? 'Esta galería necesita su enlace' : 'This gallery needs its share link'}
|
||||||
|
body={
|
||||||
|
es
|
||||||
|
? 'Solo se puede abrir con el enlace que compartieron los organizadores. Pídeles el enlace completo, o inicia sesión si eres parte del equipo.'
|
||||||
|
: 'It can only be opened with the link the organizers shared. Ask them for the full link, or log in if you’re part of the team.'
|
||||||
|
}
|
||||||
|
action={
|
||||||
|
<div className="flex flex-wrap justify-center gap-3">
|
||||||
|
<Link href="/photos">
|
||||||
|
<Button variant="outline">{es ? 'Ver galerías públicas' : 'Browse public galleries'}</Button>
|
||||||
|
</Link>
|
||||||
|
<Button onClick={() => setLoginOpen(true)}>{es ? 'Iniciar sesión' : 'Log in'}</Button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{loginModal}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (denied === 'notfound' || !gallery) {
|
||||||
|
return (
|
||||||
|
<GateMessage
|
||||||
|
icon={CameraIcon}
|
||||||
|
title={es ? 'Galería no encontrada' : 'Gallery not found'}
|
||||||
|
body={
|
||||||
|
es
|
||||||
|
? 'Este enlace no existe o ya no está disponible.'
|
||||||
|
: 'This link does not exist or is no longer available.'
|
||||||
|
}
|
||||||
|
action={
|
||||||
|
<Link href="/photos">
|
||||||
|
<Button variant="outline">{es ? 'Ver galerías públicas' : 'Browse public galleries'}</Button>
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const readyPhotos = photos.filter((p) => p.status === 'ready' && p.urls.thumb);
|
||||||
|
// previewUrl is the download endpoint's preview: rendering and saving from
|
||||||
|
// the same URL is what lets "Save photo" be answered by the HTTP cache.
|
||||||
|
const lightboxItems = readyPhotos.map((p) => ({
|
||||||
|
id: p.id,
|
||||||
|
previewUrl: p.urls.download || p.urls.preview || p.urls.original,
|
||||||
|
downloadUrl: p.urls.downloadOriginal || p.urls.original,
|
||||||
|
filename: p.originalFilename,
|
||||||
|
thumbUrl: p.urls.thumb,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const title = es && gallery.titleEs ? gallery.titleEs : gallery.title;
|
||||||
|
const description = es && gallery.descriptionEs ? gallery.descriptionEs : gallery.description;
|
||||||
|
const eventTitle = gallery.event
|
||||||
|
? es && gallery.event.titleEs
|
||||||
|
? gallery.event.titleEs
|
||||||
|
: gallery.event.title
|
||||||
|
: null;
|
||||||
|
const eventDate = gallery.event?.startDatetime
|
||||||
|
? new Date(gallery.event.startDatetime).toLocaleDateString(es ? 'es-ES' : 'en-US', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric',
|
||||||
|
timeZone: 'America/Asuncion',
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
|
||||||
|
// Hero backdrop: the cover photo's preview when available, else the
|
||||||
|
// first photo. Falls back to a navy gradient with no image.
|
||||||
|
const coverPhoto =
|
||||||
|
readyPhotos.find((p) => p.id === gallery.coverPhotoId) || readyPhotos[0] || null;
|
||||||
|
// Same preview URL the lightbox uses, so the cover photo's bytes are
|
||||||
|
// fetched once for both.
|
||||||
|
const heroUrl = coverPhoto
|
||||||
|
? coverPhoto.urls.download || coverPhoto.urls.preview || coverPhoto.urls.thumb
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{/* Hero — same frame the skeleton renders (GalleryLayout). */}
|
||||||
|
<GalleryHeroFrame
|
||||||
|
backdrop={
|
||||||
|
heroUrl ? (
|
||||||
|
<>
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img
|
||||||
|
src={heroUrl}
|
||||||
|
alt=""
|
||||||
|
className="absolute inset-0 w-full h-full object-cover opacity-60"
|
||||||
|
/>
|
||||||
|
<div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/30 to-black/20" />
|
||||||
|
</>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<h1 className="font-heading font-bold text-3xl md:text-5xl text-white drop-shadow-sm">
|
||||||
|
{title}
|
||||||
|
</h1>
|
||||||
|
{description && (
|
||||||
|
<p className="mt-2 max-w-2xl text-white/90 text-sm md:text-base">{description}</p>
|
||||||
|
)}
|
||||||
|
<div className="mt-4 flex flex-wrap items-center gap-2 text-sm">
|
||||||
|
<span className="inline-flex items-center gap-1.5 rounded-full bg-white/15 backdrop-blur px-3 py-1 text-white">
|
||||||
|
<CameraIcon className="w-4 h-4" />
|
||||||
|
{readyPhotos.length} {es ? 'fotos' : 'photos'}
|
||||||
|
</span>
|
||||||
|
{gallery.event && (
|
||||||
|
<Link
|
||||||
|
href={`/events/${gallery.event.slug}`}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-full bg-primary-yellow px-3 py-1 text-primary-dark font-medium hover:brightness-105"
|
||||||
|
>
|
||||||
|
<CalendarIcon className="w-4 h-4" />
|
||||||
|
{eventTitle}
|
||||||
|
{eventDate && <span className="hidden sm:inline font-normal">· {eventDate}</span>}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</GalleryHeroFrame>
|
||||||
|
|
||||||
|
{/* Masonry grid */}
|
||||||
|
<GalleryContainer>
|
||||||
|
{readyPhotos.length === 0 ? (
|
||||||
|
<div className="text-center py-16">
|
||||||
|
<CameraIcon className="w-16 h-16 mx-auto text-gray-300 mb-4" />
|
||||||
|
<p className="text-gray-600">
|
||||||
|
{es ? 'Las fotos estarán disponibles pronto.' : 'Photos will be available soon.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<MasonryGrid>
|
||||||
|
{readyPhotos.map((photo, i) => (
|
||||||
|
<PhotoTile
|
||||||
|
key={photo.id}
|
||||||
|
photo={photo}
|
||||||
|
eager={i < 8}
|
||||||
|
onOpen={() => setLightboxIndex(i)}
|
||||||
|
onDownload={() => downloadPhoto(photo)}
|
||||||
|
downloading={downloads.isPending(photo.id)}
|
||||||
|
labels={downloadLabels}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</MasonryGrid>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{lightboxIndex !== null && (
|
||||||
|
<Lightbox
|
||||||
|
items={lightboxItems}
|
||||||
|
index={lightboxIndex}
|
||||||
|
onClose={() => setLightboxIndex(null)}
|
||||||
|
onNavigate={setLightboxIndex}
|
||||||
|
onDownload={(it) => {
|
||||||
|
const photo = readyPhotos.find((p) => p.id === it.id);
|
||||||
|
if (photo) downloadPhoto(photo);
|
||||||
|
}}
|
||||||
|
downloadingId={
|
||||||
|
lightboxItems.find((it) => downloads.isPending(it.id))?.id ?? null
|
||||||
|
}
|
||||||
|
downloadLabels={downloadLabels}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Shared by both entry points: the tile button and the lightbox's.
|
||||||
|
Fetches nothing until it is open. */}
|
||||||
|
<SaveSheet photo={savePhoto} onClose={() => setSavePhoto(null)} />
|
||||||
|
</GalleryContainer>
|
||||||
|
|
||||||
|
{/* Call to action: send attendees to their dashboard, everyone else to
|
||||||
|
the next event. Auth state comes from the same useAuth() the gate
|
||||||
|
pages use. */}
|
||||||
|
<div className="bg-brand-navy">
|
||||||
|
<div className="container-page px-4 py-12 md:py-16 text-center">
|
||||||
|
<h2 className="font-heading font-bold text-2xl md:text-3xl text-white">
|
||||||
|
{user
|
||||||
|
? es
|
||||||
|
? '¿Listo para lo que sigue?'
|
||||||
|
: 'Ready for what’s next?'
|
||||||
|
: es
|
||||||
|
? '¿Te gustó lo que viste?'
|
||||||
|
: 'Liked what you saw?'}
|
||||||
|
</h2>
|
||||||
|
<p className="mt-2 max-w-xl mx-auto text-white/80 text-sm md:text-base">
|
||||||
|
{user
|
||||||
|
? es
|
||||||
|
? 'Revisa tus entradas y próximos eventos en tu panel.'
|
||||||
|
: 'Check your tickets and upcoming events from your dashboard.'
|
||||||
|
: es
|
||||||
|
? 'Únete a nuestro próximo evento y sé parte de las próximas fotos.'
|
||||||
|
: 'Join our next event and be part of the next set of photos.'}
|
||||||
|
</p>
|
||||||
|
<div className="mt-6">
|
||||||
|
<Link href={user ? '/dashboard' : '/next'}>
|
||||||
|
<Button size="lg">
|
||||||
|
{user
|
||||||
|
? es
|
||||||
|
? 'Ir a mi panel'
|
||||||
|
: 'Go to dashboard'
|
||||||
|
: es
|
||||||
|
? 'Únete al próximo evento'
|
||||||
|
: 'Join the next event'}
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function GateMessage({
|
||||||
|
icon: Icon,
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
action,
|
||||||
|
}: {
|
||||||
|
icon: typeof CameraIcon;
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
action?: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="section-padding">
|
||||||
|
<div className="container-page max-w-lg mx-auto text-center py-16">
|
||||||
|
<Icon className="w-16 h-16 mx-auto text-gray-300 mb-4" />
|
||||||
|
<h1 className="text-2xl font-bold text-primary-dark mb-2">{title}</h1>
|
||||||
|
<p className="text-gray-600 mb-6">{body}</p>
|
||||||
|
{action}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import GallerySkeleton from '@/components/gallery/GallerySkeleton';
|
||||||
|
|
||||||
|
// Shown while the server component fetches the gallery, so the first paint is
|
||||||
|
// already the gallery's layout rather than an empty page.
|
||||||
|
export default function Loading() {
|
||||||
|
return <GallerySkeleton />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import type { Metadata } from 'next';
|
||||||
|
import { Suspense } from 'react';
|
||||||
|
import type { PhotoGallery, Photo } from '@/lib/api';
|
||||||
|
import GalleryClient from './GalleryClient';
|
||||||
|
|
||||||
|
const photoApiUrl = process.env.PHOTO_API_URL || 'http://localhost:3003';
|
||||||
|
|
||||||
|
interface PageProps {
|
||||||
|
params: { slug: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public galleries render server-side (SEO + fast first paint); link and
|
||||||
|
// ticket galleries return null here and are fetched client-side with the
|
||||||
|
// viewer's token / share token.
|
||||||
|
async function getPublicGallery(
|
||||||
|
slug: string
|
||||||
|
): Promise<{ gallery: PhotoGallery; photos: Photo[] } | null> {
|
||||||
|
try {
|
||||||
|
const res = await fetch(
|
||||||
|
`${photoApiUrl}/api/photos/public/galleries/${encodeURIComponent(slug)}`,
|
||||||
|
{ next: { revalidate: 300 } }
|
||||||
|
);
|
||||||
|
if (!res.ok) return null;
|
||||||
|
return await res.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
|
||||||
|
const data = await getPublicGallery(params.slug);
|
||||||
|
if (!data) {
|
||||||
|
return { title: 'Photo Gallery', robots: { index: false } };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
title: `${data.gallery.title} – Photos`,
|
||||||
|
description:
|
||||||
|
data.gallery.description ||
|
||||||
|
`Photos from ${data.gallery.title}, a Spanglish language exchange event in Asunción.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function GalleryPage({ params }: PageProps) {
|
||||||
|
const initial = await getPublicGallery(params.slug);
|
||||||
|
return (
|
||||||
|
// Suspense boundary required by useSearchParams() in the client child.
|
||||||
|
<Suspense>
|
||||||
|
<GalleryClient slug={params.slug} initial={initial} />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user