@openmrs/esm-patient-chart-app 11.3.1-pre.9304 → 11.3.1-pre.9309

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.
@@ -0,0 +1,700 @@
1
+ import React, { useCallback, useEffect, useMemo, useState } from 'react';
2
+ import classNames from 'classnames';
3
+ import { Controller, FormProvider, useForm } from 'react-hook-form';
4
+ import { useTranslation } from 'react-i18next';
5
+ import { useSWRConfig } from 'swr';
6
+ import {
7
+ Button,
8
+ ButtonSet,
9
+ ContentSwitcher,
10
+ Form,
11
+ FormGroup,
12
+ InlineLoading,
13
+ InlineNotification,
14
+ RadioButton,
15
+ RadioButtonGroup,
16
+ Row,
17
+ Stack,
18
+ Switch,
19
+ } from '@carbon/react';
20
+ import { zodResolver } from '@hookform/resolvers/zod';
21
+ import {
22
+ Extension,
23
+ ExtensionSlot,
24
+ launchWorkspaceGroup2,
25
+ OpenmrsFetchError,
26
+ saveVisit,
27
+ showSnackbar,
28
+ updateVisit,
29
+ useConfig,
30
+ useConnectivity,
31
+ useEmrConfiguration,
32
+ useLayoutType,
33
+ useVisit,
34
+ type Visit,
35
+ Workspace2,
36
+ type Workspace2DefinitionProps,
37
+ type AssignedExtension,
38
+ type NewVisitPayload,
39
+ } from '@openmrs/esm-framework';
40
+ import {
41
+ createOfflineVisitForPatient,
42
+ invalidateVisitByUuid,
43
+ invalidateVisitAndEncounterData,
44
+ useActivePatientEnrollment,
45
+ } from '@openmrs/esm-patient-common-lib';
46
+ import { MemoizedRecommendedVisitType } from './recommended-visit-type.component';
47
+ import {
48
+ convertToDate,
49
+ createVisitAttribute,
50
+ deleteVisitAttribute,
51
+ extractErrorMessagesFromResponse,
52
+ updateVisitAttribute,
53
+ useConditionalVisitTypes,
54
+ useVisitFormCallbacks,
55
+ useVisitFormSchemaAndDefaultValues,
56
+ visitStatuses,
57
+ type ErrorObject,
58
+ type VisitFormCallbacks,
59
+ type VisitFormData,
60
+ } from './visit-form.resource';
61
+ import BaseVisitType from './base-visit-type.component';
62
+ import LocationSelector from './location-selector.component';
63
+ import VisitAttributeTypeFields from './visit-attribute-type.component';
64
+ import VisitDateTimeSection from './visit-date-time.component';
65
+ import { useVisitAttributeTypes } from '../hooks/useVisitAttributeType';
66
+ import { type ChartConfig } from '../../config-schema';
67
+ import styles from './visit-form.scss';
68
+
69
+ interface VisitAttribute {
70
+ attributeType: string;
71
+ value: string;
72
+ }
73
+
74
+ /**
75
+ * Extra visit information provided by extensions via the extra-visit-attribute-slot.
76
+ * Extensions can use this to add custom attributes to visits.
77
+ */
78
+ export interface ExtraVisitInfo {
79
+ /**
80
+ * Optional callback that extensions can provide to perform final
81
+ * preparation or validation before the visit is created/updated.
82
+ */
83
+ handleCreateExtraVisitInfo?: () => void;
84
+ /**
85
+ * Array of visit attributes to be included in the visit payload.
86
+ * Each attribute must have an attributeType (UUID) and a value (string).
87
+ */
88
+ attributes?: Array<VisitAttribute>;
89
+ }
90
+
91
+ export interface ExportedVisitFormProps {
92
+ /**
93
+ * A unique string identifying where the visit form is opened from.
94
+ * This string is passed into various extensions within the form to
95
+ * affect how / if they should be rendered.
96
+ */
97
+ openedFrom: string;
98
+ showPatientHeader?: boolean;
99
+ onVisitStarted?: (visit: Visit) => void;
100
+ patient: fhir.Patient;
101
+ patientUuid: string;
102
+ visitContext: Visit;
103
+ }
104
+
105
+ /**
106
+ * This form is used for starting a new visit and for editing
107
+ * an existing visit for a patient. It is similar to visit-form.workspace.tsx, but
108
+ * is not tied to the patient-chart workspace group (i.e. it is not required to operate on
109
+ * the same patient and same visit as all other workspaces within that group.) This workspace is
110
+ * suitable for use *outside* the patient chart, in workflows where we need to start a visit for any
111
+ * arbitrary patient (ex: the patient search workspace window).
112
+ *
113
+ */
114
+ const ExportedVisitForm: React.FC<Workspace2DefinitionProps<ExportedVisitFormProps, {}, {}>> = ({
115
+ closeWorkspace,
116
+ workspaceProps: {
117
+ openedFrom,
118
+ showPatientHeader = false,
119
+ onVisitStarted,
120
+ patient,
121
+ patientUuid,
122
+ visitContext: visitToEdit,
123
+ },
124
+ }) => {
125
+ const { t } = useTranslation();
126
+ const isTablet = useLayoutType() === 'tablet';
127
+ const isOnline = useConnectivity();
128
+ const config = useConfig<ChartConfig>();
129
+ const { emrConfiguration } = useEmrConfiguration();
130
+ const [visitTypeContentSwitcherIndex, setVisitTypeContentSwitcherIndex] = useState(
131
+ config.showRecommendedVisitTypeTab ? 0 : 1,
132
+ );
133
+ const visitHeaderSlotState = useMemo(() => ({ patientUuid }), [patientUuid]);
134
+ const { activePatientEnrollment, isLoading } = useActivePatientEnrollment(patientUuid);
135
+
136
+ const { mutate: globalMutate } = useSWRConfig();
137
+ const allVisitTypes = useConditionalVisitTypes();
138
+
139
+ const [errorFetchingResources, setErrorFetchingResources] = useState<{
140
+ blockSavingForm: boolean;
141
+ } | null>(null);
142
+ const { visitAttributeTypes } = useVisitAttributeTypes();
143
+ const [visitFormCallbacks, setVisitFormCallbacks] = useVisitFormCallbacks();
144
+ const [extraVisitInfo, setExtraVisitInfo] = useState<ExtraVisitInfo | null>(null);
145
+
146
+ const { visitFormSchema, defaultValues, firstEncounterDateTime, lastEncounterDateTime } =
147
+ useVisitFormSchemaAndDefaultValues(visitToEdit);
148
+
149
+ const methods = useForm<VisitFormData>({
150
+ mode: 'all',
151
+ resolver: zodResolver(visitFormSchema),
152
+ defaultValues,
153
+ });
154
+
155
+ const {
156
+ handleSubmit,
157
+ control,
158
+ getValues,
159
+ formState: { errors, isDirty, isSubmitting },
160
+ reset,
161
+ } = methods;
162
+
163
+ // default values are cached so form needs to be reset when they change (e.g. when default visit location finishes loading)
164
+ useEffect(() => {
165
+ reset(defaultValues);
166
+ }, [defaultValues, reset]);
167
+
168
+ const isValidVisitAttributesArray = useCallback((attributes: unknown): boolean => {
169
+ return (
170
+ Array.isArray(attributes) &&
171
+ attributes.length > 0 &&
172
+ attributes.every((attr) => attr?.attributeType?.trim().length > 0 && attr?.value?.trim().length > 0)
173
+ );
174
+ }, []);
175
+
176
+ const handleVisitAttributes = useCallback(
177
+ (visitAttributes: { [p: string]: string }, visitUuid: string) => {
178
+ const existingVisitAttributeTypes =
179
+ visitToEdit?.attributes?.map((attribute) => attribute.attributeType.uuid) || [];
180
+
181
+ const promises = [];
182
+
183
+ for (const [attributeType, value] of Object.entries(visitAttributes)) {
184
+ if (attributeType && existingVisitAttributeTypes.includes(attributeType)) {
185
+ const attributeToEdit = visitToEdit.attributes.find((attr) => attr.attributeType.uuid === attributeType);
186
+
187
+ if (attributeToEdit) {
188
+ // continue to next attribute if the previous value is same as new value
189
+ const isSameValue =
190
+ typeof attributeToEdit.value === 'object'
191
+ ? attributeToEdit.value.uuid === value
192
+ : attributeToEdit.value === value;
193
+
194
+ if (isSameValue) {
195
+ continue;
196
+ }
197
+
198
+ if (value) {
199
+ // Update attribute with new value
200
+ promises.push(
201
+ updateVisitAttribute(visitUuid, attributeToEdit.uuid, value).catch((err) => {
202
+ showSnackbar({
203
+ title: t('errorUpdatingVisitAttribute', 'Error updating the {{attributeName}} visit attribute', {
204
+ attributeName: attributeToEdit.attributeType.display,
205
+ }),
206
+ kind: 'error',
207
+ isLowContrast: false,
208
+ subtitle: err?.message,
209
+ });
210
+ return Promise.reject(err); // short-circuit promise chain
211
+ }),
212
+ );
213
+ } else {
214
+ // Delete attribute if no value is provided
215
+ promises.push(
216
+ deleteVisitAttribute(visitUuid, attributeToEdit.uuid).catch((err) => {
217
+ showSnackbar({
218
+ title: t('errorDeletingVisitAttribute', 'Error deleting the {{attributeName}} visit attribute', {
219
+ attributeName: attributeToEdit.attributeType.display,
220
+ }),
221
+ kind: 'error',
222
+ isLowContrast: false,
223
+ subtitle: err?.message,
224
+ });
225
+ return Promise.reject(err); // short-circuit promise chain
226
+ }),
227
+ );
228
+ }
229
+ }
230
+ } else {
231
+ if (value) {
232
+ promises.push(
233
+ createVisitAttribute(visitUuid, attributeType, value).catch((err) => {
234
+ showSnackbar({
235
+ title: t('errorCreatingVisitAttribute', 'Error creating the {{attributeName}} visit attribute', {
236
+ attributeName: visitAttributeTypes?.find((type) => type.uuid === attributeType)?.display,
237
+ }),
238
+ kind: 'error',
239
+ isLowContrast: false,
240
+ subtitle: err?.message,
241
+ });
242
+ return Promise.reject(err); // short-circuit promise chain
243
+ }),
244
+ );
245
+ }
246
+ }
247
+ }
248
+
249
+ return Promise.all(promises);
250
+ },
251
+ [visitToEdit, t, visitAttributeTypes],
252
+ );
253
+
254
+ const onSubmit = useCallback(
255
+ (data: VisitFormData) => {
256
+ const {
257
+ visitStatus,
258
+ visitStartTimeFormat,
259
+ visitStartDate,
260
+ visitLocation,
261
+ visitStartTime,
262
+ visitType,
263
+ visitAttributes,
264
+ visitStopDate,
265
+ visitStopTime,
266
+ visitStopTimeFormat,
267
+ } = data;
268
+
269
+ const { handleCreateExtraVisitInfo, attributes: extraAttributes } = extraVisitInfo ?? {};
270
+ const hasStartTime = ['ongoing', 'past'].includes(visitStatus);
271
+ const hasStopTime = 'past' === visitStatus;
272
+ const startDatetime = convertToDate(visitStartDate, visitStartTime, visitStartTimeFormat);
273
+ const stopDatetime = convertToDate(visitStopDate, visitStopTime, visitStopTimeFormat);
274
+
275
+ let payload: NewVisitPayload = {
276
+ visitType: visitType,
277
+ location: visitLocation?.uuid,
278
+ startDatetime: hasStartTime ? startDatetime : null,
279
+ stopDatetime: hasStopTime ? stopDatetime : null,
280
+ // The request throws 400 (Bad request) error when the patient is passed in the update payload for existing visit
281
+ ...(!visitToEdit && { patient: patientUuid }),
282
+ ...(isValidVisitAttributesArray(extraAttributes) && { attributes: extraAttributes }),
283
+ };
284
+
285
+ handleCreateExtraVisitInfo?.();
286
+
287
+ const abortController = new AbortController();
288
+ if (isOnline) {
289
+ const visitRequest = visitToEdit?.uuid
290
+ ? updateVisit(visitToEdit?.uuid, payload, abortController)
291
+ : saveVisit(payload, abortController);
292
+
293
+ visitRequest
294
+ .then((response) => {
295
+ showSnackbar({
296
+ isLowContrast: true,
297
+ kind: 'success',
298
+ subtitle: !visitToEdit
299
+ ? t('visitStartedSuccessfully', '{{visit}} started successfully', {
300
+ visit: response?.data?.visitType?.display ?? t('visit', 'Visit'),
301
+ })
302
+ : t('visitDetailsUpdatedSuccessfully', '{{visit}} updated successfully', {
303
+ visit: response?.data?.visitType?.display ?? t('pastVisit', 'Past visit'),
304
+ }),
305
+ title: !visitToEdit
306
+ ? t('visitStarted', 'Visit started')
307
+ : t('visitDetailsUpdated', 'Visit details updated'),
308
+ });
309
+ return response;
310
+ })
311
+ .catch((error) => {
312
+ const errorDescription =
313
+ OpenmrsFetchError && error instanceof OpenmrsFetchError
314
+ ? typeof error.responseBody === 'string'
315
+ ? error.responseBody
316
+ : extractErrorMessagesFromResponse(error.responseBody as ErrorObject, t)
317
+ : error?.message;
318
+
319
+ showSnackbar({
320
+ title: !visitToEdit
321
+ ? t('startVisitError', 'Error starting visit')
322
+ : t('errorUpdatingVisitDetails', 'Error updating visit details'),
323
+ kind: 'error',
324
+ isLowContrast: false,
325
+ subtitle: errorDescription,
326
+ });
327
+ return Promise.reject(error); // short-circuit promise chain
328
+ })
329
+ .then(async (response) => {
330
+ // now that visit is created / updated, we run post-submit actions
331
+ // to update visit attributes or any other OnVisitCreatedOrUpdated actions
332
+ const visit = response.data;
333
+
334
+ // Use targeted SWR invalidation instead of global mutateVisit
335
+ // This will invalidate visit history and encounter tables for this patient
336
+ // (if visitContext is updated, it should have been invalidated with mutateSavedOrUpdatedVisit)
337
+ invalidateVisitAndEncounterData(globalMutate, patientUuid);
338
+
339
+ // handleVisitAttributes already has code to show error snackbar when attribute fails to update
340
+ // no need for catch block here
341
+ const visitAttributesRequest = handleVisitAttributes(visitAttributes, response.data.uuid).then(
342
+ (visitAttributesResponses) => {
343
+ if (visitAttributesResponses.length > 0) {
344
+ showSnackbar({
345
+ isLowContrast: true,
346
+ kind: 'success',
347
+ title: t(
348
+ 'additionalVisitInformationUpdatedSuccessfully',
349
+ 'Additional visit information updated successfully',
350
+ ),
351
+ });
352
+ }
353
+ },
354
+ );
355
+
356
+ const onVisitCreatedOrUpdatedRequests = [...visitFormCallbacks.values()].map((callbacks) =>
357
+ callbacks.onVisitCreatedOrUpdated(visit),
358
+ );
359
+
360
+ await Promise.all([visitAttributesRequest, ...onVisitCreatedOrUpdatedRequests]);
361
+ await closeWorkspace({ discardUnsavedChanges: true });
362
+ onVisitStarted?.(visit);
363
+ })
364
+ .catch(() => {
365
+ // do nothing, this catches any reject promises used for short-circuiting
366
+ });
367
+ } else {
368
+ createOfflineVisitForPatient(
369
+ patientUuid,
370
+ visitLocation.uuid,
371
+ config.offlineVisitTypeUuid,
372
+ payload.startDatetime,
373
+ ).then(
374
+ async (visit) => {
375
+ // Also invalidate visit history and encounter tables
376
+ invalidateVisitAndEncounterData(globalMutate, patientUuid);
377
+ showSnackbar({
378
+ isLowContrast: true,
379
+ kind: 'success',
380
+ subtitle: t('visitStartedSuccessfully', '{{visit}} started successfully', {
381
+ visit: t('offlineVisit', 'Offline Visit'),
382
+ }),
383
+ title: t('visitStarted', 'Visit started'),
384
+ });
385
+ await closeWorkspace({ discardUnsavedChanges: true });
386
+ onVisitStarted?.(visit);
387
+ },
388
+ (error: Error) => {
389
+ showSnackbar({
390
+ title: t('startVisitError', 'Error starting visit'),
391
+ kind: 'error',
392
+ isLowContrast: false,
393
+ subtitle: error?.message,
394
+ });
395
+
396
+ return Promise.reject(error);
397
+ },
398
+ );
399
+
400
+ return;
401
+ }
402
+ },
403
+ [
404
+ closeWorkspace,
405
+ config.offlineVisitTypeUuid,
406
+ extraVisitInfo,
407
+ globalMutate,
408
+ handleVisitAttributes,
409
+ isOnline,
410
+ onVisitStarted,
411
+ patientUuid,
412
+ t,
413
+ visitFormCallbacks,
414
+ visitToEdit,
415
+ isValidVisitAttributesArray,
416
+ ],
417
+ );
418
+
419
+ return (
420
+ <Workspace2
421
+ title={visitToEdit ? t('editVisit', 'Edit visit') : t('startVisitWorkspaceTitle', 'Start a visit')}
422
+ hasUnsavedChanges={isDirty}
423
+ >
424
+ <FormProvider {...methods}>
425
+ <Form className={styles.form} onSubmit={handleSubmit(onSubmit)} data-openmrs-role="Start Visit Form">
426
+ {showPatientHeader && patient && (
427
+ <ExtensionSlot
428
+ name="patient-header-slot"
429
+ state={{
430
+ patient,
431
+ patientUuid: patientUuid,
432
+ hideActionsOverflow: true,
433
+ }}
434
+ />
435
+ )}
436
+ {errorFetchingResources && (
437
+ <InlineNotification
438
+ kind={errorFetchingResources?.blockSavingForm ? 'error' : 'warning'}
439
+ lowContrast
440
+ className={styles.inlineNotification}
441
+ title={t('partOfFormDidntLoad', 'Part of the form did not load')}
442
+ subtitle={t('refreshToTryAgain', 'Please refresh to try again')}
443
+ />
444
+ )}
445
+ <div>
446
+ {isTablet && (
447
+ <Row className={styles.headerGridRow}>
448
+ <ExtensionSlot
449
+ name="visit-form-header-slot"
450
+ className={styles.dataGridRow}
451
+ state={visitHeaderSlotState}
452
+ />
453
+ </Row>
454
+ )}
455
+ <Stack gap={4} className={styles.container}>
456
+ <section>
457
+ <FormGroup legendText={t('theVisitIs', 'The visit is')}>
458
+ <Controller
459
+ name="visitStatus"
460
+ control={control}
461
+ render={({ field: { onChange, value } }) => {
462
+ const validVisitStatuses = visitToEdit ? ['ongoing', 'past'] : visitStatuses;
463
+ const idx = validVisitStatuses.indexOf(value);
464
+ const selectedIndex = idx >= 0 ? idx : 0;
465
+
466
+ // For some reason, Carbon throws NPE when trying to conditionally
467
+ // render a <Switch> component
468
+ return visitToEdit ? (
469
+ <ContentSwitcher
470
+ selectedIndex={selectedIndex}
471
+ onChange={({ name }) => onChange(name)}
472
+ size="md"
473
+ >
474
+ <Switch name="ongoing" text={t('ongoing', 'Ongoing')} />
475
+ <Switch name="past" text={t('ended', 'Ended')} />
476
+ </ContentSwitcher>
477
+ ) : (
478
+ <ContentSwitcher
479
+ selectedIndex={selectedIndex}
480
+ onChange={({ name }) => onChange(name)}
481
+ size="md"
482
+ >
483
+ <Switch name="new" text={t('new', 'New')} />
484
+ <Switch name="ongoing" text={t('ongoing', 'Ongoing')} />
485
+ <Switch name="past" text={t('inThePast', 'In the past')} />
486
+ </ContentSwitcher>
487
+ );
488
+ }}
489
+ />
490
+ </FormGroup>
491
+ </section>
492
+ <VisitDateTimeSection {...{ control, firstEncounterDateTime, lastEncounterDateTime }} />
493
+ {/* Upcoming appointments. This get shown when config.showUpcomingAppointments is true. */}
494
+ {config.showUpcomingAppointments && (
495
+ <section>
496
+ <div className={styles.sectionField}>
497
+ <VisitFormExtensionSlot
498
+ name="visit-form-top-slot"
499
+ patientUuid={patientUuid}
500
+ visitFormOpenedFrom={openedFrom}
501
+ setVisitFormCallbacks={setVisitFormCallbacks}
502
+ />
503
+ </div>
504
+ </section>
505
+ )}
506
+
507
+ {/* This field lets the user select a location for the visit. The location is required for the visit to be saved. Defaults to the active session location */}
508
+ <LocationSelector control={control} />
509
+
510
+ {/* Lists available program types. This feature is dependent on the `showRecommendedVisitTypeTab` config being set
511
+ to true. */}
512
+ {config.showRecommendedVisitTypeTab && (
513
+ <section>
514
+ <h1 className={styles.sectionTitle}>{t('program', 'Program')}</h1>
515
+ <FormGroup legendText={t('selectProgramType', 'Select program type')} className={styles.sectionField}>
516
+ <Controller
517
+ name="programType"
518
+ control={control}
519
+ render={({ field: { onChange } }) => (
520
+ <RadioButtonGroup
521
+ orientation="vertical"
522
+ onChange={(uuid: string) =>
523
+ onChange(activePatientEnrollment.find(({ program }) => program.uuid === uuid)?.uuid)
524
+ }
525
+ name="program-type-radio-group"
526
+ >
527
+ {activePatientEnrollment.map(({ uuid, display, program }) => (
528
+ <RadioButton
529
+ key={uuid}
530
+ className={styles.radioButton}
531
+ id={uuid}
532
+ labelText={display}
533
+ value={program.uuid}
534
+ />
535
+ ))}
536
+ </RadioButtonGroup>
537
+ )}
538
+ />
539
+ </FormGroup>
540
+ </section>
541
+ )}
542
+
543
+ {/* Lists available visit types if no atFacilityVisitType enabled. The content switcher only gets shown when recommended visit types are enabled */}
544
+ {!emrConfiguration?.atFacilityVisitType && (
545
+ <section>
546
+ <h1 className={styles.sectionTitle}>{t('visitType_title', 'Visit Type')}</h1>
547
+ <div className={styles.sectionField}>
548
+ {config.showRecommendedVisitTypeTab ? (
549
+ <>
550
+ <ContentSwitcher
551
+ selectedIndex={visitTypeContentSwitcherIndex}
552
+ onChange={({ index }) => setVisitTypeContentSwitcherIndex(index)}
553
+ size="md"
554
+ >
555
+ <Switch name="recommended" text={t('recommended', 'Recommended')} />
556
+ <Switch name="all" text={t('all', 'All')} />
557
+ </ContentSwitcher>
558
+ {visitTypeContentSwitcherIndex === 0 && !isLoading && (
559
+ <MemoizedRecommendedVisitType
560
+ patientUuid={patientUuid}
561
+ patientProgramEnrollment={(() => {
562
+ return activePatientEnrollment?.find(
563
+ ({ program }) => program.uuid === getValues('programType'),
564
+ );
565
+ })()}
566
+ locationUuid={getValues('visitLocation')?.uuid}
567
+ />
568
+ )}
569
+ {visitTypeContentSwitcherIndex === 1 && <BaseVisitType visitTypes={allVisitTypes} />}
570
+ </>
571
+ ) : (
572
+ // Defaults to showing all possible visit types if recommended visits are not enabled
573
+ <BaseVisitType visitTypes={allVisitTypes} />
574
+ )}
575
+ </div>
576
+
577
+ {errors?.visitType && (
578
+ <section>
579
+ <div className={styles.sectionField}>
580
+ <InlineNotification
581
+ role="alert"
582
+ style={{ margin: '0', minWidth: '100%' }}
583
+ kind="error"
584
+ lowContrast={true}
585
+ title={t('missingVisitType', 'Missing visit type')}
586
+ subtitle={t('selectVisitType', 'Please select a Visit Type')}
587
+ />
588
+ </div>
589
+ </section>
590
+ )}
591
+ </section>
592
+ )}
593
+
594
+ <ExtensionSlot state={{ patientUuid, setExtraVisitInfo }} name="extra-visit-attribute-slot" />
595
+
596
+ {/* Visit type attribute fields. These get shown when visit attribute types are configured */}
597
+ <section>
598
+ <h1 className={styles.sectionTitle}>{isTablet && t('visitAttributes', 'Visit attributes')}</h1>
599
+ <div className={styles.sectionField}>
600
+ <VisitAttributeTypeFields setErrorFetchingResources={setErrorFetchingResources} />
601
+ </div>
602
+ </section>
603
+
604
+ {/* Queue location and queue fields. These get shown when config.showServiceQueueFields is true,
605
+ or when the form is opened from the queues app */}
606
+ <section>
607
+ <div className={styles.sectionField}>
608
+ <VisitFormExtensionSlot
609
+ name="visit-form-bottom-slot"
610
+ patientUuid={patientUuid}
611
+ visitFormOpenedFrom={openedFrom}
612
+ setVisitFormCallbacks={setVisitFormCallbacks}
613
+ />
614
+ </div>
615
+ </section>
616
+ </Stack>
617
+ </div>
618
+ <ButtonSet
619
+ className={classNames(styles.buttonSet, {
620
+ [styles.tablet]: isTablet,
621
+ [styles.desktop]: !isTablet,
622
+ })}
623
+ >
624
+ <Button className={styles.button} kind="secondary" onClick={() => closeWorkspace()}>
625
+ {t('discard', 'Discard')}
626
+ </Button>
627
+ <Button
628
+ className={styles.button}
629
+ disabled={isSubmitting || errorFetchingResources?.blockSavingForm}
630
+ kind="primary"
631
+ type="submit"
632
+ >
633
+ {isSubmitting ? (
634
+ <InlineLoading
635
+ className={styles.spinner}
636
+ description={
637
+ visitToEdit
638
+ ? t('updatingVisit', 'Updating visit') + '...'
639
+ : t('startingVisit', 'Starting visit') + '...'
640
+ }
641
+ />
642
+ ) : (
643
+ <span>{visitToEdit ? t('updateVisit', 'Update visit') : t('startVisit', 'Start visit')}</span>
644
+ )}
645
+ </Button>
646
+ </ButtonSet>
647
+ </Form>
648
+ </FormProvider>
649
+ </Workspace2>
650
+ );
651
+ };
652
+
653
+ interface VisitFormExtensionSlotProps {
654
+ name: string;
655
+ patientUuid: string;
656
+ visitFormOpenedFrom: string;
657
+ setVisitFormCallbacks: React.Dispatch<React.SetStateAction<Map<string, VisitFormCallbacks>>>;
658
+ }
659
+
660
+ type VisitFormExtensionState = {
661
+ patientUuid: string;
662
+
663
+ /**
664
+ * This function allows an extension to register callbacks for visit form submission.
665
+ * This callbacks can be used to make further requests. The callbacks should handle its own UI notification
666
+ * on success / failure, and its returned Promise MUST resolve on success and MUST reject on failure.
667
+ * @param callback
668
+ * @returns
669
+ */
670
+ setVisitFormCallbacks(callbacks: VisitFormCallbacks);
671
+
672
+ visitFormOpenedFrom: string;
673
+ patientChartConfig: ChartConfig;
674
+ };
675
+
676
+ const VisitFormExtensionSlot: React.FC<VisitFormExtensionSlotProps> = React.memo(
677
+ ({ name, patientUuid, visitFormOpenedFrom, setVisitFormCallbacks }) => {
678
+ const config = useConfig<ChartConfig>();
679
+
680
+ return (
681
+ <ExtensionSlot name={name}>
682
+ {(extension: AssignedExtension) => {
683
+ const state: VisitFormExtensionState = {
684
+ patientUuid,
685
+ setVisitFormCallbacks: (callbacks) => {
686
+ setVisitFormCallbacks((old) => {
687
+ return new Map(old).set(extension.id, callbacks);
688
+ });
689
+ },
690
+ visitFormOpenedFrom,
691
+ patientChartConfig: config,
692
+ };
693
+ return <Extension state={state} />;
694
+ }}
695
+ </ExtensionSlot>
696
+ );
697
+ },
698
+ );
699
+
700
+ export default ExportedVisitForm;