@photonhealth/client 2.0.0-rc.1 → 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 (158) hide show
  1. package/README.md +150 -5
  2. package/dist/analytics/lifecycleEvents.d.ts +32 -0
  3. package/dist/analytics/lifecycleEvents.d.ts.map +1 -0
  4. package/dist/analytics/lifecycleEvents.js +75 -0
  5. package/dist/analytics/lifecycleEvents.js.map +1 -0
  6. package/dist/analytics/track.d.ts +39 -0
  7. package/dist/analytics/track.d.ts.map +1 -0
  8. package/dist/analytics/track.js +91 -0
  9. package/dist/analytics/track.js.map +1 -0
  10. package/dist/api/changes/applyOption.d.ts +4 -1
  11. package/dist/api/changes/applyOption.d.ts.map +1 -1
  12. package/dist/api/changes/applyOption.js +23 -2
  13. package/dist/api/changes/applyOption.js.map +1 -1
  14. package/dist/api/client.d.ts +6 -1
  15. package/dist/api/client.d.ts.map +1 -1
  16. package/dist/api/client.js +47 -33
  17. package/dist/api/client.js.map +1 -1
  18. package/dist/api/index.d.ts +2 -0
  19. package/dist/api/index.d.ts.map +1 -1
  20. package/dist/api/index.js +2 -0
  21. package/dist/api/index.js.map +1 -1
  22. package/dist/api/me.d.ts +37 -0
  23. package/dist/api/me.d.ts.map +1 -0
  24. package/dist/api/me.js +6 -0
  25. package/dist/api/me.js.map +1 -0
  26. package/dist/api/orders.d.ts +1047 -0
  27. package/dist/api/orders.d.ts.map +1 -0
  28. package/dist/api/orders.js +7 -0
  29. package/dist/api/orders.js.map +1 -0
  30. package/dist/api/patient.d.ts +5 -2
  31. package/dist/api/patient.d.ts.map +1 -1
  32. package/dist/api/patient.js +1 -1
  33. package/dist/api/patient.js.map +1 -1
  34. package/dist/api/prescription.d.ts +7 -1
  35. package/dist/api/prescription.d.ts.map +1 -1
  36. package/dist/api/prescription.js +10 -1
  37. package/dist/api/prescription.js.map +1 -1
  38. package/dist/gql/gql.d.ts +11 -3
  39. package/dist/gql/gql.d.ts.map +1 -1
  40. package/dist/gql/gql.js +5 -3
  41. package/dist/gql/gql.js.map +1 -1
  42. package/dist/gql/graphql.d.ts +10507 -1563
  43. package/dist/gql/graphql.d.ts.map +1 -1
  44. package/dist/gql/graphql.js +2984 -435
  45. package/dist/gql/graphql.js.map +1 -1
  46. package/dist/index.d.ts +1 -1
  47. package/dist/index.js +1 -1
  48. package/dist/meta/version.d.ts +2 -0
  49. package/dist/meta/version.d.ts.map +1 -0
  50. package/dist/meta/version.js +2 -0
  51. package/dist/meta/version.js.map +1 -0
  52. package/dist/photon/auth.d.ts +9 -5
  53. package/dist/photon/auth.d.ts.map +1 -1
  54. package/dist/photon/auth.js +2 -6
  55. package/dist/photon/auth.js.map +1 -1
  56. package/dist/photon/choices.d.ts +1 -1
  57. package/dist/photon/choices.js +2 -2
  58. package/dist/photon/choices.js.map +1 -1
  59. package/dist/photon/environments.d.ts +2 -1
  60. package/dist/photon/environments.d.ts.map +1 -1
  61. package/dist/photon/environments.js +2 -1
  62. package/dist/photon/environments.js.map +1 -1
  63. package/dist/photon/index.d.ts +6 -3
  64. package/dist/photon/index.d.ts.map +1 -1
  65. package/dist/photon/index.js +2 -1
  66. package/dist/photon/index.js.map +1 -1
  67. package/dist/photon/machine.d.ts +28 -0
  68. package/dist/photon/machine.d.ts.map +1 -0
  69. package/dist/photon/machine.js +53 -0
  70. package/dist/photon/machine.js.map +1 -0
  71. package/dist/photon/map.d.ts +6 -2
  72. package/dist/photon/map.d.ts.map +1 -1
  73. package/dist/photon/map.js +133 -33
  74. package/dist/photon/map.js.map +1 -1
  75. package/dist/photon/order.d.ts +24 -5
  76. package/dist/photon/order.d.ts.map +1 -1
  77. package/dist/photon/order.js +85 -23
  78. package/dist/photon/order.js.map +1 -1
  79. package/dist/photon/orders.d.ts +5 -0
  80. package/dist/photon/orders.d.ts.map +1 -0
  81. package/dist/photon/orders.js +39 -0
  82. package/dist/photon/orders.js.map +1 -0
  83. package/dist/photon/patient.d.ts +8 -6
  84. package/dist/photon/patient.d.ts.map +1 -1
  85. package/dist/photon/patient.js +61 -30
  86. package/dist/photon/patient.js.map +1 -1
  87. package/dist/photon/photon.d.ts +39 -1
  88. package/dist/photon/photon.d.ts.map +1 -1
  89. package/dist/photon/photon.js +85 -5
  90. package/dist/photon/photon.js.map +1 -1
  91. package/dist/photon/prescription.d.ts +17 -4
  92. package/dist/photon/prescription.d.ts.map +1 -1
  93. package/dist/photon/prescription.js +48 -11
  94. package/dist/photon/prescription.js.map +1 -1
  95. package/dist/photon/session.d.ts +16 -10
  96. package/dist/photon/session.d.ts.map +1 -1
  97. package/dist/photon/session.js +26 -11
  98. package/dist/photon/session.js.map +1 -1
  99. package/dist/photon/types.d.ts +278 -46
  100. package/dist/photon/types.d.ts.map +1 -1
  101. package/dist/test-utils/msw.d.ts +2 -2
  102. package/dist/test-utils/msw.d.ts.map +1 -1
  103. package/dist/test-utils/msw.js +5 -5
  104. package/dist/test-utils/msw.js.map +1 -1
  105. package/dist/testing/{scriptedClient.d.ts → fakeNetworkApiClient.d.ts} +5 -4
  106. package/dist/testing/fakeNetworkApiClient.d.ts.map +1 -0
  107. package/dist/testing/{scriptedClient.js → fakeNetworkApiClient.js} +8 -4
  108. package/dist/testing/fakeNetworkApiClient.js.map +1 -0
  109. package/dist/testing/fixtures.d.ts +1047 -0
  110. package/dist/testing/fixtures.d.ts.map +1 -1
  111. package/dist/testing/fixtures.js +47 -13
  112. package/dist/testing/fixtures.js.map +1 -1
  113. package/dist/testing.d.ts +4 -4
  114. package/dist/testing.d.ts.map +1 -1
  115. package/dist/testing.js +4 -4
  116. package/dist/testing.js.map +1 -1
  117. package/package.json +2 -2
  118. package/src/analytics/lifecycleEvents.test.ts +437 -0
  119. package/src/analytics/lifecycleEvents.ts +172 -0
  120. package/src/analytics/track.test.ts +231 -0
  121. package/src/analytics/track.ts +129 -0
  122. package/src/api/changes/applyOption.ts +25 -2
  123. package/src/api/client.ts +71 -46
  124. package/src/api/index.ts +2 -0
  125. package/src/api/me.ts +7 -0
  126. package/src/api/orders.ts +8 -0
  127. package/src/api/patient.ts +11 -2
  128. package/src/api/prescription.ts +18 -0
  129. package/src/gql/gql.ts +21 -9
  130. package/src/gql/graphql.ts +4280 -597
  131. package/src/index.ts +1 -1
  132. package/src/meta/version.test.ts +10 -0
  133. package/src/meta/version.ts +1 -0
  134. package/src/operations/fragments.graphql +166 -20
  135. package/src/operations/me.graphql +38 -0
  136. package/src/operations/orders.graphql +35 -0
  137. package/src/operations/patient.graphql +29 -3
  138. package/src/operations/prescription.graphql +20 -0
  139. package/src/photon/auth.ts +9 -10
  140. package/src/photon/choices.ts +2 -2
  141. package/src/photon/environments.ts +3 -1
  142. package/src/photon/index.ts +17 -2
  143. package/src/photon/machine.ts +90 -0
  144. package/src/photon/map.ts +151 -35
  145. package/src/photon/order.test.ts +142 -0
  146. package/src/photon/order.ts +99 -24
  147. package/src/photon/orders.ts +42 -0
  148. package/src/photon/patient.ts +73 -33
  149. package/src/photon/photon.ts +139 -6
  150. package/src/photon/prescription.ts +71 -12
  151. package/src/photon/session.ts +39 -16
  152. package/src/photon/types.ts +280 -26
  153. package/src/test-utils/msw.ts +16 -5
  154. package/src/testing/{scriptedClient.ts → fakeNetworkApiClient.ts} +8 -4
  155. package/src/testing/fixtures.ts +55 -13
  156. package/src/testing.ts +6 -3
  157. package/dist/testing/scriptedClient.d.ts.map +0 -1
  158. package/dist/testing/scriptedClient.js.map +0 -1
