@photonhealth/react 2.0.0-rc.2 → 2.0.0-rc.3

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.
Files changed (179) hide show
  1. package/README.md +17 -1
  2. package/dist/analytics/PhotonAnalyticsProvider.d.ts +5 -2
  3. package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -1
  4. package/dist/analytics/PhotonAnalyticsProvider.js +34 -15
  5. package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -1
  6. package/dist/analytics/cardLifecycle.d.ts +10 -0
  7. package/dist/analytics/cardLifecycle.d.ts.map +1 -0
  8. package/dist/analytics/cardLifecycle.js +43 -0
  9. package/dist/analytics/cardLifecycle.js.map +1 -0
  10. package/dist/analytics/lifecycleOutcomes.d.ts +8 -0
  11. package/dist/analytics/lifecycleOutcomes.d.ts.map +1 -0
  12. package/dist/analytics/lifecycleOutcomes.js +16 -0
  13. package/dist/analytics/lifecycleOutcomes.js.map +1 -0
  14. package/dist/analytics/tracker.d.ts +5 -3
  15. package/dist/analytics/tracker.d.ts.map +1 -1
  16. package/dist/analytics/tracker.js +10 -5
  17. package/dist/analytics/tracker.js.map +1 -1
  18. package/dist/components/PhotonOrder.d.ts +18 -18
  19. package/dist/components/PhotonOrder.d.ts.map +1 -1
  20. package/dist/components/PhotonOrder.js +17 -6
  21. package/dist/components/PhotonOrder.js.map +1 -1
  22. package/dist/components/PhotonPatient.d.ts +7 -35
  23. package/dist/components/PhotonPatient.d.ts.map +1 -1
  24. package/dist/components/PhotonPatient.js +3 -77
  25. package/dist/components/PhotonPatient.js.map +1 -1
  26. package/dist/components/PhotonPrescription.d.ts +14 -14
  27. package/dist/components/PhotonPrescription.d.ts.map +1 -1
  28. package/dist/components/PhotonPrescription.js +0 -1
  29. package/dist/components/PhotonPrescription.js.map +1 -1
  30. package/dist/components/open.d.ts +11 -13
  31. package/dist/components/open.d.ts.map +1 -1
  32. package/dist/components/open.js +7 -2
  33. package/dist/components/open.js.map +1 -1
  34. package/dist/components/patient/PatientCard/PatientCard.d.ts +30 -0
  35. package/dist/components/patient/PatientCard/PatientCard.d.ts.map +1 -0
  36. package/dist/components/patient/PatientCard/PatientCard.js +101 -0
  37. package/dist/components/patient/PatientCard/PatientCard.js.map +1 -0
  38. package/dist/components/patient/PatientCard/usePatientToShow.d.ts +22 -0
  39. package/dist/components/patient/PatientCard/usePatientToShow.d.ts.map +1 -0
  40. package/dist/components/patient/PatientCard/usePatientToShow.js +40 -0
  41. package/dist/components/patient/PatientCard/usePatientToShow.js.map +1 -0
  42. package/dist/components/patient/PatientIntakeForm.d.ts +16 -0
  43. package/dist/components/patient/PatientIntakeForm.d.ts.map +1 -0
  44. package/dist/components/patient/PatientIntakeForm.js +114 -0
  45. package/dist/components/patient/PatientIntakeForm.js.map +1 -0
  46. package/dist/components/patient/PatientSearch.d.ts +12 -0
  47. package/dist/components/patient/PatientSearch.d.ts.map +1 -0
  48. package/dist/components/patient/PatientSearch.js +148 -0
  49. package/dist/components/patient/PatientSearch.js.map +1 -0
  50. package/dist/components/patient/{Benefits.d.ts → PatientSummary/BenefitsInputForm.d.ts} +2 -2
  51. package/dist/components/patient/PatientSummary/BenefitsInputForm.d.ts.map +1 -0
  52. package/dist/components/patient/{Benefits.js → PatientSummary/BenefitsInputForm.js} +5 -5
  53. package/dist/components/patient/PatientSummary/BenefitsInputForm.js.map +1 -0
  54. package/dist/components/patient/{Clinical.d.ts → PatientSummary/ClinicalInputForm.d.ts} +13 -15
  55. package/dist/components/patient/PatientSummary/ClinicalInputForm.d.ts.map +1 -0
  56. package/dist/components/patient/{Clinical.js → PatientSummary/ClinicalInputForm.js} +11 -11
  57. package/dist/components/patient/PatientSummary/ClinicalInputForm.js.map +1 -0
  58. package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts +5 -0
  59. package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts.map +1 -0
  60. package/dist/components/patient/PatientSummary/CollapsedSummary.js +30 -0
  61. package/dist/components/patient/PatientSummary/CollapsedSummary.js.map +1 -0
  62. package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts +10 -0
  63. package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts.map +1 -0
  64. package/dist/components/patient/PatientSummary/PatientDetailsForm.js +65 -0
  65. package/dist/components/patient/PatientSummary/PatientDetailsForm.js.map +1 -0
  66. package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts +53 -0
  67. package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts.map +1 -0
  68. package/dist/components/patient/PatientSummary/PatientDetailsSchema.js +78 -0
  69. package/dist/components/patient/PatientSummary/PatientDetailsSchema.js.map +1 -0
  70. package/dist/components/patient/PatientSummary/PatientSummary.d.ts +46 -0
  71. package/dist/components/patient/PatientSummary/PatientSummary.d.ts.map +1 -0
  72. package/dist/components/patient/PatientSummary/PatientSummary.js +57 -0
  73. package/dist/components/patient/PatientSummary/PatientSummary.js.map +1 -0
  74. package/dist/components/patient/PatientSummary/SummaryHeader.d.ts +19 -0
  75. package/dist/components/patient/PatientSummary/SummaryHeader.d.ts.map +1 -0
  76. package/dist/components/patient/PatientSummary/SummaryHeader.js +22 -0
  77. package/dist/components/patient/PatientSummary/SummaryHeader.js.map +1 -0
  78. package/dist/components/patient/fields.d.ts +7 -25
  79. package/dist/components/patient/fields.d.ts.map +1 -1
  80. package/dist/components/patient/fields.js +11 -53
  81. package/dist/components/patient/fields.js.map +1 -1
  82. package/dist/components/patient/parsePatientSearchQuery.d.ts +16 -0
  83. package/dist/components/patient/parsePatientSearchQuery.d.ts.map +1 -0
  84. package/dist/components/patient/{query.js → parsePatientSearchQuery.js} +3 -15
  85. package/dist/components/patient/parsePatientSearchQuery.js.map +1 -0
  86. package/dist/components/prescription/PrescriptionCard.d.ts +14 -8
  87. package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -1
  88. package/dist/components/prescription/PrescriptionCard.js +10 -3
  89. package/dist/components/prescription/PrescriptionCard.js.map +1 -1
  90. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts +6 -6
  91. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts.map +1 -1
  92. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js +6 -6
  93. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -1
  94. package/dist/components/schemaErrors.d.ts +3 -2
  95. package/dist/components/schemaErrors.d.ts.map +1 -1
  96. package/dist/components/schemaErrors.js +2 -1
  97. package/dist/components/schemaErrors.js.map +1 -1
  98. package/dist/components/search.d.ts +1 -1
  99. package/dist/components/search.js +1 -1
  100. package/dist/index.d.ts +1 -1
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +1 -1
  103. package/dist/index.js.map +1 -1
  104. package/dist/meta/version.js +1 -1
  105. package/package.json +5 -2
  106. package/src/analytics/PhotonAnalyticsProvider.test.tsx +0 -1
  107. package/src/analytics/PhotonAnalyticsProvider.tsx +75 -20
  108. package/src/analytics/cardLifecycle.test.tsx +272 -0
  109. package/src/analytics/cardLifecycle.ts +44 -0
  110. package/src/analytics/fieldInteraction.test.tsx +11 -9
  111. package/src/analytics/lifecycleOutcomes.test.ts +78 -0
  112. package/src/analytics/lifecycleOutcomes.ts +29 -0
  113. package/src/analytics/tracker.test.ts +1 -1
  114. package/src/analytics/tracker.ts +13 -6
  115. package/src/analytics/usePhotonAnalytics.test.tsx +106 -0
  116. package/src/components/PhotonOrder.test.tsx +146 -8
  117. package/src/components/PhotonOrder.tsx +37 -26
  118. package/src/components/PhotonPatient.tsx +8 -163
  119. package/src/components/PhotonPrescription.test.tsx +22 -18
  120. package/src/components/PhotonPrescription.tsx +14 -14
  121. package/src/components/ScreeningAlerts.test.tsx +81 -0
  122. package/src/components/open.ts +13 -16
  123. package/src/components/order/DraftOrderPrompt.test.tsx +3 -6
  124. package/src/components/patient/PatientCard/PatientCard.test.tsx +255 -0
  125. package/src/components/patient/PatientCard/PatientCard.tsx +177 -0
  126. package/src/components/patient/PatientCard/usePatientToShow.ts +44 -0
  127. package/src/components/patient/PatientIntakeForm.test.tsx +262 -0
  128. package/src/components/patient/PatientIntakeForm.tsx +222 -0
  129. package/src/components/patient/PatientSearch.test.tsx +204 -0
  130. package/src/components/patient/PatientSearch.tsx +221 -0
  131. package/src/components/patient/PatientSummary/BenefitsInputForm.test.tsx +164 -0
  132. package/src/components/patient/{Benefits.tsx → PatientSummary/BenefitsInputForm.tsx} +4 -4
  133. package/src/components/patient/PatientSummary/ClinicalInputForm.test.tsx +247 -0
  134. package/src/components/patient/{Clinical.tsx → PatientSummary/ClinicalInputForm.tsx} +23 -23
  135. package/src/components/patient/PatientSummary/CollapsedSummary.test.tsx +90 -0
  136. package/src/components/patient/PatientSummary/CollapsedSummary.tsx +46 -0
  137. package/src/components/patient/PatientSummary/PatientDetailsForm.test.tsx +201 -0
  138. package/src/components/patient/PatientSummary/PatientDetailsForm.tsx +320 -0
  139. package/src/components/patient/PatientSummary/PatientDetailsSchema.test.ts +296 -0
  140. package/src/components/patient/PatientSummary/PatientDetailsSchema.ts +95 -0
  141. package/src/components/patient/PatientSummary/PatientSummary.test.tsx +194 -0
  142. package/src/components/patient/PatientSummary/PatientSummary.tsx +225 -0
  143. package/src/components/patient/PatientSummary/SummaryHeader.test.tsx +183 -0
  144. package/src/components/patient/PatientSummary/SummaryHeader.tsx +85 -0
  145. package/src/components/patient/fields.tsx +12 -138
  146. package/src/components/patient/parsePatientSearchQuery.test.ts +107 -0
  147. package/src/components/patient/{query.ts → parsePatientSearchQuery.ts} +4 -21
  148. package/src/components/prescription/PrescriptionCard.test.tsx +174 -12
  149. package/src/components/prescription/PrescriptionCard.tsx +28 -14
  150. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +2 -5
  151. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +3 -6
  152. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +34 -37
  153. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +14 -14
  154. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +2 -5
  155. package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +3 -7
  156. package/src/components/schemaErrors.ts +3 -2
  157. package/src/components/search.tsx +1 -1
  158. package/src/index.ts +1 -1
  159. package/src/meta/version.test.ts +1 -0
  160. package/src/meta/version.ts +1 -1
  161. package/dist/components/patient/Benefits.d.ts.map +0 -1
  162. package/dist/components/patient/Benefits.js.map +0 -1
  163. package/dist/components/patient/Clinical.d.ts.map +0 -1
  164. package/dist/components/patient/Clinical.js.map +0 -1
  165. package/dist/components/patient/IntakeForm.d.ts +0 -10
  166. package/dist/components/patient/IntakeForm.d.ts.map +0 -1
  167. package/dist/components/patient/IntakeForm.js +0 -333
  168. package/dist/components/patient/IntakeForm.js.map +0 -1
  169. package/dist/components/patient/Summary.d.ts +0 -48
  170. package/dist/components/patient/Summary.d.ts.map +0 -1
  171. package/dist/components/patient/Summary.js +0 -90
  172. package/dist/components/patient/Summary.js.map +0 -1
  173. package/dist/components/patient/query.d.ts +0 -37
  174. package/dist/components/patient/query.d.ts.map +0 -1
  175. package/dist/components/patient/query.js.map +0 -1
  176. package/src/components/patient/IntakeForm.test.tsx +0 -89
  177. package/src/components/patient/IntakeForm.tsx +0 -564
  178. package/src/components/patient/Summary.test.tsx +0 -106
  179. package/src/components/patient/Summary.tsx +0 -330
