> Historical edition notes. Current capabilities and audience are documented in [the third-edition audit](09-third-edition-audit.md); nationwide data and additional sign-in setup are in [the current integration guide](10-nationwide-and-auth.md). The public preview retains private account data.

# Quickgency — technical architecture and API

## Stack and tradeoffs

The runnable private pilot uses the supported Sites Vinext starter, React 19, TypeScript, Cloudflare Workers and D1 SQLite, with Drizzle migrations. Vinext was selected because it is the supported deployable server framework in this environment. The pinned version is a beta; Next.js compatibility and future upgrades require regression testing. This is not a claim of universal Next.js feature parity.

D1 supports durable SQL, indexes and atomic batches without an external account. It is suitable for this bounded prototype. It is not PostGIS. Matching uses a hospital-centered geographic bounding box, then Haversine distance over at most 100 candidates, returning at most 12 personal-environment or 20 sample-environment coarse projections. At scale this cap can omit closer candidates. Before national rollout, move to an approved PostgreSQL/PostGIS service or demonstrate an alternative with measured query and load tests. A PostGIS design would use a `geography(Point,4326)` index and `ST_DWithin` before ranking. Hosting, data location and cross-border processing need review before real sensitive data.

Primary technical references: https://github.com/cloudflare/vinext ; https://developers.cloudflare.com/d1/worker-api/d1-database/ ; https://postgis.net/docs/ST_DWithin.html ; https://github.com/harfbuzz/harfbuzzjs . Versions in the lockfile are authoritative for this build.

## Boundaries

- `app/`: server-rendered pages and HTTP API routes.
- `components/qg/`: original bilingual client interface.
- `lib/service.ts`: scoped SQL workflow, access checks, effective expiry, optimistic versions and audit events.
- `lib/validation.ts`, `lib/domain.ts`: strict request contracts and state/consent rules.
- `lib/server.ts`: D1 binding, Sites identity and allowlisted operator role.
- `db/schema.ts`, `drizzle/`: schema and migration history.
- `lib/card-svg.ts`, `lib/text-shaping.ts`: exact-format card generation and Bengali shaping.
- `tests/`: SQL workflow tests and built Worker smoke verification.

The hosted identity comes exclusively from the Sites dispatch-owned ChatGPT sign-in boundary. The deployment must not expose an origin that trusts arbitrary caller-supplied identity headers. ChatGPT identity does not prove phone ownership, clinical suitability or operator authorization. Admin IDs come from an environment allowlist, never a client role field.

## Database schema

| Table | Purpose / main constraints |
|---|---|
| users | Site-scoped identity, created/deleted timestamps |
| donors | One profile per owner; optional unique phone hash; coarse area centroid; availability; demo owner |
| hospitals | Reference name, area, centroid and source; partner flag stays false |
| blood_requests | Owner, need, deadline, status, version and mutation token; unique duplicate/idempotency keys |
| responses | One donor response per request; request/donor foreign keys |
| contact_consents | One permission record per response with expiry/revocation |
| donations | One donation report per response; verification state and evidence reference |
| recognition_ledger | Unique donation-linked recognition event; future revocation field |
| notifications | Account-scoped inbox; unique deduplication key; unused external-retry fields |
| audit_log | Pseudonymous actor, entity, action, from/to state and time |
| reports | Concern category/details and moderation state |
| volunteer_assignments | Reserved schema; assignment operations not implemented |
| community_content | Source-attributed content, publication flag, reviewer |
| rate_limits | Persistent per-actor/hour action counts |

`db/schema.ts` and SQL migrations contain exact column/index definitions. Never deploy example donors into the live namespace. The sandbox uses `demo_owner` plus synthetic donor owner keys; every read and action checks scope.

## Mutation consistency

The request row has an optimistic version. A batch first updates the row only if the read version still matches, assigning a fresh mutation token. Response, permission, notification and audit writes are guarded by that token in the same D1 transaction. A losing write returns 409 and emits no secondary side effects. Unique constraints prevent duplicate donation/recognition and per-request notifications. This does not replace future donor-wide reservation/cooldown policy or a durable external-delivery outbox.

## API conventions

Base: `/api/v1`. JSON responses use private/no-store caching. Protected operations require the dispatch-owned identity. Every POST also requires same-origin `Origin` and JSON content type. A streaming reader rejects request bodies at 16,000 bytes without buffering an unbounded body. Field allowlists reject forged verification fields. Errors return `{error, code}` and schema errors add field details. Main codes: 400 validation, 401 sign-in required, 403 role/origin denied, 404 hidden/missing, 409 state/version conflict, 410 erased account, 429 rate limit, 503 unconfigured provider.

| Method and path | Input / behavior |
|---|---|
| GET `/stats` | Non-demo totals only |
| GET `/catalog` | Hospital references without coordinates |
| GET `/requests` | Active verified request projections |
| GET `/requests/:id` | Scoped details, state, authorized responses and timeline |
| POST `/requests` | `bloodGroup`, `component`, `units` 1–12, `hospitalId`, `neededAt` epoch ms, `consent:true`, `idempotencyKey` UUID |
| POST `/requests/:id/respond` | Verified donor accepts; safely retryable |
| POST `/requests/:id/action` | `action`, optional `version`, `responseId`, review `reason`; role/state checked |
| GET `/search` | `group`, `hospital`, `radius` 5/10/25/50; `demo=1` scopes to owner sandbox |
| GET/POST `/profile` | POST: `displayName`, `bloodGroup`, `areaId`, `consent:true` |
| POST `/availability` | `available` boolean; activation needs phone verification |
| GET `/dashboard` | Own requests, profile, notifications, donations and invitations |
| POST `/notifications` | Mark own inbox read |
| POST `/reports` | Optional request UUID, category `fake_request/harassment/privacy/other`, details 5–500 chars |
| POST `/demo/setup` | Idempotently seed 20 fictional donors and six initial requests for this owner |
| GET `/demo/overview` | Scoped sample directory, requests, donation history and counts |
| POST `/demo/requests` | Same strict input as real request creation; separate sample idempotency namespace |
| POST `/demo/availability` | UUID `donorId`, boolean `available`; scoped to this owner’s sample profile |
| POST `/demo` | Create or resume isolated sample request |
| POST `/demo/:id` | Same action contract, explicit synthetic scope |
| GET `/community` | Reviewed and published content only |
| GET `/admin` | Allowlisted moderation/review overview |
| POST `/content` | Admin: UUID, title, body, HTTPS sourceUrl, publish boolean |
| POST `/resolve-report` | Admin: report UUID; resolution audit |
| GET `/export` | Download own dashboard JSON; not a complete legal access-response export |
| POST `/delete-account` | `confirm:"DELETE"`; anonymize profile and revoke/cancel |
| POST `/otp` | Returns 503; no SMS attempt |
| GET `/api/card/:id` | PNG; `format=poster` for square; optional `download`; same access check as request |

Allowed actions: invite, accept, decline, withdraw, consent, coordinate, handoff, report_donation, verify, reject, cancel, unresolved. State validation is authoritative; the presence of an action name does not grant permission. Real request activation and operator provisioning are intentionally not exposed as self-service endpoints.

The default interface is the sample community. Mode choice is persisted in local storage; authorization never depends on that choice. Sample donor availability lasts seven days and can be paused/resumed in the dashboard; personal donor availability remains a separate 24-hour consent. Matching can use `group=all` only for the sample environment. A saved sample donation pauses that sample donor. Seeding never resets completed requests or restores deliberately paused profiles.