package/src/photon/map.ts CHANGED
@@ -4,10 +4,14 @@ import type {
4
4
  OrderCandidateFieldsFragment,
5
5
  OrderFieldsFragment,
6
6
  PatientFieldsFragment,
7
+ PharmacyEventFieldsFragment,
8
+ OrganizationFieldsFragment,
7
9
  PharmacyFieldsFragment,
8
10
  PharmacyOfferFieldsFragment,
11
+ RedemptionMethodFieldsFragment,
9
12
  PrescriptionFieldsFragment,
10
13
  ScreeningAlertFieldsFragment,
14
+ PrescriptionTemplateFieldsFragment,
11
15
  TreatmentFieldsFragment,
12
16
  } from "../gql/graphql.ts";
13
17
  import { isInlineOption, optionPath, parseOptionValue, type ChangeSet } from "../api/index.ts";
@@ -19,9 +23,13 @@ import type {
19
23
  OrderRecord,
20
24
  PatientRecord,
21
25
  Pharmacy,
26
+ PharmacyEvent,
27
+ Organization,
22
28
  PharmacyOffer,
23
29
  PrescriptionRecord,
30
+ RedemptionMethod,
24
31
  ScreeningAlert,
32
+ PrescriptionTemplate,
25
33
  Treatment,
26
34
  } from "./types.ts";
