@medplum/health-gorilla-react 4.4.1 → 4.4.2

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.
package/LICENSE.txt ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/index.ts", "../../src/autocomplete-endpoint.ts", "../../src/HealthGorillaLabOrderContext.ts", "../../src/HealthGorillaLabOrderProvider.tsx", "../../src/useHealthGorillaLabOrder.ts", "../../src/useHealthGorillaLabOrderContext.ts"],
4
- "sourcesContent": ["// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nexport * from './autocomplete-endpoint';\nexport * from './HealthGorillaLabOrderContext';\nexport * from './HealthGorillaLabOrderProvider';\nexport * from './useHealthGorillaLabOrder';\nexport * from './useHealthGorillaLabOrderContext';\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ContentType, MedplumClient, isCoding, isResource } from '@medplum/core';\nimport { Identifier, Questionnaire } from '@medplum/fhirtypes';\nimport { HGAutocompleteBotResponse, LabOrganization, TestCoding } from '@medplum/health-gorilla-core';\n\nexport type LabSearchParams = { type: 'lab'; query: string };\nexport type TestSearchParams = { type: 'test'; query: string; labId: string };\nexport type AOESearchParams = { type: 'aoe'; testCode: TestCoding };\n\nexport type LabSearchResult = { type: 'lab'; result: LabOrganization[] };\nexport type TestSearchResult = { type: 'test'; result: TestCoding[] };\nexport type AOESearchResult = { type: 'aoe'; result: Questionnaire | undefined };\n\nexport type LabSearch = { params: LabSearchParams; results: LabSearchResult };\nexport type TestSearch = { params: TestSearchParams; results: TestSearchResult };\nexport type AOESearch = { params: AOESearchParams; results: AOESearchResult };\nexport type HGSearch = LabSearch | TestSearch | AOESearch;\n\nexport type HGSearchFunction = <T extends HGSearch>(params: T['params']) => Promise<T['results']>;\n\nexport function getAutocompleteSearchFunction(\n medplum: MedplumClient,\n autocompleteBot: string | Identifier\n): HGSearchFunction {\n return async (params) => {\n const botResponse: HGAutocompleteBotResponse = await medplum.executeBot(autocompleteBot, params, ContentType.JSON);\n if (botResponse.type === 'error') {\n throw new Error('Error executing autocomplete bot', { cause: botResponse });\n }\n\n const { result } = botResponse;\n switch (botResponse.type) {\n case 'lab': {\n if (Array.isArray(result) && result.every((item) => isResource(item, 'Organization'))) {\n return { type: 'lab', result } as LabSearchResult;\n }\n break;\n }\n case 'test': {\n const { result } = botResponse;\n if (Array.isArray(result) && result.every((item) => isCoding(item))) {\n return { type: 'test', result } as TestSearchResult;\n }\n break;\n }\n case 'aoe': {\n const { result } = botResponse;\n if (result === undefined || result.resourceType === 'Questionnaire') {\n return { type: 'aoe', result } as AOESearchResult;\n }\n break;\n }\n default: {\n botResponse satisfies never;\n }\n }\n throw new Error(`Invalid bot response for ${JSON.stringify(params)}`);\n };\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Bundle, Coverage, Questionnaire, ServiceRequest } from '@medplum/fhirtypes';\nimport {\n BillingInformation,\n DiagnosisCodeableConcept,\n LabOrderInputErrors,\n LabOrderTestMetadata,\n LabOrganization,\n TestCoding,\n} from '@medplum/health-gorilla-core';\nimport { createContext } from 'react';\n\nexport type TestMetadata = LabOrderTestMetadata & {\n aoeStatus: 'loading' | 'loaded' | 'none' | 'error';\n /** The AOE `Questionnaire`, if any, containing Ask at Order Entry (AOE) questions for the test. */\n aoeQuestionnaire?: Questionnaire;\n};\n\nexport type HealthGorillaLabOrderState = {\n performingLab: LabOrganization | undefined;\n performingLabAccountNumber: string | undefined;\n selectedTests: TestCoding[];\n testMetadata: Record<string, TestMetadata | undefined>;\n diagnoses: DiagnosisCodeableConcept[];\n billingInformation: BillingInformation;\n specimenCollectedDateTime: Date | undefined;\n orderNotes: string | undefined;\n};\n\nexport type UseHealthGorillaLabOrderReturn = {\n state: HealthGorillaLabOrderState;\n\n searchAvailableLabs: (query: string) => Promise<LabOrganization[]>;\n /**\n * Set the desired performer for doing the diagnostic testing. Compatible with\n * results from the `searchAvailableLabs` function.\n */\n setPerformingLab: (lab: LabOrganization | undefined) => void;\n /**\n * Sets the account number for the performing lab. If not provided, the\n * `HEALTH_GORILLA_SUBTENANT_ACCOUNT_NUMBER` `Project.secret` is used.\n */\n setPerformingLabAccountNumber: (accountNumber: string | undefined) => void;\n\n searchAvailableTests: (query: string) => Promise<TestCoding[]>;\n addTest: (test: TestCoding) => void;\n removeTest: (test: TestCoding) => void;\n setTests: (tests: TestCoding[]) => void;\n\n updateTestMetadata: (test: TestCoding, metadata: Partial<LabOrderTestMetadata>) => void;\n\n addDiagnosis: (diagnosis: DiagnosisCodeableConcept) => void;\n removeDiagnosis: (diagnosis: DiagnosisCodeableConcept) => void;\n setDiagnoses: (diagnoses: DiagnosisCodeableConcept[]) => void;\n\n getActivePatientCoverages: () => Promise<Coverage[]>;\n updateBillingInformation: (billingInfo: Partial<BillingInformation>) => void;\n\n setSpecimenCollectedDateTime: (date: Date | undefined) => void;\n\n setOrderNotes: (orderNotes: string | undefined) => void;\n\n validateOrder: () => LabOrderInputErrors | undefined;\n createOrderBundle: () => Promise<{ transactionResponse: Bundle; serviceRequest: ServiceRequest }>;\n};\n\nexport const HealthGorillaLabOrderContext = createContext<UseHealthGorillaLabOrderReturn | undefined>(undefined);\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { JSX, PropsWithChildren } from 'react';\nimport { HealthGorillaLabOrderContext, UseHealthGorillaLabOrderReturn } from './HealthGorillaLabOrderContext';\n\n/**\n * A provider component that propagates the `useHealthGorillaLabOrder` return value to all children components via [React Context](https://reactjs.org/docs/context.html) API. To be used with {@link useHealthGorillaLabOrderContext}.\n *\n * @param props - entire response of `useHealthGorillaLabOrder`\n * @returns a React context provider component.\n *\n * @example\n * ```tsx\n * function App() {\n * const labOrderReturn = useHealthGorillaLabOrder({...});\n * return (\n * <HealthGorillaLabOrderProvider {...methods} >\n * <form onSubmit={labOrderReturn.createOrderBundle()}>\n * <PerformingLabInput />\n * <input type=\"submit\" />\n * </form>\n * </HealthGorillaLabOrderProvider>\n * );\n * }\n *\n * function PerformingLabInput() {\n * const { searchAvailableLabs, setPerformingLab } = useHealthGorillaLabOrderContext();\n * return (\n * <AsyncAutocomplete<LabOrganization>\n * maxValues={1}\n * loadOptions={searchAvailableLabs}\n * onChange={(item) => {\n * if (item.length > 0) {\n * setPerformingLab(item[0]);\n * } else {\n * setPerformingLab(undefined);\n * }\n * }}\n * />\n * );\n * }\n * ```\n */\nexport function HealthGorillaLabOrderProvider(props: PropsWithChildren<UseHealthGorillaLabOrderReturn>): JSX.Element {\n const { children, ...labOrderReturn } = props;\n return (\n <HealthGorillaLabOrderContext.Provider value={labOrderReturn}>{children}</HealthGorillaLabOrderContext.Provider>\n );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ResourceArray, createReference, deepClone, getExtensionValue, getIdentifier, isResource } from '@medplum/core';\nimport {\n Bundle,\n Coverage,\n Location,\n Organization,\n Patient,\n Practitioner,\n Questionnaire,\n Reference,\n ServiceRequest,\n} from '@medplum/fhirtypes';\nimport {\n BillingInformation,\n DiagnosisCodeableConcept,\n HEALTH_GORILLA_SYSTEM,\n LabOrderServiceRequest,\n LabOrderTestMetadata,\n LabOrganization,\n MEDPLUM_HEALTH_GORILLA_LAB_ORDER_PROFILE,\n TestCoding,\n createLabOrderBundle,\n isReferenceOfType,\n normalizeAoeQuestionnaire,\n questionnaireItemIterator,\n validateLabOrderInputs,\n} from '@medplum/health-gorilla-core';\nimport { useMedplum } from '@medplum/react';\nimport { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';\nimport { AOESearch, LabSearch, TestSearch, getAutocompleteSearchFunction } from './autocomplete-endpoint';\nimport {\n HealthGorillaLabOrderState,\n TestMetadata,\n UseHealthGorillaLabOrderReturn,\n} from './HealthGorillaLabOrderContext';\n\nexport type UseHealthGorillaLabOrderOptions = {\n /** Patient the tests are ordered for. */\n patient: Patient | (Reference<Patient> & { reference: string }) | undefined;\n /**\n * The physician who requests diagnostic procedures for the patient and responsible for the order.\n * The Practitioner MUST have an NPI identifier with the system http://hl7.org/fhir/sid/us-npi.\n */\n requester: Practitioner | (Reference<Practitioner> & { reference: string }) | undefined;\n\n /** For multi-location practices, optionally specify the location from which the order is being placed */\n requestingLocation?: Location | Organization | (Reference<Location | Organization> & { reference: string });\n};\n\nexport type EditableLabOrderTestMetadata = Pick<LabOrderTestMetadata, 'priority' | 'notes' | 'aoeResponses'>;\nconst EDITABLE_TEST_METADATA_KEYS: (keyof LabOrderTestMetadata)[] = ['priority', 'notes', 'aoeResponses'];\n\nconst INITIAL_TESTS: TestCoding[] = [];\nconst INITIAL_DIAGNOSES: DiagnosisCodeableConcept[] = [];\nconst INITIAL_TEST_METADATA = {};\nconst INITIAL_BILLING_INFORMATION: BillingInformation = {};\n\ntype TestsReducerState = {\n // Don't use any optional fields here, e.g. `selectedTests?: TestCoding[]` since that would cause\n // some loss of type safety in the reducer function by allowing the reducer to potentially return\n // incomplete state if a field is forgotten about. Instead, always use explicity `| undefined` for\n // fields that may legitimately be undefined in the state.\n\n selectedTests: TestCoding[];\n testMetadata: Record<string, TestMetadata | undefined>;\n specimenCollectedDateTime: Date | undefined;\n};\n\ntype AddTestAction = { type: 'add'; test: TestCoding };\ntype RemoveTestAction = { type: 'remove'; test: TestCoding };\ntype SetTestsAction = { type: 'set'; tests: TestCoding[] };\ntype UpdateMetadataAction = {\n type: 'updateMetadata';\n test: TestCoding;\n partialMetadata: Partial<EditableLabOrderTestMetadata>;\n};\ntype AoeLoadedAction = { type: 'aoeLoaded'; testAoes: [TestCoding, Questionnaire | undefined][] };\ntype SpecimentCollectionDateChangeAction = { type: 'specimenCollectionDateChange'; newDate: Date | undefined };\ntype AoeErrorAction = { type: 'aoeError'; tests: TestCoding[] };\n\ntype TestsAction =\n | AddTestAction\n | RemoveTestAction\n | SetTestsAction\n | UpdateMetadataAction\n | AoeLoadedAction\n | SpecimentCollectionDateChangeAction\n | AoeErrorAction;\n\nfunction testsReducer(prev: TestsReducerState, action: TestsAction): TestsReducerState {\n switch (action.type) {\n case 'add':\n return addTest(prev, action);\n case 'remove':\n return removeTest(prev, action);\n case 'set':\n return setTests(prev, action);\n case 'updateMetadata':\n return updateMetadata(prev, action);\n case 'aoeLoaded':\n return aoeLoaded(prev, action);\n case 'aoeError':\n return aoeError(prev, action);\n case 'specimenCollectionDateChange':\n return specimenCollectionDateChange(prev, action);\n default:\n action satisfies never;\n return prev;\n }\n}\n\nfunction addTest(prev: TestsReducerState, action: AddTestAction): TestsReducerState {\n if (prev.selectedTests.some((test) => test.code === action.test.code)) {\n return prev;\n }\n\n return {\n ...prev,\n selectedTests: [...prev.selectedTests, action.test],\n testMetadata: {\n ...prev.testMetadata,\n [action.test.code]: { aoeStatus: 'loading' },\n },\n };\n}\n\nfunction removeTest(prev: TestsReducerState, action: RemoveTestAction): TestsReducerState {\n return {\n ...prev,\n selectedTests: prev.selectedTests.filter((test) => test.code !== action.test.code),\n testMetadata: Object.fromEntries(Object.entries(prev.testMetadata).filter(([code]) => code !== action.test.code)),\n };\n}\n\nfunction setTests(prev: TestsReducerState, action: SetTestsAction): TestsReducerState {\n return {\n ...prev,\n selectedTests: action.tests,\n testMetadata: Object.fromEntries(\n action.tests.map((test) => {\n return [test.code, prev.testMetadata[test.code] ?? { aoeStatus: 'loading' }];\n })\n ),\n };\n}\n\nfunction updateMetadata(prev: TestsReducerState, action: UpdateMetadataAction): TestsReducerState {\n const { test, partialMetadata } = action;\n\n const prevTestMetadata = prev.testMetadata[test.code];\n if (!prev.selectedTests.some((t) => t.code === test.code) || !prevTestMetadata) {\n console.warn(`Cannot update metadata for test ${test.code} since it is not a selected tests`);\n return prev;\n }\n\n let allowedUpdates = partialMetadata;\n const restrictedKeys = Object.keys(partialMetadata).filter((k) => !EDITABLE_TEST_METADATA_KEYS.includes(k as any));\n\n if (restrictedKeys.length > 0) {\n console.warn(`Cannot update test metadata fields: ${restrictedKeys.join(', ')}`);\n\n allowedUpdates = Object.fromEntries(Object.entries(partialMetadata).filter(([k]) => !restrictedKeys.includes(k)));\n }\n\n return {\n ...prev,\n testMetadata: {\n ...prev.testMetadata,\n [test.code]: { ...prevTestMetadata, ...allowedUpdates },\n },\n };\n}\n\nfunction aoeLoaded(prev: TestsReducerState, action: AoeLoadedAction): TestsReducerState {\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const [test, aoeQuestionnaire] of action.testAoes) {\n const prevMetadata = prev.testMetadata[test.code];\n if (!prevMetadata) {\n continue;\n }\n\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = {\n ...prevMetadata,\n aoeStatus: aoeQuestionnaire ? 'loaded' : 'none',\n aoeQuestionnaire:\n aoeQuestionnaire &&\n (updateAoeQuestionnaireRequiredItems(aoeQuestionnaire, prev.specimenCollectedDateTime) ?? aoeQuestionnaire),\n };\n }\n\n if (!newTestMetadata) {\n return prev;\n }\n\n return {\n ...prev,\n testMetadata: newTestMetadata,\n };\n}\n\nfunction aoeError(prev: TestsReducerState, action: AoeErrorAction): TestsReducerState {\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const test of action.tests) {\n const prevMetadata = prev.testMetadata[test.code];\n if (!prevMetadata || prevMetadata.aoeStatus !== 'loading') {\n continue;\n }\n\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = {\n ...prevMetadata,\n aoeStatus: 'error',\n };\n }\n\n if (!newTestMetadata) {\n return prev;\n }\n\n return {\n ...prev,\n testMetadata: newTestMetadata,\n };\n}\n\nfunction specimenCollectionDateChange(\n prev: TestsReducerState,\n action: SpecimentCollectionDateChangeAction\n): TestsReducerState {\n // check if we can reuse the previous testMetadata object to avoid unnecessary downstream re-renders\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const test of prev.selectedTests) {\n const prevTestMetadata = prev.testMetadata[test.code];\n if (!prevTestMetadata) {\n continue;\n }\n\n if (prevTestMetadata.aoeQuestionnaire) {\n const newAoeQ = updateAoeQuestionnaireRequiredItems(prevTestMetadata.aoeQuestionnaire, action.newDate);\n if (newAoeQ) {\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = { ...prevTestMetadata, aoeQuestionnaire: newAoeQ };\n }\n }\n }\n\n return {\n ...prev,\n // If no changes to AOE questionnaire item.required, reuse the previous object\n testMetadata: newTestMetadata ?? prev.testMetadata,\n specimenCollectedDateTime: action.newDate,\n };\n}\n\nexport function useHealthGorillaLabOrder(opts: UseHealthGorillaLabOrderOptions): UseHealthGorillaLabOrderReturn {\n const medplum = useMedplum();\n const [performingLab, privateSetPerformingLab] = useState<LabOrganization | undefined>();\n const [performingLabAccountNumber, privateSetPerformingLabAccountNumber] = useState<string | undefined>();\n const [testsAndMetadata, dispatchTests] = useReducer(testsReducer, {\n specimenCollectedDateTime: undefined,\n selectedTests: INITIAL_TESTS,\n testMetadata: INITIAL_TEST_METADATA,\n });\n const [diagnoses, privateSetDiagnoses] = useState<DiagnosisCodeableConcept[]>(INITIAL_DIAGNOSES);\n const [billingInformation, setBillingInformation] = useState<BillingInformation>(INITIAL_BILLING_INFORMATION);\n const [orderNotes, privateSetOrderNotes] = useState<string | undefined>();\n\n const healthGorillaAutocomplete = useMemo(() => {\n return getAutocompleteSearchFunction(medplum, {\n system: 'https://www.medplum.com/integrations/bot-identifier',\n value: 'health-gorilla-labs/autocomplete',\n });\n }, [medplum]);\n\n const fetchAoeQuestionnaire = useCallback(\n async (testCode: TestCoding): Promise<Questionnaire | undefined> => {\n const response = await healthGorillaAutocomplete<AOESearch>({ type: 'aoe', testCode });\n const questionnaire = response.result;\n if (questionnaire) {\n normalizeAoeQuestionnaire(questionnaire);\n }\n return response.result;\n },\n [healthGorillaAutocomplete]\n );\n\n const lastSelectedTests = useRef<TestCoding[]>([]);\n useEffect(() => {\n // effect only runs when selectedTests changes\n if (lastSelectedTests.current === testsAndMetadata.selectedTests) {\n return;\n }\n lastSelectedTests.current = testsAndMetadata.selectedTests;\n\n const testCodingAoesBeingFetched: TestCoding[] = [];\n async function fetchNeededAoeQuestions(): Promise<[TestCoding, Questionnaire | undefined][]> {\n const promises: Promise<[TestCoding, Questionnaire | undefined]>[] = [];\n for (const test of testsAndMetadata.selectedTests) {\n const metadata = testsAndMetadata.testMetadata[test.code];\n if (metadata?.aoeStatus !== 'loading') {\n continue;\n }\n\n testCodingAoesBeingFetched.push(test);\n promises.push(\n new Promise((resolve, reject) => {\n fetchAoeQuestionnaire(test)\n .then((questionnaire) => {\n resolve([test, questionnaire]);\n })\n .catch(reject);\n })\n );\n }\n return Promise.all(promises);\n }\n\n fetchNeededAoeQuestions()\n .then((results) => {\n if (results.length === 0) {\n return;\n }\n\n dispatchTests({ type: 'aoeLoaded', testAoes: results });\n })\n .catch((err) => {\n console.error('Error fetching AOE questions', err);\n dispatchTests({ type: 'aoeError', tests: testCodingAoesBeingFetched });\n });\n }, [fetchAoeQuestionnaire, testsAndMetadata]);\n\n const patientRef = useMemo<(Reference<Patient> & { reference: string }) | undefined>(() => {\n if (isReferenceOfType('Patient', opts.patient)) {\n return opts.patient;\n } else if (isResource(opts.patient)) {\n return createReference(opts.patient);\n } else {\n return undefined;\n }\n }, [opts.patient]);\n\n const requesterRef = useMemo<(Reference<Practitioner> & { reference: string }) | undefined>(() => {\n if (isReferenceOfType('Practitioner', opts.requester)) {\n return opts.requester;\n } else if (isResource(opts.requester)) {\n return createReference(opts.requester) as Reference<Practitioner> & { reference: string };\n } else {\n opts.requester satisfies undefined;\n return undefined;\n }\n }, [opts.requester]);\n\n const requestingLocationRef = useMemo<\n (Reference<Location | Organization> & { reference: string }) | undefined\n >(() => {\n if (\n isReferenceOfType('Location', opts.requestingLocation) ||\n isReferenceOfType('Organization', opts.requestingLocation)\n ) {\n return opts.requestingLocation;\n } else if (isResource(opts.requestingLocation)) {\n return createReference(opts.requestingLocation);\n } else {\n return undefined;\n }\n }, [opts.requestingLocation]);\n\n const state: HealthGorillaLabOrderState = useMemo(() => {\n const cloned = deepClone({\n performingLab,\n performingLabAccountNumber,\n selectedTests: testsAndMetadata.selectedTests,\n testMetadata: testsAndMetadata.testMetadata,\n diagnoses,\n billingInformation,\n specimenCollectedDateTime: testsAndMetadata.specimenCollectedDateTime,\n orderNotes,\n });\n\n // specimenCollectedDateTime is a Date object which is serialized in deepClone\n if (cloned.specimenCollectedDateTime) {\n cloned.specimenCollectedDateTime = new Date(cloned.specimenCollectedDateTime);\n }\n\n return cloned;\n }, [\n performingLab,\n performingLabAccountNumber,\n testsAndMetadata.selectedTests,\n testsAndMetadata.testMetadata,\n testsAndMetadata.specimenCollectedDateTime,\n diagnoses,\n billingInformation,\n orderNotes,\n ]);\n\n const getActivePatientCoverages = useCallback(async (): Promise<ResourceArray<Coverage>> => {\n if (!patientRef) {\n const emptyResult: Coverage[] = [];\n return Object.assign(emptyResult, {\n bundle: { resourceType: 'Bundle', type: 'searchset', entry: [], total: 0 } as Bundle<Coverage>,\n });\n }\n\n const coverageSearch = new URLSearchParams({\n patient: patientRef.reference,\n status: 'active',\n });\n const coverages = (await medplum.searchResources('Coverage', coverageSearch)).sort((a, b) => {\n return (a.order ?? Number.POSITIVE_INFINITY) - (b.order ?? Number.POSITIVE_INFINITY);\n });\n\n return coverages;\n }, [medplum, patientRef]);\n\n const updateBillingInformation = useCallback((billingInfo: Partial<BillingInformation>): void => {\n setBillingInformation((prev) => {\n return { ...prev, ...billingInfo };\n });\n }, []);\n\n const result: UseHealthGorillaLabOrderReturn = useMemo(() => {\n return {\n state,\n searchAvailableLabs: async (query: string) => {\n const response = await healthGorillaAutocomplete<LabSearch>({ type: 'lab', query });\n // consider filtering to labs that have the https://www.healthgorilla.com/fhir/StructureDefinition/provider-compendium extension?\n return response.result;\n },\n searchAvailableTests: async (query: string): Promise<TestCoding[]> => {\n if (!performingLab) {\n return [];\n }\n\n const hgLabId = getIdentifier(performingLab, HEALTH_GORILLA_SYSTEM);\n if (!hgLabId) {\n throw new Error('No Health Gorilla identifier found for performing lab');\n }\n\n if (query.length === 0) {\n return [];\n }\n const response = await healthGorillaAutocomplete<TestSearch>({ type: 'test', query, labId: hgLabId });\n\n const tests = response.result;\n return tests;\n },\n setPerformingLab: (newLab: LabOrganization | undefined) => {\n privateSetPerformingLab(newLab);\n },\n setPerformingLabAccountNumber: (newAccountNumber: string | undefined) => {\n privateSetPerformingLabAccountNumber(newAccountNumber);\n },\n addTest: (test: TestCoding) => {\n dispatchTests({ type: 'add', test });\n },\n removeTest: (test: TestCoding) => {\n dispatchTests({ type: 'remove', test });\n },\n setTests: (newTests: TestCoding[]) => {\n dispatchTests({ type: 'set', tests: newTests });\n },\n\n updateTestMetadata: (test: TestCoding, partialMetadata: Partial<LabOrderTestMetadata>) => {\n dispatchTests({ type: 'updateMetadata', test, partialMetadata });\n },\n\n addDiagnosis(diagnosis: DiagnosisCodeableConcept) {\n privateSetDiagnoses((prev) => {\n if (prev.some((item) => toDiagnosisKey(item) === toDiagnosisKey(diagnosis))) {\n return prev;\n }\n return [...prev, diagnosis];\n });\n },\n removeDiagnosis(diagnosis: DiagnosisCodeableConcept) {\n privateSetDiagnoses((prev) => {\n const idx = prev.findIndex((item) => toDiagnosisKey(item) === toDiagnosisKey(diagnosis));\n if (idx === -1) {\n return prev;\n }\n const next = [...prev];\n next.splice(idx, 1);\n return next;\n });\n },\n setDiagnoses: (newDiagnoses: DiagnosisCodeableConcept[]) => {\n privateSetDiagnoses(newDiagnoses);\n },\n\n getActivePatientCoverages,\n updateBillingInformation,\n\n setSpecimenCollectedDateTime: (newDate: Date | undefined) => {\n dispatchTests({ type: 'specimenCollectionDateChange', newDate });\n },\n\n setOrderNotes: (newOrderNotes: string | undefined) => {\n // || instead of ?? so that empty string becomes undefined\n privateSetOrderNotes(newOrderNotes || undefined);\n },\n\n validateOrder: () => {\n return validateLabOrderInputs({\n patient: patientRef,\n requester: requesterRef,\n performingLab: state.performingLab,\n performingLabAccountNumber: state.performingLabAccountNumber,\n selectedTests: state.selectedTests,\n testMetadata: state.testMetadata,\n diagnoses: state.diagnoses,\n billingInformation: state.billingInformation,\n specimenCollectedDateTime: state.specimenCollectedDateTime,\n orderNotes: state.orderNotes,\n });\n },\n createOrderBundle: async (): Promise<{ transactionResponse: Bundle; serviceRequest: ServiceRequest }> => {\n const txn = createLabOrderBundle({\n patient: patientRef,\n requester: requesterRef,\n requestingLocation: requestingLocationRef,\n performingLab: state.performingLab,\n performingLabAccountNumber: state.performingLabAccountNumber,\n selectedTests: state.selectedTests,\n testMetadata: state.testMetadata,\n diagnoses: state.diagnoses,\n billingInformation: state.billingInformation,\n specimenCollectedDateTime: state.specimenCollectedDateTime,\n orderNotes: state.orderNotes,\n });\n\n const transactionResponse = await medplum.executeBatch(txn);\n\n let labOrderServiceRequest: LabOrderServiceRequest | undefined;\n\n for (const entry of transactionResponse?.entry ?? []) {\n if (!entry.response?.status.startsWith('2')) {\n throw new Error('Error creating lab order: Non-2XX status code in response entry', {\n cause: transactionResponse,\n });\n }\n if (entry.resource?.meta?.profile?.includes(MEDPLUM_HEALTH_GORILLA_LAB_ORDER_PROFILE)) {\n labOrderServiceRequest = entry.resource as LabOrderServiceRequest;\n }\n }\n\n if (!labOrderServiceRequest) {\n throw new Error('Error creating lab order: Lab Order Service Request not found in response entries', {\n cause: transactionResponse,\n });\n }\n\n return { transactionResponse, serviceRequest: labOrderServiceRequest };\n },\n };\n }, [\n getActivePatientCoverages,\n healthGorillaAutocomplete,\n medplum,\n patientRef,\n performingLab,\n requestingLocationRef,\n requesterRef,\n state,\n updateBillingInformation,\n ]);\n\n return result;\n}\n\nfunction toDiagnosisKey(diagnosis: DiagnosisCodeableConcept): string {\n return diagnosis.coding[0].code as string;\n}\n\nconst REQUIRED_WHEN_SPECIMEN =\n 'https://www.healthgorilla.com/fhir/StructureDefinition/questionnaire-requiredwhenspecimen';\n\n/**\n * Updates the required status of items in an AOE questionnaire based on whether a specimen is being collected.\n * @param questionnaire - The Questionnaire to update\n * @param specimenCollectedDateTime - The date and time the specimen was collected, if any\n * @returns A new Questionnaire with the required status of items updated, or undefined if no changes are needed\n */\nfunction updateAoeQuestionnaireRequiredItems(\n questionnaire: Questionnaire,\n specimenCollectedDateTime: Date | undefined\n): Questionnaire | undefined {\n let newQuestionnaire: Questionnaire | undefined;\n const requiredWhenSpecimen = Boolean(specimenCollectedDateTime);\n\n // first, check if the questionnaire needs any changes\n for (const item of questionnaireItemIterator(questionnaire.item)) {\n if (getExtensionValue(item, REQUIRED_WHEN_SPECIMEN) === true && Boolean(item.required) !== requiredWhenSpecimen) {\n // at least one item needs updating, so crete a clone to be updated rather than updating in place\n newQuestionnaire = deepClone(questionnaire);\n break;\n }\n }\n\n // if no changes are needed, return the original Questionnaire\n if (!newQuestionnaire) {\n return undefined;\n }\n\n // otherwise, update the cloned Questionnaire\n for (const item of questionnaireItemIterator(newQuestionnaire.item)) {\n if (getExtensionValue(item, REQUIRED_WHEN_SPECIMEN) === true) {\n if (Boolean(item.required) !== requiredWhenSpecimen) {\n item.required = requiredWhenSpecimen;\n }\n }\n }\n\n return newQuestionnaire;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { useContext } from 'react';\nimport { HealthGorillaLabOrderContext, UseHealthGorillaLabOrderReturn } from './HealthGorillaLabOrderContext';\n\nexport function useHealthGorillaLabOrderContext(): UseHealthGorillaLabOrderReturn {\n const context = useContext(HealthGorillaLabOrderContext);\n if (context === undefined) {\n throw new Error('useHealthGorillaLabOrderContext must be used within a HealthGorillaLabOrderProvider');\n }\n return context;\n}\n"],
5
- "mappings": "wpBAAA,kZCEA,gBAAiE,yBAmB1D,SAAS,8BACd,QACA,gBACkB,CAClB,MAAO,OAAO,QAAW,CACvB,IAAM,YAAyC,MAAM,QAAQ,WAAW,gBAAiB,OAAQ,wBAAY,IAAI,EACjH,GAAI,YAAY,OAAS,QACvB,MAAM,IAAI,MAAM,mCAAoC,CAAE,MAAO,WAAY,CAAC,EAG5E,GAAM,CAAE,MAAO,EAAI,YACnB,OAAQ,YAAY,KAAM,CACxB,IAAK,MAAO,CACV,GAAI,MAAM,QAAQ,MAAM,GAAK,OAAO,MAAO,SAAS,wBAAW,KAAM,cAAc,CAAC,EAClF,MAAO,CAAE,KAAM,MAAO,MAAO,EAE/B,KACF,CACA,IAAK,OAAQ,CACX,GAAM,CAAE,OAAAA,OAAO,EAAI,YACnB,GAAI,MAAM,QAAQA,OAAM,GAAKA,QAAO,MAAO,SAAS,sBAAS,IAAI,CAAC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,eAAgB,sBAAuB,CACvE,CACF,GACC,CACD,0BACA,0BACA,QACA,WACA,cACA,sBACA,aACA,MACA,wBACF,CAAC,CAGH,CAEA,SAAS,eAAe,UAA6C,CACnE,OAAO,UAAU,OAAO,CAAC,EAAE,IAC7B,CAEA,IAAM,uBACJ,4FAQF,SAAS,oCACP,cACA,0BAC2B,CAC3B,IAAI,iBACE,qBAAuB,EAAQ,0BAGrC,QAAW,UAAQ,sDAA0B,cAAc,IAAI,EAC7D,MAAI,gCAAkB,KAAM,sBAAsB,IAAM,IAAQ,EAAQ,KAAK,WAAc,qBAAsB,CAE/G,oBAAmB,wBAAU,aAAa,EAC1C,KACF,CAIF,GAAK,iBAKL,SAAW,UAAQ,sDAA0B,iBAAiB,IAAI,KAC5D,gCAAkB,KAAM,sBAAsB,IAAM,IAClD,EAAQ,KAAK,WAAc,uBAC7B,KAAK,SAAW,sBAKtB,OAAO,iBACT,CCvmBA,IAAAC,cAA2B,iBAGpB,SAAS,iCAAkE,CAChF,IAAM,WAAU,0BAAW,4BAA4B,EACvD,GAAI,UAAY,OACd,MAAM,IAAI,MAAM,qFAAqF,EAEvG,OAAO,OACT",
4
+ "sourcesContent": ["// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nexport * from './autocomplete-endpoint';\nexport * from './HealthGorillaLabOrderContext';\nexport * from './HealthGorillaLabOrderProvider';\nexport * from './useHealthGorillaLabOrder';\nexport * from './useHealthGorillaLabOrderContext';\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { ContentType, isCoding, isResource } from '@medplum/core';\nimport type { Identifier, Questionnaire } from '@medplum/fhirtypes';\nimport type { HGAutocompleteBotResponse, LabOrganization, TestCoding } from '@medplum/health-gorilla-core';\n\nexport type LabSearchParams = { type: 'lab'; query: string };\nexport type TestSearchParams = { type: 'test'; query: string; labId: string };\nexport type AOESearchParams = { type: 'aoe'; testCode: TestCoding };\n\nexport type LabSearchResult = { type: 'lab'; result: LabOrganization[] };\nexport type TestSearchResult = { type: 'test'; result: TestCoding[] };\nexport type AOESearchResult = { type: 'aoe'; result: Questionnaire | undefined };\n\nexport type LabSearch = { params: LabSearchParams; results: LabSearchResult };\nexport type TestSearch = { params: TestSearchParams; results: TestSearchResult };\nexport type AOESearch = { params: AOESearchParams; results: AOESearchResult };\nexport type HGSearch = LabSearch | TestSearch | AOESearch;\n\nexport type HGSearchFunction = <T extends HGSearch>(params: T['params']) => Promise<T['results']>;\n\nexport function getAutocompleteSearchFunction(\n medplum: MedplumClient,\n autocompleteBot: string | Identifier\n): HGSearchFunction {\n return async (params) => {\n const botResponse: HGAutocompleteBotResponse = await medplum.executeBot(autocompleteBot, params, ContentType.JSON);\n if (botResponse.type === 'error') {\n throw new Error('Error executing autocomplete bot', { cause: botResponse });\n }\n\n const { result } = botResponse;\n switch (botResponse.type) {\n case 'lab': {\n if (Array.isArray(result) && result.every((item) => isResource(item, 'Organization'))) {\n return { type: 'lab', result } as LabSearchResult;\n }\n break;\n }\n case 'test': {\n const { result } = botResponse;\n if (Array.isArray(result) && result.every((item) => isCoding(item))) {\n return { type: 'test', result } as TestSearchResult;\n }\n break;\n }\n case 'aoe': {\n const { result } = botResponse;\n if (result === undefined || result.resourceType === 'Questionnaire') {\n return { type: 'aoe', result } as AOESearchResult;\n }\n break;\n }\n default: {\n botResponse satisfies never;\n }\n }\n throw new Error(`Invalid bot response for ${JSON.stringify(params)}`);\n };\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Bundle, Coverage, Questionnaire, ServiceRequest } from '@medplum/fhirtypes';\nimport type {\n BillingInformation,\n DiagnosisCodeableConcept,\n LabOrderInputErrors,\n LabOrderTestMetadata,\n LabOrganization,\n TestCoding,\n} from '@medplum/health-gorilla-core';\nimport { createContext } from 'react';\n\nexport type TestMetadata = LabOrderTestMetadata & {\n aoeStatus: 'loading' | 'loaded' | 'none' | 'error';\n /** The AOE `Questionnaire`, if any, containing Ask at Order Entry (AOE) questions for the test. */\n aoeQuestionnaire?: Questionnaire;\n};\n\nexport type HealthGorillaLabOrderState = {\n performingLab: LabOrganization | undefined;\n performingLabAccountNumber: string | undefined;\n selectedTests: TestCoding[];\n testMetadata: Record<string, TestMetadata | undefined>;\n diagnoses: DiagnosisCodeableConcept[];\n billingInformation: BillingInformation;\n specimenCollectedDateTime: Date | undefined;\n orderNotes: string | undefined;\n};\n\nexport type UseHealthGorillaLabOrderReturn = {\n state: HealthGorillaLabOrderState;\n\n searchAvailableLabs: (query: string) => Promise<LabOrganization[]>;\n /**\n * Set the desired performer for doing the diagnostic testing. Compatible with\n * results from the `searchAvailableLabs` function.\n */\n setPerformingLab: (lab: LabOrganization | undefined) => void;\n /**\n * Sets the account number for the performing lab. If not provided, the\n * `HEALTH_GORILLA_SUBTENANT_ACCOUNT_NUMBER` `Project.secret` is used.\n */\n setPerformingLabAccountNumber: (accountNumber: string | undefined) => void;\n\n searchAvailableTests: (query: string) => Promise<TestCoding[]>;\n addTest: (test: TestCoding) => void;\n removeTest: (test: TestCoding) => void;\n setTests: (tests: TestCoding[]) => void;\n\n updateTestMetadata: (test: TestCoding, metadata: Partial<LabOrderTestMetadata>) => void;\n\n addDiagnosis: (diagnosis: DiagnosisCodeableConcept) => void;\n removeDiagnosis: (diagnosis: DiagnosisCodeableConcept) => void;\n setDiagnoses: (diagnoses: DiagnosisCodeableConcept[]) => void;\n\n getActivePatientCoverages: () => Promise<Coverage[]>;\n updateBillingInformation: (billingInfo: Partial<BillingInformation>) => void;\n\n setSpecimenCollectedDateTime: (date: Date | undefined) => void;\n\n setOrderNotes: (orderNotes: string | undefined) => void;\n\n validateOrder: () => LabOrderInputErrors | undefined;\n createOrderBundle: () => Promise<{ transactionResponse: Bundle; serviceRequest: ServiceRequest }>;\n};\n\nexport const HealthGorillaLabOrderContext = createContext<UseHealthGorillaLabOrderReturn | undefined>(undefined);\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { JSX, PropsWithChildren } from 'react';\nimport type { UseHealthGorillaLabOrderReturn } from './HealthGorillaLabOrderContext';\nimport { HealthGorillaLabOrderContext } from './HealthGorillaLabOrderContext';\n\n/**\n * A provider component that propagates the `useHealthGorillaLabOrder` return value to all children components via [React Context](https://reactjs.org/docs/context.html) API. To be used with {@link useHealthGorillaLabOrderContext}.\n *\n * @param props - entire response of `useHealthGorillaLabOrder`\n * @returns a React context provider component.\n *\n * @example\n * ```tsx\n * function App() {\n * const labOrderReturn = useHealthGorillaLabOrder({...});\n * return (\n * <HealthGorillaLabOrderProvider {...methods} >\n * <form onSubmit={labOrderReturn.createOrderBundle()}>\n * <PerformingLabInput />\n * <input type=\"submit\" />\n * </form>\n * </HealthGorillaLabOrderProvider>\n * );\n * }\n *\n * function PerformingLabInput() {\n * const { searchAvailableLabs, setPerformingLab } = useHealthGorillaLabOrderContext();\n * return (\n * <AsyncAutocomplete<LabOrganization>\n * maxValues={1}\n * loadOptions={searchAvailableLabs}\n * onChange={(item) => {\n * if (item.length > 0) {\n * setPerformingLab(item[0]);\n * } else {\n * setPerformingLab(undefined);\n * }\n * }}\n * />\n * );\n * }\n * ```\n */\nexport function HealthGorillaLabOrderProvider(props: PropsWithChildren<UseHealthGorillaLabOrderReturn>): JSX.Element {\n const { children, ...labOrderReturn } = props;\n return (\n <HealthGorillaLabOrderContext.Provider value={labOrderReturn}>{children}</HealthGorillaLabOrderContext.Provider>\n );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ResourceArray } from '@medplum/core';\nimport { createReference, deepClone, getExtensionValue, getIdentifier, isResource } from '@medplum/core';\nimport type {\n Bundle,\n Coverage,\n Location,\n Organization,\n Patient,\n Practitioner,\n Questionnaire,\n Reference,\n ServiceRequest,\n} from '@medplum/fhirtypes';\nimport type {\n BillingInformation,\n DiagnosisCodeableConcept,\n LabOrderServiceRequest,\n LabOrderTestMetadata,\n LabOrganization,\n TestCoding,\n} from '@medplum/health-gorilla-core';\nimport {\n HEALTH_GORILLA_SYSTEM,\n MEDPLUM_HEALTH_GORILLA_LAB_ORDER_PROFILE,\n createLabOrderBundle,\n isReferenceOfType,\n normalizeAoeQuestionnaire,\n questionnaireItemIterator,\n validateLabOrderInputs,\n} from '@medplum/health-gorilla-core';\nimport { useMedplum } from '@medplum/react';\nimport { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';\nimport type { AOESearch, LabSearch, TestSearch } from './autocomplete-endpoint';\nimport { getAutocompleteSearchFunction } from './autocomplete-endpoint';\nimport type {\n HealthGorillaLabOrderState,\n TestMetadata,\n UseHealthGorillaLabOrderReturn,\n} from './HealthGorillaLabOrderContext';\n\nexport type UseHealthGorillaLabOrderOptions = {\n /** Patient the tests are ordered for. */\n patient: Patient | (Reference<Patient> & { reference: string }) | undefined;\n /**\n * The physician who requests diagnostic procedures for the patient and responsible for the order.\n * The Practitioner MUST have an NPI identifier with the system http://hl7.org/fhir/sid/us-npi.\n */\n requester: Practitioner | (Reference<Practitioner> & { reference: string }) | undefined;\n\n /** For multi-location practices, optionally specify the location from which the order is being placed */\n requestingLocation?: Location | Organization | (Reference<Location | Organization> & { reference: string });\n};\n\nexport type EditableLabOrderTestMetadata = Pick<LabOrderTestMetadata, 'priority' | 'notes' | 'aoeResponses'>;\nconst EDITABLE_TEST_METADATA_KEYS: (keyof LabOrderTestMetadata)[] = ['priority', 'notes', 'aoeResponses'];\n\nconst INITIAL_TESTS: TestCoding[] = [];\nconst INITIAL_DIAGNOSES: DiagnosisCodeableConcept[] = [];\nconst INITIAL_TEST_METADATA = {};\nconst INITIAL_BILLING_INFORMATION: BillingInformation = {};\n\ntype TestsReducerState = {\n // Don't use any optional fields here, e.g. `selectedTests?: TestCoding[]` since that would cause\n // some loss of type safety in the reducer function by allowing the reducer to potentially return\n // incomplete state if a field is forgotten about. Instead, always use explicity `| undefined` for\n // fields that may legitimately be undefined in the state.\n\n selectedTests: TestCoding[];\n testMetadata: Record<string, TestMetadata | undefined>;\n specimenCollectedDateTime: Date | undefined;\n};\n\ntype AddTestAction = { type: 'add'; test: TestCoding };\ntype RemoveTestAction = { type: 'remove'; test: TestCoding };\ntype SetTestsAction = { type: 'set'; tests: TestCoding[] };\ntype UpdateMetadataAction = {\n type: 'updateMetadata';\n test: TestCoding;\n partialMetadata: Partial<EditableLabOrderTestMetadata>;\n};\ntype AoeLoadedAction = { type: 'aoeLoaded'; testAoes: [TestCoding, Questionnaire | undefined][] };\ntype SpecimentCollectionDateChangeAction = { type: 'specimenCollectionDateChange'; newDate: Date | undefined };\ntype AoeErrorAction = { type: 'aoeError'; tests: TestCoding[] };\n\ntype TestsAction =\n | AddTestAction\n | RemoveTestAction\n | SetTestsAction\n | UpdateMetadataAction\n | AoeLoadedAction\n | SpecimentCollectionDateChangeAction\n | AoeErrorAction;\n\nfunction testsReducer(prev: TestsReducerState, action: TestsAction): TestsReducerState {\n switch (action.type) {\n case 'add':\n return addTest(prev, action);\n case 'remove':\n return removeTest(prev, action);\n case 'set':\n return setTests(prev, action);\n case 'updateMetadata':\n return updateMetadata(prev, action);\n case 'aoeLoaded':\n return aoeLoaded(prev, action);\n case 'aoeError':\n return aoeError(prev, action);\n case 'specimenCollectionDateChange':\n return specimenCollectionDateChange(prev, action);\n default:\n action satisfies never;\n return prev;\n }\n}\n\nfunction addTest(prev: TestsReducerState, action: AddTestAction): TestsReducerState {\n if (prev.selectedTests.some((test) => test.code === action.test.code)) {\n return prev;\n }\n\n return {\n ...prev,\n selectedTests: [...prev.selectedTests, action.test],\n testMetadata: {\n ...prev.testMetadata,\n [action.test.code]: { aoeStatus: 'loading' },\n },\n };\n}\n\nfunction removeTest(prev: TestsReducerState, action: RemoveTestAction): TestsReducerState {\n return {\n ...prev,\n selectedTests: prev.selectedTests.filter((test) => test.code !== action.test.code),\n testMetadata: Object.fromEntries(Object.entries(prev.testMetadata).filter(([code]) => code !== action.test.code)),\n };\n}\n\nfunction setTests(prev: TestsReducerState, action: SetTestsAction): TestsReducerState {\n return {\n ...prev,\n selectedTests: action.tests,\n testMetadata: Object.fromEntries(\n action.tests.map((test) => {\n return [test.code, prev.testMetadata[test.code] ?? { aoeStatus: 'loading' }];\n })\n ),\n };\n}\n\nfunction updateMetadata(prev: TestsReducerState, action: UpdateMetadataAction): TestsReducerState {\n const { test, partialMetadata } = action;\n\n const prevTestMetadata = prev.testMetadata[test.code];\n if (!prev.selectedTests.some((t) => t.code === test.code) || !prevTestMetadata) {\n console.warn(`Cannot update metadata for test ${test.code} since it is not a selected tests`);\n return prev;\n }\n\n let allowedUpdates = partialMetadata;\n const restrictedKeys = Object.keys(partialMetadata).filter((k) => !EDITABLE_TEST_METADATA_KEYS.includes(k as any));\n\n if (restrictedKeys.length > 0) {\n console.warn(`Cannot update test metadata fields: ${restrictedKeys.join(', ')}`);\n\n allowedUpdates = Object.fromEntries(Object.entries(partialMetadata).filter(([k]) => !restrictedKeys.includes(k)));\n }\n\n return {\n ...prev,\n testMetadata: {\n ...prev.testMetadata,\n [test.code]: { ...prevTestMetadata, ...allowedUpdates },\n },\n };\n}\n\nfunction aoeLoaded(prev: TestsReducerState, action: AoeLoadedAction): TestsReducerState {\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const [test, aoeQuestionnaire] of action.testAoes) {\n const prevMetadata = prev.testMetadata[test.code];\n if (!prevMetadata) {\n continue;\n }\n\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = {\n ...prevMetadata,\n aoeStatus: aoeQuestionnaire ? 'loaded' : 'none',\n aoeQuestionnaire:\n aoeQuestionnaire &&\n (updateAoeQuestionnaireRequiredItems(aoeQuestionnaire, prev.specimenCollectedDateTime) ?? aoeQuestionnaire),\n };\n }\n\n if (!newTestMetadata) {\n return prev;\n }\n\n return {\n ...prev,\n testMetadata: newTestMetadata,\n };\n}\n\nfunction aoeError(prev: TestsReducerState, action: AoeErrorAction): TestsReducerState {\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const test of action.tests) {\n const prevMetadata = prev.testMetadata[test.code];\n if (!prevMetadata || prevMetadata.aoeStatus !== 'loading') {\n continue;\n }\n\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = {\n ...prevMetadata,\n aoeStatus: 'error',\n };\n }\n\n if (!newTestMetadata) {\n return prev;\n }\n\n return {\n ...prev,\n testMetadata: newTestMetadata,\n };\n}\n\nfunction specimenCollectionDateChange(\n prev: TestsReducerState,\n action: SpecimentCollectionDateChangeAction\n): TestsReducerState {\n // check if we can reuse the previous testMetadata object to avoid unnecessary downstream re-renders\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const test of prev.selectedTests) {\n const prevTestMetadata = prev.testMetadata[test.code];\n if (!prevTestMetadata) {\n continue;\n }\n\n if (prevTestMetadata.aoeQuestionnaire) {\n const newAoeQ = updateAoeQuestionnaireRequiredItems(prevTestMetadata.aoeQuestionnaire, action.newDate);\n if (newAoeQ) {\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = { ...prevTestMetadata, aoeQuestionnaire: newAoeQ };\n }\n }\n }\n\n return {\n ...prev,\n // If no changes to AOE questionnaire item.required, reuse the previous object\n testMetadata: newTestMetadata ?? prev.testMetadata,\n specimenCollectedDateTime: action.newDate,\n };\n}\n\nexport function useHealthGorillaLabOrder(opts: UseHealthGorillaLabOrderOptions): UseHealthGorillaLabOrderReturn {\n const medplum = useMedplum();\n const [performingLab, privateSetPerformingLab] = useState<LabOrganization | undefined>();\n const [performingLabAccountNumber, privateSetPerformingLabAccountNumber] = useState<string | undefined>();\n const [testsAndMetadata, dispatchTests] = useReducer(testsReducer, {\n specimenCollectedDateTime: undefined,\n selectedTests: INITIAL_TESTS,\n testMetadata: INITIAL_TEST_METADATA,\n });\n const [diagnoses, privateSetDiagnoses] = useState<DiagnosisCodeableConcept[]>(INITIAL_DIAGNOSES);\n const [billingInformation, setBillingInformation] = useState<BillingInformation>(INITIAL_BILLING_INFORMATION);\n const [orderNotes, privateSetOrderNotes] = useState<string | undefined>();\n\n const healthGorillaAutocomplete = useMemo(() => {\n return getAutocompleteSearchFunction(medplum, {\n system: 'https://www.medplum.com/integrations/bot-identifier',\n value: 'health-gorilla-labs/autocomplete',\n });\n }, [medplum]);\n\n const fetchAoeQuestionnaire = useCallback(\n async (testCode: TestCoding): Promise<Questionnaire | undefined> => {\n const response = await healthGorillaAutocomplete<AOESearch>({ type: 'aoe', testCode });\n const questionnaire = response.result;\n if (questionnaire) {\n normalizeAoeQuestionnaire(questionnaire);\n }\n return response.result;\n },\n [healthGorillaAutocomplete]\n );\n\n const lastSelectedTests = useRef<TestCoding[]>([]);\n useEffect(() => {\n // effect only runs when selectedTests changes\n if (lastSelectedTests.current === testsAndMetadata.selectedTests) {\n return;\n }\n lastSelectedTests.current = testsAndMetadata.selectedTests;\n\n const testCodingAoesBeingFetched: TestCoding[] = [];\n async function fetchNeededAoeQuestions(): Promise<[TestCoding, Questionnaire | undefined][]> {\n const promises: Promise<[TestCoding, Questionnaire | undefined]>[] = [];\n for (const test of testsAndMetadata.selectedTests) {\n const metadata = testsAndMetadata.testMetadata[test.code];\n if (metadata?.aoeStatus !== 'loading') {\n continue;\n }\n\n testCodingAoesBeingFetched.push(test);\n promises.push(\n new Promise((resolve, reject) => {\n fetchAoeQuestionnaire(test)\n .then((questionnaire) => {\n resolve([test, questionnaire]);\n })\n .catch(reject);\n })\n );\n }\n return Promise.all(promises);\n }\n\n fetchNeededAoeQuestions()\n .then((results) => {\n if (results.length === 0) {\n return;\n }\n\n dispatchTests({ type: 'aoeLoaded', testAoes: results });\n })\n .catch((err) => {\n console.error('Error fetching AOE questions', err);\n dispatchTests({ type: 'aoeError', tests: testCodingAoesBeingFetched });\n });\n }, [fetchAoeQuestionnaire, testsAndMetadata]);\n\n const patientRef = useMemo<(Reference<Patient> & { reference: string }) | undefined>(() => {\n if (isReferenceOfType('Patient', opts.patient)) {\n return opts.patient;\n } else if (isResource(opts.patient)) {\n return createReference(opts.patient);\n } else {\n return undefined;\n }\n }, [opts.patient]);\n\n const requesterRef = useMemo<(Reference<Practitioner> & { reference: string }) | undefined>(() => {\n if (isReferenceOfType('Practitioner', opts.requester)) {\n return opts.requester;\n } else if (isResource(opts.requester)) {\n return createReference(opts.requester) as Reference<Practitioner> & { reference: string };\n } else {\n opts.requester satisfies undefined;\n return undefined;\n }\n }, [opts.requester]);\n\n const requestingLocationRef = useMemo<\n (Reference<Location | Organization> & { reference: string }) | undefined\n >(() => {\n if (\n isReferenceOfType('Location', opts.requestingLocation) ||\n isReferenceOfType('Organization', opts.requestingLocation)\n ) {\n return opts.requestingLocation;\n } else if (isResource(opts.requestingLocation)) {\n return createReference(opts.requestingLocation);\n } else {\n return undefined;\n }\n }, [opts.requestingLocation]);\n\n const state: HealthGorillaLabOrderState = useMemo(() => {\n const cloned = deepClone({\n performingLab,\n performingLabAccountNumber,\n selectedTests: testsAndMetadata.selectedTests,\n testMetadata: testsAndMetadata.testMetadata,\n diagnoses,\n billingInformation,\n specimenCollectedDateTime: testsAndMetadata.specimenCollectedDateTime,\n orderNotes,\n });\n\n // specimenCollectedDateTime is a Date object which is serialized in deepClone\n if (cloned.specimenCollectedDateTime) {\n cloned.specimenCollectedDateTime = new Date(cloned.specimenCollectedDateTime);\n }\n\n return cloned;\n }, [\n performingLab,\n performingLabAccountNumber,\n testsAndMetadata.selectedTests,\n testsAndMetadata.testMetadata,\n testsAndMetadata.specimenCollectedDateTime,\n diagnoses,\n billingInformation,\n orderNotes,\n ]);\n\n const getActivePatientCoverages = useCallback(async (): Promise<ResourceArray<Coverage>> => {\n if (!patientRef) {\n const emptyResult: Coverage[] = [];\n return Object.assign(emptyResult, {\n bundle: { resourceType: 'Bundle', type: 'searchset', entry: [], total: 0 } as Bundle<Coverage>,\n });\n }\n\n const coverageSearch = new URLSearchParams({\n patient: patientRef.reference,\n status: 'active',\n });\n const coverages = (await medplum.searchResources('Coverage', coverageSearch)).sort((a, b) => {\n return (a.order ?? Number.POSITIVE_INFINITY) - (b.order ?? Number.POSITIVE_INFINITY);\n });\n\n return coverages;\n }, [medplum, patientRef]);\n\n const updateBillingInformation = useCallback((billingInfo: Partial<BillingInformation>): void => {\n setBillingInformation((prev) => {\n return { ...prev, ...billingInfo };\n });\n }, []);\n\n const result: UseHealthGorillaLabOrderReturn = useMemo(() => {\n return {\n state,\n searchAvailableLabs: async (query: string) => {\n const response = await healthGorillaAutocomplete<LabSearch>({ type: 'lab', query });\n // consider filtering to labs that have the https://www.healthgorilla.com/fhir/StructureDefinition/provider-compendium extension?\n return response.result;\n },\n searchAvailableTests: async (query: string): Promise<TestCoding[]> => {\n if (!performingLab) {\n return [];\n }\n\n const hgLabId = getIdentifier(performingLab, HEALTH_GORILLA_SYSTEM);\n if (!hgLabId) {\n throw new Error('No Health Gorilla identifier found for performing lab');\n }\n\n if (query.length === 0) {\n return [];\n }\n const response = await healthGorillaAutocomplete<TestSearch>({ type: 'test', query, labId: hgLabId });\n\n const tests = response.result;\n return tests;\n },\n setPerformingLab: (newLab: LabOrganization | undefined) => {\n privateSetPerformingLab(newLab);\n },\n setPerformingLabAccountNumber: (newAccountNumber: string | undefined) => {\n privateSetPerformingLabAccountNumber(newAccountNumber);\n },\n addTest: (test: TestCoding) => {\n dispatchTests({ type: 'add', test });\n },\n removeTest: (test: TestCoding) => {\n dispatchTests({ type: 'remove', test });\n },\n setTests: (newTests: TestCoding[]) => {\n dispatchTests({ type: 'set', tests: newTests });\n },\n\n updateTestMetadata: (test: TestCoding, partialMetadata: Partial<LabOrderTestMetadata>) => {\n dispatchTests({ type: 'updateMetadata', test, partialMetadata });\n },\n\n addDiagnosis(diagnosis: DiagnosisCodeableConcept) {\n privateSetDiagnoses((prev) => {\n if (prev.some((item) => toDiagnosisKey(item) === toDiagnosisKey(diagnosis))) {\n return prev;\n }\n return [...prev, diagnosis];\n });\n },\n removeDiagnosis(diagnosis: DiagnosisCodeableConcept) {\n privateSetDiagnoses((prev) => {\n const idx = prev.findIndex((item) => toDiagnosisKey(item) === toDiagnosisKey(diagnosis));\n if (idx === -1) {\n return prev;\n }\n const next = [...prev];\n next.splice(idx, 1);\n return next;\n });\n },\n setDiagnoses: (newDiagnoses: DiagnosisCodeableConcept[]) => {\n privateSetDiagnoses(newDiagnoses);\n },\n\n getActivePatientCoverages,\n updateBillingInformation,\n\n setSpecimenCollectedDateTime: (newDate: Date | undefined) => {\n dispatchTests({ type: 'specimenCollectionDateChange', newDate });\n },\n\n setOrderNotes: (newOrderNotes: string | undefined) => {\n // || instead of ?? so that empty string becomes undefined\n privateSetOrderNotes(newOrderNotes || undefined);\n },\n\n validateOrder: () => {\n return validateLabOrderInputs({\n patient: patientRef,\n requester: requesterRef,\n performingLab: state.performingLab,\n performingLabAccountNumber: state.performingLabAccountNumber,\n selectedTests: state.selectedTests,\n testMetadata: state.testMetadata,\n diagnoses: state.diagnoses,\n billingInformation: state.billingInformation,\n specimenCollectedDateTime: state.specimenCollectedDateTime,\n orderNotes: state.orderNotes,\n });\n },\n createOrderBundle: async (): Promise<{ transactionResponse: Bundle; serviceRequest: ServiceRequest }> => {\n const txn = createLabOrderBundle({\n patient: patientRef,\n requester: requesterRef,\n requestingLocation: requestingLocationRef,\n performingLab: state.performingLab,\n performingLabAccountNumber: state.performingLabAccountNumber,\n selectedTests: state.selectedTests,\n testMetadata: state.testMetadata,\n diagnoses: state.diagnoses,\n billingInformation: state.billingInformation,\n specimenCollectedDateTime: state.specimenCollectedDateTime,\n orderNotes: state.orderNotes,\n });\n\n const transactionResponse = await medplum.executeBatch(txn);\n\n let labOrderServiceRequest: LabOrderServiceRequest | undefined;\n\n for (const entry of transactionResponse?.entry ?? []) {\n if (!entry.response?.status.startsWith('2')) {\n throw new Error('Error creating lab order: Non-2XX status code in response entry', {\n cause: transactionResponse,\n });\n }\n if (entry.resource?.meta?.profile?.includes(MEDPLUM_HEALTH_GORILLA_LAB_ORDER_PROFILE)) {\n labOrderServiceRequest = entry.resource as LabOrderServiceRequest;\n }\n }\n\n if (!labOrderServiceRequest) {\n throw new Error('Error creating lab order: Lab Order Service Request not found in response entries', {\n cause: transactionResponse,\n });\n }\n\n return { transactionResponse, serviceRequest: labOrderServiceRequest };\n },\n };\n }, [\n getActivePatientCoverages,\n healthGorillaAutocomplete,\n medplum,\n patientRef,\n performingLab,\n requestingLocationRef,\n requesterRef,\n state,\n updateBillingInformation,\n ]);\n\n return result;\n}\n\nfunction toDiagnosisKey(diagnosis: DiagnosisCodeableConcept): string {\n return diagnosis.coding[0].code as string;\n}\n\nconst REQUIRED_WHEN_SPECIMEN =\n 'https://www.healthgorilla.com/fhir/StructureDefinition/questionnaire-requiredwhenspecimen';\n\n/**\n * Updates the required status of items in an AOE questionnaire based on whether a specimen is being collected.\n * @param questionnaire - The Questionnaire to update\n * @param specimenCollectedDateTime - The date and time the specimen was collected, if any\n * @returns A new Questionnaire with the required status of items updated, or undefined if no changes are needed\n */\nfunction updateAoeQuestionnaireRequiredItems(\n questionnaire: Questionnaire,\n specimenCollectedDateTime: Date | undefined\n): Questionnaire | undefined {\n let newQuestionnaire: Questionnaire | undefined;\n const requiredWhenSpecimen = Boolean(specimenCollectedDateTime);\n\n // first, check if the questionnaire needs any changes\n for (const item of questionnaireItemIterator(questionnaire.item)) {\n if (getExtensionValue(item, REQUIRED_WHEN_SPECIMEN) === true && Boolean(item.required) !== requiredWhenSpecimen) {\n // at least one item needs updating, so crete a clone to be updated rather than updating in place\n newQuestionnaire = deepClone(questionnaire);\n break;\n }\n }\n\n // if no changes are needed, return the original Questionnaire\n if (!newQuestionnaire) {\n return undefined;\n }\n\n // otherwise, update the cloned Questionnaire\n for (const item of questionnaireItemIterator(newQuestionnaire.item)) {\n if (getExtensionValue(item, REQUIRED_WHEN_SPECIMEN) === true) {\n if (Boolean(item.required) !== requiredWhenSpecimen) {\n item.required = requiredWhenSpecimen;\n }\n }\n }\n\n return newQuestionnaire;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { useContext } from 'react';\nimport type { UseHealthGorillaLabOrderReturn } from './HealthGorillaLabOrderContext';\nimport { HealthGorillaLabOrderContext } from './HealthGorillaLabOrderContext';\n\nexport function useHealthGorillaLabOrderContext(): UseHealthGorillaLabOrderReturn {\n const context = useContext(HealthGorillaLabOrderContext);\n if (context === undefined) {\n throw new Error('useHealthGorillaLabOrderContext must be used within a HealthGorillaLabOrderProvider');\n }\n return context;\n}\n"],
5
+ "mappings": "wpBAAA,kZCGA,gBAAkD,yBAmB3C,SAAS,8BACd,QACA,gBACkB,CAClB,MAAO,OAAO,QAAW,CACvB,IAAM,YAAyC,MAAM,QAAQ,WAAW,gBAAiB,OAAQ,wBAAY,IAAI,EACjH,GAAI,YAAY,OAAS,QACvB,MAAM,IAAI,MAAM,mCAAoC,CAAE,MAAO,WAAY,CAAC,EAG5E,GAAM,CAAE,MAAO,EAAI,YACnB,OAAQ,YAAY,KAAM,CACxB,IAAK,MAAO,CACV,GAAI,MAAM,QAAQ,MAAM,GAAK,OAAO,MAAO,SAAS,wBAAW,KAAM,cAAc,CAAC,EAClF,MAAO,CAAE,KAAM,MAAO,MAAO,EAE/B,KACF,CACA,IAAK,OAAQ,CACX,GAAM,CAAE,OAAAA,OAAO,EAAI,YACnB,GAAI,MAAM,QAAQA,OAAM,GAAKA,QAAO,MAAO,SAAS,sBAAS,IAAI,CAAC,EAChE,MAAO,CAAE,KAAM,OAAQ,OAAAA,OAAO,EAEhC,KACF,CACA,IAAK,MAAO,CACV,GAAM,CAAE,OAAAA,OAAO,EAAI,YACnB,GAAIA,UAAW,QAAaA,QAAO,eAAiB,gBAClD,MAAO,CAAE,KAAM,MAAO,OAAAA,OAAO,EAE/B,KACF,CACA,QAGF,CACA,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C3B,IAAI,iBACE,qBAAuB,EAAQ,0BAGrC,QAAW,UAAQ,sDAA0B,cAAc,IAAI,EAC7D,MAAI,gCAAkB,KAAM,sBAAsB,IAAM,IAAQ,EAAQ,KAAK,WAAc,qBAAsB,CAE/G,oBAAmB,wBAAU,aAAa,EAC1C,KACF,CAIF,GAAK,iBAKL,SAAW,UAAQ,sDAA0B,iBAAiB,IAAI,KAC5D,gCAAkB,KAAM,sBAAsB,IAAM,IAClD,EAAQ,KAAK,WAAc,uBAC7B,KAAK,SAAW,sBAKtB,OAAO,iBACT,CC3mBA,IAAAC,cAA2B,iBAIpB,SAAS,iCAAkE,CAChF,IAAM,WAAU,0BAAW,4BAA4B,EACvD,GAAI,UAAY,OACd,MAAM,IAAI,MAAM,qFAAqF,EAEvG,OAAO,OACT",
6
6
  "names": ["result", "import_core", "import_react", "import_react"]
