-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhookResources.ts
More file actions
1000 lines (903 loc) · 31.3 KB
/
hookResources.ts
File metadata and controls
1000 lines (903 loc) · 31.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
MedicationRequest,
Coding,
FhirResource,
Task,
Patient,
Bundle,
Medication,
BundleEntry,
HealthcareService
} from 'fhir/r4';
import Card, { Link, Suggestion, Action } from '../cards/Card';
import { HookPrefetch, TypedRequestBody } from '../rems-cds-hooks/resources/HookTypes';
import config from '../config';
import {
RemsCase,
Requirement,
medicationCollection,
remsCaseCollection,
Medication as MongooseMedication,
metRequirementsCollection
} from '../fhir/models';
import axios from 'axios';
import { ServicePrefetch } from '../rems-cds-hooks/resources/CdsService';
import { hydrate } from '../rems-cds-hooks/prefetch/PrefetchHydrator';
import { createNewRemsCaseFromCDSHook } from '../lib/etasu';
type HandleCallback = (
res: any,
hydratedPrefetch: HookPrefetch | undefined,
contextRequest: FhirResource | undefined,
patient: FhirResource | undefined,
fhirServer?: string
) => Promise<void>;
export interface CardRule {
links: Link[];
summary?: string;
stakeholderType?: string;
cardDetails?: string;
}
export const CARD_DETAILS = 'Documentation Required, please complete form via Smart App link.';
// TODO: this codemap should be replaced with a system similar to original CRD questionnaire package operation
// the app doesn't necessarily have to use CQL for this.
export const codeMap: { [key: string]: CardRule[] } = {
'2183126': [
{
links: [
{
label: 'Documentation Requirements',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Turalio_2020_08_04_REMS_Full.pdf'
)
},
{
label: 'Medication Guide',
type: 'absolute',
url: new URL(
'https://daiichisankyo.us/prescribing-information-portlet/getPIContent?productName=Turalio_Med&inline=true'
)
},
{
label: 'Patient Guide',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Turalio_2020_12_16_Patient_Guide.pdf'
)
}
],
stakeholderType: 'patient',
summary: 'Turalio REMS Patient Requirements',
cardDetails: CARD_DETAILS
},
{
links: [
{
label: 'Documentation Requirements',
type: 'absolute',
url: new URL(
'https://daiichisankyo.us/prescribing-information-portlet/getPIContent?productName=Turalio&inline=true'
)
},
{
label: 'Program Overview',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Turalio_2020_12_16_Program_Overview.pdf'
)
},
{
label: 'Prescriber Training',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Turalio_2020_12_16_Prescriber_Training.pdf'
)
}
],
stakeholderType: 'prescriber',
summary: 'Turalio REMS Prescriber Requirements',
cardDetails: CARD_DETAILS
}
],
'6064': [
{
links: [
{
label: 'Documentation Requirements',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Isotretinoin_2021_10_8_REMS_Document.pdf'
)
},
{
label: 'Fact Sheet',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Isotretinoin_2021_10_8_Fact_Sheet.pdf'
)
},
{
label: 'Guide For Patients Who Can Get Pregnant',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Isotretinoin_2021_10_8_Guide_for_Patients_Who_Can_Get_pregnant.pdf'
)
},
{
label: 'Contraceptive Counseling Guide',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Isotretinoin_2021_10_8_Contraception_Counseling_Guide.pdf'
)
}
],
stakeholderType: 'patient',
summary: 'iPledge/Isotretinoin REMS Patient Requirements',
cardDetails: CARD_DETAILS
},
{
links: [
{
label: 'Prescriber Guide',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Isotretinoin_2021_10_8_Prescriber_Guide.pdf'
)
},
{
label: 'Prescriber Comprehension',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Isotretinoin_2021_10_8_Comprehension_Questions.pdf'
)
}
],
stakeholderType: 'prescriber',
summary: 'iPledge/Isotretinoin REMS Prescriber Requirements',
cardDetails: CARD_DETAILS
}
],
'1237051': [
{
links: [
{
label: 'Documentation Requirements',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/TIRF_2022_08_17_REMS_Document.pdf'
)
},
{
label: 'Patient Counseling Guide',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/TIRF_2022_08_17_Patient_Counseling_Guide.pdf'
)
},
{
label: 'Patient FAQ',
type: 'absolute',
url: new URL(
'https://tirfstorageproduction.blob.core.windows.net/tirf-public/tirf-patientfaq-frequently-asked-questions.pdf?skoid=417a7522-f809-43c4-b6a8-6b192d44b69e&sktid=59fc620e-de8c-4745-abcc-18182d1bf20e&skt=2022-09-20T19%3A06%3A21Z&ske=2022-09-26T19%3A11%3A21Z&sks=b&skv=2020-04-08&sv=2020-04-08&st=2021-03-21T21%3A27%3A00Z&se=2031-03-21T23%3A59%3A59Z&sr=b&sp=rc&sig=owSGAoUBZuCtsLE41F2XC3o12x%2BG%2Bt5ogykOIt796es%3D'
)
}
],
stakeholderType: 'patient',
summary: 'TIRF REMS Patient Requirements',
cardDetails: CARD_DETAILS
},
{
links: [
{
label: 'Prescriber Education',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/TIRF_2022_08_17_Prescriber_Education.pdf'
)
},
{
label: 'Prescriber FAQ',
type: 'absolute',
url: new URL(
'https://tirfstorageproduction.blob.core.windows.net/tirf-public/tirf-prfaq-frequently-asked-questions.pdf?skoid=417a7522-f809-43c4-b6a8-6b192d44b69e&sktid=59fc620e-de8c-4745-abcc-18182d1bf20e&skt=2022-09-20T19%3A06%3A53Z&ske=2022-09-26T19%3A11%3A53Z&sks=b&skv=2020-04-08&sv=2020-04-08&st=2021-03-21T21%3A35%3A43Z&se=2031-03-21T23%3A59%3A59Z&sr=b&sp=rc&sig=fqtDzsm7qi1G8MKau210Y3gNet%2Fi20zw2EThKODdEUM%3D'
)
}
],
stakeholderType: 'prescriber',
summary: 'TIRF REMS Prescriber Requirements',
cardDetails: CARD_DETAILS
}
],
'1666386': [
{
links: [
{
label: 'Medication Guide',
type: 'absolute',
url: new URL(
'https://www.accessdata.fda.gov/drugsatfda_docs/rems/Addyi_2019_10_09_Medication_Guide.pdf'
)
}
],
stakeholderType: '',
summary: 'Addyi REMS Patient Information',
cardDetails: 'Please review safety documentation'
}
]
};
// TODO: No hardcoding of valid codes
export const validCodes: Coding[] = [
{
code: '2183126', // Turalio
system: 'http://www.nlm.nih.gov/research/umls/rxnorm'
},
{
code: '1237051', // TIRF
system: 'http://www.nlm.nih.gov/research/umls/rxnorm'
},
{
code: '6064', // iPledge
system: 'http://www.nlm.nih.gov/research/umls/rxnorm'
},
{
code: '1666386', // Addyi
system: 'http://www.nlm.nih.gov/research/umls/rxnorm'
}
];
const source = {
label: config.server.name,
url: new URL('https://github.com/mcode/rems-admin')
};
/*
* Retrieve the coding for the medication from the medicationCodeableConcept if available.
* Read coding from contained Medication matching the medicationReference otherwise.
*/
export function getDrugCodeFromMedicationRequest(
resource: FhirResource | undefined
): Coding | null {
const medicationRequest =
resource?.resourceType === 'MedicationRequest' && (resource as MedicationRequest);
if (!medicationRequest) {
return null;
}
if (medicationRequest.medicationCodeableConcept) {
return medicationRequest.medicationCodeableConcept?.coding?.[0] || null;
}
if (medicationRequest.medicationReference) {
const reference = medicationRequest.medicationReference;
const medication = medicationRequest.contained?.find(
resource =>
resource.resourceType + '/' + resource.id === reference.reference &&
resource.resourceType === 'Medication'
) as Medication;
return medication?.code?.coding?.[0] || null;
}
return null;
}
export function getFhirResource(token: string, req: TypedRequestBody) {
const ehrUrl = `${req.body.fhirServer}/${token}`;
const access_token = req.body.fhirAuthorization?.access_token;
const options = {
method: 'GET',
headers: {
Authorization: `Bearer ${access_token}`
}
};
const response = axios(ehrUrl, options);
return response.then(e => {
return e.data;
});
}
export function createSmartLink(
requirementName: string,
appContext: string | null,
request: MedicationRequest | undefined
) {
let order;
if (config.general.fullResourceInAppContext) {
order = JSON.stringify(request);
} else {
order = request?.resourceType + '/' + request?.id;
}
const newLink: Link = {
label: requirementName + ' Form',
url: new URL(config.smart.endpoint),
type: 'smart',
appContext: `${appContext}&order=${order}&coverage=${request?.insurance?.[0].reference}`
};
return newLink;
}
export function buildErrorCard(reason: string) {
const errorCard = new Card('Bad Request', reason, source, 'warning');
const cards = {
cards: [errorCard.card]
};
return cards;
}
const getErrorCard = (
hydratedPrefetch: HookPrefetch | undefined,
contextRequest: FhirResource | undefined
): { cards: Card[] } | null => {
if (!contextRequest) {
return buildErrorCard('DraftOrders does not contain a request');
}
if (contextRequest && contextRequest.resourceType !== 'MedicationRequest') {
return buildErrorCard('DraftOrders does not contain a MedicationRequest');
}
const prefetchRequest = hydratedPrefetch?.request;
if (
prefetchRequest?.id &&
contextRequest &&
contextRequest.id &&
prefetchRequest.id.replace('MedicationRequest/', '') !==
contextRequest.id.replace('MedicationRequest/', '')
) {
return buildErrorCard('Context draftOrder does not match prefetch MedicationRequest ID');
}
const medicationCode = getDrugCodeFromMedicationRequest(contextRequest) as Coding;
if (!medicationCode?.code) {
return buildErrorCard('MedicationRequest does not contain a code');
}
const shouldReturnCard = validCodes.some(e => {
return e.code === medicationCode.code && e.system === medicationCode.system;
});
if (!shouldReturnCard) {
return buildErrorCard('Unsupported code');
}
return null;
};
// handles order-sign and order-select currently
export const handleCardOrder = async (
res: any,
hydratedPrefetch: HookPrefetch | undefined,
contextRequest: FhirResource | undefined,
resource: FhirResource | undefined,
fhirServer?: string
): Promise<void> => {
const patient = resource?.resourceType === 'Patient' ? resource : undefined;
console.log('hydratedPrefetch: ' + JSON.stringify(hydratedPrefetch));
const pharmacy = hydratedPrefetch?.pharmacy as HealthcareService;
console.log(' Pharmacy: ' + pharmacy);
const errorCard = getErrorCard(hydratedPrefetch, contextRequest);
if (errorCard) {
res.json(errorCard);
return;
}
// find the drug in the medicationCollection to get the smart links
const coding = !errorCard && (getDrugCodeFromMedicationRequest(contextRequest) as Coding);
const { code, system, display } = coding;
const request = coding && (contextRequest as MedicationRequest);
const drug = await medicationCollection
.findOne({
code: code,
codeSystem: system
})
.exec();
// find a matching REMS case for the patient and this drug to only return needed results
const patientName = patient?.name?.[0];
const patientBirth = patient?.birthDate;
let remsCase = await remsCaseCollection.findOne({
patientFirstName: patientName?.given?.[0],
patientLastName: patientName?.family,
patientDOB: patientBirth,
drugCode: code
});
// If no REMS case exists and drug has requirements, create case with all requirements unmet
if (!remsCase && drug && patient && request) {
const requiresCase = drug.requirements.some(req => req.requiredToDispense);
if (requiresCase && fhirServer) {
try {
const patientReference = `Patient/${patient.id}`;
const medicationRequestReference = `${request.resourceType}/${request.id}`;
const practitionerReference = request.requester?.reference || '';
const pharmacistReference = pharmacy?.id ? `HealthcareService/${pharmacy.id}` : '';
const newCase = await createNewRemsCaseFromCDSHook(
patient,
drug,
practitionerReference,
pharmacistReference,
patientReference,
medicationRequestReference,
fhirServer
);
remsCase = newCase;
console.log(`Created REMS case from CDS Hook with originating server: ${fhirServer}`);
} catch (error) {
console.error('Failed to create REMS case from CDS Hook:', error);
}
}
}
const codeRule = (code && codeMap[code]) || [];
const cardPromises = codeRule.map(
getCardOrEmptyArrayFromRules(display, drug, remsCase, request, patient)
);
const remsCards: Card[] = (await Promise.all(cardPromises)).flat();
// Create pharmacy status card once (if pharmacy exists)
const allCards: Card[] = [];
if (pharmacy) {
const pharmacyStatusCard = await createPharmacyStatusCard(pharmacy, drug, display);
if (pharmacyStatusCard) {
allCards.push(pharmacyStatusCard);
}
}
// Add all REMS cards after the pharmacy card
allCards.push(...remsCards);
res.json({ cards: allCards });
};
const createPharmacyStatusCard = async (
pharmacy: HealthcareService,
drug: MongooseMedication | null,
display: string | undefined
): Promise<Card | null> => {
if (!pharmacy) {
return null;
}
const isCertified = await checkPharmacyCertification(pharmacy, drug?.code);
const pharmacyName = pharmacy.name || 'Selected pharmacy';
const locationInfo = pharmacy.location?.[0]?.display;
const fullPharmacyName = `${pharmacyName} (${locationInfo})`;
const statusText = `${fullPharmacyName} **is ${
isCertified ? 'certified' : 'not yet certified'
}** for ${display || 'this medication'} REMS dispensing. This medication **${
isCertified ? 'can' : 'cannot yet'
}** be dispensed at this location.`;
const pharmacyStatusCard = new Card(
'Pharmacy Certification Status',
statusText,
source,
isCertified ? 'info' : 'warning'
);
// No links or suggestions for this card - it's informational only
return pharmacyStatusCard;
};
const getCardOrEmptyArrayFromRules =
(
display: string | undefined,
drug: MongooseMedication | null,
remsCase: RemsCase | null,
request: MedicationRequest,
patient: Patient | undefined
) =>
async (rule: CardRule): Promise<Card | never[]> => {
const card = new Card(
rule.summary || display || 'Rems',
rule.cardDetails || CARD_DETAILS,
source,
'info'
);
// no construction needed
const absoluteLinks = rule.links.filter(e => e.type === 'absolute');
card.addLinks(absoluteLinks);
const requirements =
drug?.requirements.filter(
requirement => requirement.stakeholderType === rule.stakeholderType
) || [];
// process the smart links from the medicationCollection
// TODO: smart links should be built with discovered questionnaires, not hard coded ones
const predicate = (requirement: Requirement) => {
const metRequirement =
remsCase &&
remsCase.metRequirements.find(
metRequirement => metRequirement.requirementName === requirement.name
);
const formNotProcessed = metRequirement && !metRequirement.completed;
const notFound = remsCase && !metRequirement;
const noEtasuToCheckAndRequiredToDispense = !remsCase && requirement.requiredToDispense;
return formNotProcessed || notFound || noEtasuToCheckAndRequiredToDispense;
};
const smartLinks: Link[] = getSmartLinks(requirements, request, predicate);
card.addLinks(smartLinks);
const suggestions: Suggestion[] = getSuggestions(requirements, request, patient, predicate);
card.addSuggestions(suggestions);
const unmetRequirementSmartLinkCount = smartLinks.length;
const smartLinkCount = requirements.length;
const existsSmartLinksToNeededForms = unmetRequirementSmartLinkCount > 0;
const isInformationOnlyCard = smartLinkCount === 0;
if (existsSmartLinksToNeededForms || isInformationOnlyCard) {
return card;
}
return [];
};
const checkPharmacyCertification = async (
pharmacy: HealthcareService | undefined,
drugCode: string | undefined
) => {
if (!pharmacy?.id || !drugCode) {
return false;
}
const drug = await medicationCollection
.findOne({
code: drugCode,
codeSystem: 'http://www.nlm.nih.gov/research/umls/rxnorm'
})
.exec();
if (!drug) {
return false;
}
const requiredPharmacistRequirements = drug.requirements.filter(
requirement => requirement.stakeholderType === 'pharmacist' && requirement.requiredToDispense
);
if (requiredPharmacistRequirements.length === 0) {
return true;
}
const pharmacyId = `HealthcareService/${pharmacy.id}`;
for (const requirement of requiredPharmacistRequirements) {
const metRequirement = await metRequirementsCollection
.findOne({
stakeholderId: pharmacyId,
requirementName: requirement.name,
drugName: drug.name,
completed: true
})
.exec();
if (!metRequirement) {
return false;
}
}
return true;
};
const getSmartLinks = (
requirements: Requirement[],
request: MedicationRequest,
predicate: (requirement: Requirement) => boolean
): Link[] => {
return requirements.map(getLinkOrEmptyArray(request, predicate)).flat() || [];
};
const getSuggestions = (
requirements: Requirement[],
request: MedicationRequest,
patient: Patient | undefined,
predicate: (requirement: Requirement) => boolean
): Suggestion[] => {
return (
(patient && requirements.map(getSuggestionOrEmptyArray(patient, request, predicate)).flat()) ||
[]
);
};
// handles preliminary card creation. ALL hooks should go through this function.
// make sure code here is applicable to all supported hooks.
export async function handleCard(
req: TypedRequestBody,
res: any,
hydratedPrefetch: HookPrefetch,
contextRequest: FhirResource | undefined,
callback: HandleCallback
) {
const context = req.body.context;
const patient = hydratedPrefetch?.patient;
const practitioner = hydratedPrefetch?.practitioner;
const fhirServer = req.body.fhirServer;
console.log(' Patient: ' + patient?.id);
// verify ids
if (
patient?.id &&
patient.id.replace('Patient/', '') !== context.patientId?.replace('Patient/', '')
) {
res.json(buildErrorCard('Context patientId does not match prefetch Patient ID'));
return;
}
if (
practitioner?.id &&
practitioner.id.replace('Practitioner/', '') !== context.userId?.replace('Practitioner/', '')
) {
res.json(buildErrorCard('Context userId does not match prefetch Practitioner ID'));
return;
}
return callback(res, hydratedPrefetch, contextRequest, patient, fhirServer);
}
// handles all hooks, any supported hook should pass through this function
export function handleHook(
req: TypedRequestBody,
res: any,
hookPrefetch: ServicePrefetch,
contextRequest: FhirResource | undefined,
callback: HandleCallback
) {
try {
const fhirUrl = req.body.fhirServer;
const fhirAuth = req.body.fhirAuthorization;
if (fhirUrl && fhirAuth && fhirAuth.access_token) {
hydrate(getFhirResource, hookPrefetch, req.body).then(hydratedPrefetch => {
handleCard(req, res, hydratedPrefetch, contextRequest, callback);
});
} else {
if (req.body.prefetch) {
handleCard(req, res, req.body.prefetch, contextRequest, callback);
} else {
handleCard(req, res, {}, contextRequest, callback);
}
}
} catch (error) {
console.log(error);
res.json(buildErrorCard('Unknown Error'));
}
}
// process the MedicationRequests to add the Medication into contained resources
const refersToMedication = (entry: BundleEntry<FhirResource>): boolean =>
entry.resource?.resourceType === 'Medication';
const refersToMedicationRequest = (entry: BundleEntry<FhirResource>): boolean =>
entry.resource?.resourceType === 'MedicationRequest';
const refersToMedicationWithMedicationReference = (e: BundleEntry<MedicationRequest>): boolean =>
!!e.resource?.medicationReference;
const isBundleEntryMedicationReferenced =
(medicationRequestEntry: BundleEntry<MedicationRequest>) =>
(medicationEntry: BundleEntry<Medication>): boolean =>
medicationEntry?.resource?.resourceType + '/' + medicationEntry?.resource?.id ===
medicationRequestEntry.resource?.medicationReference?.reference;
const createBundleEntryWhoseMedicationRequestContainsReferencedMedication =
(medicationEntries: BundleEntry<Medication>[]) =>
(medicationRequestEntry: BundleEntry<MedicationRequest>): BundleEntry<MedicationRequest> => {
if (!medicationRequestEntry.resource) {
return medicationRequestEntry;
}
const referencedMedication = medicationEntries.find(
isBundleEntryMedicationReferenced(medicationRequestEntry)
)?.resource;
const contained = getContained(medicationRequestEntry, referencedMedication);
const mutatedMedicationRequestEntry: BundleEntry<MedicationRequest> = {
...medicationRequestEntry,
resource: {
...medicationRequestEntry.resource,
contained
}
};
return mutatedMedicationRequestEntry;
};
const getContained = (
medicationRequestEntry: BundleEntry<MedicationRequest>,
referencedMedication: Medication | undefined
): FhirResource[] => {
const existingContained = medicationRequestEntry.resource?.contained;
if (existingContained) {
const foundReferencedMedication = existingContained.find(
c => c.id === referencedMedication?.id
);
if (foundReferencedMedication || !referencedMedication) {
return existingContained;
}
return [...existingContained, referencedMedication];
}
if (!referencedMedication) {
return [];
}
return [referencedMedication];
};
const processMedicationRequests = (
medicationRequestsBundle: Bundle<MedicationRequest | Medication | FhirResource> | undefined
): Bundle<MedicationRequest | Medication | FhirResource> | undefined => {
if (!medicationRequestsBundle) {
return undefined;
}
const { entry = [], ...rest } = medicationRequestsBundle;
const medicationRequestEntries = entry.filter(
refersToMedicationRequest
) as BundleEntry<MedicationRequest>[];
const medicationRequestEntriesWithMedicationReference = medicationRequestEntries.filter(
refersToMedicationWithMedicationReference
);
const medicationEntries = entry.filter(refersToMedication) as BundleEntry<Medication>[];
const medicationRequestEntriesMutatedWithMedicationReference =
medicationRequestEntriesWithMedicationReference.map(
createBundleEntryWhoseMedicationRequestContainsReferencedMedication(medicationEntries)
);
const otherEntries = entry.filter(e => !refersToMedication(e) && !refersToMedicationRequest(e));
const medicationRequestEntriesWithoutMedicationReference = medicationRequestEntries.filter(
e => !refersToMedicationWithMedicationReference(e)
);
return {
...rest,
entry: [
...otherEntries,
...medicationEntries,
...medicationRequestEntriesWithoutMedicationReference,
...medicationRequestEntriesMutatedWithMedicationReference
]
};
};
const getSummary = (drugCode: string, drugName: string): string => {
const codeRule = codeMap[drugCode];
const rule = codeRule.find(rule => rule.stakeholderType === 'patient');
const summary = rule?.summary || drugName || 'Rems';
return summary;
};
const containsMatchingMedicationRequest =
(drugCode: string) =>
(entry: BundleEntry): boolean => {
if (entry.resource?.resourceType === 'MedicationRequest') {
const medReq: MedicationRequest = entry.resource;
const medicationCode = getDrugCodeFromMedicationRequest(medReq);
return drugCode === medicationCode?.code;
}
return false;
};
const getCardOrEmptyArrayFromCases =
(entries: BundleEntry[] | undefined) =>
async ({ drugCode, drugName, metRequirements }: RemsCase): Promise<Card | never[]> => {
// find the drug in the medicationCollection that matches the REMS case to get the smart links
const drug = await medicationCollection
.findOne({
code: drugCode,
name: drugName
})
.exec();
// get the rule summary from the codemap
const summary = getSummary(drugCode, drugName);
// create the card
const card = new Card(summary, CARD_DETAILS, source, 'info');
// find the matching MedicationRequest for the context
const request = (entries || []).find(containsMatchingMedicationRequest(drugCode))?.resource;
// if no valid request or not a MedicationRequest found skip this REMS case
if (!request || (request && request.resourceType !== 'MedicationRequest')) {
return [];
}
// grab absolute links relevant to the patient
const codeRule = codeMap[drugCode];
const rule = codeRule.find(rule => rule.stakeholderType === 'patient');
const absoluteLinks = rule?.links || [];
card.addLinks(absoluteLinks);
// find all of the matching patient forms
const requirements =
drug?.requirements.filter(requirement => requirement.stakeholderType === 'patient') || [];
// loop through all of the ETASU requirements for this drug
const predicate = (requirement: Requirement) => {
// match the requirement to the metRequirement of the REMS case
const metRequirement = metRequirements.find(metRequirement => {
return metRequirement.requirementName === requirement.name;
});
const formNotProcessed = metRequirement && !metRequirement.completed;
const notFound = !metRequirement;
return formNotProcessed || notFound;
};
const smartLinks = getSmartLinks(requirements, request, predicate);
card.addLinks(smartLinks);
return card;
};
const getLinkOrEmptyArray =
(request: MedicationRequest, predicate: (requirement: Requirement) => boolean) =>
(requirement: Requirement): Link | [] => {
const link = createSmartLink(requirement.name, requirement.appContext, request);
if (predicate(requirement)) {
return link;
}
return [];
};
const getSuggestionOrEmptyArray =
(
patient: Patient,
request: MedicationRequest,
predicate: (requirement: Requirement) => boolean
) =>
(requirement: Requirement): Suggestion | [] => {
const suggestion = getQuestionnaireSuggestion(requirement, patient, request);
if (suggestion && predicate(requirement)) {
return suggestion;
}
return [];
};
// handles patient-view and encounter-start currently
export const handleCardEncounter = async (
res: any,
hookPrefetch: HookPrefetch | undefined,
_contextRequest: FhirResource | undefined,
resource: FhirResource | undefined,
fhirServer?: string
): Promise<void> => {
const patient = resource?.resourceType === 'Patient' ? resource : undefined;
const medResource = hookPrefetch?.medicationRequests;
const medicationRequestsBundle =
medResource?.resourceType === 'Bundle'
? // process the MedicationRequests to add the Medication into contained resources
processMedicationRequests(medResource)
: undefined;
// find all matching REMS cases for the patient
const patientName = patient?.name?.[0];
const patientBirth = patient?.birthDate;
const remsCaseList = await remsCaseCollection.find({
patientFirstName: patientName?.given?.[0],
patientLastName: patientName?.family,
patientDOB: patientBirth
});
// loop through all the REMS cases in the list
const promises = remsCaseList.map(getCardOrEmptyArrayFromCases(medicationRequestsBundle?.entry));
const cards = (await Promise.all(promises)).flat();
res.json({ cards });
};
export const getQuestionnaireSuggestion = (
requirement: Requirement,
patient: Patient,
request: MedicationRequest
): Suggestion | undefined => {
if (requirement.appContext && requirement.appContext.includes('=')) {
const qArr = requirement.appContext.split('='); // break up into parts
let qUrl = null;
for (let i = 0; i < qArr.length; i++) {
if (qArr[i].toLowerCase() === 'questionnaire') {
if (i + 1 < qArr.length) {
// not at end of array
qUrl = qArr[i + 1];
}
}
}
if (qUrl) {
const action: Action = {
type: 'create',
description: `Create task for "completion of ${requirement.name} Questionnaire"`,
resource: createQuestionnaireCompletionTask(requirement, patient, qUrl, request)
};
const suggestion: Suggestion = {
label: `Add "Completion of ${requirement.name} Questionnaire" to task list`,
actions: [action]
};
return suggestion;
}
}
return undefined;
};
export function createQuestionnaireCompletionTask(
requirement: Requirement,
patient: Patient,
questionnaireUrl: string,
request: MedicationRequest
) {
const taskResource: Task = {
resourceType: 'Task',
status: 'ready',
intent: 'order',
code: {
coding: [
{
system: 'http://hl7.org/fhir/uv/sdc/CodeSystem/temp',
code: 'complete-questionnaire'
},
{
system: 'http://hl7.org/fhir/smart-app-launch/CodeSystem/smart-codes',
code: 'launch-app-ehr',
display: 'Launch application using the SMART EHR launch'
}
]
},
description: `Complete ${requirement.name} Questionnaire`,
for: {
reference: `${patient.resourceType}/${patient.id}`
},
requester: {
reference: `${request.requester?.reference}`
},
authoredOn: `${new Date(Date.now()).toISOString()}`,
input: [
{
type: {
text: 'questionnaire'
},
valueCanonical: `${questionnaireUrl}`
},
{
type: {
coding: [
{
system: 'http://hl7.org/fhir/smart-app-launch/CodeSystem/smart-codes',
code: 'smartonfhir-application',
display: 'SMART on FHIR application URL.'
}
]
},
valueUrl: config.smart.endpoint
},
{
type: {
coding: [
{
system: 'http://hl7.org/fhir/smart-app-launch/CodeSystem/smart-codes',
code: 'smartonfhir-appcontext',
display: 'Application context related to this launch.'
}
]
},
valueString: `${requirement.appContext}&order=${JSON.stringify(request)}&coverage=${
request?.insurance?.[0].reference
}`
}
]
};
return taskResource;
}