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

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 (185) 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 +16 -8
  93. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -1
  94. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts +14 -1
  95. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts.map +1 -1
  96. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js +25 -7
  97. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js.map +1 -1
  98. package/dist/components/schemaErrors.d.ts +3 -2
  99. package/dist/components/schemaErrors.d.ts.map +1 -1
  100. package/dist/components/schemaErrors.js +2 -1
  101. package/dist/components/schemaErrors.js.map +1 -1
  102. package/dist/components/search.d.ts +1 -1
  103. package/dist/components/search.js +1 -1
  104. package/dist/index.d.ts +1 -1
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +1 -1
  107. package/dist/index.js.map +1 -1
  108. package/dist/meta/version.js +1 -1
  109. package/package.json +5 -2
  110. package/src/analytics/PhotonAnalyticsProvider.test.tsx +0 -1
  111. package/src/analytics/PhotonAnalyticsProvider.tsx +75 -20
  112. package/src/analytics/cardLifecycle.test.tsx +272 -0
  113. package/src/analytics/cardLifecycle.ts +44 -0
  114. package/src/analytics/fieldInteraction.test.tsx +11 -9
  115. package/src/analytics/lifecycleOutcomes.test.ts +78 -0
  116. package/src/analytics/lifecycleOutcomes.ts +29 -0
  117. package/src/analytics/tracker.test.ts +1 -1
  118. package/src/analytics/tracker.ts +13 -6
  119. package/src/analytics/usePhotonAnalytics.test.tsx +106 -0
  120. package/src/components/PhotonOrder.test.tsx +146 -8
  121. package/src/components/PhotonOrder.tsx +37 -26
  122. package/src/components/PhotonPatient.tsx +8 -163
  123. package/src/components/PhotonPrescription.test.tsx +22 -18
  124. package/src/components/PhotonPrescription.tsx +14 -14
  125. package/src/components/ScreeningAlerts.test.tsx +81 -0
  126. package/src/components/open.ts +13 -16
  127. package/src/components/order/DraftOrderPrompt.test.tsx +3 -6
  128. package/src/components/patient/PatientCard/PatientCard.test.tsx +255 -0
  129. package/src/components/patient/PatientCard/PatientCard.tsx +177 -0
  130. package/src/components/patient/PatientCard/usePatientToShow.ts +44 -0
  131. package/src/components/patient/PatientIntakeForm.test.tsx +262 -0
  132. package/src/components/patient/PatientIntakeForm.tsx +222 -0
  133. package/src/components/patient/PatientSearch.test.tsx +204 -0
  134. package/src/components/patient/PatientSearch.tsx +221 -0
  135. package/src/components/patient/PatientSummary/BenefitsInputForm.test.tsx +164 -0
  136. package/src/components/patient/{Benefits.tsx → PatientSummary/BenefitsInputForm.tsx} +4 -4
  137. package/src/components/patient/PatientSummary/ClinicalInputForm.test.tsx +247 -0
  138. package/src/components/patient/{Clinical.tsx → PatientSummary/ClinicalInputForm.tsx} +23 -23
  139. package/src/components/patient/PatientSummary/CollapsedSummary.test.tsx +90 -0
  140. package/src/components/patient/PatientSummary/CollapsedSummary.tsx +46 -0
  141. package/src/components/patient/PatientSummary/PatientDetailsForm.test.tsx +201 -0
  142. package/src/components/patient/PatientSummary/PatientDetailsForm.tsx +320 -0
  143. package/src/components/patient/PatientSummary/PatientDetailsSchema.test.ts +296 -0
  144. package/src/components/patient/PatientSummary/PatientDetailsSchema.ts +95 -0
  145. package/src/components/patient/PatientSummary/PatientSummary.test.tsx +194 -0
  146. package/src/components/patient/PatientSummary/PatientSummary.tsx +225 -0
  147. package/src/components/patient/PatientSummary/SummaryHeader.test.tsx +183 -0
  148. package/src/components/patient/PatientSummary/SummaryHeader.tsx +85 -0
  149. package/src/components/patient/fields.tsx +12 -138
  150. package/src/components/patient/parsePatientSearchQuery.test.ts +107 -0
  151. package/src/components/patient/{query.ts → parsePatientSearchQuery.ts} +4 -21
  152. package/src/components/prescription/PrescriptionCard.test.tsx +175 -12
  153. package/src/components/prescription/PrescriptionCard.tsx +28 -14
  154. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +2 -5
  155. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +3 -6
  156. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +34 -37
  157. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +24 -16
  158. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.test.ts +166 -41
  159. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.ts +41 -9
  160. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +2 -5
  161. package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +3 -7
  162. package/src/components/schemaErrors.ts +3 -2
  163. package/src/components/search.tsx +1 -1
  164. package/src/index.ts +1 -1
  165. package/src/meta/version.test.ts +1 -0
  166. package/src/meta/version.ts +1 -1
  167. package/dist/components/patient/Benefits.d.ts.map +0 -1
  168. package/dist/components/patient/Benefits.js.map +0 -1
  169. package/dist/components/patient/Clinical.d.ts.map +0 -1
  170. package/dist/components/patient/Clinical.js.map +0 -1
  171. package/dist/components/patient/IntakeForm.d.ts +0 -10
  172. package/dist/components/patient/IntakeForm.d.ts.map +0 -1
  173. package/dist/components/patient/IntakeForm.js +0 -333
  174. package/dist/components/patient/IntakeForm.js.map +0 -1
  175. package/dist/components/patient/Summary.d.ts +0 -48
  176. package/dist/components/patient/Summary.d.ts.map +0 -1
  177. package/dist/components/patient/Summary.js +0 -90
  178. package/dist/components/patient/Summary.js.map +0 -1
  179. package/dist/components/patient/query.d.ts +0 -37
  180. package/dist/components/patient/query.d.ts.map +0 -1
  181. package/dist/components/patient/query.js.map +0 -1
  182. package/src/components/patient/IntakeForm.test.tsx +0 -89
  183. package/src/components/patient/IntakeForm.tsx +0 -564
  184. package/src/components/patient/Summary.test.tsx +0 -106
  185. package/src/components/patient/Summary.tsx +0 -330