27
35
 
@@ -30,28 +38,76 @@ import type {
30
38
  * so a schema change stops here (and typecheck says where).
31
39
  */
32
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
+
33
53
  const offer = (o: PharmacyOfferFieldsFragment): PharmacyOffer => ({
34
54
  source: o.source,
55
+ prescriptionId: o.prescriptionId,
56
+ priceType: o.priceType ?? null,
35
57
  isPromoted: o.isPromoted,
36
58
  attributeTags: o.attributeTags.map(({ kind, label }) => ({ kind, label })),
37
- priceSummary: o.priceSummary && {
38
- priceType: o.priceSummary.priceType,
39
- totalAmount: o.priceSummary.totalAmount,
40
- totalRetailAmount: o.priceSummary.totalRetailAmount,
41
- totalSavings: o.priceSummary.totalSavings,
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
+ },
42
90
  },
43
- prescriptionDeliveryEstimates: o.prescriptionDeliveryEstimates.map((d) => ({
44
- prescriptionId: d.prescriptionId,
45
- deliveryPromise: d.deliveryPromise,
46
- deliveryPromiseRangeStart: d.deliveryPromiseRangeStart,
47
- deliveryPromiseRangeEnd: d.deliveryPromiseRangeEnd,
48
- })),
49
91
  });
