@awell-health/awell-extensions 2.1.209 → 2.1.210

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -160,8 +160,8 @@
160
160
  "changelog": "# MessageBird changelog"
161
161
  },
162
162
  "metriport": {
163
- "readme": "---\ntitle: Metriport\ndescription: Metriport is Plaid for healthcare data.\n---\n# Metriport\n\nMetriport is Plaid for healthcare data. We help digital health companies access and manage patient health and medical data, through an open-source and universal API.\n\nThrough a single integration, our API enables modern health companies to get the comprehensive patient data they need from both HIEs and EHRs, as well as popular wearable devices.\n\nAs a developer-first interoperability solution, Metriport is powering the next wave of innovative companies, accelerating a revolution in digital health.\n\nTo learn more visit [https://www.metriport.com/](https://www.metriport.com/)\n# Extension settings\n\nIn order to set up this extension, **you will need to provide a Metriport API key**. You can obtain an API key via the Metriport dashboard by selecting the `Developers tab`. To learn more on how to get started with Metriport visit our [quick start docs](https://docs.metriport.com/medical-api/getting-started/quickstart) for our Medical API. Also, to better understand how our API keys work check out the [API Keys section](https://docs.metriport.com/home/api-info/api-keys) of our docs as well.\n\n# Ingestion\n\n## Metriport ADT notifications (`metriportAdt`)\n\nAn ingestion endpoint for Metriport's [real-time patient notifications](https://docs.metriport.com/medical-api/handling-data/realtime-patient-notifications). Point the webhook URL in the Metriport dashboard at it. Request verification (Metriport's HMAC-SHA256 `x-metriport-signature`, with the verification ping answered by `pong`) is implemented but switched off for the pre-release; it will be enabled, and the **Webhook Key** setting required, before general availability.\n\nHandled notification types are `patient.admit`, `patient.transfer`, `patient.discharge` and `patient.discharge-summary`. For each, the FHIR bundle behind the pre-signed `payload.url` is downloaded and the patient is resolved on `payload.externalId` (the id you gave Metriport when creating the patient, i.e. your own MRN). The endpoint saves one encounter keyed on the visit number (the patient itself is created by that resolution; demographics are not written yet), so all four notifications about one visit update the same encounter (`in-progress` until the discharge, `finished` after it, with the last transfer destination as its location). Any other notification type is acknowledged and produces nothing.\n\nEvents published, for care flows to trigger on: `patient.admitted`, `patient.transferred`, `patient.discharged` and `discharge.summary-received` (on a discharge summary). Every handled notification also publishes `fhir.bundle-received`, which FHIR data movement listens for; it carries no clinical data, the bundle is looked up by ingestion id.\n\n# Custom Actions\n\n**GENERAL NOTE: Make sure to create Organizations and Facilities in Metriport before using this extension. A Patient must be associated with a Facility by providing the facilityId when stated in the actions.**\n\n## Create Patient\n\nCreates a Patient in Metriport for the specified Facility where the Patient is receiving care. The Patient is not enrolled in real-time monitoring; use **Enroll in Monitoring** for that.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/patient/create-patient) for more info.\n\n## Enroll in Monitoring\n\nCreates a Patient in Metriport and enrolls them in real-time monitoring in one step. It takes the same Patient details as **Create Patient**, but instead of a Facility ID it takes a **Cohort Name**. By convention a Cohort and the Facility its Patients receive care at share the same name, so the action looks both up by that name: the Patient is created in the matching Facility and added to the matching Cohort.\n\nNames are matched case-insensitively, ignoring surrounding whitespace, and must identify exactly one Cohort and exactly one Facility. Both lists are cached in memory for 24 hours; a name that is not in the cached list triggers an early refresh (at most once a minute) before the action fails, so a Cohort or Facility created recently is still found.\n\nNote that enrolling a Patient in real-time monitoring has downstream consequences: once you start receiving updates about the Patient, you are expected to contribute data back to Metriport.\n\nVisit the endpoint docs for [create patient](https://docs.metriport.com/medical-api/api-reference/patient/create-patient), [list facilities](https://docs.metriport.com/medical-api/api-reference/facility/list-facilities) and [list cohorts](https://docs.metriport.com/medical-api/api-reference/cohort/list-cohorts) for more info.\n\n## Update Patient\n\nUpdates the specified Patient.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/patient/update-patient) for more info.\n\n## Get Patient\n\nRetrieves the specified Patient.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/patient/get-patient) for more info.\n\n## Remove Patient\n\nRemoves a Patient at Metriport and at HIEs the Patient is linked to.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/patient/delete-patient) for more info.\n\n## List Documents\n\nLists all Documents that can be retrieved for a Patient.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/document/list-documents) for more info.\n\n**NOTE: It also returns the status of querying Document references across HIEs, indicating whether there is an asynchronous query in progress (status processing) or not (status completed). If the query is in progress, you will also receive the total number of Documents to be queried as well as the ones that have already been completed.**\n\n## Query Documents\n\nTriggers a Document query for the specified Patient across HIEs.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/document/start-document-query) for more info.\n\n**NOTE: When executed, this endpoint triggers an asynchronous Document query with HIEs and immediately returns the status of Document query, processing .**\n\n## Get Document Url\n\nGets a presigned URL for downloading the specified Document.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/document/get-document) for more info.\n\n**NOTE: This endpoint returns a URL which you can use to download the specified Document using the file name provided from the List Documents endpoint.**\n\n## Get Facility by Name\n\nGets the Facility with the given name, so a care flow can resolve a human-readable Facility name into the `facilityId` that the Patient and Document actions require.\n\nMetriport has no endpoint to filter Facilities by name, so this action lists all Facilities in your Organization and matches in memory. The name is matched case-insensitively and ignoring surrounding whitespace, and must match **exactly one** Facility: the action errors if no Facility matches, and also if several do, rather than guessing which one was meant.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/facility/list-facilities) for more info.\n\n| Field | Type | Description |\n| --- | --- | --- |\n| `facilityName` | string | The name of the Facility to look up. Matched case-insensitively, ignoring surrounding whitespace, and must match exactly one Facility in your Organization. |\n\nThe data points mirror the Facility object Metriport returns from [Get Facility](https://docs.metriport.com/medical-api/api-reference/facility/get-facility), one data point per response field:\n\n| Data point | Type | Metriport field | Description |\n| --- | --- | --- | --- |\n| `facilityId` | string | `id` | Metriport's UUID for the Facility. This is the `facilityId` the Patient and Document actions take. |\n| `facilityName` | string | `name` | The Facility name, as stored at Metriport — the canonical casing and spacing, not the name that was searched for. |\n| `npi` | string | `npi` | The Facility's National Provider Identifier. |\n| `tin` | string | `tin` | The Facility's Taxpayer Identification Number. Optional at Metriport; left unset when absent. |\n| `active` | boolean | `active` | Whether the Facility is active. Optional at Metriport; left unset when absent. |\n| `addressLine1` | string | `address.addressLine1` | Street address line 1. |\n| `addressLine2` | string | `address.addressLine2` | Street address line 2. Optional; left unset when absent. |\n| `city` | string | `address.city` | Address city. |\n| `state` | string | `address.state` | Two-letter US state or territory code. |\n| `zip` | string | `address.zip` | Address ZIP code. |\n| `country` | string | `address.country` | Address country — always `USA` at Metriport today. Left unset when absent. |\n\n## Remove Patient from Cohort\n\nRemoves the specified Patient from a cohort.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/cohort/remove-patients-from-cohort) for more info.\n\n## Get Webhook Bundle\n\nFetches the FHIR bundle from a Metriport webhook payload URL — e.g. the [Encounter Bundle](https://docs.metriport.com/medical-api/handling-data/patient-encounter-bundle) from an ADT notification, or a discharge summary. Pass the `bundleUrl` data point emitted by the **Realtime Update** webhook; the action downloads the bundle and returns it on the `bundle` data point.\n\nWhen the payload is a Patient Encounter Bundle, the action also rewrites it into an executable FHIR transaction and returns that on the `transactionBundle` data point, ready to hand to the Medplum **Find or create resource** action.\n\nThe Encounter's Metriport id is returned separately on the `encounterId` data point, so a later step can address the imported Encounter without re-parsing the bundle.\n\n**NOTE: Metriport pre-signed URLs are only valid for 10 minutes, so this action should run early in the care flow, shortly after the realtime update webhook fires.**\n\n| Field | Type | Description |\n| --- | --- | --- |\n| `url` | string | The pre-signed payload URL to fetch (the webhook's `bundleUrl` data point). |\n| `eventType` | string (optional) | The Metriport notification type — wire this from the realtime update webhook's `eventType` data point. Recorded on the import Provenance so admit, transfer and discharge can be told apart. |\n| `provenanceReason` | text (optional) | Free-text reason recorded on the import Provenance, describing why the data was imported. |\n\n| Data point | Type | Description |\n| --- | --- | --- |\n| `bundle` | json | The FHIR bundle fetched from the URL, exactly as Metriport sent it. |\n| `transactionBundle` | json | The same data rewritten as an executable FHIR transaction. Omitted when the payload is not a Patient Encounter Bundle. |\n| `encounterId` | string | Metriport's UUID for the Encounter in the bundle. Resolve the imported Encounter in Medplum with `Encounter?identifier=https://metriport.com/fhir/encounter\\|<encounterId>`. Omitted when the bundle carries no Encounter. |\n| `reasonForVisit` … `dischargeSummaryCoverage` | string / json | The discharge summary fields, only for a `patient.discharge-summary` bundle. See \"Discharge summary fields\" below. |\n\n### Discharge summary fields\n\nA `patient.discharge-summary` bundle is Metriport's FHIR conversion of the HIE's discharge summary document: one `Composition` plus the patient's encounter history and the clinical resources the document references. The Composition's sections carry title-only narratives, so there is no text to read off them; the content lives in the resources each section points at. Both bundle actions lift the fields a care team asks for out of those resources and return them as plain data points, so a care flow, Panels or an analytics export can use them without parsing the bundle. For any other bundle the fields are all omitted.\n\nEvery field is read relative to the encounter the Composition is about (`Composition.encounter`), **not** the first Encounter in the bundle, which is just the patient's oldest visit. Each is omitted, never empty, when the document does not carry it.\n\n| Data point | Type | Where it comes from |\n| --- | --- | --- |\n| `reasonForVisit` | string | The encounter's `reasonCode` texts, `; `-separated. |\n| `visitDiagnosis` | string | The encounter's diagnoses as `<text> (<ICD-10-CM code>)`, `; `-separated, from `Encounter.diagnosis`, else from the Conditions categorised `encounter-diagnosis` that point at the encounter. |\n| `planOfTreatment` | string | The CarePlans in the Plan of care section (LOINC `18776-5`): description, then one line per activity. |\n| `procedures` | string | The Procedures in the Procedures section (`47519-4`) as `<name> (<date>)`, `; `-separated. |\n| `procedureNote` | string | The notes those Procedures report to (`Procedure.report`), each headed by the report's name. The source files these under Results rather than in a section of their own. |\n| `dischargeDisposition` | string | `Encounter.hospitalization.dischargeDisposition` as text. |\n| `dischargeDispositionCode` | string | The same, as its code (`home`, `snf`, `rehab`, …, from `http://terminology.hl7.org/CodeSystem/discharge-disposition`). |\n| `dischargeInstructions` | string | The note in the Hospital discharge instructions section (`8653-8`), else in the Discharge instructions document section (`74213-0`). |\n| `dischargeSummaryCoverage` | json | `{ documentType, documentTypeText, sections, fields }`: the Composition's LOINC type, the section codes it carried, and which of the fields above were found. Lets coverage be measured instead of guessed. |\n\nNotes are carried as base64 `DiagnosticReport.presentedForm` attachments, `text/html` or `text/plain` depending on the source EHR. HTML is reduced to plain text (paragraphs and breaks become line breaks, tags and entities are dropped or decoded); anything that is not `text/*`, such as a PDF, yields nothing. A single field is capped at 100,000 characters, far above any note seen, purely so a pathological document cannot push the activity result over the message size limit.\n\nThis is built against the documents seen from two source EHR families, keyed on section LOINC codes because the titles differ between them (\"Plan of Treatment\" in one, \"Treatment Plan\" in the other). It targets the common pattern, not every variant: a document that files a field somewhere else simply does not yield it, and `dischargeSummaryCoverage` says so.\n\n### Building the transaction bundle\n\nMetriport delivers a bundle of `type: 'collection'`, which is **not executable**. Handing it straight to Medplum does nothing useful: no entry carries `request` metadata saying what to do with it, and every internal reference points at a Metriport UUID that means nothing in Medplum. The action therefore builds a second, executable bundle rather than passing the original through.\n\nThe transformation is a pure function with no Medplum access of its own — this extension holds Metriport credentials only. That rules out reading Medplum to reconcile against what is already there, so every lookup is expressed declaratively and resolved by the server when the transaction executes.\n\n**The Patient is never written.** Awell/Medplum is the source of truth for patient demographics, so the Patient entry is dropped entirely and every reference to it becomes a conditional reference:\n\n```\nPatient?identifier=https://awellhealth.com/patients|<awell patient id>\n```\n\nOmitting the entry guarantees structurally that a Metriport ADT feed can never overwrite the patient record.\n\n**Everything else is written idempotently.** Each Metriport resource is stamped with an identifier derived from its Metriport id and written with a conditional update:\n\n```\nidentifier: { system: 'https://metriport.com/fhir/encounter', value: '<metriport id>' }\nrequest: PUT Encounter?identifier=https://metriport.com/fhir/encounter|<metriport id>\n```\n\nA conditional update creates on zero matches and updates on one, so a redelivered notification updates in place instead of duplicating Conditions, Observations, Practitioners and Locations — and the admit and discharge notifications for one visit converge on a single Encounter. Existing identifiers are kept, so the Encounter keeps its HL7 `VN` visit number alongside ours.\n\n**References are rewritten to Metriport's own `fullUrl`s.** Metriport resolves its relationships correctly, but emits them in a form FHIR cannot match: entries carry `urn:uuid:` fullUrls while references to them are relative.\n\n```\nfullUrl: urn:uuid:3ca5e8d2-7c84-45ab-91e7-834f8becde12\nreference: Location/3ca5e8d2-7c84-45ab-91e7-834f8becde12\n```\n\nA transaction resolves an internal reference by matching it against `fullUrl` verbatim, and a relative reference does not match a `urn:uuid:` one — Medplum would read it as a reference to a *Medplum* Location with that id, which does not exist. Rewriting the reference to the entry's `fullUrl` closes the gap while keeping Metriport's identity. This is also why the result is a `transaction` and not a `batch`: `urn:uuid` resolution is a transaction feature.\n\n**`meta` is stripped from every resource.** Medplum's `meta.accounts` is inherited from the compartment of the Patient a resource references, but specifying `meta` at all on a create or update replaces those inherited accounts instead of adding to them. Metriport's Encounter arrives with a `meta`, so it is removed. `resource.id` is dropped too, for a separate reason: Medplum assigns identity, and the entry's `fullUrl` already carries the local identity the transaction needs.\n\n**Two entries are synthesised.** An `Organization` named *Metriport Realtime Monitoring*, created with `ifNoneExist` so an existing one is reused rather than overwritten; and a `Provenance` recording the import — what it created, when, which Metriport bundle it came from, and which ADT event triggered it (`patient.admit` → `A01`, `patient.transfer` → `A02`, `patient.discharge` → `A03`).\n\n`extensions/metriport/actions/webhookBundle/bundle/transform.test.ts` asserts the complete output for a real `patient.admit` bundle, if you want to see the whole before/after in one place.\n\n### Wiring it into a care flow\n\n1. **Realtime Update** webhook fires and emits `bundleUrl` and `eventType`.\n2. **Get Webhook Bundle** — pass `bundleUrl` to `url` and `eventType` to `eventType`. Run this early; the URL expires after 10 minutes.\n3. Medplum **Find or create resource** — pass the `transactionBundle` data point to its `resourceJson` field. No changes to that action are needed; it detects a Bundle and executes it.\n\n**PREREQUISITE: for imported resources to be tagged with the Metriport organization, the Medplum Patient must already carry it in `meta.accounts` before the notification arrives.** Resources created without a `meta` inherit their accounts from the compartment of the Patient they reference, so tagging the Patient once causes every subsequent import to inherit it automatically. Note that this only covers resources *in* the patient compartment — `Location` and `Practitioner` are shared directory resources and are intentionally created untagged, since scoping a hospital or a physician to one patient's tenant would be wrong.\n\n**NOTE: the conditional Patient reference only resolves if your Medplum Patients carry an identifier under the `https://awellhealth.com/patients` system with the Awell patient id as its value. A conditional reference that matches no Patient fails the whole transaction.**\n\n### When the transaction bundle is omitted\n\n`Get Webhook Bundle` serves several Metriport webhook types and only ADT notifications carry encounter bundles. For any payload that is not a `collection` bundle, `transactionBundle` is simply omitted and `bundle` is emitted on its own — the action still succeeds.\n\nA `collection` bundle that is missing its Patient or Encounter entry is treated differently: that is an encounter bundle which does not describe an encounter, so the action **fails** rather than silently emitting a partial result.\n\n## Store Webhook Bundle\n\nFetches the FHIR bundle from a Metriport webhook payload URL like **Get Webhook Bundle**, but stores it and returns references to it instead of the bundle. Use it when a bundle can be too large to pass between care flow steps: a discharge summary can be larger than the 5 MiB limit on messages inside Awell, which the `bundle` and `transactionBundle` data points of **Get Webhook Bundle** would then hit.\n\nIt takes the same fields as **Get Webhook Bundle**: `url`, `eventType` and `provenanceReason`.\n\n| Data point | Type | Description |\n| --- | --- | --- |\n| `bundleRef` | string | Reference to the stored bundle, exactly as Metriport sent it. |\n| `transactionBundleRef` | string | Reference to the stored executable FHIR transaction (see \"Building the transaction bundle\" above). Omitted when the payload is not a Patient Encounter Bundle. |\n| `encounterId` | string | Metriport's UUID for the Encounter in the bundle. Omitted when the bundle carries no Encounter. |\n| `reasonForVisit` … `dischargeSummaryCoverage` | string / json | The discharge summary fields, only for a `patient.discharge-summary` bundle, exactly as **Get Webhook Bundle** returns them (see \"Discharge summary fields\" above). They are small, so they travel as plain data points even though the bundle itself is stored. |\n\nA reference is opaque: pass it on, do not build or parse one. Stored bundles are named after the activity, so a retried action replaces what the failed attempt stored. The action cannot be previewed.\n\n**NOTE: Metriport pre-signed URLs are only valid for 10 minutes, so this action should run early in the care flow, shortly after the realtime update webhook fires.**\n\n### Wiring it into a care flow\n\n1. **Realtime Update** webhook fires and emits `bundleUrl` and `eventType`.\n2. **Store Webhook Bundle** — pass `bundleUrl` to `url` and `eventType` to `eventType`.\n3. Medplum **Execute stored bundle** — pass the `transactionBundleRef` data point to its `bundleRef` field.\n\n**If the Medplum bots that sync Tasks should link them to the Encounter**, map this action's `encounterId` data point to the care flow's baseline `encounter_id` data point. The bots read `encounter_id` from the baseline data points, and the mapping belongs to the action in the care flow, so a flow that moves from **Get Webhook Bundle** to this action needs it set again. `encounterId` itself is the same value in both.\n\n# Webhooks\n\n## Realtime Update\n\nAn enrollment trigger that starts a care flow when Metriport sends a [real-time patient notification](https://docs.metriport.com/medical-api/handling-data/realtime-patient-notifications).\n\nMetriport POSTs every notification type to the same endpoint. Four of them share one payload shape — a `meta` envelope plus a `payload` pointing at a pre-signed bundle URL — and this webhook enrolls a patient on all four:\n\n- `patient.admit` (HL7 ADT^A01)\n- `patient.discharge` (HL7 ADT^A03)\n- `patient.transfer` (HL7 ADT^A02)\n- `patient.discharge-summary`\n\nThe `eventType` data point carries the raw Metriport webhook type, so a care flow can branch on it. The payload's `url` is a pre-signed link to the [FHIR Encounter Bundle](https://docs.metriport.com/medical-api/handling-data/patient-encounter-bundle).\n\nThe webhook validates the request, emits the data points (including the pre-signed bundle URL on `bundleUrl`), and replies immediately — it does **not** download the bundle. Fetch the bundle later in the care flow with the **Get Webhook Bundle** action, using the `bundleUrl` data point. Because the URL expires after 10 minutes, run that action early.\n\nAny other notification type Metriport sends — `medical.document-download`, `medical.consolidated-data`, and anything added in future — is acknowledged with a `200` and does not enroll a patient. A notification whose type *is* handled but whose payload is malformed fails loudly instead, so a genuine integration problem is not mistaken for an event we chose to ignore. Metriport [verification `ping` messages](https://docs.metriport.com/medical-api/getting-started/webhooks#the-ping-message) are answered with a `200` that echoes the ping value back as `pong: <value>`.\n\n### Data points\n\n| Data point | Type | Description |\n| --- | --- | --- |\n| `eventType` | string | The Metriport webhook type: `patient.admit`, `patient.discharge`, `patient.transfer` or `patient.discharge-summary` |\n| `metriportPatientId` | string | The Metriport patient ID (also used as the patient identifier for enrollment) |\n| `externalId` | string | Your external patient ID, if provided to Metriport |\n| `when` | date | When the event occurred — the admit time on an admit event, the discharge time on a discharge event |\n| `messageId` | string | The Metriport message ID for the notification |\n| `bundleUrl` | string | Pre-signed URL to the FHIR bundle; fetch it with the **Get Webhook Bundle** action (valid for 10 minutes) |\n\n### Verifying incoming requests\n\nOptionally set the **Webhook Key** setting to the webhook key from the Metriport dashboard (Settings/Developers tab). Metriport [authenticates each webhook](https://docs.metriport.com/medical-api/getting-started/webhooks#authentication) with an HMAC-SHA256 signature of the raw request body, keyed with your webhook key and sent in the `x-metriport-signature` header. When the setting is populated, the webhook recomputes the HMAC over the raw body and rejects any request whose signature is missing or does not match (`401`). When left empty, requests are not verified.\n\n## More Info\n\nFor more information on how to integrate with Metriport please visit our [Medical API docs](https://docs.metriport.com/medical-api/getting-started/quickstart)\n",
164
- "changelog": "# Metriport changelog\n\n## October 2026\n\n- `Get Webhook Bundle` and `Store Webhook Bundle` now lift the discharge summary fields out of a `patient.discharge-summary` bundle and return them as plain data points: `reasonForVisit`, `visitDiagnosis`, `planOfTreatment`, `procedures`, `procedureNote`, `dischargeDisposition`, `dischargeDispositionCode` and `dischargeInstructions`, plus `dischargeSummaryCoverage` (json) saying which document type it was and which fields it yielded. The fields are read from the resources the Composition's sections point at, relative to the encounter the Composition is about, since the sections themselves carry title-only narratives; notes are decoded from `DiagnosticReport.presentedForm` to plain text. All are omitted for any other bundle, and each is omitted when the document lacks it. Built for the common document shapes seen from two source EHR families (see the README for the exact mapping).\n- Add `Store Webhook Bundle` action: fetches the FHIR bundle from a Metriport webhook payload URL like `Get Webhook Bundle`, but stores the bundle and its importable transaction rewrite and returns references to them (`bundleRef`, `transactionBundleRef`) instead of the bundles, so a bundle larger than the 5 MiB limit on messages inside Awell, such as a discharge summary, no longer blocks the care flow. Pair it with the Medplum `Execute stored bundle` action. `Get Webhook Bundle` is unchanged.\n- A bundle download is now limited to 100 MB and 60 seconds (it had neither limit), for `Get Webhook Bundle`, `Store Webhook Bundle` and the `metriportAdt` endpoint. A larger bundle now fails with a clear error instead of exhausting the memory of the pod that runs every tenant's jobs.\n\n## September 2026\n\n- Add the `metriportAdt` ingestion endpoint (`source: 'webhook'`): receives Metriport real-time notifications, handles `patient.admit`, `patient.transfer`, `patient.discharge` and `patient.discharge-summary`, downloads the FHIR bundle each points at, and saves one encounter per visit (the patient is created by identifier resolution; demographics are not written yet), so admit, transfer, discharge and the summary converge on the same encounter. Publishes `patient.admitted` / `patient.transferred` / `patient.discharged` / `discharge.summary-received` for care flows and `fhir.bundle-received` for FHIR data movement. Any other notification type is acknowledged without producing a record; HMAC-SHA256 signature verification (with the ping answered by `pong`) is implemented but switched off for the pre-release. The extension now declares `identifier.system` (`https://metriport.com`).\n- Add `Enroll in Monitoring` action: creates a Patient and enrolls them in real-time monitoring in one step. It takes the same Patient details as `Create Patient` but a **Cohort Name** instead of a Facility ID; by convention a Cohort and its Facility share a name, so both are resolved from that one input. Facility and Cohort lists are cached in memory for 24 hours per API credential, refreshing early (at most once a minute) when a name is not found.\n- **Breaking: remove the `Cohort` field from `Create Patient` and `Update Patient`.** Real-time monitoring enrollment now lives on `Enroll in Monitoring`; care flows that passed a cohort ID to `Create Patient` should switch to the new action.\n\n## August 2026\n\n- Rename the `enrollment` webhook to `realtimeUpdate`. The old name described what Awell does with the notification rather than what Metriport sends, which read confusingly next to the genuine enrolment concepts (the `Cohort` field, enrolling a patient into a care flow). Behaviour is unchanged. **Breaking: the webhook endpoint URL changes, so any webhook already configured in the Metriport dashboard must be repointed.**\n- `Date of Birth` on the `Create Patient` and `Update Patient` actions is now a date field rather than a free-text string, so care flows can map a date onto it directly instead of hand-formatting `YYYY-MM-DD`. The value is normalised to the date-only string Metriport expects, so care flows already passing `YYYY-MM-DD` are unaffected.\n\n## July 2026\n\n- Add `enrollment` webhook: an enrollment trigger for Metriport real-time patient notifications. The `eventType` data point carries the Metriport webhook type (`patient.admit` or `patient.discharge-summary`) so care flows can distinguish on it. The webhook validates and replies immediately, emitting the pre-signed FHIR bundle URL on the `bundleUrl` data point rather than downloading the bundle inline.\n- Add `Get Webhook Bundle` action: fetches the FHIR bundle from a Metriport webhook payload URL (the webhook's `bundleUrl`), for use later in the care flow.\n- Add optional `Webhook Key` setting used to verify incoming webhook requests via Metriport's HMAC-SHA256 signature (`x-metriport-signature` header), computed over the raw request body.\n"
163
+ "readme": "---\ntitle: Metriport\ndescription: Metriport is Plaid for healthcare data.\n---\n# Metriport\n\nMetriport is Plaid for healthcare data. We help digital health companies access and manage patient health and medical data, through an open-source and universal API.\n\nThrough a single integration, our API enables modern health companies to get the comprehensive patient data they need from both HIEs and EHRs, as well as popular wearable devices.\n\nAs a developer-first interoperability solution, Metriport is powering the next wave of innovative companies, accelerating a revolution in digital health.\n\nTo learn more visit [https://www.metriport.com/](https://www.metriport.com/)\n# Extension settings\n\nIn order to set up this extension, **you will need to provide a Metriport API key**. You can obtain an API key via the Metriport dashboard by selecting the `Developers tab`. To learn more on how to get started with Metriport visit our [quick start docs](https://docs.metriport.com/medical-api/getting-started/quickstart) for our Medical API. Also, to better understand how our API keys work check out the [API Keys section](https://docs.metriport.com/home/api-info/api-keys) of our docs as well.\n\n# Ingestion\n\n## Metriport ADT notifications (`metriportAdt`)\n\nAn ingestion endpoint for Metriport's [real-time patient notifications](https://docs.metriport.com/medical-api/handling-data/realtime-patient-notifications). Point the webhook URL in the Metriport dashboard at it. Request verification (Metriport's HMAC-SHA256 `x-metriport-signature`, with the verification ping answered by `pong`) is implemented but switched off for the pre-release; it will be enabled, and the **Webhook Key** setting required, before general availability.\n\nHandled notification types are `patient.admit`, `patient.transfer`, `patient.discharge` and `patient.discharge-summary`. For each, the FHIR bundle behind the pre-signed `payload.url` is downloaded and the patient is resolved on `payload.externalId` (the id you gave Metriport when creating the patient, i.e. your own MRN). The endpoint saves one encounter keyed on the visit number (the patient itself is created by that resolution; demographics are not written yet), so all four notifications about one visit update the same encounter (`in-progress` until the discharge, `finished` after it, with the last transfer destination as its location). Any other notification type is acknowledged and produces nothing.\n\nEvents published, for care flows to trigger on: `patient.admitted`, `patient.transferred`, `patient.discharged` and `discharge.summary-received` (on a discharge summary). Every handled notification also publishes `fhir.bundle-received`, which FHIR data movement listens for; it carries no clinical data, the bundle is looked up by ingestion id.\n\n# Custom Actions\n\n**GENERAL NOTE: Make sure to create Organizations and Facilities in Metriport before using this extension. A Patient must be associated with a Facility by providing the facilityId when stated in the actions.**\n\n## Create Patient\n\nCreates a Patient in Metriport for the specified Facility where the Patient is receiving care. The Patient is not enrolled in real-time monitoring; use **Enroll in Monitoring** for that.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/patient/create-patient) for more info.\n\n## Enroll in Monitoring\n\nCreates a Patient in Metriport and enrolls them in real-time monitoring in one step. It takes the same Patient details as **Create Patient**, but instead of a Facility ID it takes a **Cohort Name**. By convention a Cohort and the Facility its Patients receive care at share the same name, so the action looks both up by that name: the Patient is created in the matching Facility and added to the matching Cohort.\n\nNames are matched case-insensitively, ignoring surrounding whitespace, and must identify exactly one Cohort and exactly one Facility. Both lists are cached in memory for 24 hours; a name that is not in the cached list triggers an early refresh (at most once a minute) before the action fails, so a Cohort or Facility created recently is still found.\n\nNote that enrolling a Patient in real-time monitoring has downstream consequences: once you start receiving updates about the Patient, you are expected to contribute data back to Metriport.\n\nVisit the endpoint docs for [create patient](https://docs.metriport.com/medical-api/api-reference/patient/create-patient), [list facilities](https://docs.metriport.com/medical-api/api-reference/facility/list-facilities) and [list cohorts](https://docs.metriport.com/medical-api/api-reference/cohort/list-cohorts) for more info.\n\n## Update Patient\n\nUpdates the specified Patient.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/patient/update-patient) for more info.\n\n## Get Patient\n\nRetrieves the specified Patient.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/patient/get-patient) for more info.\n\n## Remove Patient\n\nRemoves a Patient at Metriport and at HIEs the Patient is linked to.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/patient/delete-patient) for more info.\n\n## List Documents\n\nLists all Documents that can be retrieved for a Patient.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/document/list-documents) for more info.\n\n**NOTE: It also returns the status of querying Document references across HIEs, indicating whether there is an asynchronous query in progress (status processing) or not (status completed). If the query is in progress, you will also receive the total number of Documents to be queried as well as the ones that have already been completed.**\n\n## Query Documents\n\nTriggers a Document query for the specified Patient across HIEs.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/document/start-document-query) for more info.\n\n**NOTE: When executed, this endpoint triggers an asynchronous Document query with HIEs and immediately returns the status of Document query, processing .**\n\n## Get Document Url\n\nGets a presigned URL for downloading the specified Document.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/document/get-document) for more info.\n\n**NOTE: This endpoint returns a URL which you can use to download the specified Document using the file name provided from the List Documents endpoint.**\n\n## Get Facility by Name\n\nGets the Facility with the given name, so a care flow can resolve a human-readable Facility name into the `facilityId` that the Patient and Document actions require.\n\nMetriport has no endpoint to filter Facilities by name, so this action lists all Facilities in your Organization and matches in memory. The name is matched case-insensitively and ignoring surrounding whitespace, and must match **exactly one** Facility: the action errors if no Facility matches, and also if several do, rather than guessing which one was meant.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/facility/list-facilities) for more info.\n\n| Field | Type | Description |\n| --- | --- | --- |\n| `facilityName` | string | The name of the Facility to look up. Matched case-insensitively, ignoring surrounding whitespace, and must match exactly one Facility in your Organization. |\n\nThe data points mirror the Facility object Metriport returns from [Get Facility](https://docs.metriport.com/medical-api/api-reference/facility/get-facility), one data point per response field:\n\n| Data point | Type | Metriport field | Description |\n| --- | --- | --- | --- |\n| `facilityId` | string | `id` | Metriport's UUID for the Facility. This is the `facilityId` the Patient and Document actions take. |\n| `facilityName` | string | `name` | The Facility name, as stored at Metriport — the canonical casing and spacing, not the name that was searched for. |\n| `npi` | string | `npi` | The Facility's National Provider Identifier. |\n| `tin` | string | `tin` | The Facility's Taxpayer Identification Number. Optional at Metriport; left unset when absent. |\n| `active` | boolean | `active` | Whether the Facility is active. Optional at Metriport; left unset when absent. |\n| `addressLine1` | string | `address.addressLine1` | Street address line 1. |\n| `addressLine2` | string | `address.addressLine2` | Street address line 2. Optional; left unset when absent. |\n| `city` | string | `address.city` | Address city. |\n| `state` | string | `address.state` | Two-letter US state or territory code. |\n| `zip` | string | `address.zip` | Address ZIP code. |\n| `country` | string | `address.country` | Address country — always `USA` at Metriport today. Left unset when absent. |\n\n## Remove Patient from Cohort\n\nRemoves the specified Patient from a cohort.\n\nVisit [endpoint docs](https://docs.metriport.com/medical-api/api-reference/cohort/remove-patients-from-cohort) for more info.\n\n## Get Webhook Bundle\n\nFetches the FHIR bundle from a Metriport webhook payload URL — e.g. the [Encounter Bundle](https://docs.metriport.com/medical-api/handling-data/patient-encounter-bundle) from an ADT notification, or a discharge summary. Pass the `bundleUrl` data point emitted by the **Realtime Update** webhook; the action downloads the bundle and returns it on the `bundle` data point.\n\nWhen the payload is a Patient Encounter Bundle, the action also rewrites it into an executable FHIR transaction and returns that on the `transactionBundle` data point, ready to hand to the Medplum **Find or create resource** action.\n\nThe Encounter's Metriport id is returned separately on the `encounterId` data point, so a later step can address the imported Encounter without re-parsing the bundle.\n\n**NOTE: Metriport pre-signed URLs are only valid for 10 minutes, so this action should run early in the care flow, shortly after the realtime update webhook fires.**\n\n| Field | Type | Description |\n| --- | --- | --- |\n| `url` | string | The pre-signed payload URL to fetch (the webhook's `bundleUrl` data point). |\n| `eventType` | string (optional) | The Metriport notification type — wire this from the realtime update webhook's `eventType` data point. Recorded on the import Provenance so admit, transfer and discharge can be told apart. |\n| `provenanceReason` | text (optional) | Free-text reason recorded on the import Provenance, describing why the data was imported. |\n\n| Data point | Type | Description |\n| --- | --- | --- |\n| `bundle` | json | The FHIR bundle fetched from the URL, exactly as Metriport sent it. |\n| `transactionBundle` | json | The same data rewritten as an executable FHIR transaction. Omitted when the payload is not a Patient Encounter Bundle. |\n| `encounterId` | string | Metriport's UUID for the Encounter in the bundle. Resolve the imported Encounter in Medplum with `Encounter?identifier=https://metriport.com/fhir/encounter\\|<encounterId>`. Omitted when the bundle carries no Encounter. |\n| `reasonForVisit` … `dischargeSummaryCoverage` | string / json | The discharge summary fields, only for a `patient.discharge-summary` bundle. See \"Discharge summary fields\" below. |\n\n### Discharge summary fields\n\nA `patient.discharge-summary` bundle is Metriport's FHIR conversion of the HIE's discharge summary document: one `Composition` plus the patient's encounter history and the clinical resources the document references. The Composition's sections carry title-only narratives, so there is no text to read off them; the content lives in the resources each section points at. Both bundle actions lift the fields a care team asks for out of those resources and return them as plain data points, so a care flow, Panels or an analytics export can use them without parsing the bundle. For any other bundle the fields are all omitted.\n\nEvery field is read relative to the encounter the Composition is about (`Composition.encounter`), **not** the first Encounter in the bundle, which is just the patient's oldest visit. Each is omitted, never empty, when the document does not carry it.\n\n| Data point | Type | Where it comes from |\n| --- | --- | --- |\n| `reasonForVisit` | string | The encounter's `reasonCode` texts, `; `-separated. |\n| `visitDiagnosis` | string | The encounter's diagnoses as `<text> (<ICD-10-CM code>)`, `; `-separated, from `Encounter.diagnosis`, else from the Conditions categorised `encounter-diagnosis` that point at the encounter. |\n| `planOfTreatment` | string | The CarePlans in the Plan of care section (LOINC `18776-5`): description, then one line per activity. |\n| `procedures` | string | The Procedures in the Procedures section (`47519-4`) as `<name> (<date>)`, `; `-separated. |\n| `procedureNote` | string | The notes those Procedures report to (`Procedure.report`), each headed by the report's name. The source files these under Results rather than in a section of their own. |\n| `dischargeDisposition` | string | `Encounter.hospitalization.dischargeDisposition` as text. |\n| `dischargeDispositionCode` | string | The same, as its code (`home`, `snf`, `rehab`, …, from `http://terminology.hl7.org/CodeSystem/discharge-disposition`). |\n| `dischargeInstructions` | string | The note in the Hospital discharge instructions section (`8653-8`), else in the Discharge instructions document section (`74213-0`). |\n| `dischargeSummaryCoverage` | json | `{ documentType, documentTypeText, sections, fields }`: the Composition's LOINC type, the section codes it carried, and which of the fields above were found. Lets coverage be measured instead of guessed. |\n\nNotes are carried as base64 `DiagnosticReport.presentedForm` attachments, `text/html` or `text/plain` depending on the source EHR. HTML is reduced to plain text (paragraphs and breaks become line breaks, tags and entities are dropped or decoded); anything that is not `text/*`, such as a PDF, yields nothing. A single field is capped at 100,000 characters, far above any note seen, purely so a pathological document cannot push the activity result over the message size limit.\n\nThis is built against the documents seen from two source EHR families, keyed on section LOINC codes because the titles differ between them (\"Plan of Treatment\" in one, \"Treatment Plan\" in the other). It targets the common pattern, not every variant: a document that files a field somewhere else simply does not yield it, and `dischargeSummaryCoverage` says so.\n\n### Building the transaction bundle\n\nMetriport delivers a bundle of `type: 'collection'`, which is **not executable**. Handing it straight to Medplum does nothing useful: no entry carries `request` metadata saying what to do with it, and every internal reference points at a Metriport UUID that means nothing in Medplum. The action therefore builds a second, executable bundle rather than passing the original through.\n\nThe transformation is a pure function with no Medplum access of its own — this extension holds Metriport credentials only. That rules out reading Medplum to reconcile against what is already there, so every lookup is expressed declaratively and resolved by the server when the transaction executes.\n\n**The Patient is never written.** Awell/Medplum is the source of truth for patient demographics, so the Patient entry is dropped entirely and every reference to it becomes a conditional reference:\n\n```\nPatient?identifier=https://awellhealth.com/patients|<awell patient id>\n```\n\nOmitting the entry guarantees structurally that a Metriport ADT feed can never overwrite the patient record.\n\n**Everything else is written idempotently.** Each Metriport resource is stamped with an identifier derived from its Metriport id and written with a conditional update:\n\n```\nidentifier: { system: 'https://metriport.com/fhir/encounter', value: '<metriport id>' }\nrequest: PUT Encounter?identifier=https://metriport.com/fhir/encounter|<metriport id>\n```\n\nA conditional update creates on zero matches and updates on one, so a redelivered notification updates in place instead of duplicating Conditions, Observations, Practitioners and Locations — and the admit and discharge notifications for one visit converge on a single Encounter. Existing identifiers are kept, so the Encounter keeps its HL7 `VN` visit number alongside ours.\n\n**References are rewritten to Metriport's own `fullUrl`s.** Metriport resolves its relationships correctly, but emits them in a form FHIR cannot match: entries carry `urn:uuid:` fullUrls while references to them are relative.\n\n```\nfullUrl: urn:uuid:3ca5e8d2-7c84-45ab-91e7-834f8becde12\nreference: Location/3ca5e8d2-7c84-45ab-91e7-834f8becde12\n```\n\nA transaction resolves an internal reference by matching it against `fullUrl` verbatim, and a relative reference does not match a `urn:uuid:` one — Medplum would read it as a reference to a *Medplum* Location with that id, which does not exist. Rewriting the reference to the entry's `fullUrl` closes the gap while keeping Metriport's identity. This is also why the result is a `transaction` and not a `batch`: `urn:uuid` resolution is a transaction feature.\n\n**`meta` is stripped from every resource.** Medplum's `meta.accounts` is inherited from the compartment of the Patient a resource references, but specifying `meta` at all on a create or update replaces those inherited accounts instead of adding to them. Metriport's Encounter arrives with a `meta`, so it is removed. `resource.id` is dropped too, for a separate reason: Medplum assigns identity, and the entry's `fullUrl` already carries the local identity the transaction needs.\n\n**Two entries are synthesised.** An `Organization` named *Metriport Realtime Monitoring*, created with `ifNoneExist` so an existing one is reused rather than overwritten; and a `Provenance` recording the import — what it created, when, which Metriport bundle it came from, and which ADT event triggered it (`patient.admit` → `A01`, `patient.transfer` → `A02`, `patient.discharge` → `A03`).\n\n`extensions/metriport/actions/webhookBundle/bundle/transform.test.ts` asserts the complete output for a real `patient.admit` bundle, if you want to see the whole before/after in one place.\n\n### Wiring it into a care flow\n\n1. **Realtime Update** webhook fires and emits `bundleUrl` and `eventType`.\n2. **Get Webhook Bundle** — pass `bundleUrl` to `url` and `eventType` to `eventType`. Run this early; the URL expires after 10 minutes.\n3. Medplum **Find or create resource** — pass the `transactionBundle` data point to its `resourceJson` field. No changes to that action are needed; it detects a Bundle and executes it.\n\n**PREREQUISITE: for imported resources to be tagged with the Metriport organization, the Medplum Patient must already carry it in `meta.accounts` before the notification arrives.** Resources created without a `meta` inherit their accounts from the compartment of the Patient they reference, so tagging the Patient once causes every subsequent import to inherit it automatically. Note that this only covers resources *in* the patient compartment — `Location` and `Practitioner` are shared directory resources and are intentionally created untagged, since scoping a hospital or a physician to one patient's tenant would be wrong.\n\n**NOTE: the conditional Patient reference only resolves if your Medplum Patients carry an identifier under the `https://awellhealth.com/patients` system with the Awell patient id as its value. A conditional reference that matches no Patient fails the whole transaction.**\n\n### When the transaction bundle is omitted\n\n`Get Webhook Bundle` serves several Metriport webhook types and only ADT notifications carry encounter bundles. For any payload that is not a `collection` bundle, `transactionBundle` is simply omitted and `bundle` is emitted on its own — the action still succeeds.\n\nA `collection` bundle that is missing its Patient or Encounter entry is treated differently: that is an encounter bundle which does not describe an encounter, so the action **fails** rather than silently emitting a partial result.\n\n## Store Webhook Bundle\n\nFetches the FHIR bundle from a Metriport webhook payload URL like **Get Webhook Bundle**, but stores it and returns references to it instead of the bundle. Use it when a bundle can be too large to pass between care flow steps: a discharge summary can be larger than the 5 MiB limit on messages inside Awell, which the `bundle` and `transactionBundle` data points of **Get Webhook Bundle** would then hit.\n\nIt takes the same fields as **Get Webhook Bundle**: `url`, `eventType` and `provenanceReason`.\n\n| Data point | Type | Description |\n| --- | --- | --- |\n| `bundleRef` | string | Reference to the stored bundle, exactly as Metriport sent it. |\n| `transactionBundleRef` | string | Reference to the stored executable FHIR transaction (see \"Building the transaction bundle\" above). Omitted when the payload is not a Patient Encounter Bundle. |\n| `encounterId` | string | Metriport's UUID for the Encounter in the bundle. Omitted when the bundle carries no Encounter. |\n| `admissionDatetime` | date | The Encounter's `period.start`. |\n| `dischargeDatetime` | date | The Encounter's `period.end`; absent while the patient is still admitted. |\n| `encounterClass` | string | The Encounter's `class.display`, e.g. \"Ambulatory\". When the class is missing or \"unknown\", the `encounterType` value instead. |\n| `encounterType` | string | The first `type[].text` containing \"Inpatient\", \"Ambulatory\" or \"Emergency\", ignoring case. |\n| `encounterLocation` | string | The Encounter's `location[0].location.display`. |\n| `encounterReason` | string | The first `reasonCode` text. |\n| `encounterDiagnoses` | strings_array | The display text of every `diagnosis` condition, falling back to the Condition's code text when the reference has no display. |\n| `reasonForVisit` … `dischargeSummaryCoverage` | string / json | The discharge summary fields, only for a `patient.discharge-summary` bundle, exactly as **Get Webhook Bundle** returns them (see \"Discharge summary fields\" above). They are small, so they travel as plain data points even though the bundle itself is stored. |\n\nThe Encounter fields, `admissionDatetime` through `encounterDiagnoses`, are each omitted when the Encounter does not carry them, and all are omitted when `eventType` is `patient.discharge-summary`, which returns the discharge summary fields instead.\n\nA reference is opaque: pass it on, do not build or parse one. Stored bundles are named after the activity, so a retried action replaces what the failed attempt stored. The action cannot be previewed.\n\n**NOTE: Metriport pre-signed URLs are only valid for 10 minutes, so this action should run early in the care flow, shortly after the realtime update webhook fires.**\n\n### Wiring it into a care flow\n\n1. **Realtime Update** webhook fires and emits `bundleUrl` and `eventType`.\n2. **Store Webhook Bundle** — pass `bundleUrl` to `url` and `eventType` to `eventType`.\n3. Medplum **Execute stored bundle** — pass the `transactionBundleRef` data point to its `bundleRef` field.\n\n**If the Medplum bots that sync Tasks should link them to the Encounter**, map this action's `encounterId` data point to the care flow's baseline `encounter_id` data point. The bots read `encounter_id` from the baseline data points, and the mapping belongs to the action in the care flow, so a flow that moves from **Get Webhook Bundle** to this action needs it set again. `encounterId` itself is the same value in both.\n\n# Webhooks\n\n## Realtime Update\n\nAn enrollment trigger that starts a care flow when Metriport sends a [real-time patient notification](https://docs.metriport.com/medical-api/handling-data/realtime-patient-notifications).\n\nMetriport POSTs every notification type to the same endpoint. Four of them share one payload shape — a `meta` envelope plus a `payload` pointing at a pre-signed bundle URL — and this webhook enrolls a patient on all four:\n\n- `patient.admit` (HL7 ADT^A01)\n- `patient.discharge` (HL7 ADT^A03)\n- `patient.transfer` (HL7 ADT^A02)\n- `patient.discharge-summary`\n\nThe `eventType` data point carries the raw Metriport webhook type, so a care flow can branch on it. The payload's `url` is a pre-signed link to the [FHIR Encounter Bundle](https://docs.metriport.com/medical-api/handling-data/patient-encounter-bundle).\n\nThe webhook validates the request, emits the data points (including the pre-signed bundle URL on `bundleUrl`), and replies immediately — it does **not** download the bundle. Fetch the bundle later in the care flow with the **Get Webhook Bundle** action, using the `bundleUrl` data point. Because the URL expires after 10 minutes, run that action early.\n\nAny other notification type Metriport sends — `medical.document-download`, `medical.consolidated-data`, and anything added in future — is acknowledged with a `200` and does not enroll a patient. A notification whose type *is* handled but whose payload is malformed fails loudly instead, so a genuine integration problem is not mistaken for an event we chose to ignore. Metriport [verification `ping` messages](https://docs.metriport.com/medical-api/getting-started/webhooks#the-ping-message) are answered with a `200` that echoes the ping value back as `pong: <value>`.\n\n### Data points\n\n| Data point | Type | Description |\n| --- | --- | --- |\n| `eventType` | string | The Metriport webhook type: `patient.admit`, `patient.discharge`, `patient.transfer` or `patient.discharge-summary` |\n| `metriportPatientId` | string | The Metriport patient ID (also used as the patient identifier for enrollment) |\n| `externalId` | string | Your external patient ID, if provided to Metriport |\n| `when` | date | When the event occurred — the admit time on an admit event, the discharge time on a discharge event |\n| `messageId` | string | The Metriport message ID for the notification |\n| `bundleUrl` | string | Pre-signed URL to the FHIR bundle; fetch it with the **Get Webhook Bundle** action (valid for 10 minutes) |\n\n### Verifying incoming requests\n\nOptionally set the **Webhook Key** setting to the webhook key from the Metriport dashboard (Settings/Developers tab). Metriport [authenticates each webhook](https://docs.metriport.com/medical-api/getting-started/webhooks#authentication) with an HMAC-SHA256 signature of the raw request body, keyed with your webhook key and sent in the `x-metriport-signature` header. When the setting is populated, the webhook recomputes the HMAC over the raw body and rejects any request whose signature is missing or does not match (`401`). When left empty, requests are not verified.\n\n## More Info\n\nFor more information on how to integrate with Metriport please visit our [Medical API docs](https://docs.metriport.com/medical-api/getting-started/quickstart)\n",
164
+ "changelog": "# Metriport changelog\n\n## October 2026\n\n- `Store Webhook Bundle` now returns the bundle's Encounter fields as data points: `admissionDatetime` and `dischargeDatetime` (date), `encounterClass`, `encounterType`, `encounterLocation`, `encounterReason` (string) and `encounterDiagnoses` (strings_array). `encounterClass` falls back to `encounterType` when the class is missing or \"unknown\". Each is omitted when the Encounter lacks it, and all are omitted for a `patient.discharge-summary` event.\n- `Get Webhook Bundle` and `Store Webhook Bundle` now lift the discharge summary fields out of a `patient.discharge-summary` bundle and return them as plain data points: `reasonForVisit`, `visitDiagnosis`, `planOfTreatment`, `procedures`, `procedureNote`, `dischargeDisposition`, `dischargeDispositionCode` and `dischargeInstructions`, plus `dischargeSummaryCoverage` (json) saying which document type it was and which fields it yielded. The fields are read from the resources the Composition's sections point at, relative to the encounter the Composition is about, since the sections themselves carry title-only narratives; notes are decoded from `DiagnosticReport.presentedForm` to plain text. All are omitted for any other bundle, and each is omitted when the document lacks it. Built for the common document shapes seen from two source EHR families (see the README for the exact mapping).\n- Add `Store Webhook Bundle` action: fetches the FHIR bundle from a Metriport webhook payload URL like `Get Webhook Bundle`, but stores the bundle and its importable transaction rewrite and returns references to them (`bundleRef`, `transactionBundleRef`) instead of the bundles, so a bundle larger than the 5 MiB limit on messages inside Awell, such as a discharge summary, no longer blocks the care flow. Pair it with the Medplum `Execute stored bundle` action. `Get Webhook Bundle` is unchanged.\n- A bundle download is now limited to 100 MB and 60 seconds (it had neither limit), for `Get Webhook Bundle`, `Store Webhook Bundle` and the `metriportAdt` endpoint. A larger bundle now fails with a clear error instead of exhausting the memory of the pod that runs every tenant's jobs.\n\n## September 2026\n\n- Add the `metriportAdt` ingestion endpoint (`source: 'webhook'`): receives Metriport real-time notifications, handles `patient.admit`, `patient.transfer`, `patient.discharge` and `patient.discharge-summary`, downloads the FHIR bundle each points at, and saves one encounter per visit (the patient is created by identifier resolution; demographics are not written yet), so admit, transfer, discharge and the summary converge on the same encounter. Publishes `patient.admitted` / `patient.transferred` / `patient.discharged` / `discharge.summary-received` for care flows and `fhir.bundle-received` for FHIR data movement. Any other notification type is acknowledged without producing a record; HMAC-SHA256 signature verification (with the ping answered by `pong`) is implemented but switched off for the pre-release. The extension now declares `identifier.system` (`https://metriport.com`).\n- Add `Enroll in Monitoring` action: creates a Patient and enrolls them in real-time monitoring in one step. It takes the same Patient details as `Create Patient` but a **Cohort Name** instead of a Facility ID; by convention a Cohort and its Facility share a name, so both are resolved from that one input. Facility and Cohort lists are cached in memory for 24 hours per API credential, refreshing early (at most once a minute) when a name is not found.\n- **Breaking: remove the `Cohort` field from `Create Patient` and `Update Patient`.** Real-time monitoring enrollment now lives on `Enroll in Monitoring`; care flows that passed a cohort ID to `Create Patient` should switch to the new action.\n\n## August 2026\n\n- Rename the `enrollment` webhook to `realtimeUpdate`. The old name described what Awell does with the notification rather than what Metriport sends, which read confusingly next to the genuine enrolment concepts (the `Cohort` field, enrolling a patient into a care flow). Behaviour is unchanged. **Breaking: the webhook endpoint URL changes, so any webhook already configured in the Metriport dashboard must be repointed.**\n- `Date of Birth` on the `Create Patient` and `Update Patient` actions is now a date field rather than a free-text string, so care flows can map a date onto it directly instead of hand-formatting `YYYY-MM-DD`. The value is normalised to the date-only string Metriport expects, so care flows already passing `YYYY-MM-DD` are unaffected.\n\n## July 2026\n\n- Add `enrollment` webhook: an enrollment trigger for Metriport real-time patient notifications. The `eventType` data point carries the Metriport webhook type (`patient.admit` or `patient.discharge-summary`) so care flows can distinguish on it. The webhook validates and replies immediately, emitting the pre-signed FHIR bundle URL on the `bundleUrl` data point rather than downloading the bundle inline.\n- Add `Get Webhook Bundle` action: fetches the FHIR bundle from a Metriport webhook payload URL (the webhook's `bundleUrl`), for use later in the care flow.\n- Add optional `Webhook Key` setting used to verify incoming webhook requests via Metriport's HMAC-SHA256 signature (`x-metriport-signature` header), computed over the raw request body.\n"
165
165
  },
