@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.
- package/LICENSE +15 -0
- package/README.md +234 -2
- package/dist/analytics/lifecycleEvents.d.ts +29 -0
- package/dist/analytics/lifecycleEvents.d.ts.map +1 -0
- package/dist/analytics/lifecycleEvents.js +72 -0
- package/dist/analytics/lifecycleEvents.js.map +1 -0
- package/dist/api/changes/applyOption.d.ts +41 -0
- package/dist/api/changes/applyOption.d.ts.map +1 -0
- package/dist/api/changes/applyOption.js +76 -0
- package/dist/api/changes/applyOption.js.map +1 -0
- package/dist/api/changes/classifyChanges.d.ts +9 -0
- package/dist/api/changes/classifyChanges.d.ts.map +1 -0
- package/dist/api/changes/classifyChanges.js +2 -0
- package/dist/api/changes/classifyChanges.js.map +1 -0
- package/dist/api/changes/index.d.ts +3 -0
- package/dist/api/changes/index.d.ts.map +1 -0
- package/dist/api/changes/index.js +3 -0
- package/dist/api/changes/index.js.map +1 -0
- package/dist/api/client.d.ts +48 -0
- package/dist/api/client.d.ts.map +1 -0
- package/dist/api/client.js +91 -0
- package/dist/api/client.js.map +1 -0
- package/dist/api/health.d.ts +4 -0
- package/dist/api/health.d.ts.map +1 -0
- package/dist/api/health.js +6 -0
- package/dist/api/health.js.map +1 -0
- package/dist/api/index.d.ts +24 -0
- package/dist/api/index.d.ts.map +1 -0
- package/dist/api/index.js +23 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/me.d.ts +37 -0
- package/dist/api/me.d.ts.map +1 -0
- package/dist/api/me.js +6 -0
- package/dist/api/me.js.map +1 -0
- package/dist/api/order.d.ts +33 -0
- package/dist/api/order.d.ts.map +1 -0
- package/dist/api/order.js +33 -0
- package/dist/api/order.js.map +1 -0
- package/dist/api/orders.d.ts +1047 -0
- package/dist/api/orders.d.ts.map +1 -0
- package/dist/api/orders.js +7 -0
- package/dist/api/orders.js.map +1 -0
- package/dist/api/patient.d.ts +36 -0
- package/dist/api/patient.d.ts.map +1 -0
- package/dist/api/patient.js +33 -0
- package/dist/api/patient.js.map +1 -0
- package/dist/api/prescription.d.ts +37 -0
- package/dist/api/prescription.d.ts.map +1 -0
- package/dist/api/prescription.js +39 -0
- package/dist/api/prescription.js.map +1 -0
- package/dist/api/results.d.ts +30 -0
- package/dist/api/results.d.ts.map +1 -0
- package/dist/api/results.js +26 -0
- package/dist/api/results.js.map +1 -0
- package/dist/gql/gql.d.ts +29 -0
- package/dist/gql/gql.d.ts.map +1 -0
- package/dist/gql/gql.js +15 -0
- package/dist/gql/gql.js.map +1 -0
- package/dist/gql/graphql.d.ts +18618 -0
- package/dist/gql/graphql.d.ts.map +1 -0
- package/dist/gql/graphql.js +6579 -0
- package/dist/gql/graphql.js.map +1 -0
- package/dist/gql/index.d.ts +2 -0
- package/dist/gql/index.d.ts.map +1 -0
- package/dist/gql/index.js +3 -0
- package/dist/gql/index.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/meta/version.d.ts +2 -0
- package/dist/meta/version.d.ts.map +1 -0
- package/dist/meta/version.js +2 -0
- package/dist/meta/version.js.map +1 -0
- package/dist/photon/analytics.d.ts +39 -0
- package/dist/photon/analytics.d.ts.map +1 -0
- package/dist/photon/analytics.js +91 -0
- package/dist/photon/analytics.js.map +1 -0
- package/dist/photon/auth.d.ts +52 -0
- package/dist/photon/auth.d.ts.map +1 -0
- package/dist/photon/auth.js +30 -0
- package/dist/photon/auth.js.map +1 -0
- package/dist/photon/choices.d.ts +44 -0
- package/dist/photon/choices.d.ts.map +1 -0
- package/dist/photon/choices.js +58 -0
- package/dist/photon/choices.js.map +1 -0
- package/dist/photon/context.d.ts +29 -0
- package/dist/photon/context.d.ts.map +1 -0
- package/dist/photon/context.js +2 -0
- package/dist/photon/context.js.map +1 -0
- package/dist/photon/environments.d.ts +27 -0
- package/dist/photon/environments.d.ts.map +1 -0
- package/dist/photon/environments.js +27 -0
- package/dist/photon/environments.js.map +1 -0
- package/dist/photon/errors.d.ts +26 -0
- package/dist/photon/errors.d.ts.map +1 -0
- package/dist/photon/errors.js +42 -0
- package/dist/photon/errors.js.map +1 -0
- package/dist/photon/index.d.ts +26 -0
- package/dist/photon/index.d.ts.map +1 -0
- package/dist/photon/index.js +12 -0
- package/dist/photon/index.js.map +1 -0
- package/dist/photon/inputs.d.ts +7 -0
- package/dist/photon/inputs.d.ts.map +1 -0
- package/dist/photon/inputs.js +25 -0
- package/dist/photon/inputs.js.map +1 -0
- package/dist/photon/links.d.ts +68 -0
- package/dist/photon/links.d.ts.map +1 -0
- package/dist/photon/links.js +187 -0
- package/dist/photon/links.js.map +1 -0
- package/dist/photon/live.d.ts +62 -0
- package/dist/photon/live.d.ts.map +1 -0
- package/dist/photon/live.js +107 -0
- package/dist/photon/live.js.map +1 -0
- package/dist/photon/machine.d.ts +28 -0
- package/dist/photon/machine.d.ts.map +1 -0
- package/dist/photon/machine.js +53 -0
- package/dist/photon/machine.js.map +1 -0
- package/dist/photon/map.d.ts +14 -0
- package/dist/photon/map.d.ts.map +1 -0
- package/dist/photon/map.js +311 -0
- package/dist/photon/map.js.map +1 -0
- package/dist/photon/order.d.ts +168 -0
- package/dist/photon/order.d.ts.map +1 -0
- package/dist/photon/order.js +558 -0
- package/dist/photon/order.js.map +1 -0
- package/dist/photon/orders.d.ts +5 -0
- package/dist/photon/orders.d.ts.map +1 -0
- package/dist/photon/orders.js +39 -0
- package/dist/photon/orders.js.map +1 -0
- package/dist/photon/patient.d.ts +80 -0
- package/dist/photon/patient.d.ts.map +1 -0
- package/dist/photon/patient.js +347 -0
- package/dist/photon/patient.js.map +1 -0
- package/dist/photon/photon.d.ts +188 -0
- package/dist/photon/photon.d.ts.map +1 -0
- package/dist/photon/photon.js +395 -0
- package/dist/photon/photon.js.map +1 -0
- package/dist/photon/prescription.d.ts +145 -0
- package/dist/photon/prescription.d.ts.map +1 -0
- package/dist/photon/prescription.js +418 -0
- package/dist/photon/prescription.js.map +1 -0
- package/dist/photon/session.d.ts +89 -0
- package/dist/photon/session.d.ts.map +1 -0
- package/dist/photon/session.js +352 -0
- package/dist/photon/session.js.map +1 -0
- package/dist/photon/types.d.ts +643 -0
- package/dist/photon/types.d.ts.map +1 -0
- package/dist/photon/types.js +7 -0
- package/dist/photon/types.js.map +1 -0
- package/dist/test-utils/msw.d.ts +23 -0
- package/dist/test-utils/msw.d.ts.map +1 -0
- package/dist/test-utils/msw.js +51 -0
- package/dist/test-utils/msw.js.map +1 -0
- package/dist/testing/fakeNetworkApiClient.d.ts +39 -0
- package/dist/testing/fakeNetworkApiClient.d.ts.map +1 -0
- package/dist/testing/fakeNetworkApiClient.js +56 -0
- package/dist/testing/fakeNetworkApiClient.js.map +1 -0
- package/dist/testing/fixtures.d.ts +1098 -0
- package/dist/testing/fixtures.d.ts.map +1 -0
- package/dist/testing/fixtures.js +200 -0
- package/dist/testing/fixtures.js.map +1 -0
- package/dist/testing.d.ts +11 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +10 -0
- package/dist/testing.js.map +1 -0
- package/package.json +67 -4
- package/src/analytics/lifecycleEvents.test.ts +417 -0
- package/src/analytics/lifecycleEvents.ts +155 -0
- package/src/api/changes/applyOption.ts +103 -0
- package/src/api/changes/classifyChanges.ts +10 -0
- package/src/api/changes/index.ts +2 -0
- package/src/api/client.ts +149 -0
- package/src/api/health.ts +7 -0
- package/src/api/index.ts +24 -0
- package/src/api/me.ts +7 -0
- package/src/api/order.ts +64 -0
- package/src/api/orders.ts +8 -0
- package/src/api/patient.ts +67 -0
- package/src/api/prescription.ts +86 -0
- package/src/api/results.ts +45 -0
- package/src/gql/gql.ts +68 -0
- package/src/gql/graphql.ts +9027 -0
- package/src/gql/index.ts +2 -0
- package/src/index.ts +14 -0
- package/src/meta/version.test.ts +10 -0
- package/src/meta/version.ts +1 -0
- package/src/operations/fragments.graphql +497 -0
- package/src/operations/health.graphql +4 -0
- package/src/operations/me.graphql +38 -0
- package/src/operations/order.graphql +42 -0
- package/src/operations/orders.graphql +35 -0
- package/src/operations/patient.graphql +62 -0
- package/src/operations/prescription.graphql +90 -0
- package/src/photon/analytics.ts +129 -0
- package/src/photon/auth.ts +69 -0
- package/src/photon/choices.ts +79 -0
- package/src/photon/context.ts +30 -0
- package/src/photon/environments.ts +49 -0
- package/src/photon/errors.ts +56 -0
- package/src/photon/index.ts +49 -0
- package/src/photon/inputs.ts +24 -0
- package/src/photon/links.ts +197 -0
- package/src/photon/live.ts +135 -0
- package/src/photon/machine.ts +90 -0
- package/src/photon/map.ts +371 -0
- package/src/photon/order.test.ts +142 -0
- package/src/photon/order.ts +661 -0
- package/src/photon/orders.ts +42 -0
- package/src/photon/patient.ts +386 -0
- package/src/photon/photon.ts +646 -0
- package/src/photon/prescription.ts +506 -0
- package/src/photon/session.ts +454 -0
- package/src/photon/types.ts +583 -0
- package/src/test-utils/msw.ts +72 -0
- package/src/testing/fakeNetworkApiClient.ts +56 -0
- package/src/testing/fixtures.ts +233 -0
- package/src/testing.ts +25 -0
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
import { getOrder, submitOrder, syncOrder, updateOrder, type OrderOutcome } from "../api/index.ts";
|
|
2
|
+
import type { OrderFieldsFragment } from "../gql/graphql.ts";
|
|
3
|
+
import { asksForAddress, choicesIn, withChoice } from "./choices.ts";
|
|
4
|
+
import type { Context } from "./context.ts";
|
|
5
|
+
import { PhotonError, refuse, toPhotonError } from "./errors.ts";
|
|
6
|
+
import { LiveRecord } from "./live.ts";
|
|
7
|
+
import { noChanges, toChanges, toOrder, toOrderCandidate, toPrescription } from "./map.ts";
|
|
8
|
+
import { Patient } from "./patient.ts";
|
|
9
|
+
import { readOrders } from "./orders.ts";
|
|
10
|
+
import { Prescription } from "./prescription.ts";
|
|
11
|
+
import type {
|
|
12
|
+
ChangeOption,
|
|
13
|
+
Changes,
|
|
14
|
+
OrderCandidate,
|
|
15
|
+
OrderPharmacyInput,
|
|
16
|
+
OrderRecord,
|
|
17
|
+
ScreeningAlert,
|
|
18
|
+
} from "./types.ts";
|
|
19
|
+
|
|
20
|
+
export interface OrderExtra {
|
|
21
|
+
/** Who it's for — the live Patient every card shares. */
|
|
22
|
+
patient: Patient | null;
|
|
23
|
+
/**
|
|
24
|
+
* Its prescriptions, as live objects: the ones on the order and new lines (records or not yet). The
|
|
25
|
+
* server's copy of the order's list is `state.prescriptions`.
|
|
26
|
+
*/
|
|
27
|
+
prescriptions: readonly Prescription[];
|
|
28
|
+
/**
|
|
29
|
+
* The patient has several draft orders and the server asked which this is. Continue one with `pick(id)`
|
|
30
|
+
* (this order's prescriptions go on it); nothing is saved until then.
|
|
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;
|
|
39
|
+
/**
|
|
40
|
+
* The server wouldn't send it until the patient can be reached (its reason). Cleared once the patient's
|
|
41
|
+
* phone, email or address changes.
|
|
42
|
+
*/
|
|
43
|
+
contactRequest: string | null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The order mutation on a live object: its patient, prescriptions, and destination. */
|
|
47
|
+
export interface OrderUpdate {
|
|
48
|
+
/** Resolve or choose a pharmacy, including after submission. A resolved match can assign it immediately. */
|
|
49
|
+
pharmacy?: OrderPharmacyInput;
|
|
50
|
+
/**
|
|
51
|
+
* Who it's for: the live Patient (found yet or not), or a patient's id. Without one, the order takes the
|
|
52
|
+
* patient of a prescription added to it. A different patient starts the prescriptions over (one empty
|
|
53
|
+
* line). Fixed once the order is saved — another patient is a new order.
|
|
54
|
+
*/
|
|
55
|
+
patient?: Patient | { id: string } | null;
|
|
56
|
+
/**
|
|
57
|
+
* Prescriptions to add — a live Prescription, an existing one's id, one by your system's id (`{ externalId }`:
|
|
58
|
+
* the server finds it as it goes on, once the order has its patient; then it's a line), or a new line (`{}`,
|
|
59
|
+
* `{ templateId }`, or a drug by id: `{ treatment: { id } }`) — and to take off. Each goes on (or off) the
|
|
60
|
+
* server's order once it has a record.
|
|
61
|
+
*/
|
|
62
|
+
prescriptions?: {
|
|
63
|
+
add?: (Prescription | { id: string } | { externalId: string } | NewLine)[];
|
|
64
|
+
remove?: (Prescription | { id: string })[];
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A new line: from a template, or for a drug by its id. */
|
|
69
|
+
type NewLine = { templateId?: string | null } | { treatment: { id: string } };
|
|
70
|
+
|
|
71
|
+
/** What makes a patient reachable — the contact request clears when this changes. */
|
|
72
|
+
const contactOf = (p: Patient | null) => {
|
|
73
|
+
const c = p?.state?.contact;
|
|
74
|
+
return JSON.stringify([
|
|
75
|
+
c?.phone ?? null,
|
|
76
|
+
c?.email ?? null,
|
|
77
|
+
c?.address?.street1 ?? null,
|
|
78
|
+
c?.address?.postalCode ?? null,
|
|
79
|
+
]);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** One alert, comparable: the same finding from the order's screening and a prescription's. */
|
|
83
|
+
const alertKey = (a: ScreeningAlert) =>
|
|
84
|
+
JSON.stringify([a.type, a.severity, a.description, a.involvedEntities.map((e) => e.id).sort()]);
|
|
85
|
+
|
|
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. */
|
|
91
|
+
const alreadySent = () =>
|
|
92
|
+
refuse("This patient's last order was already sent, and Photon can't start another for them yet.");
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The order is the treatment: a patient, its prescriptions, and sending them. Its draft is saved as it goes,
|
|
96
|
+
* like the other objects: once its patient and a prescription have records, it's synced to the server (the
|
|
97
|
+
* patient's draft order, or a new one) — `id` fills in — and every prescription that gets a record goes on
|
|
98
|
+
* it (UpdateOrder). `submit()` sends it. Opened from an id (e.g. an order an agent drafted), it comes with its
|
|
99
|
+
* patient and prescriptions.
|
|
100
|
+
*/
|
|
101
|
+
export class Order extends LiveRecord<OrderRecord, OrderExtra> {
|
|
102
|
+
readonly #ctx: Context;
|
|
103
|
+
#unsubscribePatient: (() => void) | null = null;
|
|
104
|
+
#unsubscribeLines: (() => void)[] = [];
|
|
105
|
+
#contactAtRequest: string | null = null;
|
|
106
|
+
/** A save the server turned down for this patient and these prescriptions: not retried until they change. */
|
|
107
|
+
#declined: string | null = null;
|
|
108
|
+
/**
|
|
109
|
+
* Prescriptions given by your system's id: there's no read by it, so they go on the server's order as they
|
|
110
|
+
* are, and become lines when it answers.
|
|
111
|
+
*/
|
|
112
|
+
#refs: { externalId: string }[] = [];
|
|
113
|
+
/** The patient whose draft orders were looked for: once per patient. */
|
|
114
|
+
#lookedFor: string | null = null;
|
|
115
|
+
/** Held before the record, so a draft created once its lines are ready includes the pharmacy input. */
|
|
116
|
+
#pharmacy: OrderPharmacyInput | undefined;
|
|
117
|
+
|
|
118
|
+
constructor(
|
|
119
|
+
ctx: Context,
|
|
120
|
+
record: OrderRecord | null,
|
|
121
|
+
extra: { patient?: Patient | null; prescriptions?: Prescription[]; changes?: Changes } = {},
|
|
122
|
+
) {
|
|
123
|
+
super(
|
|
124
|
+
record,
|
|
125
|
+
{ patient: null, prescriptions: [], candidates: [], draft: null, contactRequest: null },
|
|
126
|
+
extra.changes,
|
|
127
|
+
);
|
|
128
|
+
this.#ctx = ctx;
|
|
129
|
+
this.#setLines(extra.prescriptions ?? []);
|
|
130
|
+
if (extra.patient) this.#follow(extra.patient);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
protected override onRecord() {
|
|
134
|
+
this.#ctx.register(this);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
get patient(): Patient | null {
|
|
138
|
+
return this.snapshot.patient;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
get prescriptions(): readonly Prescription[] {
|
|
142
|
+
return this.snapshot.prescriptions;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Sent (or canceled): its patient and prescriptions are final. A submitted order can still choose a pharmacy. */
|
|
146
|
+
get final(): boolean {
|
|
147
|
+
return Boolean(this.state && this.state.state !== "DRAFT");
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Pharmacy choices from the latest response, with addresses and offers; take one with `choose`. */
|
|
151
|
+
get pharmacyOptions(): ChangeOption[] {
|
|
152
|
+
return choicesIn(this.changes).flatMap((change) => change.options.filter((option) => option.pharmacy !== null));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Everything's saved: no call in flight on the order, its patient or any of its prescriptions. */
|
|
156
|
+
get saved(): boolean {
|
|
157
|
+
const busy = (o: { snapshot: { status: string } } | null) =>
|
|
158
|
+
o?.snapshot.status === "loading" || o?.snapshot.status === "saving";
|
|
159
|
+
return !busy(this) && !busy(this.patient) && !this.prescriptions.some(busy);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Screening alerts no one has acknowledged: the order's own (its prescriptions screened together) and each
|
|
164
|
+
* unsigned prescription's, less any a signed prescription carries — its signature acknowledged that one. A
|
|
165
|
+
* caller that never reads the prescriptions still sees every open alert here; a page shows them by Send.
|
|
166
|
+
* They never stop a send.
|
|
167
|
+
*/
|
|
168
|
+
get unacknowledgedAlerts(): ScreeningAlert[] {
|
|
169
|
+
const acknowledged = new Set(
|
|
170
|
+
this.prescriptions.flatMap((rx) => (rx.signed ? rx.state!.screeningAlerts.map(alertKey) : [])),
|
|
171
|
+
);
|
|
172
|
+
const open = [
|
|
173
|
+
...(this.state?.screeningAlerts ?? []),
|
|
174
|
+
...this.prescriptions.flatMap((rx) => (rx.signed ? [] : (rx.state?.screeningAlerts ?? []))),
|
|
175
|
+
];
|
|
176
|
+
const seen = new Set<string>();
|
|
177
|
+
return open.filter((a) => {
|
|
178
|
+
const key = alertKey(a);
|
|
179
|
+
if (acknowledged.has(key) || seen.has(key)) return false;
|
|
180
|
+
seen.add(key);
|
|
181
|
+
return true;
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Ready to submit: a patient with a record, at least one prescription, every one signed, no contact the
|
|
187
|
+
* server asked for still missing — and everything saved.
|
|
188
|
+
*/
|
|
189
|
+
get readyToSend(): boolean {
|
|
190
|
+
const lines = this.prescriptions;
|
|
191
|
+
return (
|
|
192
|
+
!this.final &&
|
|
193
|
+
Boolean(this.patient?.id) &&
|
|
194
|
+
lines.length > 0 &&
|
|
195
|
+
lines.every((rx) => rx.signed) &&
|
|
196
|
+
!this.snapshot.contactRequest &&
|
|
197
|
+
this.saved
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Its patient and lines change here at once; what has records is saved to the server's draft order (synced
|
|
203
|
+
* first, if it has none yet). See `OrderUpdate`.
|
|
204
|
+
*/
|
|
205
|
+
sync(input: OrderUpdate): Promise<{ changes: Changes }> {
|
|
206
|
+
return this.#change(input);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The same, for an order that has its id (it must): its lines go on or off it with UpdateOrder. */
|
|
210
|
+
update(input: OrderUpdate): Promise<{ changes: Changes }> {
|
|
211
|
+
if (!this.id)
|
|
212
|
+
return Promise.reject(new PhotonError("invalid", "update() needs the order's id; until it has one, sync()."));
|
|
213
|
+
return this.#change(input);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async #change(input: OrderUpdate): Promise<{ changes: Changes }> {
|
|
217
|
+
if (this.final) {
|
|
218
|
+
if (
|
|
219
|
+
this.state!.state !== "SUBMITTED" ||
|
|
220
|
+
!input.pharmacy ||
|
|
221
|
+
input.patient !== undefined ||
|
|
222
|
+
input.prescriptions !== undefined
|
|
223
|
+
)
|
|
224
|
+
throw refuse(`This order is ${this.state!.state.toLowerCase()}; only a submitted order's pharmacy can change.`);
|
|
225
|
+
return this.#save([], input.pharmacy);
|
|
226
|
+
}
|
|
227
|
+
if (!this.id && input.pharmacy !== undefined) this.#pharmacy = input.pharmacy;
|
|
228
|
+
// What's local applies at once (a card shows it in the same render); only ids wait for a read.
|
|
229
|
+
if (input.patient !== undefined) {
|
|
230
|
+
const patient = this.#patientFor(input.patient);
|
|
231
|
+
this.#setPatient(patient instanceof Promise ? await patient : patient);
|
|
232
|
+
}
|
|
233
|
+
const { add: given = [], remove = [] } = input.prescriptions ?? {};
|
|
234
|
+
const lines = given.flatMap((rx) => {
|
|
235
|
+
if (rx instanceof Prescription || !("externalId" in rx)) return [this.#lineFor(rx)];
|
|
236
|
+
this.#refs = [...this.#refs, { externalId: rx.externalId }];
|
|
237
|
+
return [];
|
|
238
|
+
});
|
|
239
|
+
const adding = lines.some((l) => l instanceof Promise) ? await Promise.all(lines) : (lines as Prescription[]);
|
|
240
|
+
const removing = remove.flatMap((rx) =>
|
|
241
|
+
this.prescriptions.filter((line) => line === rx || (!(rx instanceof Prescription) && line.id === rx.id)),
|
|
242
|
+
);
|
|
243
|
+
const kept = this.prescriptions.filter((line) => !removing.includes(line));
|
|
244
|
+
// A prescription is one line, however many times it's given (`rx=rx_1&rx=rx_1`); each template line is its own.
|
|
245
|
+
this.#setLines([...kept, ...adding.filter((line, i) => !kept.includes(line) && adding.indexOf(line) === i)]);
|
|
246
|
+
// No patient yet: a prescription added for one brings them.
|
|
247
|
+
const theirs = this.patient ? null : adding.find((line) => line.patientId)?.patientId;
|
|
248
|
+
if (theirs) {
|
|
249
|
+
const patient = this.#patientFor({ id: theirs });
|
|
250
|
+
this.#setPatient(patient instanceof Promise ? await patient : patient);
|
|
251
|
+
}
|
|
252
|
+
if (this.patient?.id)
|
|
253
|
+
for (const line of adding) void line.sync({ patient: { id: this.patient.id } }).catch(() => {});
|
|
254
|
+
return this.#save(
|
|
255
|
+
removing.filter((line) => this.#onServer(line.id)).map((line) => ({ id: line.id! })),
|
|
256
|
+
input.pharmacy,
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Apply a pharmacy option through the same order mutation; no additional client-side matching. */
|
|
261
|
+
async choose(option: ChangeOption): Promise<{ changes: Changes }> {
|
|
262
|
+
if (option.operation !== "order" || option.path !== "pharmacy.pharmacy.id")
|
|
263
|
+
throw new PhotonError("invalid", "Choose a pharmacy option returned for this order.");
|
|
264
|
+
const input = withChoice<OrderUpdate>({}, option);
|
|
265
|
+
return this.id ? this.update(input) : this.sync(input);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* One of `candidates`: this becomes that draft order (read), and this order's prescriptions go on it — a line
|
|
270
|
+
* nothing was written in yet gives way to the draft's, so it can be sent as it is.
|
|
271
|
+
*/
|
|
272
|
+
pick(orderId: string): Promise<{ changes: Changes }> {
|
|
273
|
+
return this.run("loading", async () => {
|
|
274
|
+
const result = await this.#settle(await getOrder(this.#ctx.client, orderId));
|
|
275
|
+
this.patch({ candidates: [], draft: null });
|
|
276
|
+
if (this.prescriptions.some((l) => l.id)) this.#setLines(this.prescriptions.filter((l) => !untouched(l)));
|
|
277
|
+
return result;
|
|
278
|
+
}).then(() => this.#save());
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Go on with the patient's draft order (`draft`): this becomes that order, and what's added goes on it. */
|
|
282
|
+
continueDraft(): Promise<{ changes: Changes }> {
|
|
283
|
+
if (!this.snapshot.draft) return Promise.reject(new PhotonError("invalid", "This order has no draft to continue."));
|
|
284
|
+
return this.pick(this.snapshot.draft.id);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Start over instead of continuing the patient's draft order (`draft`): its prescriptions come off it (taken off,
|
|
289
|
+
* not canceled) and this order is that draft, holding only what's written here. network-api continues a patient's
|
|
290
|
+
* draft whenever an order is saved, so emptying it is how a new order starts. Turned down, the draft is still
|
|
291
|
+
* there to decide on (its reason in `changes`).
|
|
292
|
+
*/
|
|
293
|
+
startNew(): Promise<{ changes: Changes }> {
|
|
294
|
+
const draft = this.snapshot.draft;
|
|
295
|
+
if (!draft) return Promise.resolve({ changes: this.changes });
|
|
296
|
+
return this.run("saving", async () => {
|
|
297
|
+
const result = await this.#settle(
|
|
298
|
+
await updateOrder(this.#ctx.client, draft.id, { prescriptions: { none: true } }),
|
|
299
|
+
);
|
|
300
|
+
if (this.id) this.patch({ draft: null });
|
|
301
|
+
return result;
|
|
302
|
+
}).then(() => this.#save());
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Send it to the patient. Refused until it's ready (see `readyToSend`). Saves what isn't saved yet first.
|
|
307
|
+
* Never sets a pharmacy: the patient chooses (one already on the order is kept). If the server's order
|
|
308
|
+
* holds prescriptions this order doesn't show (e.g. an agent's), they become lines and nothing is sent —
|
|
309
|
+
* the prescriber reviews them first. If the server won't send it, it says why in `changes` (and, when it
|
|
310
|
+
* needs a way to reach the patient, `contactRequest`).
|
|
311
|
+
*/
|
|
312
|
+
submit(): Promise<{ changes: Changes }> {
|
|
313
|
+
return this.run("saving", async () => {
|
|
314
|
+
if (this.final) throw refuse(`This order is already ${this.state!.state.toLowerCase()}.`);
|
|
315
|
+
const lines = this.prescriptions;
|
|
316
|
+
if (!this.patient?.id) throw refuse("This order has no patient yet.");
|
|
317
|
+
if (!lines.length) throw refuse("This order has no prescriptions.");
|
|
318
|
+
if (!lines.every((rx) => rx.signed)) throw refuse("Every prescription must be signed before the order is sent.");
|
|
319
|
+
const ids = lines.map((rx) => rx.id!);
|
|
320
|
+
try {
|
|
321
|
+
if (!this.id) {
|
|
322
|
+
const result = await this.#syncDraft();
|
|
323
|
+
if (this.snapshot.candidates.length)
|
|
324
|
+
throw refuse("This patient has several draft orders: pick the one to send.");
|
|
325
|
+
if (!this.id) return result; // the server said why (changes)
|
|
326
|
+
} else await this.#saveLines();
|
|
327
|
+
// Never send prescriptions the prescriber wasn't shown (e.g. an agent's, on the patient's draft order):
|
|
328
|
+
// they're lines now; nothing is sent until they're reviewed.
|
|
329
|
+
if (this.state!.prescriptions.some((rx) => !ids.includes(rx.id)))
|
|
330
|
+
throw refuse(
|
|
331
|
+
"This order holds prescriptions you haven't reviewed. They're shown now; review them, then send.",
|
|
332
|
+
);
|
|
333
|
+
const result = await this.#settle(await submitOrder(this.#ctx.client, this.id!));
|
|
334
|
+
if (this.state?.state !== "SUBMITTED") this.#askForContact(result.changes);
|
|
335
|
+
return result;
|
|
336
|
+
} catch (e) {
|
|
337
|
+
const error = toPhotonError(e);
|
|
338
|
+
if (error.kind !== "refused" && asksForAddress(null, error.message))
|
|
339
|
+
this.#askForContact(noChanges, error.message);
|
|
340
|
+
throw error;
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* The Photon Rx app's link to this record's flow (`/<flow>/<id>`); before the record, to a new one from the ids it
|
|
347
|
+
* hangs off (its patient, and its lines by id or template). `ph.url(this)`.
|
|
348
|
+
*/
|
|
349
|
+
url(): string {
|
|
350
|
+
return this.#ctx.url(this);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** The same, embeddable in an iframe; `ph.frame(this)`. */
|
|
354
|
+
frame(): string {
|
|
355
|
+
return this.#ctx.frame(this);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Read it again, with each prescription read on its own. */
|
|
359
|
+
reload(): Promise<{ changes: Changes }> {
|
|
360
|
+
if (!this.id) return Promise.resolve({ changes: this.changes });
|
|
361
|
+
return this.run("loading", async () => this.#settle(await getOrder(this.#ctx.client, this.id!)));
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// ---- Saving the draft as it goes ----
|
|
365
|
+
|
|
366
|
+
#onServer(id: string | null) {
|
|
367
|
+
return Boolean(id && this.state?.prescriptions.some((rx) => rx.id === id));
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** The patient and the prescriptions with records — what the server's draft order should hold. */
|
|
371
|
+
#draftKey() {
|
|
372
|
+
const ids = this.prescriptions.flatMap((line) => (line.id ? [line.id] : []));
|
|
373
|
+
return JSON.stringify([this.patient?.id ?? null, ids, this.#refs, this.#pharmacy]);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** What goes on the server's order: the prescriptions with records it lacks, and those given by your id. */
|
|
377
|
+
#toAdd(): ({ id: string } | { externalId: string })[] {
|
|
378
|
+
const ids = this.prescriptions.flatMap((line) => (line.id && !this.#onServer(line.id) ? [{ id: line.id }] : []));
|
|
379
|
+
return [...ids, ...this.#refs];
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** A rejected pharmacy match leaves the entire patch unapplied, including removed lines. */
|
|
383
|
+
#toRemove(): { id: string }[] {
|
|
384
|
+
return (this.state?.prescriptions ?? [])
|
|
385
|
+
.filter((rx) => !this.prescriptions.some((line) => line.id === rx.id))
|
|
386
|
+
.map(({ id }) => ({ id }));
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Save what's changed: before the record, sync the draft order once the patient and a prescription have
|
|
391
|
+
* records; after, put on what it lacks and take off what was removed. Nothing to do: no call.
|
|
392
|
+
*/
|
|
393
|
+
#save(remove: { id: string }[] = [], pharmacy = this.id ? undefined : this.#pharmacy): Promise<{ changes: Changes }> {
|
|
394
|
+
const nothing = { changes: this.changes };
|
|
395
|
+
if (this.final && !pharmacy) return Promise.resolve(nothing);
|
|
396
|
+
if (!this.id) {
|
|
397
|
+
if (this.#toLookFor())
|
|
398
|
+
return this.run("loading", () => this.#findDraft()).then(() => this.#save(remove, pharmacy));
|
|
399
|
+
if (!this.#readyToSync()) return Promise.resolve(nothing);
|
|
400
|
+
// Queued behind other calls: by its turn, another save may have made the order — then just add to it.
|
|
401
|
+
return this.run("saving", async () =>
|
|
402
|
+
this.id
|
|
403
|
+
? this.#saveLines([], pharmacy)
|
|
404
|
+
: this.#readyToSync()
|
|
405
|
+
? this.#syncDraft(pharmacy)
|
|
406
|
+
: { changes: this.changes },
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
if (!this.#toAdd().length && !remove.length && !this.#toRemove().length && pharmacy === undefined)
|
|
410
|
+
return Promise.resolve(nothing);
|
|
411
|
+
return this.run("saving", () => this.#saveLines(remove, pharmacy));
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** A patient and a prescription with records, no pick pending, and not what the server just turned down. */
|
|
415
|
+
#readyToSync() {
|
|
416
|
+
return (
|
|
417
|
+
Boolean(this.patient?.id) &&
|
|
418
|
+
(this.prescriptions.some((line) => line.id) || this.#refs.length > 0) &&
|
|
419
|
+
!this.snapshot.candidates.length &&
|
|
420
|
+
!this.snapshot.draft &&
|
|
421
|
+
this.#declined !== this.#draftKey()
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** A new order's patient, not looked for yet: nothing on this order has a record that would decide which order. */
|
|
426
|
+
#toLookFor(): string | null {
|
|
427
|
+
const id = this.patient?.id ?? null;
|
|
428
|
+
if (!id || this.id || this.#lookedFor === id || this.#refs.length || this.prescriptions.some((l) => l.id))
|
|
429
|
+
return null;
|
|
430
|
+
return id;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* The patient's draft orders (the read-only Orders query): one is `draft`, several are `candidates`. A read that
|
|
435
|
+
* fails leaves the order as it was — the server's sync still continues a draft.
|
|
436
|
+
*/
|
|
437
|
+
async #findDraft(): Promise<{ changes: Changes }> {
|
|
438
|
+
const patientId = this.#toLookFor();
|
|
439
|
+
if (!patientId) return { changes: this.changes };
|
|
440
|
+
this.#lookedFor = patientId;
|
|
441
|
+
const found = await readOrders(this.#ctx.client, { filter: { patient: { id: patientId }, state: "DRAFT" } }).catch(
|
|
442
|
+
() => null,
|
|
443
|
+
);
|
|
444
|
+
// Moved on while it read: another patient, or a record now decides.
|
|
445
|
+
const decided = Boolean(this.id || this.#refs.length || this.prescriptions.some((l) => l.id));
|
|
446
|
+
if (!found || decided || this.patient?.id !== patientId) return { changes: this.changes };
|
|
447
|
+
// A draft with nothing on it isn't worth asking about: the server's sync continues it, as a new order would start.
|
|
448
|
+
const drafts = found.orders
|
|
449
|
+
.filter((order) => order.prescriptions.length > 0)
|
|
450
|
+
.map(({ routablePharmacies: _, ...order }) => order);
|
|
451
|
+
if (drafts.length === 1) this.patch({ draft: drafts[0]! });
|
|
452
|
+
else if (drafts.length > 1)
|
|
453
|
+
this.patch({
|
|
454
|
+
candidates: drafts.map((o) => ({ id: o.id, pharmacy: o.pharmacy, prescriptions: o.prescriptions })),
|
|
455
|
+
});
|
|
456
|
+
return { changes: this.changes };
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** SyncOrder with the patient and every prescription that has a record: the patient's draft order, or a new one. */
|
|
460
|
+
async #syncDraft(pharmacy?: OrderPharmacyInput): Promise<{ changes: Changes }> {
|
|
461
|
+
const key = this.#draftKey();
|
|
462
|
+
const add = this.#toAdd();
|
|
463
|
+
const outcome = await syncOrder(this.#ctx.client, {
|
|
464
|
+
patient: { id: this.patient!.id! },
|
|
465
|
+
prescriptions: add.length ? { add } : undefined,
|
|
466
|
+
...(pharmacy !== undefined ? { pharmacy } : {}),
|
|
467
|
+
});
|
|
468
|
+
if (outcome.kind === "ok" && outcome.order) this.#sent(add);
|
|
469
|
+
if (outcome.kind === "ambiguous") {
|
|
470
|
+
this.patch({ candidates: outcome.candidates.map(toOrderCandidate) });
|
|
471
|
+
return { changes: noChanges };
|
|
472
|
+
}
|
|
473
|
+
if (outcome.order && outcome.order.state !== "DRAFT") {
|
|
474
|
+
this.#declined = key;
|
|
475
|
+
throw alreadySent();
|
|
476
|
+
}
|
|
477
|
+
const result = await this.#settle(outcome);
|
|
478
|
+
if (!this.id) this.#declined = key; // the server said why (changes); not again until something changes
|
|
479
|
+
return result;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** On the server's order: the prescriptions with records it lacks, and those to take off. */
|
|
483
|
+
async #saveLines(remove: { id: string }[] = [], pharmacy?: OrderPharmacyInput): Promise<{ changes: Changes }> {
|
|
484
|
+
const add = this.#toAdd();
|
|
485
|
+
const off = [...new Set([...remove, ...this.#toRemove()].map((rx) => rx.id))]
|
|
486
|
+
.filter((id) => this.#onServer(id))
|
|
487
|
+
.map((id) => ({ id }));
|
|
488
|
+
if (this.final && (this.state!.state !== "SUBMITTED" || add.length || off.length))
|
|
489
|
+
throw refuse(`This order is ${this.state!.state.toLowerCase()}; only a submitted order's pharmacy can change.`);
|
|
490
|
+
if (!add.length && !off.length && pharmacy === undefined) return { changes: this.changes };
|
|
491
|
+
const prescriptions = { ...(add.length ? { add } : {}), ...(off.length ? { remove: off } : {}) };
|
|
492
|
+
const outcome = await updateOrder(this.#ctx.client, this.id!, {
|
|
493
|
+
...(add.length || off.length ? { prescriptions } : {}),
|
|
494
|
+
...(pharmacy !== undefined ? { pharmacy } : {}),
|
|
495
|
+
});
|
|
496
|
+
if (outcome.kind === "ok" && outcome.order) this.#sent(add);
|
|
497
|
+
return this.#settle(outcome);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** Prescriptions given by your id went to the server: what it found is on its order (its changes say what it didn't). */
|
|
501
|
+
#sent(add: ({ id: string } | { externalId: string })[]) {
|
|
502
|
+
this.#refs = this.#refs.filter((ref) => !add.includes(ref));
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// ---- Its patient and lines ----
|
|
506
|
+
|
|
507
|
+
/** The live patient for what was given: as is, or opened by id. */
|
|
508
|
+
#patientFor(given: Patient | { id: string } | null): Patient | null | Promise<Patient> {
|
|
509
|
+
if (given === null || given instanceof Patient) return given;
|
|
510
|
+
return this.#ctx.openPatient(given.id).then((p) => {
|
|
511
|
+
if (!p) throw new PhotonError("invalid", `Patient ${given.id} not found.`);
|
|
512
|
+
return p;
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** Who it's for. A different patient starts over — prescriptions stay with the patient they were written for. */
|
|
517
|
+
#setPatient(patient: Patient | null) {
|
|
518
|
+
if (patient === this.patient || (patient?.id && patient.id === this.patient?.id)) return;
|
|
519
|
+
if (this.id) throw refuse("This order's patient is fixed: for another patient, start a new order.");
|
|
520
|
+
const switching = Boolean(this.patient && patient && this.patient.id !== patient.id) || !patient;
|
|
521
|
+
// The old lines go first: following the new patient tells every line who it's for, and a line with a picked
|
|
522
|
+
// drug waiting for its patient would be created for this one.
|
|
523
|
+
if (switching) {
|
|
524
|
+
this.#contactAtRequest = null;
|
|
525
|
+
this.patch({ contactRequest: null, candidates: [], draft: null });
|
|
526
|
+
this.#setLines([this.#newLine(null, patient?.id ?? null)]);
|
|
527
|
+
}
|
|
528
|
+
this.#follow(patient);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* The line for something to add: a live Prescription as given, one opened by id, or a new line — a drug by id
|
|
533
|
+
* looked up at once, a template line drafted once its patient is known.
|
|
534
|
+
*/
|
|
535
|
+
#lineFor(rx: Prescription | { id: string } | NewLine): Prescription | Promise<Prescription> {
|
|
536
|
+
if (rx instanceof Prescription) return rx;
|
|
537
|
+
// One the server doesn't have: an empty line in its place, saying so — the rest of the order still opens.
|
|
538
|
+
if ("id" in rx)
|
|
539
|
+
return this.#ctx.openPrescription(rx.id).then((opened) => opened ?? this.#newLine(null, undefined, rx.id));
|
|
540
|
+
const line = this.#newLine("templateId" in rx ? (rx.templateId ?? null) : null);
|
|
541
|
+
const drug = "treatment" in rx ? { treatment: { id: rx.treatment.id } } : {};
|
|
542
|
+
// A drug by id is looked up now; a template line is drafted once it has its patient (network-api doesn't expand
|
|
543
|
+
// a template without one).
|
|
544
|
+
if (drug.treatment) void line.sync(drug).catch(() => {}); // a failure lands on the line
|
|
545
|
+
return line;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** A new line for this order's patient (no record until its drug is picked). */
|
|
549
|
+
#newLine(templateId: string | null = null, patientId = this.patient?.id ?? null, missing?: string): Prescription {
|
|
550
|
+
const line: Prescription = new Prescription(this.#ctx, null, {
|
|
551
|
+
patientId,
|
|
552
|
+
templateId,
|
|
553
|
+
missing,
|
|
554
|
+
isTaken: (id) => this.prescriptions.some((other) => other !== line && other.id === id),
|
|
555
|
+
});
|
|
556
|
+
return line;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Its lines, followed: a change to one is a change to the order (a new snapshot), and one that gets a
|
|
561
|
+
* record goes on the draft order.
|
|
562
|
+
*/
|
|
563
|
+
#setLines(lines: Prescription[]) {
|
|
564
|
+
for (const stop of this.#unsubscribeLines) stop();
|
|
565
|
+
this.patch({ prescriptions: lines });
|
|
566
|
+
this.#unsubscribeLines = lines.map((line) => {
|
|
567
|
+
let had = line.id;
|
|
568
|
+
let drug = line.state?.treatment.id;
|
|
569
|
+
return line.subscribe(() => {
|
|
570
|
+
this.touch();
|
|
571
|
+
const now = line.state?.treatment.id;
|
|
572
|
+
if (line.id === had) {
|
|
573
|
+
// Another drug on a line the order holds: the order's screening is out of date — read it again.
|
|
574
|
+
if (now !== drug && this.#onServer(line.id) && !this.final) void this.reload().catch(() => {});
|
|
575
|
+
drug = now;
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
had = line.id;
|
|
579
|
+
drug = now;
|
|
580
|
+
void this.#save().catch(() => {}); // a failure lands on the object (snapshot.error)
|
|
581
|
+
});
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** The server won't send it until the patient can be reached: a missing phone, email or address (its words). */
|
|
586
|
+
#askForContact(changes: Changes, message?: string) {
|
|
587
|
+
const contact = changes.unapplied.find(
|
|
588
|
+
(c) => c.key.startsWith("patient.contact.") || asksForAddress({ applied: [], unapplied: [c] }),
|
|
589
|
+
);
|
|
590
|
+
const reason = message ?? contact?.reason ?? null;
|
|
591
|
+
if (!reason && !contact) return;
|
|
592
|
+
this.#contactAtRequest = contactOf(this.patient);
|
|
593
|
+
this.patch({ contactRequest: reason ?? "The patient needs a phone." });
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* Follow the patient: a change to them is a change to the order (a new snapshot); lines learn their
|
|
598
|
+
* patient's id when it has one (and the draft is saved then); the contact request clears on new contact info.
|
|
599
|
+
*/
|
|
600
|
+
#follow(patient: Patient | null) {
|
|
601
|
+
this.#unsubscribePatient?.();
|
|
602
|
+
this.patch({ patient });
|
|
603
|
+
if (!patient) return;
|
|
604
|
+
let had = patient.id;
|
|
605
|
+
const sync = () => {
|
|
606
|
+
if (patient.id)
|
|
607
|
+
for (const line of this.prescriptions) void line.sync({ patient: { id: patient.id } }).catch(() => {});
|
|
608
|
+
if (patient.id !== had) {
|
|
609
|
+
had = patient.id;
|
|
610
|
+
void this.#save().catch(() => {});
|
|
611
|
+
}
|
|
612
|
+
if (this.snapshot.contactRequest && contactOf(patient) !== this.#contactAtRequest) {
|
|
613
|
+
this.#contactAtRequest = null;
|
|
614
|
+
this.patch({ contactRequest: null });
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
this.#unsubscribePatient = patient.subscribe(() => {
|
|
618
|
+
this.touch();
|
|
619
|
+
sync();
|
|
620
|
+
});
|
|
621
|
+
sync();
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
async #settle(outcome: OrderOutcome): Promise<{ changes: Changes }> {
|
|
625
|
+
const changes = outcome.kind === "ok" ? toChanges(outcome.changes) : noChanges;
|
|
626
|
+
if (outcome.kind !== "ok" || !outcome.order) {
|
|
627
|
+
this.settle(null, changes);
|
|
628
|
+
return { changes };
|
|
629
|
+
}
|
|
630
|
+
const record = await adoptOrder(this.#ctx, outcome.order);
|
|
631
|
+
// Its patient, and any prescription it holds that no line shows yet, become this order's.
|
|
632
|
+
if (record.patient && !this.patient) this.#follow(this.#ctx.patient(record.patient));
|
|
633
|
+
const shown = new Set(this.prescriptions.map((l) => l.id));
|
|
634
|
+
const added = record.prescriptions
|
|
635
|
+
.filter((rx) => !shown.has(rx.id))
|
|
636
|
+
.map((rx) => this.#ctx.held.prescriptions.get(rx.id) ?? this.#ctx.prescription(rx));
|
|
637
|
+
if (added.length)
|
|
638
|
+
this.#setLines([...this.prescriptions.filter((l) => l.id), ...added, ...this.prescriptions.filter((l) => !l.id)]);
|
|
639
|
+
this.settle(record, changes);
|
|
640
|
+
return { changes };
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* An order's record; its patient and any prescriptions not yet held become live objects — each prescription
|
|
646
|
+
* read on its own (the order's copy can be wrong), sharing a read already in flight; the order's copy if the
|
|
647
|
+
* read fails.
|
|
648
|
+
*/
|
|
649
|
+
export async function adoptOrder(ctx: Context, order: OrderFieldsFragment): Promise<OrderRecord> {
|
|
650
|
+
const record = toOrder(order);
|
|
651
|
+
if (record.patient) ctx.patient(record.patient);
|
|
652
|
+
await Promise.all(
|
|
653
|
+
order.prescriptions
|
|
654
|
+
.filter((rx) => !ctx.held.prescriptions.has(rx.id))
|
|
655
|
+
.map(async (rx) => {
|
|
656
|
+
const opened = await ctx.openPrescription(rx.id).catch(() => null);
|
|
657
|
+
return opened ?? ctx.prescription(toPrescription(rx));
|
|
658
|
+
}),
|
|
659
|
+
);
|
|
660
|
+
return record;
|
|
661
|
+
}
|