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