@@ -1,6 +1,7 @@
1
1
  import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
2
2
  import { PhotonContext } from "../primitives/photonContext.ts";
3
3
  import { reactPackage } from "../meta/version.ts";
4
+ import type { Analytics, LifecycleAnalytics } from "@photonhealth/client";
4
5
  import { trackerFor, type AnalyticsProperties } from "./tracker.ts";
5
6
 
6
7
  interface AnalyticsSettings {
@@ -32,9 +33,11 @@ export function PhotonAnalyticsProvider({
32
33
 
33
34
  type Category = "elementViewed" | "fieldInteraction" | "ctaClicked";
34
35
 
36
+ type PhotonComponentName = "PhotonOrder" | "PhotonPatient" | "PhotonPrescription";
37
+
35
38
  interface Workflow {
36
39
  sessionId: string;
37
- card: string;
40
+ component: PhotonComponentName;
38
41
  }
39
42
 
40
43
  const WorkflowContext = createContext<Workflow | null>(null);
@@ -49,12 +52,12 @@ export function AnalyticsWorkflow({
49
52
  viewedProperties,
50
53
  children,
51
54
  }: {
52
- card: string;
55
+ card: PhotonComponentName;
53
56
  viewedProperties: AnalyticsProperties;
54
57
  children: ReactNode;
55
58
  }) {
56
59
  const outerWorkflow = useContext(WorkflowContext);
57
- const [workflow] = useState<Workflow>(() => ({ sessionId: newSessionId(), card }));
60
+ const [workflow] = useState<Workflow>(() => ({ sessionId: newSessionId(), component: card }));
58
61
  const track = useTrackIn(outerWorkflow ?? workflow);
59
62
  const viewedPropertiesKey = JSON.stringify(viewedProperties);
60
63
  useEffect(() => {
@@ -70,27 +73,79 @@ export function useTrack() {
70
73
  return useTrackIn(useContext(WorkflowContext));
71
74
  }
72
75
 
76
+ export function usePhotonAnalytics(): LifecycleAnalytics {
77
+ const sendFromWorkflow = useSendIn(useContext(WorkflowContext));
78
+ return useMemo(() => lifecycleAnalyticsFrom(sendFromWorkflow), [sendFromWorkflow]);
79
+ }
80
+
81
+ type SendFromWorkflow = (
82
+ category: Category,
83
+ callerProperties: AnalyticsProperties | undefined,
84
+ send: (analytics: Analytics, properties: AnalyticsProperties) => Promise<void>,
85
+ ) => Promise<void>;
86
+
73
87
  function useTrackIn(workflow: Workflow | null) {
88
+ const sendFromWorkflow = useSendIn(workflow);
89
+ return useMemo(
90
+ () =>
91
+ (event: string, category: Category, properties: AnalyticsProperties = {}) =>
92
+ void sendFromWorkflow(category, properties, (analytics, withWorkflow) => analytics.track(event, withWorkflow)),
93
+ [sendFromWorkflow],
94
+ );
95
+ }
96
+
97
+ function useSendIn(workflow: Workflow | null): SendFromWorkflow {
74
98
  const ph = useContext(PhotonContext);
75
99
  const settings = useContext(AnalyticsContext);
76
100
  return useMemo(
77
- () =>
78
- (event: string, category: Category, properties: AnalyticsProperties = {}) => {
79
- if (!ph || !settings.enabled) return;
80
- trackerFor(ph).track({
81
- event,
82
- properties: {
83
- sessionId: workflow?.sessionId ?? null,
84
- integration: "react",
85
- packageName: reactPackage.name,
86
- packageVersion: reactPackage.version,
87
- category,
88
- timestamp: new Date().toISOString(),
89
- ...properties,
90
- ...settings.hostProperties,
91
- },
92
- });
93
- },
101
+ () => async (category, callerProperties, send) => {
102
+ if (!ph || !settings.enabled) return;
103
+ const properties: AnalyticsProperties = {
104
+ sessionId: workflow?.sessionId ?? null,
105
+ integration: "react",
106
+ packageName: reactPackage.name,
107
+ packageVersion: reactPackage.version,
108
+ category,
109
+ timestamp: new Date().toISOString(),
110
+ ...callerProperties,
111
+ ...settings.hostProperties,
112
+ };
113
+ trackerFor(ph).send((analytics) => send(analytics, properties));
114
+ },
94
115
  [ph, settings, workflow],
95
116
  );
96
117
  }
118
+
119
+ function lifecycleAnalyticsFrom(sendFromWorkflow: SendFromWorkflow): LifecycleAnalytics {
120
+ const ctaClicked = (
121
+ callerProperties: AnalyticsProperties | undefined,
122
+ send: (analytics: Analytics, properties: AnalyticsProperties) => Promise<void>,
123
+ ) => sendFromWorkflow("ctaClicked", callerProperties, send);
124
+
125
+ return {
126
+ patientCreated: (patient, properties) =>
127
+ ctaClicked(properties, (analytics, withWorkflow) => analytics.patientCreated(patient, withWorkflow)),
128
+ patientUpdated: (patient, properties) =>
129
+ ctaClicked(properties, (analytics, withWorkflow) => analytics.patientUpdated(patient, withWorkflow)),
130
+ draftPrescriptionAdded: (prescription, source, properties) =>
131
+ ctaClicked(properties, (analytics, withWorkflow) =>
132
+ analytics.draftPrescriptionAdded(prescription, source, withWorkflow),
133
+ ),
134
+ draftPrescriptionDeleted: (prescriptionId, properties) =>
135
+ ctaClicked(properties, (analytics, withWorkflow) =>
136
+ analytics.draftPrescriptionDeleted(prescriptionId, withWorkflow),
137
+ ),
138
+ screeningAlertAcknowledged: (alerts, buttonText, properties) =>
139
+ ctaClicked(properties, (analytics, withWorkflow) =>
140
+ analytics.screeningAlertAcknowledged(alerts, buttonText, withWorkflow),
141
+ ),
142
+ screeningAlertCanceled: (alerts, buttonText, properties) =>
143
+ ctaClicked(properties, (analytics, withWorkflow) =>
144
+ analytics.screeningAlertCanceled(alerts, buttonText, withWorkflow),
145
+ ),
146
+ prescriptionSigned: (prescription, properties) =>
147
+ ctaClicked(properties, (analytics, withWorkflow) => analytics.prescriptionSigned(prescription, withWorkflow)),
148
+ orderSent: (order, properties) =>
149
+ ctaClicked(properties, (analytics, withWorkflow) => analytics.orderSent(order, withWorkflow)),
150
+ };
151
+ }
@@ -0,0 +1,272 @@
1
+ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
2
+ import userEvent from "@testing-library/user-event";
3
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
4
+ import { alert, change, fakeNetworkApiClient, noMatch, payload, rx } from "@photonhealth/client/testing";
5
+ import { PhotonOrder, PhotonPatient, PhotonPrescription } from "../index.ts";
6
+ import { draftOrder, fakeNetworkApi, order, patient, signed } from "../../test/cards.fixtures.tsx";
7
+ import {
8
+ meAsPrescriber,
9
+ recordAnalytics,
10
+ type RecordedAnalytics,
11
+ typeInto,
12
+ unmountAndRestoreFetch,
13
+ withAnalytics,
14
+ } from "../../test/analytics.fixtures.tsx";
15
+
16
+ type NetworkScript = Parameters<typeof fakeNetworkApiClient>[0];
17
+
18
+ const TYPED_BY_THE_PRESCRIBER = ["Grace", "Hopper", "1906-12-09", "5555550100"];
19
+
20
+ const grace = {
21
+ ...patient,
22
+ id: "pat_grace",
23
+ demographic: {
24
+ ...patient.demographic,
25
+ name: { ...patient.demographic.name, first: "Grace", last: "Hopper" },
26
+ dateOfBirth: "1906-12-09",
27
+ sex: "FEMALE",
28
+ },
29
+ };
30
+
31
+ const firstNameAdded = change({ key: "demographic.name.first", label: "First name", operation: "ADDED" });
32
+ const phoneAdded = change({ key: "contact.phone", label: "Phone", operation: "ADDED" });
33
+
34
+ let analytics: RecordedAnalytics;
35
+ beforeEach(() => {
36
+ analytics = recordAnalytics();
37
+ });
38
+ afterEach(unmountAndRestoreFetch);
39
+
40
+ describe("PhotonPatient's lifecycle events", () => {
41
+ it("Save patient that creates the record sends Patient Created once, with which fields are filled and nothing typed", async () => {
42
+ renderCard(<PhotonPatient />, {
43
+ SyncPatient: (vars: { demographic?: { sex?: string } }) =>
44
+ vars.demographic?.sex
45
+ ? payload("patient", "PatientPayload", grace, { changes: [firstNameAdded] } as never)
46
+ : noMatch(),
47
+ });
48
+ await addGraceHopper();
49
+
50
+ await expectLifecycleEvents(["Patient Created"]);
51
+ expect(lifecycleEvent("Patient Created")).toMatchObject({
52
+ patientId: "pat_grace",
53
+ snap_first_name: true,
54
+ snap_last_name: true,
55
+ snap_date_of_birth: true,
56
+ snap_sex: true,
57
+ snap_email: false,
58
+ category: "ctaClicked",
59
+ integration: "react",
60
+ });
61
+ expectNothingTypedWasSent();
62
+ });
63
+
64
+ it("Save patient that finds an existing patient sends no lifecycle event", async () => {
65
+ renderCard(<PhotonPatient />, {
66
+ SyncPatient: (vars: { demographic?: { sex?: string } }) =>
67
+ vars.demographic?.sex ? payload("patient", "PatientPayload", grace) : noMatch(),
68
+ });
69
+ await addGraceHopper();
70
+ await screen.findByRole("heading", { name: /Grace Hopper/ });
71
+
72
+ await expectLifecycleEvents([]);
73
+ });
74
+
75
+ it("saving an edit to the patient sends Patient Updated", async () => {
76
+ // Save needs every required field, sex included.
77
+ const withSex = { ...patient, demographic: { ...patient.demographic, sex: "FEMALE" } };
78
+ renderCard(<PhotonPatient patient="pat_1" />, {
79
+ GetPatient: () => payload("patient", "PatientPayload", withSex),
80
+ UpdatePatient: () => payload("patient", "PatientPayload", withSex, { changes: [phoneAdded] } as never),
81
+ });
82
+ await userEvent.click(await screen.findByRole("button", { name: "Edit patient" }));
83
+ await typeInto("Phone", "5555550100");
84
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
85
+
86
+ await expectLifecycleEvents(["Patient Updated"]);
87
+ expect(lifecycleEvent("Patient Updated")).toMatchObject({ patientId: "pat_1", snap_address_street1: true });
88
+ expectNothingTypedWasSent();
89
+ });
90
+ });
91
+
92
+ describe("PhotonPrescription's lifecycle events", () => {
93
+ const amoxicillin = { amo: [["Amoxicillin", "Capsule", "500 MG"]] } satisfies Parameters<
94
+ typeof fakeNetworkApi
95
+ >[0]["prescriptions"];
96
+
97
+ it("picking a drug that drafts the prescription sends Draft Prescription Added once, from the form", async () => {
98
+ renderCard(<PhotonPrescription patient="pat_1" />, {
99
+ GetPatient: () => payload("patient", "PatientPayload", patient),
100
+ ...fakeNetworkApi({ prescriptions: amoxicillin }),
101
+ });
102
+ await draftAmoxicillin();
103
+
104
+ await expectLifecycleEvents(["Draft Prescription Added"]);
105
+ expect(lifecycleEvent("Draft Prescription Added")).toMatchObject({
106
+ prescriptionId: "rx_1",
107
+ draftPrescriptionSource: "form",
108
+ snap_treatment: true,
109
+ snap_instructions: true,
110
+ snap_dispense_quantity: true,
111
+ });
112
+ });
113
+
114
+ it("Add sends Prescription Signed once, after the draft's Draft Prescription Added", async () => {
115
+ renderCard(<PhotonPrescription patient="pat_1" />, {
116
+ GetPatient: () => payload("patient", "PatientPayload", patient),
117
+ ...fakeNetworkApi({ prescriptions: amoxicillin }),
118
+ });
119
+ await draftAmoxicillin();
120
+ fireEvent.click(await screen.findByRole("button", { name: "Sign" }));
121
+
122
+ await expectLifecycleEvents(["Draft Prescription Added", "Prescription Signed"]);
123
+ expect(lifecycleEvent("Prescription Signed")).toMatchObject({
124
+ prescriptionId: "rx_1",
125
+ category: "ctaClicked",
126
+ screeningAlertCount: 0,
127
+ });
128
+ });
129
+
130
+ it("Add on a prescription showing a screening alert sends Prescription Signed counting the alert it acknowledged", async () => {
131
+ renderCard(<PhotonPrescription patient="pat_1" />, {
132
+ GetPatient: () => payload("patient", "PatientPayload", patient),
133
+ ...fakeNetworkApi({ prescriptions: amoxicillin, screeningAlerts: [alert] }),
134
+ });
135
+ await draftAmoxicillin();
136
+ fireEvent.click(await screen.findByRole("button", { name: "Sign" }));
137
+
138
+ await expectLifecycleEvents(["Draft Prescription Added", "Prescription Signed"]);
139
+ expect(lifecycleEvent("Prescription Signed")).toMatchObject({ prescriptionId: "rx_1", screeningAlertCount: 1 });
140
+ });
141
+
142
+ it("a prescription opened by its id sends no Draft Prescription Added: it was drafted elsewhere", async () => {
143
+ renderCard(<PhotonPrescription prescription="rx_1" />, {
144
+ GetPrescription: () => payload("prescription", "PrescriptionPayload", rx({ id: "rx_1" })),
145
+ });
146
+ await screen.findByLabelText("Directions (sig)");
147
+
148
+ await expectLifecycleEvents([]);
149
+ });
150
+ });
151
+
152
+ describe("PhotonOrder's lifecycle events", () => {
153
+ const sendableOrder = {
154
+ GetOrder: () => payload("order", "OrderPayload", order()),
155
+ GetPrescription: () => payload("prescription", "PrescriptionPayload", signed),
156
+ SubmitOrder: () => payload("order", "OrderPayload", order("SUBMITTED")),
157
+ };
158
+
159
+ it("Send sends Order Sent once, to the patient, in the same session as the card's Prescribe Workflow Viewed", async () => {
160
+ renderCard(<PhotonOrder order="ord_1" />, sendableOrder);
161
+ const send = await screen.findByRole("button", { name: /^Send prescriptions? to patient$/ });
162
+ await waitFor(() => expect(send).toBeEnabled());
163
+ fireEvent.click(send);
164
+
165
+ await expectLifecycleEvents(["Order Sent"]);
166
+ expect(lifecycleEvent("Order Sent")).toMatchObject({
167
+ orderId: "ord_1",
168
+ prescriptionCount: 1,
169
+ prescriptionIds: ["rx_a"],
170
+ fulfillmentType: "SEND_TO_PATIENT",
171
+ });
172
+ expect(lifecycleEvent("Order Sent").sessionId).toBe(sentEvent("Prescribe Workflow Viewed").sessionId);
173
+ });
174
+
175
+ it("removing a drafted line sends Draft Prescription Deleted with its id", async () => {
176
+ renderCard(<PhotonOrder patient="pat_1" />, {
177
+ ...draftOrder(),
178
+ RemovePrescriptionsFromOrder: () =>
179
+ payload("order", "OrderPayload", { ...order(), id: "ordd_1", prescriptions: [] }),
180
+ GetPatient: () => payload("patient", "PatientPayload", patient),
181
+ ...fakeNetworkApi({ prescriptions: { amo: [["Amoxicillin", "Capsule", "500 MG"]] } }),
182
+ });
183
+ await draftAmoxicillin();
184
+ await expectLifecycleEvents(["Draft Prescription Added"]);
185
+ fireEvent.click(screen.getByRole("button", { name: "Remove prescription" }));
186
+
187
+ await expectLifecycleEvents(["Draft Prescription Added", "Draft Prescription Deleted"]);
188
+ expect(lifecycleEvent("Draft Prescription Deleted")).toMatchObject({ prescriptionId: "rx_1" });
189
+ });
190
+
191
+ it("with disableAnalytics, sending the order sends nothing", async () => {
192
+ const { callNames } = renderCard(<PhotonOrder order="ord_1" />, sendableOrder, { disableAnalytics: true });
193
+ const send = await screen.findByRole("button", { name: /^Send prescriptions? to patient$/ });
194
+ await waitFor(() => expect(send).toBeEnabled());
195
+ fireEvent.click(send);
196
+ await waitFor(() => expect(callNames()).toContain("SubmitOrder"));
197
+
198
+ await act(() => new Promise((settled) => setTimeout(settled, 300)));
199
+ expect(analytics.bodies()).toEqual([]);
200
+ });
201
+ });
202
+
203
+ const LIFECYCLE_EVENTS = [
204
+ "Patient Created",
205
+ "Patient Updated",
206
+ "Draft Prescription Added",
207
+ "Draft Prescription Deleted",
208
+ "Screening Alert Acknowledged",
209
+ "Screening Alert Canceled",
210
+ "Prescription Signed",
211
+ "Order Sent",
212
+ ];
213
+
214
+ interface SentEvent {
215
+ event: string;
216
+ properties: Record<string, unknown>;
217
+ }
218
+
219
+ function renderCard(card: React.ReactElement, script: NetworkScript, options?: { disableAnalytics?: boolean }) {
220
+ const { client, names } = fakeNetworkApiClient({ ...meAsPrescriber, ...script });
221
+ render(card, { wrapper: withAnalytics(client, options) });
222
+ return { callNames: names };
223
+ }
224
+
225
+ async function addGraceHopper() {
226
+ await userEvent.type(await screen.findByLabelText("Find patient"), "Grace Hopper");
227
+ await userEvent.click(await screen.findByText("Add new patient"));
228
+ await userEvent.type(await screen.findByLabelText("Date of birth"), "1906-12-09");
229
+ await userEvent.selectOptions(screen.getByRole("combobox", { name: "Sex" }), "FEMALE");
230
+ await userEvent.click(screen.getByRole("button", { name: "Save patient" }));
231
+ }
232
+
233
+ async function draftAmoxicillin() {
234
+ await userEvent.click(await screen.findByLabelText("Treatment"));
235
+ await userEvent.keyboard("Amo");
236
+ const product = await waitFor(() => {
237
+ const row = screen.getByRole<HTMLButtonElement>("button", { name: /^Amoxicillin/ });
238
+ expect(row.disabled).toBe(false);
239
+ return row;
240
+ });
241
+ await userEvent.click(product);
242
+ await screen.findByLabelText("Directions (sig)");
243
+ }
244
+
245
+ function sent(): SentEvent[] {
246
+ return analytics.bodies().map((body) => JSON.parse(body) as SentEvent);
247
+ }
248
+
249
+ function sentEvent(name: string) {
250
+ return sent().find(({ event }) => event === name)!.properties;
251
+ }
252
+
253
+ function lifecycleEventsSent() {
254
+ return sent()
255
+ .map(({ event }) => event)
256
+ .filter((event) => LIFECYCLE_EVENTS.includes(event));
257
+ }
258
+
259
+ function lifecycleEvent(name: string) {
260
+ return sentEvent(name);
261
+ }
262
+
263
+ async function expectLifecycleEvents(expected: string[]) {
264
+ await waitFor(() => expect(lifecycleEventsSent()).toEqual(expected));
265
+ await act(() => new Promise((settled) => setTimeout(settled, 300)));
266
+ expect(lifecycleEventsSent(), "each lifecycle event once, and none after").toEqual(expected);
267
+ }
268
+
269
+ function expectNothingTypedWasSent() {
270
+ const everythingSent = analytics.bodies().join("\n");
271
+ for (const typed of TYPED_BY_THE_PRESCRIBER) expect(everythingSent).not.toContain(typed);
272
+ }
@@ -0,0 +1,44 @@
1
+ import { useCallback, useEffect, useState } from "react";
2
+ import type { Changes, DraftPrescriptionSource, Patient, Prescription } from "@photonhealth/client";
3
+ import { usePhotonAnalytics } from "./PhotonAnalyticsProvider.tsx";
4
+ import { draftedNewPrescription, patientWriteOutcome } from "./lifecycleOutcomes.ts";
5
+
6
+ type PatientSave = () => Promise<{ changes: Changes }>;
7
+
8
+ export function useSavePatientAndSendEvent() {
9
+ const analytics = usePhotonAnalytics();
10
+ return useCallback(
11
+ async (patient: Patient, save: PatientSave) => {
12
+ const hadRecord = Boolean(patient.id);
13
+ const saved = await save();
14
+ const record = patient.state;
15
+ if (!record) return saved;
16
+ const outcome = patientWriteOutcome({ hadRecord, changes: saved.changes });
17
+ if (outcome === "created") void analytics.patientCreated(record);
18
+ if (outcome === "updated") void analytics.patientUpdated(record);
19
+ return saved;
20
+ },
21
+ [analytics],
22
+ );
23
+ }
24
+
25
+ export function useSendDraftPrescriptionAdded(prescription: Prescription | null) {
26
+ const analytics = usePhotonAnalytics();
27
+ const [seenBeforeItsRecord] = useState(() => new WeakSet<Prescription>());
28
+ useEffect(() => {
29
+ if (!prescription) return;
30
+ const sendOnceDrafted = () => {
31
+ const record = prescription.state;
32
+ if (!record) return void seenBeforeItsRecord.add(prescription);
33
+ if (!seenBeforeItsRecord.delete(prescription)) return;
34
+ if (!draftedNewPrescription(prescription.changes)) return;
35
+ void analytics.draftPrescriptionAdded(record, draftSourceOf(prescription));
36
+ };
37
+ sendOnceDrafted();
38
+ return prescription.subscribe(sendOnceDrafted);
39
+ }, [prescription, analytics, seenBeforeItsRecord]);
40
+ }
41
+
42
+ function draftSourceOf(prescription: Prescription): DraftPrescriptionSource {
43
+ return prescription.templateId ? "template_prefill" : "form";
44
+ }
@@ -1,4 +1,3 @@
1
- // @vitest-environment jsdom
2
1
  import { render, screen, waitFor } from "@testing-library/react";
3
2
  import userEvent from "@testing-library/user-event";
4
3
  import { useState } from "react";
@@ -6,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6
5
  import { fakeNetworkApiClient } from "@photonhealth/client/testing";
7
6
  import { TrackedField, useFieldInteractions } from "./fieldInteraction.tsx";
8
7
  import {
9
- edited,
8
+ buildEditedEventsFor,
10
9
  meAsPrescriber,
11
10
  recordAnalytics,
12
11
  type RecordedAnalytics,
@@ -77,7 +76,7 @@ describe("useFieldInteractions", () => {
77
76
  await userEvent.keyboard("30");
78
77
  await userEvent.click(screen.getByLabelText("Elsewhere"));
79
78
 
80
- await analytics.expectEventLog([...edited("dispenseQuantity")]);
79
+ await analytics.expectEventLog([...buildEditedEventsFor("dispenseQuantity")]);
81
80
  expect(analytics.sentFor("dispenseQuantity")).toEqual([
82
81
  expect.objectContaining({
83
82
  category: "fieldInteraction",
@@ -113,7 +112,10 @@ describe("useFieldInteractions", () => {
113
112
  await userEvent.keyboard("0");
114
113
  await userEvent.click(screen.getByLabelText("Elsewhere"));
115
114
 
116
- await analytics.expectEventLog([...edited("dispenseQuantity"), ...edited("dispenseQuantity")]);
115
+ await analytics.expectEventLog([
116
+ ...buildEditedEventsFor("dispenseQuantity"),
117
+ ...buildEditedEventsFor("dispenseQuantity"),
118
+ ]);
117
119
  });
118
120
 
119
121
  it("a picker is one field: moving between its options sends no blur, and picking sends change", async () => {
@@ -123,7 +125,7 @@ describe("useFieldInteractions", () => {
123
125
  await userEvent.click(screen.getByRole("button", { name: "20 mg" }));
124
126
  await userEvent.click(screen.getByLabelText("Elsewhere"));
125
127
 
126
- await analytics.expectEventLog([...edited("strength")]);
128
+ await analytics.expectEventLog([...buildEditedEventsFor("strength")]);
127
129
  expect(analytics.sentFor("strength").map((sent) => sent.hasValue)).toEqual([false, true, true]);
128
130
  });
129
131
 
@@ -133,7 +135,7 @@ describe("useFieldInteractions", () => {
133
135
  await userEvent.keyboard("12");
134
136
  rerender(<QuantityAndStrength showQuantity={false} />);
135
137
 
136
- await analytics.expectEventLog([...edited("dispenseQuantity")]);
138
+ await analytics.expectEventLog([...buildEditedEventsFor("dispenseQuantity")]);
137
139
  expect(analytics.sentFor("dispenseQuantity")[2]).toMatchObject({ hasValue: true, changed: true });
138
140
  });
139
141
 
@@ -143,7 +145,7 @@ describe("useFieldInteractions", () => {
143
145
  await userEvent.keyboard("987654");
144
146
  await userEvent.click(screen.getByLabelText("Elsewhere"));
145
147
 
146
- await analytics.expectEventLog([...edited("dispenseQuantity")]);
148
+ await analytics.expectEventLog([...buildEditedEventsFor("dispenseQuantity")]);
147
149
  for (const body of analytics.bodies()) expect(body).not.toContain("987654");
148
150
  });
149
151
 
@@ -176,8 +178,8 @@ describe("useFieldInteractions", () => {
176
178
  await userEvent.click(screen.getByLabelText("Elsewhere"));
177
179
 
178
180
  await analytics.expectEventLog([
179
- ...edited("treatment"),
180
- ...edited("strength"),
181
+ ...buildEditedEventsFor("treatment"),
182
+ ...buildEditedEventsFor("strength"),
181
183
  ...visitedWithoutEditing("treatment"),
182
184
  ]);
183
185
  });
@@ -0,0 +1,78 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import type { Change, Changes } from "@photonhealth/client";
3
+ import { draftedNewPrescription, patientWriteOutcome } from "./lifecycleOutcomes.ts";
4
+
5
+ describe("patientWriteOutcome: which lifecycle event a patient write is", () => {
6
+ it("a patient without a record whose first name was added is created", () => {
7
+ const changes = changesWith({ applied: [applied("demographic.name.first", "ADDED")] });
8
+ expect(patientWriteOutcome({ hadRecord: false, changes })).toBe("created");
9
+ });
10
+
11
+ it("a patient that already had a record is updated, even when a first name is added", () => {
12
+ const changes = changesWith({ applied: [applied("demographic.name.first", "ADDED")] });
13
+ expect(patientWriteOutcome({ hadRecord: true, changes })).toBe("updated");
14
+ });
15
+
16
+ it("a patient found rather than added, with a field filled in, is updated", () => {
17
+ const changes = changesWith({ applied: [applied("contact.phone", "ADDED")] });
18
+ expect(patientWriteOutcome({ hadRecord: false, changes })).toBe("updated");
19
+ });
20
+
21
+ it("a first name added alongside a rejected field is updated, not created", () => {
22
+ const changes = changesWith({
23
+ applied: [applied("demographic.name.first", "ADDED")],
24
+ unapplied: [{ ...applied("contact.phone", "ADDED"), status: "REJECTED" }],
25
+ });
26
+ expect(patientWriteOutcome({ hadRecord: false, changes })).toBe("updated");
27
+ });
28
+
29
+ it("a write the server applied nothing from is unchanged", () => {
30
+ expect(patientWriteOutcome({ hadRecord: true, changes: changesWith({}) })).toBe("unchanged");
31
+ });
32
+ });
33
+
34
+ describe("draftedNewPrescription: whether a prescription's record is a new draft", () => {
35
+ it("is true when its treatment was added", () => {
36
+ expect(draftedNewPrescription(changesWith({ applied: [applied("treatment", "ADDED")] }))).toBe(true);
37
+ });
38
+
39
+ it("is false for a draft that was continued: its treatment was already there", () => {
40
+ expect(draftedNewPrescription(changesWith({ applied: [applied("instructions", "MODIFIED")] }))).toBe(false);
41
+ });
42
+
43
+ it("is false when the server rejected something in the same write", () => {
44
+ const changes = changesWith({
45
+ applied: [applied("treatment", "ADDED")],
46
+ unapplied: [{ ...applied("dispense.quantity", "ADDED"), status: "REJECTED" }],
47
+ });
48
+ expect(draftedNewPrescription(changes)).toBe(false);
49
+ });
50
+
51
+ it("is true alongside an advisory the server applied anyway", () => {
52
+ const changes = changesWith({
53
+ applied: [applied("treatment", "ADDED")],
54
+ unapplied: [{ ...applied("clinical.screeningAlerts", "ADDED"), severity: "ADVISORY" }],
55
+ });
56
+ expect(draftedNewPrescription(changes)).toBe(true);
57
+ });
58
+ });
59
+
60
+ function changesWith({ applied = [], unapplied = [] }: Partial<Changes>): Changes {
61
+ return { applied, unapplied };
62
+ }
63
+
64
+ function applied(key: string, operation: Change["operation"]): Change {
65
+ return {
66
+ key,
67
+ label: key,
68
+ status: "APPLIED",
69
+ severity: "INFO",
70
+ reason: null,
71
+ category: null,
72
+ operation,
73
+ options: [],
74
+ after: null,
75
+ inputText: null,
76
+ resolvedId: null,
77
+ };
78
+ }
@@ -0,0 +1,29 @@
1
+ import type { Changes } from "@photonhealth/client";
2
+
3
+ export type PatientWriteOutcome = "created" | "updated" | "unchanged";
4
+
5
+ export function patientWriteOutcome({
6
+ hadRecord,
7
+ changes,
8
+ }: {
9
+ hadRecord: boolean;
10
+ changes: Changes;
11
+ }): PatientWriteOutcome {
12
+ if (!changes.applied.length) return "unchanged";
13
+ return !hadRecord && addedWithNothingRejected(changes, FIELD_ONLY_A_NEW_PATIENT_ADDS) ? "created" : "updated";
14
+ }
15
+
16
+ export function draftedNewPrescription(changes: Changes): boolean {
17
+ return addedWithNothingRejected(changes, FIELD_ONLY_A_NEW_PRESCRIPTION_ADDS);
18
+ }
19
+
20
+ const FIELD_ONLY_A_NEW_PATIENT_ADDS = "demographic.name.first";
21
+ const FIELD_ONLY_A_NEW_PRESCRIPTION_ADDS = "treatment";
22
+
23
+ function addedWithNothingRejected(changes: Changes, key: string): boolean {
24
+ const nothingRejected = changes.unapplied.every((change) => change.status === "APPLIED");
25
+ const added = changes.applied.some(
26
+ (change) => change.key === key && change.status === "APPLIED" && change.operation === "ADDED",
27
+ );
28
+ return nothingRejected && added;
29
+ }
@@ -4,7 +4,7 @@ import { fakeNetworkApiClient, photonOver } from "@photonhealth/client/testing";
4
4
  import { MAX_QUEUED_EVENTS, Tracker } from "./tracker.ts";
5
5
 
6
6
  // Sending — the token, providerId, analytics-api — is @photonhealth/client's (`ph.analytics.track`, its
7
- // test/analytics.test.ts). The Tracker only holds events until the sign-in is accepted.
7
+ // src/analytics/track.test.ts). The Tracker only holds events until the sign-in is accepted.
8
8
 
9
9
  const photonWithTrackSpy = () => {
10
10
  const ph = photonOver(fakeNetworkApiClient({}).client, environmentUrls("boson"), {