@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,371 @@
1
+ import type {
2
+ ChangeFieldsFragment,
3
+ ListDocumentationStatus,
4
+ OrderCandidateFieldsFragment,
5
+ OrderFieldsFragment,
6
+ PatientFieldsFragment,
7
+ PharmacyEventFieldsFragment,
8
+ OrganizationFieldsFragment,
9
+ PharmacyFieldsFragment,
10
+ PharmacyOfferFieldsFragment,
11
+ RedemptionMethodFieldsFragment,
12
+ PrescriptionFieldsFragment,
13
+ ScreeningAlertFieldsFragment,
14
+ PrescriptionTemplateFieldsFragment,
15
+ TreatmentFieldsFragment,
16
+ } from "../gql/graphql.ts";
17
+ import { isInlineOption, optionPath, parseOptionValue, type ChangeSet } from "../api/index.ts";
18
+ import type {
19
+ Change,
20
+ ChangeOption,
21
+ Changes,
22
+ OrderCandidate,
23
+ OrderRecord,
24
+ PatientRecord,
25
+ Pharmacy,
26
+ PharmacyEvent,
27
+ Organization,
28
+ PharmacyOffer,
29
+ PrescriptionRecord,
30
+ RedemptionMethod,
31
+ ScreeningAlert,
32
+ PrescriptionTemplate,
33
+ Treatment,
34
+ } from "./types.ts";
35
+
36
+ /**
37
+ * Generated GraphQL shapes → core's records. The one place the two meet: every field is picked by name,
38
+ * so a schema change stops here (and typecheck says where).
39
+ */
40
+
41
+ /** The union has one member today, tagged by `type` so a second one doesn't change how callers switch. */
42
+ const redemptionMethod = (m: RedemptionMethodFieldsFragment): RedemptionMethod => ({
43
+ type: "discountCard",
44
+ id: m.id,
45
+ prescriptionId: m.prescriptionId,
46
+ bin: m.bin,
47
+ pcn: m.pcn,
48
+ group: m.group,
49
+ memberId: m.memberId,
50
+ externalUrl: m.externalUrl,
51
+ });
52
+
53
+ const offer = (o: PharmacyOfferFieldsFragment): PharmacyOffer => ({
54
+ source: o.source,
55
+ prescriptionId: o.prescriptionId,
56
+ priceType: o.priceType ?? null,
57
+ isPromoted: o.isPromoted,
58
+ attributeTags: o.attributeTags.map(({ kind, label }) => ({ kind, label })),
59
+ price: o.price && {
60
+ amount: o.price.amount,
61
+ retailAmount: o.price.retailAmount,
62
+ promotions: o.price.promotions.map((p) => ({ type: p.type, baseAmount: p.baseAmount, amountSaved: p.amountSaved })),
63
+ },
64
+ deliveryEstimate: o.deliveryEstimate && {
65
+ deliveryPromise: o.deliveryEstimate.deliveryPromise,
66
+ deliveryPromiseRangeStart: o.deliveryEstimate.deliveryPromiseRangeStart,
67
+ deliveryPromiseRangeEnd: o.deliveryEstimate.deliveryPromiseRangeEnd,
68
+ },
69
+ redemptionMethods: o.redemptionMethods.map(redemptionMethod),
70
+ redemptionState: o.redemptionState,
71
+ });
72
+
73
+ const pharmacyEvent = (event: PharmacyEventFieldsFragment): PharmacyEvent =>
74
+ event.__typename === "PharmacyOpen24HrEvent"
75
+ ? { type: "24hr" }
76
+ : { type: event.__typename === "PharmacyOpenEvent" ? "open" : "close", datetime: event.datetime };
77
+
78
+ const organization = (o: OrganizationFieldsFragment): Organization => ({
79
+ id: o.id,
80
+ name: o.name,
81
+ customer: o.customer?.__typename === "Customer" ? { id: o.customer.id, name: o.customer.name } : null,
82
+ settings: o.settings && {
83
+ brandColor: o.settings.brandColor,
84
+ brandLogo: o.settings.brandLogo,
85
+ priorAuthorizationExceptionMessage: o.settings.priorAuthorizationExceptionMessage,
86
+ patientUx: {
87
+ enablePatientRerouting: o.settings.patientUx.enablePatientRerouting,
88
+ enableAutomatedOps: o.settings.patientUx.enableAutomatedOps,
89
+ },
90
+ },
91
+ });
92
+
93
+ const pharmacy = (p: PharmacyFieldsFragment | null): Pharmacy | null =>
94
+ p && {
95
+ id: p.id,
96
+ name: p.name,
97
+ logo: p.logo ?? null,
98
+ phone: p.phone ?? null,
99
+ hours:
100
+ p.hours?.map((h) => ({
101
+ openFrom: h.openFrom,
102
+ openUntil: h.openUntil,
103
+ dayOfWeek: h.dayOfWeek,
104
+ is24Hr: h.is24Hr,
105
+ timezone: h.timezone,
106
+ })) ?? null,
107
+ isOpen: p.isOpen ?? null,
108
+ nextEvents: p.nextEvents
109
+ ? { open: pharmacyEvent(p.nextEvents.open), close: pharmacyEvent(p.nextEvents.close) }
110
+ : null,
111
+ address: p.address && {
112
+ street1: p.address.street1,
113
+ street2: p.address.street2,
114
+ city: p.address.city,
115
+ state: p.address.state,
116
+ postalCode: p.address.postalCode,
117
+ },
118
+ latitude: p.latitude,
119
+ longitude: p.longitude,
120
+ fulfillmentType: p.fulfillmentType,
121
+ offers: (p.offers ?? []).map(offer),
122
+ };
123
+
124
+ /**
125
+ * A patient's list: null when not recorded, [] when "none" is. A list without a status (medications, diagnoses,
126
+ * benefits until network-api stores their "none") reads empty as not recorded.
127
+ */
128
+ const recorded = <T>({ status, entries }: { status?: ListDocumentationStatus | null; entries: T[] }): T[] | null =>
129
+ status === "NO_KNOWN_CONFIRMED" ? [] : entries.length ? entries : null;
130
+
131
+ export function toPatient(p: PatientFieldsFragment): PatientRecord {
132
+ const d = p.demographic;
133
+ const ct = p.contact;
134
+ const c = p.clinical;
135
+ return {
136
+ id: p.id,
137
+ demographic: d && {
138
+ name: { first: d.name.first, middle: d.name.middle, last: d.name.last },
139
+ dateOfBirth: d.dateOfBirth,
140
+ sex: d.sex,
141
+ gender: d.gender,
142
+ },
143
+ contact: ct && {
144
+ email: ct.email,
145
+ phone: ct.phone,
146
+ address: ct.address && {
147
+ street1: ct.address.street1,
148
+ street2: ct.address.street2,
149
+ city: ct.address.city,
150
+ state: ct.address.state,
151
+ postalCode: ct.address.postalCode,
152
+ country: ct.address.country,
153
+ },
154
+ },
155
+ benefits:
156
+ recorded(p.benefits)?.map((b) => ({
157
+ id: b.id,
158
+ bin: b.bin,
159
+ pcn: b.pcn,
160
+ groupId: b.groupId,
161
+ memberId: b.memberId,
162
+ })) ?? null,
163
+ preferredPharmacy: pharmacy(p.preferredPharmacy),
164
+ clinical: c && {
165
+ allergies: recorded(c.allergies)?.map((a) => ({ id: a.id, name: a.name, rxNormId: a.rxNormId })) ?? null,
166
+ medications:
167
+ recorded(c.medications)?.map((m) => ({ id: m.id, name: m.name, rxNormId: m.rxNormId, status: m.status })) ??
168
+ null,
169
+ diagnoses: recorded(c.diagnoses)?.map((x) => ({ id: x.id, name: x.name, icd10Code: x.icd10Code })) ?? null,
170
+ notes: c.notes,
171
+ },
172
+ };
173
+ }
174
+
175
+ const toScreeningAlert = (a: ScreeningAlertFieldsFragment): ScreeningAlert => ({
176
+ severity: a.severity,
177
+ type: a.type,
178
+ description: a.description,
179
+ involvedEntities: a.involvedEntities.map((e) => ({ id: e.id, name: e.name })),
180
+ });
181
+
182
+ const toTreatment = (
183
+ t: TreatmentFieldsFragment & { templates?: readonly PrescriptionTemplateFieldsFragment[] | null },
184
+ ): Treatment => ({
185
+ id: String(t.id),
186
+ name: t.name,
187
+ prescribableName: t.prescribableName,
188
+ rxNormId: t.rxNormId,
189
+ ndc: t.ndc,
190
+ upc: t.upc,
191
+ entityKind: t.entityKind,
192
+ brandName: t.brandName,
193
+ genericName: t.genericName,
194
+ form: t.form,
195
+ route: t.route,
196
+ strength: t.strength,
197
+ medicationType: t.medicationType,
198
+ schedule: t.schedule,
199
+ templates: t.templates ? t.templates.map(toPrescriptionTemplate) : null,
200
+ });
201
+
202
+ export const toPrescriptionTemplate = (t: PrescriptionTemplateFieldsFragment): PrescriptionTemplate => ({
203
+ id: t.id,
204
+ source: t.source,
205
+ name: t.name,
206
+ instructions: t.instructions,
207
+ dispense: t.dispense && {
208
+ quantity: t.dispense.quantity,
209
+ unit: t.dispense.unit,
210
+ daysSupply: t.dispense.daysSupply,
211
+ refillsAllowed: t.dispense.refillsAllowed,
212
+ dispenseAsWritten: t.dispense.dispenseAsWritten,
213
+ },
214
+ });
215
+
216
+ export function toPrescription(rx: PrescriptionFieldsFragment): PrescriptionRecord {
217
+ return {
218
+ id: rx.id,
219
+ prescriber: rx.prescriber
220
+ ? {
221
+ id: rx.prescriber.id,
222
+ name: { first: rx.prescriber.name.first, middle: rx.prescriber.name.middle, last: rx.prescriber.name.last },
223
+ }
224
+ : null,
225
+ fulfillment: rx.fulfillment
226
+ ? {
227
+ state: rx.fulfillment.state,
228
+ pharmacyEstimatedReadyAt: rx.fulfillment.pharmacyEstimatedReadyAt,
229
+ exceptions: rx.fulfillment.exceptions.map((x) => ({
230
+ id: x.id,
231
+ type: x.type,
232
+ message: x.message,
233
+ createdAt: x.createdAt,
234
+ })),
235
+ }
236
+ : null,
237
+ templateId: rx.templateId,
238
+ patient: rx.patient && { id: rx.patient.id },
239
+ treatment: toTreatment(rx.treatment),
240
+ instructions: rx.instructions,
241
+ dispense: rx.dispense && {
242
+ quantity: rx.dispense.quantity,
243
+ unit: rx.dispense.unit,
244
+ daysSupply: rx.dispense.daysSupply,
245
+ refillsAllowed: rx.dispense.refillsAllowed,
246
+ dispenseAsWritten: rx.dispense.dispenseAsWritten,
247
+ },
248
+ clinical: rx.clinical && {
249
+ diagnoses: rx.clinical.diagnoses.map((x) => ({ id: x.id, name: x.name, icd10Code: x.icd10Code })),
250
+ notes: rx.clinical.notes,
251
+ },
252
+ screeningAlerts: (rx.screeningAlerts ?? []).map(toScreeningAlert),
253
+ signing: {
254
+ state: rx.signing.state,
255
+ contentHash: rx.signing.contentHash,
256
+ message: rx.signing.message,
257
+ signedAt: rx.signing.signedAt,
258
+ },
259
+ };
260
+ }
261
+
262
+ export function toOrder(o: OrderFieldsFragment): OrderRecord {
263
+ return {
264
+ id: o.id,
265
+ state: o.state,
266
+ organization: o.organization?.__typename === "Organization" ? organization(o.organization) : null,
267
+ patient: o.patient?.__typename === "Patient" ? toPatient(o.patient) : null,
268
+ prescriptions: o.prescriptions.map(toPrescription),
269
+ screeningAlerts: (o.screeningAlerts ?? []).map(toScreeningAlert),
270
+ // Null until a pharmacy is chosen — kept as null, not flattened to [], so "unpriced" stays distinct.
271
+ offers: { atPharmacy: o.offers.atPharmacy?.map(offer) ?? null },
272
+ pharmacy: pharmacy(o.pharmacy),
273
+ fulfillment: o.fulfillment && {
274
+ state: o.fulfillment.state,
275
+ history: o.fulfillment.history.map((entry) => ({
276
+ pharmacy: pharmacy(entry.pharmacy)!,
277
+ selector: entry.selector,
278
+ reason: entry.reason,
279
+ createdAt: entry.createdAt,
280
+ })),
281
+ routability: o.fulfillment.routability && {
282
+ allowed: o.fulfillment.routability.allowed,
283
+ reason: o.fulfillment.routability.reason,
284
+ },
285
+ exceptions: o.fulfillment.exceptions.map((x) => ({
286
+ id: x.id,
287
+ type: x.type,
288
+ message: x.message,
289
+ createdAt: x.createdAt,
290
+ })),
291
+ },
292
+ };
293
+ }
294
+
295
+ export function toOrderCandidate(c: OrderCandidateFieldsFragment): OrderCandidate {
296
+ return { id: c.id, pharmacy: pharmacy(c.pharmacy), prescriptions: c.prescriptions.map(toPrescription) };
297
+ }
298
+
299
+ /** The record an option picks: an object holding its id (`{"id":…}`), or an id at a `….id` path. */
300
+ function pickedId(path: string | null, value: unknown): string | null {
301
+ if (value && typeof value === "object" && typeof (value as { id?: unknown }).id === "string")
302
+ return (value as { id: string }).id;
303
+ return path?.split(".").at(-1) === "id" && typeof value === "string" && value ? value : null;
304
+ }
305
+
306
+ type Choice = NonNullable<ChangeFieldsFragment["after"]>;
307
+
308
+ const choicePath = (o: Choice) => (isInlineOption(o) ? optionPath(o) : null);
309
+
310
+ export const toChoice = (o: Choice): ChangeOption => {
311
+ const path = choicePath(o);
312
+ const value = parseOptionValue(o.value);
313
+ return {
314
+ displayName: o.displayName,
315
+ reason: o.reason,
316
+ path,
317
+ value,
318
+ id: pickedId(path, value),
319
+ treatment: o.entity?.__typename === "Treatment" ? toTreatment(o.entity) : null,
320
+ pharmacy: o.entity?.__typename === "Pharmacy" ? pharmacy(o.entity) : null,
321
+ operation: o.operation,
322
+ matchReasons: (o.matchReasons ?? []).map((r) => ({
323
+ type: r.type,
324
+ label: r.label,
325
+ confidence: r.confidence ?? null,
326
+ value: r.value ? { displayValue: r.value.displayValue, value: r.value.value, unit: r.value.unit } : null,
327
+ })),
328
+ };
329
+ };
330
+
331
+ const change = (c: ChangeFieldsFragment, sent: unknown): Change => {
332
+ const after = c.after ? toChoice(c.after) : null;
333
+ return {
334
+ key: c.key,
335
+ label: c.label,
336
+ status: c.status,
337
+ severity: c.severity,
338
+ reason: c.reason,
339
+ category: c.category,
340
+ operation: c.operation,
341
+ options: (c.options ?? []).map(toChoice),
342
+ after,
343
+ inputText: inputTextOf(c, sent),
344
+ resolvedId: c.status === "APPLIED" ? (after?.id ?? after?.treatment?.id ?? after?.pharmacy?.id ?? null) : null,
345
+ };
346
+ };
347
+
348
+ /**
349
+ * The text the server tried to resolve, read back from what was sent: network-api doesn't echo it, but each
350
+ * choice's path says where it went (`treatment.id` → the `treatment` sent: `{ name: "lisinopril" }`).
351
+ */
352
+ function inputTextOf(c: ChangeFieldsFragment, sent: unknown): string | null {
353
+ const choices = [...(c.options ?? []), c.after, c.before].filter((o): o is Choice => Boolean(o));
354
+ for (const path of choices.map(choicePath)) {
355
+ const segments = path?.split(".") ?? [];
356
+ if (segments.at(-1) === "id") segments.pop();
357
+ const at = segments.reduce<unknown>((node, key) => (node as Record<string, unknown> | null)?.[key], sent);
358
+ if (typeof at === "string") return at;
359
+ const reference = (at ?? {}) as { name?: unknown; rxNormId?: unknown; icd10Code?: unknown };
360
+ const text = reference.name ?? reference.rxNormId ?? reference.icd10Code;
361
+ if (typeof text === "string") return text;
362
+ }
363
+ return null;
364
+ }
365
+
366
+ export const toChanges = (set: ChangeSet | null | undefined): Changes => {
367
+ const all = (set?.changes ?? []).map((c) => change(c, set?.sent));
368
+ return { applied: all.filter((c) => c.status === "APPLIED"), unapplied: all.filter((c) => c.status !== "APPLIED") };
369
+ };
370
+
371
+ export const noChanges: Changes = { applied: [], unapplied: [] };
@@ -0,0 +1,142 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ change,
4
+ fakeNetworkApiClient,
5
+ listedOrder,
6
+ order,
7
+ orders,
8
+ patient,
9
+ payload,
10
+ photonOver,
11
+ rx,
12
+ treatment,
13
+ } from "../testing.ts";
14
+
15
+ const metoprolol = rx({ id: "rx_9", treatment: treatment({ id: "trt_9", name: "Metoprolol Tartrate" }) });
16
+ const draft = (id = "ord_9", prescriptions = [metoprolol]) => listedOrder({ id, prescriptions });
17
+
18
+ /** A new order whose patient has these draft orders (Orders answers with them). */
19
+ const setUp = (drafts: ReturnType<typeof draft>[], more: Parameters<typeof fakeNetworkApiClient>[0] = {}) => {
20
+ const fake = fakeNetworkApiClient({
21
+ GetPatient: () => payload("patient", "PatientPayload", patient()),
22
+ Orders: () => orders(drafts),
23
+ GetOrder: (vars) => payload("order", "OrderPayload", order({ id: vars.id, prescriptions: [metoprolol] })),
24
+ GetPrescription: () => payload("prescription", "PrescriptionPayload", metoprolol),
25
+ UpdateOrder: (vars) => payload("order", "OrderPayload", order({ id: vars.id, prescriptions: [] })),
26
+ ...more,
27
+ });
28
+ return { ...fake, ph: photonOver(fake.client) };
29
+ };
30
+
31
+ describe("a new order looks for its patient's draft order", () => {
32
+ it("one draft: it's `draft`, for the prescriber to decide — nothing saved, the order still new", async () => {
33
+ const { ph, names, calls } = setUp([draft()]);
34
+ const order = ph.order();
35
+ await order.sync({ patient: { id: "pat_1" } });
36
+ expect(calls.find((c) => c.op === "Orders")!.vars.filter).toEqual({ patient: { id: "pat_1" }, state: "DRAFT" });
37
+ expect(order.snapshot.draft).toMatchObject({ id: "ord_9", prescriptions: [{ id: "rx_9" }] });
38
+ expect(order.id).toBeNull();
39
+ expect(names()).not.toContain("SyncOrder");
40
+ });
41
+
42
+ it("continueDraft(): the order becomes the draft, showing only the draft's prescriptions", async () => {
43
+ const { ph } = setUp([draft()]);
44
+ const order = ph.order();
45
+ await order.sync({ patient: { id: "pat_1" }, prescriptions: { add: [{}] } });
46
+ await order.continueDraft();
47
+ expect(order.id).toBe("ord_9");
48
+ expect(order.snapshot.draft).toBeNull();
49
+ expect(order.prescriptions.map((l) => l.id)).toEqual(["rx_9"]); // the empty line gives way: send it as it is
50
+ });
51
+
52
+ it("continueDraft(): a prescription already started (from a template) stays, after the draft's", async () => {
53
+ const { ph } = setUp([draft()]);
54
+ const order = ph.order();
55
+ await order.sync({ patient: { id: "pat_1" }, prescriptions: { add: [{ templateId: "tmp_1" }] } });
56
+ await order.continueDraft();
57
+ expect(order.prescriptions.map((l) => [l.id, l.templateId])).toEqual([
58
+ ["rx_9", null],
59
+ [null, "tmp_1"],
60
+ ]);
61
+ });
62
+
63
+ it("startNew(): the draft is emptied, and the order starts over on it", async () => {
64
+ const { ph, calls } = setUp([draft()]);
65
+ const order = ph.order();
66
+ await order.sync({ patient: { id: "pat_1" }, prescriptions: { add: [{}] } });
67
+ await order.startNew();
68
+ expect(calls.find((c) => c.op === "UpdateOrder")!.vars).toMatchObject({
69
+ id: "ord_9",
70
+ prescriptions: { none: true },
71
+ });
72
+ expect(order.snapshot.draft).toBeNull();
73
+ expect(order.id).toBe("ord_9");
74
+ expect(order.prescriptions.map((l) => l.id)).toEqual([null]); // only its own empty line, nothing of the draft's
75
+ });
76
+
77
+ it("startNew() turned down: the draft is still there to decide on", async () => {
78
+ const { ph } = setUp([draft()], {
79
+ UpdateOrder: () =>
80
+ payload("order", "OrderPayload", null, {
81
+ changes: [change({ key: "prescriptions", status: "REJECTED", reason: "Not allowed." })],
82
+ }),
83
+ });
84
+ const order = ph.order();
85
+ await order.sync({ patient: { id: "pat_1" } });
86
+ await order.startNew();
87
+ expect(order.id).toBeNull();
88
+ expect(order.snapshot.draft).toMatchObject({ id: "ord_9" });
89
+ });
90
+
91
+ it("a draft with no prescriptions isn't asked about: the order goes on, and saves as it would", async () => {
92
+ const { ph, calls } = setUp([draft("ord_9", [])], {
93
+ GetPrescription: () => payload("prescription", "PrescriptionPayload", rx({ id: "rx_new" })),
94
+ SyncOrder: () => payload("order", "OrderPayload", order({ id: "ord_9", prescriptions: [rx({ id: "rx_new" })] })),
95
+ });
96
+ const started = ph.order();
97
+ await started.sync({ patient: { id: "pat_1" } });
98
+ expect(started.snapshot.draft).toBeNull();
99
+ await started.sync({ prescriptions: { add: [{ id: "rx_new" }] } });
100
+ expect(calls.find((c) => c.op === "SyncOrder")!.vars).toMatchObject({ prescriptions: { add: [{ id: "rx_new" }] } });
101
+ expect(started.id).toBe("ord_9");
102
+ });
103
+
104
+ it("several drafts: they're `candidates`, as when the server asks which", async () => {
105
+ const { ph } = setUp([draft("ord_8"), draft("ord_9")]);
106
+ const order = ph.order();
107
+ await order.sync({ patient: { id: "pat_1" } });
108
+ expect(order.snapshot.draft).toBeNull();
109
+ expect(order.snapshot.candidates.map((c) => c.id)).toEqual(["ord_8", "ord_9"]);
110
+ });
111
+
112
+ it("no draft, or a read that fails: nothing changes", async () => {
113
+ for (const answer of [() => orders([]), () => Promise.reject(new Error("down"))]) {
114
+ const { ph } = setUp([], { Orders: answer });
115
+ const order = ph.order();
116
+ await order.sync({ patient: { id: "pat_1" } });
117
+ expect(order.snapshot.draft).toBeNull();
118
+ expect(order.snapshot.candidates).toEqual([]);
119
+ expect(order.snapshot.error).toBeNull();
120
+ }
121
+ });
122
+
123
+ it("once per patient", async () => {
124
+ const { ph, names } = setUp([draft()]);
125
+ const order = ph.order();
126
+ await order.sync({ patient: { id: "pat_1" } });
127
+ await order.startNew();
128
+ await order.sync({ patient: { id: "pat_1" } });
129
+ expect(names().filter((n) => n === "Orders")).toHaveLength(1);
130
+ });
131
+
132
+ it("an order handed existing prescriptions isn't asked: they decide the order", async () => {
133
+ const { ph, names } = setUp([draft()], {
134
+ GetPrescription: () => payload("prescription", "PrescriptionPayload", rx()),
135
+ SyncOrder: () => payload("order", "OrderPayload", order()),
136
+ });
137
+ const handed = ph.order();
138
+ await handed.sync({ patient: { id: "pat_1" }, prescriptions: { add: [{ id: "rx_1" }] } });
139
+ expect(names()).not.toContain("Orders");
140
+ expect(handed.id).toBe("ord_1");
141
+ });
142
+ });