@photonhealth/react 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 (272) hide show
  1. package/README.md +52 -9
  2. package/dist/adapters/tailwind.d.ts.map +1 -1
  3. package/dist/adapters/tailwind.js +7 -4
  4. package/dist/adapters/tailwind.js.map +1 -1
  5. package/dist/analytics/PhotonAnalyticsProvider.d.ts +19 -0
  6. package/dist/analytics/PhotonAnalyticsProvider.d.ts.map +1 -0
  7. package/dist/analytics/PhotonAnalyticsProvider.js +76 -0
  8. package/dist/analytics/PhotonAnalyticsProvider.js.map +1 -0
  9. package/dist/analytics/cardLifecycle.d.ts +10 -0
  10. package/dist/analytics/cardLifecycle.d.ts.map +1 -0
  11. package/dist/analytics/cardLifecycle.js +43 -0
  12. package/dist/analytics/cardLifecycle.js.map +1 -0
  13. package/dist/analytics/fieldInteraction.d.ts +18 -0
  14. package/dist/analytics/fieldInteraction.d.ts.map +1 -0
  15. package/dist/analytics/fieldInteraction.js +102 -0
  16. package/dist/analytics/fieldInteraction.js.map +1 -0
  17. package/dist/analytics/lifecycleOutcomes.d.ts +8 -0
  18. package/dist/analytics/lifecycleOutcomes.d.ts.map +1 -0
  19. package/dist/analytics/lifecycleOutcomes.js +16 -0
  20. package/dist/analytics/lifecycleOutcomes.js.map +1 -0
  21. package/dist/analytics/tracker.d.ts +19 -0
  22. package/dist/analytics/tracker.d.ts.map +1 -0
  23. package/dist/analytics/tracker.js +41 -0
  24. package/dist/analytics/tracker.js.map +1 -0
  25. package/dist/analytics/viewed.d.ts +11 -0
  26. package/dist/analytics/viewed.d.ts.map +1 -0
  27. package/dist/analytics/viewed.js +16 -0
  28. package/dist/analytics/viewed.js.map +1 -0
  29. package/dist/components/PhotonOrder.d.ts +18 -18
  30. package/dist/components/PhotonOrder.d.ts.map +1 -1
  31. package/dist/components/PhotonOrder.js +34 -19
  32. package/dist/components/PhotonOrder.js.map +1 -1
  33. package/dist/components/PhotonPatient.d.ts +7 -35
  34. package/dist/components/PhotonPatient.d.ts.map +1 -1
  35. package/dist/components/PhotonPatient.js +6 -78
  36. package/dist/components/PhotonPatient.js.map +1 -1
  37. package/dist/components/PhotonPrescription.d.ts +15 -26
  38. package/dist/components/PhotonPrescription.d.ts.map +1 -1
  39. package/dist/components/PhotonPrescription.js +6 -360
  40. package/dist/components/PhotonPrescription.js.map +1 -1
  41. package/dist/components/format.d.ts +2 -2
  42. package/dist/components/format.js +2 -2
  43. package/dist/components/index.d.ts +1 -1
  44. package/dist/components/index.d.ts.map +1 -1
  45. package/dist/components/index.js +1 -1
  46. package/dist/components/index.js.map +1 -1
  47. package/dist/components/open.d.ts +11 -13
  48. package/dist/components/open.d.ts.map +1 -1
  49. package/dist/components/open.js +7 -2
  50. package/dist/components/open.js.map +1 -1
  51. package/dist/components/order/DraftOrderPrompt.d.ts +18 -0
  52. package/dist/components/order/DraftOrderPrompt.d.ts.map +1 -0
  53. package/dist/components/order/DraftOrderPrompt.js +26 -0
  54. package/dist/components/order/DraftOrderPrompt.js.map +1 -0
  55. package/dist/components/patient/PatientCard/PatientCard.d.ts +30 -0
  56. package/dist/components/patient/PatientCard/PatientCard.d.ts.map +1 -0
  57. package/dist/components/patient/PatientCard/PatientCard.js +101 -0
  58. package/dist/components/patient/PatientCard/PatientCard.js.map +1 -0
  59. package/dist/components/patient/PatientCard/usePatientToShow.d.ts +22 -0
  60. package/dist/components/patient/PatientCard/usePatientToShow.d.ts.map +1 -0
  61. package/dist/components/patient/PatientCard/usePatientToShow.js +40 -0
  62. package/dist/components/patient/PatientCard/usePatientToShow.js.map +1 -0
  63. package/dist/components/patient/PatientIntakeForm.d.ts +16 -0
  64. package/dist/components/patient/PatientIntakeForm.d.ts.map +1 -0
  65. package/dist/components/patient/PatientIntakeForm.js +114 -0
  66. package/dist/components/patient/PatientIntakeForm.js.map +1 -0
  67. package/dist/components/patient/PatientSearch.d.ts +12 -0
  68. package/dist/components/patient/PatientSearch.d.ts.map +1 -0
  69. package/dist/components/patient/PatientSearch.js +148 -0
  70. package/dist/components/patient/PatientSearch.js.map +1 -0
  71. package/dist/components/patient/{Benefits.d.ts → PatientSummary/BenefitsInputForm.d.ts} +2 -2
  72. package/dist/components/patient/PatientSummary/BenefitsInputForm.d.ts.map +1 -0
  73. package/dist/components/patient/{Benefits.js → PatientSummary/BenefitsInputForm.js} +6 -5
  74. package/dist/components/patient/PatientSummary/BenefitsInputForm.js.map +1 -0
  75. package/dist/components/patient/{Clinical.d.ts → PatientSummary/ClinicalInputForm.d.ts} +15 -16
  76. package/dist/components/patient/PatientSummary/ClinicalInputForm.d.ts.map +1 -0
  77. package/dist/components/patient/{Clinical.js → PatientSummary/ClinicalInputForm.js} +29 -28
  78. package/dist/components/patient/PatientSummary/ClinicalInputForm.js.map +1 -0
  79. package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts +5 -0
  80. package/dist/components/patient/PatientSummary/CollapsedSummary.d.ts.map +1 -0
  81. package/dist/components/patient/PatientSummary/CollapsedSummary.js +30 -0
  82. package/dist/components/patient/PatientSummary/CollapsedSummary.js.map +1 -0
  83. package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts +10 -0
  84. package/dist/components/patient/PatientSummary/PatientDetailsForm.d.ts.map +1 -0
  85. package/dist/components/patient/PatientSummary/PatientDetailsForm.js +65 -0
  86. package/dist/components/patient/PatientSummary/PatientDetailsForm.js.map +1 -0
  87. package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts +53 -0
  88. package/dist/components/patient/PatientSummary/PatientDetailsSchema.d.ts.map +1 -0
  89. package/dist/components/patient/PatientSummary/PatientDetailsSchema.js +78 -0
  90. package/dist/components/patient/PatientSummary/PatientDetailsSchema.js.map +1 -0
  91. package/dist/components/patient/PatientSummary/PatientSummary.d.ts +46 -0
  92. package/dist/components/patient/PatientSummary/PatientSummary.d.ts.map +1 -0
  93. package/dist/components/patient/PatientSummary/PatientSummary.js +57 -0
  94. package/dist/components/patient/PatientSummary/PatientSummary.js.map +1 -0
  95. package/dist/components/patient/PatientSummary/SummaryHeader.d.ts +19 -0
  96. package/dist/components/patient/PatientSummary/SummaryHeader.d.ts.map +1 -0
  97. package/dist/components/patient/PatientSummary/SummaryHeader.js +22 -0
  98. package/dist/components/patient/PatientSummary/SummaryHeader.js.map +1 -0
  99. package/dist/components/patient/fields.d.ts +7 -26
  100. package/dist/components/patient/fields.d.ts.map +1 -1
  101. package/dist/components/patient/fields.js +11 -52
  102. package/dist/components/patient/fields.js.map +1 -1
  103. package/dist/components/patient/parsePatientSearchQuery.d.ts +16 -0
  104. package/dist/components/patient/parsePatientSearchQuery.d.ts.map +1 -0
  105. package/dist/components/patient/{query.js → parsePatientSearchQuery.js} +3 -10
  106. package/dist/components/patient/parsePatientSearchQuery.js.map +1 -0
  107. package/dist/components/prescription/PrescriptionCard.d.ts +51 -0
  108. package/dist/components/prescription/PrescriptionCard.d.ts.map +1 -0
  109. package/dist/components/prescription/PrescriptionCard.js +186 -0
  110. package/dist/components/prescription/PrescriptionCard.js.map +1 -0
  111. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts +15 -0
  112. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.d.ts.map +1 -0
  113. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js +18 -0
  114. package/dist/components/prescription/PrescriptionDetailsForm/DirectionsInput.js.map +1 -0
  115. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts +23 -0
  116. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.d.ts.map +1 -0
  117. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js +42 -0
  118. package/dist/components/prescription/PrescriptionDetailsForm/DispenseInputs.js.map +1 -0
  119. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts +27 -0
  120. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.d.ts.map +1 -0
  121. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js +169 -0
  122. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.js.map +1 -0
  123. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts +8 -0
  124. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.d.ts.map +1 -0
  125. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js +12 -0
  126. package/dist/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.js.map +1 -0
  127. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts +11 -0
  128. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.d.ts.map +1 -0
  129. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js +25 -0
  130. package/dist/components/prescription/PrescriptionDetailsForm/TemplatePicker.js.map +1 -0
  131. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts +50 -0
  132. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.d.ts.map +1 -0
  133. package/dist/components/{TreatmentPicker.js → prescription/TreatmentSearch/TreatmentPicker.js} +113 -105
  134. package/dist/components/prescription/TreatmentSearch/TreatmentPicker.js.map +1 -0
  135. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts +28 -0
  136. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.d.ts.map +1 -0
  137. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js +146 -0
  138. package/dist/components/prescription/TreatmentSearch/TreatmentSearch.js.map +1 -0
  139. package/dist/components/schemaErrors.d.ts +13 -0
  140. package/dist/components/schemaErrors.d.ts.map +1 -0
  141. package/dist/components/schemaErrors.js +25 -0
  142. package/dist/components/schemaErrors.js.map +1 -0
  143. package/dist/components/search.d.ts +1 -1
  144. package/dist/components/search.js +1 -1
  145. package/dist/index.d.ts +2 -0
  146. package/dist/index.d.ts.map +1 -1
  147. package/dist/index.js +1 -0
  148. package/dist/index.js.map +1 -1
  149. package/dist/meta/version.d.ts +5 -0
  150. package/dist/meta/version.d.ts.map +1 -0
  151. package/dist/meta/version.js +5 -0
  152. package/dist/meta/version.js.map +1 -0
  153. package/dist/primitives/PhotonProvider.d.ts +3 -1
  154. package/dist/primitives/PhotonProvider.d.ts.map +1 -1
  155. package/dist/primitives/PhotonProvider.js +23 -11
  156. package/dist/primitives/PhotonProvider.js.map +1 -1
  157. package/dist/primitives/defaults.d.ts.map +1 -1
  158. package/dist/primitives/defaults.js +6 -3
  159. package/dist/primitives/defaults.js.map +1 -1
  160. package/dist/primitives/photonContext.d.ts +3 -0
  161. package/dist/primitives/photonContext.d.ts.map +1 -0
  162. package/dist/primitives/photonContext.js +3 -0
  163. package/dist/primitives/photonContext.js.map +1 -0
  164. package/dist/primitives/types.d.ts +15 -3
  165. package/dist/primitives/types.d.ts.map +1 -1
  166. package/dist/primitives/types.js.map +1 -1
  167. package/dist/primitives/useProvidedPhoton.d.ts +8 -0
  168. package/dist/primitives/useProvidedPhoton.d.ts.map +1 -0
  169. package/dist/primitives/useProvidedPhoton.js +8 -0
  170. package/dist/primitives/useProvidedPhoton.js.map +1 -0
  171. package/dist/styles.css +45 -3
  172. package/dist/test-utils/contract.d.ts.map +1 -1
  173. package/dist/test-utils/contract.js +23 -2
  174. package/dist/test-utils/contract.js.map +1 -1
  175. package/package.json +8 -3
  176. package/src/adapters/tailwind.tsx +52 -24
  177. package/src/analytics/PhotonAnalyticsProvider.test.tsx +190 -0
  178. package/src/analytics/PhotonAnalyticsProvider.tsx +151 -0
  179. package/src/analytics/cardLifecycle.test.tsx +272 -0
  180. package/src/analytics/cardLifecycle.ts +44 -0
  181. package/src/analytics/fieldInteraction.test.tsx +186 -0
  182. package/src/analytics/fieldInteraction.tsx +148 -0
  183. package/src/analytics/lifecycleOutcomes.test.ts +78 -0
  184. package/src/analytics/lifecycleOutcomes.ts +29 -0
  185. package/src/analytics/tracker.test.ts +52 -0
  186. package/src/analytics/tracker.ts +49 -0
  187. package/src/analytics/usePhotonAnalytics.test.tsx +106 -0
  188. package/src/analytics/viewed.ts +27 -0
  189. package/src/components/PhotonOrder.test.tsx +394 -0
  190. package/src/components/PhotonOrder.tsx +79 -53
  191. package/src/components/PhotonPatient.tsx +15 -166
  192. package/src/components/PhotonPrescription.test.tsx +120 -0
  193. package/src/components/PhotonPrescription.tsx +23 -583
  194. package/src/components/ScreeningAlerts.test.tsx +81 -0
  195. package/src/components/format.ts +2 -2
  196. package/src/components/index.ts +1 -1
  197. package/src/components/open.ts +13 -16
  198. package/src/components/order/DraftOrderPrompt.test.tsx +77 -0
  199. package/src/components/order/DraftOrderPrompt.tsx +81 -0
  200. package/src/components/patient/PatientCard/PatientCard.test.tsx +255 -0
  201. package/src/components/patient/PatientCard/PatientCard.tsx +177 -0
  202. package/src/components/patient/PatientCard/usePatientToShow.ts +44 -0
  203. package/src/components/patient/PatientIntakeForm.test.tsx +262 -0
  204. package/src/components/patient/PatientIntakeForm.tsx +222 -0
  205. package/src/components/patient/PatientSearch.test.tsx +204 -0
  206. package/src/components/patient/PatientSearch.tsx +221 -0
  207. package/src/components/patient/PatientSummary/BenefitsInputForm.test.tsx +164 -0
  208. package/src/components/patient/{Benefits.tsx → PatientSummary/BenefitsInputForm.tsx} +24 -16
  209. package/src/components/patient/PatientSummary/ClinicalInputForm.test.tsx +247 -0
  210. package/src/components/patient/{Clinical.tsx → PatientSummary/ClinicalInputForm.tsx} +53 -48
  211. package/src/components/patient/PatientSummary/CollapsedSummary.test.tsx +90 -0
  212. package/src/components/patient/PatientSummary/CollapsedSummary.tsx +46 -0
  213. package/src/components/patient/PatientSummary/PatientDetailsForm.test.tsx +201 -0
  214. package/src/components/patient/PatientSummary/PatientDetailsForm.tsx +320 -0
  215. package/src/components/patient/PatientSummary/PatientDetailsSchema.test.ts +296 -0
  216. package/src/components/patient/PatientSummary/PatientDetailsSchema.ts +95 -0
  217. package/src/components/patient/PatientSummary/PatientSummary.test.tsx +194 -0
  218. package/src/components/patient/PatientSummary/PatientSummary.tsx +225 -0
  219. package/src/components/patient/PatientSummary/SummaryHeader.test.tsx +183 -0
  220. package/src/components/patient/PatientSummary/SummaryHeader.tsx +85 -0
  221. package/src/components/patient/fields.tsx +12 -124
  222. package/src/components/patient/parsePatientSearchQuery.test.ts +107 -0
  223. package/src/components/patient/{query.ts → parsePatientSearchQuery.ts} +4 -15
  224. package/src/components/prescription/PrescriptionCard.test.tsx +247 -0
  225. package/src/components/prescription/PrescriptionCard.tsx +361 -0
  226. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.test.tsx +82 -0
  227. package/src/components/prescription/PrescriptionDetailsForm/DirectionsInput.tsx +41 -0
  228. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.test.tsx +206 -0
  229. package/src/components/prescription/PrescriptionDetailsForm/DispenseInputs.tsx +99 -0
  230. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.test.tsx +453 -0
  231. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsForm.tsx +238 -0
  232. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.test.ts +63 -0
  233. package/src/components/prescription/PrescriptionDetailsForm/PrescriptionDetailsSchema.ts +15 -0
  234. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.test.tsx +72 -0
  235. package/src/components/prescription/PrescriptionDetailsForm/TemplatePicker.tsx +41 -0
  236. package/src/components/prescription/TreatmentSearch/TreatmentPicker.tsx +375 -0
  237. package/src/components/prescription/TreatmentSearch/TreatmentSearch.test.tsx +695 -0
  238. package/src/components/prescription/TreatmentSearch/TreatmentSearch.tsx +220 -0
  239. package/src/components/schemaErrors.test.ts +49 -0
  240. package/src/components/schemaErrors.ts +34 -0
  241. package/src/components/search.tsx +1 -1
  242. package/src/index.ts +2 -0
  243. package/src/meta/version.test.ts +11 -0
  244. package/src/meta/version.ts +4 -0
  245. package/src/primitives/PhotonProvider.tsx +30 -15
  246. package/src/primitives/defaults.tsx +44 -21
  247. package/src/primitives/photonContext.ts +4 -0
  248. package/src/primitives/types.ts +15 -3
  249. package/src/primitives/useProvidedPhoton.ts +21 -0
  250. package/src/styles.css +45 -3
  251. package/src/test-utils/contract.tsx +45 -2
  252. package/dist/components/TreatmentPicker.d.ts +0 -45
  253. package/dist/components/TreatmentPicker.d.ts.map +0 -1
  254. package/dist/components/TreatmentPicker.js.map +0 -1
  255. package/dist/components/patient/Benefits.d.ts.map +0 -1
  256. package/dist/components/patient/Benefits.js.map +0 -1
  257. package/dist/components/patient/Clinical.d.ts.map +0 -1
  258. package/dist/components/patient/Clinical.js.map +0 -1
  259. package/dist/components/patient/IntakeForm.d.ts +0 -10
  260. package/dist/components/patient/IntakeForm.d.ts.map +0 -1
  261. package/dist/components/patient/IntakeForm.js +0 -324
  262. package/dist/components/patient/IntakeForm.js.map +0 -1
  263. package/dist/components/patient/Summary.d.ts +0 -48
  264. package/dist/components/patient/Summary.d.ts.map +0 -1
  265. package/dist/components/patient/Summary.js +0 -80
  266. package/dist/components/patient/Summary.js.map +0 -1
  267. package/dist/components/patient/query.d.ts +0 -23
  268. package/dist/components/patient/query.d.ts.map +0 -1
  269. package/dist/components/patient/query.js.map +0 -1
  270. package/src/components/TreatmentPicker.tsx +0 -350
  271. package/src/components/patient/IntakeForm.tsx +0 -532
  272. package/src/components/patient/Summary.tsx +0 -310