166
166
  "nexuzhealth": {
167
167
  "readme": "---\ntitle: nexuzhealth\ndescription: Demo extension for nexuzhealth\n---\n\nThis is an extension that can only be used for demo purposes.",
@@ -724,7 +724,7 @@ export declare const actions: {
724
724
  description: string;
725
725
  required: false;
726
726
  };
727
- }, "bundleRef" | "reasonForVisit" | "visitDiagnosis" | "planOfTreatment" | "procedures" | "procedureNote" | "dischargeDisposition" | "dischargeDispositionCode" | "dischargeInstructions" | "dischargeSummaryCoverage" | "encounterId" | "transactionBundleRef">;
727
+ }, "bundleRef" | "reasonForVisit" | "visitDiagnosis" | "planOfTreatment" | "procedures" | "procedureNote" | "dischargeDisposition" | "dischargeDispositionCode" | "dischargeInstructions" | "dischargeSummaryCoverage" | "encounterId" | "admissionDatetime" | "dischargeDatetime" | "encounterClass" | "encounterType" | "encounterLocation" | "encounterReason" | "encounterDiagnoses" | "transactionBundleRef">;
728
728
  removePatientFromCohort: import("@awell-health/extensions-core").Action<{
729
729
  cohortId: {
730
730
  id: string;
@@ -56,4 +56,48 @@ export declare const dataPoints: {
56
56
  key: string;
57
57
  valueType: "string";
58
58
  };
59
+ /**
60
+ * `Encounter.period.start`. Omitted, like every Encounter field below, when
61
+ * absent, and for a `patient.discharge-summary` event.
62
+ */
63
+ admissionDatetime: {
64
+ key: string;
65
+ valueType: "date";
66
+ };
67
+ /** `Encounter.period.end`; absent while the patient is still admitted. */
68
+ dischargeDatetime: {
69
+ key: string;
70
+ valueType: "date";
71
+ };
72
+ /**
73
+ * `Encounter.class.display`, e.g. "Ambulatory". When the class is missing or
74
+ * "unknown", the `encounterType` value instead.
75
+ */
76
+ encounterClass: {
77
+ key: string;
78
+ valueType: "string";
79
+ };
80
+ /**
81
+ * The first `Encounter.type` text containing "Inpatient", "Ambulatory" or
82
+ * "Emergency", ignoring case.
83
+ */
84
+ encounterType: {
85
+ key: string;
86
+ valueType: "string";
87
+ };
88
+ /** `Encounter.location[0].location.display`. */
89
+ encounterLocation: {
90
+ key: string;
91
+ valueType: "string";
92
+ };
93
+ /** The first `Encounter.reasonCode` text. */
94
+ encounterReason: {
95
+ key: string;
96
+ valueType: "string";
97
+ };
98
+ /** The display text of every `Encounter.diagnosis` condition. */
99
+ encounterDiagnoses: {
100
+ key: string;
101
+ valueType: "strings_array";
102
+ };
59
103
  };
@@ -24,6 +24,50 @@ exports.dataPoints = {
24
24
  key: 'encounterId',
25
25
  valueType: 'string',
26
26
  },
27
+ /**
28
+ * `Encounter.period.start`. Omitted, like every Encounter field below, when
29
+ * absent, and for a `patient.discharge-summary` event.
30
+ */
31
+ admissionDatetime: {
32
+ key: 'admissionDatetime',
33
+ valueType: 'date',
34
+ },
35
+ /** `Encounter.period.end`; absent while the patient is still admitted. */
36
+ dischargeDatetime: {
37
+ key: 'dischargeDatetime',
38
+ valueType: 'date',
39
+ },
40
+ /**
41
+ * `Encounter.class.display`, e.g. "Ambulatory". When the class is missing or
42
+ * "unknown", the `encounterType` value instead.
43
+ */
44
+ encounterClass: {
45
+ key: 'encounterClass',
46
+ valueType: 'string',
47
+ },
48
+ /**
49
+ * The first `Encounter.type` text containing "Inpatient", "Ambulatory" or
50
+ * "Emergency", ignoring case.
51
+ */
52
+ encounterType: {
53
+ key: 'encounterType',
54
+ valueType: 'string',
55
+ },
56
+ /** `Encounter.location[0].location.display`. */
57
+ encounterLocation: {
58
+ key: 'encounterLocation',
59
+ valueType: 'string',
60
+ },
61
+ /** The first `Encounter.reasonCode` text. */
62
+ encounterReason: {
63
+ key: 'encounterReason',
64
+ valueType: 'string',
65
+ },
66
+ /** The display text of every `Encounter.diagnosis` condition. */
67
+ encounterDiagnoses: {
68
+ key: 'encounterDiagnoses',
69
+ valueType: 'strings_array',
70
+ },
27
71
  /**
28
72
  * The discharge summary fields, present only when the bundle is a
29
73
  * `patient.discharge-summary` document. Unlike the bundle itself these are
@@ -1 +1 @@
1
- {"version":3,"file":"dataPoints.js","sourceRoot":"","sources":["../../../../../extensions/metriport/actions/storeWebhookBundle/dataPoints.ts"],"names":[],"mappings":";;;AACA,wEAA8E;AAEjE,QAAA,UAAU,GAAG;IACxB,oEAAoE;IACpE,SAAS,EAAE;QACT,GAAG,EAAE,WAAW;QAChB,SAAS,EAAE,QAAQ;KACpB;IACD;;;OAGG;IACH,oBAAoB,EAAE;QACpB,GAAG,EAAE,sBAAsB;QAC3B,SAAS,EAAE,QAAQ;KACpB;IACD;;;OAGG;IACH,WAAW,EAAE;QACX,GAAG,EAAE,aAAa;QAClB,SAAS,EAAE,QAAQ;KACpB;IACD;;;;OAIG;IACH,GAAG,6CAA0B;CACgB,CAAA"}
1
+ {"version":3,"file":"dataPoints.js","sourceRoot":"","sources":["../../../../../extensions/metriport/actions/storeWebhookBundle/dataPoints.ts"],"names":[],"mappings":";;;AACA,wEAA8E;AAEjE,QAAA,UAAU,GAAG;IACxB,oEAAoE;IACpE,SAAS,EAAE;QACT,GAAG,EAAE,WAAW;QAChB,SAAS,EAAE,QAAQ;KACpB;IACD;;;OAGG;IACH,oBAAoB,EAAE;QACpB,GAAG,EAAE,sBAAsB;QAC3B,SAAS,EAAE,QAAQ;KACpB;IACD;;;OAGG;IACH,WAAW,EAAE;QACX,GAAG,EAAE,aAAa;QAClB,SAAS,EAAE,QAAQ;KACpB;IACD;;;OAGG;IACH,iBAAiB,EAAE;QACjB,GAAG,EAAE,mBAAmB;QACxB,SAAS,EAAE,MAAM;KAClB;IACD,0EAA0E;IAC1E,iBAAiB,EAAE;QACjB,GAAG,EAAE,mBAAmB;QACxB,SAAS,EAAE,MAAM;KAClB;IACD;;;OAGG;IACH,cAAc,EAAE;QACd,GAAG,EAAE,gBAAgB;QACrB,SAAS,EAAE,QAAQ;KACpB;IACD;;;OAGG;IACH,aAAa,EAAE;QACb,GAAG,EAAE,eAAe;QACpB,SAAS,EAAE,QAAQ;KACpB;IACD,gDAAgD;IAChD,iBAAiB,EAAE;QACjB,GAAG,EAAE,mBAAmB;QACxB,SAAS,EAAE,QAAQ;KACpB;IACD,6CAA6C;IAC7C,eAAe,EAAE;QACf,GAAG,EAAE,iBAAiB;QACtB,SAAS,EAAE,QAAQ;KACpB;IACD,iEAAiE;IACjE,kBAAkB,EAAE;QAClB,GAAG,EAAE,oBAAoB;QACzB,SAAS,EAAE,eAAe;KAC3B;IACD;;;;OAIG;IACH,GAAG,6CAA0B;CACgB,CAAA"}
@@ -24,7 +24,7 @@ exports.storeWebhookBundle = {
24
24
  const { url, eventType, provenanceReason } = validation_1.getWebhookBundleSchema.parse(payload.fields);
25
25
  // No `log`: it would write every resource's identifiers (MRNs and the
26
26
  // like) to the logs, and a bundle can hold tens of thousands of resources.
27
- const { bundle, transactionBundle, encounterId, dischargeSummary } = await (0, fetchWebhookBundle_1.fetchWebhookBundle)({
27
+ const { bundle, transactionBundle, encounterId, encounterFields, dischargeSummary, } = await (0, fetchWebhookBundle_1.fetchWebhookBundle)({
28
28
  url,
29
29
  awellPatientId: payload.patient.id,
30
30
  eventType,
@@ -40,6 +40,7 @@ exports.storeWebhookBundle = {
40
40
  bundleRef,
41
41
  ...(transactionBundleRef !== undefined ? { transactionBundleRef } : {}),
42
42
  ...(encounterId !== undefined ? { encounterId } : {}),
43
+ ...encounterFields,
43
44
  // The discharge summary fields are small by construction; they are
44
45
  // the one part of a summary that is meant to travel as data points.
45
46
  ...dischargeSummary,
@@ -1 +1 @@
1
- {"version":3,"file":"storeWebhookBundle.js","sourceRoot":"","sources":["../../../../../extensions/metriport/actions/storeWebhookBundle/storeWebhookBundle.ts"],"names":[],"mappings":";;;AAAA,mEAAqE;AAErE,4DAA8D;AAC9D,oDAAgD;AAChD,4EAAwE;AACxE,4DAAoE;AACpE,6CAAyC;AAE5B,QAAA,kBAAkB,GAI3B;IACF,GAAG,EAAE,oBAAoB;IACzB,QAAQ,EAAE,0BAAQ,CAAC,gBAAgB;IACnC,KAAK,EAAE,sBAAsB;IAC7B,WAAW,EACT,uXAAuX;IACzX,MAAM,EAAN,eAAM;IACN,wDAAwD;IACxD,WAAW,EAAE,KAAK;IAClB,sEAAsE;IACtE,2CAA2C;IAC3C,0BAA0B,EAAE,IAAI;IAChC,UAAU,EAAV,uBAAU;IACV,OAAO,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,EAAiB,EAAE;QAC1E,IAAI,CAAC;YACH,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,gBAAgB,EAAE,GAAG,mCAAsB,CAAC,KAAK,CACvE,OAAO,CAAC,MAAM,CACf,CAAA;YAED,sEAAsE;YACtE,2EAA2E;YAC3E,MAAM,EAAE,MAAM,EAAE,iBAAiB,EAAE,WAAW,EAAE,gBAAgB,EAAE,GAChE,MAAM,IAAA,uCAAkB,EAAC;gBACvB,GAAG;gBACH,cAAc,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE;gBAClC,SAAS;gBACT,MAAM,EAAE,gBAAgB;aACzB,CAAC,CAAA;YAEJ,MAAM,UAAU,GAAG,CAAC,IAAY,EAAU,EAAE,CAC1C,aAAa,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,IAAI,OAAO,CAAA;YAEjD,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,WAAW,CAAC,GAAG,CAC7C,UAAU,CAAC,QAAQ,CAAC,EACpB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CACvB,CAAA;YACD,MAAM,oBAAoB,GACxB,iBAAiB,KAAK,SAAS;gBAC7B,CAAC,CAAC,SAAS;gBACX,CAAC,CAAC,MAAM,OAAO,CAAC,WAAW,CAAC,GAAG,CAC3B,UAAU,CAAC,oBAAoB,CAAC,EAChC,IAAI,CAAC,SAAS,CAAC,iBAAiB,CAAC,CAClC,CAAA;YAEP,MAAM,UAAU,CAAC;gBACf,WAAW,EAAE;oBACX,SAAS;oBACT,GAAG,CAAC,oBAAoB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,oBAAoB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACvE,GAAG,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACrD,mEAAmE;oBACnE,oEAAoE;oBACpE,GAAG,gBAAgB;iBACpB;aACF,CAAC,CAAA;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAA,iCAAkB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAA;QACxC,CAAC;IACH,CAAC;CACF,CAAA"}
1
+ {"version":3,"file":"storeWebhookBundle.js","sourceRoot":"","sources":["../../../../../extensions/metriport/actions/storeWebhookBundle/storeWebhookBundle.ts"],"names":[],"mappings":";;;AAAA,mEAAqE;AAErE,4DAA8D;AAC9D,oDAAgD;AAChD,4EAAwE;AACxE,4DAAoE;AACpE,6CAAyC;AAE5B,QAAA,kBAAkB,GAI3B;IACF,GAAG,EAAE,oBAAoB;IACzB,QAAQ,EAAE,0BAAQ,CAAC,gBAAgB;IACnC,KAAK,EAAE,sBAAsB;IAC7B,WAAW,EACT,uXAAuX;IACzX,MAAM,EAAN,eAAM;IACN,wDAAwD;IACxD,WAAW,EAAE,KAAK;IAClB,sEAAsE;IACtE,2CAA2C;IAC3C,0BAA0B,EAAE,IAAI;IAChC,UAAU,EAAV,uBAAU;IACV,OAAO,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,EAAiB,EAAE;QAC1E,IAAI,CAAC;YACH,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,gBAAgB,EAAE,GAAG,mCAAsB,CAAC,KAAK,CACvE,OAAO,CAAC,MAAM,CACf,CAAA;YAED,sEAAsE;YACtE,2EAA2E;YAC3E,MAAM,EACJ,MAAM,EACN,iBAAiB,EACjB,WAAW,EACX,eAAe,EACf,gBAAgB,GACjB,GAAG,MAAM,IAAA,uCAAkB,EAAC;gBAC3B,GAAG;gBACH,cAAc,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE;gBAClC,SAAS;gBACT,MAAM,EAAE,gBAAgB;aACzB,CAAC,CAAA;YAEF,MAAM,UAAU,GAAG,CAAC,IAAY,EAAU,EAAE,CAC1C,aAAa,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,IAAI,OAAO,CAAA;YAEjD,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,WAAW,CAAC,GAAG,CAC7C,UAAU,CAAC,QAAQ,CAAC,EACpB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CACvB,CAAA;YACD,MAAM,oBAAoB,GACxB,iBAAiB,KAAK,SAAS;gBAC7B,CAAC,CAAC,SAAS;gBACX,CAAC,CAAC,MAAM,OAAO,CAAC,WAAW,CAAC,GAAG,CAC3B,UAAU,CAAC,oBAAoB,CAAC,EAChC,IAAI,CAAC,SAAS,CAAC,iBAAiB,CAAC,CAClC,CAAA;YAEP,MAAM,UAAU,CAAC;gBACf,WAAW,EAAE;oBACX,SAAS;oBACT,GAAG,CAAC,oBAAoB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,oBAAoB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACvE,GAAG,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACrD,GAAG,eAAe;oBAClB,mEAAmE;oBACnE,oEAAoE;oBACpE,GAAG,gBAAgB;iBACpB;aACF,CAAC,CAAA;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAA,iCAAkB,EAAC,GAAG,EAAE,OAAO,CAAC,CAAA;QACxC,CAAC;IACH,CAAC;CACF,CAAA"}
@@ -13,3 +13,25 @@ import { type Bundle } from '@medplum/fhirtypes';
13
13
  * happens to include one.
14
14
  */
15
15
  export declare const findEncounterId: (bundle: Bundle) => string | undefined;
16
+ /**
17
+ * The Encounter fields handed on as data points. Each is omitted when the
18
+ * Encounter does not carry it, never emitted empty, so a missing field reads
19
+ * as missing downstream rather than as a blank value.
20
+ */
21
+ export interface EncounterFields {
22
+ admissionDatetime?: string;
23
+ dischargeDatetime?: string;
24
+ encounterClass?: string;
25
+ encounterType?: string;
26
+ encounterLocation?: string;
27
+ encounterReason?: string;
28
+ /** JSON array of the diagnoses' display text. */
29
+ encounterDiagnoses?: string;
30
+ }
31
+ /**
32
+ * The fields of the first Encounter in a webhook bundle — the same Encounter
33
+ * `findEncounterId` reads. A diagnosis is labelled by its reference's
34
+ * `display`, falling back to the Condition it points at when the bundle
35
+ * carries it.
36
+ */
37
+ export declare const extractEncounterFields: (bundle: Bundle) => EncounterFields;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findEncounterId = void 0;
3
+ exports.extractEncounterFields = exports.findEncounterId = void 0;
4
+ const resolve_1 = require("../dischargeSummary/resolve");
4
5
  /**
5
6
  * The Metriport id of the Encounter a webhook bundle describes.
6
7
  *
@@ -19,4 +20,47 @@ const findEncounterId = (bundle) => {
19
20
  return (_c = (_b = (_a = bundle.entry) === null || _a === void 0 ? void 0 : _a.find((entry) => { var _a; return ((_a = entry.resource) === null || _a === void 0 ? void 0 : _a.resourceType) === 'Encounter'; })) === null || _b === void 0 ? void 0 : _b.resource) === null || _c === void 0 ? void 0 : _c.id;
20
21
  };
21
22
  exports.findEncounterId = findEncounterId;
23
+ /** `Encounter.type` texts that name the setting, matched case-insensitively. */
24
+ const KNOWN_ENCOUNTER_TYPES = ['inpatient', 'ambulatory', 'emergency'];
25
+ const isKnownType = (text) => {
26
+ const lower = text.toLowerCase();
27
+ return KNOWN_ENCOUNTER_TYPES.some((type) => lower.includes(type));
28
+ };
29
+ const conditionLabel = (concept) => { var _a, _b, _c; return (_a = concept === null || concept === void 0 ? void 0 : concept.text) !== null && _a !== void 0 ? _a : (_c = (_b = concept === null || concept === void 0 ? void 0 : concept.coding) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.display; };
30
+ const nonEmpty = (value) => value !== undefined && value.length > 0;
31
+ /**
32
+ * The fields of the first Encounter in a webhook bundle — the same Encounter
33
+ * `findEncounterId` reads. A diagnosis is labelled by its reference's
34
+ * `display`, falling back to the Condition it points at when the bundle
35
+ * carries it.
36
+ */
37
+ const extractEncounterFields = (bundle) => {
38
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
39
+ const encounter = (_b = (_a = bundle.entry) === null || _a === void 0 ? void 0 : _a.find((entry) => { var _a; return ((_a = entry.resource) === null || _a === void 0 ? void 0 : _a.resourceType) === 'Encounter'; })) === null || _b === void 0 ? void 0 : _b.resource;
40
+ if (encounter === undefined)
41
+ return {};
42
+ const index = (0, resolve_1.indexBundle)(bundle);
43
+ const diagnoses = ((_c = encounter.diagnosis) !== null && _c !== void 0 ? _c : [])
44
+ .map(({ condition }) => {
45
+ var _a, _b;
46
+ return (_a = condition.display) !== null && _a !== void 0 ? _a : conditionLabel((_b = (0, resolve_1.resolve)(index, condition, 'Condition')) === null || _b === void 0 ? void 0 : _b.code);
47
+ })
48
+ .filter(nonEmpty);
49
+ const encounterType = (_d = encounter.type) === null || _d === void 0 ? void 0 : _d.map((type) => type.text).find((text) => nonEmpty(text) && isKnownType(text));
50
+ const classDisplay = (_e = encounter.class) === null || _e === void 0 ? void 0 : _e.display;
51
+ const fields = {
52
+ admissionDatetime: (_f = encounter.period) === null || _f === void 0 ? void 0 : _f.start,
53
+ dischargeDatetime: (_g = encounter.period) === null || _g === void 0 ? void 0 : _g.end,
54
+ // Some sources send no class, or "unknown"; the type then names the setting.
55
+ encounterClass: nonEmpty(classDisplay) && classDisplay.toLowerCase() !== 'unknown'
56
+ ? classDisplay
57
+ : encounterType,
58
+ encounterType,
59
+ encounterLocation: (_j = (_h = encounter.location) === null || _h === void 0 ? void 0 : _h[0]) === null || _j === void 0 ? void 0 : _j.location.display,
60
+ encounterReason: (_l = (_k = encounter.reasonCode) === null || _k === void 0 ? void 0 : _k.find((reason) => nonEmpty(reason.text))) === null || _l === void 0 ? void 0 : _l.text,
61
+ encounterDiagnoses: diagnoses.length > 0 ? JSON.stringify(diagnoses) : undefined,
62
+ };
63
+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => nonEmpty(value)));
64
+ };
65
+ exports.extractEncounterFields = extractEncounterFields;
22
66
  //# sourceMappingURL=encounter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"encounter.js","sourceRoot":"","sources":["../../../../../../extensions/metriport/actions/webhookBundle/bundle/encounter.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;GAYG;AACI,MAAM,eAAe,GAAG,CAAC,MAAc,EAAsB,EAAE;;IACpE,OAAA,MAAA,MAAA,MAAA,MAAM,CAAC,KAAK,0CAAE,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,WAAC,OAAA,CAAA,MAAA,KAAK,CAAC,QAAQ,0CAAE,YAAY,MAAK,WAAW,CAAA,EAAA,CAAC,0CACvE,QAAQ,0CAAE,EAAE,CAAA;CAAA,CAAA;AAFL,QAAA,eAAe,mBAEV"}
