> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usehasp.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Example: Referral Routing & Follow-Up

> A headless event-driven workflow triggered by a webhook from an external referral system — routes the referral, enriches it with AI, books intake, and follows up automatically.

This example walks through building a referral routing pipeline — a headless workflow triggered by an inbound webhook from an external referral management system. The workflow validates the referral, enriches it with AI-assisted triage, books an intake appointment, and schedules a follow-up if the patient doesn't confirm within 48 hours.

## What you're building

| Resource                     | Description                                                              |
| ---------------------------- | ------------------------------------------------------------------------ |
| **Webhook**                  | Inbound endpoint for the external referral system                        |
| **Workflow 1** (Webhook)     | Referral intake — triggered on inbound webhook                           |
| **Workflow 2** (Data-change) | Follow-up reminder — triggered when referral status stays `pending` >48h |
| **Entity**                   | `referral` — intake record with status and appointment details           |
| **Integration**              | Scheduling system (book appointment)                                     |
| **Integration**              | Email over SMTP (`email_smtp`) — patient confirmation                    |
| **Integration**              | Slack (internal routing notification)                                    |

## Step 1: Create the project

Click **New Project**. Name it *Referral Operations*.

## Step 2: Author the referral intake workflow

In chat:

> *"We receive patient referrals from an external system via webhook. When a referral comes in, I want to: validate it has the required fields, use AI to assess urgency from the referral notes, route it to the right clinical team based on specialty and urgency, book an intake appointment, and send the patient a confirmation email with the appointment details. If something's missing or urgency is critical, notify the intake coordinator on Slack immediately."*

The system asks: *"This sounds like a webhook-triggered workflow — your external referral system will POST to a URL we provision. Sound right?"* → Confirm.

The system:

* Creates a `referral` entity: `patient_name`, `dob`, `referring_provider`, `specialty`, `referral_notes`, `urgency` (routine/urgent/critical), `status`, `appointment_id`
* Provisions a webhook: `acme.usehasp.run/webhooks/referral-intake`
* Compiles workflow steps: validate payload → PHI scan → AI urgency classification → conditional routing → book appointment → send confirmation → notify on Slack if urgent/critical

## Step 3: Provide a sample payload

In chat, paste a sample from your referral system:

```json theme={null}
{
  "patient_name": "Robert Chen",
  "dob": "1962-08-22",
  "referring_provider": "Dr. Williams",
  "specialty": "cardiology",
  "referral_notes": "Patient presenting with intermittent chest pain on exertion. Echo pending.",
  "referral_id": "ref_7891234"
}
```

The system extracts the schema and adds payload validation to the contract. Referrals missing required fields return `400` before the workflow fires.

## Step 4: Add the follow-up workflow

In chat:

> *"If a referral's status is still 'pending' 48 hours after it came in — meaning the patient hasn't confirmed the appointment — send a follow-up email and try to rebook."*

The system identifies this as a **data-change trigger**: when `referral.status` has not changed from `pending` within 48 hours of `referral.created_at`.

It compiles a second workflow:

* Trigger: scheduled data-change check (every 6 hours, filter: `status == pending AND created_at < now - 48h`)
* Steps: query pending referrals → for each: send follow-up email → attempt rebook → update status

<Note>
  The follow-up workflow reads from the same `referral` entity that the intake workflow writes to — cross-workflow communication via the shared entity, no manual wiring required.
</Note>

## Step 5: Configure HMAC authentication on the webhook

Go to **Settings → Webhooks → referral-intake → Authentication → HMAC**.

Enter the shared secret from your referral system. HASP verifies the `X-Referral-Sig` header on every inbound request. Payloads that fail signature verification are rejected before the workflow fires.

## Step 6: Test with trigger simulation

From the test/run console, compose a test payload (the system pre-fills it from the sample you provided). Edit:

* `referral_notes`: *"Critical: patient reports syncope on exertion. EKG showed ST changes."*

Click **Run (Sandbox)**.

Trace:

1. `validate_payload` — all required fields present. ✓
2. `phi_scan` — detected PHI in `patient_name`, `dob`. Anonymized for inference.
3. `classify_urgency` — AI: `urgency: critical` (confidence: 0.99)
4. `condition` — urgency == critical → route to `cardiology_urgent` queue
5. `book_appointment` — **sandbox:** *"would have booked urgent cardiology slot for 2026-05-07 09:00 AM."*
6. `send_confirmation` — **sandbox:** *"would have sent confirmation email to patient."*
7. `notify_slack` — **sandbox:** *"would have posted to #intake-coordinator: CRITICAL referral received: cardiology. Appointment booked for tomorrow 9am."*

All edge-sandboxed. Review the payload that would have been sent to the scheduling system in step 5 — it's shown in full in the trace.

## Step 7: Release

Click **Release**. After publish:

* Configure your referral system to POST to `acme.usehasp.run/webhooks/referral-intake` with the shared secret.
* The intake coordinator can see all referrals in the `referral` entity. (Add a role-gated app for a live dashboard — see below.)

## Testing in production

Use **Manual Run** from the test/run console to fire the workflow with a real payload in production mode. This triggers real scheduling, real emails, and a real Slack notification. Confirm you intend this before using production mode.

## Extending the example

* **Intake coordinator dashboard**: add a role-gated app (served at `/referrals` on your org's `usehasp.run` runtime) showing all referrals grouped by status and urgency. Coordinators can click to view the full referral, see the AI urgency assessment, and manually override the routing if needed.
* **Multi-source webhooks**: a second referral partner sends data in a different schema. Create a second webhook endpoint; use a Class B multi-trigger on the same workflow, mapping both schemas into the normalized `referral` entity shape via per-trigger entry steps.
* **Referring provider notification**: when an appointment is booked, notify the referring provider via their preferred channel (email, Slack, or an EHR secure message through a `custom_http` integration).
* **SLA monitoring**: add a scheduled workflow that flags referrals approaching their specialty's target booking SLA (e.g., cardiology: 72 hours for urgent, 5 business days for routine).
