Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci-workflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}

- name: Use native MongoDB on Apple Silicon
if: runner.os == 'macOS' && runner.arch == 'ARM64'
run: echo "MONGOMS_VERSION=8.0.38" >> "$GITHUB_ENV"

- name: Install OpenSSL 1.1 on Ubuntu
if: matrix.os == 'ubuntu-latest'
Expand Down
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,33 @@ See the section about [running tests](https://create-react-app.dev/docs/running-

## Usage

The REMS Admin interacts with the [Request Generator](https://github.com/mcode/request-generator), [REMS SMART on FHIR app](https://github.com/mcode/rems-smart-on-fhir), and an [EHR](https://github.com/mcode/test-ehr). These apps are provided as part of the REMS ecosystem, but any individual part may be swapped out for something custom. The REMS Admin responds to CDS Hooks requests as well as FHIR operations for the questionnaire package ($questionnaire-package) and REMS ETASU check ($rems-etasu).
The REMS Admin interacts with the [Request Generator](https://github.com/mcode/request-generator), [REMS SMART on FHIR app](https://github.com/mcode/rems-smart-on-fhir), and an [EHR](https://github.com/mcode/test-ehr). These apps are provided as part of the REMS ecosystem, but any individual part may be swapped out for something custom. The REMS Admin responds to CDS Hooks requests as well as FHIR operations for the questionnaire package ($questionnaire-package), REMS ETASU check ($rems-etasu), and dispensing authorization ($rems-rda).

Typically, a CDS Hook will be sent from the EHR to the REMS Admin, which will respond with cards that contain information about next steps. These cards may contain a link to a SMART app. Clicking on these links in the Request Generator or REMS SMART on FHIR App acting as the EHR will launch the SMART app automatically. These links will contain information on the requirements that must be met for the REMS program. This includes forms for registration and acknowledgement of the risks involved.

The FHIR server built into the REMS Admin can be queried for the questionnaire package at the Questionnaire/$questionnaire-package endpoint. This will return a FHIR Bundle with the FHIR Questionnaire and all other FHIR Resources including CQL Libraries embedded within FHIR Libraries. The FHIR Server also contains a REMS ETASU check at the GuidanceResponse/$rems-etasu endpoint. This will return a FHIR Parameter containing a GuidanceResponse with the status of the ETASU and nested GuidanceResponse for each requirement.

### REMS dispensing authorization

POST a FHIR Parameters resource to `/4_0_0/GuidanceResponse/$rems-rda` with a case number and the requesting pharmacy.

```bash
curl -fsS 'http://localhost:8090/4_0_0/GuidanceResponse/$rems-rda' \
-H 'Content-Type: application/fhir+json' \
--data '{
"resourceType": "Parameters",
"parameter": [
{"name": "caseNumber", "valueString": "<case number>"},
{"name": "pharmacy", "resource": {"resourceType": "HealthcareService", "id": "pharm0111"}}
]
}'
```

Alternatively send a Patient and a Medication or MedicationRequest. The medication can carry RxNorm or NDC codings. The operation uses the configured product and prefers a recognized NDC when both are present. A pharmacy can be a HealthcareService or Organization. When using a different pharmacy reference than the one recorded at enrollment, include the enrolled NPI in a pharmacy identifier with system `http://hl7.org/fhir/sid/us-npi`.

If approved, the response contains a GuidanceResponse with an `rda` identifier and an `authorizationPeriod` output parameter. Search by issuing system and value using `GET /4_0_0/GuidanceResponse?identifier={system}|{value}`. The default authorization period is seven UTC calendar days.


## Routes

- `/cds-services` - The base CDS Hooks Discovery endpoint that serves a list of supported hooks/services in JSON.
Expand All @@ -87,6 +108,10 @@ The FHIR server built into the REMS Admin can be queried for the questionnaire p
- `caseNumber` - String containing the REMS Case Number, may be sent without `patient` or `medication`
- Returns a GuidanceResponse within a Parameter with the status
- Contains Nested GuidanceResponse resources for each ETASU requirement with their status
- `POST /4_0_0/GuidanceResponse/$rems-rda` - Requests a REMS dispensing authorization (RDA). Include the pharmacy and one of the following.
- The REMS case number
- The medication with an RxNorm or NDC coding and the patient's first and last name and date of birth
- `GET /4_0_0/GuidanceResponse` - Looks up an issued RDA. Pass its number as the `identifier` query parameter, optionally qualified as `system|value`.
- `/4_0_0/Questionnaire/\<form-name\>/$questionnaire-package` - The endpoint for the FHIR Operation used for retrieving the Questionnaire package for a given form
- Example: /4_0_0/Questionnaire/TIRFRemsPatientEnrollment/$questionnaire-package
- This includes the Questionnaire and any other necessary FHIR resources needed for loading the questionnaire form with the REMS SMART on FHIR app
Expand All @@ -111,6 +136,8 @@ Following are a list of modifiable paths:
| MONGO_DB_NAME | `remsadmin` | Name of the database table being used. Should be changed if not using the Mongo instructions above. |
| MONGO_URL | `mongodb://rems-user:pass@127.0.0.1:27017` | URL for the connection to the database, should be changed if not using the Mongo instructions above. |
| PORT | `8090` | Port that this server should run on, change if there are conflicts with port usage. |
| RDA_VALIDITY_DAYS | `7` | Validity of a REMS dispensing authorization in UTC calendar days. |
| RDA_IDENTIFIER_SYSTEM | `{RESOURCE_SERVER}/rda` | Identifier system for issued REMS dispensing authorizations. |
| RESOURCE_SERVER | `http://localhost:8090` | Base URL of this server, should match with port. |
| SMART_ENDPOINT | `http://localhost:4040/launch` | Launch URL of associated SMART app, should be changed if not using the REMS Smart App. |
| USE_HTTPS | `false` | Change to true to enable HTTPS. Ensure that HTTPS_CERT_PATH and HTTPS_KEY_PATH are valid. |
Expand Down
14 changes: 14 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@ export default {
}
}
},
dispensingAuthorization: {
get validityDays() {
return env.get('RDA_VALIDITY_DAYS').default('7').asIntPositive();
},
identifierSystem: env
.get('RDA_IDENTIFIER_SYSTEM')
.default(env.get('RESOURCE_SERVER').required().asUrlString().replace(/\/$/, '') + '/rda')
.asString()
},
fhirServerConfig: {
auth: {
// This server's URI
Expand Down Expand Up @@ -140,6 +149,11 @@ export default {
method: 'POST',
reference:
'https://build.fhir.org/ig/HL7/fhir-medication-rems-ig/OperationDefinition-REMS-ETASU.html'
},
{
name: 'rems-rda',
route: '/$rems-rda',
method: 'POST'
}
]
}
Expand Down
45 changes: 45 additions & 0 deletions src/fhir/dispensingAuthorizationCodes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { OperationOutcomeIssue } from 'fhir/r4';

const medicationRemsCodeSystem = 'http://hl7.org/fhir/us/medication-rems/CodeSystem/';
export const dispensingCodes = {
identifierType: {
system: medicationRemsCodeSystem + 'rems-identifier-type',
code: 'rda',
display: 'REMS Dispensing Authorization'
},
denialReasonSystem: medicationRemsCodeSystem + 'rems-reason',
denialReasonDefinitions: {
'patient-not-enrolled': {
issueCode: 'business-rule',
display: 'Patient enrollment or certification required'
},
'prescriber-not-certified': {
issueCode: 'business-rule',
display: 'Prescriber enrollment or certification required'
},
'pharmacy-not-certified': {
issueCode: 'business-rule',
display: 'Pharmacy enrollment or certification required'
},
'case-invalid': { issueCode: 'not-found', display: 'Case information incomplete or invalid' },
'program-error': { issueCode: 'exception', display: 'REMS program or configuration error' },
'patient-deactivated': {
issueCode: 'business-rule',
display: 'Patient deactivated or decertified'
},
'prescriber-deactivated': {
issueCode: 'business-rule',
display: 'Prescriber deactivated or decertified'
},
'pharmacy-deactivated': {
issueCode: 'business-rule',
display: 'Pharmacy deactivated or decertified'
}
} satisfies Record<string, { issueCode: OperationOutcomeIssue['code']; display: string }>
};

export interface MedicationDispensingDenialReason {
code: keyof typeof dispensingCodes.denialReasonDefinitions;
requirementName?: string;
diagnosticDetail?: string;
}
253 changes: 253 additions & 0 deletions src/fhir/guidanceResponseRequests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,253 @@
import { ServerError } from '@projecttacoma/node-fhir-server-core';
import {
FhirResource,
HealthcareService,
Identifier,
Medication,
MedicationRequest,
Organization,
Parameters,
ParametersParameter,
Patient
} from 'fhir/r4';
import {
getDrugCodeFromMedicationRequest,
medicationQueryForCoding,
selectMedicationCoding
} from '../hooks/hookResources';
import { normalizePharmacyReference } from '../lib/etasu';
import type { DispensingMedication } from '../lib/dispensingAuthorization';
import { medicationCollection } from './models';

type RemsOperation = '$rems-rda' | '$rems-etasu';
const FHIR_LOGICAL_ID_PATTERN = /^[A-Za-z0-9.-]{1,64}$/;
const RXNORM_SYSTEM = 'http://www.nlm.nih.gov/research/umls/rxnorm';

export async function parseMedicationDispensingRequest(resource?: Parameters) {
const operation = '$rems-rda';
const parameters = readRequestParameters(resource, operation);
const findUniqueParameter = (name: string) => {
const [parameter, duplicate] = parameters.filter(parameter => parameter?.name === name);
requireValidInput(!duplicate, `$rems-rda accepts only one '${name}' parameter`, 'invalid');
return parameter;
};
const pharmacy = findUniqueParameter('pharmacy')?.resource;
requireValidInput(
isPharmacyWithId(pharmacy),
"$rems-rda requires a 'pharmacy' parameter (HealthcareService or Organization with id)"
);
const pharmacyReference = normalizePharmacyReference(`${pharmacy.resourceType}/${pharmacy.id}`);
const pharmacyIdentifiers = readPharmacyIdentifiers(pharmacy.identifier);

const patientResource = findUniqueParameter('patient')?.resource;
const patient = patientResource?.resourceType === 'Patient' ? patientResource : undefined;
const medication = findUniqueParameter('medication')?.resource;
const caseNumberParameter = findUniqueParameter('caseNumber');
const requestIdentifierParameter = findUniqueParameter('requestIdentifier');
const requestIdentifier = requestIdentifierParameter?.valueIdentifier;
if (requestIdentifierParameter) {
const invalidField = invalidRequestIdentifierField(requestIdentifier);
requireValidInput(
!invalidField,
`'${invalidField}' is invalid in the FHIR request identifier`,
'invalid'
);
}

const caseNumber = readCaseNumber(caseNumberParameter);
const requestFields = { patient, requestIdentifier, pharmacyReference, pharmacyIdentifiers };
if (caseNumber) return { caseLookup: { case_number: caseNumber }, ...requestFields };

requireValidInput(
patient &&
(medication?.resourceType === 'Medication' ||
medication?.resourceType === 'MedicationRequest'),
`${operation} requires 'caseNumber' or both 'patient' and 'medication'`
);
return {
caseLookup: await resolvePatientMedication(patient, medication, operation),
...requestFields
};
}

export async function parseEtasuRequest(resource?: Parameters) {
const operation = '$rems-etasu';
const parameters = readRequestParameters(resource, operation);
let patient: Patient | undefined;
let medication: Medication | MedicationRequest | undefined;
let caseNumberParameter: ParametersParameter | undefined;
let pharmacyReference: string | undefined;
let pharmacyIdentifiers: Identifier[] = [];
let requestIdentifier: Identifier | undefined;

for (const parameter of parameters) {
const resource = parameter?.resource;
if (parameter?.name === 'patient' && resource?.resourceType === 'Patient') {
patient = resource;
} else if (
parameter?.name === 'medication' &&
(resource?.resourceType === 'Medication' || resource?.resourceType === 'MedicationRequest')
) {
medication = resource;
} else if (parameter?.name === 'caseNumber') {
caseNumberParameter = parameter;
} else if (parameter?.name === 'pharmacy' && isPharmacyWithId(resource)) {
pharmacyReference = normalizePharmacyReference(`${resource.resourceType}/${resource.id}`);
pharmacyIdentifiers = readPharmacyIdentifiers(resource.identifier, false);
} else if (parameter?.name === 'requestIdentifier') {
const identifier = parameter.valueIdentifier;
if (!invalidRequestIdentifierField(identifier)) requestIdentifier = identifier;
}
}

const caseNumber = readCaseNumber(caseNumberParameter);
const requestFields = { patient, pharmacyReference, pharmacyIdentifiers, requestIdentifier };
if (caseNumber) return { caseLookup: { case_number: caseNumber }, ...requestFields };

requireValidInput(
patient && medication,
`${operation} requires 'caseNumber' or both 'patient' and 'medication'`
);
return {
caseLookup: await resolvePatientMedication(patient, medication, operation),
...requestFields
};
}

function readRequestParameters(resource: Parameters | undefined, operation: RemsOperation) {
const parameters = resource?.parameter;
requireValidInput(
resource?.resourceType === 'Parameters' && Array.isArray(parameters),
`${operation} requires a FHIR Parameters resource`
);
return parameters;
}

function readCaseNumber(parameter?: ParametersParameter) {
const caseNumber = parameter?.valueString;
requireValidInput(
!parameter || (typeof caseNumber === 'string' && caseNumber.trim()),
"'caseNumber' must be a non-empty string",
'invalid'
);
return caseNumber;
}

function readPatientDemographics(patient: Patient, operation: RemsOperation) {
const name = patient.name?.[0];
const givenNames = name?.given;
const patientFirstName = Array.isArray(givenNames) ? givenNames[0] : undefined;
const patientLastName = name?.family;
const patientDOB = patient.birthDate;
requireValidInput(
typeof patientFirstName === 'string' &&
patientFirstName.trim() &&
typeof patientLastName === 'string' &&
patientLastName.trim() &&
typeof patientDOB === 'string' &&
patientDOB.trim(),
`${operation} requires 'patient' given name, family name and birthDate`
);
}

async function resolvePatientMedication(
patient: Patient,
medication: Medication | MedicationRequest,
operation: RemsOperation
) {
readPatientDemographics(patient, operation);
const coding =
medication.resourceType === 'Medication'
? await selectMedicationCoding(medication.code?.coding)
: await getDrugCodeFromMedicationRequest(medication);
requireValidInput(
coding?.code &&
(coding.system === RXNORM_SYSTEM || coding.system?.toLowerCase().endsWith('/ndc')),
`${operation} requires an RxNorm or NDC coding in 'medication'`
);

const configuredMedication = await medicationCollection
.findOne(medicationQueryForCoding(coding))
.lean<DispensingMedication | null>()
.exec();
return { patient, medication: configuredMedication, coding };
}

function isPharmacyIdentifier(identifier: unknown): identifier is Identifier {
return (
typeof identifier === 'object' &&
identifier !== null &&
!Array.isArray(identifier) &&
isValidStringField(identifier, 'system') &&
isValidStringField(identifier, 'value')
);
}

function readPharmacyIdentifiers(identifiers: unknown = [], strict = true): Identifier[] {
if (!strict) return Array.isArray(identifiers) ? identifiers.filter(isPharmacyIdentifier) : [];
requireValidInput(
Array.isArray(identifiers),
"The 'pharmacy' identifier field must be an array",
'invalid'
);
requireValidInput(
identifiers.every(isPharmacyIdentifier),
"The 'pharmacy' identifier array must contain FHIR Identifier objects",
'invalid'
);
return identifiers;
}

function isPharmacyWithId(
resource?: FhirResource
): resource is (HealthcareService | Organization) & { id: string } {
return (
(resource?.resourceType === 'HealthcareService' || resource?.resourceType === 'Organization') &&
typeof resource.id === 'string' &&
FHIR_LOGICAL_ID_PATTERN.test(resource.id)
);
}

function isValidStringField(input: object, field: string): boolean {
// The field may be omitted. A supplied value must be a nonblank string.
if (!(field in input)) return true;

const value: unknown = Reflect.get(input, field);
return typeof value === 'string' && value.trim().length > 0;
}

function invalidRequestIdentifierField(identifier?: Identifier): string | undefined {
if (!identifier || typeof identifier !== 'object' || Array.isArray(identifier)) {
return 'requestIdentifier';
}

for (const field of ['system', 'value', 'use']) {
if (!isValidStringField(identifier, field)) return `requestIdentifier.${field}`;
}
for (const field of ['type', 'period', 'assigner'] as const) {
if (!(field in identifier)) continue;
const value = identifier[field];
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return `requestIdentifier.${field}`;
}
}
const { assigner } = identifier;
if (assigner) {
const field = ['reference', 'type', 'display'].find(
field => !isValidStringField(assigner, field)
);
if (field) return `requestIdentifier.assigner.${field}`;
}
}

export function requireValidInput(
condition: unknown,
diagnostics: string,
issueCode: 'required' | 'invalid' = 'required'
): asserts condition {
if (condition) return;
throw new ServerError(diagnostics, {
statusCode: 400,
issue: [{ code: issueCode, severity: 'error', diagnostics }]
});
}
Loading
Loading