@photonhealth/client 0.0.0-stage → 2.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +234 -2
  3. package/dist/analytics/lifecycleEvents.d.ts +29 -0
  4. package/dist/analytics/lifecycleEvents.d.ts.map +1 -0
  5. package/dist/analytics/lifecycleEvents.js +72 -0
  6. package/dist/analytics/lifecycleEvents.js.map +1 -0
  7. package/dist/api/changes/applyOption.d.ts +41 -0
  8. package/dist/api/changes/applyOption.d.ts.map +1 -0
  9. package/dist/api/changes/applyOption.js +76 -0
  10. package/dist/api/changes/applyOption.js.map +1 -0
  11. package/dist/api/changes/classifyChanges.d.ts +9 -0
  12. package/dist/api/changes/classifyChanges.d.ts.map +1 -0
  13. package/dist/api/changes/classifyChanges.js +2 -0
  14. package/dist/api/changes/classifyChanges.js.map +1 -0
  15. package/dist/api/changes/index.d.ts +3 -0
  16. package/dist/api/changes/index.d.ts.map +1 -0
  17. package/dist/api/changes/index.js +3 -0
  18. package/dist/api/changes/index.js.map +1 -0
  19. package/dist/api/client.d.ts +48 -0
  20. package/dist/api/client.d.ts.map +1 -0
  21. package/dist/api/client.js +91 -0
  22. package/dist/api/client.js.map +1 -0
  23. package/dist/api/health.d.ts +4 -0
  24. package/dist/api/health.d.ts.map +1 -0
  25. package/dist/api/health.js +6 -0
  26. package/dist/api/health.js.map +1 -0
  27. package/dist/api/index.d.ts +24 -0
  28. package/dist/api/index.d.ts.map +1 -0
  29. package/dist/api/index.js +23 -0
  30. package/dist/api/index.js.map +1 -0
  31. package/dist/api/me.d.ts +37 -0
  32. package/dist/api/me.d.ts.map +1 -0
  33. package/dist/api/me.js +6 -0
  34. package/dist/api/me.js.map +1 -0
  35. package/dist/api/order.d.ts +33 -0
  36. package/dist/api/order.d.ts.map +1 -0
  37. package/dist/api/order.js +33 -0
  38. package/dist/api/order.js.map +1 -0
  39. package/dist/api/orders.d.ts +1047 -0
  40. package/dist/api/orders.d.ts.map +1 -0
  41. package/dist/api/orders.js +7 -0
  42. package/dist/api/orders.js.map +1 -0
  43. package/dist/api/patient.d.ts +36 -0
  44. package/dist/api/patient.d.ts.map +1 -0
  45. package/dist/api/patient.js +33 -0
  46. package/dist/api/patient.js.map +1 -0
  47. package/dist/api/prescription.d.ts +37 -0
  48. package/dist/api/prescription.d.ts.map +1 -0
  49. package/dist/api/prescription.js +39 -0
  50. package/dist/api/prescription.js.map +1 -0
  51. package/dist/api/results.d.ts +30 -0
  52. package/dist/api/results.d.ts.map +1 -0
  53. package/dist/api/results.js +26 -0
  54. package/dist/api/results.js.map +1 -0
  55. package/dist/gql/gql.d.ts +29 -0
  56. package/dist/gql/gql.d.ts.map +1 -0
  57. package/dist/gql/gql.js +15 -0
  58. package/dist/gql/gql.js.map +1 -0
  59. package/dist/gql/graphql.d.ts +18618 -0
  60. package/dist/gql/graphql.d.ts.map +1 -0
  61. package/dist/gql/graphql.js +6579 -0
  62. package/dist/gql/graphql.js.map +1 -0
  63. package/dist/gql/index.d.ts +2 -0
  64. package/dist/gql/index.d.ts.map +1 -0
  65. package/dist/gql/index.js +3 -0
  66. package/dist/gql/index.js.map +1 -0
  67. package/dist/index.d.ts +15 -0
  68. package/dist/index.d.ts.map +1 -0
  69. package/dist/index.js +15 -0
  70. package/dist/index.js.map +1 -0
  71. package/dist/meta/version.d.ts +2 -0
  72. package/dist/meta/version.d.ts.map +1 -0
  73. package/dist/meta/version.js +2 -0
  74. package/dist/meta/version.js.map +1 -0
  75. package/dist/photon/analytics.d.ts +39 -0
  76. package/dist/photon/analytics.d.ts.map +1 -0
  77. package/dist/photon/analytics.js +91 -0
  78. package/dist/photon/analytics.js.map +1 -0
  79. package/dist/photon/auth.d.ts +52 -0
  80. package/dist/photon/auth.d.ts.map +1 -0
  81. package/dist/photon/auth.js +30 -0
  82. package/dist/photon/auth.js.map +1 -0
  83. package/dist/photon/choices.d.ts +44 -0
  84. package/dist/photon/choices.d.ts.map +1 -0
  85. package/dist/photon/choices.js +58 -0
  86. package/dist/photon/choices.js.map +1 -0
  87. package/dist/photon/context.d.ts +29 -0
  88. package/dist/photon/context.d.ts.map +1 -0
  89. package/dist/photon/context.js +2 -0
  90. package/dist/photon/context.js.map +1 -0
  91. package/dist/photon/environments.d.ts +27 -0
  92. package/dist/photon/environments.d.ts.map +1 -0
  93. package/dist/photon/environments.js +27 -0
  94. package/dist/photon/environments.js.map +1 -0
  95. package/dist/photon/errors.d.ts +26 -0
  96. package/dist/photon/errors.d.ts.map +1 -0
  97. package/dist/photon/errors.js +42 -0
  98. package/dist/photon/errors.js.map +1 -0
  99. package/dist/photon/index.d.ts +26 -0
  100. package/dist/photon/index.d.ts.map +1 -0
  101. package/dist/photon/index.js +12 -0
  102. package/dist/photon/index.js.map +1 -0
  103. package/dist/photon/inputs.d.ts +7 -0
  104. package/dist/photon/inputs.d.ts.map +1 -0
  105. package/dist/photon/inputs.js +25 -0
  106. package/dist/photon/inputs.js.map +1 -0
  107. package/dist/photon/links.d.ts +68 -0
  108. package/dist/photon/links.d.ts.map +1 -0
  109. package/dist/photon/links.js +187 -0
  110. package/dist/photon/links.js.map +1 -0
  111. package/dist/photon/live.d.ts +62 -0
  112. package/dist/photon/live.d.ts.map +1 -0
  113. package/dist/photon/live.js +107 -0
  114. package/dist/photon/live.js.map +1 -0
  115. package/dist/photon/machine.d.ts +28 -0
  116. package/dist/photon/machine.d.ts.map +1 -0
  117. package/dist/photon/machine.js +53 -0
  118. package/dist/photon/machine.js.map +1 -0
  119. package/dist/photon/map.d.ts +14 -0
  120. package/dist/photon/map.d.ts.map +1 -0
  121. package/dist/photon/map.js +311 -0
  122. package/dist/photon/map.js.map +1 -0
  123. package/dist/photon/order.d.ts +168 -0
  124. package/dist/photon/order.d.ts.map +1 -0
  125. package/dist/photon/order.js +558 -0
  126. package/dist/photon/order.js.map +1 -0
  127. package/dist/photon/orders.d.ts +5 -0
  128. package/dist/photon/orders.d.ts.map +1 -0
  129. package/dist/photon/orders.js +39 -0
  130. package/dist/photon/orders.js.map +1 -0
  131. package/dist/photon/patient.d.ts +80 -0
  132. package/dist/photon/patient.d.ts.map +1 -0
  133. package/dist/photon/patient.js +347 -0
  134. package/dist/photon/patient.js.map +1 -0
  135. package/dist/photon/photon.d.ts +188 -0
  136. package/dist/photon/photon.d.ts.map +1 -0
  137. package/dist/photon/photon.js +395 -0
  138. package/dist/photon/photon.js.map +1 -0
  139. package/dist/photon/prescription.d.ts +145 -0
  140. package/dist/photon/prescription.d.ts.map +1 -0
  141. package/dist/photon/prescription.js +418 -0
  142. package/dist/photon/prescription.js.map +1 -0
  143. package/dist/photon/session.d.ts +89 -0
  144. package/dist/photon/session.d.ts.map +1 -0
  145. package/dist/photon/session.js +352 -0
  146. package/dist/photon/session.js.map +1 -0
  147. package/dist/photon/types.d.ts +643 -0
  148. package/dist/photon/types.d.ts.map +1 -0
  149. package/dist/photon/types.js +7 -0
  150. package/dist/photon/types.js.map +1 -0
  151. package/dist/test-utils/msw.d.ts +23 -0
  152. package/dist/test-utils/msw.d.ts.map +1 -0
  153. package/dist/test-utils/msw.js +51 -0
  154. package/dist/test-utils/msw.js.map +1 -0
  155. package/dist/testing/fakeNetworkApiClient.d.ts +39 -0
  156. package/dist/testing/fakeNetworkApiClient.d.ts.map +1 -0
  157. package/dist/testing/fakeNetworkApiClient.js +56 -0
  158. package/dist/testing/fakeNetworkApiClient.js.map +1 -0
  159. package/dist/testing/fixtures.d.ts +1098 -0
  160. package/dist/testing/fixtures.d.ts.map +1 -0
  161. package/dist/testing/fixtures.js +200 -0
  162. package/dist/testing/fixtures.js.map +1 -0
  163. package/dist/testing.d.ts +11 -0
  164. package/dist/testing.d.ts.map +1 -0
  165. package/dist/testing.js +10 -0
  166. package/dist/testing.js.map +1 -0
  167. package/package.json +67 -4
  168. package/src/analytics/lifecycleEvents.test.ts +417 -0
  169. package/src/analytics/lifecycleEvents.ts +155 -0
  170. package/src/api/changes/applyOption.ts +103 -0
  171. package/src/api/changes/classifyChanges.ts +10 -0
  172. package/src/api/changes/index.ts +2 -0
  173. package/src/api/client.ts +149 -0
  174. package/src/api/health.ts +7 -0
  175. package/src/api/index.ts +24 -0
  176. package/src/api/me.ts +7 -0
  177. package/src/api/order.ts +64 -0
  178. package/src/api/orders.ts +8 -0
  179. package/src/api/patient.ts +67 -0
  180. package/src/api/prescription.ts +86 -0
  181. package/src/api/results.ts +45 -0
  182. package/src/gql/gql.ts +68 -0
  183. package/src/gql/graphql.ts +9027 -0
  184. package/src/gql/index.ts +2 -0
  185. package/src/index.ts +14 -0
  186. package/src/meta/version.test.ts +10 -0
  187. package/src/meta/version.ts +1 -0
  188. package/src/operations/fragments.graphql +497 -0
  189. package/src/operations/health.graphql +4 -0
  190. package/src/operations/me.graphql +38 -0
  191. package/src/operations/order.graphql +42 -0
  192. package/src/operations/orders.graphql +35 -0
  193. package/src/operations/patient.graphql +62 -0
  194. package/src/operations/prescription.graphql +90 -0
  195. package/src/photon/analytics.ts +129 -0
  196. package/src/photon/auth.ts +69 -0
  197. package/src/photon/choices.ts +79 -0
  198. package/src/photon/context.ts +30 -0
  199. package/src/photon/environments.ts +49 -0
  200. package/src/photon/errors.ts +56 -0
  201. package/src/photon/index.ts +49 -0
  202. package/src/photon/inputs.ts +24 -0
  203. package/src/photon/links.ts +197 -0
  204. package/src/photon/live.ts +135 -0
  205. package/src/photon/machine.ts +90 -0
  206. package/src/photon/map.ts +371 -0
  207. package/src/photon/order.test.ts +142 -0
  208. package/src/photon/order.ts +661 -0
  209. package/src/photon/orders.ts +42 -0
  210. package/src/photon/patient.ts +386 -0
  211. package/src/photon/photon.ts +646 -0
  212. package/src/photon/prescription.ts +506 -0
  213. package/src/photon/session.ts +454 -0
  214. package/src/photon/types.ts +583 -0
  215. package/src/test-utils/msw.ts +72 -0
  216. package/src/testing/fakeNetworkApiClient.ts +56 -0
  217. package/src/testing/fixtures.ts +233 -0
  218. package/src/testing.ts +25 -0
