# EMRG Booking API: first sandbox booking

A runnable Node/TypeScript server plus a plain HTML browser page. No framework or runtime dependencies. Node 22.15+ is required; TypeScript stripping may print an experimental warning on Node 22. `npm install` installs optional type-check tooling, not a runtime dependency.

## Run

1. In EMRG's API & Webhooks settings, create a sandbox connection and issue a key with `booking:read` and `booking:write` (Full access includes both). EMRG automatically prepares synthetic clinic/provider fixtures, one consultation service and recurring daily 09:00–17:00 UTC availability. Additional keys reuse fixtures without resetting bookings. Consumer clinics sharing a provider share its synthetic schedule; patient access remains connection-scoped. EMRG must complete the one-time sandbox database/schema setup first.
2. Extract the download into a private local folder outside a website's public directory.
3. In Bash, set the key without writing it into shell history, then start:

```bash
read -rsp 'Sandbox API key: ' EMRG_API_KEY; echo
export EMRG_API_KEY
npm start
```

The default base URL is `https://api.joinemrg.com/api/v1`. An EMRG developer can set `EMRG_API_BASE_URL` to another trusted HTTPS API deployment. Never point this variable at an untrusted server: it receives the key.

4. Open http://127.0.0.1:4310 (use this exact host, not localhost). Choose a service and a date in the displayed provider-clinic timezone. Load availability and select a time/provider.
5. Create the synthetic patient. The server generates a stable external ID and unique example.com email for this workflow.
6. Create the card setup link. Open the EMRG-hosted form in a new tab. Use `4111111111111111`, a future expiry, and CVC `123`. No embedding allowlist is needed for this full-page flow. Return to the local example; it polls status, never card submission.
7. When the card status is `succeeded`, click **Book selected slot**. The server refreshes availability, then posts the appointment with notes. A confirmed appointment ID appears only after a successful booking response/replay.

8. Independently verify the saved appointment from your terminal (the example page does not perform this GET automatically). Use the same connection's key and replace the ID below with the confirmation's `appointmentId`:

```bash
APPOINTMENT_ID='YOUR_APPOINTMENT_ID'
curl --fail-with-body --silent --show-error \
  "${EMRG_API_BASE_URL:-https://api.joinemrg.com/api/v1}/partner/appointments/$APPOINTMENT_ID" \
  --header "Authorization: Bearer $EMRG_API_KEY"
```

Compare the returned patient/provider IDs, UTC times and `notes` with your booking. This GET returns current status and saved booking notes, including subsequent staff changes. A receipt or POST replay remains the original write result. A failed GET does not undo a booking: retry the read or reconcile the original write, never create a replacement booking just because verification failed. Unknown IDs and other connections' appointments return the same `404 APPOINTMENT_NOT_FOUND`. No database access is required.

If catalog loading fails, saved confirmations and **Resume original request** remain available. Use **Retry loading services** after resolving the catalog error.

No slots? Try another date/time; test bookings consume real sandbox capacity. `SANDBOX_NOT_CONFIGURED` or `SANDBOX_NOT_READY` requires EMRG to finish database setup, not a new key. `SANDBOX_PROVISIONING_BUSY` means retry shortly. To simulate a declined card use `4000000000000002`; after `failed`, deliberately create a new setup link.

## Requests and recovery

- `GET /partner/context` verifies scope at startup; the server refuses live keys and live environments.
- `GET /partner/appointment-types`, `/appointment-types/{id}/providers`, and `/appointment-types/{id}/availability` supply real IDs and UTC slots. The UI displays times in the catalog timezone.
- `POST /partner/patients` runs independently of card setup.
- `POST /partner/card-setup-sessions` returns the complete `setupUrl`. Only this link goes to the browser; raw card data goes to EMRG's hosted form.
- `GET /partner/card-setup-sessions/{id}` supplies `paymentMethodId` after `succeeded`. Polling is coalesced and spaced by at least 15 seconds, with browser backoff toward 60 seconds and respect for longer `Retry-After` values.
- `POST /partner/appointments` uses the returned patient, payment, type and provider IDs and the exact UTC slot. Booking does not charge the card.
- Before each POST, the server saves its key and exact payload to `.sandbox-state.json`. Network failures, 5xx and `REQUEST_PROCESSING` get bounded retries using the SAME payload/key. Receipt lookup helps reconciliation; a 404 never causes a new key. A 429 waits for `Retry-After`.
- If bounded recovery is exhausted, wait as instructed and click **Resume original request** (reload the page if necessary). Restarting the server preserves the workflow. Do not delete state or create a new connection to bypass an unknown outcome.
- A `401` or `403` pauses the write without finalizing its outcome. Repair the API key/permissions on the same connection, restart the server with the corrected key, and click **Resume original request**. The original payload/key are retained, including when reopening state from an older version of this example.
- After a definitive `SLOT_UNAVAILABLE`, refresh availability and choose another slot. A deliberate new booking attempt uses a new key, retaining the patient, saved card and external booking ID.
- `failed` / `expired` setup allows a deliberate fresh session. `requires_review` stops attempts; contact the clinic with the session ID. `superseded` requires the newest link, not automatic replacement.

## Files and limits

`server.ts` holds the API key server-side, performs requests and persists state. `index.html` calls only that local server and opens EMRG's form. Neither file collects, stores or logs card numbers or CVC. The server logs only its local listening URL.

This is a single-workflow, single-process local sandbox example. It binds to loopback, verifies Host/Origin on browser writes, and has no user authentication. Do not deploy it as a public booking service. It intentionally has no reset endpoint. For a new completed test workflow, stop the server and use a fresh example folder; retain the old state for reconciliation.

The state file includes the synthetic patient payload, resource IDs, idempotency keys, and secret setup capabilities. Keep it private and out of source control. The included `.gitignore` excludes it. Do not open the HTML directly or place this folder under your production web root.

For production, add authenticated/authorized user sessions, per-user workflow ownership, server-side validation and CSRF protection, and durable database transactions/locks for operation creation and recovery across processes. Replace local file persistence, bound retry jobs to your application's request lifecycle, and apply appropriate access controls to stored patient data and setup URLs. Use the same connection for key rotation; state is bound to the connection ID. Analytics and webhooks are optional follow-on integrations.

## Check

```bash
npm install
npm run check
```

The sample's automated mock tests in the documentation repository exercise successful booking, retries, receipt recovery, slot conflicts and polling. They do not validate a real merchant account or replace a provisioned sandbox run.
