@joinskips/common 0.0.0-stage → 0.1.0

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 (131) hide show
  1. package/README.md +104 -2
  2. package/dist/chat/SkipsChat.d.ts +37 -0
  3. package/dist/chat/SkipsChat.js +103 -0
  4. package/dist/chat/client.d.ts +53 -0
  5. package/dist/chat/client.js +178 -0
  6. package/dist/chat/connection.d.ts +4 -0
  7. package/dist/chat/connection.js +6 -0
  8. package/dist/chat/generated/skips-app/index.d.ts +1 -0
  9. package/dist/chat/generated/skips-app/index.js +2 -0
  10. package/dist/chat/generated/skips-app/types.gen.d.ts +733 -0
  11. package/dist/chat/generated/skips-app/types.gen.js +2 -0
  12. package/dist/chat/index.d.ts +3 -0
  13. package/dist/chat/index.js +2 -0
  14. package/dist/chat/platform.d.ts +4 -0
  15. package/dist/chat/platform.js +46 -0
  16. package/dist/chat/session.d.ts +19 -0
  17. package/dist/chat/session.js +95 -0
  18. package/dist/chat/useSkipsChat.d.ts +79 -0
  19. package/dist/chat/useSkipsChat.js +507 -0
  20. package/dist/chat/verify.d.ts +35 -0
  21. package/dist/chat/verify.js +84 -0
  22. package/dist/elements/skips-elements.js +18521 -0
  23. package/dist/helpers/attachments.d.ts +12 -0
  24. package/dist/helpers/attachments.js +34 -0
  25. package/dist/helpers/cable.d.ts +34 -0
  26. package/dist/helpers/cable.js +88 -0
  27. package/dist/helpers/cableFrames.d.ts +40 -0
  28. package/dist/helpers/cableFrames.js +70 -0
  29. package/dist/helpers/cardNote.d.ts +79 -0
  30. package/dist/helpers/cardNote.js +152 -0
  31. package/dist/helpers/commandNote.d.ts +4 -0
  32. package/dist/helpers/commandNote.js +23 -0
  33. package/dist/helpers/index.d.ts +19 -0
  34. package/dist/helpers/index.js +19 -0
  35. package/dist/helpers/markdown.d.ts +47 -0
  36. package/dist/helpers/markdown.js +129 -0
  37. package/dist/helpers/medicationOrder.d.ts +333 -0
  38. package/dist/helpers/medicationOrder.js +383 -0
  39. package/dist/helpers/message.d.ts +46 -0
  40. package/dist/helpers/message.js +12 -0
  41. package/dist/helpers/noteView.d.ts +35 -0
  42. package/dist/helpers/noteView.js +65 -0
  43. package/dist/helpers/orderForm.d.ts +126 -0
  44. package/dist/helpers/orderForm.js +271 -0
  45. package/dist/helpers/ordersMenu.d.ts +56 -0
  46. package/dist/helpers/ordersMenu.js +129 -0
  47. package/dist/helpers/regimenChoice.d.ts +42 -0
  48. package/dist/helpers/regimenChoice.js +73 -0
  49. package/dist/helpers/scrollBox.d.ts +5 -0
  50. package/dist/helpers/scrollBox.js +15 -0
  51. package/dist/helpers/skipTyping.d.ts +26 -0
  52. package/dist/helpers/skipTyping.js +29 -0
  53. package/dist/helpers/skipsMessage.d.ts +55 -0
  54. package/dist/helpers/skipsMessage.js +130 -0
  55. package/dist/helpers/stageRefill.d.ts +33 -0
  56. package/dist/helpers/stageRefill.js +41 -0
  57. package/dist/helpers/thread.d.ts +54 -0
  58. package/dist/helpers/thread.js +122 -0
  59. package/dist/helpers/typing.d.ts +13 -0
  60. package/dist/helpers/typing.js +68 -0
  61. package/dist/helpers/usrxNote.d.ts +22 -0
  62. package/dist/helpers/usrxNote.js +26 -0
  63. package/dist/helpers/visibleArea.d.ts +15 -0
  64. package/dist/helpers/visibleArea.js +11 -0
  65. package/dist/helpers/welcome.d.ts +25 -0
  66. package/dist/helpers/welcome.js +51 -0
  67. package/dist/hooks/index.d.ts +8 -0
  68. package/dist/hooks/index.js +8 -0
  69. package/dist/hooks/useCardNoteActions.d.ts +82 -0
  70. package/dist/hooks/useCardNoteActions.js +210 -0
  71. package/dist/hooks/useCodeEntry.d.ts +6 -0
  72. package/dist/hooks/useCodeEntry.js +14 -0
  73. package/dist/hooks/useComposer.d.ts +20 -0
  74. package/dist/hooks/useComposer.js +40 -0
  75. package/dist/hooks/useOrderForm.d.ts +80 -0
  76. package/dist/hooks/useOrderForm.js +403 -0
  77. package/dist/hooks/useOrdersMenu.d.ts +114 -0
  78. package/dist/hooks/useOrdersMenu.js +337 -0
  79. package/dist/hooks/useRegimenChoice.d.ts +23 -0
  80. package/dist/hooks/useRegimenChoice.js +50 -0
  81. package/dist/hooks/useResendCountdown.d.ts +2 -0
  82. package/dist/hooks/useResendCountdown.js +19 -0
  83. package/dist/hooks/useStepField.d.ts +8 -0
  84. package/dist/hooks/useStepField.js +17 -0
  85. package/dist/hooks/useTypingCue.d.ts +11 -0
  86. package/dist/hooks/useTypingCue.js +41 -0
  87. package/dist/hooks/useWelcomeTyping.d.ts +2 -0
  88. package/dist/hooks/useWelcomeTyping.js +25 -0
  89. package/dist/index.d.ts +5 -0
  90. package/dist/index.js +5 -0
  91. package/dist/staff/CardNoteActions.d.ts +10 -0
  92. package/dist/staff/CardNoteActions.js +16 -0
  93. package/dist/staff/OrderFormNote.d.ts +8 -0
  94. package/dist/staff/OrderFormNote.js +8 -0
  95. package/dist/staff/OrdersMenuNote.d.ts +8 -0
  96. package/dist/staff/OrdersMenuNote.js +8 -0
  97. package/dist/staff/RegimenChoiceNote.d.ts +7 -0
  98. package/dist/staff/RegimenChoiceNote.js +8 -0
  99. package/dist/staff/features.d.ts +9 -0
  100. package/dist/staff/features.js +8 -0
  101. package/dist/staff/index.d.ts +11 -0
  102. package/dist/staff/index.js +7 -0
  103. package/dist/ui/Bubble.d.ts +5 -0
  104. package/dist/ui/Bubble.js +9 -0
  105. package/dist/ui/CardActions.d.ts +34 -0
  106. package/dist/ui/CardActions.js +28 -0
  107. package/dist/ui/Conversation.d.ts +69 -0
  108. package/dist/ui/Conversation.js +192 -0
  109. package/dist/ui/Markdown.d.ts +11 -0
  110. package/dist/ui/Markdown.js +51 -0
  111. package/dist/ui/NoteFold.d.ts +19 -0
  112. package/dist/ui/NoteFold.js +12 -0
  113. package/dist/ui/NoteViewControl.d.ts +19 -0
  114. package/dist/ui/NoteViewControl.js +20 -0
  115. package/dist/ui/OrderForm.d.ts +71 -0
  116. package/dist/ui/OrderForm.js +118 -0
  117. package/dist/ui/OrdersMenu.d.ts +71 -0
  118. package/dist/ui/OrdersMenu.js +128 -0
  119. package/dist/ui/RegimenChoice.d.ts +23 -0
  120. package/dist/ui/RegimenChoice.js +16 -0
  121. package/dist/ui/SkipAvatar.d.ts +7 -0
  122. package/dist/ui/SkipAvatar.js +8 -0
  123. package/dist/ui/StaffButton.d.ts +18 -0
  124. package/dist/ui/StaffButton.js +17 -0
  125. package/dist/ui/Welcome.d.ts +91 -0
  126. package/dist/ui/Welcome.js +128 -0
  127. package/dist/ui/index.d.ts +8 -0
  128. package/dist/ui/index.js +7 -0
  129. package/dist/ui/parts.d.ts +38 -0
  130. package/dist/ui/parts.js +6 -0
  131. package/package.json +115 -4
