-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathEncounterCommandDialog.tsx
More file actions
540 lines (502 loc) · 16.5 KB
/
EncounterCommandDialog.tsx
File metadata and controls
540 lines (502 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import { CardListSkeleton } from "@/components/Common/SkeletonLoading";
import {
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
CommandShortcut,
} from "@/components/ui/command";
import { useShortcutDisplay } from "@/context/ShortcutContext";
import {
ArrowBigRight,
Building2,
CheckCircle2,
Component,
Edit,
HistoryIcon,
MapPin,
NotebookPen,
Pill,
Plus,
RotateCcw,
Users,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { PLUGIN_Component } from "@/PluginEngine";
import query from "@/Utils/request/query";
import { useCareApps } from "@/hooks/useCareApps";
import useQuestionnaireOptions from "@/hooks/useQuestionnaireOptions";
import { useEncounter } from "@/pages/Encounters/utils/EncounterProvider";
import { EncounterRead } from "@/types/emr/encounter/encounter";
import questionnaireApi from "@/types/questionnaire/questionnaireApi";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "raviger";
import { useTranslation } from "react-i18next";
interface ActionItem {
id: string;
label: string;
shortcut?: string;
icon?: React.ReactNode;
disabled?: boolean;
}
interface ActionGroup {
group: string;
items: ActionItem[];
}
interface EncounterCommandDialogProps {
encounter: EncounterRead;
open: boolean;
onOpenChange: (open: boolean) => void;
trigger?: React.ReactNode;
}
export function EncounterCommandDialog({
encounter,
open,
onOpenChange,
trigger,
}: EncounterCommandDialogProps) {
const {
canWriteSelectedEncounter,
canRestartSelectedEncounter,
actions,
selectedEncounterId,
primaryEncounterId,
} = useEncounter();
const { t } = useTranslation();
const [search, setSearch] = useState("");
const navigate = useNavigate();
const questionnaireOptions = useQuestionnaireOptions("encounter_actions");
const { data: questionnaires, isLoading } = useQuery({
queryKey: ["questionnaires", search, "encounter"],
queryFn: query.debounced(questionnaireApi.list, {
queryParams: {
title: search,
status: "active",
subject_type: "encounter",
},
}),
enabled: !!search,
});
useEffect(() => {
if (!open) {
setSearch("");
}
}, [open]);
const getShortcutDisplay = useShortcutDisplay();
const STORAGE_KEY = "encounter-command-dialog-recent-actions";
const MAX_RECENT_ACTIONS = 4;
const getRecentActions = useCallback((): string[] => {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
const parsed = JSON.parse(stored);
return Array.isArray(parsed) ? parsed.slice(0, MAX_RECENT_ACTIONS) : [];
}
return [];
}, []);
const [recentActionsState, setRecentActionsState] =
useState<string[]>(getRecentActions);
// Build encounter URL helper
const buildEncounterUrl = useCallback(
(path: string) => {
const currentEncounterIdToUse = primaryEncounterId || encounter.id;
const baseUrl = `/facility/${encounter.facility.id}/patient/${encounter.patient.id}/encounter/${currentEncounterIdToUse}${path}`;
// Add selectedEncounter parameter if we're viewing a different encounter
if (
selectedEncounterId &&
primaryEncounterId &&
selectedEncounterId !== primaryEncounterId
) {
const separator = path.includes("?") ? "&" : "?";
return `${baseUrl}${separator}selectedEncounter=${selectedEncounterId}`;
}
return baseUrl;
},
[encounter, selectedEncounterId, primaryEncounterId],
);
// Handle action execution
const handleAction = useCallback(
(actionId: string) => {
const actionHandlers: Record<string, () => void> = {
"add-service-request": () =>
navigate(buildEncounterUrl("/questionnaire/service_request")),
"add-medication-request": () =>
navigate(buildEncounterUrl("/questionnaire/medication_request")),
"add-allergy": () =>
navigate(buildEncounterUrl("/questionnaire/allergy_intolerance")),
"add-symptoms": () =>
navigate(buildEncounterUrl("/questionnaire/symptom")),
"add-diagnosis": () =>
navigate(buildEncounterUrl("/questionnaire/diagnosis")),
"update-encounter": () =>
navigate(buildEncounterUrl("/questionnaire/encounter")),
"service-requests": () =>
navigate(buildEncounterUrl("/service_requests")),
"diagnostic-reports": () =>
navigate(buildEncounterUrl("/diagnostic_reports")),
"clinical-history": () =>
navigate(
`/facility/${encounter.facility.id}/patient/${encounter.patient.id}/history/responses?sourceUrl=${encodeURIComponent(
buildEncounterUrl("/updates"),
)}`,
),
"treatment-summary": () =>
navigate(buildEncounterUrl("/treatment_summary")),
"encounter-overview": () => navigate(buildEncounterUrl("/updates")),
plots: () => navigate(buildEncounterUrl("/plots")),
observations: () => navigate(buildEncounterUrl("/observations")),
medicines: () => navigate(buildEncounterUrl("/medicines")),
files: () => navigate(buildEncounterUrl("/files")),
notes: () => navigate(buildEncounterUrl("/notes")),
devices: () => navigate(buildEncounterUrl("/devices")),
consents: () => navigate(buildEncounterUrl("/consents")),
"mark-as-completed": () => actions.markAsCompleted(),
"assign-location": () => actions.assignLocation(),
"view-location-history": () => actions.viewLocationHistory(),
"manage-care-team": () => actions.manageCareTeam(),
"manage-departments": () => actions.manageDepartments(),
dispense: () => actions.dispense(),
"restart-encounter": () => actions.restartEncounter(),
};
const handler = actionHandlers[actionId];
if (handler) {
handler();
return;
}
// Handle dynamic questionnaire actions
if (actionId.startsWith("questionnaire-")) {
const slug = actionId.replace("questionnaire-", "");
navigate(buildEncounterUrl(`/questionnaire/${slug}`));
}
},
[navigate, buildEncounterUrl, actions, encounter],
);
const addRecentAction = useCallback(
(actionId: string): void => {
const currentRecent = getRecentActions();
const filteredRecent = currentRecent.filter((id) => id !== actionId);
const updatedRecent = [actionId, ...filteredRecent].slice(
0,
MAX_RECENT_ACTIONS,
);
localStorage.setItem(STORAGE_KEY, JSON.stringify(updatedRecent));
setRecentActionsState(updatedRecent);
},
[getRecentActions],
);
const recentActions = recentActionsState;
const baseEncounterActions: ActionGroup[] = useMemo(() => {
const groups: ActionGroup[] = [];
// Write actions - only show when user has write permission
if (canWriteSelectedEncounter) {
groups.push({
group: t("encounter_actions"),
items: [
{
id: "add-allergy",
label: t("add_allergy_one"),
shortcut: getShortcutDisplay("add-allergy"),
icon: <Plus />,
},
{
id: "add-symptoms",
label: t("add_symptom"),
shortcut: getShortcutDisplay("add-symptoms"),
icon: <Plus />,
},
{
id: "add-diagnosis",
label: t("add_diagnosis"),
shortcut: getShortcutDisplay("add-diagnosis"),
icon: <Plus />,
},
{
id: "add-service-request",
label: t("service_request"),
shortcut: getShortcutDisplay("add-service-request"),
icon: <Plus />,
},
{
id: "add-medication-request",
label: t("add_medication"),
shortcut: getShortcutDisplay("add-medication-request"),
icon: <Plus />,
},
{
id: "update-encounter",
label: t("update_encounter_details"),
shortcut: getShortcutDisplay("update-encounter"),
icon: <Edit />,
},
],
});
}
// Actions group - different items based on encounter status
const actionItems: ActionItem[] = [
{
id: "clinical-history",
label: t("see_clinical_history"),
shortcut: getShortcutDisplay("clinical-history"),
icon: <Component />,
},
{
id: "view-location-history",
label: t("location_history"),
shortcut: getShortcutDisplay("view-location-history"),
icon: <HistoryIcon />,
},
];
// Add write actions only when user has write permission
if (canWriteSelectedEncounter) {
actionItems.push(
{
id: "consents",
label: t("manage_consents"),
shortcut: getShortcutDisplay("consents"),
icon: <NotebookPen />,
},
{
id: "mark-as-completed",
label:
encounter.encounter_class === "imp" &&
encounter?.status !== "discharged"
? t("mark_for_discharge")
: t("mark_as_completed"),
shortcut: getShortcutDisplay("mark-as-completed"),
icon: <CheckCircle2 />,
},
{
id: "assign-location",
label: t("assign_location"),
shortcut: getShortcutDisplay("assign-location"),
icon: <MapPin />,
},
{
id: "manage-care-team",
label: t("manage_care_team"),
shortcut: getShortcutDisplay("manage-care-team"),
icon: <Users />,
},
{
id: "manage-departments",
label: t("update_department"),
shortcut: getShortcutDisplay("manage-departments"),
icon: <Building2 />,
},
{
id: "dispense",
label: t("dispense"),
shortcut: getShortcutDisplay("dispense"),
icon: <Pill />,
},
);
}
// Add restart action only when user can restart
if (canRestartSelectedEncounter) {
actionItems.push({
id: "restart-encounter",
label: t("restart_encounter"),
shortcut: getShortcutDisplay("restart-encounter"),
icon: <RotateCcw />,
});
}
groups.push({
group: t("actions"),
items: actionItems,
});
// Go to navigation - always available
groups.push({
group: t("go_to"),
items: [
{
id: "encounter-overview",
label: t("ENCOUNTER_TAB__updates"),
shortcut: getShortcutDisplay("encounter-overview"),
icon: <ArrowBigRight />,
},
{
id: "plots",
label: t("ENCOUNTER_TAB__plots"),
shortcut: getShortcutDisplay("plots"),
icon: <ArrowBigRight />,
},
{
id: "observations",
label: t("observations"),
shortcut: getShortcutDisplay("observations"),
icon: <ArrowBigRight />,
},
{
id: "medicines",
label: t("medicines"),
shortcut: getShortcutDisplay("medicines"),
icon: <ArrowBigRight />,
},
{
id: "files",
label: t("files"),
shortcut: getShortcutDisplay("files"),
icon: <ArrowBigRight />,
},
{
id: "notes",
label: t("notes"),
shortcut: getShortcutDisplay("notes"),
icon: <ArrowBigRight />,
},
{
id: "devices",
label: t("devices"),
shortcut: getShortcutDisplay("devices"),
icon: <ArrowBigRight />,
},
{
id: "consents",
label: t("consents"),
shortcut: getShortcutDisplay("consents"),
icon: <ArrowBigRight />,
},
{
id: "service-requests",
label: t("service_requests"),
shortcut: getShortcutDisplay("service-requests"),
icon: <ArrowBigRight />,
},
{
id: "diagnostic-reports",
label: t("ENCOUNTER_TAB__diagnostic_reports"),
shortcut: getShortcutDisplay("diagnostic-reports"),
icon: <ArrowBigRight />,
},
],
});
// Questionnaires - only show when user has write permission
if (canWriteSelectedEncounter) {
groups.push({
group: t("questionnaire"),
items: [
...(
(search.length > 0
? questionnaires?.results
: questionnaireOptions?.results) || []
).map((option) => ({
id: `questionnaire-${option.slug}`,
label: option.title,
icon: <NotebookPen />,
shortcut: getShortcutDisplay(`questionnaire-${option.slug}`),
})),
],
});
}
return groups;
}, [
t,
questionnaireOptions,
questionnaires,
search,
getShortcutDisplay,
canWriteSelectedEncounter,
canRestartSelectedEncounter,
encounter.encounter_class,
encounter?.status,
]);
const findRecentActions = useCallback(
(actionIds: string[], groups: ActionGroup[]) => {
const allActions = groups.flatMap((group) => group.items);
return actionIds
.map((id) => allActions.find((action) => action.id === id))
.filter((action): action is ActionItem => action !== undefined);
},
[],
);
const encounterActions: ActionGroup[] = useMemo(() => {
if (!recentActions.length) return baseEncounterActions;
const recentlyUsedActions = findRecentActions(
recentActions,
baseEncounterActions,
);
if (!recentlyUsedActions.length) return baseEncounterActions;
const recentlyUsedGroup: ActionGroup = {
group: t("recently_used"),
items: recentlyUsedActions,
};
return [recentlyUsedGroup, ...baseEncounterActions];
}, [baseEncounterActions, recentActions, findRecentActions, t]);
const handleSelect = useCallback(
(actionId: string) => {
addRecentAction(actionId);
handleAction(actionId);
onOpenChange(false);
},
[handleAction, onOpenChange, addRecentAction],
);
const careApps = useCareApps();
return (
<>
{trigger}
<CommandDialog
open={open}
onOpenChange={onOpenChange}
className="md:max-w-2xl"
>
<div className="border-b border-gray-100 shadow-xs">
<CommandInput
placeholder={t("search_encounter_command")}
className="border-none focus:ring-0 text-base sm:text-sm"
onValueChange={setSearch}
/>
</div>
<CommandList className="h-[80vh] max-h-[80vh] w-full">
<CommandEmpty>
{isLoading && search.length > 0 ? (
<div className="space-y-2">
<CardListSkeleton count={3} />
</div>
) : (
t("no_results")
)}
</CommandEmpty>
{encounterActions.map((group) => (
<div key={group.group}>
<CommandGroup heading={group.group} className="px-2">
{group.items.map((action) => (
<CommandItem
key={`${group.group}-${action.id}`}
value={`${group.group} ${action.id} ${action.label}`}
onSelect={() => handleSelect(action.id)}
className="rounded-md cursor-pointer hover:bg-gray-100 flex justify-between aria-selected:bg-gray-100"
autoFocus={false}
disabled={action.disabled}
>
{action.icon}
<span className="flex-1">{action.label}</span>
{action.shortcut && (
<CommandShortcut className="ml-2 text-xs text-gray-500 bg-white border border-gray-200 shadow-xs px-1.5 py-0.5 rounded">
{action.shortcut}
</CommandShortcut>
)}
</CommandItem>
))}
</CommandGroup>
<CommandSeparator />
</div>
))}
{careApps.some(
(plugin) =>
!plugin.isLoading && plugin.components?.EncounterActions,
) && (
<CommandGroup heading={t("plugin_actions")} className="px-0">
<PLUGIN_Component
__name="EncounterActions"
encounter={encounter}
className="rounded-md cursor-pointer text-gray-600 hover:bg-gray-100 flex justify-baseline aria-selected:bg-gray-100 w-full p-2"
/>
</CommandGroup>
)}
</CommandList>
</CommandDialog>
</>
);
}