GRV-BackEnd/API.md
kirukib 7b3b9c5943 Scaffold GRV backend: applications, inquiries, tickets, discounts, merch, QR game
NestJS + Prisma/Postgres API shared by the site, admin and attendee app.
Ports the site's D1 application flow and review, stores every inquiry form,
sells tickets with discount codes (manual payment confirmation), and runs
booth/startup/mystery-investee QR scans with derived points and raffles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:24:36 +03:00

124 lines
8.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# GRV Backend API
Base URL: `http://localhost:4000` in dev (`PORT`), Swagger UI at `/docs`.
JSON in and out. Money is integer minor units (cents) with a `currency` (`"USD"`). Times are ISO-8601 UTC strings.
**Errors:** non-2xx with `{ "ok": false, "error": "<human message>", "code"?: "<machine code>", "errors"?: { field: message } }`.
**Auth:** `Authorization: Bearer <accessToken>`. One email-OTP flow for everyone; role comes from the server
(`ADMIN_EMAILS` / `STAFF_EMAILS` env allowlists, otherwise `ATTENDEE`). In dev the OTP is printed to the backend console.
There is no refresh token: attendee tokens last 30 days, staff/admin tokens 12 hours. On 401, log out and ask for a new code.
QR codes encode a URL: checkpoints `https://grv.ethiopiatrustfund.org/q/<qrToken>`, tickets `.../t/<qrToken>`.
`POST /scan` accepts either the full URL or the bare token.
## Shared shapes
```ts
type Role = "ATTENDEE" | "STAFF" | "ADMIN";
type User = { id: string; email: string; name: string | null; role: Role };
type CheckpointKind = "BOOTH" | "STARTUP_MEMBER" | "MYSTERY_INVESTEE";
type Checkpoint = {
id: string; kind: CheckpointKind;
label: string; // booth/partner name, or the person's role e.g. "Co-founder"
organisation: string | null; // partner or startup name
boothNumber: string | null;
personName: string | null;
points: number; // base points; MYSTERY_INVESTEE awards points * 2
qrToken: string; qrUrl: string; // admin only
active: boolean; // admin only
scanned?: boolean; // attendee list only
};
type OrderStatus = "PENDING" | "PAID" | "CANCELLED" | "FULFILLED";
type Order = {
id: string; number: string; // number like "GRV-1042"
kind: "TICKET" | "MERCH"; status: OrderStatus;
buyerName: string; buyerEmail: string; buyerPhone: string | null; company: string | null;
paymentMethod: "card" | "bank" | "booth";
paymentRef: string | null;
subtotalMinor: number; discountMinor: number; totalMinor: number; currency: string;
discountCode: string | null;
items: { name: string; qty: number; size: string | null; unitPriceMinor: number }[];
tickets?: Ticket[];
createdAt: string; paidAt: string | null; fulfilledAt: string | null;
};
type Ticket = { id: string; qrToken: string; qrUrl: string; tierName: string; holderEmail: string; holderName: string | null; checkedInAt: string | null };
type Tier = { id: string; code: string; name: string; description: string; scheduleLabel: string | null;
features: string[]; priceMinor: number; currency: string; capacity: number | null; sold: number; active: boolean; soldOut: boolean };
type MerchItem = { id: string; name: string; description: string | null; priceMinor: number; currency: string;
sizes: string[]; stock: number; imageUrl: string | null; active: boolean };
type Raffle = { id: string; name: string; prize: string; minPoints: number; drawnAt: string | null;
winner: { id: string; name: string | null; email?: string } | null; eligible?: boolean /* attendee */; eligibleCount?: number /* admin */ };
```
## Public
| Method | Path | Body → Response |
|---|---|---|
| GET | `/health` | `{ ok: true }` |
| GET | `/sectors` | `{ ok: true, sectors: string[] }` |
| POST | `/applications` | `{ values }` (step 1) → 201 `{ ok: true, token }` |
| GET | `/applications/:token` | `{ ok: true, status, submittedAt, values }` |
| PATCH | `/applications/:token` | `{ step, values }` → `{ ok: true }` |
| POST | `/applications/:token/submit` | `{ values }` (consents) → `{ ok: true, submittedAt }` |
| POST | `/inquiries` | site `InquiryPayload` (intent, name, email, …) → `{ ok: true }` |
| GET | `/tiers` | `Tier[]` (active only) |
| POST | `/discounts/validate` | `{ code, tierCode, quantity }` → `{ valid: boolean, message?, code?, subtotalMinor, discountMinor, totalMinor, currency }` |
| POST | `/orders` | `{ ticketId /* tier code */, quantity, name, email, company?, phone?, paymentMethod: "card"\|"bank", consent: true, discountCode? }` → `{ ok: true, orderId /* number */, totalUsd, totalMinor, discountMinor, currency, paymentMethod, instructions }` |
| GET | `/merch` | `MerchItem[]` (active only) |
| GET | `/tickets/:qrToken/qr.svg` | Ticket QR image (for the site's `/t/<token>` page) |
## Auth
| Method | Path | Body → Response |
|---|---|---|
| POST | `/auth/otp/request` | `{ email }` → `{ ok: true }` (always, to avoid email enumeration; rate limited) |
| POST | `/auth/otp/verify` | `{ email, code }` → `{ accessToken, user: User }`. 400 `{ code: "invalid_code" }` |
## Attendee (Bearer, any role)
| Method | Path | Body → Response |
|---|---|---|
| GET | `/me` | `{ user: User, points, rank: number \| null, progress: { booths: { found, total }, startups: { found, total }, mysteryFound: boolean }, tickets: Ticket[], merchOrders: Order[] }` |
| PATCH | `/me` | `{ name }` → `User` |
| POST | `/scan` | `{ token }` → `{ checkpoint: Checkpoint, pointsAwarded, total, mystery: boolean }`. 409 `{ code: "already_scanned", checkpoint }`, 404 `{ code: "unknown_code" }` |
| GET | `/checkpoints?kind=` | `Checkpoint[]` with `scanned`. Unscanned mystery entries are masked: `label: "Mystery investee"`, `organisation`/`personName`/`boothNumber` null |
| GET | `/leaderboard` | `{ rank, name, points, me: boolean }[]` (top 20; names are first name + last initial) |
| GET | `/raffles` | `Raffle[]` with `eligible` |
| POST | `/merch-orders` | `{ items: { merchItemId, qty, size? }[] }` → `Order` (kind MERCH, PENDING, pay & collect at booth) |
## Admin (Bearer, STAFF or ADMIN; ADMIN-only marked ★)
| Method | Path | Body → Response |
|---|---|---|
| GET | `/admin/stats` | `{ applications: Record<status, number>, ticketsSold, revenueMinor, currency, ordersPending, inquiriesNew, attendees, scansToday, scansTotal, leaderboard: { name, email, points }[] }` |
| GET | `/admin/applications?status&sector&stage&city&q` | `{ id, startupName, founderName, email, primarySector, stage, city, status, submittedAt, avgScore, reviewCount }[]` (drafts hidden unless `status=DRAFT`) |
| GET | `/admin/applications/:id` | `{ id, status, email, startupName, founderName, createdAt, submittedAt, sections: { title, fields: { label, value: string }[] }[], reviews: { reviewer, scores: Record<criterionId, number>, total, comment, updatedAt }[], criteria: { id, label }[] }` |
| POST | `/admin/applications/status` | `{ ids: string[], status }` → `{ updated }`. Statuses: `SUBMITTED, UNDER_REVIEW, SHORTLISTED, FINALIST, ACCEPTED, REJECTED`. Result emails go out on SHORTLISTED/FINALIST/ACCEPTED/REJECTED, only for rows whose status actually changed |
| PUT | `/admin/applications/:id/review` | `{ scores: Record<criterionId, 1..5>, comment? }` → `{ ok: true }` (one review per staff email) |
| GET | `/admin/applications/export.csv?…filters` | CSV download |
| GET | `/admin/inquiries?intent&status&q` | `{ id, intent, name, email, company, phone, message, payload, status, createdAt }[]` |
| PATCH | `/admin/inquiries/:id` | `{ status: "NEW"\|"CONTACTED"\|"CLOSED" }` |
| GET/POST | `/admin/tiers` ★POST | `Tier[]` / create `{ code, name, description, priceMinor, currency?, capacity?, features?, scheduleLabel?, active? }` |
| PATCH | `/admin/tiers/:id` ★ | partial Tier |
| GET/POST | `/admin/discounts` ★POST | `{ id, code, percentOff, amountOffMinor, tierId, tierName, maxUses, uses, startsAt, endsAt, active }[]` / create (exactly one of percentOff 1–100, amountOffMinor) |
| PATCH | `/admin/discounts/:id` ★ | partial |
| GET | `/admin/orders?kind&status&q` | `Order[]` (newest first) |
| POST | `/admin/orders/:id/mark-paid` | `{ paymentRef? }` → `Order`. Ticket orders: issues one Ticket per seat and emails the QR links |
| POST | `/admin/orders/:id/fulfil` | → `Order` (merch picked up; marks paid too) |
| POST | `/admin/orders/:id/cancel` | → `Order` |
| POST | `/admin/orders/:id/resend` | → `{ ok: true }` (re-sends ticket email) |
| GET | `/admin/tickets?q` | `(Ticket & { orderNumber })[]` |
| POST | `/admin/tickets/check-in` | `{ token }` (URL or token) → `Ticket`. 409 if already checked in |
| GET/POST | `/admin/merch` ★POST | `MerchItem[]` / create `{ name, description?, priceMinor, sizes?, stock, imageUrl?, active? }` |
| PATCH | `/admin/merch/:id` ★ | partial |
| GET/POST | `/admin/checkpoints?kind` ★POST | `Checkpoint[]` / create `{ kind, label, organisation?, boothNumber?, personName?, points? }` (default points: BOOTH 10, STARTUP_MEMBER 20, MYSTERY_INVESTEE 50 → awards 100) |
| PATCH/DELETE | `/admin/checkpoints/:id` ★ | partial / DELETE deactivates it (printed QR stops working; points already earned stay). Admin list rows also carry `scans` (count) |
| GET/POST | `/admin/raffles` ★POST | `Raffle[]` with `eligibleCount` / create `{ name, prize, minPoints }` |
| PATCH | `/admin/raffles/:id` ★ | partial |
| POST | `/admin/raffles/:id/draw` ★ | → `Raffle` with winner (random among eligible, excludes previous winners). 409 if already drawn |
| GET | `/admin/attendees?q` | `{ id, email, name, role, points, scans, tickets, createdAt }[]` |