@@ -0,0 +1,453 @@
1
+ import type { Prescription, PrescriptionRecord, PrescriptionTemplate, TemplateSource } from "@photonhealth/client";
2
+ import { treatment } from "@photonhealth/client/testing";
3
+ import { fireEvent, render, screen, within } from "@testing-library/react";
4
+ import { describe, expect, it, vi } from "vitest";
5
+ import { PrescriptionDetailsForm, type PrescriptionDetailsFormProps } from "./PrescriptionDetailsForm.tsx";
6
+
7
+ const directions = "Take 1 capsule by mouth 3 times per day";
8
+
9
+ const noDispense = { quantity: null, unit: null, daysSupply: null, refillsAllowed: null, dispenseAsWritten: null };
10
+
11
+ const prescriptionTemplate = (
12
+ source: TemplateSource,
13
+ fields: Partial<Omit<PrescriptionTemplate, "source">> = {},
14
+ ): PrescriptionTemplate => ({
15
+ id: null,
16
+ source,
17
+ name: null,
18
+ instructions: null,
19
+ dispense: null,
20
+ ...fields,
21
+ });
22
+
23
+ const renderFields = ({
24
+ dispense,
25
+ open = true,
26
+ instructions = directions,
27
+ templates = [],
28
+ pickedTemplates = null,
29
+ }: {
30
+ dispense?: Partial<NonNullable<PrescriptionRecord["dispense"]>>;
31
+ open?: boolean;
32
+ instructions?: string | null;
33
+ templates?: PrescriptionTemplate[];
34
+ pickedTemplates?: PrescriptionTemplate[] | null;
35
+ } = {}) => {
36
+ const drug = { ...treatment(), templates: pickedTemplates };
37
+ // PrescriptionDetailsForm reads only these from the live prescription.
38
+ const live = { treatment: drug, entered: {} } as Pick<Prescription, "treatment" | "entered"> as Prescription;
39
+ let record: PrescriptionRecord = {
40
+ id: "rx_1",
41
+ prescriber: null,
42
+ fulfillment: null,
43
+ templateId: null,
44
+ patient: null,
45
+ treatment: drug,
46
+ instructions,
47
+ dispense: {
48
+ quantity: 30,
49
+ unit: "Capsule",
50
+ daysSupply: 10,
51
+ refillsAllowed: 0,
52
+ dispenseAsWritten: false,
53
+ ...dispense,
54
+ },
55
+ clinical: null,
56
+ screeningAlerts: [],
57
+ signing: { state: "UNSIGNED", contentHash: "hash_0", message: null, signedAt: null },
58
+ };
59
+ const save = vi.fn<PrescriptionDetailsFormProps["save"]>();
60
+ const onSign = vi.fn<PrescriptionDetailsFormProps["onSign"]>();
61
+ const props = (): PrescriptionDetailsFormProps => ({
62
+ live,
63
+ rx: record,
64
+ open,
65
+ focusable: false,
66
+ templates,
67
+ spinning: null,
68
+ save,
69
+ onSign,
70
+ signing: false,
71
+ signDisabled: false,
72
+ });
73
+ const { rerender } = render(<PrescriptionDetailsForm {...props()} />);
74
+ return {
75
+ save,
76
+ onSign,
77
+ clickSign: () => fireEvent.click(screen.getByRole("button", { name: "Sign" })),
78
+ setOpen: (isOpen: boolean) => {
79
+ open = isOpen;
80
+ rerender(<PrescriptionDetailsForm {...props()} />);
81
+ },
82
+ // A new contentHash, as Photon gives every changed copy, is what makes the fields take it up.
83
+ receiveDirections: (instructions: string) => {
84
+ record = { ...record, instructions, signing: { ...record.signing, contentHash: "hash_1" } };
85
+ rerender(<PrescriptionDetailsForm {...props()} />);
86
+ },
87
+ };
88
+ };
89
+
90
+ const field = (label: string) => screen.getByLabelText<HTMLInputElement | HTMLTextAreaElement>(label);
91
+
92
+ const type = (label: string, value: string) => fireEvent.change(field(label), { target: { value } });
93
+
94
+ const leave = (label: string) => fireEvent.blur(field(label));
95
+
96
+ const options = () => screen.queryByRole("list", { name: "Templates" });
97
+
98
+ // Directions, quantity and days supply — the fields Sign needs — all empty.
99
+ const empty = { instructions: null, dispense: { quantity: null, daysSupply: null } };
100
+
101
+ const dispenseAsWritten = () => screen.getByRole<HTMLInputElement>("checkbox", { name: "Dispense as written" });
102
+
103
+ describe("PrescriptionDetailsForm", () => {
104
+ describe("showing the prescription", () => {
105
+ it("shows the stored directions and dispense", () => {
106
+ renderFields();
107
+ expect(field("Directions (sig)").value).toBe(directions);
108
+ expect(field("Quantity").value).toBe("30");
109
+ expect(field("Unit").value).toBe("Capsule");
110
+ expect(field("Days supply").value).toBe("10");
111
+ expect(field("Refills").value).toBe("0");
112
+ expect(dispenseAsWritten().checked).toBe(false);
113
+ });
114
+ });
115
+
116
+ describe("saving edits", () => {
117
+ it("saves only the changed field when I leave the field", () => {
118
+ const { save } = renderFields();
119
+ type("Directions (sig)", "Take 1 capsule by mouth daily");
120
+ leave("Directions (sig)");
121
+ expect(save).toHaveBeenCalledExactlyOnceWith({ instructions: "Take 1 capsule by mouth daily" }, "instructions");
122
+ });
123
+
124
+ it("doesn't save field that is unchanged when I leave the field", () => {
125
+ const { save } = renderFields();
126
+ type("Directions (sig)", "Take 1 capsule by mouth daily");
127
+ type("Directions (sig)", directions);
128
+ leave("Directions (sig)");
129
+ expect(save).not.toHaveBeenCalled();
130
+ });
131
+
132
+ it.each([
133
+ ["Quantity", "sd"],
134
+ ["Quantity", "0"],
135
+ ["Quantity", ""],
136
+ ["Days supply", "abc"],
137
+ ["Days supply", "-1"],
138
+ ["Directions (sig)", " "],
139
+ ])("doesn't save %s of %j: it isn't valid, so it's never sent", (label, value) => {
140
+ const { save } = renderFields();
141
+ type(label, value);
142
+ leave(label);
143
+ expect(save).not.toHaveBeenCalled();
144
+ });
145
+
146
+ it("saves a field once it's valid again", () => {
147
+ const { save } = renderFields();
148
+ type("Quantity", "sd");
149
+ leave("Quantity");
150
+ type("Quantity", "45");
151
+ leave("Quantity");
152
+ expect(save).toHaveBeenCalledExactlyOnceWith({ dispense: { quantity: 45 } }, "quantity");
153
+ });
154
+
155
+ it("saves a valid field while another field isn't valid", () => {
156
+ const { save } = renderFields({ dispense: { daysSupply: null } });
157
+ type("Quantity", "60");
158
+ leave("Quantity");
159
+ expect(save).toHaveBeenCalledExactlyOnceWith({ dispense: { quantity: 60 } }, "quantity");
160
+ });
161
+
162
+ it('saves "Dispense as written" and keeps it checked', () => {
163
+ const { save } = renderFields();
164
+ fireEvent.click(dispenseAsWritten());
165
+ expect(save).toHaveBeenCalledExactlyOnceWith({ dispense: { dispenseAsWritten: true } }, "daw");
166
+ expect(dispenseAsWritten().checked).toBe(true);
167
+ });
168
+ });
169
+
170
+ describe("dispense units", () => {
171
+ it("offers the units the recommended templates set", () => {
172
+ renderFields({
173
+ templates: [
174
+ prescriptionTemplate("RECOMMENDED", {
175
+ instructions: "Take 1 capsule by mouth daily",
176
+ dispense: { ...noDispense, unit: "Capsule" },
177
+ }),
178
+ prescriptionTemplate("RECOMMENDED", { dispense: { ...noDispense, unit: "Bottle" } }),
179
+ ],
180
+ });
181
+ const options = within(screen.getByRole("combobox", { name: "Unit" })).getAllByRole<HTMLOptionElement>("option");
182
+ expect(options.filter((option) => !option.disabled).map((option) => option.textContent)).toEqual([
183
+ "Capsule",
184
+ "Bottle",
185
+ ]);
186
+ });
187
+
188
+ it("doesn't offer a catalog template's unit", () => {
189
+ renderFields({
190
+ templates: [
191
+ prescriptionTemplate("ORG_CATALOG", { id: "tmp_1", dispense: { ...noDispense, unit: "Pack" } }),
192
+ prescriptionTemplate("RECOMMENDED", { dispense: { ...noDispense, unit: "Capsule" } }),
193
+ ],
194
+ });
195
+ const options = within(screen.getByRole("combobox", { name: "Unit" })).getAllByRole<HTMLOptionElement>("option");
196
+ expect(options.filter((option) => !option.disabled).map((option) => option.textContent)).toEqual(["Capsule"]);
197
+ });
198
+
199
+ it("offers the picked drug's units before the draft's templates load", () => {
200
+ const { save } = renderFields({
201
+ dispense: { unit: null },
202
+ pickedTemplates: [prescriptionTemplate("RECOMMENDED", { dispense: { ...noDispense, unit: "Capsule" } })],
203
+ });
204
+ expect(field("Unit").value).toBe("Capsule");
205
+ expect(save).toHaveBeenCalledExactlyOnceWith({ dispense: { unit: "Capsule" } }, "unit");
206
+ });
207
+
208
+ it("fills in and saves the first recommended unit when there's no unit", () => {
209
+ const { save } = renderFields({
210
+ dispense: { unit: null },
211
+ templates: [
212
+ prescriptionTemplate("RECOMMENDED", { dispense: { ...noDispense, unit: "Capsule" } }),
213
+ prescriptionTemplate("RECOMMENDED", { dispense: { ...noDispense, unit: "Bottle" } }),
214
+ ],
215
+ });
216
+ expect(field("Unit").value).toBe("Capsule");
217
+ expect(save).toHaveBeenCalledExactlyOnceWith({ dispense: { unit: "Capsule" } }, "unit");
218
+ });
219
+ });
220
+
221
+ describe("updates from Photon", () => {
222
+ it("doesn't replace directions being typed", () => {
223
+ const { receiveDirections } = renderFields();
224
+ type("Directions (sig)", "Take 2 capsules");
225
+ receiveDirections("Take as directed");
226
+ expect(field("Directions (sig)").value).toBe("Take 2 capsules");
227
+ });
228
+
229
+ it("show in a field that isn't being edited", () => {
230
+ const { receiveDirections } = renderFields();
231
+ receiveDirections("Take as directed");
232
+ expect(field("Directions (sig)").value).toBe("Take as directed");
233
+ });
234
+ });
235
+
236
+ describe("template options", () => {
237
+ it("offers ORG_CATALOG, PERSONAL_CATALOG, and RECOMMENDED templates", () => {
238
+ renderFields({
239
+ instructions: null,
240
+ templates: [
241
+ prescriptionTemplate("PERSONAL_CATALOG", { id: "tmp_1", name: "My sinusitis" }),
242
+ prescriptionTemplate("ORG_CATALOG", { id: "tmp_2", name: "Sinusitis" }),
243
+ prescriptionTemplate("RECOMMENDED", { instructions: "Take 1 capsule by mouth daily" }),
244
+ ],
245
+ });
246
+ const offered = within(options()!)
247
+ .getAllByRole("button")
248
+ .map((button) => button.textContent);
249
+ expect(offered).toEqual(["My sinusitis", "Sinusitis", "Take 1 capsule by mouth daily"]);
250
+ });
251
+
252
+ it("doesn't offer a unit-only RECOMMENDED template as a template option", () => {
253
+ renderFields({
254
+ instructions: null,
255
+ templates: [
256
+ prescriptionTemplate("RECOMMENDED", { instructions: "Take 1 capsule by mouth daily" }),
257
+ prescriptionTemplate("RECOMMENDED", { dispense: { ...noDispense, unit: "Bottle" } }),
258
+ ],
259
+ });
260
+ const offered = within(options()!)
261
+ .getAllByRole("button")
262
+ .map((button) => button.textContent);
263
+ expect(offered).toEqual(["Take 1 capsule by mouth daily"]);
264
+ });
265
+
266
+ it("uses unit-only RECOMMENDED templates to populate dispense unit options", () => {
267
+ renderFields({
268
+ instructions: null,
269
+ templates: [
270
+ prescriptionTemplate("RECOMMENDED", { instructions: "Take 1 capsule by mouth daily" }),
271
+ prescriptionTemplate("RECOMMENDED", { dispense: { ...noDispense, unit: "Bottle" } }),
272
+ ],
273
+ });
274
+ const units = within(screen.getByRole("combobox", { name: "Unit" })).getAllByRole<HTMLOptionElement>("option");
275
+ expect(units.filter((unit) => !unit.disabled).map((unit) => unit.textContent)).toContain("Bottle");
276
+ });
277
+
278
+ it("fills in and saves the option I choose", () => {
279
+ const { save } = renderFields({
280
+ instructions: null,
281
+ templates: [prescriptionTemplate("RECOMMENDED", { instructions: "Take 1 capsule by mouth daily" })],
282
+ });
283
+ fireEvent.click(screen.getByRole("button", { name: "Take 1 capsule by mouth daily" }));
284
+ expect(field("Directions (sig)").value).toBe("Take 1 capsule by mouth daily");
285
+ expect(save).toHaveBeenCalledExactlyOnceWith({ instructions: "Take 1 capsule by mouth daily" }, "instructions");
286
+ });
287
+
288
+ // A dispense value the new option leaves empty keeps the previous option's: network-api can't clear
289
+ // quantity or unit on a draft (TECH-1247)
290
+ it("replaces the directions and the dispense values it sets when I choose another option", () => {
291
+ const once = prescriptionTemplate("RECOMMENDED", {
292
+ instructions: "Take 1 capsule by mouth daily",
293
+ dispense: { ...noDispense, quantity: 30, unit: "Capsule", daysSupply: 30 },
294
+ });
295
+ const twice = prescriptionTemplate("RECOMMENDED", {
296
+ instructions: "Take 1 capsule by mouth 2 times per day",
297
+ dispense: { ...noDispense, quantity: 60, unit: "Capsule", daysSupply: 30 },
298
+ });
299
+ const { save } = renderFields({ instructions: null, templates: [once, twice] });
300
+ fireEvent.click(screen.getByRole("button", { name: "Take 1 capsule by mouth daily" }));
301
+ fireEvent.click(screen.getByRole("button", { name: "Templates" }));
302
+ fireEvent.click(screen.getByRole("button", { name: "Take 1 capsule by mouth 2 times per day" }));
303
+
304
+ expect(field("Directions (sig)").value).toBe("Take 1 capsule by mouth 2 times per day");
305
+ expect(field("Quantity").value).toBe("60");
306
+ expect(field("Days supply").value).toBe("30");
307
+ expect(save).toHaveBeenLastCalledWith(
308
+ {
309
+ instructions: "Take 1 capsule by mouth 2 times per day",
310
+ dispense: { quantity: 60, unit: "Capsule", daysSupply: 30 },
311
+ },
312
+ "instructions",
313
+ );
314
+ });
315
+
316
+ it("fills in and saves every field a catalog template sets, in one save, and leaves the rest alone", () => {
317
+ const catalog = prescriptionTemplate("ORG_CATALOG", {
318
+ id: "tmp_1",
319
+ name: "Sinusitis",
320
+ instructions: "Take 1 capsule by mouth twice daily for 10 days",
321
+ dispense: { ...noDispense, quantity: 20, daysSupply: 10 },
322
+ });
323
+ const { save } = renderFields({ instructions: null, templates: [catalog] });
324
+
325
+ fireEvent.click(screen.getByRole("button", { name: /Sinusitis/ }));
326
+
327
+ expect(field("Directions (sig)").value).toBe("Take 1 capsule by mouth twice daily for 10 days");
328
+ expect(field("Quantity").value).toBe("20");
329
+ expect(field("Days supply").value).toBe("10");
330
+ expect(field("Unit").value).toBe("Capsule");
331
+ expect(save).toHaveBeenCalledExactlyOnceWith(
332
+ { instructions: "Take 1 capsule by mouth twice daily for 10 days", dispense: { quantity: 20, daysSupply: 10 } },
333
+ "instructions",
334
+ );
335
+ });
336
+
337
+ it("hides the options once I choose one", () => {
338
+ renderFields({
339
+ instructions: null,
340
+ templates: [prescriptionTemplate("RECOMMENDED", { instructions: "Take 1 capsule by mouth daily" })],
341
+ });
342
+ fireEvent.click(screen.getByRole("button", { name: "Take 1 capsule by mouth daily" }));
343
+ expect(options()).toBeNull();
344
+ });
345
+
346
+ it("shows the templates above the directions", () => {
347
+ renderFields({
348
+ instructions: null,
349
+ templates: [prescriptionTemplate("RECOMMENDED", { instructions: "Take 1 capsule by mouth daily" })],
350
+ });
351
+ const templates = screen.getByRole("button", { name: "Templates" });
352
+ expect(
353
+ templates.compareDocumentPosition(field("Directions (sig)")) & Node.DOCUMENT_POSITION_FOLLOWING,
354
+ ).toBeTruthy();
355
+ });
356
+
357
+ it("lets me edit directions after I choose a template", () => {
358
+ const { save } = renderFields({
359
+ instructions: null,
360
+ templates: [prescriptionTemplate("RECOMMENDED", { instructions: "Take 1 capsule by mouth daily" })],
361
+ });
362
+ fireEvent.click(screen.getByRole("button", { name: "Take 1 capsule by mouth daily" }));
363
+ type("Directions (sig)", "Take 1 capsule by mouth daily with food");
364
+ leave("Directions (sig)");
365
+ expect(save).toHaveBeenLastCalledWith(
366
+ { instructions: "Take 1 capsule by mouth daily with food" },
367
+ "instructions",
368
+ );
369
+ });
370
+ });
371
+
372
+ describe("field validation", () => {
373
+ const isInvalid = (label: string) => field(label).getAttribute("aria-invalid") === "true";
374
+ // Get error message for the field with `label`
375
+ const errorOf = (label: string) => {
376
+ if (!isInvalid(label)) return null;
377
+ const note = field(label).getAttribute("aria-describedby");
378
+ return note ? document.getElementById(note)?.textContent : null;
379
+ };
380
+
381
+ it("shows no validation errors before Sign is clicked", () => {
382
+ renderFields(empty);
383
+ expect(isInvalid("Directions (sig)")).toBe(false);
384
+ expect(isInvalid("Quantity")).toBe(false);
385
+ expect(isInvalid("Days supply")).toBe(false);
386
+ expect(screen.queryByText("Required")).toBeNull();
387
+ });
388
+
389
+ it("on Sign, shows errors for directions, quantity and days supply when they're empty", () => {
390
+ const { clickSign } = renderFields(empty);
391
+ clickSign();
392
+ expect(errorOf("Directions (sig)")).toBe("Required");
393
+ expect(errorOf("Quantity")).toBe("Required");
394
+ expect(errorOf("Days supply")).toBe("Required");
395
+ });
396
+
397
+ it("on Sign, shows no errors for unit and refills", () => {
398
+ const { clickSign } = renderFields({ ...empty, dispense: { ...empty.dispense, refillsAllowed: null } });
399
+ clickSign();
400
+ expect(isInvalid("Unit")).toBe(false);
401
+ expect(isInvalid("Refills")).toBe(false);
402
+ });
403
+
404
+ it("on Sign, shows no errors when every required field is valid", () => {
405
+ const { clickSign } = renderFields();
406
+ clickSign();
407
+ expect(isInvalid("Directions (sig)")).toBe(false);
408
+ expect(isInvalid("Quantity")).toBe(false);
409
+ expect(isInvalid("Days supply")).toBe(false);
410
+ });
411
+
412
+ it("clears a field's error once it's valid, and keeps the others'", () => {
413
+ const { clickSign } = renderFields(empty);
414
+ clickSign();
415
+ type("Quantity", "30");
416
+ expect(isInvalid("Quantity")).toBe(false);
417
+ expect(errorOf("Days supply")).toBe("Required");
418
+ expect(errorOf("Directions (sig)")).toBe("Required");
419
+ });
420
+
421
+ it("shows a field's new error when its value changes to another invalid one", () => {
422
+ const { clickSign } = renderFields({ dispense: { quantity: null } });
423
+ clickSign();
424
+ expect(errorOf("Quantity")).toBe("Required");
425
+ type("Quantity", "0");
426
+ expect(errorOf("Quantity")).toBe("Must be greater than 0");
427
+ });
428
+ });
429
+
430
+ describe("clicking Sign", () => {
431
+ it("doesn't add while a field has an error", () => {
432
+ const { clickSign, onSign } = renderFields({ dispense: { daysSupply: null } });
433
+ clickSign();
434
+ expect(onSign).not.toHaveBeenCalled();
435
+ });
436
+
437
+ it("adds once every field is valid", () => {
438
+ const { clickSign, onSign } = renderFields(empty);
439
+ clickSign();
440
+ type("Directions (sig)", directions);
441
+ type("Quantity", "30");
442
+ type("Days supply", "10");
443
+ clickSign();
444
+ expect(onSign).toHaveBeenCalledOnce();
445
+ });
446
+
447
+ it("adds at once when the prescription already has every required field", () => {
448
+ const { clickSign, onSign } = renderFields();
449
+ clickSign();
450
+ expect(onSign).toHaveBeenCalledOnce();
451
+ });
452
+ });
453
+ });
@@ -0,0 +1,238 @@
1
+ import type { Prescription, PrescriptionEdits, PrescriptionRecord, PrescriptionTemplate } from "@photonhealth/client";
2
+ import { useLatestCallback } from "../../../hooks/index.ts";
3
+ import { useComponents } from "../../../primitives/index.ts";
4
+ import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
5
+ import { schemaErrors } from "../../schemaErrors.ts";
6
+ import { DirectionsInput } from "./DirectionsInput.tsx";
7
+ import { DispenseInputs, type DispenseField, type DispensePatch } from "./DispenseInputs.tsx";
8
+ import { PrescriptionDetailsSchema } from "./PrescriptionDetailsSchema.ts";
9
+ import { TemplatePicker } from "./TemplatePicker.tsx";
10
+
11
+ export interface PrescriptionDetailsFormProps {
12
+ live: Prescription | null;
13
+ rx: PrescriptionRecord | null;
14
+ /** Once a drug is set. Kept mounted while closed, so what's typed survives a drug being chosen. */
15
+ open: boolean;
16
+ /** Where the card flow (← / →) lands, when Treatment isn't. */
17
+ focusable: boolean;
18
+ /**
19
+ * The draft's templates: those with a name or directions are offered as templates; the recommended
20
+ * ones' units are the units offered.
21
+ */
22
+ templates: readonly PrescriptionTemplate[];
23
+ /** The field whose save is in flight. */
24
+ spinning: string | null;
25
+ save: (edits: PrescriptionEdits, from?: string) => void;
26
+ /** Beside Sign: the prescription's status (e.g. changed since signing). */
27
+ status?: ReactNode;
28
+ /** Sign, once every field is valid: the card signs it. */
29
+ onSign: () => void;
30
+ /** The add is in flight. */
31
+ signing: boolean;
32
+ signDisabled: boolean;
33
+ }
34
+
35
+ export function PrescriptionDetailsForm({
36
+ live,
37
+ rx,
38
+ open,
39
+ focusable,
40
+ templates,
41
+ spinning,
42
+ save,
43
+ status,
44
+ onSign,
45
+ signing,
46
+ signDisabled,
47
+ }: PrescriptionDetailsFormProps) {
48
+ const { Button, CardBody, CardFooter, Stack } = useComponents();
49
+ const [instructions, setInstructions] = useState(rx?.instructions ?? "");
50
+ const [quantity, setQuantity] = useState(rx?.dispense?.quantity?.toString() ?? "");
51
+ const [unit, setUnit] = useState(rx?.dispense?.unit ?? "");
52
+ const [daysSupply, setDaysSupply] = useState(rx?.dispense?.daysSupply?.toString() ?? "");
53
+ const [refills, setRefills] = useState(rx?.dispense?.refillsAllowed?.toString() ?? "");
54
+ const [daw, setDaw] = useState(rx?.dispense?.dispenseAsWritten ?? false);
55
+ // Fields edited but not yet saved. A server copy (a save's response, a hydrate) never overwrites
56
+ // them — otherwise a response landing mid-typing replaces what the prescriber is entering.
57
+ const [dirty, setDirty] = useState<ReadonlySet<string>>(new Set());
58
+ const edit = (field: string) => setDirty((d) => (d.has(field) ? d : new Set(d).add(field)));
59
+ const clean = (field: string) =>
60
+ setDirty((d) => {
61
+ if (!d.has(field)) return d;
62
+ const next = new Set(d);
63
+ next.delete(field);
64
+ return next;
65
+ });
66
+
67
+ // When the server's copy changes (a hydrate, a chosen option, signing), show its version.
68
+ // Adjusted during render, keyed on id + contentHash — React's pattern for deriving state from props.
69
+ const serverKey = rx ? `${rx.id}:${rx.signing.contentHash}:${rx.signing.state}` : null;
70
+ const [syncedKey, setSyncedKey] = useState(serverKey);
71
+ if (rx && serverKey !== syncedKey) {
72
+ setSyncedKey(serverKey);
73
+ if (!dirty.has("instructions")) setInstructions(rx.instructions ?? "");
74
+ if (!dirty.has("quantity")) setQuantity(rx.dispense?.quantity?.toString() ?? "");
75
+ if (!dirty.has("unit")) setUnit(rx.dispense?.unit ?? "");
76
+ if (!dirty.has("daysSupply")) setDaysSupply(rx.dispense?.daysSupply?.toString() ?? "");
77
+ if (!dirty.has("refills")) setRefills(rx.dispense?.refillsAllowed?.toString() ?? "");
78
+ setDaw(rx.dispense?.dispenseAsWritten ?? false);
79
+ }
80
+
81
+ // A line without a record shows what's entered on it — e.g. given as props (a sig): once per object.
82
+ const [filledFrom, setFilledFrom] = useState<Prescription | null>(null);
83
+ if (live && live !== filledFrom) {
84
+ setFilledFrom(live);
85
+ const { instructions: sig, dispense: d } = rx ? {} : live.entered;
86
+ const shown: [value: string | undefined, set: (value: string) => void][] = [
87
+ [sig, setInstructions],
88
+ [d?.quantity?.toString(), setQuantity],
89
+ [d?.unit, setUnit],
90
+ [d?.daysSupply?.toString(), setDaysSupply],
91
+ [d?.refillsAllowed?.toString(), setRefills],
92
+ ];
93
+ for (const [value, set] of shown) if (value) set(value);
94
+ if (d?.dispenseAsWritten) setDaw(true);
95
+ }
96
+
97
+ // What's wrong with the fields: shown once Sign is clicked (and following the values from then on), and never sent.
98
+ const [showErrors, setShowErrors] = useState(false);
99
+ const errors = schemaErrors(PrescriptionDetailsSchema, { instructions, quantity, daysSupply });
100
+ const shown = showErrors ? errors : {};
101
+ const invalid = (field: string) => field in errors;
102
+
103
+ // Patch only the field that changed (network-api merges a partial dispense); sending the whole
104
+ // block from the screen could write stale values over newer ones.
105
+ const dispense = (field: string, patch: DispensePatch) => {
106
+ clean(field);
107
+ if (patch.dispenseAsWritten !== undefined) setDaw(patch.dispenseAsWritten);
108
+ if (!invalid(field)) save({ dispense: patch }, field);
109
+ };
110
+
111
+ // Memoized so typing doesn't hand DirectionsInput new options, which would reopen them.
112
+ const choosableTemplates = useMemo(
113
+ () => templates.filter((template) => template.name || template.instructions),
114
+ [templates],
115
+ );
116
+ // The picked drug's own templates say its units before the draft's templates load
117
+ const pickedTemplates = live?.treatment?.templates;
118
+ const units = useMemo(
119
+ () => recommendedUnits([...templates, ...(pickedTemplates ?? [])]),
120
+ [templates, pickedTemplates],
121
+ );
122
+ // The first of them is the unit until the prescriber picks another — never left blank. Saved once per drug: a response without it shows it again, but doesn't send it again.
123
+ const unitsFor = units.join("|");
124
+ const unitSavedFor = useRef<string | null>(null);
125
+ const fillUnit = useLatestCallback(() => {
126
+ if (!open || !units.length || unit.trim()) return;
127
+ setUnit(units[0]!);
128
+ if (unitSavedFor.current === unitsFor) return;
129
+ unitSavedFor.current = unitsFor;
130
+ dispense("unit", { unit: units[0]! });
131
+ });
132
+ useEffect(() => fillUnit(), [unitsFor, unit, open, fillUnit]);
133
+
134
+ // A template overwrites the fields it sets and leaves the rest alone, saved together in one call.
135
+ const chooseTemplate = (template: PrescriptionTemplate) => {
136
+ const chosen: [field: string, value: string, set: (value: string) => void][] = [];
137
+ if (template.instructions !== null) chosen.push(["instructions", template.instructions, setInstructions]);
138
+ const d = template.dispense;
139
+ if (d?.quantity != null) chosen.push(["quantity", d.quantity.toString(), setQuantity]);
140
+ if (d?.unit != null) chosen.push(["unit", d.unit, setUnit]);
141
+ if (d?.daysSupply != null) chosen.push(["daysSupply", d.daysSupply.toString(), setDaysSupply]);
142
+ if (d?.refillsAllowed != null) chosen.push(["refills", d.refillsAllowed.toString(), setRefills]);
143
+ for (const [field, value, set] of chosen) {
144
+ set(value);
145
+ clean(field);
146
+ }
147
+ if (d?.dispenseAsWritten != null) setDaw(d.dispenseAsWritten);
148
+
149
+ const dispensePatch: DispensePatch = {
150
+ ...(d?.quantity != null && { quantity: d.quantity }),
151
+ ...(d?.unit != null && { unit: d.unit }),
152
+ ...(d?.daysSupply != null && { daysSupply: d.daysSupply }),
153
+ ...(d?.refillsAllowed != null && { refillsAllowed: d.refillsAllowed }),
154
+ ...(d?.dispenseAsWritten != null && { dispenseAsWritten: d.dispenseAsWritten }),
155
+ };
156
+ const edits: PrescriptionEdits = {
157
+ ...(template.instructions !== null &&
158
+ template.instructions !== (rx?.instructions ?? "") && { instructions: template.instructions }),
159
+ ...(Object.keys(dispensePatch).length > 0 && { dispense: dispensePatch }),
160
+ };
161
+ if (Object.keys(edits).length > 0) save(edits, "instructions");
162
+ };
163
+
164
+ if (!open) return null;
165
+ const setters: Record<DispenseField, (value: string) => void> = {
166
+ quantity: setQuantity,
167
+ unit: setUnit,
168
+ daysSupply: setDaysSupply,
169
+ refills: setRefills,
170
+ };
171
+ const dispenseValues = { quantity, unit, daysSupply, refills, dispenseAsWritten: daw };
172
+ const dispenseFields = Object.keys(setters) as DispenseField[];
173
+ return (
174
+ <>
175
+ <CardBody>
176
+ <Stack gap="4">
177
+ <TemplatePicker
178
+ templates={choosableTemplates}
179
+ hasDirections={instructions.trim() !== ""}
180
+ onChoose={chooseTemplate}
181
+ />
182
+ <DirectionsInput
183
+ value={instructions}
184
+ errorMessage={shown.instructions}
185
+ edited={dirty.has("instructions")}
186
+ focusable={focusable}
187
+ onEdit={(value) => {
188
+ setInstructions(value);
189
+ edit("instructions");
190
+ }}
191
+ onCommit={() => {
192
+ clean("instructions");
193
+ if (!invalid("instructions") && instructions !== (rx?.instructions ?? ""))
194
+ save({ instructions }, "instructions");
195
+ }}
196
+ />
197
+ <DispenseInputs
198
+ values={dispenseValues}
199
+ errors={shown}
200
+ units={units}
201
+ edited={new Set(dispenseFields.filter((field) => dirty.has(field)))}
202
+ spinning={spinning}
203
+ onEdit={(field, value) => {
204
+ setters[field](value);
205
+ edit(field);
206
+ }}
207
+ save={dispense}
208
+ />
209
+ </Stack>
210
+ </CardBody>
211
+ <CardFooter start={status}>
212
+ <Button
213
+ variant="secondary" // Send is the page's one primary action
214
+ // Not disabled while saving: clicking Sign leaves a field, which saves it — the sign waits
215
+ // for that save (a disabled button would swallow the click).
216
+ loading={signing}
217
+ disabled={signDisabled}
218
+ onClick={() => {
219
+ setShowErrors(true);
220
+ if (Object.keys(errors).length === 0) onSign();
221
+ }}
222
+ >
223
+ Sign
224
+ </Button>
225
+ </CardFooter>
226
+ </>
227
+ );
228
+ }
229
+
230
+ // The units the recommended templates set — a recommended sig's, then the unit-only ones — in the server's order.
231
+ const recommendedUnits = (templates: readonly PrescriptionTemplate[]): string[] => [
232
+ ...new Set(
233
+ templates
234
+ .filter((template) => template.source === "RECOMMENDED")
235
+ .map((template) => template.dispense?.unit)
236
+ .filter((unit): unit is string => Boolean(unit)),
237
+ ),
238
+ ];