7
7
  }
@@ -1,23 +1,23 @@
1
- import { BillingInformation } from '@medplum/health-gorilla-core';
2
- import { Bundle } from '@medplum/fhirtypes';
1
+ import type { BillingInformation } from '@medplum/health-gorilla-core';
2
+ import type { Bundle } from '@medplum/fhirtypes';
3
3
  import { Context } from 'react';
4
- import { Coverage } from '@medplum/fhirtypes';
5
- import { DiagnosisCodeableConcept } from '@medplum/health-gorilla-core';
6
- import { Identifier } from '@medplum/fhirtypes';
7
- import { JSX } from 'react';
8
- import { LabOrderInputErrors } from '@medplum/health-gorilla-core';
9
- import { LabOrderTestMetadata } from '@medplum/health-gorilla-core';
10
- import { LabOrganization } from '@medplum/health-gorilla-core';
11
- import { Location as Location_2 } from '@medplum/fhirtypes';
12
- import { MedplumClient } from '@medplum/core';
13
- import { Organization } from '@medplum/fhirtypes';
14
- import { Patient } from '@medplum/fhirtypes';
15
- import { Practitioner } from '@medplum/fhirtypes';
16
- import { PropsWithChildren } from 'react';
17
- import { Questionnaire } from '@medplum/fhirtypes';
18
- import { Reference } from '@medplum/fhirtypes';
19
- import { ServiceRequest } from '@medplum/fhirtypes';
20
- import { TestCoding } from '@medplum/health-gorilla-core';
4
+ import type { Coverage } from '@medplum/fhirtypes';
5
+ import type { DiagnosisCodeableConcept } from '@medplum/health-gorilla-core';
6
+ import type { Identifier } from '@medplum/fhirtypes';
7
+ import type { JSX } from 'react';
8
+ import type { LabOrderInputErrors } from '@medplum/health-gorilla-core';
9
+ import type { LabOrderTestMetadata } from '@medplum/health-gorilla-core';
10
+ import type { LabOrganization } from '@medplum/health-gorilla-core';
11
+ import type { Location as Location_2 } from '@medplum/fhirtypes';
12
+ import type { MedplumClient } from '@medplum/core';
13
+ import type { Organization } from '@medplum/fhirtypes';
14
+ import type { Patient } from '@medplum/fhirtypes';
15
+ import type { Practitioner } from '@medplum/fhirtypes';
16
+ import type { PropsWithChildren } from 'react';
17
+ import type { Questionnaire } from '@medplum/fhirtypes';
18
+ import type { Reference } from '@medplum/fhirtypes';
19
+ import type { ServiceRequest } from '@medplum/fhirtypes';
20
+ import type { TestCoding } from '@medplum/health-gorilla-core';
21
21
 