@@ -1,7 +1,7 @@
1
- // @vitest-environment jsdom
2
- import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
3
- import { afterEach, describe, expect, it } from "vitest";
1
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
2
+ import { describe, expect, it } from "vitest";
4
3
  import {
4
+ alert,
5
5
  change,
6
6
  fakeNetworkApiClient,
7
7
  listedOrder,
@@ -18,21 +18,19 @@ import {
18
18
  order,
19
19
  patient,
20
20
  pickDrug,
21
+ signed,
21
22
  typeIdentity,
22
23
  withPhoton,
23
24
  } from "../../test/cards.fixtures.tsx";
24
25
 
25
26
  // The order around its prescriptions: Send, Remove, and a line searched before the order has a patient.
26
-
27
- afterEach(cleanup);
28
-
29
27
  const lisinoprilTablets10And20Mg = choices(
30
28
  option("Lisinopril Oral Tablet 10 MG", "med_10"),
31
29
  option("Lisinopril Oral Tablet 20 MG", "med_20"),
32
30
  );
33
31
 
34
32
  describe("PhotonOrder prescriptions", () => {
35
- it("a picked product waits for Add before the order can be sent; Remove leaves a fresh line to search in", async () => {
33
+ it("a picked product waits for Sign before the order can be sent; Remove leaves a fresh line to search in", async () => {
36
34
  const component = renderComponent({
37
35
  lookupPrescriptions: lisinoprilTablets10And20Mg,
38
36
  script: {
@@ -47,7 +45,7 @@ describe("PhotonOrder prescriptions", () => {
47
45
  await component.typeIntoTreatment("lisinopril");
48
46
  await pickDrug("Lisinopril Oral Tablet 10 MG");
49
47
  await screen.findByLabelText("Directions (sig)");
50
- // No primary yet: Send waits for Add.
48
+ // No primary yet: Send waits for Sign.
51
49
  expect(document.querySelectorAll('.prx-button[data-variant="primary"]')).toHaveLength(0);
52
50
  expect(screen.queryByRole("button", { name: /^Send prescriptions? to patient$/ })).toBeNull();
53
51
 
@@ -214,6 +212,108 @@ describe("PhotonOrder and the patient's draft order", () => {
214
212
  });
215
213
  });
216
214
 
215
+ describe("PhotonOrder: screening alerts before Send", () => {
216
+ const interactionBetweenPrescriptions = {
217
+ ...alert,
218
+ type: "DRUG" as const,
219
+ severity: "MAJOR" as const,
220
+ description: "Increases the risk of bleeding.",
221
+ involvedEntities: [{ __typename: "InvolvedEntity" as const, id: "med_2", name: "warfarin" }],
222
+ };
223
+ const unsignedWithAllergy = rx({ id: "rx_unsigned", screeningAlerts: [alert] });
224
+ const signedWithAllergy = { ...signed, screeningAlerts: [alert] };
225
+
226
+ it("an interaction between the order's signed prescriptions shows above Send", async () => {
227
+ renderOrderWithAlerts({ prescriptions: [signed], screeningAlerts: [interactionBetweenPrescriptions] });
228
+ const send = await findSend();
229
+ const alertTitle = await screen.findByText("drug · major");
230
+ expect(alertTitle.compareDocumentPosition(send) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
231
+ expect(screen.getByText("Increases the risk of bleeding. (warfarin)")).toBeInTheDocument();
232
+ });
233
+
234
+ it("Send goes straight to the patient with an alert showing, without asking for confirmation", async () => {
235
+ const component = renderOrderWithAlerts({
236
+ prescriptions: [signed],
237
+ screeningAlerts: [interactionBetweenPrescriptions],
238
+ });
239
+ await screen.findByText("drug · major");
240
+ const send = await findSend();
241
+ await waitFor(() => expect(send).toBeEnabled());
242
+
243
+ fireEvent.click(send);
244
+
245
+ await waitFor(() => expect(component.names()).toContain("SubmitOrder"));
246
+ expect(screen.queryByRole("dialog")).toBeNull();
247
+ expect(screen.queryByRole("alertdialog")).toBeNull();
248
+ });
249
+
250
+ it("an alert a signed prescription carries isn't shown: its signature acknowledged it", async () => {
251
+ renderOrderWithAlerts({ prescriptions: [signedWithAllergy], screeningAlerts: [] });
252
+ await findSend();
253
+ expect(screen.queryByText("allergen · moderate")).toBeNull();
254
+ });
255
+
256
+ it("an alert the order repeats from a signed prescription isn't shown either", async () => {
257
+ renderOrderWithAlerts({ prescriptions: [signedWithAllergy], screeningAlerts: [alert] });
258
+ await findSend();
259
+ expect(screen.queryByText("allergen · moderate")).toBeNull();
260
+ });
261
+
262
+ it("reopening a draft order whose two signed prescriptions interact shows no alert, though each prescription and the order all report it", async () => {
263
+ const levonorgestrel = treatment({ id: "med_levonorgestrel", name: "Levonorgestrel" });
264
+ const ella = treatment({ id: "med_ella", name: "Ella" });
265
+ const ulipristalInteraction = {
266
+ ...alert,
267
+ type: "DRUG" as const,
268
+ severity: "MAJOR" as const,
269
+ description: "Ulipristal may decrease the effectiveness of progestins.",
270
+ involvedEntities: [ella, levonorgestrel].map(({ id, name }) => ({
271
+ __typename: "InvolvedEntity" as const,
272
+ id,
273
+ name,
274
+ })),
275
+ };
276
+ const signedAndInteracting = (id: string, drug: typeof ella) => ({
277
+ ...signed,
278
+ id,
279
+ treatment: drug,
280
+ screeningAlerts: [ulipristalInteraction],
281
+ });
282
+
283
+ renderOrderWithAlerts({
284
+ prescriptions: [signedAndInteracting("rx_levonorgestrel", levonorgestrel), signedAndInteracting("rx_ella", ella)],
285
+ screeningAlerts: [ulipristalInteraction],
286
+ });
287
+
288
+ const send = await screen.findByRole("button", { name: "Send prescriptions to patient" });
289
+ await waitFor(() => expect(send).toBeEnabled());
290
+ expect(screen.getByRole("heading", { name: "Levonorgestrel" })).toBeInTheDocument();
291
+ expect(screen.getByRole("heading", { name: "Ella" })).toBeInTheDocument();
292
+ expect(screen.queryByText("drug · major")).toBeNull();
293
+ expect(screen.queryByText(/Ulipristal may decrease/)).toBeNull();
294
+ });
295
+
296
+ it("an unsigned prescription's alert shows once, on that prescription's card", async () => {
297
+ renderOrderWithAlerts({ prescriptions: [signed, unsignedWithAllergy], screeningAlerts: [] });
298
+ await screen.findAllByText("allergen · moderate");
299
+ await screen.findByRole("button", { name: "Sign" });
300
+ expectAlertOnPrescriptionCards("allergen · moderate", 1);
301
+ });
302
+
303
+ it("an unsigned prescription with an alert keeps Send away until it is signed", async () => {
304
+ renderOrderWithAlerts({ prescriptions: [signed, unsignedWithAllergy], screeningAlerts: [] });
305
+ await screen.findAllByText("allergen · moderate");
306
+ expect(screen.getByRole("button", { name: "Sign" })).toBeEnabled();
307
+ expect(screen.queryByRole("button", { name: /^Send prescriptions? to patient$/ })).toBeNull();
308
+ });
309
+
310
+ it("order screening that failed on the server shows no alerts, the same as a clean screening", async () => {
311
+ renderOrderWithAlerts({ prescriptions: [signed], screeningAlerts: null });
312
+ await findSend();
313
+ expect(screen.queryByText(/^(allergen|drug|condition) · /)).toBeNull();
314
+ });
315
+ });
316
+
217
317
  type NetworkScript = Parameters<typeof fakeNetworkApiClient>[0];
218
318
 
219
319
  type RenderComponentOptions = {
@@ -254,3 +354,41 @@ function renderComponent({
254
354
  },
255
355
  };
256
356
  }
357
+
358
+ type FakePrescription = ReturnType<typeof rx>;
359
+
360
+ function renderOrderWithAlerts({
361
+ prescriptions,
362
+ screeningAlerts,
363
+ }: {
364
+ prescriptions: FakePrescription[];
365
+ screeningAlerts: FakePrescription["screeningAlerts"];
366
+ }) {
367
+ const orderWithAlerts = (state?: string) => ({ ...order(state), prescriptions, screeningAlerts });
368
+ return renderComponent({
369
+ photonOrderProps: { order: "ord_1" },
370
+ script: {
371
+ GetOrder: () => payload("order", "OrderPayload", orderWithAlerts()),
372
+ GetPrescription: ({ id }: { id: string }) =>
373
+ payload(
374
+ "prescription",
375
+ "PrescriptionPayload",
376
+ prescriptions.find((prescription) => prescription.id === id) ?? null,
377
+ ),
378
+ SubmitOrder: () => payload("order", "OrderPayload", orderWithAlerts("SUBMITTED")),
379
+ },
380
+ });
381
+ }
382
+
383
+ function findSend() {
384
+ return screen.findByRole("button", { name: /^Send prescriptions? to patient$/ });
385
+ }
386
+
387
+ function expectAlertOnPrescriptionCards(alertTitle: string, prescriptionCardsCarryingIt: number) {
388
+ const shown = screen.getAllByText(alertTitle);
389
+ expect(shown).toHaveLength(prescriptionCardsCarryingIt);
390
+ const endOfPrescriptionCards = screen.getByRole("button", { name: "Add another prescription" });
391
+ shown.forEach((alertShown) =>
392
+ expect(alertShown.compareDocumentPosition(endOfPrescriptionCards) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(),
393
+ );
394
+ }
@@ -1,5 +1,5 @@
1
1
  import { useComponents, usePhoton } from "../primitives/index.ts";
2
- import { AnalyticsWorkflow } from "../analytics/PhotonAnalyticsProvider.tsx";
2
+ import { AnalyticsWorkflow, usePhotonAnalytics } from "../analytics/PhotonAnalyticsProvider.tsx";
3
3
  import { viewedPropertiesFromCardProps } from "../analytics/viewed.ts";
4
4
  import { SignedIn } from "./SignedIn.tsx";
5
5
  import {
@@ -15,36 +15,37 @@ import {
15
15
  import { useLive, useOnChange } from "../hooks/index.ts";
16
16
  import { useEffect, useRef, useState } from "react";
17
17
  import { displayName } from "./format.ts";
18
- import { callFor, NotFound, openFailed, openGiven, shared, toOpen, type Given } from "./open.ts";
19
- import { PatientCard } from "./PhotonPatient.tsx";
18
+ import { callFor, NotFound, openFailed, openGiven, shared, toOpen } from "./open.ts";
19
+ import { PatientCard } from "./patient/PatientCard/PatientCard.tsx";
20
20
  import { PrescriptionCard } from "./prescription/PrescriptionCard.tsx";
21
21
  import { DraftOrderPrompt } from "./order/DraftOrderPrompt.tsx";
22
22
  import { ScreeningAlerts } from "./ScreeningAlerts.tsx";
23
23
  import { SearchResults } from "./search.tsx";
24
24
  import { cardFlowKeys, cardProps, focusProps } from "./flow.ts";
25
25
 
26
- /**
27
- * The order is the treatment: who it's for, their prescriptions, and sending them — on one card, bound to a
28
- * live Order from @photonhealth/client: the one given (live, used as given; or opened from what's given, see `Given`),
29
- * else a new order for the patient given, or for someone to find or add. The rules are the objects'; this renders
30
- * them, plus what's only about the screen: which line is focused, and the Sent summary. Send shows once the order
31
- * is ready and everything is saved.
32
- *
33
- * It renders only cards: no page, landmark or app chrome, so it sits in a page, a dialog or a side panel.
34
- */
35
26
  export interface PhotonOrderProps {
36
27
  /**
37
- * The order: a live Order (used as given), its id (`"ord_…"` or `{ id }`: read), its id with fields (that order
38
- * updated — e.g. prescriptions added), or what's known of one (synced): `{ patient: { id }, prescriptions: {
39
- * add: [{ templateId: "tmp_…" }, { id: "rx_…" }] } }` — new lines from a template, existing prescriptions (the
40
- * order takes their patient). Without prescriptions, it starts with one empty line.
28
+ * The order, one of:
29
+ * - a live `Order`: used as is
30
+ * - its id, `"ord_…"` or `{ id }`: gets the order
31
+ * - its id with fields, `{ id, … }`: updates the order (e.g. prescriptions added)
32
+ * - fields without an id: upserts the order, e.g.
33
+ * `{ patient: { id }, prescriptions: { add: [{ templateId: "tmp_…" }, { id: "rx_…" }] } }` — new lines from
34
+ * a template and existing prescriptions (the order takes their patient)
35
+ *
36
+ * Without prescriptions, it starts with one empty line.
41
37
  */
42
- order?: Order | Given<OrderInput> | null;
38
+ order?: Order | OrderInput | string | null;
43
39
  /**
44
- * Who a new order is for, when `order` doesn't say — given as a patient card's `patient` is. Without one,
45
- * someone to find or add.
40
+ * Who a new order is for, when `order` doesn't say, one of:
41
+ * - a live `Patient`: used as is
42
+ * - its id, `"pat_…"` or `{ id }`: gets the patient
43
+ * - its id with fields, `{ id, … }`: updates the patient
44
+ * - fields without an id: upserts the patient
45
+ *
46
+ * Without one, someone to find or add.
46
47
  */
47
- patient?: Patient | Given<PatientInput> | null;
48
+ patient?: Patient | PatientInput | string | null;
48
49
  /**
49
50
  * The order's patient, once it has a record and each time that record changes from the backend; `null` on
50
51
  * "Change patient".
@@ -122,7 +123,7 @@ function OrderCard(props: PhotonOrderProps) {
122
123
  useEffect(() => {
123
124
  if (sharedOrder) return;
124
125
  let live = true;
125
- const [wanted, forPatient] = JSON.parse(key) as [Given<OrderInput> | null, Given<PatientInput> | null];
126
+ const [wanted, forPatient] = JSON.parse(key) as [OrderInput | string | null, PatientInput | string | null];
126
127
  // Shared while it's in flight: StrictMode runs this twice, and a new order's draft is saved as it opens.
127
128
  shared(sharedPatient ?? ph, key, async () => {
128
129
  const opening = wanted ? callFor(wanted) : null;
@@ -200,6 +201,7 @@ function OrderView({
200
201
  }) {
201
202
  const { Alert, Button, Stack } = useComponents();
202
203
  const ph = usePhoton();
204
+ const analytics = usePhotonAnalytics();
203
205
  const snap = useLive(order)!;
204
206
  const final = order.final;
205
207
  const [sentHere, setSentHere] = useState(false);
@@ -237,6 +239,14 @@ function OrderView({
237
239
  );
238
240
  };
239
241
 
242
+ const removeLine = (line: Prescription, removal: OrderUpdate) => {
243
+ const removedId = line.id;
244
+ void change(order, removal).then((saved) => {
245
+ const removed = Boolean(saved) && !order.prescriptions.includes(line);
246
+ if (removed && removedId) void analytics.draftPrescriptionDeleted(removedId);
247
+ });
248
+ };
249
+
240
250
  const flow = useRef<HTMLDivElement>(null);
241
251
  // ← / → move between the cards: the patient, each prescription, "Add another", Send (flow.ts).
242
252
  return (
@@ -247,8 +257,8 @@ function OrderView({
247
257
  <div {...cardProps}>
248
258
  <PatientCard
249
259
  patient={patient}
250
- locked={final} // a sent order's patient is read-only
251
- fixed={handoff}
260
+ readOnly={final} // a sent order's patient is read-only
261
+ hideChangePatient={handoff}
252
262
  addressRequest={final ? null : snap.contactRequest}
253
263
  notFound={snap.patient?.id ? null : missingPatient}
254
264
  onPatient={(next) => {
@@ -299,10 +309,10 @@ function OrderView({
299
309
  final
300
310
  ? undefined
301
311
  : lines.length > 1
302
- ? () => void change(order, { prescriptions: { remove: [line] } })
312
+ ? () => removeLine(line, { prescriptions: { remove: [line] } })
303
313
  : filled(line)
304
314
  ? () => {
305
- void change(order, { prescriptions: { remove: [line], add: [{ templateId }] } });
315
+ removeLine(line, { prescriptions: { remove: [line], add: [{ templateId }] } });
306
316
  setAdded(order.prescriptions.at(-1) ?? null); // the fresh line, at once
307
317
  }
308
318
  : undefined
@@ -338,6 +348,7 @@ function OrderView({
338
348
  ready={order.readyToSend}
339
349
  onSubmitted={() => {
340
350
  setSentHere(true);
351
+ if (order.state) void analytics.orderSent(order.state);
341
352
  events.onSent?.(order);
342
353
  }}
343
354
  />
@@ -439,7 +450,7 @@ function SendSection({
439
450
  const contact = Boolean(snap.contactRequest);
440
451
  const failure = snap.error;
441
452
  const showSend = ready || sending;
442
- // Every alert no one has acknowledged — the prescriptions' interactions with each other too — before Send.
453
+ // The order's alerts no prescription carries, before Send.
443
454
  const alerts = order.unacknowledgedAlerts;
444
455
  if (!alerts.length && !notSent.length && !notSaved.length && !failure && !showSend) return null;
445
456
  return (
@@ -1,45 +1,24 @@
1
- import { useComponents, usePhoton } from "../primitives/index.ts";
2
1
  import { AnalyticsWorkflow } from "../analytics/PhotonAnalyticsProvider.tsx";
3
2
  import { viewedPropertiesFromCardProps } from "../analytics/viewed.ts";
4
3
  import { SignedIn } from "./SignedIn.tsx";
5
- import { classify, Patient, type ChangeOption, type PatientInput, type PatientResult } from "@photonhealth/client";
6
- import { useLive, useOnChange } from "../hooks/index.ts";
7
- import { useState } from "react";
8
- import { NotFound, openFailed, toOpen, useOpened, type Given } from "./open.ts";
9
- import { ChangeList } from "./ChangeList.tsx";
10
- import { PatientIntakeForm } from "./patient/IntakeForm.tsx";
11
- import { diagnosisRef, withoutInline } from "./patient/Clinical.tsx";
12
- import { PatientSummary } from "./patient/Summary.tsx";
4
+ import { type Patient, type PatientInput } from "@photonhealth/client";
5
+ import { PatientCard } from "./patient/PatientCard/PatientCard.tsx";
13
6
 
14
- type PatientClinicalInput = NonNullable<PatientInput["clinical"]>;
15
-
16
- /**
17
- * "Who is this patient?" — standalone or inside PhotonOrder. Bound to a live Patient from @photonhealth/client:
18
- * the one given (`patient`), one opened from what's given (get / update / sync, see `Given`), or a new one to
19
- * find or add. Before it has a record, every field the prescriber leaves is synced — the server decides: the
20
- * patient (found, or added), patients it might be (pick one), or what it still needs. Once it has one, edits
21
- * update it.
22
- */
23
7
  export interface PhotonPatientProps {
24
8
  /**
25
- * The patient: a live Patient (used as given; anything else holding it sees the same changes), its id
26
- * (`"pat_…"` or `{ id }`: read), its id with fields (that patient updated), or what's known of them without
27
- * one (synced: found, matched or added).
9
+ * The patient, one of:
10
+ * - a live `Patient`: used as is; anything else holding it sees the same changes
11
+ * - its id, `"pat_…"` or `{ id }`: gets the patient
12
+ * - its id with fields, `{ id, … }`: updates the patient
13
+ * - fields without an id: upserts the patient
28
14
  */
29
- patient?: Patient | Given<PatientInput> | null;
15
+ patient?: Patient | PatientInput | string | null;
30
16
  /**
31
17
  * The card's patient, once it has a record (found, picked, added, or opened with) and each time that record
32
18
  * changes from the backend. `null` on "Change patient": a card given `patient` leaves what's next to the
33
19
  * host (pass it a new one); otherwise it starts over itself.
34
20
  */
35
21
  onPatient?: (patient: Patient | null) => void;
36
- /** Read-only (e.g. on a sent order): nothing to edit, and no "Change patient". */
37
- locked?: boolean;
38
- /**
39
- * The patient is fixed — e.g. beside the host's own view of them: no "Change patient", but still editable.
40
- * (An embed whose link names the patient by id is fixed.)
41
- */
42
- fixed?: boolean;
43
22
  }
44
23
 
45
24
  /** A patient card. */
@@ -52,137 +31,3 @@ export function PhotonPatient(props: PhotonPatientProps) {
52
31
  </AnalyticsWorkflow>
53
32
  );
54
33
  }
55
-
56
- /** A stable key per live object: a different patient object gets a fresh form. */
57
- const objectKeys = new WeakMap<object, number>();
58
- let nextKey = 0;
59
- const keyOf = (obj: object) => {
60
- if (!objectKeys.has(obj)) objectKeys.set(obj, ++nextKey);
61
- return objectKeys.get(obj)!;
62
- };
63
-
64
- const patientOf = (r: PatientResult) => r.patient;
65
-
66
- /**
67
- * PhotonPatient, and what only PhotonOrder gives it: the server's request for a way to reach the patient (its
68
- * reason), which opens the contact fields. Internal: the package index exports only PhotonPatient.
69
- */
70
- export function PatientCard({
71
- patient,
72
- onPatient,
73
- locked,
74
- fixed,
75
- addressRequest,
76
- notFound,
77
- }: PhotonPatientProps & {
78
- addressRequest?: string | null;
79
- /** The patient it was given by id isn't there (PhotonOrder's): said in the form, with the matches. */
80
- notFound?: NotFound | null;
81
- }) {
82
- const { Alert, Card, CardHeader } = useComponents();
83
- const ph = usePhoton();
84
- // A new patient to find or add when the host gives none (and none to open) — and after "Change patient",
85
- // when the host didn't give one.
86
- const shared = patient instanceof Patient ? patient : null;
87
- const given = toOpen<PatientInput>(patient, Boolean(shared));
88
- const [own, setOwn] = useState<Patient | null>(() => (shared || given ? null : ph.patient()));
89
- const { opened, error: openError } = useOpened(ph.patient, given, patientOf, "patient");
90
- // Given by id and not there: someone to find or add instead, the reason said in the form — where its matches,
91
- // and anything else the server says, show. (Read-only, there's nothing to find: just the reason.)
92
- const missing = openError instanceof NotFound && !locked ? openError : null;
93
- // One patient object, always: the one given, the one opened from what's given, or the card's own — made once
94
- // there's none to show (nothing given, "Change patient", or an id the server doesn't have).
95
- if (missing && !own && !shared) setOwn(ph.patient());
96
- // The host gives another patient: that one, not the card's own.
97
- const givenKey = JSON.stringify(given);
98
- const [ownFor, setOwnFor] = useState(givenKey);
99
- if (givenKey !== ownFor) {
100
- setOwnFor(givenKey);
101
- if (given && own) setOwn(null);
102
- }
103
- const live = shared ?? own ?? opened;
104
- const snap = useLive(live);
105
- const record = snap?.state ?? null;
106
- useOnChange(live, (p) => p.state, onPatient);
107
-
108
- if (openError && !missing)
109
- return <Alert tone="critical" title={openFailed("patient", openError)} description={openError.message} />;
110
- if (!live || !snap) {
111
- return (
112
- <Card divided>
113
- <CardHeader title="Patient" description="Loading…" />
114
- </Card>
115
- );
116
- }
117
-
118
- const changes = classify(snap.changes);
119
- const update = (input: Omit<PatientInput, "id">) => void live.update(input).catch(() => {}); // failures land on the object
120
- const patchClinical = (clinical: PatientClinicalInput) => update({ clinical });
121
- const choose = (option: ChangeOption) => void live.choose(option).catch(() => {});
122
-
123
- if (record) {
124
- const messages = withoutInline(changes);
125
- const hasMessages =
126
- messages.needsChoice.length + messages.blocking.length + messages.advisories.length > 0 || Boolean(snap.error);
127
- return (
128
- <PatientSummary
129
- key={record.id}
130
- patient={record}
131
- pickedNames={snap.pickedNames}
132
- saving={snap.status === "saving"}
133
- changes={
134
- // Only when there's something to say — the card has no body otherwise.
135
- hasMessages && (
136
- <>
137
- <ChangeList changes={messages} onChoose={choose} busy={snap.status === "saving"} />
138
- {/* A failed save must never be silent (e.g. a rejected clinical patch). */}
139
- {snap.error && <Alert tone="critical" title="Couldn't save" description={snap.error.message} />}
140
- </>
141
- )
142
- }
143
- choices={changes.needsChoice}
144
- problems={changes.blocking}
145
- onChoose={choose}
146
- onAddAllergy={(name) => patchClinical({ allergies: { add: [{ name }] } })}
147
- onConfirmNone={(list) => patchClinical({ [list]: { none: true } })}
148
- onRemoveAllergy={(a) => patchClinical({ allergies: { remove: [{ id: a.id }] } })}
149
- onRemoveMedication={(m) => patchClinical({ medications: { remove: [{ id: m.id, status: m.status }] } })}
150
- onAddDiagnosis={(text) => patchClinical({ diagnoses: { add: [diagnosisRef(text)] } })}
151
- onRemoveDiagnosis={(d) => patchClinical({ diagnoses: { remove: [{ id: d.id }] } })}
152
- onAddBenefit={(b) => update({ benefits: { add: [b] } })}
153
- onRemoveBenefit={(b) => update({ benefits: { remove: [{ id: b.id }] } })}
154
- onConfirmNoBenefits={() => update({ benefits: { none: true } })}
155
- onAddMedication={(name) => patchClinical({ medications: { add: [{ name, status: "ACTIVE" }] } })}
156
- onSaveContact={(contact) => update({ contact })}
157
- onSaveDetails={(details) => update({ demographic: details })}
158
- addressRequest={locked ? null : (addressRequest ?? null)}
159
- readOnly={locked}
160
- onChangePatient={
161
- locked || fixed
162
- ? undefined
163
- : () => {
164
- onPatient?.(null); // given a patient, the host decides what's next
165
- if (!shared) setOwn(ph.patient());
166
- }
167
- }
168
- />
169
- );
170
- }
171
-
172
- // A different patient object (e.g. after "Change patient") starts a fresh form.
173
- const why = notFound ?? missing;
174
- return (
175
- <PatientIntakeForm
176
- key={keyOf(live)}
177
- patient={live}
178
- notice={why && { title: openFailed("patient", why), description: why.message }}
179
- />
180
- );
181
- }
182
-
183
- /**
184
- * Find or add the patient. Each field the prescriber leaves (and Enter) sends everything known so far to the
185
- * live Patient — one query that searches and syncs. The server decides: the patient, patients it might be
186
- * (listed to pick from), or what it still needs (shown; an address only when it asks). Fields left, not
187
- * keystrokes: a query with enough to add a patient adds them.
188
- */
@@ -1,12 +1,11 @@
1
- // @vitest-environment jsdom
2
- import { cleanup, render, screen, waitFor, within } from "@testing-library/react";
1
+ import { render, screen, waitFor, within } from "@testing-library/react";
3
2
  import userEvent from "@testing-library/user-event";
4
3
  import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
4
  import { fakeNetworkApiClient, payload } from "@photonhealth/client/testing";
6
5
  import { PhotonPrescription } from "../index.ts";
7
6
  import { fakeNetworkApi, patient } from "../../test/cards.fixtures.tsx";
8
7
  import {
9
- edited,
8
+ buildEditedEventsFor,
10
9
  leaveField,
11
10
  meAsPrescriber,
12
11
  recordAnalytics,
@@ -17,9 +16,6 @@ import {
17
16
  } from "../../test/analytics.fixtures.tsx";
18
17
 
19
18
  // The card as a workflow: its analytics. The card itself is tested in prescription/PrescriptionCard.test.tsx.
20
-
21
- afterEach(cleanup);
22
-
23
19
  const settledDrugRow = (row: RegExp) =>
24
20
  waitFor(() => {
25
21
  const button = screen.getByRole<HTMLButtonElement>("button", { name: row });
@@ -60,7 +56,12 @@ describe("PhotonPrescription: Field Interaction", () => {
60
56
  await screen.findByLabelText("Directions (sig)");
61
57
  leaveField();
62
58
 
63
- await analytics.expectEventLog(["Prescribe Workflow Viewed", ...edited("treatment")]);
59
+ await analytics.expectSentOnce("Prescribe Workflow Viewed");
60
+ await analytics.expectSentOnce("Field Interaction treatment focus");
61
+ await analytics.expectSentOnce("Field Interaction treatment change");
62
+ await analytics.expectSentOnce("Field Interaction treatment blur");
63
+ await analytics.expectSentOnce("Draft Prescription Added");
64
+ await analytics.expectEventCount(5);
64
65
  expect(analytics.sentFor("treatment").at(-1)).toMatchObject({ hasValue: true, changed: true });
65
66
  });
66
67
 
@@ -94,18 +95,21 @@ describe("PhotonPrescription: Field Interaction", () => {
94
95
  await userEvent.click(screen.getByRole("checkbox", { name: "Dispense as written" }));
95
96
  leaveField();
96
97
 
97
- await analytics.expectEventLog([
98
+ const eventsSentOnce = [
98
99
  "Prescribe Workflow Viewed",
99
- ...edited("treatment"),
100
- ...edited("form"),
101
- ...edited("strength"),
102
- ...edited("instructions"),
103
- ...edited("dispenseQuantity"),
104
- ...edited("dispenseUnit"),
105
- ...edited("daysSupply"),
106
- ...edited("refills"),
107
- ...edited("dispenseAsWritten"),
108
- ]);
100
+ ...buildEditedEventsFor("treatment"),
101
+ ...buildEditedEventsFor("form"),
102
+ ...buildEditedEventsFor("strength"),
103
+ ...buildEditedEventsFor("instructions"),
104
+ ...buildEditedEventsFor("dispenseQuantity"),
105
+ ...buildEditedEventsFor("dispenseUnit"),
106
+ ...buildEditedEventsFor("daysSupply"),
107
+ ...buildEditedEventsFor("refills"),
108
+ ...buildEditedEventsFor("dispenseAsWritten"),
109
+ "Draft Prescription Added",
110
+ ];
111
+ for (const event of eventsSentOnce) await analytics.expectSentOnce(event);
112
+ await analytics.expectEventCount(eventsSentOnce.length);
109
113
  expect(new Set(analytics.fieldInteractions().map((sent) => sent.formName))).toEqual(
110
114
  new Set(["add_prescription_form"]),
111
115
  );
@@ -3,26 +3,26 @@ import { viewedPropertiesFromCardProps } from "../analytics/viewed.ts";
3
3
  import { SignedIn } from "./SignedIn.tsx";
4
4
  import { type Patient, type Prescription, type PatientInput, type PrescriptionInput } from "@photonhealth/client";
5
5
  import { PrescriptionCard } from "./prescription/PrescriptionCard.tsx";
6
- import { type Given } from "./open.ts";
7
6
 
8
- /**
9
- * One prescription: free-text drug → the server resolves it (or offers choices) → sig and dispense →
10
- * screening → Sign. Standalone or inside PhotonOrder. Bound to a live Prescription from @photonhealth/client: the
11
- * one given (`prescription` — a line before its record, or an existing one), one opened from its id and / or an
12
- * input (get / sync / update), or else a new line. The rules are the object's; this renders it.
13
- */
14
7
  export interface PhotonPrescriptionProps {
15
8
  /**
16
- * The prescription: a live Prescription (used as given; anything else holding it sees the same changes), its
17
- * id (`"rx_…"` or `{ id }`: read), its id with fields (that prescription updated), or fields without one
18
- * (synced — e.g. `{ templateId }` or `{ treatment: { name } }`).
9
+ * The prescription, one of:
10
+ * - a live `Prescription`: used as is; anything else holding it sees the same changes
11
+ * - its id, `"rx_…"` or `{ id }`: gets the prescription
12
+ * - its id with fields, `{ id, … }`: updates the prescription
13
+ * - fields without an id, e.g. `{ templateId }` or `{ treatment: { name } }`: upserts the prescription
19
14
  */
20
- prescription?: Prescription | Given<PrescriptionInput> | null;
15
+ prescription?: Prescription | PrescriptionInput | string | null;
21
16
  /**
22
- * Who it's for — given as a patient card's `patient` is. Until it's known, a new line only looks drugs up
23
- * (a line from an order already knows).
17
+ * Who it's for, one of:
18
+ * - a live `Patient`: used as is
19
+ * - its id, `"pat_…"` or `{ id }`: gets the patient
20
+ * - its id with fields, `{ id, … }`: updates the patient
21
+ * - fields without an id: upserts the patient
22
+ *
23
+ * Until it's known, a new line only looks drugs up.
24
24
  */
25
- patient?: Patient | Given<PatientInput> | null;
25
+ patient?: Patient | PatientInput | string | null;
26
26
  /** Read-only (e.g. on a finalized order). A signed prescription is always read-only. */
27
27
  locked?: boolean;
28
28
  /** The prescriber signed it on this card — once per prescription. */