Compare commits
38
Commits
tpago-fix
...
5b478c327d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
||||
dist/
|
||||
.next/
|
||||
.next-build/
|
||||
out/
|
||||
build/
|
||||
|
||||
@@ -56,6 +57,10 @@ yarn-error.log*
|
||||
# Testing
|
||||
coverage/
|
||||
|
||||
# Go photo-api service
|
||||
photo-api/bin/
|
||||
photo-api/data/
|
||||
|
||||
# Misc
|
||||
*.pem
|
||||
|
||||
|
||||
@@ -4,17 +4,24 @@ A full-stack web app for organizing and managing language exchange events (Asunc
|
||||
|
||||
## Features
|
||||
|
||||
- **Public site**: events, booking, contact, community, legal pages, bilingual (EN/ES)
|
||||
- **User dashboard**: profile, tickets, payments, sessions/security
|
||||
- **Admin** (`/admin`): events, tickets/check-in, users/roles, payments, email templates, media uploads
|
||||
- **Public site**: events, booking, contact, community, **photo galleries**, legal pages, bilingual (EN/ES)
|
||||
- Stable `/next` and `/featured` URLs that redirect to the current event
|
||||
- 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`
|
||||
|
||||
## Tech stack
|
||||
|
||||
- **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
|
||||
- **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
|
||||
|
||||
@@ -22,6 +29,8 @@ A full-stack web app for organizing and managing language exchange events (Asunc
|
||||
|
||||
- Node.js 18+
|
||||
- npm
|
||||
- Go 1.26+ (for the `photo-api` service)
|
||||
- Optional: `libvips-tools` (or `libheif-examples`) on the host to accept HEIC photo uploads
|
||||
|
||||
### Setup
|
||||
|
||||
@@ -29,12 +38,14 @@ A full-stack web app for organizing and managing language exchange events (Asunc
|
||||
npm install
|
||||
cp backend/.env.example backend/.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)
|
||||
|
||||
```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
|
||||
@@ -43,10 +54,13 @@ npm run db:migrate
|
||||
npm run dev
|
||||
```
|
||||
|
||||
`npm run dev` starts the backend, frontend, and photo-api together (via `concurrently`).
|
||||
|
||||
Default URLs:
|
||||
|
||||
- Frontend: `http://localhost:3002`
|
||||
- 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`
|
||||
|
||||
### First user becomes admin
|
||||
@@ -58,14 +72,20 @@ The first user to register becomes the **admin**. Register at `/register`.
|
||||
Run these from the repo root:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
npm run build
|
||||
npm run dev # backend + frontend + photo-api
|
||||
npm run build # build all workspaces
|
||||
npm run start
|
||||
npm run db:generate
|
||||
npm run db:migrate
|
||||
npm run db:studio
|
||||
npm run db:export # Backup database
|
||||
npm run db:import # Restore from backup
|
||||
npm run db:export # Backup database
|
||||
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 ./...
|
||||
```
|
||||
|
||||
You can also run per workspace:
|
||||
@@ -82,12 +102,22 @@ npm run dev --workspace=frontend
|
||||
Key settings (see `backend/.env.example` for the full list):
|
||||
|
||||
- **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`
|
||||
- **URLs/ports**: `PORT`, `API_URL`, `FRONTEND_URL`
|
||||
- **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)
|
||||
|
||||
### 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
|
||||
- **Uploads/worker**: `MAX_UPLOAD_MB`, `WORKER_CONCURRENCY` (a worker generates thumb/preview JPEG variants with EXIF stripped)
|
||||
|
||||
### Frontend (`frontend/.env`)
|
||||
|
||||
Key settings (see `frontend/.env.example`):
|
||||
@@ -143,12 +173,13 @@ npm run db:import -- --yes ./data/backups/spanglish-2025-03-07.sql # Skip conf
|
||||
|
||||
This repo includes example configs in `deploy/`:
|
||||
|
||||
- **systemd**: `deploy/spanglish-backend.service`, `deploy/spanglish-frontend.service`
|
||||
- Backend runs on **3018**, frontend on **3019** by default (see the unit files)
|
||||
- **systemd**: `deploy/spanglish-backend.service`, `deploy/spanglish-frontend.service`, `deploy/spanglish-photos.service`
|
||||
- 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`
|
||||
- The photo service runs its own migrations on start (`photo-api migrate`) and needs write access to its `STORAGE_PATH` (or S3 config)
|
||||
- **nginx**:
|
||||
- `deploy/spanglish_upstreams.conf` defines upstreams for ports 3018/3019
|
||||
- `deploy/front-end_nginx.conf` proxies `/api` and `/uploads` to the backend and everything else to the frontend
|
||||
- `deploy/spanglish_upstreams.conf` defines upstreams for ports 3018/3019/3020
|
||||
- `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
|
||||
|
||||
Typical production flow:
|
||||
@@ -156,7 +187,9 @@ Typical production flow:
|
||||
```bash
|
||||
npm ci
|
||||
npm run build
|
||||
npm run build:photos
|
||||
npm run db:migrate
|
||||
npm run migrate:photos
|
||||
```
|
||||
|
||||
Then install/enable the systemd services and nginx configs for your server.
|
||||
|
||||
+32
-4
@@ -22,10 +22,18 @@ DATABASE_URL=./data/spanglish.db
|
||||
# Note: running more than one instance requires DB_TYPE=postgres. SQLite is a
|
||||
# single local file and cannot be shared safely across instances.
|
||||
|
||||
# Redis connection URL. When set, the cache, rate limiter, pub/sub (real-time
|
||||
# payment events), distributed locks, and the email hourly cap are shared across
|
||||
# all instances. When unset, each instance uses in-memory equivalents.
|
||||
# Redis connection URL. When set, the cache, rate limiter, login lockout,
|
||||
# pub/sub (real-time payment events), distributed locks, and the email hourly
|
||||
# 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://: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,
|
||||
# AWS S3). When S3_ENDPOINT and S3_BUCKET are set, uploads go to the bucket and
|
||||
@@ -42,13 +50,33 @@ DATABASE_URL=./data/spanglish.db
|
||||
# Use path-style addressing (true for Garage/MinIO). Defaults to 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=
|
||||
|
||||
# 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
|
||||
|
||||
# Google OAuth (optional - for Google Sign-In)
|
||||
# Get your Client ID from: https://console.cloud.google.com/apis/credentials
|
||||
# Note: The same Client ID should be used in frontend/.env
|
||||
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
|
||||
PORT=3001
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "vitest run",
|
||||
"start": "NODE_ENV=production node dist/index.js",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "tsx src/db/migrate.ts",
|
||||
@@ -19,9 +20,10 @@
|
||||
"@hono/zod-openapi": "^0.14.4",
|
||||
"argon2": "^0.44.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"better-sqlite3": "^11.0.0",
|
||||
"better-auth": "1.6.25",
|
||||
"better-sqlite3": "^12.11.1",
|
||||
"dotenv": "^17.2.3",
|
||||
"drizzle-orm": "^0.31.2",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"hono": "^4.4.7",
|
||||
"ioredis": "^5.11.1",
|
||||
"jose": "^5.4.0",
|
||||
@@ -41,8 +43,10 @@
|
||||
"@types/pdfkit": "^0.17.4",
|
||||
"@types/pg": "^8.11.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",
|
||||
"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);
|
||||
});
|
||||
+254
-1
@@ -199,7 +199,19 @@ async function migrate() {
|
||||
try {
|
||||
await (db as any).run(sql`ALTER TABLE tickets ADD COLUMN is_guest INTEGER NOT NULL DEFAULT 0`);
|
||||
} 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)
|
||||
// SQLite doesn't support altering column constraints, so we'll just ensure new entries work
|
||||
|
||||
@@ -532,6 +544,81 @@ async function migrate() {
|
||||
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 {
|
||||
// PostgreSQL migrations
|
||||
await (db as any).execute(sql`
|
||||
@@ -702,6 +789,18 @@ async function migrate() {
|
||||
await (db as any).execute(sql`ALTER TABLE tickets ADD COLUMN is_guest INTEGER NOT NULL DEFAULT 0`);
|
||||
} 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`
|
||||
CREATE TABLE IF NOT EXISTS payments (
|
||||
id UUID PRIMARY KEY,
|
||||
@@ -1020,6 +1119,80 @@ async function migrate() {
|
||||
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
|
||||
)
|
||||
`);
|
||||
}
|
||||
|
||||
// Indexes on foreign-key / hot-filter columns (CREATE INDEX IF NOT EXISTS works on both engines)
|
||||
@@ -1032,6 +1205,11 @@ async function migrate() {
|
||||
`CREATE INDEX IF NOT EXISTS payments_status_idx ON payments(status)`,
|
||||
`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 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)`,
|
||||
];
|
||||
for (const stmt of indexStatements) {
|
||||
try {
|
||||
@@ -1043,6 +1221,81 @@ async function migrate() {
|
||||
} 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
|
||||
`);
|
||||
}
|
||||
|
||||
// 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.
|
||||
const allEvents = await dbAll<{ id: string; title: string; slug: string | null }>(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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
|
||||
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'),
|
||||
// Incremented to invalidate previously issued JWTs (logout-everywhere, password change/reset)
|
||||
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(),
|
||||
updatedAt: text('updated_at').notNull(),
|
||||
});
|
||||
@@ -110,6 +116,8 @@ export const sqliteTickets = sqliteTable('tickets', {
|
||||
qrCode: text('qr_code'),
|
||||
adminNote: text('admin_note'),
|
||||
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'),
|
||||
createdAt: text('created_at').notNull(),
|
||||
});
|
||||
|
||||
@@ -378,6 +386,12 @@ export const pgUsers = pgTable('users', {
|
||||
accountStatus: varchar('account_status', { length: 20 }).notNull().default('active'),
|
||||
// Incremented to invalidate previously issued JWTs (logout-everywhere, password change/reset)
|
||||
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(),
|
||||
updatedAt: timestamp('updated_at').notNull(),
|
||||
});
|
||||
@@ -468,6 +482,8 @@ export const pgTickets = pgTable('tickets', {
|
||||
qrCode: varchar('qr_code', { length: 255 }),
|
||||
adminNote: pgText('admin_note'),
|
||||
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'),
|
||||
createdAt: timestamp('created_at').notNull(),
|
||||
});
|
||||
|
||||
|
||||
+178
-130
@@ -7,7 +7,9 @@ import { logger } from 'hono/logger';
|
||||
import { swaggerUI } from '@hono/swagger-ui';
|
||||
|
||||
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 ticketsRoutes from './routes/tickets.js';
|
||||
import usersRoutes from './routes/users.js';
|
||||
@@ -24,10 +26,11 @@ import legalPagesRoutes from './routes/legal-pages.js';
|
||||
import legalSettingsRoutes from './routes/legal-settings.js';
|
||||
import faqRoutes from './routes/faq.js';
|
||||
import emailService from './lib/email.js';
|
||||
import { initEmailQueue } from './lib/emailQueue.js';
|
||||
import { startBookingCleanup } from './lib/bookingCleanup.js';
|
||||
import { startHoldSweep } from './lib/holdSweep.js';
|
||||
import { startEventEndSweep } from './lib/eventEndSweep.js';
|
||||
import { initEmailQueue, stopQueue } from './lib/emailQueue.js';
|
||||
import { startBookingCleanup, stopBookingCleanup } from './lib/bookingCleanup.js';
|
||||
import { startHoldSweep, stopHoldSweep } from './lib/holdSweep.js';
|
||||
import { startEventEndSweep, stopEventEndSweep } from './lib/eventEndSweep.js';
|
||||
import { closeRedis } from './lib/redis.js';
|
||||
import { getLock } from './lib/stores/lock.js';
|
||||
import { describeBackends, describeRedis, logSelectedBackends } from './lib/backends.js';
|
||||
|
||||
@@ -56,7 +59,7 @@ app.use(
|
||||
if (!origin) return frontendUrl;
|
||||
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,
|
||||
})
|
||||
);
|
||||
@@ -109,11 +112,15 @@ const openApiSpec = {
|
||||
],
|
||||
paths: {
|
||||
// ==================== 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: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Register a new user',
|
||||
description: 'Create a new user account. First registered user becomes admin. Password must be at least 10 characters.',
|
||||
summary: 'Register a new user (Better Auth)',
|
||||
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: {
|
||||
required: true,
|
||||
content: {
|
||||
@@ -123,8 +130,8 @@ const openApiSpec = {
|
||||
required: ['email', 'password', 'name'],
|
||||
properties: {
|
||||
email: { type: 'string', format: 'email' },
|
||||
password: { type: 'string', minLength: 10, description: 'Minimum 10 characters' },
|
||||
name: { type: 'string', minLength: 2 },
|
||||
password: { type: 'string', minLength: 10 },
|
||||
name: { type: 'string' },
|
||||
phone: { type: 'string' },
|
||||
languagePreference: { type: 'string', enum: ['en', 'es'] },
|
||||
},
|
||||
@@ -133,16 +140,17 @@ const openApiSpec = {
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
201: { description: 'User created successfully' },
|
||||
400: { description: 'Email already registered or validation error' },
|
||||
200: { description: 'User created; session cookie set' },
|
||||
422: { description: 'Email already registered' },
|
||||
400: { description: 'Validation error' },
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/auth/login': {
|
||||
'/api/auth/sign-in/email': {
|
||||
post: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Login with email and password',
|
||||
description: 'Authenticate user with email and password. Rate limited to 5 attempts per 15 minutes.',
|
||||
summary: 'Login with email and password (Better Auth)',
|
||||
description: 'Starts a cookie session. Per-email lockout: 5 failures / 15 min. Per-IP rate limited.',
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
@@ -159,42 +167,46 @@ const openApiSpec = {
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: { description: 'Login successful, returns JWT token' },
|
||||
200: { description: 'Login successful; session cookie set' },
|
||||
401: { description: 'Invalid credentials' },
|
||||
429: { description: 'Too many login attempts' },
|
||||
429: { description: 'Too many attempts' },
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/auth/google': {
|
||||
'/api/auth/sign-in/social': {
|
||||
post: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Login or register with Google',
|
||||
description: 'Authenticate using Google OAuth. Creates account if user does not exist.',
|
||||
summary: 'Login or register with Google (Better Auth)',
|
||||
description: 'Sign in with a Google ID token (Google Identity Services credential). Links to an existing account by verified email.',
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['credential'],
|
||||
required: ['provider'],
|
||||
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: {
|
||||
200: { description: 'Login successful' },
|
||||
400: { description: 'Invalid Google token' },
|
||||
200: { description: 'Login successful; session cookie set' },
|
||||
401: { description: 'Invalid Google token' },
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/auth/magic-link/request': {
|
||||
'/api/auth/sign-in/magic-link': {
|
||||
post: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Request magic link login',
|
||||
description: 'Send a one-time login link to email. Link expires in 10 minutes.',
|
||||
summary: 'Request magic link login (Better Auth)',
|
||||
description: 'Emails a one-time login link (10 min TTL, single use, hashed at rest). Does not create accounts.',
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
@@ -204,46 +216,33 @@ const openApiSpec = {
|
||||
required: ['email'],
|
||||
properties: {
|
||||
email: { type: 'string', format: 'email' },
|
||||
callbackURL: { type: 'string' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: { description: 'Magic link sent (if account exists)' },
|
||||
},
|
||||
responses: { 200: { description: 'Magic link sent (if account exists)' } },
|
||||
},
|
||||
},
|
||||
'/api/auth/magic-link/verify': {
|
||||
post: {
|
||||
get: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Verify magic link token',
|
||||
description: 'Verify the magic link token and login user.',
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['token'],
|
||||
properties: {
|
||||
token: { type: 'string' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
summary: 'Verify magic link token (Better Auth)',
|
||||
parameters: [
|
||||
{ name: 'token', in: 'query', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
responses: {
|
||||
200: { description: 'Login successful' },
|
||||
200: { description: 'Login successful; session cookie set' },
|
||||
400: { description: 'Invalid or expired token' },
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/auth/password-reset/request': {
|
||||
'/api/auth/request-password-reset': {
|
||||
post: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Request password reset',
|
||||
description: 'Send a password reset link to email. Link expires in 30 minutes.',
|
||||
summary: 'Request password reset (Better Auth)',
|
||||
description: 'Emails a reset link. Token expires in 30 minutes.',
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
@@ -253,31 +252,30 @@ const openApiSpec = {
|
||||
required: ['email'],
|
||||
properties: {
|
||||
email: { type: 'string', format: 'email' },
|
||||
redirectTo: { type: 'string' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: { description: 'Reset link sent (if account exists)' },
|
||||
},
|
||||
responses: { 200: { description: 'Reset link sent (if account exists)' } },
|
||||
},
|
||||
},
|
||||
'/api/auth/password-reset/confirm': {
|
||||
'/api/auth/reset-password': {
|
||||
post: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Confirm password reset',
|
||||
description: 'Reset password using the token from email.',
|
||||
summary: 'Reset password with token (Better Auth)',
|
||||
description: 'Sets a new password and revokes all existing sessions.',
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['token', 'password'],
|
||||
required: ['newPassword', 'token'],
|
||||
properties: {
|
||||
newPassword: { type: 'string', minLength: 10 },
|
||||
token: { type: 'string' },
|
||||
password: { type: 'string', minLength: 10 },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -289,62 +287,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': {
|
||||
post: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Change password',
|
||||
description: 'Change password for authenticated user.',
|
||||
summary: 'Change password (Better Auth)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
requestBody: {
|
||||
required: true,
|
||||
@@ -356,6 +302,7 @@ const openApiSpec = {
|
||||
properties: {
|
||||
currentPassword: { type: 'string' },
|
||||
newPassword: { type: 'string', minLength: 10 },
|
||||
revokeOtherSessions: { type: 'boolean' },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -368,26 +315,66 @@ const openApiSpec = {
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/auth/me': {
|
||||
'/api/auth/get-session': {
|
||||
get: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Get current user',
|
||||
description: 'Get the currently authenticated user profile.',
|
||||
summary: 'Get current session and user (Better Auth)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
responses: {
|
||||
200: { description: 'Current user data' },
|
||||
401: { description: 'Unauthorized' },
|
||||
200: { description: '{ session, user } or null when not authenticated' },
|
||||
},
|
||||
},
|
||||
},
|
||||
'/api/auth/logout': {
|
||||
'/api/auth/sign-out': {
|
||||
post: {
|
||||
tags: ['Auth'],
|
||||
summary: 'Logout',
|
||||
description: 'Logout current user (client-side token removal).',
|
||||
responses: {
|
||||
200: { description: 'Logged out' },
|
||||
summary: 'Logout (Better Auth)',
|
||||
description: 'Revokes the current session and clears the session cookie.',
|
||||
security: [{ bearerAuth: [] }],
|
||||
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 }' } },
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1761,10 +1748,10 @@ const openApiSpec = {
|
||||
components: {
|
||||
securitySchemes: {
|
||||
bearerAuth: {
|
||||
type: 'http',
|
||||
scheme: 'bearer',
|
||||
bearerFormat: 'JWT',
|
||||
description: 'JWT token obtained from login endpoint',
|
||||
type: 'apiKey',
|
||||
in: 'cookie',
|
||||
name: 'spanglish.session_token',
|
||||
description: 'Better Auth httpOnly session cookie (set by sign-in; __Secure- prefixed in production)',
|
||||
},
|
||||
},
|
||||
schemas: {
|
||||
@@ -1898,7 +1885,29 @@ app.get('/health', (c) => {
|
||||
});
|
||||
|
||||
// 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);
|
||||
app.route('/api/events', eventsRoutes);
|
||||
app.route('/api/tickets', ticketsRoutes);
|
||||
app.route('/api/users', usersRoutes);
|
||||
@@ -1943,8 +1952,11 @@ startEventEndSweep();
|
||||
// Initialize email templates on startup.
|
||||
// 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.
|
||||
// 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()
|
||||
.withLock('seed-templates', 30_000, () => emailService.seedDefaultTemplates())
|
||||
.withLock('seed-templates', 30_000, () => emailService.seedDefaultTemplates(), { onUnavailable: 'run' })
|
||||
.then((result) => {
|
||||
if (result === null) {
|
||||
console.log('[Email] Template seeding skipped (another instance holds the lock)');
|
||||
@@ -1961,7 +1973,43 @@ console.log(`📋 OpenAPI spec at http://localhost:${port}/openapi.json`);
|
||||
// Log which backend (memory/redis, local/s3) each subsystem selected.
|
||||
logSelectedBackends();
|
||||
|
||||
serve({
|
||||
const server = serve({
|
||||
fetch: app.fetch,
|
||||
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'));
|
||||
|
||||
+92
-331
@@ -1,366 +1,127 @@
|
||||
import * as jose from 'jose';
|
||||
import * as argon2 from 'argon2';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import crypto from 'crypto';
|
||||
import { Context } from 'hono';
|
||||
import { db, dbGet, dbAll, users, magicLinkTokens, userSessions } from '../db/index.js';
|
||||
import { eq, and, gt, sql, isNull } from 'drizzle-orm';
|
||||
import { generateId, getNow, toDbDate } from './utils.js';
|
||||
import { and, eq } from 'drizzle-orm';
|
||||
import { auth } from './betterAuth.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';
|
||||
const rawJwtSecret = process.env.JWT_SECRET;
|
||||
// Auth is provided by Better Auth (lib/betterAuth.ts): httpOnly cookie
|
||||
// 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.
|
||||
if (process.env.NODE_ENV === 'production' && (!rawJwtSecret || rawJwtSecret === DEFAULT_DEV_JWT_SECRET)) {
|
||||
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.');
|
||||
}
|
||||
// Re-exported for routes that hash/validate passwords outside Better Auth
|
||||
export { hashPassword, verifyPassword, validatePassword } from './passwordPolicy.js';
|
||||
|
||||
const JWT_SECRET = new TextEncoder().encode(rawJwtSecret || DEFAULT_DEV_JWT_SECRET);
|
||||
const JWT_ISSUER = 'spanglish';
|
||||
const JWT_AUDIENCE = 'spanglish-app';
|
||||
|
||||
export interface JWTPayload {
|
||||
sub: string;
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
phone: string | null;
|
||||
role: string;
|
||||
tokenVersion?: number;
|
||||
iat: number;
|
||||
exp: number;
|
||||
languagePreference: string | null;
|
||||
isClaimed: boolean;
|
||||
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> {
|
||||
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);
|
||||
}
|
||||
|
||||
// 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> {
|
||||
/**
|
||||
* Resolve the authenticated user for a request from its Better Auth session
|
||||
* cookie, or null when there is no valid session. Suspended/unclaimed/banned
|
||||
* accounts never get API access even with a live session cookie.
|
||||
*/
|
||||
export async function getAuthUser(c: Context): Promise<AuthUser | null> {
|
||||
try {
|
||||
const { payload } = await jose.jwtVerify(token, JWT_SECRET, {
|
||||
issuer: JWT_ISSUER,
|
||||
audience: JWT_AUDIENCE,
|
||||
});
|
||||
return payload as unknown as JWTPayload;
|
||||
const session = await auth.api.getSession({ headers: c.req.raw.headers });
|
||||
if (!session?.user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = session.user as any;
|
||||
|
||||
// Suspended (banned) or unclaimed accounts must not retain API access
|
||||
if (user.banned) {
|
||||
return null;
|
||||
}
|
||||
if (user.accountStatus && user.accountStatus !== 'active') {
|
||||
return null;
|
||||
}
|
||||
|
||||
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 async function getAuthUser(c: Context): Promise<any | null> {
|
||||
const authHeader = c.req.header('Authorization');
|
||||
if (!authHeader?.startsWith('Bearer ')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const token = authHeader.slice(7);
|
||||
const payload = await verifyToken(token);
|
||||
|
||||
if (!payload) {
|
||||
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') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
export function requireAuth(roles?: string[]) {
|
||||
return async (c: Context, next: () => Promise<void>) => {
|
||||
const user = await getAuthUser(c);
|
||||
|
||||
|
||||
if (!user) {
|
||||
return c.json({ error: 'Unauthorized' }, 401);
|
||||
}
|
||||
|
||||
|
||||
if (roles && !roles.includes(user.role)) {
|
||||
return c.json({ error: 'Forbidden' }, 403);
|
||||
}
|
||||
|
||||
|
||||
c.set('user', user);
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
export async function isFirstUser(): Promise<boolean> {
|
||||
const result = await dbAll(
|
||||
(db as any).select().from(users).limit(1)
|
||||
);
|
||||
return !result || result.length === 0;
|
||||
}
|
||||
|
||||
/** Fetch only the password hash column (never expose via getAuthUser). */
|
||||
/**
|
||||
* Fetch only the credential password hash (never exposed via getAuthUser).
|
||||
* Returns null when the user has no password set (Google-only or unclaimed).
|
||||
*/
|
||||
export async function getUserPasswordHash(userId: string): Promise<string | null> {
|
||||
const row = await dbGet<any>(
|
||||
(db as any)
|
||||
.select({ password: (users as any).password })
|
||||
.from(users)
|
||||
.where(eq((users as any).id, userId))
|
||||
.select({ password: (authAccounts as any).password })
|
||||
.from(authAccounts)
|
||||
.where(
|
||||
and(
|
||||
eq((authAccounts as any).userId, userId),
|
||||
eq((authAccounts as any).providerId, 'credential')
|
||||
)
|
||||
)
|
||||
);
|
||||
const hash = row?.password;
|
||||
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
|
||||
// endpoint and startup logging.
|
||||
|
||||
import { isRedisEnabled, isRedisHealthy } from './redis.js';
|
||||
import { isRedisEnabled, isRedisHealthy, getRedisHealthDetail } from './redis.js';
|
||||
import { getRateLimiter } from './stores/rateLimiter.js';
|
||||
import { getPubSub } from './stores/pubsub.js';
|
||||
import { getCache } from './stores/cache.js';
|
||||
import { getLock } from './stores/lock.js';
|
||||
import { getLoginLockout } from './stores/loginLockout.js';
|
||||
import { getStorage } from './storage.js';
|
||||
|
||||
export function describeBackends() {
|
||||
@@ -14,12 +15,13 @@ export function describeBackends() {
|
||||
rateLimiter: getRateLimiter().backend,
|
||||
pubsub: getPubSub().backend,
|
||||
lock: getLock().backend,
|
||||
loginLockout: getLoginLockout().backend,
|
||||
storage: getStorage().backend,
|
||||
};
|
||||
}
|
||||
|
||||
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. */
|
||||
@@ -32,5 +34,6 @@ export function logSelectedBackends(): void {
|
||||
console.log(` rate limiter: ${b.rateLimiter}`);
|
||||
console.log(` pub/sub: ${b.pubsub}`);
|
||||
console.log(` lock: ${b.lock}`);
|
||||
console.log(` login lockout:${b.loginLockout}`);
|
||||
console.log(` storage: ${b.storage}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
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';
|
||||
|
||||
// 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
|
||||
delete process.env.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]);
|
||||
}
|
||||
|
||||
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);
|
||||
})();
|
||||
}, 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,341 @@
|
||||
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';
|
||||
|
||||
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);
|
||||
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,
|
||||
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'],
|
||||
},
|
||||
},
|
||||
|
||||
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' } };
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
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 { getNow, toDbDate } from './utils.js';
|
||||
import { getLock } from './stores/lock.js';
|
||||
import { MANUAL_PAYMENT_PROVIDERS } from './manualProviders.js';
|
||||
import { MANUAL_PAYMENT_PROVIDERS } from './paymentProviders.js';
|
||||
|
||||
function getTtlMs(): number {
|
||||
const minutes = parseInt(process.env.PENDING_BOOKING_TTL_MINUTES || '30', 10);
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// 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).
|
||||
*/
|
||||
export function eventSeatBreakdownQuery(executor: any, eventId?: 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));
|
||||
return (eventId ? query.where(eq((tickets as any).eventId, eventId)) : query)
|
||||
.groupBy((tickets as any).eventId);
|
||||
}
|
||||
@@ -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
|
||||
// capacity-counting statuses ('pending', 'confirmed', 'checked_in'), releasing the seat.
|
||||
// Recovering such a booking (user "I've paid" again, or an admin reactivating / marking
|
||||
// it paid / reopening a failed payment) must atomically re-check that the event still has
|
||||
// room before re-reserving the seat, exactly like the original booking-creation flow in
|
||||
// routes/tickets.ts.
|
||||
// Under the seat-holding rule (lib/capacity.ts) a seat is held by paid/checked-in
|
||||
// tickets and by 'pending_approval' payments. Promoting a booking INTO one of those
|
||||
// states — user clicking "I've paid", an admin approving/reactivating a payment —
|
||||
// must atomically re-check that the event still has room, exactly like the original
|
||||
// booking-creation flow in routes/tickets.ts. Demoting back to bare 'pending'
|
||||
// (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
|
||||
// `options.fromTicketStatuses` (default ['on_hold']); tickets not in that list — and
|
||||
// tickets that already hold a seat — are left untouched and don't consume capacity.
|
||||
// Callers choose which ticket statuses are eligible to be flipped via
|
||||
// `options.fromTicketStatuses` (default ['on_hold']); tickets not in that list are
|
||||
// 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 { getNow, calculateAvailableSeats, isEventSoldOut } from './utils.js';
|
||||
import { seatHolderCountQuery, unseatedTicketCountQuery } from './capacity.js';
|
||||
|
||||
export class HoldCapacityError extends Error {
|
||||
constructor(public available: number) {
|
||||
@@ -26,6 +29,8 @@ interface ReserveOptions {
|
||||
extraPaymentFields?: Record<string, any>;
|
||||
/** Ticket statuses eligible to be flipped to targetTicketStatus. Default: ['on_hold']. */
|
||||
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.
|
||||
* 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.
|
||||
* 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(
|
||||
eventId: string,
|
||||
@@ -46,6 +52,10 @@ export async function reserveOnHoldBooking(
|
||||
if (ticketIds.length === 0) return;
|
||||
|
||||
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>(
|
||||
(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;
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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) => {
|
||||
if (needed <= 0) return;
|
||||
if (isEventSoldOut(event.capacity, reserved)) {
|
||||
@@ -80,26 +96,14 @@ export async function reserveOnHoldBooking(
|
||||
|
||||
if (isSqlite()) {
|
||||
(db as any).transaction((tx: any) => {
|
||||
const countRow = tx
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(tickets)
|
||||
.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));
|
||||
if (checkCapacity) {
|
||||
const countRow = seatHolderCountQuery(tx, eventId).get();
|
||||
const neededRow = unseatedTicketCountQuery(tx, ticketIds).get();
|
||||
assertCapacity(Number(countRow?.count || 0), Number(neededRow?.count || 0));
|
||||
}
|
||||
|
||||
tx.update(tickets)
|
||||
.set({ status: targetTicketStatus })
|
||||
.set(ticketUpdate)
|
||||
.where(and(
|
||||
inArray((tickets as any).id, ticketIds),
|
||||
inArray((tickets as any).status, fromTicketStatuses)
|
||||
@@ -113,28 +117,14 @@ export async function reserveOnHoldBooking(
|
||||
});
|
||||
} else {
|
||||
await (db as any).transaction(async (tx: any) => {
|
||||
const countRow = await dbGet<any>(
|
||||
tx
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.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));
|
||||
if (checkCapacity) {
|
||||
const countRow = await dbGet<any>(seatHolderCountQuery(tx, eventId));
|
||||
const neededRow = await dbGet<any>(unseatedTicketCountQuery(tx, ticketIds));
|
||||
assertCapacity(Number(countRow?.count || 0), Number(neededRow?.count || 0));
|
||||
}
|
||||
|
||||
await tx.update(tickets)
|
||||
.set({ status: targetTicketStatus })
|
||||
.set(ticketUpdate)
|
||||
.where(and(
|
||||
inArray((tickets as any).id, ticketIds),
|
||||
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
|
||||
// transfer / TPago / cash) after HOLD_THRESHOLD_HOURS. It covers two states, both of
|
||||
// which keep a seat reserved while awaiting a human:
|
||||
// - 'pending_approval': the user clicked "I've paid" and is waiting for an admin.
|
||||
// - 'pending' on a manual provider (see MANUAL_PAYMENT_PROVIDERS): the booking was
|
||||
// never settled (these are exempt from the 30-min auto-fail in bookingCleanup.ts,
|
||||
// so this is their only seat-release path).
|
||||
// In either case the payment (and its ticket) is silently moved to 'on_hold', which
|
||||
// drops it out of the capacity-counting statuses ('pending', 'confirmed', 'checked_in')
|
||||
// and so releases the seat back to the event. The user receives no notification — they
|
||||
// can recover via "I've paid" again, and an admin can reactivate or mark it paid
|
||||
// directly, both re-checking capacity.
|
||||
// This job moves abandoned manual-payment bookings (bank transfer / TPago / cash)
|
||||
// to 'on_hold' after HOLD_THRESHOLD_HOURS — bookings still in bare 'pending', i.e.
|
||||
// the customer never clicked "I've paid" and no admin settled them. These are exempt
|
||||
// from the 30-min auto-fail in bookingCleanup.ts, and under the capacity rule in
|
||||
// lib/capacity.ts they hold no seat, so this sweep is pure list hygiene: it keeps
|
||||
// dead checkouts out of the admin's pending queues.
|
||||
//
|
||||
// 'pending_approval' (customer claims they paid) is deliberately NOT swept: a
|
||||
// claimed payment keeps its seat until an admin approves or rejects it — the admin
|
||||
// UI surfaces aging claims instead of silently releasing them.
|
||||
//
|
||||
// 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 { getNow, toDbDate } from './utils.js';
|
||||
import { getLock } from './stores/lock.js';
|
||||
import { MANUAL_PAYMENT_PROVIDERS } from './manualProviders.js';
|
||||
import { MANUAL_PAYMENT_PROVIDERS } from './paymentProviders.js';
|
||||
|
||||
function getThresholdMs(): number {
|
||||
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'.
|
||||
* Covers 'pending_approval' payments and 'pending' payments on manual providers.
|
||||
* Returns the number of payments put on hold.
|
||||
* Move stale unsettled manual payments (and their tickets) to 'on_hold'.
|
||||
* Covers only bare 'pending' payments on manual providers; 'pending_approval'
|
||||
* is never swept. Returns the number of payments put on hold.
|
||||
*/
|
||||
export async function sweepStaleApprovals(): Promise<number> {
|
||||
const cutoff = toDbDate(new Date(Date.now() - getThresholdMs()));
|
||||
@@ -40,13 +41,8 @@ export async function sweepStaleApprovals(): Promise<number> {
|
||||
})
|
||||
.from(payments)
|
||||
.where(and(
|
||||
or(
|
||||
eq((payments as any).status, 'pending_approval'),
|
||||
and(
|
||||
eq((payments as any).status, 'pending'),
|
||||
inArray((payments as any).provider, [...MANUAL_PAYMENT_PROVIDERS])
|
||||
)
|
||||
),
|
||||
eq((payments as any).status, 'pending'),
|
||||
inArray((payments as any).provider, [...MANUAL_PAYMENT_PROVIDERS]),
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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,37 @@
|
||||
// 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 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' },
|
||||
};
|
||||
|
||||
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';
|
||||
}
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
/** 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 {
|
||||
const forwarded = c.req.header('x-forwarded-for');
|
||||
if (forwarded) return forwarded.split(',')[0].trim();
|
||||
return c.req.header('x-real-ip') || 'unknown';
|
||||
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');
|
||||
if (forwarded) {
|
||||
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
|
||||
// command connection plus a dedicated subscriber connection (a connection in
|
||||
// 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';
|
||||
|
||||
@@ -12,6 +20,14 @@ let client: Redis | null = null;
|
||||
let subscriber: Redis | null = null;
|
||||
let healthy = 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. */
|
||||
export function isRedisEnabled(): boolean {
|
||||
@@ -23,14 +39,41 @@ export function isRedisHealthy(): boolean {
|
||||
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 {
|
||||
const url = process.env.REDIS_URL as string;
|
||||
const instance = new Redis(url, {
|
||||
// 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,
|
||||
enableOfflineQueue: false,
|
||||
lazyConnect: false,
|
||||
connectTimeout: 5000,
|
||||
retryStrategy(times) {
|
||||
// Capped exponential backoff for reconnects: 200ms, 400ms ... max 5s.
|
||||
const delay = Math.min(times * 200, 5000);
|
||||
@@ -42,30 +85,53 @@ function buildClient(label: string): Redis {
|
||||
console.log(`[redis] (${label}) connecting`);
|
||||
});
|
||||
instance.on('ready', () => {
|
||||
healthy = true;
|
||||
console.log(`[redis] (${label}) ready`);
|
||||
setHealthy(true, `${label} ready`);
|
||||
});
|
||||
instance.on('error', (err) => {
|
||||
healthy = false;
|
||||
console.error(`[redis] (${label}) error:`, err?.message || err);
|
||||
setHealthy(false, `${label} error`);
|
||||
logErrorDebounced(label, err);
|
||||
});
|
||||
instance.on('reconnecting', () => {
|
||||
healthy = false;
|
||||
console.warn(`[redis] (${label}) reconnecting`);
|
||||
setHealthy(false, `${label} reconnecting`);
|
||||
});
|
||||
instance.on('end', () => {
|
||||
healthy = false;
|
||||
console.warn(`[redis] (${label}) connection closed`);
|
||||
setHealthy(false, `${label} connection closed`);
|
||||
});
|
||||
|
||||
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 {
|
||||
if (initialized || !isRedisEnabled()) return;
|
||||
initialized = true;
|
||||
client = buildClient('commands');
|
||||
subscriber = buildClient('subscriber');
|
||||
pingTimer = setInterval(() => {
|
||||
void pingOnce();
|
||||
}, 10_000);
|
||||
(pingTimer as any).unref?.();
|
||||
}
|
||||
|
||||
/** 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). */
|
||||
export async function closeRedis(): Promise<void> {
|
||||
if (pingTimer) {
|
||||
clearInterval(pingTimer);
|
||||
pingTimer = null;
|
||||
}
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
if (client) tasks.push(client.quit().catch(() => undefined));
|
||||
if (subscriber) tasks.push(subscriber.quit().catch(() => undefined));
|
||||
|
||||
@@ -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
|
||||
// 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 { 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 {
|
||||
readonly backend: 'memory' | 'redis';
|
||||
// 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>;
|
||||
release(key: string, token: string): Promise<void>;
|
||||
// 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 ====================
|
||||
|
||||
class MemoryLock implements Lock {
|
||||
export class MemoryLock implements Lock {
|
||||
readonly backend = 'memory' as const;
|
||||
private held = new Map<string, { token: string; expiresAt: number }>();
|
||||
|
||||
@@ -58,23 +81,23 @@ class MemoryLock implements Lock {
|
||||
const RELEASE_SCRIPT =
|
||||
'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;
|
||||
|
||||
async acquire(key: string, ttlMs: number): Promise<string | null> {
|
||||
const redis = getRedis();
|
||||
if (!redis) {
|
||||
// Redis configured but unavailable: do not block critical sections.
|
||||
return randomUUID();
|
||||
throw new LockUnavailableError('redis client not initialized');
|
||||
}
|
||||
const token = randomUUID();
|
||||
try {
|
||||
const result = await redis.set(`lock:${key}`, token, 'PX', ttlMs, 'NX');
|
||||
return result === 'OK' ? token : null;
|
||||
} catch (err: any) {
|
||||
console.error('[lock] redis acquire error, proceeding without lock:', err?.message || err);
|
||||
// Fail open so a Redis outage does not deadlock startup or jobs.
|
||||
return randomUUID();
|
||||
// Do NOT fabricate a token here: during an outage every replica would
|
||||
// "acquire" every lock and run the guarded sections concurrently. Let the
|
||||
// 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> {
|
||||
const token = await this.acquire(key, ttlMs);
|
||||
async withLock<T>(key: string, ttlMs: number, fn: () => Promise<T>, opts?: WithLockOptions): Promise<T | null> {
|
||||
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;
|
||||
try {
|
||||
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:
|
||||
// - 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
|
||||
// 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';
|
||||
|
||||
export interface RateLimitResult {
|
||||
@@ -24,7 +27,7 @@ interface Bucket {
|
||||
resetAt: number;
|
||||
}
|
||||
|
||||
class MemoryRateLimiter implements RateLimiter {
|
||||
export class MemoryRateLimiter implements RateLimiter {
|
||||
readonly backend = 'memory' as const;
|
||||
private buckets = new Map<string, Bucket>();
|
||||
|
||||
@@ -58,22 +61,44 @@ class MemoryRateLimiter implements RateLimiter {
|
||||
|
||||
// ==================== 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;
|
||||
|
||||
async consume(key: string, max: number, windowMs: number): Promise<RateLimitResult> {
|
||||
const redis = getRedis();
|
||||
if (!redis) return { allowed: true };
|
||||
|
||||
const redisKey = `rl:${key}`;
|
||||
try {
|
||||
const count = await redis.incr(redisKey);
|
||||
if (count === 1) {
|
||||
// First hit in this window: set the expiry that defines the window.
|
||||
await redis.pexpire(redisKey, windowMs);
|
||||
}
|
||||
const [count, ttl] = await withConsumeCommand(redis).rlConsume(`rl:${key}`, windowMs);
|
||||
if (count > max) {
|
||||
const ttl = await redis.pttl(redisKey);
|
||||
const retryAfter = ttl > 0 ? Math.ceil(ttl / 1000) : Math.ceil(windowMs / 1000);
|
||||
return { allowed: false, retryAfter };
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { db, dbGet, dbAll, users, events, tickets, payments, contacts, emailSubs
|
||||
import { eq, and, ne, gte, sql, desc, inArray } from 'drizzle-orm';
|
||||
import { requireAuth } from '../lib/auth.js';
|
||||
import { getNow } from '../lib/utils.js';
|
||||
import { eventSeatBreakdownQuery } from '../lib/capacity.js';
|
||||
|
||||
const adminRouter = new Hono();
|
||||
|
||||
@@ -20,8 +21,9 @@ const csvEscape = (value: string) => {
|
||||
adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) => {
|
||||
const now = getNow();
|
||||
|
||||
// Get upcoming events
|
||||
const upcomingEvents = await dbAll(
|
||||
// Get upcoming events with seat counts (paid + claimed, per lib/capacity.ts)
|
||||
// so the dashboard's capacity alerts reflect real availability.
|
||||
const upcomingEventsRaw = await dbAll<any>(
|
||||
(db as any)
|
||||
.select()
|
||||
.from(events)
|
||||
@@ -34,6 +36,24 @@ adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) =>
|
||||
.orderBy((events as any).startDatetime)
|
||||
.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
|
||||
const recentTickets = await dbAll(
|
||||
@@ -70,6 +90,8 @@ adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) =>
|
||||
.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>(
|
||||
(db as any)
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
@@ -77,6 +99,13 @@ adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) =>
|
||||
.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>(
|
||||
(db as any)
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
@@ -115,6 +144,7 @@ adminRouter.get('/dashboard', requireAuth(['admin', 'organizer']), async (c) =>
|
||||
totalTickets: totalTickets?.count || 0,
|
||||
confirmedTickets: confirmedTickets?.count || 0,
|
||||
pendingPayments: pendingPayments?.count || 0,
|
||||
awaitingApprovalPayments: awaitingApprovalPayments?.count || 0,
|
||||
onHoldPayments: onHoldPayments?.count || 0,
|
||||
totalRevenue,
|
||||
newContacts: newContacts?.count || 0,
|
||||
|
||||
@@ -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,96 @@
|
||||
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 } 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 });
|
||||
}
|
||||
|
||||
const user = await dbGet<any>(
|
||||
(db as any).select().from(users).where(eq((users as any).email, email))
|
||||
);
|
||||
|
||||
const canClaim = !!user && !user.banned && user.accountStatus !== 'suspended'
|
||||
&& (!user.isClaimed || user.accountStatus === 'unclaimed');
|
||||
|
||||
return c.json({ canClaim });
|
||||
});
|
||||
|
||||
export default authExt;
|
||||
@@ -1,18 +1,12 @@
|
||||
import { Hono } from 'hono';
|
||||
import { zValidator } from '@hono/zod-validator';
|
||||
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 } from '../db/index.js';
|
||||
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 { generateId, getNow } from '../lib/utils.js';
|
||||
|
||||
// User type that includes all fields (some added in schema updates)
|
||||
type AuthUser = User & {
|
||||
isClaimed: boolean;
|
||||
googleId: string | null;
|
||||
rucNumber: string | null;
|
||||
accountStatus: string;
|
||||
};
|
||||
import { requireAuth, getUserPasswordHash, hasGoogleAccount, validatePassword, type AuthUser } from '../lib/auth.js';
|
||||
import { auth } from '../lib/betterAuth.js';
|
||||
import { authSessions, authAccounts } from '../db/auth-schema.js';
|
||||
import { getNow } from '../lib/utils.js';
|
||||
|
||||
const dashboard = new Hono();
|
||||
|
||||
@@ -50,7 +44,7 @@ dashboard.get('/profile', async (c) => {
|
||||
isClaimed: user.isClaimed,
|
||||
accountStatus: user.accountStatus,
|
||||
hasPassword,
|
||||
hasGoogleLinked: !!user.googleId,
|
||||
hasGoogleLinked: await hasGoogleAccount(user.id),
|
||||
memberSince: user.createdAt,
|
||||
membershipDays,
|
||||
createdAt: user.createdAt,
|
||||
@@ -423,49 +417,77 @@ dashboard.get('/invoices', async (c) => {
|
||||
|
||||
// ==================== 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) => {
|
||||
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({
|
||||
sessions: sessions.map((s: any) => ({
|
||||
id: s.id,
|
||||
userAgent: s.userAgent,
|
||||
ipAddress: s.ipAddress,
|
||||
lastActiveAt: s.lastActiveAt,
|
||||
lastActiveAt: s.updatedAt,
|
||||
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) => {
|
||||
const user = (c as any).get('user') as AuthUser;
|
||||
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' });
|
||||
});
|
||||
|
||||
// Revoke all sessions (logout everywhere). Bumping the token version invalidates
|
||||
// every previously issued JWT for this user, which is the actual enforcement
|
||||
// mechanism (auth is stateless JWT, not DB-session based).
|
||||
// Revoke all other sessions (logout everywhere else); the current session
|
||||
// stays valid so this device remains signed in.
|
||||
dashboard.post('/sessions/revoke-all', async (c) => {
|
||||
const user = (c as any).get('user') as AuthUser;
|
||||
|
||||
await invalidateAllUserSessions(user.id);
|
||||
await bumpTokenVersion(user.id);
|
||||
|
||||
// Issue a fresh token so the current device stays signed in
|
||||
const refreshed = await dbGet<any>(
|
||||
(db as any).select().from(users).where(eq((users as any).id, user.id))
|
||||
);
|
||||
const token = await createToken(user.id, user.email, user.role, refreshed?.tokenVersion ?? 0);
|
||||
|
||||
return c.json({ message: 'All other sessions revoked.', token });
|
||||
await (db as any)
|
||||
.delete(authSessions)
|
||||
.where(
|
||||
and(
|
||||
eq((authSessions as any).userId, user.id),
|
||||
sql`${(authSessions as any).id} != ${user.sessionId}`
|
||||
)
|
||||
);
|
||||
|
||||
return c.json({ message: 'All other sessions revoked.' });
|
||||
});
|
||||
|
||||
// Set password (for users without one)
|
||||
@@ -476,53 +498,57 @@ const setPasswordSchema = z.object({
|
||||
dashboard.post('/set-password', zValidator('json', setPasswordSchema), async (c) => {
|
||||
const user = (c as any).get('user') as AuthUser;
|
||||
const { password } = c.req.valid('json');
|
||||
|
||||
|
||||
// Check if user already has a password
|
||||
if (await getUserPasswordHash(user.id)) {
|
||||
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);
|
||||
if (!passwordValidation.valid) {
|
||||
return c.json({ error: passwordValidation.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, user.id));
|
||||
|
||||
|
||||
try {
|
||||
await auth.api.setPassword({
|
||||
body: { newPassword: password },
|
||||
headers: c.req.raw.headers,
|
||||
});
|
||||
} catch (err: any) {
|
||||
return c.json({ error: err?.body?.message || 'Failed to set password' }, 400);
|
||||
}
|
||||
|
||||
return c.json({ message: 'Password set successfully' });
|
||||
});
|
||||
|
||||
// Unlink Google account (only if password is set)
|
||||
dashboard.post('/unlink-google', async (c) => {
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
if (!(await getUserPasswordHash(user.id))) {
|
||||
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)
|
||||
.update(users)
|
||||
.set({
|
||||
googleId: null,
|
||||
updatedAt: now,
|
||||
})
|
||||
.set({ updatedAt: getNow() })
|
||||
.where(eq((users as any).id, user.id));
|
||||
|
||||
|
||||
return c.json({ message: 'Google account unlinked' });
|
||||
});
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { requireAuth, getAuthUser } from '../lib/auth.js';
|
||||
import { generateId, getNow, convertBooleansForDb, toDbDate, toDbDateTz, calculateAvailableSeats } from '../lib/utils.js';
|
||||
import { slugify, uniqueSlug } from '../lib/slugify.js';
|
||||
import { revalidateFrontendCache } from '../lib/revalidate.js';
|
||||
import { eventSeatBreakdownQuery } from '../lib/capacity.js';
|
||||
|
||||
interface UserContext {
|
||||
id: string;
|
||||
@@ -201,27 +202,28 @@ eventsRouter.get('/', async (c) => {
|
||||
|
||||
const result = await dbAll<any>(query.orderBy(desc((events as any).startDatetime)));
|
||||
|
||||
// Single grouped query for booked counts across all events (avoids N+1: previously
|
||||
// this ran one COUNT query per event).
|
||||
const countRows = await dbAll<any>(
|
||||
(db as any)
|
||||
.select({ eventId: (tickets as any).eventId, count: sql<number>`count(*)` })
|
||||
.from(tickets)
|
||||
.where(sql`${(tickets as any).status} IN ('confirmed', 'checked_in')`)
|
||||
.groupBy((tickets as any).eventId)
|
||||
);
|
||||
const countByEvent = new Map<string, number>();
|
||||
// Single grouped query for seat counts across all events (avoids N+1: previously
|
||||
// this ran one COUNT query per event). bookedCount = paid (confirmed/checked_in);
|
||||
// claimedCount = "I've paid" claims awaiting admin verification. Both hold seats,
|
||||
// so availableSeats subtracts them together — the same formula the booking-creation
|
||||
// capacity check enforces (lib/capacity.ts).
|
||||
const countRows = await dbAll<any>(eventSeatBreakdownQuery(db));
|
||||
const countByEvent = new Map<string, { paid: number; claimed: number }>();
|
||||
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 normalized = normalizeEvent(event);
|
||||
const bookedCount = countByEvent.get(event.id) || 0;
|
||||
const counts = countByEvent.get(event.id) || { paid: 0, claimed: 0 };
|
||||
return {
|
||||
...normalized,
|
||||
bookedCount,
|
||||
availableSeats: calculateAvailableSeats(normalized.capacity, bookedCount),
|
||||
bookedCount: counts.paid,
|
||||
claimedCount: counts.claimed,
|
||||
availableSeats: calculateAvailableSeats(normalized.capacity, counts.paid + counts.claimed),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -246,27 +248,14 @@ eventsRouter.get('/:id', async (c) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Count confirmed AND checked_in tickets (checked_in were previously confirmed)
|
||||
// This ensures check-in doesn't affect capacity/spots_left
|
||||
const ticketCount = await dbGet<any>(
|
||||
(db as any)
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(tickets)
|
||||
.where(
|
||||
and(
|
||||
eq((tickets as any).eventId, event.id),
|
||||
sql`${(tickets as any).status} IN ('confirmed', 'checked_in')`
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const normalized = normalizeEvent(event);
|
||||
const bookedCount = ticketCount?.count || 0;
|
||||
const counts = await getEventSeatCounts(event.id);
|
||||
return c.json({
|
||||
event: {
|
||||
...normalized,
|
||||
bookedCount,
|
||||
availableSeats: calculateAvailableSeats(normalized.capacity, bookedCount),
|
||||
bookedCount: counts.paid,
|
||||
claimedCount: counts.claimed,
|
||||
availableSeats: calculateAvailableSeats(normalized.capacity, counts.paid + counts.claimed),
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -278,20 +267,14 @@ async function getSiteTimezone(): Promise<string> {
|
||||
return settings?.timezone || 'America/Asuncion';
|
||||
}
|
||||
|
||||
// Helper function to get ticket count for an event
|
||||
async function getEventTicketCount(eventId: string): Promise<number> {
|
||||
const ticketCount = await dbGet<any>(
|
||||
(db as any)
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(tickets)
|
||||
.where(
|
||||
and(
|
||||
eq((tickets as any).eventId, eventId),
|
||||
sql`${(tickets as any).status} IN ('confirmed', 'checked_in')`
|
||||
)
|
||||
)
|
||||
);
|
||||
return ticketCount?.count || 0;
|
||||
// Helper: paid (confirmed/checked_in) and claimed (pending_approval-held) seat
|
||||
// counts for one event — see lib/capacity.ts for the seat-holding rule.
|
||||
async function getEventSeatCounts(eventId: string): Promise<{ paid: number; claimed: number }> {
|
||||
const row = await dbGet<any>(eventSeatBreakdownQuery(db, eventId));
|
||||
return {
|
||||
paid: Number(row?.paidCount) || 0,
|
||||
claimed: Number(row?.claimedCount) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Get the earliest upcoming published event with ticket counts (ignores featured promotion)
|
||||
@@ -315,12 +298,13 @@ async function getNextChronologicalUpcoming(): Promise<any | null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
const bookedCount = await getEventTicketCount(event.id);
|
||||
const counts = await getEventSeatCounts(event.id);
|
||||
const normalized = normalizeEvent(event);
|
||||
return {
|
||||
...normalized,
|
||||
bookedCount,
|
||||
availableSeats: calculateAvailableSeats(normalized.capacity, bookedCount),
|
||||
bookedCount: counts.paid,
|
||||
claimedCount: counts.claimed,
|
||||
availableSeats: calculateAvailableSeats(normalized.capacity, counts.paid + counts.claimed),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -383,13 +367,14 @@ eventsRouter.get('/next/upcoming', async (c) => {
|
||||
|
||||
// If we have a valid featured event, return it
|
||||
if (featuredEvent) {
|
||||
const bookedCount = await getEventTicketCount(featuredEvent.id);
|
||||
const counts = await getEventSeatCounts(featuredEvent.id);
|
||||
const normalized = normalizeEvent(featuredEvent);
|
||||
return c.json({
|
||||
event: {
|
||||
...normalized,
|
||||
bookedCount,
|
||||
availableSeats: calculateAvailableSeats(normalized.capacity, bookedCount),
|
||||
bookedCount: counts.paid,
|
||||
claimedCount: counts.claimed,
|
||||
availableSeats: calculateAvailableSeats(normalized.capacity, counts.paid + counts.claimed),
|
||||
isFeatured: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
} from '../lib/lnbits.js';
|
||||
import emailService from '../lib/email.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();
|
||||
|
||||
@@ -106,12 +106,26 @@ async function startBackgroundChecker(ticketId: string, paymentHash: string, exp
|
||||
|
||||
const expiryMs = expirySeconds * 1000;
|
||||
|
||||
const lockToken = await getLock().acquire(`checker:${ticketId}`, expiryMs);
|
||||
if (!lockToken) {
|
||||
let lockToken: string | null = null;
|
||||
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.
|
||||
return;
|
||||
}
|
||||
checkerLockTokens.set(ticketId, lockToken);
|
||||
if (lockToken) {
|
||||
checkerLockTokens.set(ticketId, lockToken);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
let checkCount = 0;
|
||||
@@ -270,25 +284,35 @@ async function handlePaymentComplete(ticketId: string, paymentHash: string) {
|
||||
}
|
||||
|
||||
// Confirm all tickets in the booking (idempotent: only flip pending -> confirmed)
|
||||
let transitioned = 0;
|
||||
for (const ticket of ticketsToConfirm) {
|
||||
await (db as any)
|
||||
const result: any = await (db as any)
|
||||
.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')));
|
||||
|
||||
transitioned += result?.changes ?? result?.rowCount ?? 0;
|
||||
|
||||
await (db as any)
|
||||
.update(payments)
|
||||
.set({
|
||||
.set({
|
||||
status: 'paid',
|
||||
reference: paymentHash,
|
||||
paidAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(and(eq((payments as any).ticketId, ticket.id), eq((payments as any).status, 'pending')));
|
||||
|
||||
|
||||
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
|
||||
const payment = await dbGet<any>(
|
||||
(db as any)
|
||||
@@ -296,7 +320,7 @@ async function handlePaymentComplete(ticketId: string, paymentHash: string) {
|
||||
.from(payments)
|
||||
.where(eq((payments as any).ticketId, ticketId))
|
||||
);
|
||||
|
||||
|
||||
// Send confirmation emails asynchronously
|
||||
// For multi-ticket bookings, send email with all ticket info
|
||||
Promise.all([
|
||||
@@ -372,8 +396,7 @@ lnbitsRouter.get('/stream/:ticketId', async (c) => {
|
||||
}
|
||||
}, 15000);
|
||||
|
||||
// Clean up on disconnect
|
||||
stream.onAbort(() => {
|
||||
const cleanup = () => {
|
||||
clearInterval(heartbeat);
|
||||
const connections = activeConnections.get(ticketId);
|
||||
if (connections) {
|
||||
@@ -388,11 +411,28 @@ lnbitsRouter.get('/stream/:ticketId', async (c) => {
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Keep the stream open
|
||||
while (true) {
|
||||
await stream.sleep(30000);
|
||||
};
|
||||
|
||||
// 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) {
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,6 +19,9 @@ const updatePaymentSchema = z.object({
|
||||
const approvePaymentSchema = z.object({
|
||||
adminNote: z.string().optional(),
|
||||
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({
|
||||
@@ -285,7 +288,7 @@ paymentsRouter.put('/:id', requireAuth(['admin', 'organizer']), zValidator('json
|
||||
|
||||
await (db as any)
|
||||
.update(tickets)
|
||||
.set({ status: 'confirmed' })
|
||||
.set({ status: 'confirmed', paymentStatus: 'paid' })
|
||||
.where(eq((tickets as any).id, (t as any).id));
|
||||
}
|
||||
|
||||
@@ -317,29 +320,28 @@ paymentsRouter.put('/:id', requireAuth(['admin', 'organizer']), zValidator('json
|
||||
// Approve payment (admin) - specifically for pending_approval payments
|
||||
paymentsRouter.post('/:id/approve', requireAuth(['admin', 'organizer']), zValidator('json', approvePaymentSchema), async (c) => {
|
||||
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 payment = await dbGet<any>(
|
||||
(db as any)
|
||||
.select()
|
||||
.from(payments)
|
||||
.where(eq((payments as any).id, id))
|
||||
);
|
||||
|
||||
|
||||
if (!payment) {
|
||||
return c.json({ error: 'Payment not found' }, 404);
|
||||
}
|
||||
|
||||
|
||||
// Can approve pending, pending_approval, on_hold, or failed payments.
|
||||
// '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.
|
||||
// Bare 'pending' covers customers who paid but never clicked "I've paid".
|
||||
if (!['pending', 'pending_approval', 'on_hold', 'failed'].includes(payment.status)) {
|
||||
return c.json({ error: 'Payment cannot be approved in its current state' }, 400);
|
||||
}
|
||||
|
||||
const now = getNow();
|
||||
|
||||
// Get the ticket associated with this payment
|
||||
const ticket = await dbGet<any>(
|
||||
(db as any)
|
||||
@@ -381,55 +383,35 @@ paymentsRouter.post('/:id/approve', requireAuth(['admin', 'organizer']), zValida
|
||||
}
|
||||
}
|
||||
|
||||
if (payment.status === 'on_hold' || payment.status === 'failed') {
|
||||
// The seat was released when this booking went on hold or failed - re-check
|
||||
// capacity before confirming it directly.
|
||||
try {
|
||||
await reserveOnHoldBooking(
|
||||
ticket.eventId,
|
||||
ticketsToConfirm.map((t: any) => t.id),
|
||||
'confirmed',
|
||||
'paid',
|
||||
{
|
||||
paidByAdminId: user.id,
|
||||
fromTicketStatuses:
|
||||
payment.status === 'failed' ? ['cancelled', 'on_hold', 'pending'] : ['on_hold'],
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof HoldCapacityError) {
|
||||
return c.json({
|
||||
error: 'This event is now full. Your spot was released after the payment deadline passed.',
|
||||
}, 400);
|
||||
// Confirm the booking through the shared capacity-checked reservation.
|
||||
// Tickets that already hold a seat ('pending_approval' claims) cost no new
|
||||
// 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 {
|
||||
await reserveOnHoldBooking(
|
||||
ticket.eventId,
|
||||
ticketsToConfirm.map((t: any) => t.id),
|
||||
'confirmed',
|
||||
'paid',
|
||||
{
|
||||
paidByAdminId: user.id,
|
||||
fromTicketStatuses:
|
||||
payment.status === 'failed' ? ['cancelled', 'on_hold', 'pending'] : ['on_hold', 'pending'],
|
||||
skipCapacityCheck: allowOverCapacity,
|
||||
...(adminNote ? { extraPaymentFields: { adminNote } } : {}),
|
||||
}
|
||||
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));
|
||||
);
|
||||
} catch (err) {
|
||||
if (err instanceof HoldCapacityError) {
|
||||
return c.json({
|
||||
error: 'Approving this payment puts the event over capacity.',
|
||||
code: 'EVENT_OVER_CAPACITY',
|
||||
availableSeats: err.available,
|
||||
requestedSeats: ticketsToConfirm.length,
|
||||
}, 409);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Send confirmation emails asynchronously (if sendEmail is true, which is the default)
|
||||
|
||||
+115
-211
@@ -4,12 +4,13 @@ import { z } from 'zod';
|
||||
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 { requireAuth, getAuthUser } from '../lib/auth.js';
|
||||
import { generateId, generateTicketCode, getNow, toDbDate, calculateAvailableSeats, isEventSoldOut } from '../lib/utils.js';
|
||||
import { generateId, generateTicketCode, getNow, toDbDate, toDbBool, calculateAvailableSeats, isEventSoldOut } from '../lib/utils.js';
|
||||
import { createInvoice, isLNbitsConfigured, LNBITS_INVOICE_EXPIRY_SECONDS } from '../lib/lnbits.js';
|
||||
import { rateLimitMiddleware } from '../lib/rateLimit.js';
|
||||
import emailService from '../lib/email.js';
|
||||
import { generateTicketPDF, generateCombinedTicketsPDF } from '../lib/pdf.js';
|
||||
import { reserveOnHoldBooking, HoldCapacityError } from '../lib/holdRecovery.js';
|
||||
import { seatHolderCountQuery } from '../lib/capacity.js';
|
||||
|
||||
const ticketsRouter = new Hono();
|
||||
|
||||
@@ -128,21 +129,12 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
||||
return c.json({ error: 'Selected payment method is not available for this event' }, 400);
|
||||
}
|
||||
|
||||
// Check capacity - count pending, confirmed AND checked_in tickets.
|
||||
// Pending reservations must hold seats to prevent overselling via unpaid bookings
|
||||
// (cancelled/failed tickets are excluded so abandoned/rejected bookings free their seats).
|
||||
// Check capacity against held seats (paid/checked-in tickets plus claimed
|
||||
// manual payments) — see lib/capacity.ts. Bare pending bookings hold no seat.
|
||||
const existingTicketCount = await dbGet<any>(
|
||||
(db as any)
|
||||
.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')`
|
||||
)
|
||||
)
|
||||
seatHolderCountQuery(db, data.eventId)
|
||||
);
|
||||
|
||||
|
||||
const confirmedCount = existingTicketCount?.count || 0;
|
||||
const availableSeats = calculateAvailableSeats(event.capacity, confirmedCount);
|
||||
|
||||
@@ -172,12 +164,15 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
||||
user = {
|
||||
id: userId,
|
||||
email: data.email,
|
||||
password: '', // No password for guest bookings
|
||||
password: null, // No password for guest bookings; set on claim (Better Auth credential account)
|
||||
name: fullName,
|
||||
phone: data.phone || null,
|
||||
role: 'user',
|
||||
languagePreference: null,
|
||||
rucNumber,
|
||||
isClaimed: toDbBool(false),
|
||||
accountStatus: 'unclaimed',
|
||||
emailVerified: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
@@ -230,16 +225,7 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
||||
try {
|
||||
if (isSqlite()) {
|
||||
(db as any).transaction((tx: any) => {
|
||||
const countRow = 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')`
|
||||
)
|
||||
)
|
||||
.get();
|
||||
const countRow = seatHolderCountQuery(tx, data.eventId).get();
|
||||
const reserved = Number(countRow?.count || 0);
|
||||
if (isEventSoldOut(event.capacity, reserved)) {
|
||||
throw new BookingCapacityError('SOLD_OUT');
|
||||
@@ -290,17 +276,7 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
||||
});
|
||||
} else {
|
||||
await (db as any).transaction(async (tx: any) => {
|
||||
const countRow = await dbGet<any>(
|
||||
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 countRow = await dbGet<any>(seatHolderCountQuery(tx, data.eventId));
|
||||
const reserved = Number(countRow?.count || 0);
|
||||
if (isEventSoldOut(event.capacity, reserved)) {
|
||||
throw new BookingCapacityError('SOLD_OUT');
|
||||
@@ -388,7 +364,7 @@ ticketsRouter.post('/', zValidator('json', createTicketSchema), async (c) => {
|
||||
for (const t of createdTickets) {
|
||||
await (db as any)
|
||||
.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')));
|
||||
await (db as any)
|
||||
.update(payments)
|
||||
@@ -1029,6 +1005,9 @@ ticketsRouter.post('/validate', requireAuth(['admin', 'organizer', 'staff']), as
|
||||
attendeeEmail: ticket.attendeeEmail,
|
||||
attendeePhone: ticket.attendeePhone,
|
||||
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,
|
||||
checkedInBy,
|
||||
},
|
||||
@@ -1109,10 +1088,12 @@ ticketsRouter.post('/:id/mark-paid', requireAuth(['admin', 'organizer', 'staff']
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
if (ticket.status === 'cancelled') {
|
||||
return c.json({ error: 'Cannot confirm cancelled ticket' }, 400);
|
||||
}
|
||||
@@ -1152,12 +1133,12 @@ ticketsRouter.post('/:id/mark-paid', requireAuth(['admin', 'organizer', 'staff']
|
||||
throw err;
|
||||
}
|
||||
} else {
|
||||
// Confirm all tickets in the booking
|
||||
// Confirm all tickets in the booking (checked-in tickets keep their status)
|
||||
for (const t of ticketsToConfirm) {
|
||||
// Update ticket status
|
||||
await (db as any)
|
||||
.update(tickets)
|
||||
.set({ status: 'confirmed' })
|
||||
.set({ status: t.status === 'checked_in' ? 'checked_in' : 'confirmed', paymentStatus: 'paid' })
|
||||
.where(eq((tickets as any).id, t.id));
|
||||
|
||||
// Update payment status
|
||||
@@ -1451,11 +1432,14 @@ ticketsRouter.post('/admin/create', requireAuth(['admin', 'organizer', 'staff'])
|
||||
user = {
|
||||
id: userId,
|
||||
email: attendeeEmail,
|
||||
password: '',
|
||||
password: null,
|
||||
name: adminFullName,
|
||||
phone: data.phone || null,
|
||||
role: 'user',
|
||||
languagePreference: null,
|
||||
isClaimed: toDbBool(false),
|
||||
accountStatus: 'unclaimed',
|
||||
emailVerified: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
@@ -1498,6 +1482,7 @@ ticketsRouter.post('/admin/create', requireAuth(['admin', 'organizer', 'staff'])
|
||||
attendeePhone: data.phone && data.phone.trim() ? data.phone.trim() : null,
|
||||
preferredLanguage: data.preferredLanguage || null,
|
||||
status: ticketStatus,
|
||||
paymentStatus: 'paid',
|
||||
qrCode,
|
||||
checkinAt: data.autoCheckin ? now : null,
|
||||
adminNote: data.adminNote || null,
|
||||
@@ -1541,148 +1526,26 @@ ticketsRouter.post('/admin/create', requireAuth(['admin', 'organizer', 'staff'])
|
||||
}, 201);
|
||||
});
|
||||
|
||||
// Admin create manual ticket (sends confirmation email + ticket to attendee)
|
||||
ticketsRouter.post('/admin/manual', requireAuth(['admin', 'organizer', 'staff']), zValidator('json', z.object({
|
||||
eventId: z.string(),
|
||||
firstName: z.string().min(2),
|
||||
lastName: z.string().optional().or(z.literal('')),
|
||||
email: z.string().email('Valid email is required for manual tickets'),
|
||||
phone: 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({
|
||||
// Unified admin add-attendee endpoint backing the single Add Ticket modal.
|
||||
// type drives payment handling:
|
||||
// paid — email required; paid cash payment; confirmation email + QR sent
|
||||
// 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', requireAuth(['admin', 'organizer', 'staff']), zValidator('json', z.object({
|
||||
eventId: z.string(),
|
||||
type: z.enum(['paid', 'unpaid', 'guest']),
|
||||
firstName: z.string().min(1),
|
||||
lastName: z.string().optional().or(z.literal('')),
|
||||
email: z.string().email().optional().or(z.literal('')),
|
||||
phone: z.string().optional().or(z.literal('')),
|
||||
preferredLanguage: z.enum(['en', 'es']).optional(),
|
||||
checkinNow: z.boolean().optional().default(false),
|
||||
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'],
|
||||
})), async (c) => {
|
||||
const data = c.req.valid('json');
|
||||
|
||||
@@ -1693,18 +1556,20 @@ ticketsRouter.post('/admin/guest', requireAuth(['admin', 'organizer', 'staff']),
|
||||
return c.json({ error: 'Event not found' }, 404);
|
||||
}
|
||||
|
||||
// Admin-added tickets bypass the capacity check (intentional over-capacity)
|
||||
|
||||
const now = getNow();
|
||||
const adminUser = (c as any).get('user');
|
||||
|
||||
// Find or create user (use placeholder email if none provided)
|
||||
const attendeeEmail = data.email && data.email.trim()
|
||||
? data.email.trim()
|
||||
: `guest-${generateId()}@guestinvite.local`;
|
||||
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`;
|
||||
|
||||
const fullName = data.lastName && data.lastName.trim()
|
||||
? `${data.firstName} ${data.lastName}`.trim()
|
||||
: data.firstName;
|
||||
|
||||
// Find or create user
|
||||
let user = await dbGet<any>(
|
||||
(db as any).select().from(users).where(eq((users as any).email, attendeeEmail))
|
||||
);
|
||||
@@ -1714,19 +1579,22 @@ ticketsRouter.post('/admin/guest', requireAuth(['admin', 'organizer', 'staff']),
|
||||
user = {
|
||||
id: userId,
|
||||
email: attendeeEmail,
|
||||
password: '',
|
||||
password: null,
|
||||
name: fullName,
|
||||
phone: data.phone || null,
|
||||
role: 'user',
|
||||
languagePreference: null,
|
||||
isClaimed: toDbBool(false),
|
||||
accountStatus: 'unclaimed',
|
||||
emailVerified: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
await (db as any).insert(users).values(user);
|
||||
}
|
||||
|
||||
// Check for existing active ticket (only for real emails, not placeholder)
|
||||
if (data.email && data.email.trim()) {
|
||||
// Check for existing active ticket (only when a real email was provided)
|
||||
if (hasEmail) {
|
||||
const existingTicket = await dbGet<any>(
|
||||
(db as any)
|
||||
.select()
|
||||
@@ -1745,6 +1613,7 @@ ticketsRouter.post('/admin/guest', requireAuth(['admin', 'organizer', 'staff']),
|
||||
|
||||
const ticketId = generateId();
|
||||
const qrCode = generateTicketCode();
|
||||
const paymentStatus = data.type === 'guest' ? 'comp' : data.type === 'paid' ? 'paid' : 'unpaid';
|
||||
|
||||
const newTicket = {
|
||||
id: ticketId,
|
||||
@@ -1752,50 +1621,85 @@ ticketsRouter.post('/admin/guest', requireAuth(['admin', 'organizer', 'staff']),
|
||||
eventId: data.eventId,
|
||||
attendeeFirstName: data.firstName,
|
||||
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,
|
||||
preferredLanguage: data.preferredLanguage || null,
|
||||
status: 'confirmed',
|
||||
isGuest: 1,
|
||||
status: data.checkinNow ? 'checked_in' : 'confirmed',
|
||||
isGuest: data.type === 'guest' ? 1 : 0,
|
||||
paymentStatus,
|
||||
qrCode,
|
||||
checkinAt: null,
|
||||
checkinAt: data.checkinNow ? now : null,
|
||||
checkedInByAdminId: data.checkinNow ? adminUser?.id || null : null,
|
||||
adminNote: data.adminNote || null,
|
||||
createdAt: now,
|
||||
};
|
||||
|
||||
await (db as any).insert(tickets).values(newTicket);
|
||||
|
||||
// Create a $0 payment record to track the invite
|
||||
// Payment record: paid cash for paid/guest ($0 for guest), pending tpago for unpaid
|
||||
const paymentId = generateId();
|
||||
const newPayment = {
|
||||
id: paymentId,
|
||||
ticketId,
|
||||
provider: 'cash',
|
||||
amount: 0,
|
||||
currency: event.currency,
|
||||
status: 'paid',
|
||||
reference: 'Guest invite',
|
||||
paidAt: now,
|
||||
paidByAdminId: adminUser?.id || null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
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,
|
||||
ticketId,
|
||||
provider: 'cash',
|
||||
amount: data.type === 'guest' ? 0 : event.price,
|
||||
currency: event.currency,
|
||||
status: 'paid',
|
||||
reference: data.type === 'guest' ? 'Guest invite' : 'Manual ticket',
|
||||
paidAt: now,
|
||||
paidByAdminId: adminUser?.id || null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
await (db as any).insert(payments).values(newPayment);
|
||||
|
||||
// Send booking confirmation email if a real email was provided
|
||||
if (data.email && data.email.trim()) {
|
||||
// Emails (asynchronous): paid always confirms; guest confirms when an email
|
||||
// exists; unpaid sends the TPago (Bancard) pay-link instructions instead
|
||||
if (data.type === 'unpaid') {
|
||||
if (hasEmail) {
|
||||
emailService.sendPaymentInstructions(ticketId).then(result => {
|
||||
if (!result.success) {
|
||||
console.error(`[Email] Failed to send pay link for unpaid ticket ${ticketId}:`, result.error);
|
||||
}
|
||||
}).catch(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.log(`[Email] Booking confirmation sent for guest ticket ${ticketId}`);
|
||||
} else {
|
||||
console.error(`[Email] Failed to send booking confirmation for guest ticket ${ticketId}:`, result.error);
|
||||
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 guest ticket:', err);
|
||||
console.error(`[Email] Exception sending booking confirmation for ${data.type} ticket:`, err);
|
||||
});
|
||||
}
|
||||
|
||||
const messages: Record<string, string> = {
|
||||
paid: 'Ticket created — confirmation email sent',
|
||||
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({
|
||||
ticket: {
|
||||
...newTicket,
|
||||
@@ -1806,7 +1710,7 @@ ticketsRouter.post('/admin/guest', requireAuth(['admin', 'organizer', 'staff']),
|
||||
},
|
||||
},
|
||||
payment: newPayment,
|
||||
message: 'Guest ticket created successfully',
|
||||
message: data.checkinNow ? `${messages[data.type]} · checked in` : messages[data.type],
|
||||
}, 201);
|
||||
});
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ 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 { eq, desc, sql, and, gte, lte } from 'drizzle-orm';
|
||||
import { requireAuth } from '../lib/auth.js';
|
||||
import { authSessions } from '../db/auth-schema.js';
|
||||
import { getNow, toDbDate } from '../lib/utils.js';
|
||||
|
||||
interface UserContext {
|
||||
@@ -175,11 +176,28 @@ usersRouter.put('/:id', requireAuth(['admin', 'organizer', 'staff', 'marketing',
|
||||
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)
|
||||
.update(users)
|
||||
.set({ ...data, updatedAt: getNow() })
|
||||
.set({ ...data, ...statusMirror, updatedAt: getNow() })
|
||||
.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(
|
||||
(db as any)
|
||||
.select({
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
"skipLibCheck": true,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"declaration": true,
|
||||
"declaration": false,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"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."}';
|
||||
}
|
||||
|
||||
# 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 / {
|
||||
limit_req zone=spanglish_api_limit burst=50 nodelay;
|
||||
|
||||
|
||||
@@ -28,7 +28,20 @@ services:
|
||||
|
||||
redis:
|
||||
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:
|
||||
- redisdata:/data
|
||||
healthcheck:
|
||||
@@ -46,7 +59,7 @@ services:
|
||||
DB_TYPE: postgres
|
||||
DATABASE_URL: postgresql://spanglish:spanglish@postgres:5432/spanglish
|
||||
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
|
||||
FRONTEND_URL: http://localhost:8080
|
||||
# Optional S3-compatible storage so uploads are shared across replicas.
|
||||
|
||||
@@ -79,6 +79,24 @@ server {
|
||||
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
|
||||
location /api {
|
||||
proxy_pass http://spanglish_backend;
|
||||
|
||||
@@ -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
|
||||
@@ -4,4 +4,8 @@ upstream spanglish_frontend {
|
||||
|
||||
upstream spanglish_backend {
|
||||
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)
|
||||
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)
|
||||
# Get your Client ID from: https://console.cloud.google.com/apis/credentials
|
||||
# 1. Create a new OAuth 2.0 Client ID (Web application)
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
// being hardcoded to localhost.
|
||||
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).
|
||||
const extraImageHosts = (process.env.NEXT_PUBLIC_IMAGE_HOSTS || '')
|
||||
.split(',')
|
||||
@@ -20,6 +24,9 @@ const securityHeaders = [
|
||||
];
|
||||
|
||||
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: {
|
||||
// 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).
|
||||
@@ -39,6 +46,10 @@ const nextConfig = {
|
||||
},
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: '/api/photos/:path*',
|
||||
destination: `${PHOTO_API_URL}/api/photos/:path*`,
|
||||
},
|
||||
{
|
||||
source: '/api/:path*',
|
||||
destination: `${BACKEND_URL}/api/:path*`,
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"@tiptap/pm": "^3.18.0",
|
||||
"@tiptap/react": "^3.18.0",
|
||||
"@tiptap/starter-kit": "^3.18.0",
|
||||
"better-auth": "1.6.25",
|
||||
"clsx": "^2.1.1",
|
||||
"html5-qrcode": "^2.3.8",
|
||||
"next": "^14.2.4",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, Suspense } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState, Suspense } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
@@ -9,29 +9,48 @@ import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import { authApi } from '@/lib/api';
|
||||
import { authClient } from '@/lib/auth-client';
|
||||
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() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { locale: language } = useLanguage();
|
||||
const { setAuthData } = useAuth();
|
||||
const { refreshUser } = useAuth();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [checking, setChecking] = useState(true);
|
||||
const [hasSession, setHasSession] = useState(false);
|
||||
const [alreadyClaimed, setAlreadyClaimed] = useState(false);
|
||||
const [formData, setFormData] = useState({
|
||||
password: '',
|
||||
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) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!token) {
|
||||
toast.error(language === 'es' ? 'Token no válido' : 'Invalid token');
|
||||
return;
|
||||
}
|
||||
|
||||
if (formData.password !== formData.confirmPassword) {
|
||||
toast.error(language === 'es' ? 'Las contraseñas no coinciden' : 'Passwords do not match');
|
||||
return;
|
||||
@@ -49,8 +68,8 @@ function ClaimAccountContent() {
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const result = await authApi.confirmClaimAccount(token, { password: formData.password });
|
||||
setAuthData({ user: result.user, token: result.token });
|
||||
await authApi.confirmClaimAccount(formData.password);
|
||||
await refreshUser();
|
||||
toast.success(language === 'es' ? '¡Cuenta activada!' : 'Account activated!');
|
||||
router.push('/dashboard');
|
||||
} 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 (
|
||||
<div className="section-padding min-h-[70vh] flex items-center">
|
||||
<div className="container-page">
|
||||
@@ -76,8 +109,8 @@ function ClaimAccountContent() {
|
||||
</h2>
|
||||
<p className="text-gray-600 mb-6">
|
||||
{language === 'es'
|
||||
? 'Este enlace de activación no es válido o ha expirado.'
|
||||
: 'This activation link is invalid or has expired.'}
|
||||
? '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. Request a new one using "Email Link" on the login page.'}
|
||||
</p>
|
||||
<Link href="/login">
|
||||
<Button>
|
||||
@@ -127,7 +160,7 @@ function ClaimAccountContent() {
|
||||
<p className="text-xs text-gray-500 -mt-4">
|
||||
{language === 'es' ? 'Mínimo 10 caracteres' : 'Minimum 10 characters'}
|
||||
</p>
|
||||
|
||||
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
label={language === 'es' ? 'Confirmar Contraseña' : 'Confirm Password'}
|
||||
@@ -136,7 +169,7 @@ function ClaimAccountContent() {
|
||||
onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
|
||||
required
|
||||
/>
|
||||
|
||||
|
||||
<Button type="submit" className="w-full" size="lg" isLoading={loading}>
|
||||
{language === 'es' ? 'Activar Cuenta' : 'Activate Account'}
|
||||
</Button>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useLanguage } from '@/context/LanguageContext';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import { safeInternalPath } from '@/lib/safeRedirect';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
function MagicLinkContent() {
|
||||
@@ -18,11 +19,12 @@ function MagicLinkContent() {
|
||||
const verificationAttempted = useRef(false);
|
||||
|
||||
const token = searchParams.get('token');
|
||||
const callbackURL = safeInternalPath(searchParams.get('callbackURL'), '/dashboard');
|
||||
|
||||
useEffect(() => {
|
||||
// Prevent duplicate verification attempts (React StrictMode double-invokes effects)
|
||||
if (verificationAttempted.current) return;
|
||||
|
||||
|
||||
if (token) {
|
||||
verificationAttempted.current = true;
|
||||
verifyToken();
|
||||
@@ -34,11 +36,17 @@ function MagicLinkContent() {
|
||||
|
||||
const verifyToken = async () => {
|
||||
try {
|
||||
await loginWithMagicLink(token!);
|
||||
const user = await loginWithMagicLink(token!);
|
||||
setStatus('success');
|
||||
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(() => {
|
||||
router.push('/dashboard');
|
||||
router.push(destination);
|
||||
}, 1500);
|
||||
} catch (err: any) {
|
||||
setStatus('error');
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useParams, useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
import { eventsApi, ticketsApi, paymentOptionsApi, Event, PaymentOptionsConfig } from '@/lib/api';
|
||||
import { formatDateLong, formatTime, formatRucDisplay } from '@/lib/utils';
|
||||
import { formatDateLong, formatTime, formatRucDisplay, eventSpotsLeft, isEventSoldOut } from '@/lib/utils';
|
||||
import { isSafeExternalUrl } from '@/lib/safeRedirect';
|
||||
import toast from 'react-hot-toast';
|
||||
import type {
|
||||
@@ -108,16 +108,15 @@ export default function BookingPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
const bookedCount = eventRes.event.bookedCount ?? 0;
|
||||
const capacity = eventRes.event.capacity ?? 0;
|
||||
const soldOut = bookedCount >= capacity;
|
||||
if (soldOut) {
|
||||
// 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'));
|
||||
router.push(`/events/${eventRes.event.slug}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const spotsLeft = Math.max(0, capacity - bookedCount);
|
||||
const spotsLeft = eventSpotsLeft(eventRes.event);
|
||||
setEvent(eventRes.event);
|
||||
// Cap quantity by available spots (never allow requesting more than spotsLeft)
|
||||
setTicketQuantity((q) => Math.min(q, Math.max(1, spotsLeft)));
|
||||
@@ -366,6 +365,23 @@ export default function BookingPage() {
|
||||
}
|
||||
} catch (error: any) {
|
||||
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.
|
||||
const message = String(error?.message || '');
|
||||
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 {
|
||||
setSubmitting(false);
|
||||
}
|
||||
@@ -388,8 +404,8 @@ export default function BookingPage() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const spotsLeft = Math.max(0, event.capacity - (event.bookedCount ?? 0));
|
||||
const isSoldOut = (event.bookedCount ?? 0) >= event.capacity;
|
||||
const spotsLeft = eventSpotsLeft(event);
|
||||
const isSoldOut = isEventSoldOut(event);
|
||||
|
||||
// Paying step - waiting for Lightning payment (compact design)
|
||||
if (step === 'paying' && bookingResult && bookingResult.lightningInvoice) {
|
||||
|
||||
@@ -25,7 +25,7 @@ interface AccountTabProps {
|
||||
*/
|
||||
export default function AccountTab({ onUpdate }: AccountTabProps) {
|
||||
const { locale } = useLanguage();
|
||||
const { user, updateUser, logout } = useAuth();
|
||||
const { user, updateUser } = useAuth();
|
||||
|
||||
const [profile, setProfile] = useState<UserProfile | null>(null);
|
||||
const [sessions, setSessions] = useState<UserSession[]>([]);
|
||||
@@ -187,15 +187,17 @@ export default function AccountTab({ onUpdate }: AccountTabProps) {
|
||||
if (
|
||||
!confirm(
|
||||
locale === 'es'
|
||||
? '¿Cerrar todas las sesiones? Serás desconectado.'
|
||||
: 'Log out of all sessions? You will be logged out.'
|
||||
? '¿Cerrar todas las otras sesiones? Esta sesión permanecerá activa.'
|
||||
: 'Log out of all other sessions? This session stays signed in.'
|
||||
)
|
||||
)
|
||||
return;
|
||||
try {
|
||||
await dashboardApi.revokeAllSessions();
|
||||
toast.success(locale === 'es' ? 'Todas las sesiones cerradas' : 'All sessions revoked');
|
||||
logout();
|
||||
toast.success(
|
||||
locale === 'es' ? 'Todas las otras sesiones cerradas' : 'All other sessions revoked'
|
||||
);
|
||||
loadData();
|
||||
} catch (error) {
|
||||
toast.error(locale === 'es' ? 'Error' : 'Failed');
|
||||
}
|
||||
@@ -477,7 +479,7 @@ export default function AccountTab({ onUpdate }: AccountTabProps) {
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{sessions.map((session, index) => (
|
||||
{sessions.map((session) => (
|
||||
<div
|
||||
key={session.id}
|
||||
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}`}
|
||||
</p>
|
||||
</div>
|
||||
{index === 0 ? (
|
||||
{session.current ? (
|
||||
<span className="ml-3 whitespace-nowrap text-xs font-medium text-green-600">
|
||||
{locale === 'es' ? 'Esta sesión' : 'This session'}
|
||||
</span>
|
||||
|
||||
@@ -23,7 +23,7 @@ type Tab = 'overview' | 'tickets' | 'payments' | 'account';
|
||||
export default function DashboardPage() {
|
||||
const router = useRouter();
|
||||
const { locale } = useLanguage();
|
||||
const { user, isLoading: authLoading, token } = useAuth();
|
||||
const { user, isLoading: authLoading } = useAuth();
|
||||
|
||||
const [activeTab, setActiveTab] = useState<Tab>('overview');
|
||||
const [nextEvent, setNextEvent] = useState<NextEventInfo | null>(null);
|
||||
@@ -36,11 +36,13 @@ export default function DashboardPage() {
|
||||
router.push('/login');
|
||||
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();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [user, authLoading, token]);
|
||||
}, [user, authLoading]);
|
||||
|
||||
const loadDashboardData = async () => {
|
||||
setLoading(true);
|
||||
|
||||
@@ -5,7 +5,7 @@ import Link from 'next/link';
|
||||
import Image from 'next/image';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { eventsApi, Event } from '@/lib/api';
|
||||
import { formatPrice, formatDateLong, formatTime } from '@/lib/utils';
|
||||
import { formatPrice, formatDateLong, formatTime, eventSpotsLeft, isEventSoldOut } from '@/lib/utils';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import ShareButtons from '@/components/ShareButtons';
|
||||
@@ -43,9 +43,10 @@ export default function EventDetailClient({ eventId, initialEvent }: EventDetail
|
||||
.catch(console.error);
|
||||
}, [eventId]);
|
||||
|
||||
// Spots left: never negative; sold out when confirmed >= capacity
|
||||
const spotsLeft = Math.max(0, event.capacity - (event.bookedCount ?? 0));
|
||||
const isSoldOut = (event.bookedCount ?? 0) >= event.capacity;
|
||||
// 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));
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -117,7 +117,10 @@ function generateEventJsonLd(event: Event) {
|
||||
'@type': 'Offer',
|
||||
price: event.price,
|
||||
priceCurrency: event.currency,
|
||||
availability: Math.max(0, (event.capacity ?? 0) - (event.bookedCount ?? 0)) > 0
|
||||
availability:
|
||||
(typeof event.availableSeats === 'number'
|
||||
? event.availableSeats
|
||||
: Math.max(0, (event.capacity ?? 0) - (event.bookedCount ?? 0))) > 0
|
||||
? 'https://schema.org/InStock'
|
||||
: 'https://schema.org/SoldOut',
|
||||
url: `${siteUrl}/events/${event.slug}`,
|
||||
|
||||
@@ -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,421 @@
|
||||
'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 { ImageGridSkeleton } from '@/components/ui/Skeleton';
|
||||
import Lightbox from '@/components/Lightbox';
|
||||
import LoginModal from '@/components/LoginModal';
|
||||
import {
|
||||
ArrowDownTrayIcon,
|
||||
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);
|
||||
|
||||
// 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]);
|
||||
|
||||
if (loading || (authLoading && !initial)) {
|
||||
return (
|
||||
<div className="section-padding">
|
||||
<div className="container-page">
|
||||
<ImageGridSkeleton />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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);
|
||||
const lightboxItems = readyPhotos.map((p) => ({
|
||||
id: p.id,
|
||||
previewUrl: p.urls.preview || p.urls.original,
|
||||
downloadUrl: 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;
|
||||
const heroUrl = coverPhoto ? coverPhoto.urls.preview || coverPhoto.urls.thumb : null;
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Hero */}
|
||||
<div className="relative bg-brand-navy overflow-hidden">
|
||||
{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" />
|
||||
</>
|
||||
)}
|
||||
<div className="relative container-page px-4 pt-20 pb-8 md:pt-32 md:pb-12">
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Masonry grid */}
|
||||
<div className="container-page px-2 sm:px-4 py-4 md:py-8">
|
||||
{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>
|
||||
) : (
|
||||
<div className="columns-2 sm:columns-3 lg:columns-4 gap-2 md:gap-3 [column-fill:_balance]">
|
||||
{readyPhotos.map((photo, i) => (
|
||||
<div
|
||||
key={photo.id}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => setLightboxIndex(i)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
setLightboxIndex(i);
|
||||
}
|
||||
}}
|
||||
className="group relative mb-2 md:mb-3 break-inside-avoid overflow-hidden rounded-xl bg-gray-100 cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
style={
|
||||
photo.width && photo.height
|
||||
? { aspectRatio: `${photo.width} / ${photo.height}` }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={photo.urls.thumb}
|
||||
alt=""
|
||||
loading={i < 8 ? 'eager' : 'lazy'}
|
||||
className="w-full h-auto group-hover:scale-[1.03] transition-transform duration-300"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors" />
|
||||
<a
|
||||
href={photo.urls.original}
|
||||
download={photo.originalFilename || true}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="absolute bottom-2 right-2 hidden md:flex p-2 rounded-full bg-black/50 text-white opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80"
|
||||
aria-label={es ? 'Descargar' : 'Download'}
|
||||
>
|
||||
<ArrowDownTrayIcon className="w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{lightboxIndex !== null && (
|
||||
<Lightbox
|
||||
items={lightboxItems}
|
||||
index={lightboxIndex}
|
||||
onClose={() => setLightboxIndex(null)}
|
||||
onNavigate={setLightboxIndex}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 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,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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Metadata } from 'next';
|
||||
import type { PhotoGallery } from '@/lib/api';
|
||||
import PhotosIndexClient from './PhotosIndexClient';
|
||||
|
||||
// Server-side calls go straight to the photo-api service; the browser uses
|
||||
// the same-origin /api/photos path via the Next rewrite / nginx.
|
||||
const photoApiUrl = process.env.PHOTO_API_URL || 'http://localhost:3003';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Event Photo Galleries',
|
||||
description: 'Photos from past Spanglish language exchange events in Asunción.',
|
||||
};
|
||||
|
||||
async function getGalleries(): Promise<PhotoGallery[]> {
|
||||
try {
|
||||
const res = await fetch(`${photoApiUrl}/api/photos/public/galleries`, {
|
||||
next: { revalidate: 300 },
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
const data = await res.json();
|
||||
return data.galleries || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export default async function PhotosPage() {
|
||||
const galleries = await getGalleries();
|
||||
return <PhotosIndexClient galleries={galleries} />;
|
||||
}
|
||||
@@ -107,11 +107,7 @@ export default function AdminEmailsPage() {
|
||||
|
||||
const loadEvents = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/events', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${localStorage.getItem('spanglish-token')}`,
|
||||
},
|
||||
});
|
||||
const res = await fetch('/api/events', { credentials: 'same-origin' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setEvents(data.events || []);
|
||||
@@ -169,9 +165,7 @@ export default function AdminEmailsPage() {
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/events/${composeForm.eventId}/attendees`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${localStorage.getItem('spanglish-token')}`,
|
||||
},
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
|
||||
@@ -18,3 +18,23 @@ export function StatusBadge({ status, compact = false }: { status: string; compa
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// Ticket payment status: Paid (revenue), Unpaid (balance due at door), Comp (free guest).
|
||||
// Tickets created before the payment_status column default to unpaid via backfill.
|
||||
export function PaymentBadge({ paymentStatus, compact = false }: { paymentStatus?: string; compact?: boolean }) {
|
||||
if (!paymentStatus) return null;
|
||||
const styles: Record<string, string> = {
|
||||
paid: 'bg-emerald-100 text-emerald-700',
|
||||
unpaid: 'bg-orange-100 text-orange-700',
|
||||
comp: 'bg-amber-100 text-amber-700',
|
||||
};
|
||||
return (
|
||||
<span className={clsx(
|
||||
'inline-flex items-center rounded-full font-medium',
|
||||
compact ? 'px-1.5 py-0.5 text-[10px]' : 'px-2 py-0.5 text-xs',
|
||||
styles[paymentStatus] || 'bg-gray-100 text-gray-800'
|
||||
)}>
|
||||
{paymentStatus === 'comp' ? 'Comp' : paymentStatus === 'unpaid' ? 'Unpaid' : 'Paid'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import type { Dispatch, FormEvent, SetStateAction } from 'react';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import clsx from 'clsx';
|
||||
import {
|
||||
BanknotesIcon,
|
||||
CheckCircleIcon,
|
||||
EnvelopeIcon,
|
||||
LinkIcon,
|
||||
StarIcon,
|
||||
XMarkIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import type { AddTicketType, AddTicketFormState } from '../_types';
|
||||
|
||||
interface AddTicketModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
form: AddTicketFormState;
|
||||
setForm: Dispatch<SetStateAction<AddTicketFormState>>;
|
||||
onSubmit: (e: FormEvent) => void;
|
||||
submitting: boolean;
|
||||
eventPriceLabel: string;
|
||||
}
|
||||
|
||||
const TYPE_OPTIONS: { value: AddTicketType; label: string }[] = [
|
||||
{ value: 'paid', label: 'Paid' },
|
||||
{ value: 'unpaid', label: 'Unpaid' },
|
||||
{ value: 'guest', label: 'Guest' },
|
||||
];
|
||||
|
||||
const SUBMIT_LABELS: Record<AddTicketType, string> = {
|
||||
paid: 'Create & send ticket',
|
||||
unpaid: 'Create & send pay link',
|
||||
guest: 'Invite guest',
|
||||
};
|
||||
|
||||
const SUBMIT_ICONS: Record<AddTicketType, typeof EnvelopeIcon> = {
|
||||
paid: EnvelopeIcon,
|
||||
unpaid: LinkIcon,
|
||||
guest: StarIcon,
|
||||
};
|
||||
|
||||
// Live "what happens" preview lines for the selected type / email / check-in combo
|
||||
function previewLines(form: AddTicketFormState, eventPriceLabel: string): string[] {
|
||||
const hasEmail = !!form.email.trim();
|
||||
const lines: string[] = [];
|
||||
if (form.type === 'paid') {
|
||||
lines.push(`Payment of ${eventPriceLabel} recorded as paid — counts toward revenue`);
|
||||
lines.push('Confirmation email with QR ticket sent');
|
||||
} else if (form.type === 'unpaid') {
|
||||
lines.push(`Ticket marked unpaid — balance of ${eventPriceLabel} to collect at the door`);
|
||||
lines.push('QR code issued, flagged "unpaid" for door staff');
|
||||
lines.push(hasEmail
|
||||
? 'Bancard (TPago) payment link emailed to the attendee'
|
||||
: 'No email — no pay link sent, payment collected at the door');
|
||||
} else {
|
||||
lines.push('Free guest ticket (comp) — not counted in revenue');
|
||||
lines.push('Auto-confirmed with QR code');
|
||||
lines.push(hasEmail ? 'Confirmation email sent' : 'No email — nothing is sent');
|
||||
}
|
||||
if (form.checkinNow) {
|
||||
lines.push('Checked in immediately');
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
const PREVIEW_STYLES: Record<AddTicketType, { box: string; icon: string; text: string }> = {
|
||||
paid: { box: 'bg-blue-50 border-blue-200', icon: 'text-blue-500', text: 'text-blue-800' },
|
||||
unpaid: { box: 'bg-orange-50 border-orange-200', icon: 'text-orange-500', text: 'text-orange-800' },
|
||||
guest: { box: 'bg-amber-50 border-amber-200', icon: 'text-amber-500', text: 'text-amber-800' },
|
||||
};
|
||||
|
||||
const PREVIEW_ICONS: Record<AddTicketType, typeof EnvelopeIcon> = {
|
||||
paid: CheckCircleIcon,
|
||||
unpaid: BanknotesIcon,
|
||||
guest: StarIcon,
|
||||
};
|
||||
|
||||
export function AddTicketModal({
|
||||
open,
|
||||
onClose,
|
||||
form,
|
||||
setForm,
|
||||
onSubmit,
|
||||
submitting,
|
||||
eventPriceLabel,
|
||||
}: AddTicketModalProps) {
|
||||
if (!open) return null;
|
||||
|
||||
const emailRequired = form.type === 'paid';
|
||||
const style = PREVIEW_STYLES[form.type];
|
||||
const PreviewIcon = PREVIEW_ICONS[form.type];
|
||||
const SubmitIcon = SUBMIT_ICONS[form.type];
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 z-50 flex items-end md:items-center justify-center p-0 md:p-4"
|
||||
onClick={onClose}
|
||||
role="presentation"
|
||||
>
|
||||
<Card
|
||||
className="w-full md:max-w-md max-h-[90vh] flex flex-col overflow-hidden rounded-t-2xl md:rounded-card"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between p-4 border-b border-secondary-light-gray flex-shrink-0">
|
||||
<h2 className="text-base font-bold">Add Ticket</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 hover:bg-gray-100 rounded-btn min-h-[44px] min-w-[44px] flex items-center justify-center"
|
||||
>
|
||||
<XMarkIcon className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<form onSubmit={onSubmit} className="p-4 space-y-3 overflow-y-auto flex-1 min-h-0">
|
||||
{/* Segmented ticket-type control */}
|
||||
<div className="flex rounded-btn bg-gray-100 p-1">
|
||||
{TYPE_OPTIONS.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
onClick={() => setForm((f) => ({ ...f, type: option.value }))}
|
||||
className={clsx(
|
||||
'flex-1 px-3 py-2 text-sm font-medium rounded-btn min-h-[36px] transition-colors',
|
||||
form.type === option.value
|
||||
? 'bg-white shadow-sm text-primary-dark'
|
||||
: 'text-gray-500 hover:text-gray-700'
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">First Name *</label>
|
||||
<input type="text" required value={form.firstName}
|
||||
onChange={(e) => setForm((f) => ({ ...f, firstName: e.target.value }))}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="First name" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Last Name</label>
|
||||
<input type="text" value={form.lastName}
|
||||
onChange={(e) => setForm((f) => ({ ...f, lastName: e.target.value }))}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="Last name" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Email {emailRequired && '*'}</label>
|
||||
<input type="email" required={emailRequired} value={form.email}
|
||||
onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder={emailRequired ? 'email@example.com' : 'email@example.com (optional)'} />
|
||||
<p className="text-[10px] text-gray-500 mt-1">
|
||||
{form.type === 'paid' && 'Ticket will be sent to this email'}
|
||||
{form.type === 'unpaid' && 'If provided, the payment link is sent here'}
|
||||
{form.type === 'guest' && 'If provided, a confirmation email will be sent'}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Phone</label>
|
||||
<input type="tel" value={form.phone}
|
||||
onChange={(e) => setForm((f) => ({ ...f, phone: e.target.value }))}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="+595 981 123456" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Admin Note</label>
|
||||
<textarea value={form.adminNote}
|
||||
onChange={(e) => setForm((f) => ({ ...f, adminNote: e.target.value }))}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
rows={2} placeholder="Internal note..." />
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<input type="checkbox" id="checkinNow" checked={form.checkinNow}
|
||||
onChange={(e) => setForm((f) => ({ ...f, checkinNow: e.target.checked }))}
|
||||
className="w-4 h-4 rounded border-secondary-light-gray text-primary-yellow focus:ring-primary-yellow" />
|
||||
<label htmlFor="checkinNow" className="text-sm font-medium">Check in now</label>
|
||||
</div>
|
||||
|
||||
{/* Live preview of what this submission does */}
|
||||
<div className={clsx('border rounded-lg p-3', style.box)}>
|
||||
<div className="flex items-start gap-2">
|
||||
<PreviewIcon className={clsx('w-4 h-4 mt-0.5 flex-shrink-0', style.icon)} />
|
||||
<div className={clsx('text-xs', style.text)}>
|
||||
<p className="font-medium">What happens:</p>
|
||||
<ul className="list-disc ml-4 mt-0.5 space-y-0.5">
|
||||
{previewLines(form, eventPriceLabel).map((line) => (
|
||||
<li key={line}>{line}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 pt-2">
|
||||
<Button type="button" variant="outline" onClick={onClose} className="flex-1 min-h-[44px]">Cancel</Button>
|
||||
<Button type="submit" isLoading={submitting} className="flex-1 min-h-[44px]">
|
||||
<SubmitIcon className="w-4 h-4 mr-1.5" />
|
||||
{SUBMIT_LABELS[form.type]}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +1,16 @@
|
||||
import type { Dispatch, FormEvent, SetStateAction } from 'react';
|
||||
import { Ticket } from '@/lib/api';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import { BottomSheet } from '@/components/admin/MobileComponents';
|
||||
import clsx from 'clsx';
|
||||
import {
|
||||
BanknotesIcon,
|
||||
CheckCircleIcon,
|
||||
EnvelopeIcon,
|
||||
PlusIcon,
|
||||
StarIcon,
|
||||
XMarkIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import type { AttendeeStatusFilter, AttendeeFormState, AddAtDoorFormState } from '../_types';
|
||||
import type { AttendeeStatusFilter, AddTicketType } from '../_types';
|
||||
|
||||
interface EventModalsProps {
|
||||
// counts + filter
|
||||
@@ -29,6 +28,7 @@ interface EventModalsProps {
|
||||
// add ticket sheet
|
||||
showAddTicketSheet: boolean;
|
||||
setShowAddTicketSheet: (value: boolean) => void;
|
||||
openAddTicket: (type: AddTicketType) => void;
|
||||
// export sheets
|
||||
showExportSheet: boolean;
|
||||
setShowExportSheet: (value: boolean) => void;
|
||||
@@ -36,24 +36,6 @@ interface EventModalsProps {
|
||||
showTicketExportSheet: boolean;
|
||||
setShowTicketExportSheet: (value: boolean) => void;
|
||||
handleExportTickets: (status: 'confirmed' | 'checked_in' | 'all') => void;
|
||||
// add at door
|
||||
showAddAtDoorModal: boolean;
|
||||
setShowAddAtDoorModal: (value: boolean) => void;
|
||||
addAtDoorForm: AddAtDoorFormState;
|
||||
setAddAtDoorForm: Dispatch<SetStateAction<AddAtDoorFormState>>;
|
||||
handleAddAtDoor: (e: FormEvent) => void;
|
||||
// manual ticket
|
||||
showManualTicketModal: boolean;
|
||||
setShowManualTicketModal: (value: boolean) => void;
|
||||
manualTicketForm: AttendeeFormState;
|
||||
setManualTicketForm: Dispatch<SetStateAction<AttendeeFormState>>;
|
||||
handleManualTicket: (e: FormEvent) => void;
|
||||
// invite guest
|
||||
showInviteGuestModal: boolean;
|
||||
setShowInviteGuestModal: (value: boolean) => void;
|
||||
inviteGuestForm: AttendeeFormState;
|
||||
setInviteGuestForm: Dispatch<SetStateAction<AttendeeFormState>>;
|
||||
handleInviteGuest: (e: FormEvent) => void;
|
||||
// shared submit flag
|
||||
submitting: boolean;
|
||||
// note modal
|
||||
@@ -83,27 +65,13 @@ export function EventModals(props: EventModalsProps) {
|
||||
setMobileFilterOpen,
|
||||
showAddTicketSheet,
|
||||
setShowAddTicketSheet,
|
||||
openAddTicket,
|
||||
showExportSheet,
|
||||
setShowExportSheet,
|
||||
handleExportAttendees,
|
||||
showTicketExportSheet,
|
||||
setShowTicketExportSheet,
|
||||
handleExportTickets,
|
||||
showAddAtDoorModal,
|
||||
setShowAddAtDoorModal,
|
||||
addAtDoorForm,
|
||||
setAddAtDoorForm,
|
||||
handleAddAtDoor,
|
||||
showManualTicketModal,
|
||||
setShowManualTicketModal,
|
||||
manualTicketForm,
|
||||
setManualTicketForm,
|
||||
handleManualTicket,
|
||||
showInviteGuestModal,
|
||||
setShowInviteGuestModal,
|
||||
inviteGuestForm,
|
||||
setInviteGuestForm,
|
||||
handleInviteGuest,
|
||||
submitting,
|
||||
showNoteModal,
|
||||
setShowNoteModal,
|
||||
@@ -156,27 +124,27 @@ export function EventModals(props: EventModalsProps) {
|
||||
>
|
||||
<div className="space-y-1">
|
||||
<button
|
||||
onClick={() => { setShowManualTicketModal(true); setShowAddTicketSheet(false); }}
|
||||
onClick={() => { openAddTicket('paid'); setShowAddTicketSheet(false); }}
|
||||
className="w-full text-left px-4 py-3 rounded-btn text-sm hover:bg-gray-50 min-h-[44px] flex items-center gap-3"
|
||||
>
|
||||
<EnvelopeIcon className="w-5 h-5 text-gray-500" />
|
||||
<div>
|
||||
<p className="font-medium">Manual Ticket</p>
|
||||
<p className="text-xs text-gray-500">Send confirmation email with ticket</p>
|
||||
<p className="font-medium">Paid Ticket</p>
|
||||
<p className="text-xs text-gray-500">Send confirmation email with QR ticket</p>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setShowAddAtDoorModal(true); setShowAddTicketSheet(false); }}
|
||||
onClick={() => { openAddTicket('unpaid'); setShowAddTicketSheet(false); }}
|
||||
className="w-full text-left px-4 py-3 rounded-btn text-sm hover:bg-gray-50 min-h-[44px] flex items-center gap-3"
|
||||
>
|
||||
<PlusIcon className="w-5 h-5 text-gray-500" />
|
||||
<BanknotesIcon className="w-5 h-5 text-gray-500" />
|
||||
<div>
|
||||
<p className="font-medium">Add at Door</p>
|
||||
<p className="text-xs text-gray-500">Quick add with optional auto check-in</p>
|
||||
<p className="font-medium">Unpaid Ticket</p>
|
||||
<p className="text-xs text-gray-500">Pay link now or collect at the door</p>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setShowInviteGuestModal(true); setShowAddTicketSheet(false); }}
|
||||
onClick={() => { openAddTicket('guest'); setShowAddTicketSheet(false); }}
|
||||
className="w-full text-left px-4 py-3 rounded-btn text-sm hover:bg-gray-50 min-h-[44px] flex items-center gap-3"
|
||||
>
|
||||
<StarIcon className="w-5 h-5 text-gray-500" />
|
||||
@@ -237,243 +205,6 @@ export function EventModals(props: EventModalsProps) {
|
||||
</div>
|
||||
</BottomSheet>
|
||||
|
||||
{/* Add at Door Modal */}
|
||||
{showAddAtDoorModal && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 z-50 flex items-end md:items-center justify-center p-0 md:p-4"
|
||||
onClick={() => setShowAddAtDoorModal(false)}
|
||||
role="presentation"
|
||||
>
|
||||
<Card
|
||||
className="w-full md:max-w-md max-h-[90vh] flex flex-col overflow-hidden rounded-t-2xl md:rounded-card"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between p-4 border-b border-secondary-light-gray flex-shrink-0">
|
||||
<h2 className="text-base font-bold">Add Attendee at Door</h2>
|
||||
<button
|
||||
onClick={() => setShowAddAtDoorModal(false)}
|
||||
className="p-2 hover:bg-gray-100 rounded-btn min-h-[44px] min-w-[44px] flex items-center justify-center"
|
||||
>
|
||||
<XMarkIcon className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<form onSubmit={handleAddAtDoor} className="p-4 space-y-3 overflow-y-auto flex-1 min-h-0">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">First Name *</label>
|
||||
<input type="text" required value={addAtDoorForm.firstName}
|
||||
onChange={(e) => setAddAtDoorForm({ ...addAtDoorForm, firstName: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="First name" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Last Name</label>
|
||||
<input type="text" value={addAtDoorForm.lastName}
|
||||
onChange={(e) => setAddAtDoorForm({ ...addAtDoorForm, lastName: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="Last name" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Email</label>
|
||||
<input type="email" value={addAtDoorForm.email}
|
||||
onChange={(e) => setAddAtDoorForm({ ...addAtDoorForm, email: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="email@example.com" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Phone</label>
|
||||
<input type="tel" value={addAtDoorForm.phone}
|
||||
onChange={(e) => setAddAtDoorForm({ ...addAtDoorForm, phone: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="+595 981 123456" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Admin Note</label>
|
||||
<textarea value={addAtDoorForm.adminNote}
|
||||
onChange={(e) => setAddAtDoorForm({ ...addAtDoorForm, adminNote: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
rows={2} placeholder="Internal note..." />
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<input type="checkbox" id="autoCheckin" checked={addAtDoorForm.autoCheckin}
|
||||
onChange={(e) => setAddAtDoorForm({ ...addAtDoorForm, autoCheckin: e.target.checked })}
|
||||
className="w-4 h-4 rounded border-secondary-light-gray text-primary-yellow focus:ring-primary-yellow" />
|
||||
<label htmlFor="autoCheckin" className="text-sm font-medium">Auto check-in immediately</label>
|
||||
</div>
|
||||
<div className="flex gap-3 pt-2">
|
||||
<Button type="button" variant="outline" onClick={() => setShowAddAtDoorModal(false)} className="flex-1 min-h-[44px]">Cancel</Button>
|
||||
<Button type="submit" isLoading={submitting} className="flex-1 min-h-[44px]">Add Attendee</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Manual Ticket Modal */}
|
||||
{showManualTicketModal && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 z-50 flex items-end md:items-center justify-center p-0 md:p-4"
|
||||
onClick={() => setShowManualTicketModal(false)}
|
||||
role="presentation"
|
||||
>
|
||||
<Card
|
||||
className="w-full md:max-w-md max-h-[90vh] flex flex-col overflow-hidden rounded-t-2xl md:rounded-card"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between p-4 border-b border-secondary-light-gray flex-shrink-0">
|
||||
<div>
|
||||
<h2 className="text-base font-bold">Create Manual Ticket</h2>
|
||||
<p className="text-xs text-gray-500">Confirmation email will be sent</p>
|
||||
</div>
|
||||
<button onClick={() => setShowManualTicketModal(false)}
|
||||
className="p-2 hover:bg-gray-100 rounded-btn min-h-[44px] min-w-[44px] flex items-center justify-center">
|
||||
<XMarkIcon className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<form onSubmit={handleManualTicket} className="p-4 space-y-3 overflow-y-auto flex-1 min-h-0">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">First Name *</label>
|
||||
<input type="text" required value={manualTicketForm.firstName}
|
||||
onChange={(e) => setManualTicketForm({ ...manualTicketForm, firstName: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="First name" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Last Name</label>
|
||||
<input type="text" value={manualTicketForm.lastName}
|
||||
onChange={(e) => setManualTicketForm({ ...manualTicketForm, lastName: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="Last name" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Email *</label>
|
||||
<input type="email" required value={manualTicketForm.email}
|
||||
onChange={(e) => setManualTicketForm({ ...manualTicketForm, email: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="email@example.com" />
|
||||
<p className="text-[10px] text-gray-500 mt-1">Ticket will be sent to this email</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Phone</label>
|
||||
<input type="tel" value={manualTicketForm.phone}
|
||||
onChange={(e) => setManualTicketForm({ ...manualTicketForm, phone: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="+595 981 123456" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Admin Note</label>
|
||||
<textarea value={manualTicketForm.adminNote}
|
||||
onChange={(e) => setManualTicketForm({ ...manualTicketForm, adminNote: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
rows={2} placeholder="Internal note..." />
|
||||
</div>
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<EnvelopeIcon className="w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0" />
|
||||
<div className="text-xs text-blue-800">
|
||||
<p className="font-medium">This will send:</p>
|
||||
<ul className="list-disc ml-4 mt-0.5 space-y-0.5">
|
||||
<li>Booking confirmation email</li>
|
||||
<li>Ticket with QR code</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3 pt-2">
|
||||
<Button type="button" variant="outline" onClick={() => setShowManualTicketModal(false)} className="flex-1 min-h-[44px]">Cancel</Button>
|
||||
<Button type="submit" isLoading={submitting} className="flex-1 min-h-[44px]">
|
||||
<EnvelopeIcon className="w-4 h-4 mr-1.5" />
|
||||
Create & Send
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Invite Guest Modal */}
|
||||
{showInviteGuestModal && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 z-50 flex items-end md:items-center justify-center p-0 md:p-4"
|
||||
onClick={() => setShowInviteGuestModal(false)}
|
||||
role="presentation"
|
||||
>
|
||||
<Card
|
||||
className="w-full md:max-w-md max-h-[90vh] flex flex-col overflow-hidden rounded-t-2xl md:rounded-card"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between p-4 border-b border-secondary-light-gray flex-shrink-0">
|
||||
<div>
|
||||
<h2 className="text-base font-bold">Invite Guest</h2>
|
||||
<p className="text-xs text-gray-500">Free ticket — not counted in revenue</p>
|
||||
</div>
|
||||
<button onClick={() => setShowInviteGuestModal(false)}
|
||||
className="p-2 hover:bg-gray-100 rounded-btn min-h-[44px] min-w-[44px] flex items-center justify-center">
|
||||
<XMarkIcon className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<form onSubmit={handleInviteGuest} className="p-4 space-y-3 overflow-y-auto flex-1 min-h-0">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">First Name *</label>
|
||||
<input type="text" required value={inviteGuestForm.firstName}
|
||||
onChange={(e) => setInviteGuestForm({ ...inviteGuestForm, firstName: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="First name" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Last Name</label>
|
||||
<input type="text" value={inviteGuestForm.lastName}
|
||||
onChange={(e) => setInviteGuestForm({ ...inviteGuestForm, lastName: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="Last name" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Email</label>
|
||||
<input type="email" value={inviteGuestForm.email}
|
||||
onChange={(e) => setInviteGuestForm({ ...inviteGuestForm, email: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="email@example.com (optional)" />
|
||||
<p className="text-[10px] text-gray-500 mt-1">If provided, a confirmation email will be sent</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Phone</label>
|
||||
<input type="tel" value={inviteGuestForm.phone}
|
||||
onChange={(e) => setInviteGuestForm({ ...inviteGuestForm, phone: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
placeholder="+595 981 123456" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium mb-1">Admin Note</label>
|
||||
<textarea value={inviteGuestForm.adminNote}
|
||||
onChange={(e) => setInviteGuestForm({ ...inviteGuestForm, adminNote: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
|
||||
rows={2} placeholder="Internal note..." />
|
||||
</div>
|
||||
<div className="bg-amber-50 border border-amber-200 rounded-lg p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<StarIcon className="w-4 h-4 text-amber-500 mt-0.5 flex-shrink-0" />
|
||||
<p className="text-xs text-amber-800">
|
||||
Guest tickets are <strong>free</strong> and are automatically confirmed. They are not counted toward revenue or paid ticket totals.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3 pt-2">
|
||||
<Button type="button" variant="outline" onClick={() => setShowInviteGuestModal(false)} className="flex-1 min-h-[44px]">Cancel</Button>
|
||||
<Button type="submit" isLoading={submitting} className="flex-1 min-h-[44px]">
|
||||
<StarIcon className="w-4 h-4 mr-1.5" />
|
||||
Invite Guest
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Note Modal */}
|
||||
{showNoteModal && selectedTicket && (
|
||||
<div className="fixed inset-0 bg-black/50 z-50 flex items-end md:items-center justify-center p-0 md:p-4">
|
||||
|
||||
@@ -14,9 +14,11 @@ import {
|
||||
FunnelIcon,
|
||||
ChatBubbleLeftIcon,
|
||||
ArrowPathIcon,
|
||||
BanknotesIcon,
|
||||
CheckCircleIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { StatusBadge } from '../_components/StatusBadge';
|
||||
import type { AttendeeStatusFilter, PrimaryAction } from '../_types';
|
||||
import { StatusBadge, PaymentBadge } from '../_components/StatusBadge';
|
||||
import type { AttendeeStatusFilter, AddTicketType, PrimaryAction } from '../_types';
|
||||
|
||||
interface AttendeesTabProps {
|
||||
locale: string;
|
||||
@@ -37,15 +39,15 @@ interface AttendeesTabProps {
|
||||
showAddTicketDropdown: boolean;
|
||||
setShowAddTicketDropdown: (value: boolean) => void;
|
||||
handleExportAttendees: (status: 'confirmed' | 'checked_in' | 'confirmed_pending' | 'all') => void;
|
||||
setShowManualTicketModal: (value: boolean) => void;
|
||||
setShowAddAtDoorModal: (value: boolean) => void;
|
||||
setShowInviteGuestModal: (value: boolean) => void;
|
||||
openAddTicket: (type: AddTicketType) => void;
|
||||
setMobileFilterOpen: (value: boolean) => void;
|
||||
setShowExportSheet: (value: boolean) => void;
|
||||
setShowAddTicketSheet: (value: boolean) => void;
|
||||
getPrimaryAction: (ticket: Ticket) => PrimaryAction | null;
|
||||
handleOpenNoteModal: (ticket: Ticket) => void;
|
||||
handleReactivate: (ticket: Ticket) => void;
|
||||
handleMarkPaid: (ticketId: string) => void;
|
||||
handleCheckin: (ticketId: string) => void;
|
||||
}
|
||||
|
||||
export function AttendeesTab({
|
||||
@@ -67,15 +69,15 @@ export function AttendeesTab({
|
||||
showAddTicketDropdown,
|
||||
setShowAddTicketDropdown,
|
||||
handleExportAttendees,
|
||||
setShowManualTicketModal,
|
||||
setShowAddAtDoorModal,
|
||||
setShowInviteGuestModal,
|
||||
openAddTicket,
|
||||
setMobileFilterOpen,
|
||||
setShowExportSheet,
|
||||
setShowAddTicketSheet,
|
||||
getPrimaryAction,
|
||||
handleOpenNoteModal,
|
||||
handleReactivate,
|
||||
handleMarkPaid,
|
||||
handleCheckin,
|
||||
}: AttendeesTabProps) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
@@ -143,13 +145,13 @@ export function AttendeesTab({
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<DropdownItem onClick={() => { setShowManualTicketModal(true); setShowAddTicketDropdown(false); }}>
|
||||
<EnvelopeIcon className="w-4 h-4 mr-2" /> Manual Ticket
|
||||
<DropdownItem onClick={() => { openAddTicket('paid'); setShowAddTicketDropdown(false); }}>
|
||||
<EnvelopeIcon className="w-4 h-4 mr-2" /> Paid Ticket
|
||||
</DropdownItem>
|
||||
<DropdownItem onClick={() => { setShowAddAtDoorModal(true); setShowAddTicketDropdown(false); }}>
|
||||
<PlusIcon className="w-4 h-4 mr-2" /> Add at Door
|
||||
<DropdownItem onClick={() => { openAddTicket('unpaid'); setShowAddTicketDropdown(false); }}>
|
||||
<BanknotesIcon className="w-4 h-4 mr-2" /> Unpaid Ticket
|
||||
</DropdownItem>
|
||||
<DropdownItem onClick={() => { setShowInviteGuestModal(true); setShowAddTicketDropdown(false); }}>
|
||||
<DropdownItem onClick={() => { openAddTicket('guest'); setShowAddTicketDropdown(false); }}>
|
||||
<StarIcon className="w-4 h-4 mr-2" /> Invite Guest
|
||||
</DropdownItem>
|
||||
</Dropdown>
|
||||
@@ -252,9 +254,7 @@ export function AttendeesTab({
|
||||
<td className="px-4 py-2.5">
|
||||
<div className="flex items-center gap-1 flex-wrap">
|
||||
<StatusBadge status={ticket.status} compact />
|
||||
{!!ticket.isGuest && (
|
||||
<span className="px-1.5 py-0.5 text-[10px] rounded-full bg-amber-100 text-amber-700 font-medium">Guest</span>
|
||||
)}
|
||||
<PaymentBadge paymentStatus={ticket.paymentStatus} compact />
|
||||
</div>
|
||||
{ticket.checkinAt && (
|
||||
<p className="text-[10px] text-gray-400 mt-0.5">
|
||||
@@ -279,6 +279,16 @@ export function AttendeesTab({
|
||||
<ArrowPathIcon className="w-4 h-4 mr-2" /> Reactivate
|
||||
</DropdownItem>
|
||||
)}
|
||||
{ticket.paymentStatus === 'unpaid' && ticket.status === 'checked_in' && (
|
||||
<DropdownItem onClick={() => handleMarkPaid(ticket.id)}>
|
||||
<BanknotesIcon className="w-4 h-4 mr-2" /> Mark as Paid
|
||||
</DropdownItem>
|
||||
)}
|
||||
{ticket.paymentStatus === 'unpaid' && ticket.status === 'confirmed' && (
|
||||
<DropdownItem onClick={() => handleCheckin(ticket.id)}>
|
||||
<CheckCircleIcon className="w-4 h-4 mr-2" /> Check In (unpaid)
|
||||
</DropdownItem>
|
||||
)}
|
||||
<DropdownItem onClick={() => handleOpenNoteModal(ticket)}>
|
||||
<ChatBubbleLeftIcon className="w-4 h-4 mr-2" />
|
||||
{ticket.adminNote ? 'Edit Note' : 'Add Note'}
|
||||
@@ -323,9 +333,7 @@ export function AttendeesTab({
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 flex-shrink-0 flex-wrap justify-end">
|
||||
<StatusBadge status={ticket.status} compact />
|
||||
{!!ticket.isGuest && (
|
||||
<span className="px-1.5 py-0.5 text-[10px] rounded-full bg-amber-100 text-amber-700 font-medium">Guest</span>
|
||||
)}
|
||||
<PaymentBadge paymentStatus={ticket.paymentStatus} compact />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between mt-2 pt-2 border-t border-gray-100">
|
||||
@@ -346,6 +354,16 @@ export function AttendeesTab({
|
||||
<ArrowPathIcon className="w-4 h-4 mr-2" /> Reactivate
|
||||
</DropdownItem>
|
||||
)}
|
||||
{ticket.paymentStatus === 'unpaid' && ticket.status === 'checked_in' && (
|
||||
<DropdownItem onClick={() => handleMarkPaid(ticket.id)}>
|
||||
<BanknotesIcon className="w-4 h-4 mr-2" /> Mark as Paid
|
||||
</DropdownItem>
|
||||
)}
|
||||
{ticket.paymentStatus === 'unpaid' && ticket.status === 'confirmed' && (
|
||||
<DropdownItem onClick={() => handleCheckin(ticket.id)}>
|
||||
<CheckCircleIcon className="w-4 h-4 mr-2" /> Check In (unpaid)
|
||||
</DropdownItem>
|
||||
)}
|
||||
<DropdownItem onClick={() => handleOpenNoteModal(ticket)}>
|
||||
<ChatBubbleLeftIcon className="w-4 h-4 mr-2" />
|
||||
{ticket.adminNote ? 'Edit Note' : 'Add Note'}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Event } from '@/lib/api';
|
||||
import Card from '@/components/ui/Card';
|
||||
import SensitiveValue from '@/components/admin/SensitiveValue';
|
||||
import { CalendarIcon, MapPinIcon, CurrencyDollarIcon, UsersIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
interface OverviewTabProps {
|
||||
@@ -48,8 +49,8 @@ export function OverviewTab({ event, formatDate, fmtTime, formatCurrency, confir
|
||||
<UsersIcon className="w-5 h-5 text-gray-400 mt-0.5 flex-shrink-0" />
|
||||
<div>
|
||||
<p className="font-medium text-sm">Capacity</p>
|
||||
<p className="text-sm text-gray-600">{confirmedCount + checkedInCount} / {event.capacity} spots filled</p>
|
||||
<p className="text-xs text-gray-500">{Math.max(0, event.capacity - confirmedCount - checkedInCount)} spots remaining</p>
|
||||
<p className="text-sm text-gray-600"><SensitiveValue>{confirmedCount + checkedInCount} / {event.capacity}</SensitiveValue> spots filled</p>
|
||||
<p className="text-xs text-gray-500"><SensitiveValue>{Math.max(0, event.capacity - confirmedCount - checkedInCount)}</SensitiveValue> spots remaining</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -13,14 +13,18 @@ export interface PrimaryAction {
|
||||
icon?: ComponentType<{ className?: string }>;
|
||||
}
|
||||
|
||||
export interface AttendeeFormState {
|
||||
// Ticket type in the unified Add Ticket modal:
|
||||
// paid = confirmation + QR emailed, counts toward revenue
|
||||
// unpaid = QR flagged unpaid, balance collected at door, pay link emailed if possible
|
||||
// guest = free comp ticket, auto-confirmed, no revenue
|
||||
export type AddTicketType = 'paid' | 'unpaid' | 'guest';
|
||||
|
||||
export interface AddTicketFormState {
|
||||
type: AddTicketType;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
adminNote: string;
|
||||
}
|
||||
|
||||
export interface AddAtDoorFormState extends AttendeeFormState {
|
||||
autoCheckin: boolean;
|
||||
checkinNow: boolean;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
EnvelopeIcon,
|
||||
PencilIcon,
|
||||
EyeIcon,
|
||||
EyeSlashIcon,
|
||||
UserGroupIcon,
|
||||
CreditCardIcon,
|
||||
ChevronDownIcon,
|
||||
@@ -30,14 +29,14 @@ import {
|
||||
} from '@heroicons/react/24/outline';
|
||||
import toast from 'react-hot-toast';
|
||||
import clsx from 'clsx';
|
||||
import { useStatsPrivacy } from '@/hooks/useStatsPrivacy';
|
||||
import { usePrivacy } from '@/context/PrivacyContext';
|
||||
import type {
|
||||
TabType,
|
||||
AttendeeStatusFilter,
|
||||
TicketStatusFilter,
|
||||
RecipientFilter,
|
||||
AttendeeFormState,
|
||||
AddAtDoorFormState,
|
||||
AddTicketType,
|
||||
AddTicketFormState,
|
||||
PrimaryAction,
|
||||
} from './_types';
|
||||
import { formatCurrency, downloadBlob } from './_utils/format';
|
||||
@@ -49,8 +48,19 @@ import { TicketsTab } from './_tabs/TicketsTab';
|
||||
import { EmailTab } from './_tabs/EmailTab';
|
||||
import { PaymentsTab } from './_tabs/PaymentsTab';
|
||||
import { EventModals } from './_modals/EventModals';
|
||||
import { AddTicketModal } from './_modals/AddTicketModal';
|
||||
import EventFormModal from '../_components/EventFormModal';
|
||||
|
||||
const EMPTY_ADD_TICKET_FORM: AddTicketFormState = {
|
||||
type: 'paid',
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
adminNote: '',
|
||||
checkinNow: false,
|
||||
};
|
||||
|
||||
export default function AdminEventDetailPage() {
|
||||
const params = useParams();
|
||||
const eventId = params.id as string;
|
||||
@@ -69,37 +79,21 @@ export default function AdminEventDetailPage() {
|
||||
// Attendees tab state
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState<AttendeeStatusFilter>('all');
|
||||
const [showAddAtDoorModal, setShowAddAtDoorModal] = useState(false);
|
||||
const [showManualTicketModal, setShowManualTicketModal] = useState(false);
|
||||
const [showStats, , toggleStats] = useStatsPrivacy();
|
||||
const { privacyMode } = usePrivacy();
|
||||
const showStats = !privacyMode;
|
||||
const [showNoteModal, setShowNoteModal] = useState(false);
|
||||
const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);
|
||||
const [noteText, setNoteText] = useState('');
|
||||
const [addAtDoorForm, setAddAtDoorForm] = useState<AddAtDoorFormState>({
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
autoCheckin: true,
|
||||
adminNote: '',
|
||||
});
|
||||
const [manualTicketForm, setManualTicketForm] = useState<AttendeeFormState>({
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
adminNote: '',
|
||||
});
|
||||
const [showInviteGuestModal, setShowInviteGuestModal] = useState(false);
|
||||
const [inviteGuestForm, setInviteGuestForm] = useState<AttendeeFormState>({
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
adminNote: '',
|
||||
});
|
||||
// Unified Add Ticket modal (paid / unpaid / guest via segmented control)
|
||||
const [showAddTicketModal, setShowAddTicketModal] = useState(false);
|
||||
const [addTicketForm, setAddTicketForm] = useState<AddTicketFormState>(EMPTY_ADD_TICKET_FORM);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const openAddTicket = (type: AddTicketType) => {
|
||||
setAddTicketForm({ ...EMPTY_ADD_TICKET_FORM, type });
|
||||
setShowAddTicketModal(true);
|
||||
};
|
||||
|
||||
// Export state — separate desktop (Dropdown portal) vs mobile (BottomSheet)
|
||||
const [showExportDropdown, setShowExportDropdown] = useState(false); // desktop dropdown
|
||||
const [showExportSheet, setShowExportSheet] = useState(false); // mobile bottom sheet
|
||||
@@ -220,74 +214,27 @@ export default function AdminEventDetailPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddAtDoor = async (e: React.FormEvent) => {
|
||||
const handleAddTicket = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!event) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await ticketsApi.adminCreate({
|
||||
const res = await ticketsApi.adminAdd({
|
||||
eventId: event.id,
|
||||
firstName: addAtDoorForm.firstName,
|
||||
lastName: addAtDoorForm.lastName || undefined,
|
||||
email: addAtDoorForm.email,
|
||||
phone: addAtDoorForm.phone,
|
||||
autoCheckin: addAtDoorForm.autoCheckin,
|
||||
adminNote: addAtDoorForm.adminNote || undefined,
|
||||
type: addTicketForm.type,
|
||||
firstName: addTicketForm.firstName,
|
||||
lastName: addTicketForm.lastName || undefined,
|
||||
email: addTicketForm.email || undefined,
|
||||
phone: addTicketForm.phone || undefined,
|
||||
checkinNow: addTicketForm.checkinNow,
|
||||
adminNote: addTicketForm.adminNote || undefined,
|
||||
});
|
||||
toast.success(addAtDoorForm.autoCheckin ? 'Attendee added and checked in' : 'Attendee added');
|
||||
setShowAddAtDoorModal(false);
|
||||
setAddAtDoorForm({ firstName: '', lastName: '', email: '', phone: '', autoCheckin: true, adminNote: '' });
|
||||
toast.success(res.message || 'Ticket created');
|
||||
setShowAddTicketModal(false);
|
||||
setAddTicketForm(EMPTY_ADD_TICKET_FORM);
|
||||
loadEventData();
|
||||
} catch (error: any) {
|
||||
toast.error(error.message || 'Failed to add attendee');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleManualTicket = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!event) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await ticketsApi.manualCreate({
|
||||
eventId: event.id,
|
||||
firstName: manualTicketForm.firstName,
|
||||
lastName: manualTicketForm.lastName || undefined,
|
||||
email: manualTicketForm.email,
|
||||
phone: manualTicketForm.phone || undefined,
|
||||
adminNote: manualTicketForm.adminNote || undefined,
|
||||
});
|
||||
toast.success('Manual ticket created — confirmation email sent');
|
||||
setShowManualTicketModal(false);
|
||||
setManualTicketForm({ firstName: '', lastName: '', email: '', phone: '', adminNote: '' });
|
||||
loadEventData();
|
||||
} catch (error: any) {
|
||||
toast.error(error.message || 'Failed to create manual ticket');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleInviteGuest = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!event) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await ticketsApi.guestCreate({
|
||||
eventId: event.id,
|
||||
firstName: inviteGuestForm.firstName,
|
||||
lastName: inviteGuestForm.lastName || undefined,
|
||||
email: inviteGuestForm.email || undefined,
|
||||
phone: inviteGuestForm.phone || undefined,
|
||||
adminNote: inviteGuestForm.adminNote || undefined,
|
||||
});
|
||||
toast.success('Guest invited successfully');
|
||||
setShowInviteGuestModal(false);
|
||||
setInviteGuestForm({ firstName: '', lastName: '', email: '', phone: '', adminNote: '' });
|
||||
loadEventData();
|
||||
} catch (error: any) {
|
||||
toast.error(error.message || 'Failed to invite guest');
|
||||
toast.error(error.message || 'Failed to add ticket');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
@@ -449,8 +396,11 @@ export default function AdminEventDetailPage() {
|
||||
const checkedInCount = getTicketsByStatus('checked_in').length;
|
||||
const cancelledCount = getTicketsByStatus('cancelled').length;
|
||||
const onHoldCount = getTicketsByStatus('on_hold').length;
|
||||
const paidConfirmedCount = getTicketsByStatus('confirmed').filter(t => !t.isGuest).length;
|
||||
const paidCheckedInCount = getTicketsByStatus('checked_in').filter(t => !t.isGuest).length;
|
||||
// Revenue counts only settled tickets: unpaid (balance due) and comp (guest)
|
||||
// tickets are excluded; legacy rows without paymentStatus fall back to !isGuest
|
||||
const isRevenueTicket = (t: Ticket) => (t.paymentStatus ? t.paymentStatus === 'paid' : !t.isGuest);
|
||||
const paidConfirmedCount = getTicketsByStatus('confirmed').filter(isRevenueTicket).length;
|
||||
const paidCheckedInCount = getTicketsByStatus('checked_in').filter(isRevenueTicket).length;
|
||||
const revenue = (paidConfirmedCount + paidCheckedInCount) * event.price;
|
||||
|
||||
const tabs: { key: TabType; label: string; icon: typeof CalendarIcon; count?: number }[] = [
|
||||
@@ -467,6 +417,10 @@ export default function AdminEventDetailPage() {
|
||||
return { label: 'Mark Paid', onClick: () => handleMarkPaid(ticket.id), variant: 'outline' };
|
||||
}
|
||||
if (ticket.status === 'confirmed') {
|
||||
// Unpaid tickets resolve their balance first; check-in stays available via scanner
|
||||
if (ticket.paymentStatus === 'unpaid') {
|
||||
return { label: 'Mark Paid', onClick: () => handleMarkPaid(ticket.id), variant: 'outline' };
|
||||
}
|
||||
return { label: 'Check In', onClick: () => handleCheckin(ticket.id), variant: 'primary' };
|
||||
}
|
||||
if (ticket.status === 'checked_in') {
|
||||
@@ -490,10 +444,6 @@ export default function AdminEventDetailPage() {
|
||||
</div>
|
||||
{/* Desktop header actions */}
|
||||
<div className="hidden md:flex items-center gap-2 flex-shrink-0">
|
||||
<Button variant="outline" size="sm" onClick={toggleStats} title={showStats ? 'Hide stats' : 'Show stats'}>
|
||||
{showStats ? <EyeSlashIcon className="w-4 h-4 mr-1.5" /> : <EyeIcon className="w-4 h-4 mr-1.5" />}
|
||||
{showStats ? 'Hide Stats' : 'Show Stats'}
|
||||
</Button>
|
||||
<Link href={`/events/${event.slug}`} target="_blank">
|
||||
<Button variant="outline" size="sm">
|
||||
<EyeIcon className="w-4 h-4 mr-1.5" />
|
||||
@@ -522,10 +472,6 @@ export default function AdminEventDetailPage() {
|
||||
<DropdownItem onClick={() => { setShowEditForm(true); setMobileHeaderMenuOpen(false); }}>
|
||||
<PencilIcon className="w-4 h-4 mr-2" /> Edit Event
|
||||
</DropdownItem>
|
||||
<DropdownItem onClick={() => { toggleStats(); setMobileHeaderMenuOpen(false); }}>
|
||||
{showStats ? <EyeSlashIcon className="w-4 h-4 mr-2" /> : <EyeIcon className="w-4 h-4 mr-2" />}
|
||||
{showStats ? 'Hide Stats' : 'Show Stats'}
|
||||
</DropdownItem>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</div>
|
||||
@@ -704,15 +650,15 @@ export default function AdminEventDetailPage() {
|
||||
showAddTicketDropdown={showAddTicketDropdown}
|
||||
setShowAddTicketDropdown={setShowAddTicketDropdown}
|
||||
handleExportAttendees={handleExportAttendees}
|
||||
setShowManualTicketModal={setShowManualTicketModal}
|
||||
setShowAddAtDoorModal={setShowAddAtDoorModal}
|
||||
setShowInviteGuestModal={setShowInviteGuestModal}
|
||||
openAddTicket={openAddTicket}
|
||||
setMobileFilterOpen={setMobileFilterOpen}
|
||||
setShowExportSheet={setShowExportSheet}
|
||||
setShowAddTicketSheet={setShowAddTicketSheet}
|
||||
getPrimaryAction={getPrimaryAction}
|
||||
handleOpenNoteModal={handleOpenNoteModal}
|
||||
handleReactivate={handleReactivate}
|
||||
handleMarkPaid={handleMarkPaid}
|
||||
handleCheckin={handleCheckin}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -777,27 +723,13 @@ export default function AdminEventDetailPage() {
|
||||
setMobileFilterOpen={setMobileFilterOpen}
|
||||
showAddTicketSheet={showAddTicketSheet}
|
||||
setShowAddTicketSheet={setShowAddTicketSheet}
|
||||
openAddTicket={openAddTicket}
|
||||
showExportSheet={showExportSheet}
|
||||
setShowExportSheet={setShowExportSheet}
|
||||
handleExportAttendees={handleExportAttendees}
|
||||
showTicketExportSheet={showTicketExportSheet}
|
||||
setShowTicketExportSheet={setShowTicketExportSheet}
|
||||
handleExportTickets={handleExportTickets}
|
||||
showAddAtDoorModal={showAddAtDoorModal}
|
||||
setShowAddAtDoorModal={setShowAddAtDoorModal}
|
||||
addAtDoorForm={addAtDoorForm}
|
||||
setAddAtDoorForm={setAddAtDoorForm}
|
||||
handleAddAtDoor={handleAddAtDoor}
|
||||
showManualTicketModal={showManualTicketModal}
|
||||
setShowManualTicketModal={setShowManualTicketModal}
|
||||
manualTicketForm={manualTicketForm}
|
||||
setManualTicketForm={setManualTicketForm}
|
||||
handleManualTicket={handleManualTicket}
|
||||
showInviteGuestModal={showInviteGuestModal}
|
||||
setShowInviteGuestModal={setShowInviteGuestModal}
|
||||
inviteGuestForm={inviteGuestForm}
|
||||
setInviteGuestForm={setInviteGuestForm}
|
||||
handleInviteGuest={handleInviteGuest}
|
||||
submitting={submitting}
|
||||
showNoteModal={showNoteModal}
|
||||
setShowNoteModal={setShowNoteModal}
|
||||
@@ -810,6 +742,16 @@ export default function AdminEventDetailPage() {
|
||||
setPreviewHtml={setPreviewHtml}
|
||||
/>
|
||||
|
||||
<AddTicketModal
|
||||
open={showAddTicketModal}
|
||||
onClose={() => setShowAddTicketModal(false)}
|
||||
form={addTicketForm}
|
||||
setForm={setAddTicketForm}
|
||||
onSubmit={handleAddTicket}
|
||||
submitting={submitting}
|
||||
eventPriceLabel={event.price === 0 ? 'Free' : formatCurrency(event.price, event.currency)}
|
||||
/>
|
||||
|
||||
<EventFormModal
|
||||
open={showEditForm}
|
||||
event={event}
|
||||
|
||||
@@ -222,7 +222,14 @@ export default function AdminEventsPage() {
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-600">{formatDate(event.startDatetime)}</td>
|
||||
<td className="px-4 py-3 text-sm">{event.bookedCount || 0} / {event.capacity}</td>
|
||||
<td className="px-4 py-3 text-sm">
|
||||
{(event.bookedCount || 0) + (event.claimedCount || 0)} / {event.capacity}
|
||||
{(event.claimedCount || 0) > 0 && (
|
||||
<span className="block text-[11px] text-yellow-600">
|
||||
{event.claimedCount} pending approval
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{getStatusBadge(event.status)}
|
||||
@@ -332,7 +339,12 @@ export default function AdminEventsPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between mt-2 pt-2 border-t border-gray-100">
|
||||
<p className="text-xs text-gray-500">{event.bookedCount || 0} / {event.capacity} spots</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{(event.bookedCount || 0) + (event.claimedCount || 0)} / {event.capacity} spots
|
||||
{(event.claimedCount || 0) > 0 && (
|
||||
<span className="text-yellow-600"> · {event.claimedCount} pending</span>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
|
||||
<Link href={`/admin/events/${event.id}`}
|
||||
className="p-2 hover:bg-primary-yellow/20 text-primary-dark rounded-btn min-h-[36px] min-w-[36px] flex items-center justify-center">
|
||||
|
||||
@@ -35,11 +35,7 @@ export default function AdminGalleryPage() {
|
||||
const loadMedia = async () => {
|
||||
try {
|
||||
// We need to call the media API - let's add it if it doesn't exist
|
||||
const res = await fetch('/api/media', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${localStorage.getItem('spanglish-token')}`,
|
||||
},
|
||||
});
|
||||
const res = await fetch('/api/media', { credentials: 'same-origin' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setMedia(data.media || []);
|
||||
|
||||
@@ -6,6 +6,7 @@ import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
import { PrivacyProvider, usePrivacy } from '@/context/PrivacyContext';
|
||||
import LanguageToggle from '@/components/LanguageToggle';
|
||||
import Button from '@/components/ui/Button';
|
||||
import {
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
EnvelopeIcon,
|
||||
InboxIcon,
|
||||
PhotoIcon,
|
||||
CameraIcon,
|
||||
Cog6ToothIcon,
|
||||
ArrowLeftOnRectangleIcon,
|
||||
Bars3Icon,
|
||||
@@ -25,6 +27,8 @@ import {
|
||||
QrCodeIcon,
|
||||
DocumentTextIcon,
|
||||
QuestionMarkCircleIcon,
|
||||
EyeIcon,
|
||||
EyeSlashIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import clsx from 'clsx';
|
||||
import { useState } from 'react';
|
||||
@@ -33,11 +37,24 @@ export default function AdminLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<PrivacyProvider>
|
||||
<AdminLayoutInner>{children}</AdminLayoutInner>
|
||||
</PrivacyProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function AdminLayoutInner({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const { t, locale } = useLanguage();
|
||||
const { user, hasAdminAccess, isLoading, logout } = useAuth();
|
||||
const { privacyMode, togglePrivacyMode } = usePrivacy();
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||
|
||||
type Role = 'admin' | 'organizer' | 'staff' | 'marketing';
|
||||
@@ -54,6 +71,7 @@ export default function AdminLayout({
|
||||
{ name: t('admin.nav.contacts'), href: '/admin/contacts', icon: EnvelopeIcon, allowedRoles: ['admin', 'organizer', 'marketing'] },
|
||||
{ name: t('admin.nav.emails'), href: '/admin/emails', icon: InboxIcon, allowedRoles: ['admin', 'organizer'] },
|
||||
{ name: t('admin.nav.gallery'), href: '/admin/gallery', icon: PhotoIcon, allowedRoles: ['admin', 'organizer'] },
|
||||
{ name: t('admin.nav.photos'), href: '/admin/photos', icon: CameraIcon, allowedRoles: ['admin', 'organizer'] },
|
||||
{ name: locale === 'es' ? 'Páginas Legales' : 'Legal Pages', href: '/admin/legal-pages', icon: DocumentTextIcon, allowedRoles: ['admin'] },
|
||||
{ name: 'FAQ', href: '/admin/faq', icon: QuestionMarkCircleIcon, allowedRoles: ['admin'] },
|
||||
{ name: locale === 'es' ? 'Configuración' : 'Settings', href: '/admin/settings', icon: Cog6ToothIcon, allowedRoles: ['admin'] },
|
||||
@@ -218,6 +236,21 @@ export default function AdminLayout({
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-4 ml-auto">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={togglePrivacyMode}
|
||||
title={privacyMode ? t('admin.privacy.show') : t('admin.privacy.hide')}
|
||||
>
|
||||
{privacyMode ? (
|
||||
<EyeIcon className="w-4 h-4 sm:mr-1.5" />
|
||||
) : (
|
||||
<EyeSlashIcon className="w-4 h-4 sm:mr-1.5" />
|
||||
)}
|
||||
<span className="hidden sm:inline">
|
||||
{privacyMode ? t('admin.privacy.show') : t('admin.privacy.hide')}
|
||||
</span>
|
||||
</Button>
|
||||
<LanguageToggle />
|
||||
<Link href="/">
|
||||
<Button variant="outline" size="sm">
|
||||
|
||||
@@ -4,8 +4,10 @@ import { useState, useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
import { usePrivacy } from '@/context/PrivacyContext';
|
||||
import { adminApi, DashboardData } from '@/lib/api';
|
||||
import Card from '@/components/ui/Card';
|
||||
import SensitiveValue from '@/components/admin/SensitiveValue';
|
||||
import {
|
||||
UsersIcon,
|
||||
CalendarIcon,
|
||||
@@ -15,11 +17,12 @@ import {
|
||||
UserGroupIcon,
|
||||
ExclamationTriangleIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { parseDate } from '@/lib/utils';
|
||||
import { parseDate, eventSpotsLeft, isEventSoldOut } from '@/lib/utils';
|
||||
|
||||
export default function AdminDashboardPage() {
|
||||
const { t, locale } = useLanguage();
|
||||
const { user } = useAuth();
|
||||
const { privacyMode } = usePrivacy();
|
||||
const [data, setData] = useState<DashboardData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
@@ -89,6 +92,7 @@ export default function AdminDashboardPage() {
|
||||
</div>
|
||||
|
||||
{/* Stats Grid */}
|
||||
{!privacyMode && (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
||||
{statCards.map((stat) => (
|
||||
<Link key={stat.label} href={stat.href}>
|
||||
@@ -106,22 +110,22 @@ export default function AdminDashboardPage() {
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Alerts */}
|
||||
<Card className="p-6">
|
||||
<h2 className="font-semibold text-lg mb-4">Alerts</h2>
|
||||
<div className="space-y-3">
|
||||
{/* Low capacity warnings */}
|
||||
{/* Low capacity warnings (availableSeats accounts for paid + claimed seats) */}
|
||||
{data?.upcomingEvents
|
||||
.filter(event => {
|
||||
const spotsLeft = Math.max(0, event.capacity - (event.bookedCount || 0));
|
||||
const percentFull = ((event.bookedCount || 0) / event.capacity) * 100;
|
||||
return percentFull >= 80 && spotsLeft > 0;
|
||||
const spotsLeft = eventSpotsLeft(event);
|
||||
return event.capacity > 0 && spotsLeft > 0 && spotsLeft / event.capacity <= 0.2;
|
||||
})
|
||||
.map(event => {
|
||||
const spotsLeft = Math.max(0, event.capacity - (event.bookedCount || 0));
|
||||
const percentFull = Math.round(((event.bookedCount || 0) / event.capacity) * 100);
|
||||
const spotsLeft = eventSpotsLeft(event);
|
||||
const percentFull = Math.round(((event.capacity - spotsLeft) / event.capacity) * 100);
|
||||
return (
|
||||
<Link
|
||||
key={event.id}
|
||||
@@ -132,7 +136,7 @@ export default function AdminDashboardPage() {
|
||||
<ExclamationTriangleIcon className="w-5 h-5 text-orange-600" />
|
||||
<div>
|
||||
<span className="text-sm font-medium">{event.title}</span>
|
||||
<p className="text-xs text-gray-500">Only {spotsLeft} spots left ({percentFull}% full)</p>
|
||||
<p className="text-xs text-gray-500"><SensitiveValue>Only {spotsLeft} spots left ({percentFull}% full)</SensitiveValue></p>
|
||||
</div>
|
||||
</div>
|
||||
<span className="badge badge-warning">Low capacity</span>
|
||||
@@ -142,7 +146,7 @@ export default function AdminDashboardPage() {
|
||||
|
||||
{/* Sold out events */}
|
||||
{data?.upcomingEvents
|
||||
.filter(event => Math.max(0, event.capacity - (event.bookedCount || 0)) === 0)
|
||||
.filter(event => isEventSoldOut(event))
|
||||
.map(event => (
|
||||
<Link
|
||||
key={event.id}
|
||||
@@ -160,16 +164,30 @@ export default function AdminDashboardPage() {
|
||||
</Link>
|
||||
))}
|
||||
|
||||
{data && data.stats.pendingPayments > 0 && (
|
||||
<Link
|
||||
{/* Actionable: customer says they paid, needs verification */}
|
||||
{data && (data.stats.awaitingApprovalPayments ?? 0) > 0 && (
|
||||
<Link
|
||||
href="/admin/payments"
|
||||
className="flex items-center justify-between p-3 bg-yellow-50 rounded-btn hover:bg-yellow-100 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<CurrencyDollarIcon className="w-5 h-5 text-yellow-600" />
|
||||
<span className="text-sm">Pending payments</span>
|
||||
<span className="text-sm">Payments awaiting verification</span>
|
||||
</div>
|
||||
<span className="badge badge-warning">{data.stats.pendingPayments}</span>
|
||||
<span className="badge badge-warning"><SensitiveValue>{data.stats.awaitingApprovalPayments}</SensitiveValue></span>
|
||||
</Link>
|
||||
)}
|
||||
{/* Informational: opened checkouts that never paid — hold no seats */}
|
||||
{data && data.stats.pendingPayments > 0 && (
|
||||
<Link
|
||||
href="/admin/payments"
|
||||
className="flex items-center justify-between p-3 bg-gray-50 rounded-btn hover:bg-gray-100 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<CurrencyDollarIcon className="w-5 h-5 text-gray-400" />
|
||||
<span className="text-sm text-gray-500">Unpaid started bookings</span>
|
||||
</div>
|
||||
<span className="badge badge-info"><SensitiveValue>{data.stats.pendingPayments}</SensitiveValue></span>
|
||||
</Link>
|
||||
)}
|
||||
{data && data.stats.newContacts > 0 && (
|
||||
@@ -186,10 +204,11 @@ export default function AdminDashboardPage() {
|
||||
)}
|
||||
|
||||
{/* No alerts */}
|
||||
{data &&
|
||||
data.stats.pendingPayments === 0 &&
|
||||
data.stats.newContacts === 0 &&
|
||||
!data.upcomingEvents.some(e => ((e.bookedCount || 0) / e.capacity) >= 0.8) && (
|
||||
{data &&
|
||||
data.stats.pendingPayments === 0 &&
|
||||
(data.stats.awaitingApprovalPayments ?? 0) === 0 &&
|
||||
data.stats.newContacts === 0 &&
|
||||
!data.upcomingEvents.some(e => e.capacity > 0 && eventSpotsLeft(e) / e.capacity <= 0.2) && (
|
||||
<p className="text-gray-500 text-sm text-center py-2">No alerts at this time</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -217,9 +236,16 @@ export default function AdminDashboardPage() {
|
||||
<p className="font-medium text-sm">{event.title}</p>
|
||||
<p className="text-xs text-gray-500">{formatDate(event.startDatetime)}</p>
|
||||
</div>
|
||||
<span className="text-sm text-gray-600">
|
||||
{event.bookedCount || 0}/{event.capacity}
|
||||
</span>
|
||||
{!privacyMode && (
|
||||
<span className="text-sm text-gray-600">
|
||||
{(event.bookedCount || 0) + (event.claimedCount || 0)}/{event.capacity}
|
||||
{(event.claimedCount || 0) > 0 && (
|
||||
<span className="text-xs text-yellow-600 block text-right">
|
||||
{event.claimedCount} pending approval
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
@@ -227,6 +253,7 @@ export default function AdminDashboardPage() {
|
||||
</Card>
|
||||
|
||||
{/* Quick Stats */}
|
||||
{!privacyMode && (
|
||||
<Card className="p-6">
|
||||
<h2 className="font-semibold text-lg mb-4">Quick Stats</h2>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
@@ -242,6 +269,7 @@ export default function AdminDashboardPage() {
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { paymentsApi, adminApi, eventsApi, PaymentWithDetails, Event, ExportedPayment, FinancialSummary } from '@/lib/api';
|
||||
import { isManualProvider } from '@/lib/api/payments';
|
||||
import { parseDate, formatRucDisplay } from '@/lib/utils';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
BoltIcon,
|
||||
BanknotesIcon,
|
||||
BuildingLibraryIcon,
|
||||
CalendarDaysIcon,
|
||||
CreditCardIcon,
|
||||
EnvelopeIcon,
|
||||
FunnelIcon,
|
||||
@@ -36,6 +38,9 @@ export default function AdminPaymentsPage() {
|
||||
const { t, locale } = useLanguage();
|
||||
const [payments, setPayments] = useState<PaymentWithDetails[]>([]);
|
||||
const [pendingApprovalPayments, setPendingApprovalPayments] = useState<PaymentWithDetails[]>([]);
|
||||
// Manual-gateway payments still in bare 'pending': the customer may have paid
|
||||
// without clicking "I've paid" — approvable directly from the approval tab.
|
||||
const [unclaimedManualPayments, setUnclaimedManualPayments] = useState<PaymentWithDetails[]>([]);
|
||||
const [events, setEvents] = useState<Event[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState<Tab>('pending_approval');
|
||||
@@ -69,17 +74,19 @@ export default function AdminPaymentsPage() {
|
||||
const loadData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const [pendingRes, allRes, eventsRes] = await Promise.all([
|
||||
const [pendingRes, allRes, unclaimedRes, eventsRes] = await Promise.all([
|
||||
paymentsApi.getPendingApproval(),
|
||||
paymentsApi.getAll({
|
||||
status: statusFilter || undefined,
|
||||
paymentsApi.getAll({
|
||||
status: statusFilter || undefined,
|
||||
provider: providerFilter || undefined,
|
||||
eventIds: eventFilter.length > 0 ? eventFilter : undefined,
|
||||
}),
|
||||
paymentsApi.getAll({ status: 'pending' }),
|
||||
eventsApi.getAll(),
|
||||
]);
|
||||
setPendingApprovalPayments(pendingRes.payments);
|
||||
setPayments(allRes.payments);
|
||||
setUnclaimedManualPayments(unclaimedRes.payments.filter(p => isManualProvider(p.provider)));
|
||||
setEvents(eventsRes.events);
|
||||
} catch (error) {
|
||||
toast.error('Failed to load payments');
|
||||
@@ -88,15 +95,35 @@ export default function AdminPaymentsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// Approve with over-capacity confirmation: the backend rejects an approval
|
||||
// that would overbook the event unless the admin explicitly allows it.
|
||||
const approveWithCapacityConfirm = async (id: string, note?: string, email?: boolean) => {
|
||||
try {
|
||||
await paymentsApi.approve(id, note, email);
|
||||
} catch (error: any) {
|
||||
if (error?.code !== 'EVENT_OVER_CAPACITY') throw error;
|
||||
const seatsLeft = error?.data?.availableSeats ?? 0;
|
||||
const requested = error?.data?.requestedSeats ?? 1;
|
||||
const message = locale === 'es'
|
||||
? `El evento está lleno (quedan ${seatsLeft} lugares, esta reserva necesita ${requested}). ¿Aprobar de todas formas y sobrevender?`
|
||||
: `This event is full (${seatsLeft} seat(s) left, this booking needs ${requested}). Approve anyway and overbook?`;
|
||||
if (!confirm(message)) return false;
|
||||
await paymentsApi.approve(id, note, email, true);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleApprove = async (payment: PaymentWithDetails) => {
|
||||
setProcessing(true);
|
||||
try {
|
||||
await paymentsApi.approve(payment.id, noteText, sendEmail);
|
||||
toast.success(locale === 'es' ? 'Pago aprobado' : 'Payment approved');
|
||||
setSelectedPayment(null);
|
||||
setNoteText('');
|
||||
setSendEmail(true);
|
||||
loadData();
|
||||
const approved = await approveWithCapacityConfirm(payment.id, noteText, sendEmail);
|
||||
if (approved) {
|
||||
toast.success(locale === 'es' ? 'Pago aprobado' : 'Payment approved');
|
||||
setSelectedPayment(null);
|
||||
setNoteText('');
|
||||
setSendEmail(true);
|
||||
loadData();
|
||||
}
|
||||
} catch (error: any) {
|
||||
toast.error(error.message || 'Failed to approve payment');
|
||||
} finally {
|
||||
@@ -140,11 +167,13 @@ export default function AdminPaymentsPage() {
|
||||
|
||||
const handleConfirmPayment = async (id: string) => {
|
||||
try {
|
||||
await paymentsApi.approve(id);
|
||||
toast.success('Payment confirmed');
|
||||
loadData();
|
||||
} catch (error) {
|
||||
toast.error('Failed to confirm payment');
|
||||
const approved = await approveWithCapacityConfirm(id);
|
||||
if (approved) {
|
||||
toast.success('Payment confirmed');
|
||||
loadData();
|
||||
}
|
||||
} catch (error: any) {
|
||||
toast.error(error.message || 'Failed to confirm payment');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -298,6 +327,33 @@ export default function AdminPaymentsPage() {
|
||||
return labels[provider] || provider;
|
||||
};
|
||||
|
||||
// Manual gateways need admin verification; automatic ones confirm themselves.
|
||||
const getProviderKindBadge = (provider: string) => (
|
||||
isManualProvider(provider) ? (
|
||||
<span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-orange-50 text-orange-600">
|
||||
{locale === 'es' ? 'Manual' : 'Manual'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-blue-50 text-blue-600">
|
||||
{locale === 'es' ? 'Automático' : 'Auto'}
|
||||
</span>
|
||||
)
|
||||
);
|
||||
|
||||
// Age of a claim/booking, e.g. "3h" / "2d"; used to surface rotting approvals.
|
||||
const getAgeInfo = (dateStr?: string | null) => {
|
||||
if (!dateStr) return null;
|
||||
const ms = Date.now() - parseDate(dateStr).getTime();
|
||||
if (ms < 0) return null;
|
||||
const hours = Math.floor(ms / (60 * 60 * 1000));
|
||||
const label = hours < 1
|
||||
? (locale === 'es' ? 'hace <1 h' : '<1h ago')
|
||||
: hours < 48
|
||||
? (locale === 'es' ? `hace ${hours} h` : `${hours}h ago`)
|
||||
: (locale === 'es' ? `hace ${Math.floor(hours / 24)} días` : `${Math.floor(hours / 24)}d ago`);
|
||||
return { hours, label, stale: hours >= 48 };
|
||||
};
|
||||
|
||||
// Helper to get booking info for a payment (ticket count and total)
|
||||
const getBookingInfo = (payment: PaymentWithDetails) => {
|
||||
if (!payment.ticket?.bookingId) {
|
||||
@@ -331,6 +387,22 @@ export default function AdminPaymentsPage() {
|
||||
});
|
||||
})();
|
||||
|
||||
// Manual payments never claimed by the customer — they may have paid and
|
||||
// forgotten to press "I've paid", so they stay directly approvable here.
|
||||
// Hidden once the event has ended (same rule as pending approvals above).
|
||||
const visibleUnclaimedManualPayments = (() => {
|
||||
const now = new Date();
|
||||
return unclaimedManualPayments.filter((payment) => {
|
||||
const eventId = payment.event?.id;
|
||||
const fullEvent = eventId ? events.find((e) => e.id === eventId) : undefined;
|
||||
const endIso = fullEvent?.endDatetime
|
||||
|| fullEvent?.startDatetime
|
||||
|| payment.event?.startDatetime;
|
||||
if (!endIso) return true;
|
||||
return parseDate(endIso).getTime() >= now.getTime();
|
||||
});
|
||||
})();
|
||||
|
||||
// Get booking info for pending approval payments
|
||||
const getPendingBookingInfo = (payment: PaymentWithDetails) => {
|
||||
if (!payment.ticket?.bookingId) {
|
||||
@@ -348,9 +420,15 @@ export default function AdminPaymentsPage() {
|
||||
};
|
||||
};
|
||||
|
||||
// Calculate totals (sum all individual payment amounts)
|
||||
const totalPending = payments
|
||||
.filter(p => p.status === 'pending' || p.status === 'pending_approval')
|
||||
// Calculate totals (sum all individual payment amounts).
|
||||
// Claimed ('pending_approval') money is probably already in the account and
|
||||
// just needs verification; bare 'pending' money may never arrive — keep the
|
||||
// two apart so the totals don't overstate what's owed.
|
||||
const totalAwaitingVerification = payments
|
||||
.filter(p => p.status === 'pending_approval')
|
||||
.reduce((sum, p) => sum + Number(p.amount), 0);
|
||||
const totalUnclaimed = payments
|
||||
.filter(p => p.status === 'pending')
|
||||
.reduce((sum, p) => sum + Number(p.amount), 0);
|
||||
const totalPaid = payments
|
||||
.filter(p => p.status === 'paid')
|
||||
@@ -370,9 +448,6 @@ export default function AdminPaymentsPage() {
|
||||
return count;
|
||||
};
|
||||
|
||||
const pendingBookingsCount = getUniqueBookingsCount(
|
||||
payments.filter(p => p.status === 'pending' || p.status === 'pending_approval')
|
||||
);
|
||||
const paidBookingsCount = getUniqueBookingsCount(
|
||||
payments.filter(p => p.status === 'paid')
|
||||
);
|
||||
@@ -460,12 +535,29 @@ export default function AdminPaymentsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedPayment.userMarkedPaidAt && (
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600">
|
||||
<ClockIcon className="w-4 h-4" />
|
||||
{locale === 'es' ? 'Usuario marcó como pagado:' : 'User marked as paid:'} {formatDate(selectedPayment.userMarkedPaidAt)}
|
||||
</div>
|
||||
)}
|
||||
{/* Always shown — for payments the customer never confirmed, this
|
||||
is the only timestamp there is. */}
|
||||
{(() => {
|
||||
const age = getAgeInfo(selectedPayment.createdAt);
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600">
|
||||
<CalendarDaysIcon className="w-4 h-4" />
|
||||
{locale === 'es' ? 'Reserva realizada:' : 'Booking made:'} {formatDate(selectedPayment.createdAt)}
|
||||
{age && <span className="text-gray-400">({age.label})</span>}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{selectedPayment.userMarkedPaidAt && (() => {
|
||||
const age = getAgeInfo(selectedPayment.userMarkedPaidAt);
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600">
|
||||
<ClockIcon className="w-4 h-4" />
|
||||
{locale === 'es' ? 'Usuario marcó como pagado:' : 'User marked as paid:'} {formatDate(selectedPayment.userMarkedPaidAt)}
|
||||
{age && <span className="text-gray-400">({age.label})</span>}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{selectedPayment.reminderSentAt && (
|
||||
<div className="flex items-center gap-2 text-sm text-amber-600">
|
||||
@@ -721,9 +813,12 @@ export default function AdminPaymentsPage() {
|
||||
<ClockIcon className="w-5 h-5 text-gray-600" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">{locale === 'es' ? 'Total Pendiente' : 'Total Pending'}</p>
|
||||
<p className="text-xl font-bold">{formatCurrency(totalPending, 'PYG')}</p>
|
||||
<p className="text-xs text-gray-400">{pendingBookingsCount} {locale === 'es' ? 'reservas' : 'bookings'}</p>
|
||||
<p className="text-sm text-gray-500">{locale === 'es' ? 'Por Verificar' : 'Awaiting Verification'}</p>
|
||||
<p className="text-xl font-bold text-yellow-600">{formatCurrency(totalAwaitingVerification, 'PYG')}</p>
|
||||
<p className="text-xs text-gray-400">
|
||||
{locale === 'es' ? 'Sin pagar (sin reclamar): ' : 'Unpaid (unclaimed): '}
|
||||
{formatCurrency(totalUnclaimed, 'PYG')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
@@ -817,13 +912,18 @@ export default function AdminPaymentsPage() {
|
||||
<span className="flex items-center gap-1">
|
||||
{getProviderIcon(payment.provider)}
|
||||
{getProviderLabel(payment.provider)}
|
||||
{getProviderKindBadge(payment.provider)}
|
||||
</span>
|
||||
{payment.userMarkedPaidAt && (
|
||||
<span className="flex items-center gap-1">
|
||||
<ClockIcon className="w-3 h-3" />
|
||||
{locale === 'es' ? 'Marcado:' : 'Marked:'} {formatDate(payment.userMarkedPaidAt)}
|
||||
</span>
|
||||
)}
|
||||
{payment.userMarkedPaidAt && (() => {
|
||||
const age = getAgeInfo(payment.userMarkedPaidAt);
|
||||
return (
|
||||
<span className={clsx('flex items-center gap-1', age?.stale && 'text-amber-600 font-medium')}>
|
||||
<ClockIcon className="w-3 h-3" />
|
||||
{locale === 'es' ? 'Marcado:' : 'Marked:'} {formatDate(payment.userMarkedPaidAt)}
|
||||
{age && <span>({age.label})</span>}
|
||||
</span>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
{payment.payerName && (
|
||||
<p className="text-xs text-amber-600 mt-1 font-medium">
|
||||
@@ -841,6 +941,55 @@ export default function AdminPaymentsPage() {
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Manual payments the customer never confirmed — they may have paid
|
||||
(bank transfer / TPago received) without pressing "I've paid".
|
||||
Approving one claims a seat, so it goes through the same
|
||||
over-capacity confirmation as any approval. */}
|
||||
{visibleUnclaimedManualPayments.length > 0 && (
|
||||
<details className="mt-8">
|
||||
<summary className="cursor-pointer text-sm font-medium text-gray-600 select-none">
|
||||
{locale === 'es'
|
||||
? `Pagos manuales sin confirmar por el cliente (${visibleUnclaimedManualPayments.length})`
|
||||
: `Manual payments not yet confirmed by customer (${visibleUnclaimedManualPayments.length})`}
|
||||
<span className="block text-xs font-normal text-gray-400 mt-0.5">
|
||||
{locale === 'es'
|
||||
? 'Puede que hayan pagado sin presionar "Ya pagué". No reservan lugar hasta ser aprobados.'
|
||||
: 'They may have paid without pressing "I\'ve paid". These hold no seat until approved.'}
|
||||
</span>
|
||||
</summary>
|
||||
<div className="space-y-3 mt-4">
|
||||
{visibleUnclaimedManualPayments.map((payment) => {
|
||||
const age = getAgeInfo(payment.createdAt);
|
||||
return (
|
||||
<Card key={payment.id} className="p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center flex-shrink-0">
|
||||
{getProviderIcon(payment.provider)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium truncate">
|
||||
{payment.ticket?.attendeeFirstName} {payment.ticket?.attendeeLastName}
|
||||
<span className="text-gray-400 font-normal"> · {formatCurrency(payment.amount, payment.currency)}</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-400 truncate">
|
||||
{payment.event?.title}
|
||||
{' · '}{getProviderLabel(payment.provider)}
|
||||
{age && <span> · {age.label}</span>}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={() => setSelectedPayment(payment)} size="sm" variant="outline" className="flex-shrink-0 min-h-[40px]">
|
||||
{locale === 'es' ? 'Revisar' : 'Review'}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1004,6 +1153,7 @@ export default function AdminPaymentsPage() {
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-1.5 text-xs text-gray-600">
|
||||
{getProviderIcon(payment.provider)} {getProviderLabel(payment.provider)}
|
||||
{getProviderKindBadge(payment.provider)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">{getStatusBadge(payment.status)}</td>
|
||||
@@ -1063,7 +1213,7 @@ export default function AdminPaymentsPage() {
|
||||
<div className="mt-2 flex items-center gap-2 text-xs text-gray-500">
|
||||
<span className="font-medium text-gray-700">{formatCurrency(bookingInfo.bookingTotal, payment.currency)}</span>
|
||||
<span className="text-gray-300">|</span>
|
||||
<span className="flex items-center gap-1">{getProviderIcon(payment.provider)} {getProviderLabel(payment.provider)}</span>
|
||||
<span className="flex items-center gap-1">{getProviderIcon(payment.provider)} {getProviderLabel(payment.provider)} {getProviderKindBadge(payment.provider)}</span>
|
||||
{bookingInfo.ticketCount > 1 && (
|
||||
<><span className="text-gray-300">|</span><span className="text-purple-600">{bookingInfo.ticketCount} tickets</span></>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
'use client';
|
||||
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import type { GalleryVisibility } from '@/lib/api';
|
||||
import {
|
||||
GlobeAltIcon,
|
||||
LockClosedIcon,
|
||||
LinkIcon,
|
||||
TicketIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
|
||||
const visibilityMeta: Record<
|
||||
GalleryVisibility,
|
||||
{ icon: typeof GlobeAltIcon; className: string; en: string; es: string }
|
||||
> = {
|
||||
public: { icon: GlobeAltIcon, className: 'bg-green-100 text-green-700', en: 'Public', es: 'Pública' },
|
||||
private: { icon: LockClosedIcon, className: 'bg-gray-200 text-gray-700', en: 'Private', es: 'Privada' },
|
||||
link: { icon: LinkIcon, className: 'bg-blue-100 text-blue-700', en: 'Link only', es: 'Solo enlace' },
|
||||
ticket: { icon: TicketIcon, className: 'bg-yellow-100 text-yellow-800', en: 'Ticket holders', es: 'Con entrada' },
|
||||
};
|
||||
|
||||
export default function VisibilityBadge({ visibility }: { visibility: GalleryVisibility }) {
|
||||
const { locale } = useLanguage();
|
||||
const meta = visibilityMeta[visibility] || visibilityMeta.private;
|
||||
const Icon = meta.icon;
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1 text-xs px-2 py-1 rounded ${meta.className}`}>
|
||||
<Icon className="w-3.5 h-3.5" />
|
||||
{locale === 'es' ? meta.es : meta.en}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,618 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { photosApi, eventsApi, PhotoGallery, Photo, Event, GalleryVisibility } from '@/lib/api';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import { Skeleton, ImageGridSkeleton } from '@/components/ui/Skeleton';
|
||||
import Lightbox from '@/components/Lightbox';
|
||||
import VisibilityBadge from '../VisibilityBadge';
|
||||
import {
|
||||
ArrowLeftIcon,
|
||||
ArrowUpTrayIcon,
|
||||
ArrowPathIcon,
|
||||
CheckIcon,
|
||||
CheckCircleIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronUpIcon,
|
||||
ExclamationCircleIcon,
|
||||
ExclamationTriangleIcon,
|
||||
LinkIcon,
|
||||
PhotoIcon,
|
||||
StarIcon,
|
||||
TrashIcon,
|
||||
XMarkIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { StarIcon as StarIconSolid } from '@heroicons/react/24/solid';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
interface UploadItem {
|
||||
key: string;
|
||||
name: string;
|
||||
sizeBytes: number;
|
||||
progress: number; // 0..1 while uploading
|
||||
status: 'queued' | 'uploading' | 'processing' | 'error';
|
||||
error?: string;
|
||||
photoId?: string;
|
||||
}
|
||||
|
||||
function formatBytes(n: number) {
|
||||
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MB`;
|
||||
if (n >= 1 << 10) return `${Math.round(n / (1 << 10))} KB`;
|
||||
return `${n} B`;
|
||||
}
|
||||
|
||||
export default function AdminGalleryDetailPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const { locale } = useLanguage();
|
||||
const es = locale === 'es';
|
||||
|
||||
const [gallery, setGallery] = useState<PhotoGallery | null>(null);
|
||||
const [photos, setPhotos] = useState<Photo[]>([]);
|
||||
const [events, setEvents] = useState<Event[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [dragId, setDragId] = useState<string | null>(null);
|
||||
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Uploader panel state (Google Drive style: one row per file).
|
||||
const [uploads, setUploads] = useState<UploadItem[]>([]);
|
||||
const [panelCollapsed, setPanelCollapsed] = useState(false);
|
||||
const uploadQueue = useRef<{ key: string; file: File }[]>([]);
|
||||
const pumpRunning = useRef(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const [detail, ev] = await Promise.all([photosApi.getGallery(id), eventsApi.getAll()]);
|
||||
setGallery(detail.gallery);
|
||||
setPhotos(detail.photos);
|
||||
setEvents(ev.events);
|
||||
} catch {
|
||||
toast.error(es ? 'No se pudo cargar la galería' : 'Failed to load gallery');
|
||||
router.push('/admin/photos');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
// Poll while any photo is still processing so thumbnails (and the
|
||||
// uploader panel rows) update as the worker finishes them.
|
||||
const processingCount = photos.filter((p) => p.status === 'queued' || p.status === 'processing').length;
|
||||
useEffect(() => {
|
||||
if (processingCount === 0) return;
|
||||
const timer = setInterval(async () => {
|
||||
try {
|
||||
const detail = await photosApi.getGallery(id);
|
||||
setGallery(detail.gallery);
|
||||
setPhotos(detail.photos);
|
||||
} catch {
|
||||
/* transient; next tick retries */
|
||||
}
|
||||
}, 3000);
|
||||
return () => clearInterval(timer);
|
||||
}, [processingCount, id]);
|
||||
|
||||
const patchUpload = (key: string, patch: Partial<UploadItem>) => {
|
||||
setUploads((prev) => prev.map((u) => (u.key === key ? { ...u, ...patch } : u)));
|
||||
};
|
||||
|
||||
// Sequential upload pump: one file at a time, byte progress per file.
|
||||
const pump = useCallback(async () => {
|
||||
if (pumpRunning.current) return;
|
||||
pumpRunning.current = true;
|
||||
while (uploadQueue.current.length > 0) {
|
||||
const { key, file } = uploadQueue.current.shift()!;
|
||||
patchUpload(key, { status: 'uploading', progress: 0 });
|
||||
try {
|
||||
const { photos: added } = await photosApi.uploadPhotoWithProgress(id, file, (fraction) =>
|
||||
patchUpload(key, { progress: fraction })
|
||||
);
|
||||
setPhotos((prev) => [...prev, ...added]);
|
||||
patchUpload(key, { status: 'processing', progress: 1, photoId: added[0]?.id });
|
||||
} catch (err) {
|
||||
patchUpload(key, {
|
||||
status: 'error',
|
||||
error: err instanceof Error ? err.message : 'Upload failed',
|
||||
});
|
||||
}
|
||||
}
|
||||
pumpRunning.current = false;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id]);
|
||||
|
||||
const handleUpload = (files: FileList | File[]) => {
|
||||
const list = Array.from(files);
|
||||
if (list.length === 0) return;
|
||||
const items: UploadItem[] = list.map((file) => ({
|
||||
key: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
||||
name: file.name,
|
||||
sizeBytes: file.size,
|
||||
progress: 0,
|
||||
status: 'queued',
|
||||
}));
|
||||
uploadQueue.current.push(...items.map((item, i) => ({ key: item.key, file: list[i] })));
|
||||
setUploads((prev) => [...prev, ...items]);
|
||||
setPanelCollapsed(false);
|
||||
pump();
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
};
|
||||
|
||||
// A row is "done" once its photo finished processing; the panel derives
|
||||
// this from the photos list instead of tracking it separately.
|
||||
const displayStatus = (u: UploadItem): { state: string; error?: string } => {
|
||||
if (u.status === 'processing' && u.photoId) {
|
||||
const photo = photos.find((p) => p.id === u.photoId);
|
||||
if (photo?.status === 'ready') return { state: 'done' };
|
||||
if (photo?.status === 'failed') return { state: 'error', error: photo.lastError || 'Processing failed' };
|
||||
}
|
||||
return { state: u.status, error: u.error };
|
||||
};
|
||||
|
||||
const activeUploads = uploads.filter((u) => {
|
||||
const s = displayStatus(u).state;
|
||||
return s === 'queued' || s === 'uploading' || s === 'processing';
|
||||
}).length;
|
||||
|
||||
const saveField = async (patch: Parameters<typeof photosApi.updateGallery>[1], okMsg?: string) => {
|
||||
try {
|
||||
const { gallery: updated } = await photosApi.updateGallery(id, patch);
|
||||
setGallery(updated);
|
||||
if (okMsg) toast.success(okMsg);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Update failed');
|
||||
}
|
||||
};
|
||||
|
||||
const copyShareLink = async () => {
|
||||
if (!gallery?.shareUrl) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(gallery.shareUrl);
|
||||
setCopied(true);
|
||||
toast.success(es ? 'Enlace copiado' : 'Share link copied');
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch {
|
||||
toast.error(es ? 'No se pudo copiar' : 'Failed to copy');
|
||||
}
|
||||
};
|
||||
|
||||
const rotateToken = async () => {
|
||||
if (!confirm(es ? '¿Invalidar el enlace actual y generar uno nuevo?' : 'Invalidate the current link and generate a new one?'))
|
||||
return;
|
||||
try {
|
||||
const { gallery: updated } = await photosApi.rotateShareToken(id);
|
||||
setGallery(updated);
|
||||
toast.success(es ? 'Nuevo enlace generado' : 'New share link generated');
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed');
|
||||
}
|
||||
};
|
||||
|
||||
const deletePhoto = async (photoId: string): Promise<boolean> => {
|
||||
if (!confirm(es ? '¿Eliminar esta foto?' : 'Delete this photo?')) return false;
|
||||
try {
|
||||
await photosApi.deletePhoto(photoId);
|
||||
setPhotos((prev) => prev.filter((p) => p.id !== photoId));
|
||||
toast.success(es ? 'Foto eliminada' : 'Photo deleted');
|
||||
return true;
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to delete');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const retryPhoto = async (photoId: string) => {
|
||||
try {
|
||||
const { photo } = await photosApi.retryPhoto(photoId);
|
||||
setPhotos((prev) => prev.map((p) => (p.id === photoId ? photo : p)));
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to retry');
|
||||
}
|
||||
};
|
||||
|
||||
const deleteGallery = async () => {
|
||||
if (!confirm(es ? '¿Eliminar toda la galería y sus fotos?' : 'Delete the whole gallery and its photos?')) return;
|
||||
try {
|
||||
await photosApi.deleteGallery(id);
|
||||
toast.success(es ? 'Galería eliminada' : 'Gallery deleted');
|
||||
router.push('/admin/photos');
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to delete');
|
||||
}
|
||||
};
|
||||
|
||||
// HTML5 drag-and-drop reorder; persisted on drop.
|
||||
const onDropReorder = async (targetId: string) => {
|
||||
if (!dragId || dragId === targetId) return;
|
||||
const ids = photos.map((p) => p.id);
|
||||
const from = ids.indexOf(dragId);
|
||||
const to = ids.indexOf(targetId);
|
||||
if (from < 0 || to < 0) return;
|
||||
ids.splice(to, 0, ids.splice(from, 1)[0]);
|
||||
const reordered = ids
|
||||
.map((pid) => photos.find((p) => p.id === pid))
|
||||
.filter((p): p is Photo => !!p);
|
||||
setPhotos(reordered);
|
||||
setDragId(null);
|
||||
try {
|
||||
await photosApi.reorderPhotos(id, ids);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to save order');
|
||||
load();
|
||||
}
|
||||
};
|
||||
|
||||
if (loading || !gallery) {
|
||||
return (
|
||||
<div>
|
||||
<Skeleton className="h-8 w-64 mb-6" />
|
||||
<ImageGridSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const readyPhotos = photos.filter((p) => p.status === 'ready' && p.urls.thumb);
|
||||
const lightboxItems = readyPhotos.map((p) => ({
|
||||
id: p.id,
|
||||
previewUrl: p.urls.preview || p.urls.original,
|
||||
downloadUrl: p.urls.original,
|
||||
filename: p.originalFilename,
|
||||
thumbUrl: p.urls.thumb,
|
||||
}));
|
||||
const openLightboxFor = (photoId: string) => {
|
||||
const idx = readyPhotos.findIndex((p) => p.id === photoId);
|
||||
if (idx >= 0) setLightboxIndex(idx);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
onDragOver={(e) => {
|
||||
if (e.dataTransfer.types.includes('Files')) e.preventDefault();
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
if (e.dataTransfer.files.length > 0) {
|
||||
e.preventDefault();
|
||||
handleUpload(e.dataTransfer.files);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 mb-6">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<Link href="/admin/photos" className="text-gray-400 hover:text-gray-600">
|
||||
<ArrowLeftIcon className="w-6 h-6" />
|
||||
</Link>
|
||||
<h1 className="text-2xl font-bold text-primary-dark truncate">
|
||||
{es && gallery.titleEs ? gallery.titleEs : gallery.title}
|
||||
</h1>
|
||||
<VisibilityBadge visibility={gallery.visibility} />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button onClick={() => fileInputRef.current?.click()}>
|
||||
<ArrowUpTrayIcon className="w-5 h-5 mr-2" />
|
||||
{es ? 'Subir fotos' : 'Upload photos'}
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/gif,image/webp,image/heic,.heic"
|
||||
multiple
|
||||
onChange={(e) => e.target.files && handleUpload(e.target.files)}
|
||||
className="hidden"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Settings */}
|
||||
<Card className="p-4 mb-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">{es ? 'Visibilidad' : 'Visibility'}</label>
|
||||
<select
|
||||
value={gallery.visibility}
|
||||
onChange={(e) =>
|
||||
saveField(
|
||||
{ visibility: e.target.value as GalleryVisibility },
|
||||
es ? 'Visibilidad actualizada' : 'Visibility updated'
|
||||
)
|
||||
}
|
||||
className="w-full px-4 py-2 rounded-btn border border-secondary-light-gray"
|
||||
>
|
||||
<option value="private">{es ? 'Privada (solo admins)' : 'Private (admins only)'}</option>
|
||||
<option value="public">{es ? 'Pública (listada)' : 'Public (listed)'}</option>
|
||||
<option value="link">{es ? 'Solo con enlace' : 'Link only'}</option>
|
||||
<option value="ticket">{es ? 'Con entrada del evento' : 'Ticket holders of the event'}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">{es ? 'Evento vinculado' : 'Linked event'}</label>
|
||||
<select
|
||||
value={gallery.eventId || ''}
|
||||
onChange={(e) =>
|
||||
saveField({ eventId: e.target.value }, es ? 'Evento actualizado' : 'Event updated')
|
||||
}
|
||||
className="w-full px-4 py-2 rounded-btn border border-secondary-light-gray"
|
||||
>
|
||||
<option value="">{es ? 'Ninguno' : 'None'}</option>
|
||||
{events.map((ev) => (
|
||||
<option key={ev.id} value={ev.id}>
|
||||
{ev.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{gallery.visibility === 'ticket' && !gallery.eventId && (
|
||||
<p className="text-xs text-red-600 mt-1">
|
||||
{es
|
||||
? 'El modo "con entrada" necesita un evento vinculado'
|
||||
: 'Ticket mode needs a linked event'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">{es ? 'Enlace para compartir' : 'Share link'}</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={gallery.shareUrl || ''}
|
||||
className="flex-1 min-w-0 px-3 py-2 text-sm border rounded-btn bg-gray-50"
|
||||
/>
|
||||
<Button size="sm" onClick={copyShareLink} title={es ? 'Copiar' : 'Copy'}>
|
||||
{copied ? <CheckIcon className="w-4 h-4" /> : <LinkIcon className="w-4 h-4" />}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={rotateToken} title={es ? 'Regenerar' : 'Regenerate'}>
|
||||
<ArrowPathIcon className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{gallery.event && (
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
{es
|
||||
? 'Publicada en la página del evento: '
|
||||
: 'Published on the event page: '}
|
||||
<span className="font-mono">/events/{gallery.event.slug}/gallery</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{processingCount > 0 && (
|
||||
<p className="text-sm text-gray-600 mb-4">
|
||||
{es
|
||||
? `Procesando ${processingCount} foto(s)…`
|
||||
: `Processing ${processingCount} photo(s)…`}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Photo grid */}
|
||||
{photos.length === 0 ? (
|
||||
<Card className="p-12 text-center">
|
||||
<ArrowUpTrayIcon className="w-16 h-16 mx-auto text-gray-300 mb-4" />
|
||||
<p className="text-gray-500">
|
||||
{es
|
||||
? 'Arrastra fotos aquí o usa el botón de subir'
|
||||
: 'Drag photos here or use the upload button'}
|
||||
</p>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
|
||||
{photos.map((photo) => (
|
||||
<Card
|
||||
key={photo.id}
|
||||
draggable
|
||||
onDragStart={() => setDragId(photo.id)}
|
||||
onDragOver={(e) => {
|
||||
if (dragId) e.preventDefault();
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
if (dragId) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onDropReorder(photo.id);
|
||||
}
|
||||
}}
|
||||
className={`group relative overflow-hidden aspect-square cursor-grab ${
|
||||
dragId === photo.id ? 'opacity-50' : ''
|
||||
}`}
|
||||
>
|
||||
{photo.status === 'ready' && photo.urls.thumb ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={photo.urls.thumb}
|
||||
alt=""
|
||||
className="w-full h-full object-cover cursor-pointer"
|
||||
draggable={false}
|
||||
onClick={() => openLightboxFor(photo.id)}
|
||||
/>
|
||||
) : photo.status === 'failed' ? (
|
||||
<div className="w-full h-full flex flex-col items-center justify-center bg-red-50 text-red-600 p-2 text-center">
|
||||
<ExclamationTriangleIcon className="w-8 h-8 mb-1" />
|
||||
<span className="text-xs line-clamp-3">{photo.lastError || 'Failed'}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center bg-gray-100">
|
||||
<div className="animate-spin w-6 h-6 border-2 border-primary-yellow border-t-transparent rounded-full" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{gallery.coverPhotoId === photo.id && (
|
||||
<StarIconSolid className="absolute top-2 left-2 w-5 h-5 text-primary-yellow drop-shadow" />
|
||||
)}
|
||||
|
||||
<div className="absolute inset-x-0 bottom-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 py-1.5">
|
||||
{photo.status === 'ready' && (
|
||||
<button
|
||||
onClick={() =>
|
||||
saveField({ coverPhotoId: photo.id }, es ? 'Portada actualizada' : 'Cover updated')
|
||||
}
|
||||
className="p-1.5 text-white hover:text-primary-yellow"
|
||||
title={es ? 'Usar como portada' : 'Set as cover'}
|
||||
>
|
||||
<StarIcon className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
{photo.status === 'failed' && (
|
||||
<button
|
||||
onClick={() => retryPhoto(photo.id)}
|
||||
className="p-1.5 text-white hover:text-primary-yellow"
|
||||
title={es ? 'Reintentar' : 'Retry'}
|
||||
>
|
||||
<ArrowPathIcon className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => deletePhoto(photo.id)}
|
||||
className="p-1.5 text-white hover:text-red-400"
|
||||
title={es ? 'Eliminar' : 'Delete'}
|
||||
>
|
||||
<TrashIcon className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Danger zone */}
|
||||
<div className="mt-10 pt-6 border-t border-secondary-light-gray flex justify-end">
|
||||
<Button variant="danger" onClick={deleteGallery}>
|
||||
<TrashIcon className="w-5 h-5 mr-2" />
|
||||
{es ? 'Eliminar galería' : 'Delete gallery'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Lightbox with admin actions */}
|
||||
{lightboxIndex !== null && lightboxItems.length > 0 && (
|
||||
<Lightbox
|
||||
items={lightboxItems}
|
||||
index={Math.min(lightboxIndex, lightboxItems.length - 1)}
|
||||
onClose={() => setLightboxIndex(null)}
|
||||
onNavigate={setLightboxIndex}
|
||||
renderActions={(item) => (
|
||||
<>
|
||||
<button
|
||||
onClick={() =>
|
||||
saveField({ coverPhotoId: item.id }, es ? 'Portada actualizada' : 'Cover updated')
|
||||
}
|
||||
className="text-white hover:text-primary-yellow"
|
||||
title={es ? 'Usar como portada' : 'Set as cover'}
|
||||
>
|
||||
{gallery.coverPhotoId === item.id ? (
|
||||
<StarIconSolid className="w-7 h-7 text-primary-yellow" />
|
||||
) : (
|
||||
<StarIcon className="w-7 h-7" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const before = readyPhotos.length;
|
||||
const deleted = await deletePhoto(item.id);
|
||||
if (!deleted) return;
|
||||
if (before <= 1) setLightboxIndex(null);
|
||||
else setLightboxIndex((i) => (i === null ? null : Math.max(0, Math.min(i, before - 2))));
|
||||
}}
|
||||
className="text-white hover:text-red-400"
|
||||
title={es ? 'Eliminar' : 'Delete'}
|
||||
>
|
||||
<TrashIcon className="w-7 h-7" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Uploader panel (Google Drive style) */}
|
||||
{uploads.length > 0 && (
|
||||
<div className="fixed bottom-4 right-4 z-40 w-96 max-w-[calc(100vw-2rem)]">
|
||||
<div className="bg-white rounded-card shadow-card-hover border border-secondary-light-gray overflow-hidden">
|
||||
<div className="flex items-center justify-between px-4 py-3 bg-primary-dark text-white">
|
||||
<p className="text-sm font-medium">
|
||||
{activeUploads > 0
|
||||
? es
|
||||
? `Subiendo ${uploads.length - activeUploads}/${uploads.length}…`
|
||||
: `Uploading ${uploads.length - activeUploads}/${uploads.length}…`
|
||||
: es
|
||||
? `${uploads.length} subida(s) completada(s)`
|
||||
: `${uploads.length} upload(s) complete`}
|
||||
</p>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => setPanelCollapsed((c) => !c)}
|
||||
className="p-1 hover:text-primary-yellow"
|
||||
aria-label={panelCollapsed ? 'Expand' : 'Collapse'}
|
||||
>
|
||||
{panelCollapsed ? <ChevronUpIcon className="w-5 h-5" /> : <ChevronDownIcon className="w-5 h-5" />}
|
||||
</button>
|
||||
{activeUploads === 0 && (
|
||||
<button
|
||||
onClick={() => setUploads([])}
|
||||
className="p-1 hover:text-primary-yellow"
|
||||
aria-label="Close"
|
||||
>
|
||||
<XMarkIcon className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{!panelCollapsed && (
|
||||
<ul className="max-h-72 overflow-y-auto divide-y divide-secondary-light-gray">
|
||||
{uploads.map((u) => {
|
||||
const ds = displayStatus(u);
|
||||
return (
|
||||
<li key={u.key} className="px-4 py-2.5">
|
||||
<div className="flex items-center gap-3">
|
||||
<PhotoIcon className="w-5 h-5 text-gray-400 shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm text-primary-dark truncate" title={u.name}>
|
||||
{u.name}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{ds.state === 'uploading' && `${Math.round(u.progress * 100)}% · ${formatBytes(u.sizeBytes)}`}
|
||||
{ds.state === 'queued' && (es ? 'En cola' : 'Queued')}
|
||||
{ds.state === 'processing' && (es ? 'Procesando…' : 'Processing…')}
|
||||
{ds.state === 'done' && formatBytes(u.sizeBytes)}
|
||||
{ds.state === 'error' && (
|
||||
<span className="text-red-600" title={ds.error}>
|
||||
{ds.error}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<span className="shrink-0">
|
||||
{ds.state === 'done' && <CheckCircleIcon className="w-6 h-6 text-green-600" />}
|
||||
{ds.state === 'error' && <ExclamationCircleIcon className="w-6 h-6 text-red-600" />}
|
||||
{ds.state === 'processing' && (
|
||||
<div className="animate-spin w-5 h-5 border-2 border-primary-yellow border-t-transparent rounded-full" />
|
||||
)}
|
||||
{ds.state === 'uploading' && (
|
||||
<span className="text-xs text-gray-600 tabular-nums">{Math.round(u.progress * 100)}%</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
{ds.state === 'uploading' && (
|
||||
<div className="mt-1.5 h-1 rounded-full bg-secondary-gray overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-primary-yellow transition-[width] duration-200"
|
||||
style={{ width: `${Math.round(u.progress * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { photosApi, eventsApi, PhotoGallery, Event, GalleryVisibility } from '@/lib/api';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import { Skeleton, ImageGridSkeleton } from '@/components/ui/Skeleton';
|
||||
import VisibilityBadge from './VisibilityBadge';
|
||||
import {
|
||||
CameraIcon,
|
||||
PlusIcon,
|
||||
XMarkIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
export default function AdminPhotosPage() {
|
||||
const { locale } = useLanguage();
|
||||
const [galleries, setGalleries] = useState<PhotoGallery[]>([]);
|
||||
const [events, setEvents] = useState<Event[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [form, setForm] = useState({
|
||||
title: '',
|
||||
titleEs: '',
|
||||
eventId: '',
|
||||
visibility: 'private' as GalleryVisibility,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([photosApi.getGalleries(), eventsApi.getAll()])
|
||||
.then(([g, e]) => {
|
||||
setGalleries(g.galleries);
|
||||
setEvents(e.events);
|
||||
})
|
||||
.catch(() => toast.error(locale === 'es' ? 'Error al cargar galerías' : 'Failed to load galleries'))
|
||||
.finally(() => setLoading(false));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!form.title.trim()) return;
|
||||
setCreating(true);
|
||||
try {
|
||||
const { gallery } = await photosApi.createGallery({
|
||||
title: form.title.trim(),
|
||||
titleEs: form.titleEs.trim() || undefined,
|
||||
eventId: form.eventId || undefined,
|
||||
visibility: form.visibility,
|
||||
});
|
||||
setGalleries((prev) => [gallery, ...prev]);
|
||||
setShowCreate(false);
|
||||
setForm({ title: '', titleEs: '', eventId: '', visibility: 'private' });
|
||||
toast.success(locale === 'es' ? 'Galería creada' : 'Gallery created');
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to create gallery');
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<Skeleton className="h-8 w-48" />
|
||||
<Skeleton className="h-10 w-36 rounded-btn hidden md:block" />
|
||||
</div>
|
||||
<ImageGridSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold text-primary-dark">
|
||||
{locale === 'es' ? 'Fotos de Eventos' : 'Event Photos'}
|
||||
</h1>
|
||||
<Button onClick={() => setShowCreate(true)}>
|
||||
<PlusIcon className="w-5 h-5 mr-2" />
|
||||
{locale === 'es' ? 'Nueva Galería' : 'New Gallery'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{galleries.length === 0 ? (
|
||||
<Card className="p-12 text-center">
|
||||
<CameraIcon className="w-16 h-16 mx-auto text-gray-300 mb-4" />
|
||||
<h3 className="text-lg font-semibold text-gray-600 mb-2">
|
||||
{locale === 'es' ? 'Sin galerías todavía' : 'No galleries yet'}
|
||||
</h3>
|
||||
<p className="text-gray-500 mb-4">
|
||||
{locale === 'es'
|
||||
? 'Crea una galería para compartir las fotos de un evento'
|
||||
: 'Create a gallery to share photos from a past event'}
|
||||
</p>
|
||||
<Button onClick={() => setShowCreate(true)}>
|
||||
<PlusIcon className="w-5 h-5 mr-2" />
|
||||
{locale === 'es' ? 'Crear la primera' : 'Create the first one'}
|
||||
</Button>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{galleries.map((g) => (
|
||||
<Link key={g.id} href={`/admin/photos/${g.id}`}>
|
||||
<Card className="overflow-hidden hover:shadow-card-hover transition-shadow cursor-pointer 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" />
|
||||
) : (
|
||||
<CameraIcon className="w-12 h-12 text-gray-300" />
|
||||
)}
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<h3 className="font-semibold text-primary-dark truncate">
|
||||
{locale === 'es' && g.titleEs ? g.titleEs : g.title}
|
||||
</h3>
|
||||
<VisibilityBadge visibility={g.visibility} />
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
{g.photoCount} {locale === 'es' ? 'fotos' : 'photos'}
|
||||
{g.event && <> · {locale === 'es' && g.event.titleEs ? g.event.titleEs : g.event.title}</>}
|
||||
</p>
|
||||
</div>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showCreate && (
|
||||
<div className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-lg p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-bold text-primary-dark">
|
||||
{locale === 'es' ? 'Nueva Galería' : 'New Gallery'}
|
||||
</h2>
|
||||
<button onClick={() => setShowCreate(false)} className="text-gray-400 hover:text-gray-600">
|
||||
<XMarkIcon className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
<form onSubmit={handleCreate} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
{locale === 'es' ? 'Título (inglés)' : 'Title (English)'} *
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={form.title}
|
||||
onChange={(e) => setForm({ ...form, title: e.target.value })}
|
||||
className="w-full px-4 py-2 rounded-btn border border-secondary-light-gray"
|
||||
placeholder="June Language Exchange"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
{locale === 'es' ? 'Título (español)' : 'Title (Spanish)'}
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.titleEs}
|
||||
onChange={(e) => setForm({ ...form, titleEs: e.target.value })}
|
||||
className="w-full px-4 py-2 rounded-btn border border-secondary-light-gray"
|
||||
placeholder="Intercambio de Junio"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
{locale === 'es' ? 'Evento vinculado' : 'Linked event'}
|
||||
</label>
|
||||
<select
|
||||
value={form.eventId}
|
||||
onChange={(e) => setForm({ ...form, eventId: e.target.value })}
|
||||
className="w-full px-4 py-2 rounded-btn border border-secondary-light-gray"
|
||||
>
|
||||
<option value="">{locale === 'es' ? 'Ninguno' : 'None'}</option>
|
||||
{events.map((ev) => (
|
||||
<option key={ev.id} value={ev.id}>
|
||||
{ev.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
{locale === 'es' ? 'Visibilidad' : 'Visibility'}
|
||||
</label>
|
||||
<select
|
||||
value={form.visibility}
|
||||
onChange={(e) => setForm({ ...form, visibility: e.target.value as GalleryVisibility })}
|
||||
className="w-full px-4 py-2 rounded-btn border border-secondary-light-gray"
|
||||
>
|
||||
<option value="private">{locale === 'es' ? 'Privada (solo admins)' : 'Private (admins only)'}</option>
|
||||
<option value="public">{locale === 'es' ? 'Pública (listada)' : 'Public (listed)'}</option>
|
||||
<option value="link">{locale === 'es' ? 'Solo con enlace' : 'Link only'}</option>
|
||||
<option value="ticket">
|
||||
{locale === 'es' ? 'Con entrada del evento' : 'Ticket holders of the event'}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex gap-2 justify-end pt-2">
|
||||
<Button type="button" variant="outline" onClick={() => setShowCreate(false)}>
|
||||
{locale === 'es' ? 'Cancelar' : 'Cancel'}
|
||||
</Button>
|
||||
<Button type="submit" isLoading={creating}>
|
||||
{locale === 'es' ? 'Crear' : 'Create'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
VideoCameraIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import toast from 'react-hot-toast';
|
||||
import { parseDate, EVENT_TIMEZONE } from '@/lib/utils';
|
||||
import { parseDate, formatCurrency, EVENT_TIMEZONE } from '@/lib/utils';
|
||||
import clsx from 'clsx';
|
||||
|
||||
// ─── Types ───────────────────────────────────────────────────
|
||||
@@ -273,6 +273,17 @@ function ValidTicketScreen({
|
||||
{validation.ticket?.attendeeEmail && (
|
||||
<p className="text-emerald-100 text-lg mb-4">{validation.ticket.attendeeEmail}</p>
|
||||
)}
|
||||
{/* Unpaid tickets are valid for entry but the balance is collected at the door */}
|
||||
{validation.ticket?.paymentStatus === 'unpaid' && (
|
||||
<div className="bg-orange-500 rounded-2xl px-6 py-3 w-full max-w-sm text-center mb-3">
|
||||
<p className="font-bold text-lg">UNPAID — collect payment</p>
|
||||
{!!validation.ticket.amountDue && (
|
||||
<p className="text-orange-100 text-sm">
|
||||
Balance due: {formatCurrency(validation.ticket.amountDue)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="bg-white/15 rounded-2xl px-6 py-4 w-full max-w-sm space-y-2 text-center">
|
||||
{validation.event && (
|
||||
<p className="font-semibold text-lg">{validation.event.title}</p>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { usersApi, eventsApi, User, Event } from '@/lib/api';
|
||||
import { parseDate, formatRucDisplay } from '@/lib/utils';
|
||||
@@ -9,12 +9,26 @@ import Button from '@/components/ui/Button';
|
||||
import { AdminPageSkeleton } from '@/components/ui/Skeleton';
|
||||
import Input from '@/components/ui/Input';
|
||||
import { MoreMenu, DropdownItem, BottomSheet, AdminMobileStyles } from '@/components/admin/MobileComponents';
|
||||
import { TrashIcon, PencilSquareIcon, FunnelIcon, XMarkIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline';
|
||||
import { TrashIcon, PencilSquareIcon, FunnelIcon, XMarkIcon, MagnifyingGlassIcon, ChevronLeftIcon, ChevronRightIcon } from '@heroicons/react/24/outline';
|
||||
import toast from 'react-hot-toast';
|
||||
import clsx from 'clsx';
|
||||
|
||||
type RegisteredRange = '' | '7d' | '30d' | '90d';
|
||||
|
||||
const PAGE_SIZE_OPTIONS = [10, 25, 50, 100];
|
||||
|
||||
function getPageNumbers(current: number, totalPages: number): (number | '...')[] {
|
||||
if (totalPages <= 7) return Array.from({ length: totalPages }, (_, i) => i + 1);
|
||||
const pages: (number | '...')[] = [1];
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(totalPages - 1, current + 1);
|
||||
if (start > 2) pages.push('...');
|
||||
for (let i = start; i <= end; i++) pages.push(i);
|
||||
if (end < totalPages - 1) pages.push('...');
|
||||
pages.push(totalPages);
|
||||
return pages;
|
||||
}
|
||||
|
||||
function registeredAfterFromRange(range: RegisteredRange): string | undefined {
|
||||
if (!range) return undefined;
|
||||
const days = range === '7d' ? 7 : range === '30d' ? 30 : 90;
|
||||
@@ -35,6 +49,8 @@ export default function AdminUsersPage() {
|
||||
const [eventFilter, setEventFilter] = useState<string>('');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(25);
|
||||
const [editingUser, setEditingUser] = useState<User | null>(null);
|
||||
const [editForm, setEditForm] = useState({
|
||||
name: '',
|
||||
@@ -57,9 +73,20 @@ export default function AdminUsersPage() {
|
||||
eventsApi.getAll().then((res) => setEvents(res.events)).catch(() => {});
|
||||
}, []);
|
||||
|
||||
// When a filter changes, jump back to page 1 before fetching (skipping the
|
||||
// fetch for the stale page); otherwise fetch for the current page/pageSize.
|
||||
const filterKey = JSON.stringify([roleFilter, statusFilter, hasBookingsFilter, registeredRange, eventFilter, debouncedSearch]);
|
||||
const prevFilterKey = useRef(filterKey);
|
||||
useEffect(() => {
|
||||
if (prevFilterKey.current !== filterKey) {
|
||||
prevFilterKey.current = filterKey;
|
||||
if (page !== 1) {
|
||||
setPage(1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
loadUsers();
|
||||
}, [roleFilter, statusFilter, hasBookingsFilter, registeredRange, eventFilter, debouncedSearch]);
|
||||
}, [filterKey, page, pageSize]);
|
||||
|
||||
const hasActiveFilters =
|
||||
roleFilter || statusFilter || hasBookingsFilter || registeredRange || eventFilter || searchQuery;
|
||||
@@ -82,10 +109,16 @@ export default function AdminUsersPage() {
|
||||
registeredAfter: registeredAfterFromRange(registeredRange),
|
||||
eventId: eventFilter || undefined,
|
||||
search: debouncedSearch.trim() || undefined,
|
||||
pageSize: 200,
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
setUsers(users);
|
||||
setTotal(total);
|
||||
// If the current page emptied out (e.g. after deleting the last user on
|
||||
// it), fall back to the new last page.
|
||||
if (users.length === 0 && total > 0 && page > 1) {
|
||||
setPage(Math.max(1, Math.ceil(total / pageSize)));
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error('Failed to load users');
|
||||
} finally {
|
||||
@@ -385,6 +418,65 @@ export default function AdminUsersPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{total > 0 && (
|
||||
<div className="mt-4 flex flex-col sm:flex-row items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600">
|
||||
<label htmlFor="users-page-size" className="whitespace-nowrap">Per page</label>
|
||||
<select
|
||||
id="users-page-size"
|
||||
value={pageSize}
|
||||
onChange={(e) => { setPageSize(Number(e.target.value)); setPage(1); }}
|
||||
className="px-2 py-1.5 rounded-btn border border-secondary-light-gray text-sm"
|
||||
>
|
||||
{PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<option key={size} value={size}>{size}</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="text-xs text-gray-500 whitespace-nowrap">
|
||||
{(page - 1) * pageSize + 1}–{Math.min(page * pageSize, total)} of {total}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => setPage(page - 1)}
|
||||
disabled={page <= 1}
|
||||
className="p-2 rounded-btn border border-secondary-light-gray text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:pointer-events-none min-h-[36px] min-w-[36px] flex items-center justify-center"
|
||||
aria-label="Previous page"
|
||||
>
|
||||
<ChevronLeftIcon className="w-4 h-4" />
|
||||
</button>
|
||||
{getPageNumbers(page, Math.max(1, Math.ceil(total / pageSize))).map((p, i) =>
|
||||
p === '...' ? (
|
||||
<span key={`ellipsis-${i}`} className="px-1.5 text-sm text-gray-400">…</span>
|
||||
) : (
|
||||
<button
|
||||
key={p}
|
||||
onClick={() => setPage(p)}
|
||||
className={clsx(
|
||||
'min-h-[36px] min-w-[36px] px-2 rounded-btn text-sm',
|
||||
p === page
|
||||
? 'bg-primary-yellow text-primary-dark font-semibold'
|
||||
: 'border border-secondary-light-gray text-gray-600 hover:bg-gray-50'
|
||||
)}
|
||||
aria-current={p === page ? 'page' : undefined}
|
||||
>
|
||||
{p}
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
<button
|
||||
onClick={() => setPage(page + 1)}
|
||||
disabled={page >= Math.ceil(total / pageSize)}
|
||||
className="p-2 rounded-btn border border-secondary-light-gray text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:pointer-events-none min-h-[36px] min-w-[36px] flex items-center justify-center"
|
||||
aria-label="Next page"
|
||||
>
|
||||
<ChevronRightIcon className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mobile Filter BottomSheet */}
|
||||
<BottomSheet open={mobileFilterOpen} onClose={() => setMobileFilterOpen(false)} title="Filters">
|
||||
<div className="space-y-4">
|
||||
|
||||
@@ -2,6 +2,26 @@ import { MetadataRoute } from 'next';
|
||||
|
||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://spanglish.com.py';
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
||||
const photoApiUrl = process.env.PHOTO_API_URL || 'http://localhost:3003';
|
||||
|
||||
interface SitemapPhotoGallery {
|
||||
slug: string;
|
||||
updatedAt: string;
|
||||
event?: { slug: string };
|
||||
}
|
||||
|
||||
/** Public photo galleries from the photo-api service (public visibility only). */
|
||||
async function getPublicPhotoGalleries(): Promise<SitemapPhotoGallery[]> {
|
||||
try {
|
||||
const res = await fetch(`${photoApiUrl}/api/photos/public/galleries`, {
|
||||
next: { revalidate: 3600 },
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
return ((await res.json()).galleries as SitemapPhotoGallery[]) || [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
interface SitemapEvent {
|
||||
id: string;
|
||||
@@ -41,7 +61,10 @@ async function getIndexableEvents(): Promise<SitemapEvent[]> {
|
||||
}
|
||||
|
||||
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
const events = await getIndexableEvents();
|
||||
const [events, photoGalleries] = await Promise.all([
|
||||
getIndexableEvents(),
|
||||
getPublicPhotoGalleries(),
|
||||
]);
|
||||
const now = new Date();
|
||||
|
||||
// Static pages
|
||||
@@ -88,6 +111,12 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
changeFrequency: 'monthly',
|
||||
priority: 0.6,
|
||||
},
|
||||
{
|
||||
url: `${siteUrl}/photos`,
|
||||
lastModified: now,
|
||||
changeFrequency: 'weekly',
|
||||
priority: 0.6,
|
||||
},
|
||||
// Legal pages
|
||||
{
|
||||
url: `${siteUrl}/legal/terms-policy`,
|
||||
@@ -120,5 +149,13 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
};
|
||||
});
|
||||
|
||||
return [...staticPages, ...eventPages];
|
||||
const photoPages: MetadataRoute.Sitemap = photoGalleries.map((g) => ({
|
||||
// Event-linked galleries live under the event's URL.
|
||||
url: g.event ? `${siteUrl}/events/${g.event.slug}/gallery` : `${siteUrl}/photos/${g.slug}`,
|
||||
lastModified: g.updatedAt ? new Date(g.updatedAt) : now,
|
||||
changeFrequency: 'monthly' as const,
|
||||
priority: 0.5,
|
||||
}));
|
||||
|
||||
return [...staticPages, ...eventPages, ...photoPages];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useCallback, useRef, useState } from 'react';
|
||||
import {
|
||||
XMarkIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
ArrowDownTrayIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
|
||||
export interface LightboxItem {
|
||||
id: string;
|
||||
previewUrl: string;
|
||||
downloadUrl: string;
|
||||
filename?: string;
|
||||
/** Small thumbnail for the filmstrip; falls back to previewUrl. */
|
||||
thumbUrl?: string;
|
||||
}
|
||||
|
||||
interface LightboxProps {
|
||||
items: LightboxItem[];
|
||||
index: number;
|
||||
onClose: () => void;
|
||||
onNavigate: (index: number) => void;
|
||||
/** Extra per-item action buttons rendered in the top bar (admin use). */
|
||||
renderActions?: (item: LightboxItem, index: number) => React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-screen photo lightbox with keyboard and swipe navigation, in the
|
||||
* style of the admin gallery preview modal (fixed inset-0 bg-black/90).
|
||||
*/
|
||||
export default function Lightbox({ items, index, onClose, onNavigate, renderActions }: LightboxProps) {
|
||||
const touchStart = useRef<{ x: number; y: number } | null>(null);
|
||||
const activeThumbRef = useRef<HTMLButtonElement | null>(null);
|
||||
const item = items[index];
|
||||
const hasMultiple = items.length > 1;
|
||||
|
||||
const prev = useCallback(() => {
|
||||
onNavigate(index > 0 ? index - 1 : items.length - 1);
|
||||
}, [index, items.length, onNavigate]);
|
||||
const next = useCallback(() => {
|
||||
onNavigate(index < items.length - 1 ? index + 1 : 0);
|
||||
}, [index, items.length, onNavigate]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
if (e.key === 'ArrowLeft') prev();
|
||||
if (e.key === 'ArrowRight') next();
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey);
|
||||
document.body.style.overflow = '';
|
||||
};
|
||||
}, [onClose, prev, next]);
|
||||
|
||||
// Keep the active thumbnail centred in the filmstrip as you navigate.
|
||||
useEffect(() => {
|
||||
activeThumbRef.current?.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
inline: 'center',
|
||||
block: 'nearest',
|
||||
});
|
||||
}, [index]);
|
||||
|
||||
if (!item) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/90 z-50 flex flex-col"
|
||||
onClick={onClose}
|
||||
onTouchStart={(e) => {
|
||||
touchStart.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
|
||||
}}
|
||||
onTouchEnd={(e) => {
|
||||
if (touchStart.current === null) return;
|
||||
const dx = e.changedTouches[0].clientX - touchStart.current.x;
|
||||
const dy = e.changedTouches[0].clientY - touchStart.current.y;
|
||||
touchStart.current = null;
|
||||
// Only treat as a swipe when it's clearly horizontal.
|
||||
if (Math.abs(dx) < 50 || Math.abs(dx) < Math.abs(dy)) return;
|
||||
if (dx > 0) prev();
|
||||
else next();
|
||||
}}
|
||||
>
|
||||
<button
|
||||
className="absolute top-4 right-4 text-white hover:text-gray-300 z-10 p-2 -m-2"
|
||||
onClick={onClose}
|
||||
aria-label="Close"
|
||||
>
|
||||
<XMarkIcon className="w-8 h-8" />
|
||||
</button>
|
||||
|
||||
<div
|
||||
className="absolute top-4 left-4 z-10 flex items-center gap-4"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<a
|
||||
href={item.downloadUrl}
|
||||
download={item.filename || true}
|
||||
className="text-white hover:text-gray-300"
|
||||
aria-label="Download"
|
||||
>
|
||||
<ArrowDownTrayIcon className="w-7 h-7" />
|
||||
</a>
|
||||
{renderActions?.(item, index)}
|
||||
</div>
|
||||
|
||||
{/* Main image area */}
|
||||
<div className="relative flex-1 min-h-0 flex items-center justify-center">
|
||||
{hasMultiple && (
|
||||
<>
|
||||
<button
|
||||
className="absolute left-2 md:left-4 top-1/2 -translate-y-1/2 text-white/80 hover:text-white z-10 p-2"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
prev();
|
||||
}}
|
||||
aria-label="Previous"
|
||||
>
|
||||
<ChevronLeftIcon className="w-9 h-9" />
|
||||
</button>
|
||||
<button
|
||||
className="absolute right-2 md:right-4 top-1/2 -translate-y-1/2 text-white/80 hover:text-white z-10 p-2"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
next();
|
||||
}}
|
||||
aria-label="Next"
|
||||
>
|
||||
<ChevronRightIcon className="w-9 h-9" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={item.previewUrl}
|
||||
alt=""
|
||||
className="max-w-[95vw] max-h-full object-contain select-none"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
draggable={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Counter + thumbnail filmstrip you can skip through. */}
|
||||
<div
|
||||
className="shrink-0 pb-3 pt-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onTouchStart={(e) => e.stopPropagation()}
|
||||
onTouchEnd={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="text-center text-white/70 text-sm mb-2">
|
||||
{index + 1} / {items.length}
|
||||
</div>
|
||||
{hasMultiple && (
|
||||
<div className="flex gap-2 overflow-x-auto px-4 pb-1 justify-start sm:justify-center [scrollbar-width:thin]">
|
||||
{items.map((it, i) => (
|
||||
<button
|
||||
key={it.id}
|
||||
ref={i === index ? activeThumbRef : null}
|
||||
onClick={() => onNavigate(i)}
|
||||
aria-label={`Photo ${i + 1}`}
|
||||
aria-current={i === index}
|
||||
className={`relative shrink-0 overflow-hidden rounded transition ${
|
||||
i === index
|
||||
? 'ring-2 ring-white opacity-100'
|
||||
: 'opacity-50 hover:opacity-90'
|
||||
}`}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={it.thumbUrl || it.previewUrl}
|
||||
alt=""
|
||||
className="h-14 w-14 sm:h-16 sm:w-16 object-cover"
|
||||
draggable={false}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Preload neighbours so prev/next feels instant. */}
|
||||
<div className="hidden" aria-hidden>
|
||||
{hasMultiple && (
|
||||
<>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={items[(index + 1) % items.length].previewUrl} alt="" />
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={items[(index - 1 + items.length) % items.length].previewUrl} alt="" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { usePathname, useSearchParams } from 'next/navigation';
|
||||
import { useLanguage } from '@/context/LanguageContext';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import GoogleSignInButton from '@/components/GoogleSignInButton';
|
||||
import { authApi } from '@/lib/api';
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
interface LoginModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
/** Called after a successful password login (Google logins reload the page). */
|
||||
onSuccess?: () => void;
|
||||
/** Optional context line shown under the title (e.g. why login is needed). */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reusable login pop-up: same capabilities as /login (password,
|
||||
* magic link, Google) but inline, so the visitor stays on the page —
|
||||
* used by gated photo galleries.
|
||||
*/
|
||||
export default function LoginModal({ open, onClose, onSuccess, message }: LoginModalProps) {
|
||||
const { t, locale } = useLanguage();
|
||||
const es = locale === 'es';
|
||||
const { login } = useAuth();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const [mode, setMode] = useState<'password' | 'magic-link'>('password');
|
||||
const [magicLinkSent, setMagicLinkSent] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
|
||||
// Google logins hard-reload; send them back to exactly where they are
|
||||
// (including a ?token= share link).
|
||||
const query = searchParams.toString();
|
||||
const currentUrl = query ? `${pathname}?${query}` : pathname;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey);
|
||||
document.body.style.overflow = '';
|
||||
};
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const handlePasswordLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
try {
|
||||
await login(email, password);
|
||||
toast.success(es ? '¡Bienvenido!' : 'Welcome back!');
|
||||
onClose();
|
||||
onSuccess?.();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t('auth.errors.invalidCredentials'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMagicLink = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!email) {
|
||||
toast.error(es ? 'Ingresa tu email' : 'Please enter your email');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
await authApi.requestMagicLink(email);
|
||||
setMagicLinkSent(true);
|
||||
toast.success(es ? 'Revisa tu correo para el enlace de acceso' : 'Check your email for the login link');
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : es ? 'Error' : 'Failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4"
|
||||
onClick={onClose}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
>
|
||||
<Card className="w-full max-w-md p-6 md:p-8" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="flex items-start justify-between mb-1">
|
||||
<h2 className="text-xl font-bold text-primary-dark">{t('auth.login.title')}</h2>
|
||||
<button onClick={onClose} className="text-gray-400 hover:text-gray-600 p-1 -m-1" aria-label="Close">
|
||||
<XMarkIcon className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
{message && <p className="text-sm text-gray-600 mb-4">{message}</p>}
|
||||
|
||||
<div className="mt-4">
|
||||
<GoogleSignInButton redirectTo={currentUrl} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 my-5">
|
||||
<div className="flex-1 h-px bg-secondary-light-gray" />
|
||||
<span className="text-xs text-gray-500">{es ? 'o' : 'or'}</span>
|
||||
<div className="flex-1 h-px bg-secondary-light-gray" />
|
||||
</div>
|
||||
|
||||
{mode === 'password' ? (
|
||||
<form onSubmit={handlePasswordLogin} className="space-y-4">
|
||||
<Input
|
||||
id="login-modal-email"
|
||||
label={t('auth.login.email')}
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
id="login-modal-password"
|
||||
label={t('auth.login.password')}
|
||||
type="password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
<Button type="submit" className="w-full" isLoading={loading}>
|
||||
{t('auth.login.submit')}
|
||||
</Button>
|
||||
</form>
|
||||
) : magicLinkSent ? (
|
||||
<p className="text-sm text-gray-600 text-center py-4">
|
||||
{es
|
||||
? 'Te enviamos un enlace de acceso. Abre tu correo y vuelve a esta página.'
|
||||
: 'We sent you a login link. Open your email and come back to this page.'}
|
||||
</p>
|
||||
) : (
|
||||
<form onSubmit={handleMagicLink} className="space-y-4">
|
||||
<Input
|
||||
id="login-modal-magic-email"
|
||||
label={t('auth.login.email')}
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
<Button type="submit" className="w-full" isLoading={loading}>
|
||||
{es ? 'Enviarme un enlace de acceso' : 'Email me a login link'}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="mt-4 flex items-center justify-between text-sm">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMode(mode === 'password' ? 'magic-link' : 'password');
|
||||
setMagicLinkSent(false);
|
||||
}}
|
||||
className="text-secondary-blue hover:underline"
|
||||
>
|
||||
{mode === 'password'
|
||||
? es
|
||||
? 'Entrar con enlace por correo'
|
||||
: 'Log in with an email link'
|
||||
: es
|
||||
? 'Entrar con contraseña'
|
||||
: 'Log in with a password'}
|
||||
</button>
|
||||
<Link href="/register" className="text-secondary-blue hover:underline" onClick={onClose}>
|
||||
{es ? 'Crear cuenta' : 'Create account'}
|
||||
</Link>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
'use client';
|
||||
|
||||
import { ReactNode } from 'react';
|
||||
import { usePrivacy } from '@/context/PrivacyContext';
|
||||
|
||||
export const PRIVACY_MASK = '••••';
|
||||
|
||||
/**
|
||||
* Renders its children normally, but shows a mask while privacy mode is on.
|
||||
* Use for inline sensitive numbers that can't be hidden without breaking
|
||||
* the surrounding row/badge.
|
||||
*/
|
||||
export default function SensitiveValue({
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
const { privacyMode } = usePrivacy();
|
||||
return <span className={className}>{privacyMode ? PRIVACY_MASK : children}</span>;
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode, useCallback } from 'react';
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL || '';
|
||||
import { authClient } from '@/lib/auth-client';
|
||||
import { fetchApi } from '@/lib/api/client';
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
@@ -18,18 +18,19 @@ interface User {
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
/** Always null: auth moved to httpOnly session cookies (Better Auth). Kept for compat. */
|
||||
token: string | null;
|
||||
isLoading: boolean;
|
||||
isAdmin: boolean;
|
||||
hasAdminAccess: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
loginWithGoogle: (credential: string) => Promise<void>;
|
||||
loginWithMagicLink: (token: string) => Promise<void>;
|
||||
loginWithMagicLink: (token: string) => Promise<User | null>;
|
||||
register: (data: RegisterData) => Promise<void>;
|
||||
logout: () => void;
|
||||
updateUser: (user: User) => void;
|
||||
setAuthData: (data: { user: User; token: string }) => void;
|
||||
refreshUser: () => Promise<void>;
|
||||
setAuthData: (data: { user: User; token?: string }) => void;
|
||||
refreshUser: () => Promise<User | null>;
|
||||
}
|
||||
|
||||
interface RegisterData {
|
||||
@@ -42,178 +43,139 @@ interface RegisterData {
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
const TOKEN_KEY = 'spanglish-token';
|
||||
const USER_KEY = 'spanglish-user';
|
||||
const AUTH_COOKIE = 'spanglish-auth';
|
||||
// Legacy storage from the pre-Better-Auth JWT era; cleared once on mount.
|
||||
const LEGACY_TOKEN_KEY = 'spanglish-token';
|
||||
const LEGACY_USER_KEY = 'spanglish-user';
|
||||
const LEGACY_AUTH_COOKIE = 'spanglish-auth';
|
||||
|
||||
function setAuthCookie() {
|
||||
if (typeof document === 'undefined') return;
|
||||
document.cookie = `${AUTH_COOKIE}=1; path=/; max-age=${60 * 60 * 24}; SameSite=Lax`;
|
||||
function mapSessionUser(sessionUser: any): User {
|
||||
return {
|
||||
id: sessionUser.id,
|
||||
email: sessionUser.email,
|
||||
name: sessionUser.name,
|
||||
role: sessionUser.role ?? 'user',
|
||||
phone: sessionUser.phone ?? undefined,
|
||||
languagePreference: sessionUser.languagePreference ?? undefined,
|
||||
isClaimed: Boolean(sessionUser.isClaimed ?? true),
|
||||
rucNumber: sessionUser.rucNumber ?? undefined,
|
||||
accountStatus: sessionUser.accountStatus ?? 'active',
|
||||
};
|
||||
}
|
||||
|
||||
function clearAuthCookie() {
|
||||
if (typeof document === 'undefined') return;
|
||||
document.cookie = `${AUTH_COOKIE}=; path=/; max-age=0; SameSite=Lax`;
|
||||
function messageFrom(error: { message?: string; code?: string; status?: number } | null, fallback: string): string {
|
||||
return error?.message || fallback;
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
const refreshUser = useCallback(async () => {
|
||||
const currentToken = localStorage.getItem(TOKEN_KEY);
|
||||
if (!currentToken) return;
|
||||
|
||||
const refreshUser = useCallback(async (): Promise<User | null> => {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/auth/me`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${currentToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setUser(data.user);
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(data.user));
|
||||
setAuthCookie();
|
||||
} else if (res.status === 401) {
|
||||
// Token is invalid, clear auth state
|
||||
setToken(null);
|
||||
setUser(null);
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
clearAuthCookie();
|
||||
const { data } = await authClient.getSession();
|
||||
if (data?.user) {
|
||||
const mapped = mapSessionUser(data.user);
|
||||
setUser(mapped);
|
||||
return mapped;
|
||||
}
|
||||
setUser(null);
|
||||
return null;
|
||||
} catch (error) {
|
||||
// Network error, keep using cached data
|
||||
// Network error: keep current state
|
||||
console.error('Failed to refresh user data:', error);
|
||||
return null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// Load auth state from localStorage
|
||||
const savedToken = localStorage.getItem(TOKEN_KEY);
|
||||
const savedUser = localStorage.getItem(USER_KEY);
|
||||
|
||||
if (savedToken && savedUser) {
|
||||
// Guard against corrupt/tampered localStorage so the whole app doesn't crash.
|
||||
let parsedUser: User | null = null;
|
||||
try {
|
||||
parsedUser = JSON.parse(savedUser);
|
||||
} catch {
|
||||
parsedUser = null;
|
||||
}
|
||||
|
||||
if (parsedUser) {
|
||||
setToken(savedToken);
|
||||
setUser(parsedUser);
|
||||
// Refresh user data from server to get latest role/permissions (source of truth)
|
||||
refreshUser().finally(() => setIsLoading(false));
|
||||
} else {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
setIsLoading(false);
|
||||
}
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
// One-time cleanup of legacy JWT-era storage
|
||||
try {
|
||||
localStorage.removeItem(LEGACY_TOKEN_KEY);
|
||||
localStorage.removeItem(LEGACY_USER_KEY);
|
||||
document.cookie = `${LEGACY_AUTH_COOKIE}=; path=/; max-age=0; SameSite=Lax`;
|
||||
} catch {
|
||||
/* SSR / storage unavailable */
|
||||
}
|
||||
|
||||
refreshUser().finally(() => setIsLoading(false));
|
||||
}, [refreshUser]);
|
||||
|
||||
const setAuthData = useCallback((data: { user: User; token: string }) => {
|
||||
setToken(data.token);
|
||||
setUser(data.user);
|
||||
localStorage.setItem(TOKEN_KEY, data.token);
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(data.user));
|
||||
setAuthCookie();
|
||||
}, []);
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const res = await fetch(`${API_BASE}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.error || 'Login failed');
|
||||
const { error } = await authClient.signIn.email({ email, password });
|
||||
if (error) {
|
||||
throw new Error(messageFrom(error, 'Login failed'));
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
setAuthData(data);
|
||||
await refreshUser();
|
||||
};
|
||||
|
||||
const loginWithGoogle = async (credential: string) => {
|
||||
const res = await fetch(`${API_BASE}/api/auth/google`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ credential }),
|
||||
const { error } = await authClient.signIn.social({
|
||||
provider: 'google',
|
||||
idToken: { token: credential },
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.error || 'Google login failed');
|
||||
if (error) {
|
||||
throw new Error(messageFrom(error, 'Google login failed'));
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
setAuthData(data);
|
||||
await refreshUser();
|
||||
};
|
||||
|
||||
const loginWithMagicLink = async (magicToken: string) => {
|
||||
const res = await fetch(`${API_BASE}/api/auth/magic-link/verify`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: magicToken }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.error || 'Magic link login failed');
|
||||
const loginWithMagicLink = async (magicToken: string): Promise<User | null> => {
|
||||
const { error } = await authClient.magicLink.verify({ query: { token: magicToken } });
|
||||
if (error) {
|
||||
throw new Error(messageFrom(error, 'Invalid or expired link'));
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
setAuthData(data);
|
||||
return refreshUser();
|
||||
};
|
||||
|
||||
const register = async (registerData: RegisterData) => {
|
||||
const res = await fetch(`${API_BASE}/api/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(registerData),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json();
|
||||
throw new Error(error.error || 'Registration failed');
|
||||
const { error } = await authClient.signUp.email({
|
||||
email: registerData.email,
|
||||
password: registerData.password,
|
||||
name: registerData.name,
|
||||
phone: registerData.phone || undefined,
|
||||
languagePreference: registerData.languagePreference || undefined,
|
||||
} as any);
|
||||
if (error) {
|
||||
// Existing-but-unclaimed accounts (created during guest booking) should
|
||||
// point the user to the claim flow instead of a bare "already exists".
|
||||
if (error.code === 'USER_ALREADY_EXISTS') {
|
||||
try {
|
||||
const { canClaim } = await fetchApi<{ canClaim: boolean }>(
|
||||
`/api/auth-ext/claim-eligibility?email=${encodeURIComponent(registerData.email)}`
|
||||
);
|
||||
if (canClaim) {
|
||||
const err = new Error(
|
||||
'This email has an unclaimed account from a previous booking. Use "Email Link" on the login page to claim it.'
|
||||
);
|
||||
(err as any).canClaim = true;
|
||||
throw err;
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (e?.canClaim) throw e;
|
||||
/* eligibility check failed: fall through to generic message */
|
||||
}
|
||||
}
|
||||
throw new Error(messageFrom(error, 'Registration failed'));
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
setAuthData(data);
|
||||
await refreshUser();
|
||||
};
|
||||
|
||||
const logout = useCallback(() => {
|
||||
// Best-effort server-side invalidation (bumps token version so the JWT can't be reused).
|
||||
const currentToken = localStorage.getItem(TOKEN_KEY);
|
||||
if (currentToken) {
|
||||
fetch(`${API_BASE}/api/auth/logout`, {
|
||||
method: 'POST',
|
||||
headers: { 'Authorization': `Bearer ${currentToken}` },
|
||||
}).catch(() => {
|
||||
// Ignore network errors; local state is cleared regardless.
|
||||
});
|
||||
}
|
||||
setToken(null);
|
||||
// Best-effort server-side revocation; local state clears regardless.
|
||||
authClient.signOut().catch(() => {
|
||||
/* ignore network errors */
|
||||
});
|
||||
setUser(null);
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
clearAuthCookie();
|
||||
}, []);
|
||||
|
||||
const updateUser = useCallback((updatedUser: User) => {
|
||||
setUser(updatedUser);
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(updatedUser));
|
||||
}, []);
|
||||
|
||||
// Compat shim for callers that used to push {user, token} after custom auth
|
||||
// flows; the session cookie is already set by then, so only state updates.
|
||||
const setAuthData = useCallback((data: { user: User; token?: string }) => {
|
||||
setUser(data.user);
|
||||
}, []);
|
||||
|
||||
const isAdmin = user?.role === 'admin' || user?.role === 'organizer';
|
||||
@@ -221,16 +183,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
token,
|
||||
isLoading,
|
||||
isAdmin,
|
||||
value={{
|
||||
user,
|
||||
token: null,
|
||||
isLoading,
|
||||
isAdmin,
|
||||
hasAdminAccess,
|
||||
login,
|
||||
login,
|
||||
loginWithGoogle,
|
||||
loginWithMagicLink,
|
||||
register,
|
||||
register,
|
||||
logout,
|
||||
updateUser,
|
||||
setAuthData,
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
'use client';
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
|
||||
|
||||
interface PrivacyContextType {
|
||||
/** true = stats and sensitive data are hidden */
|
||||
privacyMode: boolean;
|
||||
setPrivacyMode: (value: boolean) => void;
|
||||
togglePrivacyMode: () => void;
|
||||
}
|
||||
|
||||
const PrivacyContext = createContext<PrivacyContextType | undefined>(undefined);
|
||||
|
||||
// Same key the old per-page useStatsPrivacy hook used ('true' = hidden), so
|
||||
// existing operators keep their saved preference.
|
||||
const STORAGE_KEY = 'spanglish-admin-stats-hidden';
|
||||
|
||||
export function PrivacyProvider({ children }: { children: ReactNode }) {
|
||||
const [privacyMode, setPrivacyModeState] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored !== null) {
|
||||
setPrivacyModeState(stored === 'true');
|
||||
}
|
||||
} catch {
|
||||
// localStorage unavailable (private mode etc.) - keep default
|
||||
}
|
||||
}, []);
|
||||
|
||||
const setPrivacyMode = useCallback((value: boolean) => {
|
||||
setPrivacyModeState(value);
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, String(value));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
|
||||
const togglePrivacyMode = useCallback(() => {
|
||||
setPrivacyModeState((prev) => {
|
||||
const next = !prev;
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, String(next));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<PrivacyContext.Provider value={{ privacyMode, setPrivacyMode, togglePrivacyMode }}>
|
||||
{children}
|
||||
</PrivacyContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function usePrivacy() {
|
||||
const context = useContext(PrivacyContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('usePrivacy must be used within a PrivacyProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
|
||||
const STORAGE_KEY = 'spanglish-admin-stats-hidden';
|
||||
|
||||
export function useStatsPrivacy() {
|
||||
const [showStats, setShowStatsState] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored !== null) {
|
||||
setShowStatsState(stored !== 'true');
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
|
||||
const setShowStats = useCallback((value: boolean | ((prev: boolean) => boolean)) => {
|
||||
setShowStatsState((prev) => {
|
||||
const next = typeof value === 'function' ? value(prev) : value;
|
||||
try {
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem(STORAGE_KEY, String(!next));
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleStats = useCallback(() => {
|
||||
setShowStats((prev) => !prev);
|
||||
}, [setShowStats]);
|
||||
|
||||
return [showStats, setShowStats, toggleStats] as const;
|
||||
}
|
||||
@@ -255,6 +255,10 @@
|
||||
}
|
||||
},
|
||||
"admin": {
|
||||
"privacy": {
|
||||
"hide": "Hide Stats",
|
||||
"show": "Show Stats"
|
||||
},
|
||||
"dashboard": {
|
||||
"title": "Dashboard",
|
||||
"welcome": "Welcome back",
|
||||
@@ -275,6 +279,7 @@
|
||||
"contacts": "Messages",
|
||||
"emails": "Emails",
|
||||
"gallery": "Gallery",
|
||||
"photos": "Photos",
|
||||
"settings": "Settings"
|
||||
},
|
||||
"events": {
|
||||
|
||||
@@ -255,6 +255,10 @@
|
||||
}
|
||||
},
|
||||
"admin": {
|
||||
"privacy": {
|
||||
"hide": "Ocultar Datos",
|
||||
"show": "Mostrar Datos"
|
||||
},
|
||||
"dashboard": {
|
||||
"title": "Panel de Control",
|
||||
"welcome": "Bienvenido de nuevo",
|
||||
@@ -275,6 +279,7 @@
|
||||
"contacts": "Mensajes",
|
||||
"emails": "Emails",
|
||||
"gallery": "Galería",
|
||||
"photos": "Fotos",
|
||||
"settings": "Configuración"
|
||||
},
|
||||
"events": {
|
||||
|
||||
@@ -1,63 +1,97 @@
|
||||
import { authClient } from '../auth-client';
|
||||
import { fetchApi } from './client';
|
||||
import type { User } from './types';
|
||||
|
||||
// Thin wrappers over the Better Auth client, preserving the legacy authApi
|
||||
// call surface used by the auth pages.
|
||||
|
||||
type ClientError = { message?: string; code?: string; status: number } | null;
|
||||
|
||||
function throwIfError(error: ClientError, fallback: string): void {
|
||||
if (error) {
|
||||
const err = new Error(error.message || fallback);
|
||||
(err as any).code = error.code;
|
||||
(err as any).status = error.status;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
// Magic link
|
||||
requestMagicLink: (email: string) =>
|
||||
fetchApi<{ message: string }>('/api/auth/magic-link/request', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email }),
|
||||
}),
|
||||
// Magic link login. Enumeration-safe UX parity: unknown emails resolve with
|
||||
// the same generic message (magic links never create accounts server-side);
|
||||
// only rate limiting surfaces as an error.
|
||||
requestMagicLink: async (email: string, callbackURL: string = '/dashboard') => {
|
||||
const { error } = await authClient.signIn.magicLink({ email, callbackURL });
|
||||
if (error && error.status === 429) {
|
||||
throwIfError(error, 'Too many requests. Please try again later.');
|
||||
}
|
||||
return { message: 'If an account exists with this email, a login link has been sent.' };
|
||||
},
|
||||
|
||||
verifyMagicLink: (token: string) =>
|
||||
fetchApi<{ user: User; token: string; refreshToken: string }>('/api/auth/magic-link/verify', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ token }),
|
||||
}),
|
||||
verifyMagicLink: async (token: string) => {
|
||||
const { data, error } = await authClient.magicLink.verify({ query: { token } });
|
||||
throwIfError(error, 'Invalid or expired token');
|
||||
return data;
|
||||
},
|
||||
|
||||
// Password reset
|
||||
requestPasswordReset: (email: string) =>
|
||||
fetchApi<{ message: string }>('/api/auth/password-reset/request', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email }),
|
||||
}),
|
||||
// Password reset (Better Auth is enumeration-safe here by default)
|
||||
requestPasswordReset: async (email: string) => {
|
||||
const { error } = await authClient.requestPasswordReset({
|
||||
email,
|
||||
redirectTo: '/auth/reset-password',
|
||||
});
|
||||
throwIfError(error, 'Failed to request password reset');
|
||||
return { message: 'If an account exists with this email, a password reset link has been sent.' };
|
||||
},
|
||||
|
||||
confirmPasswordReset: (token: string, password: string) =>
|
||||
fetchApi<{ message: string }>('/api/auth/password-reset/confirm', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ token, password }),
|
||||
}),
|
||||
confirmPasswordReset: async (token: string, password: string) => {
|
||||
const { error } = await authClient.resetPassword({ newPassword: password, token });
|
||||
throwIfError(error, 'Invalid or expired token');
|
||||
return { message: 'Password reset successfully. Please log in with your new password.' };
|
||||
},
|
||||
|
||||
// Account claiming
|
||||
// Account claiming: a magic link that lands on the claim page, where the
|
||||
// session-holding user sets a password via /api/auth-ext/claim-account.
|
||||
requestClaimAccount: (email: string) =>
|
||||
fetchApi<{ message: string }>('/api/auth/claim-account/request', {
|
||||
authApi.requestMagicLink(email, '/auth/claim-account'),
|
||||
|
||||
confirmClaimAccount: (password: string) =>
|
||||
fetchApi<{ user: User; message: string }>('/api/auth-ext/claim-account', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email }),
|
||||
body: JSON.stringify({ password }),
|
||||
}),
|
||||
|
||||
confirmClaimAccount: (token: string, data: { password?: string; googleId?: string }) =>
|
||||
fetchApi<{ user: User; token: string; refreshToken: string; message: string }>(
|
||||
'/api/auth/claim-account/confirm',
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ token, ...data }),
|
||||
}
|
||||
claimEligibility: (email: string) =>
|
||||
fetchApi<{ canClaim: boolean }>(
|
||||
`/api/auth-ext/claim-eligibility?email=${encodeURIComponent(email)}`
|
||||
),
|
||||
|
||||
// Google OAuth
|
||||
googleAuth: (credential: string) =>
|
||||
fetchApi<{ user: User; token: string; refreshToken: string }>('/api/auth/google', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ credential }),
|
||||
}),
|
||||
// Google Identity Services credential (ID token) sign-in
|
||||
googleAuth: async (credential: string) => {
|
||||
const { data, error } = await authClient.signIn.social({
|
||||
provider: 'google',
|
||||
idToken: { token: credential },
|
||||
});
|
||||
throwIfError(error, 'Google login failed');
|
||||
return data;
|
||||
},
|
||||
|
||||
// Change password
|
||||
changePassword: (currentPassword: string, newPassword: string) =>
|
||||
fetchApi<{ message: string }>('/api/auth/change-password', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ currentPassword, newPassword }),
|
||||
}),
|
||||
// Change password; other sessions are revoked so a stolen session can't
|
||||
// outlive the change (this device stays signed in).
|
||||
changePassword: async (currentPassword: string, newPassword: string) => {
|
||||
const { error } = await authClient.changePassword({
|
||||
currentPassword,
|
||||
newPassword,
|
||||
revokeOtherSessions: true,
|
||||
});
|
||||
throwIfError(error, 'Failed to change password');
|
||||
return { message: 'Password changed successfully' };
|
||||
},
|
||||
|
||||
// Get current user
|
||||
me: () => fetchApi<{ user: User }>('/api/auth/me'),
|
||||
me: async (): Promise<{ user: User | null }> => {
|
||||
const { data, error } = await authClient.getSession();
|
||||
throwIfError(error, 'Failed to load session');
|
||||
return { user: (data?.user as unknown as User) ?? null };
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,30 +1,25 @@
|
||||
export const API_BASE = process.env.NEXT_PUBLIC_API_URL || '';
|
||||
|
||||
// Auth rides on the Better Auth httpOnly session cookie. With API_BASE unset
|
||||
// (same-origin via Next rewrites) 'same-origin' sends it; a cross-origin
|
||||
// API_BASE needs 'include' plus CORS credentials on the backend.
|
||||
const CREDENTIALS: RequestCredentials = API_BASE ? 'include' : 'same-origin';
|
||||
|
||||
export interface ApiError {
|
||||
error: string;
|
||||
}
|
||||
|
||||
/** Read the stored auth token (browser only). */
|
||||
export function getToken(): string | null {
|
||||
return typeof window !== 'undefined' ? localStorage.getItem('spanglish-token') : null;
|
||||
}
|
||||
|
||||
export async function fetchApi<T>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
const token = getToken();
|
||||
|
||||
const headers: HeadersInit = {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
if (token) {
|
||||
(headers as Record<string, string>)['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const res = await fetch(`${API_BASE}${endpoint}`, {
|
||||
credentials: CREDENTIALS,
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
@@ -34,7 +29,12 @@ export async function fetchApi<T>(
|
||||
const errorMessage = typeof errorData.error === 'string'
|
||||
? errorData.error
|
||||
: (errorData.message || JSON.stringify(errorData) || 'Request failed');
|
||||
throw new Error(errorMessage);
|
||||
const error = new Error(errorMessage);
|
||||
// Preserve structured error info (e.g. code: 'EVENT_OVER_CAPACITY') so
|
||||
// callers can react beyond the message text.
|
||||
(error as any).code = errorData.code;
|
||||
(error as any).data = errorData;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res.json();
|
||||
@@ -48,11 +48,7 @@ export async function fetchBlob(
|
||||
endpoint: string,
|
||||
fallbackFilename: string
|
||||
): Promise<{ blob: Blob; filename: string }> {
|
||||
const token = getToken();
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
|
||||
const res = await fetch(`${API_BASE}${endpoint}`, { headers });
|
||||
const res = await fetch(`${API_BASE}${endpoint}`, { credentials: CREDENTIALS });
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({ error: 'Export failed' }));
|
||||
throw new Error(errorData.error || 'Export failed');
|
||||
|
||||
@@ -17,3 +17,11 @@ export { siteSettingsApi } from './siteSettings';
|
||||
export { legalSettingsApi } from './legalSettings';
|
||||
export { legalPagesApi } from './legalPages';
|
||||
export { faqApi } from './faq';
|
||||
export { photosApi } from './photos';
|
||||
export type {
|
||||
Photo,
|
||||
PhotoGallery,
|
||||
PhotoGalleryEvent,
|
||||
GalleryVisibility,
|
||||
CreateGalleryInput,
|
||||
} from './photos';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { fetchApi, API_BASE, getToken } from './client';
|
||||
import { fetchApi, API_BASE } from './client';
|
||||
import type { Media } from './types';
|
||||
|
||||
export const mediaApi = {
|
||||
@@ -11,16 +11,15 @@ export const mediaApi = {
|
||||
},
|
||||
|
||||
upload: async (file: File, relatedId?: string, relatedType?: string) => {
|
||||
const token = getToken();
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
if (relatedId) formData.append('relatedId', relatedId);
|
||||
if (relatedType) formData.append('relatedType', relatedType);
|
||||
|
||||
// Auth rides on the session cookie
|
||||
const res = await fetch(`${API_BASE}/api/media/upload`, {
|
||||
method: 'POST',
|
||||
headers: token ? { 'Authorization': `Bearer ${token}` } : {},
|
||||
credentials: API_BASE ? 'include' : 'same-origin',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import { fetchApi } from './client';
|
||||
import type { Payment, PaymentWithDetails } from './types';
|
||||
|
||||
// Mirrors backend/src/lib/paymentProviders.ts: manual gateways need an admin to
|
||||
// verify the money arrived; automatic ones (lightning) confirm themselves.
|
||||
export const MANUAL_PAYMENT_PROVIDERS = ['tpago', 'bank_transfer', 'card', 'cash'];
|
||||
|
||||
export function isManualProvider(provider: string): boolean {
|
||||
return MANUAL_PAYMENT_PROVIDERS.includes(provider);
|
||||
}
|
||||
|
||||
export const paymentsApi = {
|
||||
getAll: (params?: { status?: string; provider?: string; pendingApproval?: boolean; eventId?: string; eventIds?: string[] }) => {
|
||||
const query = new URLSearchParams();
|
||||
@@ -21,10 +29,10 @@ export const paymentsApi = {
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
approve: (id: string, adminNote?: string, sendEmail: boolean = true) =>
|
||||
approve: (id: string, adminNote?: string, sendEmail: boolean = true, allowOverCapacity: boolean = false) =>
|
||||
fetchApi<{ payment: Payment; message: string }>(`/api/payments/${id}/approve`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ adminNote, sendEmail }),
|
||||
body: JSON.stringify({ adminNote, sendEmail, allowOverCapacity }),
|
||||
}),
|
||||
|
||||
reject: (id: string, adminNote?: string, sendEmail: boolean = true) =>
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import { fetchApi, API_BASE } from './client';
|
||||
|
||||
// Client for the standalone photo-api Go service (photo-api/), reachable
|
||||
// under /api/photos via the Next rewrite (dev) or nginx (prod).
|
||||
|
||||
export type GalleryVisibility = 'public' | 'private' | 'link' | 'ticket';
|
||||
|
||||
export interface PhotoGalleryEvent {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
titleEs?: string;
|
||||
startDatetime: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface PhotoGallery {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
titleEs?: string;
|
||||
description?: string;
|
||||
descriptionEs?: string;
|
||||
eventId?: string;
|
||||
visibility: GalleryVisibility;
|
||||
coverPhotoId?: string;
|
||||
photoCount: number;
|
||||
coverUrl?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
event?: PhotoGalleryEvent;
|
||||
// Present on admin responses only:
|
||||
shareToken?: string;
|
||||
shareUrl?: string;
|
||||
}
|
||||
|
||||
export interface Photo {
|
||||
id: string;
|
||||
galleryId: string;
|
||||
position: number;
|
||||
originalFilename?: string;
|
||||
contentType: string;
|
||||
sizeBytes: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
takenAt?: string;
|
||||
status: 'queued' | 'processing' | 'ready' | 'failed';
|
||||
lastError?: string;
|
||||
createdAt: string;
|
||||
urls: {
|
||||
thumb?: string;
|
||||
preview?: string;
|
||||
original: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CreateGalleryInput {
|
||||
title: string;
|
||||
titleEs?: string;
|
||||
description?: string;
|
||||
descriptionEs?: string;
|
||||
eventId?: string;
|
||||
visibility?: GalleryVisibility;
|
||||
}
|
||||
|
||||
export const photosApi = {
|
||||
// Admin (requires admin/organizer token)
|
||||
createGallery: (data: CreateGalleryInput) =>
|
||||
fetchApi<{ gallery: PhotoGallery }>('/api/photos/galleries', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
getGalleries: (eventId?: string) => {
|
||||
const query = eventId ? `?eventId=${encodeURIComponent(eventId)}` : '';
|
||||
return fetchApi<{ galleries: PhotoGallery[] }>(`/api/photos/galleries${query}`);
|
||||
},
|
||||
|
||||
getGallery: (id: string) =>
|
||||
fetchApi<{ gallery: PhotoGallery; photos: Photo[] }>(`/api/photos/galleries/${id}`),
|
||||
|
||||
updateGallery: (id: string, data: Partial<CreateGalleryInput> & { coverPhotoId?: string }) =>
|
||||
fetchApi<{ gallery: PhotoGallery }>(`/api/photos/galleries/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
deleteGallery: (id: string) =>
|
||||
fetchApi<{ message: string }>(`/api/photos/galleries/${id}`, { method: 'DELETE' }),
|
||||
|
||||
rotateShareToken: (id: string) =>
|
||||
fetchApi<{ gallery: PhotoGallery }>(`/api/photos/galleries/${id}/share-token`, {
|
||||
method: 'POST',
|
||||
}),
|
||||
|
||||
uploadPhoto: async (galleryId: string, file: File) => {
|
||||
const formData = new FormData();
|
||||
formData.append('files', file);
|
||||
|
||||
// Auth rides on the session cookie (sent same-origin automatically)
|
||||
const res = await fetch(`${API_BASE}/api/photos/galleries/${galleryId}/photos`, {
|
||||
method: 'POST',
|
||||
credentials: API_BASE ? 'include' : 'same-origin',
|
||||
body: formData,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({ error: 'Upload failed' }));
|
||||
throw new Error(errorData.error || 'Upload failed');
|
||||
}
|
||||
return res.json() as Promise<{ photos: Photo[] }>;
|
||||
},
|
||||
|
||||
/**
|
||||
* Upload with byte-level progress (0..1). fetch() cannot report upload
|
||||
* progress, so this uses XMLHttpRequest; used by the admin uploader panel.
|
||||
*/
|
||||
uploadPhotoWithProgress: (
|
||||
galleryId: string,
|
||||
file: File,
|
||||
onProgress: (fraction: number) => void
|
||||
) =>
|
||||
new Promise<{ photos: Photo[] }>((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', `${API_BASE}/api/photos/galleries/${galleryId}/photos`);
|
||||
// Auth rides on the session cookie; XHR sends same-origin cookies by
|
||||
// default, withCredentials is only needed for a cross-origin API_BASE.
|
||||
if (API_BASE) xhr.withCredentials = true;
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable && e.total > 0) onProgress(e.loaded / e.total);
|
||||
};
|
||||
xhr.onload = () => {
|
||||
try {
|
||||
const body = JSON.parse(xhr.responseText || '{}');
|
||||
if (xhr.status >= 200 && xhr.status < 300) resolve(body);
|
||||
else reject(new Error(body.error || `Upload failed (${xhr.status})`));
|
||||
} catch {
|
||||
reject(new Error(`Upload failed (${xhr.status})`));
|
||||
}
|
||||
};
|
||||
xhr.onerror = () => reject(new Error('Network error during upload'));
|
||||
xhr.onabort = () => reject(new Error('Upload cancelled'));
|
||||
const formData = new FormData();
|
||||
formData.append('files', file);
|
||||
xhr.send(formData);
|
||||
}),
|
||||
|
||||
reorderPhotos: (galleryId: string, photoIds: string[]) =>
|
||||
fetchApi<{ message: string }>(`/api/photos/galleries/${galleryId}/order`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ photoIds }),
|
||||
}),
|
||||
|
||||
deletePhoto: (photoId: string) =>
|
||||
fetchApi<{ message: string }>(`/api/photos/photos/${photoId}`, { method: 'DELETE' }),
|
||||
|
||||
retryPhoto: (photoId: string) =>
|
||||
fetchApi<{ photo: Photo }>(`/api/photos/photos/${photoId}/retry`, { method: 'POST' }),
|
||||
|
||||
// Viewer (anonymous or member token; share token via query param)
|
||||
getPublicGalleries: () =>
|
||||
fetchApi<{ galleries: PhotoGallery[] }>('/api/photos/public/galleries'),
|
||||
|
||||
getPublicGallery: (slug: string, token?: string) => {
|
||||
const query = token ? `?token=${encodeURIComponent(token)}` : '';
|
||||
return fetchApi<{ gallery: PhotoGallery; photos: Photo[] }>(
|
||||
`/api/photos/public/galleries/${encodeURIComponent(slug)}${query}`
|
||||
);
|
||||
},
|
||||
|
||||
/** Newest gallery linked to an event; backs /events/[slug]/gallery. */
|
||||
getEventGallery: (eventSlug: string, token?: string) => {
|
||||
const query = token ? `?token=${encodeURIComponent(token)}` : '';
|
||||
return fetchApi<{ gallery: PhotoGallery; photos: Photo[] }>(
|
||||
`/api/photos/public/events/${encodeURIComponent(eventSlug)}/gallery${query}`
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -105,30 +105,20 @@ export const ticketsApi = {
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
manualCreate: (data: {
|
||||
eventId: string;
|
||||
firstName: string;
|
||||
lastName?: string;
|
||||
email: string;
|
||||
phone?: string;
|
||||
preferredLanguage?: 'en' | 'es';
|
||||
adminNote?: string;
|
||||
}) =>
|
||||
fetchApi<{ ticket: Ticket; payment: Payment; message: string }>('/api/tickets/admin/manual', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
guestCreate: (data: {
|
||||
// Unified add-attendee endpoint behind the single Add Ticket modal
|
||||
// (paid = confirmation + QR, unpaid = pay link + door collection, guest = free comp)
|
||||
adminAdd: (data: {
|
||||
eventId: string;
|
||||
type: 'paid' | 'unpaid' | 'guest';
|
||||
firstName: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
preferredLanguage?: 'en' | 'es';
|
||||
checkinNow?: boolean;
|
||||
adminNote?: string;
|
||||
}) =>
|
||||
fetchApi<{ ticket: Ticket; payment: Payment; message: string }>('/api/tickets/admin/guest', {
|
||||
fetchApi<{ ticket: Ticket; payment: Payment; message: string }>('/api/tickets/admin/add', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
|
||||
@@ -18,8 +18,9 @@ export interface Event {
|
||||
bannerUrl?: string;
|
||||
externalBookingEnabled?: boolean;
|
||||
externalBookingUrl?: string;
|
||||
bookedCount?: number;
|
||||
availableSeats?: number;
|
||||
bookedCount?: number; // paid seats (confirmed + checked_in)
|
||||
claimedCount?: number; // "I've paid" claims awaiting admin verification (hold seats)
|
||||
availableSeats?: number; // capacity - booked - claimed; the server-authoritative number
|
||||
isFeatured?: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -52,6 +53,7 @@ export interface Ticket {
|
||||
qrCode: string;
|
||||
adminNote?: string;
|
||||
isGuest?: boolean;
|
||||
paymentStatus?: 'paid' | 'unpaid' | 'comp';
|
||||
createdAt: string;
|
||||
event?: Event;
|
||||
payment?: Payment;
|
||||
@@ -69,6 +71,8 @@ export interface TicketValidationResult {
|
||||
attendeeEmail?: string;
|
||||
attendeePhone?: string;
|
||||
status: string;
|
||||
paymentStatus?: 'paid' | 'unpaid' | 'comp';
|
||||
amountDue?: number;
|
||||
checkinAt?: string;
|
||||
checkedInBy?: string;
|
||||
};
|
||||
@@ -221,7 +225,10 @@ export interface DashboardData {
|
||||
totalEvents: number;
|
||||
totalTickets: number;
|
||||
confirmedTickets: number;
|
||||
/** Checkouts opened but never paid nor claimed — informational, holds no seat */
|
||||
pendingPayments: number;
|
||||
/** Customer says they paid; needs admin verification — actionable */
|
||||
awaitingApprovalPayments: number;
|
||||
totalRevenue: number;
|
||||
newContacts: number;
|
||||
totalSubscribers: number;
|
||||
@@ -432,6 +439,9 @@ export interface UserSession {
|
||||
ipAddress?: string;
|
||||
lastActiveAt: string;
|
||||
createdAt: string;
|
||||
expiresAt?: string;
|
||||
/** True for the session backing the current request. */
|
||||
current?: boolean;
|
||||
}
|
||||
|
||||
export interface DashboardSummary {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createAuthClient } from 'better-auth/react';
|
||||
import { magicLinkClient, adminClient, inferAdditionalFields } from 'better-auth/client/plugins';
|
||||
|
||||
// Better Auth client. Sessions are httpOnly cookies set by the backend; with
|
||||
// NEXT_PUBLIC_API_URL unset everything is same-origin through the Next.js
|
||||
// rewrites (see next.config.js), so cookies flow automatically.
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: process.env.NEXT_PUBLIC_API_URL || '',
|
||||
plugins: [
|
||||
magicLinkClient(),
|
||||
adminClient(),
|
||||
inferAdditionalFields({
|
||||
user: {
|
||||
phone: { type: 'string', required: false },
|
||||
languagePreference: { type: 'string', required: false },
|
||||
rucNumber: { type: 'string', required: false },
|
||||
isClaimed: { type: 'boolean', required: false },
|
||||
accountStatus: { type: 'string', required: false },
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
@@ -205,3 +205,33 @@ export function getTpagoLink(
|
||||
const key = (count <= 1 ? 'tpagoLink' : `tpagoLink${count}`) as keyof TpagoLinkConfig;
|
||||
return config[key] || config.tpagoLink || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spots left for an event, trusting the server's `availableSeats` (which uses
|
||||
* the same seat-holding formula the booking API enforces: paid + claimed
|
||||
* seats count, abandoned pending bookings don't). Falls back to deriving it
|
||||
* from the counts for older API responses.
|
||||
*/
|
||||
export function eventSpotsLeft(event: {
|
||||
capacity: number;
|
||||
bookedCount?: number;
|
||||
claimedCount?: number;
|
||||
availableSeats?: number;
|
||||
}): number {
|
||||
if (typeof event.availableSeats === 'number') {
|
||||
return Math.max(0, event.availableSeats);
|
||||
}
|
||||
return Math.max(
|
||||
0,
|
||||
(event.capacity ?? 0) - (event.bookedCount ?? 0) - (event.claimedCount ?? 0)
|
||||
);
|
||||
}
|
||||
|
||||
export function isEventSoldOut(event: {
|
||||
capacity: number;
|
||||
bookedCount?: number;
|
||||
claimedCount?: number;
|
||||
availableSeats?: number;
|
||||
}): boolean {
|
||||
return eventSpotsLeft(event) <= 0;
|
||||
}
|
||||
|
||||
@@ -3,16 +3,24 @@ import { NextRequest, NextResponse } from 'next/server';
|
||||
/**
|
||||
* Defense-in-depth guard for authenticated areas.
|
||||
*
|
||||
* Auth tokens live in localStorage (not readable here), so we rely on a lightweight
|
||||
* `spanglish-auth` cookie set alongside login. The API remains the authoritative gate;
|
||||
* this only keeps unauthenticated visitors from loading the admin/dashboard JS shell.
|
||||
* Auth is a Better Auth httpOnly session cookie, which IS visible to this
|
||||
* server-side middleware (unlike client JS). The API remains the authoritative
|
||||
* gate — cookie presence is not validated here; this only keeps clearly
|
||||
* unauthenticated visitors from loading the admin/dashboard JS shell.
|
||||
*/
|
||||
const SESSION_COOKIES = [
|
||||
'__Secure-spanglish.session_token', // production (useSecureCookies)
|
||||
'spanglish.session_token', // development
|
||||
];
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
if (pathname.startsWith('/admin') || pathname.startsWith('/dashboard')) {
|
||||
const hasAuthCookie = request.cookies.get('spanglish-auth')?.value === '1';
|
||||
if (!hasAuthCookie) {
|
||||
const hasSessionCookie = SESSION_COOKIES.some(
|
||||
(name) => !!request.cookies.get(name)?.value
|
||||
);
|
||||
if (!hasSessionCookie) {
|
||||
const loginUrl = new URL('/login', request.url);
|
||||
loginUrl.searchParams.set('redirect', pathname);
|
||||
return NextResponse.redirect(loginUrl);
|
||||
|
||||
+18
-4
@@ -1,6 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
@@ -18,9 +22,19 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next-build/types/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
|
||||
+13
-1
@@ -4,12 +4,16 @@
|
||||
"private": true,
|
||||
"description": "Spanglish - Language Exchange Event Platform",
|
||||
"scripts": {
|
||||
"dev": "concurrently \"npm run dev:backend\" \"npm run dev:frontend\"",
|
||||
"dev": "concurrently \"npm run dev:backend\" \"npm run dev:frontend\" \"npm run dev:photos\"",
|
||||
"dev:backend": "npm run dev --workspace=backend",
|
||||
"dev:frontend": "npm run dev --workspace=frontend",
|
||||
"dev:photos": "cd photo-api && go run ./cmd/photo-api",
|
||||
"build": "npm run build --workspaces",
|
||||
"build:backend": "npm run build --workspace=backend",
|
||||
"build:frontend": "npm run build --workspace=frontend",
|
||||
"build:photos": "cd photo-api && go build -o bin/photo-api ./cmd/photo-api",
|
||||
"test:photos": "cd photo-api && go test ./...",
|
||||
"migrate:photos": "cd photo-api && go run ./cmd/photo-api migrate",
|
||||
"start": "concurrently \"npm run start:backend\" \"npm run start:frontend\"",
|
||||
"start:backend": "npm run start --workspace=backend",
|
||||
"start:frontend": "npm run start --workspace=frontend",
|
||||
@@ -28,5 +32,13 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "^16.2.10"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.18.20": true,
|
||||
"esbuild@0.25.12": true,
|
||||
"esbuild@0.27.2": true,
|
||||
"better-sqlite3@12.11.1": true,
|
||||
"sharp@0.34.5": true,
|
||||
"argon2@0.44.0": true
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user