50
92
 
51
93
  const pharmacy = (p: PharmacyFieldsFragment | null): Pharmacy | null =>
52
94
  p && {
53
95
  id: p.id,
54
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,
55
111
  address: p.address && {
56
112
  street1: p.address.street1,
57
113
  street2: p.address.street2,
@@ -74,6 +130,7 @@ const recorded = <T>({ status, entries }: { status?: ListDocumentationStatus | n
74
130
 
75
131
  export function toPatient(p: PatientFieldsFragment): PatientRecord {
76
132
  const d = p.demographic;
133
+ const ct = p.contact;
77
134
  const c = p.clinical;
78
135
  return {
79
136
  id: p.id,
@@ -82,26 +139,28 @@ export function toPatient(p: PatientFieldsFragment): PatientRecord {
82
139
  dateOfBirth: d.dateOfBirth,
83
140
  sex: d.sex,
84
141
  gender: d.gender,
85
- email: d.email,
86
- phone: d.phone,
87
- address: d.address && {
88
- street1: d.address.street1,
89
- street2: d.address.street2,
90
- city: d.address.city,
91
- state: d.address.state,
92
- postalCode: d.address.postalCode,
93
- country: d.address.country,
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,
94
153
  },
95
- benefits:
96
- recorded(d.benefits)?.map((b) => ({
97
- id: b.id,
98
- bin: b.bin,
99
- pcn: b.pcn,
100
- groupId: b.groupId,
101
- memberId: b.memberId,
102
- })) ?? null,
103
- preferredPharmacy: pharmacy(d.preferredPharmacy),
104
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),
105
164
  clinical: c && {
106
165
  allergies: recorded(c.allergies)?.map((a) => ({ id: a.id, name: a.name, rxNormId: a.rxNormId })) ?? null,
107
166
  medications:
@@ -120,7 +179,9 @@ const toScreeningAlert = (a: ScreeningAlertFieldsFragment): ScreeningAlert => ({
120
179
  involvedEntities: a.involvedEntities.map((e) => ({ id: e.id, name: e.name })),
121
180
  });
122
181
 
123
- const toTreatment = (t: TreatmentFieldsFragment): Treatment => ({
182
+ const toTreatment = (
183
+ t: TreatmentFieldsFragment & { templates?: readonly PrescriptionTemplateFieldsFragment[] | null },
184
+ ): Treatment => ({
124
185
  id: String(t.id),
125
186
  name: t.name,
126
187
  prescribableName: t.prescribableName,
@@ -135,12 +196,44 @@ const toTreatment = (t: TreatmentFieldsFragment): Treatment => ({
135
196
  strength: t.strength,
136
197
  medicationType: t.medicationType,
137
198
  schedule: t.schedule,
138
- recommendedDispenseUnits: t.recommendedDispenseUnits ? [...t.recommendedDispenseUnits] : null,
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
+ },
139
214
  });
140
215
 
141
216
  export function toPrescription(rx: PrescriptionFieldsFragment): PrescriptionRecord {
142
217
  return {
143
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,
144
237
  templateId: rx.templateId,
145
238
  patient: rx.patient && { id: rx.patient.id },
146
239
  treatment: toTreatment(rx.treatment),
@@ -170,11 +263,32 @@ export function toOrder(o: OrderFieldsFragment): OrderRecord {
170
263
  return {
171
264
  id: o.id,
172
265
  state: o.state,
266
+ organization: o.organization?.__typename === "Organization" ? organization(o.organization) : null,
173
267
  patient: o.patient?.__typename === "Patient" ? toPatient(o.patient) : null,
174
268
  prescriptions: o.prescriptions.map(toPrescription),
175
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 },
176
272
  pharmacy: pharmacy(o.pharmacy),
177
- exceptions: o.exceptions.map((x) => ({ id: x.id, type: x.type, message: x.message, createdAt: x.createdAt })),
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
+ },
178
292
  };
179
293
  }
180
294
 
@@ -193,7 +307,7 @@ type Choice = NonNullable<ChangeFieldsFragment["after"]>;
193
307
 
194
308
  const choicePath = (o: Choice) => (isInlineOption(o) ? optionPath(o) : null);
195
309
 
196
- const choice = (o: Choice): ChangeOption => {
310
+ export const toChoice = (o: Choice): ChangeOption => {
197
311
  const path = choicePath(o);
198
312
  const value = parseOptionValue(o.value);
199
313
  return {
@@ -209,12 +323,13 @@ const choice = (o: Choice): ChangeOption => {
209
323
  type: r.type,
210
324
  label: r.label,
211
325
  confidence: r.confidence ?? null,
326
+ value: r.value ? { displayValue: r.value.displayValue, value: r.value.value, unit: r.value.unit } : null,
212
327
  })),
213
328
  };
214
329
  };
215
330
 
216
331
  const change = (c: ChangeFieldsFragment, sent: unknown): Change => {
217
- const after = c.after ? choice(c.after) : null;
332
+ const after = c.after ? toChoice(c.after) : null;
218
333
  return {
219
334
  key: c.key,
220
335
  label: c.label,
@@ -223,7 +338,8 @@ const change = (c: ChangeFieldsFragment, sent: unknown): Change => {
223
338
  reason: c.reason,
224
339
  category: c.category,
225
340
  operation: c.operation,
226
- options: (c.options ?? []).map(choice),
341
+ options: (c.options ?? []).map(toChoice),
342
+ after,
227
343
  inputText: inputTextOf(c, sent),
228
344
  resolvedId: c.status === "APPLIED" ? (after?.id ?? after?.treatment?.id ?? after?.pharmacy?.id ?? null) : null,
229
345
  };
@@ -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
+ });
@@ -6,6 +6,7 @@ import { PhotonError, refuse, toPhotonError } from "./errors.ts";
6
6
  import { LiveRecord } from "./live.ts";
7
7
  import { noChanges, toChanges, toOrder, toOrderCandidate, toPrescription } from "./map.ts";
8
8
  import { Patient } from "./patient.ts";
9
+ import { readOrders } from "./orders.ts";
9
10
  import { Prescription } from "./prescription.ts";
10
11
  import type {
11
12
  ChangeOption,
@@ -29,6 +30,12 @@ export interface OrderExtra {
29
30
  * (this order's prescriptions go on it); nothing is saved until then.
30
31
  */
31
32
  candidates: OrderCandidate[];
33
+ /**
34
+ * The patient's draft order with prescriptions on it, found once a new order has its patient (before any
35
+ * prescription has a record): what's on it, for the prescriber to decide. `continueDraft()` makes this order that one; `startNew()` empties it and
36
+ * starts over on it. Nothing is saved until then.
37
+ */
38
+ draft: OrderRecord | null;
32
39
  /**
33
40
  * The server wouldn't send it until the patient can be reached (its reason). Cleared once the patient's
34
41
  * phone, email or address changes.
@@ -63,12 +70,12 @@ type NewLine = { templateId?: string | null } | { treatment: { id: string } };
63
70
 
64
71
  /** What makes a patient reachable — the contact request clears when this changes. */
65
72
  const contactOf = (p: Patient | null) => {
66
- const d = p?.state?.demographic;
73
+ const c = p?.state?.contact;
67
74
  return JSON.stringify([
68
- d?.phone ?? null,
69
- d?.email ?? null,
70
- d?.address?.street1 ?? null,
71
- d?.address?.postalCode ?? null,
75
+ c?.phone ?? null,
76
+ c?.email ?? null,
77
+ c?.address?.street1 ?? null,
78
+ c?.address?.postalCode ?? null,
72
79
  ]);
73
80
  };
74
81
 
@@ -76,7 +83,11 @@ const contactOf = (p: Patient | null) => {
76
83
  const alertKey = (a: ScreeningAlert) =>
77
84
  JSON.stringify([a.type, a.severity, a.description, a.involvedEntities.map((e) => e.id).sort()]);
78
85
 
79
- /** network-api won't start another order for a patient whose last one was sent (docs/api-gaps.md). */
86
+ /** A new line nothing was written in: no record, no drug picked, no template, nothing entered. */
87
+ const untouched = (line: Prescription) =>
88
+ !line.id && !line.snapshot.pick && !line.templateId && Object.keys(line.entered).length === 0;
89
+
90
+ /** network-api won't start another order for a patient whose last one was sent. */
80
91
  const alreadySent = () =>
81
92
  refuse("This patient's last order was already sent, and Photon can't start another for them yet.");
82
93
 
@@ -99,6 +110,8 @@ export class Order extends LiveRecord<OrderRecord, OrderExtra> {
99
110
  * are, and become lines when it answers.
100
111
  */
101
112
  #refs: { externalId: string }[] = [];
113
+ /** The patient whose draft orders were looked for: once per patient. */
114
+ #lookedFor: string | null = null;
102
115
  /** Held before the record, so a draft created once its lines are ready includes the pharmacy input. */
103
116
  #pharmacy: OrderPharmacyInput | undefined;
104
117
 
@@ -107,7 +120,11 @@ export class Order extends LiveRecord<OrderRecord, OrderExtra> {
107
120
  record: OrderRecord | null,
108
121
  extra: { patient?: Patient | null; prescriptions?: Prescription[]; changes?: Changes } = {},
109
122
  ) {
110
- super(record, { patient: null, prescriptions: [], candidates: [], contactRequest: null }, extra.changes);
123
+ super(
124
+ record,
125
+ { patient: null, prescriptions: [], candidates: [], draft: null, contactRequest: null },
126
+ extra.changes,
127
+ );
111
128
  this.#ctx = ctx;
112
129
  this.#setLines(extra.prescriptions ?? []);
113
130
  if (extra.patient) this.#follow(extra.patient);
@@ -143,23 +160,18 @@ export class Order extends LiveRecord<OrderRecord, OrderExtra> {
143
160
  }
144
161
 
145
162
  /**
146
- * Screening alerts no one has acknowledged: the order's own (its prescriptions screened together) and each
147
- * unsigned prescription's, less any a signed prescription carries — its signature acknowledged that one. A
148
- * caller that never reads the prescriptions still sees every open alert here; a page shows them by Send.
149
- * They never stop a send.
163
+ * The order's screening alerts (its prescriptions screened together) that none of its prescriptions carries,
164
+ * signed or not: an unsigned prescription shows its own and a signed one's are acknowledged, so a page shows
165
+ * only these by Send. They never stop a send.
150
166
  */
151
167
  get unacknowledgedAlerts(): ScreeningAlert[] {
152
- const acknowledged = new Set(
153
- this.prescriptions.flatMap((rx) => (rx.signed ? rx.state!.screeningAlerts.map(alertKey) : [])),
168
+ const carriedByAPrescription = new Set(
169
+ this.prescriptions.flatMap((rx) => (rx.state?.screeningAlerts ?? []).map(alertKey)),
154
170
  );
155
- const open = [
156
- ...(this.state?.screeningAlerts ?? []),
157
- ...this.prescriptions.flatMap((rx) => (rx.signed ? [] : (rx.state?.screeningAlerts ?? []))),
158
- ];
159
171
  const seen = new Set<string>();
160
- return open.filter((a) => {
172
+ return (this.state?.screeningAlerts ?? []).filter((a) => {
161
173
  const key = alertKey(a);
162
- if (acknowledged.has(key) || seen.has(key)) return false;
174
+ if (carriedByAPrescription.has(key) || seen.has(key)) return false;
163
175
  seen.add(key);
164
176
  return true;
165
177
  });
@@ -249,12 +261,38 @@ export class Order extends LiveRecord<OrderRecord, OrderExtra> {
249
261
  }
250
262
 
251
263
  /**
252
- * One of `candidates`: this becomes that draft order (read), and this order's prescriptions go on it.
264
+ * One of `candidates`: this becomes that draft order (read), and this order's prescriptions go on it — a line
265
+ * nothing was written in yet gives way to the draft's, so it can be sent as it is.
253
266
  */
254
267
  pick(orderId: string): Promise<{ changes: Changes }> {
255
268
  return this.run("loading", async () => {
256
269
  const result = await this.#settle(await getOrder(this.#ctx.client, orderId));
257
- this.patch({ candidates: [] });
270
+ this.patch({ candidates: [], draft: null });
271
+ if (this.prescriptions.some((l) => l.id)) this.#setLines(this.prescriptions.filter((l) => !untouched(l)));
272
+ return result;
273
+ }).then(() => this.#save());
274
+ }
275
+
276
+ /** Go on with the patient's draft order (`draft`): this becomes that order, and what's added goes on it. */
277
+ continueDraft(): Promise<{ changes: Changes }> {
278
+ if (!this.snapshot.draft) return Promise.reject(new PhotonError("invalid", "This order has no draft to continue."));
279
+ return this.pick(this.snapshot.draft.id);
280
+ }
281
+
282
+ /**
283
+ * Start over instead of continuing the patient's draft order (`draft`): its prescriptions come off it (taken off,
284
+ * not canceled) and this order is that draft, holding only what's written here. network-api continues a patient's
285
+ * draft whenever an order is saved, so emptying it is how a new order starts. Turned down, the draft is still
286
+ * there to decide on (its reason in `changes`).
287
+ */
288
+ startNew(): Promise<{ changes: Changes }> {
289
+ const draft = this.snapshot.draft;
290
+ if (!draft) return Promise.resolve({ changes: this.changes });
291
+ return this.run("saving", async () => {
292
+ const result = await this.#settle(
293
+ await updateOrder(this.#ctx.client, draft.id, { prescriptions: { none: true } }),
294
+ );
295
+ if (this.id) this.patch({ draft: null });
258
296
  return result;
259
297
  }).then(() => this.#save());
260
298
  }
@@ -351,6 +389,8 @@ export class Order extends LiveRecord<OrderRecord, OrderExtra> {
351
389
  const nothing = { changes: this.changes };
352
390
  if (this.final && !pharmacy) return Promise.resolve(nothing);
353
391
  if (!this.id) {
392
+ if (this.#toLookFor())
393
+ return this.run("loading", () => this.#findDraft()).then(() => this.#save(remove, pharmacy));
354
394
  if (!this.#readyToSync()) return Promise.resolve(nothing);
355
395
  // Queued behind other calls: by its turn, another save may have made the order — then just add to it.
356
396
  return this.run("saving", async () =>
@@ -372,10 +412,45 @@ export class Order extends LiveRecord<OrderRecord, OrderExtra> {
372
412
  Boolean(this.patient?.id) &&
373
413
  (this.prescriptions.some((line) => line.id) || this.#refs.length > 0) &&
374
414
  !this.snapshot.candidates.length &&
415
+ !this.snapshot.draft &&
375
416
  this.#declined !== this.#draftKey()
376
417
  );
377
418
  }
378
419
 
420
+ /** A new order's patient, not looked for yet: nothing on this order has a record that would decide which order. */
421
+ #toLookFor(): string | null {
422
+ const id = this.patient?.id ?? null;
423
+ if (!id || this.id || this.#lookedFor === id || this.#refs.length || this.prescriptions.some((l) => l.id))
424
+ return null;
425
+ return id;
426
+ }
427
+
428
+ /**
429
+ * The patient's draft orders (the read-only Orders query): one is `draft`, several are `candidates`. A read that
430
+ * fails leaves the order as it was — the server's sync still continues a draft.
431
+ */
432
+ async #findDraft(): Promise<{ changes: Changes }> {
433
+ const patientId = this.#toLookFor();
434
+ if (!patientId) return { changes: this.changes };
435
+ this.#lookedFor = patientId;
436
+ const found = await readOrders(this.#ctx.client, { filter: { patient: { id: patientId }, state: "DRAFT" } }).catch(
437
+ () => null,
438
+ );
439
+ // Moved on while it read: another patient, or a record now decides.
440
+ const decided = Boolean(this.id || this.#refs.length || this.prescriptions.some((l) => l.id));
441
+ if (!found || decided || this.patient?.id !== patientId) return { changes: this.changes };
442
+ // A draft with nothing on it isn't worth asking about: the server's sync continues it, as a new order would start.
443
+ const drafts = found.orders
444
+ .filter((order) => order.prescriptions.length > 0)
445
+ .map(({ routablePharmacies: _, ...order }) => order);
446
+ if (drafts.length === 1) this.patch({ draft: drafts[0]! });
447
+ else if (drafts.length > 1)
448
+ this.patch({
449
+ candidates: drafts.map((o) => ({ id: o.id, pharmacy: o.pharmacy, prescriptions: o.prescriptions })),
450
+ });
451
+ return { changes: this.changes };
452
+ }
453
+
379
454
  /** SyncOrder with the patient and every prescription that has a record: the patient's draft order, or a new one. */
380
455
  async #syncDraft(pharmacy?: OrderPharmacyInput): Promise<{ changes: Changes }> {
381
456
  const key = this.#draftKey();
@@ -442,7 +517,7 @@ export class Order extends LiveRecord<OrderRecord, OrderExtra> {
442
517
  // drug waiting for its patient would be created for this one.
443
518
  if (switching) {
444
519
  this.#contactAtRequest = null;
445
- this.patch({ contactRequest: null, candidates: [] });
520
+ this.patch({ contactRequest: null, candidates: [], draft: null });
446
521
  this.#setLines([this.#newLine(null, patient?.id ?? null)]);
447
522
  }
448
523
  this.#follow(patient);
@@ -460,7 +535,7 @@ export class Order extends LiveRecord<OrderRecord, OrderExtra> {
460
535
  const line = this.#newLine("templateId" in rx ? (rx.templateId ?? null) : null);
461
536
  const drug = "treatment" in rx ? { treatment: { id: rx.treatment.id } } : {};
462
537
  // A drug by id is looked up now; a template line is drafted once it has its patient (network-api doesn't expand
463
- // a template without one — docs/api-gaps.md).
538
+ // a template without one).
464
539
  if (drug.treatment) void line.sync(drug).catch(() => {}); // a failure lands on the line
465
540
  return line;
466
541
  }
@@ -505,7 +580,7 @@ export class Order extends LiveRecord<OrderRecord, OrderExtra> {
505
580
  /** The server won't send it until the patient can be reached: a missing phone, email or address (its words). */
506
581
  #askForContact(changes: Changes, message?: string) {
507
582
  const contact = changes.unapplied.find(
508
- (c) => c.key.startsWith("patient.demographic.") || asksForAddress({ applied: [], unapplied: [c] }),
583
+ (c) => c.key.startsWith("patient.contact.") || asksForAddress({ applied: [], unapplied: [c] }),
509
584
  );
510
585
  const reason = message ?? contact?.reason ?? null;
511
586
  if (!reason && !contact) return;