@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
@@ -0,0 +1,262 @@
1
+ import { 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 { change, fakeNetworkApiClient, noMatch, payload, photonOver } from "@photonhealth/client/testing";
5
+ import type { Patient } from "@photonhealth/client";
6
+ import { PhotonPatient } from "../../index.ts";
7
+ import { PatientIntakeForm } from "./PatientIntakeForm.tsx";
8
+ import { patient as ada, withPhoton } from "../../../test/cards.fixtures.tsx";
9
+ import {
10
+ buildEditedEventsFor,
11
+ leaveField,
12
+ meAsPrescriber,
13
+ recordAnalytics,
14
+ type RecordedAnalytics,
15
+ typeInto,
16
+ unmountAndRestoreFetch,
17
+ visitedWithoutEditing,
18
+ withAnalytics,
19
+ } from "../../../test/analytics.fixtures.tsx";
20
+
21
+ type NetworkScript = Parameters<typeof fakeNetworkApiClient>[0];
22
+ type SyncVars = { demographic?: { sex?: string }; contact?: { phone?: string; email?: string } };
23
+
24
+ /** A server message about one field: rejected, so the patient can't be added until it's answered. */
25
+ const rejected = (key: string, reason: string) =>
26
+ change({ key, label: key, status: "REJECTED", severity: "BLOCKING", reason });
27
+
28
+ /**
29
+ * PatientIntakeForm on its own, over a fake network-api that finds no one unless `script` says otherwise.
30
+ * `hostDetails` are what a host passed to PhotonPatient: synced before the form opens, so the patient already has
31
+ * what the server said about them.
32
+ * `sent` collects every SyncPatient's variables, to check what Save sends.
33
+ */
34
+ const renderIntakeForm = async ({
35
+ query,
36
+ script = {},
37
+ hostDetails,
38
+ }: {
39
+ query?: string;
40
+ script?: NetworkScript;
41
+ hostDetails?: Parameters<Patient["sync"]>[0];
42
+ } = {}) => {
43
+ const sent: SyncVars[] = [];
44
+ const answer = (script.SyncPatient ?? noMatch) as (vars: SyncVars) => unknown;
45
+ const { client } = fakeNetworkApiClient({
46
+ ...script,
47
+ SyncPatient: (vars: SyncVars) => {
48
+ sent.push(vars);
49
+ return answer(vars);
50
+ },
51
+ });
52
+ const live = photonOver(client).patient();
53
+ if (hostDetails) await live.sync(hostDetails).catch(() => {});
54
+ const user = userEvent.setup();
55
+ render(<PatientIntakeForm patient={live} query={query} />, { wrapper: withPhoton(client) });
56
+ return { live, user, lastSent: () => sent.at(-1) };
57
+ };
58
+
59
+ const sexField = () => screen.getByRole("combobox", { name: "Sex" });
60
+ const NEEDED = "Needed to add a patient";
61
+
62
+ describe("PatientIntakeForm", () => {
63
+ describe("initial values", () => {
64
+ it("text typed in PatientSearch: fills in first name, last name, date of birth, phone and email from that text", async () => {
65
+ await renderIntakeForm({ query: "Grace Hopper 12/09/1906 4155550172 grace@example.com" });
66
+ expect(screen.getByLabelText("First name")).toHaveValue("Grace");
67
+ expect(screen.getByLabelText("Last name")).toHaveValue("Hopper");
68
+ expect(screen.getByLabelText("Date of birth")).toHaveValue("1906-12-09");
69
+ expect(screen.getByLabelText("Phone")).toHaveValue("+1 (415) 555-0172");
70
+ expect(screen.getByLabelText("Email")).toHaveValue("grace@example.com");
71
+ });
72
+
73
+ it("nothing typed in PatientSearch: fills in the fields from the details the patient already has (e.g. details a host passed)", async () => {
74
+ await renderIntakeForm({
75
+ hostDetails: { demographic: { name: { first: "Grace", last: "Hopper" }, sex: "FEMALE" } },
76
+ });
77
+ expect(screen.getByLabelText("First name")).toHaveValue("Grace");
78
+ expect(screen.getByLabelText("Last name")).toHaveValue("Hopper");
79
+ expect(sexField()).toHaveValue("FEMALE");
80
+ });
81
+
82
+ it("nothing typed in PatientSearch and no details from a host: every field starts empty", async () => {
83
+ await renderIntakeForm();
84
+ for (const label of ["First name", "Last name", "Date of birth", "Phone", "Email"]) {
85
+ expect(screen.getByLabelText(label)).toHaveValue("");
86
+ }
87
+ expect(sexField()).toHaveValue("");
88
+ });
89
+
90
+ // TODO: Fix the UX here
91
+ // The cursor should be on whatever the first empty required input is
92
+ it("once PatientIntakeForm opens: cursor starts on the Sex field, even when first name, last name and date of birth are empty", async () => {
93
+ // Nothing typed and no host details: first name, last name and date of birth are all empty.
94
+ await renderIntakeForm();
95
+ expect(screen.getByLabelText("First name")).toHaveValue("");
96
+ await waitFor(() => expect(sexField()).toHaveFocus());
97
+ });
98
+ });
99
+
100
+ // TODO: Need a separate, more rigorously tested util (probably Zod schema)
101
+ // for patient input validation
102
+ describe("saving", () => {
103
+ it("Save with required fields empty: each empty required field shows a validation error message", async () => {
104
+ const { user } = await renderIntakeForm({ query: "Grace" });
105
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
106
+ // Last name, date of birth and sex are empty; first name was typed.
107
+ expect(screen.getAllByText(NEEDED)).toHaveLength(3);
108
+ expect(screen.getByLabelText("Last name")).toHaveAttribute("aria-invalid", "true");
109
+ });
110
+
111
+ // Pins today's behavior. The form means to move the cursor to the first field Save is waiting on, but it
112
+ // looks for the first element marked invalid, and with the default building blocks that's the field's
113
+ // wrapper <div>, which can't take focus.
114
+ // TODO: focus the first invalid input, not its wrapper
115
+ it("Save with required fields empty: the cursor stays on the Save button", async () => {
116
+ const { user } = await renderIntakeForm({ query: "Grace" });
117
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
118
+ expect(screen.getByRole("button", { name: "Save patient" })).toHaveFocus();
119
+ });
120
+
121
+ it("after Save, typing into an empty required field: removes the validation error message from that field", async () => {
122
+ const { user } = await renderIntakeForm({ query: "Grace" });
123
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
124
+ await user.type(screen.getByLabelText("Last name"), "Hopper");
125
+ expect(screen.getAllByText(NEEDED)).toHaveLength(2);
126
+ });
127
+
128
+ it("Save with first name, last name, date of birth and sex filled in: the patient is added", async () => {
129
+ const { user, live } = await renderIntakeForm({
130
+ query: "Ada Lovelace 1990-01-01",
131
+ script: { SyncPatient: () => payload("patient", "PatientPayload", ada) },
132
+ });
133
+ await user.selectOptions(sexField(), "FEMALE");
134
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
135
+ await waitFor(() => expect(live.id).toBe("pat_1"));
136
+ expect(screen.queryByText(NEEDED)).not.toBeInTheDocument();
137
+ });
138
+
139
+ // TODO: abstract patient validation to a separate util
140
+ // so we can remove this test
141
+ it("Save with a phone number: the phone number is sent in E.164 format", async () => {
142
+ const { user, lastSent } = await renderIntakeForm({ query: "Grace Hopper 1906-12-09" });
143
+ await user.type(screen.getByLabelText("Phone"), "415-555-0172");
144
+ await user.selectOptions(sexField(), "FEMALE");
145
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
146
+ await waitFor(() => expect(lastSent()?.contact).toEqual({ phone: "+14155550172" }));
147
+ });
148
+
149
+ // Pins today's behavior.
150
+ // TODO: we shouldn't show the browser's own validation
151
+ it("Save with an email that isn't valid: the browser's own validation stops Save, so the patient isn't added", async () => {
152
+ const { user, live } = await renderIntakeForm({
153
+ query: "Ada Lovelace 1990-01-01",
154
+ script: { SyncPatient: () => payload("patient", "PatientPayload", ada) },
155
+ });
156
+ await user.type(screen.getByLabelText("Email"), "not-an-email");
157
+ await user.selectOptions(sexField(), "FEMALE");
158
+ await user.click(screen.getByRole("button", { name: "Save patient" }));
159
+ await new Promise((done) => setTimeout(done, 100));
160
+ expect(live.id).toBeNull();
161
+ });
162
+ });
163
+
164
+ // TODO: Replace this test after implementing more rigorous frontend validation
165
+ // If we still get a server message, add tests for how to display them
166
+ describe("server messages", () => {
167
+ it('the server\'s "still needed" messages for name, date of birth and sex: hidden until all four fields are filled in', async () => {
168
+ const { user } = await renderIntakeForm({
169
+ script: {
170
+ SyncPatient: () =>
171
+ payload("patient", "PatientPayload", null, {
172
+ changes: [
173
+ rejected("demographic.dateOfBirth", "Date of birth is needed"),
174
+ rejected("contact.phone", "Phone isn't valid"),
175
+ ],
176
+ }),
177
+ },
178
+ hostDetails: { contact: { phone: "1" } },
179
+ });
180
+ // Other messages show straight away.
181
+ expect(await screen.findByText(/Phone isn't valid/)).toBeInTheDocument();
182
+ expect(screen.queryByText(/Date of birth is needed/)).not.toBeInTheDocument();
183
+ await user.type(screen.getByLabelText("First name"), "Grace");
184
+ await user.type(screen.getByLabelText("Last name"), "Hopper");
185
+ await user.type(screen.getByLabelText("Date of birth"), "1906-12-09");
186
+ await user.selectOptions(sexField(), "FEMALE");
187
+ expect(screen.getByText(/Date of birth is needed/)).toBeInTheDocument();
188
+ });
189
+ });
190
+ });
191
+
192
+ const renderPatientCard = () =>
193
+ render(<PhotonPatient />, {
194
+ wrapper: withAnalytics(fakeNetworkApiClient({ ...meAsPrescriber, SyncPatient: noMatch }).client),
195
+ });
196
+
197
+ describe("PatientIntakeForm: Field Interaction", () => {
198
+ let analytics: RecordedAnalytics;
199
+ beforeEach(() => {
200
+ analytics = recordAnalytics();
201
+ });
202
+ afterEach(unmountAndRestoreFetch);
203
+
204
+ it("typing in PatientSearch's Find patient field: sends focus, one change and blur events for find_patient's patientSearch field, without what was typed", async () => {
205
+ renderPatientCard();
206
+ await typeInto("Find patient", "Zqxfirst Zqxlast");
207
+
208
+ await analytics.expectEventLog([
209
+ "Field Interaction patientSearch focus",
210
+ "Prescribe Workflow Viewed",
211
+ "Field Interaction patientSearch change",
212
+ "Field Interaction patientSearch blur",
213
+ ]);
214
+ expect(analytics.sentFor("patientSearch")).toEqual([
215
+ expect.objectContaining({ formName: "find_patient", hasValue: false, isOptional: false }),
216
+ expect.objectContaining({ hasValue: true }),
217
+ expect.objectContaining({ hasValue: true, changed: true, durationMs: expect.any(Number) }),
218
+ ]);
219
+ for (const body of analytics.bodies()) expect(body).not.toMatch(/Zqx/i);
220
+ });
221
+
222
+ it("adding a patient: each field visited sends focus, one change and blur events for new_patient_form, without what was typed", async () => {
223
+ renderPatientCard();
224
+ await typeInto("Find patient", "Zqxfirst Zqxlast");
225
+ await userEvent.click(await screen.findByRole("option", { name: /Add new patient/ }));
226
+ await typeInto("First name", "Zqxa");
227
+ await typeInto("Last name", "Zqxb");
228
+ await userEvent.click(screen.getByLabelText("Date of birth"));
229
+ fireEvent.change(screen.getByLabelText("Date of birth"), { target: { value: "1990-01-01" } });
230
+ leaveField();
231
+ await userEvent.selectOptions(screen.getByRole("combobox", { name: "Sex" }), "FEMALE");
232
+ leaveField();
233
+ await typeInto("Phone", "5555550100");
234
+ await typeInto("Email", "zqx@example.com");
235
+
236
+ await analytics.expectEventLog([
237
+ "Field Interaction patientSearch focus",
238
+ "Prescribe Workflow Viewed",
239
+ "Field Interaction patientSearch change",
240
+ "Field Interaction patientSearch blur",
241
+ ...visitedWithoutEditing("firstName"),
242
+ ...visitedWithoutEditing("sex"),
243
+ ...buildEditedEventsFor("firstName"),
244
+ ...buildEditedEventsFor("lastName"),
245
+ ...buildEditedEventsFor("dateOfBirth"),
246
+ ...buildEditedEventsFor("sex"),
247
+ ...buildEditedEventsFor("phone"),
248
+ ...buildEditedEventsFor("email"),
249
+ ]);
250
+ const sent = analytics.fieldInteractions().filter((s) => s.fieldName !== "patientSearch");
251
+ expect(new Set(sent.map((s) => s.formName))).toEqual(new Set(["new_patient_form"]));
252
+ expect(Object.fromEntries(sent.map((s) => [s.fieldName, s.isOptional]))).toEqual({
253
+ firstName: false,
254
+ lastName: false,
255
+ dateOfBirth: false,
256
+ sex: false,
257
+ phone: true,
258
+ email: true,
259
+ });
260
+ for (const body of analytics.bodies()) expect(body).not.toMatch(/Zqx|1990|5555550100|FEMALE/i);
261
+ });
262
+ });
@@ -0,0 +1,222 @@
1
+ /** PhotonPatient before a record, adding them: the fields network-api needs, and what the server says about them. */
2
+ import { useComponents } from "../../primitives/index.ts";
3
+ import { classify, type Patient, type Sex } from "@photonhealth/client";
4
+ import { useLive } from "../../hooks/index.ts";
5
+ import { useEffect, useId, useRef, useState, type SubmitEvent } from "react";
6
+ import { ChangeList } from "../ChangeList.tsx";
7
+ import { formatPhone, PHONE_PATTERN, toE164 } from "../format.ts";
8
+
9
+ import { IDENTITY_KEYS, noAutofill, SEX_OPTIONS } from "./fields.tsx";
10
+ import { focusProps } from "../flow.ts";
11
+ import { parsePatientSearchQuery } from "./parsePatientSearchQuery.ts";
12
+ import { TrackedField, useFieldInteractions } from "../../analytics/fieldInteraction.tsx";
13
+ import { useSavePatientAndSendEvent } from "../../analytics/cardLifecycle.ts";
14
+
15
+ type Field = "first" | "last" | "dob" | "sex";
16
+
17
+ export function PatientIntakeForm({
18
+ patient,
19
+ query,
20
+ notice,
21
+ }: {
22
+ patient: Patient;
23
+ /**
24
+ * What was typed in PatientSearch before "Add new patient": split into the fields, so nothing is retyped and the
25
+ * prescriber can see, and correct, how it was read. Without one, the fields start from what the patient already
26
+ * has (e.g. a host's details the server hasn't matched yet).
27
+ */
28
+ query?: string | null;
29
+ /** Why someone else is being added (e.g. the patient given by id isn't there). */
30
+ notice?: { title: string; description: string } | null;
31
+ }) {
32
+ const { Alert, Badge, Button, Card, CardBody, CardFooter, CardHeader, Grid, Input, Select, Spinner, Stack } =
33
+ useComponents();
34
+ const snap = useLive(patient)!;
35
+ const formId = useId();
36
+ const savePatientAndSendEvent = useSavePatientAndSendEvent();
37
+ const known = patient.known;
38
+ const typed = query != null ? parsePatientSearchQuery(query) : null;
39
+ const [first, setFirst] = useState((typed ? typed.name?.first : known.demographic?.name?.first) ?? "");
40
+ const [last, setLast] = useState((typed ? typed.name?.last : known.demographic?.name?.last) ?? "");
41
+ const [dob, setDob] = useState((typed ? typed.dateOfBirth : known.demographic?.dateOfBirth) ?? "");
42
+ const [sex, setSex] = useState<Sex | null>(known.demographic?.sex ?? null);
43
+ const sexPicked = useFieldInteractions("new_patient_form")("sex", { isOptional: false, hasValue: Boolean(sex) });
44
+ const [email, setEmail] = useState(typed?.email ?? known.contact?.email ?? "");
45
+ const knownPhone = typed?.phone ?? known.contact?.phone;
46
+ const [phone, setPhone] = useState(knownPhone ? formatPhone(knownPhone) : "");
47
+ /** Which of the four network-api needs were empty when Save was last pressed. */
48
+ const [missing, setMissing] = useState<Field[]>([]);
49
+ /** What a required field says while Save is waiting on it. The server names all four at once; we don't. */
50
+ const gap = (field: Field) =>
51
+ missing.includes(field) ? { invalid: true, errorMessage: "Needed to add a patient" } : {};
52
+
53
+ const busy = snap.status === "loading" || snap.status === "saving";
54
+ // What the server still needs to add the patient (name, DOB, sex) is what this form asks for next — not an
55
+ // error. Once the prescriber has filled all four, anything it still rejects about them is shown.
56
+ const identityFilled = Boolean(first.trim() && last.trim() && dob && sex);
57
+ const changes = classify({
58
+ ...snap.changes,
59
+ unapplied: snap.changes.unapplied.filter((c) => identityFilled || !IDENTITY_KEYS.includes(c.key)),
60
+ });
61
+
62
+ /** Everything known on the form. Phone / email ride along once they're valid; the browser shows why otherwise. */
63
+ const form = () => {
64
+ const validPhone = new RegExp(`^(?:${PHONE_PATTERN})$`).test(phone.trim());
65
+ const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
66
+ const demographic = {
67
+ name: { first, last },
68
+ dateOfBirth: dob,
69
+ ...(sex ? { sex } : {}),
70
+ };
71
+ const contact = {
72
+ ...(validPhone ? { phone: toE164(phone) } : {}),
73
+ ...(validEmail ? { email: email.trim() } : {}),
74
+ };
75
+ return { demographic, contact };
76
+ };
77
+ /** Send everything known: the server may find or add the patient. The object adds it to what it sent before. */
78
+ const send = () => void savePatientAndSendEvent(patient, () => patient.sync(form())).catch(() => {}); // failures land on the object
79
+
80
+ /** A field changed: keep it. Answering what Save asked for puts it right at once. */
81
+ const type = (field: Field | null, set: (value: string) => void) => (e: { target: { value: string } }) => {
82
+ set(e.target.value);
83
+ if (field && e.target.value.trim()) setMissing((m) => m.filter((f) => f !== field));
84
+ };
85
+ const submit = (e: SubmitEvent) => {
86
+ e.preventDefault();
87
+ save();
88
+ };
89
+
90
+ /**
91
+ * Add them. network-api creates a patient only with a first name, a last name, a date of birth and a sex
92
+ * (`Sex` has UNKNOWN, so there is always an answer), and the schema says nothing about which of them a
93
+ * payload is short of — so the form checks before it sends, rather than Save failing with a rejection
94
+ * naming every field at once.
95
+ *
96
+ * The server still decides what this means: it may find the patient instead of adding them, or come back
97
+ * with people it might be. Only this press asks it.
98
+ */
99
+ const REQUIRED: [Field, boolean][] = [
100
+ ["first", Boolean(first.trim())],
101
+ ["last", Boolean(last.trim())],
102
+ ["dob", Boolean(dob)],
103
+ ["sex", Boolean(sex)],
104
+ ];
105
+ const save = () => {
106
+ const empty = REQUIRED.filter(([, filled]) => !filled).map(([field]) => field);
107
+ setMissing(empty);
108
+ if (empty.length) return; // the fields say which; the cursor goes to the first of them (below)
109
+ send();
110
+ };
111
+
112
+ // Sex is the one thing a search never fills in, and the one network-api needs to create, so that's where focus
113
+ // goes: the form is filled in and the deliberate act is choosing it.
114
+ const sexField = useRef<HTMLDivElement | null>(null);
115
+ const fields = useRef<HTMLFormElement | null>(null);
116
+ // Save pressed with gaps: the cursor goes to the first field it is waiting on, so answering starts there.
117
+ useEffect(() => {
118
+ if (!missing.length) return;
119
+ fields.current?.querySelector<HTMLElement>('[aria-invalid="true"], [data-invalid]')?.focus();
120
+ }, [missing]);
121
+ // Once the form is up, the cursor goes to Sex (the Select is a building block, so by where it lands).
122
+ const landed = useRef(false);
123
+ useEffect(() => {
124
+ if (landed.current || !sexField.current) return;
125
+ landed.current = true;
126
+ sexField.current.querySelector<HTMLElement>("input, select, button")?.focus();
127
+ }, []);
128
+
129
+ return (
130
+ <Card divided>
131
+ <CardHeader title="Patient" />
132
+ <CardBody>
133
+ <form {...noAutofill} ref={fields} id={formId} onSubmit={submit}>
134
+ <Stack gap="3">
135
+ <Grid min="200px" gap="3">
136
+ <div {...focusProps}>
137
+ <TrackedField formName="new_patient_form" fieldName="firstName" isOptional={false}>
138
+ <Input
139
+ {...gap("first")}
140
+ label="First name"
141
+ value={first}
142
+ onChange={type("first", setFirst)}
143
+ autoFocus
144
+ {...noAutofill}
145
+ />
146
+ </TrackedField>
147
+ </div>
148
+ <TrackedField formName="new_patient_form" fieldName="lastName" isOptional={false}>
149
+ <Input
150
+ {...gap("last")}
151
+ label="Last name"
152
+ value={last}
153
+ onChange={type("last", setLast)}
154
+ {...noAutofill}
155
+ />
156
+ </TrackedField>
157
+ <TrackedField formName="new_patient_form" fieldName="dateOfBirth" isOptional={false}>
158
+ <Input
159
+ {...gap("dob")}
160
+ label="Date of birth"
161
+ type="date"
162
+ {...noAutofill}
163
+ value={dob}
164
+ onChange={type("dob", setDob)}
165
+ />
166
+ </TrackedField>
167
+ <div ref={sexField} onFocus={sexPicked.onFocus} onBlur={sexPicked.onBlur}>
168
+ <Select
169
+ {...gap("sex")}
170
+ label="Sex"
171
+ placeholder="Select…"
172
+ options={SEX_OPTIONS}
173
+ value={sex}
174
+ onChange={(next) => {
175
+ sexPicked.onChange(true);
176
+ setSex(next);
177
+ setMissing((m) => m.filter((f) => f !== "sex"));
178
+ }}
179
+ />
180
+ </div>
181
+ <TrackedField formName="new_patient_form" fieldName="phone" isOptional>
182
+ <Input
183
+ label="Phone"
184
+ helper="The patient is texted their order link here, so a mobile number."
185
+ type="tel"
186
+ inputMode="tel"
187
+ pattern={PHONE_PATTERN}
188
+ value={phone}
189
+ onChange={type(null, setPhone)}
190
+ onBlur={() => setPhone(formatPhone(phone))}
191
+ {...noAutofill}
192
+ />
193
+ </TrackedField>
194
+ <TrackedField formName="new_patient_form" fieldName="email" isOptional>
195
+ <Input
196
+ label="Email"
197
+ type="email"
198
+ inputMode="email"
199
+ value={email}
200
+ onChange={type(null, setEmail)}
201
+ {...noAutofill}
202
+ />
203
+ </TrackedField>
204
+ </Grid>
205
+
206
+ {/* Why someone else is being added, what the server said, and what failed. */}
207
+ {notice && <Alert tone="critical" title={notice.title} description={notice.description} />}
208
+ <ChangeList changes={changes} />
209
+ {snap.error && <Badge tone="critical">{snap.error.message}</Badge>}
210
+ </Stack>
211
+ </form>
212
+ </CardBody>
213
+ {/* Adding a patient is a deliberate act, so it takes a press. Until this, nothing has been sent and nobody
214
+ has been created — the prescriber can still fix every field above, or walk away. */}
215
+ <CardFooter start={busy ? <Spinner label="Adding…" /> : undefined}>
216
+ <Button type="submit" form={formId} loading={busy}>
217
+ Save patient
218
+ </Button>
219
+ </CardFooter>
220
+ </Card>
221
+ );
222
+ }