1
+ {"version":3,"file":"encounter.js","sourceRoot":"","sources":["../../../../../../extensions/metriport/actions/webhookBundle/bundle/encounter.ts"],"names":[],"mappings":";;;AAMA,yDAAkE;AAElE;;;;;;;;;;;;GAYG;AACI,MAAM,eAAe,GAAG,CAAC,MAAc,EAAsB,EAAE;;IACpE,OAAA,MAAA,MAAA,MAAA,MAAM,CAAC,KAAK,0CAAE,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,WAAC,OAAA,CAAA,MAAA,KAAK,CAAC,QAAQ,0CAAE,YAAY,MAAK,WAAW,CAAA,EAAA,CAAC,0CACvE,QAAQ,0CAAE,EAAE,CAAA;CAAA,CAAA;AAFL,QAAA,eAAe,mBAEV;AAkBlB,gFAAgF;AAChF,MAAM,qBAAqB,GAAG,CAAC,WAAW,EAAE,YAAY,EAAE,WAAW,CAAC,CAAA;AAEtE,MAAM,WAAW,GAAG,CAAC,IAAY,EAAW,EAAE;IAC5C,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,EAAE,CAAA;IAChC,OAAO,qBAAqB,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAA;AACnE,CAAC,CAAA;AAED,MAAM,cAAc,GAAG,CACrB,OAAoC,EAChB,EAAE,mBAAC,OAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,mCAAI,MAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,0CAAG,CAAC,CAAC,0CAAE,OAAO,CAAA,EAAA,CAAA;AAEvE,MAAM,QAAQ,GAAG,CAAC,KAAyB,EAAmB,EAAE,CAC9D,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAA;AAEzC;;;;;GAKG;AACI,MAAM,sBAAsB,GAAG,CAAC,MAAc,EAAmB,EAAE;;IACxE,MAAM,SAAS,GAAG,MAAA,MAAA,MAAM,CAAC,KAAK,0CAAE,IAAI,CAClC,CAAC,KAAK,EAAE,EAAE,WAAC,OAAA,CAAA,MAAA,KAAK,CAAC,QAAQ,0CAAE,YAAY,MAAK,WAAW,CAAA,EAAA,CACxD,0CAAE,QAAiC,CAAA;IACpC,IAAI,SAAS,KAAK,SAAS;QAAE,OAAO,EAAE,CAAA;IAEtC,MAAM,KAAK,GAAG,IAAA,qBAAW,EAAC,MAAM,CAAC,CAAA;IACjC,MAAM,SAAS,GAAG,CAAC,MAAA,SAAS,CAAC,SAAS,mCAAI,EAAE,CAAC;SAC1C,GAAG,CACF,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE;;QAChB,OAAA,MAAA,SAAS,CAAC,OAAO,mCACjB,cAAc,CAAC,MAAA,IAAA,iBAAO,EAAY,KAAK,EAAE,SAAS,EAAE,WAAW,CAAC,0CAAE,IAAI,CAAC,CAAA;KAAA,CAC1E;SACA,MAAM,CAAC,QAAQ,CAAC,CAAA;IAEnB,MAAM,aAAa,GAAG,MAAA,SAAS,CAAC,IAAI,0CAChC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EACxB,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,IAAI,CAAC,CAAC,CAAA;IACtD,MAAM,YAAY,GAAG,MAAA,SAAS,CAAC,KAAK,0CAAE,OAAO,CAAA;IAE7C,MAAM,MAAM,GAAoB;QAC9B,iBAAiB,EAAE,MAAA,SAAS,CAAC,MAAM,0CAAE,KAAK;QAC1C,iBAAiB,EAAE,MAAA,SAAS,CAAC,MAAM,0CAAE,GAAG;QACxC,6EAA6E;QAC7E,cAAc,EACZ,QAAQ,CAAC,YAAY,CAAC,IAAI,YAAY,CAAC,WAAW,EAAE,KAAK,SAAS;YAChE,CAAC,CAAC,YAAY;YACd,CAAC,CAAC,aAAa;QACnB,aAAa;QACb,iBAAiB,EAAE,MAAA,MAAA,SAAS,CAAC,QAAQ,0CAAG,CAAC,CAAC,0CAAE,QAAQ,CAAC,OAAO;QAC5D,eAAe,EAAE,MAAA,MAAA,SAAS,CAAC,UAAU,0CAAE,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CACrD,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CACtB,0CAAE,IAAI;QACP,kBAAkB,EAChB,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS;KAC/D,CAAA;IAED,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAC9D,CAAA;AACH,CAAC,CAAA;AAxCY,QAAA,sBAAsB,0BAwClC"}
@@ -1,10 +1,11 @@
1
1
  import { type Bundle } from '@medplum/fhirtypes';
