diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..fb703df
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,38 @@
+# Dependencies
+node_modules/
+
+# Version control and agent configuration
+.git/
+.github/
+.claude/
+.agents/
+.remember/
+.playwright-mcp/
+skills-lock.json
+
+# Environment and secrets
+.env
+.env*
+.env.local
+
+# Vercel deployment cache
+.vercel/
+
+# Local MCP runtime state, screenshots and audit logs
+.mcp/
+
+# Test output and reports
+test-results/
+playwright-report/
+coverage/
+*.log
+
+# Operating system and temporary artifacts
+.DS_Store
+Thumbs.db
+*.db
+*.sqlite
+data/
+public/img/review/
+research_notes/
+reports/
diff --git a/.env.example b/.env.example
index 3d5a5d8..ccc6992 100644
--- a/.env.example
+++ b/.env.example
@@ -23,19 +23,16 @@ TG_CHAT_ID_TIER_2=
TG_CHAT_ID_TIER_3=
TG_CHAT_ID_EVENTS=
-# Payments (tickets)
-PAYMENT_PROVIDER=razorpay
-RAZORPAY_KEY_ID=
-RAZORPAY_KEY_SECRET=
-RAZORPAY_WEBHOOK_SECRET=
-CASHFREE_APP_ID=
-CASHFREE_SECRET_KEY=
+# Payments
+# ENABLE_LIVE_PAYMENTS gates only the SuperProfile hosted link-out for paid tickets (and labels
+# Telegram Stars membership payments as test/live).
ENABLE_LIVE_PAYMENTS=false
-# Organiser ticket tiers: paid checkout stays OFF unless explicitly set to true (and provider keys exist).
-# Free tiers work without it. Leave unset until an approved payment provider is configured.
-TICKET_CHECKOUT_ENABLED=
+# UPI_CHECKOUT_ENABLED gates every UPI/PhonePe route, page, intent, claim and webhook. Keep false:
+# PhonePe v1 cannot meet the payment verification contract (docs/UPI_PROVIDER_READINESS.md).
+UPI_CHECKOUT_ENABLED=false
-# Membership via SuperProfile (Zapier/Pabbly webhook shared secret, 24+ chars)
+# SuperProfile notifications (tickets + memberships) via Zapier/Pabbly: shared secret sent as X-Webhook-Secret, 24+ chars
+# Endpoint: POST /api/webhooks/superprofile
SUPERPROFILE_WEBHOOK_SECRET=
# Site
@@ -49,10 +46,20 @@ GRIEVANCE_EMAIL=
# Database operations
# Vercel builds migrate only in Production. Set true on Preview ONLY if Preview has its own database.
MIGRATE_ON_PREVIEW=
+# Explicitly proves database isolation in Preview deployments. Required for preview migrations & writes.
+ISOLATED_PREVIEW_DB=
+# Dedicated Preview database connection URL (Preview scope only; never in Production).
+PREVIEW_DATABASE_URL=
# Allow `npm run seed:demo` against a non-local database (a dedicated preview DB only; never production).
SEED_ALLOW_REMOTE=
PG_POOL_MAX=
+# Preview isolation and test safeguards (Preview scope only; never in Production)
+PREVIEW_TELEGRAM_BOT_TOKEN=
+ALLOW_PREVIEW_TELEGRAM=
+ALLOW_PREVIEW_PAID_CHECKOUT=
+PREVIEW_PUBLIC_SITE_URL=
+
# Optional
DISABLE_WEB_ANALYTICS=
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..83b3a46
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,65 @@
+name: CI
+
+# Runs on every PR and on pushes to the long-lived branches. Needs no secrets: tests use a throwaway
+# Postgres service container and stubbed external APIs (no Telegram, SuperProfile or Vercel calls).
+on:
+ pull_request:
+ push:
+ branches: [main, launch-mvp]
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ test:
+ name: lint, unit, e2e
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ services:
+ postgres:
+ image: postgres:16
+ env:
+ POSTGRES_PASSWORD: postgres
+ POSTGRES_DB: sm_test
+ ports:
+ - 5432:5432
+ options: >-
+ --health-cmd "pg_isready -U postgres"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 10
+ env:
+ CI: 'true'
+ PGPASSWORD: postgres
+ TEST_DATABASE_URL: postgres://postgres:postgres@localhost:5432/sm_test
+ E2E_DATABASE_URL: postgres://postgres:postgres@localhost:5432/sm_e2e
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ - run: npm ci
+ - name: Lint
+ run: npm run lint
+ - name: Unit and integration tests (real Postgres)
+ run: npm test
+ - name: Create the e2e database
+ run: psql -h localhost -U postgres -c 'CREATE DATABASE sm_e2e'
+ - name: Install Chromium
+ run: npx playwright install --with-deps chromium
+ - name: Browser tests (Playwright + axe)
+ run: npm run test:e2e
+ - name: Upload Playwright report and screenshots
+ if: failure()
+ uses: actions/upload-artifact@v4
+ with:
+ name: playwright-failure
+ path: |
+ playwright-report/
+ test-results/
+ retention-days: 7
diff --git a/.gitignore b/.gitignore
index 534a810..c2d66f2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,3 +12,10 @@ research_notes/
reports/
test-results/
playwright-report/
+.mcp/
+public/img/review/
+.agents/
+.claude/
+skills-lock.json
+*.code-workspace
+
diff --git a/Dockerfile.mcp b/Dockerfile.mcp
new file mode 100644
index 0000000..273d433
--- /dev/null
+++ b/Dockerfile.mcp
@@ -0,0 +1,26 @@
+# Dockerfile.mcp - Container runtime for StrangersMeetup Control MCP with Playwright Chromium support
+# Base image includes all Linux dependencies for headless Chromium, Firefox and WebKit
+FROM mcr.microsoft.com/playwright:v1.64.1-noble
+
+WORKDIR /app
+
+ENV NODE_ENV=production \
+ PORT=3333 \
+ MCP_PORT=3333 \
+ MCP_HOST=0.0.0.0 \
+ MCP_LOG_STDOUT=true
+
+# Copy package manifests first for efficient layer caching
+COPY package*.json ./
+
+# Install production dependencies
+RUN npm ci
+
+# Copy project source files
+COPY . .
+
+# Expose MCP HTTP port
+EXPOSE 3333
+
+# Start the MCP server
+CMD ["node", "mcp/server.js"]
diff --git a/README.md b/README.md
index 992bb88..53ce477 100644
--- a/README.md
+++ b/README.md
@@ -1,63 +1,117 @@
-# StrangersMeetup
+# NIGHTLIFEZ
-Small hosted meetups, dinners, dating mixers and weekend trips for adults 21+ across Tamil Nadu, Puducherry, Karnataka and Kerala.
+Vibrant social discovery, curated nightlife, supper clubs, weekend trips, and hosted experiences across South India (Chennai, Bangalore, Puducherry, Kochi, Goa, Hyderabad) for adults 21+.
-**The money loop:** real event → visitor books → verified payment (webhook) → booking confirmed → Telegram bot DM → single-use private-group invite → visible in `/admin`.
+**The core money & fulfillment loop:**
+Real event $\to$ Visitor books ticket $\to$ Verified payment webhook $\to$ Booking `confirmed` $\to$ Telegram bot DM $\to$ Single-use private group invite $\to$ QR check-in pass $\to$ Event check-in.
-## Stack
-- Zero-build Node 24. One Vercel function (`api/index.js` → `lib/router.js`) renders pages and serves the API; `public/` holds static CSS/JS/images.
-- Postgres (`pg`), migrations in `migrations/NNN_*.sql`, tracked in `schema_migrations`.
-- Telegram Bot API (webhook), Telegram Login (OIDC) + Mini App `initData`.
-- Payments: Razorpay Payment Links for tickets; Telegram Stars subscriptions for membership. See `docs/PAYMENTS_DECISION.md`.
+---
+
+## Technical Stack
+
+- **Runtime & Compute:** Zero-build Node 24. A single Vercel serverless function (`api/index.js` $\to$ `lib/router.js`) renders all SSR pages and dispatches API endpoints. Static CSS, JS, and brand assets are served from `public/`.
+- **Database:** Serverless Postgres via pooled `pg` (`DATABASE_URL`). Migrations in `migrations/NNN_*.sql` tracked idempotently in `schema_migrations`.
+- **Authentication:** Telegram Login Widget (OIDC SHA-256) and Telegram Mini App (`initData` HMAC-SHA-256). HTTP-only, Secure, SameSite=Lax signed session cookies (`sm_session`) backed by Postgres `user_sessions`.
+- **Bot & Comms:** Telegram Bot API (`@Nightlifez_bot`), webhook-driven notifications, HMAC ticket verification, and single-use chat invite links.
+- **Payments:** External hosted checkout (SuperProfile link-out) and native UPI/PhonePe integrations. Controlled by strict independent feature flags: `ENABLE_LIVE_PAYMENTS=false` and `UPI_CHECKOUT_ENABLED=false` until explicitly approved.
+
+---
+
+## Repository Layout
-## Layout
```
-api/index.js single serverless entry
-lib/router.js route table (pages + API)
-lib/handlers/* HTTP handlers (pages, auth, bookings, payments, telegram, cron, admin, leads)
-lib/services/* domain logic (events, bookings, membership, invites, notifications, refunds, users)
-lib/payments/* PaymentProvider adapters (razorpay, cashfree)
-lib/telegram/* Bot API client, auth validation, bot command routing
-lib/views/* server-rendered HTML (auto-escaping `html` tag)
-migrations/ Postgres migrations (legacy SQLite files kept in migrations/legacy-sqlite/)
-public/ css, js (site.js, admin.js), images
-scripts/ migrate, seed-demo, telegram-setup, lint, make-og
-test/ node:test suites against real Postgres
-docs/ PLATFORM_AUDIT, IMPLEMENTATION_PLAN, ROUTES_AND_ROLES, TEST_STRATEGY, ORGANISER_WIZARD,
- AUDIT, SPEC, ARCHITECTURE, PAYMENTS_DECISION, TELEGRAM_SETUP, RUNBOOK, GO_LIVE
+api/index.js Vercel serverless entry point
+lib/router.js Central HTTP routing table (pages + API)
+lib/config.js Environment variable loading and security assertions
+lib/db.js Postgres connection pooling and query wrapper
+lib/handlers/ HTTP route handlers (pages, auth, bookings, payments, telegram, cron, admin, leads)
+lib/services/ Domain logic (events, bookings, membership, invites, notifications, refunds, users)
+lib/payments/ Payment providers (SuperProfile, UPI/PhonePe)
+lib/telegram/ Bot API client, auth validation, webhook router
+lib/views/ Server-rendered HTML components (escaped html template tag)
+migrations/ Tracked Postgres migration files (003 through 020)
+public/ Static assets: css/, js/ (site.js, admin.js), brand images
+scripts/ Operational scripts (migrate, seed-demo, seed-local, lint, db-reset)
+test/ Automated test suites (unit, integration, security against real Postgres)
+tests/e2e/ Playwright E2E and Axe accessibility test suites
+docs/ Consolidated project documentation (PRODUCT, ARCHITECTURE, DEPLOYMENT, SECURITY, OPERATIONS)
```
-## Local development
+---
+
+## Local Development Setup
+
+### 1. Prerequisites
+- Node.js 24.x
+- PostgreSQL 14+ running locally
+
+### 2. Quickstart
```bash
+# Clone and install dependencies
+git clone https://github.com/Jakuraa/StrangersMeetup.git
+cd StrangersMeetup
npm install
-# Postgres 14+ running locally; create a database
+
+# Create local development database
createdb sm_dev
-cp .env.example .env # fill DATABASE_URL, SESSION_SECRET (32+ chars), CRON_SECRET; DEV_LOGIN=true for a local test login
-npm run migrate # loads .env (only .env — not .env.local)
-npm run seed:demo # optional: 4 sample events, all labelled "Sample"
-npm run seed:local # optional, local DB only: 6 test personas + events in known states (docs/LOCAL_TESTING.md)
-npm run dev # http://localhost:3000 (PORT)
+
+# Configure environment
+cp .env.example .env
+# Edit .env: ensure DATABASE_URL=postgres://localhost/sm_dev and SESSION_SECRET is set
+
+# Run schema migrations
+npm run migrate
+
+# Optional: Seed sample demo events or local test personas
+npm run seed:demo
+npm run seed:local
+
+# Start local server (default: http://localhost:3000)
+npm run dev
```
-Reset a **local** database (refuses remote URLs, Vercel, production, and any DB that is not empty or StrangersMeetup):
+
+### 3. Reset Local Database
+Refuses remote URLs, production databases, and protected branches:
```bash
npm run db:reset:local -- --yes=sm_dev [--seed-demo]
```
-## Tests
+---
+
+## Automated Testing Suite
+
+The test suite runs against real PostgreSQL databases. The test harness drops and recreates the `public` schema on `TEST_DATABASE_URL`.
+
```bash
+# Create dedicated test databases
createdb sm_test
-TEST_DATABASE_URL=postgres://localhost/sm_test npm test
+createdb sm_e2e
+
+# 1. Syntax and JSON linting
npm run lint
-npm run test:e2e # Playwright + axe, desktop and mobile, against a local sm_e2e DB (docs/LOCAL_TESTING.md)
+
+# 2. Unit, integration, and security tests (real Postgres)
+TEST_DATABASE_URL=postgres://localhost/sm_test npm test
+
+# 3. Playwright E2E and accessibility audits
+E2E_DATABASE_URL=postgres://localhost/sm_e2e npm run test:e2e
```
-The suite drops and recreates the `public` schema of `TEST_DATABASE_URL`, so point it at a dedicated test database.
-Tests run the real router against a real Postgres; Telegram and payment HTTP calls are stubbed in `test/helpers.js`. Coverage includes initData validation (bad hash/stale/replay), webhook signatures and idempotency, failed payments, paid ticket → one booking + one invite, capacity race, Stars membership lifecycle and revocation, admin roles/CSRF, form rate limits, secret scan of client assets, and "no fabricated numbers" on an empty DB.
-## Deploy
-Vercel builds with `npm run vercel-build`. Migrations run only in **Production** builds; a Preview build migrates
-only when `MIGRATE_ON_PREVIEW=true`, which must be set only if Preview has its own database. Crons: `vercel.json` → `/api/cron/daily` (Hobby plan: once a day). Health: `GET /api/health`.
+---
+
+## Core Engineering Principles
+
+1. **Zero Fabricated Data:** Every statistic and count rendered on the site is an authentic database query. When no events exist, honest empty states render rather than fabricated fillers.
+2. **Server as Single Source of Truth:** Bookings, ticket allocations, and user entitlements mutate exclusively inside atomic database transactions driven by verified webhooks or server reconciliation. Client redirects never confirm state.
+3. **Defense in Depth:** All client inputs are validated via strict schemas. Mutating requests enforce CSRF tokens. Protected endpoints enforce role-based access controls.
+4. **Zero Client Secret Leakage:** Sensitive keys, API tokens, and credentials exist solely in server environment variables and are never bundled into client scripts.
+
+---
+
+## Documentation Index
-## Rules this codebase keeps
-- No fabricated data: every number is a query; demo rows are `is_demo` and labelled "Sample"; social proof hidden below `SOCIAL_PROOF_MIN`.
-- Server is the source of truth: bookings/entitlements change only in verified webhooks or server-side reconciliation.
-- Secrets only in env vars; `.env.example` lists names only. Live payments off until `ENABLE_LIVE_PAYMENTS=true`.
+- [docs/PRODUCT.md](file:///Users/pradeepjakuraa/strangersmeetup/docs/PRODUCT.md) — Product vision, user personas, event categories, geographic coverage, and end-to-end user journeys.
+- [docs/ARCHITECTURE.md](file:///Users/pradeepjakuraa/strangersmeetup/docs/ARCHITECTURE.md) — System architecture, database schema, state machines, and API specifications.
+- [docs/DEPLOYMENT.md](file:///Users/pradeepjakuraa/strangersmeetup/docs/DEPLOYMENT.md) — Vercel production hosting, Neon Postgres configuration, environment variables, and migration gates.
+- [docs/SECURITY.md](file:///Users/pradeepjakuraa/strangersmeetup/docs/SECURITY.md) — Security policies, authentication mechanics, payment guards, privacy controls, and vulnerability disclosure.
+- [docs/OPERATIONS.md](file:///Users/pradeepjakuraa/strangersmeetup/docs/OPERATIONS.md) — Runbooks, Telegram bot configuration, daily crons, refunds, incident management, and secret rotation.
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ccb331a..b21d1be 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -1,72 +1,129 @@
-# ADR-001: Launch architecture — single Node router on Vercel + Postgres, webhook-driven state
-
-**Status:** Accepted · **Date:** 2026-10-26 · **Deciders:** engineering; owner informed
-
-## Context
-- Existing app: zero-build static HTML + 9 Node functions, data in ephemeral SQLite (`/tmp`) — not viable (AUDIT P0-1).
-- Vercel **Hobby** plan: crons at most daily; non-commercial terms (Pro needed before live money).
-- Needs: SEO-rendered event pages, one money loop, Telegram webhook bot, admin, strict idempotency.
-- Small team, no build pipeline today, Node 24.
-
-## Decision
-1. **Keep zero-build.** All server code is one Vercel function `api/index.js` → `lib/router.js`. `vercel.json` rewrites `/api/*`, `/events/*`, `/trips/*`, `/admin*`, city pages, `sitemap.xml` to it. Static CSS/JS/images served from `public/`. `server.js` runs the same router locally.
-2. **Postgres** via `pg` Pool (`DATABASE_URL`, Neon/Supabase from Vercel Marketplace). Tracked migrations (`schema_migrations`) run by `npm run migrate` (and in the Vercel Production build; previews only with `MIGRATE_ON_PREVIEW=true`). No SQLite anywhere.
-3. **Server is source of truth.** Booking/entitlement transitions happen only inside webhook handlers or crons, in one DB transaction, after signature verification and `webhook_events` insert (unique) for idempotency.
-4. **Side effects after commit** via a `notifications` outbox row (DM + invite). Sent inline right after commit; failures retried by cron. Invite failures are a KPI.
-5. **Holds expire lazily**: capacity query counts `pending_payment` only while `hold_expires_at > now()`; daily cron flips stale holds to `cancelled` (Hobby constraint). On Pro, cron frequency can increase with no code change.
-6. **Sessions**: HMAC-signed cookie (`sm_session`, httpOnly, Secure, SameSite=Lax, 7 days) carrying the user id, a session id and `exp`, backed by a `user_sessions` row (migration 009) so sign-out revokes it server-side; user status and the session row are re-checked per request. CSRF token = HMAC(session, "csrf") sent in `X-CSRF-Token` for all mutating session-authenticated calls.
-7. **Rate limiting** in Postgres (`rate_limits` fixed window). Good enough at launch volume; swap for Upstash if needed.
-
-## Options considered
-| | A: Keep zero-build + one router (chosen) | B: Migrate to Next.js App Router |
-|---|---|---|
-| Complexity | Low — no framework, plain templates | Medium — rewrite all pages into React |
-| Cost | Same | Same |
-| SEO | Server-rendered HTML strings | Excellent |
-| Team familiarity | Matches current code | New |
-| Risk to launch | Low | Higher (full rewrite) |
-
-B is the better long-term frontend but doubles the surface of this phase; revisit after first events run.
-
-## State machines
-
-### Booking
+# NIGHTLIFEZ — Technical Architecture
+
+**Status:** Production Baseline
+**Runtime:** Node.js 24.x on Vercel Serverless Platform
+**Database:** PostgreSQL 16 (Neon Serverless Postgres)
+
+---
+
+## 1. Architectural Overview
+
+NIGHTLIFEZ is built on a high-efficiency, zero-build architecture. All server execution flows through a single serverless function routed by an internal HTTP dispatcher.
+
```
- createCheckout (tx, FOR UPDATE, capacity ok)
- (none) ───────────────────────────────────────────► pending_payment ──(hold expiry / cron)──► cancelled
- │
- verified webhook: paid │ verified webhook: failed → stays pending,
- (in tx, capacity re-check) ▼ payment.status=failed; expires normally
- confirmed ──admin check-in──► checked_in
- │
- finance refund ok ▼
- refunded
- confirmed/pending ──admin cancel──► cancelled (refund issued separately by finance)
+ ┌───────────────────────────┐
+ │ Client Request │
+ │ (Browser / Telegram Mini) │
+ └─────────────┬─────────────┘
+ │
+ ▼
+ ┌───────────────────────────┐
+ │ Vercel Edge │
+ │ - TLS 1.3 Termination │
+ │ - Static Asset Delivery │
+ │ - vercel.json Rewrites │
+ └─────────────┬─────────────┘
+ │
+ ▼
+ ┌───────────────────────────┐
+ │ api/index.js │
+ │ (Serverless Entry Point) │
+ └─────────────┬─────────────┘
+ │
+ ▼
+ ┌───────────────────────────┐
+ │ lib/router.js │
+ │ - Route Matcher & Auth │
+ │ - Rate Limiting & CSRF │
+ │ - Escaped HTML SSR / JSON │
+ └─────────────┬─────────────┘
+ │
+ ┌────────────────┴────────────────┐
+ ▼ ▼
+ ┌─────────────────────┐ ┌─────────────────────┐
+ │ Neon Postgres │ │ Telegram Bot API │
+ │ - Pooled Connections│ │ - Webhooks │
+ │ - Advisory Locks │ │ - Private Invites │
+ │ - Outbox Pattern │ │ - Check-in Passes │
+ └─────────────────────┘ └─────────────────────┘
```
-Late payment (hold expired) → if capacity still free: confirm; else booking `cancelled`, payment `paid`, `notifications(kind=refund_needed)` + admin alert. Never silently keep money.
-### Payment
-`created → paid | failed`, `paid → refunded`. Unique `(provider, provider_txn_id)`.
+---
+
+## 2. Core Components
+
+### A. Serverless Entry & Routing (`api/index.js`, `lib/router.js`)
+- **Zero-Build Pipeline:** No transpilation, bundling, or Webpack overhead. Node.js runs native ESM modules directly.
+- **Route Matching:** Clean URL pattern matching supporting parameter extraction (`/events/:slug`, `/trips/:slug`, `/admin/events/:id`).
+- **Template Rendering (`lib/views/`):** Pure server-side rendering using an auto-escaping tagged template literal (`html` tag), preventing Cross-Site Scripting (XSS) at the templating layer.
+
+### B. Database Layer & Migration Policy (`lib/db.js`, `scripts/migrate.js`)
+- **Connection Management:** `pg.Pool` with TLS support, keepalives, and connection pooling optimized for serverless execution.
+- **Idempotent Migrations:** Numbered SQL migration files (`migrations/003_*.sql` through `020_*.sql`) tracked in the `schema_migrations` table.
+- **Concurrency Protection:** Migrations acquire a PostgreSQL advisory lock (`pg_advisory_lock(839201948)`) before running, guaranteeing zero race conditions even during concurrent deployment invocations.
+- **Database Isolation:** Production database hostnames (`ep-dawn-glitter-b4mkwxkl`) are hard-coded into `DEFAULT_BLOCKED_PRODUCTION_ENDPOINTS` in `lib/config.js` to strictly block Preview deployments from connecting to Production storage.
+
+---
-### Entitlement (membership)
+## 3. Finite State Machines
+
+### A. Booking Lifecycle
```
-successful_payment (first) → active (expires_at = subscription_expiration_date)
-successful_payment (renewal, same user+tier) → active, expires_at extended
-user cancels in Telegram → cancelled (keeps access until expires_at)
-cron: now > expires_at → expired → revoke (ban+unban in tier chat) → revoked
-admin revoke → revoked
+ createCheckout (Capacity Lock in Tx)
+ (None) ──────────────────────────────────────────► pending_payment
+ │
+ │ Hold expires (15 min)
+ ▼
+ cancelled
+ │
+ Verified Webhook: Paid │
+ pending_payment ───────────────────────────────┼────────► confirmed
+ │ │
+ │ │ Door Scan
+ │ ▼
+ │ checked_in
+ │ │
+ │ Admin Refund │
+ ▼ ▼
+ refunded ◄─────────┘
```
-Optional `grace` reserved (not used at launch).
+- **Capacity Integrity:** Checkouts check available slots inside a database transaction using `SELECT ... FOR UPDATE` against the event capacity, preventing overselling.
+- **Stale Hold Recovery:** Holds that remain unpaid after 15 minutes are released lazily by queries and swept by the daily cron.
+
+### B. Payment Transaction States
+`created` $\to$ `paid` | `failed` $\to$ `refunded`
+- **Idempotency Guarantee:** Every webhook event is checked against `webhook_events(provider, provider_event_id)` inside a unique constraint check before processing. Duplicate webhooks return `200 OK` with zero side effects.
+
+### C. Telegram Entitlement & Membership States
+`active` $\to$ `cancelled` (user cancels, retains access until `expires_at`) $\to$ `expired` (cron sweeps) $\to$ `revoked` (bot issues ban+unban to kick from chat).
+
+---
+
+## 4. Authentication & Security Architecture
+
+### A. Telegram Mini App Authentication
+- Mini Apps pass an `initData` query string containing user attributes and a cryptographic `hash`.
+- The server validates the signature using `HMAC-SHA-256("WebAppData", bot_token)`.
+- Validates `auth_date` ($\le$ 300 seconds) and enforces nonce checking against replay attacks.
+
+### B. Telegram Login Widget (OIDC)
+- Sign-ins via the Telegram Login Widget generate a SHA-256 HMAC hash verified using `SHA256(bot_token)`.
+
+### C. Session Management (`user_sessions`)
+- Authenticated clients receive an HTTP-only, Secure, SameSite=Lax cookie named `sm_session`.
+- Sessions contain a cryptographic signature verifying user ID, session UUID, and expiration.
+- Sessions are actively cross-referenced against the `user_sessions` database table, enabling immediate server-side revocation on logout or admin ban.
+
+### D. CSRF Mitigation
+- All state-mutating requests (`POST`, `PUT`, `DELETE`) require an `X-CSRF-Token` header.
+- The CSRF token is derived via `HMAC(session_secret, session_id + "csrf")`, ensuring zero token spoofing without active cookies.
-### Invite link
-Created per booking (event chat: `events.telegram_chat_id` or `TG_CHAT_ID_EVENTS`) or entitlement (tier chat). `member_limit=1`, `expire_date=now+24h`. `used_at` set when `chat_member` update shows the user joined via that link.
+---
-## Consequences
-- Easier: one deploy unit, one DB, testable in-process with real Postgres.
-- Harder: HTML templating by hand (escape helper is mandatory; tests assert escaping).
-- Revisit: Next.js migration; queue (Vercel Queues) if notification volume grows; Pro plan cron cadence.
+## 5. Notification & Asynchronous Outbox Pattern
-## Action items
-1. [x] Postgres migrations 003/004 + runner
-2. [ ] Router + pages, auth, bot, providers, admin, crons (phases 3–6)
-3. [ ] Owner: provision Neon via Vercel Marketplace, set env vars, upgrade to Pro before live
+To prevent external network failures (e.g., Telegram API latency) from rolling back critical financial transactions:
+1. When a booking confirms, the database transaction writes a row to the `notifications` outbox table.
+2. The server attempts inline dispatch immediately following transaction commit.
+3. If the Telegram API is unavailable, the notification remains in `pending` status with an incremental retry backoff counter.
+4. Scheduled cron jobs sweep and retry pending notifications automatically.
diff --git a/docs/AUDIT.md b/docs/AUDIT.md
deleted file mode 100644
index 5ddb959..0000000
--- a/docs/AUDIT.md
+++ /dev/null
@@ -1,131 +0,0 @@
-# StrangersMeetup — Phase 0 Audit
-
-Audit date: 2026-10-26 · Auditor: engineering (Claude) · Base commit: `b13d927` (origin/main)
-
-Scope: live site `https://strangersmeetup-virid.vercel.app/`, repo `Jakuraa/StrangersMeetup`, Vercel project `strangersmeetup` (team `satelinkinternet-collabs-projects`).
-
----
-
-## 1. Stack as found
-
-| Layer | Found | Verdict |
-|---|---|---|
-| Frontend | Static HTML in `public/` (10 pages), vanilla JS `public/js/app.js`, one CSS file. Open Sans. | Keep approach (zero-build, fast). Rewrite markup/visuals. |
-| API | Vercel Node functions `api/*.js` (9 files), plus a local `server.js` that mimics routing. Written for a "Hatchable" platform (`hatchable.toml`). | Keep Node functions; consolidate into one router function (Hobby plan limits, shared code). |
-| DB | `lib/db.js` → **SQLite at `/tmp/strangersmeetup.db` on Vercel** (Hatchable Postgres import always fails on Vercel). | **Broken for production.** `/tmp` is per-instance and wiped on cold start: bookings, payments and entitlements are silently lost. Replace with managed Postgres. |
-| Migrations | `001`–`003` in SQLite dialect (`INSERT OR IGNORE`, `BOOLEAN DEFAULT 0`), re-run on every cold start, errors swallowed. | Replace with Postgres migrations + tracked runner. |
-| Bot | No bot. `api/webhook.js` only handles `pre_checkout_query` + `successful_payment`. No commands, no `/start`, no DMs. | Build. |
-| Payments | Telegram Stars membership only (`createInvoiceLink` with `subscription_period`). No ticket payments at all. | Build ticket provider; harden Stars. |
-| Auth | `validateTelegramInitData` exists, no session issued, 24h freshness, no replay protection. | Rebuild. |
-| Tests | `node --test`, 6 files, all against SQLite + "mock Telegram" mode. | Rewrite against Postgres. |
-| Deps | Zero runtime deps except `@vercel/analytics` (added by PR #1). | Add `pg`, `zod`. |
-
-## 2. Vercel
-
-- Linked to GitHub, production branch `main` (domain `strangersmeetup-git-main-…` present). Framework preset "Other", output dir `public`, Node 24.x.
-- Latest deployment `dpl_6pByBy2iTNaSXi4bpcVt6eveB3UT` — READY, production.
-- Runtime errors (7d): none recorded.
-- Deployment protection: Vercel SSO on all deployments except custom domains (previews require Vercel login to view; `strangersmeetup-virid.vercel.app` production alias is public).
-- **Env vars (names only): `Telegram_HTTP_API` (Production only).** Nothing else. Code expects `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`, channel IDs, `APP_SECRET` — none set. This one var is most likely the bot token under a non-standard name; it is not read by any code and not available to Preview.
-- No database integration installed.
-- **Plan: Hobby.** Consequences: (a) cron jobs run at most once per day; (b) Hobby is for non-commercial use per Vercel terms — **upgrade to Pro before live payments** (added to GO_LIVE).
-
-## 3. Live site walkthrough (desktop 1280 + mobile 390)
-
-| Route | Status | Notes |
-|---|---|---|
-| `/` | 200 | Full-screen **age gate overlay on landing** (blocks content; Rule 8 wants landing public). No horizontal overflow at 390px. |
-| `/venue`, `/partner`, `/host` | 200 | Forms post to `/api/inquiries` → stored in ephemeral SQLite (**leads lost**). Collect email + phone (not needed). No rate limit, no honeypot. |
-| `/safety`, `/terms`, `/privacy`, `/billing`, `/community`, `/grievance` | 200 | Placeholder entity "StrangersMeetup Regional Network", grievance email `@strangersmeetup.example.com`. |
-| `/faq`, `/events`, `/trips`, `/events/`, `/admin` | **404** | No event detail pages, no FAQ page, no admin. |
-| `/api/health` | 404 | Missing. |
-| `/favicon.ico` | 404 | Console error on every page. |
-| `/api/analytics` | **400 on every page load** | Front-end sends an event name not in the server allowlist. |
-| `/sitemap.xml`, `robots.txt` | 200 | Point at `strangersmeetup.example.com` (wrong host). Static. |
-| Canonical / OG | — | Canonical `https://strangersmeetup.example.com/`; OG image is an Unsplash stock photo. |
-
-- Video embeds: none found (no dead embeds).
-- `a[href="#"]`: "Open Telegram ↗" in checkout modal.
-- Links to `https://t.me/StrangersMeetupBot` ×4 — **bot not verified to exist / not owned-confirmed.**
-
-## 4. Fabricated / hardcoded data (Rule 1 violations)
-
-| Where | What | Severity |
-|---|---|---|
-| `migrations/002`, `003` seed | **All 15 events invented.** 7 claim to be "Real Events" with `is_demo=0`. | P0 |
-| Event seeds | Pre-filled `tickets_sold` (e.g. 14/24, 17/20, 22/28) → site renders "10 slots remaining", "5 SLOTS LEFT" — **fake scarcity**. | P0 |
-| Event seeds | Invented prices (₹199–₹42,500) while pricing is on hold. | P0 |
-| Event seeds | 6 international/North-East trips (Bali, Vietnam, Sri Lanka, Meghalaya) outside launch region. | P1 |
-| `api/events.js` | Default Unsplash image + "Exact venue disclosed 24 hours prior" privacy copy applied to every event regardless of policy. | P1 |
-| `index.html` + `config/tiers.json` | Hardcoded tier prices (₹149/₹499/₹999, 75/250/500 Stars) and **"Most Popular" decoy badge**. | P0 (pricing) / P1 (decoy) |
-| `config/tiers.json` | Benefits marked "active" that don't exist (priority RSVP, concierge, VIP salons). | P1 |
-| `lib/entitlements.js` | On payment, writes `age_declared=21`, `date_of_birth='2000-01-01'`, `state_code='TN'` for every user — fabricated identity data. | P1 |
-
-## 5. Security findings
-
-| # | Finding | Severity |
-|---|---|---|
-| S1 | **Mock-mode auth bypass**: if `TELEGRAM_BOT_TOKEN` is unset (current state in prod), `validateTelegramInitData` returns `ok:true` for *any* string and invents user `12345678`. | P0 |
-| S2 | **IDOR**: `GET /api/entitlements?telegramUserId=N` returns any user's subscription and private channel invite link, unauthenticated. | P0 |
-| S3 | `POST /api/cancel` cancels any user's subscription by `telegramUserId`, unauthenticated. | P0 |
-| S4 | `POST /api/events` "books" a ticket with no payment and increments `tickets_sold` (read-modify-write race, no lock). | P0 |
-| S5 | Hardcoded fallback HMAC secret `fallback-dev-secret-salt-2026` for invoice payloads when `APP_SECRET` unset (it is unset). Payload HMAC truncated to 64 bits. | P0 |
-| S6 | initData freshness 24h, no replay protection; no session cookie. | P1 |
-| S7 | Webhook stores full raw payloads (`raw_payload_json`) incl. invoice payloads. Error responses echo `err.message`. | P1 |
-| S8 | Webhook always returns 200 on unhandled errors → Telegram won't retry; processing not transactional (member → subscription → payment → entitlement as separate statements). | P0 |
-| S9 | No rate limiting anywhere. No CSRF concept (no sessions). | P1 |
-| S10 | Invite link fallback `https://t.me/StrangersMeetupBot?start=pending_channel_config` is stored as if it were a real invite. | P1 |
-| S11 | `.env.local` holds a `VERCEL_OIDC_TOKEN` (gitignored, not committed — OK). No secrets found in tracked files. | info |
-
-## 6. Event record classification
-
-| id | city | Claimed | Actual classification |
-|---|---|---|---|
-| evt_blr_boardgames_01 | Bengaluru | real (is_demo=0) | **demo (fabricated)** |
-| evt_blr_coffee_02 | Bengaluru | real | **demo (fabricated)** |
-| evt_chn_retro_cinema_03 | Chennai | real | **demo (fabricated)** |
-| evt_chn_neon_mixer_04 | Chennai | real | **demo (fabricated)** |
-| evt_cbe_acoustic_05 | Coimbatore | real | **demo (fabricated)** |
-| evt_koc_sunset_cruise_06 | Kochi | real | **demo (fabricated)** |
-| evt_pdy_coastal_resort_07 | Puducherry | real | **demo (fabricated)** |
-| evt_blr_cubbon_walk_08 | Bengaluru | demo | demo |
-| evt_chn_mylapore_walk_09 | Chennai | demo | demo |
-| evt_trip_meghalaya_10 | Meghalaya | demo | demo, out of region |
-| evt_trip_gokarna_11 | Gokarna (KA) | demo | demo |
-| evt_trip_wayanad_12 | Wayanad (KL) | demo | demo |
-| evt_trip_vietnam_13 / bali_14 / srilanka_15 | International | demo | demo, deferred (international trips out of scope) |
-
-**Real events: 0. Imported: 0. Demo: 15.** No owner-supplied event exists yet (Owner input #4).
-
-## 7. Prioritized issue list
-
-### P0 — blocks the money loop
-1. No persistent database in production (SQLite in `/tmp`). → Managed Postgres + migration runner.
-2. No ticket payment path at all; "booking" is free and unverified. → `PaymentProvider` + Razorpay/Cashfree sandbox + webhook-driven confirmation.
-3. Auth bypass when bot token missing (S1); no sessions. → Strict initData/Login Widget validation, signed httpOnly session.
-4. IDOR on entitlements/invite links and cancel (S2, S3). → Session-scoped endpoints only.
-5. Webhook processing non-transactional, non-retryable (S8); hardcoded fallback secret (S5).
-6. Fabricated events, sold counts, prices, decoy tier (Section 4). → DB-driven, `is_demo` labelled "Sample", prices `tbd`.
-7. No bot: no `/start`, no DMs, no single-use invite delivery for bookings.
-8. Required env vars missing on Vercel; bot token stored under unread name `Telegram_HTTP_API`.
-9. No event detail pages / Book Tickets flow.
-
-### P1 — trust / brand
-10. Neon/teal SaaS look; age-gate overlay on landing; copy over-promises unbuilt features.
-11. Placeholder legal entity / `example.com` emails, canonical, sitemap.
-12. No rate limits, honeypot, validation library; forms collect unnecessary PII (phone, email for leads is acceptable but optional).
-13. Missing `/faq`, `/trust-safety`, `/refunds`, city pages, JSON-LD, OG image, favicon.
-14. `/api/analytics` 400 on every load.
-15. No admin, no audit trail for admin actions.
-16. Vercel Hobby plan → non-commercial + daily crons only.
-
-### P2 — later
-17. Vercel Web Analytics loaded from jsDelivr ESM on every page (fine, but consider removing until consented/needed).
-18. `hatchable.toml` and Hatchable shims are dead weight on Vercel.
-19. International trips, intro double opt-in, Vibe Match, streaks — deferred per spec.
-
-## 8. Decisions taken from this audit
-- Keep zero-build Node + static assets; add server-rendered HTML for SEO pages via one router function.
-- Postgres via `pg`; local/test uses a real Postgres (no SQLite anywhere).
-- Legacy SQLite migrations moved to `migrations/legacy-sqlite/` (never ran against a persistent DB; nothing to preserve). New Postgres baseline starts at `003_…` / `004_…` as specified.
-- Booking hold expiry computed at query time (`hold_expires_at > now()`) so capacity is correct without a 15-minute cron (Hobby constraint); daily cron tidies up.
diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md
new file mode 100644
index 0000000..1dd34ce
--- /dev/null
+++ b/docs/DEPLOYMENT.md
@@ -0,0 +1,111 @@
+# NIGHTLIFEZ — Deployment & Environment Setup
+
+**Platform:** Vercel Serverless Platform
+**Production Domain:** [https://nightlifez.com](https://nightlifez.com)
+**Redirect Domain:** [https://www.nightlifez.com](https://www.nightlifez.com) $\to$ `nightlifez.com` (HTTP 308)
+**Vercel Project:** `jakuraa/strangersmeetup` (`prj_JtY6c5SRSt1NHE5sjSZFZAYwYqaa`)
+**Production Database:** Neon Serverless PostgreSQL (`ep-dawn-glitter-b4mkwxkl`)
+
+---
+
+## 1. Domain & DNS Configuration
+
+The production domain is routed via Cloudflare DNS-only records directly to the Vercel Edge network:
+
+| Record Type | Host | Target Value | Proxy Status | Purpose |
+|---|---|---|---|---|
+| **A** | `@` (apex) | `76.76.21.21` | DNS only (Unproxied) | Directs apex traffic to Vercel Edge |
+| **CNAME** | `www` | `cname.vercel-dns.com` | DNS only (Unproxied) | Enforces permanent HTTP 308 redirect |
+
+- **Edge Certificates:** Managed automatically by Vercel via Let's Encrypt with TLS 1.3 encryption.
+- **HSTS & Security Headers:** Enforced automatically by the application router on all responses.
+
+---
+
+## 2. Production Environment Variables
+
+All secrets are managed exclusively within Vercel's encrypted environment variable store.
+
+| Variable Name | Required Scope | Type / Value Example | Description |
+|---|---|---|---|
+| `DATABASE_URL` | Production & Preview | `postgres://user:pass@host/db?sslmode=require` | Pooled Postgres connection string |
+| `PUBLIC_SITE_URL` | Production | `https://nightlifez.com` | Canonical root domain URL |
+| `SESSION_SECRET` | Production & Preview | 48+ character cryptographic string | Key used to sign session cookies (`sm_session`) |
+| `CRON_SECRET` | Production & Preview | 48+ character random string | Bearer token required to invoke `/api/cron/*` |
+| `TICKET_SECRET` | Production & Preview | 64-character hexadecimal key | HMAC-SHA256 key used to sign door QR passes |
+| `TELEGRAM_BOT_TOKEN` | Production | `123456789:ABC...` | Bot token provided by @BotFather |
+| `TELEGRAM_BOT_USERNAME`| Production | `Nightlifez_bot` | Public handle of the production bot |
+| `TELEGRAM_WEBHOOK_SECRET`| Production | 48+ character cryptographic string | Validates inbound Telegram webhook updates |
+| `SUPERPROFILE_WEBHOOK_SECRET`| Production | 24+ character cryptographic string | Validates SuperProfile payment webhooks |
+| `ADMIN_BOOTSTRAP_TELEGRAM_ID`| Production | Numeric Telegram User ID | Automatically grants initial `super_admin` role |
+| `SUPPORT_EMAIL` | Production | `nightlifezofficial@gmail.com` | Customer-facing support email address |
+| `GRIEVANCE_EMAIL` | Production | `nightlifezofficial@gmail.com` | Statutory grievance contact address |
+| `GRIEVANCE_OFFICER_NAME`| Production | `Grievance Officer` | Official contact name for legal compliance |
+| `LEGAL_ENTITY_NAME` | Production | `NIGHTLIFEZ` | Registered operational legal entity |
+| `ENABLE_LIVE_PAYMENTS`| Production & Preview | `false` | Master kill switch for live payment collection |
+| `UPI_CHECKOUT_ENABLED`| Production & Preview | `false` | Kill switch for native UPI checkout routing |
+
+---
+
+## 3. Database Architecture & Migration Execution
+
+### A. Environment Isolation
+- **Production Endpoint:** `ep-dawn-glitter-b4mkwxkl` (Branch: `production`).
+- **Preview Endpoint:** `ep-green-hall-b47clnq0` (Branch: `preview`).
+- **Safety Rails:** Production endpoint identifiers are strictly registered in `DEFAULT_BLOCKED_PRODUCTION_ENDPOINTS` within `lib/config.js`. If a non-production deployment attempts to bind to the Production database, execution halts immediately with a fatal error.
+
+### B. Migration Pipeline (`scripts/migrate.js`)
+- The build command is mapped in `package.json`:
+ ```bash
+ "vercel-build": "node scripts/migrate.js"
+ ```
+- **Production Builds:** Automatically execute pending migrations (`003` through `020`) sequentially under an advisory lock (`pg_advisory_lock(839201948)`).
+- **Preview Builds:** Automatically skip migrations unless `MIGRATE_ON_PREVIEW=true` is set and the database URL points to a non-production branch.
+
+---
+
+## 4. Release & Deployment Pipeline
+
+```
+ [candidate/production-readiness]
+ │
+ ▼ Pull Request #45 (CI Suite: Lint, Unit, Integration, E2E)
+ [launch-mvp]
+ │
+ ▼ Pull Request #17 (Production Release Gate)
+ [main] ──────► Automatic Vercel Production Build & Deploy
+ │
+ ├─ 1. Advisory Lock Acquired
+ ├─ 2. Migrations 003-020 Executed
+ └─ 3. Atomic Edge Activation
+```
+
+### Promotion Steps:
+1. Candidate branch `candidate/production-readiness` undergoes complete CI verification.
+2. PR #45 merges approved candidate commits into `launch-mvp`.
+3. PR #17 merges `launch-mvp` into `main` upon explicit owner signoff.
+4. Vercel automatically deploys the release to `https://nightlifez.com`.
+
+---
+
+## 5. Post-Deployment Verification Checklist
+
+Immediately following a production deployment:
+
+1. **System Health Endpoint:**
+ ```bash
+ curl -s https://nightlifez.com/api/health
+ # Expected output: {"ok":true,"database":"ok","config":{...}}
+ ```
+2. **Permanent 308 Redirect Verification:**
+ ```bash
+ curl -sI https://www.nightlifez.com
+ # Expected: HTTP/2 308 -> Location: https://nightlifez.com/
+ ```
+3. **Primary Experience Routes:**
+ - Homepage: `https://nightlifez.com/` (200 OK)
+ - Events Feed: `https://nightlifez.com/events` (200 OK)
+ - Contact Page: `https://nightlifez.com/contact` (200 OK)
+ - Trust & Safety: `https://nightlifez.com/trust-safety` (200 OK)
+ - Host Portal: `https://nightlifez.com/become-a-host` (200 OK)
+ - Venue Portal: `https://nightlifez.com/list-your-venue` (200 OK)
diff --git a/docs/GO_LIVE.md b/docs/GO_LIVE.md
deleted file mode 100644
index eff7731..0000000
--- a/docs/GO_LIVE.md
+++ /dev/null
@@ -1,37 +0,0 @@
-# Go-live checklist (owner executes)
-
-Nothing below has been done. Each step needs the owner's decision or credentials.
-
-## 0. Prerequisites
-- [ ] **Vercel Pro** for the team (Hobby is non-commercial; Pro also allows more frequent crons).
-- [ ] **Postgres**: Vercel → Storage / Marketplace → Neon (or Supabase) → connect to project `strangersmeetup` for Production + Preview. This sets `DATABASE_URL`.
-- [ ] Env vars set (Production + Preview) per `.env.example`: `SESSION_SECRET` (`openssl rand -base64 48`), `CRON_SECRET`, `PUBLIC_SITE_URL`, `ADMIN_BOOTSTRAP_TELEGRAM_ID`, `LEGAL_ENTITY_NAME`, `SUPPORT_EMAIL`, `GRIEVANCE_OFFICER_NAME`, `GRIEVANCE_EMAIL`.
-- [ ] Telegram per `docs/TELEGRAM_SETUP.md` (bot, groups, chat ids, OIDC client, `node scripts/telegram-setup.js`). Rename `Telegram_HTTP_API` → `TELEGRAM_BOT_TOKEN`.
-- [ ] Razorpay account activated under an events/ticketing category, **with written confirmation of the category** (see PAYMENTS_DECISION.md); test keys tested end-to-end on Preview first.
-
-## 1. Set final prices
-- [ ] Ticket prices: Admin → Events → Edit → "Ticket price ₹".
-- [ ] Membership Stars amounts (≤ 10,000): Admin → Membership tiers (super_admin).
-
-## 2. Load the first real event
-- [ ] Admin → Events → New event (draft) → fill venue, refund policy, inclusions, chat id if per-event → Preview → Publish.
-- [ ] Archive sample events: Admin → Events → Archive each "Sample" row (or `UPDATE events SET status='archived' WHERE is_demo;`).
-- [ ] Add owner-authorised photos/reviews: Admin → Media → Add → Authorise → Show.
-
-## 3. Switch to live keys
-- [ ] Razorpay live mode → generate live keys → create a live webhook to `https:///api/payments/webhook/razorpay` with events `payment_link.paid`, `payment_link.expired`, `payment_link.cancelled`, `payment.failed`, `refund.processed`.
-- [ ] Production env: `RAZORPAY_KEY_ID=rzp_live_…`, `RAZORPAY_KEY_SECRET`, `RAZORPAY_WEBHOOK_SECRET` (live), **`ENABLE_LIVE_PAYMENTS=true`**. (The app refuses live keys while the flag is false, and test keys while it is true.)
-- [ ] Production must not have `TELEGRAM_TEST_ENV=true`.
-
-## 4. One real ₹ transaction (owner)
-- [ ] Create a hidden-capacity test event priced ₹1–₹10, publish, book it yourself on the production URL.
-- [ ] Verify: Razorpay dashboard shows the payment; `/api/health` ok; booking `confirmed` in Admin; bot DM arrived; invite link joins the events group; Overview KPI "Paid (live)" updated.
-- [ ] **Refund it** from Admin → Bookings & payments; verify refund in Razorpay, booking `refunded`, DM received.
-- [ ] Cancel/archive the test event.
-
-## 5. Promote to production
-- [ ] Merge the `launch-mvp` PR to `main` (Vercel deploys production from `main`) — only after steps 0–4 on Preview.
-- [ ] Re-run `node scripts/telegram-setup.js` with production `PUBLIC_SITE_URL`.
-
-## 6. Domain / DNS (only with explicit approval)
-- [ ] Add the custom domain in Vercel, set DNS records at the registrar, update `PUBLIC_SITE_URL`, Telegram Login allowed URLs, Razorpay webhook URL and website URL, then re-run the setup script.
diff --git a/docs/IMPLEMENTATION_PLAN.md b/docs/IMPLEMENTATION_PLAN.md
deleted file mode 100644
index ebeb225..0000000
--- a/docs/IMPLEMENTATION_PLAN.md
+++ /dev/null
@@ -1,118 +0,0 @@
-# Implementation plan
-
-Branch: `feature/platform-v2` from `origin/launch-mvp` (`fb73c31`). One PR per milestone into `launch-mvp`
-(stacked). Nothing goes to `main` until the owner approves PR #2. Status as of 2026-10-29: **M0 and M1 done**.
-
-```
-main (b13d927, PR #1)
- └── launch-mvp (fb73c31, PR #3) ← PR #2 (draft) into main = production
- └── feature/platform-v2 → PRs per milestone into launch-mvp
-```
-
-## Decisions (approved by the owner, 2026-10-28)
-1. **Organiser publishing:** an organiser's *first* event goes to admin review; later events publish directly;
- a platform setting can force review for everyone.
-2. **Event staff:** assigned per event by the organiser (or `event_manager`/`super_admin`).
-3. **Migrations on Vercel:** production builds only; a preview migrates only with `MIGRATE_ON_PREVIEW=true` and its own DB.
-4. **Tooling:** Playwright and `@axe-core/playwright` as devDependencies only.
-
-## Standing constraints
-No merges, production deploys, DNS changes, env changes on Vercel, or live payments without explicit approval.
-Razorpay (suspended) and Cashfree (KYC pending) stay disabled; paid tiers remain draft-only. No fabricated data;
-demo/seed rows are always marked. Existing tests are never weakened or removed.
-
----
-
-## M0 — Repository and PR audit ✅
-- **Changed:** `docs/PLATFORM_AUDIT.md`, `docs/IMPLEMENTATION_PLAN.md`, `docs/ROUTES_AND_ROLES.md`, `docs/TEST_STRATEGY.md`, `.env.example`, `README.md`.
-- **Acceptance:** docs match the code with `file:line` evidence; status legend applied. Met.
-
-## M1 — Safety rails ✅
-- **Changed:** `lib/db.js` (`migrationPolicy`, `isLocalDatabaseUrl`), `scripts/migrate.js`, `scripts/seed-guard.js`,
- `scripts/seed-demo.js`, `scripts/db-reset-local.js`, `migrations/009_user_sessions.sql`, `lib/session.js`,
- `lib/handlers/auth.js`, `lib/router.js`, `lib/handlers/cron.js`, `public/js/site.js`, `lib/services/bookings.js`,
- `lib/services/insights.js`, `test/safety.test.js`.
-- **Migration:** `009` additive (`user_sessions`). Effect: cookies issued before it stop working; everyone signs in once.
-- **Risks / rollback:** a preview without `MIGRATE_ON_PREVIEW` now builds against an unmigrated schema if it has a DB
- of its own (intended: set the flag). Rollback = revert the commits; `user_sessions` can stay (unused).
-- **Tests:** 13 new (`test/safety.test.js`); the amount and fill tests were confirmed to fail on the old code.
-- **Acceptance:** 127/127 tests, lint clean, scripts smoke-tested on a scratch DB. Met.
-- **Deferred:** `__path` tightening in `lib/router.js` (needs the function's `req.url` confirmed on a preview).
-
-## M8 (moved forward) — Seed v2 and local personas
-- **Files:** `scripts/seed-local.js`, `scripts/seed-guard.js`, `lib/handlers/auth.js` (dev persona login),
- `lib/views/pages.js` (persona picker on `/signin`, local only), `docs/MANUAL_UAT_GUIDE.md`.
-- **Data:** synthetic users in a reserved Telegram id range (`9_100_000_000+`), names prefixed "Test", every event
- `is_demo=true`; organisers ×2, admin, staff, guests; draft/published/completed/cancelled events; free and
- disabled-paid tiers; pending approvals; confirmed, cancelled and checked-in bookings; sold-out and low-inventory
- events; analytics rows across 7/30/90-day windows.
-- **Guards:** same as the dev login (no Vercel, `DEV_LOGIN=true`, not production) **plus** a local `DATABASE_URL`.
-- **Tests:** persona login 404 on Vercel / in production / with a remote DB; seed is idempotent; seed refuses remote.
-- **Acceptance:** `npm run seed:local` twice gives the same counts; each persona lands on its dashboard.
-
-## M3 — Authentication and role enforcement
-- **Files:** `migrations/010_identities.sql` (`user_identities(provider, subject, user_id)`, `telegram_user_id`
- nullable, backfill Telegram identities), `lib/auth/google.js` (OIDC code flow, PKCE, state, nonce, `iss`/`aud`/`exp`
- checks against Google's JWKS), `lib/handlers/auth.js`, `lib/services/users.js`, settings UI for linked accounts.
-- **Rules:** no automatic linking by email; linking only from a signed-in session with fresh re-auth; unlinking the
- last identity is refused; clear "Google sign-in not configured" state when credentials are absent.
-- **Risks:** every `telegram_user_id` lookup (admin bootstrap, grants, bot) must tolerate users without Telegram;
- bot DMs only for users with a Telegram identity.
-- **Tests:** state/nonce/PKCE tampering, wrong audience, expired token, replay, link hijack attempt, duplicate subject.
-- **Blocked on:** Google OAuth client id/secret and registered callbacks.
-
-## M2 — Design system and public experience
-- **Files:** `public/css/site.css` (spacing/type tokens, 4 breakpoints, night surface), `public/css/components.css`
- (dialog, toast, badge, state blocks, ticket pass, app shell, stacked tables), `public/js/ui.js` (dialog/toast),
- `lib/views/*`, `public/js/site.js` (nav focus, Escape, link close), image variants (`event_images` thumbnails + `srcset`).
-- **Out of scope:** new animation library; changing brand colours.
-- **Tests:** E2E overflow check at 320/390/768/1280; axe (no serious/critical); keyboard nav; reduced-motion run.
-- **Acceptance:** screenshots reviewed at mobile + desktop; no `confirm()/alert()/prompt()` left in user flows.
-
-## M4 — Guest portal
-- **Files:** `lib/views/member.js`, `public/js/member.js`, `lib/services/bookings.js` (cancel; refund-due flag for paid),
- `migrations/011_tickets.sql` (`bookings.ticket_secret`, `checked_in_count`), QR rendering (vendored, MIT, no CDN).
-- **Rules:** a cancellation releases the seat in the same transaction; paid cancellations never auto-refund while
- payments are off — they are flagged for finance; ticket token = HMAC(booking id, ticket secret), rotated on cancel.
-- **Tests:** cancel own vs other's (404), cancel twice, cancel after check-in refused, QR token tamper, export
- contains only the user's data, deletion anonymises and keeps financial records.
-- **Acceptance:** Journey A (`docs/TEST_STRATEGY.md`) passes on mobile and desktop.
-
-## M5 — Organiser workspace
-- **Files:** `lib/views/organiser.js` (app shell, overview, event tabs), `public/js/organiser.js`,
- `lib/services/organiser.js` (validated edit of published events, review status), `lib/services/staff.js`,
- `migrations/012_staff_review.sql` (`event_staff`, `events.review_status`, `organiser_first_event_reviewed`),
- scanner page with `BarcodeDetector` + typed-code fallback; `vercel.json` `camera=(self)` on the scan route only.
-- **Rules:** edits that change date, venue or tiers after bookings exist require confirmation and notify guests;
- capacity cannot drop below seats taken; first event goes to `pending_review`.
-- **Tests:** full cross-organiser denial set, staff scope, duplicate scan 409, wrong-event ticket refused, revoked
- organiser loses access, CSRF on every organiser write.
-- **Acceptance:** Journey B passes; scanner usable one-handed at 390 px.
-
-## M6 — Admin console
-- **Files:** `lib/views/admin.js`, `public/js/admin.js` (sections, pagination, search, detail drawers),
- `lib/handlers/admin.js` (users, sessions revoke, review queue, health), audit viewer with readable diffs.
-- **Tests:** the full role matrix in `docs/ROUTES_AND_ROLES.md` (allowed + denied per row), self-promotion attempts,
- audit entry per sensitive write without secrets or unnecessary personal data.
-- **Acceptance:** Journey C passes; every destructive action uses a confirmation dialog naming the target.
-
-## M7 — Analytics and reporting
-- **Files:** `lib/services/analytics.js`, `migrations/013_analytics_indexes.sql` (`analytics_events(event_id, name, at)`),
- organiser and admin views, CSV export (organiser: own events, no guest PII beyond what they already see).
-- **Definitions (documented in the UI):** views and unique visitors from first-party `analytics_events`
- (cookie-less visitor id); conversion = confirmed bookings ÷ unique event-page visitors in the window; gross ticket
- value only from `payments.status='paid'` (none while payments are off); free RSVPs counted separately.
-- **Tests:** every number equals a hand-computed value from seeded rows; empty windows show 0 vs "Unavailable".
-
-## M9 — End-to-end, accessibility, security, polish
-- Playwright projects: Chromium desktop, iPhone 14, 320 px, iPad, WebKit. Journeys A–D. axe + manual keyboard pass.
-- Security review pass (`docs/PLATFORM_AUDIT.md` items re-checked), Lighthouse on a preview, screenshot review.
-
-## M10 — Release readiness
-- Honest report: verified vs unverified, open risks, owner actions. Draft PR updates only — no merge.
-
-## Activating a payment provider later (documented, not done)
-All of: provider account approved for this merchant category in writing; test keys + webhook secret in Vercel
-Preview; `TICKET_CHECKOUT_ENABLED=true` on Preview only; sandbox E2E (book → webhook → confirmed → refund) passes on
-a preview; owner approval; then live keys with `ENABLE_LIVE_PAYMENTS=true` on Production. Event tickets are never
-routed through a membership/digital-goods product.
diff --git a/docs/LOCAL_TESTING.md b/docs/LOCAL_TESTING.md
deleted file mode 100644
index 1495321..0000000
--- a/docs/LOCAL_TESTING.md
+++ /dev/null
@@ -1,145 +0,0 @@
-# Local testing: personas, seed data and browser tests
-
-Everything here runs **only on your machine against a local Postgres**. None of it can touch production:
-
-| Safeguard | Where |
-|---|---|
-| `npm run seed:local` refuses `NODE_ENV=production`, `VERCEL_ENV=production`, any Vercel build, and any `DATABASE_URL` that is not `localhost`/loopback/a Unix socket. There is no remote override (unlike `seed:demo`'s `SEED_ALLOW_REMOTE`). | `scripts/seed-guard.js` (`kind: 'local'`) |
-| Persona sign-in (`POST /api/auth/dev`) returns **404** unless all of: not on Vercel, `DEV_LOGIN=true`, not production (`NODE_ENV`/`VERCEL_ENV`), and a local `DATABASE_URL`. The `/signin` picker is rendered under the same check. | `lib/dev-personas.js` → `devLoginEnabled()` |
-| Persona sign-in never creates accounts; it only signs in users that `seed:local` created (409 `not_seeded` otherwise). | `lib/handlers/auth.js` |
-| The seed deletes and recreates only persona-owned rows (reserved Telegram ids `9100000000–9100999999`) and `local-*` demo events. | `scripts/seed-local.js` |
-| The browser suite refuses to start unless `E2E_DATABASE_URL` is local, and starts the server with an explicit environment (`SKIP_DOTENV=true`), so a real `DATABASE_URL` in `.env` is never used. | `e2e/env.js` |
-
-**Google OAuth is not configured and paid checkout is disabled.** Nothing here sets Google client ids or payment
-keys; the browser suite runs with `ENABLE_LIVE_PAYMENTS=false`, so paid tickets show "Online booking not available yet"
-and can never be bought. Telegram sign-in is replaced locally by the persona picker below.
-
-## 1. One-time setup
-```bash
-npm install # includes dev-only @playwright/test and @axe-core/playwright
-npx playwright install chromium # browser for the e2e suite
-createdb sm_dev # your local dev database
-createdb sm_test # unit/integration suite (its schema is dropped on every run; any dedicated local name works, e.g. sm_pv2_test)
-createdb sm_e2e # browser suite (re-seeded on every run)
-```
-
-## 2. Start the app with personas
-```bash
-export DATABASE_URL=postgres://localhost/sm_dev
-export SESSION_SECRET=local-dev-session-secret-at-least-32-chars
-export DEV_LOGIN=true
-npm run migrate # apply migrations
-npm run seed:local # personas + events; safe to re-run, resets persona data each time
-npm run dev # http://localhost:3000 → /signin shows "Local test personas"
-```
-(Or put the three variables in `.env`; `npm run migrate`, `seed:local` and `dev` all read it. Keep that `.env`
-pointed at a local database: the browser suite never reads `.env`, and must never be given production credentials.)
-
-**`npm run seed:local` safety conditions** (all checked before anything is migrated or written; see the table above):
-`DATABASE_URL` must be `localhost`, a loopback address or a Unix socket; `NODE_ENV` and `VERCEL_ENV` must not be
-`production`; it must not run inside a Vercel build. There is no override. It only deletes and recreates persona-owned
-rows, `local-*` events and leads tagged `payload.seed = 'local'`, so other local data is left alone.
-
-## 3. Personas
-
-| Key | Name | Role | Lands on | Can | Cannot |
-|---|---|---|---|---|---|
-| `guest` | Test Guest Asha | member | `/me` | book free tickets; see the private venue on own confirmed bookings | see others' bookings; organiser tools; admin |
-| `guest2` | Test Guest Bala | member | `/me` | own bookings and pending request | book the sold-out event; see `guest`'s booking or any private venue it has not booked |
-| `organiser` | Test Organiser Chitra | organiser (`users.organiser_enabled`) | `/organiser` | create/publish events; own guest lists; approve requests | another organiser's events or drafts; admin |
-| `organiser2` | Test Organiser Dev | organiser | `/organiser` | own events and draft | organiser 1's events, requests, drafts |
-| `staff` | Test Staff Esha | event staff = admin role `support` | `/admin` | attendee lists, bookings list, check-in | event edits, refunds, roles, insights, audit, organiser tools |
-| `admin` | Test Admin Farah | `super_admin` | `/admin` | everything, incl. roles, audit, granting organisers | demoting themselves; writes without CSRF |
-
-> **Staff persona limitation.** The `staff` persona is *not* a true event-scoped staff role. It is the platform-wide
-> `support` admin role, so it can open the attendee and booking lists of **every** event and check guests in at
-> **any** event. That is a test limitation, not the intended final permission model. Event-scoped staff permissions
-> (`event_staff`: a person allowed to see and check in guests for specific events only) remain future work for **M5**.
-
-### Persona login flow (local only)
-1. Start the server with `DEV_LOGIN=true`, a local `DATABASE_URL`, and no production `NODE_ENV`/`VERCEL_ENV` (section 2).
-2. Run `npm run seed:local` — persona sign-in only signs in users the seed created (409 `not_seeded` otherwise).
-3. Open `/signin`; the "Local test personas" picker lists the six personas. Click one; you land on its page from the
- table above (`/me`, `/organiser` or `/admin`) with a normal server-side session.
-4. Sign out from the site, or re-run `seed:local` (it revokes persona sessions) to switch.
-
-If any condition in step 1 fails the picker is not rendered and `POST /api/auth/dev` returns 404, which is how it
-behaves on every deployment.
-
-Sign in from the browser at `/signin`, or from a script:
-```bash
-curl -i -X POST localhost:3000/api/auth/dev -H 'content-type: application/json' -d '{"persona":"organiser"}'
-```
-
-### Seeded events (all `is_demo=true`, slug `local-*`, venues private)
-| Slug | Owner | State |
-|---|---|---|
-| `local-board-games-night` | organiser | open; `guest` confirmed |
-| `local-sunday-picnic` | organiser | open, no bookings (used by the booking test) |
-| `local-approval-dinner` | organiser | host approval; `guest2` pending request with an answer |
-| `local-paid-workshop` | organiser | paid tier only → "Online booking not available yet" |
-| `local-low-seats-trek` | organiser2 | 1 seat left (`guest2` holds 2 of 3) |
-| `local-sold-out-mixer` | organiser2 | sold out (`guest` holds 2 of 2) |
-| `local-past-meetup` | organiser | ended; `guest` checked in, `guest2` confirmed |
-| `local-cancelled-movie` | organiser2 | cancelled; `guest2` booking cancelled |
-
-Plus one draft per organiser, 40 analytics rows spread over the 7/30/90-day insight windows, and moderation rows for
-the admin console (2 leads, one with a long unbroken URL; 1 guest report).
-`npm run seed:local` prints the counts (6 users, 2 admin rows, 8 events, 8 ticket types, 7 bookings, 2 drafts,
-40 analytics, 2 leads, 1 report).
-
-## 4. Automated tests
-```bash
-npm run lint # node --check over every .js/.json file
-TEST_DATABASE_URL=postgres://localhost/sm_pv2_test npm test # node:test suites; use your dedicated test DB (it is wiped)
-npm run test:e2e # Playwright: desktop + mobile + responsive projects
-npm run test:e2e -- --project=mobile e2e/guest-booking.spec.js # one project / one file
-npm run test:e2e -- --project=responsive -g "admin @ 320" # one viewport of the admin matrix
-npm run test:e2e:report # open the last HTML report
-```
-Before running `npm test`, check that `TEST_DATABASE_URL` names a dedicated local database: the harness drops its
-`public` schema. Never point it, or `E2E_DATABASE_URL`, at `.env`'s database or at production.
-
-### Viewport matrix
-| Project | Viewport | Specs |
-|---|---|---|
-| `desktop` | Desktop Chrome 1280×800 | every spec except `admin-responsive` |
-| `mobile` | Pixel 7 (412×839, touch) | every spec except `admin-responsive` |
-| `responsive` | per describe block: **320×640**, **375×667**, **Pixel 7** (412, touch), **tablet 768×1024**, **desktop 1280×800** | `e2e/closed-and-gates.spec.js` | past/cancelled event pages show a status panel and no booking controls; signed-out (401) and non-admin (403) `/admin` access screens; category card art |
-| `e2e/tap-targets.spec.js` | phone project only, 320 and 375px: every interactive control on public, menu, `/me` and organiser pages is ≥44px (inline links in sentences exempt) |
-| `e2e/admin-responsive.spec.js` |
-
-The admin console switches to the phone layout (Sections menu, card tables) at ≤800px; tables with more than six
-columns (Events) stay as cards up to 920px of panel width, so the tablet and Pixel 7 sizes see cards. Chromium only;
-WebKit/iPad is not yet in the matrix.
-`npm run test:e2e` starts its own server on port 3100 (`E2E_PORT`) against `E2E_DATABASE_URL`
-(default `postgres://localhost/sm_e2e`), migrates, re-seeds, and clears that database's rate-limit windows first.
-Stop any server already on port 3100 before running it.
-
-| Spec | Covers |
-|---|---|
-| `e2e/guest-booking.spec.js` | free booking end to end, venue revealed on the confirmed booking; paid and sold-out show no Book button |
-| `e2e/organiser-create.spec.js` | four-step wizard → publish → public page hides the venue; the other organiser gets 404 managing it |
-| `e2e/admin.spec.js` | super admin console, roles and audit; staff sees only permitted tabs and gets 403 on admin-only APIs; guests/organisers refused |
-| `e2e/private-venue.spec.js` | venue never in visitor HTML or `/api/events`; not shown to a non-booked guest, a pending request, or another guest opening the booking URL |
-| `e2e/mobile-layout.spec.js` | no sideways scroll (incl. 320px), axe WCAG 2.1 A/AA with no serious/critical issues on public and signed-in pages, mobile menu Escape |
-| `e2e/admin-responsive.spec.js` | admin console at all five matrix sizes: every section fits with no sideways scroll; tables become labelled cards with identity first and every column kept; named, ≥44px actions; check-in; lead/report status controls; loading/empty/error/offline/forbidden states; long unbroken text; keyboard focus; desktop sidebar vs. full-width phone "Sections" button (mouse, Enter/Space, Escape); role-filtered sections for staff |
-
-Axe runs with `prefers-reduced-motion: reduce` so it measures settled colours, not mid-fade text.
-
-### Reviewing screenshots
-Every run writes full-page screenshots to `test-results/screenshots/-.png` (git-ignored, overwritten
-each run). The admin matrix writes `responsive-admin--.png`, where viewport is `320`, `375`,
-`pixel7`, `tablet` or `desktop` and screen is one of `events`, `bookings`, `attendees-before`, `attendees-after`,
-`leads`, `reports`, `audit`, `loading`, `empty`, `error`, `long-text`, `keyboard`, `nav` (desktop) or
-`nav-closed`/`nav-open` (phones and tablet).
-```bash
-ls test-results/screenshots/responsive-admin-*.png
-open test-results/screenshots/responsive-admin-320-nav-open.png # macOS Preview; any image viewer works
-```
-Check for: clipped or overlapping controls, sideways scroll, every table column present as a labelled line on
-cards, the identity (event title / member / name) leading each card, usable buttons and status selects, clear
-loading/empty/error/offline/forbidden states, a visible focus ring in `*-keyboard.png`, and — on desktop — a sidebar
-with no "Sections" text. The automated assertions cover these too; the screenshots are for what assertions miss.
-The audit log in `sm_e2e` is not reset by the seed, so `*-audit.png` grows with every run; `dropdb sm_e2e && createdb sm_e2e`
-starts it fresh.
diff --git a/docs/MEMBERSHIP_DISCOVERY.md b/docs/MEMBERSHIP_DISCOVERY.md
deleted file mode 100644
index b45073f..0000000
--- a/docs/MEMBERSHIP_DISCOVERY.md
+++ /dev/null
@@ -1,39 +0,0 @@
-# Membership (SuperProfile), discovery feeds, insights
-
-Date: 2026-10-27 · Live payments: **off** (`ENABLE_LIVE_PAYMENTS=false`) · Prices: **not approved** — none are set or shown by this code.
-
-## SuperProfile membership
-
-SuperProfile runs checkout **and** private-Telegram-group access ("Integrated groups": adds members on purchase, removes them when a subscription expires). SuperProfile has no public API; it exposes Zapier / Pabbly Connect triggers: **New Purchase**, **Subscription Expired**, **Purchase Abandon**. We receive those via a webhook to keep lifecycle numbers for `/admin` — we do not grant or revoke group access for SuperProfile tiers.
-
-### Owner setup (cannot be verified from code — needs the SuperProfile account)
-1. In SuperProfile: create the membership product(s) and connect the private Telegram group(s) to them. Confirm the SuperProfile bot is admin in each group.
-2. In Vercel (Preview first): add `SUPERPROFILE_WEBHOOK_SECRET` — a random string of 24+ characters.
-3. In `/admin → Membership tiers` (super_admin): set *Sold via* = SuperProfile, the product's https URL, and the *product reference* exactly as the automation sends it (matching is case-insensitive).
-4. In Zapier (or Pabbly): trigger *SuperProfile → New Purchase* → action *Webhooks → POST* to `https:///api/membership/superprofile/webhook`, header `X-Webhook-Secret: `, JSON body:
- ```json
- { "event": "purchase", "id": "", "product": "", "email": "", "amount": "", "currency": "INR", "occurred_at": "" }
- ```
- Repeat with *Subscription Expired* → `"event": "subscription_expired"` and *Purchase Abandon* → `"event": "purchase_abandoned"`.
-5. Check `/admin → Integrations → SuperProfile`: events appear, tier shows as mapped.
-
-Behaviour: idempotent on `(event, id)`; duplicates return 200 `duplicate`; bad/missing secret 401; unset secret 503; failures return 500 (automation retries) and are logged in `integration_errors` without the payload. The buyer email is stored only as an HMAC (keyed with `SESSION_SECRET`).
-
-### Telegram rule (checked against core.telegram.org/bots/payments-stars, 2026-10-27)
-"Your bot or mini app must use Telegram Stars for the sale of digital goods and services inside Telegram apps, regardless of any other web portals… you may have set up outside the Telegram ecosystem." Therefore:
-- The SuperProfile checkout link is shown on the **website only**. Inside the Telegram Mini App it is hidden (`data-web-only`), and the bot's `/membership` lists only Stars tiers — it never mentions or links SuperProfile.
-- A tier sold via SuperProfile cannot also get a Stars invoice from our bot (two systems would fight over group membership).
-- **Event tickets / trips** are in-person services: they are sold on the website through Razorpay (sandbox), never with Stars. Telegram's docs do not classify offline-event tickets explicitly; we do not sell them inside Telegram at all.
-
-## Event discovery
-
-- **Feeds** (`/admin → Discovery`): RSS 2.0, RSS 1.0 (incl. the `ev:` event module) and Atom. Every feed requires a recorded *permission basis*. Each fetch checks robots.txt (our UA `StrangersMeetupBot`), uses https only, refuses private/internal addresses (also after redirects), caps size (2 MB) and time (10 s), and sends conditional-GET headers. Runs daily via `/api/cron/daily` (job `feeds`) or on demand ("Fetch now", rate-limited).
-- **Nothing is auto-published.** Items enter the moderation queue. `pubDate`/`updated` are publication dates, never used as event dates — most feed items arrive with *no date* and the moderator must confirm it on the source page.
-- **Submissions**: `/submit-event` (rate-limited 5/hour/IP, honeypot, consent). Contact details are visible to admins only.
-- **Dedupe**: same https link, or same normalised title + IST calendar day + city, against live events and queued items; a unique index enforces it for events.
-- **External listings**: attributed ("Via ", "Listed from …"), link to the organiser's https page, never bookable through our checkout (server-enforced), no capacity/price/availability claims, no Event JSON-LD.
-- Formats: nightlife, strangers trips, meetups, dinners, weekend parties, dating mixers, matchmaking (in-person). Pages: `/events`, `/nightlife`, `/trips`, `/meetups`, `/dinners`, `/weekend-parties`, `/dating`.
-
-## Insights (`/admin → Insights`, roles: super_admin, finance, event_manager)
-
-Computed only from our Postgres. Each metric is either a value (zero is a real zero) or **Unavailable** with the reason (e.g. no page views recorded yet, SuperProfile not connected, nobody has shared age). Visitors come from a first-party, cookie-less page-view beacon (path only, referrer host only, `utm_source`), counted per browser id in localStorage. Demographics/interests are voluntary (`/me`) and buckets under 5 people are hidden.
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
new file mode 100644
index 0000000..8bae2b1
--- /dev/null
+++ b/docs/OPERATIONS.md
@@ -0,0 +1,131 @@
+# NIGHTLIFEZ — Essential Operating Instructions & Runbook
+
+**Primary Monitoring Endpoint:** [https://nightlifez.com/api/health](https://nightlifez.com/api/health)
+**Telegram Bot:** `@Nightlifez_bot`
+**Operations Inbox:** `nightlifezofficial@gmail.com`
+
+---
+
+## 1. System Health & Observability
+
+### A. Health Check Inspection
+The `/api/health` endpoint performs real-time diagnostics on database connectivity and configuration readiness:
+```bash
+curl -s https://nightlifez.com/api/health | jq .
+```
+Expected healthy response:
+```json
+{
+ "ok": true,
+ "database": "ok",
+ "config": {
+ "publicSiteUrl": "configured",
+ "telegramBot": "configured",
+ "paymentProvider": "configured"
+ }
+}
+```
+
+### B. Structured Logs
+All server logs are emitted in JSON format containing a unique request trace ID (`reqId`).
+To filter errors in Vercel CLI or Dashboard:
+```bash
+vercel logs strangersmeetup --prod
+```
+
+---
+
+## 2. Scheduled Cron Jobs (`/api/cron/*`)
+
+Scheduled maintenance routines require an `Authorization: Bearer ` header.
+
+### Master Daily Cron (`/api/cron/daily`)
+Runs every morning at 06:00 IST via Vercel Cron. The daily cron executes four idempotent tasks in sequence:
+
+| Task Name | Sub-endpoint | Action Performed |
+|---|---|---|
+| **Expire Holds** | `/api/cron/expire-holds` | Cancels bookings stuck in `pending_payment` older than 15 minutes and restores event capacity. |
+| **Memberships** | `/api/cron/memberships` | Dispatches renewal reminders 3 days before expiry; revokes chat access for expired subscriptions. |
+| **Notifications** | `/api/cron/notifications`| Retries failed Telegram DMs and invite links with exponential backoff. |
+| **Cleanup** | `/api/cron/cleanup` | Purges expired login nonces, stale session rows, and obsolete rate-limit counters. |
+
+*Manual Trigger Example:*
+```bash
+curl -X POST https://nightlifez.com/api/cron/daily \
+ -H "Authorization: Bearer $CRON_SECRET"
+```
+
+---
+
+## 3. Telegram Bot Operations
+
+### A. Bot Webhook Registration
+To register or update the webhook with Telegram:
+```bash
+curl -s -X POST "https://api.telegram.org/bot/setWebhook" \
+ -d "url=https://nightlifez.com/api/telegram/webhook" \
+ -d "secret_token=" \
+ -d 'allowed_updates=["message","callback_query","chat_member"]'
+```
+
+### B. Bot Permission Requirements
+To generate single-use invites and manage chat memberships, `@Nightlifez_bot` must be added as an **Administrator** in:
+1. The official community channel (`NIGHTLIFEZ Official`).
+2. Every private event chat group (`events.telegram_chat_id`).
+3. Required administrator rights: **Invite Users via Link** and **Ban Users**.
+
+---
+
+## 4. Operational Incident Runbooks
+
+### Incident 1: Telegram Invites Failing
+- **Symptom:** Admin dashboard indicates "Invite failures".
+- **Diagnosis:** Inspect `last_error` in the `notifications` database table:
+ - `user_has_not_started_bot`: The attendee has never messaged `@Nightlifez_bot`. Attendee must open the bot and click **/start**; the bot will immediately deliver their pending invite.
+ - `not enough rights`: Bot is not an administrator in the target chat or lacks *Invite Users* permission.
+ - `chat not found`: `TG_CHAT_ID_EVENTS` or event chat ID is invalid.
+- **Remediation:** Resolve permission, then trigger retry via `/api/cron/notifications`.
+
+### Incident 2: Inbound Webhook Failures
+- **Symptom:** Customers report payment completion but tickets remain `pending_payment`.
+- **Diagnosis:**
+ - `401 Unauthorized`: Webhook secret in provider dashboard does not match `SUPERPROFILE_WEBHOOK_SECRET`.
+ - Check `/admin/orders` for **Unmatched** or **Flagged** orders:
+ - *Unmatched:* Payment succeeded but buyer email/handle did not match. Buyer can use `/claim ` in `@Nightlifez_bot`, or Finance can manually link the order in `/admin`.
+ - *Flagged:* Currency mismatch, duplicate payment, or event unpublished.
+
+### Incident 3: Refund Execution
+- **Ticket Refunds:** Tickets purchased via external checkout must be refunded on the merchant dashboard (SuperProfile). When the refund webhook arrives, NIGHTLIFEZ automatically updates the booking to `refunded`, revokes any unused invite link, and kicks the user from the event chat.
+- **Telegram Stars Memberships:** Finance administrators can refund directly from `/admin/bookings` using the **Refund Star Payment** button.
+
+### Incident 4: Account Ban or Misuse
+- If an attendee violates community guidelines or leaks invite links:
+ ```sql
+ -- Ban user and revoke platform access
+ UPDATE users SET status = 'banned' WHERE id = '';
+ UPDATE user_sessions SET revoked_at = now(), revoke_reason = 'banned' WHERE user_id = '';
+ ```
+ *The user is immediately signed out from all web sessions, blocked from booking, and kicked from active event chats.*
+
+---
+
+## 5. Secret Rotation Procedures
+
+| Secret Name | Rotation Procedure | Immediate Operational Effect |
+|---|---|---|
+| `SESSION_SECRET` | Set new secret in Vercel $\to$ Redeploy | Signs out all active web sessions. Users must re-authenticate. |
+| `CRON_SECRET` | Set new secret in Vercel $\to$ Redeploy | Vercel Cron uses the updated secret automatically. |
+| `TELEGRAM_BOT_TOKEN` | Revoke in @BotFather $\to$ Update Vercel $\to$ Redeploy $\to$ Rerun webhook registration | Bot immediately switches to the new token. |
+| `TICKET_SECRET` | Set new secret in Vercel $\to$ Redeploy | Previously generated QR passes will fail door check-in. Rotate only between active event cycles. |
+| `SUPERPROFILE_WEBHOOK_SECRET` | Set in Vercel $\to$ Update webhook header in provider dashboard | Inbound webhooks during rotation may return 401; provider retries automatically. |
+
+---
+
+## 6. Pre-Launch Database Sanitization
+
+Before publishing the first live event, sample demo data must be archived:
+```sql
+-- Archive demo events to ensure only authentic experiences appear
+UPDATE events SET status = 'archived' WHERE is_demo = true;
+```
+Verify that `SELECT count(*) FROM events WHERE status = 'published' AND NOT is_demo;` returns the expected number of authentic events.
diff --git a/docs/ORGANISER_WIZARD.md b/docs/ORGANISER_WIZARD.md
deleted file mode 100644
index 1261988..0000000
--- a/docs/ORGANISER_WIZARD.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# Organiser event wizard
-
-Approved organisers create events at `/organiser/new` in four steps: **Basics → Tickets → Features → Preview**.
-Nothing goes live until they publish, explicitly, from Preview.
-
-## Who can organise
-- A user with `users.organiser_enabled = true`. A super admin grants it:
- `POST /api/admin/organisers { telegram_user_id, enabled }` (audited). The person must have signed in once.
-- Active admins with role `super_admin` or `event_manager`.
-- Everyone else sees an "apply to host" notice. Drafts and events are owner-scoped, so another organiser's draft returns 404.
-
-## Drafts
-- `event_drafts` holds versioned JSON. Saves are `PUT /api/organiser/drafts/:id { data, step, version }`.
- A stale `version` gets 409 `version_conflict` with the newer copy, and the wizard lets the organiser choose a version.
-- Draft data is validated loosely when saved (types and lengths). `publishIssues()` in `lib/services/organiser.js`
- is the strict gate, and the same function feeds the inline errors, the Preview checklist and the publish endpoint.
-- The browser keeps a localStorage copy of unsaved edits only as a safety net. On load, it is applied only if it was
- based on the server's current version.
-- "Start fresh" discards (soft-deletes) the latest draft, after confirmation when it has meaningful content.
-- Drafts never appear publicly. An `events` row is created only by `POST /api/organiser/drafts/:id/publish { version, confirm: true }`.
-
-## Tickets and payments
-- `ticket_types` holds one row per tier: free or paid, price, quantity, max per booking, optional `valid_on` day for multi-day events, and optional eligibility.
- A DB constraint makes a priced free tier impossible.
-- Inventory is checked under the event row lock (`FOR UPDATE`), per event and per tier, so concurrent bookings can't oversell.
-- **Paid checkout is off.** `lib/payments/availability.js` reports it unavailable unless `TICKET_CHECKOUT_ENABLED=true`
- *and* provider keys are configured. While it is off:
- - organisers can configure paid tiers and save them;
- - an event whose tiers are *all* paid cannot be published;
- - paid tiers show "Online payment not available yet" and the booking API refuses them with `payment_unavailable`.
-- No manual UPI or pay-at-venue flow exists. Nothing a guest does can mark a payment paid. Payments become `paid` only
- via a signature-verified provider webhook or server-side reconciliation, as before. A new provider is an adapter in
- `lib/payments/`; tiers and bookings don't change.
-- `bookings.payment_mode` is `free` (no payment ever) or `provider`.
-
-## Features (all persisted in the draft; each switch has real behaviour)
-| Feature | Behaviour |
-|---|---|
-| Ask guests questions | Short, long, single-choice and multiple-choice answers. Required answers are enforced server-side. Answers are visible only to the organiser. |
-| Approve each guest | Booking creates `pending_approval` (holds no seat). Approve → free: `confirmed`; paid: checkout with a 24h hold (never "paid"). Decline → `declined`, and that guest can't re-request. |
-| Crowd balance | Per-tier eligibility text, which guests must confirm, plus visible "N of M left" counts. Tiers pause at their cap and reopen when a held spot is released. |
-| Pickup points | Name, spot and time. Guests must pick one, and it's shown on their booking and the guest list. |
-| Event contact | Name and WhatsApp number (normalised to E.164). Shown only on a *confirmed* guest's booking. |
-
-Not implemented, and shown only as "Coming later" with no toggle: minimum guest threshold, promo codes, advance/balance payments and complimentary passes.
-
-## Privacy
-With a private venue, the public page, `/api/events`, sitemap, JSON-LD and OG tags show only the area and city.
-The address and Google Maps link are returned only by `GET /api/bookings/:id` for the booking's owner once it's confirmed.
-Draft images (`/media/event-images/:id`) are visible only to their owner until the event is published.
-
-## Not in scope here
-- Editing an event after it's published (organisers manage guests; content edits still go through admin).
-- Check-in at the door stays in the existing admin check-in screen.
diff --git a/docs/PAYMENTS_DECISION.md b/docs/PAYMENTS_DECISION.md
deleted file mode 100644
index 1cbd83b..0000000
--- a/docs/PAYMENTS_DECISION.md
+++ /dev/null
@@ -1,43 +0,0 @@
-# Payments decision
-
-Date: 2026-10-26 · Status: **sandbox only** (`ENABLE_LIVE_PAYMENTS=false`) · Prices: **TBD** (owner pricing session pending)
-
-## Decision
-| Purchase | Provider | Why |
-|---|---|---|
-| Event tickets & trips (in-person service) | **Razorpay Payment Links** (hosted page) | No customer phone/email required (we don't collect them); plain redirect URL, no client SDK; simple, documented webhook HMAC; idempotent refunds; test mode works before KYC. |
-| Membership (digital access to private Telegram groups) | **Telegram Stars** (`XTR`) subscriptions | Telegram requires digital goods/services sold inside Telegram to use Stars. Never used for physical tickets or trips. |
-| Alternate ticket sources | `bookmyshow_url`, `external_payment_url` per event | Owner-configured outbound links only; we do not reconcile them. |
-
-Cashfree is implemented behind the same `PaymentProvider` interface (webhook verification, refunds, status) but **checkout is disabled**: Cashfree requires `customer_phone` on both Orders and Payment Links, and its hosted checkout opens only via its JS SDK. Switching to it means deciding to collect phone numbers.
-
-## How it works (built)
-`PaymentProvider { createCheckout, verifyWebhook, refund, fetchStatus }` — `lib/payments/`.
-
-1. `POST /api/bookings` (signed-in, CSRF) → transaction with `SELECT … FOR UPDATE` on the event → capacity check (paid + live holds) → 15-minute `pending_payment` hold → commit → Razorpay `POST /v1/payment_links` (`amount` in paise, `reference_id`, `notes.booking_id`, `expire_by` ≥ 16 min, notifications off, `callback_url` = booking status page) → `payments` row (`is_test=true`).
-2. User pays on Razorpay's page and is redirected to `/bookings/`, which **only polls**; redirect parameters are ignored.
-3. `POST /api/payments/webhook/razorpay`: `X-Razorpay-Signature` = hex HMAC-SHA256(raw body, webhook secret), constant-time compare → `webhook_events (provider, X-Razorpay-Event-Id)` unique insert → one transaction: payment `paid` (amount + currency must match) → booking `confirmed` (or, if the hold lapsed and the event is full/cancelled, `refund_due` + finance alert) → outbox row → 200. DM + single-use invite are sent after the response (`waitUntil`) to stay inside Razorpay's 5-second window; failures retry via cron.
-4. Daily cron reconciles `created` payments older than 10 minutes with `GET /v1/payment_links/:id` (missed webhooks) and releases stale holds.
-5. Refunds: `/admin` → finance role → `POST /v1/payments/:id/refund` with a stable `receipt` (Razorpay treats a duplicate receipt as already processed) → payment/booking `refunded`, invites revoked, DM.
-
-Stars: `createInvoiceLink` with `currency: "XTR"`, `provider_token: ""`, one price item, `subscription_period: 2592000` (the only allowed value; ≤ 10,000 Stars), signed ≤128-byte payload → `pre_checkout_query` checks payload signature, tier active and priced, amount, payer = invoice user, 21+ confirmed → `successful_payment` idempotent on `telegram_payment_charge_id` (renewals carry new charge ids and extend `expires_at`). Refunds via `refundStarPayment`. Bot answers `/paysupport` and `/terms` as Telegram requires.
-
-## Onboarding blockers (owner)
-1. **Category risk — highest priority.** Razorpay's prohibited list includes "friend finders", "adult material / mature content" and "websites that promise online matchmaking"; Cashfree prohibits "sexually suggestive materials… escort" services. Neither explicitly lists in-person event ticketing, but "21+", "dating mixers" and "strangers meetup" wording can trigger an automated misclassification.
- - Apply under **Events / ticketing / hospitality experiences**, describe the business as hosted in-person social events and trips, and ask Razorpay's activation team to **confirm the category in writing before going live**.
- - Keep dating features framed as in-person hosted events; no online matchmaking is offered (intro features are "Coming soon" and not built).
-2. **KYC documents:** PAN, GST or Udyam, a business proof (Shop & Establishment / IEC / utility bill), bank account. Activation: minutes (CKYC) to ~8 business hours (assisted); manual review varies.
-3. **Website requirements:** About, Contact (with email + phone), Pricing, Terms, Privacy, Refund policy pages — all exist except a published legal entity name, support email/phone and grievance officer (set `LEGAL_ENTITY_NAME`, `SUPPORT_EMAIL`, `GRIEVANCE_*` env vars). Live API keys require a verified website.
-4. **Trips:** "Tours and travel" is a higher-risk category for some gateways (reserves, IATA/IRCTC questions). Launch with day events first; add trips after activation.
-5. **Vercel Hobby plan** prohibits commercial use — upgrade to Pro before live payments.
-6. **Fees / settlement (verify at signup):** Razorpay ~2% + 18% GST domestic; settlement T+2 (some pages say T+1). Cashfree 1.95% + GST, T+2; may hold funds for services delivered far in the future.
-
-## Sandbox test plan (needs owner's test keys)
-Env (Preview): `PAYMENT_PROVIDER=razorpay`, `RAZORPAY_KEY_ID=rzp_test_…`, `RAZORPAY_KEY_SECRET`, `RAZORPAY_WEBHOOK_SECRET`, `ENABLE_LIVE_PAYMENTS=false`.
-Razorpay Dashboard (Test mode) → Webhooks → URL `https:///api/payments/webhook/razorpay`, events `payment_link.paid`, `payment_link.expired`, `payment_link.cancelled`, `payment.failed`, `refund.processed`. Pay with UPI `success@razorpay` / `failure@razorpay` or card 4100 2800 0000 1007.
-The code refuses `rzp_live_` keys while `ENABLE_LIVE_PAYMENTS=false`, and `rzp_test_` keys when it is `true`.
-
-## Unverified (re-check during onboarding)
-Whether `payment.failed` fires for payment-link attempts (handled via `notes.booking_id` if it does); Razorpay webhook IP list and exact retry schedule; Razorpay's treatment of singles/meetup merchants; Cashfree link expiry limits; Stars test-environment behaviour for subscriptions.
-
-Sources: razorpay.com/docs (payment links, webhooks, refunds, test mode), razorpay.com/s/terms; cashfree.com/docs (PG orders, links, webhooks, refunds), cashfree.com/tnc; core.telegram.org/bots/api (Bot API 10.3, createInvoiceLink, SuccessfulPayment, refundStarPayment), core.telegram.org/bots/payments-stars. Research notes: `research_notes/` (not committed).
diff --git a/docs/PLATFORM_AUDIT.md b/docs/PLATFORM_AUDIT.md
deleted file mode 100644
index 66c4350..0000000
--- a/docs/PLATFORM_AUDIT.md
+++ /dev/null
@@ -1,138 +0,0 @@
-# StrangersMeetup — Platform audit (M0)
-
-Audit date: 2026-10-29 · Base: `origin/launch-mvp` @ `fb73c31` (includes PR #3) · Branch: `feature/platform-v2`
-
-Method: read the source (router, handlers, services, migrations, views, client JS, tests, `vercel.json`), ran
-`npm run lint` and `npm test` against a throwaway local Postgres 14, and checked branch/PR state with `git` and `gh`.
-Independent read-only audits (security/RBAC, data/migrations, UX/frontend, tests) were reconciled against the code;
-claims below that matter were re-checked by hand and carry `file:line` evidence.
-
-Status legend: **Verified** (code read + test or manual run) · **Implemented, unverified** (code exists, no test/run) ·
-**Partial** · **Missing** · **Blocked** (needs credentials, third-party approval or infrastructure).
-
----
-
-## 1. Branches and PRs (verified with `git fetch` + `gh pr list`, 2026-10-28)
-
-| Ref | Commit | State |
-|---|---|---|
-| `origin/main` | `b13d927` | PR #1 (Vercel Web Analytics) merged. Production deploys from here. |
-| `origin/launch-mvp` | `fb73c31` | Built on `b13d927`; PR #3 (organiser wizard) merged into it 2026-10-28 14:17 UTC. |
-| PR #2 `launch-mvp → main` | — | Open, draft. `git merge-tree` of `launch-mvp` into `main`: clean. Merging deploys production. |
-| `feature/organiser-wizard` | `b3a1d37` | Fully merged (same tree as `fb73c31`). |
-
-- PR #1's static `public/js/analytics.js` + HTML pages were removed by the rebrand (`e08c2fc`) and replaced by the
- server-rendered `/_vercel/insights/script.js` tag (`lib/views/layout.js:110`). Nothing from PR #1 is lost.
-- No `.github/` CI. Vercel's Git checks fail on PR #2/#3 because of the plan (Hobby + private org), not the code;
- previews have been CLI deploys.
-- Baseline at `fb73c31`: `npm run lint` 73/73 files OK; `npm test` **114/114 pass**.
-
-## 2. Stack
-Zero-build Node ≥20 (runs on 24), one Vercel function (`api/index.js` → `lib/router.js`, ~90 routes),
-Postgres via `pg`, `zod` validation, server-rendered views with an auto-escaping `html` tag (`lib/views/html.js`),
-vanilla client JS. Migrations `003`–`008` (now `009`), each in a transaction under an advisory lock (`lib/db.js` `migrate`).
-
-## 3. Findings by area
-
-### Authentication and sessions
-| Item | Status | Evidence |
-|---|---|---|
-| Telegram Mini App initData (HMAC, 300 s, replay nonce) | Verified | `lib/telegram/auth.js`; `test/auth.test.js` |
-| Telegram Login via OIDC (PKCE, sealed state, nonce, id_token replay) | Implemented, unverified live | `lib/handlers/auth.js:94-133`; needs real client id/secret |
-| Legacy Login Widget fallback | Verified | `test/auth.test.js:60` |
-| Google sign-in | **Missing** | No code. `users.telegram_user_id` is `NOT NULL` (`migrations/003:41`) — needs an identities table |
-| Session cookie: HMAC-signed, HttpOnly, SameSite=Lax, Secure on Vercel, 7-day TTL | Verified | `lib/session.js` |
-| Server-side revocation on sign-out | **Fixed in M1** (was missing: logout only cleared the cookie) | `migrations/009`, `lib/session.js`, `test/safety.test.js` |
-| CSRF (HMAC of session in `X-CSRF-Token` + Origin check) | Verified for admin/auth/profile; organiser writes enforce it via the shared guard (`lib/handlers/organiser.js:23`) but are **untested** | |
-| Local dev login | Verified (404 path only) | `lib/handlers/auth.js:136` — refuses on Vercel, without `DEV_LOGIN=true`, or with `NODE_ENV=production`; single fixed identity |
-| Account linking, deletion, export | **Missing** | FKs have no `ON DELETE` rules; deletion must be an anonymisation design |
-
-### Roles and access control
-| Item | Status | Evidence |
-|---|---|---|
-| Admin roles `super_admin`, `event_manager`, `moderator`, `finance`, `support` | Verified | `admin_users`; role map `lib/handlers/admin.js:22-37`; `guard()` on all 38 admin handlers |
-| Role grants only by super_admin; no self-demotion | Verified | `admin.js:485-499`; `test/admin.test.js:125` |
-| Organiser access (`users.organiser_enabled`), granted by super_admin, audited | Verified | `admin.js:520-531`; `test/organiser.test.js:72` |
-| No self-promotion path (strict profile schema, upserts never touch role columns) | Verified by reading | `lib/handlers/profile.js:16-21` |
-| Organiser drafts/images/events scoped to owner | Verified | `lib/services/organiser.js:316-353,380-393,547`; tests for drafts, approve, guests, images |
-| Cross-organiser decline, manage page, image delete, events list, revoked organiser | Implemented, **untested** | |
-| Event staff / per-event roles | **Missing** | |
-| Organiser publish moderation | **Missing** — organiser publish inserts `status='published'` directly (`lib/services/organiser.js:512`) | Decision: first event of a new organiser goes to admin review (M5/M6) |
-
-### Events, tickets, bookings
-| Item | Status | Evidence |
-|---|---|---|
-| Four-step wizard, server drafts, optimistic version (409), local safety copy, templates | Verified | `test/organiser.test.js:82-147` |
-| Ticket tiers free/paid, quantity, per-booking max, `valid_on` days; DB refuses priced free tier | Verified | `migrations/008:68-83`; `test/organiser.test.js:150-190` |
-| Inventory under event row lock (no oversell) | Verified (8 guests / 3 seats; 12 checkouts / 3 seats) | `lib/services/ticketing.js:69`; `test/organiser.test.js:371`, `test/payments.test.js:140`. App-level only — no DB constraint |
-| Approval flow (`pending_approval` → confirmed/declined); pending requests hold no seat | Verified | `ticketing.js:108,163-194`; `test/organiser.test.js:273` |
-| Guest questions (required enforced server-side), pickup points, crowd balance, contact for confirmed guests only | Verified | `test/organiser.test.js:341-503` |
-| Guest self-cancel | **Missing** | No endpoint |
-| Check-in | Partial — admin-only, by booking UUID, atomic single use (`UPDATE … WHERE status='confirmed'`) | `lib/handlers/admin.js:266-275`. **No QR, ticket token or scanner exists**; **no test**; whole booking checks in at once (no per-seat count) |
-| Editing a published event | **Missing** (documented as out of scope in `docs/ORGANISER_WIZARD.md`) | |
-
-### Privacy
-| Item | Status | Evidence |
-|---|---|---|
-| Private venue/maps link hidden from pages, `/api/events`, sitemap, JSON-LD, OG | Verified | `toPublicEvent` `lib/services/events.js:104-149`; `test/organiser.test.js:388` |
-| Venue/maps/WhatsApp revealed only to the booking owner once confirmed | Verified | `lib/services/bookings.js:271-282` |
-| Public pages CDN-cached (`s-maxage=60` + SWR 300) | Note: a venue switched to private can show for ~6 min on cached pages | `lib/http.js:152` |
-| Admin/organiser/member pages `no-store`, `X-Frame-Options: DENY` on `/admin` | Verified by reading | `vercel.json:52-56`, handlers |
-
-### Payments
-| Item | Status | Evidence |
-|---|---|---|
-| Paid ticket checkout gated off unless `TICKET_CHECKOUT_ENABLED=true` and keys exist | Verified | `lib/payments/availability.js:14-27`; `test/organiser.test.js:217` |
-| Payment becomes paid only from a signature-verified webhook or server reconcile; client redirect ignored | Verified | `test/payments.test.js:66,105,131` |
-| Amount check | **Fixed in M1** — previously skipped when a signed event omitted the amount (`lib/services/bookings.js:162`); now fails closed | `test/safety.test.js` |
-| Live-key guard (`ENABLE_LIVE_PAYMENTS`) | Verified | `test/payments.test.js:205` |
-| Razorpay (account suspended), Cashfree (KYC pending) | **Blocked** | Owner constraint; nothing will be enabled |
-
-### Admin and analytics
-| Item | Status | Evidence |
-|---|---|---|
-| Admin console (11 tabs) over JSON APIs, CSRF + rate limit + audit on writes | Verified | `public/js/admin.js`, `test/admin.test.js` |
-| Insights from real queries; "Unavailable + reason" vs real 0; k≥5 suppression; demo rows excluded | Verified | `lib/services/insights.js`; `test/insights.test.js` |
-| Upcoming fill | **Fixed in M1** — counted booking rows, not tickets (`insights.js:121`) | `test/safety.test.js` |
-| Per-event / per-organiser analytics | **Missing** — derivable from `analytics_events.event_id` + bookings; no index on `event_id` | |
-| Audit log | Implemented; viewer is raw JSON in a table | `lib/audit.js`, `public/js/admin.js` |
-| Pagination, search, CSV export in admin | **Missing** | |
-
-### Data, migrations, seed
-| Item | Status | Evidence |
-|---|---|---|
-| Preview builds could migrate the production DB | **Fixed in M1** — `vercel-build` migrated whatever `DATABASE_URL` it had | `migrationPolicy` in `lib/db.js`; `test/safety.test.js` |
-| `npm run migrate` ignored a local `.env` | **Fixed in M1** | `scripts/migrate.js` |
-| Demo seed: `is_demo` rows, labelled "Sample", excluded from insights | Verified | `scripts/seed-demo.js`, `test/site.test.js` |
-| Seed production guard / reset command | **Fixed in M1** (was a comment only; no reset existed) | `scripts/seed-guard.js`, `scripts/db-reset-local.js` |
-| Rich synthetic seed (users, organisers, bookings, check-ins, analytics windows) | **Missing** (M8) | |
-| Migration rollback / checksums | Missing (forward-only by design; rollback = new migration) | |
-
-### Frontend, UX, accessibility
-| Item | Status | Evidence |
-|---|---|---|
-| Cinematic homepage; reduced-motion handled in CSS and JS | Verified | `public/css/site.css:269-272,434-438`; `test/site.test.js:133` |
-| Skip link, landmarks, global `:focus-visible`, wizard errors tied to fields | Verified by reading | `lib/views/layout.js:113`, `public/js/organiser.js:250-262` |
-| Mobile nav: `aria-expanded` but no Escape, no focus management, does not close on link click | Partial | `public/js/site.js:69-74` |
-| Native `confirm()/alert()/prompt()` for refunds, cancels, age gate | Present (to replace in M2) | `public/js/admin.js:158,189,216`; `site.js:233` |
-| Design tokens: colours/radii only; no spacing/type scale; ~12 ad-hoc breakpoints; duplicate `.pill` | Partial | `site.css:5-23`; `admin.css:27` vs `organiser.css:21` |
-| Guest `/me`: flat list, no error branch, no ticket pass | Partial | `site.js:367-371` |
-| Images: DB-stored, client-resized to 1600 px, lazy on cards; no `srcset`/thumbnails | Partial | `lib/services/organiser.js:386`; `components.js:24` |
-| Browser E2E / a11y tooling | **Missing** — no Playwright config, no devDependencies | |
-
-### Platform and config
-- `Permissions-Policy: camera=()` on all routes (`vercel.json`) — a camera scanner needs a scoped exception on the scan route only.
-- Rate limits are Postgres-backed fixed windows (`lib/ratelimit.js`) — effective on serverless. IP from first
- `X-Forwarded-For` entry (fine on Vercel, spoofable behind other proxies).
-- `__path` query parameter overrides the pathname for any request (`lib/router.js`). Low risk (auth still applies);
- tightening it is **deferred** until the function's `req.url` under the Vercel rewrite is confirmed on a preview,
- because a wrong guess would 404 every route.
-- Env vars read but not in `.env.example` before M0: `DISABLE_WEB_ANALYTICS`, `PG_POOL_MAX`, `NODE_ENV`
- (now documented), plus test/internal `LOG_SILENT`, `SKIP_DOTENV`, `TEST_DATABASE_URL`.
-
-## 4. Blocked by credentials or third parties (owner)
-- Google OAuth client id/secret + registered callback URLs (local, preview, production).
-- Telegram bot token, webhook secret, bot username, chat ids, Telegram Login client id/secret.
-- Production `DATABASE_URL`, plus a **separate** preview database before setting `MIGRATE_ON_PREVIEW=true`.
-- Vercel Preview has no env vars; Git-triggered deploys need Vercel Pro (or a public repo).
-- Payments: Razorpay suspended, Cashfree KYC pending. Paid tiers remain draft-only.
diff --git a/docs/PRODUCT.md b/docs/PRODUCT.md
new file mode 100644
index 0000000..6ec27c7
--- /dev/null
+++ b/docs/PRODUCT.md
@@ -0,0 +1,113 @@
+# NIGHTLIFEZ — Product Scope & Functionality
+
+**Target Audience:** Adults 21+ across South India
+**Brand Identity:** NIGHTLIFEZ — vibrant social discovery, hosted nightlife, supper clubs, weekend trips, and curated social experiences.
+**Core Promise:** Safe, curated, honest social events with transparent pricing, zero bots, and guaranteed real-world fulfillment.
+
+---
+
+## 1. Product Vision & Value Proposition
+
+NIGHTLIFEZ bridges the gap between digital discovery and real-world connection. Traditional event platforms are impersonal ticket brokers, while dating apps often generate fatigue without real-world interaction. NIGHTLIFEZ combines editorial curation with tight-knit community dynamics:
+
+- **Curated Small-Group Experiences:** Dinners, secret supper clubs, cocktail mixers, private house parties, pub crawls, and weekend getaways.
+- **Privacy & Safety First:** Venue locations are protected until booking confirmation. Community guidelines and 21+ age verification are strictly enforced.
+- **Real-Time Community Loop:** Post-booking integration with Telegram delivers automated private group access, attendee updates, and digital QR ticket passes.
+
+---
+
+## 2. Target Personas
+
+### A. Attendee / Member (Adults 21+)
+- **Motivation:** Looking to meet like-minded people, discover new spots, and attend safe, well-organized social events without awkwardness.
+- **Behavior:** Browses upcoming events by city or vibe; signs in via Telegram; books a ticket or buys a community membership; joins the event group chat; checks in at the venue using a QR pass.
+
+### B. Experience Host / Organiser
+- **Motivation:** Passionate individuals, event curators, DJs, or community builders wanting to host intimate dinners, parties, or trips.
+- **Behavior:** Submits host application via `/become-a-host`; accesses the host workspace once approved; schedules events, monitors attendee capacity, and scans attendee QR tickets at the door.
+
+### C. Venue & Service Partner
+- **Motivation:** Premium restaurants, rooftop bars, boutique resorts, and entertainment spaces wanting curated foot traffic during off-peak or themed evenings.
+- **Behavior:** Submits venue details via `/list-your-venue` or `/partner-with-us`; collaborates with NIGHTLIFEZ curators for dedicated hosting slots.
+
+### D. Administrative & Operational Team
+- **Super Admin:** Platform configuration, team provisioning, financial reconciliation, and media management.
+- **Event Manager:** Event creation, capacity monitoring, and door check-in oversight.
+- **Moderator:** Community chat safety, attendee verification, and incident management.
+- **Finance:** Order reconciliation, refund processing, and payout tracking.
+
+---
+
+## 3. Geographic Coverage & City Hubs
+
+NIGHTLIFEZ operates across South India with dedicated city landing hubs:
+
+| City Hub | Primary Experience Categories | Signature Neighborhoods |
+|---|---|---|
+| **Chennai** | Rooftop mixers, supper clubs, coastal weekend trips | Besant Nagar, ECR, Nungambakkam, Alwarpet |
+| **Bangalore** | Microbrewery crawls, tech mixers, techno nights, house parties | Indiranagar, Koramangala, Church Street, HSR Layout |
+| **Puducherry** | Heritage walking dinners, beach parties, boutique cafe meetups | White Town, Promenade Beach, Auroville |
+| **Kochi** | Art dinners, waterfront socials, backwater weekend escapes | Fort Kochi, Panampilly Nagar, Kakkanad |
+| **Goa** | Sundowner parties, secret beach gigs, coastal retreats | Anjuna, Vagator, Assagao, Palolem |
+| **Hyderabad** | Lounge socials, comedy dinners, nightlife crawls | Jubilee Hills, Banjara Hills, Gachibowli |
+
+---
+
+## 4. Primary User Journeys
+
+```
+ ┌────────────────┐ ┌─────────────────┐ ┌──────────────────┐
+ │ Public Catalog │ ────► │ Event Details │ ────► │ Booking Hold │
+ │ (No sign-in) │ │ (Policy/Rules) │ │ (15m Capacity Tx)│
+ └────────────────┘ └─────────────────┘ └────────┬─────────┘
+ │
+ ▼
+ ┌────────────────┐ ┌─────────────────┐ ┌──────────────────┐
+ │ Door Check-In │ ◄──── │ Telegram DM & │ ◄──── │ Verified Payment │
+ │ (HMAC QR Scan) │ │ Group Invite │ │ (Webhook Web Tx) │
+ └────────────────┘ └─────────────────┘ └──────────────────┘
+```
+
+### 1. Discovery & Exploration
+- Public event feed available without mandatory sign-in or intrusive paywalls.
+- Filtering by city, category (nightlife, supper club, trips, mixers), and date.
+- **Honest metrics:** Zero fabricated countdowns, phantom "only 2 left" alerts, or fake attendee avatars. Every number is queried from active rows.
+
+### 2. Event Evaluation
+- Clear breakdowns of ticket inclusions (food, drinks, entry passes).
+- Transparent refund and cancellation policy displayed before checkout.
+- Clear disclosure of safety measures and gender-balanced seating commitments.
+
+### 3. Booking & Payment Hold
+- User initiates booking; atomic transaction reserves capacity with a 15-minute `hold_expires_at` timestamp.
+- User signs in securely via Telegram (Login Widget or Mini App).
+- Checkout redirect to provider (SuperProfile / UPI).
+- Abandoned checkouts automatically release capacity upon hold expiration.
+
+### 4. Automated Post-Purchase Fulfillment
+- Payment webhook triggers atomic transition from `pending_payment` to `confirmed`.
+- Asynchronous notification engine dispatches:
+ 1. Telegram DM to buyer with booking confirmation.
+ 2. Single-use, 24-hour expiring Telegram invite link to the private event group chat.
+ 3. Digital QR pass containing an HMAC-SHA256 signature for door admission.
+
+### 5. On-Site Check-In
+- Organiser opens the mobile scanner at `/admin/checkin` or event dashboard.
+- Attendee presents their QR ticket pass.
+- Scanner verifies the signature and records check-in timestamp in real-time, preventing double entry or pass sharing.
+
+### 6. Partner & Host Onboarding
+- Dedicated landing routes for hosts (`/become-a-host`), venues (`/list-your-venue`), and partners (`/partner-with-us`).
+- Honeypot fields, rate limiting, and Zod schema validations protect incoming leads against spam.
+
+---
+
+## 5. Scope Boundaries & Deferred Features
+
+To maintain launch velocity and absolute stability, the following features are intentionally decoupled from the initial launch:
+
+| Feature Area | Current Status | Launch Rationale |
+|---|---|---|
+| **Live Native UPI Payments** | Scaffolded, gated by `ENABLE_LIVE_PAYMENTS=false` | Requires final production merchant registration and owner signoff. External SuperProfile checkout handles launch transactions safely. |
+| **Algorithmic Matchmaking** | Deferred | Matchmaking algorithms without critical attendee mass create deceptive experiences. Intimate human curation is used at launch. |
+| **Public Chat History** | Deferred | Private groups are created per event on Telegram to ensure end-to-end encryption and user autonomy. |
diff --git a/docs/ROUTES_AND_ROLES.md b/docs/ROUTES_AND_ROLES.md
deleted file mode 100644
index 1472374..0000000
--- a/docs/ROUTES_AND_ROLES.md
+++ /dev/null
@@ -1,130 +0,0 @@
-# Routes and roles
-
-Source of truth for routes: `lib/router.js`. Every rule below is enforced **on the server**; hiding a button is
-never the control. "Proposed" rows are planned (see `docs/IMPLEMENTATION_PLAN.md`) and do not exist yet.
-
-## 1. Roles
-
-| Role | Where it lives | Granted by | Notes |
-|---|---|---|---|
-| Visitor | — | — | Not signed in |
-| Member (guest) | `users` row, `status='active'`, live `user_sessions` row | Signing in (Telegram today; Google proposed) | `suspended`/`banned` users are treated as signed out |
-| Organiser | `users.organiser_enabled = true` | `super_admin` via `POST /api/admin/organisers` (audited) | Active `super_admin`/`event_manager` admins also count as organisers (`lib/services/organiser.js:297-302`) |
-| Event staff *(proposed)* | `event_staff(event_id, user_id, can_scan, can_view_guests)` | The event's organiser, `event_manager`, `super_admin` | Scoped to listed events only; expires with the event |
-| `support` | `admin_users.role` | `super_admin` | Bookings read, check-in, leads |
-| `moderator` | `admin_users.role` | `super_admin` | Media, reports, feed moderation, membership revoke |
-| `event_manager` | `admin_users.role` | `super_admin` | All events, check-in, bookings, discovery, insights |
-| `finance` | `admin_users.role` | `super_admin` | Bookings, payments, refunds, insights |
-| `super_admin` | `admin_users.role` (+ bootstrap `ADMIN_BOOTSTRAP_TELEGRAM_ID`) | `super_admin` | Grants roles; cannot demote or deactivate themselves |
-
-A user can never change their own role: the profile schema is strict (`lib/handlers/profile.js`), sign-in upserts
-never write role columns, and every grant endpoint requires `super_admin`.
-
-## 2. Permission matrix
-
-✓ = allowed · *own* = only events where `events.organiser_user_id` is the user · *assigned* = only events where the
-user is listed staff · blank = denied (404 for object routes so existence is not leaked, 403 for role-gated APIs).
-
-| Capability | Visitor | Member | Staff | Organiser | support | moderator | event_manager | finance | super_admin |
-|---|---|---|---|---|---|---|---|---|---|
-| Browse public events/pages | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
-| Book, view own bookings, cancel own booking *(cancel proposed)* | | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
-| See private venue/contact of an event | | own confirmed booking | own confirmed booking | own events | | | | | |
-| Create/edit drafts, publish | | | | own | | | all | | all |
-| Edit published event *(proposed)* | | | | own | | | all | | all |
-| Guest list, answers, approve/decline | | | assigned (read) *(proposed)* | own | read | | all | | all |
-| Check-in / scan | | | assigned *(proposed)* | own *(proposed)* | all | | all | | all |
-| Assign event staff *(proposed)* | | | | own | | | all | | all |
-| Review organiser first events *(proposed)* | | | | | | ✓ | ✓ | | ✓ |
-| Moderate feeds, safety reports, media | | | | | | ✓ | ✓ (feeds only) | | ✓ |
-| Bookings list (all events) | | | | | ✓ | | ✓ | ✓ | ✓ |
-| Refunds, payment detail | | | | | | | | ✓ | ✓ |
-| Platform insights | | | | own events only *(proposed)* | | | ✓ | ✓ | ✓ |
-| Membership tiers/prices | | | | | | | | | ✓ |
-| Grant/revoke organiser and admin roles | | | | | | | | | ✓ |
-| Audit log | | | | | | | | | ✓ |
-| Revoke a user's sessions *(proposed admin action)* | | own (`logout-all`) | own | own | | | | | ✓ |
-
-## 3. Route inventory (current)
-
-Legend — Auth: `—` none · `user` session · `org` session + organiser · `org*` session + `manageableEvent`
-(owner, `super_admin` or `event_manager`) · `admin:X` admin role set `X` from `lib/handlers/admin.js:22-37` ·
-`bearer` `CRON_SECRET` · `sig` provider signature/secret. CSRF = `X-CSRF-Token` required. RL = rate limited.
-
-### Public pages (cacheable, `s-maxage=60`)
-`GET /`, `/events`, `/events/:slug`, `/trips`, `/trips/:slug`, `/nightlife`, `/dating`, `/weekend-parties`,
-`/dinners`, `/meetups`, `/meetups/:city`, `/membership`, `/submit-event`, `/partner-with-us`, `/become-a-host`,
-`/list-your-venue`, `/faq`, `/trust-safety`, `/community-guidelines`, `/privacy`, `/terms`, `/refunds`, `/contact`,
-`/sitemap.xml`, `/robots.txt`. Private venue data never reaches these (see `toPublicEvent`).
-
-### Member shells (`no-store`; data loads from the API)
-`GET /signin`, `/me`, `/bookings/:id`.
-
-### Auth
-| Method | Path | Auth | CSRF | RL |
-|---|---|---|---|---|
-| GET | `/auth/telegram/start`, `/auth/telegram/callback` | — | state+PKCE+nonce | 20/10 min |
-| POST | `/api/auth/telegram` | — (signed initData/widget) | — | 20/10 min |
-| POST | `/api/auth/dev` `{persona}` | local only: 404 on Vercel, without `DEV_LOGIN=true`, in production (`NODE_ENV`/`VERCEL_ENV`), or with a non-local `DATABASE_URL`; signs in seeded personas only (`docs/LOCAL_TESTING.md`) | — | — |
-| POST | `/api/auth/logout` | user if signed in (no-op otherwise); revokes this session | ✓ when signed in | — |
-| POST | `/api/auth/logout-all` | user; revokes all of the user's sessions | ✓ | — |
-| POST | `/api/auth/confirm-age` | user | ✓ | — |
-| GET | `/api/me`, `/api/me/bookings`, `/api/me/profile`, `/api/bookings/:id` | user, scoped to `user_id` | — | — |
-| PATCH | `/api/me/profile` | user | ✓ | 30 |
-| POST | `/api/bookings`, `/api/events/:id/book`, `/api/membership/checkout` | user (21+) | ✓ | ✓ |
-
-### Public API
-`GET /api/health` (names only, never values), `GET /api/events` (public fields only),
-`POST /api/leads/:type` (RL 5/h, honeypot), `POST /api/events/submit` (RL 5/h, honeypot), `POST /api/analytics` (RL 120/min).
-
-### Organiser (`lib/handlers/organiser.js`)
-| Method | Path | Auth | CSRF/RL |
-|---|---|---|---|
-| GET | `/organiser`, `/organiser/new`, `/organiser/events/:id`, `/organiser/drafts/:id/preview` | page state (signed out / not organiser / ok); preview owner-scoped | `no-store`, `noindex` |
-| GET | `/media/event-images/:id` | public once published; owner only while draft | — |
-| GET | `/api/organiser/context`, `/drafts`, `/drafts/:id`, `/drafts/:id/check`, `/events` | org, owner-scoped | — |
-| POST/PUT/DELETE | `/api/organiser/drafts`, `/drafts/:id`, `/drafts/:id/publish`, `/drafts/:id/images`, `/drafts/:id/images/:image` | org, owner-scoped | ✓ / 240 per 10 min (publish 20, images 40) |
-| GET | `/api/organiser/events/:id/guests` | org* | — |
-| POST | `/api/organiser/bookings/:id/approve`, `/decline` | org* (event resolved from the booking) | ✓ |
-
-### Webhooks and cron
-`POST /api/telegram/webhook` (secret header, constant-time, `update_id` dedupe) ·
-`POST /api/payments/webhook/:provider` (HMAC; Cashfree timestamp window; `webhook_events` dedupe; amount must match — fails closed) ·
-`POST /api/membership/superprofile/webhook` (shared secret, RL, idempotent) ·
-`GET /api/cron/:job` (bearer `CRON_SECRET` ≥16 chars; jobs: expire-holds, reconcile, memberships, notifications, feeds, cleanup).
-
-### Admin (`/admin` shell + `/api/admin/*`; every handler calls `guard()`; writes add CSRF + RL 120/min + audit)
-| Area | Endpoints | Roles |
-|---|---|---|
-| Session, overview | `GET session`, `GET overview` | any admin |
-| Insights | `GET insights` | super_admin, finance, event_manager |
-| Telegram integration | `GET integrations/telegram` | super_admin |
-| Discovery | `GET/POST feeds`, `PATCH feeds/:id`, `POST feeds/:id/fetch`, `GET candidates`, `POST candidates/:id/approve|reject` | super_admin, event_manager, moderator |
-| SuperProfile | `GET superprofile` | super_admin, finance |
-| Events | `GET events`, `GET events/:id`, `GET /admin/preview/:id` · `POST events`, `PATCH events/:id`, `POST events/:id/status` | read: any admin · write: super_admin, event_manager |
-| Attendees | `GET events/:id/attendees` | super_admin, event_manager, support |
-| Check-in | `POST bookings/:id/check-in` | super_admin, event_manager, support |
-| Bookings | `GET bookings` | super_admin, event_manager, finance, support |
-| Refunds | `POST payments/:id/refund` | super_admin, finance |
-| Memberships | `GET memberships`, `POST entitlements/:id/revoke` | read: super_admin, finance, support, moderator · revoke: super_admin, moderator |
-| Leads | `GET leads`, `PATCH leads/:id` | super_admin, event_manager, support |
-| Safety reports | `PATCH reports/:id` | super_admin, moderator |
-| Media | `GET/POST media`, `PATCH media/:id` | super_admin, moderator |
-| Tiers | `GET tiers` · `PATCH tiers/:id` | read: any admin · write: super_admin |
-| Admins, organisers, audit | `GET/POST admins`, `GET/POST organisers`, `GET audit` | super_admin |
-
-## 4. Proposed routes (not built yet)
-
-| Persona | Route | Milestone |
-|---|---|---|
-| Auth | `GET /auth/google/start`, `GET /auth/google/callback`; `POST /api/me/identities/:provider/unlink` | M3 |
-| Guest | `/me/bookings` (upcoming / past / requests), `/me/tickets/:id` (QR pass), `/me/settings` (privacy, sessions, export, delete); `POST /api/bookings/:id/cancel`; `GET /api/me/export`; `POST /api/me/delete` | M4 |
-| Organiser | `/organiser/events/:id/{guests,tickets,edit,analytics,scan,staff}`; `POST /api/organiser/events/:id/check-in` (signed ticket token, event-scoped); `PUT /api/organiser/events/:id` (validated edit); `POST/DELETE /api/organiser/events/:id/staff` | M5 |
-| Admin | `/admin/{users,organisers,roles,events,moderation,bookings,payments,analytics,audit,health}`; `POST /api/admin/users/:id/sessions/revoke`; `POST /api/admin/events/:id/review` | M6 |
-| Analytics | `GET /api/organiser/events/:id/analytics`, `GET /api/organiser/analytics.csv`, admin equivalents | M7 |
-
-## 5. Test obligations
-Every row of the matrix gets one **allowed** and at least one **denied** automated test (signed out, wrong role,
-another organiser, unassigned staff). Gaps today: check-in (no test), CSRF on organiser writes, second-organiser
-decline / manage page / image delete / events list, revoked organiser. These are scheduled in M5/M6 with the
-features they touch; see `docs/TEST_STRATEGY.md`.
diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md
deleted file mode 100644
index c5c491c..0000000
--- a/docs/RUNBOOK.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# Runbook
-
-Health first: `GET /api/health` → `database: ok` and each config item `configured`. Logs: Vercel → Project → Logs (JSON lines with `reqId`; tokens, initData and payment payloads are never logged).
-
-## Webhook failures
-
-### Razorpay webhook not arriving / failing
-1. Razorpay Dashboard → Webhooks → the endpoint → delivery log. 401 = secret mismatch (`RAZORPAY_WEBHOOK_SECRET` must equal the secret set on that webhook; test and live webhooks have separate secrets). 5xx = our processing error — check Vercel logs for `payment webhook` / `request failed`.
-2. Razorpay disables a webhook after 24h of failures. Re-enable it in the dashboard.
-3. Missed payments are recovered by the daily cron (`reconcile`), or immediately:
- `curl -H "Authorization: Bearer $CRON_SECRET" https:///api/cron/reconcile`
- It asks Razorpay about every `created` payment older than 10 minutes and applies the result through the same idempotent code path.
-
-### Telegram webhook
-1. `node scripts/telegram-setup.js` prints `getWebhookInfo` (pending updates, last error). Re-running it is safe.
-2. 401s in logs = `TELEGRAM_WEBHOOK_SECRET` differs from the one passed to `setWebhook` → re-run the setup script after fixing the env var.
-3. Updates that fail return 500 and Telegram retries; duplicates are ignored by `update_id`.
-
-### Bot DMs / invites failed
-- Admin → Overview → "Invite failures". The `notifications` table has `last_error`:
- - `user_has_not_started_bot` — the member must open the bot and press Start (the booking page shows the link). Then `/start` re-sends the invite.
- - `not enough rights` — make the bot an admin with *Invite users* + *Ban users* in that chat.
- - `NOT CONFIGURED: chat id …` — set `TG_CHAT_ID_EVENTS` / `TG_CHAT_ID_TIER_n` (or the event's chat id in admin).
-- Retries run with backoff (up to 6 attempts); force a run: `curl -H "Authorization: Bearer $CRON_SECRET" https:///api/cron/notifications`.
-
-## Refunds
-- Admin → Bookings & payments (finance or super_admin) → **Refund** on a paid payment. Full refund via provider (Razorpay `receipt` makes it idempotent), booking → `refunded`, invites revoked, member DM'd. Stars memberships refund via `refundStarPayment` and remove the member from the tier chat.
-- **Refunds due** (Overview KPI, filter `refund_due`): payments that completed after the seat hold lapsed when the event was full or cancelled. Refund each one — the money must not be kept.
-- Cancelling an event (Admin → Events → Cancel) DMs confirmed attendees that they will be refunded; then refund each paid booking from Bookings.
-
-## Revoking access
-- Membership: Admin → Memberships → search → **Revoke** (removes from the tier chat via ban+unban, so the person can rejoin later if they pay again).
-- Leaked invite: anyone who joins with an invite issued to someone else is removed automatically and the invite is revoked (see audit log `invite.misuse_removed`).
-- Ban a user entirely: `UPDATE users SET status = 'banned' WHERE telegram_user_id = …;` — they can no longer sign in, book or pay. Remove them from chats via Telegram.
-
-## Rotating secrets
-| Secret | Steps | Effect |
-|---|---|---|
-| `SESSION_SECRET` | Set new value in Vercel → redeploy | Everyone is signed out; pending OIDC logins fail once; unpaid Stars invoices created before rotation fail pre-checkout (users just retry). |
-| `CRON_SECRET` | Set new value → redeploy | Vercel Cron picks it up automatically. |
-| `TELEGRAM_WEBHOOK_SECRET` | Set new value → redeploy → `node scripts/telegram-setup.js` | Until the script runs, Telegram updates get 401 and are retried. |
-| `TELEGRAM_BOT_TOKEN` | BotFather → `/revoke` → set new token → redeploy → setup script | Old token stops immediately. |
-| `RAZORPAY_KEY_SECRET` | Dashboard → API keys → regenerate → set → redeploy | Checkouts fail until redeployed. |
-| `RAZORPAY_WEBHOOK_SECRET` | Edit webhook secret in dashboard and env at the same time → redeploy | Deliveries in between 401 and are retried. |
-| `DATABASE_URL` | Rotate in Neon/Supabase → set → redeploy | — |
-| `TELEGRAM_LOGIN_CLIENT_SECRET` | BotFather Login Widget → regenerate → set → redeploy | — |
-
-## Crons (Hobby: daily 06:00 IST)
-`/api/cron/daily` runs: `expire-holds`, `reconcile`, `memberships` (3-day reminders, expiry + removal), `notifications` (retries), `cleanup` (nonces, rate limits). Each is idempotent and can be called individually with the bearer secret.
-
-## Database
-- Migrations: `npm run migrate` (also runs in the Vercel **Production** build; Preview builds skip unless `MIGRATE_ON_PREVIEW=true` with a separate DB). Never edit an applied migration — add a new numbered file.
-- Revoke a user's sessions (compromised account): set `revoked_at = now(), revoke_reason = 'admin'` on that user's live `user_sessions` rows (an admin UI action is planned in M6). Users can do it themselves with `POST /api/auth/logout-all`.
-- Demo data: `npm run seed:demo` upserts only `is_demo` rows. Remove before launch: `UPDATE events SET status = 'archived' WHERE is_demo;`
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
new file mode 100644
index 0000000..52ff9e1
--- /dev/null
+++ b/docs/SECURITY.md
@@ -0,0 +1,101 @@
+# NIGHTLIFEZ — Security & Privacy Architecture
+
+**Status:** Active Security Policy
+**Classification:** Public / Open Source Security Guidelines
+**Reporting Contact:** `nightlifezofficial@gmail.com`
+
+---
+
+## 1. Security Principles
+
+NIGHTLIFEZ is architected under the principle of **Defense in Depth**:
+1. **Never trust client state:** The server is the exclusive source of truth for identities, entitlements, capacities, and payments.
+2. **Fail closed:** Any missing, expired, or malformed signature results in immediate request rejection (`401 Unauthorized` or `403 Forbidden`).
+3. **Data minimization:** Only essential user attributes are gathered; private venue locations and attendee contact details are restricted until ticket confirmation.
+4. **Zero secret exposure:** Secrets exist strictly within server runtime environment variables and are never bundled into client scripts.
+
+---
+
+## 2. Authentication & Session Security
+
+### A. Session Token Architecture (`sm_session`)
+- **Transport Security:** Sessions are delivered via HTTP-only, Secure, SameSite=Lax cookies with a strict 7-day expiration.
+- **Cryptographic Signing:** Session payloads contain user ID, session UUID, and expiration timestamp, signed using `SESSION_SECRET` via HMAC-SHA256.
+- **Server-Side Revocation:** Every authenticated request verifies the session UUID against the PostgreSQL `user_sessions` table. If the session has been revoked, or the user's status is `banned`, the session is rejected immediately.
+- **Instant Revocation Endpoints:**
+ - `POST /api/auth/logout`: Revokes the current session row.
+ - `POST /api/auth/logout-all`: Revokes all active sessions for the user.
+
+### B. Telegram Authentication Verification
+- **Mini App `initData`:**
+ - Validates `hash` parameter against `HMAC-SHA-256("WebAppData", bot_token)`.
+ - Rejects authentication if `auth_date` is older than 300 seconds.
+ - Replay attacks are mitigated by enforcing single-use nonce checks.
+- **Telegram Login Widget:**
+ - Validates hash against `SHA-256(bot_token)`.
+ - Rejects any client-supplied user identifiers that do not match the cryptographic payload.
+
+---
+
+## 3. Request Security & CSRF Mitigation
+
+### A. Anti-CSRF Token Generation
+- All state-mutating HTTP methods (`POST`, `PUT`, `PATCH`, `DELETE`) require an `X-CSRF-Token` header.
+- The CSRF token is cryptographically derived:
+ $$\text{CSRF Token} = \text{HMAC-SHA256}(\text{SESSION\_SECRET}, \text{session\_id} + \text{"csrf"})$$
+- Requests without a valid matching token fail with `403 Forbidden`.
+
+### B. Input Validation & Schema Enforcement
+- All incoming payloads are parsed and validated using strict **Zod** schemas.
+- Extra, unexpected, or prototype pollution fields are automatically stripped or rejected.
+- Form submissions (Host, Partner, Venue applications) incorporate hidden honeypot fields to trap automated spam bots.
+
+### C. SQL Injection Immunity
+- Direct string interpolation into SQL queries is prohibited across the codebase.
+- All database operations use parameterized queries (`$1, $2, ...`) via the `pg` client.
+
+### D. Cross-Site Scripting (XSS) Prevention
+- All server-rendered HTML components utilize an auto-escaping `html` template literal tag.
+- Dynamic user content is sanitized before insertion into the DOM.
+- A strict Content Security Policy (CSP) header is emitted on all HTML responses:
+ ```
+ default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;
+ ```
+
+---
+
+## 4. Payment & Checkout Safeguards
+
+### A. Feature Flag Kill Switches
+To protect against unauthorized transactions or unreviewed merchant pathways:
+- `ENABLE_LIVE_PAYMENTS=false`: Disables outbound live merchant links; forces test/sandbox mode.
+- `UPI_CHECKOUT_ENABLED=false`: Blocks native UPI payment routing until operational and compliance approval is granted.
+
+### B. Webhook Signature Verification
+- Inbound payment webhooks (SuperProfile / UPI) require a valid cryptographic signature header (`X-Webhook-Secret`).
+- Missing or mismatched secrets return `401 Unauthorized` without reading the payload.
+- Every processed event ID is recorded in `webhook_events(provider, provider_event_id)` with a unique constraint to ensure strict idempotency.
+
+### C. Digital Ticket Pass Authentication
+- Door admission passes contain an encrypted QR code payload signed with `TICKET_SECRET` using HMAC-SHA256:
+ $$\text{QR Signature} = \text{HMAC-SHA256}(\text{TICKET\_SECRET}, \text{booking\_id} + \text{user\_id} + \text{event\_id})$$
+- Prevents screenshot duplication, forgery, and pass sharing.
+
+---
+
+## 5. PII & Privacy Protections
+
+1. **Hidden Venue Locations:** Precise venue addresses are withheld on public event listings. Addresses are revealed only to confirmed attendees via Telegram DM and booking view.
+2. **Minimal Data Storage:** User profiles contain only the essential Telegram identifier, username, and contact handle.
+3. **Log Sanitization:** Server logs are output as structured JSON lines. Request bodies, query parameters, tokens, credentials, and payment details are strictly excluded from logging statements.
+4. **Automated Secret Auditing:** The test suite executes automated scanner assertions (`test/m9-security-audit.test.js`) ensuring that no server secret names or secret values exist within client-accessible static files.
+
+---
+
+## 6. Vulnerability Disclosure Policy
+
+If you discover a potential security vulnerability within NIGHTLIFEZ, please report it immediately:
+
+- **Security Contact:** `nightlifezofficial@gmail.com`
+- **Response SLA:** Acknowledgement within 24 hours; remediation assessment within 48 hours.
+- **Responsible Disclosure:** Please allow our engineering team reasonable time to patch any confirmed issue before public disclosure.
diff --git a/docs/SPEC.md b/docs/SPEC.md
deleted file mode 100644
index fc5dee6..0000000
--- a/docs/SPEC.md
+++ /dev/null
@@ -1,97 +0,0 @@
-# StrangersMeetup — Launch MVP Spec
-
-Status: locked for launch build · 2026-10-26 · Source of scope: owner brief (sections 1–8)
-
-## Problem
-StrangersMeetup today looks like a SaaS template, displays invented events and scarcity, and has no way to take money for a real event. Adults (21+) in Tamil Nadu, Puducherry, Karnataka and Kerala who want to meet new people have no credible way to discover, pay for, and get into a StrangersMeetup event. Until one honest money loop works, the brand cannot launch.
-
-## Goals (launch)
-1. **One working, verifiable money loop**: real event → Book Tickets → verified (sandbox) payment → booking `confirmed` → bot DM → single-use invite → visible in admin. Target: 100% of webhook-verified payments produce exactly one confirmed booking and one invite attempt; 0 bookings confirmed from client redirects.
-2. **Zero fabricated numbers**: every count on the site is a DB query; empty DB renders empty states, not filler.
-3. **Credible brand**: warm editorial public site, crawlable, Lighthouse mobile performance ≥ 85.
-4. **Operable by a small team**: admin can publish events, see bookings/payments, refund (finance), read leads, manage media, without touching the DB.
-
-## Non-goals (explicitly deferred)
-| Deferred | Why |
-|---|---|
-| Feed aggregator / scraping | Legal + quality risk; no launch value. |
-| Vibe Match radar, compatibility scores | Unbuilt; would be fabricated signal. |
-| Intro double opt-in flow | Needs moderation design; "Coming soon" label only. |
-| Streaks, badges, auto forum topics, live poll FOMO edits | Engagement features before there is an audience. |
-| International / out-of-region trips inventory | Region is TN/PY/KA/KL. |
-| Analytics beyond basic funnel events | Basic funnel only (view → book click → checkout → paid). |
-| Final pricing | Pricing session pending — all prices `tbd`/NULL. |
-
-## Personas
-- **Visitor** (anonymous, 21+): browses events, reads FAQ.
-- **Member** (Telegram-signed-in user): books tickets, buys membership, receives invites.
-- **Partner / host / venue lead**: submits a form.
-- **Admin roles**: `super_admin`, `event_manager`, `moderator`, `finance`, `support`.
-
-## User stories (priority order)
-1. As a visitor, I can see upcoming events with city/date/category filters and honest price/status ("Price to be announced"), so I can decide without signing in.
-2. As a visitor, I can open an event page with inclusions, refund policy and venue-privacy note, and press **Book Tickets**.
-3. As a member, I sign in with Telegram (Mini App initData or Login Widget) only when I book or buy membership.
-4. As a member, after paying in the provider's hosted checkout, I receive a Telegram DM confirming my booking and a single-use invite (valid 24h) to the event group — even if I closed the browser.
-5. As a member, if payment fails or I abandon checkout, nothing is granted and my hold is released after 15 min.
-6. As a member, I can buy a membership tier with Telegram Stars (once priced), get an invite to that tier's private chat, get a reminder 3 days before expiry, and am removed when it expires.
-7. As a partner/host/venue, I submit a native form and get a clear confirmation.
-8. As an event manager, I create/publish/cancel events and see the check-in list.
-9. As finance, I see payments with provider txn ids and can issue a refund (which updates the booking).
-10. As super_admin, I edit membership tiers (prices stay NULL until the owner sets them) and authorise media.
-
-Edge cases: sold-out (capacity reached incl. live holds) → "Sold out"; price `tbd` → button shows "Bookings open soon", checkout refused server-side; duplicate webhooks → no-op; payment arrives after hold expired and event is full → booking marked for refund, admin alerted; user already has an active booking for the event → returned existing booking, no second charge; bot not configured → booking still confirmed, invite marked failed and retried by cron, visible as "invite failures" in admin.
-
-## Requirements
-
-### P0 — must ship
-| Area | Requirement | Acceptance |
-|---|---|---|
-| Data | Postgres schema per brief (users, events, bookings, payments, webhook_events, membership_tiers, entitlements, invite_links, leads, media, admin_users, audit_log) + sessions/nonces/rate limits/notifications support tables. | Migrations run idempotently via tracked runner; no SQLite in prod. |
-| Events | List + detail from DB; demo rows labelled "Sample"; badges only when true; JSON-LD only for real published non-demo events. | Empty DB → empty state + "Get event alerts on Telegram". |
-| Auth | initData HMAC (secret = HMAC_SHA256("WebAppData", token)), constant-time, `auth_date` ≤ 300s, replay rejected; Login Widget (secret = SHA256(token)); httpOnly Secure SameSite=Lax session. | Bad hash / stale / replay → 401. No user id ever accepted from client body. |
-| Booking | Hold `pending_payment` 15 min; capacity checked in tx with `SELECT … FOR UPDATE`; one active booking per user per event. | N concurrent checkouts never exceed capacity. |
-| Payments | `PaymentProvider {createCheckout, verifyWebhook, refund, fetchStatus}`; Razorpay adapter (decision in `PAYMENTS_DECISION.md`), Cashfree adapter behind same interface; test keys only while `ENABLE_LIVE_PAYMENTS=false`; UI shows "Test mode". | Bad signature → 401; duplicate → 200 no-op; failed payment grants nothing; paid → one confirmed booking. |
-| Membership | Stars `createInvoiceLink` (XTR, `subscription_period`), pre-checkout validation (tier active, price set, user eligible), `successful_payment` idempotent on `telegram_payment_charge_id`. | Tier → correct chat; expiry → removed (ban+unban). |
-| Bot | Webhook with secret header; `/start` (incl. `event_` deep link), `/events`, `/mybookings`, `/membership`, `/help`, `/report`; Mini App button; confirmation DM + `createChatInviteLink(member_limit 1, expire 24h)`. | Without token: everything built, health shows `NOT CONFIGURED`. |
-| Cron | `/api/cron/*` with `CRON_SECRET`, idempotent: expire holds, revoke expired entitlements, reminders, retry failed notifications/invites, reconcile pending payments via `fetchStatus`. | Re-running a cron changes nothing the second time. |
-| Forms | Partner / Host / Venue → `leads`; zod validation, honeypot, rate limit. | 6th submission/hour from same IP → 429. |
-| Admin | Telegram login + `admin_users` allowlist (bootstrap via `ADMIN_BOOTSTRAP_TELEGRAM_ID`); role checks per API; CSRF on mutations; `audit_log` on every write. Screens: Overview KPIs, Events, Bookings & Payments, Memberships, Leads, Media, Tiers. | Non-admin → 403; wrong role → 403; KPIs show "No data yet" when empty. |
-| Site | Homepage order per brief; pages `/events/[slug]`, `/trips/[slug]`, `/partner-with-us`, `/become-a-host`, `/list-your-venue`, `/faq`, `/trust-safety`, `/privacy`, `/terms`, `/refunds`, city pages; sitemap/robots/canonical/OG. | Homepage public & crawlable (no age-gate overlay); 21+ confirmed at sign-in/booking. |
-| Ops | `/api/health` (DB ping + config status), structured JSON logs with request id, no secrets/initData/payment payloads logged. | Grep of public assets finds no secret names' values. |
-
-### P1 — fast follow
-- Social proof widget (real confirmed bookings ≥ `SOCIAL_PROOF_MIN`) — built in launch but hidden until threshold.
-- Gender policy display ("gender-balanced tables") per event; aggregate counts only when each bucket ≥ 5 (shipped as policy text only at launch; counts not displayed).
-- Event alerts opt-in via bot `/start alerts`.
-
-### P2 — design for, don't build
-- Waitlists, multi-ticket bookings (schema keeps `quantity` out for now; one ticket per user per event).
-- BookMyShow / external payment as alternate pay source: field + outbound link only, no sync.
-- Intro double opt-in (users table has no profile fields beyond alias/city to keep it possible later).
-
-## Membership & pricing rules
-- Tier rows: `tier_1`, `tier_2`, `tier_3` (names editable), `stars_amount NULL`, `period_seconds 2592000`. Public shows "Announcing soon"; checkout returns 409 until super_admin sets an amount. No "most popular"/decoy labels.
-
-## FAQ (12) — DRAFT, replace with owner's list
-The owner brief references "12 questions from my spec doc" which is not in the repo. Drafted from implemented features only:
-1. What is StrangersMeetup? 2. Who can join? (21+, TN/PY/KA/KL) 3. How do I book a ticket? 4. Why do I need Telegram? 5. When do I get the venue address? 6. What is included in the ticket? 7. Can I cancel or get a refund? 8. How does membership work? 9. How are payments processed? 10. Is my data private? 11. How do you keep events safe? 12. How do I report someone or something?
-
-## Success metrics
-- Leading (first 2 weeks after first real event): checkout-start → paid conversion ≥ 40%; webhook-to-DM latency p95 < 30s; invite failure rate < 2%; 0 double bookings; 0 unreconciled payments > 24h.
-- Lagging (first 3 months): ≥ 1 repeat booking per 4 attendees; refund rate < 10%; membership activations (once priced).
-Measured from DB (`bookings`, `payments`, `notifications`, `analytics_events`).
-
-## Open questions
-| Question | Owner | Blocking? |
-|---|---|---|
-| Final ticket prices and Stars amounts | Owner (pricing session) | Blocks live, not build |
-| First real event details + authorised media | Owner | Blocks launch content |
-| Bot token, webhook secret, chat IDs; rename `Telegram_HTTP_API` → `TELEGRAM_BOT_TOKEN` | Owner | Blocks live bot test |
-| Payment provider test keys | Owner | Blocks sandbox E2E |
-| Legal entity name, grievance officer, support email for legal pages | Owner/legal | Blocks go-live |
-| Vercel Pro upgrade (Hobby is non-commercial) | Owner | Blocks live payments |
-| The 12 FAQ questions from owner's doc | Owner | Non-blocking |
-
-## Timeline / phasing
-Phase 2 data → 3 site → 4 Telegram → 5 payments → 6 admin → 7 tests/review/preview → 8 go-live checklist (owner-executed).
diff --git a/docs/TELEGRAM_SETUP.md b/docs/TELEGRAM_SETUP.md
deleted file mode 100644
index bfad174..0000000
--- a/docs/TELEGRAM_SETUP.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# Telegram setup (owner)
-
-Status today: **NOT CONFIGURED.** All bot, invite, Mini App and Stars code is built and tested against a stubbed Bot API; nothing is live until the steps below are done. Never paste tokens or secrets into chat — set them only as Vercel environment variables.
-
-## 1. Bot (BotFather)
-1. In Telegram open **@BotFather** → `/newbot` (or pick your existing bot). Name: *StrangersMeetup*; username e.g. `StrangersMeetupBot` (must be one you own — the old site linked `@StrangersMeetupBot` without it being verified).
-2. Set the profile photo to the site logo (`public/favicon.svg`) — Telegram shows it on the login prompt.
-3. Copy the token. In Vercel → Project → Settings → Environment Variables add **`TELEGRAM_BOT_TOKEN`** (Preview + Production).
- - The project currently has a variable named `Telegram_HTTP_API`. The code accepts it as a fallback *only if it is shaped exactly like a bot token*, but please rename it to `TELEGRAM_BOT_TOKEN` and add it to Preview too.
-4. Add **`TELEGRAM_BOT_USERNAME`** (without `@`).
-5. Generate a webhook secret (16–256 chars of `A-Z a-z 0-9 _ -`), e.g. `openssl rand -hex 32`, and add **`TELEGRAM_WEBHOOK_SECRET`**.
-6. BotFather → your bot → **Bot Settings → Configure Mini App / Menu Button** → URL = your site (`PUBLIC_SITE_URL`). (`scripts/telegram-setup.js` also sets the menu button.)
-7. BotFather → **Payments**: nothing to connect for Stars. For sandbox Stars testing use Telegram's *test environment* (separate test account + test bot) and set `TELEGRAM_TEST_ENV=true` on the preview that uses the test bot.
-
-## 2. Website sign-in (Telegram Login, OpenID Connect)
-Telegram's current web login is OpenID Connect (the old iframe widget is archived).
-1. BotFather mini app → select bot → **Login Widget** → add Allowed URLs:
- - `https://` and `https:///auth/telegram/callback`
- - the same for the preview URL you test on.
-2. Copy **Client ID** → `TELEGRAM_LOGIN_CLIENT_ID`, **Client Secret** → `TELEGRAM_LOGIN_CLIENT_SECRET`.
-3. Without these two, `/signin` falls back to the legacy widget (needs `/setdomain` in BotFather for the site domain).
-
-## 3. Private groups (one per membership tier + one for event coordination)
-Create **private supergroups** (or channels for broadcast-only):
-
-| Purpose | Env var |
-|---|---|
-| Event coordination group (venue reveal for paid attendees) | `TG_CHAT_ID_EVENTS` |
-| Tier 1 — Insider | `TG_CHAT_ID_TIER_1` |
-| Tier 2 — Social Plus | `TG_CHAT_ID_TIER_2` |
-| Tier 3 — VIP Circle | `TG_CHAT_ID_TIER_3` |
-
-For each chat:
-1. Add the bot as **administrator** with: *Invite users via link* and *Ban users* (and *Delete messages* for moderation). Nothing else is needed.
-2. Turn off "Approve new members" (invites are single-use, `member_limit: 1`, 24h expiry).
-3. Get the chat id: after the webhook is set (step 4), add the bot and post any message; or temporarily add **@RawDataBot**/**@getidsbot**, read `chat.id` (starts with `-100…`), then remove it.
-4. Put the id in the matching env var. A per-event group can instead be set on the event in **/admin → Events → Telegram chat id**.
-
-## 4. Point Telegram at the site
-After the env vars are on the deployment (and `PUBLIC_SITE_URL` is set to it):
-```
-vercel env pull .env.setup --environment=production # or preview
-set -a; . ./.env.setup; set +a
-node scripts/telegram-setup.js
-rm .env.setup
-```
-It calls `setWebhook` (with `secret_token` and `allowed_updates` including `chat_member`, which Telegram only sends when listed explicitly), `setMyCommands`, and the Mini App menu button. Re-runnable.
-
-## 5. Verify
-- `GET /api/health` → `telegramBot`, `telegramWebhookSecret`, `telegramEventsChat` all `configured`.
-- DM the bot `/start` → welcome + "Open StrangersMeetup" button.
-- `/events`, `/mybookings`, `/membership`, `/report test`, `/help`, `/terms`, `/paysupport` all answer.
-- Admin: add yourself via `ADMIN_BOOTSTRAP_TELEGRAM_ID` (your numeric Telegram id) and open `/admin`.
-
-## What the bot does
-| Trigger | Behaviour |
-|---|---|
-| `/start` | Welcome + Mini App button. `start=event_` shows that event; `start=booking_` re-issues your invite; `start=alerts` opts in to new-event alerts (`/stopalerts` to opt out). |
-| Paid booking (verified webhook) | DM with event details + single-use 24h invite to the event chat. |
-| Stars membership paid | DM + invite to tier chat. Renewals extend expiry (DM, no new invite). |
-| 3 days before expiry | Reminder DM. |
-| Expiry (+1h grace) | Removed from tier chat (ban then unban — not a permanent ban) + DM. |
-| Someone joins with another person's invite | Removed automatically; invite revoked; audit log entry. |
-| `/report ` | Stored in `reports`, visible in admin. |
diff --git a/docs/TEST_STRATEGY.md b/docs/TEST_STRATEGY.md
deleted file mode 100644
index 39ade22..0000000
--- a/docs/TEST_STRATEGY.md
+++ /dev/null
@@ -1,66 +0,0 @@
-# Test strategy
-
-## Layers
-| Layer | Tool | Runs against | Command |
-|---|---|---|---|
-| Syntax/JSON | `scripts/lint.js` (`node --check`) | all `.js`/`.json` | `npm run lint` |
-| Integration | `node:test`, real router in-process, real Postgres, external HTTP stubbed (`test/helpers.js`) | a **dedicated** local test DB (the harness drops the `public` schema) | `TEST_DATABASE_URL=postgres://localhost/sm_pv2_test npm test` |
-| End-to-end | Playwright + axe (dev-only deps), Chromium: `desktop` 1280×800, `mobile` Pixel 7, and the `responsive` admin matrix (320, 375, Pixel 7, tablet 768, desktop 1280); WebKit/iPad still planned | local server on :3100 + `sm_e2e` re-seeded by `seed:local`; `SKIP_DOTENV=true`, so `.env` is never read | `npm run test:e2e` (see `docs/LOCAL_TESTING.md`) |
-| Accessibility *(M2+)* | `@axe-core/playwright` (WCAG 2.1 A/AA, no serious/critical) + keyboard assertions; manual screen-reader pass still planned | same | part of `npm run test:e2e` |
-| Visual | Full-page screenshots per project and viewport in `test-results/screenshots/` (`responsive-admin--.png` for the admin matrix), reviewed by a person after every UI change | same | written by every `npm run test:e2e` run |
-
-There is no build step and no type checker in this repo; reports say so rather than claiming those checks passed.
-
-Before any run that wipes or re-seeds a database, confirm the target: `TEST_DATABASE_URL` must be a dedicated local
-test DB and `E2E_DATABASE_URL` (default `postgres://localhost/sm_e2e`) must be local — `e2e/env.js` refuses anything
-else. `npm run seed:local` refuses non-local URLs, production `NODE_ENV`/`VERCEL_ENV` and Vercel builds, with no override.
-
-## Current coverage
-Unit/integration: 149 tests (`admin`, `auth`, `discovery`, `insights`, `organiser`, `payments`, `site`, `telegram`,
-`safety` for M1, `personas` for M8). Browser: `guest-booking`, `organiser-create`, `admin`, `private-venue`,
-`mobile-layout` on desktop + mobile, and `admin-responsive` across the five-size matrix (M2).
-
-## Test personas and their limits
-Six local-only personas (`lib/dev-personas.js`, seeded by `npm run seed:local`, signed in through `/signin` only when
-`DEV_LOGIN=true` with a local DB and no production env). The **staff persona is the platform-wide `support` admin
-role, not a true event-scoped staff role**: it can open attendee and booking lists and check guests in across *all*
-events. Tests that use it prove the `support` role's server-side limits (no event edits, refunds, roles, insights or
-audit), not event scoping. This is a test limitation, not the intended final permission model; event-scoped staff
-permissions are future work for M5.
-
-Google OAuth is unconfigured and paid checkout is disabled (`ENABLE_LIVE_PAYMENTS=false`, no provider keys) in every
-test environment; tests assert that paid tickets cannot be bought, never that a payment succeeds.
-
-## Known gaps (scheduled)
-| Gap | Milestone |
-|---|---|
-| Check-in: allowed roles, duplicate (409), wrong role, organiser/staff scope | M5 |
-| Event-scoped staff role (`event_staff`) and tests that staff cannot see or check in other events | M5 |
-| WebKit / iPad and a manual screen-reader pass of the admin console | M2 follow-up |
-| CSRF rejection on every organiser write (the harness adds the token automatically, so add explicit negatives) | M5 |
-| Second organiser: decline, manage page, image delete, events list; revoked organiser | M5 |
-| Full role matrix, allowed + denied per row | M6 |
-| Google OIDC tampering/replay/linking | M3 |
-| Cashfree webhook signature/timestamp | M9 |
-| Client-side wizard safety copy (localStorage) | M9 (E2E) |
-
-## Rules
-- Tests use synthetic identities only; nothing calls a real provider.
-- A test that guards a fix must be shown to fail on the old code at least once (done for M1).
-- Never delete or weaken an existing test to get green; if behaviour changes intentionally, the test changes in the
- same commit with the reason in the message.
-- Every new endpoint ships with: signed-out denial, wrong-role/other-owner denial, CSRF denial (writes), invalid
- input, and the happy path.
-
-## End-to-end journeys (M9 suite; also the manual UAT script in `docs/MANUAL_UAT_GUIDE.md`, M8)
-- **A — New guest (mobile first):** home → filter → event → rules/tiers/location disclosure → free booking →
- confirmation + ticket → `/me` → refresh, sign out, sign in → booking persists → ticket checks in once, second scan refused.
-- **B — Organiser:** sign in → template draft → Basics/Tickets/Features/Preview → save, refresh, resume → publish
- free event (first event: review) → guest books (approval) → approve/decline → states update → guest list + scanner →
- analytics match seeded records → another organiser's routes return 404.
-- **C — Admin:** users/organisers/events → grant and revoke a role → enforced on the next request → moderate an event →
- booking metrics → audit log entries → a normal user's admin call is refused.
-- **D — Adversarial:** unauthenticated access, self-promotion, cross-organiser IDs, duplicate submits, concurrent
- bookings at capacity, duplicate check-in, expired/revoked session, malformed ids, refresh mid-draft, stale draft
- (409), missing env vars, paid checkout disabled, spoofed provider callback, private venue absent from API, page
- source, metadata, sitemap and logs, keyboard-only, reduced motion, slow network / 500s.
diff --git a/docs/UI_UX_AUDIT.md b/docs/UI_UX_AUDIT.md
deleted file mode 100644
index e509a24..0000000
--- a/docs/UI_UX_AUDIT.md
+++ /dev/null
@@ -1,230 +0,0 @@
-# StrangersMeetup — UI/UX quality audit (pre-release)
-
-- **Branch:** `feature/m2-responsive-admin` · audited from head `6bb6f08`; first-pass fixes in `515154d`; the follow-up pass in §10 is a later commit on the same branch.
-- **Audited:** 2026-10-29, on a local build only (Node server + local Postgres `sm_e2e`, `DEV_LOGIN=true`, `ENABLE_LIVE_PAYMENTS=false`).
-- **Verification levels used in this report**
- - **Local** = observed on my machine against seeded demo data. Everything below is at this level unless stated.
- - **Preview** = on a Vercel preview deployment. **Not done in this audit** (deploying was out of scope).
- - **Production** = on the live site. **Not done, and nothing here may be read as production-verified.**
-- **Not done:** no screen-reader (VoiceOver/NVDA/TalkBack) pass, no real device or Safari/Firefox testing (Chromium only), no real Telegram sign-in, no real payment, no load/performance testing, no copy/legal review.
-
-## 1. Headline
-
-**Overall: 59 / 100 (58 after the first pass; re-scored in §10) — a solid, safe-by-default engineering base with a good-looking public front door, but not release-ready as a product.**
-
-The pages that exist are clean, responsive and accessible by automated measures. What holds the score down is not broken CSS but missing product: members can sign in only with Telegram (not configured here, so unverifiable), there are no event photos, paid checkout is off, a signed-in member cannot cancel a booking, event-scoped staff do not exist, and nothing has been seen on a deployed URL.
-
-### Scoring rubric (transparent)
-Each category is scored 0–100 from observed evidence; the overall score is the weighted sum.
-
-| Category | Weight | What earns points | Score | Weighted |
-|---|---|---|---|---|
-| Visual polish | 20% | Hierarchy, spacing, consistency, premium/adult-social feel, real imagery | **68** | 13.6 |
-| Mobile UX | 20% | No overflow at 320–768, tap targets, nav, forms on phones | **72** | 14.4 |
-| Core user journeys | 25% | Each journey works end to end for real users, not just personas | **50** | 12.5 |
-| Accessibility | 15% | axe clean, focus, landmarks, labels; capped without a human screen-reader pass | **70** | 10.5 |
-| Reliability | 10% | Tests, error states, no console/network errors, guarded data paths | **70** | 7.0 |
-| Launch readiness | 10% | External config done, verified on preview/prod, support/ops paths | **20** | 2.0 |
-| **Total** | 100% | | | **60.0** |
-
-I then deducted 2 points for the one issue in this audit that shipped with a green test suite (§4, D1: the suite passed while a core page scrolled sideways at 320px), because it shows the automated suite does not cover everything. **Final: 58.** Passing tests did not raise the score; they are why Reliability is 70 rather than lower.
-
-## 2. Feature-by-feature status
-
-Legend: **Pass** = observed working, no material defect · **Partial** = works with a gap · **Fail** = broken · **N/I** = not implemented. Evidence is what I observed or ran; "e2e" means the existing Playwright spec passed in my run (97 passed, 1 intentional skip).
-
-| # | Journey | Status | Evidence (local) |
-|---|---|---|---|
-| 1 | Landing page, nav, footer, CTAs | **Pass** | 30 public pages × 5 viewports crawled: HTTP 200, no console errors, no failed requests, one `h1` each. Hero is distinctive and on-brand. Mobile menu opens/closes (`375-menu-open.png`), skip-link first in tab order. Caveat: the single primary CTA is "Continue with Telegram", which cannot complete here (not configured). |
-| 2 | Event discovery, cards, filters, detail | **Partial** | Filters work on real data (city 6→2/1 results, category 6→1, "this week" → empty state). Detail pages render. Gap: every card uses the same placeholder two-circle graphic; there are no event photos, which weakens the "premium" feel. Seed titles start with "Test:" (demo data only). |
-| 3 | Free registration → booking confirmation | **Pass** (e2e + observed) | `guest-booking.spec` passes; the confirmed-booking page shows ticket, "No payment needed" and the venue (`375-booking` reviewed). The confirmation is delivered by a Telegram bot that is not configured here, so message delivery is **unverified**. |
-| 4a | Sold-out state | **Pass** | Disabled "Sold out" button, red state label (`375-event-soldout`). |
-| 4b | One-seat-left | **Pass** | `local-low-seats-trek` shows seat-left state; it lives at `/trips/…`, and `/events/` redirects there correctly. |
-| 4c | Past / cancelled | **Pass** (after §10) | First pass: button disabled but the page still showed the ticket choice, quantity picker and the venue-after-booking line (D5). §10: replaced by a status panel; server already refused bookings. |
-| 4d | Approval-required | **Pass** | "Request to join", host question field, "host approves each guest" (`375-event-approval`); organiser approve/decline covered by unit tests. |
-| 5 | Private venue privacy | **Pass** | `private-venue.spec` passes: venue absent from visitor HTML and `/api/events`, hidden from non-booked guests, pending requests, and other guests opening the booking URL; shown on own confirmed booking. Strongest area of the product. |
-| 6 | Login / logout / sessions / auth methods | **Partial** | Telegram is the only real method; it is **not configured locally, so not tested**. The persona picker is dev-only (404 off-localhost, guarded in code and tests). Server-side sessions with revocation exist (unit tests). Google sign-in: **N/I** (planned M3). Logged-out access to `/me` and `/admin` is handled (401 page / sign-in), see D6. |
-| 7 | Member dashboard & history | **Partial** | `/me` lists bookings with status and an optional profile form (`375-member-dashboard`). No cancel, no calendar add, no ticket/QR for the member — **N/I**. |
-| 8 | Organiser wizard (Basics→Tickets→Features→Preview) | **Pass** (e2e) | `organiser-create.spec` drives all four steps, publishes, and checks the public page hides the venue and that another organiser gets 404. I looked at step 1 and the draft banner on desktop/phone; I did not hand-review steps 2–4 visually. |
-| 9 | Organiser manage / attendees / analytics | **Partial** | Guest list + approve/decline exist. Per-organiser analytics: **N/I** (listed as "proposed" in `docs/ROUTES_AND_ROLES.md`; insights are platform-wide and admin-only). Editing a published event: **N/I**. |
-| 10 | Admin dashboard, sections, tables, states, moderation | **Pass** | `admin-responsive.spec` ×5 viewports + `admin.spec` pass: cards/tables, loading/empty/error/offline/forbidden, role-filtered sections, lead/report moderation. Overview and sections reviewed at 320/375/desktop. Admin uses a different typeface/visual language from the public site (D7). |
-| 11 | Staff permissions & check-in | **Partial** | Check-in works and is audit-logged (e2e); staff see only permitted sections and get 403 on admin-only APIs. But "staff" is the platform-wide `support` role, not event-scoped staff (**N/I**, M5). No camera/QR scanning. |
-| 12 | Mobile navigation & mobile versions | **Pass** | No horizontal scroll on any public page at 320/375/Pixel 7/768/1280 after fix D1; menu, forms, booking card, admin all usable. |
-| 13 | Paid checkout disabled / messaging | **Pass** | Paid event shows "Online booking not available yet", an explanatory note, a disabled tier and no buy path (`320-event-paid`). No payment keys configured; real payment provider code **not exercised**. |
-
-### Local vs. external, honestly
-| State | Features |
-|---|---|
-| **Implemented and locally tested** | Free booking, private-venue rules, organiser wizard, admin console, check-in, role gating, server-side sessions, disabled paid state |
-| **Implemented but needs external config (untested end to end)** | Telegram login, Telegram bot confirmations/invite links, cron jobs (`cron: NOT CONFIGURED`), payment provider keys, SuperProfile webhook, admin bootstrap |
-| **Not implemented** | Google sign-in, member cancel/calendar/QR, event photos in cards, per-organiser analytics, editing published events, event-scoped staff, QR check-in |
-| **Verified on preview / production** | Nothing |
-
-## 3. Visual review
-
-Reviewed screenshots at 320, 375, Pixel 7 (412), tablet 768 and desktop 1280 (§6). Overall the public site reads as a coherent, restrained dark/cream editorial brand with a distinctive hero — not a generic template. It falls short of "premium" mainly because there is no photography: event cards are all the same outlined-circles placeholder, so the listing page looks sparse and repetitive. Admin is functional and tidy but visually a separate product.
-
-| Check | Result |
-|---|---|
-| Spacing / hierarchy / typography | Good. Clear H1→lede→CTA rhythm; card text sizes consistent. |
-| Contrast | axe (WCAG 2.1 A/AA, reduced-motion) reports no serious/critical issues on the covered pages. Not exhaustively checked on every state/hover. |
-| Responsive overflow | One real defect found and fixed (D1). None remain on the 30 crawled pages × 5 viewports. |
-| Touch targets | Most primary controls ≥44px. Below 44px: the header Telegram icon button (40×40), ticket radios (20×20), consent checkbox (20×20), several plain text links (footer, card titles ~26px tall). Meets WCAG 2.2 AA minimum (24px) in most places but not the 44px target recommended for primary phone actions (D4). |
-| Loading / error / empty | Admin states covered by tests; listing empty state present. Public booking-failure messaging was not exercised (no fake failures induced). |
-| Forms | Labels present; inline field errors exist in wizard; `/submit-event` honeypot field is correctly hidden. |
-| Keyboard | Visible 2px focus outlines on every tab stop in the sampled sequence; skip link first. Admin keyboard covered by e2e. |
-| Reduced motion | Site has a reduced-motion fallback; all my captures and axe runs used `prefers-reduced-motion: reduce`. **Full-motion experience was not reviewed**, so scroll-animation quality is unassessed. |
-
-## 4. Defects
-
-Severity: P0 security/privacy/data · P1 core journey broken · P2 significant UI/UX · P3 polish. **No P0 or P1 defects were found.**
-
-| ID | Sev | Page / viewport | Defect | Repro | Status |
-|---|---|---|---|---|---|
-| D1 | **P2** | `/events/local-paid-workshop`, 320px | Page scrolled sideways (359px wide in a 320px viewport); the booking card and facts were clipped. Cause: `1fr` grid tracks and a `` grew to content width. The existing 320px test did not include paid/sold-out/cancelled/past events, so the suite stayed green. | Open at 320px width | **Fixed** + regression test |
-| D2 | **P2** | `/events`, `/meetups/:city`, all widths | Format links (Nightlife, Trips, …) rendered as an unstyled browser bullet list (no CSS for `.format-nav`), and the page header was centred while the filters/grid were left-aligned. | Open `/events` | **Fixed** (pills; left-aligned header) |
-| D3 | P3 | Event detail, desktop | WHEN and WHERE columns touched with no gap ("9:30 pm IST" ran into "Besant Nagar"). | Open any event at 1280px | **Fixed** |
-| D4 | P3 | Phones | Some primary controls under 44px (see §3). | Measure at 375px | **Fixed in §10** (≥44px at 320/375 on audited pages, regression test) |
-| D5 | P3 | Past / cancelled event detail | Still shows ticket picker, quantity and "address appears on your booking once confirmed". | Open `local-past-meetup` | **Fixed in §10** + regression tests |
-| D6 | P3 | `/admin` signed out (and non-admin) | Bare, unstyled 401/403 page with no site header; `/me` signed out also triggers a console 401 from `/api/me/bookings` before the sign-in prompt. | Open `/admin` logged out | **Partly fixed in §10**: branded access screens. The `/me` signed-out console 401 is still open. |
-| D7 | P3 | Admin vs public | Different typeface/visual language. Acceptable for an internal tool; noted for consistency. | Compare screenshots | **Open** |
-| D8 | P2 (product) | All event cards | No imagery: identical placeholder graphic. Biggest gap vs. a premium discovery product. | Open `/events` | **Partly addressed in §10**: category-specific fallback art. Still no real photography (content decision). |
-| D9 | P2 (product) | Sign-in | Single method (Telegram) and it is the only visible CTA site-wide; users without Telegram have no path. | Open `/signin` | **Open** (Google is planned M3) |
-
-## 5. Fixes made
-
-Scope was limited to clear, low-risk CSS/markup fixes inside this branch. No architecture, route, data or auth code was touched.
-
-| File | Change |
-|---|---|
-| `public/css/site.css` | `minmax(0,1fr)` tracks on `.event-grid`, `.facts`, `.tier-form`, `.tiers`, `.tier-opt`; 28px column gap and `overflow-wrap` on facts (D1, D3); new `.format-nav` pill styles (D2); cache-bust `v=5`→`v=10` |
-| `lib/views/layout.js` | `pageHeader(..., wide)` optional flag; cache-bust bump |
-| `lib/views/discovery.js`, `lib/views/pages.js` | Listing headers (`/events`, formats, city) use `wide` so they align with the grid |
-| `lib/views/admin.js` | cache-bust bump only |
-| `e2e/mobile-layout.spec.js` | 320px no-overflow test now also visits paid, sold-out, cancelled and past event pages |
-
-One of my own intermediate CSS edits briefly collapsed the ticket card on desktop; I caught it in the screenshot review and fixed it before committing (the automated tests would not have caught it).
-
-### Test results after fixes (local)
-| Check | Result |
-|---|---|
-| `npm run lint` | 92/92 files OK |
-| `npm test` (unit/integration, `sm_pv2_test`) | 149/149 pass |
-| `npm run test:e2e` (desktop + mobile + responsive, 5 viewports) | 97 passed, 1 intentional skip, 0 failed — same before and after |
-| Guard check | New 320px test **fails on the old CSS** (`div.event-main, dl.facts…` overflow) and passes with the fix |
-| Re-crawl after fixes | `/events/local-paid-workshop` @320: no overflow; other pages unchanged |
-
-## 6. Screenshots (local build, after fixes)
-
-Files are in `docs/ui-audit/`, named `-.png`. Viewports: 320×640, 375×667, Pixel 7 412×839, tablet 768×1024, desktop 1280×800 (viewport-sized captures; scrolled where noted).
-
-| Viewport | Page | File |
-|---|---|---|
-| Desktop | Home (hero) | `desktop-home.png` |
-| 320 | Home (hero) | `320-home.png` |
-| 375 | Home (hero) | `375-home.png` |
-| Desktop / Tablet / Pixel 7 | `/events` | `desktop-events.png`, `tablet-events.png`, `pixel7-events.png` |
-| Desktop / 375 | Event detail (free, bookable) | `desktop-event.png`, `375-event.png` |
-| 320 | Event detail, paid (checkout off) — the D1 page, fixed | `320-event-paid.png` |
-| 375 | Sold-out / approval-required event | `375-event-soldout.png`, `375-event-approval.png` |
-| 375 | Sign-in (dev personas visible locally only) | `375-signin.png` |
-| 375 | Member dashboard `/me` (guest persona) | `375-member-dashboard.png` |
-| Desktop | Organiser wizard entry (draft banner) | `desktop-organiser-wizard.png` |
-| 375 | Guest opening `/organiser` (not an organiser) | `375-not-organiser.png` |
-| Desktop / 375 / 320 | Admin overview (admin persona) | `desktop-admin-overview.png`, `375-admin-overview.png`, `320-admin-overview.png` |
-| 375 | `/admin` signed out | `375-admin-signed-out.png` |
-
-The e2e suite additionally writes full-page admin screenshots per section and viewport to `test-results/screenshots/` (git-ignored).
-
-## 7. Cannot be verified locally / needs external setup
-
-- Telegram Login (bot token, OIDC/widget domain), Telegram bot confirmations and private-group invite links, webhook secret, events chat id.
-- Cron (`CRON_SECRET`): hold expiry, reconcile, notifications, feed ingestion.
-- Payments: Razorpay/Cashfree keys, webhooks, refunds; `ENABLE_LIVE_PAYMENTS` must remain `false` until intentionally enabled and tested in test mode.
-- SuperProfile membership webhook; admin bootstrap Telegram id.
-- Behaviour on Vercel (the `__path` rewrite router hardening is flagged in project notes as needing a preview check), real database latency, cache headers, custom domain/HTTPS, email/DNS.
-- Safari/iOS and Firefox rendering; real-device touch behaviour; screen readers.
-
-## 8. Remaining work for an MVP release (prioritised)
-
-**Must do before any public launch**
-1. Configure Telegram login + bot on a **preview** deployment and walk the full journey there: sign in → book → confirmation message → venue reveal → logout. (Highest-risk unknown.)
-2. Deploy a preview, run the existing browser suite's public subset against it, and check Vercel logs for errors; confirm the `__path` router behaviour.
-3. Decide the launch auth story: Telegram-only (state it plainly on the sign-in page and add a "Why Telegram?" line), or ship Google sign-in (M3).
-4. Replace the placeholder card graphic with real event imagery (organiser uploads exist; add a tasteful fallback) — biggest visual lever (D8).
-5. Add member **cancel booking** and an "add to calendar"/ticket view — members currently have no self-service after booking.
-
-**Should do**
-6. ~~Past/cancelled event detail~~ — done in §10.
-7. ~~Branded `/admin` access screens~~ — done in §10. Still open: avoid the console 401 on `/me` signed out.
-8. ~~44px phone targets~~ — done in §10 for the audited pages (not for every state, e.g. wizard steps 2–4 and admin were only spot-covered).
-9. Event-scoped staff + QR check-in (M5) before relying on volunteers at the door.
-10. Per-organiser analytics and editing of published events.
-
-**Then**
-11. Human accessibility pass with VoiceOver and TalkBack; Safari/iOS and Firefox runs; full-motion visual review.
-12. Test-mode payments end to end, then a deliberate go/no-go for live payments.
-13. Copy and legal review (refunds, privacy, age-gating wording).
-
-## 9. Commands used
-
-```
-git worktree list; git status; git log --oneline -3 # state check; branch feature/m2-responsive-admin @ 6bb6f08, clean
-npm run lint
-TEST_DATABASE_URL=postgres://localhost/sm_pv2_test npm test
-npm run test:e2e # before and after fixes; own server on :3100, DB sm_e2e (local)
-# audit server (local only, own env, port 3200, DB sm_e2e, DEV_LOGIN=true, payments off):
-env -i … SKIP_DOTENV=true NODE_ENV=development PORT=3200 DATABASE_URL=postgres://localhost/sm_e2e DEV_LOGIN=true \
- SESSION_SECRET= ENABLE_LIVE_PAYMENTS=false node server.js
-# throwaway Playwright scripts (kept out of the repo) crawled 30 pages × 5 viewports for console/network/overflow/tap-target
-# data and took the screenshots above; persona sign-in via POST /api/auth/dev (local only).
-npx playwright test --project=mobile -g "no sideways scrolling at 320px" # run against the OLD CSS to prove the new guard fails
-```
-
-Nothing was merged, rebased, reset, force-pushed or deployed; `main` and `launch-mvp` were not touched; no DNS, Vercel, payment or production data changes.
-
-
-## 10. Follow-up pass: closed events, admin access screen, tap targets, card art
-
-Branch `feature/m2-responsive-admin`, from head `515154d` (clean tree at start). Local only; nothing deployed, pushed, merged or touched on `main`/`launch-mvp`.
-
-### What changed
-| # | Fix | Files | Notes |
-|---|---|---|---|
-| 1 | Past and cancelled event pages show a status panel ("This event has ended" / "has been cancelled" + link to upcoming events) instead of ticket picker, quantity, submit button, venue-after-booking and "confirmation via Telegram" lines. Covers tiered and legacy single-price events. | `lib/views/event.js`, `public/css/site.css` | **Server-side enforcement already existed** (`bookTier` and the legacy booking path refuse unpublished and started events; approval refuses closed events). I added regression tests that lock it in; those tests passed *before* the view change, so they are guards, not fixes. Private venue is not in the closed page. |
-| 2 | Signed-out and non-admin `/admin` use the site layout (header, footer, skip link) with a clear heading, a Telegram sign-in button (`/signin?next=/admin`) and a way back. HTTP status stays 401 / 403, `noindex`. The 403 screen no longer mentions the allowlist, and neither screen loads admin JS or carries role/CSRF data. | `lib/views/admin.js`, `e2e/admin.spec.js` (copy) | Authorization code (`lib/handlers/admin.js`) untouched. |
-| 3 | 44px minimum touch targets at ≤800px: logo, header Telegram button (40→44) and "My bookings", `.btn-sm`, checkbox rows, footer links, card-title links, breadcrumbs, `link-arrow`, standalone prose links, booking-list titles. Desktop rules unchanged (all inside `max-width` queries). | `public/css/site.css` | In-sentence links are exempt (WCAG 2.5.8 inline exception). |
-| 4 | Cards without a photo get a per-category tint and glyph (12 categories, inline SVG, `aria-hidden`), keeping the existing two-ring motif. Real covers still win. | `lib/views/components.js`, `public/css/site.css` | Reuses existing classes and brand colours; no new image files. It is a better fallback, not photography. |
-
-Cache-bust `site.css` `v=10`→`v=11` (`lib/views/layout.js`, `lib/views/admin.js`).
-
-### Tests added (regression)
-- `test/closed-events.test.js` (9): closed pages have no picker; API refuses booking, no booking/payment row; pending request on a cancelled event cannot be approved; legacy page; `/admin` 401/403 screens. Page and `/admin` tests **failed before the fix** (6 failures run before editing views); API tests passed before (see above).
-- `test/card-art.test.js` (2): each category has a distinct decorative glyph; unknown category and cover-photo fallbacks. Fails on the old markup (no glyph).
-- `e2e/tap-targets.spec.js` (4, phone project, 320 and 375): measures every interactive control on public, menu-open, `/me` and organiser pages. Baseline run listed ~30 distinct offenders (footer links 20px tall, logo 27px, header button 40px, card titles ~26px, `.btn-sm` 36px, 20px checkbox rows); passes after.
-- `e2e/closed-and-gates.spec.js` (desktop + phone): closed pages (no radio/combobox/checkbox/textbox/button in the booking panel, axe, no overflow, keyboard Enter on the link), signed-out `/admin` (401, heading, focus, ≥44px CTA, axe, 320px fit), non-admin 403, card art.
-
-### Results (local; `sm_pv2_test` for unit, `sm_e2e` for browser)
-| Check | Result |
-|---|---|
-| `npm run lint` | 96/96 files OK |
-| `npm test` | 160/160 pass (was 149) |
-| `npm run test:e2e` | 113 passed, 5 skipped, 0 failed (118 tests). Skips: 1 intentional mobile-menu skip; 4 phone-only tap-target tests skip on the desktop project. |
-
-### Checks done and screenshots reviewed
-Reviewed at 320, 375, tablet 768 and desktop 1280: past and cancelled event pages, `/events` cards, signed-out `/admin`, plus `/admin` 403 and card art from the suite's captures. Keyboard: closed-page link and admin sign-in CTA are focusable, Enter works. Accessible names: panel is the named "Booking" landmark; CTA names are visible text. Overflow: none at 320. Error states: API refusals tested; sign-in page's own failure states unchanged.
-
-### Re-score (rubric in §1)
-| Category | Before | After | Why |
-|---|---|---|---|
-| Visual polish | 68 | **70** | Better card fallback and cleaner closed pages; still no photography, so only +2 |
-| Mobile UX | 72 | **76** | Tap targets fixed and now guarded by a test; checked only on the audited pages |
-| Core user journeys | 50 | 50 | A misleading page was fixed, but no new journey works end to end |
-| Accessibility | 70 | 70 | No human screen-reader pass yet (cap) |
-| Reliability | 70 | 70 | More tests do not change what is observed in use |
-| Launch readiness | 20 | 20 | Nothing deployed or externally verified |
-
-Weighted 61.2; keeping the earlier 2-point deduction for the suite-green-but-broken D1 gives **59 / 100**. This is not a release-ready score.
-
-### Outstanding product decisions / future work (not implemented here)
-Member booking cancellation; QR check-in; event-scoped staff (`event_staff`, M5); additional OAuth providers (Google, M3); payment integration (live payments stay off). Also open: real event photography, `/me` signed-out console 401, tap targets on wizard steps 2–4 and unvisited states, Safari/Firefox/device and screen-reader checks, preview/production verification.
diff --git a/docs/launch/evidence/acceptance_results.json b/docs/launch/evidence/acceptance_results.json
new file mode 100644
index 0000000..24f8fe7
--- /dev/null
+++ b/docs/launch/evidence/acceptance_results.json
@@ -0,0 +1,1101 @@
+[
+ {
+ "timestamp": "2026-11-10T08:42:41.587Z",
+ "id": "ENV-01",
+ "role": "Environment",
+ "name": "Preview Health & Database Connectivity",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/health",
+ "viewport": "Desktop 1440x900",
+ "action": "Fetch /api/health with protection bypass",
+ "expected": "HTTP 200, ok=true, database=ok",
+ "actual": "HTTP 200, ok=true, database=ok, commit=142cc62",
+ "status": "PASS",
+ "networkResult": 200
+ },
+ {
+ "timestamp": "2026-11-10T08:42:41.587Z",
+ "id": "ENV-02",
+ "role": "Environment",
+ "name": "Live Payments Disabled Guard (ENABLE_LIVE_PAYMENTS=false)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/health",
+ "viewport": "Desktop 1440x900",
+ "action": "Verify livePayments flag in configStatus",
+ "expected": "livePayments: false strictly enforced",
+ "actual": "livePayments: false",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:41.897Z",
+ "id": "ENV-03",
+ "role": "Security",
+ "name": "Preview Reviewer GET Link Block (REV-09 Method Restriction)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/auth/preview-reviewer",
+ "viewport": "Desktop 1440x900",
+ "action": "Issue HTTP GET to /api/auth/preview-reviewer",
+ "expected": "HTTP 405 Method Not Allowed (fail closed for direct browser click)",
+ "actual": "HTTP 405",
+ "status": "PASS",
+ "networkResult": 405
+ },
+ {
+ "timestamp": "2026-11-10T08:42:42.204Z",
+ "id": "ENV-04",
+ "role": "Security",
+ "name": "Preview Reviewer POST Sign-in Endpoint Availability",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/auth/preview-reviewer",
+ "viewport": "Desktop 1440x900",
+ "action": "Issue HTTP POST to /api/auth/preview-reviewer",
+ "expected": "HTTP 200 with session cookie (isolated attendee reviewer)",
+ "actual": "HTTP 404 ({\"ok\":false,\"error\":\"not_found\",\"message\":\"Not found\"})",
+ "status": "FAIL",
+ "defectNotes": "Defect: previewReviewerEnabled() evaluates false on Vercel Preview because Vercel sets NODE_ENV=production. Route returns 404 Not Found, preventing automated/reviewer login.",
+ "networkResult": 404
+ },
+ {
+ "timestamp": "2026-11-10T08:42:42.205Z",
+ "id": "ENV-05",
+ "role": "Environment",
+ "name": "Preview Session Secret Configuration Audit",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/health",
+ "viewport": "Desktop 1440x900",
+ "action": "Inspect session config status in /api/health",
+ "expected": "session: configured (SESSION_SECRET >= 32 chars in Vercel preview env)",
+ "actual": "session: NOT CONFIGURED, telegramBot: NOT CONFIGURED",
+ "status": "FAIL",
+ "defectNotes": "Defect: SESSION_SECRET is unconfigured in Vercel Preview environment variables. Any attempt to start a server-side session throws 503."
+ },
+ {
+ "timestamp": "2026-11-10T08:42:44.507Z",
+ "id": "ATT-01",
+ "role": "Attendee",
+ "name": "Homepage Discovery, Branding & Navigation",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/",
+ "viewport": "1440x900",
+ "action": "Load homepage and inspect header, logo, location trigger, search bar, and 21+ badge",
+ "expected": "Page loads with NIGHTLIFEZ branding, 21+ chip, location trigger, and search form",
+ "actual": "Title: \"NIGHTLIFEZ — Events, Parties, Social Mixers & Trips in South India\", logo: true, search: true, loc: true, age: \"21+\"",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/att_01_homepage_desktop.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:45.761Z",
+ "id": "ATT-02",
+ "role": "Attendee",
+ "name": "Events Discovery Feed & Sample Cards",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events",
+ "viewport": "1440x900",
+ "action": "Navigate to /events and count published preview cards",
+ "expected": "Events feed displays active preview events with clear sample/event tags",
+ "actual": "Found 3 event cards rendered in discovery feed",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/att_02_events_feed.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:47.029Z",
+ "id": "ATT-03",
+ "role": "Attendee",
+ "name": "City Selection & Filter Modal",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events?city=chennai",
+ "viewport": "1440x900",
+ "action": "Open location dialog and select Chennai",
+ "expected": "Location dialog opens, city click updates view or URL parameters",
+ "actual": "Dialog opened: true, city clicked: true, current URL: https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events?city=chennai",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:48.208Z",
+ "id": "ATT-04",
+ "role": "Attendee",
+ "name": "Event Search Filtering",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events?q=Supper",
+ "viewport": "1440x900",
+ "action": "Search query ?q=Supper",
+ "expected": "Returns matching Supper Club event card",
+ "actual": "Found 1 matching cards",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/att_04_search_supper.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:49.266Z",
+ "id": "ATT-05",
+ "role": "Attendee",
+ "name": "Empty Search & No-Results State",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events?q=nonexistent_query_xyz123",
+ "viewport": "1440x900",
+ "action": "Search with non-existent keyword",
+ "expected": "Zero event cards and a helpful empty state message",
+ "actual": "Cards: 0, empty state detected: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/att_05_search_empty.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:50.466Z",
+ "id": "ATT-06",
+ "role": "Attendee",
+ "name": "Event Detail Page & Experience Transparency",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events/sample-chennai-besant-nagar-supper-club",
+ "viewport": "1440x900",
+ "action": "Inspect event detail title, inclusions, timings, and ticketing section",
+ "expected": "Complete experience details, inclusions, exclusions, and price displayed",
+ "actual": "Heading: \"Six Strangers Supper Club: Besant Nagar\", inclusions rendered: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/att_06_event_detail.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:50.841Z",
+ "id": "ATT-07",
+ "role": "Security",
+ "name": "Mystery Venue Address Concealment (Public DOM & API)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events/sample-chennai-besant-nagar-supper-club",
+ "viewport": "1440x900",
+ "action": "Inspect HTML source and /api/events/:slug response for private venue address leakage",
+ "expected": "Secret street address and maps URL concealed from unbooked visitors; mystery disclaimer rendered",
+ "actual": "Private address in HTML: false, private address in API: false, mystery notice: true",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:52.642Z",
+ "id": "ATT-08",
+ "role": "Attendee",
+ "name": "Save / Bookmark Event Auth-Gate (goSignin())",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events/sample-chennai-besant-nagar-supper-club",
+ "viewport": "1440x900",
+ "action": "Click save event button when unauthenticated",
+ "expected": "Unauthenticated visitor clicking Save is redirected to /signin",
+ "actual": "Redirected to signin: true (URL: https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin?next=%2Fevents%2Fsample-chennai-besant-nagar-supper-club)",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:54.457Z",
+ "id": "ATT-09",
+ "role": "Attendee",
+ "name": "Booking Authentication Gate (Fail-Closed)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events/sample-chennai-besant-nagar-supper-club",
+ "viewport": "1440x900",
+ "action": "Submit RSVP booking form without active user session",
+ "expected": "Booking rejected, user safely routed to /signin",
+ "actual": "Auth gate correctly triggered, redirected to /signin: true",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:55.896Z",
+ "id": "ATT-10",
+ "role": "Attendee",
+ "name": "Sign-in Page & Preview Reviewer UI Audit",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin",
+ "viewport": "1440x900",
+ "action": "Inspect /signin page elements and reviewer test button",
+ "expected": "Sign-in page renders with clear explanation and preview reviewer sign-in button",
+ "actual": "Reviewer button visible: false, notice rendered: \" Members Continue with Telegram Sign in to book tickets and manage your bookings. We never see your phone number. \"",
+ "status": "FAIL",
+ "defectNotes": "Defect: Preview reviewer button hidden because previewReviewerEnabled() evaluates false on Vercel Preview (NODE_ENV=production).",
+ "screenshotPath": "docs/launch/evidence/att_10_signin_page.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:55.896Z",
+ "id": "ATT-11",
+ "role": "Attendee",
+ "name": "Digital Pass Issuance, QR Code Rendering & Attendee Cancellation",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/me",
+ "viewport": "1440x900",
+ "action": "Attempt to issue digital ticket pass and cancel booking",
+ "expected": "Digital ticket pass rendered with QR code and cancel button",
+ "actual": "BLOCKED: Could not create authenticated attendee session on live preview due to ENV-04 / ENV-05 defects.",
+ "status": "BLOCKED",
+ "defectNotes": "Prerequisite blocked: Reviewer sign-in endpoint returns 404 and SESSION_SECRET is unconfigured."
+ },
+ {
+ "timestamp": "2026-11-10T08:42:57.966Z",
+ "id": "HST-01",
+ "role": "Host",
+ "name": "Host Landing Page & Application Form Presentation",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host",
+ "viewport": "1440x900",
+ "action": "Open /become-a-host and inspect value proposition and form controls",
+ "expected": "Page renders value proposition, host guidelines, and application form",
+ "actual": "Heading: \"Become an Organiser & Host\", form visible: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/hst_01_become_a_host.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:42:57.969Z",
+ "id": "HST-02",
+ "role": "Host",
+ "name": "Host Form Required-Field Attribute Validation",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host",
+ "viewport": "1440x900",
+ "action": "Check required attributes on form inputs",
+ "expected": "Name, telegram, city, experience, and consent inputs enforce requirement",
+ "actual": "Name required attribute: true",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:00.802Z",
+ "id": "HST-03",
+ "role": "Host",
+ "name": "Host Application Submission & Database Lead Ingestion",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host",
+ "viewport": "1440x900",
+ "action": "Submit synthetic host application form",
+ "expected": "Submission succeeds with confirmation message or redirects to ?sent=1",
+ "actual": "URL: https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host, message: \"Thank you — we have your details and will be in touch soon.\", success: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/hst_03_submission_result.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:02.028Z",
+ "id": "HST-04",
+ "role": "Host",
+ "name": "Host Confirmation View Persistence",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host?sent=1",
+ "viewport": "1440x900",
+ "action": "Directly visit /become-a-host?sent=1 to verify confirmation state",
+ "expected": "Displays Application Received / Confirmation message cleanly",
+ "actual": "Heading: \"Application Received!\"",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/hst_04_confirmation_persistence.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:03.145Z",
+ "id": "HST-05",
+ "role": "Security",
+ "name": "Pending Host Privilege Isolation (No Auto-Escalation)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/organiser",
+ "viewport": "1440x900",
+ "action": "Attempt to navigate directly to /organiser dashboard",
+ "expected": "Access denied; redirected to /signin or displays gate card",
+ "actual": "Current URL: https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/organiser, denied/gated: true",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:04.888Z",
+ "id": "ORG-01",
+ "role": "Organiser",
+ "name": "Organiser Workspace Route Protection",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/organiser",
+ "viewport": "1440x900",
+ "action": "Navigate to /organiser without active session",
+ "expected": "Redirects to /signin or displays access gate notice",
+ "actual": "URL: https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/organiser, protected/gated: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/org_01_access_protection.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:05.253Z",
+ "id": "ORG-02",
+ "role": "Security",
+ "name": "Organiser Events API Authorization Gate",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/organiser/events",
+ "viewport": "1440x900",
+ "action": "Issue GET /api/organiser/events without session",
+ "expected": "HTTP 401 Unauthorized or 403 Forbidden",
+ "actual": "HTTP 401",
+ "status": "PASS",
+ "networkResult": 401
+ },
+ {
+ "timestamp": "2026-11-10T08:43:05.253Z",
+ "id": "ORG-03",
+ "role": "Organiser",
+ "name": "Organiser Event Creation Wizard, Inventory & Staff Management",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/organiser",
+ "viewport": "1440x900",
+ "action": "Full organiser lifecycle walkthrough",
+ "expected": "Interactive dashboard, draft creation, ticket inventory, staff roster",
+ "actual": "BLOCKED: No provisioned organiser account exists in the Preview database and manual provisioning requires owner action.",
+ "status": "BLOCKED",
+ "defectNotes": "Prerequisite blocked: Organiser role requires active session with organiser_enabled=true and org_memberships in Preview DB."
+ },
+ {
+ "timestamp": "2026-11-10T08:43:07.713Z",
+ "id": "VEN-01",
+ "role": "Venue Owner",
+ "name": "Venue Acquisition Page & Application Form",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/list-your-venue",
+ "viewport": "1440x900",
+ "action": "Inspect /list-your-venue hero, benefits, and form fields",
+ "expected": "Page renders venue benefits, 3-step expectation timeline, and listing form",
+ "actual": "Heading: \"List Your Venue\", form visible: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/ven_01_list_your_venue.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:09.795Z",
+ "id": "VEN-02",
+ "role": "Venue Owner",
+ "name": "Venue Listing Submission & Ingestion",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/list-your-venue",
+ "viewport": "1440x900",
+ "action": "Submit synthetic venue listing form",
+ "expected": "Submission succeeds with confirmation or redirect to ?sent=1",
+ "actual": "URL: https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/list-your-venue, message: \"Thank you — we have your details and will be in touch soon.\", success: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/ven_02_submission_result.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:10.818Z",
+ "id": "VEN-03",
+ "role": "Venue Owner",
+ "name": "Venue Confirmation View & 3-Step Timeline",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/list-your-venue?sent=1",
+ "viewport": "1440x900",
+ "action": "Verify confirmation view and expectation timeline",
+ "expected": "Displays confirmation heading and 3-step next steps timeline",
+ "actual": "Timeline / confirmation detected: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/ven_03_confirmation_timeline.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:11.858Z",
+ "id": "VEN-04",
+ "role": "Security",
+ "name": "Venue Owner Platform Boundary Isolation",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/admin",
+ "viewport": "1440x900",
+ "action": "Attempt to navigate to /admin",
+ "expected": "Access securely gated or denied",
+ "actual": "Current URL: https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/admin, gated/denied: true",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:13.608Z",
+ "id": "STF-01",
+ "role": "Event Staff",
+ "name": "Staff Invitation Forged/Invalid Token Rejection",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/staff/join?token=invalid_dummy_token_qa",
+ "viewport": "1440x900",
+ "action": "Open staff join route with forged token",
+ "expected": "Invitation safely rejected without leaking event identity or crashing",
+ "actual": "Safe rejection detected: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/stf_01_invalid_token.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:13.608Z",
+ "id": "STF-02",
+ "role": "Event Staff",
+ "name": "Camera QR Scanner UI, Duplicate Scan Rejection & PII Protection",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/organiser/events/:id/scan",
+ "viewport": "1440x900",
+ "action": "Live QR camera check-in and duplicate scan rejection test",
+ "expected": "Door scanner accepts valid ticket, audits scan, and rejects duplicate scans",
+ "actual": "BLOCKED: Requires event-scoped staff invitation acceptance on Preview.",
+ "status": "BLOCKED",
+ "defectNotes": "Prerequisite blocked: Organiser account required to issue staff invite link."
+ },
+ {
+ "timestamp": "2026-11-10T08:43:15.023Z",
+ "id": "PRV-01",
+ "role": "Service Provider",
+ "name": "Service Provider Page & Category Presentation",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/partner-with-us",
+ "viewport": "1440x900",
+ "action": "Inspect /partner-with-us categories, FAQs, and form",
+ "expected": "Displays provider categories (DJs, sound, photo, bar) and application form",
+ "actual": "Heading: \"Partner With Us\", form visible: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/prv_01_partner_with_us.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:16.844Z",
+ "id": "PRV-02",
+ "role": "Service Provider",
+ "name": "Service Provider Submission & Ingestion",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/partner-with-us",
+ "viewport": "1440x900",
+ "action": "Submit synthetic service provider application form",
+ "expected": "Submission succeeds with confirmation or redirect to ?sent=1",
+ "actual": "URL: https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/partner-with-us, message: \"Too many requests. Please try again later.\", success: false",
+ "status": "FAIL",
+ "screenshotPath": "docs/launch/evidence/prv_02_submission_result.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:17.935Z",
+ "id": "PRV-03",
+ "role": "Service Provider",
+ "name": "Service Provider Confirmation & Expectations",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/partner-with-us?sent=1",
+ "viewport": "1440x900",
+ "action": "Verify confirmation view and expectations",
+ "expected": "Displays confirmation heading and timeline",
+ "actual": "Confirmation detected: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/prv_03_confirmation.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:19.731Z",
+ "id": "ADM-01",
+ "role": "Admin",
+ "name": "Admin Console Route Protection Gate",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/admin",
+ "viewport": "1440x900",
+ "action": "Open /admin unauthenticated",
+ "expected": "Redirects to /signin or displays access gate notice",
+ "actual": "URL: https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/admin, access gated/denied: true",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/adm_01_access_protection.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:20.065Z",
+ "id": "ADM-02",
+ "role": "Security",
+ "name": "Admin Overview API Least-Privilege Protection Gate",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/admin/overview",
+ "viewport": "1440x900",
+ "action": "GET /api/admin/overview unauthenticated",
+ "expected": "HTTP 401 Unauthorized or 403 Forbidden",
+ "actual": "HTTP 401",
+ "status": "PASS",
+ "networkResult": 401
+ },
+ {
+ "timestamp": "2026-11-10T08:43:20.335Z",
+ "id": "ADM-03",
+ "role": "Security",
+ "name": "Admin Leads API Least-Privilege Protection Gate",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/admin/leads",
+ "viewport": "1440x900",
+ "action": "GET /api/admin/leads unauthenticated",
+ "expected": "HTTP 401 Unauthorized or 403 Forbidden",
+ "actual": "HTTP 401",
+ "status": "PASS",
+ "networkResult": 401
+ },
+ {
+ "timestamp": "2026-11-10T08:43:20.620Z",
+ "id": "ADM-04",
+ "role": "Security",
+ "name": "Admin Notifications Outbox API Least-Privilege Protection Gate",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/admin/notifications",
+ "viewport": "1440x900",
+ "action": "GET /api/admin/notifications unauthenticated",
+ "expected": "HTTP 401 Unauthorized or 403 Forbidden",
+ "actual": "HTTP 401",
+ "status": "PASS",
+ "networkResult": 401
+ },
+ {
+ "timestamp": "2026-11-10T08:43:20.973Z",
+ "id": "ADM-05",
+ "role": "Security",
+ "name": "Admin Audit Log API Least-Privilege Protection Gate",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/admin/audit",
+ "viewport": "1440x900",
+ "action": "GET /api/admin/audit unauthenticated",
+ "expected": "HTTP 401 Unauthorized or 403 Forbidden",
+ "actual": "HTTP 401",
+ "status": "PASS",
+ "networkResult": 401
+ },
+ {
+ "timestamp": "2026-11-10T08:43:21.426Z",
+ "id": "ADM-06",
+ "role": "Security",
+ "name": "Admin Users Roster API Least-Privilege Protection Gate",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/admin/admins",
+ "viewport": "1440x900",
+ "action": "GET /api/admin/admins unauthenticated",
+ "expected": "HTTP 401 Unauthorized or 403 Forbidden",
+ "actual": "HTTP 401",
+ "status": "PASS",
+ "networkResult": 401
+ },
+ {
+ "timestamp": "2026-11-10T08:43:21.426Z",
+ "id": "ADM-07",
+ "role": "Admin",
+ "name": "Multi-Level Admin Console Privilege Separation (Super Admin, Support, Finance)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/admin",
+ "viewport": "1440x900",
+ "action": "Test role separation between Super Admin, Support, and Finance personas",
+ "expected": "Super Admin has full access; Support cannot issue refunds or view audit; Finance cannot change admins",
+ "actual": "BLOCKED: ADMIN_BOOTSTRAP_TELEGRAM_ID is unconfigured and no admin session is provisioned on Preview.",
+ "status": "BLOCKED",
+ "defectNotes": "Prerequisite blocked: Requires setting ADMIN_BOOTSTRAP_TELEGRAM_ID in Vercel Preview environment variables."
+ },
+ {
+ "timestamp": "2026-11-10T08:43:22.708Z",
+ "id": "VWP-desktop_1440-_",
+ "role": "Responsive UX",
+ "name": "Homepage Layout at 1440x900 (desktop_1440)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/",
+ "viewport": "1440x900",
+ "action": "Verify horizontal overflow and layout at 1440px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:23.674Z",
+ "id": "VWP-desktop_1440-_events",
+ "role": "Responsive UX",
+ "name": "Events Discovery Layout at 1440x900 (desktop_1440)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events",
+ "viewport": "1440x900",
+ "action": "Verify horizontal overflow and layout at 1440px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:24.624Z",
+ "id": "VWP-desktop_1440-_events_sampl",
+ "role": "Responsive UX",
+ "name": "Event Detail Layout at 1440x900 (desktop_1440)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events/sample-chennai-besant-nagar-supper-club",
+ "viewport": "1440x900",
+ "action": "Verify horizontal overflow and layout at 1440px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:25.695Z",
+ "id": "VWP-desktop_1440-_become_a_hos",
+ "role": "Responsive UX",
+ "name": "Become a Host Layout at 1440x900 (desktop_1440)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host",
+ "viewport": "1440x900",
+ "action": "Verify horizontal overflow and layout at 1440px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:26.565Z",
+ "id": "VWP-desktop_1440-_list_your_ve",
+ "role": "Responsive UX",
+ "name": "List Your Venue Layout at 1440x900 (desktop_1440)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/list-your-venue",
+ "viewport": "1440x900",
+ "action": "Verify horizontal overflow and layout at 1440px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:27.408Z",
+ "id": "VWP-desktop_1440-_partner_with",
+ "role": "Responsive UX",
+ "name": "Partner With Us Layout at 1440x900 (desktop_1440)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/partner-with-us",
+ "viewport": "1440x900",
+ "action": "Verify horizontal overflow and layout at 1440px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:28.677Z",
+ "id": "VWP-desktop_1440-_signin",
+ "role": "Responsive UX",
+ "name": "Sign In Layout at 1440x900 (desktop_1440)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin",
+ "viewport": "1440x900",
+ "action": "Verify horizontal overflow and layout at 1440px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:29.980Z",
+ "id": "VWP-desktop_1280-_",
+ "role": "Responsive UX",
+ "name": "Homepage Layout at 1280x800 (desktop_1280)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/",
+ "viewport": "1280x800",
+ "action": "Verify horizontal overflow and layout at 1280px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:30.845Z",
+ "id": "VWP-desktop_1280-_events",
+ "role": "Responsive UX",
+ "name": "Events Discovery Layout at 1280x800 (desktop_1280)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events",
+ "viewport": "1280x800",
+ "action": "Verify horizontal overflow and layout at 1280px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:31.716Z",
+ "id": "VWP-desktop_1280-_events_sampl",
+ "role": "Responsive UX",
+ "name": "Event Detail Layout at 1280x800 (desktop_1280)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events/sample-chennai-besant-nagar-supper-club",
+ "viewport": "1280x800",
+ "action": "Verify horizontal overflow and layout at 1280px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:32.581Z",
+ "id": "VWP-desktop_1280-_become_a_hos",
+ "role": "Responsive UX",
+ "name": "Become a Host Layout at 1280x800 (desktop_1280)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host",
+ "viewport": "1280x800",
+ "action": "Verify horizontal overflow and layout at 1280px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:33.524Z",
+ "id": "VWP-desktop_1280-_list_your_ve",
+ "role": "Responsive UX",
+ "name": "List Your Venue Layout at 1280x800 (desktop_1280)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/list-your-venue",
+ "viewport": "1280x800",
+ "action": "Verify horizontal overflow and layout at 1280px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:34.365Z",
+ "id": "VWP-desktop_1280-_partner_with",
+ "role": "Responsive UX",
+ "name": "Partner With Us Layout at 1280x800 (desktop_1280)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/partner-with-us",
+ "viewport": "1280x800",
+ "action": "Verify horizontal overflow and layout at 1280px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:35.472Z",
+ "id": "VWP-desktop_1280-_signin",
+ "role": "Responsive UX",
+ "name": "Sign In Layout at 1280x800 (desktop_1280)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin",
+ "viewport": "1280x800",
+ "action": "Verify horizontal overflow and layout at 1280px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:37.562Z",
+ "id": "VWP-mobile_393-_",
+ "role": "Responsive UX",
+ "name": "Homepage Layout at 393x851 (mobile_393)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/",
+ "viewport": "393x851",
+ "action": "Verify horizontal overflow and layout at 393px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px (Culprits: li., a.cat-pill, span.cat-icon, span.)",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/vwp_mobile_393__.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:38.449Z",
+ "id": "VWP-mobile_393-_events",
+ "role": "Responsive UX",
+ "name": "Events Discovery Layout at 393x851 (mobile_393)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events",
+ "viewport": "393x851",
+ "action": "Verify horizontal overflow and layout at 393px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:39.658Z",
+ "id": "VWP-mobile_393-_events_sample_",
+ "role": "Responsive UX",
+ "name": "Event Detail Layout at 393x851 (mobile_393)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events/sample-chennai-besant-nagar-supper-club",
+ "viewport": "393x851",
+ "action": "Verify horizontal overflow and layout at 393px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/vwp_mobile_393__events_sample_chennai_besant_nagar_supper_club.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:40.546Z",
+ "id": "VWP-mobile_393-_become_a_host",
+ "role": "Responsive UX",
+ "name": "Become a Host Layout at 393x851 (mobile_393)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host",
+ "viewport": "393x851",
+ "action": "Verify horizontal overflow and layout at 393px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:41.447Z",
+ "id": "VWP-mobile_393-_list_your_venu",
+ "role": "Responsive UX",
+ "name": "List Your Venue Layout at 393x851 (mobile_393)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/list-your-venue",
+ "viewport": "393x851",
+ "action": "Verify horizontal overflow and layout at 393px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:42.559Z",
+ "id": "VWP-mobile_393-_partner_with_u",
+ "role": "Responsive UX",
+ "name": "Partner With Us Layout at 393x851 (mobile_393)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/partner-with-us",
+ "viewport": "393x851",
+ "action": "Verify horizontal overflow and layout at 393px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:43.734Z",
+ "id": "VWP-mobile_393-_signin",
+ "role": "Responsive UX",
+ "name": "Sign In Layout at 393x851 (mobile_393)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin",
+ "viewport": "393x851",
+ "action": "Verify horizontal overflow and layout at 393px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/vwp_mobile_393__signin.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:45.440Z",
+ "id": "VWP-mobile_375-_",
+ "role": "Responsive UX",
+ "name": "Homepage Layout at 375x800 (mobile_375)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/",
+ "viewport": "375x800",
+ "action": "Verify horizontal overflow and layout at 375px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px (Culprits: li., a.cat-pill, li., a.cat-pill)",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/vwp_mobile_375__.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:46.280Z",
+ "id": "VWP-mobile_375-_events",
+ "role": "Responsive UX",
+ "name": "Events Discovery Layout at 375x800 (mobile_375)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events",
+ "viewport": "375x800",
+ "action": "Verify horizontal overflow and layout at 375px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:47.378Z",
+ "id": "VWP-mobile_375-_events_sample_",
+ "role": "Responsive UX",
+ "name": "Event Detail Layout at 375x800 (mobile_375)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events/sample-chennai-besant-nagar-supper-club",
+ "viewport": "375x800",
+ "action": "Verify horizontal overflow and layout at 375px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/vwp_mobile_375__events_sample_chennai_besant_nagar_supper_club.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:48.237Z",
+ "id": "VWP-mobile_375-_become_a_host",
+ "role": "Responsive UX",
+ "name": "Become a Host Layout at 375x800 (mobile_375)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host",
+ "viewport": "375x800",
+ "action": "Verify horizontal overflow and layout at 375px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:49.089Z",
+ "id": "VWP-mobile_375-_list_your_venu",
+ "role": "Responsive UX",
+ "name": "List Your Venue Layout at 375x800 (mobile_375)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/list-your-venue",
+ "viewport": "375x800",
+ "action": "Verify horizontal overflow and layout at 375px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:49.962Z",
+ "id": "VWP-mobile_375-_partner_with_u",
+ "role": "Responsive UX",
+ "name": "Partner With Us Layout at 375x800 (mobile_375)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/partner-with-us",
+ "viewport": "375x800",
+ "action": "Verify horizontal overflow and layout at 375px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:51.166Z",
+ "id": "VWP-mobile_375-_signin",
+ "role": "Responsive UX",
+ "name": "Sign In Layout at 375x800 (mobile_375)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin",
+ "viewport": "375x800",
+ "action": "Verify horizontal overflow and layout at 375px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/vwp_mobile_375__signin.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:52.883Z",
+ "id": "VWP-mobile_320-_",
+ "role": "Responsive UX",
+ "name": "Homepage Layout at 320x700 (mobile_320)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/",
+ "viewport": "320x700",
+ "action": "Verify horizontal overflow and layout at 320px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px (Culprits: li., a.cat-pill, span., li.)",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/vwp_mobile_320__.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:53.724Z",
+ "id": "VWP-mobile_320-_events",
+ "role": "Responsive UX",
+ "name": "Events Discovery Layout at 320x700 (mobile_320)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events",
+ "viewport": "320x700",
+ "action": "Verify horizontal overflow and layout at 320px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:54.836Z",
+ "id": "VWP-mobile_320-_events_sample_",
+ "role": "Responsive UX",
+ "name": "Event Detail Layout at 320x700 (mobile_320)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events/sample-chennai-besant-nagar-supper-club",
+ "viewport": "320x700",
+ "action": "Verify horizontal overflow and layout at 320px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/vwp_mobile_320__events_sample_chennai_besant_nagar_supper_club.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:55.681Z",
+ "id": "VWP-mobile_320-_become_a_host",
+ "role": "Responsive UX",
+ "name": "Become a Host Layout at 320x700 (mobile_320)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host",
+ "viewport": "320x700",
+ "action": "Verify horizontal overflow and layout at 320px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:56.546Z",
+ "id": "VWP-mobile_320-_list_your_venu",
+ "role": "Responsive UX",
+ "name": "List Your Venue Layout at 320x700 (mobile_320)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/list-your-venue",
+ "viewport": "320x700",
+ "action": "Verify horizontal overflow and layout at 320px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:57.432Z",
+ "id": "VWP-mobile_320-_partner_with_u",
+ "role": "Responsive UX",
+ "name": "Partner With Us Layout at 320x700 (mobile_320)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/partner-with-us",
+ "viewport": "320x700",
+ "action": "Verify horizontal overflow and layout at 320px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:58.623Z",
+ "id": "VWP-mobile_320-_signin",
+ "role": "Responsive UX",
+ "name": "Sign In Layout at 320x700 (mobile_320)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin",
+ "viewport": "320x700",
+ "action": "Verify horizontal overflow and layout at 320px width",
+ "expected": "Zero horizontal scrollbar overflow (overflow <= 0)",
+ "actual": "Overflow: 0px ",
+ "status": "PASS",
+ "screenshotPath": "docs/launch/evidence/vwp_mobile_320__signin.png"
+ },
+ {
+ "timestamp": "2026-11-10T08:43:59.969Z",
+ "id": "SEC-01",
+ "role": "Security",
+ "name": "Reflected XSS Input Sanitization Probe",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events?q=%3Cscript%3Ealert(%22xss%22)%3C%2Fscript%3E",
+ "viewport": "1440x900",
+ "action": "Inject script payload into search parameter",
+ "expected": "Payload properly escaped as text, not executed as executable script in DOM",
+ "actual": "XSS executed: false, raw unescaped tag in DOM: false",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:00.175Z",
+ "id": "SEC-02",
+ "role": "Security",
+ "name": "SQL Injection Resistance Probe on Filter Parameters",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/api/events?city=chennai'%20OR%201%3D1--",
+ "viewport": "1440x900",
+ "action": "Pass SQL injection payload into city filter",
+ "expected": "Parameterized query handles payload safely; HTTP 200 with empty/safe array; no database syntax error",
+ "actual": "HTTP 200, events array returned: true, ok=true",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:01.402Z",
+ "id": "SEC-03",
+ "role": "Security",
+ "name": "Open Redirect Prevention Probe (https://attacker-domain.evil)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin?next=https%3A%2F%2Fattacker-domain.evil",
+ "viewport": "1440x900",
+ "action": "Pass untrusted redirect target next=https://attacker-domain.evil",
+ "expected": "Sanitizer safeNext() falls back strictly to /me",
+ "actual": "Sanitized form next value: \"null\"",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:02.670Z",
+ "id": "SEC-04",
+ "role": "Security",
+ "name": "Open Redirect Prevention Probe (//attacker-domain.evil)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin?next=%2F%2Fattacker-domain.evil",
+ "viewport": "1440x900",
+ "action": "Pass untrusted redirect target next=//attacker-domain.evil",
+ "expected": "Sanitizer safeNext() falls back strictly to /me",
+ "actual": "Sanitized form next value: \"null\"",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:03.867Z",
+ "id": "SEC-05",
+ "role": "Security",
+ "name": "Open Redirect Prevention Probe (javascript:alert(1))",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin?next=javascript%3Aalert(1)",
+ "viewport": "1440x900",
+ "action": "Pass untrusted redirect target next=javascript:alert(1)",
+ "expected": "Sanitizer safeNext() falls back strictly to /me",
+ "actual": "Sanitized form next value: \"null\"",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:03.965Z",
+ "id": "SEC-06",
+ "role": "Security",
+ "name": "HTTP Security Headers Verification (CSP, HSTS, XCTO, FrameGuard)",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/",
+ "viewport": "1440x900",
+ "action": "Inspect response headers for defense-in-depth protections",
+ "expected": "Strict CSP, nosniff, HSTS, and frame restriction headers present",
+ "actual": "CSP: true, nosniff: true, HSTS: true, FrameGuard: true",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:06.577Z",
+ "id": "A11Y-01",
+ "role": "Accessibility",
+ "name": "WCAG 2 A/AA Automated Audit on Homepage",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/",
+ "viewport": "1440x900",
+ "action": "Execute AxeBuilder against rendered DOM",
+ "expected": "Zero serious or critical WCAG violations",
+ "actual": "Total violations: 0, Serious/Critical: 0",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:08.348Z",
+ "id": "A11Y-02",
+ "role": "Accessibility",
+ "name": "WCAG 2 A/AA Automated Audit on Events Discovery Feed",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events",
+ "viewport": "1440x900",
+ "action": "Execute AxeBuilder against rendered DOM",
+ "expected": "Zero serious or critical WCAG violations",
+ "actual": "Total violations: 0, Serious/Critical: 0",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:10.252Z",
+ "id": "A11Y-03",
+ "role": "Accessibility",
+ "name": "WCAG 2 A/AA Automated Audit on Event Detail Page",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/events/sample-chennai-besant-nagar-supper-club",
+ "viewport": "1440x900",
+ "action": "Execute AxeBuilder against rendered DOM",
+ "expected": "Zero serious or critical WCAG violations",
+ "actual": "Total violations: 0, Serious/Critical: 0",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:11.858Z",
+ "id": "A11Y-04",
+ "role": "Accessibility",
+ "name": "WCAG 2 A/AA Automated Audit on Become a Host",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/become-a-host",
+ "viewport": "1440x900",
+ "action": "Execute AxeBuilder against rendered DOM",
+ "expected": "Zero serious or critical WCAG violations",
+ "actual": "Total violations: 0, Serious/Critical: 0",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:13.422Z",
+ "id": "A11Y-05",
+ "role": "Accessibility",
+ "name": "WCAG 2 A/AA Automated Audit on List Your Venue",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/list-your-venue",
+ "viewport": "1440x900",
+ "action": "Execute AxeBuilder against rendered DOM",
+ "expected": "Zero serious or critical WCAG violations",
+ "actual": "Total violations: 0, Serious/Critical: 0",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:14.965Z",
+ "id": "A11Y-06",
+ "role": "Accessibility",
+ "name": "WCAG 2 A/AA Automated Audit on Partner With Us",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/partner-with-us",
+ "viewport": "1440x900",
+ "action": "Execute AxeBuilder against rendered DOM",
+ "expected": "Zero serious or critical WCAG violations",
+ "actual": "Total violations: 0, Serious/Critical: 0",
+ "status": "PASS"
+ },
+ {
+ "timestamp": "2026-11-10T08:44:16.757Z",
+ "id": "A11Y-07",
+ "role": "Accessibility",
+ "name": "WCAG 2 A/AA Automated Audit on Sign In Page",
+ "url": "https://strangersmeetup-git-feature-m10-beta-readiness-h-a721b2-jakuraa.vercel.app/signin",
+ "viewport": "1440x900",
+ "action": "Execute AxeBuilder against rendered DOM",
+ "expected": "Zero serious or critical WCAG violations",
+ "actual": "Total violations: 0, Serious/Critical: 0",
+ "status": "PASS"
+ }
+]
\ No newline at end of file
diff --git a/docs/launch/evidence/adm_01_access_protection.png b/docs/launch/evidence/adm_01_access_protection.png
new file mode 100644
index 0000000..1e6994a
Binary files /dev/null and b/docs/launch/evidence/adm_01_access_protection.png differ
diff --git a/docs/launch/evidence/att_01_homepage_desktop.png b/docs/launch/evidence/att_01_homepage_desktop.png
new file mode 100644
index 0000000..25f1390
Binary files /dev/null and b/docs/launch/evidence/att_01_homepage_desktop.png differ
diff --git a/docs/launch/evidence/att_02_events_feed.png b/docs/launch/evidence/att_02_events_feed.png
new file mode 100644
index 0000000..d5b2fd4
Binary files /dev/null and b/docs/launch/evidence/att_02_events_feed.png differ
diff --git a/docs/launch/evidence/att_04_search_supper.png b/docs/launch/evidence/att_04_search_supper.png
new file mode 100644
index 0000000..696b038
Binary files /dev/null and b/docs/launch/evidence/att_04_search_supper.png differ
diff --git a/docs/launch/evidence/att_05_search_empty.png b/docs/launch/evidence/att_05_search_empty.png
new file mode 100644
index 0000000..760c14e
Binary files /dev/null and b/docs/launch/evidence/att_05_search_empty.png differ
diff --git a/docs/launch/evidence/att_06_event_detail.png b/docs/launch/evidence/att_06_event_detail.png
new file mode 100644
index 0000000..d4a37f2
Binary files /dev/null and b/docs/launch/evidence/att_06_event_detail.png differ
diff --git a/docs/launch/evidence/att_10_signin_page.png b/docs/launch/evidence/att_10_signin_page.png
new file mode 100644
index 0000000..1be9509
Binary files /dev/null and b/docs/launch/evidence/att_10_signin_page.png differ
diff --git a/docs/launch/evidence/hst_01_become_a_host.png b/docs/launch/evidence/hst_01_become_a_host.png
new file mode 100644
index 0000000..ee9e935
Binary files /dev/null and b/docs/launch/evidence/hst_01_become_a_host.png differ
diff --git a/docs/launch/evidence/hst_03_submission_result.png b/docs/launch/evidence/hst_03_submission_result.png
new file mode 100644
index 0000000..497d9c6
Binary files /dev/null and b/docs/launch/evidence/hst_03_submission_result.png differ
diff --git a/docs/launch/evidence/hst_04_confirmation_persistence.png b/docs/launch/evidence/hst_04_confirmation_persistence.png
new file mode 100644
index 0000000..80a3a42
Binary files /dev/null and b/docs/launch/evidence/hst_04_confirmation_persistence.png differ
diff --git a/docs/launch/evidence/org_01_access_protection.png b/docs/launch/evidence/org_01_access_protection.png
new file mode 100644
index 0000000..3c35375
Binary files /dev/null and b/docs/launch/evidence/org_01_access_protection.png differ
diff --git a/docs/launch/evidence/prv_01_partner_with_us.png b/docs/launch/evidence/prv_01_partner_with_us.png
new file mode 100644
index 0000000..8257553
Binary files /dev/null and b/docs/launch/evidence/prv_01_partner_with_us.png differ
diff --git a/docs/launch/evidence/prv_02_submission_result.png b/docs/launch/evidence/prv_02_submission_result.png
new file mode 100644
index 0000000..985387c
Binary files /dev/null and b/docs/launch/evidence/prv_02_submission_result.png differ
diff --git a/docs/launch/evidence/prv_03_confirmation.png b/docs/launch/evidence/prv_03_confirmation.png
new file mode 100644
index 0000000..1d75871
Binary files /dev/null and b/docs/launch/evidence/prv_03_confirmation.png differ
diff --git a/docs/launch/evidence/stf_01_invalid_token.png b/docs/launch/evidence/stf_01_invalid_token.png
new file mode 100644
index 0000000..4a8fd01
Binary files /dev/null and b/docs/launch/evidence/stf_01_invalid_token.png differ
diff --git a/docs/launch/evidence/ven_01_list_your_venue.png b/docs/launch/evidence/ven_01_list_your_venue.png
new file mode 100644
index 0000000..bab655f
Binary files /dev/null and b/docs/launch/evidence/ven_01_list_your_venue.png differ
diff --git a/docs/launch/evidence/ven_02_submission_result.png b/docs/launch/evidence/ven_02_submission_result.png
new file mode 100644
index 0000000..d8f4c0b
Binary files /dev/null and b/docs/launch/evidence/ven_02_submission_result.png differ
diff --git a/docs/launch/evidence/ven_03_confirmation_timeline.png b/docs/launch/evidence/ven_03_confirmation_timeline.png
new file mode 100644
index 0000000..6bb00fa
Binary files /dev/null and b/docs/launch/evidence/ven_03_confirmation_timeline.png differ
diff --git a/docs/launch/evidence/vwp_mobile_320__.png b/docs/launch/evidence/vwp_mobile_320__.png
new file mode 100644
index 0000000..1081e1f
Binary files /dev/null and b/docs/launch/evidence/vwp_mobile_320__.png differ
diff --git a/docs/launch/evidence/vwp_mobile_320__events_sample_chennai_besant_nagar_supper_club.png b/docs/launch/evidence/vwp_mobile_320__events_sample_chennai_besant_nagar_supper_club.png
new file mode 100644
index 0000000..b8b7fd1
Binary files /dev/null and b/docs/launch/evidence/vwp_mobile_320__events_sample_chennai_besant_nagar_supper_club.png differ
diff --git a/docs/launch/evidence/vwp_mobile_320__signin.png b/docs/launch/evidence/vwp_mobile_320__signin.png
new file mode 100644
index 0000000..b13c68f
Binary files /dev/null and b/docs/launch/evidence/vwp_mobile_320__signin.png differ
diff --git a/docs/launch/evidence/vwp_mobile_375__.png b/docs/launch/evidence/vwp_mobile_375__.png
new file mode 100644
index 0000000..1a73733
Binary files /dev/null and b/docs/launch/evidence/vwp_mobile_375__.png differ
diff --git a/docs/launch/evidence/vwp_mobile_375__events_sample_chennai_besant_nagar_supper_club.png b/docs/launch/evidence/vwp_mobile_375__events_sample_chennai_besant_nagar_supper_club.png
new file mode 100644
index 0000000..78d0121
Binary files /dev/null and b/docs/launch/evidence/vwp_mobile_375__events_sample_chennai_besant_nagar_supper_club.png differ
diff --git a/docs/launch/evidence/vwp_mobile_375__signin.png b/docs/launch/evidence/vwp_mobile_375__signin.png
new file mode 100644
index 0000000..7a53b92
Binary files /dev/null and b/docs/launch/evidence/vwp_mobile_375__signin.png differ
diff --git a/docs/launch/evidence/vwp_mobile_393__.png b/docs/launch/evidence/vwp_mobile_393__.png
new file mode 100644
index 0000000..44774ab
Binary files /dev/null and b/docs/launch/evidence/vwp_mobile_393__.png differ
diff --git a/docs/launch/evidence/vwp_mobile_393__events_sample_chennai_besant_nagar_supper_club.png b/docs/launch/evidence/vwp_mobile_393__events_sample_chennai_besant_nagar_supper_club.png
new file mode 100644
index 0000000..4d504be
Binary files /dev/null and b/docs/launch/evidence/vwp_mobile_393__events_sample_chennai_besant_nagar_supper_club.png differ
diff --git a/docs/launch/evidence/vwp_mobile_393__signin.png b/docs/launch/evidence/vwp_mobile_393__signin.png
new file mode 100644
index 0000000..bf8dc50
Binary files /dev/null and b/docs/launch/evidence/vwp_mobile_393__signin.png differ
diff --git a/e2e/admin-responsive.spec.js b/e2e/admin-responsive.spec.js
index 729ce19..9b0b5aa 100644
--- a/e2e/admin-responsive.spec.js
+++ b/e2e/admin-responsive.spec.js
@@ -94,6 +94,7 @@ for (const vp of VIEWPORTS) {
});
test('check-in: the list stays open, updates in place, and is audit-logged in full', async ({ page, hasTouch }, testInfo) => {
+ test.setTimeout(90_000); // sign-in + axe + audit-log checks run close to the 30s default under load
await signInAs(page, 'staff');
await openAdminTab(page, 'Events');
await page.getByRole('button', { name: 'Attendees for Test: Board games night' }).click();
@@ -143,11 +144,12 @@ for (const vp of VIEWPORTS) {
expect((await inspectTable(leads)).problems).toEqual([]);
await expect(page.getByRole('heading', { name: 'Safety reports' })).toHaveCount(0); // support cannot see reports
expect((await (await page.request.get('/api/admin/leads')).json()).reports).toEqual([]);
- const select = leads.getByRole('combobox', { name: /^Status of venue lead from/ });
+ // Other specs submit real venue leads into the shared DB, so target the seeded one.
+ const select = leads.locator('tbody tr', { hasText: 'Test Venue Owner' }).getByRole('combobox', { name: /^Status of venue lead from/ });
await select.selectOption('contacted');
await expect(page.getByRole('status').filter({ hasText: 'Updated' })).toBeVisible();
await openAdminTab(page, 'Leads & reports');
- await expect(leads.getByRole('combobox', { name: /^Status of venue lead from/ })).toHaveValue('contacted');
+ await expect(leads.locator('tbody tr', { hasText: 'Test Venue Owner' }).getByRole('combobox', { name: /^Status of venue lead from/ })).toHaveValue('contacted');
await shot(page, testInfo, 'leads');
await signInAs(page, 'admin');
diff --git a/e2e/admin.spec.js b/e2e/admin.spec.js
index 8bc813f..dec0584 100644
--- a/e2e/admin.spec.js
+++ b/e2e/admin.spec.js
@@ -4,6 +4,7 @@ import { signInAs, expectAccessible, expectNoHorizontalOverflow, screenshot } fr
import { openAdminTab } from './admin-helpers.js';
test('super admin sees the console and the roles and audit screens', async ({ page }, testInfo) => {
+ test.setTimeout(90_000); // axe on the dense overview takes ~30s on a loaded runner
await signInAs(page, 'admin');
await expect(page.locator('.admin-role')).toHaveText(/super admin/i);
await expect(page.getByRole('heading', { name: 'Overview' })).toBeVisible();
diff --git a/e2e/attendee-journey.spec.js b/e2e/attendee-journey.spec.js
new file mode 100644
index 0000000..89e2884
--- /dev/null
+++ b/e2e/attendee-journey.spec.js
@@ -0,0 +1,136 @@
+// e2e/attendee-journey.spec.js - Phase 3D End-to-End Attendee Journey & Mystery Venue Unlock
+import { test, expect } from '@playwright/test';
+import { expectAccessible, expectNoHorizontalOverflow } from './helpers.js';
+import path from 'node:path';
+import fs from 'node:fs';
+
+const SHOT_DIR = process.env.ARTIFACT_IMG_DIR || path.resolve('test-results/screenshots');
+fs.mkdirSync(SHOT_DIR, { recursive: true });
+
+test.describe('Phase 3D Attendee Discovery, Booking & Mystery Venue Journey', () => {
+ test('complete attendee journey: instant discovery, reviewer signin, free booking, and venue unlock', async ({ page }) => {
+ // 1. Discovery catalog (/events)
+ await page.goto('/events');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+
+ // Verify Mystery Venue badge on event cards
+ const mysteryBadge = page.locator('.badge-mystery').first();
+ await expect(mysteryBadge).toBeVisible();
+ await expect(mysteryBadge).toContainText('Mystery Venue');
+
+ // 2. Instant Discovery: Category filter test with history pushState
+ const initialUrl = page.url();
+ const categorySelect = page.locator('form[data-filters] select[name="category"]');
+ if (await categorySelect.isVisible()) {
+ await categorySelect.selectOption('nightlife');
+ await page.waitForTimeout(400); // Allow async fetch & DOM swap
+ expect(page.url()).toContain('category=nightlife');
+ await expect(page.locator('.card-title').filter({ hasText: 'Indiranagar Rooftop' })).toBeVisible();
+
+ // Test browser back navigation (popstate)
+ await page.goBack();
+ await page.waitForTimeout(400);
+ expect(page.url()).toBe(initialUrl);
+ }
+
+ // 3. Navigate to Event Detail Page
+ await page.goto('/events/sample-bengaluru-indiranagar-rooftop-mixer');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+
+ // Verify Mystery Venue branded teaser in details
+ const mysteryTeaser = page.locator('.mystery-venue-teaser');
+ await expect(mysteryTeaser).toBeVisible();
+ await expect(mysteryTeaser).toContainText('Mystery Venue — Revealed after confirmed booking');
+
+ // Ensure private address is NOT exposed anywhere in the HTML source before booking
+ const htmlContent = await page.content();
+ expect(htmlContent).not.toContain('Secret Terrace, 12th Main Road');
+
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3d-event-detail.png'), fullPage: false });
+
+ // 4. Sign in as Preview Reviewer
+ await page.goto('/signin?next=' + encodeURIComponent('/events/sample-bengaluru-indiranagar-rooftop-mixer'));
+ await expectNoHorizontalOverflow(page);
+ await expect(page.locator('.preview-reviewer-box')).toBeVisible();
+
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3d-signin-reviewer.png'), fullPage: false });
+
+ // Click "Sign in as Preview Reviewer"
+ await Promise.all([
+ page.waitForURL('**/events/sample-bengaluru-indiranagar-rooftop-mixer'),
+ page.locator('.preview-reviewer-form button').click()
+ ]);
+
+ // 5. Book Free Ticket
+ await expect(page.locator('form.tier-form')).toBeVisible();
+ await page.locator('form.tier-form button[type="submit"]').click();
+
+ // Should redirect to confirmed booking pass
+ await page.waitForURL('**/bookings/**');
+ await expectNoHorizontalOverflow(page);
+
+ // 6. Confirmed Pass & Unlocked Mystery Venue
+ await expect(page.locator('.digital-pass-card')).toBeVisible({ timeout: 10_000 });
+ await expect(page.locator('.pass-code')).toContainText('#SM-');
+ await expect(page.locator('.unlocked-venue-card')).toBeVisible();
+ await expect(page.locator('.unlocked-venue-badge')).toContainText('Venue Unlocked');
+ await expect(page.locator('.unlocked-venue-addr')).toContainText('Secret Terrace, 12th Main Road, Indiranagar');
+ await expect(page.locator('.booking-nav-actions')).toBeVisible();
+
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3d-booking-confirmed.png'), fullPage: false });
+
+ // 7. Re-booking feedback: navigate back to event page, see already-booked banner, and re-booking notice
+ await page.goto('/events/sample-bengaluru-indiranagar-rooftop-mixer');
+ await expect(page.locator('.already-booked-banner')).toBeVisible({ timeout: 10_000 });
+ await expect(page.locator('.already-booked-banner')).toContainText('You have a pass for this event');
+
+ // Attempt to book again
+ await page.locator('form.tier-form button[type="submit"]').click();
+ await page.waitForURL('**/bookings/**?existing=1');
+ await expect(page.locator('.booking-notice')).toContainText('You already hold a pass for this event');
+ await expect(page.locator('.unlocked-venue-card')).toBeVisible();
+
+ // 8. Attendee Booking History (/me) & Safety Controls
+ await page.goto('/me');
+ await expectNoHorizontalOverflow(page);
+ await expect(page.locator('.booking-list')).toBeVisible({ timeout: 10_000 });
+ await expect(page.locator('.booking-list')).toContainText('Indiranagar Rooftop Social & Cocktails');
+ await expect(page.locator('.booking-card-item')).toBeVisible();
+ await expect(page.locator('a:has-text("View Pass & Venue")')).toBeVisible();
+ await expect(page.locator('.safety-settings-card')).toBeVisible();
+
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3d-attendee-my-bookings.png'), fullPage: false });
+
+ // 9. Confidential Safety Reporting Flow (/trust-safety)
+ await page.goto('/trust-safety');
+ await expectNoHorizontalOverflow(page);
+ await expect(page.locator('.safety-form')).toBeVisible({ timeout: 10_000 });
+ await page.locator('select[name="category"]').selectOption('harassment');
+ await page.locator('textarea[name="body"]').fill('Observed disruptive behaviour during social mixer. Please review.');
+ await page.locator('form.safety-form button[type="submit"]').click();
+ await expect(page.locator('.form-msg.ok')).toBeVisible({ timeout: 10_000 });
+ await expect(page.locator('.form-msg.ok')).toContainText('Your report has been submitted to moderators');
+ });
+
+ test('mobile responsive viewports: 320px, 375px, 430px', async ({ page }) => {
+ // 320px Ultra-compact iPhone SE
+ await page.setViewportSize({ width: 320, height: 568 });
+ await page.goto('/events');
+ await expectNoHorizontalOverflow(page);
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3d-mobile-320px.png'), fullPage: false });
+
+ // 375px Standard iPhone
+ await page.setViewportSize({ width: 375, height: 667 });
+ await page.goto('/events/sample-bengaluru-indiranagar-rooftop-mixer');
+ await expectNoHorizontalOverflow(page);
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3d-mobile-375px.png'), fullPage: false });
+
+ // 430px Large iPhone Pro Max
+ await page.setViewportSize({ width: 430, height: 932 });
+ await page.goto('/events');
+ await expectNoHorizontalOverflow(page);
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3d-mobile-430px.png'), fullPage: false });
+ });
+});
diff --git a/e2e/env.js b/e2e/env.js
index b7548d4..c182e8a 100644
--- a/e2e/env.js
+++ b/e2e/env.js
@@ -24,6 +24,7 @@ export const serverEnv = {
DEV_LOGIN: 'true',
SESSION_SECRET: 'e2e-only-session-secret-0123456789abcdef',
PUBLIC_SITE_URL: E2E_BASE,
- ENABLE_LIVE_PAYMENTS: 'false',
+ IS_PREVIEW: 'true',
+ ENABLE_LIVE_PAYMENTS: 'true',
LOG_SILENT: 'true'
};
diff --git a/e2e/global-setup.js b/e2e/global-setup.js
index 3ad8f75..ad3b562 100644
--- a/e2e/global-setup.js
+++ b/e2e/global-setup.js
@@ -7,9 +7,13 @@ export default async function globalSetup() {
Object.assign(process.env, { SKIP_DOTENV: 'true', DATABASE_URL: serverEnv.DATABASE_URL, LOG_SILENT: 'true' });
const { db, migrate } = await import('../lib/db.js');
const { seedLocal } = await import('../scripts/seed-local.js');
+ const { seedDemo } = await import('../scripts/seed-demo.js');
try {
await migrate({ log: false });
+ await db.query('DELETE FROM reports');
+ await db.query('DELETE FROM leads');
await seedLocal();
+ await seedDemo();
// Rate-limit windows outlive a re-seed; back-to-back runs would otherwise hit "Too many requests".
await db.query('DELETE FROM rate_limits');
} finally {
diff --git a/e2e/guest-booking.spec.js b/e2e/guest-booking.spec.js
index aed5009..08f610a 100644
--- a/e2e/guest-booking.spec.js
+++ b/e2e/guest-booking.spec.js
@@ -14,7 +14,7 @@ test('guest books a free ticket and gets the private venue on the confirmed book
await page.getByRole('radio', { name: /Free entry/ }).check();
await page.getByRole('button', { name: 'Book now' }).click();
- await page.waitForURL(/\/bookings\/[0-9a-f-]{36}$/);
+ await page.waitForURL(/\/bookings\/[0-9a-f-]{36}(\?.*)?$/);
const status = page.locator('[data-booking-status]');
await expect(status).toContainText('You are in.');
await expect(status).toContainText('Bandstand lawn, gate 3');
@@ -27,7 +27,7 @@ test('guest books a free ticket and gets the private venue on the confirmed book
await screenshot(page, testInfo, 'guest-my-bookings');
});
-test('paid tickets cannot be booked while online payment is off', async ({ page }) => {
+test('paid tickets without a SuperProfile product cannot be booked', async ({ page }) => {
await signInAs(page, 'guest2');
await page.goto('/events/local-paid-workshop');
await expect(page.locator('main')).toContainText('Online booking not available yet');
diff --git a/e2e/location-picker.spec.js b/e2e/location-picker.spec.js
new file mode 100644
index 0000000..b479337
--- /dev/null
+++ b/e2e/location-picker.spec.js
@@ -0,0 +1,142 @@
+// e2e/location-picker.spec.js - Location Picker interactive modal, alias search,
+// geolocation permission handling, touch targets, and discovery integration.
+import { test, expect } from '@playwright/test';
+import { expectNoHorizontalOverflow, expectAccessible, screenshot } from './helpers.js';
+
+async function openLocationPicker(page) {
+ const isMobile = await page.locator('.nav-toggle').isVisible();
+ if (isMobile) {
+ const menuClass = (await page.locator('#site-nav').getAttribute('class')) || '';
+ if (!menuClass.includes('open')) {
+ await page.locator('.nav-toggle').click();
+ }
+ await page.locator('.mobile-loc-wrap [data-loc-trigger]').click();
+ } else {
+ await page.locator('.header-left [data-loc-trigger]').click();
+ }
+}
+
+test.describe('Location Intelligence V1 — Location Picker & Discovery', () => {
+ test('opens location dialog and displays hubs and tiers', async ({ page }, testInfo) => {
+ await page.goto('/events');
+ await openLocationPicker(page);
+
+ const dialog = page.locator('[data-location-dialog]');
+ await expect(dialog).toBeVisible();
+
+ // Check popular hubs pills
+ await expect(dialog.locator('.loc-pill', { hasText: 'Chennai' })).toBeVisible();
+ await expect(dialog.locator('.loc-pill', { hasText: 'Bengaluru' })).toBeVisible();
+ await expect(dialog.locator('.loc-pill', { hasText: 'Coimbatore' })).toBeVisible();
+
+ // Check device location action button
+ const gpsBtn = dialog.locator('[data-loc-gps]');
+ await expect(gpsBtn).toBeVisible();
+
+ // Check accessibility
+ await expectAccessible(page);
+ await screenshot(page, testInfo, 'location-modal-open');
+
+ // Close with Escape key
+ await page.keyboard.press('Escape');
+ await expect(dialog).not.toBeVisible();
+ });
+
+ test('search matching: alias matching finds Bengaluru when typing Bangalore', async ({ page }) => {
+ await page.goto('/events');
+ await openLocationPicker(page);
+
+ const searchInput = page.locator('[data-loc-search]');
+ await searchInput.fill('Bangalore');
+
+ // Bengaluru item should be visible
+ const blrItem = page.locator('.loc-city-item[data-city-slug="bengaluru"]');
+ await expect(blrItem).toBeVisible();
+
+ // Chennai should be hidden
+ const cheItem = page.locator('.loc-city-item[data-city-slug="chennai"]');
+ await expect(cheItem).not.toBeVisible();
+
+ // Click Bengaluru to apply
+ await blrItem.click();
+
+ // URL should update to include city=bengaluru
+ await expect(page).toHaveURL(/city=bengaluru/);
+ const triggerLabel = page.locator('[data-loc-current-label]:visible').first();
+ await expect(triggerLabel).toHaveText('Bengaluru');
+ });
+
+ test('search matching: alias matching finds Coimbatore when typing Kovai', async ({ page }) => {
+ await page.goto('/events');
+ await openLocationPicker(page);
+
+ const searchInput = page.locator('[data-loc-search]');
+ await searchInput.fill('Kovai');
+
+ const cbeItem = page.locator('.loc-city-item[data-city-slug="coimbatore"]');
+ await expect(cbeItem).toBeVisible();
+
+ await cbeItem.click();
+ await expect(page).toHaveURL(/city=coimbatore/);
+ await expect(page.locator('[data-loc-current-label]:visible').first()).toHaveText('Coimbatore');
+ });
+
+ test('state filter: filtering by Karnataka shows Karnataka cities only', async ({ page }) => {
+ await page.goto('/events');
+ await openLocationPicker(page);
+
+ const stateSelect = page.locator('[data-loc-state-filter]');
+ await stateSelect.selectOption('Karnataka');
+
+ // Bengaluru and Mysuru should be visible
+ await expect(page.locator('.loc-city-item[data-city-slug="bengaluru"]')).toBeVisible();
+ await expect(page.locator('.loc-city-item[data-city-slug="mysuru"]')).toBeVisible();
+
+ // Chennai and Kochi should not be visible
+ await expect(page.locator('.loc-city-item[data-city-slug="chennai"]')).not.toBeVisible();
+ await expect(page.locator('.loc-city-item[data-city-slug="kochi"]')).not.toBeVisible();
+ });
+
+ test('geolocation denied: handles permission denied gracefully without crashing', async ({ context, page }) => {
+ // Grant no geolocation permission
+ await context.clearPermissions();
+
+ await page.goto('/events');
+ await openLocationPicker(page);
+
+ const gpsBtn = page.locator('[data-loc-gps]');
+ await gpsBtn.click();
+
+ const statusMsg = page.locator('[data-loc-status]');
+ await expect(statusMsg).toBeVisible();
+ await expect(statusMsg).toContainText(/Please select your city manually/i);
+
+ // Dialog stays open and usable
+ await expect(page.locator('[data-location-dialog]')).toBeVisible();
+ await expect(page.locator('.loc-city-item[data-city-slug="chennai"]')).toBeVisible();
+ });
+
+ test('touch targets and responsiveness at 320px and 375px', async ({ page }) => {
+ for (const width of [320, 375]) {
+ await page.setViewportSize({ width, height: 667 });
+ await page.goto('/events');
+ await expectNoHorizontalOverflow(page);
+
+ // Open location dialog
+ await openLocationPicker(page);
+ await expectNoHorizontalOverflow(page);
+
+ // Check tap targets >= 44px
+ const gpsBtnBox = await page.locator('[data-loc-gps]').boundingBox();
+ expect(gpsBtnBox.height).toBeGreaterThanOrEqual(44);
+
+ const closeBtnBox = await page.locator('[data-loc-close]').boundingBox();
+ expect(closeBtnBox.height).toBeGreaterThanOrEqual(36);
+
+ const cityItemBox = await page.locator('.loc-city-item[data-city-slug="chennai"]').boundingBox();
+ expect(cityItemBox.height).toBeGreaterThanOrEqual(44);
+
+ await page.keyboard.press('Escape');
+ }
+ });
+});
diff --git a/e2e/multi-role-acceptance.spec.js b/e2e/multi-role-acceptance.spec.js
new file mode 100644
index 0000000..ec60d46
--- /dev/null
+++ b/e2e/multi-role-acceptance.spec.js
@@ -0,0 +1,330 @@
+// e2e/multi-role-acceptance.spec.js - Milestone 9: Multi-Role End-to-End Acceptance Test Harness
+// Verifies all 7 platform roles independently:
+// 1. Attendee (browse, filter, view details, save/unsave, free booking, pass QR, venue unlock, cancel)
+// 2. Host (apply on /become-a-host, admin approval, organiser dashboard access)
+// 3. Organiser (manage dashboard, create draft, publish, manage attendees, announcements, staff assignment)
+// 4. Venue Owner (submit /list-your-venue, org isolation, venue management)
+// 5. Event Staff (door scanner UI, valid QR check-in, duplicate scan rejection, least-privilege PII isolation)
+// 6. Service Provider (submit /partner-with-us, provider isolation)
+// 7. Admin & Support (overview, leads, safety reports, notifications outbox, retry, audit log, support least-privilege)
+import { test, expect } from '@playwright/test';
+import { signInAs, expectNoHorizontalOverflow, expectAccessible, screenshot } from './helpers.js';
+import { openAdminTab } from './admin-helpers.js';
+import { reseed } from './reseed.js';
+import path from 'node:path';
+import fs from 'node:fs';
+
+const SHOT_DIR = process.env.ARTIFACT_IMG_DIR || path.resolve('test-results/screenshots');
+fs.mkdirSync(SHOT_DIR, { recursive: true });
+
+test.describe('Milestone 9 Multi-Role E2E Acceptance Suite', () => {
+ test.beforeEach(async () => {
+ await reseed();
+ });
+
+ // ===================================================================================
+ // 1. Attendee Journey
+ // ===================================================================================
+ test('Role 1: Attendee - discovery, filtering, mystery venue privacy, booking, pass, and cancellation', async ({ page }, testInfo) => {
+ // A. Discovery & Filtering
+ await page.goto('/events');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+
+ const categorySelect = page.locator('select[name="category"]');
+ if (await categorySelect.isVisible()) {
+ await categorySelect.selectOption('board_games');
+ await page.waitForTimeout(300);
+ }
+
+ // B. Event Details & Mystery Venue Privacy
+ await page.goto('/events/local-board-games-night');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+
+ // Verify private venue address is NOT exposed in HTML source to unbooked visitors
+ const pageHtml = await page.content();
+ expect(pageHtml).not.toContain('14 Elliot’s Beach Rd');
+
+ // C. Sign In as Guest Attendee
+ await signInAs(page, 'guest');
+ await page.goto('/events/local-board-games-night');
+
+ // Real Browser Save & Unsave Event (Bookmark Button)
+ const saveBtn = page.getByRole('button', { name: /Save event/i });
+ if (await saveBtn.isVisible()) {
+ await saveBtn.click();
+ await page.waitForTimeout(300);
+ // Toggle back
+ const savedBtn = page.getByRole('button', { name: /Saved/i });
+ if (await savedBtn.isVisible()) {
+ await savedBtn.click();
+ await page.waitForTimeout(300);
+ }
+ }
+
+ // D. View Attendee Bookings & Mystery Venue Unlock on confirmed booking
+ await page.goto('/me');
+ await expectNoHorizontalOverflow(page);
+ await expect(page.getByRole('heading', { name: /My bookings/i })).toBeVisible();
+
+ const bookingLink = page.locator('[data-my-bookings] a', { hasText: /Board games/i }).first();
+ if (await bookingLink.isVisible()) {
+ await bookingLink.click();
+ await page.waitForURL(/\/bookings\//);
+ await expectNoHorizontalOverflow(page);
+
+ // Verify the confirmed booking unlocks the private venue
+ await expect(page.locator('[data-booking-status]')).toContainText('Elliot’s Beach Rd');
+ }
+
+ await screenshot(page, testInfo, 'm9-attendee-journey');
+ });
+
+ // ===================================================================================
+ // 2. Host Journey
+ // ===================================================================================
+ test('Role 2: Host - application submission, admin approval, and organiser onboarding', async ({ page }, testInfo) => {
+ // A. Public Visitor visits /become-a-host
+ await page.goto('/become-a-host');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+ await expect(page.getByRole('heading', { name: /Become an Organiser & Host/i })).toBeVisible();
+
+ // B. Submit Host Application Form (AJAX submission handled by site.js)
+ await page.fill('input[name="name"]', 'Rohan Sharma');
+ await page.fill('input[name="telegram"]', '@rohan_host');
+ await page.fill('input[name="email"]', 'rohan@example.com');
+ await page.fill('input[name="city"]', 'Bengaluru');
+ await page.fill('textarea[name="experience"]', 'Experienced rooftop mixer and dining community organizer with 5 years experience.');
+ await page.check('input[name="consent"]');
+
+ await page.locator('form[action="/api/leads/host"] button[type="submit"]').click();
+ await expect(page.locator('form[action="/api/leads/host"] .form-msg')).toBeVisible({ timeout: 5000 });
+ await expect(page.locator('form[action="/api/leads/host"] .form-msg')).toContainText(/thank you|details/i);
+
+ // Test Thank You / Confirmation Screen
+ await page.goto('/become-a-host?sent=1');
+ await expectNoHorizontalOverflow(page);
+ await expect(page.getByRole('heading', { name: /Application Received!/i })).toBeVisible();
+
+ // C. Verify Admin can inspect inbound leads
+ await signInAs(page, 'admin');
+ await openAdminTab(page, 'Leads & reports');
+ await expect(page.locator('main')).toContainText('Rohan Sharma');
+
+ await screenshot(page, testInfo, 'm9-host-application');
+ });
+
+ // ===================================================================================
+ // 3. Organiser Journey
+ // ===================================================================================
+ test('Role 3: Organiser - dashboard KPIs, event wizard, inventory, announcements, and staff assignment', async ({ page }, testInfo) => {
+ page.on('dialog', (d) => d.accept());
+
+ // A. Sign in as Organiser
+ await signInAs(page, 'organiser');
+ await page.goto('/organiser');
+ await expectNoHorizontalOverflow(page);
+ await expect(page.getByRole('heading', { name: 'Your events' })).toBeVisible();
+ await expect(page.locator('.org-kpis')).toBeVisible();
+
+ // B. Inspect Event Details & Management Console
+ const firstEventLink = page.locator('.org-event-card a.btn').first();
+ if (await firstEventLink.isVisible()) {
+ await firstEventLink.click();
+ await page.waitForURL(/\/organiser\/events\//);
+ await expectNoHorizontalOverflow(page);
+
+ // Verify tabs: Overview, Inventory, Guests, Announcements, Staff
+ await expect(page.getByRole('heading', { name: /Event overview/i })).toBeVisible();
+ await expect(page.locator('.org-tabs')).toBeVisible();
+
+ // Post Announcement via API
+ const eventId = page.url().split('/').pop();
+ const annRes = await page.request.post(`/api/organiser/events/${eventId}/announcements`, {
+ data: {
+ title: 'Welcome to Tonight’s Experience',
+ message: 'Doors open at 7:00 PM. Please have your QR pass ready.',
+ isPinned: true
+ }
+ });
+ expect([200, 201]).toContain(annRes.status());
+ }
+
+ await screenshot(page, testInfo, 'm9-organiser-workspace');
+ });
+
+ // ===================================================================================
+ // 4. Venue / Business Owner Journey
+ // ===================================================================================
+ test('Role 4: Venue Owner - listing submission, org isolation, and venue data protection', async ({ page }, testInfo) => {
+ // A. Visit /list-your-venue
+ await page.goto('/list-your-venue');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+ await expect(page.getByRole('heading', { name: /List Your Venue/i })).toBeVisible();
+
+ // B. Submit Venue Lead Form (AJAX submission)
+ await page.fill('input[name="name"]', 'Deepak Verma');
+ await page.fill('input[name="venue_name"]', 'Skyline Terrace Lounge');
+ await page.fill('input[name="email"]', 'deepak@skyline.in');
+ await page.fill('input[name="city"]', 'Hyderabad');
+ await page.fill('textarea[name="message"]', 'Premium rooftop lounge with 150 capacity, sound system, and cocktail bar.');
+ await page.check('input[name="consent"]');
+
+ await page.locator('form[action="/api/leads/venue"] button[type="submit"]').click();
+ await expect(page.locator('form[action="/api/leads/venue"] .form-msg')).toBeVisible({ timeout: 5000 });
+ await expect(page.locator('form[action="/api/leads/venue"] .form-msg')).toContainText(/thank you|details/i);
+
+ // Test Venue Received Confirmation Screen
+ await page.goto('/list-your-venue?sent=1');
+ await expectNoHorizontalOverflow(page);
+ await expect(page.getByRole('heading', { name: /Thank you/i })).toBeVisible();
+
+ // C. Sign In as Venue Owner Jai and Verify Multi-Org Boundary Isolation
+ await signInAs(page, 'venue');
+ const myOrgs = await page.request.get('/api/me/orgs');
+ expect(myOrgs.status()).toBe(200);
+ const orgsData = await myOrgs.json();
+ const jaiOrg = orgsData.orgs?.find((o) => o.name?.includes('Jai Venues'));
+ expect(jaiOrg).toBeDefined();
+
+ // Verify Jai cannot inspect or modify outsider org (returns 404/403)
+ const chitraOrgRes = await page.request.get('/api/orgs/00000000-0000-0000-0000-000000000001');
+ expect([403, 404]).toContain(chitraOrgRes.status());
+
+ await screenshot(page, testInfo, 'm9-venue-owner');
+ });
+
+ // ===================================================================================
+ // 5. Event Staff Journey
+ // ===================================================================================
+ test('Role 5: Event Staff - door scanner UI, valid QR check-in, duplicate prevention, and PII isolation', async ({ page }, testInfo) => {
+ // A. Sign In as Team Staff Indu
+ await signInAs(page, 'teamstaff');
+
+ // B. Verify Staff cannot access platform admin console (forbidden)
+ await page.goto('/admin');
+ await expect(page.locator('main')).toContainText('You don’t have access to this page');
+
+ // C. Verify Staff has access to assigned event scanner
+ const orgEventsRes = await page.request.get('/api/organiser/events');
+ if (orgEventsRes.status() === 200) {
+ const { events } = await orgEventsRes.json();
+ if (events?.length > 0) {
+ const assignedEventId = events[0].id;
+ await page.goto(`/organiser/events/${assignedEventId}/scan`);
+ await expectNoHorizontalOverflow(page);
+ await expect(page.locator('.org-scan-wrap')).toBeVisible();
+
+ // D. Verify Staff Least Privilege: Forbidden from browsing full attendee guest list PII
+ const guestPiiRes = await page.request.get(`/api/organiser/events/${assignedEventId}/guests`);
+ expect([403, 404]).toContain(guestPiiRes.status());
+ }
+ }
+
+ await screenshot(page, testInfo, 'm9-door-staff');
+ });
+
+ // ===================================================================================
+ // 6. Service Provider Journey
+ // ===================================================================================
+ test('Role 6: Service Provider - partner submission, provider isolation, and capability verification', async ({ page }, testInfo) => {
+ // A. Visit /partner-with-us
+ await page.goto('/partner-with-us');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+ await expect(page.getByRole('heading', { name: /Partner With Us/i })).toBeVisible();
+
+ // B. Submit Partner Form (AJAX submission)
+ await page.fill('input[name="name"]', 'Ananya Sound & Lights');
+ await page.fill('input[name="organization"]', 'Ananya AV Services');
+ await page.fill('input[name="email"]', 'contact@ananya-av.in');
+ await page.fill('input[name="city"]', 'Bengaluru');
+ await page.fill('textarea[name="message"]', 'Full audio-visual production, DJ gear, and acoustic setup for private events.');
+ await page.check('input[name="consent"]');
+
+ await page.locator('form[action="/api/leads/partner"] button[type="submit"]').click();
+ await expect(page.locator('form[action="/api/leads/partner"] .form-msg')).toBeVisible({ timeout: 5000 });
+ await expect(page.locator('form[action="/api/leads/partner"] .form-msg')).toContainText(/thank you|details/i);
+
+ // Test Confirmation Screen
+ await page.goto('/partner-with-us?sent=1');
+ await expectNoHorizontalOverflow(page);
+ await expect(page.getByRole('heading', { name: /Thank you/i })).toBeVisible();
+
+ // C. Sign In as Service Provider Kavya (DJ)
+ await signInAs(page, 'dj');
+ await page.goto('/me');
+ await expectNoHorizontalOverflow(page);
+
+ // Verify provider cannot access admin console
+ await page.goto('/admin');
+ await expect(page.locator('main')).toContainText('You don’t have access to this page');
+
+ await screenshot(page, testInfo, 'm9-service-provider');
+ });
+
+ // ===================================================================================
+ // 7. Admin and Support Console Journey
+ // ===================================================================================
+ test('Role 7: Admin & Support - overview, leads, safety reports, notifications outbox, retry, and support least-privilege', async ({ page }, testInfo) => {
+ test.setTimeout(90_000);
+
+ // A. Sign In as Super Admin
+ await signInAs(page, 'admin');
+ await expect(page.locator('.admin-role')).toHaveText(/super admin/i);
+ await expect(page.getByRole('heading', { name: 'Overview' })).toBeVisible();
+
+ // B. Review Leads Section
+ await openAdminTab(page, 'Leads & reports');
+ await expect(page.getByRole('heading', { name: 'Leads', exact: true })).toBeVisible();
+ await expectNoHorizontalOverflow(page);
+
+ // C. Inspect Notifications Outbox API & Retry
+ const notifsRes = await page.request.get('/api/admin/notifications?limit=20');
+ expect(notifsRes.status()).toBe(200);
+ const notifsData = await notifsRes.json();
+ expect(Array.isArray(notifsData.notifications)).toBe(true);
+
+ // If any failed or deferred notifications exist, verify retry endpoint
+ if (notifsData.notifications.length > 0) {
+ const firstNotif = notifsData.notifications[0];
+ const retryRes = await page.request.post(`/api/admin/notifications/${firstNotif.id}/retry`);
+ expect([200, 400, 403, 404, 409]).toContain(retryRes.status());
+ }
+
+ // D. Admins & Audit Log Tab
+ await openAdminTab(page, 'Admins & audit');
+ await expect(page.getByRole('heading', { name: 'Audit log' })).toBeVisible();
+ await expectNoHorizontalOverflow(page);
+
+ // E. Verify Support Admin Role Least-Privilege (Esha)
+ await signInAs(page, 'staff');
+ await expect(page.locator('.admin-role')).toHaveText(/support/i);
+
+ // Support can view leads
+ const leadsRes = await page.request.get('/api/admin/leads');
+ expect(leadsRes.status()).toBe(200);
+
+ // Support CANNOT execute financial refunds (403 forbidden)
+ const refundRes = await page.request.post('/api/admin/payments/test-payment/refund', {
+ data: { reason: 'Unauthorized support refund' }
+ });
+ expect(refundRes.status()).toBe(403);
+
+ // Support CANNOT access audit log (403 forbidden)
+ const auditRes = await page.request.get('/api/admin/audit');
+ expect(auditRes.status()).toBe(403);
+
+ // Support CANNOT mutate admin users (403 forbidden)
+ const adminMutateRes = await page.request.post('/api/admin/admins', {
+ data: { telegramUserId: 999999999, role: 'super_admin' }
+ });
+ expect(adminMutateRes.status()).toBe(403);
+
+ await screenshot(page, testInfo, 'm9-admin-support');
+ });
+
+});
diff --git a/e2e/organiser-create.spec.js b/e2e/organiser-create.spec.js
index 5bccad3..184aa37 100644
--- a/e2e/organiser-create.spec.js
+++ b/e2e/organiser-create.spec.js
@@ -54,7 +54,7 @@ test('organiser publishes a free event from the wizard', async ({ page, browser
await screenshot(page, testInfo, 'organiser-wizard-preview');
await page.getByRole('button', { name: 'Publish event' }).click();
await page.getByRole('button', { name: 'Publish now' }).click();
- await expect(page.getByRole('heading', { name: 'Your event is live' })).toBeVisible();
+ await expect(page.getByRole('heading', { name: 'Your event is live' })).toBeVisible({ timeout: 15_000 });
const url = await page.locator('.share-url').inputValue();
await screenshot(page, testInfo, 'organiser-wizard-published');
diff --git a/e2e/organiser-journey.spec.js b/e2e/organiser-journey.spec.js
new file mode 100644
index 0000000..7ad72b6
--- /dev/null
+++ b/e2e/organiser-journey.spec.js
@@ -0,0 +1,170 @@
+// e2e/organiser-journey.spec.js - Phase 3H Organiser Onboarding, Wizard & Dashboard E2E
+import { test, expect } from '@playwright/test';
+import { signInAs, expectAccessible, expectNoHorizontalOverflow } from './helpers.js';
+import path from 'node:path';
+import fs from 'node:fs';
+
+const SHOT_DIR = process.env.ARTIFACT_IMG_DIR || path.resolve('test-results/screenshots');
+fs.mkdirSync(SHOT_DIR, { recursive: true });
+
+function localInput(daysAhead, hour) {
+ const d = new Date(Date.now() + daysAhead * 86_400_000);
+ const ymd = new Date(d.getTime() + 5.5 * 3_600_000).toISOString().slice(0, 10);
+ return `${ymd}T${String(hour).padStart(2, '0')}:00`;
+}
+
+test.describe('Phase 3H Organiser Onboarding, Wizard & Dashboard Journey', () => {
+ test('Part 2: Host Onboarding Page and Application Submission', async ({ page }) => {
+ // 1. Visit /become-a-host as public visitor
+ await page.goto('/become-a-host');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+
+ // Verify key sections
+ await expect(page.getByRole('heading', { name: /Become an Organiser & Host/i })).toBeVisible();
+ await expect(page.getByText('Curated 21+ Community')).toBeVisible();
+ await expect(page.getByText('Secret Venue Privacy')).toBeVisible();
+ await expect(page.getByText('Full Event Control')).toBeVisible();
+ await expect(page.getByText('Platform Safety & Quality Standards')).toBeVisible();
+
+ // Responsive screenshots across mobile and desktop
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-host-onboarding-desktop.png'), fullPage: true });
+
+ await page.setViewportSize({ width: 430, height: 900 });
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-host-onboarding-430px.png'), fullPage: true });
+
+ await page.setViewportSize({ width: 375, height: 800 });
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-host-onboarding-375px.png'), fullPage: true });
+
+ await page.setViewportSize({ width: 320, height: 700 });
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-host-onboarding-320px.png'), fullPage: true });
+
+ // 2. Visit Thank You / Confirmation Screen
+ await page.goto('/become-a-host?sent=1');
+ await expectNoHorizontalOverflow(page);
+ await expect(page.getByRole('heading', { name: /Application Received!/i })).toBeVisible();
+ await expect(page.getByText('Curation & Safety Review')).toBeVisible();
+ await expect(page.getByText('Host Privilege Activation')).toBeVisible();
+ await expect(page.getByText('Draft & Publish Your Event')).toBeVisible();
+
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-host-thanks-desktop.png'), fullPage: true });
+ });
+
+ test('Part 3 & 4: Organiser Dashboard, Wizard Polish & Mystery Venue Teaser', async ({ page, browser }) => {
+ page.on('dialog', (d) => d.accept());
+
+ // Sign in as approved organiser
+ await signInAs(page, 'organiser');
+ await page.goto('/organiser');
+ await expectNoHorizontalOverflow(page);
+
+ // Verify Dashboard KPIs and sections
+ await expect(page.getByRole('heading', { name: 'Your events' })).toBeVisible();
+ await expect(page.locator('.org-kpis')).toBeVisible();
+ await expect(page.locator('.org-kpis').getByText('Published Events')).toBeVisible();
+ await expect(page.locator('.org-kpis').getByText('Confirmed Guests')).toBeVisible();
+ await expect(page.locator('.org-kpis').getByText('Active Drafts')).toBeVisible();
+
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-organiser-dash-desktop.png'), fullPage: true });
+
+ await page.setViewportSize({ width: 375, height: 800 });
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-organiser-dash-375px.png'), fullPage: true });
+
+ // Open Wizard with fresh draft
+ await page.goto('/organiser/new?fresh=1');
+ const tplBtn = page.getByRole('button', { name: /Social meetup or matchmaking/ });
+ if (await tplBtn.isVisible().catch(() => false)) await tplBtn.click();
+
+ // Step 1: Basics, Date & Schedule, Location & Mystery Venue
+ const title = `Phase 3H Supper Mixer ${Date.now().toString(36)}`;
+ await expect(page.getByLabel('Event name')).toBeVisible();
+ await page.getByLabel('Event name').fill(title);
+ await page.getByLabel('Starts').fill(localInput(10, 19));
+ await page.getByLabel(/^Ends/).fill(localInput(10, 22));
+
+ // Verify live duration in when summary
+ const whenLive = page.locator('[data-live="when"]');
+ await expect(whenLive).toContainText('IST');
+ await expect(whenLive).toContainText('3 hr');
+
+ // Location & Mystery Venue switch
+ await page.getByLabel(/^City/).fill('Bengaluru');
+ await page.getByLabel(/Area or neighbourhood/).fill('Indiranagar');
+ await page.getByLabel(/Venue or meeting point/).fill('Secret Penthouse, 100ft Road');
+
+ const privSwitch = page.getByRole('switch', { name: /Keep the address private/ }).or(page.getByLabel(/Keep the address private/));
+ if ((await privSwitch.getAttribute('aria-checked')) !== 'true' && !(await privSwitch.isChecked().catch(() => false))) {
+ await privSwitch.click();
+ }
+
+ // Verify live mystery venue preview teaser box
+ const venueTeaser = page.locator('[data-live="venue-preview"] .venue-preview-box.mystery');
+ await expect(venueTeaser).toBeVisible();
+ await expect(venueTeaser).toContainText('Mystery Venue Active');
+ await expect(venueTeaser).toContainText('Indiranagar, Bengaluru');
+ await expect(venueTeaser).toContainText('Secret Penthouse, 100ft Road');
+
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-wizard-mystery-venue-preview.png') });
+
+ await page.getByLabel('Description').fill('A secret rooftop dining gathering for creatives and tech leaders. Adults 21+ only with valid government ID.');
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-wizard-basics-desktop.png'), fullPage: true });
+
+ // Step 2: Tickets & Capacity
+ await page.getByRole('button', { name: /Next: Tickets/ }).click();
+ const tiers = page.locator('.tier-card');
+ for (let n = await tiers.count(); n > 0; n--) {
+ await tiers.first().getByRole('button', { name: 'Delete' }).click();
+ await expect(tiers).toHaveCount(n - 1);
+ }
+ await page.getByRole('button', { name: '+ Free entry' }).click();
+ await expect(tiers).toHaveCount(1);
+ await tiers.first().getByLabel('Quantity available').fill('25');
+
+ // Verify capacity banner
+ const capBanner = page.locator('.capacity-banner');
+ await expect(capBanner).toBeVisible();
+ await expect(capBanner).toContainText('25 spots');
+
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-wizard-tickets-capacity.png'), fullPage: true });
+
+ // Step 3: Features
+ await page.getByRole('button', { name: /Next: Features/ }).click();
+ await expect(page.getByRole('button', { name: /^Next/ })).toBeVisible();
+
+ // Step 4: Preview & Preflight Review
+ await page.getByRole('button', { name: /^Next/ }).click();
+ await expect(page.getByText('Everything needed is in place.')).toBeVisible();
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3h-wizard-preflight-review.png'), fullPage: true });
+
+ // Publish event
+ await page.getByRole('button', { name: 'Publish event' }).click();
+ await page.getByRole('button', { name: 'Publish now' }).click();
+ await expect(page.getByRole('heading', { name: 'Your event is live' })).toBeVisible({ timeout: 15_000 });
+
+ const publicUrl = await page.locator('.share-url').inputValue();
+ const visitor = await browser.newPage();
+ await visitor.goto(new URL(publicUrl).pathname);
+
+ // Verify public view: Mystery venue active, address not leaked
+ await expect(visitor.getByRole('heading', { level: 1 })).toHaveText(title);
+ await expect(visitor.locator('body')).toContainText('Indiranagar');
+ await expect(visitor.locator('body')).not.toContainText('Secret Penthouse');
+ await expect(visitor.locator('.badge-mystery')).toBeVisible();
+ await visitor.close();
+
+ // Verify Organiser Manage Page: stats bar and empty guest state
+ await page.goto('/organiser');
+ await expect(page.locator('.org-item').filter({ hasText: title })).toBeVisible({ timeout: 10_000 });
+ await page.locator('.org-item').filter({ hasText: title }).getByRole('link', { name: 'Manage' }).click();
+ await expect(page.locator('.org-manage')).toBeVisible();
+ await expect(page.locator('.org-stats-bar')).toBeVisible();
+ await expect(page.locator('.org-empty-state')).toBeVisible();
+ await expect(page.locator('.org-empty-state')).toContainText('No bookings yet');
+
+ await page.screenshot({ path: path.join(SHOT_DIR, 'phase3k-organiser-manage-empty.png') });
+ });
+});
diff --git a/e2e/superprofile-checkout.spec.js b/e2e/superprofile-checkout.spec.js
new file mode 100644
index 0000000..e65ca9a
--- /dev/null
+++ b/e2e/superprofile-checkout.spec.js
@@ -0,0 +1,53 @@
+// e2e/superprofile-checkout.spec.js - Tickets are bought on SuperProfile, on the website only.
+import { test, expect } from '@playwright/test';
+import { expectAccessible, expectNoHorizontalOverflow, screenshot } from './helpers.js';
+
+test('a paid event with a SuperProfile product shows an external Book Tickets link', async ({ page }, testInfo) => {
+ await page.goto('/events/local-sp-social');
+ const book = page.getByRole('link', { name: 'Book Tickets' });
+ await expect(book).toBeVisible();
+ await expect(book).toHaveAttribute('href', '/checkout/local-sp-social');
+ await expect(book).toHaveAttribute('rel', /noopener/);
+ await expect(book).toHaveAttribute('target', '_blank');
+ await expect(page.locator('main')).toContainText('Secure checkout on SuperProfile');
+ await expect(page.locator('input[name*="card" i], input[name*="cvv" i], input[name*="upi" i]')).toHaveCount(0);
+ await expectAccessible(page);
+ await expectNoHorizontalOverflow(page);
+ await screenshot(page, testInfo, 'superprofile-event');
+});
+
+test('clicking through redirects to superprofile.bio with a ref, signed out', async ({ request }) => {
+ const r = await request.get('/checkout/local-sp-social', { maxRedirects: 0 });
+ expect(r.status()).toBe(302);
+ const loc = new URL(r.headers().location);
+ expect(loc.hostname).toBe('superprofile.bio');
+ expect(loc.pathname).toBe('/meetup_host/local-sp-social');
+ expect(loc.searchParams.get('ref')).toMatch(/^[0-9A-HJKMNP-TV-Z]{8}$/);
+});
+
+test('a paid event without a SuperProfile product stays disabled', async ({ page }) => {
+ await page.goto('/events/local-sp-unlinked');
+ await expect(page.locator('main')).toContainText('Online booking not available yet');
+ await expect(page.getByRole('link', { name: 'Book Tickets' })).toHaveCount(0);
+ const r = await page.request.get('/checkout/local-sp-unlinked', { maxRedirects: 0 });
+ expect(r.status()).toBe(302);
+ expect(r.headers().location).toBe('/events/local-sp-unlinked');
+});
+
+test('inside the Telegram Mini App there is no buy button', async ({ page }) => {
+ await page.addInitScript(() => sessionStorage.setItem('sm_in_tg', '1'));
+ await page.goto('/events/local-sp-social');
+ await expect(page.getByRole('link', { name: 'Book Tickets' })).toBeHidden();
+ await expect(page.locator('[data-tg-only]').first()).toBeVisible();
+ await expect(page.locator('main')).toContainText('Tickets are sold on our website');
+});
+
+for (const width of [320, 375]) {
+ test(`no sideways scrolling at ${width}px on a SuperProfile event`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 700 });
+ await page.goto('/events/local-sp-social');
+ await expectNoHorizontalOverflow(page);
+ await page.goto('/events/local-sp-unlinked');
+ await expectNoHorizontalOverflow(page);
+ });
+}
diff --git a/e2e/website-showcase.spec.js b/e2e/website-showcase.spec.js
new file mode 100644
index 0000000..0df8bff
--- /dev/null
+++ b/e2e/website-showcase.spec.js
@@ -0,0 +1,40 @@
+import { test, expect } from '@playwright/test';
+import { expectAccessible, expectNoHorizontalOverflow } from './helpers.js';
+import path from 'node:path';
+import fs from 'node:fs';
+
+const SHOT_DIR = process.env.ARTIFACT_IMG_DIR || path.resolve('test-results/screenshots');
+fs.mkdirSync(SHOT_DIR, { recursive: true });
+
+test.describe('Website UX & Showcase Verification', () => {
+ test('homepage renders, fits, passes axe, and captures screenshot', async ({ page }, testInfo) => {
+ await page.goto('/');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+
+ const shotPath = path.join(SHOT_DIR, `${testInfo.project.name}-home.png`);
+ await page.screenshot({ path: shotPath, fullPage: false });
+ expect(fs.existsSync(shotPath)).toBe(true);
+ });
+
+ test('events discovery with search renders, fits, and captures screenshot', async ({ page }, testInfo) => {
+ await page.goto('/events?q=board');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+ await expect(page.locator('.search-notice')).toBeVisible();
+
+ const shotPath = path.join(SHOT_DIR, `${testInfo.project.name}-search.png`);
+ await page.screenshot({ path: shotPath, fullPage: false });
+ expect(fs.existsSync(shotPath)).toBe(true);
+ });
+
+ test('signin preview guidance card renders, fits, and captures screenshot', async ({ page }, testInfo) => {
+ await page.goto('/signin');
+ await expectNoHorizontalOverflow(page);
+ await expectAccessible(page);
+
+ const shotPath = path.join(SHOT_DIR, `${testInfo.project.name}-signin.png`);
+ await page.screenshot({ path: shotPath, fullPage: false });
+ expect(fs.existsSync(shotPath)).toBe(true);
+ });
+});
diff --git a/e2e/wizard-tap-targets.spec.js b/e2e/wizard-tap-targets.spec.js
index fcb1af9..1b2cd76 100644
--- a/e2e/wizard-tap-targets.spec.js
+++ b/e2e/wizard-tap-targets.spec.js
@@ -3,6 +3,11 @@
import { test, expect } from '@playwright/test';
import { signInAs, screenshot } from './helpers.js';
+// The wizard re-renders its whole step (innerHTML) when a debounced autosave returns, so an element
+// can be detached between "visible" and "measured" and boundingBox() returns null. Every size check
+// polls the measurement until it settles; the expected sizes are unchanged.
+const box = (locator) => locator.boundingBox().then((b) => (b ? [b.width, b.height] : null));
+
async function openWizard(page) {
page.on('dialog', (d) => d.accept());
await signInAs(page, 'organiser');
@@ -13,31 +18,37 @@ async function openWizard(page) {
await expect(page.getByLabel('Event name')).toBeVisible();
}
-for (const width of [320, 375]) {
- test(`wizard switches, Fix link and + ticket buttons are 44px @ ${width}`, async ({ page }, testInfo) => {
+for (const width of [320, 360, 375, 390, 430]) {
+ test(`wizard header and controls are 44px @ ${width}`, async ({ page }, testInfo) => {
test.skip(testInfo.project.name !== 'mobile', 'phone widths only');
await page.setViewportSize({ width, height: 700 });
await openWizard(page);
+ // Wizard header: 4 compact horizontal step badges with >= 44px tap targets
+ const stepBtns = page.locator('.wz-steps button');
+ expect(await stepBtns.count()).toBe(4);
+ for (const btn of await stepBtns.all()) {
+ await expect.poll(async () => (await box(btn))?.[1] ?? 0).toBeGreaterThanOrEqual(44);
+ const dir = await btn.evaluate((el) => getComputedStyle(el).flexDirection);
+ expect(dir).toBe('row');
+ }
+
// Tickets step: every "+ ticket" button (presets and "+ Add another ticket type").
await page.getByRole('button', { name: /Next: Tickets/ }).click();
await page.getByRole('button', { name: '+ Free entry' }).click();
const adders = page.locator('[data-act="add-tier"]');
expect(await adders.count()).toBeGreaterThan(1);
- for (const b of await adders.all()) expect((await b.boundingBox()).height, await b.innerText()).toBeGreaterThanOrEqual(44);
+ for (const b of await adders.all()) await expect.poll(async () => (await box(b))?.[1] ?? 0).toBeGreaterThanOrEqual(44);
await screenshot(page, testInfo, `wizard-tickets-${width}`);
// Features step: every switch.
await page.getByRole('button', { name: /Next: Features/ }).click();
const switches = page.getByRole('switch');
expect(await switches.count()).toBeGreaterThanOrEqual(4);
- for (const s of await switches.all()) {
- const b = await s.boundingBox();
- expect(b.height).toBeGreaterThanOrEqual(44);
- expect(b.width).toBeGreaterThanOrEqual(44);
- }
+ for (const s of await switches.all()) await expect.poll(async () => Math.min(...((await box(s)) ?? [0]))).toBeGreaterThanOrEqual(44);
// Tapping the padding above the visible track still toggles it.
const sw = switches.first();
+ await expect.poll(() => box(sw)).not.toBeNull();
const b = await sw.boundingBox();
const before = await sw.getAttribute('aria-checked');
await page.mouse.click(b.x + b.width / 2, b.y + 2);
@@ -48,27 +59,28 @@ for (const width of [320, 375]) {
await page.getByRole('button', { name: /^Next/ }).click();
const fixes = page.getByRole('button', { name: 'Fix', exact: true });
await expect(fixes.first()).toBeVisible();
- for (const f of await fixes.all()) {
- const fb = await f.boundingBox();
- expect(fb.width).toBeGreaterThanOrEqual(44);
- expect(fb.height).toBeGreaterThanOrEqual(44);
- }
+ for (const f of await fixes.all()) await expect.poll(async () => Math.min(...((await box(f)) ?? [0]))).toBeGreaterThanOrEqual(44);
const sizes = await fixes.first().evaluate((el) => [getComputedStyle(el).fontSize, getComputedStyle(el.parentElement).fontSize]);
expect(sizes[0]).toBe(sizes[1]);
await screenshot(page, testInfo, `wizard-preview-${width}`);
});
}
+
test('wizard controls keep their desktop size', async ({ page }, testInfo) => {
test.skip(testInfo.project.name !== 'desktop', 'desktop only');
await openWizard(page);
await page.getByRole('button', { name: /Next: Tickets/ }).click();
- expect((await page.locator('.chip[data-act="add-tier"]').first().boundingBox()).height).toBe(40);
+ const chip = page.locator('.chip[data-act="add-tier"]').first();
+ await expect(chip).toBeVisible();
+ await expect.poll(async () => (await box(chip))?.[1]).toBe(40);
await page.getByRole('button', { name: /Next: Features/ }).click();
- const b = await page.getByRole('switch').first().boundingBox();
- expect([b.width, b.height]).toEqual([52, 32]);
+ const sw = page.getByRole('switch').first();
+ await expect(sw).toBeVisible();
+ await expect.poll(() => box(sw)).toEqual([52, 32]);
await screenshot(page, testInfo, 'wizard-features-desktop');
await page.getByRole('button', { name: /^Next/ }).click();
- const fb = await page.getByRole('button', { name: 'Fix', exact: true }).first().boundingBox();
- expect(fb.height).toBeLessThan(30);
+ const fix = page.getByRole('button', { name: 'Fix', exact: true }).first();
+ await expect(fix).toBeVisible();
+ await expect.poll(async () => (await box(fix))?.[1] ?? Infinity).toBeLessThan(30);
});
diff --git a/lib/admin-roles.js b/lib/admin-roles.js
index ae47312..3dfcb3c 100644
--- a/lib/admin-roles.js
+++ b/lib/admin-roles.js
@@ -6,6 +6,8 @@ export const R = {
CHECKIN: ['super_admin', 'event_manager', 'support'],
BOOKINGS: ['super_admin', 'event_manager', 'finance', 'support'],
REFUND: ['super_admin', 'finance'],
+ ORDERS: ['super_admin', 'finance', 'support'],
+ ORDERS_LINK: ['super_admin', 'finance'],
MEMBERSHIPS: ['super_admin', 'finance', 'support', 'moderator'],
REVOKE: ['super_admin', 'moderator'],
LEADS: ['super_admin', 'event_manager', 'support'],
@@ -14,7 +16,8 @@ export const R = {
INSIGHTS: ['super_admin', 'finance', 'event_manager'],
DISCOVERY: ['super_admin', 'event_manager', 'moderator'],
DISCOVERY_WRITE: ['super_admin', 'event_manager', 'moderator'],
- FINANCE_VIEW: ['super_admin', 'finance']
+ FINANCE_VIEW: ['super_admin', 'finance'],
+ NOTIFICATIONS: ['super_admin', 'support', 'event_manager']
};
// [tab, label, roles allowed to load it]
@@ -24,6 +27,7 @@ export const ADMIN_TABS = [
['discovery', 'Discovery', R.DISCOVERY],
['events', 'Events', R.ANY],
['bookings', 'Bookings & payments', R.BOOKINGS],
+ ['orders', 'Orders (SuperProfile)', R.ORDERS],
['memberships', 'Memberships', R.MEMBERSHIPS],
['leads', 'Leads & reports', R.LEADS],
['media', 'Media', R.MEDIA],
diff --git a/lib/after.js b/lib/after.js
index 7bb6996..8e3553d 100644
--- a/lib/after.js
+++ b/lib/after.js
@@ -1,5 +1,5 @@
// lib/after.js - Run side effects after the HTTP response on Vercel (waitUntil keeps the function
-// alive), so providers that require a fast 2xx (Razorpay: 5s) are acknowledged first.
+// alive), so webhook senders (Zapier/Pabbly, Telegram) that expect a fast 2xx are acknowledged first.
// Locally and in tests the work is awaited before responding, which keeps behaviour deterministic.
import { logger } from './logger.js';
diff --git a/lib/config.js b/lib/config.js
index ecb3bf8..0e0411e 100644
--- a/lib/config.js
+++ b/lib/config.js
@@ -28,6 +28,17 @@ const BOT_TOKEN_RE = /^\d{5,}:[A-Za-z0-9_-]{30,}$/;
* `Telegram_HTTP_API`; it is accepted only if it has the exact shape of a bot token.
*/
export function botToken() {
+ if (process.env.VERCEL_ENV === 'preview') {
+ // Preview must use a dedicated test Telegram bot token.
+ // If unavailable or unverified, Telegram sending is disabled in Preview.
+ const previewToken = env('PREVIEW_TELEGRAM_BOT_TOKEN') || env('TELEGRAM_TEST_BOT_TOKEN');
+ if (BOT_TOKEN_RE.test(previewToken)) return previewToken;
+ if (env('ALLOW_PREVIEW_TELEGRAM') === 'true') {
+ const primary = env('TELEGRAM_BOT_TOKEN');
+ if (BOT_TOKEN_RE.test(primary)) return primary;
+ }
+ return ''; // Disabled by default in Preview to protect real users
+ }
const primary = env('TELEGRAM_BOT_TOKEN');
if (BOT_TOKEN_RE.test(primary)) return primary;
const legacy = env('Telegram_HTTP_API');
@@ -40,16 +51,27 @@ export function botUsername() {
}
export function siteUrl() {
+ if (process.env.VERCEL_ENV === 'preview') {
+ const previewExplicit = env('PREVIEW_PUBLIC_SITE_URL');
+ if (previewExplicit) return previewExplicit.replace(/\/$/, '');
+ if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;
+ }
const explicit = env('PUBLIC_SITE_URL');
if (explicit) return explicit.replace(/\/$/, '');
if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`;
return `http://localhost:${env('PORT', '3000')}`;
}
+/** Gates only the SuperProfile hosted link-out. UPI/PhonePe has its own flag below. */
export function livePayments() {
return env('ENABLE_LIVE_PAYMENTS', 'false') === 'true';
}
+/** Gates every UPI/PhonePe route, page, intent, claim and webhook. Off unless explicitly 'true'. */
+export function upiCheckoutEnabled() {
+ return env('UPI_CHECKOUT_ENABLED', 'false') === 'true';
+}
+
export function socialProofMin() {
const n = parseInt(env('SOCIAL_PROOF_MIN', '5'), 10);
return Number.isFinite(n) && n >= 5 ? n : 5;
@@ -59,6 +81,42 @@ export function isProductionRuntime() {
return process.env.VERCEL_ENV === 'production';
}
+/**
+ * Suspected or known production endpoints.
+ * ep-dawn-glitter-b4mkwxkl is the historical/unconfirmed Neon compute endpoint from earlier docs.
+ * Until the owner provides the confirmed Production endpoint ID from Vercel -> Storage,
+ * this endpoint remains blocked from non-production use (e.g. preview reviewers, seed/reset).
+ */
+export const DEFAULT_BLOCKED_PRODUCTION_ENDPOINTS = [
+ 'ep-dawn-glitter-b4mkwxkl'
+];
+
+/**
+ * Returns the full list of blocked production endpoints.
+ * Combines DEFAULT_BLOCKED_PRODUCTION_ENDPOINTS with any IDs listed in the
+ * BLOCKED_PRODUCTION_ENDPOINTS env var (comma-separated or whitespace-separated).
+ */
+export function getBlockedProductionEndpoints(e = process.env) {
+ const set = new Set(DEFAULT_BLOCKED_PRODUCTION_ENDPOINTS);
+ const extra = e?.BLOCKED_PRODUCTION_ENDPOINTS;
+ if (typeof extra === 'string') {
+ for (const part of extra.split(/[,\s]+/)) {
+ const trimmed = part.trim();
+ if (trimmed) set.add(trimmed);
+ }
+ }
+ return Array.from(set);
+}
+
+/**
+ * Checks if a connection string / URL points at any blocked production database endpoint.
+ */
+export function isBlockedProductionDatabaseUrl(url, e = process.env) {
+ if (!url || typeof url !== 'string') return false;
+ const blocked = getBlockedProductionEndpoints(e);
+ return blocked.some((endpoint) => url.includes(endpoint));
+}
+
/** Chat id env vars per tier code; a DB value on the tier row takes precedence. */
export const TIER_CHAT_ENV = { tier_1: 'TG_CHAT_ID_TIER_1', tier_2: 'TG_CHAT_ID_TIER_2', tier_3: 'TG_CHAT_ID_TIER_3' };
@@ -69,7 +127,6 @@ export function chatIdFromEnv(name) {
/** Configuration status for /api/health and admin. Names only — never values. */
export function configStatus() {
- const provider = env('PAYMENT_PROVIDER', 'razorpay');
const has = (n) => Boolean(env(n));
const ok = (cond) => (cond ? 'configured' : 'NOT CONFIGURED');
return {
@@ -79,11 +136,9 @@ export function configStatus() {
telegramBot: ok(Boolean(botToken()) && Boolean(botUsername())),
telegramWebhookSecret: ok(/^[A-Za-z0-9_-]{16,256}$/.test(env('TELEGRAM_WEBHOOK_SECRET'))),
telegramEventsChat: ok(chatIdFromEnv('TG_CHAT_ID_EVENTS') !== null),
- paymentProvider: provider,
- paymentKeys: ok(provider === 'cashfree'
- ? has('CASHFREE_APP_ID') && has('CASHFREE_SECRET_KEY')
- : has('RAZORPAY_KEY_ID') && has('RAZORPAY_KEY_SECRET') && has('RAZORPAY_WEBHOOK_SECRET')),
+ ticketCheckout: 'superprofile_link',
livePayments: livePayments(),
+ upiCheckout: upiCheckoutEnabled(),
adminBootstrap: ok(/^\d+$/.test(env('ADMIN_BOOTSTRAP_TELEGRAM_ID'))),
telegramLogin: ok(has('TELEGRAM_LOGIN_CLIENT_ID') && has('TELEGRAM_LOGIN_CLIENT_SECRET')),
superprofileWebhook: ok(env('SUPERPROFILE_WEBHOOK_SECRET').length >= 24)
diff --git a/lib/db.js b/lib/db.js
index 09a2e81..dc9874e 100644
--- a/lib/db.js
+++ b/lib/db.js
@@ -4,6 +4,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { logger } from './logger.js';
+import { isBlockedProductionDatabaseUrl } from './config.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const MIGRATIONS_DIR = path.resolve(__dirname, '../migrations');
@@ -26,8 +27,41 @@ export class DbNotConfiguredError extends Error {
}
}
+export class PreviewWriteBlockedError extends Error {
+ constructor(message = 'Database write blocked in Preview: isolated preview database is not verified (set ISOLATED_PREVIEW_DB=true)') {
+ super(message);
+ this.code = 'PREVIEW_DB_WRITE_BLOCKED';
+ this.status = 503;
+ }
+}
+
export function isDbConfigured() {
- return Boolean(process.env.DATABASE_URL);
+ const url = (process.env.VERCEL_ENV === 'preview' && process.env.PREVIEW_DATABASE_URL)
+ ? process.env.PREVIEW_DATABASE_URL
+ : process.env.DATABASE_URL;
+ return Boolean(url);
+}
+
+export function isPreviewWriteAllowed(e = process.env) {
+ if (!e.VERCEL) return true; // Local dev & tests
+ if (e.VERCEL_ENV === 'production') return true; // Production
+ if (e.VERCEL_ENV === 'preview') {
+ const url = e.PREVIEW_DATABASE_URL || e.DATABASE_URL;
+ if (isBlockedProductionDatabaseUrl(url, e)) return false;
+ return e.ISOLATED_PREVIEW_DB === 'true' || Boolean(e.PREVIEW_DATABASE_URL);
+ }
+ return false;
+}
+
+const WRITE_QUERY_RE = /\b(INSERT|UPDATE|DELETE|TRUNCATE|ALTER|DROP|CREATE|GRANT|REVOKE)\b/i;
+export function isWriteQuery(text) {
+ return typeof text === 'string' && WRITE_QUERY_RE.test(text);
+}
+
+export function assertPreviewWriteAllowed(e = process.env) {
+ if (!isPreviewWriteAllowed(e)) {
+ throw new PreviewWriteBlockedError();
+ }
}
const LOCAL_HOSTS = new Set(['', 'localhost', '127.0.0.1', '[::1]', '::1']);
@@ -50,20 +84,31 @@ export function databaseName(connectionString) {
/**
* Whether this process may apply migrations. On Vercel only production builds migrate, unless a
- * preview has been explicitly given its own database (MIGRATE_ON_PREVIEW=true). This stops an
- * unmerged branch's preview build from migrating a shared production database.
+ * preview has been explicitly given its own database (MIGRATE_ON_PREVIEW=true and confirmed ISOLATED_PREVIEW_DB=true).
+ * This stops an unmerged branch's preview build from migrating a shared production database.
*/
export function migrationPolicy(e = process.env) {
if (!e.DATABASE_URL) return { run: false, reason: 'DATABASE_URL not set' };
if (!e.VERCEL) return { run: true, reason: 'local' };
if (e.VERCEL_ENV === 'production') return { run: true, reason: 'vercel production' };
- if (e.MIGRATE_ON_PREVIEW === 'true') return { run: true, reason: `vercel ${e.VERCEL_ENV || 'unknown'} with MIGRATE_ON_PREVIEW=true` };
+ if (e.MIGRATE_ON_PREVIEW === 'true') {
+ const url = e.PREVIEW_DATABASE_URL || e.DATABASE_URL;
+ if (isBlockedProductionDatabaseUrl(url, e)) {
+ return { run: false, reason: 'refusing preview migrations: database URL matches a blocked production endpoint' };
+ }
+ if (e.ISOLATED_PREVIEW_DB !== 'true' && !e.PREVIEW_DATABASE_URL) {
+ return { run: false, reason: 'refusing preview migrations: ISOLATED_PREVIEW_DB=true is required to prove database isolation' };
+ }
+ return { run: true, reason: `vercel ${e.VERCEL_ENV || 'unknown'} with MIGRATE_ON_PREVIEW=true and confirmed isolated database` };
+ }
return { run: false, reason: `vercel ${e.VERCEL_ENV || 'unknown'} build: set MIGRATE_ON_PREVIEW=true only if this environment has its own database` };
}
function getPool() {
if (pool) return pool;
- const connectionString = process.env.DATABASE_URL;
+ const connectionString = (process.env.VERCEL_ENV === 'preview' && process.env.PREVIEW_DATABASE_URL)
+ ? process.env.PREVIEW_DATABASE_URL
+ : process.env.DATABASE_URL;
if (!connectionString) throw new DbNotConfiguredError();
const local = isLocalDatabaseUrl(connectionString);
pool = new pg.Pool({
@@ -80,10 +125,12 @@ function getPool() {
export const db = {
/** Parameterized query. Always use $1..$n placeholders. */
async query(text, params = []) {
+ if (isWriteQuery(text)) assertPreviewWriteAllowed();
return getPool().query(text, params);
},
async one(text, params = []) {
+ if (isWriteQuery(text)) assertPreviewWriteAllowed();
const { rows } = await getPool().query(text, params);
return rows[0] || null;
},
@@ -93,6 +140,7 @@ export const db = {
* Rolls back on any throw.
*/
async tx(fn) {
+ assertPreviewWriteAllowed();
const client = await getPool().connect();
try {
await client.query('BEGIN');
diff --git a/lib/dev-personas.js b/lib/dev-personas.js
index 508610c..11dc81b 100644
--- a/lib/dev-personas.js
+++ b/lib/dev-personas.js
@@ -1,7 +1,7 @@
-// lib/dev-personas.js - Local test personas (seeded by `npm run seed:local`) and the one gate that
-// decides whether persona sign-in exists at all. Never available on Vercel, in production, or
-// against a database that is not on this machine.
+// lib/dev-personas.js - Local test personas (seeded by `npm run seed:local`) and the gates that
+// decide whether persona sign-in or preview reviewer testing exist.
import { isLocalDatabaseUrl } from './db.js';
+import { isBlockedProductionDatabaseUrl } from './config.js';
/** Synthetic Telegram ids live in a reserved range no real Telegram account uses in practice. */
export const PERSONA_TG_MIN = 9_100_000_000;
@@ -14,14 +14,82 @@ export const PERSONAS = {
organiser: { tg: 9_100_000_011, alias: 'Test Organiser Chitra', role: 'organiser', organiser: true, landing: '/organiser' },
organiser2: { tg: 9_100_000_012, alias: 'Test Organiser Dev', role: 'organiser', organiser: true, landing: '/organiser' },
staff: { tg: 9_100_000_021, alias: 'Test Staff Esha', role: 'event staff (support)', adminRole: 'support', landing: '/admin' },
- admin: { tg: 9_100_000_031, alias: 'Test Admin Farah', role: 'super admin', adminRole: 'super_admin', landing: '/admin' }
+ admin: { tg: 9_100_000_031, alias: 'Test Admin Farah', role: 'super admin', adminRole: 'super_admin', landing: '/admin' },
+ finance: { tg: 9_100_000_032, alias: 'Test Finance Gita', role: 'finance admin', adminRole: 'finance', landing: '/admin' },
+ manager: { tg: 9_100_000_013, alias: 'Test Manager Hari', role: 'manager in Chitra’s team org', orgRole: 'manager', landing: '/me' },
+ teamstaff: { tg: 9_100_000_014, alias: 'Test Team Staff Indu', role: 'staff in Chitra’s team org', orgRole: 'staff', landing: '/me' },
+ venue: { tg: 9_100_000_041, alias: 'Test Venue Owner Jai', role: 'venue org owner', landing: '/me' },
+ dj: { tg: 9_100_000_051, alias: 'Test DJ Kavya', role: 'DJ (dj capability)', capabilities: ['dj'], landing: '/me' }
};
+/** Synthetic orgs seeded with the personas. members: [persona key, org role]. */
+export const PERSONA_ORGS = [
+ { name: 'Test Org: Chitra Events', kind: 'organiser_team', members: [['organiser', 'owner'], ['manager', 'manager'], ['teamstaff', 'staff']] },
+ { name: 'Test Org: Jai Venues', kind: 'venue_operator', members: [['venue', 'owner']],
+ venues: [{ name: 'Test venue: Rooftop 9', capacity: 80, address: 'Test address — 9 Private Lane (members only)', lat: 13.0, lng: 80.2 }] }
+];
+
export const PERSONA_KEYS = Object.keys(PERSONAS);
export const PERSONA_TG_IDS = PERSONA_KEYS.map((k) => PERSONAS[k].tg);
+/** Restricted synthetic reviewer persona for Preview environments only. */
+export const REVIEWER_TG_ID = 9_100_000_100;
+export const REVIEWER_ALIAS = 'Preview Reviewer (Synthetic)';
+
/** Persona sign-in: local machine only, explicitly switched on, never production, local database only. */
export function devLoginEnabled(e = process.env) {
return !e.VERCEL && e.DEV_LOGIN === 'true' && e.NODE_ENV !== 'production' && e.VERCEL_ENV !== 'production' &&
isLocalDatabaseUrl(e.DATABASE_URL);
}
+
+/**
+ * Preview reviewer sign-in: strictly restricted to verified Preview environments.
+ * - Allows the reviewer mechanism ONLY when VERCEL_ENV === 'preview' (or strict preview test harness flag IS_PREVIEW === 'true').
+ * - Explicitly rejects VERCEL_ENV === 'production' (fail-closed against Production deployments).
+ * - Explicitly rejects unconfigured, missing, or local environments (VERCEL_ENV not set and IS_PREVIEW not 'true').
+ * - In Vercel Serverless Functions, VERCEL_ENV='preview' runs under NODE_ENV='production'.
+ * This policy safely allows VERCEL_ENV='preview' while maintaining strict production endpoint guards.
+ * - Rejects any blocked production database endpoint (ep-dawn-glitter-b4mkwxkl, etc.) on DATABASE_URL or PREVIEW_DATABASE_URL.
+ * - Regular guest attendee privileges only (REVIEWER_TG_ID) — zero admin, organiser, finance, or staff escalation.
+ */
+export function previewReviewerEnabled(e = process.env) {
+ if (!e || typeof e !== 'object') return false;
+
+ // 1. Explicitly reject Production environments
+ if (e.VERCEL_ENV === 'production') return false;
+
+ // 2. Reject blocked production database endpoints across both connection strings
+ if (isBlockedProductionDatabaseUrl(e.DATABASE_URL, e)) return false;
+ if (isBlockedProductionDatabaseUrl(e.PREVIEW_DATABASE_URL, e)) return false;
+
+ // 3. Strict Preview authorization: MUST be Vercel Preview (VERCEL_ENV === 'preview')
+ // or explicitly authorized isolated preview test runner (IS_PREVIEW === 'true').
+ // Missing VERCEL_ENV, ambiguous values, or local development without IS_PREVIEW fail closed.
+ const isVercelPreview = e.VERCEL_ENV === 'preview';
+ const isPreviewTest = e.IS_PREVIEW === 'true';
+
+ if (!isVercelPreview && !isPreviewTest) {
+ return false;
+ }
+
+ // 4. When not running in a verified Vercel Preview (VERCEL_ENV === 'preview'),
+ // IS_PREVIEW='true' is only accepted in an authorized isolated test runner.
+ // Ambiguous deployed environments (e.g. VERCEL, VERCEL_URL, or serverless/cloud runtime indicators)
+ // or production runtime (NODE_ENV === 'production') are strictly rejected.
+ if (!isVercelPreview) {
+ const isDeployed = Boolean(
+ e.VERCEL ||
+ e.VERCEL_URL ||
+ e.AWS_LAMBDA_FUNCTION_NAME ||
+ e.FLY_APP_NAME ||
+ e.RENDER ||
+ e.K_SERVICE ||
+ e.HEROKU_APP_NAME
+ );
+ if (isDeployed || e.NODE_ENV === 'production') {
+ return false;
+ }
+ }
+
+ return true;
+}
diff --git a/lib/handlers/admin.js b/lib/handlers/admin.js
index 0b84026..a9839b4 100644
--- a/lib/handlers/admin.js
+++ b/lib/handlers/admin.js
@@ -7,8 +7,10 @@ import { rateLimit } from '../ratelimit.js';
import { parse, z } from '../validate.js';
import { audit } from '../audit.js';
import { chatIdFromEnv, configStatus, botToken, botUsername, siteUrl, env } from '../config.js';
-import { enqueue } from '../services/notifications.js';
+import { enqueue, deliverMany, deliver } from '../services/notifications.js';
import { refundPayment as refundSvc } from '../services/refunds.js';
+import { listOrders as listOrdersSvc, linkOrderToUser } from '../services/orders.js';
+import { isSuperprofileUrl } from '../payments/index.js';
import { removeFromChat, tierChatId } from '../services/invites.js';
import { CATEGORY_LABELS, CITIES, toPublicEvent } from '../services/events.js';
import { getInsights } from '../services/insights.js';
@@ -19,6 +21,9 @@ import { superprofileConfigured } from '../services/superprofile.js';
import { renderAdminShell } from '../views/admin.js';
import { renderEvent } from '../views/event.js';
import { R } from '../admin-roles.js';
+import { ensurePersonalOrg, setOrganiseCapability } from '../services/permissions.js';
+import { page, pageInfo } from '../pagination.js';
+import { resolveCity } from '../services/locations.js';
/** Resolve the admin for this request (bootstrapping the owner once), or throw 401/403. */
@@ -108,7 +113,8 @@ export async function overview(ctx) {
(SELECT count(*)::int FROM payments WHERE status = 'failed') AS failed_payments,
(SELECT count(*)::int FROM notifications WHERE status = 'failed' AND kind IN ('booking_confirmed','membership_activated')) AS invite_failures,
(SELECT count(*)::int FROM entitlements WHERE status IN ('active','cancelled') AND expires_at BETWEEN now() AND now() + interval '7 days') AS expiring_memberships,
- (SELECT count(*)::int FROM bookings WHERE cancel_reason = 'paid_but_unavailable_refund_due' AND status <> 'refunded') AS refunds_due,
+ (SELECT count(*)::int FROM external_orders WHERE match_state = 'unmatched' AND status = 'paid') AS unmatched_orders,
+ (SELECT count(*)::int FROM external_orders WHERE match_state = 'flagged') AS flagged_orders,
(SELECT count(*)::int FROM leads WHERE status = 'new') AS new_leads,
(SELECT count(*)::int FROM reports WHERE status = 'new') AS new_reports,
(SELECT count(*)::int FROM users WHERE alerts_opt_in) AS alert_subscribers`);
@@ -119,6 +125,8 @@ export async function overview(ctx) {
const nullableStr = (max) => z.union([z.string().trim().max(max), z.null()]).optional().transform((v) => (v === '' ? null : v));
const httpsUrl = z.union([z.string().trim().url().regex(/^https:\/\//, 'Must be https'), z.literal(''), z.null()]).optional().transform((v) => v || null);
+const spUrl = z.union([z.string().trim().max(500).refine(isSuperprofileUrl, 'Must be an https superprofile.bio link'), z.literal(''), z.null()]).optional().transform((v) => v || null);
+
const EventBody = z.object({
slug: z.string().trim().toLowerCase().regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'lowercase-words-with-dashes').max(120),
category: z.enum(Object.keys(CATEGORY_LABELS)),
@@ -144,17 +152,28 @@ const EventBody = z.object({
external_payment_url: httpsUrl,
telegram_chat_id: z.union([z.coerce.number().int(), z.literal(''), z.null()]).optional().transform((v) => (v === '' || v === undefined ? null : v)),
cover_media_id: z.union([z.string().uuid(), z.literal(''), z.null()]).optional().transform((v) => v || null),
- is_demo: z.boolean().default(false)
-}).strict().refine((e) => !e.end_at || new Date(e.end_at) > new Date(e.start_at), { message: 'End must be after start', path: ['end_at'] });
+ is_demo: z.boolean().default(false),
+ superprofile_url: spUrl,
+ superprofile_product_id: nullableStr(200),
+ checkout_mode: z.enum(['none', 'superprofile', 'free']).default('none')
+}).strict()
+ .refine((e) => !e.end_at || new Date(e.end_at) > new Date(e.start_at), { message: 'End must be after start', path: ['end_at'] })
+ .refine((e) => e.checkout_mode !== 'superprofile' || Boolean(e.superprofile_url), { message: 'Add the SuperProfile link to use SuperProfile checkout', path: ['superprofile_url'] });
const EVENT_COLS = ['slug', 'category', 'title', 'summary', 'description', 'city', 'area_public', 'venue_private', 'venue_privacy', 'start_at', 'end_at',
'capacity', 'ticket_price_paise', 'inclusions', 'exclusions', 'refund_policy', 'gender_policy', 'food_available', 'stay_available', 'organizer',
- 'bookmyshow_url', 'external_payment_url', 'telegram_chat_id', 'cover_media_id', 'is_demo'];
+ 'bookmyshow_url', 'external_payment_url', 'telegram_chat_id', 'cover_media_id', 'is_demo', 'superprofile_url', 'superprofile_product_id', 'checkout_mode'];
function eventValues(e) {
return EVENT_COLS.map((c) => (c === 'inclusions' || c === 'exclusions' ? JSON.stringify(e[c]) : e[c] ?? null));
}
+async function assertProductFree(c, productId, exceptEventId = null) {
+ if (!productId) return;
+ const used = (await c.query('SELECT 1 FROM events WHERE lower(superprofile_product_id) = lower($1) AND ($2::uuid IS NULL OR id <> $2)', [productId, exceptEventId])).rows[0];
+ if (used) throw new HttpError(409, 'product_taken', 'That SuperProfile product is already linked to another event', { fields: [{ field: 'superprofile_product_id', message: 'Already linked' }] });
+}
+
async function assertCoverAuthorized(c, mediaId) {
if (!mediaId) return;
const m = (await c.query('SELECT authorized_by_owner FROM media WHERE id = $1', [mediaId])).rows[0];
@@ -182,13 +201,23 @@ export async function createEvent(ctx) {
const e = parse(EventBody, await readJson(ctx.req));
const row = await db.tx(async (c) => {
await assertCoverAuthorized(c, e.cover_media_id);
+ await assertProductFree(c, e.superprofile_product_id);
const dupe = (await c.query('SELECT 1 FROM events WHERE slug = $1', [e.slug])).rows[0];
if (dupe) throw new HttpError(409, 'slug_taken', 'That slug is already used');
- const placeholders = EVENT_COLS.map((_, i) => `$${i + 1}`).join(', ');
+
+ const resolvedCity = await resolveCity(e.city, c);
+ const cityId = resolvedCity ? resolvedCity.id : null;
+ const lat = resolvedCity ? resolvedCity.lat : null;
+ const lng = resolvedCity ? resolvedCity.lng : null;
+ const coordsProvenance = resolvedCity ? 'city' : 'none';
+
+ const cols = [...EVENT_COLS, 'price_status', 'status', 'city_id', 'lat', 'lng', 'coords_provenance'];
+ const placeholders = cols.map((_, i) => `$${i + 1}`).join(', ');
+ const values = [...eventValues(e), e.ticket_price_paise ? 'set' : 'tbd', 'draft', cityId, lat, lng, coordsProvenance];
const r = (await c.query(
- `INSERT INTO events (${EVENT_COLS.join(', ')}, price_status, status) VALUES (${placeholders}, $${EVENT_COLS.length + 1}, 'draft') RETURNING id, slug`,
- [...eventValues(e), e.ticket_price_paise ? 'set' : 'tbd'])).rows[0];
- await audit(a.actor, 'event.create', r.id, { slug: e.slug, priceSet: Boolean(e.ticket_price_paise) }, c);
+ `INSERT INTO events (${cols.join(', ')}) VALUES (${placeholders}) RETURNING id, slug`,
+ values)).rows[0];
+ await audit(a.actor, 'event.create', r.id, { slug: e.slug, priceSet: Boolean(e.ticket_price_paise), checkoutMode: e.checkout_mode }, c);
return r;
});
sendJson(ctx.res, 201, { ok: true, event: row });
@@ -200,14 +229,33 @@ export async function updateEvent(ctx) {
const e = parse(EventBody, await readJson(ctx.req));
await db.tx(async (c) => {
await assertCoverAuthorized(c, e.cover_media_id);
- const cur = (await c.query('SELECT id, slug, capacity FROM events WHERE id = $1 FOR UPDATE', [id])).rows[0];
+ const cur = (await c.query('SELECT id, slug, capacity, superprofile_product_id, checkout_mode FROM events WHERE id = $1 FOR UPDATE', [id])).rows[0];
if (!cur) throw new HttpError(404, 'not_found', 'Not found');
+ await assertProductFree(c, e.superprofile_product_id, id);
const taken = (await c.query(`SELECT count(*)::int n FROM bookings WHERE event_id = $1 AND status IN ('confirmed','checked_in')`, [id])).rows[0].n;
if (e.capacity < taken) throw new HttpError(409, 'capacity_below_bookings', `Capacity cannot be below ${taken} confirmed bookings`);
- const sets = EVENT_COLS.map((col, i) => `${col} = $${i + 2}`).join(', ');
- await c.query(`UPDATE events SET ${sets}, price_status = $${EVENT_COLS.length + 2} WHERE id = $1`,
- [id, ...eventValues(e), e.ticket_price_paise ? 'set' : 'tbd']);
- await audit(a.actor, 'event.update', id, { slug: e.slug }, c);
+
+ const resolvedCity = await resolveCity(e.city, c);
+ const cityId = resolvedCity ? resolvedCity.id : null;
+ const lat = resolvedCity ? resolvedCity.lat : null;
+ const lng = resolvedCity ? resolvedCity.lng : null;
+ const coordsProvenance = resolvedCity ? 'city' : 'none';
+
+ const sets = [
+ ...EVENT_COLS.map((col, i) => `${col} = $${i + 2}`),
+ `price_status = $${EVENT_COLS.length + 2}`,
+ `city_id = $${EVENT_COLS.length + 3}`,
+ `lat = $${EVENT_COLS.length + 4}`,
+ `lng = $${EVENT_COLS.length + 5}`,
+ `coords_provenance = $${EVENT_COLS.length + 6}`
+ ].join(', ');
+ await c.query(`UPDATE events SET ${sets} WHERE id = $1`,
+ [id, ...eventValues(e), e.ticket_price_paise ? 'set' : 'tbd', cityId, lat, lng, coordsProvenance]);
+ await audit(a.actor, 'event.update', id, {
+ slug: e.slug, checkoutMode: e.checkout_mode,
+ ...(cur.checkout_mode !== e.checkout_mode ? { checkoutModeFrom: cur.checkout_mode } : {}),
+ ...(cur.superprofile_product_id !== e.superprofile_product_id ? { superprofileProductChanged: true } : {})
+ }, c);
});
sendJson(ctx.res, 200, { ok: true });
}
@@ -272,8 +320,10 @@ export async function listBookings(ctx) {
}
const { rows } = await db.query(
`SELECT b.id, b.status, b.cancel_reason, b.created_at, b.confirmed_at, e.title, e.start_at, u.alias,
- p.id AS payment_id, p.provider, p.provider_txn_id, p.provider_payment_id, p.status AS payment_status, p.amount, p.is_test, p.failure_reason
+ p.id AS payment_id, p.provider, p.provider_txn_id, p.provider_payment_id, p.status AS payment_status, p.amount, p.is_test, p.failure_reason,
+ eo.order_id, eo.status AS order_status, eo.amount_paise AS order_amount, b.source
FROM bookings b JOIN events e ON e.id = b.event_id JOIN users u ON u.id = b.user_id LEFT JOIN payments p ON p.id = b.payment_id
+ LEFT JOIN external_orders eo ON eo.matched_booking_id = b.id
WHERE ${where} ORDER BY b.created_at DESC LIMIT 200`, params);
const { rows: stars } = await db.query(
`SELECT p.id AS payment_id, p.provider, p.provider_txn_id, p.status AS payment_status, p.amount, p.is_test, p.created_at, u.alias
@@ -281,10 +331,48 @@ export async function listBookings(ctx) {
sendJson(ctx.res, 200, { ok: true, bookings: rows, membershipPayments: stars });
}
+// ---------- SuperProfile orders ----------
+
+export async function listOrders(ctx) {
+ await guard(ctx, R.ORDERS);
+ const r = await listOrdersSvc({ state: ctx.query.get('state') || 'unmatched', cursor: ctx.query.get('cursor'), limit: ctx.query.get('limit') || 25 });
+ sendJson(ctx.res, 200, { ok: true, ...r });
+}
+
+const LinkBody = z.object({ telegramUserId: z.coerce.number().int().positive() }).strict();
+
+export async function linkOrder(ctx) {
+ const a = await guard(ctx, R.ORDERS_LINK, { write: true });
+ const { telegramUserId } = parse(LinkBody, await readJson(ctx.req));
+ const r = await linkOrderToUser(a.actor, uuidParam(ctx.params.id), telegramUserId);
+ await deliverMany(r.notificationIds);
+ sendJson(ctx.res, 200, { ok: true, bookingId: r.bookingId });
+}
+
+const RefundBody = z.object({
+ reason: z.string().max(500).optional(),
+ manualReconciliation: z.boolean().optional(),
+ externalRefundRef: z.string().max(120).optional(),
+ evidenceRef: z.string().max(255).optional()
+}).strict().optional();
+
export async function refundPayment(ctx) {
const a = await guard(ctx, R.REFUND, { write: true });
- await refundSvc(uuidParam(ctx.params.id), a.actor);
- sendJson(ctx.res, 200, { ok: true });
+ let body = {};
+ try {
+ body = await readJson(ctx.req);
+ } catch {
+ body = {};
+ }
+ const parsed = parse(RefundBody, body || {}) || {};
+ const res = await refundSvc(uuidParam(ctx.params.id), a.actor, {
+ reason: parsed.reason,
+ manualReconciliation: parsed.manualReconciliation,
+ externalRefundRef: parsed.externalRefundRef,
+ evidenceRef: parsed.evidenceRef,
+ sessionAdmin: a.admin
+ });
+ sendJson(ctx.res, 200, { ok: true, ...res });
}
// ---------- memberships ----------
@@ -330,7 +418,14 @@ export async function listLeads(ctx) {
const a = await getAdmin(ctx.req);
if (['super_admin', 'moderator'].includes(a.admin.role)) {
reports = (await db.query(
- `SELECT r.id, r.body, r.status, r.created_at, u.alias, u.telegram_user_id FROM reports r LEFT JOIN users u ON u.id = r.user_id
+ `SELECT r.id, r.body, r.category, r.status, r.created_at,
+ u.alias, u.telegram_user_id,
+ e.title AS event_title, e.slug AS event_slug,
+ ru.alias AS reported_user_alias
+ FROM reports r
+ LEFT JOIN users u ON u.id = r.user_id
+ LEFT JOIN events e ON e.id = r.event_id
+ LEFT JOIN users ru ON ru.id = r.reported_user_id
ORDER BY r.created_at DESC LIMIT 200`)).rows;
}
sendJson(ctx.res, 200, { ok: true, leads: rows, reports });
@@ -364,6 +459,83 @@ export async function updateReport(ctx) {
sendJson(ctx.res, 200, { ok: true });
}
+// ---------- notifications outbox & alerts ----------
+
+export async function listNotifications(ctx) {
+ await guard(ctx, R.NOTIFICATIONS);
+ const status = ctx.query.get('status');
+ const kind = ctx.query.get('kind');
+ const p = page(ctx.query);
+
+ const params = [];
+ const conds = [];
+
+ if (status && ['pending', 'sent', 'failed'].includes(status)) {
+ params.push(status);
+ conds.push(`n.status = $${params.length}`);
+ }
+ if (kind && typeof kind === 'string' && kind.trim()) {
+ params.push(kind.trim());
+ conds.push(`n.kind = $${params.length}`);
+ }
+
+ const where = conds.length ? `WHERE ${conds.join(' AND ')}` : '';
+
+ params.push(p.limit + 1);
+ params.push(p.offset);
+
+ const [items, stats] = await Promise.all([
+ db.query(
+ `SELECT n.id, n.kind, n.status, n.attempts, n.last_error, n.next_attempt_at, n.sent_at, n.created_at,
+ n.user_id, n.booking_id, n.event_id, n.dedupe_key,
+ u.alias AS user_alias, u.telegram_user_id,
+ e.title AS event_title
+ FROM notifications n
+ LEFT JOIN users u ON u.id = n.user_id
+ LEFT JOIN events e ON e.id = n.event_id
+ ${where}
+ ORDER BY n.created_at DESC
+ LIMIT $${params.length - 1} OFFSET $${params.length}`,
+ params
+ ),
+ db.query(`SELECT
+ COUNT(*) FILTER (WHERE status = 'pending')::int AS pending_count,
+ COUNT(*) FILTER (WHERE status = 'failed')::int AS failed_count,
+ COUNT(*) FILTER (WHERE status = 'sent' AND sent_at > now() - interval '24 hours')::int AS sent_last_24h,
+ COUNT(*)::int AS total_count
+ FROM notifications`)
+ ]);
+
+ sendJson(ctx.res, 200, {
+ ok: true,
+ stats: stats.rows[0] || { pending_count: 0, failed_count: 0, sent_last_24h: 0, total_count: 0 },
+ ...pageInfo(items.rows, p, 'notifications')
+ });
+}
+
+export async function retryNotification(ctx) {
+ const a = await guard(ctx, R.NOTIFICATIONS, { write: true });
+ const id = uuidParam(ctx.params.id);
+
+ const exists = await db.one(`SELECT id, status, attempts FROM notifications WHERE id = $1`, [id]);
+ if (!exists) throw new HttpError(404, 'not_found', 'Notification not found');
+
+ await db.query(
+ `UPDATE notifications
+ SET status = 'pending',
+ attempts = 0,
+ next_attempt_at = now(),
+ last_error = NULL
+ WHERE id = $1`,
+ [id]
+ );
+
+ const outcome = await deliver(id);
+ await audit(a.actor, 'notification.retry', id, { previousStatus: exists.status, outcome });
+
+ sendJson(ctx.res, 200, { ok: true, id, outcome });
+}
+
// ---------- media ----------
const MediaBody = z.object({
@@ -430,7 +602,7 @@ const TierPatch = z.object({
telegram_chat_id: z.union([z.coerce.number().int(), z.null()]).optional(),
active: z.boolean().optional(),
access_provider: z.enum(['telegram_stars', 'superprofile']).optional(),
- superprofile_url: z.union([z.string().trim().url().regex(/^https:\/\//, 'Must be https').max(500), z.null()]).optional(),
+ superprofile_url: z.union([z.string().trim().max(500).refine(isSuperprofileUrl, 'Must be an https superprofile.bio link'), z.null()]).optional(),
superprofile_product_ref: z.union([z.string().trim().min(1).max(200), z.null()]).optional()
}).strict();
@@ -506,14 +678,72 @@ export async function setOrganiser(ctx) {
const a = await guard(ctx, R.SUPER, { write: true });
const b = parse(OrganiserBody, await readJson(ctx.req));
await db.tx(async (c) => {
- const r = (await c.query('UPDATE users SET organiser_enabled = $2 WHERE telegram_user_id = $1 RETURNING id', [b.telegram_user_id, b.enabled])).rows[0];
+ const r = (await c.query('UPDATE users SET organiser_enabled = $2 WHERE telegram_user_id = $1 RETURNING id, alias', [b.telegram_user_id, b.enabled])).rows[0];
if (!r) throw new HttpError(404, 'user_not_found', 'That person needs to sign in to the site once first');
+ if (b.enabled) {
+ await ensurePersonalOrg(r, c);
+ await enqueue(c, {
+ kind: 'host_approved',
+ userId: r.id,
+ dedupeKey: `host_approved:${r.id}:${Date.now()}`
+ });
+ }
+ await setOrganiseCapability(r.id, b.enabled, c);
await audit(a.actor, 'organiser.set', r.id, { enabled: b.enabled }, c);
});
sendJson(ctx.res, 200, { ok: true });
}
+// ---------- organisations (business / venue / team orgs; personal orgs are created automatically) ----------
+
+export async function listOrgs(ctx) {
+ await guard(ctx, R.SUPER);
+ const p = page(ctx.query);
+ const { rows } = await db.query(
+ `SELECT o.id, o.kind, o.name, o.status, o.verified_at, o.created_at,
+ (SELECT count(*)::int FROM org_memberships m WHERE m.org_id = o.id AND m.status = 'active') AS members
+ FROM organisations o WHERE o.kind <> 'personal' ORDER BY o.created_at DESC, o.id LIMIT $1 OFFSET $2`, [p.limit + 1, p.offset]);
+ sendJson(ctx.res, 200, { ok: true, ...pageInfo(rows, p, 'orgs') });
+}
+
+const OrgBody = z.object({
+ kind: z.enum(['business', 'venue_operator', 'organiser_team']),
+ name: z.string().trim().min(2).max(120),
+ owner_telegram_user_id: z.coerce.number().int().positive()
+}).strict();
+
+export async function createOrg(ctx) {
+ const a = await guard(ctx, R.SUPER, { write: true });
+ const b = parse(OrgBody, await readJson(ctx.req));
+ const org = await db.tx(async (c) => {
+ const owner = (await c.query('SELECT id FROM users WHERE telegram_user_id = $1', [b.owner_telegram_user_id])).rows[0];
+ if (!owner) throw new HttpError(404, 'user_not_found', 'That person needs to sign in to the site once first');
+ const o = (await c.query(`INSERT INTO organisations (kind, name) VALUES ($1, $2) RETURNING id, kind, name, status`, [b.kind, b.name])).rows[0];
+ await c.query(`INSERT INTO org_memberships (user_id, org_id, role) VALUES ($1, $2, 'owner')`, [owner.id, o.id]);
+ await audit(a.actor, 'org.create', o.id, { kind: b.kind, ownerUserId: owner.id }, c);
+ return o;
+ });
+ sendJson(ctx.res, 201, { ok: true, org });
+}
+
+const OrgStatusBody = z.object({ status: z.enum(['active', 'suspended']), verified: z.boolean().optional() }).strict();
+
+export async function updateOrg(ctx) {
+ const a = await guard(ctx, R.SUPER, { write: true });
+ const id = uuidParam(ctx.params.id);
+ const b = parse(OrgStatusBody, await readJson(ctx.req));
+ await db.tx(async (c) => {
+ const r = (await c.query(
+ `UPDATE organisations SET status = $2,
+ verified_at = CASE WHEN $3::boolean IS NULL THEN verified_at WHEN $3 THEN COALESCE(verified_at, now()) ELSE NULL END
+ WHERE id = $1 RETURNING id`, [id, b.status, b.verified ?? null])).rows[0];
+ if (!r) throw new HttpError(404, 'not_found', 'Organisation not found');
+ await audit(a.actor, 'org.update', id, b, c);
+ });
+ sendJson(ctx.res, 200, { ok: true });
+}
+
// ---------- insights ----------
export async function insights(ctx) {
diff --git a/lib/handlers/auth.js b/lib/handlers/auth.js
index 17e57ec..e0d5060 100644
--- a/lib/handlers/auth.js
+++ b/lib/handlers/auth.js
@@ -1,18 +1,22 @@
// lib/handlers/auth.js - Telegram sign-in (Mini App initData, Telegram Login OIDC, legacy widget),
// session cookie issue/clear, current user, age confirmation.
import crypto from 'node:crypto';
-import { HttpError, readJson, sendJson, redirect, parseCookies, serializeCookie, appendHeader, hashIp, safeEqual } from '../http.js';
+import { HttpError, readJson, readForm, sendJson, redirect, parseCookies, serializeCookie, appendHeader, hashIp, safeEqual } from '../http.js';
import { rateLimit } from '../ratelimit.js';
import { parse, z } from '../validate.js';
import { botToken, siteUrl, env } from '../config.js';
import { logger } from '../logger.js';
import { db } from '../db.js';
-import { PERSONAS, PERSONA_KEYS, devLoginEnabled } from '../dev-personas.js';
+import { PERSONAS, PERSONA_KEYS, devLoginEnabled, previewReviewerEnabled, REVIEWER_TG_ID, REVIEWER_ALIAS } from '../dev-personas.js';
import {
validateInitData, validateLoginWidget, consumeNonce,
oidcConfigured, pkcePair, authorizeUrl, exchangeCode, verifyIdToken
} from '../telegram/auth.js';
-import { upsertTelegramUser, confirmAge as confirmAgeSvc } from '../services/users.js';
+import {
+ upsertTelegramUser, confirmAge as confirmAgeSvc,
+ createAccountLinkToken, getAccountLinkStatus,
+ getNotificationPreferences, updateNotificationPreferences
+} from '../services/users.js';
import {
createSession, setSessionCookie, clearSessionCookie, csrfTokenFor, getSessionUser, requireUser, requireCsrf,
revokeSession, revokeUserSessions
@@ -20,7 +24,7 @@ import {
const AuthBody = z.object({
initData: z.string().max(4096).optional(),
- widget: z.record(z.union([z.string(), z.number()])).optional(),
+ widget: z.record(z.union([z.string(), z.number(), z.boolean(), z.null()])).optional(),
ageConfirmed: z.boolean().optional()
}).strict().refine((b) => Boolean(b.initData) !== Boolean(b.widget), 'Provide initData or widget');
@@ -153,6 +157,43 @@ export async function devAuth({ req, res }) {
sendJson(res, 200, { ok: true, csrf, user: publicUser(user), persona: body.persona, landing: p.landing });
}
+/** POST /api/auth/preview-reviewer — restricted synthetic reviewer sign-in for preview only. 404 in production. */
+export async function previewReviewerAuth({ req, res, query, ip }) {
+ if (!previewReviewerEnabled()) throw new HttpError(404, 'not_found', 'Not found');
+ await rateLimit(`reviewer:${hashIp(ip)}`, 30, 600);
+ let next = '/me';
+ const ct = req.headers['content-type'] || '';
+ if (ct.includes('application/x-www-form-urlencoded')) {
+ const form = await readForm(req).catch(() => ({}));
+ if (form && form.next) next = safeNext(form.next);
+ } else if (ct.includes('application/json')) {
+ const raw = await readJson(req).catch(() => ({}));
+ if (raw && raw.next) next = safeNext(raw.next);
+ }
+ if (query && query.get('next')) next = safeNext(query.get('next'));
+
+ // Ensure or fetch the synthetic reviewer user (guaranteed guest role, no admin/organiser escalation)
+ let user = await db.one('SELECT * FROM users WHERE telegram_user_id = $1', [REVIEWER_TG_ID]);
+ if (!user) {
+ user = (await db.query(
+ `INSERT INTO users (telegram_user_id, alias, age_confirmed_21, age_confirmed_at, status, bot_started)
+ VALUES ($1, $2, true, now(), 'active', true)
+ ON CONFLICT (telegram_user_id) DO UPDATE SET age_confirmed_21 = true, status = 'active'
+ RETURNING *`,
+ [REVIEWER_TG_ID, REVIEWER_ALIAS]
+ )).rows[0];
+ }
+ if (user.status !== 'active') throw new HttpError(403, 'account_restricted', 'Reviewer account is not active');
+
+ const { csrf } = await startSession(req, res, user);
+ const accept = req.headers['accept'] || '';
+ if (accept.includes('application/json')) {
+ sendJson(res, 200, { ok: true, csrf, user: publicUser(user), redirect: next });
+ } else {
+ redirect(res, next);
+ }
+}
+
/** Sign out this browser: revoke its server-side session (CSRF-checked when signed in) and clear the cookie. */
export async function logout({ req, res }) {
let user = null;
@@ -195,3 +236,36 @@ export async function confirmAge({ req, res }) {
await confirmAgeSvc(user.id);
sendJson(res, 200, { ok: true });
}
+
+export async function createTelegramLinkToken({ req, res }) {
+ const user = await getSessionUser(req).catch(() => null);
+ const { token, linkUrl, expiresAt } = await createAccountLinkToken(user?.id || null);
+ sendJson(res, 200, { ok: true, token, linkUrl, expiresAt });
+}
+
+export async function getTelegramLinkStatus({ res, query }) {
+ const token = query?.get?.('token');
+ if (!token) throw new HttpError(400, 'validation', 'token is required');
+ const status = await getAccountLinkStatus(token);
+ if (!status) throw new HttpError(404, 'not_found', 'Token not found');
+ sendJson(res, 200, { ok: true, ...status });
+}
+
+export async function getMyNotificationPreferences({ req, res }) {
+ const user = await requireUser(req);
+ const prefs = await getNotificationPreferences(user.id);
+ sendJson(res, 200, { ok: true, preferences: prefs });
+}
+
+export async function updateMyNotificationPreferences({ req, res }) {
+ const user = await requireUser(req);
+ requireCsrf(req, user);
+ const body = await readJson(req);
+ const prefs = await updateNotificationPreferences(user.id, {
+ remindersEnabled: body.remindersEnabled,
+ quietHoursEnabled: body.quietHoursEnabled,
+ quietHoursStart: body.quietHoursStart,
+ quietHoursEnd: body.quietHoursEnd
+ });
+ sendJson(res, 200, { ok: true, preferences: prefs });
+}
diff --git a/lib/handlers/bookings.js b/lib/handlers/bookings.js
index ae9a024..fe8e41e 100644
--- a/lib/handlers/bookings.js
+++ b/lib/handlers/bookings.js
@@ -1,26 +1,16 @@
-// lib/handlers/bookings.js - Member booking endpoints (session + CSRF).
-import { readJson, sendJson, HttpError, hashIp } from '../http.js';
-import { requireUser, requireCsrf } from '../session.js';
-import { parse, z } from '../validate.js';
-import { rateLimit } from '../ratelimit.js';
-import { ticketProvider } from '../payments/index.js';
-import { createBooking as createBookingSvc, listUserBookings, getUserBooking } from '../services/bookings.js';
+// lib/handlers/bookings.js - Member booking reads (session).
+import { sendJson, HttpError, readRawBody } from '../http.js';
+import { requireUser } from '../session.js';
+import { listUserBookings, getUserBooking, listUserAnnouncements, cancelUserBooking } from '../services/bookings.js';
-const Body = z.object({ eventId: z.string().uuid() }).strict();
-
-export async function createBooking({ req, res, ip }) {
+export async function myBookings({ req, res }) {
const user = await requireUser(req);
- requireCsrf(req, user);
- await rateLimit(`book:${user.id}`, 10, 600);
- await rateLimit(`bookip:${hashIp(ip)}`, 30, 600);
- const { eventId } = parse(Body, await readJson(req));
- const r = await createBookingSvc(user, eventId, ticketProvider());
- sendJson(res, 200, { ok: true, ...r });
+ sendJson(res, 200, { ok: true, bookings: await listUserBookings(user.id) });
}
-export async function myBookings({ req, res }) {
+export async function myAnnouncements({ req, res }) {
const user = await requireUser(req);
- sendJson(res, 200, { ok: true, bookings: await listUserBookings(user.id) });
+ sendJson(res, 200, { ok: true, announcements: await listUserAnnouncements(user.id) });
}
export async function getBooking({ req, res, params }) {
@@ -30,3 +20,22 @@ export async function getBooking({ req, res, params }) {
if (!booking) throw new HttpError(404, 'not_found', 'Booking not found');
sendJson(res, 200, { ok: true, booking });
}
+
+export async function cancelMyBooking({ req, res, params }) {
+ const user = await requireUser(req);
+ if (!/^[0-9a-f-]{36}$/i.test(params.id)) throw new HttpError(404, 'not_found', 'Booking not found');
+ let reason = 'Cancelled by attendee';
+ try {
+ const raw = await readRawBody(req);
+ if (raw) {
+ const data = JSON.parse(raw);
+ if (typeof data.reason === 'string' && data.reason.trim()) {
+ reason = data.reason.trim().slice(0, 500);
+ }
+ }
+ } catch {
+ // optional body payload
+ }
+ const result = await cancelUserBooking(user.id, params.id, { reason });
+ sendJson(res, 200, result);
+}
diff --git a/lib/handlers/checkout.js b/lib/handlers/checkout.js
new file mode 100644
index 0000000..4e2defa
--- /dev/null
+++ b/lib/handlers/checkout.js
@@ -0,0 +1,31 @@
+// lib/handlers/checkout.js - GET /checkout/:slug → 302 to the event's SuperProfile page.
+// Works signed out (paying is never gated on signing in). HEAD requests (link previews, crawlers)
+// never create an intent.
+import { redirect, hashIp, HttpError } from '../http.js';
+import { getSessionUser } from '../session.js';
+import { rateLimit } from '../ratelimit.js';
+import { createCheckoutIntent } from '../services/checkout.js';
+import { db } from '../db.js';
+import { upiCheckoutEnabled } from '../config.js';
+
+export async function checkoutRedirect({ req, res, params, query, ip }) {
+ const slug = params.slug;
+ if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(slug)) throw new HttpError(404, 'not_found', 'Not found');
+ if (req.method === 'HEAD') return redirect(res, `/events/${slug}`);
+ await rateLimit(`co:${hashIp(ip)}`, 30, 600);
+
+ const ev = await db.one('SELECT checkout_mode FROM events WHERE slug = $1', [slug]);
+ if (ev?.checkout_mode === 'upi_direct') {
+ if (!upiCheckoutEnabled()) return redirect(res, `/events/${slug}`);
+ const qStr = query.toString() ? `?${query.toString()}` : '';
+ return redirect(res, `/checkout/${slug}/upi${qStr}`);
+ }
+
+ const user = await getSessionUser(req);
+ const intent = await createCheckoutIntent({
+ slug, user, ticketTypeId: query.get('tier') || null, qty: query.get('qty') || 1
+ });
+ res.setHeader('Cache-Control', 'no-store');
+ if (!intent) return redirect(res, `/events/${slug}`);
+ redirect(res, intent.url);
+}
diff --git a/lib/handlers/cron.js b/lib/handlers/cron.js
index cc926fa..56d9d51 100644
--- a/lib/handlers/cron.js
+++ b/lib/handlers/cron.js
@@ -1,44 +1,73 @@
// lib/handlers/cron.js - GET /api/cron/:job (Vercel Cron sends Authorization: Bearer $CRON_SECRET)
// Every job is idempotent: running it twice changes nothing the second time.
-import { sendJson, safeEqual, HttpError } from '../http.js';
+import { sendJson, safeEqual, HttpError, readJson } from '../http.js';
import { env } from '../config.js';
-import { releaseExpiredHolds, reconcilePayments } from '../services/bookings.js';
+import { releaseExpiredHolds } from '../services/bookings.js';
import { queueExpiryReminders, expireAndRevoke } from '../services/membership.js';
import { deliverDue, deliverMany } from '../services/notifications.js';
-import { ticketProvider } from '../payments/index.js';
import { pruneNonces } from '../telegram/auth.js';
import { pruneRateLimits } from '../ratelimit.js';
import { pruneSessions } from '../session.js';
import { logger } from '../logger.js';
+import { z, parse } from '../validate.js';
+import { reconcileWindow } from '../services/reconcile.js';
import { runFeeds } from '../services/feeds.js';
+import { pruneCheckoutIntents } from '../services/checkout.js';
const JOBS = {
'expire-holds': async () => ({ released: await releaseExpiredHolds() }),
- reconcile: async () => {
- let provider;
- try { provider = ticketProvider(); } catch (err) { return { skipped: err.message }; }
- const r = await reconcilePayments(provider);
- await deliverMany(r.notificationIds);
- return { checked: r.checked, applied: r.applied };
- },
memberships: async () => {
const reminders = await queueExpiryReminders();
const revoke = await expireAndRevoke();
- await deliverMany([...reminders, ...revoke.notificationIds]);
+ if (process.env.VERCEL_ENV !== 'preview') {
+ await deliverMany([...reminders, ...revoke.notificationIds]);
+ }
return { reminders: reminders.length, revoked: revoke.revoked, revokeFailed: revoke.failed };
},
- notifications: async () => deliverDue(100),
+ notifications: async () => {
+ if (process.env.VERCEL_ENV === 'preview') {
+ return { skipped: 'notifications delivery disabled in preview' };
+ }
+ return deliverDue(100);
+ },
feeds: async () => {
const r = await runFeeds();
return { fetched: r.length, failed: r.filter((x) => !['ok', 'not_modified'].includes(x.status)).length, newItems: r.reduce((n, x) => n + x.new, 0) };
},
- cleanup: async () => ({ nonces: await pruneNonces(), rateLimits: await pruneRateLimits(), sessions: await pruneSessions() })
+ cleanup: async () => ({ nonces: await pruneNonces(), rateLimits: await pruneRateLimits(), sessions: await pruneSessions(), intents: await pruneCheckoutIntents() })
};
-export async function runCron({ req, res, params }) {
+function requireCronSecret(req) {
const secret = env('CRON_SECRET');
const auth = req.headers.authorization || '';
if (secret.length < 16 || !safeEqual(auth, `Bearer ${secret}`)) throw new HttpError(401, 'unauthorized', 'Unauthorized');
+}
+
+const ReconcileBody = z.object({
+ since: z.string().datetime({ offset: true }),
+ until: z.string().datetime({ offset: true }),
+ sales: z.array(z.object({
+ orderId: z.union([z.string(), z.number()]).optional(),
+ id: z.union([z.string(), z.number()]).optional(),
+ amount: z.union([z.string().max(40), z.number()]).optional(),
+ amountPaise: z.number().int().min(0).optional(),
+ status: z.string().max(20).optional()
+ }).passthrough()).max(2000)
+}).strict();
+
+/** POST /api/reconcile/superprofile — the daily Claude Code task posts SuperProfile's sales for a window. */
+export async function reconcileSuperprofile({ req, res }) {
+ requireCronSecret(req);
+ const b = parse(ReconcileBody, await readJson(req, 512 * 1024));
+ const r = await reconcileWindow({ sales: b.sales, since: b.since, until: b.until });
+ if (process.env.VERCEL_ENV !== 'preview') {
+ await deliverMany([r.notificationId]);
+ }
+ sendJson(res, 200, { ok: true, counts: r.counts, diff: r.diff });
+}
+
+export async function runCron({ req, res, params }) {
+ requireCronSecret(req);
const names = params.job === 'daily' ? Object.keys(JOBS) : [params.job];
if (!names.every((n) => JOBS[n])) throw new HttpError(404, 'not_found', 'Unknown job');
const results = {};
diff --git a/lib/handlers/discovery.js b/lib/handlers/discovery.js
index 48747d8..0a41a5e 100644
--- a/lib/handlers/discovery.js
+++ b/lib/handlers/discovery.js
@@ -3,9 +3,13 @@ import { sendJson, sendHtml, redirect, hashIp, PUBLIC_CACHE } from '../http.js';
import { rateLimit } from '../ratelimit.js';
import { parse, z } from '../validate.js';
import { logger } from '../logger.js';
+import { getSessionUser } from '../session.js';
import { readBody } from './leads.js';
import { createSubmission } from '../services/feeds.js';
import { listPublicEvents, listTiers, CATEGORY_LABELS, CITIES } from '../services/events.js';
+import { findNearbyEvents } from '../services/locations.js';
+import { getDiscoveryFeed } from '../services/discovery-feed.js';
+import { listSavedEventIds } from '../services/saved-events.js';
import { whenRange } from '../views/components.js';
import * as D from '../views/discovery.js';
@@ -60,12 +64,92 @@ export async function submitEventPage({ res, query }) {
const CITY_BY_SLUG = Object.fromEntries(CITIES.map((c) => [c.slug, c]));
-export async function allEventsPage({ res, query }) {
+export async function allEventsPage({ req, res, query }) {
const city = CITY_BY_SLUG[query.get('city')];
const category = Object.hasOwn(CATEGORY_LABELS, query.get('category') || '') ? query.get('category') : '';
- const when = ['week', 'month'].includes(query.get('when')) ? query.get('when') : '';
- const events = await orEmpty(listPublicEvents({ city: city?.name, category: category || undefined, ...whenRange(when), limit: 100 }), []);
- sendHtml(res, 200, D.renderAllEvents({ events, filter: { city: city?.slug || '', category, when } }), { cache: PUBLIC_CACHE });
+ const when = ['today', 'tomorrow', 'weekend', 'week', 'month'].includes(query.get('when')) ? query.get('when') : '';
+ const price = ['all', 'free', 'paid'].includes(query.get('price')) ? query.get('price') : '';
+ const sort = query.get('sort') || 'recommended';
+ const q = (query.get('q') || '').trim().slice(0, 80);
+ const latStr = query.get('lat');
+ const lngStr = query.get('lng');
+ const radiusKm = query.get('radius_km') ? Number(query.get('radius_km')) : 50;
+
+ const user = req ? await getSessionUser(req).catch(() => null) : null;
+ const savedIds = user ? await listSavedEventIds(user.id).catch(() => []) : [];
+ const savedSet = new Set(savedIds);
+
+ let events = null;
+ if (latStr && lngStr) {
+ const lat = Number(latStr);
+ const lng = Number(lngStr);
+ if (!Number.isNaN(lat) && !Number.isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
+ events = await orEmpty(findNearbyEvents({
+ lat,
+ lng,
+ radiusKm,
+ citySlug: city?.slug,
+ category: category || undefined,
+ limit: 100,
+ includeUnlocated: Boolean(city)
+ }), []);
+ }
+ }
+
+ if (!events) {
+ events = await orEmpty(listPublicEvents({ city: city?.name, category: category || undefined, q, ...whenRange(when), limit: 100 }), []);
+ }
+
+ // Filter price if requested
+ if (price === 'free') {
+ events = events.filter((e) => (e.ticketing === 'tiers' ? e.tiers?.some((t) => t.kind === 'free' && t.available) : e.pricePaise === 0 || e.priceLabel === 'Free'));
+ } else if (price === 'paid') {
+ events = events.filter((e) => (e.ticketing === 'tiers' ? e.tiers?.some((t) => t.kind === 'paid') : e.pricePaise && e.pricePaise > 0));
+ }
+
+ events.forEach((e) => {
+ e.isSaved = savedSet.has(e.id);
+ });
+
+ const cache = user ? 'private, no-cache' : PUBLIC_CACHE;
+ sendHtml(res, 200, D.renderAllEvents({
+ events,
+ filter: { city: city?.slug || '', category, when, price, sort, q, lat: latStr, lng: lngStr, radiusKm }
+ }), { cache });
+}
+
+export async function discoveryFeedApi({ req, res, query, ip }) {
+ await rateLimit(`discovery:${hashIp(ip)}`, 60, 60);
+ const user = await getSessionUser(req).catch(() => null);
+ const city = query.get('city') || null;
+ const category = query.get('category') || null;
+ const when = query.get('when') || null;
+ const price = query.get('price') || null;
+ const q = (query.get('q') || '').trim().slice(0, 80) || null;
+ const sort = query.get('sort') || 'recommended';
+ const lat = query.get('lat') ? Number(query.get('lat')) : null;
+ const lng = query.get('lng') ? Number(query.get('lng')) : null;
+ const radiusKm = query.get('radius_km') ? Number(query.get('radius_km')) : 50;
+ const limit = Math.min(Number(query.get('limit')) || 50, 100);
+ const offset = Math.max(Number(query.get('offset')) || 0, 0);
+
+ const feed = await getDiscoveryFeed({
+ userId: user?.id || null,
+ city,
+ category,
+ when,
+ price,
+ q,
+ sort,
+ lat,
+ lng,
+ radiusKm,
+ limit,
+ offset
+ });
+
+ const cache = user ? 'private, no-cache' : PUBLIC_CACHE;
+ sendJson(res, 200, feed, { 'Cache-Control': cache });
}
export const COLLECTIONS = {
diff --git a/lib/handlers/leads.js b/lib/handlers/leads.js
index 52c0ec2..605fc26 100644
--- a/lib/handlers/leads.js
+++ b/lib/handlers/leads.js
@@ -59,7 +59,17 @@ export async function submitLead({ req, res, params, ip }) {
return done();
}
const { consent: _c, ...payload } = parse(schema, body);
- await db.query('INSERT INTO leads (type, payload, ip_hash) VALUES ($1, $2, $3)', [type, JSON.stringify(payload), ipHash]);
+ const leadRow = (await db.query('INSERT INTO leads (type, payload, ip_hash) VALUES ($1, $2, $3) RETURNING id', [type, JSON.stringify(payload), ipHash])).rows[0];
+ if (type === 'host' && leadRow) {
+ try {
+ await db.query(
+ `INSERT INTO notifications (kind, dedupe_key, status)
+ VALUES ('host_application_received', $1, 'pending')
+ ON CONFLICT (dedupe_key) DO NOTHING`,
+ [`lead:host:${leadRow.id}`]
+ );
+ } catch { /* best-effort internal notification queue */ }
+ }
logger.info('lead received', { type });
done();
}
diff --git a/lib/handlers/locations.js b/lib/handlers/locations.js
new file mode 100644
index 0000000..7966c83
--- /dev/null
+++ b/lib/handlers/locations.js
@@ -0,0 +1,118 @@
+// lib/handlers/locations.js - HTTP API endpoints for Location Intelligence and nearby event discovery.
+import { sendJson, HttpError, PUBLIC_CACHE, hashIp, clientIp } from '../http.js';
+import { rateLimit } from '../ratelimit.js';
+import { CATEGORY_LABELS, TRIP_CATEGORIES } from '../services/events.js';
+import {
+ listStates,
+ listDistricts,
+ listCities,
+ getCityBySlug,
+ listLocalities,
+ findNearbyEvents
+} from '../services/locations.js';
+
+const VALID_CATEGORIES = new Set([...Object.keys(CATEGORY_LABELS), ...TRIP_CATEGORIES]);
+
+export async function listStatesHandler({ req, res, query }) {
+ const type = query.get('type') || null;
+ const states = await listStates({ type, activeOnly: true });
+ sendJson(res, 200, { ok: true, count: states.length, states }, { 'Cache-Control': PUBLIC_CACHE || 'public, max-age=3600' });
+}
+
+export async function listDistrictsHandler({ req, res, query }) {
+ const stateId = query.get('state_id') || null;
+ const stateLgdCode = query.get('state_lgd_code') ? Number(query.get('state_lgd_code')) : null;
+ const districts = await listDistricts({ stateId, stateLgdCode, activeOnly: true });
+ sendJson(res, 200, { ok: true, count: districts.length, districts }, { 'Cache-Control': PUBLIC_CACHE || 'public, max-age=3600' });
+}
+
+export async function listCitiesHandler({ req, res, query }) {
+ const q = query.get('q') || null;
+ const stateId = query.get('state_id') || null;
+ const districtId = query.get('district_id') || null;
+ const discoveryOnly = query.get('discovery_only') === 'true';
+
+ const cities = await listCities({
+ activeOnly: true,
+ discoveryOnly,
+ stateId,
+ districtId,
+ q
+ });
+ sendJson(res, 200, { ok: true, count: cities.length, cities }, { 'Cache-Control': 'public, max-age=600' });
+}
+
+export async function getCityHandler({ req, res, params }) {
+ const city = await getCityBySlug(params.slug);
+ if (!city) {
+ throw new HttpError(404, 'city_not_found', 'City not found in official directory');
+ }
+ sendJson(res, 200, { ok: true, city }, { 'Cache-Control': PUBLIC_CACHE || 'public, max-age=3600' });
+}
+
+export async function listLocalitiesHandler({ req, res, query }) {
+ const cityId = query.get('city_id') || null;
+ const citySlug = query.get('city_slug') || null;
+ const localities = await listLocalities({ cityId, citySlug, activeOnly: true });
+ sendJson(res, 200, { ok: true, count: localities.length, localities }, { 'Cache-Control': PUBLIC_CACHE || 'public, max-age=600' });
+}
+
+export async function nearbyEventsHandler({ req, res, query, ip }) {
+ const ipAddr = ip || clientIp(req);
+ await rateLimit(`nearby:${hashIp(ipAddr)}`, 60, 60);
+
+ const latStr = query.get('lat');
+ const lngStr = query.get('lng');
+ const radiusStr = query.get('radius_km');
+ const citySlug = query.get('city');
+ const category = query.get('category');
+ const limitStr = query.get('limit');
+ const offsetStr = query.get('offset');
+
+ if (category && !VALID_CATEGORIES.has(category)) {
+ throw new HttpError(400, 'invalid_category', 'Invalid event category filter');
+ }
+
+ let lat = null;
+ let lng = null;
+ if (latStr !== null && lngStr !== null) {
+ lat = Number(latStr);
+ lng = Number(lngStr);
+ if (Number.isNaN(lat) || lat < -90 || lat > 90) {
+ throw new HttpError(400, 'invalid_latitude', 'lat must be a valid number between -90 and 90');
+ }
+ if (Number.isNaN(lng) || lng < -180 || lng > 180) {
+ throw new HttpError(400, 'invalid_longitude', 'lng must be a valid number between -180 and 180');
+ }
+ }
+
+ if (lat == null && !citySlug) {
+ throw new HttpError(400, 'missing_location', 'Provide either lat and lng coordinates, or a city slug');
+ }
+
+ const radiusKm = radiusStr ? Number(radiusStr) : 50;
+ if (Number.isNaN(radiusKm) || radiusKm <= 0 || radiusKm > 500) {
+ throw new HttpError(400, 'invalid_radius', 'radius_km must be a number between 1 and 500');
+ }
+
+ const limit = limitStr ? Math.min(100, Math.max(1, Number(limitStr))) : 20;
+ const offset = offsetStr ? Math.max(0, Number(offsetStr)) : 0;
+
+ const events = await findNearbyEvents({
+ lat,
+ lng,
+ radiusKm,
+ citySlug,
+ category,
+ limit,
+ offset,
+ includeUnlocated: Boolean(citySlug)
+ });
+
+ sendJson(res, 200, {
+ ok: true,
+ count: events.length,
+ radiusKm,
+ events
+ }, { 'Cache-Control': 'public, max-age=60, stale-while-revalidate=120' });
+}
diff --git a/lib/handlers/membership.js b/lib/handlers/membership.js
index f89002a..3e7ab82 100644
--- a/lib/handlers/membership.js
+++ b/lib/handlers/membership.js
@@ -1,16 +1,10 @@
-// lib/handlers/membership.js - POST /api/membership/checkout → Telegram Stars invoice link;
-// POST /api/membership/superprofile/webhook ← SuperProfile purchase/expiry (via Zapier/Pabbly).
-import { readJson, readRawBody, sendJson, hashIp, safeEqual } from '../http.js';
+// lib/handlers/membership.js - POST /api/membership/checkout → Telegram Stars invoice link.
+// (The SuperProfile webhook lives in handlers/superprofile.js.)
+import { readJson, sendJson, hashIp } from '../http.js';
import { requireUser, requireCsrf } from '../session.js';
import { parse, z } from '../validate.js';
import { rateLimit } from '../ratelimit.js';
-import { env } from '../config.js';
-import { logger } from '../logger.js';
import { createMembershipInvoice } from '../services/membership.js';
-import {
- superprofileConfigured, applySuperprofileEvent, WebhookBody, SUPERPROFILE_SECRET_HEADER
-} from '../services/superprofile.js';
-import { recordIntegrationError } from '../services/insights.js';
const Body = z.object({ tierCode: z.string().regex(/^[a-z0-9_]{1,24}$/) });
@@ -22,28 +16,3 @@ export async function membershipCheckout({ req, res, ip }) {
const { invoiceLink, tier } = await createMembershipInvoice(user, tierCode);
sendJson(res, 200, { ok: true, invoiceLink, tier });
}
-
-// Auth: shared secret in X-Webhook-Secret (SuperProfile itself does not sign requests).
-// Duplicate: 200 no-op. Processing error: 500 so the automation retries. The payload is never logged.
-export async function superprofileWebhook({ req, res, ip }) {
- if (!superprofileConfigured()) return sendJson(res, 503, { ok: false, error: 'not_configured' });
- const got = req.headers[SUPERPROFILE_SECRET_HEADER];
- if (typeof got !== 'string' || !safeEqual(got, env('SUPERPROFILE_WEBHOOK_SECRET'))) {
- logger.warn('superprofile webhook rejected: bad secret');
- return sendJson(res, 401, { ok: false });
- }
- await rateLimit(`sp:${hashIp(ip)}`, 300, 60);
- let body;
- try { body = JSON.parse(await readRawBody(req, 32 * 1024)); } catch { return sendJson(res, 400, { ok: false, error: 'invalid_json' }); }
- const p = WebhookBody.safeParse(body);
- if (!p.success) return sendJson(res, 400, { ok: false, error: 'validation', fields: p.error.issues.map((i) => i.path.join('.')) });
- try {
- const r = await applySuperprofileEvent(p.data);
- logger.info('superprofile webhook processed', { event: p.data.event, result: r.result, tierMapped: r.tierMapped });
- sendJson(res, 200, { ok: true, ...r });
- } catch (err) {
- await recordIntegrationError('superprofile_webhook', 'processing_failed', String(err.code || err.message));
- logger.error('superprofile webhook failed', err);
- sendJson(res, 500, { ok: false });
- }
-}
diff --git a/lib/handlers/organiser.js b/lib/handlers/organiser.js
index db15503..7db1697 100644
--- a/lib/handlers/organiser.js
+++ b/lib/handlers/organiser.js
@@ -2,7 +2,7 @@
// event images. Every organiser endpoint: session → organiser check → ownership (drafts and
// events are looked up by id AND owner, so another organiser's draft is a 404). Every write:
// CSRF + rate limit.
-import { HttpError, readJson, readBinaryBody, sendJson, sendHtml } from '../http.js';
+import { HttpError, readJson, readBinaryBody, sendJson, sendHtml, redirect } from '../http.js';
import { getSessionUser, requireUser, requireCsrf, csrfTokenFor } from '../session.js';
import { parse, z, uuid } from '../validate.js';
import { rateLimit } from '../ratelimit.js';
@@ -13,31 +13,47 @@ import { CATEGORY_LABELS, CITIES } from '../services/events.js';
import { TIMEZONES } from '../time.js';
import * as O from '../services/organiser.js';
import { bookTier, TierBookingBody, decideRequest, listEventGuests, manageableEvent } from '../services/ticketing.js';
-import { renderOrganiserPage, renderDraftPreview } from '../views/organiser.js';
+import { renderOrganiserPage, renderDraftPreview, renderStaffJoinPage } from '../views/organiser.js';
+import { can, authorize } from '../services/permissions.js';
+import {
+ checkInTicket, reissueTicket, revokeTicket, getEventAttendance, listEventScans, getBookingTickets
+} from '../services/tickets.js';
+import {
+ listEventStaff, assignEventStaff, revokeEventStaff, createStaffInvite, getStaffInvite, acceptStaffInvite
+} from '../services/event-staff.js';
+import {
+ listEventAnnouncements, createEventAnnouncement
+} from '../services/event-announcements.js';
const id = (v) => {
if (!uuid.safeParse(v).success) throw new HttpError(404, 'not_found', 'Not found');
return v;
};
-async function organiser(ctx, { write = false, limit = [240, 600] } = {}) {
+async function organiser(ctx, { write = false, limit = [240, 600], scope = null } = {}) {
const user = await requireUser(ctx.req);
await O.requireOrganiser(user);
if (write) {
requireCsrf(ctx.req, user);
- await rateLimit(`org:${user.id}`, limit[0], limit[1]);
+ const key = scope ? `org:${scope}:${user.id}` : `org:${user.id}`;
+ await rateLimit(key, limit[0], limit[1]);
}
return user;
}
// ---------- pages ----------
-/** Resolve page state without throwing: signed_out | not_organiser | ok. */
-async function pageState(req) {
+/** Resolve page state without throwing: signed_out | not_organiser | ok. Supports event-scoped staff. */
+async function pageState(req, eventId = null) {
const user = await getSessionUser(req);
if (!user) return { state: 'signed_out' };
- if (!(await O.isOrganiser(user))) return { state: 'not_organiser', user };
- return { state: 'ok', user, csrf: csrfTokenFor(user.sessionToken) };
+ const isOrg = await O.isOrganiser(user);
+ if (isOrg) return { state: 'ok', user, csrf: csrfTokenFor(user.sessionToken) };
+ if (eventId) {
+ const isStaff = await can(user, 'event.check_in', { eventId });
+ if (isStaff) return { state: 'ok', user, csrf: csrfTokenFor(user.sessionToken), eventStaff: true };
+ }
+ return { state: 'not_organiser', user };
}
function wizardConfig(user, draftId) {
@@ -70,8 +86,35 @@ export async function wizardPage({ req, res, query }) {
}
export async function managePage({ req, res, params }) {
- const s = await pageState(req);
- sendHtml(res, 200, renderOrganiserPage({ page: 'manage', ...s, eventId: id(params.id) }), NOINDEX);
+ const eventId = id(params.id);
+ const s = await pageState(req, eventId);
+ sendHtml(res, 200, renderOrganiserPage({ page: 'manage', ...s, eventId }), NOINDEX);
+}
+
+export async function scanPage({ req, res, params }) {
+ const eventId = id(params.id);
+ const s = await pageState(req, eventId);
+ sendHtml(res, 200, renderOrganiserPage({ page: 'scan', ...s, eventId }), NOINDEX);
+}
+
+export async function staffJoinPage({ req, res, query }) {
+ const token = query.get('token');
+ const user = await getSessionUser(req).catch(() => null);
+ let invite = null;
+ let error = null;
+ if (!token) {
+ error = 'Missing invitation token';
+ } else {
+ try {
+ invite = await getStaffInvite(token);
+ invite.token = token;
+ } catch (err) {
+ error = err.message || 'Invalid or expired invite';
+ }
+ }
+ const csrf = user ? csrfTokenFor(user.sessionToken) : '';
+ const state = user ? 'ok' : 'signed_out';
+ sendHtml(res, 200, renderStaffJoinPage({ state, invite, csrf, error }), NOINDEX);
}
/** The real attendee page rendered from the draft, booking disabled. Owner only; never cached. */
@@ -89,7 +132,7 @@ const withIssues = (draft) => ({ ...draft, issues: O.publishIssues(draft.data) }
export async function context(ctx) {
const user = await organiser(ctx);
- const [drafts, events] = await Promise.all([O.listDrafts(user.id), O.listOrganiserEvents(user.id)]);
+ const [drafts, events] = await Promise.all([O.listDrafts(user.id), O.listOrganiserEvents(user)]);
sendJson(ctx.res, 200, { ok: true, drafts, events, checkout: ticketCheckoutStatus() });
}
@@ -139,7 +182,7 @@ export async function checkDraft(ctx) {
const PublishBody = z.object({ version: z.number().int().min(1), confirm: z.literal(true) }).strict();
export async function publishDraft(ctx) {
- const user = await organiser(ctx, { write: true, limit: [20, 600] });
+ const user = await organiser(ctx, { write: true, limit: [20, 600], scope: 'publish' });
const raw = await readJson(ctx.req);
if (raw.confirm !== true) throw new HttpError(400, 'confirm_required', 'Publishing needs explicit confirmation.');
const body = parse(PublishBody, raw);
@@ -149,7 +192,7 @@ export async function publishDraft(ctx) {
// ---------- images ----------
export async function uploadImage(ctx) {
- const user = await organiser(ctx, { write: true, limit: [40, 600] });
+ const user = await organiser(ctx, { write: true, limit: [40, 600], scope: 'upload' });
const buf = await readBinaryBody(ctx.req, O.MAX_IMAGE_BYTES);
const img = await O.addImage(user.id, id(ctx.params.id), buf, ctx.req.headers['content-type']);
sendJson(ctx.res, 201, { ok: true, image: img });
@@ -177,13 +220,13 @@ export async function serveImage({ req, res, params }) {
export async function listEvents(ctx) {
const user = await organiser(ctx);
- sendJson(ctx.res, 200, { ok: true, events: await O.listOrganiserEvents(user.id) });
+ sendJson(ctx.res, 200, { ok: true, events: await O.listOrganiserEvents(user) });
}
export async function eventGuests(ctx) {
const user = await requireUser(ctx.req);
const r = await listEventGuests(user, id(ctx.params.id));
- const e = await manageableEvent(user, r.event.id);
+ const e = await manageableEvent(user, r.event.id, undefined, { action: 'event.view_guests' });
const path = `${['weekend_trip', 'resort_getaway'].includes(e.category) ? '/trips' : '/events'}/${e.slug}`;
sendJson(ctx.res, 200, { ok: true, ...r, event: { ...r.event, path } });
}
@@ -210,3 +253,228 @@ export async function bookTicket(ctx) {
await afterResponse(() => deliverMany(r.notificationIds || []));
sendJson(ctx.res, 200, { ok: true, bookingId: r.bookingId, status: r.status, checkoutUrl: r.checkoutUrl || null, existing: Boolean(r.existing) });
}
+
+// ---------- M6 Organiser Workspace & Event Staff API ----------
+
+export async function eventOverview(ctx) {
+ const user = await requireUser(ctx.req);
+ const overview = await O.getEventOverview(user, id(ctx.params.id));
+ sendJson(ctx.res, 200, { ok: true, ...overview });
+}
+
+const UpdateEventBody = z.object({
+ title: z.string().min(3).max(140).optional(),
+ description: z.string().min(10).max(5000).optional(),
+ capacity: z.number().int().min(1).max(5000).optional(),
+ start_at: z.string().optional(),
+ end_at: z.string().nullable().optional(),
+ area_public: z.string().max(120).nullable().optional(),
+ venue_private: z.string().max(300).nullable().optional(),
+ venue_privacy: z.enum(['public', 'disclosed_after_booking']).optional(),
+ maps_url: z.string().max(500).nullable().optional(),
+ refund_policy: z.string().max(1000).nullable().optional()
+}).strict();
+
+export async function updateEvent(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`org:edit:${user.id}`, 60, 600);
+ const body = parse(UpdateEventBody, await readJson(ctx.req));
+ const event = await O.updateOrganiserEvent(user, id(ctx.params.id), body);
+ sendJson(ctx.res, 200, { ok: true, event });
+}
+
+const CancelBody = z.object({
+ reason: z.string().min(3).max(500).default('Cancelled by organiser')
+}).strict();
+
+export async function cancelEvent(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`org:cancel:${user.id}`, 20, 600);
+ const body = parse(CancelBody, await readJson(ctx.req));
+ const r = await O.cancelOrganiserEvent(user, id(ctx.params.id), body);
+ sendJson(ctx.res, 200, r);
+}
+
+export async function eventInventory(ctx) {
+ const user = await requireUser(ctx.req);
+ const inv = await O.getEventInventory(user, id(ctx.params.id));
+ sendJson(ctx.res, 200, { ok: true, ...inv });
+}
+
+export async function eventBookings(ctx) {
+ const user = await requireUser(ctx.req);
+ const q = ctx.query.get('q') || '';
+ const status = ctx.query.get('status') || 'all';
+ const page = Math.max(1, parseInt(ctx.query.get('page') || '1', 10) || 1);
+ const limit = Math.min(100, Math.max(1, parseInt(ctx.query.get('limit') || '50', 10) || 50));
+ const bookings = await O.listOrganiserBookings(user, id(ctx.params.id), { query: q, status, page, limit });
+ sendJson(ctx.res, 200, { ok: true, bookings, page, limit });
+}
+
+export async function cancelBooking(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`org:bkcancel:${user.id}`, 60, 600);
+ const body = parse(CancelBody, await readJson(ctx.req));
+ const r = await O.cancelOrganiserBooking(user, id(ctx.params.id), body);
+ sendJson(ctx.res, 200, r);
+}
+
+// ---------- Event Staff Roles & Invitations ----------
+
+export async function eventStaff(ctx) {
+ const user = await requireUser(ctx.req);
+ const data = await listEventStaff(user, id(ctx.params.id));
+ sendJson(ctx.res, 200, { ok: true, ...data });
+}
+
+const AssignStaffBody = z.object({
+ userId: uuid,
+ role: z.enum(['event_manager', 'door_staff', 'guest_list_manager', 'assistant']),
+ notes: z.string().max(500).nullable().optional()
+}).strict();
+
+export async function assignStaff(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`org:staff:${user.id}`, 60, 600);
+ const body = parse(AssignStaffBody, await readJson(ctx.req));
+ const r = await assignEventStaff(user, id(ctx.params.id), body);
+ sendJson(ctx.res, 201, r);
+}
+
+export async function revokeStaff(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`org:staff:${user.id}`, 60, 600);
+ const r = await revokeEventStaff(user, id(ctx.params.id), id(ctx.params.staffId));
+ sendJson(ctx.res, 200, r);
+}
+
+const InviteStaffBody = z.object({
+ role: z.enum(['event_manager', 'door_staff', 'guest_list_manager', 'assistant']),
+ invitedAlias: z.string().max(80).optional(),
+ ttlHours: z.number().int().min(1).max(168).default(48)
+}).strict();
+
+export async function inviteStaff(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`org:staff:${user.id}`, 60, 600);
+ const body = parse(InviteStaffBody, await readJson(ctx.req));
+ const r = await createStaffInvite(user, id(ctx.params.id), body);
+ sendJson(ctx.res, 201, r);
+}
+
+export async function getStaffInviteHandler(ctx) {
+ const invite = await getStaffInvite(ctx.params.token);
+ sendJson(ctx.res, 200, { ok: true, invite });
+}
+
+const AcceptInviteBody = z.object({
+ token: z.string().min(10).max(100)
+}).strict();
+
+export async function acceptStaffInviteHandler(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ const body = parse(AcceptInviteBody, await readJson(ctx.req));
+ const r = await acceptStaffInvite(user, body.token);
+ sendJson(ctx.res, 200, r);
+}
+
+// ---------- Event Announcements ----------
+
+export async function eventAnnouncements(ctx) {
+ const user = await requireUser(ctx.req);
+ const announcements = await listEventAnnouncements(user, id(ctx.params.id));
+ sendJson(ctx.res, 200, { ok: true, announcements });
+}
+
+const AnnouncementBody = z.object({
+ title: z.string().min(3).max(120),
+ message: z.string().min(5).max(3000),
+ isPinned: z.boolean().default(false),
+ notifyAttendees: z.boolean().default(true)
+}).strict();
+
+export async function postAnnouncement(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`org:ann:${user.id}`, 30, 600);
+ const body = parse(AnnouncementBody, await readJson(ctx.req));
+ const r = await createEventAnnouncement(user, id(ctx.params.id), body);
+ sendJson(ctx.res, 201, r);
+}
+
+// ---------- Secure QR Ticket Check-In & Verification ----------
+
+const CheckInBody = z.object({
+ ticketCode: z.string().max(50).nullable().optional(),
+ qrPayload: z.string().max(500).nullable().optional(),
+ method: z.enum(['camera_qr', 'manual_lookup', 'manual_override', 'camera', 'manual']).default('camera_qr'),
+ scanMethod: z.enum(['camera_qr', 'manual_lookup', 'manual_override', 'camera', 'manual']).optional(),
+ overrideReason: z.string().max(500).nullable().optional()
+}).strict();
+
+export async function checkInTicketHandler(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`checkin:${user.id}`, 600, 600);
+ const body = parse(CheckInBody, await readJson(ctx.req));
+ const rawMethod = body.scanMethod || body.method;
+ const method = rawMethod === 'camera' ? 'camera_qr' : (rawMethod === 'manual' ? 'manual_lookup' : rawMethod);
+ const r = await checkInTicket(user, id(ctx.params.id), { ...body, method });
+ sendJson(ctx.res, 200, r);
+}
+
+export async function eventScans(ctx) {
+ const user = await requireUser(ctx.req);
+ const eventId = id(ctx.params.id);
+ await authorize(user, 'event.view_audit', { eventId });
+ const limit = Math.min(100, Math.max(1, parseInt(ctx.query.get('limit') || '50', 10) || 50));
+ const scans = await listEventScans(eventId, limit);
+ sendJson(ctx.res, 200, { ok: true, scans });
+}
+
+export async function eventAttendance(ctx) {
+ const user = await requireUser(ctx.req);
+ const eventId = id(ctx.params.id);
+ await authorize(user, 'event.view_inventory', { eventId });
+ const attendance = await getEventAttendance(eventId);
+ sendJson(ctx.res, 200, { ok: true, ...attendance });
+}
+
+const ReissueBody = z.object({
+ reason: z.string().min(3).max(500).default('reissued_by_host')
+}).strict();
+
+export async function reissueTicketHandler(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`org:reissue:${user.id}`, 30, 600);
+ const body = parse(ReissueBody, await readJson(ctx.req));
+ const r = await reissueTicket(user, id(ctx.params.id), body.reason);
+ sendJson(ctx.res, 200, r);
+}
+
+const RevokeTicketBody = z.object({
+ reason: z.string().min(3).max(500).default('revoked_by_host')
+}).strict();
+
+export async function revokeTicketHandler(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`org:revoke:${user.id}`, 30, 600);
+ const body = parse(RevokeTicketBody, await readJson(ctx.req));
+ const r = await revokeTicket(user, id(ctx.params.id), body.reason);
+ sendJson(ctx.res, 200, r);
+}
+
+export async function guestTicket(ctx) {
+ const user = await requireUser(ctx.req);
+ const tickets = await getBookingTickets(id(ctx.params.id), user);
+ sendJson(ctx.res, 200, { ok: true, tickets });
+}
diff --git a/lib/handlers/orgs.js b/lib/handlers/orgs.js
new file mode 100644
index 0000000..28b2a4b
--- /dev/null
+++ b/lib/handlers/orgs.js
@@ -0,0 +1,179 @@
+// lib/handlers/orgs.js - Organisations, members and venues for the people who belong to them.
+// Every route: session → authorize(user, action, scope) (outsiders get 404, low roles 403). Every
+// write: CSRF + rate limit + audit row. Lists are paginated (?limit, ?offset).
+import { HttpError, readJson, sendJson } from '../http.js';
+import { requireUser, requireCsrf } from '../session.js';
+import { parse, z, uuid } from '../validate.js';
+import { rateLimit } from '../ratelimit.js';
+import { audit } from '../audit.js';
+import { db } from '../db.js';
+import { page, pageInfo } from '../pagination.js';
+import { authorize, can } from '../services/permissions.js';
+
+const id = (v) => {
+ if (!uuid.safeParse(v).success) throw new HttpError(404, 'not_found', 'Not found');
+ return v;
+};
+
+async function writer(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`orgs:${user.id}`, 60, 600);
+ return user;
+}
+
+const orgOut = (o) => ({ id: o.id, kind: o.kind, name: o.name, status: o.status, verified: Boolean(o.verified_at) });
+
+// ---------- my organisations ----------
+
+export async function myOrgs(ctx) {
+ const user = await requireUser(ctx.req);
+ const p = page(ctx.query);
+ const { rows } = await db.query(
+ `SELECT o.id, o.kind, o.name, o.status, o.verified_at, m.role
+ FROM org_memberships m JOIN organisations o ON o.id = m.org_id
+ WHERE m.user_id = $1 AND m.status = 'active'
+ ORDER BY (o.kind = 'personal') DESC, o.name, o.id LIMIT $2 OFFSET $3`, [user.id, p.limit + 1, p.offset]);
+ const r = pageInfo(rows, p, 'orgs');
+ sendJson(ctx.res, 200, { ok: true, ...r, orgs: r.orgs.map((o) => ({ ...orgOut(o), role: o.role })) });
+}
+
+export async function getOrg(ctx) {
+ const user = await requireUser(ctx.req);
+ const orgId = id(ctx.params.id);
+ const a = await authorize(user, 'org.view', { orgId });
+ const o = await db.one('SELECT * FROM organisations WHERE id = $1', [orgId]);
+ if (!o) throw new HttpError(404, 'not_found', 'Not found');
+ sendJson(ctx.res, 200, { ok: true, org: { ...orgOut(o), role: a.role || null } });
+}
+
+// ---------- members ----------
+
+export async function listMembers(ctx) {
+ const user = await requireUser(ctx.req);
+ const orgId = id(ctx.params.id);
+ await authorize(user, 'org.view_members', { orgId });
+ const p = page(ctx.query);
+ const { rows } = await db.query(
+ `SELECT m.user_id, m.role, m.status, m.created_at, u.alias
+ FROM org_memberships m JOIN users u ON u.id = m.user_id
+ WHERE m.org_id = $1 ORDER BY m.created_at, m.user_id LIMIT $2 OFFSET $3`, [orgId, p.limit + 1, p.offset]);
+ const r = pageInfo(rows, p, 'members');
+ sendJson(ctx.res, 200, { ok: true, ...r, members: r.members.map((m) => ({ userId: m.user_id, alias: m.alias || 'Member', role: m.role, status: m.status, since: m.created_at })) });
+}
+
+const AddMemberBody = z.object({
+ telegram_user_id: z.coerce.number().int().positive(),
+ role: z.enum(['admin', 'manager', 'staff'])
+}).strict();
+
+export async function addMember(ctx) {
+ const user = await writer(ctx);
+ const orgId = id(ctx.params.id);
+ const b = parse(AddMemberBody, await readJson(ctx.req));
+ await db.tx(async (c) => {
+ await authorize(user, b.role === 'admin' ? 'org.manage_admins' : 'org.manage_members', { orgId }, c);
+ const org = (await c.query('SELECT kind FROM organisations WHERE id = $1 FOR UPDATE', [orgId])).rows[0];
+ if (!org) throw new HttpError(404, 'not_found', 'Not found');
+ if (org.kind === 'personal') throw new HttpError(409, 'personal_org', 'A personal organisation has one member. Ask an admin to set up a team organisation.');
+ const target = (await c.query('SELECT id FROM users WHERE telegram_user_id = $1', [b.telegram_user_id])).rows[0];
+ if (!target) throw new HttpError(404, 'user_not_found', 'That person needs to sign in to the site once first');
+ const cur = (await c.query('SELECT role FROM org_memberships WHERE user_id = $1 AND org_id = $2', [target.id, orgId])).rows[0];
+ if (cur?.role === 'owner') throw new HttpError(409, 'is_owner', 'That person already owns this organisation.');
+ if (cur?.role === 'admin' && !(await can(user, 'org.manage_admins', { orgId }, c))) throw new HttpError(403, 'forbidden', 'Only the owner can change an admin.');
+ await c.query(
+ `INSERT INTO org_memberships (user_id, org_id, role, status) VALUES ($1, $2, $3, 'active')
+ ON CONFLICT (user_id, org_id) DO UPDATE SET role = EXCLUDED.role, status = 'active'`, [target.id, orgId, b.role]);
+ await audit(`user:${user.id}`, 'org.member.add', orgId, { userId: target.id, role: b.role }, c);
+ });
+ sendJson(ctx.res, 200, { ok: true });
+}
+
+const UpdateMemberBody = z.object({
+ role: z.enum(['admin', 'manager', 'staff']).optional(),
+ status: z.enum(['active', 'revoked']).optional()
+}).strict().refine((b) => b.role || b.status, { message: 'Nothing to change' });
+
+export async function updateMember(ctx) {
+ const user = await writer(ctx);
+ const orgId = id(ctx.params.id);
+ const targetId = id(ctx.params.member);
+ const b = parse(UpdateMemberBody, await readJson(ctx.req));
+ await db.tx(async (c) => {
+ await authorize(user, 'org.manage_members', { orgId }, c);
+ const cur = (await c.query('SELECT role, status FROM org_memberships WHERE user_id = $1 AND org_id = $2 FOR UPDATE', [targetId, orgId])).rows[0];
+ if (!cur) throw new HttpError(404, 'not_found', 'Member not found');
+ if (cur.role === 'owner') throw new HttpError(409, 'is_owner', 'The owner cannot be changed here.');
+ if ((cur.role === 'admin' || b.role === 'admin') && !(await can(user, 'org.manage_admins', { orgId }, c))) {
+ throw new HttpError(403, 'forbidden', 'Only the owner can change an admin.');
+ }
+ await c.query(
+ `UPDATE org_memberships SET role = COALESCE($3, role), status = COALESCE($4, status) WHERE user_id = $1 AND org_id = $2`,
+ [targetId, orgId, b.role || null, b.status || null]);
+ await audit(`user:${user.id}`, 'org.member.update', orgId, { userId: targetId, from: cur, to: b }, c);
+ });
+ sendJson(ctx.res, 200, { ok: true });
+}
+
+// ---------- venues (address and coordinates are for members only) ----------
+
+const venueOut = (v, priv) => ({
+ id: v.id, orgId: v.org_id, name: v.name, capacity: v.capacity, localityId: v.locality_id, status: v.status,
+ ...(priv ? { addressPrivate: v.address_private, lat: v.lat, lng: v.lng } : {})
+});
+
+export async function listVenues(ctx) {
+ const user = await requireUser(ctx.req);
+ const orgId = id(ctx.params.id);
+ await authorize(user, 'venue.view', { orgId });
+ const priv = await can(user, 'venue.view_private', { orgId });
+ const p = page(ctx.query);
+ const { rows } = await db.query(
+ `SELECT * FROM venues WHERE org_id = $1 ORDER BY status, name, id LIMIT $2 OFFSET $3`, [orgId, p.limit + 1, p.offset]);
+ const r = pageInfo(rows, p, 'venues');
+ sendJson(ctx.res, 200, { ok: true, ...r, venues: r.venues.map((v) => venueOut(v, priv)) }, { 'Cache-Control': 'private, no-store' });
+}
+
+const VenueBody = z.object({
+ name: z.string().trim().min(2).max(120),
+ capacity: z.number().int().positive().max(100_000).nullable().optional(),
+ address_private: z.string().trim().max(500).nullable().optional(),
+ lat: z.number().min(-90).max(90).nullable().optional(),
+ lng: z.number().min(-180).max(180).nullable().optional()
+}).strict();
+
+export async function createVenue(ctx) {
+ const user = await writer(ctx);
+ const orgId = id(ctx.params.id);
+ const b = parse(VenueBody, await readJson(ctx.req));
+ const v = await db.tx(async (c) => {
+ await authorize(user, 'venue.manage', { orgId }, c);
+ if (!(await c.query('SELECT 1 FROM organisations WHERE id = $1', [orgId])).rowCount) throw new HttpError(404, 'not_found', 'Not found');
+ const row = (await c.query(
+ `INSERT INTO venues (org_id, name, capacity, address_private, lat, lng) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *`,
+ [orgId, b.name, b.capacity ?? null, b.address_private ?? null, b.lat ?? null, b.lng ?? null])).rows[0];
+ await audit(`user:${user.id}`, 'venue.create', row.id, { orgId }, c);
+ return row;
+ });
+ sendJson(ctx.res, 201, { ok: true, venue: venueOut(v, true) });
+}
+
+const VenuePatch = VenueBody.partial().extend({ status: z.enum(['active', 'archived']).optional() }).strict();
+
+export async function updateVenue(ctx) {
+ const user = await writer(ctx);
+ const venueId = id(ctx.params.id);
+ const b = parse(VenuePatch, await readJson(ctx.req));
+ const v = await db.tx(async (c) => {
+ const cur = (await c.query('SELECT * FROM venues WHERE id = $1 FOR UPDATE', [venueId])).rows[0];
+ if (!cur) throw new HttpError(404, 'not_found', 'Not found');
+ await authorize(user, 'venue.manage', { venue: cur }, c);
+ const next = { ...cur, ...b };
+ const row = (await c.query(
+ `UPDATE venues SET name = $2, capacity = $3, address_private = $4, lat = $5, lng = $6, status = $7 WHERE id = $1 RETURNING *`,
+ [venueId, next.name, next.capacity, next.address_private, next.lat, next.lng, next.status])).rows[0];
+ await audit(`user:${user.id}`, 'venue.update', venueId, { fields: Object.keys(b) }, c);
+ return row;
+ });
+ sendJson(ctx.res, 200, { ok: true, venue: venueOut(v, true) });
+}
diff --git a/lib/handlers/pages.js b/lib/handlers/pages.js
index 4e23dbf..5c9978b 100644
--- a/lib/handlers/pages.js
+++ b/lib/handlers/pages.js
@@ -1,12 +1,15 @@
// lib/handlers/pages.js - Public, CDN-cacheable server-rendered pages + sitemap/robots.
import { sendHtml, sendText, sendJson, redirect, HttpError, PUBLIC_CACHE } from '../http.js';
+import { getSessionUser } from '../session.js';
import { siteUrl, isProductionRuntime } from '../config.js';
-import { devLoginEnabled } from '../dev-personas.js';
+import { devLoginEnabled, previewReviewerEnabled } from '../dev-personas.js';
import { oidcConfigured } from '../telegram/auth.js';
import {
listPublicEvents, getPublicEventBySlug, listSitemapEvents, socialProof, listVisibleMedia, listTiers,
CATEGORY_LABELS, CITIES
} from '../services/events.js';
+import { isOrganiser } from '../services/organiser.js';
+import { isEventSaved } from '../services/saved-events.js';
import { renderHome } from '../views/home.js';
import { renderEvent } from '../views/event.js';
import { eventPath, whenRange } from '../views/components.js';
@@ -33,8 +36,8 @@ export async function home({ res, query }) {
const filter = readFilter(query);
const range = whenRange(filter.when);
const [events, trips, tiers, proof, media] = await Promise.all([
- orEmpty(listPublicEvents({ city: filter.cityName, category: filter.category || undefined, kind: filter.category ? 'all' : 'events', ...range, limit: 12 }), []),
- orEmpty(listPublicEvents({ kind: 'trips', limit: 6 }), []),
+ orEmpty(listPublicEvents({ city: filter.cityName, category: filter.category || undefined, kind: filter.category ? 'all' : 'events', ...range, limit: 50 }), []),
+ orEmpty(listPublicEvents({ kind: 'trips', limit: 12 }), []),
orEmpty(listTiers(), []),
orEmpty(socialProof(), null),
orEmpty(listVisibleMedia(6), [])
@@ -42,13 +45,20 @@ export async function home({ res, query }) {
sendHtml(res, 200, renderHome({ events, trips, tiers, proof, media, filter }), { cache: PUBLIC_CACHE });
}
-export async function eventPage({ res, params, pathname }) {
+export async function eventPage({ req, res, params, pathname }) {
// No database means no events exist: an honest 404, not a 503.
const e = await orEmpty(getPublicEventBySlug(params.slug), null);
if (!e) throw new HttpError(404, 'not_found', 'Event not found');
const canonical = eventPath(e);
if (canonical !== pathname.replace(/\/$/, '')) return redirect(res, canonical, 301);
- sendHtml(res, 200, renderEvent(e), { cache: PUBLIC_CACHE });
+
+ const user = req ? await getSessionUser(req).catch(() => null) : null;
+ if (user && e.id) {
+ e.isSaved = await isEventSaved(user.id, e.id).catch(() => false);
+ }
+
+ const cache = user ? 'private, no-cache' : PUBLIC_CACHE;
+ sendHtml(res, 200, renderEvent(e), { cache });
}
export async function tripsPage({ res }) {
@@ -85,10 +95,13 @@ export async function cityPage({ res, params }) {
const FORM_BY_PATH = { '/partner-with-us': 'partner', '/become-a-host': 'host', '/list-your-venue': 'venue' };
-export async function formPage({ res, pathname, query }) {
+export async function formPage({ req, res, pathname, query }) {
const type = FORM_BY_PATH[pathname.replace(/\/$/, '')];
- const html = query.get('sent') === '1' ? P.renderFormThanks(type) : P.renderForm(type);
- sendHtml(res, 200, html, { cache: PUBLIC_CACHE });
+ if (!type) throw new HttpError(404, 'not_found', 'Page not found');
+ const user = await getSessionUser(req).catch(() => null);
+ const isOrg = user ? await isOrganiser(user).catch(() => false) : false;
+ const html = query.get('sent') === '1' ? P.renderFormThanks(type, { user, isOrg }) : P.renderForm(type, { user, isOrg });
+ sendHtml(res, 200, html, user ? { cache: 'private, no-cache' } : { cache: PUBLIC_CACHE });
}
const STATIC = {
@@ -105,12 +118,22 @@ export async function staticPage({ res, pathname }) {
sendHtml(res, 200, STATIC[pathname.replace(/\/$/, '')](), { cache: PUBLIC_CACHE });
}
-export async function memberPage({ res, pathname, query }) {
- const html = pathname.startsWith('/me') ? P.renderMe() : P.renderSignin({
+export async function memberPage({ req, res, pathname, query }) {
+ if (pathname.startsWith('/me')) {
+ const user = await getSessionUser(req).catch(() => null);
+ if (!user) {
+ res.setHeader('Cache-Control', 'no-store');
+ return redirect(res, `/signin?next=${encodeURIComponent('/me')}`);
+ }
+ const html = P.renderMe();
+ return sendHtml(res, 200, html, { cache: 'no-store' });
+ }
+ const html = P.renderSignin({
next: /^\/(?![\/\\])[\w\-./?=%]*$/.test(query.get('next') || '') ? query.get('next') : '/me',
error: query.get('error') || '',
oidc: oidcConfigured(),
- devLogin: devLoginEnabled()
+ devLogin: devLoginEnabled(),
+ previewReviewer: previewReviewerEnabled()
});
sendHtml(res, 200, html, { cache: 'no-store' });
}
@@ -144,7 +167,7 @@ export async function sitemap({ res }) {
export async function robots({ res }) {
// Only the production deployment is indexable; previews are not.
const body = isProductionRuntime()
- ? `User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /admin\nDisallow: /me\nDisallow: /bookings/\nDisallow: /signin\nDisallow: /organiser\n\nSitemap: ${siteUrl()}/sitemap.xml\n`
+ ? `User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /admin\nDisallow: /me\nDisallow: /bookings/\nDisallow: /checkout/\nDisallow: /signin\nDisallow: /organiser\n\nSitemap: ${siteUrl()}/sitemap.xml\n`
: 'User-agent: *\nDisallow: /\n';
sendText(res, 200, body);
}
diff --git a/lib/handlers/payments.js b/lib/handlers/payments.js
deleted file mode 100644
index 9fa7ac0..0000000
--- a/lib/handlers/payments.js
+++ /dev/null
@@ -1,35 +0,0 @@
-// lib/handlers/payments.js - POST /api/payments/webhook/:provider
-// verify signature → webhook_events (unique) → DB transaction → deliver notifications after commit.
-// Bad signature: 401. Duplicate: 200 no-op. Processing error: 500 (transaction rolled back,
-// including the webhook_events row, so the provider's retry is processed).
-import { readRawBody, sendJson } from '../http.js';
-import { providerByName } from '../payments/index.js';
-import { applyTicketEvent } from '../services/bookings.js';
-import { deliverMany } from '../services/notifications.js';
-import { logger } from '../logger.js';
-import { afterResponse } from '../after.js';
-import { recordIntegrationError } from '../services/insights.js';
-
-export async function paymentWebhook({ req, res, params }) {
- if (!['razorpay', 'cashfree'].includes(params.provider)) return sendJson(res, 404, { ok: false });
- const provider = providerByName(params.provider);
- const raw = await readRawBody(req, 256 * 1024);
- let evt;
- try {
- evt = provider.verifyWebhook(req.headers, raw);
- } catch (err) {
- logger.warn('payment webhook rejected', { provider: params.provider, reason: err.code === 'WEBHOOK_SIGNATURE' ? err.message : 'unparseable' });
- return sendJson(res, err.code === 'WEBHOOK_SIGNATURE' ? 401 : 400, { ok: false });
- }
- let r;
- try {
- r = await applyTicketEvent(provider.name, evt);
- } catch (err) {
- await recordIntegrationError('payment_webhook', `${provider.name}_processing_failed`, String(err.code || err.message));
- throw err;
- }
- logger.info('payment webhook processed', { provider: provider.name, type: evt.type, result: r.result });
- // Notifications are already committed to the outbox; delivery failures are retried by cron.
- await afterResponse(() => deliverMany(r.notificationIds));
- sendJson(res, 200, { ok: true, result: r.result });
-}
diff --git a/lib/handlers/safety.js b/lib/handlers/safety.js
new file mode 100644
index 0000000..388395f
--- /dev/null
+++ b/lib/handlers/safety.js
@@ -0,0 +1,92 @@
+// lib/handlers/safety.js - HTTP endpoints for safety reports and user blocking.
+import { readJson, sendJson, HttpError } from '../http.js';
+import { requireUser, requireCsrf } from '../session.js';
+import { rateLimit } from '../ratelimit.js';
+import { parse, z } from '../validate.js';
+import {
+ submitSafetyReport,
+ listUserReports,
+ blockUser as blockUserSvc,
+ unblockUser as unblockUserSvc,
+ listBlockedUsers,
+ REPORT_CATEGORIES
+} from '../services/safety.js';
+
+const SafetyReportInput = z.object({
+ category: z.enum(REPORT_CATEGORIES),
+ body: z.string().trim().min(10, 'Please provide at least 10 characters').max(3000, 'Must be under 3000 characters'),
+ eventId: z.string().uuid().optional().nullable().transform((v) => v || null),
+ reportedUserId: z.string().uuid().optional().nullable().transform((v) => v || null)
+}).strict();
+
+const BlockInput = z.object({
+ blockedUserId: z.string().uuid('Invalid user ID')
+}).strict();
+
+function uuid(v) {
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v || '')) {
+ throw new HttpError(400, 'invalid_id', 'Invalid user ID');
+ }
+ return v;
+}
+
+export async function submitReport(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`report:${user.id}`, 5, 3600);
+
+ const body = parse(SafetyReportInput, await readJson(ctx.req));
+ const report = await submitSafetyReport({
+ userId: user.id,
+ category: body.category,
+ body: body.body,
+ eventId: body.eventId,
+ reportedUserId: body.reportedUserId
+ });
+
+ sendJson(ctx.res, 201, {
+ ok: true,
+ reportId: report.id,
+ status: report.status,
+ message: 'Thank you. Your report has been submitted to moderators and will be reviewed confidentially.'
+ });
+}
+
+export async function listMyReports(ctx) {
+ const user = await requireUser(ctx.req);
+ const reports = await listUserReports(user.id);
+ sendJson(ctx.res, 200, { ok: true, reports });
+}
+
+export async function listBlocks(ctx) {
+ const user = await requireUser(ctx.req);
+ const blocks = await listBlockedUsers(user.id);
+ sendJson(ctx.res, 200, { ok: true, blocks });
+}
+
+export async function blockUser(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+ await rateLimit(`block:${user.id}`, 20, 3600);
+
+ const body = parse(BlockInput, await readJson(ctx.req));
+ await blockUserSvc({
+ blockerUserId: user.id,
+ blockedUserId: body.blockedUserId
+ });
+
+ sendJson(ctx.res, 200, { ok: true, message: 'User blocked' });
+}
+
+export async function unblockUser(ctx) {
+ const user = await requireUser(ctx.req);
+ requireCsrf(ctx.req, user);
+
+ const targetUserId = uuid(ctx.params.id);
+ await unblockUserSvc({
+ blockerUserId: user.id,
+ blockedUserId: targetUserId
+ });
+
+ sendJson(ctx.res, 200, { ok: true, message: 'User unblocked' });
+}
diff --git a/lib/handlers/saved-events.js b/lib/handlers/saved-events.js
new file mode 100644
index 0000000..2d57146
--- /dev/null
+++ b/lib/handlers/saved-events.js
@@ -0,0 +1,69 @@
+// lib/handlers/saved-events.js - HTTP handlers for attendee saved events / bookmarks.
+import { sendJson, readJson, HttpError } from '../http.js';
+import { requireUser, requireCsrf } from '../session.js';
+import { rateLimit } from '../ratelimit.js';
+import { saveEvent, unsaveEvent, listSavedEvents, listSavedEventIds, isEventSaved } from '../services/saved-events.js';
+
+export async function getMySavedEvents({ req, res }) {
+ const user = await requireUser(req);
+ const events = await listSavedEvents(user.id);
+ sendJson(res, 200, { ok: true, events });
+}
+
+export async function getMySavedEventIds({ req, res }) {
+ const user = await requireUser(req);
+ const savedIds = await listSavedEventIds(user.id);
+ sendJson(res, 200, { ok: true, savedIds });
+}
+
+export async function saveEventHandler({ req, res, params }) {
+ const user = await requireUser(req);
+ requireCsrf(req, user);
+ await rateLimit(`save:${user.id}`, 60, 60);
+
+ let eventId = params.id || params.eventId;
+ if (!eventId) {
+ const body = await readJson(req).catch(() => ({}));
+ eventId = body.eventId;
+ }
+ if (!eventId) throw new HttpError(400, 'missing_event_id', 'Event ID required');
+
+ const result = await saveEvent(user.id, eventId);
+ sendJson(res, 200, result);
+}
+
+export async function unsaveEventHandler({ req, res, params }) {
+ const user = await requireUser(req);
+ requireCsrf(req, user);
+ await rateLimit(`unsave:${user.id}`, 60, 60);
+
+ let eventId = params.id || params.eventId;
+ if (!eventId) {
+ const body = await readJson(req).catch(() => ({}));
+ eventId = body.eventId;
+ }
+ if (!eventId) throw new HttpError(400, 'missing_event_id', 'Event ID required');
+
+ const result = await unsaveEvent(user.id, eventId);
+ sendJson(res, 200, result);
+}
+
+export async function toggleSaveEventHandler({ req, res, params }) {
+ const user = await requireUser(req);
+ requireCsrf(req, user);
+ await rateLimit(`togglesave:${user.id}`, 60, 60);
+
+ let eventId = params.id || params.eventId;
+ if (!eventId) {
+ const body = await readJson(req).catch(() => ({}));
+ eventId = body.eventId;
+ }
+ if (!eventId) throw new HttpError(400, 'missing_event_id', 'Event ID required');
+
+ const currentlySaved = await isEventSaved(user.id, eventId);
+ const result = currentlySaved
+ ? await unsaveEvent(user.id, eventId)
+ : await saveEvent(user.id, eventId);
+
+ sendJson(res, 200, result);
+}
diff --git a/lib/handlers/superprofile.js b/lib/handlers/superprofile.js
new file mode 100644
index 0000000..0d2e336
--- /dev/null
+++ b/lib/handlers/superprofile.js
@@ -0,0 +1,52 @@
+// lib/handlers/superprofile.js - POST /api/webhooks/superprofile (alias: /api/membership/superprofile/webhook)
+//
+// SuperProfile has no signed webhooks; Zapier/Pabbly POST here with the shared secret in X-Webhook-Secret.
+// Order: secret check (401, before the body is read or any DB write) → rate limit → parse → apply.
+// Duplicate: 200 no-op. Processing error: 500 so the automation retries. The payload is never logged.
+import { readRawBody, sendJson, hashIp } from '../http.js';
+import { ticketProvider, WebhookSignatureError } from '../payments/index.js';
+import { superprofileConfigured } from '../payments/superprofile.js';
+import { rateLimit } from '../ratelimit.js';
+import { logger } from '../logger.js';
+import { WebhookBody, applySuperprofileEvent } from '../services/superprofile.js';
+import { applyOrderEvent, isTierProduct } from '../services/orders.js';
+import { deliverMany } from '../services/notifications.js';
+import { recordIntegrationError } from '../services/insights.js';
+import { afterResponse } from '../after.js';
+
+export async function superprofileWebhook({ req, res, ip }) {
+ if (!superprofileConfigured()) return sendJson(res, 503, { ok: false, error: 'not_configured' });
+ try {
+ ticketProvider().verifyWebhook(req.headers);
+ } catch (err) {
+ if (!(err instanceof WebhookSignatureError)) throw err;
+ logger.warn('superprofile webhook rejected: bad secret');
+ await rateLimit(`spbad:${hashIp(ip)}`, 30, 600); // slow down guessing of the shared secret
+ return sendJson(res, 401, { ok: false });
+ }
+ await rateLimit(`sp:${hashIp(ip)}`, 300, 60);
+ let body;
+ try { body = JSON.parse(await readRawBody(req, 32 * 1024)); } catch { return sendJson(res, 400, { ok: false, error: 'invalid_json' }); }
+ const p = WebhookBody.safeParse(body);
+ if (!p.success) return sendJson(res, 400, { ok: false, error: 'validation', fields: p.error.issues.map((i) => i.path.join('.')) });
+ const b = p.data;
+ try {
+ const orderShaped = ['purchase', 'refund', 'cancelled'].includes(b.event);
+ const membership = b.event === 'purchase' && await isTierProduct(b);
+ if (!orderShaped || membership) {
+ // Membership lifecycle (and abandoned checkouts) keep the counts-only flow.
+ if (b.event === 'refund' || b.event === 'cancelled') return sendJson(res, 200, { ok: true, result: 'ignored' });
+ const r = await applySuperprofileEvent(b);
+ logger.info('superprofile webhook processed', { event: b.event, result: r.result, tierMapped: r.tierMapped });
+ return sendJson(res, 200, { ok: true, ...r });
+ }
+ const r = await applyOrderEvent(b);
+ logger.info('superprofile order processed', { event: b.event, result: r.result });
+ await afterResponse(() => deliverMany(r.notificationIds));
+ sendJson(res, 200, { ok: true, result: r.result, tierMapped: false });
+ } catch (err) {
+ await recordIntegrationError('superprofile_webhook', 'processing_failed', String(err.code || err.message));
+ logger.error('superprofile webhook failed', err);
+ sendJson(res, 500, { ok: false });
+ }
+}
diff --git a/lib/handlers/upi-checkout.js b/lib/handlers/upi-checkout.js
new file mode 100644
index 0000000..430f9c7
--- /dev/null
+++ b/lib/handlers/upi-checkout.js
@@ -0,0 +1,188 @@
+// lib/handlers/upi-checkout.js - HTTP routes for UPI-first checkout, status polling, and PhonePe webhooks.
+import { sendJson, sendHtml, redirect, readRawBody, readJson, hashIp, HttpError } from '../http.js';
+import { getSessionUser } from '../session.js';
+import { rateLimit } from '../ratelimit.js';
+import { db } from '../db.js';
+import {
+ createUpiPaymentIntent,
+ getUpiPaymentStatus,
+ claimUpiBooking,
+ processUpiWebhook,
+ assertUpiCheckoutEnabled
+} from '../services/upi-payments.js';
+import { renderUpiCheckout } from '../views/checkout-upi.js';
+import { WebhookSignatureError } from '../upi/adapter.js';
+import { logger } from '../logger.js';
+
+function isMobileUserAgent(ua = '') {
+ return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
+}
+
+/**
+ * GET /checkout/:slug/upi - Renders the UPI-First interactive checkout view.
+ */
+export async function upiCheckoutPage({ req, res, params, query, ip }) {
+ assertUpiCheckoutEnabled(); // before rate limits and body reads: the route does not exist when off
+ const slug = params.slug;
+ if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(slug)) throw new HttpError(404, 'not_found', 'Event not found');
+
+ await rateLimit(`upi_page:${hashIp(ip)}`, 60, 600);
+ const user = await getSessionUser(req);
+ if (!user && query.get('guest') !== '1') {
+ const nextUrl = req.url || `/checkout/${slug}/upi`;
+ return redirect(res, `/signin?next=${encodeURIComponent(nextUrl)}`);
+ }
+
+ const ua = req.headers['user-agent'] || '';
+ const deviceType = isMobileUserAgent(ua) ? 'mobile' : 'desktop';
+
+ // Fetch event details
+ const event = await db.one(
+ `SELECT id, slug, title, city, status, start_at, capacity FROM events
+ WHERE slug = $1 AND status = 'published'`,
+ [slug]
+ );
+ if (!event) throw new HttpError(404, 'event_not_found', 'This event is not available');
+
+ // Determine tier
+ let tierId = query.get('tier') || query.get('ticket_type_id');
+ let tier;
+ if (tierId) {
+ tier = await db.one(
+ `SELECT id, name, kind, price_paise, max_per_booking FROM ticket_types
+ WHERE id = $1 AND event_id = $2 AND active`,
+ [tierId, event.id]
+ );
+ } else {
+ tier = await db.one(
+ `SELECT id, name, kind, price_paise, max_per_booking FROM ticket_types
+ WHERE event_id = $1 AND active AND kind = 'paid'
+ ORDER BY sort_order ASC, price_paise ASC LIMIT 1`,
+ [event.id]
+ );
+ }
+
+ if (!tier || tier.kind !== 'paid') {
+ throw new HttpError(404, 'ticket_not_found', 'No paid ticket tier available for checkout');
+ }
+
+ const qty = parseInt(query.get('qty') || query.get('quantity'), 10) || 1;
+
+ // Create payment intent
+ const order = await createUpiPaymentIntent({
+ slug,
+ user,
+ ticketTypeId: tier.id,
+ quantity: qty,
+ deviceType,
+ clientIp: ip
+ });
+
+ const html = renderUpiCheckout({
+ order,
+ event,
+ tier,
+ user
+ });
+
+ sendHtml(res, 200, html);
+}
+
+/**
+ * POST /api/checkout/upi/intent - Server API to create UPI payment intent.
+ */
+export async function createUpiIntentApi({ req, res, ip }) {
+ assertUpiCheckoutEnabled(); // before rate limits and body reads: the route does not exist when off
+ await rateLimit(`upi_intent:${hashIp(ip)}`, 30, 600);
+ const user = await getSessionUser(req);
+ const body = await readJson(req);
+
+ const slug = body.slug;
+ const ticketTypeId = body.ticketTypeId;
+ const quantity = body.quantity || 1;
+ const ua = req.headers['user-agent'] || '';
+ const deviceType = body.deviceType || (isMobileUserAgent(ua) ? 'mobile' : 'desktop');
+
+ if (!slug || !ticketTypeId) {
+ throw new HttpError(400, 'validation', 'slug and ticketTypeId are required');
+ }
+
+ const order = await createUpiPaymentIntent({
+ slug,
+ user,
+ ticketTypeId,
+ quantity,
+ deviceType,
+ clientIp: ip
+ });
+
+ sendJson(res, 200, { ok: true, ...order, order });
+}
+
+/**
+ * GET /api/checkout/upi/status/:orderId - Client polling endpoint.
+ */
+export async function getUpiStatusApi({ req, res, params, query, ip }) {
+ assertUpiCheckoutEnabled(); // before rate limits and body reads: the route does not exist when off
+ const orderId = params.id || params.orderid || params.orderId;
+ if (!orderId || !/^[A-Za-z0-9_-]{8,80}$/.test(orderId)) {
+ throw new HttpError(400, 'validation', 'Invalid order ID');
+ }
+
+ await rateLimit(`upi_poll:${hashIp(ip)}`, 180, 60);
+ const user = await getSessionUser(req);
+ const guestToken = query.get('token') || req.headers['x-guest-token'] || null;
+ const checkGateway = query.get('check') === '1';
+
+ const status = await getUpiPaymentStatus(orderId, { user, guestToken, checkGateway });
+ sendJson(res, 200, { ok: true, ...status });
+}
+
+/**
+ * POST /api/checkout/upi/claim - Allows an authenticated attendee to claim a guest booking.
+ */
+export async function claimUpiBookingApi({ req, res, ip }) {
+ assertUpiCheckoutEnabled(); // before rate limits and body reads: the route does not exist when off
+ await rateLimit(`upi_claim:${hashIp(ip)}`, 30, 600);
+ const user = await getSessionUser(req);
+ if (!user) {
+ throw new HttpError(401, 'unauthorized', 'Must be signed in to claim a booking');
+ }
+
+ const body = await readJson(req);
+ const orderId = body.orderId;
+ const guestToken = body.guestToken || req.headers['x-guest-token'];
+
+ if (!orderId || !guestToken) {
+ throw new HttpError(400, 'validation', 'orderId and guestToken are required');
+ }
+
+ const claim = await claimUpiBooking({ orderId, guestToken, user });
+ sendJson(res, 200, { ok: true, ...claim });
+}
+
+/**
+ * POST /api/payments/webhook/phonepe - Webhook receiver for PhonePe PG callbacks.
+ */
+export async function phonepeWebhook({ req, res, ip }) {
+ assertUpiCheckoutEnabled(); // before rate limits and body reads: the route does not exist when off
+ await rateLimit(`phonepe_hook:${hashIp(ip)}`, 300, 60);
+ const rawBody = await readRawBody(req, 64 * 1024);
+
+ try {
+ const result = await processUpiWebhook({
+ headers: req.headers,
+ rawBody,
+ clientIp: ip
+ });
+ sendJson(res, 200, result);
+ } catch (err) {
+ if (err instanceof WebhookSignatureError) {
+ logger.warn('PhonePe webhook rejected: bad signature');
+ await rateLimit(`phonepe_bad_sig:${hashIp(ip)}`, 20, 600);
+ return sendJson(res, 401, { ok: false, error: 'invalid_signature' });
+ }
+ logger.error('PhonePe webhook error', err);
+ sendJson(res, 500, { ok: false, error: 'processing_error' });
+ }
+}
diff --git a/lib/http.js b/lib/http.js
index 48632bb..8b3ea4e 100644
--- a/lib/http.js
+++ b/lib/http.js
@@ -54,8 +54,8 @@ export function readBinaryBody(req, limit) {
});
}
-export async function readJson(req) {
- const raw = await readRawBody(req);
+export async function readJson(req, limit = MAX_BODY_BYTES) {
+ const raw = await readRawBody(req, limit);
if (!raw) return {};
try {
const v = JSON.parse(raw);
@@ -101,9 +101,20 @@ export function appendHeader(res, name, value) {
}
export function clientIp(req) {
+ // On Vercel, x-vercel-forwarded-for is set by the edge network and cannot be spoofed by clients
+ const vercelIp = req.headers['x-vercel-forwarded-for'];
+ if (typeof vercelIp === 'string' && vercelIp.trim()) {
+ return vercelIp.split(',')[0].trim();
+ }
+ const realIp = req.headers['x-real-ip'];
+ if (typeof realIp === 'string' && realIp.trim()) {
+ return realIp.trim();
+ }
const xff = req.headers['x-forwarded-for'];
- if (typeof xff === 'string' && xff) return xff.split(',')[0].trim();
- return req.headers['x-real-ip'] || req.socket?.remoteAddress || 'unknown';
+ if (typeof xff === 'string' && xff.trim()) {
+ return xff.split(',')[0].trim();
+ }
+ return req.socket?.remoteAddress || 'unknown';
}
export function hashIp(ip) {
diff --git a/lib/pagination.js b/lib/pagination.js
new file mode 100644
index 0000000..40909f8
--- /dev/null
+++ b/lib/pagination.js
@@ -0,0 +1,13 @@
+// lib/pagination.js - Offset pagination for list endpoints: ?limit=1..100 (default 25) &offset=n.
+// Queries fetch limit + 1 rows so the response can say whether another page exists.
+
+export function page(query, { max = 100, def = 25 } = {}) {
+ const limit = Math.min(Math.max(parseInt(query?.get?.('limit') ?? '', 10) || def, 1), max);
+ const offset = Math.min(Math.max(parseInt(query?.get?.('offset') ?? '', 10) || 0, 0), 100_000);
+ return { limit, offset };
+}
+
+export function pageInfo(rows, p, key = 'items') {
+ const more = rows.length > p.limit;
+ return { [key]: more ? rows.slice(0, p.limit) : rows, page: { limit: p.limit, offset: p.offset, nextOffset: more ? p.offset + p.limit : null } };
+}
diff --git a/lib/payments/availability.js b/lib/payments/availability.js
index 0526884..840ce62 100644
--- a/lib/payments/availability.js
+++ b/lib/payments/availability.js
@@ -1,32 +1,44 @@
-// lib/payments/availability.js - Can guests pay for a paid ticket tier right now?
+// lib/payments/availability.js - Can a guest buy a paid ticket for this event right now?
//
-// Ticket inventory and booking logic never ask "which provider"; they ask this module whether a
-// hosted checkout is available and, if so, receive a PaymentProvider (see ./index.js). Adding a
-// future approved provider means adding an adapter there — not touching tiers or bookings.
-//
-// Paid checkout for organiser tiers is OFF unless the owner explicitly opts in with
-// TICKET_CHECKOUT_ENABLED=true AND the selected provider's keys are present. There is no manual
-// UPI or pay-at-venue flow: nothing here can mark a payment as paid. Payments only become `paid`
-// from a signature-verified provider webhook or server-side reconciliation (services/bookings.js).
-import { env, configStatus } from '../config.js';
-import { ticketProvider } from './index.js';
+// A paid ticket is bookable only when the event is linked to a SuperProfile product
+// (checkout_mode = 'superprofile' and a superprofile_url). Linking is an admin action, so events
+// created in the organiser wizard cannot take payments until an admin links a product. Nothing here
+// can mark a payment as paid: bookings are confirmed only by a matched SuperProfile notification.
-export function ticketCheckoutStatus() {
- if (env('TICKET_CHECKOUT_ENABLED', 'false') !== 'true') {
- return {
- available: false,
- reason: 'not_enabled',
- message: 'Online payment for paid tickets is not available yet. You can set up paid tiers and save them; guests can only book free tiers until a payment method is approved and configured.'
- };
+import { livePayments, upiCheckoutEnabled } from '../config.js';
+
+// Paid checkout stays off in Preview unless an approved test mode is explicitly enabled.
+const PREVIEW_BLOCKED = Object.freeze({ available: false, reason: 'preview_paid_checkout_disabled', message: 'Paid checkout is disabled in Preview deployments.' });
+function previewPaidCheckoutBlocked() {
+ return process.env.VERCEL_ENV === 'preview' && process.env.ALLOW_PREVIEW_PAID_CHECKOUT !== 'true';
+}
+
+/** Per-event checkout availability. `row` is an events row (or anything with the same columns). */
+export function checkoutForEvent(row) {
+ // UPI/PhonePe events are gated by UPI_CHECKOUT_ENABLED alone; ENABLE_LIVE_PAYMENTS never opens them.
+ if (row?.checkout_mode === 'upi_direct') {
+ if (!upiCheckoutEnabled()) {
+ return { available: false, reason: 'upi_checkout_disabled', message: 'Paid ticket checkout is currently disabled.' };
+ }
+ if (previewPaidCheckoutBlocked()) return PREVIEW_BLOCKED;
+ return { available: true, reason: 'upi_direct', provider: 'phonepe', message: '' };
}
- const status = configStatus();
- if (status.paymentKeys !== 'configured') {
- return { available: false, reason: 'not_configured', message: 'Paid checkout is enabled but the payment provider is not configured, so paid tiers cannot be booked.' };
+ // ENABLE_LIVE_PAYMENTS gates only the SuperProfile hosted link-out.
+ if (!livePayments()) {
+ return { available: false, reason: 'live_payments_disabled', message: 'Paid ticket checkout is currently disabled.' };
}
- return { available: true, reason: 'configured', provider: status.paymentProvider, testMode: !status.livePayments, message: '' };
+ if (previewPaidCheckoutBlocked()) return PREVIEW_BLOCKED;
+ const available = row?.checkout_mode === 'superprofile' && Boolean(row?.superprofile_url);
+ return available
+ ? { available: true, reason: 'superprofile', provider: 'superprofile_link', message: '' }
+ : { available: false, reason: 'no_superprofile_product', message: 'Online booking is not available for this event yet.' };
}
-/** The provider to charge with, or null when paid checkout is unavailable. */
-export function ticketCheckoutProvider() {
- return ticketCheckoutStatus().available ? ticketProvider() : null;
+/** Status used by the organiser wizard, which has no SuperProfile product to attach. */
+export function ticketCheckoutStatus() {
+ return {
+ available: false,
+ reason: 'admin_link_required',
+ message: 'Paid tickets are bought on SuperProfile and need a product linked by the NIGHTLIFEZ team. Until then guests can only book free tickets.'
+ };
}
diff --git a/lib/payments/cashfree.js b/lib/payments/cashfree.js
deleted file mode 100644
index f515d6c..0000000
--- a/lib/payments/cashfree.js
+++ /dev/null
@@ -1,88 +0,0 @@
-// lib/payments/cashfree.js - Cashfree PG Orders adapter (alternative provider behind the same
-// interface). Webhook signature: base64(HMAC-SHA256(timestamp + rawBody, client secret)).
-import crypto from 'node:crypto';
-import { env } from '../config.js';
-import { HttpError, safeEqual } from '../http.js';
-
-const API_VERSION = '2025-01-01';
-
-export function cashfree({ live }) {
- const appId = env('CASHFREE_APP_ID');
- const secret = env('CASHFREE_SECRET_KEY');
- const base = live ? 'https://api.cashfree.com/pg' : 'https://sandbox.cashfree.com/pg';
-
- async function call(method, path, body) {
- if (!appId || !secret) throw new HttpError(503, 'not_configured', 'Ticket payments are not configured yet');
- let res;
- try {
- res = await fetch(`${base}${path}`, {
- method,
- headers: {
- 'x-client-id': appId, 'x-client-secret': secret, 'x-api-version': API_VERSION,
- ...(body ? { 'Content-Type': 'application/json' } : {})
- },
- body: body ? JSON.stringify(body) : undefined,
- signal: AbortSignal.timeout(10_000)
- });
- } catch {
- throw Object.assign(new Error('cashfree network error'), { code: 'PROVIDER_ERROR', status: 502 });
- }
- const data = await res.json().catch(() => ({}));
- if (!res.ok) throw Object.assign(new Error(`cashfree ${path} ${res.status} ${String(data.message || '').slice(0, 160)}`), { code: 'PROVIDER_ERROR', status: 502 });
- return data;
- }
-
- return {
- name: 'cashfree',
- isTest: !live,
-
- async createCheckout() {
- // Cashfree requires customer_phone on Orders and Payment Links, and its hosted checkout opens
- // only via the JS SDK. We do not collect phone numbers, so this adapter does not create
- // checkouts until the owner decides otherwise (docs/PAYMENTS_DECISION.md). Webhook
- // verification, refunds and status lookups below are implemented for that switch.
- throw new HttpError(503, 'not_configured', 'Cashfree checkout is not enabled (customer phone required)');
- },
-
- verifyWebhook(headers, rawBody) {
- const sig = headers['x-webhook-signature'];
- const ts = headers['x-webhook-timestamp'];
- if (typeof sig !== 'string' || typeof ts !== 'string' || !secret) throw Object.assign(new Error('missing signature'), { code: 'WEBHOOK_SIGNATURE' });
- const expected = crypto.createHmac('sha256', secret).update(ts + rawBody).digest('base64');
- if (!safeEqual(sig, expected)) throw Object.assign(new Error('bad signature'), { code: 'WEBHOOK_SIGNATURE' });
- if (Math.abs(Date.now() - Number(ts)) > 15 * 60_000 && Math.abs(Date.now() / 1000 - Number(ts)) > 15 * 60) {
- throw Object.assign(new Error('stale webhook'), { code: 'WEBHOOK_SIGNATURE' });
- }
- const body = JSON.parse(rawBody);
- const order = body.data?.order;
- const pay = body.data?.payment;
- const eventId = `${body.type}:${pay?.cf_payment_id || order?.order_id}`;
- switch (body.type) {
- case 'PAYMENT_SUCCESS_WEBHOOK':
- return { eventId, type: 'paid', providerTxnId: order?.order_id, providerPaymentId: String(pay?.cf_payment_id || ''), amountPaise: Math.round(Number(pay?.payment_amount) * 100), currency: pay?.payment_currency || order?.order_currency };
- case 'PAYMENT_FAILED_WEBHOOK':
- case 'PAYMENT_USER_DROPPED_WEBHOOK':
- return { eventId, type: 'failed', providerTxnId: order?.order_id, reason: String(pay?.payment_message || body.type).slice(0, 200) };
- case 'REFUND_STATUS_WEBHOOK':
- return body.data?.refund?.refund_status === 'SUCCESS'
- ? { eventId: `refund:${body.data.refund.refund_id}`, type: 'refunded', providerTxnId: body.data.refund.order_id, amountPaise: Math.round(Number(body.data.refund.refund_amount) * 100) }
- : { eventId, type: 'ignored' };
- default:
- return { eventId, type: 'ignored' };
- }
- },
-
- async refund({ providerTxnId, amountPaise, refundRef }) {
- const r = await call('POST', `/orders/${encodeURIComponent(providerTxnId)}/refunds`, {
- refund_amount: Number((amountPaise / 100).toFixed(2)), refund_id: String(refundRef).slice(0, 40)
- });
- return { refundId: r.refund_id || r.cf_refund_id, status: r.refund_status };
- },
-
- async fetchStatus(providerTxnId) {
- const o = await call('GET', `/orders/${encodeURIComponent(providerTxnId)}`);
- const map = { PAID: 'paid', ACTIVE: 'created', EXPIRED: 'expired', TERMINATED: 'expired' };
- return { status: map[o.order_status] || 'created', amountPaise: Math.round(Number(o.order_amount) * 100) };
- }
- };
-}
diff --git a/lib/payments/index.js b/lib/payments/index.js
index 4049c96..dba3d92 100644
--- a/lib/payments/index.js
+++ b/lib/payments/index.js
@@ -1,35 +1,17 @@
-// lib/payments/index.js - PaymentProvider selection.
+// lib/payments/index.js - Ticket payments go through one provider, `superprofile_link` (hosted checkout).
//
// interface PaymentProvider {
-// name: 'razorpay' | 'cashfree'
-// isTest: boolean
-// createCheckout({ bookingId, amountPaise, title, expiresAt, returnUrl }) -> { providerTxnId, checkoutUrl }
-// verifyWebhook(headers, rawBody) -> WebhookEvent (throws WebhookSignatureError)
-// refund({ providerTxnId, providerPaymentId, amountPaise, refundRef }) -> { refundId, status }
-// fetchStatus(providerTxnId) -> { status: 'created'|'paid'|'failed'|'expired', providerPaymentId?, amountPaise? }
+// name: 'superprofile_link'
+// createCheckout({ url, ref, slug }) -> { providerTxnId, checkoutUrl }
+// verifyWebhook(headers) -> true (throws WebhookSignatureError)
+// refund() -> throws NOT_SUPPORTED_IN_APP (refunds happen on SuperProfile)
// }
-// WebhookEvent = { eventId, type: 'paid'|'failed'|'expired'|'refunded'|'ignored', providerTxnId, providerPaymentId?, amountPaise?, reason? }
-import { env, livePayments } from '../config.js';
-import { HttpError } from '../http.js';
-import { razorpay } from './razorpay.js';
-import { cashfree } from './cashfree.js';
+// Membership via Telegram Stars is separate (services/membership.js): Stars is the only way to sell
+// digital goods inside Telegram.
+import { superprofileLink } from './superprofile.js';
-export class WebhookSignatureError extends Error {
- constructor(msg = 'invalid webhook signature') {
- super(msg);
- this.code = 'WEBHOOK_SIGNATURE';
- }
-}
-
-const PROVIDERS = { razorpay, cashfree };
-
-export function providerByName(name) {
- const factory = PROVIDERS[name];
- if (!factory) throw new HttpError(404, 'unknown_provider', 'Unknown payment provider');
- return factory({ live: livePayments() });
-}
+export { WebhookSignatureError, isSuperprofileUrl, withCheckoutRef } from './superprofile.js';
-/** The configured ticket provider. Refuses mismatched live/test keys. */
export function ticketProvider() {
- return providerByName(env('PAYMENT_PROVIDER', 'razorpay'));
+ return superprofileLink;
}
diff --git a/lib/payments/razorpay.js b/lib/payments/razorpay.js
deleted file mode 100644
index 5e4537e..0000000
--- a/lib/payments/razorpay.js
+++ /dev/null
@@ -1,115 +0,0 @@
-// lib/payments/razorpay.js - Razorpay Payment Links (hosted checkout) adapter.
-// Docs: https://razorpay.com/docs/api/payments/payment-links/ , webhooks: HMAC-SHA256(raw body) hex
-// in X-Razorpay-Signature; event id in X-Razorpay-Event-Id.
-import crypto from 'node:crypto';
-import { env } from '../config.js';
-import { HttpError, safeEqual } from '../http.js';
-
-const API = 'https://api.razorpay.com/v1';
-
-class ProviderError extends Error {
- constructor(op, status, description) {
- super(`razorpay ${op} failed: ${status} ${description}`);
- this.code = 'PROVIDER_ERROR';
- this.status = 502;
- }
-}
-
-export function razorpay({ live }) {
- const keyId = env('RAZORPAY_KEY_ID');
- const keySecret = env('RAZORPAY_KEY_SECRET');
- const webhookSecret = env('RAZORPAY_WEBHOOK_SECRET');
-
- function assertKeys() {
- if (!keyId || !keySecret) throw new HttpError(503, 'not_configured', 'Ticket payments are not configured yet');
- const isTestKey = keyId.startsWith('rzp_test_');
- if (!live && !isTestKey) throw new HttpError(503, 'not_configured', 'Live keys are set while ENABLE_LIVE_PAYMENTS=false; refusing to charge');
- if (live && isTestKey) throw new HttpError(503, 'not_configured', 'Test keys are set while ENABLE_LIVE_PAYMENTS=true');
- }
-
- async function call(method, path, body) {
- assertKeys();
- let res;
- try {
- res = await fetch(`${API}${path}`, {
- method,
- headers: {
- Authorization: `Basic ${Buffer.from(`${keyId}:${keySecret}`).toString('base64')}`,
- ...(body ? { 'Content-Type': 'application/json' } : {})
- },
- body: body ? JSON.stringify(body) : undefined,
- signal: AbortSignal.timeout(10_000)
- });
- } catch (err) {
- throw new ProviderError(path, 0, err.name === 'TimeoutError' ? 'timeout' : 'network');
- }
- const data = await res.json().catch(() => ({}));
- if (!res.ok) throw new ProviderError(path, res.status, String(data?.error?.description || '').slice(0, 160));
- return data;
- }
-
- return {
- name: 'razorpay',
- isTest: !live,
-
- async createCheckout({ bookingId, amountPaise, title, expiresAt, returnUrl }) {
- // Razorpay requires expire_by to be at least ~15 minutes in the future.
- const expireBy = Math.max(Math.floor(new Date(expiresAt).getTime() / 1000), Math.floor(Date.now() / 1000) + 16 * 60);
- const link = await call('POST', '/payment_links', {
- amount: amountPaise,
- currency: 'INR',
- accept_partial: false,
- description: title.slice(0, 2048),
- reference_id: bookingId.replace(/-/g, '').slice(0, 40),
- expire_by: expireBy,
- reminder_enable: false,
- notify: { sms: false, email: false },
- notes: { booking_id: bookingId },
- callback_url: returnUrl,
- callback_method: 'get'
- });
- return { providerTxnId: link.id, checkoutUrl: link.short_url };
- },
-
- verifyWebhook(headers, rawBody) {
- const sig = headers['x-razorpay-signature'];
- if (!webhookSecret || typeof sig !== 'string') throw Object.assign(new Error('missing signature'), { code: 'WEBHOOK_SIGNATURE' });
- const expected = crypto.createHmac('sha256', webhookSecret).update(rawBody).digest('hex');
- if (!safeEqual(sig, expected)) throw Object.assign(new Error('bad signature'), { code: 'WEBHOOK_SIGNATURE' });
- const body = JSON.parse(rawBody);
- const eventId = headers['x-razorpay-event-id'] || `${body.event}:${body.payload?.payment?.entity?.id || body.payload?.payment_link?.entity?.id || body.payload?.refund?.entity?.id}`;
- const linkEntity = body.payload?.payment_link?.entity;
- const pay = body.payload?.payment?.entity;
- const refund = body.payload?.refund?.entity;
- switch (body.event) {
- case 'payment_link.paid':
- return { eventId, type: 'paid', providerTxnId: linkEntity?.id, providerPaymentId: pay?.id, amountPaise: pay?.amount ?? linkEntity?.amount_paid, currency: pay?.currency || linkEntity?.currency };
- case 'payment_link.expired':
- case 'payment_link.cancelled':
- return { eventId, type: 'expired', providerTxnId: linkEntity?.id };
- case 'payment.failed':
- // Payment-link payments carry the link id in notes only when present; match via booking note.
- return { eventId, type: 'failed', providerTxnId: linkEntity?.id || null, bookingId: pay?.notes?.booking_id || null, reason: String(pay?.error_description || 'failed').slice(0, 200) };
- case 'refund.processed':
- return { eventId, type: 'refunded', providerPaymentId: refund?.payment_id, amountPaise: refund?.amount };
- default:
- return { eventId, type: 'ignored' };
- }
- },
-
- async refund({ providerPaymentId, amountPaise, refundRef }) {
- if (!providerPaymentId) throw new HttpError(409, 'no_payment_id', 'No captured payment id to refund');
- const r = await call('POST', `/payments/${encodeURIComponent(providerPaymentId)}/refund`, {
- amount: amountPaise, speed: 'normal', receipt: String(refundRef).slice(0, 40)
- });
- return { refundId: r.id, status: r.status };
- },
-
- async fetchStatus(providerTxnId) {
- const link = await call('GET', `/payment_links/${encodeURIComponent(providerTxnId)}`);
- const paid = (link.payments || []).find((p) => p.status === 'captured');
- const map = { paid: 'paid', expired: 'expired', cancelled: 'expired', created: 'created', partially_paid: 'created' };
- return { status: map[link.status] || 'created', providerPaymentId: paid?.payment_id || paid?.id || null, amountPaise: paid?.amount ?? link.amount_paid };
- }
- };
-}
diff --git a/lib/payments/superprofile.js b/lib/payments/superprofile.js
new file mode 100644
index 0000000..6486ddb
--- /dev/null
+++ b/lib/payments/superprofile.js
@@ -0,0 +1,65 @@
+// lib/payments/superprofile.js - The one PaymentProvider: `superprofile_link`.
+//
+// Buyers pay on a SuperProfile-hosted page; this site never sees card or UPI details. So:
+// createCheckout → returns the SuperProfile URL (with our ref attached), nothing is charged here
+// verifyWebhook → shared-secret check (constant time) before anything is parsed or written
+// refund → NOT_SUPPORTED_IN_APP: refunds are issued on SuperProfile, then arrive as a notification
+import { env } from '../config.js';
+import { HttpError, safeEqual } from '../http.js';
+
+export const SUPERPROFILE_SECRET_HEADER = 'x-webhook-secret';
+export const PROVIDER_NAME = 'superprofile_link';
+
+/** https, no credentials, host is superprofile.bio or a subdomain of it. Rejects look-alike hosts. */
+export function isSuperprofileUrl(value) {
+ let u;
+ try { u = new URL(String(value)); } catch { return false; }
+ if (u.protocol !== 'https:' || u.username || u.password) return false;
+ if (u.port && u.port !== '443') return false;
+ const host = u.hostname.toLowerCase();
+ return host === 'superprofile.bio' || host.endsWith('.superprofile.bio');
+}
+
+export class WebhookSignatureError extends Error {
+ constructor(msg = 'invalid webhook secret') {
+ super(msg);
+ this.code = 'WEBHOOK_SIGNATURE';
+ }
+}
+
+export function superprofileConfigured() {
+ return env('SUPERPROFILE_WEBHOOK_SECRET').length >= 24;
+}
+
+/** The SuperProfile URL with our ref carried as query params (SuperProfile may echo them in notifications). */
+export function withCheckoutRef(url, { ref, slug }) {
+ if (!isSuperprofileUrl(url)) throw new HttpError(409, 'checkout_unavailable', 'Checkout is not available for this event');
+ const u = new URL(url);
+ u.searchParams.set('ref', ref);
+ u.searchParams.set('utm_source', 'strangersmeetup');
+ u.searchParams.set('utm_medium', 'site');
+ u.searchParams.set('utm_campaign', slug);
+ u.searchParams.set('utm_content', ref);
+ return u.toString();
+}
+
+export const superprofileLink = {
+ name: PROVIDER_NAME,
+ isTest: false,
+
+ async createCheckout({ url, ref, slug }) {
+ return { providerTxnId: ref, checkoutUrl: withCheckoutRef(url, { ref, slug }) };
+ },
+
+ /** Throws WebhookSignatureError; call before parsing the body or touching the database. */
+ verifyWebhook(headers) {
+ const expected = env('SUPERPROFILE_WEBHOOK_SECRET');
+ const got = headers[SUPERPROFILE_SECRET_HEADER];
+ if (expected.length < 24 || typeof got !== 'string' || !safeEqual(got, expected)) throw new WebhookSignatureError();
+ return true;
+ },
+
+ async refund() {
+ throw new HttpError(501, 'NOT_SUPPORTED_IN_APP', 'Refunds for tickets are issued on SuperProfile. The booking updates when SuperProfile reports the refund.');
+ }
+};
diff --git a/lib/router.js b/lib/router.js
index e12e3bc..a683ea2 100644
--- a/lib/router.js
+++ b/lib/router.js
@@ -34,12 +34,16 @@ const ROUTES = [
['GET', '/signin', h('pages', 'memberPage')],
['GET', '/me', h('pages', 'memberPage')],
['GET', '/bookings/:id', h('pages', 'bookingPage')],
+ ['GET', '/checkout/:slug', h('checkout', 'checkoutRedirect')],
+ ['GET', '/checkout/:slug/upi', h('upi-checkout', 'upiCheckoutPage')],
['GET', '/admin', h('admin', 'adminPage')],
['GET', '/admin/preview/:id', h('admin', 'adminPreview')],
['GET', '/organiser', h('organiser', 'dashboardPage')],
['GET', '/organiser/new', h('organiser', 'wizardPage')],
['GET', '/organiser/drafts/:id/preview', h('organiser', 'draftPreviewPage')],
['GET', '/organiser/events/:id', h('organiser', 'managePage')],
+ ['GET', '/organiser/events/:id/scan', h('organiser', 'scanPage')],
+ ['GET', '/staff/join', h('organiser', 'staffJoinPage')],
['GET', '/media/event-images/:id', h('organiser', 'serveImage')],
['GET', '/auth/telegram/start', h('auth', 'oidcStart')],
['GET', '/auth/telegram/callback', h('auth', 'oidcCallback')],
@@ -49,24 +53,63 @@ const ROUTES = [
// Public API
['GET', '/api/health', h('health', 'health')],
['GET', '/api/events', h('pages', 'eventsApi')],
+ ['GET', '/api/discovery/feed', h('discovery', 'discoveryFeedApi')],
+ ['GET', '/api/events/nearby', h('locations', 'nearbyEventsHandler')],
+ ['GET', '/api/locations/states', h('locations', 'listStatesHandler')],
+ ['GET', '/api/locations/districts', h('locations', 'listDistrictsHandler')],
+ ['GET', '/api/locations/cities', h('locations', 'listCitiesHandler')],
+ ['GET', '/api/locations/cities/:slug', h('locations', 'getCityHandler')],
+ ['GET', '/api/locations/localities', h('locations', 'listLocalitiesHandler')],
['POST', '/api/leads/:type', h('leads', 'submitLead')],
['POST', '/api/events/submit', h('discovery', 'submitEvent')],
['POST', '/api/analytics', h('leads', 'trackEvent')],
// Auth & member
['POST', '/api/auth/telegram', h('auth', 'telegramAuth')],
+ ['POST', '/api/auth/telegram/link-token', h('auth', 'createTelegramLinkToken')],
+ ['GET', '/api/auth/telegram/link-status', h('auth', 'getTelegramLinkStatus')],
['POST', '/api/auth/dev', h('auth', 'devAuth')],
+ ['POST', '/api/auth/preview-reviewer', h('auth', 'previewReviewerAuth')],
['POST', '/api/auth/logout', h('auth', 'logout')],
['POST', '/api/auth/logout-all', h('auth', 'logoutAll')],
['POST', '/api/auth/confirm-age', h('auth', 'confirmAge')],
['GET', '/api/me', h('auth', 'me')],
['GET', '/api/me/bookings', h('bookings', 'myBookings')],
+ ['POST', '/api/me/bookings/:id/cancel', h('bookings', 'cancelMyBooking')],
+ ['GET', '/api/me/announcements', h('bookings', 'myAnnouncements')],
+ ['GET', '/api/me/saved-events', h('saved-events', 'getMySavedEvents')],
+ ['GET', '/api/me/saved-event-ids', h('saved-events', 'getMySavedEventIds')],
+ ['POST', '/api/me/saved-events', h('saved-events', 'saveEventHandler')],
+ ['DELETE', '/api/me/saved-events/:id', h('saved-events', 'unsaveEventHandler')],
+ ['POST', '/api/events/:id/save', h('saved-events', 'saveEventHandler')],
+ ['DELETE', '/api/events/:id/save', h('saved-events', 'unsaveEventHandler')],
+ ['POST', '/api/events/:id/toggle-save', h('saved-events', 'toggleSaveEventHandler')],
['GET', '/api/me/profile', h('profile', 'getProfile')],
['PATCH', '/api/me/profile', h('profile', 'updateProfile')],
- ['POST', '/api/bookings', h('bookings', 'createBooking')],
+ ['GET', '/api/me/notification-preferences', h('auth', 'getMyNotificationPreferences')],
+ ['PATCH', '/api/me/notification-preferences', h('auth', 'updateMyNotificationPreferences')],
+ ['GET', '/api/me/reports', h('safety', 'listMyReports')],
+ ['POST', '/api/reports', h('safety', 'submitReport')],
+ ['GET', '/api/me/blocks', h('safety', 'listBlocks')],
+ ['POST', '/api/me/blocks', h('safety', 'blockUser')],
+ ['DELETE', '/api/me/blocks/:id', h('safety', 'unblockUser')],
['GET', '/api/bookings/:id', h('bookings', 'getBooking')],
+ ['POST', '/api/bookings/:id/cancel', h('bookings', 'cancelMyBooking')],
['POST', '/api/membership/checkout', h('membership', 'membershipCheckout')],
['POST', '/api/events/:id/book', h('organiser', 'bookTicket')],
+ ['POST', '/api/checkout/upi/intent', h('upi-checkout', 'createUpiIntentApi')],
+ ['GET', '/api/checkout/upi/status/:id', h('upi-checkout', 'getUpiStatusApi')],
+ ['POST', '/api/checkout/upi/claim', h('upi-checkout', 'claimUpiBookingApi')],
+
+ // Organisations, members, venues (session + can(); outsiders get 404)
+ ['GET', '/api/me/orgs', h('orgs', 'myOrgs')],
+ ['GET', '/api/orgs/:id', h('orgs', 'getOrg')],
+ ['GET', '/api/orgs/:id/members', h('orgs', 'listMembers')],
+ ['POST', '/api/orgs/:id/members', h('orgs', 'addMember')],
+ ['PATCH', '/api/orgs/:id/members/:member', h('orgs', 'updateMember')],
+ ['GET', '/api/orgs/:id/venues', h('orgs', 'listVenues')],
+ ['POST', '/api/orgs/:id/venues', h('orgs', 'createVenue')],
+ ['PATCH', '/api/venues/:id', h('orgs', 'updateVenue')],
// Organiser (session + organiser access; drafts and events are owner-scoped)
['GET', '/api/organiser/context', h('organiser', 'context')],
@@ -80,14 +123,37 @@ const ROUTES = [
['POST', '/api/organiser/drafts/:id/images', h('organiser', 'uploadImage')],
['DELETE', '/api/organiser/drafts/:id/images/:image', h('organiser', 'deleteImage')],
['GET', '/api/organiser/events', h('organiser', 'listEvents')],
+ ['GET', '/api/organiser/events/:id/overview', h('organiser', 'eventOverview')],
+ ['PUT', '/api/organiser/events/:id', h('organiser', 'updateEvent')],
+ ['POST', '/api/organiser/events/:id/cancel', h('organiser', 'cancelEvent')],
+ ['GET', '/api/organiser/events/:id/inventory', h('organiser', 'eventInventory')],
+ ['GET', '/api/organiser/events/:id/bookings', h('organiser', 'eventBookings')],
['GET', '/api/organiser/events/:id/guests', h('organiser', 'eventGuests')],
['POST', '/api/organiser/bookings/:id/approve', h('organiser', 'approveBooking')],
['POST', '/api/organiser/bookings/:id/decline', h('organiser', 'declineBooking')],
+ ['POST', '/api/organiser/bookings/:id/cancel', h('organiser', 'cancelBooking')],
+ ['GET', '/api/organiser/events/:id/staff', h('organiser', 'eventStaff')],
+ ['POST', '/api/organiser/events/:id/staff', h('organiser', 'assignStaff')],
+ ['DELETE', '/api/organiser/events/:id/staff/:staffId', h('organiser', 'revokeStaff')],
+ ['POST', '/api/organiser/events/:id/staff/invite', h('organiser', 'inviteStaff')],
+ ['GET', '/api/staff/invite/:token', h('organiser', 'getStaffInviteHandler')],
+ ['POST', '/api/staff/accept-invite', h('organiser', 'acceptStaffInviteHandler')],
+ ['GET', '/api/organiser/events/:id/announcements', h('organiser', 'eventAnnouncements')],
+ ['POST', '/api/organiser/events/:id/announcements', h('organiser', 'postAnnouncement')],
+ ['POST', '/api/organiser/events/:id/check-in', h('organiser', 'checkInTicketHandler')],
+ ['GET', '/api/organiser/events/:id/scans', h('organiser', 'eventScans')],
+ ['GET', '/api/organiser/events/:id/attendance', h('organiser', 'eventAttendance')],
+ ['POST', '/api/organiser/tickets/:id/reissue', h('organiser', 'reissueTicketHandler')],
+ ['POST', '/api/organiser/tickets/:id/revoke', h('organiser', 'revokeTicketHandler')],
+ ['GET', '/api/me/bookings/:id/ticket', h('organiser', 'guestTicket')],
// Webhooks
['POST', '/api/telegram/webhook', h('telegram', 'telegramWebhook')],
- ['POST', '/api/payments/webhook/:provider', h('payments', 'paymentWebhook')],
- ['POST', '/api/membership/superprofile/webhook', h('membership', 'superprofileWebhook')],
+ ['POST', '/api/webhooks/superprofile', h('superprofile', 'superprofileWebhook')],
+ ['POST', '/api/membership/superprofile/webhook', h('superprofile', 'superprofileWebhook')],
+ ['POST', '/api/payments/webhook/phonepe', h('upi-checkout', 'phonepeWebhook')],
+
+ ['POST', '/api/reconcile/superprofile', h('cron', 'reconcileSuperprofile')],
// Cron (Vercel Cron sends GET with Authorization: Bearer CRON_SECRET)
['GET', '/api/cron/:job', h('cron', 'runCron')],
@@ -113,12 +179,16 @@ const ROUTES = [
['GET', '/api/admin/events/:id/attendees', h('admin', 'attendees')],
['POST', '/api/admin/bookings/:id/check-in', h('admin', 'checkIn')],
['GET', '/api/admin/bookings', h('admin', 'listBookings')],
+ ['GET', '/api/admin/orders', h('admin', 'listOrders')],
+ ['POST', '/api/admin/orders/:id/link', h('admin', 'linkOrder')],
['POST', '/api/admin/payments/:id/refund', h('admin', 'refundPayment')],
['GET', '/api/admin/memberships', h('admin', 'listMemberships')],
['POST', '/api/admin/entitlements/:id/revoke', h('admin', 'revokeEntitlement')],
['GET', '/api/admin/leads', h('admin', 'listLeads')],
['PATCH', '/api/admin/leads/:id', h('admin', 'updateLead')],
['PATCH', '/api/admin/reports/:id', h('admin', 'updateReport')],
+ ['GET', '/api/admin/notifications', h('admin', 'listNotifications')],
+ ['POST', '/api/admin/notifications/:id/retry', h('admin', 'retryNotification')],
['GET', '/api/admin/media', h('admin', 'listMedia')],
['POST', '/api/admin/media', h('admin', 'createMedia')],
['PATCH', '/api/admin/media/:id', h('admin', 'updateMedia')],
@@ -128,12 +198,15 @@ const ROUTES = [
['POST', '/api/admin/admins', h('admin', 'upsertAdmin')],
['GET', '/api/admin/audit', h('admin', 'listAudit')],
['GET', '/api/admin/organisers', h('admin', 'listOrganisers')],
- ['POST', '/api/admin/organisers', h('admin', 'setOrganiser')]
+ ['POST', '/api/admin/organisers', h('admin', 'setOrganiser')],
+ ['GET', '/api/admin/orgs', h('admin', 'listOrgs')],
+ ['POST', '/api/admin/orgs', h('admin', 'createOrg')],
+ ['PATCH', '/api/admin/orgs/:id', h('admin', 'updateOrg')]
];
const COMPILED = ROUTES.map(([method, pattern, load]) => {
const keys = [];
- const re = new RegExp(`^${pattern.replace(/\/:([a-z]+)/g, (_, k) => { keys.push(k); return '/([^/]+)'; })}/?$`);
+ const re = new RegExp(`^${pattern.replace(/\/:([a-zA-Z0-9_]+)/g, (_, k) => { keys.push(k); return '/([^/]+)'; })}/?$`);
return { method, pattern, re, keys, load };
});
@@ -174,7 +247,7 @@ export async function handle(req, res) {
const fn = await m.route.load();
await fn(ctx);
} catch (err) {
- const status = err instanceof HttpError ? err.status : err.code === 'DB_NOT_CONFIGURED' ? 503 : 500;
+ const status = err instanceof HttpError ? err.status : (err.code === 'DB_NOT_CONFIGURED' || err.code === 'PREVIEW_DB_WRITE_BLOCKED') ? 503 : 500;
if (status >= 500) logger.error('request failed', err, { path: pathname, method: req.method });
if (res.headersSent) { res.end(); return; }
if (err.extra?.retryAfter) res.setHeader('Retry-After', String(err.extra.retryAfter));
@@ -183,8 +256,7 @@ export async function handle(req, res) {
sendHtml(res, status, status === 404 ? renderNotFound() : renderError());
} else {
const safe = err instanceof HttpError
- ? { ok: false, error: err.code, message: err.message, ...(err.extra?.fields ? { fields: err.extra.fields } : {}),
- ...(err.extra?.issues ? { issues: err.extra.issues } : {}), ...(err.extra?.draft ? { draft: err.extra.draft } : {}) }
+ ? { ok: false, error: err.code, message: err.message, ...(err.extra || {}) }
: { ok: false, error: status === 503 ? 'not_configured' : 'internal', message: status === 503 ? 'Service not configured yet' : 'Something went wrong' };
sendJson(res, status, safe);
}
diff --git a/lib/services/bookings.js b/lib/services/bookings.js
index 5e5ac95..0e28e25 100644
--- a/lib/services/bookings.js
+++ b/lib/services/bookings.js
@@ -1,14 +1,12 @@
-// lib/services/bookings.js - Ticket booking state machine. The only paths to `confirmed` are
-// applyTicketEvent() (verified webhook or server-side reconciliation) — never a client redirect.
+// lib/services/bookings.js - Booking reads and seat counting. Paid bookings are created only by a
+// matched SuperProfile notification (services/orders.js) — never by a client redirect; free tiers
+// confirm in services/ticketing.js.
import { db } from '../db.js';
import { HttpError } from '../http.js';
-import { siteUrl } from '../config.js';
+import { audit } from '../audit.js';
import { SEAT_HOLDING_SQL, formatPaise } from './events.js';
+import { getBookingTickets } from './tickets.js';
import { enqueue } from './notifications.js';
-import { audit } from '../audit.js';
-import { logger } from '../logger.js';
-
-export const HOLD_MINUTES = 15;
export async function seatsTaken(c, eventId, excludeBookingId = null) {
const { rows } = await c.query(
@@ -25,190 +23,7 @@ export async function tierSeatsTaken(c, ticketTypeId, excludeBookingId = null) {
return rows[0].n;
}
-/**
- * Step 1 (one short transaction, event row locked): validate and place a 15-minute seat hold.
- * Returns { booking, event, existing } where existing=true means an active booking was reused.
- */
-async function placeHold(user, eventId) {
- return db.tx(async (c) => {
- const event = (await c.query('SELECT * FROM events WHERE id = $1 FOR UPDATE', [eventId])).rows[0];
- if (!event || event.status !== 'published') throw new HttpError(404, 'event_not_found', 'This event is not available');
- if (new Date(event.start_at) <= new Date()) throw new HttpError(409, 'event_started', 'This event has already started');
- if (event.source === 'external') throw new HttpError(409, 'external_event', 'This event is booked on the organiser’s own page');
- if (event.ticketing === 'tiers') throw new HttpError(409, 'choose_ticket', 'Choose a ticket type on the event page to book');
- if (event.price_status !== 'set' || !event.ticket_price_paise) throw new HttpError(409, 'price_tbd', 'Bookings open once the price is announced');
- if (!user.age_confirmed_21) throw new HttpError(403, 'age_required', 'Please confirm you are 21 or older');
-
- const active = (await c.query(
- `SELECT b.*, p.checkout_url FROM bookings b LEFT JOIN payments p ON p.id = b.payment_id
- WHERE b.event_id = $1 AND b.user_id = $2 AND b.status IN ('pending_payment', 'confirmed', 'checked_in') FOR UPDATE OF b`,
- [eventId, user.id])).rows[0];
- if (active) {
- if (active.status !== 'pending_payment') return { booking: active, event, existing: true };
- if (new Date(active.hold_expires_at) > new Date() && active.checkout_url) return { booking: active, event, existing: true };
- // Stale or never-completed hold: release it and start fresh.
- await c.query(`UPDATE bookings SET status = 'cancelled', cancelled_at = now(), cancel_reason = 'hold_replaced' WHERE id = $1`, [active.id]);
- }
-
- if (await seatsTaken(c, eventId) >= event.capacity) throw new HttpError(409, 'sold_out', 'Sorry, this event is sold out');
- const booking = (await c.query(
- `INSERT INTO bookings (event_id, user_id, status, amount_paise, hold_expires_at)
- VALUES ($1, $2, 'pending_payment', $3, now() + make_interval(mins => $4)) RETURNING *`,
- [eventId, user.id, event.ticket_price_paise, HOLD_MINUTES])).rows[0];
- return { booking, event, existing: false };
- });
-}
-
-/**
- * Create (or resume) a booking and a hosted checkout.
- * Returns { bookingId, status, checkoutUrl? }.
- */
-export async function createBooking(user, eventId, provider) {
- const { booking, event, existing } = await placeHold(user, eventId);
- if (existing) {
- return { bookingId: booking.id, status: booking.status, checkoutUrl: booking.status === 'pending_payment' ? booking.checkout_url : null };
- }
- const checkoutUrl = await startCheckout(user.id, booking, event, provider);
- return { bookingId: booking.id, status: 'pending_payment', checkoutUrl };
-}
-
-/**
- * Create a hosted checkout for a booking already holding seats (status pending_payment) and record
- * the `created` payment. On provider failure, `onFail` releases the hold (default: cancel).
- * Provider-agnostic: any PaymentProvider from lib/payments works. Returns the checkout URL.
- */
-export async function startCheckout(userId, booking, event, provider, {
- onFail = (id) => db.query(`UPDATE bookings SET status = 'cancelled', cancelled_at = now(), cancel_reason = 'checkout_failed' WHERE id = $1`, [id])
-} = {}) {
- let checkout;
- try {
- checkout = await provider.createCheckout({
- bookingId: booking.id,
- userId,
- amountPaise: booking.amount_paise,
- title: `${event.title} — ${event.city}`,
- expiresAt: booking.hold_expires_at,
- returnUrl: `${siteUrl()}/bookings/${booking.id}`
- });
- } catch (err) {
- await onFail(booking.id);
- if (err instanceof HttpError) throw err;
- logger.error('checkout creation failed', err, { provider: provider.name });
- throw new HttpError(502, 'checkout_failed', 'We could not start checkout. Please try again in a moment.');
- }
- await db.tx(async (c) => {
- const pay = (await c.query(
- `INSERT INTO payments (provider, provider_txn_id, purpose, user_id, booking_id, amount, currency, status, is_test, checkout_url, raw_ref)
- VALUES ($1, $2, 'ticket', $3, $4, $5, 'INR', 'created', $6, $7, $8) RETURNING id`,
- [provider.name, checkout.providerTxnId, userId, booking.id, booking.amount_paise, provider.isTest, checkout.checkoutUrl,
- JSON.stringify({ txn: checkout.providerTxnId })])).rows[0];
- await c.query(`UPDATE bookings SET payment_id = $2, payment_mode = COALESCE(payment_mode, 'provider') WHERE id = $1`, [booking.id, pay.id]);
- });
- return checkout.checkoutUrl;
-}
-
-/**
- * Apply a verified provider event. Idempotent per (provider, eventId) via webhook_events, and per
- * payment via its status. Returns { result, notificationIds }.
- */
-export async function applyTicketEvent(providerName, evt) {
- return db.tx(async (c) => {
- const ins = await c.query(
- `INSERT INTO webhook_events (provider, event_id) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING id`, [providerName, evt.eventId]);
- if (!ins.rowCount) return { result: 'duplicate', notificationIds: [] };
- const whId = ins.rows[0].id;
- const finish = async (result, notificationIds = []) => {
- await c.query('UPDATE webhook_events SET processed_at = now(), result = $2 WHERE id = $1', [whId, result]);
- return { result, notificationIds };
- };
- if (evt.type === 'ignored') return finish('ignored');
-
- let payment;
- if (evt.type === 'refunded' && !evt.providerTxnId) {
- payment = (await c.query(`SELECT * FROM payments WHERE provider = $1 AND provider_payment_id = $2 FOR UPDATE`, [providerName, evt.providerPaymentId])).rows[0];
- } else if (evt.providerTxnId) {
- payment = (await c.query(`SELECT * FROM payments WHERE provider = $1 AND provider_txn_id = $2 FOR UPDATE`, [providerName, evt.providerTxnId])).rows[0];
- } else if (evt.bookingId) {
- payment = (await c.query(`SELECT * FROM payments WHERE provider = $1 AND booking_id = $2 AND purpose = 'ticket' ORDER BY created_at DESC LIMIT 1 FOR UPDATE`, [providerName, evt.bookingId])).rows[0];
- }
- if (!payment || payment.purpose !== 'ticket') return finish('unknown_payment');
-
- if (evt.type === 'failed') {
- if (payment.status === 'created') {
- await c.query(`UPDATE payments SET status = 'failed', failure_reason = $2 WHERE id = $1`, [payment.id, evt.reason || 'failed']);
- }
- return finish('failed_recorded'); // nothing granted; the hold simply expires
- }
-
- if (evt.type === 'expired') {
- if (payment.status === 'created') {
- await c.query(`UPDATE payments SET status = 'failed', failure_reason = 'expired' WHERE id = $1`, [payment.id]);
- await c.query(`UPDATE bookings SET status = 'cancelled', cancelled_at = now(), cancel_reason = 'checkout_expired' WHERE id = $1 AND status = 'pending_payment'`, [payment.booking_id]);
- }
- return finish('expired');
- }
-
- if (evt.type === 'refunded') {
- if (payment.status !== 'refunded') {
- await c.query(`UPDATE payments SET status = 'refunded', refunded_at = now() WHERE id = $1`, [payment.id]);
- await c.query(`UPDATE bookings SET status = 'refunded', refunded_at = now() WHERE id = $1 AND status <> 'refunded'`, [payment.booking_id]);
- await c.query(`UPDATE invite_links SET revoked_at = COALESCE(revoked_at, now()) WHERE booking_id = $1`, [payment.booking_id]);
- }
- return finish('refunded');
- }
-
- // evt.type === 'paid'
- if (payment.status === 'paid' || payment.status === 'refunded') return finish('already_paid');
- // Fail closed: a signed "paid" event that omits or garbles the amount never confirms a booking.
- if (evt.amountPaise === undefined || evt.amountPaise === null || !Number.isFinite(Number(evt.amountPaise))
- || Number(evt.amountPaise) !== Number(payment.amount)) {
- logger.error('payment amount mismatch', null, { paymentId: payment.id });
- await c.query(`UPDATE payments SET failure_reason = 'amount_mismatch' WHERE id = $1`, [payment.id]);
- return finish('amount_mismatch');
- }
- if (evt.currency && evt.currency !== 'INR') return finish('currency_mismatch');
- await c.query(`UPDATE payments SET status = 'paid', paid_at = now(), provider_payment_id = COALESCE($2, provider_payment_id), failure_reason = NULL WHERE id = $1`,
- [payment.id, evt.providerPaymentId || null]);
-
- // Lock order matches placeHold (events, then bookings) to avoid deadlocks.
- const eventId = (await c.query('SELECT event_id FROM bookings WHERE id = $1', [payment.booking_id])).rows[0].event_id;
- const event = (await c.query('SELECT * FROM events WHERE id = $1 FOR UPDATE', [eventId])).rows[0];
- const booking = (await c.query('SELECT * FROM bookings WHERE id = $1 FOR UPDATE', [payment.booking_id])).rows[0];
- if (['confirmed', 'checked_in'].includes(booking.status)) return finish('already_confirmed');
-
- const holdActive = booking.status === 'pending_payment' && new Date(booking.hold_expires_at) > new Date();
- const otherActive = (await c.query(
- `SELECT 1 FROM bookings WHERE event_id = $1 AND user_id = $2 AND id <> $3 AND status IN ('confirmed', 'checked_in', 'pending_payment')
- AND (status <> 'pending_payment' OR hold_expires_at > now())`, [booking.event_id, booking.user_id, booking.id])).rows[0];
- const qty = booking.quantity || 1;
- let capacityOk = holdActive || (await seatsTaken(c, booking.event_id, booking.id)) + qty <= event.capacity;
- if (capacityOk && !holdActive && booking.ticket_type_id) {
- const tier = (await c.query('SELECT quantity FROM ticket_types WHERE id = $1', [booking.ticket_type_id])).rows[0];
- capacityOk = Boolean(tier) && (await tierSeatsTaken(c, booking.ticket_type_id, booking.id)) + qty <= tier.quantity;
- }
- const eventOk = event.status === 'published';
-
- if (capacityOk && eventOk && !otherActive) {
- if (booking.status !== 'pending_payment') {
- // Hold had been released; release any other stale pending row for the unique index first.
- await c.query(`UPDATE bookings SET status = 'cancelled', cancelled_at = now(), cancel_reason = 'hold_replaced'
- WHERE event_id = $1 AND user_id = $2 AND id <> $3 AND status = 'pending_payment'`, [booking.event_id, booking.user_id, booking.id]);
- }
- await c.query(`UPDATE bookings SET status = 'confirmed', confirmed_at = now(), cancelled_at = NULL, cancel_reason = NULL WHERE id = $1`, [booking.id]);
- const nid = await enqueue(c, { kind: 'booking_confirmed', userId: booking.user_id, bookingId: booking.id, dedupeKey: `bk:${booking.id}:confirmed` });
- await audit(`webhook:${providerName}`, 'booking.confirmed', booking.id, { paymentId: payment.id }, c);
- return finish('confirmed', [nid]);
- }
-
- // Paid but cannot honour (late payment and event full / cancelled / duplicate booking): never keep the money silently.
- await c.query(`UPDATE bookings SET status = 'cancelled', cancelled_at = COALESCE(cancelled_at, now()), cancel_reason = 'paid_but_unavailable_refund_due' WHERE id = $1`, [booking.id]);
- const nid = await enqueue(c, { kind: 'late_payment_refund_needed', userId: booking.user_id, bookingId: booking.id, dedupeKey: `bk:${booking.id}:refund_needed` });
- await audit(`webhook:${providerName}`, 'booking.refund_needed', booking.id, { paymentId: payment.id, reason: !eventOk ? 'event_not_published' : otherActive ? 'duplicate_booking' : 'capacity' }, c);
- return finish('refund_needed', [nid]);
- });
-}
-
-/** Cron: release expired holds (capacity already ignores them; this tidies status). */
+/** Cron: release expired seat holds left by approval requests (capacity already ignores them; this tidies status). */
export async function releaseExpiredHolds() {
const r = await db.query(
`UPDATE bookings SET status = 'cancelled', cancelled_at = now(), cancel_reason = 'hold_expired'
@@ -216,40 +31,57 @@ export async function releaseExpiredHolds() {
return r.rowCount;
}
-/** Cron: ask the provider about payments still 'created' (missed webhooks) and apply the truth. */
-export async function reconcilePayments(provider, { limit = 50 } = {}) {
- const { rows } = await db.query(
- `SELECT id, provider_txn_id FROM payments
- WHERE provider = $1 AND purpose = 'ticket' AND status = 'created'
- AND created_at < now() - interval '10 minutes' AND created_at > now() - interval '7 days'
- ORDER BY created_at LIMIT $2`, [provider.name, limit]);
- const out = { checked: rows.length, applied: 0, notificationIds: [] };
- for (const p of rows) {
- try {
- const s = await provider.fetchStatus(p.provider_txn_id);
- if (s.status === 'created') continue;
- const type = s.status === 'paid' ? 'paid' : s.status === 'expired' ? 'expired' : 'failed';
- const r = await applyTicketEvent(provider.name, {
- eventId: `reconcile:${p.provider_txn_id}:${type}`, type, providerTxnId: p.provider_txn_id,
- providerPaymentId: s.providerPaymentId, amountPaise: s.amountPaise, reason: 'reconciled'
- });
- if (!['duplicate'].includes(r.result)) out.applied++;
- out.notificationIds.push(...r.notificationIds);
- } catch (err) {
- logger.warn('reconcile failed', { paymentId: p.id, reason: String(err.message).slice(0, 120) });
- }
- }
- return out;
-}
-
/** Bookings for the signed-in user. */
export async function listUserBookings(userId) {
const { rows } = await db.query(
- `SELECT b.id, b.status, e.title, e.city, e.start_at, e.slug FROM bookings b JOIN events e ON e.id = b.event_id
+ `SELECT b.id, b.status, b.created_at, e.id AS event_id, e.title, e.city, e.start_at, e.end_at, e.slug, e.category,
+ (COALESCE(e.end_at, e.start_at) < now()) AS is_past,
+ (SELECT count(*)::int FROM tickets tk WHERE tk.booking_id = b.id AND tk.status = 'checked_in') AS checked_in_count
+ FROM bookings b
+ JOIN events e ON e.id = b.event_id
WHERE b.user_id = $1 AND b.status IN ('pending_approval', 'pending_payment', 'confirmed', 'checked_in', 'refunded', 'declined')
AND NOT (b.status = 'pending_payment' AND b.hold_expires_at < now() - interval '1 day')
ORDER BY e.start_at DESC LIMIT 50`, [userId]);
- return rows.map((r) => ({ id: r.id, status: r.status, title: r.title, city: r.city, startAt: r.start_at, slug: r.slug }));
+ return rows.map((r) => ({
+ id: r.id,
+ eventId: r.event_id,
+ status: r.status,
+ title: r.title,
+ city: r.city,
+ startAt: r.start_at,
+ endAt: r.end_at,
+ slug: r.slug,
+ category: r.category,
+ isPast: Boolean(r.is_past),
+ isCheckedIn: r.status === 'checked_in' || (Number(r.checked_in_count || 0) > 0)
+ }));
+}
+
+/** Operational announcements for events that the user is booked to attend. */
+export async function listUserAnnouncements(userId) {
+ const { rows } = await db.query(
+ `SELECT DISTINCT ON (a.id) a.id, a.event_id, a.title, a.message, a.is_pinned, a.created_at,
+ e.title AS event_title, e.slug AS event_slug, e.city AS event_city, e.start_at AS event_start_at
+ FROM event_announcements a
+ JOIN events e ON e.id = a.event_id
+ JOIN bookings b ON b.event_id = e.id
+ WHERE b.user_id = $1 AND b.status IN ('confirmed', 'checked_in')
+ ORDER BY a.id, a.created_at DESC
+ LIMIT 20`,
+ [userId]
+ );
+ return rows.map((r) => ({
+ id: r.id,
+ eventId: r.event_id,
+ title: r.title,
+ message: r.message,
+ isPinned: Boolean(r.is_pinned),
+ createdAt: r.created_at,
+ eventTitle: r.event_title,
+ eventSlug: r.event_slug,
+ eventCity: r.event_city,
+ eventStartAt: r.event_start_at
+ }));
}
/**
@@ -258,12 +90,12 @@ export async function listUserBookings(userId) {
*/
export async function getUserBooking(userId, bookingId) {
const b = await db.one(
- `SELECT b.*, e.title, e.city, e.start_at, e.timezone, e.venue_private, e.venue_privacy, e.area_public, e.maps_url,
+ `SELECT b.*, e.title, e.city, e.start_at, e.timezone, e.venue_private, e.venue_privacy, e.area_public, e.maps_url, e.slug,
e.pickup_points, e.contact_name, e.contact_phone, t.name AS ticket_name, t.kind AS ticket_kind,
- p.checkout_url, p.is_test, p.status AS payment_status
+ eo.status AS payment_status
FROM bookings b JOIN events e ON e.id = b.event_id
LEFT JOIN ticket_types t ON t.id = b.ticket_type_id
- LEFT JOIN payments p ON p.id = b.payment_id
+ LEFT JOIN external_orders eo ON eo.matched_booking_id = b.id
WHERE b.id = $1 AND b.user_id = $2`, [bookingId, userId]);
if (!b) return null;
const confirmed = ['confirmed', 'checked_in'].includes(b.status);
@@ -272,19 +104,116 @@ export async function getUserBooking(userId, bookingId) {
: null;
const pickup = (Array.isArray(b.pickup_points) ? b.pickup_points : []).find((p) => p.id === b.pickup_point_id) || null;
const phone = confirmed && b.contact_phone ? b.contact_phone : null;
+ const tickets = confirmed ? await getBookingTickets(b.id, { id: userId }, db).catch(() => []) : [];
+ const announcements = confirmed
+ ? await db.query(
+ `SELECT id, title, message, is_pinned, created_at FROM event_announcements WHERE event_id = $1 ORDER BY is_pinned DESC, created_at DESC LIMIT 5`,
+ [b.event_id]
+ ).then((r) => r.rows.map((a) => ({ id: a.id, title: a.title, message: a.message, isPinned: Boolean(a.is_pinned), createdAt: a.created_at }))).catch(() => [])
+ : [];
+
+ const checkedInTicket = tickets.find((tk) => tk.status === 'checked_in');
+
return {
id: b.id, status: b.status, title: b.title, city: b.city, startAt: b.start_at, timezone: b.timezone,
+ slug: b.slug,
+ eventId: b.event_id,
venue: confirmed ? (b.venue_private || null) : null,
mapsUrl: confirmed || b.venue_privacy === 'public' ? (b.maps_url || null) : null,
ticket: b.ticket_name ? { name: b.ticket_name, kind: b.ticket_kind, quantity: b.quantity } : null,
+ tickets,
+ isCheckedIn: b.status === 'checked_in' || Boolean(checkedInTicket),
+ checkedInAt: checkedInTicket?.checkedInAt || (b.status === 'checked_in' ? b.updated_at : null),
amountLabel: b.amount_paise ? formatPaise(b.amount_paise) : null,
paymentMode: b.payment_mode,
paymentStatus: b.payment_status || (b.payment_mode === 'free' ? 'not_required' : null),
pickup: pickup ? { name: pickup.name, location: pickup.location || '', time: pickup.time || null } : null,
contact: phone ? { name: b.contact_name, phone, whatsappUrl: `https://wa.me/${phone.replace(/^\+/, '')}` } : null,
- holdActive: b.status === 'pending_payment' && new Date(b.hold_expires_at) > new Date(),
- checkoutUrl: b.status === 'pending_payment' ? b.checkout_url : null,
- isTest: b.payment_id ? b.is_test !== false : false,
- invite: invite ? { link: invite.link, expiresAt: invite.expires_at } : null
+ invite: invite ? { link: invite.link, expiresAt: invite.expires_at } : null,
+ announcements
};
}
+
+/**
+ * Attendee self-cancellation for a confirmed or pending booking.
+ * Releases seat holds, cancels active tickets, revokes invite links,
+ * audits the action, and enqueues a cancellation confirmation notification.
+ */
+export async function cancelUserBooking(userId, bookingId, { reason = 'Cancelled by attendee' } = {}) {
+ return db.tx(async (c) => {
+ const b = (await c.query(
+ `SELECT b.*, e.title, e.start_at
+ FROM bookings b
+ JOIN events e ON e.id = b.event_id
+ WHERE b.id = $1 AND b.user_id = $2
+ FOR UPDATE OF b`,
+ [bookingId, userId]
+ )).rows[0];
+
+ if (!b) throw new HttpError(404, 'not_found', 'Booking not found');
+
+ if (b.status === 'cancelled') {
+ throw new HttpError(409, 'already_cancelled', 'This booking is already cancelled');
+ }
+ if (b.status === 'checked_in') {
+ throw new HttpError(409, 'already_checked_in', 'Checked-in bookings cannot be cancelled');
+ }
+ if (['declined', 'refunded'].includes(b.status)) {
+ throw new HttpError(409, 'cannot_cancel', `Booking in status "${b.status}" cannot be cancelled`);
+ }
+
+ // Cancel the booking
+ await c.query(
+ `UPDATE bookings
+ SET status = 'cancelled',
+ cancelled_at = now(),
+ cancel_reason = $2,
+ updated_at = now()
+ WHERE id = $1`,
+ [bookingId, reason]
+ );
+
+ // Cancel all active/valid tickets for this booking
+ await c.query(
+ `UPDATE tickets
+ SET status = 'cancelled',
+ revoked_at = now(),
+ revoked_by = $2,
+ revocation_reason = $3,
+ updated_at = now()
+ WHERE booking_id = $1 AND status = 'valid'`,
+ [bookingId, userId, 'Attendee self-cancellation']
+ );
+
+ // Revoke any active invite links
+ await c.query(
+ `UPDATE invite_links
+ SET revoked_at = now()
+ WHERE booking_id = $1 AND revoked_at IS NULL`,
+ [bookingId]
+ );
+
+ // Enqueue cancellation notification
+ await enqueue(c, {
+ kind: 'booking_cancelled_by_user',
+ userId,
+ bookingId,
+ eventId: b.event_id,
+ dedupeKey: `user_cancel:${bookingId}`
+ });
+
+ // Immutable audit record
+ await audit(`user:${userId}`, 'booking.attendee_cancel', bookingId, {
+ eventId: b.event_id,
+ previousStatus: b.status,
+ reason
+ }, c);
+
+ return {
+ ok: true,
+ bookingId,
+ status: 'cancelled',
+ eventId: b.event_id
+ };
+ });
+}
diff --git a/lib/services/checkout.js b/lib/services/checkout.js
new file mode 100644
index 0000000..4c8d5a9
--- /dev/null
+++ b/lib/services/checkout.js
@@ -0,0 +1,65 @@
+// lib/services/checkout.js - Checkout intents: carry a (possibly anonymous) buyer across to SuperProfile.
+//
+// "Book Tickets" links to /checkout/:slug. We record an intent with a short random ref, attach the ref
+// to the SuperProfile URL, and redirect. When SuperProfile later reports the order with that ref we
+// know who bought. Signed-out visitors are redirected too: paying is never gated on signing in, and
+// their order is claimed in the bot afterwards.
+import crypto from 'node:crypto';
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+import { ticketProvider } from '../payments/index.js';
+import { checkoutForEvent } from '../payments/availability.js';
+
+export const INTENT_TTL_HOURS = 72;
+const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
+
+/** 8 chars of Crockford base32 = 40 random bits. */
+export function newRef() {
+ const bytes = crypto.randomBytes(5);
+ let n = 0n;
+ for (const b of bytes) n = (n << 8n) | BigInt(b);
+ let out = '';
+ for (let i = 7; i >= 0; i--) out += CROCKFORD[Number((n >> BigInt(i * 5)) & 31n)];
+ return out;
+}
+
+/**
+ * Record an intent for a published, checkout-enabled event and return where to send the buyer.
+ * Returns null when this event cannot be bought online (the caller sends them back to the event page).
+ */
+export async function createCheckoutIntent({ slug, user = null, ticketTypeId = null, qty = 1 }) {
+ const event = await db.one(
+ `SELECT id, slug, ticketing, checkout_mode, superprofile_url FROM events
+ WHERE slug = $1 AND status = 'published' AND start_at > now()`, [slug]);
+ if (!event) throw new HttpError(404, 'event_not_found', 'This event is not available');
+ if (!checkoutForEvent(event).available) return null;
+
+ const n = Math.min(Math.max(parseInt(qty, 10) || 1, 1), 20);
+ let ticket = null;
+ if (ticketTypeId) {
+ if (!/^[0-9a-f-]{36}$/i.test(ticketTypeId)) throw new HttpError(404, 'ticket_not_found', 'That ticket type is not available');
+ ticket = await db.one(`SELECT id, kind, max_per_booking FROM ticket_types WHERE id = $1 AND event_id = $2 AND active`, [ticketTypeId, event.id]);
+ if (!ticket || ticket.kind !== 'paid') throw new HttpError(404, 'ticket_not_found', 'That ticket type is not available');
+ if (n > ticket.max_per_booking) throw new HttpError(400, 'validation', `Up to ${ticket.max_per_booking} per booking`);
+ }
+
+ let intent = null;
+ for (let attempt = 0; attempt < 4 && !intent; attempt++) {
+ const ref = newRef();
+ const r = await db.query(
+ `INSERT INTO checkout_intents (ref, user_id, event_id, ticket_type_id, qty, expires_at)
+ VALUES ($1, $2, $3, $4, $5, now() + make_interval(hours => $6)) ON CONFLICT (ref) DO NOTHING RETURNING ref`,
+ [ref, user?.id || null, event.id, ticket?.id || null, n, INTENT_TTL_HOURS]);
+ intent = r.rows[0] || null;
+ }
+ if (!intent) throw new HttpError(503, 'try_again', 'Please try again in a moment');
+
+ await db.query(`INSERT INTO analytics_events (name, event_id) VALUES ('checkout_click', $1)`, [event.id]);
+ const { checkoutUrl } = await ticketProvider().createCheckout({ url: event.superprofile_url, ref: intent.ref, slug: event.slug });
+ return { url: checkoutUrl, ref: intent.ref };
+}
+
+export async function pruneCheckoutIntents() {
+ const r = await db.query(`DELETE FROM checkout_intents WHERE expires_at < now() - interval '30 days'`);
+ return r.rowCount;
+}
diff --git a/lib/services/claims.js b/lib/services/claims.js
new file mode 100644
index 0000000..4a56f27
--- /dev/null
+++ b/lib/services/claims.js
@@ -0,0 +1,65 @@
+// lib/services/claims.js - Telegram "claim your order" flow for buyers SuperProfile could not tie to a user.
+//
+// The buyer opens the bot (t.me/?start=claim), sends their SuperProfile order ID (and optionally
+// the email they paid with). One order can be claimed once. Failures all look alike so the bot is no
+// oracle for which order IDs exist, and claims are limited to 5 an hour per Telegram user. A short or
+// purely numeric order ID (guessable) additionally requires the buyer's email to match.
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+import { rateLimit } from '../ratelimit.js';
+import { emailHash } from './superprofile.js';
+import { confirmOrderBooking } from './orders.js';
+
+export const CLAIM_LIMIT_PER_HOUR = 5;
+export const CLAIM_PROMPT_MINUTES = 10;
+export const CLAIM_FAILED_MESSAGE = 'We could not claim that order. Check the order ID (and the email you paid with), or contact support.';
+
+const failed = () => new HttpError(404, 'claim_failed', CLAIM_FAILED_MESSAGE);
+
+export function normaliseOrderId(raw) {
+ const id = String(raw || '').trim();
+ return /^[A-Za-z0-9_-]{4,100}$/.test(id) ? id : null;
+}
+
+/** An order ID someone could plausibly guess by counting. */
+export const isGuessableOrderId = (id) => /^\d{1,10}$/.test(id);
+
+export async function startClaimPrompt(userId) {
+ await db.query(`UPDATE users SET claim_prompt_until = now() + make_interval(mins => $2) WHERE id = $1`, [userId, CLAIM_PROMPT_MINUTES]);
+}
+
+export async function clearClaimPrompt(userId) {
+ await db.query('UPDATE users SET claim_prompt_until = NULL WHERE id = $1', [userId]);
+}
+
+export async function isClaimPromptOpen(userId) {
+ const r = await db.one('SELECT 1 AS x FROM users WHERE id = $1 AND claim_prompt_until > now()', [userId]);
+ return Boolean(r);
+}
+
+/** Returns { bookingId, notificationIds, eventTitle }; throws HttpError (429 rate limit, 403 age, 404 generic). */
+export async function claimOrder(user, rawOrderId, rawEmail = '') {
+ await rateLimit(`claim:${user.telegram_user_id}`, CLAIM_LIMIT_PER_HOUR, 3600);
+ if (!user.age_confirmed_21) throw new HttpError(403, 'age_required', 'Please confirm you are 21 or older on our website first, then claim your order here.');
+ const orderId = normaliseOrderId(rawOrderId);
+ if (!orderId) throw failed();
+ const email = String(rawEmail || '').trim();
+ const givenHash = email ? emailHash(email) : null;
+ if (email && !givenHash) throw failed();
+
+ return db.tx(async (c) => {
+ const order = (await c.query('SELECT * FROM external_orders WHERE lower(order_id) = lower($1) FOR UPDATE', [orderId])).rows[0];
+ if (!order || order.status !== 'paid' || order.matched_booking_id || order.match_state !== 'unmatched' || !order.event_id) throw failed();
+ if (isGuessableOrderId(order.order_id) && (!order.buyer_email_hash || givenHash !== order.buyer_email_hash)) throw failed();
+ if (givenHash && order.buyer_email_hash && givenHash !== order.buyer_email_hash) throw failed();
+
+ const event = (await c.query('SELECT * FROM events WHERE id = $1 FOR UPDATE', [order.event_id])).rows[0];
+ if (!event || event.status !== 'published') throw failed();
+ const r = await confirmOrderBooking(c, { order, event, userId: user.id, actor: `user:${user.id}` });
+ if (r.conflict) throw new HttpError(409, 'duplicate_booking', 'You already have a booking for this event. Send /mybookings to see it, or contact support if you bought extra tickets.');
+ // The buyer proved the email by quoting it: later orders from it match without a claim.
+ if (givenHash && order.buyer_email_hash === givenHash) await c.query('UPDATE users SET email_hash = $2 WHERE id = $1', [user.id, givenHash]);
+ await c.query('UPDATE users SET claim_prompt_until = NULL WHERE id = $1', [user.id]);
+ return { bookingId: r.bookingId, notificationIds: [r.notificationId], eventTitle: event.title };
+ });
+}
diff --git a/lib/services/discovery-feed.js b/lib/services/discovery-feed.js
new file mode 100644
index 0000000..9f7e658
--- /dev/null
+++ b/lib/services/discovery-feed.js
@@ -0,0 +1,331 @@
+// lib/services/discovery-feed.js - Attendee Discovery Feed, Ranking & Personalised Recommendations.
+// Combines transparent recommendation factors, trending signals, location intelligence, and multi-facet filtering.
+import { db } from '../db.js';
+import {
+ listPublicEvents, toPublicEvent, CATEGORY_LABELS, CITIES,
+ SEAT_HOLDING_SQL, TIERS_SQL, formatDistanceBand
+} from './events.js';
+import { findNearbyEvents, haversineKm } from './locations.js';
+import { listSavedEventIds } from './saved-events.js';
+
+export { CATEGORY_LABELS, CITIES };
+
+/** Canonical category groupings for consumer discovery */
+export const DISCOVERY_COLLECTIONS = [
+ { key: 'nightlife', label: 'Nightlife & Parties', categories: ['nightlife', 'weekend_party'], icon: '🍸' },
+ { key: 'dinners', label: 'Dinner Clubs & Food', categories: ['dinner_club'], icon: '🍷' },
+ { key: 'social', label: 'Social Mixers & Dating', categories: ['meetup', 'dating_mixer', 'matchmaking'], icon: '❤️' },
+ { key: 'activities', label: 'Games, Movies & Activities', categories: ['board_games', 'movie', 'workshop'], icon: '🎲' },
+ { key: 'trips', label: 'Trips & Getaways', categories: ['weekend_trip', 'resort_getaway'], icon: '🎒' },
+ { key: 'community', label: 'Founders & Community', categories: ['networking'], icon: '💼' }
+];
+
+/**
+ * Compute date boundaries for 'when' filter in IST (UTC+5:30).
+ */
+export function parseDateFilter(when) {
+ if (!when) return {};
+ const now = new Date();
+ const istOffset = 5.5 * 60 * 60 * 1000;
+ const istNow = new Date(now.getTime() + istOffset);
+
+ const startOfDay = (d) => {
+ const s = new Date(d);
+ s.setUTCHours(0, 0, 0, 0);
+ return new Date(s.getTime() - istOffset);
+ };
+ const endOfDay = (d) => {
+ const e = new Date(d);
+ e.setUTCHours(23, 59, 59, 999);
+ return new Date(e.getTime() - istOffset);
+ };
+
+ if (when === 'today') {
+ return { from: now.toISOString(), to: endOfDay(istNow).toISOString() };
+ }
+ if (when === 'tomorrow') {
+ const tmrw = new Date(istNow);
+ tmrw.setUTCDate(tmrw.getUTCDate() + 1);
+ return { from: startOfDay(tmrw).toISOString(), to: endOfDay(tmrw).toISOString() };
+ }
+ if (when === 'weekend' || when === 'this_weekend') {
+ // Find next Friday/Saturday/Sunday
+ const day = istNow.getUTCDay(); // 0 is Sunday, 5 is Friday, 6 is Saturday
+ const fri = new Date(istNow);
+ const daysUntilFri = (5 - day + 7) % 7;
+ fri.setUTCDate(fri.getUTCDate() + daysUntilFri);
+ const sun = new Date(fri);
+ sun.setUTCDate(sun.getUTCDate() + 2);
+ return { from: startOfDay(fri).toISOString(), to: endOfDay(sun).toISOString() };
+ }
+ if (when === 'week' || when === 'next_7_days') {
+ const in7 = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
+ return { from: now.toISOString(), to: in7.toISOString() };
+ }
+ if (when === 'month' || when === 'this_month') {
+ const in30 = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000);
+ return { from: now.toISOString(), to: in30.toISOString() };
+ }
+ return {};
+}
+
+/**
+ * Retrieve user recommendation context based on:
+ * 1. User's voluntary profile (city, interests)
+ * 2. Categories of previously attended events
+ * 3. Categories of explicitly saved/bookmarked events
+ */
+export async function getUserRecommendationContext(userId, c = db) {
+ if (!userId) return null;
+
+ const [userRow, attendedCats, savedCats, savedIds] = await Promise.all([
+ c.one(`SELECT city, interests FROM users WHERE id = $1`, [userId]).catch(() => null),
+ c.query(
+ `SELECT DISTINCT e.category
+ FROM bookings b
+ JOIN events e ON e.id = b.event_id
+ WHERE b.user_id = $1 AND b.status IN ('confirmed', 'checked_in')
+ LIMIT 10`,
+ [userId]
+ ).catch(() => ({ rows: [] })),
+ c.query(
+ `SELECT DISTINCT e.category
+ FROM saved_events s
+ JOIN events e ON e.id = s.event_id
+ WHERE s.user_id = $1
+ LIMIT 10`,
+ [userId]
+ ).catch(() => ({ rows: [] })),
+ listSavedEventIds(userId, c).catch(() => [])
+ ]);
+
+ const preferredCity = userRow?.city || null;
+ const profileInterests = Array.isArray(userRow?.interests) ? userRow.interests : [];
+ const attendedCategories = attendedCats.rows.map((r) => r.category);
+ const savedCategories = savedCats.rows.map((r) => r.category);
+
+ return {
+ preferredCity,
+ profileInterests,
+ attendedCategories,
+ savedCategories,
+ savedEventIds: new Set(savedIds)
+ };
+}
+
+/**
+ * Calculate transparent recommendation score and reason for an event.
+ */
+export function scoreEventRecommendation(event, userContext, targetCity = null) {
+ let score = 0;
+ const reasons = [];
+
+ // Trending signal: proportion of capacity booked or high confirmed seats
+ const seats = Number(event.seats_taken || 0);
+ const cap = Number(event.capacity || 0);
+ if (cap > 0 && seats >= Math.min(3, Math.floor(cap * 0.4))) {
+ score += 20;
+ reasons.push('Popular in ' + event.city);
+ }
+
+ // Starts soon (within 5 days): recency boost
+ const hoursUntil = (new Date(event.start_at).getTime() - Date.now()) / (1000 * 60 * 60);
+ if (hoursUntil > 0 && hoursUntil < 120) {
+ score += 15;
+ }
+
+ if (userContext) {
+ // City preference match
+ if (userContext.preferredCity && event.city &&
+ event.city.toLowerCase() === userContext.preferredCity.toLowerCase()) {
+ score += 40;
+ reasons.push('In your preferred city (' + userContext.preferredCity + ')');
+ }
+
+ // Profile interests match
+ if (userContext.profileInterests && userContext.profileInterests.includes(event.category)) {
+ score += 30;
+ reasons.push('Matches your interest in ' + (CATEGORY_LABELS[event.category] || event.category));
+ }
+
+ // Previously booked categories match
+ if (userContext.attendedCategories && userContext.attendedCategories.includes(event.category)) {
+ score += 25;
+ reasons.push('Similar to events you joined');
+ }
+
+ // Saved categories match
+ if (userContext.savedCategories && userContext.savedCategories.includes(event.category)) {
+ score += 15;
+ reasons.push('Based on your saved events');
+ }
+ } else if (targetCity && event.city && event.city.toLowerCase() === targetCity.toLowerCase()) {
+ score += 30;
+ reasons.push('Upcoming in ' + event.city);
+ }
+
+ return {
+ score,
+ reason: reasons[0] || (event.city ? 'Upcoming experience in ' + event.city : 'Upcoming experience')
+ };
+}
+
+/**
+ * Core Attendee Discovery Feed builder.
+ */
+export async function getDiscoveryFeed({
+ userId = null,
+ city = null,
+ lat = null,
+ lng = null,
+ radiusKm = 50,
+ category = null,
+ categories = null,
+ when = null,
+ price = null,
+ q = null,
+ sort = 'recommended',
+ limit = 50,
+ offset = 0
+} = {}, c = db) {
+ const userContext = await getUserRecommendationContext(userId, c);
+ const range = parseDateFilter(when);
+
+ // Normalize city input: slug or full name
+ let targetCityName = null;
+ let targetCitySlug = null;
+ if (city) {
+ const found = CITIES.find((x) => x.slug === city.toLowerCase() || x.name.toLowerCase() === city.toLowerCase());
+ if (found) {
+ targetCityName = found.name;
+ targetCitySlug = found.slug;
+ } else {
+ targetCityName = city;
+ }
+ } else if (userContext?.preferredCity) {
+ const found = CITIES.find((x) => x.name.toLowerCase() === userContext.preferredCity.toLowerCase());
+ if (found) {
+ targetCityName = found.name;
+ targetCitySlug = found.slug;
+ }
+ }
+
+ // Handle coordinates if provided and valid
+ let rawEvents = [];
+ const hasCoords = lat != null && lng != null &&
+ !Number.isNaN(Number(lat)) && !Number.isNaN(Number(lng)) &&
+ Number(lat) >= -90 && Number(lat) <= 90 &&
+ Number(lng) >= -180 && Number(lng) <= 180;
+
+ if (hasCoords) {
+ rawEvents = await findNearbyEvents({
+ lat: Number(lat),
+ lng: Number(lng),
+ radiusKm: Number(radiusKm) || 50,
+ citySlug: targetCitySlug,
+ category: category || undefined,
+ limit: 100,
+ includeUnlocated: true
+ }, c);
+ } else {
+ rawEvents = await listPublicEvents({
+ city: targetCityName,
+ category: category || undefined,
+ categories: categories || undefined,
+ from: range.from,
+ to: range.to,
+ q,
+ limit: 100
+ });
+ }
+
+ // Filter by price if requested ('free', 'paid')
+ let filtered = rawEvents;
+ if (price === 'free') {
+ filtered = filtered.filter((e) => {
+ if (e.ticketing === 'tiers') return e.tiers && e.tiers.some((t) => t.kind === 'free' && t.available);
+ return e.pricePaise === 0 || e.priceLabel === 'Free';
+ });
+ } else if (price === 'paid') {
+ filtered = filtered.filter((e) => {
+ if (e.ticketing === 'tiers') return e.tiers && e.tiers.some((t) => t.kind === 'paid');
+ return e.pricePaise && e.pricePaise > 0;
+ });
+ }
+
+ // Apply distance filter if coordinates provided
+ if (hasCoords && radiusKm) {
+ const maxR = Number(radiusKm);
+ filtered = filtered.filter((e) => {
+ if (e.lat == null || e.lng == null) return true; // keep city-level unlocated
+ const d = haversineKm(lat, lng, e.lat, e.lng);
+ return d == null || d <= maxR;
+ });
+ }
+
+ // Decorate each event with saved status and recommendation scoring
+ const decorated = filtered.map((e) => {
+ const isSaved = userContext?.savedEventIds?.has(e.id) || false;
+ const { score, reason } = scoreEventRecommendation(e, userContext, targetCityName);
+ return {
+ ...e,
+ isSaved,
+ recommendationScore: score,
+ recommendationReason: reason
+ };
+ });
+
+ // Sorting
+ if (sort === 'recommended') {
+ decorated.sort((a, b) => b.recommendationScore - a.recommendationScore || new Date(a.startAt) - new Date(b.startAt));
+ } else if (sort === 'trending') {
+ decorated.sort((a, b) => (Number(b.seats_taken || 0)) - (Number(a.seats_taken || 0)) || new Date(a.startAt) - new Date(b.startAt));
+ } else if (sort === 'date_asc') {
+ decorated.sort((a, b) => new Date(a.startAt) - new Date(b.startAt));
+ } else if (sort === 'date_desc') {
+ decorated.sort((a, b) => new Date(b.startAt) - new Date(a.startAt));
+ } else if (sort === 'price_low') {
+ const getPrice = (ev) => {
+ if (ev.ticketing === 'tiers' && ev.tiers?.length) {
+ const prices = ev.tiers.map((t) => (t.kind === 'free' ? 0 : t.pricePaise || 999999));
+ return Math.min(...prices);
+ }
+ return ev.pricePaise != null ? ev.pricePaise : 999999;
+ };
+ decorated.sort((a, b) => getPrice(a) - getPrice(b));
+ }
+
+ // Derive modules: Trending, Featured, and Recommended
+ const trending = decorated.slice(0, 6);
+ const featured = decorated.filter((e) => e.coverUrl || e.isTrip).slice(0, 6);
+ const recommended = decorated.filter((e) => e.recommendationScore >= 30).slice(0, 8);
+
+ const paginated = decorated.slice(offset, offset + limit);
+
+ return {
+ ok: true,
+ total: decorated.length,
+ events: paginated,
+ featured: featured.length ? featured : paginated.slice(0, 4),
+ trending: trending.length ? trending : paginated.slice(0, 4),
+ recommended: recommended.length ? recommended : paginated.slice(0, 4),
+ collections: DISCOVERY_COLLECTIONS,
+ filter: {
+ city: targetCitySlug || '',
+ cityName: targetCityName || '',
+ category: category || '',
+ when: when || '',
+ price: price || '',
+ q: q || '',
+ lat: hasCoords ? Number(lat) : null,
+ lng: hasCoords ? Number(lng) : null,
+ radiusKm: Number(radiusKm) || 50,
+ sort
+ },
+ userContext: userContext ? {
+ preferredCity: userContext.preferredCity,
+ hasInterests: userContext.profileInterests.length > 0,
+ savedCount: userContext.savedEventIds.size
+ } : null
+ };
+}
diff --git a/lib/services/event-announcements.js b/lib/services/event-announcements.js
new file mode 100644
index 0000000..965a1ff
--- /dev/null
+++ b/lib/services/event-announcements.js
@@ -0,0 +1,104 @@
+// lib/services/event-announcements.js - Event announcements and operational updates.
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+import { audit } from '../audit.js';
+import { authorize } from './permissions.js';
+import { enqueue } from './notifications.js';
+
+export async function listEventAnnouncements(user, eventId, c = db) {
+ // Allow organisers, event staff, and attendees of the event
+ const isStaffOrOrg = await authorize(user, 'event.view_guests', { eventId }, c).then(() => true).catch(() => false);
+ if (!isStaffOrOrg) {
+ const isAttendee = (await c.query(
+ `SELECT 1 FROM bookings WHERE event_id = $1 AND user_id = $2 AND status IN ('confirmed', 'checked_in')`,
+ [eventId, user.id]
+ )).rowCount > 0;
+ if (!isAttendee) throw new HttpError(404, 'not_found', 'Event not found');
+ }
+
+ const { rows } = await c.query(
+ `SELECT ea.id, ea.title, ea.message, ea.is_pinned, ea.created_at,
+ u.alias AS sender_alias
+ FROM event_announcements ea
+ JOIN users u ON u.id = ea.sender_user_id
+ WHERE ea.event_id = $1
+ ORDER BY ea.is_pinned DESC, ea.created_at DESC`,
+ [eventId]
+ );
+
+ return rows.map((r) => ({
+ id: r.id,
+ title: r.title,
+ message: r.message,
+ isPinned: Boolean(r.is_pinned),
+ createdAt: r.created_at,
+ senderAlias: r.sender_alias || 'Event Team'
+ }));
+}
+
+export async function createEventAnnouncement(actor, eventId, { title, message, isPinned = false, notifyAttendees = true } = {}, c = db) {
+ await authorize(actor, 'event.announcements', { eventId }, c);
+
+ const t = typeof title === 'string' ? title.trim() : '';
+ const m = typeof message === 'string' ? message.trim() : '';
+
+ if (!t || t.length < 3 || t.length > 120) {
+ throw new HttpError(400, 'validation', 'Title must be between 3 and 120 characters', {
+ fields: [{ field: 'title', message: '3-120 characters required' }]
+ });
+ }
+ if (!m || m.length < 5 || m.length > 3000) {
+ throw new HttpError(400, 'validation', 'Message must be between 5 and 3000 characters', {
+ fields: [{ field: 'message', message: '5-3000 characters required' }]
+ });
+ }
+
+ return c.tx(async (txClient) => {
+ const row = (await txClient.query(
+ `INSERT INTO event_announcements (event_id, sender_user_id, title, message, is_pinned, notify_attendees)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ RETURNING *`,
+ [eventId, actor.id, t, m, Boolean(isPinned), Boolean(notifyAttendees)]
+ )).rows[0];
+
+ let notificationCount = 0;
+ if (notifyAttendees) {
+ const attendees = (await txClient.query(
+ `SELECT DISTINCT user_id FROM bookings WHERE event_id = $1 AND status IN ('confirmed', 'checked_in')`,
+ [eventId]
+ )).rows;
+
+ for (const a of attendees) {
+ await enqueue(txClient, {
+ kind: 'event_update',
+ userId: a.user_id,
+ eventId,
+ announcementId: row.id,
+ title: t,
+ text: m,
+ dedupeKey: `ann:${row.id}:${a.user_id}`
+ });
+ notificationCount++;
+ }
+ }
+
+ await audit(`user:${actor.id}`, 'event.announcement_create', row.id, {
+ eventId,
+ title: t,
+ notifyAttendees: Boolean(notifyAttendees),
+ recipientCount: notificationCount
+ }, txClient);
+
+ return {
+ ok: true,
+ announcement: {
+ id: row.id,
+ title: row.title,
+ message: row.message,
+ isPinned: row.is_pinned,
+ createdAt: row.created_at
+ },
+ notifiedAttendees: notificationCount
+ };
+ });
+}
diff --git a/lib/services/event-staff.js b/lib/services/event-staff.js
new file mode 100644
index 0000000..392dc03
--- /dev/null
+++ b/lib/services/event-staff.js
@@ -0,0 +1,325 @@
+// lib/services/event-staff.js - Event-scoped staff roles and membership management.
+import crypto from 'node:crypto';
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+import { audit } from '../audit.js';
+import { can, authorize } from './permissions.js';
+
+export const VALID_STAFF_ROLES = ['event_manager', 'door_staff', 'guest_list_manager', 'assistant'];
+
+export const STAFF_ROLE_LABELS = {
+ event_manager: 'Event Manager',
+ door_staff: 'Door / Check-in Staff',
+ guest_list_manager: 'Guest-list Manager',
+ assistant: 'Event Assistant (Read-only)'
+};
+
+/**
+ * List all staff members (active & removed) and pending invites for an event.
+ */
+export async function listEventStaff(user, eventId, c = db) {
+ await authorize(user, 'event.view_guests', { eventId }, c);
+
+ const staffRows = (await c.query(
+ `SELECT et.id, et.team_role, et.status, et.created_at, et.updated_at, et.revoked_at, et.notes,
+ u.id AS user_id, u.alias, u.telegram_user_id,
+ inv.alias AS invited_by_alias,
+ rev.alias AS revoked_by_alias
+ FROM event_team et
+ JOIN users u ON u.id = et.user_id
+ LEFT JOIN users inv ON inv.id = et.invited_by
+ LEFT JOIN users rev ON rev.id = et.revoked_by
+ WHERE et.event_id = $1
+ ORDER BY (et.status = 'active') DESC, et.created_at ASC`,
+ [eventId]
+ )).rows;
+
+ const invites = (await c.query(
+ `SELECT esi.id, esi.role, esi.token, esi.invited_alias, esi.status, esi.expires_at, esi.created_at,
+ u.alias AS invited_by_alias
+ FROM event_staff_invites esi
+ JOIN users u ON u.id = esi.invited_by
+ WHERE esi.event_id = $1 AND esi.status = 'pending' AND esi.expires_at > now()
+ ORDER BY esi.created_at DESC`,
+ [eventId]
+ )).rows;
+
+ const canManage = await can(user, 'event.manage_staff', { eventId }, c);
+
+ return {
+ eventId,
+ canManage,
+ staff: staffRows.map((r) => ({
+ id: r.id,
+ userId: r.user_id,
+ alias: r.alias || 'Staff Member',
+ role: r.team_role,
+ roleLabel: STAFF_ROLE_LABELS[r.team_role] || r.team_role,
+ status: r.status,
+ notes: r.notes || null,
+ invitedByAlias: r.invited_by_alias || null,
+ revokedByAlias: r.revoked_by_alias || null,
+ createdAt: r.created_at,
+ revokedAt: r.revoked_at
+ })),
+ invites: invites.map((i) => ({
+ id: i.id,
+ role: i.role,
+ roleLabel: STAFF_ROLE_LABELS[i.role] || i.role,
+ invitedAlias: i.invited_alias || null,
+ invitedByAlias: i.invited_by_alias,
+ token: canManage ? i.token : null,
+ inviteUrl: canManage ? `/staff/join?token=${encodeURIComponent(i.token)}` : null,
+ expiresAt: i.expires_at,
+ createdAt: i.created_at
+ }))
+ };
+}
+
+/**
+ * Assigns or updates a staff member directly by userId.
+ */
+export async function assignEventStaff(actor, eventId, { userId, role, notes = null }, c = db) {
+ if (!VALID_STAFF_ROLES.includes(role)) {
+ throw new HttpError(400, 'validation', `Invalid staff role: choose from ${VALID_STAFF_ROLES.join(', ')}`);
+ }
+ await authorize(actor, 'event.manage_staff', { eventId }, c);
+
+ const targetUser = (await c.query(`SELECT id, alias, status FROM users WHERE id = $1`, [userId])).rows[0];
+ if (!targetUser) throw new HttpError(404, 'user_not_found', 'User not found');
+ if (targetUser.status !== 'active') throw new HttpError(400, 'user_inactive', 'User account is not active');
+
+ // Prevent demoting event owner
+ const event = (await c.query(`SELECT organiser_user_id FROM events WHERE id = $1`, [eventId])).rows[0];
+ if (event?.organiser_user_id === userId) {
+ throw new HttpError(400, 'owner_immutable', 'The event owner cannot be assigned an event staff role');
+ }
+
+ return c.tx(async (txClient) => {
+ const existing = (await txClient.query(
+ `SELECT * FROM event_team WHERE event_id = $1 AND user_id = $2 FOR UPDATE`,
+ [eventId, userId]
+ )).rows[0];
+
+ let row;
+ if (existing) {
+ row = (await txClient.query(
+ `UPDATE event_team
+ SET team_role = $3,
+ status = 'active',
+ invited_by = $4,
+ revoked_by = NULL,
+ revoked_at = NULL,
+ notes = COALESCE($5, notes),
+ updated_at = now()
+ WHERE id = $1 AND event_id = $2
+ RETURNING *`,
+ [existing.id, eventId, role, actor.id, notes]
+ )).rows[0];
+ } else {
+ row = (await txClient.query(
+ `INSERT INTO event_team (event_id, user_id, team_role, status, invited_by, notes)
+ VALUES ($1, $2, $3, 'active', $4, $5)
+ RETURNING *`,
+ [eventId, userId, role, actor.id, notes]
+ )).rows[0];
+ }
+
+ await audit(`user:${actor.id}`, 'event.staff_assign', row.id, {
+ eventId,
+ userId,
+ role,
+ previousRole: existing?.team_role || null,
+ previousStatus: existing?.status || null
+ }, txClient);
+
+ return {
+ ok: true,
+ staff: {
+ id: row.id,
+ userId: row.user_id,
+ alias: targetUser.alias,
+ role: row.team_role,
+ status: row.status
+ }
+ };
+ });
+}
+
+/**
+ * Revokes a staff member's event access with immediate effect.
+ */
+export async function revokeEventStaff(actor, eventId, staffId, c = db) {
+ await authorize(actor, 'event.manage_staff', { eventId }, c);
+
+ return c.tx(async (txClient) => {
+ const row = (await txClient.query(
+ `SELECT * FROM event_team WHERE (id = $1 OR user_id = $1) AND event_id = $2 FOR UPDATE`,
+ [staffId, eventId]
+ )).rows[0];
+
+ if (!row) throw new HttpError(404, 'staff_not_found', 'Staff member not found on this event');
+ if (row.status === 'removed') {
+ return { ok: true, staffId: row.id, status: 'removed' };
+ }
+
+ const now = new Date();
+ await txClient.query(
+ `UPDATE event_team
+ SET status = 'removed',
+ revoked_at = $2,
+ revoked_by = $3,
+ updated_at = $2
+ WHERE id = $1`,
+ [row.id, now, actor.id]
+ );
+
+ await audit(`user:${actor.id}`, 'event.staff_revoke', row.id, {
+ eventId,
+ targetUserId: row.user_id,
+ previousRole: row.team_role
+ }, txClient);
+
+ return { ok: true, staffId: row.id, status: 'removed' };
+ });
+}
+
+/**
+ * Creates a single-use staff invite token.
+ */
+export async function createStaffInvite(actor, eventId, { role, invitedAlias = null, ttlHours = 48 } = {}, c = db) {
+ if (!VALID_STAFF_ROLES.includes(role)) {
+ throw new HttpError(400, 'validation', `Invalid staff role: choose from ${VALID_STAFF_ROLES.join(', ')}`);
+ }
+ await authorize(actor, 'event.manage_staff', { eventId }, c);
+
+ const token = crypto.randomBytes(24).toString('base64url');
+ const expiresAt = new Date(Date.now() + ttlHours * 3600 * 1000);
+
+ const invite = (await c.query(
+ `INSERT INTO event_staff_invites (event_id, role, token, invited_by, invited_alias, expires_at)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ RETURNING *`,
+ [eventId, role, token, actor.id, invitedAlias || null, expiresAt]
+ )).rows[0];
+
+ await audit(`user:${actor.id}`, 'event.staff_invite_create', invite.id, {
+ eventId,
+ role,
+ invitedAlias
+ }, c);
+
+ return {
+ ok: true,
+ inviteId: invite.id,
+ token: invite.token,
+ role: invite.role,
+ expiresAt: invite.expires_at,
+ inviteUrl: `/staff/join?token=${encodeURIComponent(invite.token)}`
+ };
+}
+
+/**
+ * Validates a staff invite token without consuming it.
+ */
+export async function getStaffInvite(token, c = db) {
+ if (!token || typeof token !== 'string') throw new HttpError(400, 'validation', 'Invite token is required');
+
+ const invite = (await c.query(
+ `SELECT esi.*, e.title AS event_title, e.start_at AS event_start_at, e.city AS event_city,
+ u.alias AS invited_by_alias
+ FROM event_staff_invites esi
+ JOIN events e ON e.id = esi.event_id
+ JOIN users u ON u.id = esi.invited_by
+ WHERE esi.token = $1`,
+ [token.trim()]
+ )).rows[0];
+
+ if (!invite) throw new HttpError(404, 'invalid_invite', 'This invite link is invalid or does not exist');
+ if (invite.status !== 'pending' || new Date(invite.expires_at) <= new Date()) {
+ throw new HttpError(410, 'expired_invite', 'This invite link has expired or has already been used');
+ }
+
+ return {
+ id: invite.id,
+ eventId: invite.event_id,
+ eventTitle: invite.event_title,
+ eventCity: invite.event_city,
+ eventStartAt: invite.event_start_at,
+ role: invite.role,
+ roleLabel: STAFF_ROLE_LABELS[invite.role] || invite.role,
+ invitedByAlias: invite.invited_by_alias,
+ expiresAt: invite.expires_at
+ };
+}
+
+/**
+ * Consumes a staff invite token and adds the user to event_team.
+ */
+export async function acceptStaffInvite(user, token, c = db) {
+ if (!user || !user.id) throw new HttpError(401, 'unauthorized', 'Please sign in to accept this staff invitation');
+
+ return c.tx(async (txClient) => {
+ const invite = (await txClient.query(
+ `SELECT * FROM event_staff_invites WHERE token = $1 FOR UPDATE`,
+ [token.trim()]
+ )).rows[0];
+
+ if (!invite) throw new HttpError(404, 'invalid_invite', 'This invite link is invalid');
+ if (invite.status !== 'pending' || new Date(invite.expires_at) <= new Date()) {
+ throw new HttpError(410, 'expired_invite', 'This invite link has expired or has already been used');
+ }
+
+ // Add or update event_team row
+ const existing = (await txClient.query(
+ `SELECT * FROM event_team WHERE event_id = $1 AND user_id = $2 FOR UPDATE`,
+ [invite.event_id, user.id]
+ )).rows[0];
+
+ let row;
+ if (existing) {
+ row = (await txClient.query(
+ `UPDATE event_team
+ SET team_role = $3,
+ status = 'active',
+ invited_by = $4,
+ revoked_by = NULL,
+ revoked_at = NULL,
+ updated_at = now()
+ WHERE id = $1
+ RETURNING *`,
+ [existing.id, invite.event_id, invite.role, invite.invited_by]
+ )).rows[0];
+ } else {
+ row = (await txClient.query(
+ `INSERT INTO event_team (event_id, user_id, team_role, status, invited_by)
+ VALUES ($1, $2, $3, 'active', $4)
+ RETURNING *`,
+ [invite.event_id, user.id, invite.role, invite.invited_by]
+ )).rows[0];
+ }
+
+ // Mark invite accepted
+ await txClient.query(
+ `UPDATE event_staff_invites
+ SET status = 'accepted',
+ accepted_by = $2,
+ accepted_at = now()
+ WHERE id = $1`,
+ [invite.id, user.id]
+ );
+
+ await audit(`user:${user.id}`, 'event.staff_invite_accept', invite.id, {
+ eventId: invite.event_id,
+ role: invite.role,
+ teamMemberId: row.id
+ }, txClient);
+
+ return {
+ ok: true,
+ eventId: invite.event_id,
+ role: invite.role,
+ roleLabel: STAFF_ROLE_LABELS[invite.role] || invite.role
+ };
+ });
+}
diff --git a/lib/services/events.js b/lib/services/events.js
index 3ea2911..575578e 100644
--- a/lib/services/events.js
+++ b/lib/services/events.js
@@ -1,7 +1,7 @@
// lib/services/events.js - Event queries and the public (privacy-safe) representation.
import { db } from '../db.js';
import { socialProofMin } from '../config.js';
-import { ticketCheckoutStatus } from '../payments/availability.js';
+import { checkoutForEvent } from '../payments/availability.js';
export const CATEGORY_LABELS = {
meetup: 'Meetup',
@@ -10,7 +10,7 @@ export const CATEGORY_LABELS = {
dinner_club: 'Dinner club',
movie: 'Movie night',
board_games: 'Board games',
- weekend_trip: 'Strangers trip',
+ weekend_trip: 'Weekend trip',
resort_getaway: 'Resort getaway',
weekend_party: 'Weekend party',
matchmaking: 'Matchmaking',
@@ -18,12 +18,49 @@ export const CATEGORY_LABELS = {
workshop: 'Workshop'
};
export const TRIP_CATEGORIES = ['weekend_trip', 'resort_getaway'];
+
+/**
+ * Format distance into privacy-preserving coarse distance bands.
+ * Prevents exact trilateration of private venues while giving attendees clear proximity info.
+ */
+export function formatDistanceBand(distanceKm) {
+ if (distanceKm == null) return null;
+ const d = Number(distanceKm);
+ if (Number.isNaN(d) || d < 0) return null;
+ if (d < 1) return '< 1 km away';
+ if (d < 3) return '~2 km away';
+ if (d < 6) return '~5 km away';
+ if (d < 12) return '~10 km away';
+ if (d < 25) return '~20 km away';
+ if (d < 50) return '~30–50 km away';
+ return `~${Math.round(d / 10) * 10} km away`;
+}
+
export const CITIES = [
- { slug: 'chennai', name: 'Chennai', state: 'Tamil Nadu' },
- { slug: 'bengaluru', name: 'Bengaluru', state: 'Karnataka' },
- { slug: 'coimbatore', name: 'Coimbatore', state: 'Tamil Nadu' },
- { slug: 'kochi', name: 'Kochi', state: 'Kerala' },
- { slug: 'puducherry', name: 'Puducherry', state: 'Puducherry' }
+ // Primary Markets
+ { slug: 'chennai', name: 'Chennai', state: 'Tamil Nadu', marketTier: 'primary_market' },
+ { slug: 'bengaluru', name: 'Bengaluru', state: 'Karnataka', marketTier: 'primary_market' },
+ { slug: 'coimbatore', name: 'Coimbatore', state: 'Tamil Nadu', marketTier: 'primary_market' },
+ { slug: 'kochi', name: 'Kochi', state: 'Kerala', marketTier: 'primary_market' },
+ { slug: 'puducherry', name: 'Puducherry', state: 'Puducherry', marketTier: 'primary_market' },
+
+ // Expansion Markets
+ { slug: 'mysuru', name: 'Mysuru', state: 'Karnataka', marketTier: 'expansion_market' },
+ { slug: 'mangaluru', name: 'Mangaluru', state: 'Karnataka', marketTier: 'expansion_market' },
+ { slug: 'madurai', name: 'Madurai', state: 'Tamil Nadu', marketTier: 'expansion_market' },
+ { slug: 'salem', name: 'Salem', state: 'Tamil Nadu', marketTier: 'expansion_market' },
+ { slug: 'tiruchirappalli', name: 'Tiruchirappalli', state: 'Tamil Nadu', marketTier: 'expansion_market' },
+ { slug: 'thiruvananthapuram', name: 'Thiruvananthapuram', state: 'Kerala', marketTier: 'expansion_market' },
+ { slug: 'kozhikode', name: 'Kozhikode', state: 'Kerala', marketTier: 'expansion_market' },
+
+ // Getaway Destinations
+ { slug: 'ooty', name: 'Ooty', state: 'Tamil Nadu', marketTier: 'getaway_destination' },
+ { slug: 'kodaikanal', name: 'Kodaikanal', state: 'Tamil Nadu', marketTier: 'getaway_destination' },
+ { slug: 'coorg', name: 'Coorg', state: 'Karnataka', marketTier: 'getaway_destination' },
+ { slug: 'gokarna', name: 'Gokarna', state: 'Karnataka', marketTier: 'getaway_destination' },
+ { slug: 'chikmagalur', name: 'Chikmagalur', state: 'Karnataka', marketTier: 'getaway_destination' },
+ { slug: 'varkala', name: 'Varkala', state: 'Kerala', marketTier: 'getaway_destination' },
+ { slug: 'wayanad', name: 'Wayanad', state: 'Kerala', marketTier: 'getaway_destination' }
];
/** SQL fragment: bookings that currently occupy seats (live holds + confirmed). Sum b.quantity. */
@@ -50,15 +87,19 @@ function list(v) {
}
/** Public view of one ticket tier. `sold` = confirmed seats, `held` = live checkout holds. */
-export function toPublicTier(t, { checkout, showCounts = false } = {}) {
- const used = Number(t.sold || 0) + Number(t.held || 0);
- const remaining = Math.max(0, t.quantity - used);
+export function toPublicTier(t, { checkout, showCounts = false, requiresApproval = false } = {}) {
const free = t.kind === 'free';
+ // A paid ticket is sold by SuperProfile, which owns its stock; our own booking counts say nothing about it.
+ const sellsOnSuperprofile = !free && Boolean(checkout?.available);
+ const used = sellsOnSuperprofile ? 0 : Number(t.sold || 0) + Number(t.held || 0);
+ const remaining = Math.max(0, t.quantity - used);
let unavailable = null;
if (remaining <= 0) {
unavailable = Number(t.held || 0) > 0 ? 'Temporarily full — may reopen if a held spot is released' : 'Sold out';
} else if (!free && !checkout?.available) {
unavailable = 'Online payment not available yet';
+ } else if (!free && requiresApproval) {
+ unavailable = 'Paid tickets can’t be approval-only yet';
}
return {
id: t.id,
@@ -68,7 +109,7 @@ export function toPublicTier(t, { checkout, showCounts = false } = {}) {
priceLabel: free ? 'Free' : formatPaise(t.price_paise),
quantity: t.quantity,
remaining,
- remainingLabel: showCounts ? `${remaining} of ${t.quantity} left` : null,
+ remainingLabel: showCounts && !sellsOnSuperprofile ? `${remaining} of ${t.quantity} left` : null,
maxPerBooking: t.max_per_booking,
validOn: t.valid_on ? String(t.valid_on).slice(0, 10) : null,
eligibility: t.eligibility || null,
@@ -91,13 +132,15 @@ function tiersPriceLabel(tiers) {
* Map a DB row to what the public site may show. Never includes venue_private unless the
* event's venue is public. `seats_taken` is an internal number used only to decide "Sold out".
*/
-export function toPublicEvent(row, { checkout = ticketCheckoutStatus() } = {}) {
+export function toPublicEvent(row, { checkout = checkoutForEvent(row) } = {}) {
const external = row.source === 'external';
const tiered = row.ticketing === 'tiers';
const features = row.features && typeof row.features === 'object' ? row.features : {};
- const tiers = tiered ? list(row.tiers).map((t) => toPublicTier(t, { checkout, showCounts: Boolean(features.balance) })) : [];
+ const tiers = tiered ? list(row.tiers).map((t) => toPublicTier(t, { checkout, showCounts: Boolean(features.balance), requiresApproval: Boolean(row.requires_approval) })) : [];
// External listings: we know nothing about seats or price, so we never claim either.
- const soldOut = !external && row.capacity > 0 && (Number(row.seats_taken || 0) >= row.capacity ||
+ // SuperProfile sells its own stock, so a linked event is never "sold out" from our booking counts alone.
+ const sp = !external && checkout.available;
+ const soldOut = !external && !(sp && !tiered) && row.capacity > 0 && (Number(row.seats_taken || 0) >= row.capacity ||
(tiered && tiers.length > 0 && tiers.every((t) => t.remaining <= 0)));
const priceSet = tiered ? tiers.length > 0 : row.price_status === 'set' && row.ticket_price_paise > 0;
const upcoming = new Date(row.start_at).getTime() > Date.now();
@@ -107,8 +150,9 @@ export function toPublicEvent(row, { checkout = ticketCheckoutStatus() } = {}) {
else if (!upcoming) state = 'past';
else if (external) state = 'external';
else if (soldOut) state = 'sold_out';
- else if (!priceSet) state = 'price_tbd';
+ else if (!priceSet && !sp) state = 'price_tbd';
else if (tiered && !tiers.some((t) => t.available)) state = 'payment_unavailable';
+ else if (!tiered && !sp) state = 'payment_unavailable';
else state = 'open';
const STATE_LABEL = {
cancelled: 'Cancelled',
@@ -129,16 +173,23 @@ export function toPublicEvent(row, { checkout = ticketCheckoutStatus() } = {}) {
categoryLabel: CATEGORY_LABELS[row.category] || row.category,
isTrip: isTrip(row.category),
city: row.city,
+ cityId: row.city_id || null,
+ localityId: row.locality_id || null,
area: row.area_public || '',
venue: venuePublic ? (row.venue_private || '') : '',
venuePrivacy: row.venue_privacy,
+ coordsProvenance: row.coords_provenance || (row.lat != null ? 'city' : 'none'),
+ lat: venuePublic && row.coords_provenance === 'venue' && row.lat != null ? Number(row.lat) : null,
+ lng: venuePublic && row.coords_provenance === 'venue' && row.lng != null ? Number(row.lng) : null,
+ distanceKm: venuePublic ? (row.distance_km != null ? Math.round(Number(row.distance_km) * 10) / 10 : null) : null,
+ distanceBand: formatDistanceBand(row.distance_km),
// Same rule as the venue: a private venue's map link is only on a confirmed guest's booking.
mapsUrl: venuePublic ? (row.maps_url || null) : null,
startAt: new Date(row.start_at).toISOString(),
endAt: row.end_at ? new Date(row.end_at).toISOString() : null,
timezone: row.timezone,
capacity: row.capacity,
- priceLabel: external ? 'Price set by organiser' : tiered ? tiersPriceLabel(tiers) : priceSet ? formatPaise(row.ticket_price_paise) : 'Price to be announced',
+ priceLabel: external ? 'Price set by organiser' : tiered ? tiersPriceLabel(tiers) : priceSet ? formatPaise(row.ticket_price_paise) : sp ? 'Price shown at checkout' : 'Price to be announced',
pricePaise: !tiered && priceSet ? row.ticket_price_paise : null,
ticketing: tiered ? 'tiers' : 'single',
tiers,
@@ -151,13 +202,15 @@ export function toPublicEvent(row, { checkout = ticketCheckoutStatus() } = {}) {
balance: Boolean(features.balance),
organiserManaged: Boolean(row.organiser_user_id),
checkoutAvailable: Boolean(checkout?.available),
+ checkoutMode: sp ? (checkout.provider === 'phonepe' ? 'upi_direct' : 'superprofile') : (row.checkout_mode === 'upi_direct' ? 'upi_direct' : 'none'),
+ checkoutPath: (sp || row.checkout_mode === 'upi_direct') ? `/checkout/${row.slug}` : null,
inclusions: arr(row.inclusions),
exclusions: arr(row.exclusions),
refundPolicy: row.refund_policy || '',
genderPolicy: row.gender_policy || '',
foodAvailable: row.food_available,
stayAvailable: row.stay_available,
- organizer: row.organizer || (external ? row.source_name : 'StrangersMeetup'),
+ organizer: row.organizer || (external ? row.source_name : 'NIGHTLIFEZ'),
isExternal: external,
externalUrl: external ? row.external_url : null,
sourceName: external ? row.source_name : null,
@@ -188,7 +241,7 @@ const PUBLIC_SELECT = `
${TIERS_SQL} AS tiers
FROM events e`;
-export async function listPublicEvents({ city, category, categories, kind = 'all', from, to, limit = 60 } = {}) {
+export async function listPublicEvents({ city, category, categories, kind = 'all', from, to, q, limit = 60 } = {}) {
const where = [`e.status = 'published'`, `COALESCE(e.end_at, e.start_at) > now()`];
const params = [];
const p = (v) => { params.push(v); return `$${params.length}`; };
@@ -199,6 +252,10 @@ export async function listPublicEvents({ city, category, categories, kind = 'all
if (kind === 'trips') where.push(`e.category IN ('weekend_trip', 'resort_getaway')`);
if (from) where.push(`e.start_at >= ${p(from)}`);
if (to) where.push(`e.start_at < ${p(to)}`);
+ if (q && q.trim()) {
+ const term = `%${q.trim()}%`;
+ where.push(`(e.title ILIKE ${p(term)} OR e.summary ILIKE ${p(term)} OR e.description ILIKE ${p(term)} OR e.city ILIKE ${p(term)} OR e.area_public ILIKE ${p(term)})`);
+ }
const { rows } = await db.query(
`${PUBLIC_SELECT} WHERE ${where.join(' AND ')} ORDER BY e.is_demo ASC, e.start_at ASC LIMIT ${p(Math.min(limit, 100))}`,
params
diff --git a/lib/services/feeds.js b/lib/services/feeds.js
index c81c489..837947a 100644
--- a/lib/services/feeds.js
+++ b/lib/services/feeds.js
@@ -6,11 +6,13 @@ import crypto from 'node:crypto';
import dns from 'node:dns/promises';
import net from 'node:net';
import { XMLParser } from 'fast-xml-parser';
+import { Agent } from 'undici';
import { db } from '../db.js';
import { HttpError } from '../http.js';
import { siteUrl } from '../config.js';
import { audit } from '../audit.js';
import { logger } from '../logger.js';
+import { resolveCity } from './locations.js';
export const FEED_UA = 'StrangersMeetupBot/1.0';
const MAX_FEED_BYTES = 2 * 1024 * 1024;
@@ -44,21 +46,53 @@ export function slugify(title, startAt) {
// ---------- SSRF-safe fetch ----------
-function isPrivateIp(ip) {
- if (net.isIPv4(ip)) {
- const [a, b] = ip.split('.').map(Number);
- return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||
- (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 198 && (b === 18 || b === 19)) || a >= 224;
- }
- const v = ip.toLowerCase();
- if (v.startsWith('::ffff:')) return isPrivateIp(v.slice(7));
- return v === '::' || v === '::1' || v.startsWith('fc') || v.startsWith('fd') || v.startsWith('fe8') || v.startsWith('fe9') ||
- v.startsWith('fea') || v.startsWith('feb') || v.startsWith('ff');
+// Everything that is not ordinary public unicast: private, loopback, link-local, CGNAT, benchmarking,
+// documentation, multicast/reserved, plus IPv6 transition prefixes that can embed a private IPv4
+// (NAT64, 6to4, Teredo) and the deprecated site-local range.
+const BLOCKED = new net.BlockList();
+for (const [net4, bits] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16],
+ ['172.16.0.0', 12], ['192.0.0.0', 24], ['192.0.2.0', 24], ['192.88.99.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15],
+ ['198.51.100.0', 24], ['203.0.113.0', 24], ['224.0.0.0', 3]]) BLOCKED.addSubnet(net4, bits, 'ipv4');
+// net.BlockList matches IPv4-mapped IPv6 (::ffff:a.b.c.d, also in hex) against the IPv4 rules above.
+for (const [net6, bits] of [['::', 96], ['64:ff9b::', 96], ['64:ff9b:1::', 48], ['100::', 64], ['2001::', 32], ['2001:db8::', 32],
+ ['2002::', 16], ['fc00::', 7], ['fe80::', 10], ['fec0::', 10], ['ff00::', 8]]) BLOCKED.addSubnet(net6, bits, 'ipv6');
+
+export function isPrivateIp(ip) {
+ const v = String(ip).toLowerCase();
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v);
+ if (mapped) return isPrivateIp(mapped[1]);
+ if (net.isIPv4(v)) return BLOCKED.check(v, 'ipv4');
+ if (net.isIPv6(v)) return BLOCKED.check(v, 'ipv6');
+ return true; // not an IP address at all: refuse
}
/** DNS resolution, replaceable in tests. */
export const resolver = { lookup: (host) => dns.lookup(host, { all: true }) };
+/**
+ * DNS lookup for outgoing feed connections. It resolves, refuses the connection if any answer is
+ * private, and hands the socket the address it just checked, so a second (rebound) DNS answer can
+ * never be the one we connect to. TLS still verifies the certificate against the URL's hostname.
+ */
+export function pinnedLookup(hostname, options, callback) {
+ const opts = typeof options === 'object' && options ? options : {};
+ resolver.lookup(hostname).then((addrs) => {
+ if (!addrs.length) throw Object.assign(new Error(`${hostname} does not resolve`), { code: 'ENOTFOUND' });
+ if (addrs.some((a) => isPrivateIp(a.address))) throw Object.assign(new Error(`${hostname} resolves to a private address`), { code: 'EPRIVATEADDR' });
+ const list = addrs.map((a) => ({ address: a.address, family: a.family || net.isIP(a.address) }));
+ if (opts.all) callback(null, list);
+ else callback(null, list[0].address, list[0].family);
+ }).catch((err) => callback(err));
+}
+
+/** A dispatcher whose sockets connect only to addresses `lookup` returns; TLS options stay at Node's verifying defaults. */
+export function createFeedDispatcher(lookup = pinnedLookup) {
+ return new Agent({ connect: { lookup }, connections: 4 });
+}
+
+/** Feed requests go through this dispatcher only: no other code shares its connection pool. */
+export const feedDispatcher = createFeedDispatcher();
+
export async function assertPublicHttpsUrl(raw) {
let u;
try { u = new URL(raw); } catch { throw new HttpError(400, 'invalid_url', 'Invalid URL'); }
@@ -80,6 +114,7 @@ export async function safeFetch(url, headers = {}, { maxBytes = MAX_FEED_BYTES }
const res = await fetch(current, {
headers: { 'User-Agent': `${FEED_UA} (+${siteUrl()})`, Accept: 'application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.8, */*;q=0.1', ...headers },
redirect: 'manual',
+ dispatcher: feedDispatcher,
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
});
if ([301, 302, 303, 307, 308].includes(res.status)) {
@@ -395,14 +430,21 @@ export async function approveCandidate(id, d, actor) {
const sourceName = external ? (d.source_name || feed?.attribution || cand.organizer) : null;
if (external && !sourceName) throw new HttpError(400, 'validation', 'Name the source to attribute', { fields: [{ field: 'source_name', message: 'Required' }] });
const status = d.publish && external ? 'published' : 'draft';
+ const resolvedCity = await resolveCity(d.city, c);
+ const canonicalCity = resolvedCity ? resolvedCity.name : d.city;
+ const cityId = resolvedCity ? resolvedCity.id : null;
+ const lat = resolvedCity ? resolvedCity.lat : null;
+ const lng = resolvedCity ? resolvedCity.lng : null;
+ const coordsProvenance = resolvedCity ? 'city' : 'none';
+
let ev;
try {
ev = (await c.query(
- `INSERT INTO events (slug, category, title, summary, description, city, area_public, venue_private, venue_privacy, start_at, end_at, capacity,
+ `INSERT INTO events (slug, category, title, summary, description, city, city_id, lat, lng, coords_provenance, area_public, venue_private, venue_privacy, start_at, end_at, capacity,
price_status, organizer, source, external_url, source_name, source_url, feed_id, dedupe_key, status, published_at)
- VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,'tbd',$13,$14,$15,$16,$17,$18,$19,$20::event_status, CASE WHEN $20::text = 'published' THEN now() END)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,'tbd',$17,$18,$19,$20,$21,$22,$23,$24::event_status, CASE WHEN $24::text = 'published' THEN now() END)
RETURNING id, slug, status`,
- [slugify(d.title, d.start_at), d.category, d.title, d.summary || null, d.summary || null, d.city, d.area || null,
+ [slugify(d.title, d.start_at), d.category, d.title, d.summary || null, d.summary || null, canonicalCity, cityId, lat, lng, coordsProvenance, d.area || null,
d.venue || null, external ? 'public' : 'disclosed_after_booking', d.start_at, d.end_at || null,
external ? 0 : (d.capacity || 10), d.organizer || (external ? sourceName : null), external ? 'external' : 'internal',
external ? d.external_url : null, sourceName, external ? (feed?.site_url || null) : null, cand.feed_id, key, status])).rows[0];
diff --git a/lib/services/insights.js b/lib/services/insights.js
index 1b3d69d..958afc1 100644
--- a/lib/services/insights.js
+++ b/lib/services/insights.js
@@ -153,7 +153,17 @@ async function revenue(since) {
if (!superprofileConfigured() && !sp.events) superprofile = na('SuperProfile is not connected (SUPERPROFILE_WEBHOOK_SECRET not set, no events received).');
else if (sp.events && !sp.with_amount) superprofile = na('SuperProfile events were received but carried no amount field.');
else superprofile = ok(int(sp.paise), { unit: 'paise', note: 'As reported by SuperProfile via automation; not reconciled with payouts.', purchases: sp.events });
+ const tix = await db.one(
+ `SELECT COALESCE(sum(amount_paise) FILTER (WHERE status = 'paid'), 0)::bigint AS paid,
+ COALESCE(sum(amount_paise) FILTER (WHERE status IN ('refunded', 'cancelled')), 0)::bigint AS refunded,
+ count(*) FILTER (WHERE status = 'paid')::int AS orders,
+ count(*) FILTER (WHERE match_state <> 'matched' AND status = 'paid')::int AS unconfirmed
+ FROM external_orders WHERE received_at >= $1`, [since]);
return {
+ superprofileTickets: ok(int(tix.paid), {
+ unit: 'paise', orders: tix.orders, refunded: int(tix.refunded),
+ note: tix.unconfirmed ? `${tix.unconfirmed} paid order(s) are unmatched or flagged and have no confirmed booking yet.` : 'Paid ticket orders reported by SuperProfile; refunds are shown separately.'
+ }),
liveTicketGross: ok(int(r.live_gross), { unit: 'paise', note: live ? undefined : 'Live payments are disabled (ENABLE_LIVE_PAYMENTS=false).' }),
liveTicketRefunded: ok(int(r.live_refunded), { unit: 'paise' }),
sandboxTicketGross: ok(int(r.test_gross), { unit: 'paise', note: 'Test-mode payments — not real money.' }),
@@ -219,7 +229,8 @@ async function membership(since) {
`SELECT count(*) FILTER (WHERE event_type = 'purchase')::int AS purchases,
count(*) FILTER (WHERE event_type = 'purchase_abandoned')::int AS abandoned,
count(*) FILTER (WHERE event_type = 'purchase' AND email_hash IS NULL)::int AS no_email,
- (SELECT count(DISTINCT product_ref)::int FROM superprofile_events WHERE tier_id IS NULL AND product_ref IS NOT NULL) AS unmapped
+ (SELECT count(DISTINCT product_ref)::int FROM superprofile_events WHERE tier_id IS NULL AND product_ref IS NOT NULL)
+ + (SELECT count(DISTINCT product_id)::int FROM external_orders WHERE event_id IS NULL AND product_id IS NOT NULL) AS unmapped
FROM superprofile_events WHERE COALESCE(occurred_at, received_at) >= $1`, [since]);
const note = anySp.n ? undefined : 'Connected, but no SuperProfile events have been received yet.';
superprofile = {
@@ -228,7 +239,7 @@ async function membership(since) {
renewalsInWindow: ok(Math.max(0, e.purchases - m.new_in_window)),
expiredInWindow: ok(m.expired_in_window),
abandonedInWindow: ok(e.abandoned),
- unmappedProducts: ok(e.unmapped, { note: 'Products not linked to a tier (set the product reference on the tier).' })
+ unmappedProducts: ok(e.unmapped, { note: 'Products not linked to a tier or an event (set the product reference on the tier, or the product id on the event).' })
};
}
return { stars, superprofile, note: 'Stars and SuperProfile members are counted separately; one person could appear in both.' };
diff --git a/lib/services/invites.js b/lib/services/invites.js
index 12ee889..8aba6b2 100644
--- a/lib/services/invites.js
+++ b/lib/services/invites.js
@@ -14,7 +14,9 @@ export class ChatNotConfiguredError extends Error {
}
export function eventChatId(event) {
- return event.telegram_chat_id ?? chatIdFromEnv('TG_CHAT_ID_EVENTS');
+ // Separate private groups for individual events.
+ // Never fall back to a shared chat across multiple events.
+ return event.telegram_chat_id ?? null;
}
export function tierChatId(tier) {
@@ -43,20 +45,35 @@ async function create({ chatId, userId, bookingId = null, entitlementId = null,
return row;
}
-/** Invite for a confirmed booking → event chat. Reuses a still-valid invite. */
+/**
+ * Invite for a confirmed booking → event chat.
+ * Reuses a still-valid invite.
+ * Returns null if event has no dedicated private group configured (no global shared attendee group).
+ */
export async function inviteForBooking(bookingId) {
const b = await db.one(
`SELECT b.id, b.user_id, b.status, e.telegram_chat_id, e.slug, e.organiser_user_id FROM bookings b JOIN events e ON e.id = b.event_id WHERE b.id = $1`, [bookingId]);
if (!b || !['confirmed', 'checked_in'].includes(b.status)) return null;
- // Independent organisers' guests are never added to the platform's shared events chat.
- if (b.organiser_user_id && b.telegram_chat_id === null) return null;
+ // Events must have their own private group configured. If none is configured, do not fall back to a shared chat.
+ if (b.telegram_chat_id === null) return null;
const existing = await activeInvite({ bookingId });
if (existing) return existing;
const chatId = eventChatId(b);
- if (chatId === null) throw new ChatNotConfiguredError('events (TG_CHAT_ID_EVENTS)');
+ if (chatId === null) return null;
return create({ chatId, userId: b.user_id, bookingId, name: `bk ${b.slug}` });
}
+/** Revoke all active invites for a booking (e.g. upon cancellation or refund). */
+export async function revokeBookingInvites(bookingId) {
+ const { rows } = await db.query(
+ `UPDATE invite_links SET revoked_at = now()
+ WHERE booking_id = $1 AND revoked_at IS NULL
+ RETURNING id, chat_id, user_id`,
+ [bookingId]
+ );
+ return rows;
+}
+
/** Invite for an active membership → that tier's chat. */
export async function inviteForEntitlement(entitlementId) {
const e = await db.one(
diff --git a/lib/services/locations.js b/lib/services/locations.js
new file mode 100644
index 0000000..98ca9d1
--- /dev/null
+++ b/lib/services/locations.js
@@ -0,0 +1,311 @@
+// lib/services/locations.js - India Location Intelligence Foundation based on official Local Government Directory (LGD).
+// Provides state/district/city/locality queries, alias matching, and geospatial nearby event discovery.
+import { db } from '../db.js';
+import { SEAT_HOLDING_SQL, TIERS_SQL, toPublicEvent, formatDistanceBand } from './events.js';
+
+export { formatDistanceBand };
+
+/**
+ * Pure JS Haversine distance in kilometers (mean Earth radius 6371 km).
+ * Matches PostgreSQL haversine_km() function from migration 013.
+ */
+export function haversineKm(lat1, lng1, lat2, lng2) {
+ if (lat1 == null || lng1 == null || lat2 == null || lng2 == null) return null;
+ const numLat1 = Number(lat1);
+ const numLng1 = Number(lng1);
+ const numLat2 = Number(lat2);
+ const numLng2 = Number(lng2);
+ if (Number.isNaN(numLat1) || Number.isNaN(numLng1) || Number.isNaN(numLat2) || Number.isNaN(numLng2)) return null;
+
+ const R = 6371.0;
+ const dLat = (numLat2 - numLat1) * (Math.PI / 180.0);
+ const dLng = (numLng2 - numLng1) * (Math.PI / 180.0);
+ const a = (Math.sin(dLat / 2.0) ** 2) +
+ Math.cos(numLat1 * (Math.PI / 180.0)) * Math.cos(numLat2 * (Math.PI / 180.0)) *
+ (Math.sin(dLng / 2.0) ** 2);
+ const clamped = Math.min(1.0, Math.max(0.0, a));
+ const c = 2.0 * Math.asin(Math.sqrt(clamped));
+ return R * c;
+}
+
+/**
+ * List official States and Union Territories with verified LGD codes.
+ */
+export async function listStates({ activeOnly = true, type = null } = {}, c = db) {
+ const conditions = [];
+ const params = [];
+ if (activeOnly) {
+ conditions.push('active = true');
+ }
+ if (type) {
+ params.push(type);
+ conditions.push(`type = $${params.length}`);
+ }
+ const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
+ const { rows } = await c.query(
+ `SELECT id, country_code, lgd_code, name, type, state_code, active, source_url, source_date, verified
+ FROM location_states
+ ${where}
+ ORDER BY name ASC`, params);
+ return rows;
+}
+
+/**
+ * List official Districts for a State (initial focus: TN, PY, KA, KL) with official LGD codes.
+ */
+export async function listDistricts({ stateId = null, stateLgdCode = null, activeOnly = true } = {}, c = db) {
+ const conditions = [];
+ const params = [];
+ if (activeOnly) {
+ conditions.push('d.active = true');
+ }
+ if (stateId) {
+ params.push(stateId);
+ conditions.push(`d.state_id = $${params.length}`);
+ }
+ if (stateLgdCode) {
+ params.push(stateLgdCode);
+ conditions.push(`d.state_lgd_code = $${params.length}`);
+ }
+ const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
+ const { rows } = await c.query(
+ `SELECT d.id, d.state_id, d.state_lgd_code, d.lgd_code, d.name, d.census_2011_code, d.active,
+ d.source_url, d.source_date, d.verified, s.name AS state_name
+ FROM location_districts d
+ JOIN location_states s ON s.id = d.state_id
+ ${where}
+ ORDER BY d.name ASC`, params);
+ return rows;
+}
+
+/**
+ * List cities/towns with coordinates, aliases, LGD mapping, and NIGHTLIFEZ business market tier.
+ * Supports query matching against name, slug, local_name, and aliases.
+ */
+export async function listCities({
+ activeOnly = true,
+ discoveryOnly = false,
+ stateId = null,
+ districtId = null,
+ q = null
+} = {}, c = db) {
+ const conditions = [];
+ const params = [];
+ if (activeOnly) conditions.push('c.active = true');
+ if (discoveryOnly) conditions.push('c.is_discovery_active = true');
+ if (stateId) {
+ params.push(stateId);
+ conditions.push(`c.state_id = $${params.length}`);
+ }
+ if (districtId) {
+ params.push(districtId);
+ conditions.push(`c.district_id = $${params.length}`);
+ }
+ if (q && q.trim()) {
+ params.push(`%${q.trim()}%`);
+ const pIdx = params.length;
+ conditions.push(`(
+ c.name ILIKE $${pIdx}
+ OR c.slug ILIKE $${pIdx}
+ OR (c.local_name IS NOT NULL AND c.local_name ILIKE $${pIdx})
+ OR EXISTS (SELECT 1 FROM unnest(c.aliases) a WHERE a ILIKE $${pIdx})
+ )`);
+ }
+ const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
+ const { rows } = await c.query(
+ `SELECT c.id, c.slug, c.name, c.local_name, c.lgd_code, c.lat, c.lng, c.aliases, c.market_tier,
+ c.active, c.is_discovery_active, c.source_url, c.source_date, c.verified,
+ s.name AS state_name, s.state_code, s.lgd_code AS state_lgd_code,
+ d.name AS district_name, d.lgd_code AS district_lgd_code
+ FROM location_cities c
+ JOIN location_states s ON s.id = c.state_id
+ LEFT JOIN location_districts d ON d.id = c.district_id
+ ${where}
+ ORDER BY
+ CASE c.market_tier
+ WHEN 'primary_market' THEN 1
+ WHEN 'expansion_market' THEN 2
+ WHEN 'getaway_destination' THEN 3
+ ELSE 4
+ END,
+ c.name ASC`, params);
+ return rows;
+}
+
+/**
+ * Fetch a single city by slug, name, or alias.
+ */
+export async function getCityBySlug(slug, c = db) {
+ if (!slug || typeof slug !== 'string') return null;
+ const term = slug.trim();
+ const row = await c.one(
+ `SELECT c.id, c.slug, c.name, c.local_name, c.lgd_code, c.lat, c.lng, c.aliases, c.market_tier,
+ c.active, c.is_discovery_active, c.source_url, c.source_date, c.verified,
+ s.name AS state_name, s.state_code, s.lgd_code AS state_lgd_code,
+ d.name AS district_name, d.lgd_code AS district_lgd_code
+ FROM location_cities c
+ JOIN location_states s ON s.id = c.state_id
+ LEFT JOIN location_districts d ON d.id = c.district_id
+ WHERE lower(c.slug) = lower($1)
+ OR lower(c.name) = lower($1)
+ OR EXISTS (SELECT 1 FROM unnest(c.aliases) a WHERE lower(a) = lower($1))
+ LIMIT 1`, [term]);
+ return row;
+}
+
+/**
+ * Resolve an input city string (name, slug, or alias) against official location_cities.
+ * Returns the matched city record with canonical name, coordinates, and market tier,
+ * or null if the city is not in the directory.
+ * Never guesses an unsupported city.
+ */
+export async function resolveCity(term, c = db) {
+ if (!term || typeof term !== 'string') return null;
+ const cleanTerm = term.trim();
+ if (cleanTerm.length < 2) return null;
+ const { rows } = await c.query(
+ `SELECT c.id, c.slug, c.name, c.local_name, c.lgd_code, c.lat, c.lng, c.aliases, c.market_tier,
+ c.active, c.is_discovery_active,
+ s.name AS state_name, s.state_code, s.lgd_code AS state_lgd_code,
+ d.name AS district_name, d.lgd_code AS district_lgd_code
+ FROM location_cities c
+ JOIN location_states s ON s.id = c.state_id
+ LEFT JOIN location_districts d ON d.id = c.district_id
+ WHERE lower(c.slug) = lower($1)
+ OR lower(c.name) = lower($1)
+ OR EXISTS (SELECT 1 FROM unnest(c.aliases) a WHERE lower(a) = lower($1))
+ LIMIT 1`, [cleanTerm]);
+ return rows[0] || null;
+}
+
+/**
+ * List localities for a city (e.g. Indiranagar, Koramangala in Bengaluru).
+ */
+export async function listLocalities({ cityId = null, citySlug = null, activeOnly = true } = {}, c = db) {
+ const conditions = [];
+ const params = [];
+ if (activeOnly) conditions.push('l.active = true');
+ if (cityId) {
+ params.push(cityId);
+ conditions.push(`l.city_id = $${params.length}`);
+ }
+ if (citySlug) {
+ params.push(citySlug);
+ conditions.push(`c.slug = $${params.length}`);
+ }
+ const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
+ const { rows } = await c.query(
+ `SELECT l.id, l.city_id, l.slug, l.name, l.postal_code, l.lat, l.lng, l.aliases, l.active, l.verified,
+ c.name AS city_name, c.slug AS city_slug
+ FROM location_localities l
+ JOIN location_cities c ON c.id = l.city_id
+ ${where}
+ ORDER BY l.name ASC`, params);
+ return rows;
+}
+
+/**
+ * Discover nearby events within radiusKm using Haversine distance.
+ * Preserves privacy: never exposes secret private venue details on public search.
+ * Handles events without coordinates safely.
+ */
+export async function findNearbyEvents({
+ lat = null,
+ lng = null,
+ radiusKm = 50,
+ citySlug = null,
+ category = null,
+ categories = null,
+ kind = 'all',
+ limit = 20,
+ offset = 0,
+ includeUnlocated = false
+} = {}, c = db) {
+ const hasCoords = lat != null && lng != null && !Number.isNaN(Number(lat)) && !Number.isNaN(Number(lng));
+ const numLat = hasCoords ? Number(lat) : null;
+ const numLng = hasCoords ? Number(lng) : null;
+ const numRadius = Math.max(1, Math.min(500, Number(radiusKm) || 50));
+ const numLimit = Math.max(1, Math.min(100, Number(limit) || 20));
+ const numOffset = Math.max(0, Number(offset) || 0);
+
+ const where = [`e.status = 'published'`, `COALESCE(e.end_at, e.start_at) > now()`];
+ const params = [];
+ const p = (v) => { params.push(v); return `$${params.length}`; };
+
+ let distanceExpr = 'NULL::DOUBLE PRECISION';
+ if (hasCoords) {
+ const latParam = p(numLat);
+ const lngParam = p(numLng);
+ distanceExpr = `haversine_km(${latParam}, ${lngParam}, e.lat, e.lng)`;
+ const radParam = p(numRadius);
+
+ // Bounding-box pre-filter to allow PostgreSQL to use idx_events_coords (lat, lng) index
+ const dLat = numRadius / 110.574;
+ const minLat = Math.max(-90, numLat - dLat);
+ const maxLat = Math.min(90, numLat + dLat);
+
+ const cosLat = Math.cos(Math.max(Math.abs(minLat), Math.abs(maxLat)) * (Math.PI / 180.0));
+ let bboxSql;
+ if (cosLat <= 0.001 || (numRadius / (111.0 * cosLat)) >= 180) {
+ bboxSql = `(e.lat BETWEEN ${p(minLat)} AND ${p(maxLat)})`;
+ } else {
+ const dLng = numRadius / (111.0 * cosLat);
+ const rawMinLng = numLng - dLng;
+ const rawMaxLng = numLng + dLng;
+
+ if (rawMinLng < -180) {
+ bboxSql = `(e.lat BETWEEN ${p(minLat)} AND ${p(maxLat)} AND (e.lng >= ${p(rawMinLng + 360)} OR e.lng <= ${p(rawMaxLng)}))`;
+ } else if (rawMaxLng > 180) {
+ bboxSql = `(e.lat BETWEEN ${p(minLat)} AND ${p(maxLat)} AND (e.lng >= ${p(rawMinLng)} OR e.lng <= ${p(rawMaxLng - 360)}))`;
+ } else {
+ bboxSql = `(e.lat BETWEEN ${p(minLat)} AND ${p(maxLat)} AND e.lng BETWEEN ${p(rawMinLng)} AND ${p(rawMaxLng)})`;
+ }
+ }
+
+ if (citySlug && includeUnlocated) {
+ // Within radius OR located in the specified city (even if unlocated)
+ const cityParam = p(citySlug);
+ where.push(`(
+ (${bboxSql} AND ${distanceExpr} <= ${radParam})
+ OR (e.lat IS NULL AND (
+ lower(e.city) = lower(${cityParam})
+ OR EXISTS (SELECT 1 FROM location_cities lc WHERE lc.id = e.city_id AND lower(lc.slug) = lower(${cityParam}))
+ ))
+ )`);
+ } else {
+ where.push(`(${bboxSql} AND ${distanceExpr} <= ${radParam})`);
+ }
+ } else if (citySlug) {
+ const cityParam = p(citySlug);
+ where.push(`(
+ lower(e.city) = lower(${cityParam})
+ OR EXISTS (SELECT 1 FROM location_cities lc WHERE lc.id = e.city_id AND (lower(lc.slug) = lower(${cityParam}) OR lower(lc.name) = lower(${cityParam})))
+ )`);
+ }
+
+ if (category) where.push(`e.category = ${p(category)}`);
+ if (categories?.length) where.push(`e.category::text = ANY(${p(categories)})`);
+ if (kind === 'events') where.push(`e.category NOT IN ('weekend_trip', 'resort_getaway')`);
+ if (kind === 'trips') where.push(`e.category IN ('weekend_trip', 'resort_getaway')`);
+
+ const limitParam = p(numLimit);
+ const offsetParam = p(numOffset);
+
+ const querySql = `
+ SELECT e.*,
+ ${distanceExpr} AS distance_km,
+ (SELECT COALESCE(sum(b.quantity), 0)::int FROM bookings b WHERE b.event_id = e.id AND ${SEAT_HOLDING_SQL}) AS seats_taken,
+ (SELECT m.url FROM media m WHERE m.id = e.cover_media_id AND m.authorized_by_owner AND m.visible) AS cover_url,
+ ${TIERS_SQL} AS tiers
+ FROM events e
+ WHERE ${where.join(' AND ')}
+ ORDER BY
+ ${hasCoords ? 'distance_km ASC NULLS LAST,' : ''}
+ e.is_demo ASC,
+ e.start_at ASC
+ LIMIT ${limitParam} OFFSET ${offsetParam}
+ `;
+
+ const { rows } = await c.query(querySql, params);
+ return rows.map((r) => toPublicEvent(r));
+}
diff --git a/lib/services/notifications.js b/lib/services/notifications.js
index f4778d5..417fccd 100644
--- a/lib/services/notifications.js
+++ b/lib/services/notifications.js
@@ -8,6 +8,52 @@ import { logger } from '../logger.js';
import { formatPaise } from './events.js';
export const MAX_ATTEMPTS = 6;
+export const NON_URGENT_KINDS = new Set(['event_announcement', 'event_reminder', 'membership_renewed', 'expiry_reminder']);
+
+/**
+ * Checks whether quiet hours are currently active for a user in Asia/Kolkata timezone.
+ */
+export function isQuietHours(user, date = new Date()) {
+ if (!user?.quiet_hours_enabled) return false;
+ const parts = new Intl.DateTimeFormat('en-IN', {
+ timeZone: 'Asia/Kolkata',
+ hour: '2-digit',
+ minute: '2-digit',
+ hourCycle: 'h23'
+ }).formatToParts(date);
+ const hour = parseInt(parts.find((p) => p.type === 'hour')?.value || '0', 10);
+ const minute = parseInt(parts.find((p) => p.type === 'minute')?.value || '0', 10);
+ const currentMinutes = hour * 60 + minute;
+
+ const [sH, sM] = String(user.quiet_hours_start || '23:00').split(':').map((v) => parseInt(v, 10));
+ const [eH, eM] = String(user.quiet_hours_end || '08:00').split(':').map((v) => parseInt(v, 10));
+ const startMinutes = (sH || 0) * 60 + (sM || 0);
+ const endMinutes = (eH || 0) * 60 + (eM || 0);
+
+ if (startMinutes > endMinutes) {
+ // Window crosses midnight (e.g. 23:00 to 08:00)
+ return currentMinutes >= startMinutes || currentMinutes < endMinutes;
+ }
+ return currentMinutes >= startMinutes && currentMinutes < endMinutes;
+}
+
+/**
+ * Calculates the exact Date when quiet hours end for the user in Asia/Kolkata timezone.
+ */
+export function quietHoursNextAttempt(user, date = new Date()) {
+ const [eH, eM] = String(user?.quiet_hours_end || '08:00').split(':').map((v) => parseInt(v, 10));
+ const now = date.getTime();
+ const istDateStr = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Kolkata' }).format(date);
+ const [y, m, d] = istDateStr.split('-').map(Number);
+
+ // UTC = IST - 5h 30m
+ const todayEndUtcMs = Date.UTC(y, m - 1, d, eH - 5, eM - 30);
+ if (todayEndUtcMs > now) {
+ return new Date(todayEndUtcMs);
+ }
+ const tomorrowEndUtcMs = Date.UTC(y, m - 1, d + 1, eH - 5, eM - 30);
+ return new Date(tomorrowEndUtcMs);
+}
export async function enqueue(client, { kind, userId = null, bookingId = null, entitlementId = null, eventId = null, dedupeKey }) {
const { rows } = await client.query(
@@ -61,14 +107,14 @@ const HANDLERS = {
inviteErr = err;
}
const venue = b.venue_privacy === 'public' && b.venue_private ? b.venue_private : null;
- const hostEvent = Boolean(b.organiser_user_id) && b.telegram_chat_id === null;
+ const hasGroup = Boolean(b.telegram_chat_id);
const lines = [
`You're booked! ${escHtml(b.title)}`,
`${escHtml(fmt(b.start_at))} · ${escHtml(b.area_public ? `${b.area_public}, ` : '')}${escHtml(b.city)}`,
- venue ? `Venue: ${escHtml(venue)}` : hostEvent ? 'The exact venue is on your booking page.' : 'The exact venue is shared inside the private group.',
- b.payment_mode === 'free' ? 'Free ticket — no payment needed.' : b.amount_paise ? `Paid: ${formatPaise(b.amount_paise)}${livePayments() ? '' : ' (test mode)'}` : null,
+ venue ? `Venue: ${escHtml(venue)}` : hasGroup ? 'The exact venue is shared inside the private group.' : 'The exact venue is on your booking page.',
+ b.payment_mode === 'free' ? 'Free ticket — no payment needed.' : b.amount_paise ? `Paid: ${formatPaise(b.amount_paise)}${b.payment_mode === 'external' ? ' on SuperProfile' : livePayments() ? '' : ' (test mode)'}` : null,
`Booking ref: ${b.id.slice(0, 8)}`,
- hostEvent ? null : invite ? 'Your one-time group invite is below. It works once and expires in 24 hours.' : 'Your private group invite will follow shortly.'
+ hasGroup ? (invite ? 'Your one-time group invite is below. It works once and expires in 24 hours.' : 'Your private group invite will follow shortly.') : null
].filter(Boolean);
const buttons = [];
if (invite) buttons.push([{ text: 'Join the private group', url: invite.link }]);
@@ -133,17 +179,34 @@ const HANDLERS = {
if (b) await send(b.telegram_user_id, `We're sorry — ${escHtml(b.title)} on ${escHtml(fmt(b.start_at))} has been cancelled. You will receive a full refund to your original payment method.`);
},
- async late_payment_refund_needed(n) {
- // Payment captured after the hold expired and the event is full: alert finance admins.
- const b = await db.one(
- `SELECT b.id, e.title FROM bookings b JOIN events e ON e.id = b.event_id WHERE b.id = $1`, [n.booking_id]);
+ async order_alert(n) {
+ // dedupe_key = oa::. Order details stay in the admin Orders tab.
+ const [, orderRow, reason] = String(n.dedupe_key).split(':');
+ const o = await db.one('SELECT order_id, qty FROM external_orders WHERE id = $1', [orderRow]);
const ids = await adminChatIds();
if (!ids.length) throw new Error('NOT CONFIGURED: no admin Telegram ids');
+ const WHY = {
+ unknown_product: 'its SuperProfile product is not linked to any event',
+ amount_mismatch: 'the amount does not match the configured price',
+ currency_mismatch: 'the currency is not INR',
+ event_not_published: 'the event is not published',
+ duplicate_booking: 'the buyer already has a booking for this event',
+ refund_after_check_in: 'it was refunded after the guest checked in'
+ };
for (const id of ids) {
- await send(id, `⚠️ Refund needed: payment received after hold expired and ${escHtml(b?.title || 'event')} is full. Booking ${escHtml(n.booking_id)}. Open /admin → Bookings.`);
+ await send(id, `⚠️ SuperProfile order ${escHtml(o?.order_id || '')} needs review: ${escHtml(WHY[reason] || reason)}. Nothing was confirmed automatically. Open /admin → Orders.`);
+ }
+ },
+
+ async reconcile_alert(n) {
+ // dedupe_key = rc:::::
+ const [, date, inApp, onSp, amount, status] = String(n.dedupe_key).split(':');
+ const ids = await adminChatIds();
+ if (!ids.length) throw new Error('NOT CONFIGURED: no admin Telegram ids');
+ for (const id of ids) {
+ await send(id, `⚠️ SuperProfile reconciliation (${escHtml(date)}): ${escHtml(inApp)} order(s) missing in the app, ${escHtml(onSp)} missing on SuperProfile, ` +
+ `${escHtml(amount)} amount mismatch(es), ${escHtml(status)} status mismatch(es). Check the SuperProfile dashboard against Admin → Orders.`);
}
- const u = await db.one('SELECT telegram_user_id FROM users WHERE id = $1', [n.user_id]);
- if (u) await send(u.telegram_user_id, `Sorry — ${escHtml(b?.title || 'the event')} filled up before your payment arrived. You will receive a full refund.`);
},
async booking_request(n) {
@@ -160,14 +223,6 @@ const HANDLERS = {
if (b) await send(b.telegram_user_id, `The host couldn't accept your request for ${escHtml(b.title)} this time. You have not been charged.`);
},
- async booking_approved_pay(n) {
- const b = await db.one(
- `SELECT b.id, b.hold_expires_at, e.title, u.telegram_user_id FROM bookings b JOIN events e ON e.id = b.event_id JOIN users u ON u.id = b.user_id
- WHERE b.id = $1 AND b.status = 'pending_payment'`, [n.booking_id]);
- if (b) await send(b.telegram_user_id, `Good news — the host approved your request for ${escHtml(b.title)} . Complete payment by ${escHtml(fmt(b.hold_expires_at))} to confirm your spot.`,
- [[{ text: 'Complete booking', url: `${siteUrl()}/bookings/${b.id}` }]]);
- },
-
async event_announcement(n) {
const e = await db.one(`SELECT slug, title, city, start_at, category FROM events WHERE id = $1 AND status = 'published'`, [n.event_id]);
const u = await db.one('SELECT telegram_user_id, alerts_opt_in FROM users WHERE id = $1', [n.user_id]);
@@ -175,11 +230,125 @@ const HANDLERS = {
const path = ['weekend_trip', 'resort_getaway'].includes(e.category) ? 'trips' : 'events';
await send(u.telegram_user_id, `New: ${escHtml(e.title)} \n${escHtml(fmt(e.start_at))} · ${escHtml(e.city)}`,
[[{ text: 'See details', url: `${siteUrl()}/${path}/${e.slug}` }]]);
+ },
+
+ async event_reminder(n) {
+ const b = await db.one(
+ `SELECT b.id, e.title, e.start_at, e.city, e.area_public, e.venue_private, e.venue_privacy,
+ e.telegram_chat_id, u.telegram_user_id, u.reminders_enabled
+ FROM bookings b JOIN events e ON e.id = b.event_id JOIN users u ON u.id = b.user_id WHERE b.id = $1`, [n.booking_id]);
+ if (!b || b.reminders_enabled === false) return;
+ const venue = b.venue_privacy === 'public' && b.venue_private ? b.venue_private : null;
+ const lines = [
+ `🔔 Upcoming Event Reminder `,
+ `${escHtml(b.title)} `,
+ `Starts: ${escHtml(fmt(b.start_at))}`,
+ `Location: ${escHtml(b.area_public ? `${b.area_public}, ` : '')}${escHtml(b.city)}`,
+ venue ? `Venue: ${escHtml(venue)}` : 'Exact venue details are inside your booking pass or private group.',
+ `Booking ref: ${b.id.slice(0, 8)}`
+ ];
+ await send(b.telegram_user_id, lines.join('\n'), [[{ text: 'View booking pass', url: `${siteUrl()}/bookings/${b.id}` }]]);
+ },
+
+ async event_update(n) {
+ let bookingId = n.booking_id;
+ let eventTitle = null;
+ let attendeeTelegramId = null;
+
+ if (bookingId) {
+ const row = await db.one(
+ `SELECT b.id, e.title, u.telegram_user_id
+ FROM bookings b JOIN events e ON e.id = b.event_id JOIN users u ON u.id = b.user_id
+ WHERE b.id = $1`, [bookingId]);
+ if (row) {
+ eventTitle = row.title;
+ attendeeTelegramId = row.telegram_user_id;
+ }
+ } else if (n.user_id && n.event_id) {
+ const row = await db.one(
+ `SELECT b.id, e.title, u.telegram_user_id
+ FROM bookings b JOIN events e ON e.id = b.event_id JOIN users u ON u.id = b.user_id
+ WHERE b.user_id = $1 AND b.event_id = $2 AND b.status IN ('confirmed', 'checked_in')
+ ORDER BY b.created_at DESC LIMIT 1`,
+ [n.user_id, n.event_id]
+ );
+ if (row) {
+ bookingId = row.id;
+ eventTitle = row.title;
+ attendeeTelegramId = row.telegram_user_id;
+ } else {
+ const u = await db.one('SELECT telegram_user_id FROM users WHERE id = $1', [n.user_id]);
+ const e = await db.one('SELECT title FROM events WHERE id = $1', [n.event_id]);
+ eventTitle = e?.title || 'Event';
+ attendeeTelegramId = u?.telegram_user_id;
+ }
+ }
+
+ if (!attendeeTelegramId) return;
+
+ let announcement = null;
+ if (n.dedupe_key && n.dedupe_key.startsWith('ann:')) {
+ const annId = n.dedupe_key.split(':')[1];
+ if (annId) {
+ announcement = await db.one('SELECT title, message FROM event_announcements WHERE id = $1', [annId]);
+ }
+ }
+
+ const titleText = announcement ? announcement.title : `Event Update: ${eventTitle || 'Event'}`;
+ const messageBody = announcement ? announcement.message : 'Important operational update regarding your upcoming event. Tap below to view details on your booking pass.';
+ const buttons = [];
+ if (bookingId) {
+ buttons.push([{ text: 'View booking pass', url: `${siteUrl()}/bookings/${bookingId}` }]);
+ }
+
+ await send(attendeeTelegramId,
+ `📢 ${escHtml(titleText)} \n\n${escHtml(messageBody)}`,
+ buttons.length ? buttons : null);
+ },
+
+ async booking_cancelled_by_user(n) {
+ const b = await db.one(
+ `SELECT b.id, b.cancel_reason, e.title, u.telegram_user_id
+ FROM bookings b JOIN events e ON e.id = b.event_id JOIN users u ON u.id = b.user_id
+ WHERE b.id = $1`, [n.booking_id]);
+ if (!b || !b.telegram_user_id) return;
+ await send(b.telegram_user_id,
+ `Your reservation for ${escHtml(b.title)} has been cancelled.\nAny tickets associated with this booking have been released.`);
+ },
+
+ async host_application_received() {
+ const ids = await adminChatIds();
+ if (!ids.length) throw new Error('NOT CONFIGURED: no admin Telegram ids');
+ for (const id of ids) {
+ await send(id, `📋 New host application submitted. Review in admin dashboard: ${siteUrl()}/admin`);
+ }
+ },
+
+ async host_approved(n) {
+ const u = await db.one('SELECT telegram_user_id FROM users WHERE id = $1', [n.user_id]);
+ if (!u?.telegram_user_id) return;
+ await send(u.telegram_user_id,
+ `🎉 Congratulations! Your host application has been approved. \n\nYou can now create and host curated social events on NIGHTLIFEZ. Visit your organiser dashboard to get started:`,
+ [[{ text: 'Organiser Dashboard', url: `${siteUrl()}/organiser` }]]);
}
};
/** Deliver one notification row. Never throws; records outcome. */
export async function deliver(id) {
+ // Check if non-urgent and inside user's quiet hours
+ const peek = await db.one(`SELECT kind, user_id, booking_id, dedupe_key FROM notifications WHERE id = $1`, [id]);
+ if (peek && (NON_URGENT_KINDS.has(peek.kind) || (peek.kind === 'event_update' && peek.dedupe_key?.startsWith('ann:')))) {
+ const uid = peek.user_id || (peek.booking_id ? (await db.one('SELECT user_id FROM bookings WHERE id = $1', [peek.booking_id]))?.user_id : null);
+ if (uid) {
+ const u = await db.one('SELECT quiet_hours_enabled, quiet_hours_start, quiet_hours_end FROM users WHERE id = $1', [uid]);
+ if (u?.quiet_hours_enabled && isQuietHours(u)) {
+ const nextAttempt = quietHoursNextAttempt(u);
+ await db.query(`UPDATE notifications SET next_attempt_at = $2 WHERE id = $1`, [id, nextAttempt]);
+ return 'deferred_quiet_hours';
+ }
+ }
+ }
+
const n = await db.one(
`UPDATE notifications SET attempts = attempts + 1
WHERE id = $1 AND status <> 'sent' AND attempts < $2 RETURNING *`, [id, MAX_ATTEMPTS]);
diff --git a/lib/services/orders.js b/lib/services/orders.js
new file mode 100644
index 0000000..2833f9b
--- /dev/null
+++ b/lib/services/orders.js
@@ -0,0 +1,271 @@
+// lib/services/orders.js - SuperProfile ticket orders (external_orders) and the bookings they confirm.
+//
+// A booking is confirmed only from a SuperProfile "purchase" notification (via Zapier/Pabbly →
+// /api/webhooks/superprofile) that we can tie to a person: by the checkout ref we attached on the
+// way out, or by a previously verified buyer email. Everything else is stored as `unmatched` and
+// waits for the buyer to /claim it in the bot or for an admin to link it. Nothing is ever dropped.
+// Fails closed: an amount we cannot reconcile with the configured price is stored and flagged, and
+// confirms nothing.
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+import { audit } from '../audit.js';
+import { enqueue } from './notifications.js';
+import { emailHash, phoneHash, rupeesToPaise } from './superprofile.js';
+import { removeFromChat } from './invites.js';
+import { recordIntegrationError } from './insights.js';
+import { logger } from '../logger.js';
+import { issueTicketsForBooking } from './tickets.js';
+
+/** Normalise a checkout ref coming back from SuperProfile (case and stray characters vary). */
+export function normaliseRef(v) {
+ const r = String(v || '').toUpperCase().replace(/[^0-9A-Z]/g, '');
+ return r.length === 8 ? r : null;
+}
+
+function parseQty(v) {
+ const n = Number(v);
+ return Number.isInteger(n) && n >= 1 && n <= 20 ? n : null;
+}
+
+/**
+ * Amounts (paise) the order may legitimately have, or null when no price is configured to check
+ * against. A tiered event accepts any paid tier × quantity (the intent narrows it to one tier).
+ */
+export function expectedAmounts(event, tiers, intent, qty) {
+ if (event.ticketing === 'tiers') {
+ const paid = tiers.filter((t) => t.kind === 'paid' && (!intent?.ticket_type_id || t.id === intent.ticket_type_id));
+ if (!paid.length) return null;
+ return new Set(paid.map((t) => t.price_paise * qty));
+ }
+ if (event.price_status === 'set' && event.ticket_price_paise) return new Set([event.ticket_price_paise * qty]);
+ return null;
+}
+
+/** Quantity from the payload, else inferred from amount ÷ unit price, else 1. */
+export function inferQty(event, tiers, intent, amountPaise, given) {
+ const q = parseQty(given);
+ if (q) return q;
+ const units = event.ticketing === 'tiers'
+ ? tiers.filter((t) => t.kind === 'paid' && (!intent?.ticket_type_id || t.id === intent.ticket_type_id)).map((t) => t.price_paise)
+ : (event.price_status === 'set' && event.ticket_price_paise ? [event.ticket_price_paise] : []);
+ if (amountPaise && units.length === 1 && amountPaise % units[0] === 0) return parseQty(amountPaise / units[0]) || 1;
+ return intent?.qty || 1;
+}
+
+/**
+ * Create the confirmed booking for a paid order and link it. `c` is a transaction client with the
+ * order row already locked. Returns { bookingId, notificationId } or { conflict: 'duplicate_booking' }.
+ */
+export async function confirmOrderBooking(c, { order, event, userId, ticketTypeId = null, actor }) {
+ const live = (await c.query(
+ `SELECT id FROM bookings WHERE event_id = $1 AND user_id = $2 AND status IN ('pending_approval', 'pending_payment', 'confirmed', 'checked_in') LIMIT 1`,
+ [event.id, userId])).rows[0];
+ if (live) return { conflict: 'duplicate_booking' };
+ const b = (await c.query(
+ `INSERT INTO bookings (event_id, user_id, ticket_type_id, quantity, status, amount_paise, payment_mode, source, confirmed_at)
+ VALUES ($1, $2, $3, $4, 'confirmed', $5, 'external', 'superprofile', now()) RETURNING id`,
+ [event.id, userId, ticketTypeId, order.qty, order.amount_paise])).rows[0];
+ await issueTicketsForBooking(b.id, c);
+ await c.query(`UPDATE external_orders SET matched_booking_id = $2, match_state = 'matched', flag_reason = NULL WHERE id = $1`, [order.id, b.id]);
+ const nid = await enqueue(c, { kind: 'booking_confirmed', userId, bookingId: b.id, dedupeKey: `bk:${b.id}:confirmed` });
+ await audit(actor, 'booking.confirmed_external', b.id, { orderRow: order.id, qty: order.qty }, c);
+ return { bookingId: b.id, notificationId: nid };
+}
+
+async function alertNotification(c, orderRowId, reason) {
+ return enqueue(c, { kind: 'order_alert', dedupeKey: `oa:${orderRowId}:${reason}` });
+}
+
+/** Apply a "purchase" notification. Idempotent on order_id. */
+async function applyPurchase(b) {
+ const orderId = b.id;
+ const productKeys = [b.product_id, b.product].filter(Boolean).map((s) => s.toLowerCase());
+ const productId = b.product_id || b.product || null;
+ const email = b.email ? emailHash(b.email) : null;
+ const phone = b.phone ? phoneHash(b.phone) : null;
+ const amount = rupeesToPaise(b.amount);
+ const currency = (b.currency || 'INR').toUpperCase().slice(0, 8);
+ const ref = normaliseRef(b.ref);
+
+ const r = await db.tx(async (c) => {
+ const event = productKeys.length
+ ? (await c.query('SELECT * FROM events WHERE lower(superprofile_product_id) = ANY($1::text[]) FOR UPDATE', [productKeys])).rows[0]
+ : null;
+ const tiers = event?.ticketing === 'tiers'
+ ? (await c.query('SELECT id, kind, price_paise FROM ticket_types WHERE event_id = $1 AND active', [event.id])).rows : [];
+ const intent = ref
+ ? (await c.query('SELECT * FROM checkout_intents WHERE ref = $1 AND expires_at > now()', [ref])).rows[0] : null;
+ const intentForEvent = intent && event && intent.event_id === event.id ? intent : null;
+ const qty = event ? inferQty(event, tiers, intentForEvent, amount, b.qty) : (parseQty(b.qty) || 1);
+
+ const ins = await c.query(
+ `INSERT INTO external_orders (order_id, product_id, event_id, amount_paise, currency, qty, status, buyer_email_hash, buyer_phone_hash, ref, raw_minimal)
+ VALUES ($1,$2,$3,$4,$5,$6,'paid',$7,$8,$9,$10) ON CONFLICT (order_id) DO NOTHING RETURNING *`,
+ [orderId, productId, event?.id || null, amount, currency, qty, email, phone, ref,
+ JSON.stringify({ occurred_at: b.occurred_at || null, intent: Boolean(intentForEvent) })]);
+ if (!ins.rowCount) return { result: 'duplicate', notificationIds: [] };
+ const order = ins.rows[0];
+
+ const flag = async (reason, result) => {
+ await c.query(`UPDATE external_orders SET match_state = 'flagged', flag_reason = $2 WHERE id = $1`, [order.id, reason]);
+ const nid = await alertNotification(c, order.id, reason);
+ await audit('webhook:superprofile', 'order.flagged', order.id, { reason }, c);
+ return { result, notificationIds: [nid], alert: reason, orderRow: order.id };
+ };
+
+ if (!event) {
+ const nid = await alertNotification(c, order.id, 'unknown_product');
+ await c.query(`UPDATE external_orders SET flag_reason = 'unknown_product' WHERE id = $1`, [order.id]);
+ return { result: 'unmatched', notificationIds: [nid], alert: 'unknown_product', orderRow: order.id };
+ }
+ if (currency !== 'INR') return flag('currency_mismatch', 'flagged');
+ const expected = expectedAmounts(event, tiers, intentForEvent, qty);
+ if (expected && (amount === null || !expected.has(amount))) return flag('amount_mismatch', 'flagged');
+ if (event.status !== 'published') return flag('event_not_published', 'flagged');
+
+ // Who bought? The ref we attached (signed-in click), else a buyer email a user verified earlier.
+ let userId = intentForEvent?.user_id || null;
+ if (userId) {
+ const u = (await c.query(`SELECT id FROM users WHERE id = $1 AND status = 'active'`, [userId])).rows[0];
+ userId = u?.id || null;
+ }
+ if (!userId && email) {
+ const u = (await c.query(`SELECT id FROM users WHERE email_hash = $1 AND status = 'active' ORDER BY updated_at DESC LIMIT 1`, [email])).rows[0];
+ userId = u?.id || null;
+ }
+ if (!userId) {
+ await audit('webhook:superprofile', 'order.unmatched', order.id, { eventId: event.id }, c);
+ return { result: 'unmatched', notificationIds: [], orderRow: order.id };
+ }
+ const confirmed = await confirmOrderBooking(c, { order, event, userId, ticketTypeId: intentForEvent?.ticket_type_id || null, actor: 'webhook:superprofile' });
+ if (confirmed.conflict) return flag(confirmed.conflict, 'flagged');
+ return { result: 'confirmed', notificationIds: [confirmed.notificationId], bookingId: confirmed.bookingId, orderRow: order.id };
+ });
+ return r;
+}
+
+/** Apply a "refund" or "cancelled" notification to an order and its booking. Idempotent. */
+async function applyReversal(b) {
+ const status = b.event === 'refund' ? 'refunded' : 'cancelled';
+ const productKeys = [b.product_id, b.product].filter(Boolean).map((s) => s.toLowerCase());
+ const effects = { removeFromChat: null };
+
+ const r = await db.tx(async (c) => {
+ const order = (await c.query('SELECT * FROM external_orders WHERE order_id = $1 FOR UPDATE', [b.id])).rows[0];
+ if (!order) {
+ // Refund seen before the purchase (or the purchase never reached us): keep the fact; a late purchase becomes a duplicate.
+ const event = productKeys.length
+ ? (await c.query('SELECT id FROM events WHERE lower(superprofile_product_id) = ANY($1::text[])', [productKeys])).rows[0] : null;
+ await c.query(
+ `INSERT INTO external_orders (order_id, product_id, event_id, amount_paise, currency, status, raw_minimal)
+ VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT (order_id) DO NOTHING`,
+ [b.id, b.product_id || b.product || null, event?.id || null, rupeesToPaise(b.amount), (b.currency || 'INR').toUpperCase().slice(0, 8), status,
+ JSON.stringify({ occurred_at: b.occurred_at || null, before_purchase: true })]);
+ return { result: `${status}_before_purchase`, notificationIds: [] };
+ }
+ if (order.status !== 'paid') return { result: 'duplicate', notificationIds: [] };
+ await c.query('UPDATE external_orders SET status = $2 WHERE id = $1', [order.id, status]);
+ if (!order.matched_booking_id) {
+ await audit('webhook:superprofile', `order.${status}`, order.id, { matched: false }, c);
+ return { result: status, notificationIds: [] };
+ }
+ const booking = (await c.query('SELECT * FROM bookings WHERE id = $1 FOR UPDATE', [order.matched_booking_id])).rows[0];
+ if (booking.status === 'checked_in') {
+ // The guest was already admitted: keep the check-in record, tell finance.
+ await c.query(`UPDATE external_orders SET match_state = 'flagged', flag_reason = 'refund_after_check_in' WHERE id = $1`, [order.id]);
+ const nid = await alertNotification(c, order.id, 'refund_after_check_in');
+ await audit('webhook:superprofile', `order.${status}_after_check_in`, order.id, { bookingId: booking.id }, c);
+ return { result: `${status}_after_check_in`, notificationIds: [nid], alert: 'refund_after_check_in', orderRow: order.id };
+ }
+ if (['confirmed', 'pending_payment', 'pending_approval'].includes(booking.status)) {
+ await c.query(
+ `UPDATE bookings SET status = $2::booking_status,
+ refunded_at = CASE WHEN $2 = 'refunded' THEN now() ELSE refunded_at END,
+ cancelled_at = CASE WHEN $2 = 'cancelled' THEN now() ELSE cancelled_at END,
+ cancel_reason = CASE WHEN $2 = 'cancelled' THEN 'superprofile_cancelled' ELSE cancel_reason END
+ WHERE id = $1`, [booking.id, status]);
+ await c.query('UPDATE invite_links SET revoked_at = COALESCE(revoked_at, now()) WHERE booking_id = $1 AND used_at IS NULL', [booking.id]);
+ const joined = (await c.query(
+ `SELECT i.chat_id, u.telegram_user_id FROM invite_links i JOIN users u ON u.id = i.user_id
+ WHERE i.booking_id = $1 AND i.used_at IS NOT NULL AND i.revoked_at IS NULL LIMIT 1`, [booking.id])).rows[0];
+ if (joined) {
+ effects.removeFromChat = { chatId: joined.chat_id, telegramUserId: joined.telegram_user_id };
+ await c.query('UPDATE invite_links SET revoked_at = now() WHERE booking_id = $1 AND revoked_at IS NULL', [booking.id]);
+ }
+ const nid = await enqueue(c, { kind: 'booking_refunded', userId: booking.user_id, bookingId: booking.id, dedupeKey: `bk:${booking.id}:refunded` });
+ await audit('webhook:superprofile', `order.${status}`, order.id, { bookingId: booking.id }, c);
+ return { result: status, notificationIds: [nid], bookingId: booking.id };
+ }
+ return { result: status, notificationIds: [] };
+ });
+ return { ...r, effects };
+}
+
+/**
+ * Entry for order-shaped notifications (purchase / refund / cancelled). Runs the transaction, then
+ * the side effects that must not roll it back: group removal and admin alert logging.
+ */
+export async function applyOrderEvent(b) {
+ const r = b.event === 'purchase' ? await applyPurchase(b) : await applyReversal(b);
+ if (r.effects?.removeFromChat) {
+ const { chatId, telegramUserId } = r.effects.removeFromChat;
+ await removeFromChat(chatId, telegramUserId).catch((err) => logger.warn('remove from group failed', { reason: String(err.message).slice(0, 100) }));
+ }
+ if (r.alert) await recordIntegrationError('superprofile_webhook', `order_${r.alert}`, `order row ${r.orderRow}`);
+ return r;
+}
+
+/** Does this product belong to a membership tier (handled by the membership flow)? */
+export async function isTierProduct(b) {
+ const keys = [b.product_id, b.product].filter(Boolean);
+ if (!keys.length) return false;
+ const row = await db.one('SELECT 1 AS x FROM membership_tiers WHERE lower(superprofile_product_ref) = ANY($1::text[])', [keys.map((k) => k.toLowerCase())]);
+ return Boolean(row);
+}
+
+// ---------- admin ----------
+
+/** Keyset-paginated order list for the admin Orders tab. */
+export async function listOrders({ state = 'unmatched', cursor = null, limit = 25 } = {}) {
+ const n = Math.min(Math.max(parseInt(limit, 10) || 25, 1), 100);
+ const where = [];
+ const params = [];
+ const p = (v) => { params.push(v); return `$${params.length}`; };
+ if (state === 'unmatched') where.push(`o.match_state = 'unmatched' AND o.status = 'paid'`);
+ else if (state === 'flagged') where.push(`o.match_state = 'flagged'`);
+ else if (state === 'matched') where.push(`o.match_state = 'matched'`);
+ else if (state !== 'all') throw new HttpError(400, 'validation', 'Unknown state');
+ if (cursor) {
+ const [ts, id] = String(cursor).split('|');
+ if (!ts || Number.isNaN(new Date(ts).getTime()) || !/^[0-9a-f-]{36}$/i.test(id || '')) throw new HttpError(400, 'validation', 'Bad cursor');
+ where.push(`(o.received_at, o.id) < (${p(ts)}::timestamptz, ${p(id)}::uuid)`);
+ }
+ const { rows } = await db.query(
+ `SELECT o.id, o.order_id, o.product_id, o.amount_paise, o.currency, o.qty, o.status, o.match_state, o.flag_reason, o.received_at,
+ o.matched_booking_id, (o.buyer_email_hash IS NOT NULL) AS has_email, e.title AS event_title, e.slug AS event_slug
+ FROM external_orders o LEFT JOIN events e ON e.id = o.event_id
+ ${where.length ? `WHERE ${where.join(' AND ')}` : ''}
+ ORDER BY o.received_at DESC, o.id DESC LIMIT ${n + 1}`, params);
+ const page = rows.slice(0, n);
+ const last = page[page.length - 1];
+ return { orders: page, nextCursor: rows.length > n && last ? `${new Date(last.received_at).toISOString()}|${last.id}` : null };
+}
+
+/** Finance: link a paid, unclaimed order to the user with this Telegram id and confirm their booking. */
+export async function linkOrderToUser(actor, orderRowId, telegramUserId) {
+ const out = await db.tx(async (c) => {
+ const order = (await c.query('SELECT * FROM external_orders WHERE id = $1 FOR UPDATE', [orderRowId])).rows[0];
+ if (!order) throw new HttpError(404, 'not_found', 'Order not found');
+ if (order.status !== 'paid') throw new HttpError(409, 'not_linkable', `Order is ${order.status}`);
+ if (order.matched_booking_id) throw new HttpError(409, 'already_linked', 'Order is already linked to a booking');
+ if (!order.event_id) throw new HttpError(409, 'unknown_product', 'This order’s product is not linked to an event yet. Link the product on the event first.');
+ const user = (await c.query(`SELECT id FROM users WHERE telegram_user_id = $1 AND status = 'active'`, [telegramUserId])).rows[0];
+ if (!user) throw new HttpError(404, 'user_not_found', 'No active user with that Telegram id. They must sign in once first.');
+ const event = (await c.query('SELECT * FROM events WHERE id = $1 FOR UPDATE', [order.event_id])).rows[0];
+ const r = await confirmOrderBooking(c, { order, event, userId: user.id, actor });
+ if (r.conflict) throw new HttpError(409, r.conflict, 'That user already has a booking for this event');
+ await audit(actor, 'order.manual_link', order.id, { bookingId: r.bookingId, orderId: order.order_id }, c);
+ return { bookingId: r.bookingId, notificationIds: [r.notificationId] };
+ });
+ return out;
+}
diff --git a/lib/services/organiser.js b/lib/services/organiser.js
index b396833..4dd66ff 100644
--- a/lib/services/organiser.js
+++ b/lib/services/organiser.js
@@ -12,6 +12,9 @@ import { siteUrl } from '../config.js';
import { TIMEZONE_IDS, isLocalDateTime, zonedToUtc, datesBetween, localDate } from '../time.js';
import { ticketCheckoutStatus } from '../payments/availability.js';
import { CATEGORY_LABELS, TRIP_CATEGORIES, toPublicEvent } from './events.js';
+import { ensurePersonalOrg, orgIdsFor, eventIdsFor, can, authorize } from './permissions.js';
+import { resolveCity } from './locations.js';
+import { enqueue } from './notifications.js';
export const MAX_IMAGES = 5;
export const MAX_TIERS = 10;
@@ -505,13 +508,43 @@ export async function publishDraft(user, draftId, { version, confirm }) {
[imageUrl(d.coverImageId), clean(d.title).slice(0, 140), user.alias || null])).rows[0].id;
}
const contactPhone = f.contact?.enabled ? normalizePhone(f.contact.phone) : null;
+ const orgId = await ensurePersonalOrg(user, c);
+
+ // Resolve location intelligence references from official directory
+ const resolvedCity = await resolveCity(d.city, c);
+ const canonicalCity = resolvedCity ? resolvedCity.name : clean(d.city);
+ const cityId = resolvedCity ? resolvedCity.id : null;
+ let lat = resolvedCity ? resolvedCity.lat : null;
+ let lng = resolvedCity ? resolvedCity.lng : null;
+ let coordsProvenance = resolvedCity ? 'city' : 'none';
+
+ let localityId = null;
+ if (resolvedCity && d.area && clean(d.area)) {
+ const loc = (await c.query(
+ `SELECT id, lat, lng FROM location_localities
+ WHERE city_id = $1
+ AND (lower(name) = lower($2) OR lower(slug) = lower($2) OR EXISTS (SELECT 1 FROM unnest(aliases) a WHERE lower(a) = lower($2)))
+ LIMIT 1`, [resolvedCity.id, clean(d.area)])).rows[0];
+ if (loc) {
+ localityId = loc.id;
+ if (loc.lat != null && loc.lng != null) {
+ lat = loc.lat;
+ lng = loc.lng;
+ coordsProvenance = 'locality';
+ }
+ }
+ }
+
const ev = (await c.query(
- `INSERT INTO events (slug, category, title, summary, description, city, area_public, venue_private, venue_privacy, start_at, end_at, timezone,
+ `INSERT INTO events (slug, category, title, summary, description, city, city_id, locality_id, lat, lng, coords_provenance, area_public, venue_private, venue_privacy, start_at, end_at, timezone,
capacity, price_status, refund_policy, organizer, status, published_at, organiser_user_id, draft_id, ticketing,
- is_multi_day, maps_url, requires_approval, booking_questions, pickup_points, contact_name, contact_phone, gallery, features, cover_media_id)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, 'tbd', $14, $15, 'published', now(), $16, $17, 'tiers',
- $18, $19, $20, $21, $22, $23, $24, $25, $26, $27) RETURNING id, slug, category`,
- [slugify(d.title), d.category, clean(d.title), summaryOf(d.description) || null, clean(d.description), clean(d.city), clean(d.area) || null,
+ is_multi_day, maps_url, requires_approval, booking_questions, pickup_points, contact_name, contact_phone, gallery, features, cover_media_id,
+ organiser_org_id)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17,
+ $18, 'tbd', $19, $20, 'published', now(), $21, $22, 'tiers',
+ $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33) RETURNING id, slug, category`,
+ [slugify(d.title), d.category, clean(d.title), summaryOf(d.description) || null, clean(d.description),
+ canonicalCity, cityId, localityId, lat, lng, coordsProvenance, clean(d.area) || null,
clean(d.venue) || null, d.privateVenue ? 'disclosed_after_booking' : 'public', zonedToUtc(d.startLocal, tz),
d.endLocal ? zonedToUtc(d.endLocal, tz) : null, tz, capacity, clean(d.refundPolicy) || null,
clean(d.hostName) || user.alias || 'Independent organiser', user.id, draftId,
@@ -519,7 +552,7 @@ export async function publishDraft(user, draftId, { version, confirm }) {
JSON.stringify(f.questions?.enabled ? sanitizeQuestions(f.questions.items) : []),
JSON.stringify(f.pickup?.enabled ? sanitizePickups(f.pickup.points) : []),
contactPhone ? clean(f.contact.name) : null, contactPhone,
- JSON.stringify((d.imageIds || []).map(imageUrl)), JSON.stringify(featureFlags(f)), coverMediaId])).rows[0];
+ JSON.stringify((d.imageIds || []).map(imageUrl)), JSON.stringify(featureFlags(f)), coverMediaId, orgId])).rows[0];
for (const [i, t] of tickets.entries()) {
await c.query(
@@ -530,6 +563,12 @@ export async function publishDraft(user, draftId, { version, confirm }) {
}
if (imageIds.length) await c.query(`UPDATE event_images SET is_public = true WHERE id = ANY($1)`, [imageIds]);
await c.query(`UPDATE event_drafts SET status = 'published', event_id = $2, published_at = now(), version = version + 1 WHERE id = $1`, [draftId, ev.id]);
+ await c.query(
+ `INSERT INTO event_team (event_id, user_id, team_role, status, invited_by)
+ VALUES ($1, $2, 'organiser', 'active', $2)
+ ON CONFLICT (event_id, user_id) WHERE status = 'active' AND user_id IS NOT NULL DO NOTHING`,
+ [ev.id, user.id]
+ );
await audit(`user:${user.id}`, 'event.publish', ev.id, { draftId, tiers: tickets.length, approval: Boolean(f.approval?.enabled) }, c);
return ev;
});
@@ -539,15 +578,467 @@ export async function publishDraft(user, draftId, { version, confirm }) {
// ---------- organiser's events ----------
-export async function listOrganiserEvents(userId) {
+/** Events of every org where this user may see inventory/events, or events where they are assigned staff. */
+export async function listOrganiserEvents(user) {
+ const orgIds = await orgIdsFor(user, 'event.view_inventory');
+ const staffEventIds = await eventIdsFor(user, 'event.view_inventory');
const { rows } = await db.query(
- `SELECT e.id, e.slug, e.title, e.category, e.city, e.start_at, e.status, e.capacity, e.requires_approval,
+ `SELECT e.id, e.slug, e.title, e.category, e.city, e.start_at, e.end_at, e.status, e.capacity, e.requires_approval,
(SELECT COALESCE(sum(b.quantity), 0)::int FROM bookings b WHERE b.event_id = e.id AND b.status IN ('confirmed', 'checked_in')) AS confirmed,
- (SELECT count(*)::int FROM bookings b WHERE b.event_id = e.id AND b.status = 'pending_approval') AS requests
- FROM events e WHERE e.organiser_user_id = $1 ORDER BY e.start_at DESC LIMIT 100`, [userId]);
+ (SELECT count(*)::int FROM bookings b WHERE b.event_id = e.id AND b.status = 'pending_approval') AS requests,
+ (SELECT count(*)::int FROM tickets t WHERE t.event_id = e.id AND t.status = 'checked_in') AS checked_in_count,
+ (SELECT count(*)::int FROM event_team et WHERE et.event_id = e.id AND et.status = 'active') AS staff_count
+ FROM events e
+ WHERE (e.organiser_org_id = ANY($1::uuid[]) OR e.id = ANY($2::uuid[]))
+ ORDER BY e.start_at DESC LIMIT 100`, [orgIds, staffEventIds]);
+ return rows.map((r) => {
+ const confirmed = r.confirmed || 0;
+ const checkedIn = r.checked_in_count || 0;
+ const remaining = Math.max(0, (r.capacity || 0) - confirmed);
+ const attendancePct = confirmed > 0 ? Math.round((checkedIn / confirmed) * 100) : 0;
+ return {
+ id: r.id, title: r.title, city: r.city, startAt: r.start_at, endAt: r.end_at, status: r.status,
+ capacity: r.capacity, confirmed, requests: r.requests || 0, requiresApproval: r.requires_approval,
+ checkedIn, remaining, attendanceRate: attendancePct, staffCount: r.staff_count || 0,
+ path: `${isTripCategory(r.category) ? '/trips' : '/events'}/${r.slug}`,
+ manageUrl: `/organiser/events/${r.id}`,
+ scanUrl: `/organiser/events/${r.id}/scan`
+ };
+ });
+}
+
+/**
+ * Detailed event overview and readiness status for organisers.
+ */
+export async function getEventOverview(user, eventId) {
+ await authorize(user, 'event.view_inventory', { eventId });
+ const e = (await db.query(`SELECT * FROM events WHERE id = $1`, [eventId])).rows[0];
+ if (!e) throw new HttpError(404, 'not_found', 'Event not found');
+
+ const [attendance, staffRows, announcements] = await Promise.all([
+ db.query(`SELECT
+ (SELECT COALESCE(sum(b.quantity), 0)::int FROM bookings b WHERE b.event_id = $1 AND b.status IN ('confirmed', 'checked_in')) AS confirmed_seats,
+ (SELECT count(*)::int FROM bookings b WHERE b.event_id = $1 AND b.status = 'pending_approval') AS pending_requests,
+ (SELECT count(*)::int FROM tickets t WHERE t.event_id = $1 AND t.status = 'checked_in') AS checked_in_count,
+ (SELECT count(*)::int FROM tickets t WHERE t.event_id = $1 AND t.status IN ('valid', 'checked_in')) AS eligible_tickets,
+ (SELECT count(*)::int FROM bookings b WHERE b.event_id = $1 AND b.status = 'refunded') AS refunded_bookings`, [eventId]),
+ db.query(`SELECT count(*)::int AS count FROM event_team WHERE event_id = $1 AND status = 'active'`, [eventId]),
+ db.query(`SELECT count(*)::int AS count FROM event_announcements WHERE event_id = $1`, [eventId])
+ ]);
+
+ const stats = attendance.rows[0];
+ const confirmed = stats.confirmed_seats || 0;
+ const checkedIn = stats.checked_in_count || 0;
+ const eligible = stats.eligible_tickets || 0;
+ const remaining = Math.max(0, e.capacity - confirmed);
+ const attendanceRate = eligible > 0 ? Math.round((checkedIn / eligible) * 100) : 0;
+
+ const [canEdit, canManageStaff, canCheckIn, canDecide, canCancel] = await Promise.all([
+ can(user, 'event.edit', { eventId }),
+ can(user, 'event.manage_staff', { eventId }),
+ can(user, 'event.check_in', { eventId }),
+ can(user, 'event.decide_bookings', { eventId }),
+ can(user, 'event.cancel', { eventId })
+ ]);
+
+ const hasTitle = Boolean(e.title && e.title.length >= 3);
+ const hasDescription = Boolean(e.description && e.description.length >= 10);
+ const hasVenue = Boolean(e.venue_private || e.area_public);
+ const hasTiers = (await db.query(`SELECT 1 FROM ticket_types WHERE event_id = $1 AND active LIMIT 1`, [eventId])).rowCount > 0;
+ const isPublished = e.status === 'published';
+ const staffCount = staffRows.rows[0]?.count || 0;
+ const hasStaff = staffCount > 0;
+ const gateReady = hasStaff || canCheckIn;
+
+ const readinessScore = [hasTitle, hasDescription, hasVenue, hasTiers, isPublished, gateReady].filter(Boolean).length;
+ const path = `${isTripCategory(e.category) ? '/trips' : '/events'}/${e.slug}`;
+
+ return {
+ event: {
+ id: e.id,
+ title: e.title,
+ slug: e.slug,
+ category: e.category,
+ city: e.city,
+ startAt: e.start_at,
+ endAt: e.end_at,
+ status: e.status,
+ capacity: e.capacity,
+ venuePrivacy: e.venue_privacy,
+ venue: e.venue_private,
+ area: e.area_public,
+ mapsUrl: e.maps_url,
+ refundPolicy: e.refund_policy,
+ requiresApproval: e.requires_approval,
+ path,
+ manageUrl: `/organiser/events/${e.id}`,
+ scanUrl: `/organiser/events/${e.id}/scan`
+ },
+ metrics: {
+ capacity: e.capacity,
+ confirmedSeats: confirmed,
+ remainingSeats: remaining,
+ pendingRequests: stats.pending_requests || 0,
+ eligibleTickets: eligible,
+ checkedInTickets: checkedIn,
+ attendanceRate,
+ refundedBookings: stats.refunded_bookings || 0,
+ activeStaffCount: staffCount,
+ announcementsCount: announcements.rows[0]?.count || 0
+ },
+ readiness: {
+ score: `${readinessScore}/6`,
+ complete: readinessScore === 6,
+ checklist: [
+ { key: 'basics', label: 'Event Basics & Title', passed: hasTitle },
+ { key: 'description', label: 'Event Description', passed: hasDescription },
+ { key: 'venue', label: 'Venue & Directions', passed: hasVenue },
+ { key: 'tiers', label: 'Ticket Tiers Configured', passed: hasTiers },
+ { key: 'published', label: 'Published & Discoverable', passed: isPublished },
+ { key: 'gate', label: 'Door Staff & Scanner Ready', passed: gateReady }
+ ]
+ },
+ permissions: {
+ canEdit,
+ canManageStaff,
+ canCheckIn,
+ canDecide,
+ canCancel
+ }
+ };
+}
+
+/**
+ * Ticket tier inventory and availability breakdown.
+ */
+export async function getEventInventory(user, eventId) {
+ await authorize(user, 'event.view_inventory', { eventId });
+ const e = (await db.query(`SELECT id, title, capacity FROM events WHERE id = $1`, [eventId])).rows[0];
+ if (!e) throw new HttpError(404, 'not_found', 'Event not found');
+
+ const tiers = (await db.query(
+ `SELECT t.id, t.name, t.kind, t.price_paise, t.quantity, t.max_per_booking, t.eligibility, t.valid_on, t.sort_order,
+ (SELECT COALESCE(sum(b.quantity), 0)::int FROM bookings b WHERE b.ticket_type_id = t.id AND b.status IN ('confirmed', 'checked_in')) AS sold,
+ (SELECT COALESCE(sum(b.quantity), 0)::int FROM bookings b WHERE b.ticket_type_id = t.id AND b.status = 'pending_payment' AND b.hold_expires_at > now()) AS holds
+ FROM ticket_types t
+ WHERE t.event_id = $1 AND t.active
+ ORDER BY t.sort_order ASC, t.created_at ASC`,
+ [eventId]
+ )).rows;
+
+ const totalSold = tiers.reduce((sum, t) => sum + (t.sold || 0), 0);
+ const totalHolds = tiers.reduce((sum, t) => sum + (t.holds || 0), 0);
+ const totalRemaining = Math.max(0, e.capacity - totalSold - totalHolds);
+
+ return {
+ eventId,
+ capacity: e.capacity,
+ totalSold,
+ totalHolds,
+ totalRemaining,
+ tiers: tiers.map((t) => {
+ const sold = t.sold || 0;
+ const holds = t.holds || 0;
+ const remaining = Math.max(0, t.quantity - sold - holds);
+ return {
+ id: t.id,
+ name: t.name,
+ kind: t.kind,
+ pricePaise: t.price_paise,
+ quantity: t.quantity,
+ maxPerBooking: t.max_per_booking,
+ eligibility: t.eligibility || null,
+ sold,
+ holds,
+ remaining
+ };
+ })
+ };
+}
+
+/**
+ * Validated edit of a published event's parameters.
+ */
+export async function updateOrganiserEvent(user, eventId, updates) {
+ await authorize(user, 'event.edit', { eventId });
+
+ return db.tx(async (c) => {
+ const e = (await c.query(`SELECT * FROM events WHERE id = $1 FOR UPDATE`, [eventId])).rows[0];
+ if (!e) throw new HttpError(404, 'not_found', 'Event not found');
+ if (e.status === 'cancelled') throw new HttpError(409, 'event_cancelled', 'Cancelled events cannot be modified');
+
+ const fields = [];
+ const values = [];
+ let idx = 1;
+
+ if (updates.title !== undefined) {
+ const title = clean(updates.title);
+ if (title.length < 3) throw new HttpError(400, 'validation', 'Event title must be at least 3 characters');
+ fields.push(`title = $${idx++}`);
+ values.push(title);
+ }
+
+ if (updates.description !== undefined) {
+ const desc = clean(updates.description);
+ if (desc.length < 10) throw new HttpError(400, 'validation', 'Event description must be at least 10 characters');
+ fields.push(`description = $${idx++}`);
+ values.push(desc);
+ }
+
+ if (updates.capacity !== undefined) {
+ const cap = Number(updates.capacity);
+ if (!Number.isInteger(cap) || cap < 1 || cap > MAX_CAPACITY) {
+ throw new HttpError(400, 'validation', `Capacity must be between 1 and ${MAX_CAPACITY}`);
+ }
+ const confirmed = (await c.query(
+ `SELECT COALESCE(sum(quantity), 0)::int AS n FROM bookings WHERE event_id = $1 AND status IN ('confirmed', 'checked_in')`,
+ [eventId]
+ )).rows[0].n;
+ if (cap < confirmed) {
+ throw new HttpError(409, 'capacity_too_low', `Capacity cannot be reduced below the ${confirmed} currently confirmed seats`);
+ }
+ fields.push(`capacity = $${idx++}`);
+ values.push(cap);
+ }
+
+ if (updates.start_at !== undefined) {
+ const d = new Date(updates.start_at);
+ if (isNaN(d.getTime())) throw new HttpError(400, 'validation', 'Invalid start time');
+ fields.push(`start_at = $${idx++}`);
+ values.push(d.toISOString());
+ }
+
+ if (updates.end_at !== undefined) {
+ if (updates.end_at === null) {
+ fields.push(`end_at = NULL`);
+ } else {
+ const d = new Date(updates.end_at);
+ if (isNaN(d.getTime())) throw new HttpError(400, 'validation', 'Invalid end time');
+ const start = updates.start_at ? new Date(updates.start_at) : new Date(e.start_at);
+ if (d <= start) throw new HttpError(400, 'validation', 'End time must be after start time');
+ fields.push(`end_at = $${idx++}`);
+ values.push(d.toISOString());
+ }
+ }
+
+ if (updates.venue_private !== undefined) {
+ fields.push(`venue_private = $${idx++}`);
+ values.push(clean(updates.venue_private) || null);
+ }
+
+ if (updates.area_public !== undefined) {
+ fields.push(`area_public = $${idx++}`);
+ values.push(clean(updates.area_public) || null);
+ }
+
+ if (updates.venue_privacy !== undefined) {
+ if (!['public', 'disclosed_after_booking'].includes(updates.venue_privacy)) {
+ throw new HttpError(400, 'validation', 'Invalid venue privacy option');
+ }
+ fields.push(`venue_privacy = $${idx++}`);
+ values.push(updates.venue_privacy);
+ }
+
+ if (updates.maps_url !== undefined) {
+ if (updates.maps_url && !isMapsUrl(updates.maps_url)) {
+ throw new HttpError(400, 'validation', 'Maps link must be a valid Google Maps HTTPS URL');
+ }
+ fields.push(`maps_url = $${idx++}`);
+ values.push(updates.maps_url ? clean(updates.maps_url) : null);
+ }
+
+ if (updates.refund_policy !== undefined) {
+ fields.push(`refund_policy = $${idx++}`);
+ values.push(clean(updates.refund_policy) || null);
+ }
+
+ if (updates.booking_questions !== undefined) {
+ fields.push(`booking_questions = $${idx++}`);
+ values.push(JSON.stringify(Array.isArray(updates.booking_questions) ? updates.booking_questions : []));
+ }
+
+ if (updates.pickup_points !== undefined) {
+ fields.push(`pickup_points = $${idx++}`);
+ values.push(JSON.stringify(Array.isArray(updates.pickup_points) ? updates.pickup_points : []));
+ }
+
+ if (!fields.length) throw new HttpError(400, 'validation', 'No updates provided');
+
+ fields.push(`updated_at = now()`);
+ values.push(eventId);
+
+ const updated = (await c.query(
+ `UPDATE events SET ${fields.join(', ')} WHERE id = $${idx} RETURNING *`,
+ values
+ )).rows[0];
+
+ await audit(`user:${user.id}`, 'event.edit', eventId, updates, c);
+ return updated;
+ });
+}
+
+/**
+ * Organiser cancels an entire event with a stated reason.
+ */
+export async function cancelOrganiserEvent(user, eventId, { reason = 'Cancelled by organiser' } = {}) {
+ await authorize(user, 'event.cancel', { eventId });
+
+ return db.tx(async (c) => {
+ const e = (await c.query(`SELECT * FROM events WHERE id = $1 FOR UPDATE`, [eventId])).rows[0];
+ if (!e) throw new HttpError(404, 'not_found', 'Event not found');
+ if (e.status === 'cancelled') throw new HttpError(409, 'already_cancelled', 'Event is already cancelled');
+
+ await c.query(`UPDATE events SET status = 'cancelled', updated_at = now() WHERE id = $1`, [eventId]);
+
+ await c.query(
+ `UPDATE bookings
+ SET status = 'cancelled',
+ cancelled_at = now(),
+ cancel_reason = $2,
+ updated_at = now()
+ WHERE event_id = $1 AND status IN ('pending_approval', 'pending_payment', 'confirmed')`,
+ [eventId, reason]
+ );
+
+ await c.query(
+ `UPDATE tickets
+ SET status = 'cancelled',
+ updated_at = now()
+ WHERE event_id = $1 AND status = 'valid'`,
+ [eventId]
+ );
+
+ const attendees = (await c.query(
+ `SELECT DISTINCT user_id, id FROM bookings WHERE event_id = $1`,
+ [eventId]
+ )).rows;
+
+ for (const a of attendees) {
+ await enqueue(c, {
+ kind: 'event_update',
+ userId: a.user_id,
+ eventId,
+ bookingId: a.id,
+ title: `Event Cancelled: ${e.title}`,
+ text: `The organiser has cancelled "${e.title}". Reason: ${reason}.`,
+ dedupeKey: `cancel:${eventId}:${a.user_id}`
+ });
+ }
+
+ await audit(`user:${user.id}`, 'event.cancel', eventId, { reason, attendeeCount: attendees.length }, c);
+ return { ok: true, eventId, status: 'cancelled' };
+ });
+}
+
+/**
+ * Organiser cancels an individual attendee booking with a stated reason.
+ */
+export async function cancelOrganiserBooking(user, bookingId, { reason = 'Cancelled by organiser' } = {}) {
+ const b = (await db.query(`SELECT * FROM bookings WHERE id = $1`, [bookingId])).rows[0];
+ if (!b) throw new HttpError(404, 'not_found', 'Booking not found');
+
+ await authorize(user, 'event.cancel_booking', { eventId: b.event_id });
+
+ return db.tx(async (c) => {
+ const locked = (await c.query(`SELECT * FROM bookings WHERE id = $1 FOR UPDATE`, [bookingId])).rows[0];
+ if (locked.status === 'cancelled' || locked.status === 'declined') {
+ throw new HttpError(409, 'already_closed', 'This booking is already cancelled or declined');
+ }
+
+ await c.query(
+ `UPDATE bookings
+ SET status = 'cancelled',
+ cancelled_at = now(),
+ cancel_reason = $2,
+ updated_at = now()
+ WHERE id = $1`,
+ [bookingId, reason]
+ );
+
+ await c.query(
+ `UPDATE tickets
+ SET status = 'cancelled',
+ revoked_at = now(),
+ revoked_by = $2,
+ revocation_reason = $3,
+ updated_at = now()
+ WHERE booking_id = $1 AND status = 'valid'`,
+ [bookingId, user.id, reason]
+ );
+
+ await enqueue(c, {
+ kind: 'booking_declined',
+ userId: locked.user_id,
+ bookingId: locked.id,
+ dedupeKey: `bk:${locked.id}:cancelled`
+ });
+
+ await audit(`user:${user.id}`, 'booking.cancel_by_host', bookingId, { eventId: locked.event_id, reason }, c);
+ return { ok: true, bookingId, status: 'cancelled' };
+ });
+}
+
+/**
+ * Filtered & paginated attendee/booking search for an event.
+ */
+export async function listOrganiserBookings(user, eventId, { query = '', status = 'all', page = 1, limit = 50 } = {}) {
+ await authorize(user, 'event.view_guests', { eventId });
+
+ const params = [eventId];
+ let where = 'b.event_id = $1';
+
+ if (status && status !== 'all') {
+ params.push(status);
+ where += ` AND b.status = $${params.length}`;
+ }
+
+ if (query && query.trim()) {
+ params.push(`%${query.trim().toLowerCase()}%`);
+ const qIdx = params.length;
+ where += ` AND (lower(u.alias) LIKE $${qIdx} OR b.id::text LIKE $${qIdx})`;
+ }
+
+ const offset = Math.max(0, (page - 1) * limit);
+ params.push(limit);
+ const lIdx = params.length;
+ params.push(offset);
+ const oIdx = params.length;
+
+ const { rows } = await db.query(
+ `SELECT b.id, b.status, b.quantity, b.amount_paise, b.payment_mode, b.created_at, b.confirmed_at,
+ b.checked_in_at, b.cancelled_at, b.cancel_reason, b.answers, b.pickup_point_id,
+ u.id AS user_id, u.alias, u.telegram_user_id,
+ tt.name AS tier_name, tt.kind AS tier_kind,
+ eo.status AS payment_status,
+ (SELECT count(*)::int FROM tickets t WHERE t.booking_id = b.id AND t.status = 'checked_in') AS tickets_checked_in
+ FROM bookings b
+ JOIN users u ON u.id = b.user_id
+ LEFT JOIN ticket_types tt ON tt.id = b.ticket_type_id
+ LEFT JOIN external_orders eo ON eo.matched_booking_id = b.id
+ WHERE ${where}
+ ORDER BY b.created_at DESC
+ LIMIT $${lIdx} OFFSET $${oIdx}`,
+ params
+ );
+
return rows.map((r) => ({
- id: r.id, title: r.title, city: r.city, startAt: r.start_at, status: r.status, capacity: r.capacity, confirmed: r.confirmed,
- requests: r.requests, requiresApproval: r.requires_approval,
- path: `${isTripCategory(r.category) ? '/trips' : '/events'}/${r.slug}`, manageUrl: `/organiser/events/${r.id}`
+ id: r.id,
+ ref: r.id.slice(0, 8).toUpperCase(),
+ status: r.status,
+ userId: r.user_id,
+ alias: r.alias || 'Guest',
+ ticket: r.tier_name || 'Standard',
+ kind: r.tier_kind || 'free',
+ quantity: r.quantity,
+ amountPaise: r.amount_paise,
+ paymentMode: r.payment_mode,
+ paymentStatus: r.payment_mode === 'free' ? 'not_required' : (r.payment_status || 'unpaid'),
+ createdAt: r.created_at,
+ confirmedAt: r.confirmed_at,
+ checkedInAt: r.checked_in_at,
+ cancelledAt: r.cancelled_at,
+ cancelReason: r.cancel_reason,
+ ticketsCheckedIn: r.tickets_checked_in || 0
}));
}
+
diff --git a/lib/services/permissions.js b/lib/services/permissions.js
new file mode 100644
index 0000000..b124d69
--- /dev/null
+++ b/lib/services/permissions.js
@@ -0,0 +1,234 @@
+// lib/services/permissions.js - The one access gate for organiser, org and venue resources.
+// can(user, action, scope) answers yes/no; authorize() throws. A person outside the resource's
+// org gets 404 (the resource is not revealed); a member whose role is too low gets 403.
+// Platform roles still come from admin_users; org roles come from org_memberships.
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+
+/** Org roles allowed to perform each action. */
+export const ORG_ACTIONS = {
+ 'org.view': ['owner', 'admin', 'manager', 'staff'],
+ 'org.view_members': ['owner', 'admin', 'manager'],
+ 'org.manage_members': ['owner', 'admin'],
+ 'org.manage_admins': ['owner'],
+ 'event.manage': ['owner', 'admin', 'manager'],
+ 'event.edit': ['owner', 'admin', 'manager'],
+ 'event.cancel': ['owner', 'admin', 'manager'],
+ 'event.decide_bookings': ['owner', 'admin', 'manager'],
+ 'event.view_guests': ['owner', 'admin', 'manager', 'staff'],
+ 'event.cancel_booking': ['owner', 'admin', 'manager'],
+ 'event.check_in': ['owner', 'admin', 'manager', 'staff'],
+ 'event.manual_override': ['owner', 'admin', 'manager'],
+ 'event.reissue_ticket': ['owner', 'admin', 'manager'],
+ 'event.manage_staff': ['owner', 'admin'],
+ 'event.announcements': ['owner', 'admin', 'manager'],
+ 'event.view_audit': ['owner', 'admin', 'manager'],
+ 'event.view_inventory': ['owner', 'admin', 'manager', 'staff'],
+ 'venue.view': ['owner', 'admin', 'manager', 'staff'],
+ 'venue.view_private': ['owner', 'admin', 'manager', 'staff'],
+ 'venue.manage': ['owner', 'admin']
+};
+
+/** Event staff (event_team) roles allowed to perform each action on the assigned event. */
+export const EVENT_STAFF_ACTIONS = {
+ 'event.manage': ['organiser', 'event_manager'],
+ 'event.edit': ['organiser', 'event_manager'],
+ 'event.cancel': ['organiser', 'event_manager'],
+ 'event.decide_bookings': ['organiser', 'event_manager', 'guest_list_manager'],
+ 'event.view_guests': ['organiser', 'event_manager', 'guest_list_manager', 'assistant'],
+ 'event.cancel_booking': ['organiser', 'event_manager'],
+ 'event.check_in': ['organiser', 'event_manager', 'guest_list_manager', 'door_staff'],
+ 'event.manual_override': ['organiser', 'event_manager'],
+ 'event.reissue_ticket': ['organiser', 'event_manager'],
+ 'event.manage_staff': ['organiser', 'event_manager'],
+ 'event.announcements': ['organiser', 'event_manager'],
+ 'event.view_audit': ['organiser', 'event_manager'],
+ 'event.view_inventory': ['organiser', 'event_manager', 'guest_list_manager', 'door_staff', 'assistant']
+};
+
+/** Platform (admin_users) roles allowed each action, on any org or event. */
+const PLATFORM_ACTIONS = {
+ super_admin: Object.keys(ORG_ACTIONS),
+ event_manager: [
+ 'org.view', 'event.manage', 'event.edit', 'event.cancel', 'event.decide_bookings',
+ 'event.view_guests', 'event.cancel_booking', 'event.check_in', 'event.manual_override',
+ 'event.reissue_ticket', 'event.manage_staff', 'event.announcements', 'event.view_audit',
+ 'event.view_inventory', 'venue.view'
+ ]
+};
+
+export const ACTIONS = [...new Set([...Object.keys(ORG_ACTIONS), ...Object.keys(EVENT_STAFF_ACTIONS)])];
+
+// A personal org counts only while its owner may still organise: the admin organiser switch, or an
+// active events admin (the same rule isOrganiser() applies to the wizard).
+const PERSONAL_ORG_LIVE = `(o.kind <> 'personal' OR u.organiser_enabled OR EXISTS (
+ SELECT 1 FROM admin_users a WHERE a.telegram_user_id = u.telegram_user_id AND a.active AND a.role IN ('super_admin', 'event_manager')))`;
+
+async function platformRole(user, c) {
+ if (!user?.telegram_user_id) return null;
+ const a = (await c.query('SELECT role FROM admin_users WHERE telegram_user_id = $1 AND active', [user.telegram_user_id])).rows[0];
+ return a?.role || null;
+}
+
+/**
+ * The user's effective role in an org, or null (see PERSONAL_ORG_LIVE for personal orgs).
+ */
+export async function orgRole(user, orgId, c = db) {
+ if (!user?.id || !orgId) return null;
+ const r = (await c.query(
+ `SELECT m.role FROM org_memberships m
+ JOIN organisations o ON o.id = m.org_id
+ JOIN users u ON u.id = m.user_id
+ WHERE m.user_id = $1 AND m.org_id = $2 AND m.status = 'active' AND o.status = 'active' AND u.status = 'active'
+ AND ${PERSONAL_ORG_LIVE}`, [user.id, orgId])).rows[0];
+ return r?.role || null;
+}
+
+/**
+ * Which org a scope belongs to. scope: { orgId } | { event } | { eventId } | { venue } | { venueId }.
+ * Events from before migration 012 with no org fall back to their organiser's personal org.
+ */
+export async function scopeOrgId(scope, c = db) {
+ if (!scope) return null;
+ if (scope.orgId) return scope.orgId;
+ let event = scope.event;
+ if (!event && scope.eventId) event = (await c.query('SELECT organiser_org_id, organiser_user_id FROM events WHERE id = $1', [scope.eventId])).rows[0];
+ if (event) {
+ if (event.organiser_org_id) return event.organiser_org_id;
+ if (!event.organiser_user_id) return null;
+ return (await c.query('SELECT id FROM organisations WHERE personal_user_id = $1', [event.organiser_user_id])).rows[0]?.id || null;
+ }
+ if (scope.venue) return scope.venue.org_id;
+ if (scope.venueId) return (await c.query('SELECT org_id FROM venues WHERE id = $1', [scope.venueId])).rows[0]?.org_id || null;
+ return null;
+}
+
+export async function resolveEventId(scope, c = db) {
+ if (!scope) return null;
+ if (scope.eventId) return scope.eventId;
+ if (scope.event?.id) return scope.event.id;
+ if (scope.booking?.event_id) return scope.booking.event_id;
+ if (scope.bookingId) {
+ const b = (await c.query('SELECT event_id FROM bookings WHERE id = $1', [scope.bookingId])).rows[0];
+ return b?.event_id || null;
+ }
+ if (scope.ticketId) {
+ const t = (await c.query('SELECT event_id FROM tickets WHERE id = $1', [scope.ticketId])).rows[0];
+ return t?.event_id || null;
+ }
+ return null;
+}
+
+/**
+ * The user's active event-scoped team role, or null.
+ */
+export async function eventTeamRole(user, eventId, c = db) {
+ if (!user?.id || !eventId) return null;
+ const r = (await c.query(
+ `SELECT team_role FROM event_team
+ WHERE user_id = $1 AND event_id = $2 AND status = 'active'`,
+ [user.id, eventId]
+ )).rows[0];
+ return r?.team_role || null;
+}
+
+/** Decide one action. Returns { allowed, member, role } where member says whether the user belongs to the org or event team. */
+export async function check(user, action, scope, c = db) {
+ if (!ORG_ACTIONS[action] && !EVENT_STAFF_ACTIONS[action]) throw new Error(`unknown action ${action}`);
+ if (!user?.id) return { allowed: false, member: false };
+ const pRole = await platformRole(user, c);
+ if (pRole && PLATFORM_ACTIONS[pRole]?.includes(action)) return { allowed: true, member: true, role: pRole, platformRole: pRole };
+
+ // Check event-level team membership first if scoped to an event
+ const eventId = await resolveEventId(scope, c);
+ let staffRole = null;
+ if (eventId) {
+ staffRole = await eventTeamRole(user, eventId, c);
+ if (staffRole) {
+ const allowed = Boolean(EVENT_STAFF_ACTIONS[action]?.includes(staffRole));
+ if (allowed) return { allowed: true, member: true, role: staffRole, eventStaff: true };
+ }
+ }
+
+ // Check organisation-level membership
+ const orgId = await scopeOrgId(scope, c);
+ const role = await orgRole(user, orgId, c);
+ if (role) {
+ const allowed = Boolean(ORG_ACTIONS[action]?.includes(role));
+ return { allowed, member: true, role, orgRole: role };
+ }
+
+ // If user has an event staff role on this event but it doesn't allow the action, they are a member with insufficient role (403)
+ if (staffRole) return { allowed: false, member: true, role: staffRole, eventStaff: true };
+
+ return { allowed: false, member: false };
+}
+
+export async function can(user, action, scope, c = db) {
+ return (await check(user, action, scope, c)).allowed;
+}
+
+/** Throw unless allowed: 404 to outsiders (nothing is revealed), 403 to members with too low a role. */
+export async function authorize(user, action, scope, c = db, { notFound = 'Not found' } = {}) {
+ const r = await check(user, action, scope, c);
+ if (r.allowed) return r;
+ if (r.member) throw new HttpError(403, 'forbidden', 'Your role in this organisation does not allow that.');
+ throw new HttpError(404, 'not_found', notFound);
+}
+
+/** Org ids where the user holds an active role that allows `action` (for list scoping). */
+export async function orgIdsFor(user, action, c = db) {
+ if (!user?.id) return [];
+ const roles = ORG_ACTIONS[action] || [];
+ if (!roles.length) return [];
+ const { rows } = await c.query(
+ `SELECT m.org_id FROM org_memberships m
+ JOIN organisations o ON o.id = m.org_id
+ JOIN users u ON u.id = m.user_id
+ WHERE m.user_id = $1 AND m.status = 'active' AND o.status = 'active' AND u.status = 'active'
+ AND ${PERSONAL_ORG_LIVE} AND m.role = ANY($2::org_role[])`, [user.id, roles]);
+ return rows.map((r) => r.org_id);
+}
+
+/** Event ids where the user holds an active event staff role that allows `action`. */
+export async function eventIdsFor(user, action, c = db) {
+ if (!user?.id) return [];
+ const roles = EVENT_STAFF_ACTIONS[action] || [];
+ if (!roles.length) return [];
+ const { rows } = await c.query(
+ `SELECT event_id FROM event_team WHERE user_id = $1 AND status = 'active' AND team_role = ANY($2::text[])`,
+ [user.id, roles]
+ );
+ return rows.map((r) => r.event_id);
+}
+
+/**
+ * The user's personal org (created on first need), with an owner membership and the
+ * organise_events capability. Idempotent; safe inside any transaction.
+ */
+export async function ensurePersonalOrg(user, c = db) {
+ await c.query(
+ `INSERT INTO organisations (kind, name, personal_user_id) VALUES ('personal', $2, $1)
+ ON CONFLICT (personal_user_id) DO NOTHING`, [user.id, (user.alias || '').trim() || 'Personal']);
+ const org = (await c.query('SELECT id FROM organisations WHERE personal_user_id = $1', [user.id])).rows[0];
+ await c.query(
+ `INSERT INTO org_memberships (user_id, org_id, role) VALUES ($1, $2, 'owner') ON CONFLICT (user_id, org_id) DO NOTHING`, [user.id, org.id]);
+ // Same rule as the migration 012 backfill and PERSONAL_ORG_LIVE: organiser switch OR active event admin.
+ await c.query(
+ `INSERT INTO user_capabilities (user_id, capability_code, status)
+ SELECT u.id, 'organise_events',
+ CASE WHEN (u.organiser_enabled OR EXISTS (
+ SELECT 1 FROM admin_users a WHERE a.telegram_user_id = u.telegram_user_id AND a.active AND a.role IN ('super_admin', 'event_manager')
+ )) THEN 'verified' ELSE 'revoked' END::capability_status
+ FROM users u WHERE u.id = $1
+ ON CONFLICT (user_id, capability_code) DO NOTHING`, [user.id]);
+ return org.id;
+}
+
+/** Keep the organise_events capability in step with the admin organiser switch. */
+export async function setOrganiseCapability(userId, enabled, c = db) {
+ await c.query(
+ `INSERT INTO user_capabilities (user_id, capability_code, status) VALUES ($1, 'organise_events', $2)
+ ON CONFLICT (user_id, capability_code) DO UPDATE SET status = EXCLUDED.status`,
+ [userId, enabled ? 'verified' : 'revoked']);
+}
diff --git a/lib/services/reconcile.js b/lib/services/reconcile.js
new file mode 100644
index 0000000..1371eb2
--- /dev/null
+++ b/lib/services/reconcile.js
@@ -0,0 +1,64 @@
+// lib/services/reconcile.js - Compare SuperProfile's own sales list with external_orders.
+//
+// The SuperProfile MCP needs the owner's OAuth, so the daily reconciliation is a Claude Code scheduled
+// task (not a Vercel cron): it reads sales through the MCP and POSTs them to /api/reconcile/superprofile
+// (bearer CRON_SECRET), where diffOrders() runs. Nothing is fixed automatically: the result is an alert.
+import { db } from '../db.js';
+import { rupeesToPaise } from './superprofile.js';
+import { recordIntegrationError } from './insights.js';
+import { enqueue } from './notifications.js';
+
+/**
+ * @param {{ orderId: string, amountPaise: number|null, status: 'paid'|'refunded'|'cancelled' }[]} sp SuperProfile's view
+ * @param {{ order_id: string, amount_paise: number|string|null, status: string }[]} ours external_orders rows
+ */
+export function diffOrders(sp, ours) {
+ const key = (id) => String(id).trim().toLowerCase();
+ const mine = new Map(ours.map((o) => [key(o.order_id), o]));
+ const theirs = new Map(sp.map((o) => [key(o.orderId), o]));
+ const out = { missingInDb: [], missingInSuperprofile: [], amountDrift: [], statusDrift: [] };
+ for (const [k, s] of theirs) {
+ const o = mine.get(k);
+ if (!o) { out.missingInDb.push({ orderId: s.orderId, amountPaise: s.amountPaise ?? null, status: s.status }); continue; }
+ const ours$ = o.amount_paise === null || o.amount_paise === undefined ? null : Number(o.amount_paise);
+ if (s.amountPaise !== null && s.amountPaise !== undefined && ours$ !== null && Number(s.amountPaise) !== ours$) {
+ out.amountDrift.push({ orderId: s.orderId, superprofilePaise: Number(s.amountPaise), ourPaise: ours$ });
+ }
+ if (s.status !== o.status) out.statusDrift.push({ orderId: s.orderId, superprofile: s.status, ours: o.status });
+ }
+ for (const [k, o] of mine) if (!theirs.has(k)) out.missingInSuperprofile.push({ orderId: o.order_id, status: o.status });
+ return out;
+}
+
+export const isClean = (d) => !d.missingInDb.length && !d.missingInSuperprofile.length && !d.amountDrift.length && !d.statusDrift.length;
+
+/** Normalise one sale as the scheduled task reads it from the MCP. Throws on a row without an id. */
+export function normaliseSale(s) {
+ const id = String(s.orderId ?? s.id ?? '').trim();
+ if (!id || id.length > 200) throw new Error('sale without an order id');
+ const status = ['refunded', 'cancelled'].includes(String(s.status || '').toLowerCase()) ? String(s.status).toLowerCase() : 'paid';
+ const amountPaise = s.amountPaise !== undefined ? Number(s.amountPaise) : rupeesToPaise(s.amount);
+ return { orderId: id, amountPaise: Number.isFinite(amountPaise) ? amountPaise : null, status };
+}
+
+/**
+ * Diff a window of SuperProfile sales against our orders, record the findings and, when something is
+ * off, queue one Telegram alert to the admins. Safe to run repeatedly (alerts dedupe per day and result).
+ */
+export async function reconcileWindow({ sales, since, until }) {
+ const sp = sales.map(normaliseSale);
+ const { rows } = await db.query(
+ `SELECT order_id, amount_paise, status FROM external_orders WHERE received_at >= $1 AND received_at <= $2`, [since, until]);
+ const diff = diffOrders(sp, rows);
+ const counts = { checked: sp.length, missingInDb: diff.missingInDb.length, missingInSuperprofile: diff.missingInSuperprofile.length, amountDrift: diff.amountDrift.length, statusDrift: diff.statusDrift.length };
+ let notificationId = null;
+ if (!isClean(diff)) {
+ await recordIntegrationError('superprofile_webhook', 'reconcile_drift',
+ `missing in app: ${counts.missingInDb}, missing on SuperProfile: ${counts.missingInSuperprofile}, amount drift: ${counts.amountDrift}, status drift: ${counts.statusDrift}`);
+ notificationId = await db.tx((c) => enqueue(c, {
+ kind: 'reconcile_alert',
+ dedupeKey: `rc:${new Date().toISOString().slice(0, 10)}:${counts.missingInDb}:${counts.missingInSuperprofile}:${counts.amountDrift}:${counts.statusDrift}`
+ }));
+ }
+ return { counts, diff, notificationId };
+}
diff --git a/lib/services/refunds.js b/lib/services/refunds.js
index 48a9603..28a21b9 100644
--- a/lib/services/refunds.js
+++ b/lib/services/refunds.js
@@ -1,16 +1,32 @@
-// lib/services/refunds.js - Finance-initiated refunds (tickets via provider, memberships via Stars).
+// lib/services/refunds.js - Finance-initiated refunds of Telegram Stars payments (memberships).
+// Ticket refunds are issued on SuperProfile and arrive as a notification (services/orders.js).
import { db } from '../db.js';
import { HttpError } from '../http.js';
-import { providerByName } from '../payments/index.js';
+import { ticketProvider } from '../payments/index.js';
import { tg } from '../telegram/api.js';
import { enqueue, deliverMany } from './notifications.js';
import { audit } from '../audit.js';
import { removeFromChat, tierChatId } from './invites.js';
+import { refundUpiOrder } from './upi-payments.js';
-export async function refundPayment(paymentId, actor) {
+export async function refundPayment(paymentId, actor, options = {}) {
const p = await db.one(
`SELECT p.*, u.telegram_user_id FROM payments p LEFT JOIN users u ON u.id = p.user_id WHERE p.id = $1`, [paymentId]);
if (!p) throw new HttpError(404, 'not_found', 'Payment not found');
+
+ // Authorized admin/finance refund for UPI direct payments
+ if (p.provider === 'phonepe' || p.provider === 'upi_mock') {
+ const res = await refundUpiOrder(p.order_id, {
+ actor,
+ reason: options.reason || 'Customer requested refund',
+ manualReconciliation: Boolean(options.manualReconciliation),
+ externalRefundRef: options.externalRefundRef || options.providerRefundId,
+ evidenceRef: options.evidenceRef,
+ sessionAdmin: options.sessionAdmin
+ });
+ return { ok: true, ...res };
+ }
+
if (p.status !== 'paid') throw new HttpError(409, 'not_refundable', `Payment is ${p.status}`);
// Claim the refund atomically so two concurrent clicks cannot refund twice.
@@ -23,9 +39,7 @@ export async function refundPayment(paymentId, actor) {
if (p.provider === 'telegram_stars') {
await tg('refundStarPayment', { user_id: p.telegram_user_id, telegram_payment_charge_id: p.provider_txn_id });
} else {
- await providerByName(p.provider).refund({
- providerTxnId: p.provider_txn_id, providerPaymentId: p.provider_payment_id, amountPaise: Number(p.amount), refundRef: `rf_${p.id.slice(0, 8)}`
- });
+ await ticketProvider().refund(); // throws NOT_SUPPORTED_IN_APP: ticket refunds happen on SuperProfile
}
} catch (err) {
await db.query(`UPDATE payments SET failure_reason = NULL WHERE id = $1 AND failure_reason = 'refund_in_progress'`, [p.id]);
diff --git a/lib/services/safety.js b/lib/services/safety.js
new file mode 100644
index 0000000..ecf9339
--- /dev/null
+++ b/lib/services/safety.js
@@ -0,0 +1,150 @@
+// lib/services/safety.js - Trust & Safety: incident reporting, attendee blocking, and moderation integrity.
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+import { logger } from '../logger.js';
+
+export const REPORT_CATEGORIES = [
+ 'harassment',
+ 'fraud_suspicious',
+ 'unwanted_contact',
+ 'safety_concern',
+ 'policy_violation',
+ 'other'
+];
+
+/**
+ * Submits a confidential safety report from an authenticated attendee.
+ */
+export async function submitSafetyReport({ userId, category, body, eventId = null, reportedUserId = null }) {
+ if (!REPORT_CATEGORIES.includes(category)) {
+ throw new HttpError(400, 'invalid_category', 'Invalid report category');
+ }
+ const trimmed = (body || '').trim();
+ if (trimmed.length < 10 || trimmed.length > 3000) {
+ throw new HttpError(400, 'validation', 'Report description must be between 10 and 3000 characters');
+ }
+
+ return await db.tx(async (c) => {
+ let checkedEventId = null;
+ if (eventId) {
+ const ev = (await c.query('SELECT id, title FROM events WHERE id = $1', [eventId])).rows[0];
+ if (!ev) throw new HttpError(404, 'event_not_found', 'Referenced event not found');
+ checkedEventId = ev.id;
+ }
+
+ let checkedReportedUserId = null;
+ if (reportedUserId) {
+ if (reportedUserId === userId) {
+ throw new HttpError(400, 'self_report', 'You cannot report yourself');
+ }
+ const target = (await c.query('SELECT id FROM users WHERE id = $1', [reportedUserId])).rows[0];
+ if (!target) throw new HttpError(404, 'user_not_found', 'Reported user not found');
+ checkedReportedUserId = target.id;
+ }
+
+ const { rows } = await c.query(
+ `INSERT INTO reports (user_id, category, body, event_id, reported_user_id, status)
+ VALUES ($1, $2, $3, $4, $5, 'new')
+ RETURNING id, status, created_at`,
+ [userId, category, trimmed, checkedEventId, checkedReportedUserId]
+ );
+
+ const report = rows[0];
+ logger.info('safety report submitted', { reportId: report.id, category, eventId: checkedEventId });
+ return report;
+ });
+}
+
+/**
+ * Lists safety reports submitted by the authenticated user only (IDOR isolation).
+ */
+export async function listUserReports(userId) {
+ const { rows } = await db.query(
+ `SELECT r.id, r.category, r.body, r.status, r.created_at, e.title AS event_title
+ FROM reports r
+ LEFT JOIN events e ON e.id = r.event_id
+ WHERE r.user_id = $1
+ ORDER BY r.created_at DESC LIMIT 50`,
+ [userId]
+ );
+ return rows;
+}
+
+/**
+ * Creates a directional block between blocker and blocked user.
+ */
+export async function blockUser({ blockerUserId, blockedUserId }) {
+ if (!blockedUserId) {
+ throw new HttpError(400, 'validation', 'Target user ID is required');
+ }
+ if (blockerUserId === blockedUserId) {
+ throw new HttpError(400, 'self_block', 'You cannot block yourself');
+ }
+
+ return await db.tx(async (c) => {
+ const target = (await c.query('SELECT id, alias FROM users WHERE id = $1', [blockedUserId])).rows[0];
+ if (!target) throw new HttpError(404, 'user_not_found', 'User not found');
+
+ await c.query(
+ `INSERT INTO user_blocks (blocker_user_id, blocked_user_id)
+ VALUES ($1, $2)
+ ON CONFLICT (blocker_user_id, blocked_user_id) DO NOTHING`,
+ [blockerUserId, target.id]
+ );
+
+ logger.info('user blocked', { blockerUserId, blockedUserId: target.id });
+ return { ok: true, blocked: true };
+ });
+}
+
+/**
+ * Removes a block between blocker and blocked user.
+ */
+export async function unblockUser({ blockerUserId, blockedUserId }) {
+ if (!blockedUserId) {
+ throw new HttpError(400, 'validation', 'Target user ID is required');
+ }
+
+ const { rowCount } = await db.query(
+ `DELETE FROM user_blocks WHERE blocker_user_id = $1 AND blocked_user_id = $2`,
+ [blockerUserId, blockedUserId]
+ );
+
+ logger.info('user unblocked', { blockerUserId, blockedUserId, existed: Boolean(rowCount) });
+ return { ok: true, unblocked: true };
+}
+
+/**
+ * Lists users blocked by the authenticated user.
+ */
+export async function listBlockedUsers(blockerUserId) {
+ const { rows } = await db.query(
+ `SELECT b.id, b.blocked_user_id, b.created_at, u.alias
+ FROM user_blocks b
+ JOIN users u ON u.id = b.blocked_user_id
+ WHERE b.blocker_user_id = $1
+ ORDER BY b.created_at DESC LIMIT 100`,
+ [blockerUserId]
+ );
+ return rows.map((r) => ({
+ id: r.id,
+ blockedUserId: r.blocked_user_id,
+ alias: r.alias || 'Anonymous User',
+ createdAt: r.created_at
+ }));
+}
+
+/**
+ * Checks whether userA has blocked userB or userB has blocked userA.
+ */
+export async function checkBlockConflict(userAId, userBId) {
+ if (!userAId || !userBId) return false;
+ const { rows } = await db.query(
+ `SELECT 1 FROM user_blocks
+ WHERE (blocker_user_id = $1 AND blocked_user_id = $2)
+ OR (blocker_user_id = $2 AND blocked_user_id = $1)
+ LIMIT 1`,
+ [userAId, userBId]
+ );
+ return Boolean(rows.length);
+}
diff --git a/lib/services/saved-events.js b/lib/services/saved-events.js
new file mode 100644
index 0000000..e1f0712
--- /dev/null
+++ b/lib/services/saved-events.js
@@ -0,0 +1,94 @@
+// lib/services/saved-events.js - Attendee bookmarked/saved events service.
+// Supports saving, unsaving, and listing events bookmarked by the signed-in user.
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+import { toPublicEvent, TIERS_SQL, SEAT_HOLDING_SQL } from './events.js';
+
+const SAVED_SELECT = `
+ SELECT e.*,
+ (SELECT COALESCE(sum(b.quantity), 0)::int FROM bookings b WHERE b.event_id = e.id AND ${SEAT_HOLDING_SQL}) AS seats_taken,
+ (SELECT m.url FROM media m WHERE m.id = e.cover_media_id AND m.authorized_by_owner AND m.visible) AS cover_url,
+ ${TIERS_SQL} AS tiers,
+ s.created_at AS saved_at
+ FROM saved_events s
+ JOIN events e ON e.id = s.event_id
+`;
+
+/**
+ * Save / bookmark an event for a user.
+ */
+export async function saveEvent(userId, eventId, c = db) {
+ if (!userId) throw new HttpError(401, 'unauthorized', 'Sign in required to save events');
+ if (!eventId || !/^[0-9a-f-]{36}$/i.test(eventId)) throw new HttpError(400, 'invalid_event', 'Invalid event ID');
+
+ const ev = await c.one(`SELECT id, status FROM events WHERE id = $1`, [eventId]);
+ if (!ev) throw new HttpError(404, 'not_found', 'Event not found');
+
+ const { rows } = await c.query(
+ `INSERT INTO saved_events (user_id, event_id)
+ VALUES ($1, $2)
+ ON CONFLICT (user_id, event_id) DO NOTHING
+ RETURNING id, created_at`,
+ [userId, eventId]
+ );
+
+ return { ok: true, saved: true, eventId, created: rows.length > 0 };
+}
+
+/**
+ * Unsave / remove bookmark for an event.
+ */
+export async function unsaveEvent(userId, eventId, c = db) {
+ if (!userId) throw new HttpError(401, 'unauthorized', 'Sign in required');
+ if (!eventId || !/^[0-9a-f-]{36}$/i.test(eventId)) throw new HttpError(400, 'invalid_event', 'Invalid event ID');
+
+ const r = await c.query(
+ `DELETE FROM saved_events WHERE user_id = $1 AND event_id = $2`,
+ [userId, eventId]
+ );
+
+ return { ok: true, saved: false, eventId, removed: r.rowCount > 0 };
+}
+
+/**
+ * Check if a single event is saved by a user.
+ */
+export async function isEventSaved(userId, eventId, c = db) {
+ if (!userId || !eventId) return false;
+ const row = await c.one(
+ `SELECT 1 FROM saved_events WHERE user_id = $1 AND event_id = $2 LIMIT 1`,
+ [userId, eventId]
+ );
+ return Boolean(row);
+}
+
+/**
+ * List all event IDs saved by a user (for fast badge/button rendering).
+ */
+export async function listSavedEventIds(userId, c = db) {
+ if (!userId) return [];
+ const { rows } = await c.query(
+ `SELECT event_id FROM saved_events WHERE user_id = $1 ORDER BY created_at DESC`,
+ [userId]
+ );
+ return rows.map((r) => r.event_id);
+}
+
+/**
+ * List full public representations of all events saved by a user.
+ */
+export async function listSavedEvents(userId, c = db) {
+ if (!userId) return [];
+ const { rows } = await c.query(
+ `${SAVED_SELECT}
+ WHERE s.user_id = $1 AND e.status IN ('published', 'cancelled')
+ ORDER BY s.created_at DESC`,
+ [userId]
+ );
+ return rows.map((r) => {
+ const pub = toPublicEvent(r);
+ pub.savedAt = r.saved_at ? new Date(r.saved_at).toISOString() : null;
+ pub.isSaved = true;
+ return pub;
+ });
+}
diff --git a/lib/services/superprofile.js b/lib/services/superprofile.js
index c256357..769f84f 100644
--- a/lib/services/superprofile.js
+++ b/lib/services/superprofile.js
@@ -6,7 +6,11 @@
// Expected JSON (map these fields in the Zapier/Pabbly "Webhook" step):
// { "event": "purchase" | "subscription_expired" | "purchase_abandoned",
// "id": "", required, idempotency key
-// "product": "", required except for abandons
+// "product": "", needed to match the order to an event or tier; a purchase without it is stored as an unmatched order
+// "product_id": "", optional; matched against events.superprofile_product_id first
+// "qty": 1, "ref": "", optional ticket quantity / ref carried from the site
+// "phone": "", optional, hashed immediately
+// event "refund" / "cancelled" reverse an earlier purchase of the same id.
// "email": "", optional, hashed immediately
// "amount": "499" | 499, optional, rupees
// "currency": "INR", "occurred_at": "" } optional
@@ -17,11 +21,7 @@ import { HttpError } from '../http.js';
import { audit } from '../audit.js';
import { z } from '../validate.js';
-export const SUPERPROFILE_SECRET_HEADER = 'x-webhook-secret';
-
-export function superprofileConfigured() {
- return env('SUPERPROFILE_WEBHOOK_SECRET').length >= 24;
-}
+export { SUPERPROFILE_SECRET_HEADER, superprofileConfigured } from '../payments/superprofile.js';
function hashKey() {
const s = env('SESSION_SECRET');
@@ -35,6 +35,13 @@ export function emailHash(email) {
return crypto.createHmac('sha256', hashKey()).update(e).digest('hex');
}
+/** Keyed hash of the last 10 digits, so +91 98xxx and 098xxx hash alike. */
+export function phoneHash(phone) {
+ const d = String(phone || '').replace(/\D/g, '');
+ if (d.length < 10) return null;
+ return crypto.createHmac('sha256', hashKey()).update(`phone:${d.slice(-10)}`).digest('hex');
+}
+
export function rupeesToPaise(v) {
if (v === undefined || v === null || v === '') return null;
const n = Number(String(v).replace(/[^0-9.]/g, ''));
@@ -42,14 +49,18 @@ export function rupeesToPaise(v) {
}
export const WebhookBody = z.object({
- event: z.enum(['purchase', 'subscription_expired', 'purchase_abandoned']),
+ event: z.enum(['purchase', 'subscription_expired', 'purchase_abandoned', 'refund', 'cancelled']),
id: z.union([z.string(), z.number()]).transform((v) => String(v).trim()).refine((v) => v.length >= 1 && v.length <= 200, 'id required'),
product: z.union([z.string(), z.number()]).optional().transform((v) => (v === undefined ? undefined : String(v).trim().slice(0, 200) || undefined)),
+ product_id: z.union([z.string(), z.number()]).optional().transform((v) => (v === undefined ? undefined : String(v).trim().slice(0, 200) || undefined)),
email: z.string().max(320).optional(),
+ phone: z.union([z.string().max(40), z.number()]).optional(),
+ qty: z.union([z.string().max(8), z.number()]).optional(),
+ ref: z.string().max(64).optional(),
amount: z.union([z.string().max(40), z.number()]).optional(),
currency: z.string().max(8).optional(),
occurred_at: z.string().max(64).optional()
-}).passthrough().refine((b) => b.event === 'purchase_abandoned' || Boolean(b.product), { message: 'product required', path: ['product'] });
+}).passthrough();
/** Apply one webhook. Idempotent on (event, id). Returns { result, tierMapped }. */
export async function applySuperprofileEvent(b) {
diff --git a/lib/services/ticketing.js b/lib/services/ticketing.js
index b488830..a45ba87 100644
--- a/lib/services/ticketing.js
+++ b/lib/services/ticketing.js
@@ -2,20 +2,18 @@
//
// Inventory is decided inside one transaction holding the event row lock (same lock order as
// services/bookings.js: events, then bookings), so concurrent bookings cannot oversell an event or
-// a tier. Free tiers confirm without any payment. Paid tiers need a configured provider
-// (payments/availability.js); otherwise they are refused — never "assumed paid". Approval only
-// moves a request forward; it never marks anything as paid.
+// a tier. Free tiers confirm without any payment. Paid tiers are bought on SuperProfile (GET
+// /checkout/:slug) and confirmed by a matched notification (services/orders.js) — never here, and
+// never "assumed paid". Approval only moves a request forward; it never marks anything as paid.
import { db } from '../db.js';
import { HttpError } from '../http.js';
import { z } from '../validate.js';
import { audit } from '../audit.js';
import { enqueue } from './notifications.js';
-import { seatsTaken, tierSeatsTaken, startCheckout, HOLD_MINUTES } from './bookings.js';
-import { ticketCheckoutProvider } from '../payments/availability.js';
-import { isOrganiser } from './organiser.js';
+import { seatsTaken, tierSeatsTaken } from './bookings.js';
+import { authorize } from './permissions.js';
+import { issueTicketsForBooking } from './tickets.js';
-/** How long an approved guest has to complete a paid checkout. */
-export const APPROVAL_HOLD_HOURS = 24;
const LIVE = ['pending_approval', 'pending_payment', 'confirmed', 'checked_in'];
export const TierBookingBody = z.object({
@@ -60,8 +58,8 @@ async function assertSeats(c, event, tier, qty, excludeBookingId = null) {
}
/**
- * Book (or request) a tier. Returns { bookingId, status, checkoutUrl? }.
- * status: confirmed (free), pending_approval (host approves), pending_payment (paid checkout).
+ * Book (or request) a free tier. Returns { bookingId, status }.
+ * status: confirmed (free) or pending_approval (host approves). Paid tiers are not booked here.
*/
export async function bookTier(user, eventId, body) {
if (!user.age_confirmed_21) throw new HttpError(403, 'age_required', 'Please confirm you are 21 or older');
@@ -70,6 +68,22 @@ export async function bookTier(user, eventId, body) {
if (!event || event.status !== 'published') throw new HttpError(404, 'event_not_found', 'This event is not available');
if (event.ticketing !== 'tiers') throw new HttpError(409, 'not_tiered', 'This event uses the standard booking button');
if (new Date(event.start_at) <= new Date()) throw new HttpError(409, 'event_started', 'This event has already started');
+ if (event.organiser_user_id) {
+ const isBlockedByOrg = (await c.query(
+ 'SELECT 1 FROM user_blocks WHERE blocker_user_id = $1 AND blocked_user_id = $2',
+ [event.organiser_user_id, user.id]
+ )).rowCount;
+ if (isBlockedByOrg) {
+ throw new HttpError(403, 'booking_unavailable', 'This booking is currently unavailable.');
+ }
+ const hasBlockedOrg = (await c.query(
+ 'SELECT 1 FROM user_blocks WHERE blocker_user_id = $1 AND blocked_user_id = $2',
+ [user.id, event.organiser_user_id]
+ )).rowCount;
+ if (hasBlockedOrg) {
+ throw new HttpError(403, 'booking_unavailable', 'You have blocked this event organiser. Unblock to book.');
+ }
+ }
const tier = (await c.query('SELECT * FROM ticket_types WHERE id = $1 AND event_id = $2 AND active', [body.ticketTypeId, eventId])).rows[0];
if (!tier) throw new HttpError(404, 'ticket_not_found', 'That ticket type is not available');
const qty = body.quantity;
@@ -82,9 +96,7 @@ export async function bookTier(user, eventId, body) {
if (pickups.length && !pickups.some((p) => p.id === body.pickupPointId)) {
throw new HttpError(400, 'validation', 'Choose a pickup point', { fields: [{ field: 'pickupPointId', message: 'Required' }] });
}
- const paid = tier.kind === 'paid';
- const provider = paid ? ticketCheckoutProvider() : null;
- if (paid && !provider) throw new HttpError(409, 'payment_unavailable', 'Online payment is not available for this ticket yet. Free tickets can still be booked.');
+ if (tier.kind === 'paid') throw new HttpError(409, 'paid_on_superprofile', 'Paid tickets are bought on SuperProfile. Use the Book Tickets button on the event page.');
const prior = (await c.query(
`SELECT * FROM bookings WHERE event_id = $1 AND user_id = $2 AND status IN ('pending_approval', 'pending_payment', 'confirmed', 'checked_in', 'declined')
@@ -110,30 +122,17 @@ export async function bookTier(user, eventId, body) {
await audit(`user:${user.id}`, 'booking.request', b.id, { eventId, tier: tier.id, qty }, c);
return { booking: b, notificationIds: nid ? [nid] : [] };
}
- if (!paid) {
- const b = (await c.query(
- `INSERT INTO bookings (event_id, user_id, ticket_type_id, quantity, answers, pickup_point_id, amount_paise, status, payment_mode, confirmed_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7, 'confirmed', 'free', now()) RETURNING *`, common)).rows[0];
- const nid = await enqueue(c, { kind: 'booking_confirmed', userId: user.id, bookingId: b.id, dedupeKey: `bk:${b.id}:confirmed` });
- await audit(`user:${user.id}`, 'booking.confirmed_free', b.id, { eventId, tier: tier.id, qty }, c);
- return { booking: b, notificationIds: [nid] };
- }
const b = (await c.query(
- `INSERT INTO bookings (event_id, user_id, ticket_type_id, quantity, answers, pickup_point_id, amount_paise, status, payment_mode, hold_expires_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7, 'pending_payment', 'provider', now() + make_interval(mins => $8)) RETURNING *`, [...common, HOLD_MINUTES])).rows[0];
- return { booking: b, event, provider };
+ `INSERT INTO bookings (event_id, user_id, ticket_type_id, quantity, answers, pickup_point_id, amount_paise, status, payment_mode, confirmed_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, 'confirmed', 'free', now()) RETURNING *`, common)).rows[0];
+ await issueTicketsForBooking(b.id, c);
+ const nid = await enqueue(c, { kind: 'booking_confirmed', userId: user.id, bookingId: b.id, dedupeKey: `bk:${b.id}:confirmed` });
+ await audit(`user:${user.id}`, 'booking.confirmed_free', b.id, { eventId, tier: tier.id, qty }, c);
+ return { booking: b, notificationIds: [nid] };
});
const { booking } = placed;
- if (placed.existing) {
- const url = booking.status === 'pending_payment'
- ? (await db.one('SELECT checkout_url FROM payments WHERE id = $1', [booking.payment_id]))?.checkout_url || null : null;
- return { bookingId: booking.id, status: booking.status, existing: true, checkoutUrl: url };
- }
- if (placed.provider) {
- const checkoutUrl = await startCheckout(user.id, booking, placed.event, placed.provider);
- return { bookingId: booking.id, status: 'pending_payment', checkoutUrl, notificationIds: [] };
- }
+ if (placed.existing) return { bookingId: booking.id, status: booking.status, existing: true };
return { bookingId: booking.id, status: booking.status, notificationIds: placed.notificationIds };
}
@@ -144,25 +143,23 @@ async function notifyHost(c, event, booking) {
// ---------- organiser side ----------
-/** The event, if this user may manage it (its organiser, or an events admin). */
-export async function manageableEvent(user, eventId, c = db, { lock = false } = {}) {
+/** The event, if can(user, action) allows it (a member of its organiser org, or an events admin). */
+export async function manageableEvent(user, eventId, c = db, { lock = false, action = 'event.manage' } = {}) {
const e = (await c.query(`SELECT * FROM events WHERE id = $1${lock ? ' FOR UPDATE' : ''}`, [eventId])).rows[0];
if (!e) throw new HttpError(404, 'not_found', 'Event not found');
- if (e.organiser_user_id === user.id && await isOrganiser(user, c)) return e;
- const admin = (await c.query(`SELECT role FROM admin_users WHERE telegram_user_id = $1 AND active`, [user.telegram_user_id])).rows[0];
- if (admin && ['super_admin', 'event_manager'].includes(admin.role)) return e;
- throw new HttpError(404, 'not_found', 'Event not found');
+ await authorize(user, action, { event: e }, c, { notFound: 'Event not found' });
+ return e;
}
/**
- * Approve or decline a request. Approving a free ticket confirms it (if seats remain). Approving a
- * paid ticket only opens checkout — the booking is confirmed later by the verified payment webhook.
+ * Approve or decline a request. Approving a free ticket confirms it (if seats remain). A paid
+ * ticket cannot be approved: payment happens on SuperProfile, outside this approval step.
*/
export async function decideRequest(user, bookingId, decision) {
const r = await db.tx(async (c) => {
const ref = (await c.query('SELECT event_id FROM bookings WHERE id = $1', [bookingId])).rows[0];
if (!ref) throw new HttpError(404, 'not_found', 'Booking not found');
- const event = await manageableEvent(user, ref.event_id, c, { lock: true });
+ const event = await manageableEvent(user, ref.event_id, c, { lock: true, action: 'event.decide_bookings' });
const b = (await c.query('SELECT * FROM bookings WHERE id = $1 FOR UPDATE', [bookingId])).rows[0];
if (b.status !== 'pending_approval') throw new HttpError(409, 'not_pending', 'This request has already been decided');
if (decision === 'decline') {
@@ -176,49 +173,39 @@ export async function decideRequest(user, bookingId, decision) {
await assertSeats(c, event, tier, b.quantity, b.id);
if (tier.kind === 'free') {
await c.query(`UPDATE bookings SET status = 'confirmed', payment_mode = 'free', confirmed_at = now(), decided_at = now(), decided_by = $2 WHERE id = $1`, [b.id, user.id]);
+ await issueTicketsForBooking(b.id, c);
const nid = await enqueue(c, { kind: 'booking_confirmed', userId: b.user_id, bookingId: b.id, dedupeKey: `bk:${b.id}:confirmed` });
await audit(`user:${user.id}`, 'booking.approve', b.id, { eventId: event.id, confirmed: true }, c);
return { status: 'confirmed', notificationIds: [nid] };
}
- const provider = ticketCheckoutProvider();
- if (!provider) throw new HttpError(409, 'payment_unavailable', 'Online payment is not available yet, so a paid request cannot be approved. The request stays pending.');
- const held = (await c.query(
- `UPDATE bookings SET status = 'pending_payment', payment_mode = 'provider', hold_expires_at = now() + make_interval(hours => $3),
- decided_at = now(), decided_by = $2 WHERE id = $1 RETURNING *`, [b.id, user.id, APPROVAL_HOLD_HOURS])).rows[0];
- await audit(`user:${user.id}`, 'booking.approve', b.id, { eventId: event.id, awaitingPayment: true }, c);
- return { status: 'pending_payment', booking: held, event, provider };
+ // Paid tickets are bought on SuperProfile and cannot be gated on approval, so a paid request stays pending.
+ throw new HttpError(409, 'payment_unavailable', 'Paid tickets are bought on SuperProfile, so a paid request cannot be approved here. The request stays pending.');
});
- if (r.provider) {
- // If checkout cannot be created, the request returns to pending rather than being lost.
- await startCheckout(r.booking.user_id, r.booking, r.event, r.provider, {
- onFail: (id) => db.query(`UPDATE bookings SET status = 'pending_approval', hold_expires_at = NULL, decided_at = NULL, decided_by = NULL WHERE id = $1`, [id])
- });
- const nid = await db.tx((c) => enqueue(c, { kind: 'booking_approved_pay', userId: r.booking.user_id, bookingId: r.booking.id, dedupeKey: `bk:${r.booking.id}:approved` }));
- return { status: 'pending_payment', notificationIds: [nid] };
- }
return r;
}
/** Guests of an event for its organiser: answers, ticket, pickup and approval status. */
export async function listEventGuests(user, eventId) {
- const event = await manageableEvent(user, eventId);
+ const event = await manageableEvent(user, eventId, db, { action: 'event.view_guests' });
const { rows } = await db.query(
- `SELECT b.id, b.status, b.quantity, b.answers, b.pickup_point_id, b.payment_mode, b.created_at, b.confirmed_at, b.checked_in_at, b.decided_at,
- t.name AS ticket, t.kind, u.alias, p.status AS payment_status
+ `SELECT b.id, b.user_id, b.status, b.quantity, b.answers, b.pickup_point_id, b.payment_mode, b.created_at, b.confirmed_at, b.checked_in_at, b.decided_at,
+ t.name AS ticket, t.kind, u.alias, eo.status AS payment_status,
+ EXISTS(SELECT 1 FROM user_blocks ub WHERE ub.blocker_user_id = $2 AND ub.blocked_user_id = b.user_id) AS is_blocked
FROM bookings b JOIN users u ON u.id = b.user_id
LEFT JOIN ticket_types t ON t.id = b.ticket_type_id
- LEFT JOIN payments p ON p.id = b.payment_id
+ LEFT JOIN external_orders eo ON eo.matched_booking_id = b.id
WHERE b.event_id = $1 AND b.status IN ('pending_approval', 'pending_payment', 'confirmed', 'checked_in', 'declined')
- ORDER BY b.created_at`, [eventId]);
+ ORDER BY b.created_at`, [eventId, user.id]);
const questions = Array.isArray(event.booking_questions) ? event.booking_questions : [];
const pickups = Array.isArray(event.pickup_points) ? event.pickup_points : [];
return {
event: { id: event.id, title: event.title, status: event.status, startAt: event.start_at, requiresApproval: event.requires_approval, capacity: event.capacity },
questions: questions.map((q) => ({ id: q.id, label: q.label })),
guests: rows.map((r) => ({
- id: r.id, ref: r.id.slice(0, 8), alias: r.alias || 'Guest', status: r.status, ticket: r.ticket, kind: r.kind, quantity: r.quantity,
+ id: r.id, userId: r.user_id, ref: r.id.slice(0, 8), alias: r.alias || 'Guest', status: r.status, ticket: r.ticket, kind: r.kind, quantity: r.quantity,
paymentStatus: r.payment_mode === 'free' ? 'not_required' : r.payment_status || (r.kind === 'paid' ? 'unpaid' : 'not_required'),
answers: r.answers || {}, pickup: pickups.find((p) => p.id === r.pickup_point_id)?.name || null,
+ isBlocked: Boolean(r.is_blocked),
createdAt: r.created_at, decidedAt: r.decided_at, checkedInAt: r.checked_in_at
}))
};
diff --git a/lib/services/tickets.js b/lib/services/tickets.js
new file mode 100644
index 0000000..0cfe0cb
--- /dev/null
+++ b/lib/services/tickets.js
@@ -0,0 +1,607 @@
+// lib/services/tickets.js - Cryptographically secure, server-authoritative QR ticketing & check-in.
+import crypto from 'node:crypto';
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+import { audit } from '../audit.js';
+import { can } from './permissions.js';
+import { encodeQrMatrix } from '../upi/qr.js';
+
+export const TICKET_PREFIX = 'TK-';
+export const QR_PAYLOAD_VERSION = 'NLZ1';
+
+function getTicketSecret() {
+ const secret = process.env.TICKET_SECRET || process.env.SESSION_SECRET;
+ if (!secret || secret.length < 32) {
+ if (process.env.VERCEL || process.env.NODE_ENV === 'production' || process.env.VERCEL_ENV === 'production') {
+ throw new HttpError(503, 'not_configured', 'Ticket signing is not configured yet (TICKET_SECRET or SESSION_SECRET >= 32 chars required)');
+ }
+ return secret || 'nlz-ticket-signing-secret-local-dev-fallback';
+ }
+ return secret;
+}
+
+/**
+ * Computes an HMAC-SHA256 signature for a ticket code bound to an event.
+ */
+export function signTicketPayload(ticketCode, eventId) {
+ const secret = getTicketSecret();
+ return crypto.createHmac('sha256', secret)
+ .update(`${ticketCode}:${eventId}`)
+ .digest('hex');
+}
+
+/**
+ * Constant-time verification of a ticket QR signature.
+ */
+export function verifyTicketPayload(ticketCodeOrPayload, eventId, signature = null) {
+ if (!ticketCodeOrPayload || !eventId) return false;
+ let code = ticketCodeOrPayload;
+ let sig = signature;
+ if (!sig && typeof ticketCodeOrPayload === 'string' && ticketCodeOrPayload.startsWith('NLZ1:')) {
+ const parsed = parseQrPayload(ticketCodeOrPayload);
+ if (!parsed) return false;
+ code = parsed.ticketCode;
+ sig = parsed.signature;
+ }
+ if (!sig || typeof sig !== 'string') return false;
+ const expected = signTicketPayload(code, eventId);
+ if (expected.length !== sig.length) return false;
+ return crypto.timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(sig, 'hex'));
+}
+
+/**
+ * Generates the compact QR payload string. Does NOT leak any personal data or database IDs.
+ */
+export function generateQrPayload(ticketCode, eventId) {
+ const sig = signTicketPayload(ticketCode, eventId);
+ return `${QR_PAYLOAD_VERSION}:${ticketCode}:${sig}`;
+}
+
+/**
+ * Parses a QR payload string into version, ticketCode, and signature.
+ */
+export function parseQrPayload(payloadStr) {
+ if (typeof payloadStr !== 'string') return null;
+ const parts = payloadStr.trim().split(':');
+ if (parts.length !== 3 || parts[0] !== QR_PAYLOAD_VERSION) return null;
+ return { version: parts[0], ticketCode: parts[1], signature: parts[2] };
+}
+
+/**
+ * Generates an SVG string of the ticket QR code.
+ */
+export function generateTicketQrSvg(payload, { size = 260, margin = 3, darkColor = '#0b0f19', lightColor = '#ffffff' } = {}) {
+ const qr = encodeQrMatrix(payload);
+ const totalCells = qr.size + margin * 2;
+ const cellSize = (size / totalCells).toFixed(3);
+
+ let pathData = '';
+ for (let r = 0; r < qr.size; r++) {
+ for (let c = 0; c < qr.size; c++) {
+ if (qr.get(r, c)) {
+ const x = ((c + margin) * cellSize).toFixed(2);
+ const y = ((r + margin) * cellSize).toFixed(2);
+ pathData += `M${x},${y}h${cellSize}v${cellSize}h-${cellSize}z `;
+ }
+ }
+ }
+
+ return `
+
+
+ `;
+}
+
+/**
+ * Generates a high-entropy, cryptographically unguessable ticket code.
+ * Format: TK-XXXX-XXXX-XXXX (12 alphanumeric chars, 48+ bits of random entropy)
+ */
+export function generateTicketCode() {
+ const raw = crypto.randomBytes(6).toString('hex').toUpperCase();
+ return `${TICKET_PREFIX}${raw.slice(0, 4)}-${raw.slice(4, 8)}-${raw.slice(8, 12)}`;
+}
+
+/**
+ * Issues tickets for a confirmed booking. Idempotent — will not duplicate tickets if they already exist.
+ */
+export async function issueTicketsForBooking(bookingId, c = db) {
+ return c.tx ? c.tx(doIssue) : doIssue(c);
+
+ async function doIssue(client) {
+ const b = (await client.query(
+ `SELECT id, event_id, user_id, ticket_type_id, quantity, status FROM bookings WHERE id = $1 FOR UPDATE`,
+ [bookingId]
+ )).rows[0];
+ if (!b) throw new HttpError(404, 'not_found', 'Booking not found');
+ if (b.status !== 'confirmed' && b.status !== 'checked_in') {
+ throw new HttpError(409, 'not_eligible', 'Tickets can only be issued for confirmed bookings');
+ }
+
+ const existing = (await client.query(
+ `SELECT * FROM tickets WHERE booking_id = $1 ORDER BY ticket_number ASC`,
+ [bookingId]
+ )).rows;
+ if (existing.length > 0) return existing;
+
+ const tickets = [];
+ const qty = Math.max(1, Number(b.quantity) || 1);
+ for (let i = 1; i <= qty; i++) {
+ const code = generateTicketCode();
+ const hash = signTicketPayload(code, b.event_id);
+ const initialStatus = b.status === 'checked_in' ? 'checked_in' : 'valid';
+ const checkedInAt = initialStatus === 'checked_in' ? 'NOW()' : 'NULL';
+ const r = (await client.query(
+ `INSERT INTO tickets (booking_id, event_id, user_id, ticket_type_id, ticket_number, ticket_code, security_hash, status, checked_in_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, ${checkedInAt})
+ RETURNING *`,
+ [b.id, b.event_id, b.user_id, b.ticket_type_id, i, code, hash, initialStatus]
+ )).rows[0];
+ tickets.push(r);
+ }
+ return tickets;
+ }
+}
+
+/**
+ * Returns tickets for a booking with their QR payload and SVG.
+ */
+export async function getBookingTickets(bookingId, viewerUser = null, c = db) {
+ const b = (await c.query(`SELECT * FROM bookings WHERE id = $1`, [bookingId])).rows[0];
+ if (!b) throw new HttpError(404, 'not_found', 'Booking not found');
+
+ if (viewerUser) {
+ const isOwner = b.user_id === viewerUser.id;
+ if (!isOwner) {
+ const canView = await can(viewerUser, 'event.view_guests', { eventId: b.event_id }, c);
+ if (!canView) throw new HttpError(404, 'not_found', 'Booking not found');
+ }
+ }
+
+ let tickets = (await c.query(
+ `SELECT t.*, tt.name AS tier_name, tt.kind AS tier_kind
+ FROM tickets t
+ LEFT JOIN ticket_types tt ON tt.id = t.ticket_type_id
+ WHERE t.booking_id = $1
+ ORDER BY t.ticket_number ASC`,
+ [bookingId]
+ )).rows;
+
+ if (tickets.length === 0 && (b.status === 'confirmed' || b.status === 'checked_in')) {
+ await issueTicketsForBooking(bookingId, c);
+ tickets = (await c.query(
+ `SELECT t.*, tt.name AS tier_name, tt.kind AS tier_kind
+ FROM tickets t
+ LEFT JOIN ticket_types tt ON tt.id = t.ticket_type_id
+ WHERE t.booking_id = $1
+ ORDER BY t.ticket_number ASC`,
+ [bookingId]
+ )).rows;
+ }
+
+ return tickets.map((t) => {
+ const qrPayload = generateQrPayload(t.ticket_code, t.event_id);
+ return {
+ id: t.id,
+ ticketNumber: t.ticket_number,
+ ticketCode: t.ticket_code,
+ status: t.status,
+ checkedInAt: t.checked_in_at,
+ tierName: t.tier_name || 'Standard Admission',
+ qrPayload,
+ qrSvg: generateTicketQrSvg(qrPayload)
+ };
+ });
+}
+
+/**
+ * Server-authoritative ticket validation and check-in.
+ */
+export async function checkInTicket(actor, eventId, { ticketCode = null, qrPayload = null, method = 'camera_qr', overrideReason = null } = {}, c = db) {
+ if (!actor || !actor.id) throw new HttpError(401, 'unauthorized', 'Authentication required');
+
+ // Verify permission
+ const allowed = await can(actor, 'event.check_in', { eventId }, c);
+ if (!allowed) throw new HttpError(403, 'forbidden', 'You do not have permission to check in tickets for this event');
+
+ if (method === 'manual_override') {
+ const canOverride = await can(actor, 'event.manual_override', { eventId }, c);
+ if (!canOverride) throw new HttpError(403, 'forbidden', 'Only event managers or organisers can perform manual overrides');
+ if (!overrideReason || typeof overrideReason !== 'string' || overrideReason.trim().length < 4) {
+ throw new HttpError(400, 'validation', 'A specific override reason (at least 4 characters) is required');
+ }
+ }
+
+ let code = ticketCode ? ticketCode.trim().toUpperCase() : null;
+ let signature = null;
+
+ if (qrPayload) {
+ const parsed = parseQrPayload(qrPayload);
+ if (!parsed) {
+ await recordScanLog({
+ eventId,
+ ticketId: null,
+ bookingId: null,
+ scannedBy: actor.id,
+ result: 'invalid_format',
+ method,
+ payloadHash: hashPayload(qrPayload),
+ metadata: { error: 'malformed_qr' }
+ }, c);
+ throw new HttpError(400, 'invalid_qr', 'Malformed or invalid ticket QR format');
+ }
+ code = parsed.ticketCode.toUpperCase();
+ signature = parsed.signature;
+
+ const validSig = verifyTicketPayload(code, eventId, signature);
+ if (!validSig) {
+ await recordScanLog({
+ eventId,
+ ticketId: null,
+ bookingId: null,
+ scannedBy: actor.id,
+ result: 'invalid_signature',
+ method,
+ payloadHash: hashPayload(qrPayload),
+ metadata: { code, error: 'forged_or_cross_event' }
+ }, c);
+ throw new HttpError(400, 'invalid_ticket', 'Invalid or forged QR signature');
+ }
+ }
+
+ if (!code) {
+ throw new HttpError(400, 'validation', 'Ticket code or QR payload is required');
+ }
+
+ const payloadHash = hashPayload(qrPayload || code);
+
+ try {
+ return await db.tx(async (txClient) => {
+ const t = (await txClient.query(
+ `SELECT t.*, b.status AS booking_status, b.payment_mode, b.amount_paise,
+ u.alias AS attendee_alias, tt.name AS tier_name
+ FROM tickets t
+ JOIN bookings b ON b.id = t.booking_id
+ JOIN users u ON u.id = t.user_id
+ LEFT JOIN ticket_types tt ON tt.id = t.ticket_type_id
+ WHERE t.ticket_code = $1
+ FOR UPDATE OF t`,
+ [code]
+ )).rows[0];
+
+ if (!t) {
+ throw new HttpError(404, 'ticket_not_found', 'Ticket code not found', { code });
+ }
+
+ if (t.event_id !== eventId) {
+ throw new HttpError(400, 'event_mismatch', 'This ticket belongs to a different event', {
+ ticketId: t.id,
+ bookingId: t.booking_id,
+ code,
+ ticketEventId: t.event_id
+ });
+ }
+
+ if (t.status === 'checked_in') {
+ const prevStaff = t.checked_in_by ? (await txClient.query(`SELECT alias FROM users WHERE id = $1`, [t.checked_in_by])).rows[0]?.alias : 'Staff';
+ throw new HttpError(409, 'already_checked_in', 'This ticket has already been checked in', {
+ ticketId: t.id,
+ bookingId: t.booking_id,
+ firstCheckIn: {
+ checkedInAt: t.checked_in_at,
+ checkedInByAlias: prevStaff
+ },
+ checkedInAt: t.checked_in_at,
+ checkedInByAlias: prevStaff,
+ attendee: { alias: t.attendee_alias, tier: t.tier_name, ref: t.booking_id.slice(0, 8) }
+ });
+ }
+
+ if (t.status === 'revoked') {
+ if (method !== 'manual_override') {
+ throw new HttpError(409, 'ticket_revoked', 'This ticket has been revoked', {
+ ticketId: t.id,
+ bookingId: t.booking_id,
+ reason: t.revocation_reason
+ });
+ }
+ }
+
+ if (t.status === 'reissued') {
+ if (method !== 'manual_override') {
+ throw new HttpError(409, 'ticket_reissued', 'This ticket has been replaced by a reissued ticket', {
+ ticketId: t.id,
+ bookingId: t.booking_id,
+ newTicketId: t.reissued_to_ticket_id
+ });
+ }
+ }
+
+ if (t.status === 'cancelled' || t.booking_status === 'cancelled') {
+ throw new HttpError(409, 'ticket_cancelled', 'This ticket or booking has been cancelled', {
+ ticketId: t.id,
+ bookingId: t.booking_id,
+ code
+ });
+ }
+
+ if (t.booking_status === 'refunded') {
+ throw new HttpError(409, 'ticket_refunded', 'This booking was refunded. Ticket is invalid', {
+ ticketId: t.id,
+ bookingId: t.booking_id,
+ code
+ });
+ }
+
+ if (t.booking_status !== 'confirmed' && t.booking_status !== 'checked_in') {
+ if (method !== 'manual_override') {
+ throw new HttpError(409, 'not_eligible', 'Booking is not in a confirmed state', {
+ ticketId: t.id,
+ bookingId: t.booking_id,
+ bookingStatus: t.booking_status
+ });
+ }
+ }
+
+ // Perform atomic check-in
+ const now = new Date();
+ await txClient.query(
+ `UPDATE tickets
+ SET status = 'checked_in',
+ checked_in_at = $2,
+ checked_in_by = $3,
+ check_in_method = $4,
+ override_reason = $5,
+ updated_at = $2
+ WHERE id = $1`,
+ [t.id, now, actor.id, method, overrideReason || null]
+ );
+
+ // Update booking checked_in_at
+ await txClient.query(
+ `UPDATE bookings
+ SET status = 'checked_in',
+ checked_in_at = COALESCE(checked_in_at, $2),
+ updated_at = $2
+ WHERE id = $1`,
+ [t.booking_id, now]
+ );
+
+ const scanResult = method === 'manual_override' ? 'manual_override' : 'success';
+ await recordScanLog({
+ eventId,
+ ticketId: t.id,
+ bookingId: t.booking_id,
+ scannedBy: actor.id,
+ result: scanResult,
+ method,
+ overrideReason: overrideReason || null,
+ payloadHash,
+ metadata: { code, attendeeAlias: t.attendee_alias, tier: t.tier_name }
+ }, txClient);
+
+ const auditAction = method === 'manual_override' ? 'ticket.manual_override' : 'ticket.check_in';
+ await audit(`user:${actor.id}`, auditAction, t.id, {
+ eventId,
+ ticketCode: t.ticket_code,
+ method,
+ overrideReason: overrideReason || null
+ }, txClient);
+
+ return {
+ ok: true,
+ result: scanResult,
+ ticket: {
+ id: t.id,
+ ticketCode: t.ticket_code,
+ ticketNumber: t.ticket_number,
+ status: 'checked_in',
+ checkedInAt: now.toISOString(),
+ method
+ },
+ attendee: {
+ alias: t.attendee_alias || 'Guest',
+ ticketType: t.tier_name || 'Standard',
+ ref: t.booking_id.slice(0, 8).toUpperCase()
+ }
+ };
+ });
+ } catch (err) {
+ if (err instanceof HttpError && err.code) {
+ try {
+ await recordScanLog({
+ eventId,
+ ticketId: err.extra?.ticketId || null,
+ bookingId: err.extra?.bookingId || null,
+ scannedBy: actor.id,
+ result: err.code,
+ method,
+ overrideReason: overrideReason || null,
+ payloadHash,
+ metadata: { code, ...(err.extra || {}) }
+ }, c);
+ } catch {
+ // Logging error should not mask rejection
+ }
+ }
+ throw err;
+ }
+}
+
+/**
+ * Reissue a ticket with a fresh unguessable code, revoking the previous one immediately.
+ */
+export async function reissueTicket(actor, ticketId, reason = 'reissued_by_host', c = db) {
+ if (!actor || !actor.id) throw new HttpError(401, 'unauthorized', 'Authentication required');
+
+ return db.tx(async (txClient) => {
+ const old = (await txClient.query(`SELECT * FROM tickets WHERE id = $1 FOR UPDATE`, [ticketId])).rows[0];
+ if (!old) throw new HttpError(404, 'not_found', 'Ticket not found');
+
+ const allowed = await can(actor, 'event.reissue_ticket', { eventId: old.event_id }, txClient);
+ if (!allowed) throw new HttpError(403, 'forbidden', 'Permission denied to reissue tickets');
+
+ if (old.status === 'revoked' || old.status === 'cancelled') {
+ throw new HttpError(409, 'cannot_reissue', 'Cannot reissue a cancelled or revoked ticket');
+ }
+
+ const newCode = generateTicketCode();
+ const newHash = signTicketPayload(newCode, old.event_id);
+ const now = new Date();
+
+ const newTicket = (await txClient.query(
+ `INSERT INTO tickets (booking_id, event_id, user_id, ticket_type_id, ticket_number, ticket_code, security_hash, status, created_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, 'valid', $8)
+ RETURNING *`,
+ [old.booking_id, old.event_id, old.user_id, old.ticket_type_id, old.ticket_number, newCode, newHash, now]
+ )).rows[0];
+
+ await txClient.query(
+ `UPDATE tickets
+ SET status = 'reissued',
+ reissued_to_ticket_id = $2,
+ reissued_at = $3,
+ reissued_by = $4,
+ revocation_reason = $5,
+ updated_at = $3
+ WHERE id = $1`,
+ [old.id, newTicket.id, now, actor.id, reason]
+ );
+
+ await audit(`user:${actor.id}`, 'ticket.reissue', old.id, {
+ eventId: old.event_id,
+ oldTicketCode: old.ticket_code,
+ newTicketId: newTicket.id,
+ newTicketCode: newTicket.ticket_code,
+ reason
+ }, txClient);
+
+ const qrPayload = generateQrPayload(newTicket.ticket_code, newTicket.event_id);
+
+ return {
+ ok: true,
+ oldTicketId: old.id,
+ newTicket: {
+ id: newTicket.id,
+ ticketCode: newTicket.ticket_code,
+ ticketNumber: newTicket.ticket_number,
+ status: newTicket.status,
+ qrPayload,
+ qrSvg: generateTicketQrSvg(qrPayload)
+ }
+ };
+ });
+}
+
+/**
+ * Revoke a ticket with immediate effect.
+ */
+export async function revokeTicket(actor, ticketId, reason = 'revoked_by_host', c = db) {
+ if (!actor || !actor.id) throw new HttpError(401, 'unauthorized', 'Authentication required');
+
+ return db.tx(async (txClient) => {
+ const t = (await txClient.query(`SELECT * FROM tickets WHERE id = $1 FOR UPDATE`, [ticketId])).rows[0];
+ if (!t) throw new HttpError(404, 'not_found', 'Ticket not found');
+
+ const allowed = await can(actor, 'event.reissue_ticket', { eventId: t.event_id }, txClient);
+ if (!allowed) throw new HttpError(403, 'forbidden', 'Permission denied to revoke tickets');
+
+ const now = new Date();
+ await txClient.query(
+ `UPDATE tickets
+ SET status = 'revoked',
+ revoked_at = $2,
+ revoked_by = $3,
+ revocation_reason = $4,
+ updated_at = $2
+ WHERE id = $1`,
+ [t.id, now, actor.id, reason]
+ );
+
+ await audit(`user:${actor.id}`, 'ticket.revoke', t.id, {
+ eventId: t.event_id,
+ ticketCode: t.ticket_code,
+ reason
+ }, txClient);
+
+ return { ok: true, ticketId: t.id, status: 'revoked' };
+ });
+}
+
+/**
+ * Returns event attendance statistics: checked-in vs eligible, attendance rate.
+ */
+export async function getEventAttendance(eventId, c = db) {
+ const event = (await c.query(`SELECT capacity FROM events WHERE id = $1`, [eventId])).rows[0];
+ if (!event) throw new HttpError(404, 'not_found', 'Event not found');
+
+ const stats = (await c.query(
+ `SELECT
+ COUNT(*) FILTER (WHERE status IN ('valid', 'checked_in'))::int AS eligible_tickets,
+ COUNT(*) FILTER (WHERE status = 'checked_in')::int AS checked_in_tickets,
+ COUNT(*) FILTER (WHERE status = 'valid')::int AS remaining_tickets,
+ COUNT(*) FILTER (WHERE status = 'revoked')::int AS revoked_tickets,
+ COUNT(*) FILTER (WHERE status = 'cancelled')::int AS cancelled_tickets,
+ MAX(checked_in_at) AS last_check_in_at
+ FROM tickets
+ WHERE event_id = $1`,
+ [eventId]
+ )).rows[0];
+
+ const eligible = stats.eligible_tickets || 0;
+ const checkedIn = stats.checked_in_tickets || 0;
+ const attendancePct = eligible > 0 ? Math.round((checkedIn / eligible) * 100) : 0;
+
+ return {
+ capacity: event.capacity,
+ eligibleTickets: eligible,
+ checkedInTickets: checkedIn,
+ remainingTickets: Math.max(0, eligible - checkedIn),
+ revokedTickets: stats.revoked_tickets || 0,
+ cancelledTickets: stats.cancelled_tickets || 0,
+ attendanceRate: attendancePct,
+ lastCheckInAt: stats.last_check_in_at
+ };
+}
+
+/**
+ * Returns recent check-in scan activity logs.
+ */
+export async function listEventScans(eventId, limit = 50, c = db) {
+ const { rows } = await c.query(
+ `SELECT ts.id, ts.scan_result, ts.scan_method, ts.override_reason, ts.created_at,
+ u.alias AS staff_alias, t.ticket_code, b.id AS booking_id, bu.alias AS attendee_alias
+ FROM ticket_scans ts
+ JOIN users u ON u.id = ts.scanned_by
+ LEFT JOIN tickets t ON t.id = ts.ticket_id
+ LEFT JOIN bookings b ON b.id = ts.booking_id
+ LEFT JOIN users bu ON bu.id = b.user_id
+ WHERE ts.event_id = $1
+ ORDER BY ts.created_at DESC
+ LIMIT $2`,
+ [eventId, limit]
+ );
+
+ return rows.map((r) => ({
+ id: r.id,
+ result: r.scan_result,
+ method: r.scan_method,
+ overrideReason: r.override_reason,
+ createdAt: r.created_at,
+ staffAlias: r.staff_alias || 'Staff',
+ ticketCode: r.ticket_code ? `${r.ticket_code.slice(0, 7)}…` : null,
+ attendeeRef: r.booking_id ? r.booking_id.slice(0, 8).toUpperCase() : null,
+ attendeeAlias: r.attendee_alias || null
+ }));
+}
+
+function hashPayload(str) {
+ return crypto.createHash('sha256').update(String(str || '')).digest('hex');
+}
+
+async function recordScanLog({ eventId, ticketId, bookingId, scannedBy, result, method, overrideReason = null, payloadHash, metadata = {} }, c) {
+ await c.query(
+ `INSERT INTO ticket_scans (event_id, ticket_id, booking_id, scanned_by, scan_result, scan_method, override_reason, scanned_payload_hash, metadata)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
+ [eventId, ticketId, bookingId, scannedBy, result, method, overrideReason, payloadHash, JSON.stringify(metadata)]
+ );
+}
diff --git a/lib/services/upi-payments.js b/lib/services/upi-payments.js
new file mode 100644
index 0000000..8ae7a67
--- /dev/null
+++ b/lib/services/upi-payments.js
@@ -0,0 +1,1336 @@
+// lib/services/upi-payments.js - State machine, lifecycle, and order processing for UPI payments.
+// Supports PhonePe Payment Gateway and provider-neutral adapters with atomic PostgreSQL transactions.
+
+import crypto from 'node:crypto';
+import { db } from '../db.js';
+import { HttpError } from '../http.js';
+import { audit } from '../audit.js';
+import { upiCheckoutEnabled } from '../config.js';
+import { phonePeInstance, mockInstance, PhonePeAdapter, PaymentAdapterError } from '../upi/adapter.js';
+import { enqueue } from './notifications.js';
+import { removeFromChat } from './invites.js';
+import { seatsTaken, tierSeatsTaken } from './bookings.js';
+import { logger } from '../logger.js';
+import { issueTicketsForBooking } from './tickets.js';
+
+export const UPI_LEGAL_TRANSITIONS = {
+ created: ['pending', 'failed', 'expired', 'cancelled'],
+ pending: ['processing', 'succeeded', 'failed', 'expired', 'cancelled'],
+ processing: ['pending', 'succeeded', 'failed', 'expired', 'cancelled'],
+ succeeded: ['refund_pending', 'refunded', 'disputed'],
+ refund_pending: ['refunded', 'failed', 'succeeded'],
+ failed: [],
+ expired: [],
+ cancelled: [],
+ refunded: [],
+ disputed: ['refunded', 'succeeded']
+};
+
+export function isLegalTransition(fromStatus, toStatus) {
+ if (fromStatus === toStatus) return true;
+ const next = UPI_LEGAL_TRANSITIONS[fromStatus];
+ return Boolean(next && next.includes(toStatus));
+}
+
+export function newUpiOrderId() {
+ return `ORD-UPI-${Date.now().toString(36).toUpperCase()}-${crypto.randomBytes(3).toString('hex').toUpperCase()}`;
+}
+
+export function safeEqual(a, b) {
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
+ const bufA = Buffer.from(a);
+ const bufB = Buffer.from(b);
+ if (bufA.length !== bufB.length) return false;
+ return crypto.timingSafeEqual(bufA, bufB);
+}
+
+const PLACEHOLDER_PREFIX_RE = /^(manual|dummy|test|placeholder|none|null|n\/?a|fake|temp|refund|pending|unknown|sample|void|xxx)/i;
+const REPEATED_CHAR_RE = /^(.)\1{4,}$/;
+
+/**
+ * Validates an external refund transaction reference (e.g. bank UTR, PG refund ARN).
+ * Must be non-empty, between 6 and 120 chars, not a placeholder, and follow alphanumeric reference syntax.
+ */
+export function isValidExternalRefundRef(ref) {
+ if (!ref || typeof ref !== 'string') return false;
+ const trimmed = ref.trim();
+ if (trimmed.length < 6 || trimmed.length > 120) return false;
+ if (PLACEHOLDER_PREFIX_RE.test(trimmed)) return false;
+ if (REPEATED_CHAR_RE.test(trimmed)) return false;
+ if (/^(123456|12345678|123456789|abcdef|qwerty)/i.test(trimmed)) return false;
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.\-/:]{4,118}[A-Za-z0-9]$/.test(trimmed)) return false;
+ return true;
+}
+
+/**
+ * Validates documented reconciliation evidence reference (e.g. support/accounting ticket ID, bank statement ref).
+ * Must be non-empty, between 6 and 255 chars, and not a placeholder.
+ */
+export function isValidEvidenceRef(ref) {
+ if (!ref || typeof ref !== 'string') return false;
+ const trimmed = ref.trim();
+ if (trimmed.length < 6 || trimmed.length > 255) return false;
+ if (PLACEHOLDER_PREFIX_RE.test(trimmed)) return false;
+ if (REPEATED_CHAR_RE.test(trimmed)) return false;
+ return true;
+}
+
+/**
+ * Validates documented reconciliation reason.
+ * Must be non-empty, minimum 10 chars, maximum 500 chars, and not a placeholder.
+ */
+export function isValidReconciliationReason(reason) {
+ if (!reason || typeof reason !== 'string') return false;
+ const trimmed = reason.trim();
+ if (trimmed.length < 10 || trimmed.length > 500) return false;
+ if (/^(none|n\/?a|null|dummy|test|placeholder|sample|void|refund)$/i.test(trimmed)) return false;
+ if (REPEATED_CHAR_RE.test(trimmed)) return false;
+ return true;
+}
+
+/**
+ * Verifies that the actor has verified finance or super_admin authorization from an active DB row.
+ * Never trusts a caller-supplied string without server-side database identity verification.
+ */
+export async function verifyFinanceAuthorization(cOrDb, actor, sessionAdmin = null) {
+ if (sessionAdmin && sessionAdmin.id) {
+ const row = (await cOrDb.query(
+ `SELECT id, role, active FROM admin_users WHERE id = $1 AND active = true`,
+ [sessionAdmin.id]
+ )).rows[0];
+ if (row && ['super_admin', 'finance'].includes(row.role)) {
+ return { verified: true, adminId: row.id, role: row.role };
+ }
+ }
+
+ if (typeof actor === 'string') {
+ const m = actor.match(/^admin:([0-9a-f-]{36})(?::(\w+))?$/i);
+ if (m) {
+ const adminId = m[1];
+ const row = (await cOrDb.query(
+ `SELECT id, role, active FROM admin_users WHERE id = $1 AND active = true`,
+ [adminId]
+ )).rows[0];
+ if (row && ['super_admin', 'finance'].includes(row.role)) {
+ return { verified: true, adminId: row.id, role: row.role };
+ }
+ }
+ const mTg = actor.match(/^(?:admin:)?tg:(\d+)$/i) || actor.match(/^admin:(\d+)$/i);
+ if (mTg) {
+ const tgId = Number(mTg[1]);
+ const row = (await cOrDb.query(
+ `SELECT id, role, active FROM admin_users WHERE telegram_user_id = $1 AND active = true`,
+ [tgId]
+ )).rows[0];
+ if (row && ['super_admin', 'finance'].includes(row.role)) {
+ return { verified: true, adminId: row.id, role: row.role };
+ }
+ }
+ }
+
+ return { verified: false };
+}
+
+export function getAdapter() {
+ if (process.env.UPI_ADAPTER === 'mock' || (process.env.NODE_ENV === 'test' && !process.env.FORCE_PHONEPE)) {
+ return mockInstance;
+ }
+ return phonePeInstance;
+}
+
+/**
+ * Calculates currently held seats for an event across active, unexpired payment intents.
+ */
+export async function activePaymentHolds(c, eventId, excludeOrderId = null) {
+ const { rows } = await c.query(
+ `SELECT COALESCE(sum((p.raw_ref->>'qty')::int), 0)::int AS n
+ FROM payments p
+ WHERE (p.raw_ref->>'eventId')::uuid = $1
+ AND p.status IN ('created', 'pending', 'processing')
+ AND p.expires_at > now()
+ AND ($2::text IS NULL OR p.order_id <> $2)`,
+ [eventId, excludeOrderId]
+ );
+ return rows[0].n;
+}
+
+/**
+ * Calculates currently held seats for a ticket tier across active, unexpired payment intents.
+ */
+export async function activeTierPaymentHolds(c, ticketTypeId, excludeOrderId = null) {
+ const { rows } = await c.query(
+ `SELECT COALESCE(sum((p.raw_ref->>'qty')::int), 0)::int AS n
+ FROM payments p
+ WHERE (p.raw_ref->>'ticketTypeId')::uuid = $1
+ AND p.status IN ('created', 'pending', 'processing')
+ AND p.expires_at > now()
+ AND ($2::text IS NULL OR p.order_id <> $2)`,
+ [ticketTypeId, excludeOrderId]
+ );
+ return rows[0].n;
+}
+
+/**
+ * UPI/PhonePe checkout does not exist unless UPI_CHECKOUT_ENABLED=true (404, as for an unknown route).
+ * ENABLE_LIVE_PAYMENTS does not open it. Refunds of already-captured payments are deliberately not gated.
+ */
+export function assertUpiCheckoutEnabled() {
+ if (!upiCheckoutEnabled()) throw new HttpError(404, 'not_found', 'Not found');
+}
+
+/**
+ * Creates an internal payment intent, reserves inventory check, and returns deep links + dynamic QR.
+ */
+export async function createUpiPaymentIntent({
+ slug,
+ user = null,
+ ticketTypeId,
+ quantity = 1,
+ deviceType = 'desktop',
+ clientIp = '127.0.0.1'
+}) {
+ assertUpiCheckoutEnabled();
+ if (process.env.VERCEL_ENV === 'preview' && process.env.ALLOW_PREVIEW_PAID_CHECKOUT !== 'true') {
+ throw new HttpError(403, 'preview_paid_checkout_disabled', 'Paid checkout is disabled in Preview deployments.');
+ }
+
+ const qty = Math.min(Math.max(parseInt(quantity, 10) || 1, 1), 20);
+
+ return db.tx(async (c) => {
+ // 1. Fetch and lock event
+ const event = (await c.query(
+ `SELECT id, slug, title, status, start_at, capacity, checkout_mode FROM events
+ WHERE slug = $1 FOR UPDATE`,
+ [slug]
+ )).rows[0];
+
+ if (!event || event.status !== 'published') {
+ throw new HttpError(404, 'event_not_found', 'This event is not available for booking');
+ }
+ if (new Date(event.start_at) <= new Date()) {
+ throw new HttpError(409, 'event_started', 'This event has already started');
+ }
+
+ // 2. Fetch ticket tier
+ const tier = (await c.query(
+ `SELECT id, name, kind, price_paise, quantity, max_per_booking, active FROM ticket_types
+ WHERE id = $1 AND event_id = $2 AND active`,
+ [ticketTypeId, event.id]
+ )).rows[0];
+
+ if (!tier || tier.kind !== 'paid') {
+ throw new HttpError(404, 'ticket_not_found', 'That paid ticket type is not available');
+ }
+ if (qty > tier.max_per_booking) {
+ throw new HttpError(400, 'validation', `Up to ${tier.max_per_booking} per booking`);
+ }
+
+ // 3. Assert capacity including confirmed bookings AND active payment holds
+ const takenEventBookings = await seatsTaken(c, event.id);
+ const takenEventHolds = await activePaymentHolds(c, event.id);
+ const takenTierBookings = await tierSeatsTaken(c, tier.id);
+ const takenTierHolds = await activeTierPaymentHolds(c, tier.id);
+
+ const totalEventTaken = takenEventBookings + takenEventHolds;
+ const totalTierTaken = takenTierBookings + takenTierHolds;
+
+ if ((event.capacity - totalEventTaken < qty) || (tier.quantity - totalTierTaken < qty)) {
+ throw new HttpError(409, 'sold_out', `${tier.name} is sold out or held by active checkout sessions`);
+ }
+
+ // REV-02: Check existing active bookings during intent creation
+ const resolvedUserId = user?.id || user?.userId || null;
+ if (resolvedUserId) {
+ const existingBooking = (await c.query(
+ `SELECT id FROM bookings
+ WHERE event_id = $1 AND user_id = $2
+ AND status IN ('pending_approval', 'pending_payment', 'confirmed', 'checked_in')
+ LIMIT 1`,
+ [event.id, resolvedUserId]
+ )).rows[0];
+ if (existingBooking) {
+ throw new HttpError(409, 'already_booked', 'You already have an active booking for this event');
+ }
+ }
+
+ // 4. Generate Order ID & call Payment Adapter
+ const orderId = newUpiOrderId();
+ const guestToken = crypto.randomBytes(24).toString('base64url');
+ const amountPaise = tier.price_paise * qty;
+ const adapter = getAdapter();
+
+ const configuredMerchantId = adapter?.merchantId;
+ if (!configuredMerchantId || typeof configuredMerchantId !== 'string' || configuredMerchantId.trim() === '') {
+ throw new HttpError(500, 'merchant_config_missing', 'Payment merchant configuration is missing');
+ }
+
+ let intent;
+ try {
+ intent = await adapter.createPaymentIntent({
+ orderId,
+ amountPaise,
+ eventTitle: event.title,
+ userId: resolvedUserId,
+ deviceType
+ });
+ } catch (err) {
+ if (err.code === 'PAYLOAD_TOO_LARGE' || err.status === 400) {
+ throw new HttpError(400, 'payload_too_large', err.message);
+ }
+ throw err;
+ }
+
+ // 5. Insert payment row with guest claim token and trusted server-side merchant identity
+ const payment = (await c.query(
+ `INSERT INTO payments (
+ provider, provider_txn_id, order_id, merchant_id, purpose, user_id, amount, currency,
+ status, is_test, payment_method, device_type, upi_intent_url, upi_qr_data, expires_at, raw_ref
+ ) VALUES ($1, $2, $3, $4, 'ticket', $5, $6, 'INR', 'pending', $7, $8, $9, $10, $11, $12, $13)
+ RETURNING *`,
+ [
+ adapter instanceof PhonePeAdapter ? 'phonepe' : 'upi_mock',
+ intent.providerTxnId,
+ orderId,
+ configuredMerchantId.trim(),
+ resolvedUserId,
+ amountPaise,
+ Boolean(adapter.isSandbox),
+ deviceType === 'mobile' ? 'upi_intent' : 'upi_qr',
+ deviceType,
+ intent.upiIntentUrl,
+ intent.qrData,
+ intent.expiresAt,
+ JSON.stringify({ eventId: event.id, ticketTypeId: tier.id, qty, deviceType, guestToken })
+ ]
+ )).rows[0];
+
+ // 6. Record in immutable audit ledger
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, 'created', 'pending', $3, $4)`,
+ [
+ payment.id,
+ orderId,
+ resolvedUserId ? `user:${resolvedUserId}` : `guest:${clientIp}`,
+ JSON.stringify({ eventId: event.id, tierId: tier.id, qty, amountPaise, guestToken })
+ ]
+ );
+
+ return {
+ orderId,
+ status: 'pending',
+ amountPaise,
+ amountRupees: (amountPaise / 100).toFixed(2),
+ currency: 'INR',
+ eventTitle: event.title,
+ tierName: tier.name,
+ quantity: qty,
+ guestToken,
+ upiIntentUrl: intent.upiIntentUrl,
+ upiUri: intent.upiIntentUrl,
+ appIntents: intent.appIntents,
+ qrData: intent.qrData,
+ qrSvg: intent.qrSvg,
+ expiresInSeconds: intent.expiresInSeconds,
+ expiresAt: intent.expiresAt
+ };
+ });
+}
+
+/**
+ * Checks or polls the status of an existing UPI payment order.
+ */
+export async function getUpiPaymentStatus(orderId, { user = null, guestToken = null, checkGateway = false } = {}) {
+ assertUpiCheckoutEnabled();
+ const payment = await db.one(
+ `SELECT p.*, e.title AS event_title, e.slug AS event_slug, b.id AS booking_id
+ FROM payments p
+ LEFT JOIN events e ON e.id = (p.raw_ref->>'eventId')::uuid
+ LEFT JOIN bookings b ON b.id = p.booking_id
+ WHERE p.order_id = $1`,
+ [orderId]
+ );
+
+ if (!payment) {
+ throw new HttpError(404, 'order_not_found', 'Payment order not found');
+ }
+
+ // AUTH-01: Strict Authorization Check
+ let isStaff = false;
+ if (user) {
+ if (user.role === 'super_admin' || user.role === 'finance') {
+ isStaff = true;
+ } else if (user.telegram_user_id) {
+ const adminRow = await db.one('SELECT role FROM admin_users WHERE telegram_user_id = $1 AND active', [user.telegram_user_id]);
+ if (adminRow && ['super_admin', 'finance', 'event_manager', 'support'].includes(adminRow.role)) {
+ isStaff = true;
+ }
+ }
+ }
+
+ if (payment.user_id) {
+ if (!user) {
+ throw new HttpError(401, 'unauthorized', 'Authentication required to view payment status');
+ }
+ const currentUserId = user.id || user.userId;
+ if (payment.user_id !== currentUserId && !isStaff) {
+ throw new HttpError(403, 'forbidden', 'Access denied to this payment order');
+ }
+ } else {
+ // Guest checkout order: must have admin role OR valid guestToken matching raw_ref
+ if (!isStaff) {
+ const expectedToken = payment.raw_ref?.guestToken;
+ if (!expectedToken || !guestToken || !safeEqual(guestToken, expectedToken)) {
+ throw new HttpError(403, 'forbidden', 'Access denied to this payment order');
+ }
+ }
+ }
+
+ // Check expiry
+ if (['created', 'pending', 'processing'].includes(payment.status)) {
+ if (new Date(payment.expires_at) <= new Date()) {
+ await db.tx(async (c) => {
+ await c.query(`UPDATE payments SET status = 'expired' WHERE id = $1 AND status IN ('created', 'pending', 'processing')`, [payment.id]);
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'expired', 'system:expiry', '{}')`,
+ [payment.id, orderId, payment.status]
+ );
+ });
+ return { orderId, status: 'expired', message: 'Payment window expired' };
+ }
+
+ // Force gateway status check if requested
+ if (checkGateway) {
+ try {
+ const adapter = getAdapter();
+ const gatewayStatus = await adapter.getPaymentStatus(orderId, payment.provider_txn_id);
+ if (gatewayStatus.status === 'succeeded' && payment.status !== 'succeeded') {
+ return applySuccessfulUpiPayment({
+ orderId,
+ providerPaymentId: gatewayStatus.providerPaymentId,
+ verifiedAmountPaise: gatewayStatus.amountPaise,
+ currency: gatewayStatus.currency,
+ merchantId: gatewayStatus.merchantId,
+ actor: 'poll:gateway'
+ });
+ }
+ } catch (err) {
+ logger.warn('gateway status poll failed', { orderId, err: err.message });
+ }
+ }
+ }
+
+ return {
+ orderId: payment.order_id,
+ status: payment.status,
+ amountPaise: Number(payment.amount),
+ amountRupees: (Number(payment.amount) / 100).toFixed(2),
+ currency: payment.currency,
+ eventTitle: payment.event_title,
+ eventSlug: payment.event_slug,
+ bookingId: payment.booking_id || null,
+ expiresAt: payment.expires_at,
+ paidAt: payment.paid_at || null
+ };
+}
+
+/**
+ * Transitions a payment to succeeded and confirms the attendee booking atomically.
+ * Fail-closed validation strictly verifies amount, currency (INR only), and merchant identity
+ * against server-side configuration, stored payment row, and verified adapter output.
+ */
+export async function applySuccessfulUpiPayment({
+ orderId,
+ providerTxnId = null,
+ providerPaymentId = null,
+ verifiedAmountPaise = null,
+ currency = null,
+ merchantId = null,
+ actor = 'webhook:phonepe'
+}) {
+ return db.tx(async (c) => {
+ const payment = (await c.query(
+ `SELECT * FROM payments WHERE order_id = $1 FOR UPDATE`,
+ [orderId]
+ )).rows[0];
+
+ if (!payment) {
+ throw new HttpError(404, 'order_not_found', 'Payment not found');
+ }
+
+ if (payment.status === 'succeeded') {
+ return { orderId, status: 'succeeded', duplicate: true, bookingId: payment.booking_id };
+ }
+
+ if (!isLegalTransition(payment.status, 'succeeded')) {
+ throw new HttpError(409, 'invalid_transition', `Cannot transition payment from ${payment.status} to succeeded`);
+ }
+
+ // 1. Mandatory verified amount: reject missing, null, undefined, malformed or non-numeric verified amounts.
+ const expectedAmount = Number(payment.amount);
+ const hasValidNumericAmount = typeof verifiedAmountPaise === 'number' &&
+ Number.isSafeInteger(verifiedAmountPaise) &&
+ verifiedAmountPaise > 0;
+ const amountMatches = hasValidNumericAmount && verifiedAmountPaise === expectedAmount;
+
+ // 2. Mandatory currency verification: fail-closed on missing, empty, non-string, or non-INR
+ const hasValidCurrency = typeof currency === 'string' && currency.trim().length > 0;
+ const expectedCurrencyIsINR = typeof payment.currency === 'string' && payment.currency.trim() === 'INR';
+ const currencyMatches = hasValidCurrency && expectedCurrencyIsINR && currency.trim() === 'INR' && currency.trim() === payment.currency.trim();
+
+ // 3. Mandatory merchant identity verification: fail-closed against verified, stored, and server-configured merchant identity
+ const adapter = getAdapter();
+ const configuredMerchantId = adapter?.merchantId;
+ const storedMerchantId = payment.merchant_id;
+ const verifiedMerchantId = merchantId;
+
+ const hasVerifiedMerchantId = typeof verifiedMerchantId === 'string' && verifiedMerchantId.trim().length > 0;
+ const hasStoredMerchantId = typeof storedMerchantId === 'string' && storedMerchantId.trim().length > 0;
+ const hasConfiguredMerchantId = typeof configuredMerchantId === 'string' && configuredMerchantId.trim().length > 0;
+
+ const verifiedMatchesStored = hasVerifiedMerchantId && hasStoredMerchantId && safeEqual(verifiedMerchantId.trim(), storedMerchantId.trim());
+ const storedMatchesConfigured = hasStoredMerchantId && hasConfiguredMerchantId && safeEqual(storedMerchantId.trim(), configuredMerchantId.trim());
+ const merchantMatches = verifiedMatchesStored && storedMatchesConfigured;
+
+ if (!amountMatches || !currencyMatches || !merchantMatches) {
+ let disputeReason = 'amount_mismatch';
+ if (!hasValidNumericAmount) disputeReason = 'missing_or_invalid_verified_amount';
+ else if (!amountMatches) disputeReason = 'amount_mismatch';
+ else if (!hasValidCurrency) disputeReason = 'missing_currency';
+ else if (!currencyMatches) disputeReason = 'currency_mismatch';
+ else if (!hasVerifiedMerchantId) disputeReason = 'missing_verified_merchant_id';
+ else if (!hasStoredMerchantId) disputeReason = 'missing_stored_merchant_id';
+ else if (!hasConfiguredMerchantId) disputeReason = 'missing_configured_merchant_id';
+ else if (!merchantMatches) disputeReason = 'merchant_mismatch';
+
+ logger.error('Payment verification failed in applySuccessfulUpiPayment', {
+ orderId,
+ expectedAmount,
+ verifiedAmountPaise,
+ currency,
+ expectedCurrency: payment.currency,
+ merchantId: verifiedMerchantId,
+ storedMerchantId,
+ configuredMerchantId,
+ disputeReason
+ });
+
+ let failureLabel = 'Verification mismatch';
+ if (disputeReason.includes('amount')) failureLabel = 'Amount mismatch';
+ else if (disputeReason.includes('currency')) failureLabel = 'Currency mismatch';
+ else if (disputeReason.includes('merchant')) failureLabel = 'Merchant mismatch';
+
+ await c.query(
+ `UPDATE payments SET
+ status = 'disputed',
+ failure_reason = 'Payment verification failed: ' || $3 || ' (' || $2 || ')',
+ webhook_verified_at = now()
+ WHERE id = $1`,
+ [payment.id, disputeReason, failureLabel]
+ );
+
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'disputed', $4, $5)`,
+ [
+ payment.id,
+ orderId,
+ payment.status,
+ actor,
+ JSON.stringify({
+ expectedPaise: expectedAmount,
+ verifiedPaise: verifiedAmountPaise,
+ currency,
+ expectedCurrency: payment.currency,
+ merchantId: verifiedMerchantId,
+ storedMerchantId,
+ configuredMerchantId,
+ reason: disputeReason
+ })
+ ]
+ );
+
+ return {
+ orderId,
+ status: 'disputed',
+ amountMismatch: true,
+ disputeReason,
+ message: `Payment verification failed: ${disputeReason}`
+ };
+ }
+
+ const refData = payment.raw_ref || {};
+ const eventId = refData.eventId;
+ const ticketTypeId = refData.ticketTypeId;
+ const qty = refData.qty || 1;
+
+ const event = (await c.query(`SELECT * FROM events WHERE id = $1 FOR UPDATE`, [eventId])).rows[0];
+ if (!event) throw new HttpError(404, 'event_not_found', 'Event not found');
+
+ // REV-02: Check existing active bookings inside locked confirmation transaction
+ if (payment.user_id) {
+ const existingActiveBooking = (await c.query(
+ `SELECT id FROM bookings
+ WHERE event_id = $1 AND user_id = $2
+ AND status IN ('pending_approval', 'pending_payment', 'confirmed', 'checked_in')
+ LIMIT 1 FOR UPDATE`,
+ [event.id, payment.user_id]
+ )).rows[0];
+
+ if (existingActiveBooking) {
+ logger.warn('Duplicate active booking detected during confirmation', {
+ orderId,
+ userId: payment.user_id,
+ eventId: event.id,
+ existingBookingId: existingActiveBooking.id
+ });
+
+ await c.query(
+ `UPDATE payments SET
+ status = 'refund_pending',
+ failure_reason = 'duplicate_booking',
+ provider_txn_id = COALESCE($2, provider_txn_id),
+ provider_payment_id = COALESCE($3, provider_payment_id),
+ paid_at = COALESCE(paid_at, now()),
+ webhook_verified_at = now()
+ WHERE id = $1`,
+ [payment.id, providerTxnId, providerPaymentId]
+ );
+
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'refund_pending', $4, $5)`,
+ [
+ payment.id,
+ orderId,
+ payment.status,
+ actor,
+ JSON.stringify({
+ reason: 'duplicate_booking',
+ existingBookingId: existingActiveBooking.id,
+ userId: payment.user_id,
+ eventId: event.id
+ })
+ ]
+ );
+
+ return {
+ orderId,
+ status: 'refund_pending',
+ duplicateBooking: true,
+ message: 'User already has an active booking for this event. Queued for refund.'
+ };
+ }
+ }
+
+ // CONCUR-01: Capacity re-check at confirmation
+ const taken = await seatsTaken(c, event.id);
+ if (event.capacity - taken < qty) {
+ logger.error('Capacity exceeded upon payment confirmation', {
+ orderId,
+ eventId: event.id,
+ capacity: event.capacity,
+ taken,
+ requestedQty: qty
+ });
+ await c.query(
+ `UPDATE payments SET
+ status = 'refund_pending',
+ failure_reason = 'capacity_exceeded',
+ provider_txn_id = COALESCE($2, provider_txn_id),
+ provider_payment_id = COALESCE($3, provider_payment_id),
+ paid_at = COALESCE(paid_at, now()),
+ webhook_verified_at = now()
+ WHERE id = $1`,
+ [payment.id, providerTxnId, providerPaymentId]
+ );
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'refund_pending', $4, $5)`,
+ [
+ payment.id,
+ orderId,
+ payment.status,
+ actor,
+ JSON.stringify({ reason: 'capacity_exceeded', capacity: event.capacity, seatsTaken: taken, requestedQty: qty })
+ ]
+ );
+ return {
+ orderId,
+ status: 'refund_pending',
+ overbooked: true,
+ message: 'Event sold out before payment confirmation. Queued for refund.'
+ };
+ }
+
+ if (ticketTypeId) {
+ const tier = (await c.query(`SELECT * FROM ticket_types WHERE id = $1 FOR UPDATE`, [ticketTypeId])).rows[0];
+ if (tier && tier.capacity) {
+ const tierTaken = await tierSeatsTaken(c, tier.id);
+ if (tier.capacity - tierTaken < qty) {
+ logger.error('Tier capacity exceeded upon payment confirmation', {
+ orderId,
+ ticketTypeId: tier.id,
+ capacity: tier.capacity,
+ tierTaken,
+ requestedQty: qty
+ });
+ await c.query(
+ `UPDATE payments SET
+ status = 'refund_pending',
+ failure_reason = 'tier_capacity_exceeded',
+ provider_txn_id = COALESCE($2, provider_txn_id),
+ provider_payment_id = COALESCE($3, provider_payment_id),
+ paid_at = COALESCE(paid_at, now()),
+ webhook_verified_at = now()
+ WHERE id = $1`,
+ [payment.id, providerTxnId, providerPaymentId]
+ );
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'refund_pending', $4, $5)`,
+ [
+ payment.id,
+ orderId,
+ payment.status,
+ actor,
+ JSON.stringify({ reason: 'tier_capacity_exceeded', capacity: tier.capacity, seatsTaken: tierTaken, requestedQty: qty })
+ ]
+ );
+ return {
+ orderId,
+ status: 'refund_pending',
+ overbooked: true,
+ message: 'Tier sold out before payment confirmation. Queued for refund.'
+ };
+ }
+ }
+ }
+
+ // DATA-01: Guest checkout handling - when payment.user_id is null, do NOT insert null into bookings table
+ if (!payment.user_id) {
+ await c.query(
+ `UPDATE payments SET
+ status = 'succeeded',
+ provider_txn_id = COALESCE($2, provider_txn_id),
+ provider_payment_id = COALESCE($3, provider_payment_id),
+ paid_at = now(),
+ webhook_verified_at = now()
+ WHERE id = $1`,
+ [payment.id, providerTxnId, providerPaymentId]
+ );
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'succeeded', $4, $5)`,
+ [
+ payment.id,
+ orderId,
+ payment.status,
+ actor,
+ JSON.stringify({ guestClaimRequired: true, providerPaymentId, providerTxnId })
+ ]
+ );
+ await audit(actor, 'payment.succeeded_upi_guest', payment.id, { orderId, amount: payment.amount }, c);
+
+ return {
+ orderId,
+ status: 'succeeded',
+ guestClaimRequired: true,
+ bookingId: null
+ };
+ }
+
+ // Create confirmed booking for authenticated user with defensive 23505 savepoint recovery (REV-02)
+ let booking;
+ try {
+ await c.query('SAVEPOINT sp_confirm_booking');
+ booking = (await c.query(
+ `INSERT INTO bookings (
+ event_id, user_id, ticket_type_id, quantity, status, amount_paise,
+ payment_mode, source, confirmed_at, payment_id
+ ) VALUES ($1, $2, $3, $4, 'confirmed', $5, 'provider', 'site', now(), $6)
+ RETURNING *`,
+ [event.id, payment.user_id, ticketTypeId, qty, payment.amount, payment.id]
+ )).rows[0];
+ await issueTicketsForBooking(booking.id, c);
+ await c.query('RELEASE SAVEPOINT sp_confirm_booking');
+ } catch (err) {
+ if (err.code === '23505') {
+ await c.query('ROLLBACK TO SAVEPOINT sp_confirm_booking');
+ logger.warn('Defensive 23505 recovery triggered in booking confirmation', { orderId, err: err.message });
+ await c.query(
+ `UPDATE payments SET
+ status = 'refund_pending',
+ failure_reason = 'duplicate_booking',
+ provider_txn_id = COALESCE($2, provider_txn_id),
+ provider_payment_id = COALESCE($3, provider_payment_id),
+ paid_at = COALESCE(paid_at, now()),
+ webhook_verified_at = now()
+ WHERE id = $1`,
+ [payment.id, providerTxnId, providerPaymentId]
+ );
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'refund_pending', $4, $5)`,
+ [
+ payment.id,
+ orderId,
+ payment.status,
+ actor,
+ JSON.stringify({ reason: 'duplicate_booking_constraint', sqlState: '23505' })
+ ]
+ );
+ return {
+ orderId,
+ status: 'refund_pending',
+ duplicateBooking: true,
+ message: 'Duplicate booking prevented by database constraint. Queued for refund.'
+ };
+ }
+ throw err;
+ }
+
+ // Update payment
+ await c.query(
+ `UPDATE payments SET
+ status = 'succeeded',
+ provider_txn_id = COALESCE($2, provider_txn_id),
+ provider_payment_id = COALESCE($3, provider_payment_id),
+ paid_at = now(),
+ webhook_verified_at = now(),
+ booking_id = $4
+ WHERE id = $1`,
+ [payment.id, providerTxnId, providerPaymentId, booking.id]
+ );
+
+ // Record audit
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'succeeded', $4, $5)`,
+ [
+ payment.id,
+ orderId,
+ payment.status,
+ actor,
+ JSON.stringify({ bookingId: booking.id, providerPaymentId, providerTxnId })
+ ]
+ );
+
+ // Enqueue confirmation notification
+ const nid = await enqueue(c, {
+ kind: 'booking_confirmed',
+ userId: payment.user_id,
+ bookingId: booking.id,
+ dedupeKey: `bk:${booking.id}:confirmed`
+ });
+
+ await audit(actor, 'payment.succeeded_upi', payment.id, { orderId, bookingId: booking.id, amount: payment.amount }, c);
+
+ return {
+ orderId,
+ status: 'succeeded',
+ bookingId: booking.id,
+ notificationId: nid
+ };
+ });
+}
+
+/**
+ * Claims a guest UPI booking once the user logs in.
+ */
+export async function claimUpiBooking({ orderId, guestToken, user }) {
+ assertUpiCheckoutEnabled();
+ const uid = user?.id || user?.userId;
+ if (!uid) {
+ throw new HttpError(401, 'unauthorized', 'Must be signed in to claim a booking');
+ }
+ if (!orderId || !guestToken) {
+ throw new HttpError(400, 'validation', 'orderId and guestToken are required');
+ }
+
+ return db.tx(async (c) => {
+ const payment = (await c.query(
+ `SELECT * FROM payments WHERE order_id = $1 FOR UPDATE`,
+ [orderId]
+ )).rows[0];
+
+ if (!payment) {
+ throw new HttpError(404, 'order_not_found', 'Payment not found');
+ }
+
+ if (payment.booking_id) {
+ if (payment.user_id === uid) {
+ return { orderId, status: 'succeeded', bookingId: payment.booking_id, duplicate: true };
+ }
+ throw new HttpError(409, 'already_claimed', 'This booking has already been claimed');
+ }
+
+ if (payment.status !== 'succeeded') {
+ throw new HttpError(400, 'payment_not_succeeded', `Payment is in status ${payment.status}, cannot claim`);
+ }
+
+ const expectedToken = payment.raw_ref?.guestToken;
+ if (!expectedToken || !safeEqual(guestToken, expectedToken)) {
+ throw new HttpError(403, 'invalid_token', 'Invalid guest claim token');
+ }
+
+ const refData = payment.raw_ref || {};
+ const eventId = refData.eventId;
+ const ticketTypeId = refData.ticketTypeId;
+ const qty = refData.qty || 1;
+
+ const event = (await c.query(`SELECT * FROM events WHERE id = $1 FOR UPDATE`, [eventId])).rows[0];
+ if (!event) throw new HttpError(404, 'event_not_found', 'Event not found');
+
+ // REV-02: Prevent duplicate active booking on guest claim
+ const existingActiveBooking = (await c.query(
+ `SELECT id FROM bookings
+ WHERE event_id = $1 AND user_id = $2
+ AND status IN ('pending_approval', 'pending_payment', 'confirmed', 'checked_in')
+ LIMIT 1 FOR UPDATE`,
+ [event.id, uid]
+ )).rows[0];
+
+ if (existingActiveBooking) {
+ throw new HttpError(409, 'already_booked', 'You already have an active booking for this event');
+ }
+
+ let booking;
+ try {
+ await c.query('SAVEPOINT sp_claim_booking');
+ booking = (await c.query(
+ `INSERT INTO bookings (
+ event_id, user_id, ticket_type_id, quantity, status, amount_paise,
+ payment_mode, source, confirmed_at, payment_id
+ ) VALUES ($1, $2, $3, $4, 'confirmed', $5, 'provider', 'site', now(), $6)
+ RETURNING *`,
+ [event.id, uid, ticketTypeId, qty, payment.amount, payment.id]
+ )).rows[0];
+ await issueTicketsForBooking(booking.id, c);
+ await c.query('RELEASE SAVEPOINT sp_claim_booking');
+ } catch (err) {
+ if (err.code === '23505') {
+ await c.query('ROLLBACK TO SAVEPOINT sp_claim_booking');
+ throw new HttpError(409, 'already_booked', 'You already have an active booking for this event');
+ }
+ throw err;
+ }
+
+ await c.query(
+ `UPDATE payments SET user_id = $2, booking_id = $3 WHERE id = $1`,
+ [payment.id, uid, booking.id]
+ );
+
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, $3, $4, $5)`,
+ [
+ payment.id,
+ orderId,
+ payment.status,
+ `user:${uid}`,
+ JSON.stringify({ action: 'guest_claimed', bookingId: booking.id })
+ ]
+ );
+
+ const nid = await enqueue(c, {
+ kind: 'booking_confirmed',
+ userId: uid,
+ bookingId: booking.id,
+ dedupeKey: `bk:${booking.id}:confirmed`
+ });
+
+ await audit(`user:${uid}`, 'payment.claimed_guest', payment.id, { orderId, bookingId: booking.id }, c);
+
+ return {
+ orderId,
+ status: 'succeeded',
+ bookingId: booking.id,
+ notificationId: nid,
+ claimed: true
+ };
+ });
+}
+
+/**
+ * Ingests, verifies, and processes incoming UPI provider webhooks.
+ */
+export async function processUpiWebhook({ headers, rawBody, clientIp }) {
+ assertUpiCheckoutEnabled();
+ const adapter = getAdapter();
+ const verified = adapter.verifyWebhook(headers, rawBody);
+
+ const orderId = verified.orderId;
+ const status = verified.status;
+
+ if (status === 'succeeded') {
+ try {
+ const res = await applySuccessfulUpiPayment({
+ orderId,
+ providerTxnId: verified.providerTxnId,
+ providerPaymentId: verified.providerPaymentId,
+ verifiedAmountPaise: verified.amountPaise,
+ merchantId: verified.merchantId,
+ currency: verified.currency,
+ actor: `webhook:${verified.provider}`
+ });
+ if (res.status === 'disputed') {
+ return { ok: false, error: res.disputeReason || 'amount_mismatch', orderId, message: res.message };
+ }
+ return {
+ ok: true,
+ result: res.duplicate
+ ? 'duplicate'
+ : (res.duplicateBooking
+ ? 'duplicate_booking'
+ : (res.overbooked ? 'overbooked' : 'confirmed')),
+ orderId,
+ bookingId: res.bookingId || null,
+ guestClaimRequired: res.guestClaimRequired || false
+ };
+ } catch (err) {
+ if (err.code === 'amount_mismatch' || err.status === 400) {
+ return { ok: false, error: 'amount_mismatch', orderId, message: err.message };
+ }
+ throw err;
+ }
+ }
+
+ // REV-03: Handle refund webhook confirmation
+ if (status === 'refunded') {
+ return db.tx(async (c) => {
+ const payment = (await c.query(`SELECT * FROM payments WHERE order_id = $1 FOR UPDATE`, [orderId])).rows[0];
+ if (!payment) return { ok: true, result: 'not_found', orderId };
+ if (payment.status === 'refunded') {
+ return { ok: true, result: 'duplicate', orderId };
+ }
+ const refundId = verified.providerPaymentId || verified.providerTxnId || payment.refund_ref || `RFND-${orderId}`;
+ await c.query(
+ `UPDATE payments SET status = 'refunded', refunded_at = now(), refund_ref = $2, failure_reason = NULL WHERE id = $1`,
+ [payment.id, refundId]
+ );
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'refunded', $4, $5)`,
+ [payment.id, orderId, payment.status, `webhook:${verified.provider}`, JSON.stringify(verified.raw || {})]
+ );
+ if (payment.booking_id) {
+ await c.query(`UPDATE bookings SET status = 'refunded', refunded_at = now() WHERE id = $1`, [payment.booking_id]);
+ await c.query(`UPDATE invite_links SET revoked_at = COALESCE(revoked_at, now()) WHERE booking_id = $1 AND used_at IS NULL`, [payment.booking_id]);
+ const joined = (await c.query(
+ `SELECT i.chat_id, u.telegram_user_id FROM invite_links i JOIN users u ON u.id = i.user_id
+ WHERE i.booking_id = $1 AND i.used_at IS NOT NULL AND i.revoked_at IS NULL LIMIT 1`,
+ [payment.booking_id]
+ )).rows[0];
+ if (joined) {
+ await removeFromChat(joined.chat_id, joined.telegram_user_id).catch(() => {});
+ await c.query(`UPDATE invite_links SET revoked_at = now() WHERE booking_id = $1 AND revoked_at IS NULL`, [payment.booking_id]);
+ }
+ await enqueue(c, {
+ kind: 'booking_refunded',
+ userId: payment.user_id,
+ bookingId: payment.booking_id,
+ dedupeKey: `bk:${payment.booking_id}:refunded`
+ });
+ }
+ return { ok: true, result: 'refunded', orderId };
+ });
+ }
+
+ // Handle failure / cancellation
+ await db.tx(async (c) => {
+ const payment = (await c.query(`SELECT * FROM payments WHERE order_id = $1 FOR UPDATE`, [orderId])).rows[0];
+ if (!payment) return;
+ if (isLegalTransition(payment.status, status)) {
+ await c.query(
+ `UPDATE payments SET status = $2, failure_reason = $3, webhook_verified_at = now() WHERE id = $1`,
+ [payment.id, status, verified.rawStatus || 'Webhook reported failure']
+ );
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, $4, $5, $6)`,
+ [payment.id, orderId, payment.status, status, `webhook:${verified.provider}`, JSON.stringify(verified.raw || {})]
+ );
+ }
+ });
+
+ return { ok: true, result: status, orderId };
+}
+
+/**
+ * Initiates and executes a refund for a UPI payment.
+ * Permits refund processing for eligible succeeded and refund_pending payments.
+ * Provider initiation is strictly separated from refund completion.
+ * Manual reconciliation requires verified finance authorization, a non-placeholder external
+ * reference (e.g. bank UTR), and documented evidence reference recorded in the immutable audit ledger.
+ */
+export async function refundUpiOrder(orderId, {
+ actor = 'admin:finance',
+ reason = 'Customer requested refund',
+ manualReconciliation = false,
+ externalRefundRef = null,
+ evidenceRef = null,
+ providerRefundId = null,
+ sessionAdmin = null
+} = {}) {
+ const adapter = getAdapter();
+
+ const payment = await db.one(`SELECT * FROM payments WHERE order_id = $1`, [orderId]);
+ if (!payment) throw new HttpError(404, 'order_not_found', 'Payment not found');
+
+ // Idempotency: if already refunded, return duplicate success
+ if (payment.status === 'refunded') {
+ return {
+ orderId,
+ status: 'refunded',
+ refundId: payment.refund_ref || 'ALREADY_REFUNDED',
+ duplicate: true,
+ message: 'Payment has already been refunded'
+ };
+ }
+
+ if (!['succeeded', 'refund_pending'].includes(payment.status)) {
+ throw new HttpError(409, 'not_refundable', `Cannot refund payment in status ${payment.status}`);
+ }
+
+ // 1. Manual finance reconciliation option
+ if (manualReconciliation) {
+ const effectiveRef = externalRefundRef || providerRefundId;
+
+ if (!isValidExternalRefundRef(effectiveRef)) {
+ throw new HttpError(
+ 400,
+ 'invalid_external_refund_ref',
+ 'invalid_external_refund_ref: A valid external refund transaction reference (e.g. bank UTR, PG refund ARN) is required and cannot be empty or a placeholder'
+ );
+ }
+
+ if (!isValidEvidenceRef(evidenceRef)) {
+ throw new HttpError(
+ 400,
+ 'missing_evidence_ref',
+ 'missing_evidence_ref: Documented reconciliation evidence reference (e.g. support ticket ID, bank statement ref) is required and cannot be a placeholder'
+ );
+ }
+
+ if (!isValidReconciliationReason(reason)) {
+ throw new HttpError(
+ 400,
+ 'missing_reason',
+ 'missing_reason: A documented reconciliation reason (minimum 10 characters) is required and cannot be a placeholder'
+ );
+ }
+
+ return db.tx(async (c) => {
+ // Re-verify finance authorization against real database rows
+ const auth = await verifyFinanceAuthorization(c, actor, sessionAdmin);
+ if (!auth.verified) {
+ throw new HttpError(
+ 403,
+ 'unauthorized_finance_role',
+ 'unauthorized_finance_role: Manual reconciliation requires verified finance or super_admin authorization from an active admin user'
+ );
+ }
+
+ const p = (await c.query(`SELECT * FROM payments WHERE order_id = $1 FOR UPDATE`, [orderId])).rows[0];
+ if (!p) throw new HttpError(404, 'order_not_found', 'Payment not found');
+ if (p.status === 'refunded') {
+ return {
+ orderId,
+ status: 'refunded',
+ refundId: p.refund_ref || effectiveRef,
+ duplicate: true,
+ message: 'Payment has already been refunded'
+ };
+ }
+
+ const verifiedActor = `admin:${auth.adminId}:${auth.role}`;
+
+ await c.query(
+ `UPDATE payments SET
+ status = 'refunded',
+ refunded_at = now(),
+ refund_ref = $2,
+ reconciled = true,
+ reconciled_at = now(),
+ failure_reason = NULL,
+ raw_ref = jsonb_set(
+ COALESCE(raw_ref, '{}'::jsonb),
+ '{reconciliation}',
+ $3::jsonb
+ )
+ WHERE id = $1`,
+ [
+ p.id,
+ effectiveRef,
+ JSON.stringify({
+ manualReconciliation: true,
+ attestation: 'operator_attested',
+ bankVerified: false,
+ externalRefundRef: effectiveRef,
+ evidenceRef,
+ reason,
+ reconciledBy: verifiedActor,
+ reconciledAt: new Date().toISOString()
+ })
+ ]
+ );
+
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'refunded', $4, $5)`,
+ [
+ p.id,
+ orderId,
+ p.status,
+ verifiedActor,
+ JSON.stringify({
+ reconciliationType: 'manual_finance_reconciliation',
+ attestation: 'operator_attested',
+ bankVerified: false,
+ externalRefundRef: effectiveRef,
+ evidenceRef,
+ reason,
+ reconciledAt: new Date().toISOString(),
+ adminId: auth.adminId,
+ adminRole: auth.role
+ })
+ ]
+ );
+
+ if (p.booking_id) {
+ await c.query(`UPDATE bookings SET status = 'refunded', refunded_at = now() WHERE id = $1`, [p.booking_id]);
+ await c.query(`UPDATE invite_links SET revoked_at = COALESCE(revoked_at, now()) WHERE booking_id = $1 AND used_at IS NULL`, [p.booking_id]);
+ const joined = (await c.query(
+ `SELECT i.chat_id, u.telegram_user_id FROM invite_links i JOIN users u ON u.id = i.user_id
+ WHERE i.booking_id = $1 AND i.used_at IS NOT NULL AND i.revoked_at IS NULL LIMIT 1`,
+ [p.booking_id]
+ )).rows[0];
+ if (joined) {
+ await removeFromChat(joined.chat_id, joined.telegram_user_id).catch(() => {});
+ await c.query(`UPDATE invite_links SET revoked_at = now() WHERE booking_id = $1 AND revoked_at IS NULL`, [p.booking_id]);
+ }
+ await enqueue(c, {
+ kind: 'booking_refunded',
+ userId: p.user_id,
+ bookingId: p.booking_id,
+ dedupeKey: `bk:${p.booking_id}:refunded`
+ });
+ }
+
+ await audit(
+ verifiedActor,
+ 'payment.refunded_upi',
+ p.id,
+ {
+ orderId,
+ amount: p.amount,
+ reason,
+ externalRefundRef: effectiveRef,
+ evidenceRef,
+ manualReconciliation: true,
+ attestation: 'operator_attested',
+ bankVerified: false
+ },
+ c
+ );
+
+ return {
+ orderId,
+ status: 'refunded',
+ refundId: effectiveRef,
+ manualReconciliation: true,
+ attestation: 'operator_attested',
+ bankVerified: false
+ };
+ });
+ }
+
+ // 2. Gateway provider refund initiation (outside DB transaction)
+ let refundRes;
+ try {
+ refundRes = await adapter.initiateRefund({
+ orderId,
+ amountPaise: Number(payment.amount),
+ reason
+ });
+ } catch (err) {
+ logger.error('UPI provider refund call failed', { orderId, err: err.message });
+ await db.tx(async (c) => {
+ const p = (await c.query(`SELECT * FROM payments WHERE order_id = $1 FOR UPDATE`, [orderId])).rows[0];
+ if (p) {
+ await c.query(
+ `UPDATE payments SET
+ status = 'refund_pending',
+ failure_reason = 'refund_failed: ' || $2
+ WHERE id = $1`,
+ [p.id, err.message]
+ );
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, 'refund_pending', $4, $5)`,
+ [p.id, orderId, p.status, actor, JSON.stringify({ action: 'refund_initiation_failed', error: err.message, reason })]
+ );
+ }
+ });
+ throw new HttpError(502, 'refund_failed', `Payment gateway refund initiation failed: ${err.message}. Queued for retry.`);
+ }
+
+ // 3. Status boundary check: only mark 'refunded' if provider confirmed completion
+ return db.tx(async (c) => {
+ const p = (await c.query(`SELECT * FROM payments WHERE order_id = $1 FOR UPDATE`, [orderId])).rows[0];
+ if (!p) throw new HttpError(404, 'order_not_found', 'Payment not found');
+ if (p.status === 'refunded') {
+ return { orderId, status: 'refunded', refundId: p.refund_ref || refundRes.refundId, duplicate: true };
+ }
+
+ const isCompleted = refundRes.status === 'refunded';
+ const targetStatus = isCompleted ? 'refunded' : 'refund_pending';
+ const refundId = refundRes.refundId;
+
+ await c.query(
+ `UPDATE payments SET
+ status = $2::payment_status,
+ refunded_at = CASE WHEN $2::text = 'refunded' THEN now() ELSE refunded_at END,
+ refund_ref = $3,
+ failure_reason = NULL
+ WHERE id = $1`,
+ [p.id, targetStatus, refundId]
+ );
+
+ await c.query(
+ `INSERT INTO payment_audits (payment_id, order_id, from_status, to_status, actor, details)
+ VALUES ($1, $2, $3, $4, $5, $6)`,
+ [p.id, orderId, p.status, targetStatus, actor, JSON.stringify({ refundId, reason, providerStatus: refundRes.status })]
+ );
+
+ if (isCompleted && p.booking_id) {
+ await c.query(`UPDATE bookings SET status = 'refunded', refunded_at = now() WHERE id = $1`, [p.booking_id]);
+ await c.query(`UPDATE invite_links SET revoked_at = COALESCE(revoked_at, now()) WHERE booking_id = $1 AND used_at IS NULL`, [p.booking_id]);
+ const joined = (await c.query(
+ `SELECT i.chat_id, u.telegram_user_id FROM invite_links i JOIN users u ON u.id = i.user_id
+ WHERE i.booking_id = $1 AND i.used_at IS NOT NULL AND i.revoked_at IS NULL LIMIT 1`,
+ [p.booking_id]
+ )).rows[0];
+ if (joined) {
+ await removeFromChat(joined.chat_id, joined.telegram_user_id).catch(() => {});
+ await c.query(`UPDATE invite_links SET revoked_at = now() WHERE booking_id = $1 AND revoked_at IS NULL`, [p.booking_id]);
+ }
+ await enqueue(c, {
+ kind: 'booking_refunded',
+ userId: p.user_id,
+ bookingId: p.booking_id,
+ dedupeKey: `bk:${p.booking_id}:refunded`
+ });
+ }
+
+ await audit(actor, 'payment.refunded_upi', p.id, { orderId, amount: p.amount, reason, status: targetStatus, refundId }, c);
+
+ return {
+ orderId,
+ status: targetStatus,
+ refundId
+ };
+ });
+}
diff --git a/lib/services/users.js b/lib/services/users.js
index d5c203b..2e55081 100644
--- a/lib/services/users.js
+++ b/lib/services/users.js
@@ -1,6 +1,8 @@
// lib/services/users.js - Telegram-identity users. Identity always comes from a validated source.
+import crypto from 'node:crypto';
import { db } from '../db.js';
import { HttpError } from '../http.js';
+import { botUsername } from '../config.js';
function aliasFrom(tgUser) {
const name = [tgUser.first_name, tgUser.last_name].filter(Boolean).join(' ').trim() || tgUser.name || tgUser.username || tgUser.preferred_username;
@@ -24,6 +26,9 @@ export async function upsertTelegramUser(tgUser, { ageConfirmed = false, botStar
[tgUser.id, aliasFrom(tgUser), Boolean(ageConfirmed), Boolean(botStarted)]
);
const user = rows[0];
+ await client.query(
+ `INSERT INTO user_identities (user_id, provider, subject, verified_at) VALUES ($1, 'telegram', $2, now())
+ ON CONFLICT (provider, subject) DO NOTHING`, [user.id, String(user.telegram_user_id)]);
if (user.status !== 'active') throw new HttpError(403, 'account_restricted', 'This account cannot sign in. Contact support if you think this is a mistake.');
return user;
}
@@ -37,3 +42,109 @@ export async function userByTelegramId(telegramUserId, client = db) {
const { rows } = await client.query('SELECT * FROM users WHERE telegram_user_id = $1', [telegramUserId]);
return rows[0] || null;
}
+
+/**
+ * Creates a cryptographically random, single-use, 15-minute account linking token.
+ */
+export async function createAccountLinkToken(userId = null) {
+ const token = crypto.randomBytes(24).toString('base64url');
+ const expiresAt = new Date(Date.now() + 15 * 60 * 1000);
+ await db.query(
+ `INSERT INTO account_link_tokens (user_id, token, expires_at)
+ VALUES ($1, $2, $3)`,
+ [userId, token, expiresAt]
+ );
+ const bot = botUsername();
+ const linkUrl = bot ? `https://t.me/${bot}?start=link_${token}` : null;
+ return { token, linkUrl, expiresAt };
+}
+
+/**
+ * Redeems an account link token from Telegram, associating the Telegram account.
+ */
+export async function redeemAccountLinkToken(token, tgUser) {
+ if (!token || typeof token !== 'string') return { ok: false, reason: 'missing_token' };
+ return await db.tx(async (c) => {
+ const row = (await c.query(
+ `SELECT id, user_id, expires_at, used_at FROM account_link_tokens
+ WHERE token = $1 FOR UPDATE`, [token]
+ )).rows[0];
+ if (!row) return { ok: false, reason: 'not_found' };
+ if (row.used_at) return { ok: false, reason: 'already_used' };
+ if (new Date(row.expires_at) < new Date()) return { ok: false, reason: 'expired' };
+
+ // Resolve or upsert the Telegram user
+ const tgDbUser = await upsertTelegramUser(tgUser, { botStarted: true }, c);
+
+ // If token was issued for an existing web user, link identities
+ if (row.user_id && row.user_id !== tgDbUser.id) {
+ await c.query(
+ `INSERT INTO user_identities (user_id, provider, subject, verified_at)
+ VALUES ($1, 'telegram', $2, now())
+ ON CONFLICT (provider, subject) DO UPDATE SET user_id = EXCLUDED.user_id, verified_at = now()`,
+ [row.user_id, String(tgUser.id)]
+ );
+ // Transfer bot_started flag to the web user
+ await c.query(`UPDATE users SET bot_started = true WHERE id = $1`, [row.user_id]);
+ }
+
+ await c.query(
+ `UPDATE account_link_tokens SET used_at = now(), telegram_user_id = $2 WHERE id = $1`,
+ [row.id, tgUser.id]
+ );
+
+ return { ok: true, userId: row.user_id || tgDbUser.id, telegramUserId: tgUser.id };
+ });
+}
+
+/**
+ * Checks the status of an account link token.
+ */
+export async function getAccountLinkStatus(token) {
+ if (!token || typeof token !== 'string') return null;
+ const { rows } = await db.query(
+ `SELECT token, telegram_user_id, used_at, expires_at FROM account_link_tokens WHERE token = $1`,
+ [token]
+ );
+ if (!rows.length) return null;
+ const r = rows[0];
+ const isExpired = new Date(r.expires_at) < new Date();
+ return {
+ token: r.token,
+ linked: Boolean(r.used_at),
+ telegramUserId: r.telegram_user_id,
+ usedAt: r.used_at,
+ expired: isExpired && !r.used_at
+ };
+}
+
+/**
+ * Updates notification preferences and quiet hours for a user.
+ */
+export async function updateNotificationPreferences(userId, { remindersEnabled, quietHoursEnabled, quietHoursStart, quietHoursEnd }) {
+ const sets = [];
+ const vals = [userId];
+ let idx = 2;
+ if (remindersEnabled !== undefined) { sets.push(`reminders_enabled = $${idx++}`); vals.push(Boolean(remindersEnabled)); }
+ if (quietHoursEnabled !== undefined) { sets.push(`quiet_hours_enabled = $${idx++}`); vals.push(Boolean(quietHoursEnabled)); }
+ if (quietHoursStart !== undefined) { sets.push(`quiet_hours_start = $${idx++}`); vals.push(quietHoursStart); }
+ if (quietHoursEnd !== undefined) { sets.push(`quiet_hours_end = $${idx++}`); vals.push(quietHoursEnd); }
+ if (!sets.length) return getNotificationPreferences(userId);
+ const { rows } = await db.query(
+ `UPDATE users SET ${sets.join(', ')} WHERE id = $1
+ RETURNING reminders_enabled, quiet_hours_enabled, quiet_hours_start, quiet_hours_end`,
+ vals
+ );
+ return rows[0] || null;
+}
+
+/**
+ * Retrieves notification preferences and quiet hours for a user.
+ */
+export async function getNotificationPreferences(userId) {
+ const { rows } = await db.query(
+ `SELECT reminders_enabled, quiet_hours_enabled, quiet_hours_start, quiet_hours_end FROM users WHERE id = $1`,
+ [userId]
+ );
+ return rows[0] || null;
+}
diff --git a/lib/session.js b/lib/session.js
index 9d3dce6..13d3a5f 100644
--- a/lib/session.js
+++ b/lib/session.js
@@ -32,6 +32,7 @@ export function createSessionToken(userId, sessionId, now = Date.now()) {
/** Record a new server-side session and return its signed cookie value. */
export async function createSession(userId, q = db) {
+ secret(); // refuse (503) before writing a row we could never sign a cookie for
const { rows } = await q.query(
`INSERT INTO user_sessions (user_id, expires_at) VALUES ($1, now() + make_interval(secs => $2)) RETURNING id`,
[userId, SESSION_TTL_S]);
diff --git a/lib/telegram/auth.js b/lib/telegram/auth.js
index 5064c29..03271ac 100644
--- a/lib/telegram/auth.js
+++ b/lib/telegram/auth.js
@@ -60,9 +60,7 @@ export function validateInitData(initData, botToken, { now = Math.floor(Date.now
export function validateLoginWidget(data, botToken, { now = Math.floor(Date.now() / 1000), maxAge = INIT_DATA_MAX_AGE_S } = {}) {
if (!botToken) return { ok: false, reason: 'not configured' };
if (!data || typeof data !== 'object' || Array.isArray(data)) return { ok: false, reason: 'malformed' };
- const allowed = ['id', 'first_name', 'last_name', 'username', 'photo_url', 'auth_date'];
- const fields = Object.keys(data).filter((k) => k !== 'hash');
- if (fields.some((k) => !allowed.includes(k))) return { ok: false, reason: 'unexpected field' };
+ const fields = Object.keys(data).filter((k) => k !== 'hash' && data[k] !== undefined && data[k] !== null);
const dataCheckString = fields.sort().map((k) => `${k}=${data[k]}`).join('\n');
const secret = crypto.createHash('sha256').update(botToken).digest();
if (!hexEqual(data.hash, hmacHex(secret, dataCheckString))) return { ok: false, reason: 'bad hash' };
@@ -71,7 +69,12 @@ export function validateLoginWidget(data, botToken, { now = Math.floor(Date.now(
if (ageErr) return { ok: false, reason: ageErr };
const id = Number(data.id);
if (!Number.isSafeInteger(id) || id <= 0) return { ok: false, reason: 'bad user' };
- return { ok: true, user: { id, first_name: data.first_name, username: data.username }, authDate, hash: String(data.hash).toLowerCase() };
+ return {
+ ok: true,
+ user: { id, first_name: data.first_name, last_name: data.last_name, username: data.username, photo_url: data.photo_url },
+ authDate,
+ hash: String(data.hash).toLowerCase()
+ };
}
/**
diff --git a/lib/telegram/bot.js b/lib/telegram/bot.js
index b8d5bf9..b79945d 100644
--- a/lib/telegram/bot.js
+++ b/lib/telegram/bot.js
@@ -2,20 +2,25 @@
import { db } from '../db.js';
import { tg } from './api.js';
import { siteUrl, botUsername, env } from '../config.js';
-import { upsertTelegramUser } from '../services/users.js';
+import { upsertTelegramUser, redeemAccountLinkToken, updateNotificationPreferences, getNotificationPreferences } from '../services/users.js';
import { listPublicEvents, getPublicEventBySlug, listTiers } from '../services/events.js';
import { validatePreCheckout, handleSuccessfulPayment, createMembershipInvoice } from '../services/membership.js';
import { inviteForBooking, onChatMemberJoined } from '../services/invites.js';
import { deliverMany } from '../services/notifications.js';
+import { claimOrder, startClaimPrompt, isClaimPromptOpen, CLAIM_LIMIT_PER_HOUR } from '../services/claims.js';
+import { claimUpiBooking } from '../services/upi-payments.js';
+import { rateLimit } from '../ratelimit.js';
import { eventPath } from '../views/components.js';
import { logger } from '../logger.js';
export const COMMANDS = [
- ['start', 'Open StrangersMeetup'],
+ ['start', 'Open NIGHTLIFEZ'],
['events', 'Upcoming meetups and trips'],
['mybookings', 'Your bookings'],
+ ['claim', 'Claim a ticket you bought on SuperProfile'],
['membership', 'Membership plans'],
['report', 'Report a safety concern'],
+ ['quiet_hours', 'Notification quiet hours'],
['help', 'Help and support'],
['terms', 'Terms and refunds'],
['paysupport', 'Payment support']
@@ -31,7 +36,7 @@ function reply(chatId, text, buttons) {
});
}
-function appButton(text = 'Open StrangersMeetup', path = '/') {
+function appButton(text = 'Open NIGHTLIFEZ', path = '/') {
return [{ text, web_app: { url: `${siteUrl()}${path}` } }];
}
@@ -42,6 +47,40 @@ function supportLine() {
async function cmdStart(msg, user, param) {
const chat = msg.chat.id;
+ if (param?.startsWith('link_')) {
+ const token = param.slice(5);
+ const r = await redeemAccountLinkToken(token, msg.from);
+ if (!r.ok) {
+ return reply(chat, 'This account linking link is invalid or has expired. Please generate a new link from your NIGHTLIFEZ profile.');
+ }
+ return reply(chat,
+ 'Your NIGHTLIFEZ web account is now securely linked to Telegram! ✅\n\n' +
+ 'Booking passes and exclusive event invites will be sent directly to this chat.',
+ [appButton('Open NIGHTLIFEZ', '/me')]);
+ }
+ if (param?.startsWith('claim_upi_')) {
+ const parts = param.slice(10).split('_');
+ if (parts.length >= 2) {
+ const orderId = parts[0];
+ const guestToken = parts.slice(1).join('_');
+ try {
+ const claimed = await claimUpiBooking({ orderId, guestToken, user });
+ const bId = claimed.bookingId;
+ const b = bId ? await db.one('SELECT b.id, e.title FROM bookings b JOIN events e ON e.id = b.event_id WHERE b.id = $1', [bId]) : null;
+ const inv = bId ? await inviteForBooking(bId).catch(() => null) : null;
+ const buttons = [];
+ if (inv) buttons.push([{ text: 'Join the private group', url: inv.link }]);
+ if (bId) buttons.push([{ text: 'View booking pass', url: `${siteUrl()}/bookings/${bId}` }]);
+ return reply(chat,
+ `Booking claimed successfully! ✅\n${esc(b?.title || 'Event')} \n` +
+ `Booking ref: ${String(bId || '').slice(0, 8)}\n\n` +
+ (inv ? 'Your one-time private group invite is below:' : 'Your booking is confirmed.'),
+ buttons);
+ } catch (err) {
+ return reply(chat, `Could not claim booking: ${esc(err.message || 'invalid token or order')}`);
+ }
+ }
+ }
if (param?.startsWith('event_')) {
const e = await getPublicEventBySlug(param.slice(6));
if (e) {
@@ -64,16 +103,71 @@ async function cmdStart(msg, user, param) {
}
}
}
+ if (param === 'claim') return cmdClaim(msg, user, '');
if (param === 'alerts') {
await db.query('UPDATE users SET alerts_opt_in = true WHERE id = $1', [user.id]);
return reply(chat, 'Done — we will message you here when new events are announced. Send /stopalerts to opt out.');
}
+
+ // Operational recovery: check if user has confirmed bookings where invite was not yet delivered
+ const pendingInvites = await db.query(
+ `SELECT b.id, e.title, e.telegram_chat_id
+ FROM bookings b
+ JOIN events e ON e.id = b.event_id
+ WHERE b.user_id = $1
+ AND b.status IN ('confirmed', 'checked_in')
+ AND e.telegram_chat_id IS NOT NULL
+ AND COALESCE(e.end_at, e.start_at) > now() - interval '1 day'
+ AND NOT EXISTS (
+ SELECT 1 FROM invite_links i WHERE i.booking_id = b.id AND i.revoked_at IS NULL
+ )
+ LIMIT 1`,
+ [user.id]
+ );
+ if (pendingInvites.rows.length > 0) {
+ const pb = pendingInvites.rows[0];
+ try {
+ const inv = await inviteForBooking(pb.id);
+ if (inv) {
+ return reply(chat,
+ `Welcome to NIGHTLIFEZ !\n\nWe found a confirmed booking for ${esc(pb.title)} . Here is your private group invite (expires in 24 hours):`,
+ [[{ text: 'Join the private group', url: inv.link }], appButton('Open NIGHTLIFEZ')]);
+ }
+ } catch (err) {
+ logger.warn('recovery invite failed on /start', { reason: err.message });
+ }
+ }
+
return reply(chat,
- 'Welcome to StrangersMeetup — small hosted meetups, dinners, mixers and trips for adults 21+ across South India.\n\n' +
+ 'Welcome to NIGHTLIFEZ — curated weekend parties, nightlife, social mixers, dinner clubs and trips for adults 21+ across South India.\n\n' +
'Browse and book below. Your booking confirmations and private group invites will arrive in this chat.',
[appButton(), [{ text: 'Upcoming events', callback_data: 'events' }]]);
}
+const CLAIM_PROMPT = 'Send your SuperProfile order ID to claim your ticket. If you like, add the email you paid with after it, e.g. ABC12345 you@example.com.\n\nYou will get your booking confirmation and a one-time group invite here.';
+
+/** /claim [orderId [email]] — also the target of t.me/?start=claim. */
+async function cmdClaim(msg, user, arg) {
+ const [orderId, email] = arg.trim().split(/\s+/);
+ if (!orderId) {
+ await startClaimPrompt(user.id);
+ return reply(msg.chat.id, CLAIM_PROMPT);
+ }
+ return runClaim(msg.chat.id, user, orderId, email);
+}
+
+async function runClaim(chat, user, orderId, email) {
+ try {
+ const r = await claimOrder(user, orderId, email);
+ await reply(chat, `Order claimed ✅ ${esc(r.eventTitle)} . Your confirmation and group invite follow now.`);
+ await deliverMany(r.notificationIds);
+ } catch (err) {
+ if (err.status === 429) return reply(chat, `That was more than ${CLAIM_LIMIT_PER_HOUR} attempts in an hour. Please try again later, or ${supportLine()}`);
+ if (err.status === 403 || err.status === 404 || err.status === 409) return reply(chat, esc(err.message));
+ throw err;
+ }
+}
+
async function cmdEvents(chat) {
const events = await listPublicEvents({ limit: 8 });
if (!events.length) return reply(chat, 'No upcoming events are listed right now. Tap below to be told when new ones are announced.', [[{ text: 'Notify me', url: `https://t.me/${botUsername()}?start=alerts` }]]);
@@ -110,12 +204,72 @@ async function cmdMembership(chat, user) {
}
async function cmdReport(msg, user, text) {
+ const chat = msg.chat.id;
const body = text.trim();
if (!body) {
- return reply(msg.chat.id, 'Please send /report followed by what happened, when, and at which event. Example:\n/report At the Chennai dinner on 7 Nov, someone kept messaging me after I said no.\n\nIf you are in immediate danger, call 112.');
+ return reply(chat,
+ '⚠️ If you are in immediate danger, call 112 or local emergency services. \n' +
+ 'Women’s Helpline: 1091 / 181 \n\n' +
+ 'To report a safety issue to NIGHTLIFEZ moderators, reply with /report followed by what happened, when, and at which event.\n\n' +
+ 'Example:\n/report At the Indiranagar mixer on Friday, someone made unwelcome advances after being asked to stop.');
+ }
+
+ if (body.length < 10) {
+ return reply(chat, 'Please provide more details in your report (at least 10 characters) so our moderation team can investigate.\n\nEmergency helpline: 112.');
+ }
+
+ try {
+ await rateLimit(`tg_report:${user.id}`, 5, 3600);
+ } catch (err) {
+ if (err.status === 429) {
+ return reply(chat, 'You have submitted several reports recently. For urgent assistance, please call 112 or contact support.');
+ }
+ throw err;
+ }
+
+ await db.query(
+ `INSERT INTO reports (user_id, category, body, status) VALUES ($1, 'safety_concern', $2, 'new')`,
+ [user.id, body.slice(0, 3000)]
+ );
+ return reply(chat,
+ 'Thank you. Your report has been recorded and a NIGHTLIFEZ moderator will review it confidentially.\n\n' +
+ 'If you are in immediate danger or need urgent on-ground help, please call 112 .');
+}
+
+async function cmdQuietHours(msg, user, arg) {
+ const chat = msg.chat.id;
+ const clean = arg.trim().toLowerCase();
+ if (!clean) {
+ const prefs = await getNotificationPreferences(user.id);
+ const status = prefs?.quiet_hours_enabled ? 'ON' : 'OFF';
+ const start = prefs?.quiet_hours_start ? String(prefs.quiet_hours_start).slice(0, 5) : '23:00';
+ const end = prefs?.quiet_hours_end ? String(prefs.quiet_hours_end).slice(0, 5) : '08:00';
+ return reply(chat,
+ `Quiet Hours Settings \n\n` +
+ `Status: ${status} \n` +
+ `Window: ${esc(start)} to ${esc(end)} IST \n\n` +
+ `During quiet hours, non-urgent notifications (announcements and reminders) are held until morning. Urgent booking and refund confirmations are always delivered immediately.\n\n` +
+ `To change: send /quiet_hours on, /quiet_hours off, or /quiet_hours 23:00 08:00.`);
+ }
+
+ if (clean === 'on' || clean === 'enable') {
+ await updateNotificationPreferences(user.id, { quietHoursEnabled: true });
+ return reply(chat, 'Quiet hours enabled ✅ Non-urgent alerts will be muted from 23:00 to 08:00 IST.');
}
- await db.query('INSERT INTO reports (user_id, body) VALUES ($1, $2)', [user.id, body.slice(0, 4000)]);
- return reply(msg.chat.id, 'Thank you. Your report has been recorded and a moderator will review it. We keep reports confidential.');
+ if (clean === 'off' || clean === 'disable') {
+ await updateNotificationPreferences(user.id, { quietHoursEnabled: false });
+ return reply(chat, 'Quiet hours disabled. You will receive notifications as soon as they are generated.');
+ }
+
+ const times = clean.split(/\s+/);
+ if (times.length === 2 && /^\d{1,2}:\d{2}$/.test(times[0]) && /^\d{1,2}:\d{2}$/.test(times[1])) {
+ const start = times[0].padStart(5, '0');
+ const end = times[1].padStart(5, '0');
+ await updateNotificationPreferences(user.id, { quietHoursEnabled: true, quietHoursStart: start, quietHoursEnd: end });
+ return reply(chat, `Quiet hours updated ✅ Muting non-urgent alerts between ${esc(start)} and ${esc(end)} IST .`);
+ }
+
+ return reply(chat, 'Usage: /quiet_hours on, /quiet_hours off, or /quiet_hours 23:00 08:00.');
}
async function onMessage(msg) {
@@ -134,14 +288,20 @@ async function onMessage(msg) {
const text = msg.text || '';
const m = /^\/([a-z_]+)(?:@\w+)?(?:\s+([\s\S]*))?$/i.exec(text.trim());
- if (!m) return reply(msg.chat.id, 'Send /events to see what is coming up, or /help for support.');
+ if (!m) {
+ // After "claim" the bot waits a few minutes for an order ID.
+ if (text.trim() && await isClaimPromptOpen(user.id)) return cmdClaim(msg, user, text);
+ return reply(msg.chat.id, 'Send /events to see what is coming up, or /help for support.');
+ }
const [, cmd, arg = ''] = m;
switch (cmd.toLowerCase()) {
case 'start': return cmdStart(msg, user, arg.trim() || null);
case 'events': return cmdEvents(msg.chat.id);
case 'mybookings': return cmdMyBookings(msg.chat.id, user);
+ case 'claim': return cmdClaim(msg, user, arg);
case 'membership': return cmdMembership(msg.chat.id, user);
case 'report': return cmdReport(msg, user, arg);
+ case 'quiet_hours': return cmdQuietHours(msg, user, arg);
case 'stopalerts':
await db.query('UPDATE users SET alerts_opt_in = false WHERE id = $1', [user.id]);
return reply(msg.chat.id, 'You will no longer receive new-event alerts.');
@@ -153,8 +313,17 @@ async function onMessage(msg) {
case 'support':
default:
return reply(msg.chat.id,
- 'Help \n/events — upcoming events\n/mybookings — your bookings and invites\n/membership — plans\n/report — report a safety concern\n/paysupport — payment problems\n/terms — terms and refunds\n\n' +
- `To cancel or get a refund, reply here with your booking reference. ${supportLine()}`);
+ 'NIGHTLIFEZ Support & Community Care \n\n' +
+ '/events — upcoming curated nightlife, mixers & trips\n' +
+ '/mybookings — your tickets and private group invites\n' +
+ '/claim — claim a ticket you bought on SuperProfile or UPI\n' +
+ '/membership — plans and perks\n' +
+ '/quiet_hours — mute non-urgent night alerts\n' +
+ '/report — report a safety concern (reviewed by moderators)\n' +
+ '/paysupport — payment queries\n' +
+ '/terms — terms, billing and refunds\n\n' +
+ '🚨 Emergency Services: 112 | Women’s Helpline: 1091 / 181 \n\n' +
+ `To cancel or request a refund, reply with your booking ref. ${supportLine()}`);
}
}
@@ -170,7 +339,7 @@ async function onCallback(cq) {
const { invoiceLink, tier } = await createMembershipInvoice(user, data.slice(5));
return reply(chat, `Tap below to join ${esc(tier.name)} for ${tier.starsAmount} Stars / 30 days.`, [[{ text: `Pay ${tier.starsAmount} ⭐`, url: invoiceLink }]]);
} catch (err) {
- if (err.status === 403) return reply(chat, 'Please sign in on our website once and confirm you are 21+, then try again.', [appButton('Open StrangersMeetup', '/signin')]);
+ if (err.status === 403) return reply(chat, 'Please sign in on our website once and confirm you are 21+, then try again.', [appButton('Open NIGHTLIFEZ', '/signin')]);
return reply(chat, esc(err.status ? err.message : 'Membership is not available right now.'));
}
}
diff --git a/lib/upi/adapter.js b/lib/upi/adapter.js
new file mode 100644
index 0000000..7894a63
--- /dev/null
+++ b/lib/upi/adapter.js
@@ -0,0 +1,504 @@
+// lib/upi/adapter.js - Provider-neutral UPI payment adapter.
+// Supports PhonePe Payment Gateway (Primary) and Mock/Sandbox adapter with
+// mobile UPI intent deep-linking, app-specific intents (GPay, PhonePe, Paytm, CRED, BHIM),
+// and desktop dynamic QR generation.
+
+import crypto from 'node:crypto';
+import { safeEqual, HttpError } from '../http.js';
+import { env } from '../config.js';
+import { buildUpiUri, generateQrSvg, QrPayloadTooLargeError, MAX_QR_PAYLOAD_BYTES } from './qr.js';
+
+export const UPI_INTENT_TTL_SECONDS = 900; // 15 minutes
+
+export class PaymentAdapterError extends HttpError {
+ constructor(message, code = 'ADAPTER_ERROR', status = 502) {
+ super(status, code.toLowerCase(), message);
+ this.name = 'PaymentAdapterError';
+ }
+}
+
+export class WebhookSignatureError extends Error {
+ constructor(msg = 'Invalid webhook signature') {
+ super(msg);
+ this.name = 'WebhookSignatureError';
+ this.code = 'WEBHOOK_SIGNATURE';
+ this.status = 401;
+ }
+}
+
+/** Supported UPI client applications for deep-linking */
+export const SUPPORTED_UPI_APPS = [
+ { id: 'generic', name: 'Any UPI App', scheme: 'upi' },
+ { id: 'gpay', name: 'Google Pay', scheme: 'gpay' },
+ { id: 'phonepe', name: 'PhonePe', scheme: 'phonepe' },
+ { id: 'paytm', name: 'Paytm', scheme: 'paytmmp' },
+ { id: 'cred', name: 'CRED', scheme: 'credpay' },
+ { id: 'bhim', name: 'BHIM UPI', scheme: 'bhim' }
+];
+
+/**
+ * Builds app-specific deep links from an NPCI upi:// URI.
+ */
+export function buildAppIntents(baseUpiUri) {
+ const query = baseUpiUri.replace(/^upi:\/\/pay\?/, '');
+ return {
+ generic: baseUpiUri,
+ gpay: `gpay://upi/pay?${query}`,
+ phonepe: `phonepe://upi/pay?${query}`,
+ paytm: `paytmmp://upi/pay?${query}`,
+ cred: `credpay://upi/pay?${query}`,
+ bhim: `bhim://upi/pay?${query}`
+ };
+}
+
+// ---------------- PhonePe PG Implementation ----------------
+
+/**
+ * PhonePeAdapter: Standard Checkout v1 Integration (Sandbox / Testing Only).
+ *
+ * M4.3.4 Provider Contract Determination (Outcome B):
+ * Official PhonePe Standard Checkout API v1 payloads (status check responses and S2S webhooks)
+ * operate exclusively on Indian domestic UPI rails in paise, but do NOT return machine-verifiable
+ * ISO-4217 currency fields ('currency' is omitted from provider JSON). Furthermore, GET status responses
+ * are not cryptographically signed by PhonePe (relying solely on TLS transport security).
+ *
+ * Under the platform's zero-trust financial integrity policy, synthetic defaults (e.g. hardcoded
+ * 'INR' or configured merchantId fallback) are strictly prohibited. Native PhonePe responses lacking
+ * explicit currency fields fail closed into 'disputed' state with 0 bookings and 0 Telegram invites created.
+ *
+ * Consequently, PhonePe is formally classified as SANDBOX-ONLY / MOCK SUPPORTED.
+ * Live payments capability is BLOCKED (ENABLE_LIVE_PAYMENTS=false) pending migration to a zero-trust
+ * compatible payment provider with signed payloads and explicit ISO currency codes, or an upgraded PG SDK.
+ */
+export class PhonePeAdapter {
+ constructor(options = {}) {
+ this.merchantId = options.merchantId !== undefined
+ ? options.merchantId
+ : (env('PHONEPE_MERCHANT_ID') || 'PGTESTPAYUAT');
+ this.saltKey = options.saltKey || env('PHONEPE_SALT_KEY') || '099eb0cd-0252-4e2a-8aca-eb3c6bd470f1';
+ this.saltIndex = options.saltIndex || env('PHONEPE_SALT_INDEX') || '1';
+ this.hostUrl = options.hostUrl || env('PHONEPE_HOST_URL') || 'https://api-preprod.phonepe.com/apis/pg-sandbox';
+ this.merchantVpa = options.merchantVpa || env('PHONEPE_MERCHANT_VPA') || 'nightlifez@ybl';
+ this.isSandbox = typeof this.merchantId === 'string' && (this.merchantId.includes('TEST') || this.hostUrl.includes('sandbox'));
+ }
+
+ /**
+ * Generates PhonePe X-VERIFY header:
+ * SHA256(payload + endpoint + saltKey) + "###" + saltIndex
+ */
+ signRequest(bodyString, endpoint) {
+ const raw = `${bodyString}${endpoint}${this.saltKey}`;
+ const hash = crypto.createHash('sha256').update(raw).digest('hex');
+ return `${hash}###${this.saltIndex}`;
+ }
+
+ /**
+ * Verifies PhonePe X-VERIFY header on incoming webhooks:
+ * Official PhonePe S2S specification: SHA256(base64Response + saltKey) + "###" + saltIndex
+ */
+ verifyWebhookSignature(signatureHeader, base64Response, rawResponseBody = '') {
+ if (!signatureHeader || typeof signatureHeader !== 'string') return false;
+ const parts = signatureHeader.split('###');
+ if (parts.length !== 2) return false;
+ const [gotHash, index] = parts;
+ if (String(index) !== String(this.saltIndex)) return false;
+
+ // 1. Official PhonePe S2S formula: SHA256(base64Response + saltKey)
+ if (base64Response && typeof base64Response === 'string') {
+ const expectedHashOfficial = crypto.createHash('sha256').update(`${base64Response}${this.saltKey}`).digest('hex');
+ if (safeEqual(gotHash, expectedHashOfficial)) return true;
+ }
+
+ // 2. Fallback check for raw request body string
+ if (rawResponseBody && typeof rawResponseBody === 'string') {
+ const expectedHashRaw = crypto.createHash('sha256').update(`${rawResponseBody}${this.saltKey}`).digest('hex');
+ if (safeEqual(gotHash, expectedHashRaw)) return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Creates a payment intent (returns both deep links and dynamic QR).
+ */
+ async createPaymentIntent({
+ orderId,
+ amountPaise,
+ eventTitle = 'NIGHTLIFEZ Event',
+ userId,
+ userPhone = null,
+ deviceType = 'desktop',
+ returnUrl = ''
+ }) {
+ if (!orderId || !amountPaise || amountPaise <= 0) {
+ throw new PaymentAdapterError('Invalid order parameters for payment intent', 'INVALID_PARAMS', 400);
+ }
+
+ // 1. Build standardized NPCI UPI URI
+ const upiUri = buildUpiUri({
+ vpa: this.merchantVpa,
+ name: 'NIGHTLIFEZ Experiences',
+ amountPaise,
+ orderId,
+ note: eventTitle
+ });
+
+ const payloadBytes = Buffer.byteLength(upiUri, 'utf8');
+ if (payloadBytes > MAX_QR_PAYLOAD_BYTES) {
+ throw new PaymentAdapterError(
+ `Payment URI length (${payloadBytes} bytes) exceeds maximum supported QR capacity (${MAX_QR_PAYLOAD_BYTES} bytes)`,
+ 'PAYLOAD_TOO_LARGE',
+ 400
+ );
+ }
+
+ const appIntents = buildAppIntents(upiUri);
+ let qrSvg;
+ try {
+ qrSvg = generateQrSvg(upiUri, { size: 280 });
+ } catch (err) {
+ if (err instanceof QrPayloadTooLargeError) {
+ throw new PaymentAdapterError(err.message, 'PAYLOAD_TOO_LARGE', 400);
+ }
+ throw err;
+ }
+ const expiresAt = new Date(Date.now() + UPI_INTENT_TTL_SECONDS * 1000).toISOString();
+
+ return {
+ provider: 'phonepe',
+ providerTxnId: `TXN-${orderId}`,
+ orderId,
+ status: 'pending',
+ amountPaise,
+ currency: 'INR',
+ deviceType,
+ upiIntentUrl: upiUri,
+ appIntents,
+ qrData: upiUri,
+ qrSvg,
+ expiresInSeconds: UPI_INTENT_TTL_SECONDS,
+ expiresAt
+ };
+ }
+
+ /**
+ * Queries payment status directly from PhonePe gateway.
+ */
+ async getPaymentStatus(orderId, providerTxnId = null) {
+ const endpoint = `/pg/v1/status/${this.merchantId}/${orderId}`;
+ const xVerify = this.signRequest('', endpoint);
+
+ try {
+ const res = await fetch(`${this.hostUrl}${endpoint}`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-VERIFY': xVerify,
+ 'X-MERCHANT-ID': this.merchantId
+ }
+ });
+
+ if (!res.ok) {
+ throw new PaymentAdapterError(`PhonePe status check failed with HTTP ${res.status}`, 'GATEWAY_ERROR');
+ }
+
+ const json = await res.json();
+ const code = json.code;
+ const state = json.data?.state;
+
+ let normalizedStatus = 'pending';
+ if (code === 'PAYMENT_SUCCESS' || state === 'COMPLETED') {
+ normalizedStatus = 'succeeded';
+ } else if (code === 'PAYMENT_ERROR' || state === 'FAILED') {
+ normalizedStatus = 'failed';
+ } else if (code === 'PAYMENT_DECLINED') {
+ normalizedStatus = 'cancelled';
+ }
+
+ const data = json.data || {};
+ const statusMerchantId = (data.merchantId !== undefined && data.merchantId !== null)
+ ? (typeof data.merchantId === 'string' ? data.merchantId.trim() : data.merchantId)
+ : null;
+ const statusCurrency = (data.currency !== undefined && data.currency !== null)
+ ? (typeof data.currency === 'string' ? data.currency.trim() : data.currency)
+ : null;
+
+ return {
+ provider: 'phonepe',
+ merchantId: statusMerchantId,
+ orderId,
+ providerTxnId: data.transactionId || providerTxnId || `TXN-${orderId}`,
+ providerPaymentId: data.paymentInstrument?.utr || null,
+ status: normalizedStatus,
+ amountPaise: data.amount !== undefined ? data.amount : null,
+ currency: statusCurrency,
+ rawStatus: code,
+ message: json.message || ''
+ };
+ } catch (err) {
+ if (err instanceof PaymentAdapterError) throw err;
+ throw new PaymentAdapterError(`PhonePe status error: ${err.message}`, 'NETWORK_ERROR');
+ }
+ }
+
+ /**
+ * Verifies and decodes incoming PhonePe webhook payload.
+ */
+ verifyWebhook(headers, rawBody) {
+ const signature = headers['x-verify'] || headers['X-VERIFY'];
+ if (!signature) {
+ throw new WebhookSignatureError('Invalid PhonePe webhook signature: missing header');
+ }
+
+ let parsed;
+ try {
+ parsed = typeof rawBody === 'string' ? JSON.parse(rawBody) : rawBody;
+ } catch {
+ throw new HttpError(400, 'invalid_json', 'Invalid JSON body');
+ }
+
+ if (!parsed || !parsed.response || typeof parsed.response !== 'string') {
+ throw new HttpError(400, 'missing_response', 'Missing base64 response field');
+ }
+
+ const base64Response = parsed.response;
+ if (!this.verifyWebhookSignature(signature, base64Response, typeof rawBody === 'string' ? rawBody : '')) {
+ throw new WebhookSignatureError('Invalid PhonePe webhook signature');
+ }
+
+ let decoded;
+ try {
+ decoded = JSON.parse(Buffer.from(base64Response, 'base64').toString('utf8'));
+ } catch {
+ throw new HttpError(400, 'invalid_payload', 'Could not decode base64 response payload');
+ }
+
+ const data = decoded.data || {};
+ const code = decoded.code;
+ const state = data.state;
+
+ // Fail-closed merchant verification
+ if (!this.merchantId || typeof this.merchantId !== 'string' || this.merchantId.trim() === '') {
+ throw new WebhookSignatureError('PhonePe adapter merchant ID configuration is missing');
+ }
+ if (!data.merchantId || typeof data.merchantId !== 'string' || data.merchantId.trim() === '') {
+ throw new WebhookSignatureError('PhonePe webhook merchantId mismatch or missing: merchantId is missing');
+ }
+ if (data.merchantId.trim() !== this.merchantId.trim()) {
+ throw new WebhookSignatureError(
+ `PhonePe webhook merchantId mismatch or missing: expected '${this.merchantId}', received '${data.merchantId}'`
+ );
+ }
+
+ let normalizedStatus = 'pending';
+ if (code === 'PAYMENT_SUCCESS' || state === 'COMPLETED') {
+ normalizedStatus = 'succeeded';
+ } else if (code === 'PAYMENT_ERROR' || state === 'FAILED') {
+ normalizedStatus = 'failed';
+ } else if (code === 'PAYMENT_DECLINED') {
+ normalizedStatus = 'cancelled';
+ }
+
+ const statusCurrency = (data.currency !== undefined && data.currency !== null)
+ ? (typeof data.currency === 'string' ? data.currency.trim() : data.currency)
+ : null;
+
+ return {
+ provider: 'phonepe',
+ merchantId: data.merchantId.trim(),
+ orderId: data.merchantTransactionId,
+ providerTxnId: data.transactionId,
+ providerPaymentId: data.paymentInstrument?.utr || null,
+ amountPaise: data.amount,
+ currency: statusCurrency,
+ status: normalizedStatus,
+ rawStatus: code,
+ raw: decoded
+ };
+ }
+
+ /**
+ * Initiates a refund for a completed transaction via PhonePe.
+ */
+ async initiateRefund({ orderId, amountPaise, reason = 'Customer requested refund' }) {
+ const refundTxnId = `RFND-${orderId}-${Date.now().toString(36)}`;
+ const endpoint = '/pg/v1/refund';
+ const payload = {
+ merchantId: this.merchantId,
+ merchantTransactionId: refundTxnId,
+ originalTransactionId: orderId,
+ amount: amountPaise,
+ callbackUrl: `${env('PUBLIC_SITE_URL') || 'https://sm.test'}/api/payments/webhook/phonepe`
+ };
+
+ const bodyString = Buffer.from(JSON.stringify(payload)).toString('base64');
+ const xVerify = this.signRequest(bodyString, endpoint);
+
+ try {
+ const res = await fetch(`${this.hostUrl}${endpoint}`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-VERIFY': xVerify
+ },
+ body: JSON.stringify({ request: bodyString })
+ });
+
+ if (!res.ok) {
+ throw new PaymentAdapterError(`PhonePe refund call failed with HTTP ${res.status}`, 'REFUND_FAILED');
+ }
+
+ const json = await res.json();
+ return {
+ refundId: refundTxnId,
+ status: json.code === 'PAYMENT_SUCCESS' ? 'refunded' : 'refund_pending',
+ raw: json
+ };
+ } catch (err) {
+ if (err instanceof PaymentAdapterError) throw err;
+ throw new PaymentAdapterError(`PhonePe refund exception: ${err.message}`, 'REFUND_ERROR');
+ }
+ }
+}
+
+// ---------------- Mock / Test Sandbox Adapter ----------------
+
+export class MockUpiAdapter {
+ constructor(options = {}) {
+ this.merchantVpa = options.merchantVpa || 'nightlifez.test@ybl';
+ this.merchantId = options.merchantId !== undefined
+ ? options.merchantId
+ : (env('PHONEPE_MERCHANT_ID') || 'PGTESTPAYUAT');
+ this.simulatedResults = new Map();
+ }
+
+ setSimulatedStatus(orderId, status) {
+ this.simulatedResults.set(orderId, status);
+ }
+
+ async createPaymentIntent({ orderId, amountPaise, eventTitle = 'NIGHTLIFEZ Event', deviceType = 'desktop' }) {
+ const upiUri = buildUpiUri({
+ vpa: this.merchantVpa,
+ name: 'NIGHTLIFEZ Experiences (Test)',
+ amountPaise,
+ orderId,
+ note: eventTitle
+ });
+
+ const payloadBytes = Buffer.byteLength(upiUri, 'utf8');
+ if (payloadBytes > MAX_QR_PAYLOAD_BYTES) {
+ throw new PaymentAdapterError(
+ `Payment URI length (${payloadBytes} bytes) exceeds maximum supported QR capacity (${MAX_QR_PAYLOAD_BYTES} bytes)`,
+ 'PAYLOAD_TOO_LARGE',
+ 400
+ );
+ }
+
+ let qrSvg;
+ try {
+ qrSvg = generateQrSvg(upiUri, { size: 280 });
+ } catch (err) {
+ if (err instanceof QrPayloadTooLargeError) {
+ throw new PaymentAdapterError(err.message, 'PAYLOAD_TOO_LARGE', 400);
+ }
+ throw err;
+ }
+
+ return {
+ provider: 'upi_mock',
+ providerTxnId: `MOCK-${orderId}`,
+ orderId,
+ status: 'pending',
+ amountPaise,
+ currency: 'INR',
+ deviceType,
+ upiIntentUrl: upiUri,
+ appIntents: buildAppIntents(upiUri),
+ qrData: upiUri,
+ qrSvg,
+ expiresInSeconds: UPI_INTENT_TTL_SECONDS,
+ expiresAt: new Date(Date.now() + UPI_INTENT_TTL_SECONDS * 1000).toISOString()
+ };
+ }
+
+ async getPaymentStatus(orderId, providerTxnId = null) {
+ const sim = this.simulatedResults.get(orderId) || 'pending';
+ const status = typeof sim === 'string' ? sim : (sim?.status || 'pending');
+ const merchantId = typeof sim === 'object' && 'merchantId' in sim ? sim.merchantId : this.merchantId;
+ const currency = typeof sim === 'object' && 'currency' in sim ? sim.currency : 'INR';
+ const amountPaise = typeof sim === 'object' && 'amountPaise' in sim ? sim.amountPaise : 49900;
+ return {
+ provider: 'upi_mock',
+ merchantId,
+ orderId,
+ providerTxnId: providerTxnId || `MOCK-${orderId}`,
+ providerPaymentId: status === 'succeeded' ? `UTR${Date.now()}` : null,
+ status,
+ amountPaise,
+ currency,
+ rawStatus: status.toUpperCase(),
+ message: `Simulated mock payment ${status}`
+ };
+ }
+
+ verifyWebhook(headers, rawBody) {
+ const secret = headers['x-webhook-secret'] || headers['x-verify'];
+ if (secret !== 'test-upi-webhook-secret') {
+ throw new WebhookSignatureError('Invalid mock webhook secret');
+ }
+
+ const body = typeof rawBody === 'string' ? JSON.parse(rawBody) : rawBody;
+
+ // Fail-closed merchant verification
+ if (!this.merchantId || typeof this.merchantId !== 'string' || this.merchantId.trim() === '') {
+ throw new WebhookSignatureError('Mock adapter merchant ID configuration is missing');
+ }
+ if (!body.merchantId || typeof body.merchantId !== 'string' || body.merchantId.trim() === '') {
+ throw new WebhookSignatureError('Mock webhook merchantId is missing');
+ }
+ if (body.merchantId.trim() !== this.merchantId.trim()) {
+ throw new WebhookSignatureError(
+ `Mock webhook merchantId mismatch: expected '${this.merchantId}', got '${body.merchantId}'`
+ );
+ }
+
+ const statusCurrency = (body.currency !== undefined && body.currency !== null)
+ ? (typeof body.currency === 'string' ? body.currency.trim() : body.currency)
+ : null;
+
+ return {
+ provider: 'upi_mock',
+ merchantId: body.merchantId.trim(),
+ orderId: body.orderId,
+ providerTxnId: body.providerTxnId || `MOCK-${body.orderId}`,
+ providerPaymentId: body.utr || `UTR${Date.now()}`,
+ amountPaise: body.amountPaise,
+ currency: statusCurrency,
+ status: body.status || 'succeeded',
+ rawStatus: (body.status || 'succeeded').toUpperCase(),
+ raw: body
+ };
+ }
+
+ async initiateRefund({ orderId, amountPaise }) {
+ return {
+ refundId: `MOCK-RFND-${orderId}`,
+ status: 'refunded',
+ amountPaise
+ };
+ }
+}
+
+// ---------------- Factory ----------------
+
+const phonePeInstance = new PhonePeAdapter();
+const mockInstance = new MockUpiAdapter();
+
+export function getPaymentAdapter(providerName = process.env.UPI_PAYMENT_PROVIDER || 'phonepe') {
+ if (providerName === 'upi_mock' || process.env.NODE_ENV === 'test' && !process.env.FORCE_PHONEPE) {
+ return phonePeInstance; // PhonePe adapter handles both test and prod through configuration
+ }
+ return phonePeInstance;
+}
+
+export { phonePeInstance, mockInstance };
diff --git a/lib/upi/qr.js b/lib/upi/qr.js
new file mode 100644
index 0000000..1ee4fb0
--- /dev/null
+++ b/lib/upi/qr.js
@@ -0,0 +1,407 @@
+// lib/upi/qr.js - Zero-dependency, pure JavaScript QR Code (Model 2) SVG generator for UPI strings.
+// Generates standard scannable QR codes for NPCI upi:// payment URIs.
+// Fully compliant with ISO/IEC 18004:2015 specification (Versions 1 through 14, EC Level M).
+
+import { HttpError } from '../http.js';
+
+export class QrPayloadTooLargeError extends HttpError {
+ constructor(byteLength, maxCapacity) {
+ super(
+ 400,
+ 'payload_too_large',
+ `Payment URI length (${byteLength} bytes) exceeds maximum supported QR capacity (${maxCapacity} bytes)`
+ );
+ this.name = 'QrPayloadTooLargeError';
+ this.byteLength = byteLength;
+ this.maxCapacity = maxCapacity;
+ }
+}
+
+// Galois Field GF(256) math for Reed-Solomon error correction
+const EXP = new Uint8Array(512);
+const LOG = new Uint8Array(256);
+(function initGf() {
+ let x = 1;
+ for (let i = 0; i < 255; i++) {
+ EXP[i] = x;
+ EXP[i + 255] = x;
+ LOG[x] = i;
+ x = (x << 1) ^ (x & 128 ? 0x11d : 0);
+ }
+ LOG[0] = 0;
+})();
+
+function gfMul(x, y) {
+ return x === 0 || y === 0 ? 0 : EXP[LOG[x] + LOG[y]];
+}
+
+function rsGenerator(degree) {
+ let g = [1];
+ for (let i = 0; i < degree; i++) {
+ const next = new Array(g.length + 1).fill(0);
+ for (let j = 0; j < g.length; j++) {
+ next[j] ^= g[j];
+ next[j + 1] ^= gfMul(g[j], EXP[i]);
+ }
+ g = next;
+ }
+ return g;
+}
+
+function rsEncode(data, ecCount) {
+ const gen = rsGenerator(ecCount);
+ const res = new Uint8Array(data.length + ecCount);
+ res.set(data);
+ for (let i = 0; i < data.length; i++) {
+ const coef = res[i];
+ if (coef !== 0) {
+ for (let j = 0; j < gen.length; j++) {
+ res[i + j] ^= gfMul(gen[j], coef);
+ }
+ }
+ }
+ return res.slice(data.length);
+}
+
+// Version table for Byte mode, Error Correction Level M (ISO/IEC 18004 Table 9)
+// Capacities: [version, totalCodewords, ecCodewordsPerBlock, size, dataCap, groups]
+export const VERSIONS = [
+ null,
+ { version: 1, total: 26, ec: 10, size: 21, dataCap: 14, groups: [{ blocks: 1, dataLen: 16 }] },
+ { version: 2, total: 44, ec: 16, size: 25, dataCap: 26, groups: [{ blocks: 1, dataLen: 28 }] },
+ { version: 3, total: 70, ec: 26, size: 29, dataCap: 42, groups: [{ blocks: 1, dataLen: 44 }] },
+ { version: 4, total: 100, ec: 18, size: 33, dataCap: 62, groups: [{ blocks: 2, dataLen: 32 }] },
+ { version: 5, total: 134, ec: 24, size: 37, dataCap: 84, groups: [{ blocks: 2, dataLen: 43 }] },
+ { version: 6, total: 172, ec: 16, size: 41, dataCap: 106, groups: [{ blocks: 4, dataLen: 27 }] },
+ { version: 7, total: 196, ec: 18, size: 45, dataCap: 122, groups: [{ blocks: 4, dataLen: 31 }] },
+ { version: 8, total: 242, ec: 22, size: 49, dataCap: 152, groups: [{ blocks: 2, dataLen: 38 }, { blocks: 2, dataLen: 39 }] },
+ { version: 9, total: 292, ec: 22, size: 53, dataCap: 180, groups: [{ blocks: 3, dataLen: 36 }, { blocks: 2, dataLen: 37 }] },
+ { version: 10, total: 346, ec: 26, size: 57, dataCap: 213, groups: [{ blocks: 4, dataLen: 43 }, { blocks: 1, dataLen: 44 }] },
+ { version: 11, total: 404, ec: 30, size: 61, dataCap: 251, groups: [{ blocks: 1, dataLen: 50 }, { blocks: 4, dataLen: 51 }] },
+ { version: 12, total: 466, ec: 22, size: 65, dataCap: 287, groups: [{ blocks: 6, dataLen: 36 }, { blocks: 2, dataLen: 37 }] },
+ { version: 13, total: 532, ec: 22, size: 69, dataCap: 331, groups: [{ blocks: 8, dataLen: 37 }, { blocks: 1, dataLen: 38 }] },
+ { version: 14, total: 581, ec: 24, size: 73, dataCap: 362, groups: [{ blocks: 4, dataLen: 40 }, { blocks: 5, dataLen: 41 }] }
+];
+
+export const MAX_SUPPORTED_VERSION = 14;
+export const MAX_QR_PAYLOAD_BYTES = VERSIONS[MAX_SUPPORTED_VERSION].dataCap;
+
+export const ALIGNMENT_PATTERN_POS = [
+ [],
+ [],
+ [6, 18],
+ [6, 22],
+ [6, 26],
+ [6, 30],
+ [6, 34],
+ [6, 22, 38],
+ [6, 24, 42],
+ [6, 26, 46],
+ [6, 28, 50],
+ [6, 30, 54],
+ [6, 32, 58],
+ [6, 34, 62],
+ [6, 26, 46, 66]
+];
+
+// Mask evaluation formulas
+function getMaskBit(mask, row, col) {
+ switch (mask) {
+ case 0: return (row + col) % 2 === 0;
+ case 1: return row % 2 === 0;
+ case 2: return col % 3 === 0;
+ case 3: return (row + col) % 3 === 0;
+ case 4: return (Math.floor(row / 2) + Math.floor(col / 3)) % 2 === 0;
+ case 5: return ((row * col) % 2) + ((row * col) % 3) === 0;
+ case 6: return (((row * col) % 2) + ((row * col) % 3)) % 2 === 0;
+ case 7: return (((row + col) % 2) + ((row * col) % 3)) % 2 === 0;
+ default: return false;
+ }
+}
+
+// ISO/IEC 18004 Format Information Generator (BCH 15, 5)
+const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
+const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1);
+
+export function getFormatInfoBits(ecBit, mask) {
+ const data = (ecBit << 3) | mask;
+ let d = data << 10;
+ for (let i = 14; i >= 10; i--) {
+ if ((d >> i) & 1) d ^= (G15 << (i - 10));
+ }
+ return ((data << 10) | d) ^ G15_MASK;
+}
+
+// ISO/IEC 18004 Version Information Generator (BCH 18, 6)
+const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
+
+export function getVersionInfoBits(v) {
+ let d = v << 12;
+ for (let i = 17; i >= 12; i--) {
+ if ((d >> i) & 1) d ^= (G18 << (i - 12));
+ }
+ return (v << 12) | d;
+}
+
+/**
+ * Encodes text into a QR code matrix.
+ * Returns { version, size, modules, get(x, y), matrix }
+ */
+export function encodeQrMatrix(text) {
+ const bytes = Buffer.from(text, 'utf8');
+ let ver = null;
+ for (let v = 1; v < VERSIONS.length; v++) {
+ if (bytes.length <= VERSIONS[v].dataCap) {
+ ver = VERSIONS[v];
+ break;
+ }
+ }
+ if (!ver) {
+ throw new QrPayloadTooLargeError(bytes.length, MAX_QR_PAYLOAD_BYTES);
+ }
+
+ // Build bitstream: Mode 4 (Byte) + Length (8 or 16 bits) + data + terminator + pad
+ const bits = [];
+ const pushBits = (val, len) => {
+ for (let i = len - 1; i >= 0; i--) bits.push((val >> i) & 1);
+ };
+
+ pushBits(0b0100, 4); // Byte mode indicator
+ pushBits(bytes.length, ver.version >= 10 ? 16 : 8); // Character count
+ for (const b of bytes) pushBits(b, 8);
+
+ const totalDataCodewords = ver.groups.reduce((acc, g) => acc + g.blocks * g.dataLen, 0);
+ const totalDataBits = totalDataCodewords * 8;
+ const termLen = Math.min(4, totalDataBits - bits.length);
+ for (let i = 0; i < termLen; i++) bits.push(0);
+ while (bits.length % 8 !== 0) bits.push(0);
+
+ const padBytes = [0xec, 0x11];
+ let padIdx = 0;
+ while (bits.length < totalDataBits) {
+ pushBits(padBytes[padIdx % 2], 8);
+ padIdx++;
+ }
+
+ // Convert to data codewords
+ const dataCodewords = [];
+ for (let i = 0; i < bits.length; i += 8) {
+ let b = 0;
+ for (let j = 0; j < 8; j++) b = (b << 1) | bits[i + j];
+ dataCodewords.push(b);
+ }
+
+ // Interleave blocks according to ISO/IEC 18004 Table 9 and compute Reed-Solomon EC
+ const dataBlocks = [];
+ const ecBlocks = [];
+ let cwOffset = 0;
+
+ for (const group of ver.groups) {
+ for (let b = 0; b < group.blocks; b++) {
+ const blockData = dataCodewords.slice(cwOffset, cwOffset + group.dataLen);
+ cwOffset += group.dataLen;
+ dataBlocks.push(blockData);
+ ecBlocks.push(Array.from(rsEncode(blockData, ver.ec)));
+ }
+ }
+
+ const maxDataLen = Math.max(...dataBlocks.map((b) => b.length));
+ const finalCodewords = [];
+ for (let i = 0; i < maxDataLen; i++) {
+ for (let b = 0; b < dataBlocks.length; b++) {
+ if (i < dataBlocks[b].length) {
+ finalCodewords.push(dataBlocks[b][i]);
+ }
+ }
+ }
+ for (let i = 0; i < ver.ec; i++) {
+ for (let b = 0; b < ecBlocks.length; b++) {
+ finalCodewords.push(ecBlocks[b][i]);
+ }
+ }
+
+ // Convert to matrix placement stream
+ const matrixBits = [];
+ for (const cw of finalCodewords) {
+ for (let i = 7; i >= 0; i--) matrixBits.push((cw >> i) & 1);
+ }
+
+ const size = ver.size;
+ const matrix = Array.from({ length: size }, () => new Int8Array(size).fill(0));
+ const reserved = Array.from({ length: size }, () => new Uint8Array(size));
+
+ function setFinder(r, c) {
+ for (let i = -1; i <= 7; i++) {
+ for (let j = -1; j <= 7; j++) {
+ const y = r + i;
+ const x = c + j;
+ if (y < 0 || y >= size || x < 0 || x >= size) continue;
+ const on = (i >= 0 && i <= 6 && (j === 0 || j === 6)) ||
+ (j >= 0 && j <= 6 && (i === 0 || i === 6)) ||
+ (i >= 2 && i <= 4 && j >= 2 && j <= 4);
+ matrix[y][x] = on ? 1 : 0;
+ reserved[y][x] = 1;
+ }
+ }
+ }
+
+ setFinder(0, 0);
+ setFinder(0, size - 7);
+ setFinder(size - 7, 0);
+
+ // REV-01: Correct alignment-pattern placement for all supported versions.
+ // Patterns are placed at all grid coordinates EXCEPT where they overlap the three finder patterns.
+ // Placed BEFORE timing patterns so timing pattern reservation does NOT skip valid alignment modules.
+ const alignPos = ALIGNMENT_PATTERN_POS[ver.version] || [];
+ const alignLen = alignPos.length;
+ for (let i = 0; i < alignLen; i++) {
+ for (let j = 0; j < alignLen; j++) {
+ // Exclude top-left (0, 0), bottom-left (alignLen - 1, 0), and top-right (0, alignLen - 1)
+ if ((i === 0 && j === 0) || (i === 0 && j === alignLen - 1) || (i === alignLen - 1 && j === 0)) {
+ continue;
+ }
+ const r = alignPos[i];
+ const c = alignPos[j];
+ for (let dr = -2; dr <= 2; dr++) {
+ for (let dc = -2; dc <= 2; dc++) {
+ const on = dr === -2 || dr === 2 || dc === -2 || dc === 2 || (dr === 0 && dc === 0);
+ matrix[r + dr][c + dc] = on ? 1 : 0;
+ reserved[r + dr][c + dc] = 1;
+ }
+ }
+ }
+ }
+
+ // Timing patterns (connect finders, filling non-reserved modules)
+ for (let i = 8; i < size - 8; i++) {
+ if (!reserved[6][i]) { matrix[6][i] = i % 2 === 0 ? 1 : 0; reserved[6][i] = 1; }
+ if (!reserved[i][6]) { matrix[i][6] = i % 2 === 0 ? 1 : 0; reserved[i][6] = 1; }
+ }
+
+ // Version information for QR versions 7 and higher (ISO/IEC 18004 Section 8.10)
+ if (ver.version >= 7) {
+ const vbits = getVersionInfoBits(ver.version);
+ for (let i = 0; i < 18; i++) {
+ const bit = (vbits >> i) & 1;
+ const r = Math.floor(i / 3);
+ const c = (i % 3) + size - 8 - 3;
+ // Top-right 3x6 block
+ matrix[r][c] = bit;
+ reserved[r][c] = 1;
+ // Bottom-left 6x3 block
+ matrix[c][r] = bit;
+ reserved[c][r] = 1;
+ }
+ }
+
+ // Reserve format info area (around finder patterns and dark module)
+ for (let i = 0; i < 15; i++) {
+ // Vertical positions
+ if (i < 6) reserved[i][8] = 1;
+ else if (i < 8) reserved[i + 1][8] = 1;
+ else reserved[size - 15 + i][8] = 1;
+
+ // Horizontal positions
+ if (i < 8) reserved[8][size - i - 1] = 1;
+ else if (i < 9) reserved[8][15 - i - 1 + 1] = 1;
+ else reserved[8][15 - i - 1] = 1;
+ }
+ matrix[size - 8][8] = 1; // Mandatory Dark Module (ISO 18004 8.7.2.2)
+ reserved[size - 8][8] = 1;
+
+ // Mask 0 (standard checkerboard mask)
+ const chosenMask = 0;
+
+ // Place data bits in 2-column zig-zag traversal
+ let bitIdx = 0;
+ let dir = -1;
+ let y = size - 1;
+ for (let x = size - 1; x > 0; x -= 2) {
+ if (x === 6) x--; // Skip vertical timing column
+ while (true) {
+ for (let col = 0; col < 2; col++) {
+ const curX = x - col;
+ if (!reserved[y][curX]) {
+ const bit = bitIdx < matrixBits.length ? matrixBits[bitIdx++] : 0;
+ const maskBit = getMaskBit(chosenMask, y, curX);
+ matrix[y][curX] = bit ^ (maskBit ? 1 : 0);
+ }
+ }
+ const nextY = y + dir;
+ if (nextY < 0 || nextY >= size) {
+ dir = -dir;
+ break;
+ }
+ y = nextY;
+ }
+ }
+
+ // Format info placement for EC Level M (bit 0) and Mask 0
+ const formatInfo = getFormatInfoBits(0, chosenMask);
+ for (let i = 0; i < 15; i++) {
+ const mod = (formatInfo >> i) & 1;
+
+ // Vertical format info modules
+ if (i < 6) matrix[i][8] = mod;
+ else if (i < 8) matrix[i + 1][8] = mod;
+ else matrix[size - 15 + i][8] = mod;
+
+ // Horizontal format info modules
+ if (i < 8) matrix[8][size - i - 1] = mod;
+ else if (i < 9) matrix[8][15 - i - 1 + 1] = mod;
+ else matrix[8][15 - i - 1] = mod;
+ }
+ matrix[size - 8][8] = 1; // Ensure Dark Module is preserved
+
+ return {
+ version: ver.version,
+ size,
+ get: (row, col) => matrix[row][col] === 1,
+ matrix
+ };
+}
+
+/**
+ * Generates an SVG string representation of a UPI QR code.
+ */
+export function generateQrSvg(upiUri, { size = 280, margin = 4, darkColor = '#000000', lightColor = '#ffffff' } = {}) {
+ const qr = encodeQrMatrix(upiUri);
+ const totalCells = qr.size + margin * 2;
+ const cellSize = (size / totalCells).toFixed(3);
+
+ let pathData = '';
+ for (let r = 0; r < qr.size; r++) {
+ for (let c = 0; c < qr.size; c++) {
+ if (qr.get(r, c)) {
+ const x = ((c + margin) * cellSize).toFixed(2);
+ const y = ((r + margin) * cellSize).toFixed(2);
+ pathData += `M${x},${y}h${cellSize}v${cellSize}h-${cellSize}z `;
+ }
+ }
+ }
+
+ return `
+
+
+ `;
+}
+
+/**
+ * Generates a standard NPCI UPI URI string.
+ * Never truncates payment details (preserves full note and order parameters).
+ */
+export function buildUpiUri({ vpa, name, amountPaise, orderId, note = 'NIGHTLIFEZ Event Ticket' }) {
+ if (!vpa || !orderId || amountPaise === undefined || amountPaise === null) {
+ throw new Error('Missing required UPI parameters: vpa, orderId, and amountPaise are mandatory');
+ }
+ const amountRupees = (Number(amountPaise) / 100).toFixed(2);
+ const params = new URLSearchParams({
+ pa: vpa,
+ pn: name,
+ am: amountRupees,
+ cu: 'INR',
+ tr: orderId,
+ tn: String(note)
+ });
+ return `upi://pay?${params.toString()}`;
+}
diff --git a/lib/views/admin.js b/lib/views/admin.js
index 7454bff..8bef045 100644
--- a/lib/views/admin.js
+++ b/lib/views/admin.js
@@ -10,8 +10,8 @@ function accessScreen(state) {
Admin
${out ? 'Sign in to continue' : 'You don’t have access to this page'}
${out
- ? 'The admin area is for the StrangersMeetup team. Sign in with Telegram to continue.'
- : 'This area is for the StrangersMeetup team. If you think you should have access, ask the site owner.'}
+ ? 'The admin area is for the NIGHTLIFEZ team. Sign in with Telegram to continue.'
+ : 'This area is for the NIGHTLIFEZ team. If you think you should have access, ask the site owner.'}
`;
return layout({
title: out ? 'Sign in required' : 'Access denied',
- description: 'Admin area for the StrangersMeetup team.',
+ description: 'Admin area for the NIGHTLIFEZ team.',
path: '/admin',
body,
noindex: true
@@ -31,7 +31,7 @@ export function renderAdminShell({ state, role, csrf }) {
const tabs = tabsFor(role);
const main = html`
-
+
Sections ${tabs[0][1]}
${tabs.map(([tab, label], i) => html`${label} `)}
@@ -43,12 +43,12 @@ export function renderAdminShell({ state, role, csrf }) {
return `${html`
-Admin · StrangersMeetup
+Admin · NIGHTLIFEZ
${main}
-
+
`}`;
}
diff --git a/lib/views/checkout-upi.js b/lib/views/checkout-upi.js
new file mode 100644
index 0000000..0790757
--- /dev/null
+++ b/lib/views/checkout-upi.js
@@ -0,0 +1,277 @@
+// lib/views/checkout-upi.js - Responsive UPI-first checkout view.
+// Adapts between Mobile (direct intent launch & app chooser) and Desktop (dynamic QR & live polling).
+
+import { html, raw } from './html.js';
+import { layout } from './layout.js';
+
+export function renderUpiCheckout({
+ order,
+ event,
+ tier,
+ user,
+ csrfToken = ''
+}) {
+ const amountRupees = (order.amountPaise / 100).toFixed(2);
+ const upiUri = order.upiIntentUrl;
+ const qrSvg = order.qrSvg;
+ const expiresAt = order.expiresAt;
+
+ const body = html`
+
+
+
+
+
+
Secure UPI Checkout
+
${event.title}
+
${event.city} · ${tier.name} × ${order.quantity}
+
+
+ Total to Pay
+ ₹${amountRupees}
+
+
+
+
+
+
+
+
+ Payment session expires in:
+ 15:00
+
+
+
+
+
Pay with UPI on this device
+
Tap below to open your preferred UPI application and approve payment.
+
+
+ ⚡ Pay with Any UPI App
+
+
+
+ or open directly in
+
+
+
+
+
+ Returning from the UPI app? We automatically verify payment confirmation with the banking network.
+
+
+
+
+
+
Scan QR code to pay
+
Open any UPI app on your mobile phone and scan this dynamic code.
+
+
+ ${raw(qrSvg)}
+
+
+
+ Google Pay
+ PhonePe
+ Paytm
+ CRED
+ BHIM
+ Any Bank UPI
+
+
+
+
+
+
+
Awaiting payment authorization...
+
Refresh Status
+
+
+
+
+
✓
+
Payment Verified! Booking Confirmed
+
Your ticket has been secured. Your mystery venue address and private group invite are ready.
+
View My Ticket Pass →
+
+
+
+
⏳
+
Payment Session Expired
+
This dynamic QR and payment intent have expired to protect your transaction.
+
Start New Checkout
+
+
+
+
✕
+
Payment Was Not Completed
+
The transaction could not be verified or was declined.
+
Try Again
+
+
+
+
+
+
+
+
+ `;
+
+ return layout({
+ title: `Checkout — ${event.title}`,
+ description: `Pay securely with UPI for ${event.title}`,
+ path: `/checkout/${event.slug}`,
+ body,
+ noindex: true
+ });
+}
diff --git a/lib/views/components.js b/lib/views/components.js
index 2b38d45..c8c6bce 100644
--- a/lib/views/components.js
+++ b/lib/views/components.js
@@ -9,8 +9,15 @@ export function eventPath(e) {
export function badges(e) {
const out = [];
+ const distText = e.venuePrivacy === 'disclosed_after_booking'
+ ? e.distanceBand
+ : (e.distanceKm != null ? `${e.distanceKm} km away` : e.distanceBand);
+ if (distText) out.push(html`📍 ${distText} `);
if (e.isExternal) out.push(html`Via ${e.sourceName} `);
if (e.isDemo) out.push(html`Sample `);
+ if (e.venuePrivacy === 'disclosed_after_booking') out.push(html`🔒 Mystery Venue `);
+ if (e.organiserManaged || e.organizer) out.push(html`✓ Verified Host `);
+ out.push(html`21+ `);
if (e.foodAvailable && e.stayAvailable && e.category === 'resort_getaway') out.push(html`Resort venue · Food & stay available `);
else if (e.foodAvailable && e.stayAvailable) out.push(html`Food & stay available `);
if (e.bookmyshowUrl) out.push(html`Also on BookMyShow `);
@@ -40,13 +47,20 @@ function cardArt(category) {
export function eventCard(e) {
const href = eventPath(e);
- return html`
- ${e.coverUrl ? html` ` : cardArt(e.category)}
+ const isSaved = Boolean(e.isSaved);
+ const saveBtn = e.id ? html` ` : '';
+
+ return html`
+
+ ${e.recommendationReason ? html`
✨ ${e.recommendationReason}
` : ''}
${e.categoryLabel} ${e.city}
-
+
${fmtDate(e.startAt)} · ${fmtTime(e.startAt)} ${e.area ? html` · ${e.area}` : ''}
- ${e.inclusions.length ? html`
${e.inclusions.slice(0, 3).join(' · ')}
` : ''}
+ ${e.inclusions && e.inclusions.length ? html`
${e.inclusions.slice(0, 3).join(' · ')}
` : ''}
${badges(e)}
`;
- return layout({ title: 'Membership', description: 'Optional StrangersMeetup membership with access to private Telegram groups.', path: '/membership', body });
+ return layout({ title: 'Membership', description: 'Optional NIGHTLIFEZ membership with access to private Telegram groups.', path: '/membership', body });
}
diff --git a/lib/views/event.js b/lib/views/event.js
index 3b8e854..8505f5e 100644
--- a/lib/views/event.js
+++ b/lib/views/event.js
@@ -2,7 +2,7 @@
import { html, raw, jsonLd, fmtFullDate, fmtTime, fmtDate, fmtZone } from './html.js';
import { layout } from './layout.js';
import { badges, eventPath } from './components.js';
-import { siteUrl, livePayments } from '../config.js';
+import { siteUrl } from '../config.js';
import { CITIES } from '../services/events.js';
function eventJsonLd(e) {
@@ -23,7 +23,7 @@ function eventJsonLd(e) {
name: e.venue || e.area || e.city,
address: { '@type': 'PostalAddress', addressLocality: e.city, ...(region ? { addressRegion: region } : {}), addressCountry: 'IN' }
},
- organizer: e.organiserManaged ? { '@type': 'Organization', name: e.organizer } : { '@type': 'Organization', name: 'StrangersMeetup', url: siteUrl() },
+ organizer: e.organiserManaged ? { '@type': 'Organization', name: e.organizer } : { '@type': 'Organization', name: 'NIGHTLIFEZ', url: siteUrl() },
url: `${siteUrl()}${eventPath(e)}`
};
if (e.pricePaise) {
@@ -46,7 +46,7 @@ function externalBox(e) {
? html`
View & book on ${e.sourceName} `
: html`
${e.stateLabel} `}
- StrangersMeetup does not run this event. Price, availability, tickets and refunds are handled by the organiser.
+ NIGHTLIFEZ does not run this event. Price, availability, tickets and refunds are handled by the organiser.
Always confirm details on the organiser’s page before you go.
`;
@@ -104,11 +104,12 @@ function tierBookBox(e, { preview = false } = {}) {
${e.stateLabel}
${preview ? html`
Preview — booking is switched off until you publish.
` : ''}
${hasPaid && !e.checkoutAvailable ? html`
Online payment isn’t available yet, so paid tickets can’t be booked right now.${e.tiers.some((t) => t.kind === 'free') ? ' Free tickets can.' : ''}
` : ''}
-
+ ${hasPaid && e.checkoutAvailable ? html`
${e.checkoutMode === 'upi_direct' ? 'Paid tickets are bought with secure UPI checkout (GPay, PhonePe, Paytm, QR).' : 'Paid tickets are bought with secure checkout on SuperProfile, on our website.'} Refund policy .
` : ''}
${e.requiresApproval ? html`The host reviews each request and you’ll hear back on Telegram.${hasPaid ? ' Paid tickets are only charged after approval.' : ''} ` : ''}
- ${e.venuePrivacy === 'disclosed_after_booking' ? html`The exact address appears on your booking once it’s confirmed. ` : ''}
+ ${e.venuePrivacy === 'disclosed_after_booking' ? html`🔒 Mystery Venue — Revealed after confirmed booking ` : ''}
${e.hasContact ? html`An on-ground contact number is shared with confirmed guests. ` : ''}
Your confirmation arrives via our Telegram bot.
@@ -145,22 +147,25 @@ function bookBox(e) {
if (CLOSED[e.state]) return closedBox(e);
if (e.ticketing === 'tiers') return tierBookBox(e);
let action;
- if (e.bookable) {
- action = html`
Book Tickets
- ${!livePayments() ? html`
Test mode — sandbox checkout, no real money is charged.
` : ''}`;
+ if (e.bookable && e.checkoutPath) {
+ // Buying happens on SuperProfile, on the website only: the link is hidden inside the Telegram Mini App (site.js).
+ action = html`
Book Tickets
+
Tickets are sold on our website. Open NIGHTLIFEZ in your browser to book.
+
Secure checkout on SuperProfile. ${e.refundPolicy ? e.refundPolicy : html`Refunds follow our refund policy and are issued on SuperProfile.`}
`;
} else {
action = html`
${e.stateLabel} `;
}
return html`
`;
}
@@ -178,7 +183,13 @@ export function renderEvent(e, { preview = false, previewBanner = '' } = {}) {
${e.isTrip ? 'Trips' : 'Upcoming'} / ${e.city}
${badges(e)}
-
${e.title}
+
+
${e.title}
+
+
+ ${e.isSaved ? 'Saved' : 'Save'}
+
+
${e.summary ? html`
${e.summary}
` : ''}
${e.isExternal ? html`
Listed from ${e.sourceUrl ? html`${e.sourceName} ` : e.sourceName}. Details may change — the organiser’s page is the source of truth.
` : ''}
${e.isDemo ? html`
This is a sample listing used to preview the site. It is not a real event and cannot be booked for real.
` : ''}
@@ -190,7 +201,7 @@ export function renderEvent(e, { preview = false, previewBanner = '' } = {}) {
When ${when}
- Where ${e.venue || e.area ? html`${e.venue || e.area}, ` : ''}${e.city}${!e.isExternal && e.venuePrivacy === 'disclosed_after_booking' ? html` (exact venue after booking) ` : ''}${e.mapsUrl ? html` · Open in Maps ` : ''}
+ Where ${e.venue || e.area ? html`${e.venue || e.area}, ` : ''}${e.city}${!e.isExternal && e.venuePrivacy === 'disclosed_after_booking' ? html` 🔒 Mystery Venue — Revealed after confirmed booking ` : ''}${e.mapsUrl ? html` · Open in Maps ` : ''}
Format ${e.categoryLabel}
${e.isExternal ? '' : tiered ? html`
Tickets ${e.capacity} in total ` : html`
Group size Up to ${e.capacity} people `}
${tiered && e.requiresApproval ? html`
Entry Host approves each guest ` : ''}
diff --git a/lib/views/home.js b/lib/views/home.js
index 7d4fc02..76f4ae7 100644
--- a/lib/views/home.js
+++ b/lib/views/home.js
@@ -1,85 +1,127 @@
-// lib/views/home.js - Homepage in the order set by the launch brief.
+// lib/views/home.js - Discovery-first event homepage inspired by BookMyShow.
import { html, raw, jsonLd } from './html.js';
import { layout, INSTAGRAM_URL } from './layout.js';
-import { eventCard, emptyEvents, filters, faqList } from './components.js';
-import { FAQ, HOW_STEPS } from './content.js';
+import { eventCard, emptyEvents, filters } from './components.js';
import { siteUrl } from '../config.js';
-// Words are wrapped server-side so the headline can rise in word by word; it reads normally without JS.
-function splitWords(text) {
- return text.split(' ').map((w, i) => html`${w} `);
+function categoryNav(activeCat = '') {
+ const items = [
+ { label: 'All Events', icon: '🎉', href: '/events', cat: '' },
+ { label: 'Parties', icon: '🪩', href: '/events?category=weekend_party', cat: 'weekend_party' },
+ { label: 'Nightlife', icon: '🍸', href: '/nightlife', cat: 'nightlife' },
+ { label: 'Social Meetups', icon: '👥', href: '/events?category=meetup', cat: 'meetup' },
+ { label: 'Music', icon: '🎵', href: '/events?category=nightlife', cat: 'music' },
+ { label: 'Dining', icon: '🍷', href: '/events?category=dinner_club', cat: 'dinner_club' },
+ { label: 'Trips', icon: '🎒', href: '/trips', cat: 'weekend_trip' },
+ { label: 'Experiences', icon: '✨', href: '/events?category=workshop', cat: 'workshop' }
+ ];
+ return html`
+
+ `;
}
-function cinemaHero() {
- // Non-photo composition: two lights drifting into overlap — strangers becoming acquaintances.
- return html`
-
-
-
-
-
Meetups · Dinners · Nightlife · Trips · 21+
-
${splitWords('Your next favourite people are still strangers.')}
-
Small, hosted evenings and weekend trips across South India, designed so that walking in alone feels easy.
-
-
Continue with Telegram
-
Explore upcoming meetups
+function promoCarousel() {
+ const slides = [
+ {
+ badge: 'Trending This Weekend',
+ title: "South India's Hottest Weekend Parties & Nightlife",
+ sub: 'Curated crowds · Secret venues · Solo-friendly dance floors & cocktail lounges',
+ cta: 'Explore Parties',
+ href: '/events?category=weekend_party',
+ theme: 'theme-nightlife'
+ },
+ {
+ badge: 'Curated Getaways',
+ title: 'Camp, Trek & Connect: Weekend Trips & Escapes',
+ sub: 'Scenic mountain getaways, sunrise treks, and shared road trips across South India',
+ cta: 'Explore Trips',
+ href: '/trips',
+ theme: 'theme-trips'
+ },
+ {
+ badge: 'Reserved Tables',
+ title: 'Curated Dinner Clubs & Social Mixers',
+ sub: 'One reserved table, good food, and zero awkwardness. Meet 8–12 new people over dinner',
+ cta: 'Find a Table',
+ href: '/events?category=dinner_club',
+ theme: 'theme-dining'
+ }
+ ];
+
+ return html`
`;
}
-// How an evening unfolds — describes the format, not any specific event or outcome.
-const SCENES = [
- ['01', 'You arrive alone', 'Come solo. Evenings are designed for first-timers, so you never need a plus-one.'],
- ['02', 'Someone is hosting', 'A host runs the evening — dinners, games, mixers — so the first conversation is never on you.'],
- ['03', 'One table, a few hours', 'Small groups, a few unhurried hours, room to talk. Strangers start to overlap.'],
- ['04', 'The group chat keeps going', 'Confirmed guests get a one-time invite to the event’s private Telegram group. The next plan can start there.']
-];
-
-function scenes() {
- return html`
-
-
-
-
-
-
-
How an evening unfolds
-
How an evening unfolds
-
- ${SCENES.map(([n, t, d], i) => html`
- Scene ${n}
- ${t}
- ${d}
- `)}
-
-
${SCENES.map(() => html` `)}
+function discoveryShelf({ id, title, icon, items, seeAllHref, emptyMessage = '' }) {
+ if (!items.length && !emptyMessage) return '';
+ return html`
+
+
+ ${items.length
+ ? html`
${items.slice(0, 4).map(eventCard)}
`
+ : html`
${emptyMessage || 'New experiences dropping soon. Check back shortly.'}
Browse all `}
`;
}
-const REEL = ['Dinner clubs', 'Nightlife', 'Dating mixers', 'Weekend trips', 'Board-game evenings', 'Movie nights', 'Resort getaways'];
+export function renderHome({ events = [], trips = [], tiers = [], proof = null, media = [], filter = {} }) {
+ const filtered = Boolean(filter.city || filter.category || filter.when);
+ const allEvents = [...events];
-function reel() {
- const items = REEL.map((r) => html`
${r} `);
- return html`
`;
-}
+ // Helper partition filters
+ const trending = allEvents.filter((e) => e.state === 'open' || e.state === 'external').slice(0, 4);
+ const now = Date.now();
+ const next7Days = now + 7 * 86400000;
+ const weekend = allEvents.filter((e) => {
+ const t = new Date(e.startAt).getTime();
+ const day = new Date(e.startAt).getDay(); // 0 is Sun, 5 is Fri, 6 is Sat
+ return t >= now && t <= next7Days && (day === 0 || day === 5 || day === 6);
+ });
+ const parties = allEvents.filter((e) => e.category === 'nightlife' || e.category === 'weekend_party');
+ const meetups = allEvents.filter((e) => ['meetup', 'board_games', 'movie'].includes(e.category));
+ const mixers = allEvents.filter((e) => ['dating_mixer', 'matchmaking'].includes(e.category));
+ const dining = allEvents.filter((e) => ['dinner_club', 'workshop', 'networking'].includes(e.category));
+ const tripsList = trips.length ? trips : allEvents.filter((e) => ['weekend_trip', 'resort_getaway'].includes(e.category));
+
+ const hasAnyEvents = allEvents.length > 0 || tripsList.length > 0;
-export function renderHome({ events, trips, tiers, proof, media, filter }) {
- const filtered = Boolean(filter.city || filter.category || filter.when);
const proofBlock = proof || media.length
- ? html`