22
22
  export declare type AOESearch = {
23
23
  params: AOESearchParams;
@@ -1,23 +1,23 @@
1
- import { BillingInformation } from '@medplum/health-gorilla-core';
2
- import { Bundle } from '@medplum/fhirtypes';
1
+ import type { BillingInformation } from '@medplum/health-gorilla-core';
2
+ import type { Bundle } from '@medplum/fhirtypes';
3
3
  import { Context } from 'react';
4
- import { Coverage } from '@medplum/fhirtypes';
5
- import { DiagnosisCodeableConcept } from '@medplum/health-gorilla-core';
6
- import { Identifier } from '@medplum/fhirtypes';
7
- import { JSX } from 'react';
8
- import { LabOrderInputErrors } from '@medplum/health-gorilla-core';
9
- import { LabOrderTestMetadata } from '@medplum/health-gorilla-core';
10
- import { LabOrganization } from '@medplum/health-gorilla-core';
11
- import { Location as Location_2 } from '@medplum/fhirtypes';
12
- import { MedplumClient } from '@medplum/core';
13
- import { Organization } from '@medplum/fhirtypes';
14
- import { Patient } from '@medplum/fhirtypes';
15
- import { Practitioner } from '@medplum/fhirtypes';
16
- import { PropsWithChildren } from 'react';
17
- import { Questionnaire } from '@medplum/fhirtypes';
18
- import { Reference } from '@medplum/fhirtypes';
19
- import { ServiceRequest } from '@medplum/fhirtypes';
20
- import { TestCoding } from '@medplum/health-gorilla-core';
4
+ import type { Coverage } from '@medplum/fhirtypes';
5
+ import type { DiagnosisCodeableConcept } from '@medplum/health-gorilla-core';
6
+ import type { Identifier } from '@medplum/fhirtypes';
7
+ import type { JSX } from 'react';
8
+ import type { LabOrderInputErrors } from '@medplum/health-gorilla-core';
9
+ import type { LabOrderTestMetadata } from '@medplum/health-gorilla-core';
10
+ import type { LabOrganization } from '@medplum/health-gorilla-core';
11
+ import type { Location as Location_2 } from '@medplum/fhirtypes';
12
+ import type { MedplumClient } from '@medplum/core';
13
+ import type { Organization } from '@medplum/fhirtypes';
14
+ import type { Patient } from '@medplum/fhirtypes';
15
+ import type { Practitioner } from '@medplum/fhirtypes';
16
+ import type { PropsWithChildren } from 'react';
17
+ import type { Questionnaire } from '@medplum/fhirtypes';
18
+ import type { Reference } from '@medplum/fhirtypes';
19
+ import type { ServiceRequest } from '@medplum/fhirtypes';
20
+ import type { TestCoding } from '@medplum/health-gorilla-core';
21
21
 
22
22
  export declare type AOESearch = {
23
23
  params: AOESearchParams;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/autocomplete-endpoint.ts", "../../src/HealthGorillaLabOrderContext.ts", "../../src/HealthGorillaLabOrderProvider.tsx", "../../src/useHealthGorillaLabOrder.ts", "../../src/useHealthGorillaLabOrderContext.ts"],
4
- "sourcesContent": ["// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ContentType, MedplumClient, isCoding, isResource } from '@medplum/core';\nimport { Identifier, Questionnaire } from '@medplum/fhirtypes';\nimport { HGAutocompleteBotResponse, LabOrganization, TestCoding } from '@medplum/health-gorilla-core';\n\nexport type LabSearchParams = { type: 'lab'; query: string };\nexport type TestSearchParams = { type: 'test'; query: string; labId: string };\nexport type AOESearchParams = { type: 'aoe'; testCode: TestCoding };\n\nexport type LabSearchResult = { type: 'lab'; result: LabOrganization[] };\nexport type TestSearchResult = { type: 'test'; result: TestCoding[] };\nexport type AOESearchResult = { type: 'aoe'; result: Questionnaire | undefined };\n\nexport type LabSearch = { params: LabSearchParams; results: LabSearchResult };\nexport type TestSearch = { params: TestSearchParams; results: TestSearchResult };\nexport type AOESearch = { params: AOESearchParams; results: AOESearchResult };\nexport type HGSearch = LabSearch | TestSearch | AOESearch;\n\nexport type HGSearchFunction = <T extends HGSearch>(params: T['params']) => Promise<T['results']>;\n\nexport function getAutocompleteSearchFunction(\n medplum: MedplumClient,\n autocompleteBot: string | Identifier\n): HGSearchFunction {\n return async (params) => {\n const botResponse: HGAutocompleteBotResponse = await medplum.executeBot(autocompleteBot, params, ContentType.JSON);\n if (botResponse.type === 'error') {\n throw new Error('Error executing autocomplete bot', { cause: botResponse });\n }\n\n const { result } = botResponse;\n switch (botResponse.type) {\n case 'lab': {\n if (Array.isArray(result) && result.every((item) => isResource(item, 'Organization'))) {\n return { type: 'lab', result } as LabSearchResult;\n }\n break;\n }\n case 'test': {\n const { result } = botResponse;\n if (Array.isArray(result) && result.every((item) => isCoding(item))) {\n return { type: 'test', result } as TestSearchResult;\n }\n break;\n }\n case 'aoe': {\n const { result } = botResponse;\n if (result === undefined || result.resourceType === 'Questionnaire') {\n return { type: 'aoe', result } as AOESearchResult;\n }\n break;\n }\n default: {\n botResponse satisfies never;\n }\n }\n throw new Error(`Invalid bot response for ${JSON.stringify(params)}`);\n };\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Bundle, Coverage, Questionnaire, ServiceRequest } from '@medplum/fhirtypes';\nimport {\n BillingInformation,\n DiagnosisCodeableConcept,\n LabOrderInputErrors,\n LabOrderTestMetadata,\n LabOrganization,\n TestCoding,\n} from '@medplum/health-gorilla-core';\nimport { createContext } from 'react';\n\nexport type TestMetadata = LabOrderTestMetadata & {\n aoeStatus: 'loading' | 'loaded' | 'none' | 'error';\n /** The AOE `Questionnaire`, if any, containing Ask at Order Entry (AOE) questions for the test. */\n aoeQuestionnaire?: Questionnaire;\n};\n\nexport type HealthGorillaLabOrderState = {\n performingLab: LabOrganization | undefined;\n performingLabAccountNumber: string | undefined;\n selectedTests: TestCoding[];\n testMetadata: Record<string, TestMetadata | undefined>;\n diagnoses: DiagnosisCodeableConcept[];\n billingInformation: BillingInformation;\n specimenCollectedDateTime: Date | undefined;\n orderNotes: string | undefined;\n};\n\nexport type UseHealthGorillaLabOrderReturn = {\n state: HealthGorillaLabOrderState;\n\n searchAvailableLabs: (query: string) => Promise<LabOrganization[]>;\n /**\n * Set the desired performer for doing the diagnostic testing. Compatible with\n * results from the `searchAvailableLabs` function.\n */\n setPerformingLab: (lab: LabOrganization | undefined) => void;\n /**\n * Sets the account number for the performing lab. If not provided, the\n * `HEALTH_GORILLA_SUBTENANT_ACCOUNT_NUMBER` `Project.secret` is used.\n */\n setPerformingLabAccountNumber: (accountNumber: string | undefined) => void;\n\n searchAvailableTests: (query: string) => Promise<TestCoding[]>;\n addTest: (test: TestCoding) => void;\n removeTest: (test: TestCoding) => void;\n setTests: (tests: TestCoding[]) => void;\n\n updateTestMetadata: (test: TestCoding, metadata: Partial<LabOrderTestMetadata>) => void;\n\n addDiagnosis: (diagnosis: DiagnosisCodeableConcept) => void;\n removeDiagnosis: (diagnosis: DiagnosisCodeableConcept) => void;\n setDiagnoses: (diagnoses: DiagnosisCodeableConcept[]) => void;\n\n getActivePatientCoverages: () => Promise<Coverage[]>;\n updateBillingInformation: (billingInfo: Partial<BillingInformation>) => void;\n\n setSpecimenCollectedDateTime: (date: Date | undefined) => void;\n\n setOrderNotes: (orderNotes: string | undefined) => void;\n\n validateOrder: () => LabOrderInputErrors | undefined;\n createOrderBundle: () => Promise<{ transactionResponse: Bundle; serviceRequest: ServiceRequest }>;\n};\n\nexport const HealthGorillaLabOrderContext = createContext<UseHealthGorillaLabOrderReturn | undefined>(undefined);\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { JSX, PropsWithChildren } from 'react';\nimport { HealthGorillaLabOrderContext, UseHealthGorillaLabOrderReturn } from './HealthGorillaLabOrderContext';\n\n/**\n * A provider component that propagates the `useHealthGorillaLabOrder` return value to all children components via [React Context](https://reactjs.org/docs/context.html) API. To be used with {@link useHealthGorillaLabOrderContext}.\n *\n * @param props - entire response of `useHealthGorillaLabOrder`\n * @returns a React context provider component.\n *\n * @example\n * ```tsx\n * function App() {\n * const labOrderReturn = useHealthGorillaLabOrder({...});\n * return (\n * <HealthGorillaLabOrderProvider {...methods} >\n * <form onSubmit={labOrderReturn.createOrderBundle()}>\n * <PerformingLabInput />\n * <input type=\"submit\" />\n * </form>\n * </HealthGorillaLabOrderProvider>\n * );\n * }\n *\n * function PerformingLabInput() {\n * const { searchAvailableLabs, setPerformingLab } = useHealthGorillaLabOrderContext();\n * return (\n * <AsyncAutocomplete<LabOrganization>\n * maxValues={1}\n * loadOptions={searchAvailableLabs}\n * onChange={(item) => {\n * if (item.length > 0) {\n * setPerformingLab(item[0]);\n * } else {\n * setPerformingLab(undefined);\n * }\n * }}\n * />\n * );\n * }\n * ```\n */\nexport function HealthGorillaLabOrderProvider(props: PropsWithChildren<UseHealthGorillaLabOrderReturn>): JSX.Element {\n const { children, ...labOrderReturn } = props;\n return (\n <HealthGorillaLabOrderContext.Provider value={labOrderReturn}>{children}</HealthGorillaLabOrderContext.Provider>\n );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ResourceArray, createReference, deepClone, getExtensionValue, getIdentifier, isResource } from '@medplum/core';\nimport {\n Bundle,\n Coverage,\n Location,\n Organization,\n Patient,\n Practitioner,\n Questionnaire,\n Reference,\n ServiceRequest,\n} from '@medplum/fhirtypes';\nimport {\n BillingInformation,\n DiagnosisCodeableConcept,\n HEALTH_GORILLA_SYSTEM,\n LabOrderServiceRequest,\n LabOrderTestMetadata,\n LabOrganization,\n MEDPLUM_HEALTH_GORILLA_LAB_ORDER_PROFILE,\n TestCoding,\n createLabOrderBundle,\n isReferenceOfType,\n normalizeAoeQuestionnaire,\n questionnaireItemIterator,\n validateLabOrderInputs,\n} from '@medplum/health-gorilla-core';\nimport { useMedplum } from '@medplum/react';\nimport { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';\nimport { AOESearch, LabSearch, TestSearch, getAutocompleteSearchFunction } from './autocomplete-endpoint';\nimport {\n HealthGorillaLabOrderState,\n TestMetadata,\n UseHealthGorillaLabOrderReturn,\n} from './HealthGorillaLabOrderContext';\n\nexport type UseHealthGorillaLabOrderOptions = {\n /** Patient the tests are ordered for. */\n patient: Patient | (Reference<Patient> & { reference: string }) | undefined;\n /**\n * The physician who requests diagnostic procedures for the patient and responsible for the order.\n * The Practitioner MUST have an NPI identifier with the system http://hl7.org/fhir/sid/us-npi.\n */\n requester: Practitioner | (Reference<Practitioner> & { reference: string }) | undefined;\n\n /** For multi-location practices, optionally specify the location from which the order is being placed */\n requestingLocation?: Location | Organization | (Reference<Location | Organization> & { reference: string });\n};\n\nexport type EditableLabOrderTestMetadata = Pick<LabOrderTestMetadata, 'priority' | 'notes' | 'aoeResponses'>;\nconst EDITABLE_TEST_METADATA_KEYS: (keyof LabOrderTestMetadata)[] = ['priority', 'notes', 'aoeResponses'];\n\nconst INITIAL_TESTS: TestCoding[] = [];\nconst INITIAL_DIAGNOSES: DiagnosisCodeableConcept[] = [];\nconst INITIAL_TEST_METADATA = {};\nconst INITIAL_BILLING_INFORMATION: BillingInformation = {};\n\ntype TestsReducerState = {\n // Don't use any optional fields here, e.g. `selectedTests?: TestCoding[]` since that would cause\n // some loss of type safety in the reducer function by allowing the reducer to potentially return\n // incomplete state if a field is forgotten about. Instead, always use explicity `| undefined` for\n // fields that may legitimately be undefined in the state.\n\n selectedTests: TestCoding[];\n testMetadata: Record<string, TestMetadata | undefined>;\n specimenCollectedDateTime: Date | undefined;\n};\n\ntype AddTestAction = { type: 'add'; test: TestCoding };\ntype RemoveTestAction = { type: 'remove'; test: TestCoding };\ntype SetTestsAction = { type: 'set'; tests: TestCoding[] };\ntype UpdateMetadataAction = {\n type: 'updateMetadata';\n test: TestCoding;\n partialMetadata: Partial<EditableLabOrderTestMetadata>;\n};\ntype AoeLoadedAction = { type: 'aoeLoaded'; testAoes: [TestCoding, Questionnaire | undefined][] };\ntype SpecimentCollectionDateChangeAction = { type: 'specimenCollectionDateChange'; newDate: Date | undefined };\ntype AoeErrorAction = { type: 'aoeError'; tests: TestCoding[] };\n\ntype TestsAction =\n | AddTestAction\n | RemoveTestAction\n | SetTestsAction\n | UpdateMetadataAction\n | AoeLoadedAction\n | SpecimentCollectionDateChangeAction\n | AoeErrorAction;\n\nfunction testsReducer(prev: TestsReducerState, action: TestsAction): TestsReducerState {\n switch (action.type) {\n case 'add':\n return addTest(prev, action);\n case 'remove':\n return removeTest(prev, action);\n case 'set':\n return setTests(prev, action);\n case 'updateMetadata':\n return updateMetadata(prev, action);\n case 'aoeLoaded':\n return aoeLoaded(prev, action);\n case 'aoeError':\n return aoeError(prev, action);\n case 'specimenCollectionDateChange':\n return specimenCollectionDateChange(prev, action);\n default:\n action satisfies never;\n return prev;\n }\n}\n\nfunction addTest(prev: TestsReducerState, action: AddTestAction): TestsReducerState {\n if (prev.selectedTests.some((test) => test.code === action.test.code)) {\n return prev;\n }\n\n return {\n ...prev,\n selectedTests: [...prev.selectedTests, action.test],\n testMetadata: {\n ...prev.testMetadata,\n [action.test.code]: { aoeStatus: 'loading' },\n },\n };\n}\n\nfunction removeTest(prev: TestsReducerState, action: RemoveTestAction): TestsReducerState {\n return {\n ...prev,\n selectedTests: prev.selectedTests.filter((test) => test.code !== action.test.code),\n testMetadata: Object.fromEntries(Object.entries(prev.testMetadata).filter(([code]) => code !== action.test.code)),\n };\n}\n\nfunction setTests(prev: TestsReducerState, action: SetTestsAction): TestsReducerState {\n return {\n ...prev,\n selectedTests: action.tests,\n testMetadata: Object.fromEntries(\n action.tests.map((test) => {\n return [test.code, prev.testMetadata[test.code] ?? { aoeStatus: 'loading' }];\n })\n ),\n };\n}\n\nfunction updateMetadata(prev: TestsReducerState, action: UpdateMetadataAction): TestsReducerState {\n const { test, partialMetadata } = action;\n\n const prevTestMetadata = prev.testMetadata[test.code];\n if (!prev.selectedTests.some((t) => t.code === test.code) || !prevTestMetadata) {\n console.warn(`Cannot update metadata for test ${test.code} since it is not a selected tests`);\n return prev;\n }\n\n let allowedUpdates = partialMetadata;\n const restrictedKeys = Object.keys(partialMetadata).filter((k) => !EDITABLE_TEST_METADATA_KEYS.includes(k as any));\n\n if (restrictedKeys.length > 0) {\n console.warn(`Cannot update test metadata fields: ${restrictedKeys.join(', ')}`);\n\n allowedUpdates = Object.fromEntries(Object.entries(partialMetadata).filter(([k]) => !restrictedKeys.includes(k)));\n }\n\n return {\n ...prev,\n testMetadata: {\n ...prev.testMetadata,\n [test.code]: { ...prevTestMetadata, ...allowedUpdates },\n },\n };\n}\n\nfunction aoeLoaded(prev: TestsReducerState, action: AoeLoadedAction): TestsReducerState {\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const [test, aoeQuestionnaire] of action.testAoes) {\n const prevMetadata = prev.testMetadata[test.code];\n if (!prevMetadata) {\n continue;\n }\n\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = {\n ...prevMetadata,\n aoeStatus: aoeQuestionnaire ? 'loaded' : 'none',\n aoeQuestionnaire:\n aoeQuestionnaire &&\n (updateAoeQuestionnaireRequiredItems(aoeQuestionnaire, prev.specimenCollectedDateTime) ?? aoeQuestionnaire),\n };\n }\n\n if (!newTestMetadata) {\n return prev;\n }\n\n return {\n ...prev,\n testMetadata: newTestMetadata,\n };\n}\n\nfunction aoeError(prev: TestsReducerState, action: AoeErrorAction): TestsReducerState {\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const test of action.tests) {\n const prevMetadata = prev.testMetadata[test.code];\n if (!prevMetadata || prevMetadata.aoeStatus !== 'loading') {\n continue;\n }\n\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = {\n ...prevMetadata,\n aoeStatus: 'error',\n };\n }\n\n if (!newTestMetadata) {\n return prev;\n }\n\n return {\n ...prev,\n testMetadata: newTestMetadata,\n };\n}\n\nfunction specimenCollectionDateChange(\n prev: TestsReducerState,\n action: SpecimentCollectionDateChangeAction\n): TestsReducerState {\n // check if we can reuse the previous testMetadata object to avoid unnecessary downstream re-renders\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const test of prev.selectedTests) {\n const prevTestMetadata = prev.testMetadata[test.code];\n if (!prevTestMetadata) {\n continue;\n }\n\n if (prevTestMetadata.aoeQuestionnaire) {\n const newAoeQ = updateAoeQuestionnaireRequiredItems(prevTestMetadata.aoeQuestionnaire, action.newDate);\n if (newAoeQ) {\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = { ...prevTestMetadata, aoeQuestionnaire: newAoeQ };\n }\n }\n }\n\n return {\n ...prev,\n // If no changes to AOE questionnaire item.required, reuse the previous object\n testMetadata: newTestMetadata ?? prev.testMetadata,\n specimenCollectedDateTime: action.newDate,\n };\n}\n\nexport function useHealthGorillaLabOrder(opts: UseHealthGorillaLabOrderOptions): UseHealthGorillaLabOrderReturn {\n const medplum = useMedplum();\n const [performingLab, privateSetPerformingLab] = useState<LabOrganization | undefined>();\n const [performingLabAccountNumber, privateSetPerformingLabAccountNumber] = useState<string | undefined>();\n const [testsAndMetadata, dispatchTests] = useReducer(testsReducer, {\n specimenCollectedDateTime: undefined,\n selectedTests: INITIAL_TESTS,\n testMetadata: INITIAL_TEST_METADATA,\n });\n const [diagnoses, privateSetDiagnoses] = useState<DiagnosisCodeableConcept[]>(INITIAL_DIAGNOSES);\n const [billingInformation, setBillingInformation] = useState<BillingInformation>(INITIAL_BILLING_INFORMATION);\n const [orderNotes, privateSetOrderNotes] = useState<string | undefined>();\n\n const healthGorillaAutocomplete = useMemo(() => {\n return getAutocompleteSearchFunction(medplum, {\n system: 'https://www.medplum.com/integrations/bot-identifier',\n value: 'health-gorilla-labs/autocomplete',\n });\n }, [medplum]);\n\n const fetchAoeQuestionnaire = useCallback(\n async (testCode: TestCoding): Promise<Questionnaire | undefined> => {\n const response = await healthGorillaAutocomplete<AOESearch>({ type: 'aoe', testCode });\n const questionnaire = response.result;\n if (questionnaire) {\n normalizeAoeQuestionnaire(questionnaire);\n }\n return response.result;\n },\n [healthGorillaAutocomplete]\n );\n\n const lastSelectedTests = useRef<TestCoding[]>([]);\n useEffect(() => {\n // effect only runs when selectedTests changes\n if (lastSelectedTests.current === testsAndMetadata.selectedTests) {\n return;\n }\n lastSelectedTests.current = testsAndMetadata.selectedTests;\n\n const testCodingAoesBeingFetched: TestCoding[] = [];\n async function fetchNeededAoeQuestions(): Promise<[TestCoding, Questionnaire | undefined][]> {\n const promises: Promise<[TestCoding, Questionnaire | undefined]>[] = [];\n for (const test of testsAndMetadata.selectedTests) {\n const metadata = testsAndMetadata.testMetadata[test.code];\n if (metadata?.aoeStatus !== 'loading') {\n continue;\n }\n\n testCodingAoesBeingFetched.push(test);\n promises.push(\n new Promise((resolve, reject) => {\n fetchAoeQuestionnaire(test)\n .then((questionnaire) => {\n resolve([test, questionnaire]);\n })\n .catch(reject);\n })\n );\n }\n return Promise.all(promises);\n }\n\n fetchNeededAoeQuestions()\n .then((results) => {\n if (results.length === 0) {\n return;\n }\n\n dispatchTests({ type: 'aoeLoaded', testAoes: results });\n })\n .catch((err) => {\n console.error('Error fetching AOE questions', err);\n dispatchTests({ type: 'aoeError', tests: testCodingAoesBeingFetched });\n });\n }, [fetchAoeQuestionnaire, testsAndMetadata]);\n\n const patientRef = useMemo<(Reference<Patient> & { reference: string }) | undefined>(() => {\n if (isReferenceOfType('Patient', opts.patient)) {\n return opts.patient;\n } else if (isResource(opts.patient)) {\n return createReference(opts.patient);\n } else {\n return undefined;\n }\n }, [opts.patient]);\n\n const requesterRef = useMemo<(Reference<Practitioner> & { reference: string }) | undefined>(() => {\n if (isReferenceOfType('Practitioner', opts.requester)) {\n return opts.requester;\n } else if (isResource(opts.requester)) {\n return createReference(opts.requester) as Reference<Practitioner> & { reference: string };\n } else {\n opts.requester satisfies undefined;\n return undefined;\n }\n }, [opts.requester]);\n\n const requestingLocationRef = useMemo<\n (Reference<Location | Organization> & { reference: string }) | undefined\n >(() => {\n if (\n isReferenceOfType('Location', opts.requestingLocation) ||\n isReferenceOfType('Organization', opts.requestingLocation)\n ) {\n return opts.requestingLocation;\n } else if (isResource(opts.requestingLocation)) {\n return createReference(opts.requestingLocation);\n } else {\n return undefined;\n }\n }, [opts.requestingLocation]);\n\n const state: HealthGorillaLabOrderState = useMemo(() => {\n const cloned = deepClone({\n performingLab,\n performingLabAccountNumber,\n selectedTests: testsAndMetadata.selectedTests,\n testMetadata: testsAndMetadata.testMetadata,\n diagnoses,\n billingInformation,\n specimenCollectedDateTime: testsAndMetadata.specimenCollectedDateTime,\n orderNotes,\n });\n\n // specimenCollectedDateTime is a Date object which is serialized in deepClone\n if (cloned.specimenCollectedDateTime) {\n cloned.specimenCollectedDateTime = new Date(cloned.specimenCollectedDateTime);\n }\n\n return cloned;\n }, [\n performingLab,\n performingLabAccountNumber,\n testsAndMetadata.selectedTests,\n testsAndMetadata.testMetadata,\n testsAndMetadata.specimenCollectedDateTime,\n diagnoses,\n billingInformation,\n orderNotes,\n ]);\n\n const getActivePatientCoverages = useCallback(async (): Promise<ResourceArray<Coverage>> => {\n if (!patientRef) {\n const emptyResult: Coverage[] = [];\n return Object.assign(emptyResult, {\n bundle: { resourceType: 'Bundle', type: 'searchset', entry: [], total: 0 } as Bundle<Coverage>,\n });\n }\n\n const coverageSearch = new URLSearchParams({\n patient: patientRef.reference,\n status: 'active',\n });\n const coverages = (await medplum.searchResources('Coverage', coverageSearch)).sort((a, b) => {\n return (a.order ?? Number.POSITIVE_INFINITY) - (b.order ?? Number.POSITIVE_INFINITY);\n });\n\n return coverages;\n }, [medplum, patientRef]);\n\n const updateBillingInformation = useCallback((billingInfo: Partial<BillingInformation>): void => {\n setBillingInformation((prev) => {\n return { ...prev, ...billingInfo };\n });\n }, []);\n\n const result: UseHealthGorillaLabOrderReturn = useMemo(() => {\n return {\n state,\n searchAvailableLabs: async (query: string) => {\n const response = await healthGorillaAutocomplete<LabSearch>({ type: 'lab', query });\n // consider filtering to labs that have the https://www.healthgorilla.com/fhir/StructureDefinition/provider-compendium extension?\n return response.result;\n },\n searchAvailableTests: async (query: string): Promise<TestCoding[]> => {\n if (!performingLab) {\n return [];\n }\n\n const hgLabId = getIdentifier(performingLab, HEALTH_GORILLA_SYSTEM);\n if (!hgLabId) {\n throw new Error('No Health Gorilla identifier found for performing lab');\n }\n\n if (query.length === 0) {\n return [];\n }\n const response = await healthGorillaAutocomplete<TestSearch>({ type: 'test', query, labId: hgLabId });\n\n const tests = response.result;\n return tests;\n },\n setPerformingLab: (newLab: LabOrganization | undefined) => {\n privateSetPerformingLab(newLab);\n },\n setPerformingLabAccountNumber: (newAccountNumber: string | undefined) => {\n privateSetPerformingLabAccountNumber(newAccountNumber);\n },\n addTest: (test: TestCoding) => {\n dispatchTests({ type: 'add', test });\n },\n removeTest: (test: TestCoding) => {\n dispatchTests({ type: 'remove', test });\n },\n setTests: (newTests: TestCoding[]) => {\n dispatchTests({ type: 'set', tests: newTests });\n },\n\n updateTestMetadata: (test: TestCoding, partialMetadata: Partial<LabOrderTestMetadata>) => {\n dispatchTests({ type: 'updateMetadata', test, partialMetadata });\n },\n\n addDiagnosis(diagnosis: DiagnosisCodeableConcept) {\n privateSetDiagnoses((prev) => {\n if (prev.some((item) => toDiagnosisKey(item) === toDiagnosisKey(diagnosis))) {\n return prev;\n }\n return [...prev, diagnosis];\n });\n },\n removeDiagnosis(diagnosis: DiagnosisCodeableConcept) {\n privateSetDiagnoses((prev) => {\n const idx = prev.findIndex((item) => toDiagnosisKey(item) === toDiagnosisKey(diagnosis));\n if (idx === -1) {\n return prev;\n }\n const next = [...prev];\n next.splice(idx, 1);\n return next;\n });\n },\n setDiagnoses: (newDiagnoses: DiagnosisCodeableConcept[]) => {\n privateSetDiagnoses(newDiagnoses);\n },\n\n getActivePatientCoverages,\n updateBillingInformation,\n\n setSpecimenCollectedDateTime: (newDate: Date | undefined) => {\n dispatchTests({ type: 'specimenCollectionDateChange', newDate });\n },\n\n setOrderNotes: (newOrderNotes: string | undefined) => {\n // || instead of ?? so that empty string becomes undefined\n privateSetOrderNotes(newOrderNotes || undefined);\n },\n\n validateOrder: () => {\n return validateLabOrderInputs({\n patient: patientRef,\n requester: requesterRef,\n performingLab: state.performingLab,\n performingLabAccountNumber: state.performingLabAccountNumber,\n selectedTests: state.selectedTests,\n testMetadata: state.testMetadata,\n diagnoses: state.diagnoses,\n billingInformation: state.billingInformation,\n specimenCollectedDateTime: state.specimenCollectedDateTime,\n orderNotes: state.orderNotes,\n });\n },\n createOrderBundle: async (): Promise<{ transactionResponse: Bundle; serviceRequest: ServiceRequest }> => {\n const txn = createLabOrderBundle({\n patient: patientRef,\n requester: requesterRef,\n requestingLocation: requestingLocationRef,\n performingLab: state.performingLab,\n performingLabAccountNumber: state.performingLabAccountNumber,\n selectedTests: state.selectedTests,\n testMetadata: state.testMetadata,\n diagnoses: state.diagnoses,\n billingInformation: state.billingInformation,\n specimenCollectedDateTime: state.specimenCollectedDateTime,\n orderNotes: state.orderNotes,\n });\n\n const transactionResponse = await medplum.executeBatch(txn);\n\n let labOrderServiceRequest: LabOrderServiceRequest | undefined;\n\n for (const entry of transactionResponse?.entry ?? []) {\n if (!entry.response?.status.startsWith('2')) {\n throw new Error('Error creating lab order: Non-2XX status code in response entry', {\n cause: transactionResponse,\n });\n }\n if (entry.resource?.meta?.profile?.includes(MEDPLUM_HEALTH_GORILLA_LAB_ORDER_PROFILE)) {\n labOrderServiceRequest = entry.resource as LabOrderServiceRequest;\n }\n }\n\n if (!labOrderServiceRequest) {\n throw new Error('Error creating lab order: Lab Order Service Request not found in response entries', {\n cause: transactionResponse,\n });\n }\n\n return { transactionResponse, serviceRequest: labOrderServiceRequest };\n },\n };\n }, [\n getActivePatientCoverages,\n healthGorillaAutocomplete,\n medplum,\n patientRef,\n performingLab,\n requestingLocationRef,\n requesterRef,\n state,\n updateBillingInformation,\n ]);\n\n return result;\n}\n\nfunction toDiagnosisKey(diagnosis: DiagnosisCodeableConcept): string {\n return diagnosis.coding[0].code as string;\n}\n\nconst REQUIRED_WHEN_SPECIMEN =\n 'https://www.healthgorilla.com/fhir/StructureDefinition/questionnaire-requiredwhenspecimen';\n\n/**\n * Updates the required status of items in an AOE questionnaire based on whether a specimen is being collected.\n * @param questionnaire - The Questionnaire to update\n * @param specimenCollectedDateTime - The date and time the specimen was collected, if any\n * @returns A new Questionnaire with the required status of items updated, or undefined if no changes are needed\n */\nfunction updateAoeQuestionnaireRequiredItems(\n questionnaire: Questionnaire,\n specimenCollectedDateTime: Date | undefined\n): Questionnaire | undefined {\n let newQuestionnaire: Questionnaire | undefined;\n const requiredWhenSpecimen = Boolean(specimenCollectedDateTime);\n\n // first, check if the questionnaire needs any changes\n for (const item of questionnaireItemIterator(questionnaire.item)) {\n if (getExtensionValue(item, REQUIRED_WHEN_SPECIMEN) === true && Boolean(item.required) !== requiredWhenSpecimen) {\n // at least one item needs updating, so crete a clone to be updated rather than updating in place\n newQuestionnaire = deepClone(questionnaire);\n break;\n }\n }\n\n // if no changes are needed, return the original Questionnaire\n if (!newQuestionnaire) {\n return undefined;\n }\n\n // otherwise, update the cloned Questionnaire\n for (const item of questionnaireItemIterator(newQuestionnaire.item)) {\n if (getExtensionValue(item, REQUIRED_WHEN_SPECIMEN) === true) {\n if (Boolean(item.required) !== requiredWhenSpecimen) {\n item.required = requiredWhenSpecimen;\n }\n }\n }\n\n return newQuestionnaire;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { useContext } from 'react';\nimport { HealthGorillaLabOrderContext, UseHealthGorillaLabOrderReturn } from './HealthGorillaLabOrderContext';\n\nexport function useHealthGorillaLabOrderContext(): UseHealthGorillaLabOrderReturn {\n const context = useContext(HealthGorillaLabOrderContext);\n if (context === undefined) {\n throw new Error('useHealthGorillaLabOrderContext must be used within a HealthGorillaLabOrderProvider');\n }\n return context;\n}\n"],
5
- "mappings": "AAEA,OAAS,YAA4B,SAAU,eAAkB,gBAmB1D,SAAS,8BACd,QACA,gBACkB,CAClB,MAAO,OAAO,QAAW,CACvB,IAAM,YAAyC,MAAM,QAAQ,WAAW,gBAAiB,OAAQ,YAAY,IAAI,EACjH,GAAI,YAAY,OAAS,QACvB,MAAM,IAAI,MAAM,mCAAoC,CAAE,MAAO,WAAY,CAAC,EAG5E,GAAM,CAAE,MAAO,EAAI,YACnB,OAAQ,YAAY,KAAM,CACxB,IAAK,MAAO,CACV,GAAI,MAAM,QAAQ,MAAM,GAAK,OAAO,MAAO,MAAS,WAAW,KAAM,cAAc,CAAC,EAClF,MAAO,CAAE,KAAM,MAAO,MAAO,EAE/B,KACF,CACA,IAAK,OAAQ,CACX,GAAM,CAAE,OAAAA,OAAO,EAAI,YACnB,GAAI,MAAM,QAAQA,OAAM,GAAKA,QAAO,MAAO,MAAS,SAAS,IAAI,CAAC,EAChE,MAAO,CAAE,KAAM,OAAQ,OAAAA,OAAO,EAEhC,KACF,CACA,IAAK,MAAO,CACV,GAAM,CAAE,OAAAA,OAAO,EAAI,YACnB,GAAIA,UAAW,QAAaA,QAAO,eAAiB,gBAClD,MAAO,CAAE,KAAM,MAAO,OAAAA,OAAO,EAE/B,KACF,CACA,QAGF,CACA,MAAM,IAAI,MAAM,4BAA4B,KAAK,UAAU,MAAM,CAAC,EAAE,CACtE,CACF,CChDA,OAAS,kBAAqB,QAwDvB,IAAM,6BAA+B,cAA0D,MA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AuB,EAAQ,0BAGrC,QAAW,QAAQ,0BAA0B,cAAc,IAAI,EAC7D,GAAI,kBAAkB,KAAM,sBAAsB,IAAM,IAAQ,EAAQ,KAAK,WAAc,qBAAsB,CAE/G,iBAAmB,UAAU,aAAa,EAC1C,KACF,CAIF,GAAK,iBAKL,SAAW,QAAQ,0BAA0B,iBAAiB,IAAI,EAC5D,kBAAkB,KAAM,sBAAsB,IAAM,IAClD,EAAQ,KAAK,WAAc,uBAC7B,KAAK,SAAW,sBAKtB,OAAO,iBACT,CCvmBA,OAAS,eAAkB,QAGpB,SAAS,iCAAkE,CAChF,IAAM,QAAU,WAAW,4BAA4B,EACvD,GAAI,UAAY,OACd,MAAM,IAAI,MAAM,qFAAqF,EAEvG,OAAO,OACT",
4
+ "sourcesContent": ["// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { ContentType, isCoding, isResource } from '@medplum/core';\nimport type { Identifier, Questionnaire } from '@medplum/fhirtypes';\nimport type { HGAutocompleteBotResponse, LabOrganization, TestCoding } from '@medplum/health-gorilla-core';\n\nexport type LabSearchParams = { type: 'lab'; query: string };\nexport type TestSearchParams = { type: 'test'; query: string; labId: string };\nexport type AOESearchParams = { type: 'aoe'; testCode: TestCoding };\n\nexport type LabSearchResult = { type: 'lab'; result: LabOrganization[] };\nexport type TestSearchResult = { type: 'test'; result: TestCoding[] };\nexport type AOESearchResult = { type: 'aoe'; result: Questionnaire | undefined };\n\nexport type LabSearch = { params: LabSearchParams; results: LabSearchResult };\nexport type TestSearch = { params: TestSearchParams; results: TestSearchResult };\nexport type AOESearch = { params: AOESearchParams; results: AOESearchResult };\nexport type HGSearch = LabSearch | TestSearch | AOESearch;\n\nexport type HGSearchFunction = <T extends HGSearch>(params: T['params']) => Promise<T['results']>;\n\nexport function getAutocompleteSearchFunction(\n medplum: MedplumClient,\n autocompleteBot: string | Identifier\n): HGSearchFunction {\n return async (params) => {\n const botResponse: HGAutocompleteBotResponse = await medplum.executeBot(autocompleteBot, params, ContentType.JSON);\n if (botResponse.type === 'error') {\n throw new Error('Error executing autocomplete bot', { cause: botResponse });\n }\n\n const { result } = botResponse;\n switch (botResponse.type) {\n case 'lab': {\n if (Array.isArray(result) && result.every((item) => isResource(item, 'Organization'))) {\n return { type: 'lab', result } as LabSearchResult;\n }\n break;\n }\n case 'test': {\n const { result } = botResponse;\n if (Array.isArray(result) && result.every((item) => isCoding(item))) {\n return { type: 'test', result } as TestSearchResult;\n }\n break;\n }\n case 'aoe': {\n const { result } = botResponse;\n if (result === undefined || result.resourceType === 'Questionnaire') {\n return { type: 'aoe', result } as AOESearchResult;\n }\n break;\n }\n default: {\n botResponse satisfies never;\n }\n }\n throw new Error(`Invalid bot response for ${JSON.stringify(params)}`);\n };\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Bundle, Coverage, Questionnaire, ServiceRequest } from '@medplum/fhirtypes';\nimport type {\n BillingInformation,\n DiagnosisCodeableConcept,\n LabOrderInputErrors,\n LabOrderTestMetadata,\n LabOrganization,\n TestCoding,\n} from '@medplum/health-gorilla-core';\nimport { createContext } from 'react';\n\nexport type TestMetadata = LabOrderTestMetadata & {\n aoeStatus: 'loading' | 'loaded' | 'none' | 'error';\n /** The AOE `Questionnaire`, if any, containing Ask at Order Entry (AOE) questions for the test. */\n aoeQuestionnaire?: Questionnaire;\n};\n\nexport type HealthGorillaLabOrderState = {\n performingLab: LabOrganization | undefined;\n performingLabAccountNumber: string | undefined;\n selectedTests: TestCoding[];\n testMetadata: Record<string, TestMetadata | undefined>;\n diagnoses: DiagnosisCodeableConcept[];\n billingInformation: BillingInformation;\n specimenCollectedDateTime: Date | undefined;\n orderNotes: string | undefined;\n};\n\nexport type UseHealthGorillaLabOrderReturn = {\n state: HealthGorillaLabOrderState;\n\n searchAvailableLabs: (query: string) => Promise<LabOrganization[]>;\n /**\n * Set the desired performer for doing the diagnostic testing. Compatible with\n * results from the `searchAvailableLabs` function.\n */\n setPerformingLab: (lab: LabOrganization | undefined) => void;\n /**\n * Sets the account number for the performing lab. If not provided, the\n * `HEALTH_GORILLA_SUBTENANT_ACCOUNT_NUMBER` `Project.secret` is used.\n */\n setPerformingLabAccountNumber: (accountNumber: string | undefined) => void;\n\n searchAvailableTests: (query: string) => Promise<TestCoding[]>;\n addTest: (test: TestCoding) => void;\n removeTest: (test: TestCoding) => void;\n setTests: (tests: TestCoding[]) => void;\n\n updateTestMetadata: (test: TestCoding, metadata: Partial<LabOrderTestMetadata>) => void;\n\n addDiagnosis: (diagnosis: DiagnosisCodeableConcept) => void;\n removeDiagnosis: (diagnosis: DiagnosisCodeableConcept) => void;\n setDiagnoses: (diagnoses: DiagnosisCodeableConcept[]) => void;\n\n getActivePatientCoverages: () => Promise<Coverage[]>;\n updateBillingInformation: (billingInfo: Partial<BillingInformation>) => void;\n\n setSpecimenCollectedDateTime: (date: Date | undefined) => void;\n\n setOrderNotes: (orderNotes: string | undefined) => void;\n\n validateOrder: () => LabOrderInputErrors | undefined;\n createOrderBundle: () => Promise<{ transactionResponse: Bundle; serviceRequest: ServiceRequest }>;\n};\n\nexport const HealthGorillaLabOrderContext = createContext<UseHealthGorillaLabOrderReturn | undefined>(undefined);\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { JSX, PropsWithChildren } from 'react';\nimport type { UseHealthGorillaLabOrderReturn } from './HealthGorillaLabOrderContext';\nimport { HealthGorillaLabOrderContext } from './HealthGorillaLabOrderContext';\n\n/**\n * A provider component that propagates the `useHealthGorillaLabOrder` return value to all children components via [React Context](https://reactjs.org/docs/context.html) API. To be used with {@link useHealthGorillaLabOrderContext}.\n *\n * @param props - entire response of `useHealthGorillaLabOrder`\n * @returns a React context provider component.\n *\n * @example\n * ```tsx\n * function App() {\n * const labOrderReturn = useHealthGorillaLabOrder({...});\n * return (\n * <HealthGorillaLabOrderProvider {...methods} >\n * <form onSubmit={labOrderReturn.createOrderBundle()}>\n * <PerformingLabInput />\n * <input type=\"submit\" />\n * </form>\n * </HealthGorillaLabOrderProvider>\n * );\n * }\n *\n * function PerformingLabInput() {\n * const { searchAvailableLabs, setPerformingLab } = useHealthGorillaLabOrderContext();\n * return (\n * <AsyncAutocomplete<LabOrganization>\n * maxValues={1}\n * loadOptions={searchAvailableLabs}\n * onChange={(item) => {\n * if (item.length > 0) {\n * setPerformingLab(item[0]);\n * } else {\n * setPerformingLab(undefined);\n * }\n * }}\n * />\n * );\n * }\n * ```\n */\nexport function HealthGorillaLabOrderProvider(props: PropsWithChildren<UseHealthGorillaLabOrderReturn>): JSX.Element {\n const { children, ...labOrderReturn } = props;\n return (\n <HealthGorillaLabOrderContext.Provider value={labOrderReturn}>{children}</HealthGorillaLabOrderContext.Provider>\n );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ResourceArray } from '@medplum/core';\nimport { createReference, deepClone, getExtensionValue, getIdentifier, isResource } from '@medplum/core';\nimport type {\n Bundle,\n Coverage,\n Location,\n Organization,\n Patient,\n Practitioner,\n Questionnaire,\n Reference,\n ServiceRequest,\n} from '@medplum/fhirtypes';\nimport type {\n BillingInformation,\n DiagnosisCodeableConcept,\n LabOrderServiceRequest,\n LabOrderTestMetadata,\n LabOrganization,\n TestCoding,\n} from '@medplum/health-gorilla-core';\nimport {\n HEALTH_GORILLA_SYSTEM,\n MEDPLUM_HEALTH_GORILLA_LAB_ORDER_PROFILE,\n createLabOrderBundle,\n isReferenceOfType,\n normalizeAoeQuestionnaire,\n questionnaireItemIterator,\n validateLabOrderInputs,\n} from '@medplum/health-gorilla-core';\nimport { useMedplum } from '@medplum/react';\nimport { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';\nimport type { AOESearch, LabSearch, TestSearch } from './autocomplete-endpoint';\nimport { getAutocompleteSearchFunction } from './autocomplete-endpoint';\nimport type {\n HealthGorillaLabOrderState,\n TestMetadata,\n UseHealthGorillaLabOrderReturn,\n} from './HealthGorillaLabOrderContext';\n\nexport type UseHealthGorillaLabOrderOptions = {\n /** Patient the tests are ordered for. */\n patient: Patient | (Reference<Patient> & { reference: string }) | undefined;\n /**\n * The physician who requests diagnostic procedures for the patient and responsible for the order.\n * The Practitioner MUST have an NPI identifier with the system http://hl7.org/fhir/sid/us-npi.\n */\n requester: Practitioner | (Reference<Practitioner> & { reference: string }) | undefined;\n\n /** For multi-location practices, optionally specify the location from which the order is being placed */\n requestingLocation?: Location | Organization | (Reference<Location | Organization> & { reference: string });\n};\n\nexport type EditableLabOrderTestMetadata = Pick<LabOrderTestMetadata, 'priority' | 'notes' | 'aoeResponses'>;\nconst EDITABLE_TEST_METADATA_KEYS: (keyof LabOrderTestMetadata)[] = ['priority', 'notes', 'aoeResponses'];\n\nconst INITIAL_TESTS: TestCoding[] = [];\nconst INITIAL_DIAGNOSES: DiagnosisCodeableConcept[] = [];\nconst INITIAL_TEST_METADATA = {};\nconst INITIAL_BILLING_INFORMATION: BillingInformation = {};\n\ntype TestsReducerState = {\n // Don't use any optional fields here, e.g. `selectedTests?: TestCoding[]` since that would cause\n // some loss of type safety in the reducer function by allowing the reducer to potentially return\n // incomplete state if a field is forgotten about. Instead, always use explicity `| undefined` for\n // fields that may legitimately be undefined in the state.\n\n selectedTests: TestCoding[];\n testMetadata: Record<string, TestMetadata | undefined>;\n specimenCollectedDateTime: Date | undefined;\n};\n\ntype AddTestAction = { type: 'add'; test: TestCoding };\ntype RemoveTestAction = { type: 'remove'; test: TestCoding };\ntype SetTestsAction = { type: 'set'; tests: TestCoding[] };\ntype UpdateMetadataAction = {\n type: 'updateMetadata';\n test: TestCoding;\n partialMetadata: Partial<EditableLabOrderTestMetadata>;\n};\ntype AoeLoadedAction = { type: 'aoeLoaded'; testAoes: [TestCoding, Questionnaire | undefined][] };\ntype SpecimentCollectionDateChangeAction = { type: 'specimenCollectionDateChange'; newDate: Date | undefined };\ntype AoeErrorAction = { type: 'aoeError'; tests: TestCoding[] };\n\ntype TestsAction =\n | AddTestAction\n | RemoveTestAction\n | SetTestsAction\n | UpdateMetadataAction\n | AoeLoadedAction\n | SpecimentCollectionDateChangeAction\n | AoeErrorAction;\n\nfunction testsReducer(prev: TestsReducerState, action: TestsAction): TestsReducerState {\n switch (action.type) {\n case 'add':\n return addTest(prev, action);\n case 'remove':\n return removeTest(prev, action);\n case 'set':\n return setTests(prev, action);\n case 'updateMetadata':\n return updateMetadata(prev, action);\n case 'aoeLoaded':\n return aoeLoaded(prev, action);\n case 'aoeError':\n return aoeError(prev, action);\n case 'specimenCollectionDateChange':\n return specimenCollectionDateChange(prev, action);\n default:\n action satisfies never;\n return prev;\n }\n}\n\nfunction addTest(prev: TestsReducerState, action: AddTestAction): TestsReducerState {\n if (prev.selectedTests.some((test) => test.code === action.test.code)) {\n return prev;\n }\n\n return {\n ...prev,\n selectedTests: [...prev.selectedTests, action.test],\n testMetadata: {\n ...prev.testMetadata,\n [action.test.code]: { aoeStatus: 'loading' },\n },\n };\n}\n\nfunction removeTest(prev: TestsReducerState, action: RemoveTestAction): TestsReducerState {\n return {\n ...prev,\n selectedTests: prev.selectedTests.filter((test) => test.code !== action.test.code),\n testMetadata: Object.fromEntries(Object.entries(prev.testMetadata).filter(([code]) => code !== action.test.code)),\n };\n}\n\nfunction setTests(prev: TestsReducerState, action: SetTestsAction): TestsReducerState {\n return {\n ...prev,\n selectedTests: action.tests,\n testMetadata: Object.fromEntries(\n action.tests.map((test) => {\n return [test.code, prev.testMetadata[test.code] ?? { aoeStatus: 'loading' }];\n })\n ),\n };\n}\n\nfunction updateMetadata(prev: TestsReducerState, action: UpdateMetadataAction): TestsReducerState {\n const { test, partialMetadata } = action;\n\n const prevTestMetadata = prev.testMetadata[test.code];\n if (!prev.selectedTests.some((t) => t.code === test.code) || !prevTestMetadata) {\n console.warn(`Cannot update metadata for test ${test.code} since it is not a selected tests`);\n return prev;\n }\n\n let allowedUpdates = partialMetadata;\n const restrictedKeys = Object.keys(partialMetadata).filter((k) => !EDITABLE_TEST_METADATA_KEYS.includes(k as any));\n\n if (restrictedKeys.length > 0) {\n console.warn(`Cannot update test metadata fields: ${restrictedKeys.join(', ')}`);\n\n allowedUpdates = Object.fromEntries(Object.entries(partialMetadata).filter(([k]) => !restrictedKeys.includes(k)));\n }\n\n return {\n ...prev,\n testMetadata: {\n ...prev.testMetadata,\n [test.code]: { ...prevTestMetadata, ...allowedUpdates },\n },\n };\n}\n\nfunction aoeLoaded(prev: TestsReducerState, action: AoeLoadedAction): TestsReducerState {\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const [test, aoeQuestionnaire] of action.testAoes) {\n const prevMetadata = prev.testMetadata[test.code];\n if (!prevMetadata) {\n continue;\n }\n\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = {\n ...prevMetadata,\n aoeStatus: aoeQuestionnaire ? 'loaded' : 'none',\n aoeQuestionnaire:\n aoeQuestionnaire &&\n (updateAoeQuestionnaireRequiredItems(aoeQuestionnaire, prev.specimenCollectedDateTime) ?? aoeQuestionnaire),\n };\n }\n\n if (!newTestMetadata) {\n return prev;\n }\n\n return {\n ...prev,\n testMetadata: newTestMetadata,\n };\n}\n\nfunction aoeError(prev: TestsReducerState, action: AoeErrorAction): TestsReducerState {\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const test of action.tests) {\n const prevMetadata = prev.testMetadata[test.code];\n if (!prevMetadata || prevMetadata.aoeStatus !== 'loading') {\n continue;\n }\n\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = {\n ...prevMetadata,\n aoeStatus: 'error',\n };\n }\n\n if (!newTestMetadata) {\n return prev;\n }\n\n return {\n ...prev,\n testMetadata: newTestMetadata,\n };\n}\n\nfunction specimenCollectionDateChange(\n prev: TestsReducerState,\n action: SpecimentCollectionDateChangeAction\n): TestsReducerState {\n // check if we can reuse the previous testMetadata object to avoid unnecessary downstream re-renders\n let newTestMetadata: TestsReducerState['testMetadata'] | undefined;\n for (const test of prev.selectedTests) {\n const prevTestMetadata = prev.testMetadata[test.code];\n if (!prevTestMetadata) {\n continue;\n }\n\n if (prevTestMetadata.aoeQuestionnaire) {\n const newAoeQ = updateAoeQuestionnaireRequiredItems(prevTestMetadata.aoeQuestionnaire, action.newDate);\n if (newAoeQ) {\n newTestMetadata ??= { ...prev.testMetadata };\n newTestMetadata[test.code] = { ...prevTestMetadata, aoeQuestionnaire: newAoeQ };\n }\n }\n }\n\n return {\n ...prev,\n // If no changes to AOE questionnaire item.required, reuse the previous object\n testMetadata: newTestMetadata ?? prev.testMetadata,\n specimenCollectedDateTime: action.newDate,\n };\n}\n\nexport function useHealthGorillaLabOrder(opts: UseHealthGorillaLabOrderOptions): UseHealthGorillaLabOrderReturn {\n const medplum = useMedplum();\n const [performingLab, privateSetPerformingLab] = useState<LabOrganization | undefined>();\n const [performingLabAccountNumber, privateSetPerformingLabAccountNumber] = useState<string | undefined>();\n const [testsAndMetadata, dispatchTests] = useReducer(testsReducer, {\n specimenCollectedDateTime: undefined,\n selectedTests: INITIAL_TESTS,\n testMetadata: INITIAL_TEST_METADATA,\n });\n const [diagnoses, privateSetDiagnoses] = useState<DiagnosisCodeableConcept[]>(INITIAL_DIAGNOSES);\n const [billingInformation, setBillingInformation] = useState<BillingInformation>(INITIAL_BILLING_INFORMATION);\n const [orderNotes, privateSetOrderNotes] = useState<string | undefined>();\n\n const healthGorillaAutocomplete = useMemo(() => {\n return getAutocompleteSearchFunction(medplum, {\n system: 'https://www.medplum.com/integrations/bot-identifier',\n value: 'health-gorilla-labs/autocomplete',\n });\n }, [medplum]);\n\n const fetchAoeQuestionnaire = useCallback(\n async (testCode: TestCoding): Promise<Questionnaire | undefined> => {\n const response = await healthGorillaAutocomplete<AOESearch>({ type: 'aoe', testCode });\n const questionnaire = response.result;\n if (questionnaire) {\n normalizeAoeQuestionnaire(questionnaire);\n }\n return response.result;\n },\n [healthGorillaAutocomplete]\n );\n\n const lastSelectedTests = useRef<TestCoding[]>([]);\n useEffect(() => {\n // effect only runs when selectedTests changes\n if (lastSelectedTests.current === testsAndMetadata.selectedTests) {\n return;\n }\n lastSelectedTests.current = testsAndMetadata.selectedTests;\n\n const testCodingAoesBeingFetched: TestCoding[] = [];\n async function fetchNeededAoeQuestions(): Promise<[TestCoding, Questionnaire | undefined][]> {\n const promises: Promise<[TestCoding, Questionnaire | undefined]>[] = [];\n for (const test of testsAndMetadata.selectedTests) {\n const metadata = testsAndMetadata.testMetadata[test.code];\n if (metadata?.aoeStatus !== 'loading') {\n continue;\n }\n\n testCodingAoesBeingFetched.push(test);\n promises.push(\n new Promise((resolve, reject) => {\n fetchAoeQuestionnaire(test)\n .then((questionnaire) => {\n resolve([test, questionnaire]);\n })\n .catch(reject);\n })\n );\n }\n return Promise.all(promises);\n }\n\n fetchNeededAoeQuestions()\n .then((results) => {\n if (results.length === 0) {\n return;\n }\n\n dispatchTests({ type: 'aoeLoaded', testAoes: results });\n })\n .catch((err) => {\n console.error('Error fetching AOE questions', err);\n dispatchTests({ type: 'aoeError', tests: testCodingAoesBeingFetched });\n });\n }, [fetchAoeQuestionnaire, testsAndMetadata]);\n\n const patientRef = useMemo<(Reference<Patient> & { reference: string }) | undefined>(() => {\n if (isReferenceOfType('Patient', opts.patient)) {\n return opts.patient;\n } else if (isResource(opts.patient)) {\n return createReference(opts.patient);\n } else {\n return undefined;\n }\n }, [opts.patient]);\n\n const requesterRef = useMemo<(Reference<Practitioner> & { reference: string }) | undefined>(() => {\n if (isReferenceOfType('Practitioner', opts.requester)) {\n return opts.requester;\n } else if (isResource(opts.requester)) {\n return createReference(opts.requester) as Reference<Practitioner> & { reference: string };\n } else {\n opts.requester satisfies undefined;\n return undefined;\n }\n }, [opts.requester]);\n\n const requestingLocationRef = useMemo<\n (Reference<Location | Organization> & { reference: string }) | undefined\n >(() => {\n if (\n isReferenceOfType('Location', opts.requestingLocation) ||\n isReferenceOfType('Organization', opts.requestingLocation)\n ) {\n return opts.requestingLocation;\n } else if (isResource(opts.requestingLocation)) {\n return createReference(opts.requestingLocation);\n } else {\n return undefined;\n }\n }, [opts.requestingLocation]);\n\n const state: HealthGorillaLabOrderState = useMemo(() => {\n const cloned = deepClone({\n performingLab,\n performingLabAccountNumber,\n selectedTests: testsAndMetadata.selectedTests,\n testMetadata: testsAndMetadata.testMetadata,\n diagnoses,\n billingInformation,\n specimenCollectedDateTime: testsAndMetadata.specimenCollectedDateTime,\n orderNotes,\n });\n\n // specimenCollectedDateTime is a Date object which is serialized in deepClone\n if (cloned.specimenCollectedDateTime) {\n cloned.specimenCollectedDateTime = new Date(cloned.specimenCollectedDateTime);\n }\n\n return cloned;\n }, [\n performingLab,\n performingLabAccountNumber,\n testsAndMetadata.selectedTests,\n testsAndMetadata.testMetadata,\n testsAndMetadata.specimenCollectedDateTime,\n diagnoses,\n billingInformation,\n orderNotes,\n ]);\n\n const getActivePatientCoverages = useCallback(async (): Promise<ResourceArray<Coverage>> => {\n if (!patientRef) {\n const emptyResult: Coverage[] = [];\n return Object.assign(emptyResult, {\n bundle: { resourceType: 'Bundle', type: 'searchset', entry: [], total: 0 } as Bundle<Coverage>,\n });\n }\n\n const coverageSearch = new URLSearchParams({\n patient: patientRef.reference,\n status: 'active',\n });\n const coverages = (await medplum.searchResources('Coverage', coverageSearch)).sort((a, b) => {\n return (a.order ?? Number.POSITIVE_INFINITY) - (b.order ?? Number.POSITIVE_INFINITY);\n });\n\n return coverages;\n }, [medplum, patientRef]);\n\n const updateBillingInformation = useCallback((billingInfo: Partial<BillingInformation>): void => {\n setBillingInformation((prev) => {\n return { ...prev, ...billingInfo };\n });\n }, []);\n\n const result: UseHealthGorillaLabOrderReturn = useMemo(() => {\n return {\n state,\n searchAvailableLabs: async (query: string) => {\n const response = await healthGorillaAutocomplete<LabSearch>({ type: 'lab', query });\n // consider filtering to labs that have the https://www.healthgorilla.com/fhir/StructureDefinition/provider-compendium extension?\n return response.result;\n },\n searchAvailableTests: async (query: string): Promise<TestCoding[]> => {\n if (!performingLab) {\n return [];\n }\n\n const hgLabId = getIdentifier(performingLab, HEALTH_GORILLA_SYSTEM);\n if (!hgLabId) {\n throw new Error('No Health Gorilla identifier found for performing lab');\n }\n\n if (query.length === 0) {\n return [];\n }\n const response = await healthGorillaAutocomplete<TestSearch>({ type: 'test', query, labId: hgLabId });\n\n const tests = response.result;\n return tests;\n },\n setPerformingLab: (newLab: LabOrganization | undefined) => {\n privateSetPerformingLab(newLab);\n },\n setPerformingLabAccountNumber: (newAccountNumber: string | undefined) => {\n privateSetPerformingLabAccountNumber(newAccountNumber);\n },\n addTest: (test: TestCoding) => {\n dispatchTests({ type: 'add', test });\n },\n removeTest: (test: TestCoding) => {\n dispatchTests({ type: 'remove', test });\n },\n setTests: (newTests: TestCoding[]) => {\n dispatchTests({ type: 'set', tests: newTests });\n },\n\n updateTestMetadata: (test: TestCoding, partialMetadata: Partial<LabOrderTestMetadata>) => {\n dispatchTests({ type: 'updateMetadata', test, partialMetadata });\n },\n\n addDiagnosis(diagnosis: DiagnosisCodeableConcept) {\n privateSetDiagnoses((prev) => {\n if (prev.some((item) => toDiagnosisKey(item) === toDiagnosisKey(diagnosis))) {\n return prev;\n }\n return [...prev, diagnosis];\n });\n },\n removeDiagnosis(diagnosis: DiagnosisCodeableConcept) {\n privateSetDiagnoses((prev) => {\n const idx = prev.findIndex((item) => toDiagnosisKey(item) === toDiagnosisKey(diagnosis));\n if (idx === -1) {\n return prev;\n }\n const next = [...prev];\n next.splice(idx, 1);\n return next;\n });\n },\n setDiagnoses: (newDiagnoses: DiagnosisCodeableConcept[]) => {\n privateSetDiagnoses(newDiagnoses);\n },\n\n getActivePatientCoverages,\n updateBillingInformation,\n\n setSpecimenCollectedDateTime: (newDate: Date | undefined) => {\n dispatchTests({ type: 'specimenCollectionDateChange', newDate });\n },\n\n setOrderNotes: (newOrderNotes: string | undefined) => {\n // || instead of ?? so that empty string becomes undefined\n privateSetOrderNotes(newOrderNotes || undefined);\n },\n\n validateOrder: () => {\n return validateLabOrderInputs({\n patient: patientRef,\n requester: requesterRef,\n performingLab: state.performingLab,\n performingLabAccountNumber: state.performingLabAccountNumber,\n selectedTests: state.selectedTests,\n testMetadata: state.testMetadata,\n diagnoses: state.diagnoses,\n billingInformation: state.billingInformation,\n specimenCollectedDateTime: state.specimenCollectedDateTime,\n orderNotes: state.orderNotes,\n });\n },\n createOrderBundle: async (): Promise<{ transactionResponse: Bundle; serviceRequest: ServiceRequest }> => {\n const txn = createLabOrderBundle({\n patient: patientRef,\n requester: requesterRef,\n requestingLocation: requestingLocationRef,\n performingLab: state.performingLab,\n performingLabAccountNumber: state.performingLabAccountNumber,\n selectedTests: state.selectedTests,\n testMetadata: state.testMetadata,\n diagnoses: state.diagnoses,\n billingInformation: state.billingInformation,\n specimenCollectedDateTime: state.specimenCollectedDateTime,\n orderNotes: state.orderNotes,\n });\n\n const transactionResponse = await medplum.executeBatch(txn);\n\n let labOrderServiceRequest: LabOrderServiceRequest | undefined;\n\n for (const entry of transactionResponse?.entry ?? []) {\n if (!entry.response?.status.startsWith('2')) {\n throw new Error('Error creating lab order: Non-2XX status code in response entry', {\n cause: transactionResponse,\n });\n }\n if (entry.resource?.meta?.profile?.includes(MEDPLUM_HEALTH_GORILLA_LAB_ORDER_PROFILE)) {\n labOrderServiceRequest = entry.resource as LabOrderServiceRequest;\n }\n }\n\n if (!labOrderServiceRequest) {\n throw new Error('Error creating lab order: Lab Order Service Request not found in response entries', {\n cause: transactionResponse,\n });\n }\n\n return { transactionResponse, serviceRequest: labOrderServiceRequest };\n },\n };\n }, [\n getActivePatientCoverages,\n healthGorillaAutocomplete,\n medplum,\n patientRef,\n performingLab,\n requestingLocationRef,\n requesterRef,\n state,\n updateBillingInformation,\n ]);\n\n return result;\n}\n\nfunction toDiagnosisKey(diagnosis: DiagnosisCodeableConcept): string {\n return diagnosis.coding[0].code as string;\n}\n\nconst REQUIRED_WHEN_SPECIMEN =\n 'https://www.healthgorilla.com/fhir/StructureDefinition/questionnaire-requiredwhenspecimen';\n\n/**\n * Updates the required status of items in an AOE questionnaire based on whether a specimen is being collected.\n * @param questionnaire - The Questionnaire to update\n * @param specimenCollectedDateTime - The date and time the specimen was collected, if any\n * @returns A new Questionnaire with the required status of items updated, or undefined if no changes are needed\n */\nfunction updateAoeQuestionnaireRequiredItems(\n questionnaire: Questionnaire,\n specimenCollectedDateTime: Date | undefined\n): Questionnaire | undefined {\n let newQuestionnaire: Questionnaire | undefined;\n const requiredWhenSpecimen = Boolean(specimenCollectedDateTime);\n\n // first, check if the questionnaire needs any changes\n for (const item of questionnaireItemIterator(questionnaire.item)) {\n if (getExtensionValue(item, REQUIRED_WHEN_SPECIMEN) === true && Boolean(item.required) !== requiredWhenSpecimen) {\n // at least one item needs updating, so crete a clone to be updated rather than updating in place\n newQuestionnaire = deepClone(questionnaire);\n break;\n }\n }\n\n // if no changes are needed, return the original Questionnaire\n if (!newQuestionnaire) {\n return undefined;\n }\n\n // otherwise, update the cloned Questionnaire\n for (const item of questionnaireItemIterator(newQuestionnaire.item)) {\n if (getExtensionValue(item, REQUIRED_WHEN_SPECIMEN) === true) {\n if (Boolean(item.required) !== requiredWhenSpecimen) {\n item.required = requiredWhenSpecimen;\n }\n }\n }\n\n return newQuestionnaire;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { useContext } from 'react';\nimport type { UseHealthGorillaLabOrderReturn } from './HealthGorillaLabOrderContext';\nimport { HealthGorillaLabOrderContext } from './HealthGorillaLabOrderContext';\n\nexport function useHealthGorillaLabOrderContext(): UseHealthGorillaLabOrderReturn {\n const context = useContext(HealthGorillaLabOrderContext);\n if (context === undefined) {\n throw new Error('useHealthGorillaLabOrderContext must be used within a HealthGorillaLabOrderProvider');\n }\n return context;\n}\n"],
5
+ "mappings": "A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CC3mBA,OAAS,eAAkB,QAIpB,SAAS,iCAAkE,CAChF,IAAM,QAAU,WAAW,4BAA4B,EACvD,GAAI,UAAY,OACd,MAAM,IAAI,MAAM,qFAAqF,EAEvG,OAAO,OACT",
6
6
  "names": ["result", "isResource", "isResource"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@medplum/health-gorilla-react",
3
- "version": "4.4.1",
3
+ "version": "4.4.2",
4
4
  "description": "Medplum Health Gorilla React SDK",
5
5
  "keywords": [
6
6
  "medplum",
@@ -59,29 +59,29 @@
59
59
  "test:watch": "vitest watch"
60
60
  },
61
61
  "devDependencies": {
62
- "@medplum/core": "4.4.1",
63
- "@medplum/definitions": "4.4.1",
64
- "@medplum/fhirtypes": "4.4.1",
65
- "@medplum/health-gorilla-core": "4.4.1",
66
- "@medplum/mock": "4.4.1",
67
- "@medplum/react": "4.4.1",
68
- "@testing-library/jest-dom": "6.8.0",
62
+ "@medplum/core": "4.4.2",
63
+ "@medplum/definitions": "4.4.2",
64
+ "@medplum/fhirtypes": "4.4.2",
65
+ "@medplum/health-gorilla-core": "4.4.2",
66
+ "@medplum/mock": "4.4.2",
67
+ "@medplum/react": "4.4.2",
68
+ "@testing-library/jest-dom": "6.9.1",
69
69
  "@testing-library/react": "16.3.0",
70
- "@types/node": "20.19.17",
71
- "@types/react": "19.1.13",
72
- "@types/react-dom": "19.1.9",
73
- "@vitejs/plugin-react": "5.0.3",
70
+ "@types/node": "20.19.19",
71
+ "@types/react": "19.2.0",
72
+ "@types/react-dom": "19.2.0",
73
+ "@vitejs/plugin-react": "5.0.4",
74
74
  "jsdom": "27.0.0",
75
- "react": "19.1.1",
76
- "react-dom": "19.1.1",
77
- "react-router": "7.9.1",
75
+ "react": "19.2.0",
76
+ "react-dom": "19.2.0",
77
+ "react-router": "7.9.3",
78
78
  "vitest": "3.2.4"
79
79
  },
80
80
  "peerDependencies": {
81
- "@medplum/core": "4.4.1",
82
- "@medplum/fhirtypes": "4.4.1",
83
- "@medplum/health-gorilla-core": "4.4.1",
84
- "@medplum/react": "4.4.1",
81
+ "@medplum/core": "4.4.2",
82
+ "@medplum/fhirtypes": "4.4.2",
83
+ "@medplum/health-gorilla-core": "4.4.2",
84
+ "@medplum/react": "4.4.2",
85
85
  "react": "^18.0.0 || ^19.0.0"
86
86
  },
87
87
  "engines": {