@@ -0,0 +1,271 @@
1
+ // The Order form's rules: its medicines and their rounds, the SIG and dispense amount it fills in, the pharmacy each
2
+ // medicine goes to, and when Create, Update or a queued save may run. Ported from skips-app's patch 180 Order form.
3
+ import { changedFields, dispenseAmount, frequencyCode, isComplete, itemFromCard, lookupFailure, LOOKUP_MESSAGES, oneLine, orderItem, pharmacyMatches, roundNote, SHOWN_PHARMACIES, sigInputs, sigText, AS_NEEDED, } from "./medicationOrder.js";
4
+ import { pharmacyNameOf } from "./ordersMenu.js";
5
+ import { isObject, isString } from "./skipsMessage.js";
6
+ /** usrx's drug search answers a term of at least this many letters. */
7
+ export const SHORTEST_TERM = 3;
8
+ /** The pause in typing after which the drug search runs. */
9
+ export const TYPING_PAUSE_MS = 300;
10
+ export function newItem(key) {
11
+ return {
12
+ key,
13
+ term: '',
14
+ found: [],
15
+ searching: false,
16
+ loadingChoices: false,
17
+ drug: null,
18
+ choices: null,
19
+ doseUnitId: '',
20
+ quantity: '',
21
+ frequencyId: '',
22
+ maxPerDay: '',
23
+ days: '',
24
+ dispenseUnitId: '',
25
+ dispenseAmount: '',
26
+ filledAmount: '',
27
+ refills: '0',
28
+ pharmacyNotes: '',
29
+ earliestFillDate: '',
30
+ substituteOk: true,
31
+ indication: '',
32
+ };
33
+ }
34
+ function sentPharmacy(order) {
35
+ const ncpdpid = order.pharmacy?.ncpdpid;
36
+ return ncpdpid
37
+ ? {
38
+ ncpdpid,
39
+ name: pharmacyNameOf(order),
40
+ address: order.pharmacy?.address ?? '',
41
+ }
42
+ : null;
43
+ }
44
+ /** A sent order read as the card it was sent from, which usrx keeps with it. */
45
+ export function cardOfOrder(order) {
46
+ return {
47
+ uid: order.uid,
48
+ ddid: order.ddid ?? '',
49
+ drugName: order.drugName ?? '',
50
+ ...(order.drugDetails === undefined ? {} : { drugDetails: order.drugDetails }),
51
+ doseUnitId: order.doseUnitId,
52
+ quantity: order.quantity,
53
+ frequencyId: order.frequencyId,
54
+ days: order.days,
55
+ sig: order.sig ?? '',
56
+ dispenseUnitId: order.dispenseUnitId,
57
+ dispenseAmount: order.dispenseAmount,
58
+ refills: order.refills,
59
+ pharmacyNotes: order.pharmacyNotes ?? null,
60
+ ...(order.substituteOk === undefined ? {} : { substituteOk: order.substituteOk }),
61
+ pharmacyName: pharmacyNameOf(order),
62
+ pharmacy: sentPharmacy(order),
63
+ };
64
+ }
65
+ export function isPastOrder(card) {
66
+ return 'sentAt' in card;
67
+ }
68
+ /** A staged card opened to change, its fields as Treat holds them. */
69
+ export function cardItem(card, key) {
70
+ // A card in Treat was ordered already, so it is not asked its indication (joinskips/usrx#455).
71
+ return { ...newItem(key), ...itemFromCard(card), indication: undefined };
72
+ }
73
+ /** A sent order to order again: a new order with no fill date and no round start, which the form numbers again. */
74
+ export function reorderItem(card, key) {
75
+ return {
76
+ ...cardItem(card, key),
77
+ earliestFillDate: '',
78
+ pharmacyNotes: roundNote(card.pharmacyNotes, 1, 1),
79
+ };
80
+ }
81
+ // A select gives its value as text, and a card may hold an id as a number.
82
+ function chosen(list, id) {
83
+ return list?.find((each) => each.id === String(id)) ?? null;
84
+ }
85
+ export function frequencyOf(item) {
86
+ return chosen(item.choices?.frequencies, item.frequencyId);
87
+ }
88
+ /** Plain as needed states no count, so the form asks for the most times a day. */
89
+ export function isAsNeeded(item) {
90
+ return frequencyCode(frequencyOf(item)?.name) === AS_NEEDED;
91
+ }
92
+ /** The item with its chosen options, its one-line notes and its SIG, which a SIG typed in Treat keeps until its inputs change. */
93
+ export function resolved(item) {
94
+ const doseUnit = chosen(item.choices?.doseUnits, item.doseUnitId);
95
+ const frequency = frequencyOf(item);
96
+ const cardSig = item.cardSigInputs === sigInputs(item) ? item.cardSig : undefined;
97
+ return {
98
+ ...item,
99
+ doseUnit,
100
+ frequency,
101
+ dispenseUnit: chosen(item.choices?.dispenseUnits, item.dispenseUnitId),
102
+ pharmacyNotes: oneLine(item.pharmacyNotes),
103
+ sig: cardSig ??
104
+ sigText({
105
+ quantity: item.quantity,
106
+ doseUnit: doseUnit?.name,
107
+ frequency: frequency?.name,
108
+ days: item.days,
109
+ }),
110
+ };
111
+ }
112
+ export function computedAmount(item) {
113
+ const frequency = frequencyOf(item);
114
+ return dispenseAmount({
115
+ quantity: item.quantity,
116
+ frequency: frequency?.name,
117
+ perDay: frequency?.count,
118
+ days: item.days,
119
+ maxPerDay: item.maxPerDay,
120
+ });
121
+ }
122
+ export function newPicker() {
123
+ return {
124
+ zip: '',
125
+ words: '',
126
+ mailOrder: false,
127
+ pharmacies: null,
128
+ pharmacy: null,
129
+ pickedWith: null,
130
+ };
131
+ }
132
+ /** The place a search is for. The words only filter its answer, so they never search again. */
133
+ export function placeOf(picker) {
134
+ return `${picker.zip.trim()}|${String(picker.mailOrder)}`;
135
+ }
136
+ export function canSearchPharmacies(picker) {
137
+ return picker.mailOrder || /^\d{5}$/.test(picker.zip.trim());
138
+ }
139
+ export function shownPharmacies(picker) {
140
+ return (picker.pharmacies ?? [])
141
+ .filter((pharmacy) => pharmacyMatches(pharmacy, picker.words))
142
+ .slice(0, SHOWN_PHARMACIES);
143
+ }
144
+ export function picked(picker, pharmacy) {
145
+ return {
146
+ ...picker,
147
+ pharmacy,
148
+ pickedWith: {
149
+ zip: picker.zip.trim(),
150
+ words: picker.words.trim(),
151
+ mailOrder: picker.mailOrder,
152
+ },
153
+ };
154
+ }
155
+ export function pharmacyChange(picker) {
156
+ const { pharmacy, pickedWith } = picker;
157
+ if (!pharmacy || !pickedWith)
158
+ return null;
159
+ return {
160
+ ncpdp_id: pharmacy.ncpdpid,
161
+ ...(pickedWith.mailOrder ? {} : { zip: pickedWith.zip }),
162
+ search_text: pickedWith.words,
163
+ mail_order: pickedWith.mailOrder,
164
+ };
165
+ }
166
+ /** A medicine after the first follows the first one's pharmacy until it picks its own. */
167
+ export function pharmacyOf(medicines, medicine) {
168
+ return medicine.picker.pharmacy ?? medicines[0]?.picker.pharmacy ?? null;
169
+ }
170
+ /** Each round's notes start with which round it is, once a medicine has two or more. */
171
+ export function renumbered(rounds) {
172
+ return rounds.map((item, index) => ({
173
+ ...item,
174
+ pharmacyNotes: roundNote(item.pharmacyNotes, index + 1, rounds.length),
175
+ }));
176
+ }
177
+ function readyItem(item, pharmacy) {
178
+ const { drug, doseUnit, frequency, dispenseUnit, sig } = item;
179
+ if (!pharmacy || !drug || !doseUnit || !frequency || !dispenseUnit || !sig || !isComplete(item)) {
180
+ return null;
181
+ }
182
+ return { ...item, drug, doseUnit, frequency, dispenseUnit, sig, pharmacy };
183
+ }
184
+ /**
185
+ * A new order's items, every round complete and going to its medicine's pharmacy, or null while any is not. A medicine
186
+ * in rounds is one set, numbered from 1, and a one-round medicine has none.
187
+ */
188
+ export function newOrderItems(medicines) {
189
+ const items = medicines.flatMap((medicine, set) => medicine.rounds.map((item, round, [first]) => {
190
+ // A medicine's indication and duplicate choice are asked on its first round and go with each of its rounds.
191
+ const asked = { ...item, indication: first?.indication, discontinueDuplicate: first?.discontinueDuplicate };
192
+ const ready = readyItem(resolved(asked), pharmacyOf(medicines, medicine));
193
+ if (!ready || medicine.rounds.length < 2)
194
+ return ready;
195
+ return { ...ready, set: set + 1, round: round + 1 };
196
+ }));
197
+ return items.every((item) => item !== null) ? items : null;
198
+ }
199
+ // A card may lack what a new order needs, such as a frequency, so a change asks only that nothing it changes is left
200
+ // blank. usrx refuses what Treat cannot take, in words the form shows.
201
+ export const CAN_BE_BLANK = ['days', 'pharmacyNotes', 'earliestFillDate'];
202
+ /** A staged card's changes, or null while there are none, the choices have not loaded, or a changed field is blank. */
203
+ export function cardChanges(card, item, picker) {
204
+ if (!item.choices)
205
+ return null;
206
+ const changes = changedFields(card, resolved(item));
207
+ const entries = Object.entries(changes);
208
+ if (entries.length === 0 && !picker.pharmacy)
209
+ return null;
210
+ return entries.every(([name, value]) => CAN_BE_BLANK.includes(name) || String(value ?? '') !== '') ? changes : null;
211
+ }
212
+ /** A queued medicine is saved whole, so it is one a new order could stage, changed and with a pharmacy. */
213
+ export function queuedChange(card, item, picker) {
214
+ const changed = Object.keys(changedFields(card, resolved(item))).length > 0 || picker.pharmacy !== null;
215
+ const ready = readyItem(resolved(item), picker.pharmacy ?? card.pharmacy ?? null);
216
+ return changed && ready ? orderItem(ready) : null;
217
+ }
218
+ const FIELD_INPUTS = {
219
+ pharmacy: 'pharmacy',
220
+ dose: 'quantity',
221
+ 'dose unit': 'doseUnit',
222
+ frequency: 'frequency',
223
+ sig: 'quantity',
224
+ 'dispense amount': 'dispenseAmount',
225
+ 'dispense unit': 'dispenseUnit',
226
+ };
227
+ /** The input a refusal's field opens at: the SIG's first input for any field the form does not name. */
228
+ export function focusField(focus) {
229
+ return FIELD_INPUTS[focus] ?? 'quantity';
230
+ }
231
+ const text = (value) => (isString(value) ? value : '');
232
+ function chartOf(value) {
233
+ if (!isObject(value) || !isString(value.uid) || !value.uid)
234
+ return [];
235
+ return [
236
+ {
237
+ uid: value.uid,
238
+ firstName: text(value.firstName),
239
+ lastName: text(value.lastName),
240
+ dob: text(value.dob),
241
+ phoneEnding: text(value.phoneEnding),
242
+ city: text(value.city),
243
+ zip: text(value.zip),
244
+ lastVisit: text(value.lastVisit),
245
+ pharmacy: text(value.pharmacy),
246
+ },
247
+ ];
248
+ }
249
+ /** The charts Create asks staff to pick from: only when more than one fits, since usrx stages on a lone one itself. */
250
+ export function chartsToPick(answer) {
251
+ const charts = isObject(answer) && Array.isArray(answer.charts) ? answer.charts.flatMap(chartOf) : [];
252
+ return {
253
+ charts: charts.length > 1 ? charts : [],
254
+ searchLink: isObject(answer) ? text(answer.searchLink) : '',
255
+ };
256
+ }
257
+ /** What a Treat call that rejected shows: treat_lookups' answer when it is one, or that the lookup failed. */
258
+ export function lookupFailureOf(error) {
259
+ return (lookupFailure(error) ?? {
260
+ message: LOOKUP_MESSAGES.LOOKUP_FAILED,
261
+ code: error instanceof Error ? error.name : 'unknown',
262
+ status: undefined,
263
+ ref: '',
264
+ });
265
+ }
266
+ /** usrx's words for a change it refused, '' when it gave none, or null when it took the change. */
267
+ export function refusalOf(answer) {
268
+ if (!isObject(answer) || !answer.refused)
269
+ return null;
270
+ return isString(answer.why) ? answer.why : '';
271
+ }
@@ -0,0 +1,56 @@
1
+ import { type OrderRow, type PastOrder, type StagedCard } from './medicationOrder.ts';
2
+ export type OrderList = 'staged' | 'current' | 'refills' | 'past';
3
+ export interface OrderLists {
4
+ current: OrderRow[];
5
+ refills: OrderRow[];
6
+ past: OrderRow[];
7
+ }
8
+ /** Current orders holds what is running and not cancelled, Refills what a pharmacy can still fill, Past orders all. */
9
+ export declare function orderLists(orders: readonly PastOrder[], today: string): OrderLists;
10
+ /** A row's first order, the one a re-order starts from and whose send day and pharmacy it shows. */
11
+ export declare function firstOf(row: OrderRow): PastOrder;
12
+ /** The order a row speaks for: a set's round running today, else its last. */
13
+ export declare function shownOrder(row: OrderRow, today: string): PastOrder;
14
+ /** The order's pharmacy name, '' when it has none. Treat writes `none` for a missing part. */
15
+ export declare function pharmacyNameOf(order: PastOrder): string;
16
+ /** Where an order went, as one line, leaving out the "none" Treat writes for a pharmacy it has no record of. */
17
+ export declare function pharmacyWords(order: PastOrder): string;
18
+ export type TagTone = 'available' | 'ended' | 'plain' | 'warning';
19
+ export type TagName = 'cancelled' | 'current' | 'supplyEnds' | 'completed' | 'roundOf' | 'refillsLeft' | 'discontinued' | 'memberStopped' | 'cancelPending' | 'cancelDenied' | 'cancelFailed';
20
+ /** The values a tag's words take: a day as YYYY-MM-DD, a round of so many, refills left of the total. */
21
+ export interface TagValues {
22
+ day?: string;
23
+ round?: number | undefined;
24
+ rounds?: number | undefined;
25
+ left?: number;
26
+ total?: string | number | null | undefined;
27
+ }
28
+ export interface RowTag {
29
+ name: TagName;
30
+ tone: TagTone;
31
+ values: TagValues;
32
+ }
33
+ /**
34
+ * A row's tags, green only for what a pharmacy can still fill. Past orders says each row's status. Current orders and
35
+ * Refills hold no cancelled order, and say what is left of it: a set's round, refills, or its supply.
36
+ */
37
+ export declare function rowTags(row: OrderRow, list: OrderList, today: string): RowTag[];
38
+ export declare const STATUS_LIST: readonly string[];
39
+ export declare function rowStatuses(row: OrderRow, today: string): Set<string>;
40
+ /** How many of the rows carry a status, whatever the filter shows. A row with two statuses counts for both. */
41
+ export declare function statusCount(rows: readonly OrderRow[], status: string, today: string): number;
42
+ /** The rows carrying any ticked status. */
43
+ export declare function tickedRows(rows: readonly OrderRow[], ticked: ReadonlySet<string>, today: string): OrderRow[];
44
+ /** A card's key in the list: a queued card has no Treat uid of its own yet. */
45
+ export declare function cardKey(card: Pick<StagedCard, 'status' | 'uid' | 'queuedId'>): string;
46
+ /** The pharmacy whose order must go before a queued card can, or '' when the patient's other order is in Treat only. */
47
+ export declare function stagedPharmacy(cards: readonly StagedCard[]): string;
48
+ export type OrderAction = 'cancel' | 'discontinue' | 'pharmacy';
49
+ /** A Discontinue or Cancel Rx starts from the member's own stop reason, one they asked for and nobody acted on. */
50
+ export declare function actionReason(action: OrderAction, row: OrderRow): string;
51
+ /**
52
+ * The private note an action posts. Discontinue names every order of the row, since the chart marks it whatever the
53
+ * pharmacy still holds. Cancel Rx and Change pharmacy name the rounds Treat still takes a cancel for, and a pharmacy
54
+ * change gives no reason.
55
+ */
56
+ export declare function actionCommand(action: OrderAction, row: OrderRow, reason: string, now?: Date): string;
@@ -0,0 +1,129 @@
1
+ // The Orders menu's rules: which sent orders each list shows, the tags a row carries, the Past orders status filter and
2
+ // what a row's actions post. The menu draws these on the web dashboard and in the mobile app alike.
3
+ import { cancelCommand, discontinueCommand } from "./cardNote.js";
4
+ import { cancelBadge, cancellableUids, CANCEL_BADGES, currentRound, isQueued, orderRows, orderStatuses, ORDER_STATUS, supplyRunning, } from "./medicationOrder.js";
5
+ /** Current orders holds what is running and not cancelled, Refills what a pharmacy can still fill, Past orders all. */
6
+ export function orderLists(orders, today) {
7
+ return {
8
+ current: orderRows(orders.filter((order) => orderStatuses(order, today).includes(ORDER_STATUS.CURRENT))),
9
+ // A pharmacy fills nothing more of a cancelled prescription.
10
+ refills: orderRows(orders.filter((order) => Boolean(order.refillsLeft) && !order.cancelled)),
11
+ past: orderRows(orders),
12
+ };
13
+ }
14
+ function inRow(order) {
15
+ if (!order)
16
+ throw new Error('An order row holds at least one order');
17
+ return order;
18
+ }
19
+ /** A row's first order, the one a re-order starts from and whose send day and pharmacy it shows. */
20
+ export function firstOf(row) {
21
+ return inRow(row.orders[0]);
22
+ }
23
+ /** The order a row speaks for: a set's round running today, else its last. */
24
+ export function shownOrder(row, today) {
25
+ return (row.set ? currentRound(row, today) : null) ?? inRow(row.orders.at(-1));
26
+ }
27
+ /** The order's pharmacy name, '' when it has none. Treat writes `none` for a missing part. */
28
+ export function pharmacyNameOf(order) {
29
+ return [order.pharmacy?.name, order.pharmacyName].find((words) => words && words !== 'none') ?? '';
30
+ }
31
+ /** Where an order went, as one line, leaving out the "none" Treat writes for a pharmacy it has no record of. */
32
+ export function pharmacyWords(order) {
33
+ return [pharmacyNameOf(order), order.pharmacy?.address]
34
+ .filter((words) => words && words !== 'none')
35
+ .join(', ');
36
+ }
37
+ const CANCEL_TAGS = new Map([
38
+ [CANCEL_BADGES.PENDING, { name: 'cancelPending', tone: 'plain', values: {} }],
39
+ [CANCEL_BADGES.DENIED, { name: 'cancelDenied', tone: 'warning', values: {} }],
40
+ [CANCEL_BADGES.FAILED, { name: 'cancelFailed', tone: 'warning', values: {} }],
41
+ ]);
42
+ /**
43
+ * A row's tags, green only for what a pharmacy can still fill. Past orders says each row's status. Current orders and
44
+ * Refills hold no cancelled order, and say what is left of it: a set's round, refills, or its supply.
45
+ */
46
+ export function rowTags(row, list, today) {
47
+ const round = row.set ? currentRound(row, today) : null;
48
+ const order = shownOrder(row, today);
49
+ // An empty end from Treat means none was counted, as no end does.
50
+ const endsOn = [row.set?.endsOn, order.supplyEndsOn].find((day) => day);
51
+ const cancelled = row.orders.some((each) => each.cancelled);
52
+ const discontinued = row.orders.some((each) => each.discontinued);
53
+ const tags = [];
54
+ const add = (name, tone, values = {}) => tags.push({ name, tone, values });
55
+ if (list === 'past') {
56
+ if (cancelled)
57
+ add('cancelled', 'ended');
58
+ else if (!endsOn)
59
+ add('current', 'available');
60
+ else if (supplyRunning({ supplyEndsOn: endsOn }, today)) {
61
+ add('current', 'available');
62
+ add('supplyEnds', 'plain', { day: endsOn });
63
+ }
64
+ else
65
+ add('completed', 'plain', { day: endsOn });
66
+ }
67
+ else {
68
+ if (row.set && round)
69
+ add('roundOf', 'available', { round: round.set?.round, rounds: row.set.rounds });
70
+ if (order.refillsLeft) {
71
+ add('refillsLeft', discontinued ? 'plain' : 'available', { left: order.refillsLeft, total: order.refills });
72
+ }
73
+ else if (endsOn)
74
+ add('supplyEnds', 'plain', { day: endsOn });
75
+ }
76
+ if (discontinued)
77
+ add('discontinued', 'warning');
78
+ // The member said they stopped it in the chat's check-in, and nobody has acted on it yet. A Cancel Rx is acting on
79
+ // it, though usrx records no stop for one.
80
+ else if (!cancelled && row.orders.some((each) => each.stop?.requested))
81
+ add('memberStopped', 'warning');
82
+ const cancel = row.orders.map((each) => cancelBadge(each.cancelStatus)).find(Boolean);
83
+ const cancelTag = CANCEL_TAGS.get(cancel ?? '');
84
+ if (cancelTag)
85
+ tags.push(cancelTag);
86
+ return tags;
87
+ }
88
+ // The Past orders status filter's statuses, in the order it lists them.
89
+ export const STATUS_LIST = [
90
+ ORDER_STATUS.CURRENT,
91
+ ORDER_STATUS.COMPLETED,
92
+ ORDER_STATUS.CANCELLED,
93
+ ORDER_STATUS.DISCONTINUED,
94
+ ];
95
+ export function rowStatuses(row, today) {
96
+ return new Set(row.orders.flatMap((order) => orderStatuses(order, today)));
97
+ }
98
+ /** How many of the rows carry a status, whatever the filter shows. A row with two statuses counts for both. */
99
+ export function statusCount(rows, status, today) {
100
+ return rows.filter((row) => rowStatuses(row, today).has(status)).length;
101
+ }
102
+ /** The rows carrying any ticked status. */
103
+ export function tickedRows(rows, ticked, today) {
104
+ return rows.filter((row) => [...rowStatuses(row, today)].some((status) => ticked.has(status)));
105
+ }
106
+ /** A card's key in the list: a queued card has no Treat uid of its own yet. */
107
+ export function cardKey(card) {
108
+ return isQueued(card) ? `queued-${String(card.queuedId)}` : card.uid;
109
+ }
110
+ /** The pharmacy whose order must go before a queued card can, or '' when the patient's other order is in Treat only. */
111
+ export function stagedPharmacy(cards) {
112
+ return cards.find((card) => !isQueued(card))?.pharmacyName ?? '';
113
+ }
114
+ /** A Discontinue or Cancel Rx starts from the member's own stop reason, one they asked for and nobody acted on. */
115
+ export function actionReason(action, row) {
116
+ if (action === 'pharmacy')
117
+ return '';
118
+ return row.orders.find((order) => order.stop?.requested)?.stop?.reason ?? '';
119
+ }
120
+ /**
121
+ * The private note an action posts. Discontinue names every order of the row, since the chart marks it whatever the
122
+ * pharmacy still holds. Cancel Rx and Change pharmacy name the rounds Treat still takes a cancel for, and a pharmacy
123
+ * change gives no reason.
124
+ */
125
+ export function actionCommand(action, row, reason, now = new Date()) {
126
+ if (action === 'discontinue')
127
+ return discontinueCommand(row.orders.map((order) => order.uid), reason);
128
+ return cancelCommand(cancellableUids(row, now), action === 'pharmacy' ? '' : reason);
129
+ }
@@ -0,0 +1,42 @@
1
+ import { type StaffMessage } from './usrxNote.ts';
2
+ export declare const FIRST_LINE_TAG = "[open-evidence]";
3
+ export declare const PICK_COMMAND = "/treat-pick";
4
+ export declare function pickNote(number: number): string;
5
+ export interface RegimenOption {
6
+ number: number;
7
+ text: string;
8
+ /** The Treat product the button builds, or null when usrx names none. */
9
+ product: string | null;
10
+ }
11
+ /** The options of a regimen choice note, each with a text and a whole number, and none from any other note. */
12
+ export declare function regimenOptions(contentAttributes: unknown): RegimenOption[];
13
+ export declare function optionLabel(option: RegimenOption): string;
14
+ export declare const PICK_ANSWER_SECONDS = 600;
15
+ export interface ChoiceState {
16
+ picked: number | null;
17
+ /** A newer choice note came before any pick: usrx applies a pick to the latest one, so this one's numbers are stale. */
18
+ replaced: boolean;
19
+ waiting: boolean;
20
+ /** When the wait on an unanswered pick ends, in seconds, while it lasts. */
21
+ waitEnds: number | null;
22
+ }
23
+ /**
24
+ * What became of a choice note: the option a later private note picked, or that a newer choice note replaced it.
25
+ * now is in seconds, as a message's createdAt is.
26
+ */
27
+ export declare function choiceState(messages: readonly StaffMessage[] | undefined, noteId: number, options: readonly RegimenOption[], now: number): ChoiceState;
28
+ /** A press of an option on this device, at a time in seconds, whose note may not be in the messages yet. */
29
+ export interface PickPress {
30
+ number: number;
31
+ at: number;
32
+ }
33
+ export interface ChoiceView extends ChoiceState {
34
+ /** No option can be pressed: one was picked or pressed, or a newer choice note replaced this one. */
35
+ closed: boolean;
36
+ }
37
+ /**
38
+ * What a choice note shows once this device's press is counted. A note on its way has no id yet for choiceState to
39
+ * read, so the press holds the options until its note shows, and no longer than a pick waits on usrx, in case it never
40
+ * does.
41
+ */
42
+ export declare function choiceView(state: ChoiceState, press: PickPress | null, now: number): ChoiceView;
@@ -0,0 +1,73 @@
1
+ // A private note usrx posts when OpenEvidence's answer names several regimens, each a button that stages its Treat card
2
+ // unsent (joinskips/open-evidence#4). A click posts pickNote as a private note, the way a provider types /treat-pick.
3
+ import { isNumber, isObject, isString } from "./skipsMessage.js";
4
+ import { isUsrxNote, messagesAfter, noteAttribute, withoutLeadingMarks } from "./usrxNote.js";
5
+ // usrx's first-line notes, its answer to a pick among them, start with this (joinskips/usrx, skips-app/first-line-notes.ts).
6
+ export const FIRST_LINE_TAG = '[open-evidence]';
7
+ export const PICK_COMMAND = '/treat-pick';
8
+ export function pickNote(number) {
9
+ return `${PICK_COMMAND} ${String(number)}`;
10
+ }
11
+ function regimenOption(value) {
12
+ if (!isObject(value) || !isString(value.text) || !value.text)
13
+ return [];
14
+ if (!isNumber(value.number) || !Number.isInteger(value.number))
15
+ return [];
16
+ const product = isObject(value.product) && isString(value.product.text) && value.product.text ? value.product.text : null;
17
+ return [{ number: value.number, text: value.text, product }];
18
+ }
19
+ /** The options of a regimen choice note, each with a text and a whole number, and none from any other note. */
20
+ export function regimenOptions(contentAttributes) {
21
+ const choice = isObject(contentAttributes) ? contentAttributes.usrxRegimenChoice : undefined;
22
+ const options = isObject(choice) ? choice.options : undefined;
23
+ return Array.isArray(options) ? options.flatMap(regimenOption) : [];
24
+ }
25
+ export function optionLabel(option) {
26
+ return option.product ? `${option.text} (${option.product})` : option.text;
27
+ }
28
+ // usrx's receiver reads a pick the same way (lambda/receiver.ts), so a note it acts on is a note this counts.
29
+ const PICK = new RegExp(`^${PICK_COMMAND}[*_\`]*\\s+(\\d+)\\b`, 'i');
30
+ function pickedNumber(message) {
31
+ const match = PICK.exec(withoutLeadingMarks(message.content));
32
+ return message.private && match ? Number(match[1]) : null;
33
+ }
34
+ // usrx's runner takes one job at a time for up to 300 seconds (joinskips/usrx, infra/aws.sh), and a run that stops
35
+ // before staging posts nothing, so a pick stops waiting after this long.
36
+ export const PICK_ANSWER_SECONDS = 600;
37
+ /**
38
+ * What became of a choice note: the option a later private note picked, or that a newer choice note replaced it.
39
+ * now is in seconds, as a message's createdAt is.
40
+ */
41
+ export function choiceState(messages, noteId, options, now) {
42
+ const later = messagesAfter(messages, noteId);
43
+ const next = later.findIndex((message) => Boolean(noteAttribute(message, 'usrxRegimenChoice')));
44
+ const answering = next < 0 ? later : later.slice(0, next);
45
+ const pickAt = answering.findIndex((message) => options.some((option) => option.number === pickedNumber(message)));
46
+ const pick = answering[pickAt];
47
+ if (!pick)
48
+ return { picked: null, replaced: next >= 0, waiting: false, waitEnds: null };
49
+ // A pick waits until usrx answers it with a note of its own, which may come after a newer choice note.
50
+ const answered = later
51
+ .slice(pickAt + 1)
52
+ .some((message) => isUsrxNote(message.content) || (message.content ?? '').startsWith(FIRST_LINE_TAG));
53
+ const waitEnds = pick.createdAt + PICK_ANSWER_SECONDS;
54
+ const waiting = !answered && now < waitEnds;
55
+ return { picked: pickedNumber(pick), replaced: false, waiting, waitEnds: waiting ? waitEnds : null };
56
+ }
57
+ /**
58
+ * What a choice note shows once this device's press is counted. A note on its way has no id yet for choiceState to
59
+ * read, so the press holds the options until its note shows, and no longer than a pick waits on usrx, in case it never
60
+ * does.
61
+ */
62
+ export function choiceView(state, press, now) {
63
+ const pressEnds = press && state.picked === null ? press.at + PICK_ANSWER_SECONDS : null;
64
+ const held = press !== null && pressEnds !== null && now < pressEnds ? press : null;
65
+ const picked = state.picked ?? held?.number ?? null;
66
+ return {
67
+ picked,
68
+ replaced: state.replaced,
69
+ closed: picked !== null || state.replaced,
70
+ waiting: held !== null || state.waiting,
71
+ waitEnds: state.waitEnds ?? (held ? pressEnds : null),
72
+ };
73
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Whether a scroll box holds all its content, so there is nothing to scroll. False before the box is laid out, and for
3
+ * a node with no heights to read, as a phone's handle is.
4
+ */
5
+ export declare function contentFits(box: unknown): boolean;
@@ -0,0 +1,15 @@
1
+ function measured(box) {
2
+ return (typeof box === 'object' &&
3
+ box !== null &&
4
+ 'clientHeight' in box &&
5
+ 'scrollHeight' in box &&
6
+ typeof box.clientHeight === 'number' &&
7
+ typeof box.scrollHeight === 'number');
8
+ }
9
+ /**
10
+ * Whether a scroll box holds all its content, so there is nothing to scroll. False before the box is laid out, and for
11
+ * a node with no heights to read, as a phone's handle is.
12
+ */
13
+ export function contentFits(box) {
14
+ return measured(box) && box.clientHeight > 0 && box.scrollHeight <= box.clientHeight;
15
+ }
@@ -0,0 +1,26 @@
1
+ export declare const DOT_CYCLE_MS = 1000;
2
+ export interface TypingState {
3
+ dots: boolean;
4
+ shown: boolean;
5
+ ending: boolean;
6
+ since: number;
7
+ turn: number;
8
+ beats: number;
9
+ }
10
+ export interface TypingStarted {
11
+ type: 'typing';
12
+ skipsLines: number;
13
+ }
14
+ export interface TypingSignal {
15
+ type: 'stopped' | 'shown' | 'capped';
16
+ }
17
+ export type TypingEvent = TypingStarted | TypingSignal;
18
+ export declare const TYPING_IDLE: TypingState;
19
+ export declare function typingReducer(state: TypingState, event: TypingEvent): TypingState;
20
+ /** Where Skips' lines start being kept out of sight, or null while nothing is held. */
21
+ export declare function heldFrom(state: TypingState): number | null;
22
+ export interface TypingTimes {
23
+ leastMs: number;
24
+ limitMs: number;
25
+ }
26
+ export declare const TYPING_TIMES: TypingTimes;
@@ -0,0 +1,29 @@
1
+ // Skip typing, as the Skips App reports it: the dots come up when it says Skip is typing and go when it says Skip
2
+ // stopped or the reply lands. They stay up for at least their minimum, and a reply that lands sooner waits out of
3
+ // sight until then, so the dots never flash.
4
+ // One rise and fall of the three dots. The dots stay up at least this long.
5
+ export const DOT_CYCLE_MS = 1000;
6
+ export const TYPING_IDLE = { dots: false, shown: false, ending: false, since: 0, turn: 0, beats: 0 };
7
+ function down(state) {
8
+ return { ...state, dots: false, shown: false, ending: false };
9
+ }
10
+ export function typingReducer(state, event) {
11
+ if (event.type === 'typing') {
12
+ if (state.dots)
13
+ return { ...state, ending: false, beats: state.beats + 1 };
14
+ return { dots: true, shown: false, ending: false, since: event.skipsLines, turn: state.turn + 1, beats: state.beats + 1 };
15
+ }
16
+ // A timer or a stop that comes after the dots have gone changes nothing.
17
+ if (!state.dots)
18
+ return state;
19
+ if (event.type === 'shown')
20
+ return state.ending ? down(state) : { ...state, shown: true };
21
+ if (event.type === 'stopped' && !state.shown)
22
+ return { ...state, ending: true };
23
+ return down(state);
24
+ }
25
+ /** Where Skips' lines start being kept out of sight, or null while nothing is held. */
26
+ export function heldFrom(state) {
27
+ return state.dots && !state.shown ? state.since : null;
28
+ }
29
+ export const TYPING_TIMES = { leastMs: DOT_CYCLE_MS, limitMs: 30_000 };