2
2
  import { type Helpers } from '@awell-health/extensions-core';
3
+ import { type EncounterFields } from './bundle/encounter';
3
4
  import { type DischargeSummaryFields } from './dischargeSummary';
4
5
  /**
5
6
  * Downloads a Metriport webhook bundle and derives what both bundle actions
6
- * hand on: the importable transaction rewrite, the Encounter's id, and, for a
7
- * discharge summary, the fields lifted from the document. They differ only in
7
+ * hand on: the importable transaction rewrite, the Encounter's id and fields,
8
+ * and, for a discharge summary, the fields lifted from the document. They differ only in
8
9
  * how they publish the result.
9
10
  */
10
11
  export declare const fetchWebhookBundle: ({ url, awellPatientId, eventType, reason, log, }: {
@@ -17,6 +18,8 @@ export declare const fetchWebhookBundle: ({ url, awellPatientId, eventType, reas
17
18
  bundle: Bundle;
18
19
  transactionBundle: Bundle | undefined;
19
20
  encounterId: string | undefined;
21
+ /** Empty when the bundle carries no Encounter, or for a discharge summary event. */
22
+ encounterFields: EncounterFields;
20
23
  /** Undefined for any bundle that is not a discharge summary document. */
21
24
  dischargeSummary: DischargeSummaryFields | undefined;
22
25
  }>;
@@ -5,10 +5,11 @@ const fetchBundle_1 = require("../../shared/fetchBundle");
5
5
  const bundle_1 = require("./bundle");
6
6
  const encounter_1 = require("./bundle/encounter");
7
7
  const dischargeSummary_1 = require("./dischargeSummary");
8
+ const DISCHARGE_SUMMARY_EVENT = 'patient.discharge-summary';
8
9
  /**
9
10
  * Downloads a Metriport webhook bundle and derives what both bundle actions
10
- * hand on: the importable transaction rewrite, the Encounter's id, and, for a
11
- * discharge summary, the fields lifted from the document. They differ only in
11
+ * hand on: the importable transaction rewrite, the Encounter's id and fields,
12
+ * and, for a discharge summary, the fields lifted from the document. They differ only in
12
13
  * how they publish the result.
13
14
  */
14
15
  const fetchWebhookBundle = async ({ url, awellPatientId, eventType, reason, log, }) => {
@@ -29,6 +30,10 @@ const fetchWebhookBundle = async ({ url, awellPatientId, eventType, reason, log,
29
30
  bundle,
30
31
  transactionBundle,
31
32
  encounterId: (0, encounter_1.findEncounterId)(bundle),
33
+ // A discharge summary hands on its own fields instead.
34
+ encounterFields: eventType === DISCHARGE_SUMMARY_EVENT
35
+ ? {}
36
+ : (0, encounter_1.extractEncounterFields)(bundle),
32
37
  dischargeSummary: (0, dischargeSummary_1.extractDischargeSummary)(bundle),
33
38
  };
34
39
  };
@@ -1 +1 @@
1
- {"version":3,"file":"fetchWebhookBundle.js","sourceRoot":"","sources":["../../../../../extensions/metriport/actions/webhookBundle/fetchWebhookBundle.ts"],"names":[],"mappings":";;;AAEA,0DAAsD;AACtD,qCAAiD;AACjD,kDAAoD;AACpD,yDAG2B;AAE3B;;;;;GAKG;AACI,MAAM,kBAAkB,GAAG,KAAK,EAAE,EACvC,GAAG,EACH,cAAc,EACd,SAAS,EACT,MAAM,EACN,GAAG,GAOJ,EAME,EAAE;IACH,MAAM,MAAM,GAAG,MAAM,IAAA,yBAAW,EAAC,GAAG,CAAC,CAAA;IAErC,wEAAwE;IACxE,0EAA0E;IAC1E,wEAAwE;IACxE,0EAA0E;IAC1E,kEAAkE;IAClE,MAAM,iBAAiB,GAAG,IAAA,+BAAsB,EAAC;QAC/C,MAAM;QACN,cAAc;QACd,SAAS;QACT,MAAM;QACN,GAAG;KACJ,CAAC,CAAA;IAEF,OAAO;QACL,MAAM;QACN,iBAAiB;QACjB,WAAW,EAAE,IAAA,2BAAe,EAAC,MAAM,CAAC;QACpC,gBAAgB,EAAE,IAAA,0CAAuB,EAAC,MAAM,CAAC;KAClD,CAAA;AACH,CAAC,CAAA;AAxCY,QAAA,kBAAkB,sBAwC9B"}
1
+ {"version":3,"file":"fetchWebhookBundle.js","sourceRoot":"","sources":["../../../../../extensions/metriport/actions/webhookBundle/fetchWebhookBundle.ts"],"names":[],"mappings":";;;AAEA,0DAAsD;AACtD,qCAAiD;AACjD,kDAI2B;AAC3B,yDAG2B;AAE3B,MAAM,uBAAuB,GAAG,2BAA2B,CAAA;AAE3D;;;;;GAKG;AACI,MAAM,kBAAkB,GAAG,KAAK,EAAE,EACvC,GAAG,EACH,cAAc,EACd,SAAS,EACT,MAAM,EACN,GAAG,GAOJ,EAQE,EAAE;IACH,MAAM,MAAM,GAAG,MAAM,IAAA,yBAAW,EAAC,GAAG,CAAC,CAAA;IAErC,wEAAwE;IACxE,0EAA0E;IAC1E,wEAAwE;IACxE,0EAA0E;IAC1E,kEAAkE;IAClE,MAAM,iBAAiB,GAAG,IAAA,+BAAsB,EAAC;QAC/C,MAAM;QACN,cAAc;QACd,SAAS;QACT,MAAM;QACN,GAAG;KACJ,CAAC,CAAA;IAEF,OAAO;QACL,MAAM;QACN,iBAAiB;QACjB,WAAW,EAAE,IAAA,2BAAe,EAAC,MAAM,CAAC;QACpC,uDAAuD;QACvD,eAAe,EACb,SAAS,KAAK,uBAAuB;YACnC,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,IAAA,kCAAsB,EAAC,MAAM,CAAC;QACpC,gBAAgB,EAAE,IAAA,0CAAuB,EAAC,MAAM,CAAC;KAClD,CAAA;AACH,CAAC,CAAA;AA/CY,QAAA,kBAAkB,sBA+C9B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awell-health/awell-extensions",
3
- "version": "2.1.209",
3
+ "version": "2.1.210",
4
4
  "packageManager": "yarn@4.5.3",
5
5
  "main": "dist/src/index.js",
6
6
  "repository": {