@@ -0,0 +1,417 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { fakeNetworkApiClient, photonOver } from "../testing.ts";
3
+ import type { Analytics } from "../photon/analytics.ts";
4
+ import { environmentUrls } from "../photon/environments.ts";
5
+ import type { OrderRecord, Pharmacy, PatientRecord, PrescriptionRecord, ScreeningAlert } from "../photon/types.ts";
6
+
7
+ const typedByPrescriber = {
8
+ firstName: "Paige",
9
+ middleName: "Quincy",
10
+ lastName: "Turner",
11
+ dateOfBirth: "1984-02-29",
12
+ gender: "nonbinary",
13
+ email: "paige.turner@example.com",
14
+ phone: "+15555550123",
15
+ street1: "12 Sycamore Lane",
16
+ street2: "Apt 4B",
17
+ city: "Springfield",
18
+ state: "WY",
19
+ postalCode: "97477",
20
+ instructions: "Take one tablet by mouth nightly",
21
+ notes: "Patient prefers evening doses",
22
+ alertDescription: "Penicillin allergy reported",
23
+ pharmacyName: "Corner Drug",
24
+ };
25
+
26
+ const fullPatient = (): PatientRecord => ({
27
+ id: "pat_1",
28
+ demographic: {
29
+ name: {
30
+ first: typedByPrescriber.firstName,
31
+ middle: typedByPrescriber.middleName,
32
+ last: typedByPrescriber.lastName,
33
+ },
34
+ dateOfBirth: typedByPrescriber.dateOfBirth,
35
+ sex: "FEMALE",
36
+ gender: typedByPrescriber.gender,
37
+ },
38
+ contact: {
39
+ email: typedByPrescriber.email,
40
+ phone: typedByPrescriber.phone,
41
+ address: {
42
+ street1: typedByPrescriber.street1,
43
+ street2: typedByPrescriber.street2,
44
+ city: typedByPrescriber.city,
45
+ state: typedByPrescriber.state,
46
+ postalCode: typedByPrescriber.postalCode,
47
+ },
48
+ },
49
+ benefits: null,
50
+ preferredPharmacy: pharmacy(),
51
+ clinical: null,
52
+ });
53
+
54
+ const barePatient = (): PatientRecord => ({
55
+ id: "pat_2",
56
+ demographic: {
57
+ name: { first: typedByPrescriber.firstName, middle: null, last: typedByPrescriber.lastName },
58
+ dateOfBirth: typedByPrescriber.dateOfBirth,
59
+ sex: null,
60
+ gender: null,
61
+ },
62
+ contact: { email: null, phone: "", address: null },
63
+ benefits: null,
64
+ preferredPharmacy: null,
65
+ clinical: null,
66
+ });
67
+
68
+ function pharmacy(fulfillmentType: Pharmacy["fulfillmentType"] = ["PICK_UP"]): Pharmacy {
69
+ return {
70
+ id: "phr_1",
71
+ name: typedByPrescriber.pharmacyName,
72
+ logo: null,
73
+ phone: null,
74
+ hours: null,
75
+ isOpen: null,
76
+ nextEvents: null,
77
+ address: null,
78
+ latitude: null,
79
+ longitude: null,
80
+ fulfillmentType,
81
+ offers: [],
82
+ };
83
+ }
84
+
85
+ const alert = (): ScreeningAlert => ({
86
+ severity: "MAJOR",
87
+ type: "ALLERGEN",
88
+ description: typedByPrescriber.alertDescription,
89
+ involvedEntities: [{ id: "med_1", name: "Amoxicillin" }],
90
+ });
91
+
92
+ const prescription = (id = "rx_1", overrides: Partial<PrescriptionRecord> = {}): PrescriptionRecord => ({
93
+ id,
94
+ prescriber: { id: "usr_1", name: { first: "Ada", middle: null, last: "Lovelace" } },
95
+ fulfillment: null,
96
+ templateId: null,
97
+ patient: { id: "pat_1" },
98
+ treatment: {
99
+ id: "med_1",
100
+ name: "Lisinopril",
101
+ prescribableName: "Lisinopril Oral Tablet 10 MG",
102
+ rxNormId: "314076",
103
+ ndc: null,
104
+ upc: null,
105
+ entityKind: "MEDICATION",
106
+ brandName: "Lisinopril",
107
+ genericName: "Lisinopril",
108
+ form: "Tablet",
109
+ route: "Oral",
110
+ strength: "10 MG",
111
+ medicationType: "RX",
112
+ schedule: null,
113
+ templates: null,
114
+ },
115
+ instructions: typedByPrescriber.instructions,
116
+ dispense: { quantity: 30, unit: "Tablet", daysSupply: 30, refillsAllowed: 0, dispenseAsWritten: false },
117
+ clinical: { diagnoses: [], notes: typedByPrescriber.notes },
118
+ screeningAlerts: [alert()],
119
+ signing: { state: "SIGNED", contentHash: "hash_1", message: null, signedAt: "2026-11-06T12:00:00.000Z" },
120
+ ...overrides,
121
+ });
122
+
123
+ const order = (overrides: Partial<OrderRecord> = {}): OrderRecord => ({
124
+ id: "ord_1",
125
+ state: "SUBMITTED",
126
+ organization: null,
127
+ patient: fullPatient(),
128
+ prescriptions: [prescription("rx_1"), prescription("rx_2")],
129
+ screeningAlerts: [alert()],
130
+ pharmacy: null,
131
+ offers: { atPharmacy: null },
132
+ fulfillment: null,
133
+ ...overrides,
134
+ });
135
+
136
+ const jwt = (claims: Record<string, unknown>) => `x.${btoa(JSON.stringify(claims)).replace(/=+$/, "")}.y`;
137
+
138
+ const analyticsAsPrescriber = (): Analytics => {
139
+ const network = fakeNetworkApiClient({
140
+ Me: () => ({
141
+ me: {
142
+ __typename: "User",
143
+ id: "usr_1",
144
+ name: { first: "Ada", last: "Lovelace" },
145
+ organization: { __typename: "Organization", id: "org_1", name: "Acme Clinic" },
146
+ permissions: [],
147
+ },
148
+ }),
149
+ });
150
+ return photonOver(network.client, environmentUrls("boson"), {
151
+ analytics: {
152
+ url: "https://analytics-api.boson.health",
153
+ token: async () => jwt({ sub: "auth0|1", org_id: "org_1" }),
154
+ clientName: "photon-mcp",
155
+ },
156
+ }).analytics!;
157
+ };
158
+
159
+ interface SentEvent {
160
+ event: string;
161
+ properties: Record<string, unknown>;
162
+ }
163
+
164
+ let fetchSpy: ReturnType<typeof vi.fn>;
165
+ const sentEvents = (): SentEvent[] =>
166
+ fetchSpy.mock.calls.map(([, init]) => JSON.parse((init as RequestInit).body as string) as SentEvent);
167
+ const rawBodiesSent = () => fetchSpy.mock.calls.map(([, init]) => (init as RequestInit).body as string).join("\n");
168
+
169
+ const propertiesSentBy = async (send: (analytics: Analytics) => Promise<void>) => {
170
+ await send(analyticsAsPrescriber());
171
+ return sentEvents().at(-1)!.properties;
172
+ };
173
+
174
+ const commonProperties = ["providerId", "orgId", "environment", "clientName", "clientVersion", "timestamp"];
175
+ const ownProperties = (properties: Record<string, unknown>) =>
176
+ Object.fromEntries(Object.entries(properties).filter(([name]) => !commonProperties.includes(name)));
177
+
178
+ const sendEveryLifecycleEvent = async (analytics: Analytics) => {
179
+ await analytics.patientCreated(fullPatient());
180
+ await analytics.patientUpdated(fullPatient());
181
+ await analytics.draftPrescriptionAdded(prescription(), "form");
182
+ await analytics.draftPrescriptionDeleted("rx_1");
183
+ await analytics.screeningAlertAcknowledged([alert()], "Send");
184
+ await analytics.screeningAlertCanceled([alert()], "Cancel");
185
+ await analytics.prescriptionSigned(prescription());
186
+ await analytics.orderSent(order());
187
+ };
188
+
189
+ beforeEach(() => {
190
+ fetchSpy = vi.fn(async () => new Response(JSON.stringify({ status: "ok" })));
191
+ vi.stubGlobal("fetch", fetchSpy);
192
+ });
193
+ afterEach(() => vi.unstubAllGlobals());
194
+
195
+ describe("ph.analytics lifecycle events use <photon-prescribe-workflow>'s names, so Mixpanel reports keep working", () => {
196
+ it("sends each one under its elements name, none dropped by the guards", async () => {
197
+ await sendEveryLifecycleEvent(analyticsAsPrescriber());
198
+ expect(sentEvents().map(({ event }) => event)).toEqual([
199
+ "Patient Created",
200
+ "Patient Updated",
201
+ "Draft Prescription Added",
202
+ "Draft Prescription Deleted",
203
+ "Screening Alert Acknowledged",
204
+ "Screening Alert Canceled",
205
+ "Prescription Signed",
206
+ "Order Sent",
207
+ ]);
208
+ });
209
+
210
+ it("every lifecycle event is a ctaClicked, as in elements", async () => {
211
+ await sendEveryLifecycleEvent(analyticsAsPrescriber());
212
+ expect(new Set(sentEvents().map(({ properties }) => properties.category))).toEqual(new Set(["ctaClicked"]));
213
+ });
214
+
215
+ it("carries the prescriber, organization and environment like any tracked event", async () => {
216
+ expect(await propertiesSentBy((analytics) => analytics.draftPrescriptionDeleted("rx_1"))).toMatchObject({
217
+ providerId: "usr_1",
218
+ orgId: "org_1",
219
+ environment: "boson",
220
+ clientName: "photon-mcp",
221
+ });
222
+ });
223
+ });
224
+
225
+ describe("patientCreated and patientUpdated", () => {
226
+ it("send the patient's id and which of the patient form's fields are filled, all filled", async () => {
227
+ expect(ownProperties(await propertiesSentBy((analytics) => analytics.patientCreated(fullPatient())))).toEqual({
228
+ category: "ctaClicked",
229
+ patientId: "pat_1",
230
+ snap_first_name: true,
231
+ snap_last_name: true,
232
+ snap_date_of_birth: true,
233
+ snap_phone: true,
234
+ snap_sex: true,
235
+ snap_gender: true,
236
+ snap_email: true,
237
+ snap_address_street1: true,
238
+ snap_address_street2: true,
239
+ snap_address_city: true,
240
+ snap_address_state: true,
241
+ snap_address_zip: true,
242
+ snap_preferred_pharmacy: true,
243
+ });
244
+ });
245
+
246
+ it("mark a field unfilled when the record has it null, empty or missing", async () => {
247
+ expect(ownProperties(await propertiesSentBy((analytics) => analytics.patientUpdated(barePatient())))).toEqual({
248
+ category: "ctaClicked",
249
+ patientId: "pat_2",
250
+ snap_first_name: true,
251
+ snap_last_name: true,
252
+ snap_date_of_birth: true,
253
+ snap_phone: false,
254
+ snap_sex: false,
255
+ snap_gender: false,
256
+ snap_email: false,
257
+ snap_address_street1: false,
258
+ snap_address_street2: false,
259
+ snap_address_city: false,
260
+ snap_address_state: false,
261
+ snap_address_zip: false,
262
+ snap_preferred_pharmacy: false,
263
+ });
264
+ });
265
+ });
266
+
267
+ describe("draftPrescriptionAdded", () => {
268
+ it("sends the line's id, where it came from, and which prescription fields are filled", async () => {
269
+ const sent = await propertiesSentBy((analytics) =>
270
+ analytics.draftPrescriptionAdded(prescription(), "template_prefill"),
271
+ );
272
+ expect(ownProperties(sent)).toEqual({
273
+ category: "ctaClicked",
274
+ prescriptionId: "rx_1",
275
+ draftPrescriptionSource: "template_prefill",
276
+ snap_treatment: true,
277
+ snap_dispense_quantity: true,
278
+ snap_dispense_unit: true,
279
+ snap_days_supply: true,
280
+ snap_refills: true,
281
+ snap_instructions: true,
282
+ snap_notes: true,
283
+ });
284
+ });
285
+
286
+ it("marks dispense fields and notes unfilled on a line that has none yet", async () => {
287
+ const sparse = prescription("rx_3", { dispense: null, instructions: null, clinical: null });
288
+ const sent = await propertiesSentBy((analytics) =>
289
+ analytics.draftPrescriptionAdded(sparse, "prescription_id_prefill"),
290
+ );
291
+ expect(sent).toMatchObject({
292
+ prescriptionId: "rx_3",
293
+ draftPrescriptionSource: "prescription_id_prefill",
294
+ snap_treatment: true,
295
+ snap_dispense_quantity: false,
296
+ snap_dispense_unit: false,
297
+ snap_days_supply: false,
298
+ snap_refills: false,
299
+ snap_instructions: false,
300
+ snap_notes: false,
301
+ });
302
+ });
303
+ });
304
+
305
+ describe("draftPrescriptionDeleted and prescriptionSigned", () => {
306
+ it("send only the prescription's id", async () => {
307
+ expect(ownProperties(await propertiesSentBy((analytics) => analytics.draftPrescriptionDeleted("rx_9")))).toEqual({
308
+ category: "ctaClicked",
309
+ prescriptionId: "rx_9",
310
+ });
311
+ expect(
312
+ ownProperties(await propertiesSentBy((analytics) => analytics.prescriptionSigned(prescription("rx_4")))),
313
+ ).toEqual({ category: "ctaClicked", prescriptionId: "rx_4" });
314
+ });
315
+ });
316
+
317
+ describe("screeningAlertAcknowledged and screeningAlertCanceled", () => {
318
+ it("count the alerts and send the button the prescriber pressed", async () => {
319
+ expect(
320
+ ownProperties(
321
+ await propertiesSentBy((analytics) => analytics.screeningAlertAcknowledged([alert(), alert()], "Send")),
322
+ ),
323
+ ).toEqual({ category: "ctaClicked", screeningAlertCount: 2, buttonText: "Send" });
324
+ expect(
325
+ ownProperties(await propertiesSentBy((analytics) => analytics.screeningAlertCanceled([alert()], "Cancel"))),
326
+ ).toEqual({ category: "ctaClicked", screeningAlertCount: 1, buttonText: "Cancel" });
327
+ });
328
+ });
329
+
330
+ describe("orderSent", () => {
331
+ it("sends the order's id, its prescriptions, and SEND_TO_PATIENT when the patient chooses the pharmacy", async () => {
332
+ expect(ownProperties(await propertiesSentBy((analytics) => analytics.orderSent(order())))).toEqual({
333
+ category: "ctaClicked",
334
+ orderId: "ord_1",
335
+ prescriptionCount: 2,
336
+ prescriptionIds: ["rx_1", "rx_2"],
337
+ fulfillmentType: "SEND_TO_PATIENT",
338
+ });
339
+ });
340
+
341
+ it.each([
342
+ ["a pick-up pharmacy", pharmacy(["PICK_UP"]), "PICK_UP"],
343
+ ["a mail-order pharmacy", pharmacy(["MAIL_ORDER"]), "MAIL_ORDER"],
344
+ ["a pharmacy that does both", pharmacy(["PICK_UP", "MAIL_ORDER"]), null],
345
+ ["a pharmacy that doesn't say", pharmacy(null), null],
346
+ ])("sends the fulfillment type of %s", async (_why, chosen, expectedType) => {
347
+ const sent = await propertiesSentBy((analytics) => analytics.orderSent(order({ pharmacy: chosen })));
348
+ expect(sent.fulfillmentType).toBe(expectedType);
349
+ });
350
+ });
351
+
352
+ describe("the caller's own properties", () => {
353
+ it("ride along, as a surface's sessionId and integration do", async () => {
354
+ const sent = await propertiesSentBy((analytics) =>
355
+ analytics.orderSent(order(), { sessionId: "ses_1", integration: "react" }),
356
+ );
357
+ expect(sent).toMatchObject({ sessionId: "ses_1", integration: "react", orderId: "ord_1" });
358
+ });
359
+
360
+ it("never replace what the record says", async () => {
361
+ const sent = await propertiesSentBy((analytics) =>
362
+ analytics.orderSent(order(), { orderId: "ord_forged", prescriptionCount: 99, category: "fieldInteraction" }),
363
+ );
364
+ expect(sent).toMatchObject({ orderId: "ord_1", prescriptionCount: 2, category: "ctaClicked" });
365
+ });
366
+ });
367
+
368
+ describe("never PHI", () => {
369
+ it("no value a prescriber typed or a record holds as free text appears in any lifecycle event", async () => {
370
+ await sendEveryLifecycleEvent(analyticsAsPrescriber());
371
+ for (const value of Object.values(typedByPrescriber)) expect(rawBodiesSent()).not.toContain(value);
372
+ });
373
+ });
374
+
375
+ describe("each method takes only the fields it reads, so a surface's own record types fit", () => {
376
+ it("sends from objects holding nothing but those fields", async () => {
377
+ const analytics = analyticsAsPrescriber();
378
+ await analytics.patientCreated({ id: "pat_9", demographic: null, contact: null, preferredPharmacy: null });
379
+ await analytics.draftPrescriptionAdded(
380
+ {
381
+ id: "rx_9",
382
+ treatment: prescription().treatment,
383
+ dispense: null,
384
+ instructions: null,
385
+ clinical: { notes: null },
386
+ },
387
+ "form",
388
+ );
389
+ await analytics.prescriptionSigned({ id: "rx_9" });
390
+ await analytics.orderSent({
391
+ id: "ord_9",
392
+ prescriptions: [{ id: "rx_9" }],
393
+ pharmacy: { fulfillmentType: ["MAIL_ORDER"] },
394
+ });
395
+ expect(sentEvents().map(({ event, properties }) => [event, ownProperties(properties)])).toEqual([
396
+ [
397
+ "Patient Created",
398
+ expect.objectContaining({ patientId: "pat_9", snap_first_name: false, snap_preferred_pharmacy: false }),
399
+ ],
400
+ [
401
+ "Draft Prescription Added",
402
+ expect.objectContaining({ prescriptionId: "rx_9", snap_treatment: true, snap_notes: false }),
403
+ ],
404
+ ["Prescription Signed", { category: "ctaClicked", prescriptionId: "rx_9" }],
405
+ [
406
+ "Order Sent",
407
+ {
408
+ category: "ctaClicked",
409
+ orderId: "ord_9",
410
+ prescriptionCount: 1,
411
+ prescriptionIds: ["rx_9"],
412
+ fulfillmentType: "MAIL_ORDER",
413
+ },
414
+ ],
415
+ ]);
416
+ });
417
+ });
@@ -0,0 +1,155 @@
1
+ import type { AnalyticsProperties } from "../photon/analytics.ts";
2
+ import type { OrderRecord, PatientRecord, PrescriptionRecord, ScreeningAlert } from "../photon/types.ts";
3
+
4
+ export type LifecycleEventName =
5
+ | "Patient Created"
6
+ | "Patient Updated"
7
+ | "Draft Prescription Added"
8
+ | "Draft Prescription Deleted"
9
+ | "Screening Alert Acknowledged"
10
+ | "Screening Alert Canceled"
11
+ | "Prescription Signed"
12
+ | "Order Sent";
13
+
14
+ export type DraftPrescriptionSource = "form" | "template_prefill" | "prescription_id_prefill";
15
+
16
+ export type PatientForLifecycleAnalytics = Pick<PatientRecord, "id" | "demographic" | "contact" | "preferredPharmacy">;
17
+
18
+ export type DraftPrescriptionForLifecycleAnalytics = Pick<
19
+ PrescriptionRecord,
20
+ "id" | "treatment" | "dispense" | "instructions"
21
+ > & {
22
+ clinical: { notes: string | null } | null;
23
+ };
24
+
25
+ export type PrescriptionForLifecycleAnalytics = Pick<PrescriptionRecord, "id">;
26
+
27
+ export type OrderForLifecycleAnalytics = Pick<OrderRecord, "id"> & {
28
+ prescriptions: readonly PrescriptionForLifecycleAnalytics[];
29
+ pharmacy: Pick<NonNullable<OrderRecord["pharmacy"]>, "fulfillmentType"> | null;
30
+ };
31
+
32
+ export interface LifecycleAnalytics {
33
+ patientCreated(patient: PatientForLifecycleAnalytics, properties?: AnalyticsProperties): Promise<void>;
34
+ patientUpdated(patient: PatientForLifecycleAnalytics, properties?: AnalyticsProperties): Promise<void>;
35
+ draftPrescriptionAdded(
36
+ prescription: DraftPrescriptionForLifecycleAnalytics,
37
+ source: DraftPrescriptionSource,
38
+ properties?: AnalyticsProperties,
39
+ ): Promise<void>;
40
+ draftPrescriptionDeleted(prescriptionId: string, properties?: AnalyticsProperties): Promise<void>;
41
+ screeningAlertAcknowledged(
42
+ alerts: readonly ScreeningAlert[],
43
+ buttonText: string,
44
+ properties?: AnalyticsProperties,
45
+ ): Promise<void>;
46
+ screeningAlertCanceled(
47
+ alerts: readonly ScreeningAlert[],
48
+ buttonText: string,
49
+ properties?: AnalyticsProperties,
50
+ ): Promise<void>;
51
+ prescriptionSigned(prescription: PrescriptionForLifecycleAnalytics, properties?: AnalyticsProperties): Promise<void>;
52
+ orderSent(order: OrderForLifecycleAnalytics, properties?: AnalyticsProperties): Promise<void>;
53
+ }
54
+
55
+ type Track = (event: string, properties?: AnalyticsProperties) => Promise<void>;
56
+
57
+ const SEND_TO_PATIENT = "SEND_TO_PATIENT";
58
+
59
+ export function lifecycleAnalyticsSentWith(track: Track): LifecycleAnalytics {
60
+ const sendCtaClicked = (
61
+ event: LifecycleEventName,
62
+ derivedProperties: AnalyticsProperties,
63
+ callerProperties: AnalyticsProperties = {},
64
+ ) => track(event, { ...callerProperties, category: "ctaClicked", ...derivedProperties });
65
+
66
+ return {
67
+ patientCreated: (patient, properties) => sendCtaClicked("Patient Created", patientProperties(patient), properties),
68
+ patientUpdated: (patient, properties) => sendCtaClicked("Patient Updated", patientProperties(patient), properties),
69
+ draftPrescriptionAdded: (prescription, source, properties) =>
70
+ sendCtaClicked(
71
+ "Draft Prescription Added",
72
+ {
73
+ prescriptionId: prescription.id,
74
+ draftPrescriptionSource: source,
75
+ ...prescriptionFormSnapshot(prescription),
76
+ },
77
+ properties,
78
+ ),
79
+ draftPrescriptionDeleted: (prescriptionId, properties) =>
80
+ sendCtaClicked("Draft Prescription Deleted", { prescriptionId }, properties),
81
+ screeningAlertAcknowledged: (alerts, buttonText, properties) =>
82
+ sendCtaClicked("Screening Alert Acknowledged", { screeningAlertCount: alerts.length, buttonText }, properties),
83
+ screeningAlertCanceled: (alerts, buttonText, properties) =>
84
+ sendCtaClicked("Screening Alert Canceled", { screeningAlertCount: alerts.length, buttonText }, properties),
85
+ prescriptionSigned: (prescription, properties) =>
86
+ sendCtaClicked("Prescription Signed", { prescriptionId: prescription.id }, properties),
87
+ orderSent: (order, properties) =>
88
+ sendCtaClicked(
89
+ "Order Sent",
90
+ {
91
+ orderId: order.id,
92
+ prescriptionCount: order.prescriptions.length,
93
+ prescriptionIds: order.prescriptions.map((prescription) => prescription.id),
94
+ fulfillmentType: fulfillmentTypeOf(order),
95
+ },
96
+ properties,
97
+ ),
98
+ };
99
+ }
100
+
101
+ function patientProperties(patient: PatientForLifecycleAnalytics): AnalyticsProperties {
102
+ return { patientId: patient.id, ...patientFormSnapshot(patient) };
103
+ }
104
+
105
+ function fulfillmentTypeOf(order: OrderForLifecycleAnalytics): string | null {
106
+ if (!order.pharmacy) return SEND_TO_PATIENT;
107
+ const offeredTypes = order.pharmacy.fulfillmentType ?? [];
108
+ return offeredTypes.length === 1 ? offeredTypes[0]! : null;
109
+ }
110
+
111
+ function patientFormSnapshot(patient: PatientForLifecycleAnalytics): AnalyticsProperties {
112
+ const { demographic, contact, preferredPharmacy } = patient;
113
+ return completedFieldSnapshot({
114
+ firstName: demographic?.name.first,
115
+ lastName: demographic?.name.last,
116
+ dateOfBirth: demographic?.dateOfBirth,
117
+ phone: contact?.phone,
118
+ sex: demographic?.sex,
119
+ gender: demographic?.gender,
120
+ email: contact?.email,
121
+ address_street1: contact?.address?.street1,
122
+ address_street2: contact?.address?.street2,
123
+ address_city: contact?.address?.city,
124
+ address_state: contact?.address?.state,
125
+ address_zip: contact?.address?.postalCode,
126
+ preferredPharmacy,
127
+ });
128
+ }
129
+
130
+ function prescriptionFormSnapshot(prescription: DraftPrescriptionForLifecycleAnalytics): AnalyticsProperties {
131
+ const { treatment, dispense, instructions, clinical } = prescription;
132
+ return completedFieldSnapshot({
133
+ treatment,
134
+ dispenseQuantity: dispense?.quantity,
135
+ dispenseUnit: dispense?.unit,
136
+ daysSupply: dispense?.daysSupply,
137
+ refills: dispense?.refillsAllowed,
138
+ instructions,
139
+ notes: clinical?.notes,
140
+ });
141
+ }
142
+
143
+ function completedFieldSnapshot(valuesByFieldName: Record<string, unknown>): AnalyticsProperties {
144
+ return Object.fromEntries(
145
+ Object.entries(valuesByFieldName).map(([fieldName, value]) => [snapshotPropertyName(fieldName), isFilled(value)]),
146
+ );
147
+ }
148
+
149
+ function snapshotPropertyName(fieldName: string): string {
150
+ return `snap_${fieldName.replace(/([A-Z])/g, "_$1").toLowerCase()}`;
151
+ }
152
+
153
+ function isFilled(value: unknown): boolean {
154
+ return value !== undefined && value !== null && value !== "" && value !== false;
155
+ }
@@ -0,0 +1,103 @@
1
+ import type { ChoiceFieldsFragment } from "../../gql/graphql.ts";
2
+
3
+ /**
4
+ * Apply a Choice to the input you sent, producing the input to send next.
5
+ *
6
+ * A Change's options are structured next actions: `argument` is a dotted path
7
+ * into the operation's input (numeric segments index arrays) and `value` is
8
+ * what to set there. Picking "Amoxicillin 500 MG Oral Capsule" from a
9
+ * DISAMBIGUATION change is just: applyOption(input, option) → re-send.
10
+ *
11
+ * Options with a null `argument` mean "call a different operation" — they
12
+ * can't be applied inline; check `isInlineOption` first.
13
+ *
14
+ * Pure and immutable: the original input is never modified.
15
+ */
16
+
17
+ type ApplicableOption = Pick<ChoiceFieldsFragment, "argument" | "value" | "operation"> & {
18
+ /** How the option is shown ("Lisinopril Oral Tablet 10 MG"). */
19
+ displayName?: string;
20
+ };
21
+
22
+ export const isInlineOption = (option: ApplicableOption): option is ApplicableOption & { argument: string } =>
23
+ typeof option.argument === "string" && option.argument.length > 0;
24
+
25
+ /**
26
+ * `value` arrives as a string. Structured values (objects, arrays, booleans,
27
+ * null) are JSON-encoded; anything else — including numeric-looking ids — is
28
+ * kept as a string so an id like "0123" is never turned into 123.
29
+ */
30
+ export function parseOptionValue(value: string | null | undefined): unknown {
31
+ if (value == null) return null;
32
+ const trimmed = value.trim();
33
+ if (/^[[{]/.test(trimmed) || trimmed === "true" || trimmed === "false" || trimmed === "null") {
34
+ try {
35
+ return JSON.parse(trimmed);
36
+ } catch {
37
+ return value;
38
+ }
39
+ }
40
+ return value;
41
+ }
42
+
43
+ export function setAtPath<T>(input: T, path: string, value: unknown): T {
44
+ const segments = path.split(".").filter(Boolean);
45
+ if (segments.length === 0) return input;
46
+
47
+ const write = (node: unknown, depth: number): unknown => {
48
+ const segment = segments[depth]!;
49
+ const index = /^\d+$/.test(segment) ? Number(segment) : null;
50
+ const isLast = depth === segments.length - 1;
51
+
52
+ if (index !== null) {
53
+ const array = Array.isArray(node) ? [...node] : [];
54
+ array[index] = isLast ? value : write(array[index], depth + 1);
55
+ return array;
56
+ }
57
+ const object = node && typeof node === "object" && !Array.isArray(node) ? { ...(node as object) } : {};
58
+ (object as Record<string, unknown>)[segment] = isLast
59
+ ? value
60
+ : write((object as Record<string, unknown>)[segment], depth + 1);
61
+ return object;
62
+ };
63
+
64
+ return write(input, 0) as T;
65
+ }
66
+
67
+ /**
68
+ * Reference inputs (TreatmentReferenceInput, AllergyReferenceInput, …) take exactly ONE locator.
69
+ * Choosing an option like `treatment.id` must replace the free text `treatment.name` the user typed,
70
+ * not sit beside it — so setting a locator clears its sibling locators. (Seen on boson: a
71
+ * DISAMBIGUATION change returns options `{ argument: "treatment.id", value: "med_…" }`.)
72
+ */
73
+ const LOCATORS = new Set(["id", "name", "rxNormId", "ndc", "upc", "icd10Code", "externalId"]);
74
+
75
+ /**
76
+ * An option's argument path, relative to the mutation's input. network-api sometimes roots it at the
77
+ * argument name — `patient.clinical.allergies.add.0.id` for the `patient` mutation (boson,
78
+ * 2026-09-29) — and sometimes not (`treatment.id` for `prescription`); drop that leading name.
79
+ */
80
+ export function optionPath(option: ApplicableOption & { argument: string }): string {
81
+ const root = `${option.operation}.`;
82
+ const path = option.argument.startsWith(root) ? option.argument.slice(root.length) : option.argument;
83
+ // network-api's pharmacy options omit the OrderPharmacyInput wrapper.
84
+ return option.operation === "order" && path === "pharmacy.id" ? "pharmacy.pharmacy.id" : path;
85
+ }
86
+
87
+ export function applyOption<T>(input: T, option: ApplicableOption): T {
88
+ if (!isInlineOption(option)) {
89
+ throw new Error(`Option "${option.operation}" has no argument path; it calls a different operation.`);
90
+ }
91
+ return applyAt(input, optionPath(option), parseOptionValue(option.value));
92
+ }
93
+
94
+ /** Put a picked value at its path in the input; a locator (`….id`) replaces its siblings (the typed name). */
95
+ export function applyAt<T>(input: T, path: string, value: unknown): T {
96
+ const segments = path.split(".").filter(Boolean);
97
+ const last = segments.at(-1)!;
98
+ if (segments.length > 1 && LOCATORS.has(last)) {
99
+ const parentPath = segments.slice(0, -1).join(".");
100
+ return setAtPath(input, parentPath, { [last]: value });
101
+ }
102
+ return setAtPath(input, path, value);
103
+ }
@@ -0,0 +1,10 @@
1
+ import type { ChangeFieldsFragment } from "../../gql/graphql.ts";
2
+
3
+ export type Change = ChangeFieldsFragment;
4
+
5
+ /** Every payload's changes; `status` says which took effect. */
6
+ export interface ChangeSet {
7
+ changes: Change[];
8
+ /** The input that produced these changes: network-api doesn't echo what it tried to resolve. */
9
+ sent?: unknown;
10
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./applyOption.ts";
2
+ export * from "./classifyChanges.ts";