@kenyaemr/esm-billing-app 5.4.7 → 5.4.8-pre.1663

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 (98) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/1072.js +1 -1
  3. package/dist/1072.js.map +1 -1
  4. package/dist/2231.js +1 -1
  5. package/dist/2231.js.map +1 -1
  6. package/dist/2624.js +1 -1
  7. package/dist/2624.js.map +1 -1
  8. package/dist/2836.js +1 -0
  9. package/dist/2836.js.map +1 -0
  10. package/dist/301.js +1 -1
  11. package/dist/301.js.map +1 -1
  12. package/dist/3091.js +1 -1
  13. package/dist/3091.js.map +1 -1
  14. package/dist/3291.js +1 -0
  15. package/dist/3291.js.map +1 -0
  16. package/dist/3294.js +1 -1
  17. package/dist/3294.js.map +1 -1
  18. package/dist/3378.js +1 -1
  19. package/dist/3378.js.map +1 -1
  20. package/dist/3846.js +1 -0
  21. package/dist/3846.js.map +1 -0
  22. package/dist/4164.js +1 -0
  23. package/dist/4164.js.map +1 -0
  24. package/dist/5117.js +1 -1
  25. package/dist/5117.js.map +1 -1
  26. package/dist/5305.js +1 -0
  27. package/dist/5305.js.map +1 -0
  28. package/dist/5857.js +1 -0
  29. package/dist/5857.js.map +1 -0
  30. package/dist/6229.js +1 -0
  31. package/dist/6229.js.map +1 -0
  32. package/dist/6484.js +1 -0
  33. package/dist/6484.js.map +1 -0
  34. package/dist/6508.js +1 -1
  35. package/dist/6508.js.map +1 -1
  36. package/dist/6605.js +1 -1
  37. package/dist/6605.js.map +1 -1
  38. package/dist/7515.js +1 -1
  39. package/dist/7515.js.map +1 -1
  40. package/dist/8575.js +1 -0
  41. package/dist/8575.js.map +1 -0
  42. package/dist/9326.js +1 -1
  43. package/dist/9326.js.map +1 -1
  44. package/dist/9449.js +1 -1
  45. package/dist/9806.js +1 -1
  46. package/dist/9806.js.map +1 -1
  47. package/dist/9914.js +1 -0
  48. package/dist/9914.js.map +1 -0
  49. package/dist/kenyaemr-esm-billing-app.js +2 -2
  50. package/dist/kenyaemr-esm-billing-app.js.buildmanifest.json +278 -200
  51. package/dist/kenyaemr-esm-billing-app.js.map +1 -1
  52. package/dist/main.js +2 -2
  53. package/dist/main.js.map +1 -1
  54. package/dist/routes.json +1 -1
  55. package/package.json +3 -2
  56. package/src/billing-form/social-health-authority/type/index.ts +1 -0
  57. package/src/billing-tabs/billling-tabs.component.tsx +8 -1
  58. package/src/claims/claims-management/table/virtual-claim-preauth/utils/index.ts +3 -0
  59. package/src/claims/claims-wrap/claim-workspaces/attachements/claim-attachments-resource.ts +5 -2
  60. package/src/claims/claims-wrap/claim-workspaces/claim-submission/ClaimSubmitWorkspace.tsx +50 -12
  61. package/src/claims/claims-wrap/claim-workspaces/interventions/manage-interventions-workspace.tsx +1 -1
  62. package/src/claims/claims-wrap/claims-main-component.tsx +163 -33
  63. package/src/claims/claims-wrap/claims-main.resource.ts +12 -0
  64. package/src/claims/claims-wrap/claims-main.scss +16 -0
  65. package/src/claims/claims-wrap/type/index.ts +3 -0
  66. package/src/claims/overseas-referrals/overseas-referral-details.scss +13 -0
  67. package/src/claims/overseas-referrals/overseas-referral-details.workspace.tsx +85 -0
  68. package/src/claims/overseas-referrals/overseas-referral-form.scss +107 -0
  69. package/src/claims/overseas-referrals/overseas-referral-form.workspace.tsx +840 -0
  70. package/src/claims/overseas-referrals/overseas-referrals.component.tsx +336 -0
  71. package/src/claims/overseas-referrals/overseas-referrals.resource.test.ts +164 -0
  72. package/src/claims/overseas-referrals/overseas-referrals.resource.tsx +367 -0
  73. package/src/claims/overseas-referrals/overseas-referrals.scss +78 -0
  74. package/src/claims/overseas-referrals/overseas-referrals.utils.ts +31 -0
  75. package/src/claims/overseas-referrals/pending-referrals.component.tsx +337 -0
  76. package/src/claims/overseas-referrals/pending-referrals.test.tsx +157 -0
  77. package/src/claims/overseas-referrals/simple-table.component.tsx +83 -0
  78. package/src/index.ts +10 -0
  79. package/src/routes.json +10 -0
  80. package/src/visits/visits.resource.ts +15 -5
  81. package/translations/am.json +75 -0
  82. package/translations/en.json +78 -1
  83. package/translations/fr.json +75 -0
  84. package/translations/sw.json +75 -0
  85. package/dist/1187.js +0 -1
  86. package/dist/1187.js.map +0 -1
  87. package/dist/1346.js +0 -1
  88. package/dist/1346.js.map +0 -1
  89. package/dist/2034.js +0 -1
  90. package/dist/2034.js.map +0 -1
  91. package/dist/4156.js +0 -1
  92. package/dist/4156.js.map +0 -1
  93. package/dist/4266.js +0 -1
  94. package/dist/4266.js.map +0 -1
  95. package/dist/4818.js +0 -1
  96. package/dist/4818.js.map +0 -1
  97. package/dist/8332.js +0 -1
  98. package/dist/8332.js.map +0 -1
@@ -0,0 +1,840 @@
1
+ import React, { useMemo, useState } from 'react';
2
+ import { useTranslation } from 'react-i18next';
3
+ import { Controller, useFieldArray, useForm } from 'react-hook-form';
4
+ import { zodResolver } from '@hookform/resolvers/zod';
5
+ import { z } from 'zod';
6
+ import classNames from 'classnames';
7
+ import {
8
+ Button,
9
+ ButtonSet,
10
+ ComboBox,
11
+ FileUploader,
12
+ Form,
13
+ FormGroup,
14
+ InlineLoading,
15
+ InlineNotification,
16
+ Layer,
17
+ Select,
18
+ SelectItem,
19
+ Stack,
20
+ TextArea,
21
+ TextInput,
22
+ } from '@carbon/react';
23
+ import { TrashCan } from '@carbon/react/icons';
24
+ import {
25
+ ExtensionSlot,
26
+ showSnackbar,
27
+ useConfig,
28
+ useLayoutType,
29
+ useVisit,
30
+ Workspace2,
31
+ type Workspace2DefinitionProps,
32
+ } from '@openmrs/esm-framework';
33
+ import { type BillingConfig } from '../../config-schema';
34
+ import usePatient from '../../hooks/usePatient';
35
+ import { resolveShaError } from '../../helpers/sha-error';
36
+ import { useClaimForVisit } from '../../bill-administration/patient-billing/workspaces/create-bill/create-bill.resource';
37
+ import PatientBanner from '../claims-management/table/virtual-claim-preauth/elective-auth-workspace/patient-banner/patient-banner.component';
38
+ import ServiceDateTimeField from '../claims-management/table/virtual-claim-preauth/pre-auth-workspace/service-datetime.component';
39
+ import ProviderSearch from '../claims-management/table/virtual-claim-preauth/pre-auth-workspace/provider-search-component/provider-search-component';
40
+ import DiagnosisSearch from '../claims-management/table/virtual-claim-preauth/pre-auth-workspace/diagnosis-component/diagnosis-component';
41
+ import RequiredLabel from '../claims-management/table/virtual-claim-preauth/pre-auth-workspace/components/required-label.component';
42
+ import { formatSavannahDate, normalizeRegulationBody } from '../claims-management/table/virtual-claim-preauth/utils';
43
+ import { launchOverseasReferralDetails } from './overseas-referrals.utils';
44
+ import {
45
+ CAREGIVER_RELATIONSHIPS,
46
+ createOverseasReferral,
47
+ type NewOverseasReferral,
48
+ OVERSEAS_ADMISSION_TYPES,
49
+ OVERSEAS_REFERRAL_DOCUMENTS,
50
+ OVERSEAS_URGENCIES,
51
+ type OverseasReferralDoctor,
52
+ useOverseasReferralInterventions,
53
+ } from './overseas-referrals.resource';
54
+ import styles from './overseas-referral-form.scss';
55
+
56
+ const dateValue = z.union([z.date(), z.string()]).nullable().optional();
57
+
58
+ const doctorSchema = z.object({
59
+ display: z.string().optional(),
60
+ identification_number: z.string().trim(),
61
+ regulation_body: z.string().trim(),
62
+ });
63
+
64
+ const requiredDoctorSchema = doctorSchema.extend({
65
+ identification_number: z.string().trim().min(1, 'Registration number is required'),
66
+ regulation_body: z.string().trim().min(1, 'Regulation body is required'),
67
+ });
68
+
69
+ const overseasReferralSchema = z
70
+ .object({
71
+ patientUuid: z.string().min(1, 'Select a patient'),
72
+ interventionCode: z.string().min(1, 'Select an intervention'),
73
+ urgency: z.string(),
74
+ admissionType: z.string(),
75
+ referralReason: z.string(),
76
+ serviceStart: dateValue,
77
+ serviceStartTime: z.string().optional(),
78
+ serviceStartTimeFormat: z.string().optional(),
79
+ serviceEnd: dateValue,
80
+ serviceEndTime: z.string().optional(),
81
+ serviceEndTimeFormat: z.string().optional(),
82
+ providerNotificationEmail: z.union([z.literal(''), z.string().trim().email('Enter a valid email address')]),
83
+ items: z.array(
84
+ z.object({
85
+ description: z.string().trim().min(1, 'Description is required'),
86
+ unit_price: z
87
+ .string()
88
+ .trim()
89
+ .regex(/^\d+(\.\d{1,2})?$/, 'Enter an amount, e.g. 250000.00'),
90
+ quantity: z
91
+ .string()
92
+ .trim()
93
+ .regex(/^[1-9]\d*$/, 'Enter a whole number of 1 or more'),
94
+ }),
95
+ ),
96
+ referringDoctor: doctorSchema,
97
+ peerReviewers: z.array(requiredDoctorSchema),
98
+ diagnoses: z.array(
99
+ z.object({
100
+ icd11_code: z.string().min(1, 'Select a diagnosis'),
101
+ description: z.string(),
102
+ }),
103
+ ),
104
+ plannedProcedures: z.array(
105
+ z.object({
106
+ procedure_code: z.string().trim().min(1, 'Procedure code is required'),
107
+ description: z.string().trim().min(1, 'Description is required'),
108
+ }),
109
+ ),
110
+ clinicalNotes: z.string(),
111
+ caregiver: z.object({
112
+ full_name: z.string().trim(),
113
+ relationship: z.string(),
114
+ phone_number: z.string().trim(),
115
+ }),
116
+ attachments: z.record(z.string(), z.custom<File | null>().optional()),
117
+ })
118
+ .superRefine((data, ctx) => {
119
+ const { full_name, relationship, phone_number } = data.caregiver;
120
+ // A caregiver is optional, but one that is started must be complete.
121
+ if (full_name || relationship || phone_number) {
122
+ if (!full_name) {
123
+ ctx.addIssue({ code: 'custom', path: ['caregiver', 'full_name'], message: 'Full name is required' });
124
+ }
125
+ if (!relationship) {
126
+ ctx.addIssue({ code: 'custom', path: ['caregiver', 'relationship'], message: 'Relationship is required' });
127
+ }
128
+ if (!phone_number) {
129
+ ctx.addIssue({ code: 'custom', path: ['caregiver', 'phone_number'], message: 'Phone number is required' });
130
+ }
131
+ }
132
+ if (data.referringDoctor.identification_number && !data.referringDoctor.regulation_body) {
133
+ ctx.addIssue({
134
+ code: 'custom',
135
+ path: ['referringDoctor', 'regulation_body'],
136
+ message: 'Regulation body is required',
137
+ });
138
+ }
139
+ if (data.serviceStart && data.serviceEnd) {
140
+ const start = formatSavannahDate(data.serviceStart, data.serviceStartTime, data.serviceStartTimeFormat);
141
+ const end = formatSavannahDate(data.serviceEnd, data.serviceEndTime, data.serviceEndTimeFormat);
142
+ if (start && end && new Date(end) < new Date(start)) {
143
+ ctx.addIssue({ code: 'custom', path: ['serviceEnd'], message: 'Service end must be after service start' });
144
+ }
145
+ }
146
+ });
147
+
148
+ type OverseasReferralFormData = z.infer<typeof overseasReferralSchema>;
149
+
150
+ const emptyDoctor = { display: '', identification_number: '', regulation_body: 'KMPDC' };
151
+
152
+ const defaultValues: OverseasReferralFormData = {
153
+ patientUuid: '',
154
+ interventionCode: '',
155
+ urgency: '',
156
+ admissionType: '',
157
+ referralReason: '',
158
+ serviceStart: null,
159
+ serviceStartTime: '',
160
+ serviceStartTimeFormat: 'AM',
161
+ serviceEnd: null,
162
+ serviceEndTime: '',
163
+ serviceEndTimeFormat: 'AM',
164
+ providerNotificationEmail: '',
165
+ items: [],
166
+ referringDoctor: { ...emptyDoctor, regulation_body: '' },
167
+ peerReviewers: [],
168
+ diagnoses: [],
169
+ plannedProcedures: [],
170
+ clinicalNotes: '',
171
+ caregiver: { full_name: '', relationship: '', phone_number: '' },
172
+ attachments: {},
173
+ };
174
+
175
+ const toDoctor = (doctor: { identification_number?: string; regulation_body?: string }): OverseasReferralDoctor => ({
176
+ identification_number: (doctor.identification_number ?? '').trim(),
177
+ identification_type: 'registration_number',
178
+ regulation_body: normalizeRegulationBody(doctor.regulation_body),
179
+ });
180
+
181
+ /** The form's values in SHA's field names, with the consent token of the patient's active visit. */
182
+ const toNewOverseasReferral = (data: OverseasReferralFormData, consentToken: string): NewOverseasReferral => ({
183
+ consent_token: consentToken,
184
+ intervention_code: data.interventionCode,
185
+ urgency: data.urgency,
186
+ admission_type: data.admissionType,
187
+ referral_reason: data.referralReason,
188
+ service_start: data.serviceStart
189
+ ? formatSavannahDate(data.serviceStart, data.serviceStartTime, data.serviceStartTimeFormat)
190
+ : undefined,
191
+ service_end: data.serviceEnd
192
+ ? formatSavannahDate(data.serviceEnd, data.serviceEndTime, data.serviceEndTimeFormat)
193
+ : undefined,
194
+ provider_notification_email: data.providerNotificationEmail,
195
+ items: data.items.map(({ description, unit_price, quantity }) => ({
196
+ description: description.trim(),
197
+ unit_price: unit_price.trim(),
198
+ quantity: quantity.trim(),
199
+ })),
200
+ referring_doctor: data.referringDoctor.identification_number ? toDoctor(data.referringDoctor) : undefined,
201
+ peer_reviewers: data.peerReviewers.map(toDoctor),
202
+ clinical_information: {
203
+ diagnoses: data.diagnoses.map(({ icd11_code, description }) => ({
204
+ icd11_code: icd11_code ?? '',
205
+ description: description ?? '',
206
+ })),
207
+ planned_procedures: data.plannedProcedures.map(({ procedure_code, description }) => ({
208
+ procedure_code: procedure_code.trim(),
209
+ description: description.trim(),
210
+ })),
211
+ clinical_notes: data.clinicalNotes.trim() || undefined,
212
+ },
213
+ caregiver: data.caregiver.full_name
214
+ ? {
215
+ full_name: data.caregiver.full_name,
216
+ relationship: data.caregiver.relationship ?? '',
217
+ phone_number: data.caregiver.phone_number ?? '',
218
+ }
219
+ : undefined,
220
+ attachments: OVERSEAS_REFERRAL_DOCUMENTS.flatMap(({ document_type, document_title }) => {
221
+ const file = data.attachments[document_type];
222
+ return file ? [{ document_type, document_title, file }] : [];
223
+ }),
224
+ });
225
+
226
+ const humanize = (value: string) => value.charAt(0) + value.slice(1).toLowerCase().replaceAll('_', ' ');
227
+
228
+ interface OverseasReferralFormProps {
229
+ mutate?: () => void;
230
+ /** The patient to refer, e.g. from the Pending tab; otherwise the user searches for one. */
231
+ patientUuid?: string;
232
+ /**
233
+ * The consent token of the patient's submitted claim, from a Pending row. With it the form uses this token
234
+ * (shown read-only) and `beneficiaryGuid` for the interventions, instead of looking up the active visit.
235
+ */
236
+ consentToken?: string;
237
+ beneficiaryGuid?: string | null;
238
+ /** Called once SHA accepts the referral, with its guid when the backend returns one. */
239
+ onSubmitted?: (referralGuid: string | null) => void;
240
+ }
241
+
242
+ const OverseasReferralForm: React.FC<Workspace2DefinitionProps<OverseasReferralFormProps, object, object>> = ({
243
+ closeWorkspace,
244
+ workspaceProps,
245
+ }) => {
246
+ const { t } = useTranslation();
247
+ const isTablet = useLayoutType() === 'tablet';
248
+ const { crIdentificationNumberUUID } = useConfig<BillingConfig>();
249
+ const [submitError, setSubmitError] = useState<string | null>(null);
250
+ const idempotencyKey = useMemo(
251
+ () =>
252
+ typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
253
+ ? crypto.randomUUID()
254
+ : `k-${Date.now()}-${Math.random().toString(36).slice(2)}`,
255
+ [],
256
+ );
257
+
258
+ const {
259
+ control,
260
+ handleSubmit,
261
+ setValue,
262
+ watch,
263
+ reset,
264
+ formState: { errors, isDirty, isSubmitting },
265
+ } = useForm<OverseasReferralFormData>({
266
+ resolver: zodResolver(overseasReferralSchema),
267
+ defaultValues: { ...defaultValues, patientUuid: workspaceProps?.patientUuid ?? '' },
268
+ });
269
+ const items = useFieldArray({ control, name: 'items' });
270
+ const peerReviewers = useFieldArray({ control, name: 'peerReviewers' });
271
+ const diagnoses = useFieldArray({ control, name: 'diagnoses' });
272
+ const plannedProcedures = useFieldArray({ control, name: 'plannedProcedures' });
273
+
274
+ // From a Pending row the claim is already known, so the visit isn't looked up.
275
+ const isFromPendingRow = Boolean(workspaceProps?.consentToken);
276
+ const patientUuid = watch('patientUuid');
277
+ const { patient } = usePatient(patientUuid);
278
+ const { activeVisit, isLoading: isLoadingVisit } = useVisit(isFromPendingRow ? '' : patientUuid);
279
+ const {
280
+ authorizationCode: visitConsentToken,
281
+ beneficiaryCrId,
282
+ isLoading: isLoadingClaim,
283
+ hasNoClaim,
284
+ } = useClaimForVisit(isFromPendingRow ? '' : activeVisit?.uuid ?? '');
285
+ const consentToken = isFromPendingRow ? workspaceProps.consentToken : visitConsentToken;
286
+ const patientCrId =
287
+ patient?.identifiers?.find((id) => id.identifierType?.uuid === crIdentificationNumberUUID)?.identifier ?? null;
288
+ const beneficiary = isFromPendingRow
289
+ ? workspaceProps.beneficiaryGuid ?? undefined
290
+ : beneficiaryCrId ?? patientCrId ?? undefined;
291
+ const { interventions, isLoading: isLoadingInterventions } = useOverseasReferralInterventions(beneficiary);
292
+
293
+ const isResolvingVisit =
294
+ !isFromPendingRow && Boolean(patientUuid) && (isLoadingVisit || (Boolean(activeVisit) && isLoadingClaim));
295
+ let visitProblem: string | null = null;
296
+ if (isFromPendingRow) {
297
+ if (!beneficiary) {
298
+ visitProblem = t(
299
+ 'overseasNoBeneficiaryGuid',
300
+ "This claim has no SHA beneficiary, so its overseas interventions can't be looked up. Check the claim with SHA.",
301
+ );
302
+ }
303
+ } else if (patientUuid && !isResolvingVisit) {
304
+ if (!activeVisit) {
305
+ visitProblem = t('overseasNoActiveVisit', 'This patient has no active visit. Start an SHA visit first.');
306
+ } else if (hasNoClaim || !consentToken) {
307
+ visitProblem = t(
308
+ 'overseasNoConsentToken',
309
+ "The patient's active visit has no SHA consent token. Check the patient in under SHA first.",
310
+ );
311
+ }
312
+ }
313
+
314
+ const changePatient = (uuid: string) => {
315
+ reset({ ...defaultValues, patientUuid: uuid }, { keepDefaultValues: true });
316
+ setSubmitError(null);
317
+ };
318
+
319
+ const onSubmit = async (data: OverseasReferralFormData) => {
320
+ setSubmitError(null);
321
+ if (!consentToken) {
322
+ setSubmitError(visitProblem ?? t('overseasNoConsentTokenShort', 'No SHA consent token for this visit.'));
323
+ return;
324
+ }
325
+ try {
326
+ const { referralGuid } = await createOverseasReferral(toNewOverseasReferral(data, consentToken), idempotencyKey);
327
+ showSnackbar({
328
+ kind: 'success',
329
+ title: t('overseasReferralCreated', 'Overseas referral submitted'),
330
+ subtitle: t('overseasReferralCreatedSubtitle', 'The referral was sent to SHA for review.'),
331
+ ...(referralGuid
332
+ ? {
333
+ actionButtonLabel: t('viewReferral', 'View referral'),
334
+ onActionButtonClick: () => launchOverseasReferralDetails(referralGuid),
335
+ }
336
+ : {}),
337
+ });
338
+ workspaceProps?.mutate?.();
339
+ workspaceProps?.onSubmitted?.(referralGuid);
340
+ closeWorkspace({ discardUnsavedChanges: true });
341
+ } catch (error) {
342
+ const resolved = resolveShaError(error, t, t('submitFailed', 'Submission failed. Please try again.'));
343
+ setSubmitError(
344
+ resolved.traceId ? `${resolved.message} (${t('shaErrorRef', 'Ref')}: ${resolved.traceId})` : resolved.message,
345
+ );
346
+ }
347
+ };
348
+
349
+ const canSubmit = Boolean(consentToken) && !visitProblem && !isSubmitting;
350
+
351
+ return (
352
+ <Workspace2 title={t('newOverseasReferral', 'New overseas referral')} hasUnsavedChanges={isDirty}>
353
+ <Form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
354
+ <div className={styles.formBody}>
355
+ <Stack gap={6}>
356
+ {/* Patient and the consent token of their active visit */}
357
+ <Controller
358
+ control={control}
359
+ name="patientUuid"
360
+ render={({ field }) =>
361
+ !field.value ? (
362
+ <div>
363
+ <p className={styles.sectionTitle}>
364
+ <RequiredLabel>{t('patient', 'Patient')}</RequiredLabel>
365
+ </p>
366
+ <ExtensionSlot
367
+ name="patient-search-bar-slot"
368
+ state={{ selectPatientAction: changePatient, buttonProps: { kind: 'secondary' } }}
369
+ />
370
+ {errors.patientUuid && <p className={styles.fieldError}>{errors.patientUuid.message}</p>}
371
+ </div>
372
+ ) : (
373
+ <div className={styles.patientBannerWrapper}>
374
+ <PatientBanner patientUuid={field.value} />
375
+ {!isFromPendingRow && (
376
+ <Button kind="secondary" size="sm" onClick={() => changePatient('')}>
377
+ {t('changePatient', 'Change patient')}
378
+ </Button>
379
+ )}
380
+ </div>
381
+ )
382
+ }
383
+ />
384
+ {isResolvingVisit && <InlineLoading description={t('checkingVisit', 'Checking the active visit...')} />}
385
+ {visitProblem && (
386
+ <InlineNotification
387
+ kind={isFromPendingRow ? 'error' : 'warning'}
388
+ lowContrast
389
+ hideCloseButton
390
+ title={visitProblem}
391
+ />
392
+ )}
393
+
394
+ {/* Referral details */}
395
+ <FormGroup legendText={t('referralDetails', 'Referral details')}>
396
+ <Stack gap={5}>
397
+ {isFromPendingRow && (
398
+ <TextInput
399
+ id="overseas-consent-token"
400
+ labelText={t('consentToken', 'Consent token')}
401
+ value={consentToken ?? ''}
402
+ readOnly
403
+ />
404
+ )}
405
+ {/* Without a beneficiary there's nothing to pick from; the error above says why. */}
406
+ {!(isFromPendingRow && !beneficiary) && (
407
+ <Controller
408
+ control={control}
409
+ name="interventionCode"
410
+ render={({ field }) => (
411
+ <ComboBox
412
+ id="overseas-intervention"
413
+ titleText={<RequiredLabel>{t('intervention', 'Intervention')}</RequiredLabel>}
414
+ placeholder={
415
+ isLoadingInterventions
416
+ ? t('loadingInterventions', 'Loading interventions...')
417
+ : t('selectIntervention', 'Select an intervention')
418
+ }
419
+ items={interventions}
420
+ itemToString={(item) =>
421
+ item ? [item.intervention_code, item.intervention_name].filter(Boolean).join(' — ') : ''
422
+ }
423
+ selectedItem={interventions.find((item) => item.intervention_code === field.value) ?? null}
424
+ onChange={({ selectedItem }) => field.onChange(selectedItem?.intervention_code ?? '')}
425
+ disabled={!beneficiary || isLoadingInterventions}
426
+ invalid={Boolean(errors.interventionCode)}
427
+ invalidText={errors.interventionCode?.message}
428
+ />
429
+ )}
430
+ />
431
+ )}
432
+ <div className={styles.twoColumns}>
433
+ <Controller
434
+ control={control}
435
+ name="urgency"
436
+ render={({ field }) => (
437
+ <Select id="overseas-urgency" labelText={t('urgency', 'Urgency')} {...field}>
438
+ <SelectItem value="" text={t('notSpecified', 'Not specified')} />
439
+ {OVERSEAS_URGENCIES.map((value) => (
440
+ <SelectItem key={value} value={value} text={humanize(value)} />
441
+ ))}
442
+ </Select>
443
+ )}
444
+ />
445
+ <Controller
446
+ control={control}
447
+ name="admissionType"
448
+ render={({ field }) => (
449
+ <Select id="overseas-admission-type" labelText={t('admissionType', 'Admission type')} {...field}>
450
+ <SelectItem value="" text={t('notSpecified', 'Not specified')} />
451
+ {OVERSEAS_ADMISSION_TYPES.map((value) => (
452
+ <SelectItem key={value} value={value} text={humanize(value)} />
453
+ ))}
454
+ </Select>
455
+ )}
456
+ />
457
+ </div>
458
+ <Controller
459
+ control={control}
460
+ name="referralReason"
461
+ render={({ field }) => (
462
+ <TextArea
463
+ id="overseas-referral-reason"
464
+ labelText={t('referralReason', 'Reason for referral')}
465
+ rows={3}
466
+ {...field}
467
+ />
468
+ )}
469
+ />
470
+ <div className={styles.twoColumns}>
471
+ <ServiceDateTimeField
472
+ control={control}
473
+ errors={errors}
474
+ dateField={{ name: 'serviceStart', label: t('serviceStart', 'Service start') }}
475
+ timeField={{ name: 'serviceStartTime', label: t('time', 'Time') }}
476
+ timeFormatField={{ name: 'serviceStartTimeFormat', label: t('timeFormat', 'Time format') }}
477
+ />
478
+ <ServiceDateTimeField
479
+ control={control}
480
+ errors={errors}
481
+ dateField={{ name: 'serviceEnd', label: t('serviceEnd', 'Service end') }}
482
+ timeField={{ name: 'serviceEndTime', label: t('time', 'Time') }}
483
+ timeFormatField={{ name: 'serviceEndTimeFormat', label: t('timeFormat', 'Time format') }}
484
+ minDate={watch('serviceStart') ?? undefined}
485
+ />
486
+ </div>
487
+ <Controller
488
+ control={control}
489
+ name="providerNotificationEmail"
490
+ render={({ field }) => (
491
+ <TextInput
492
+ id="overseas-notification-email"
493
+ type="email"
494
+ labelText={t('providerNotificationEmail', 'Provider notification email')}
495
+ invalid={Boolean(errors.providerNotificationEmail)}
496
+ invalidText={errors.providerNotificationEmail?.message}
497
+ {...field}
498
+ />
499
+ )}
500
+ />
501
+ </Stack>
502
+ </FormGroup>
503
+
504
+ {/* Items */}
505
+ <FormGroup legendText={t('referralItems', 'Items')}>
506
+ <Stack gap={4}>
507
+ {items.fields.map((item, index) => (
508
+ <Layer key={item.id} className={styles.rowCard}>
509
+ <div className={styles.itemRow}>
510
+ <Controller
511
+ control={control}
512
+ name={`items.${index}.description`}
513
+ render={({ field }) => (
514
+ <TextInput
515
+ id={`overseas-item-description-${index}`}
516
+ labelText={t('description', 'Description')}
517
+ invalid={Boolean(errors.items?.[index]?.description)}
518
+ invalidText={errors.items?.[index]?.description?.message}
519
+ {...field}
520
+ />
521
+ )}
522
+ />
523
+ <Controller
524
+ control={control}
525
+ name={`items.${index}.unit_price`}
526
+ render={({ field }) => (
527
+ <TextInput
528
+ id={`overseas-item-price-${index}`}
529
+ labelText={t('unitPrice', 'Unit price (KES)')}
530
+ inputMode="decimal"
531
+ invalid={Boolean(errors.items?.[index]?.unit_price)}
532
+ invalidText={errors.items?.[index]?.unit_price?.message}
533
+ {...field}
534
+ />
535
+ )}
536
+ />
537
+ <Controller
538
+ control={control}
539
+ name={`items.${index}.quantity`}
540
+ render={({ field }) => (
541
+ <TextInput
542
+ id={`overseas-item-quantity-${index}`}
543
+ labelText={t('quantity', 'Quantity')}
544
+ inputMode="numeric"
545
+ invalid={Boolean(errors.items?.[index]?.quantity)}
546
+ invalidText={errors.items?.[index]?.quantity?.message}
547
+ {...field}
548
+ />
549
+ )}
550
+ />
551
+ <RemoveButton label={t('remove', 'Remove')} onClick={() => items.remove(index)} />
552
+ </div>
553
+ </Layer>
554
+ ))}
555
+ <AddButton onClick={() => items.append({ description: '', unit_price: '', quantity: '1' })}>
556
+ {t('addItem', '+ Add item')}
557
+ </AddButton>
558
+ </Stack>
559
+ </FormGroup>
560
+
561
+ {/* Doctors */}
562
+ <FormGroup legendText={t('referringDoctor', 'Referring doctor')}>
563
+ <ProviderSearch
564
+ idx={0}
565
+ editable
566
+ selectedDisplay={watch('referringDoctor.display') ?? ''}
567
+ selectedLicenseNumber={watch('referringDoctor.identification_number') ?? ''}
568
+ selectedRegulationBody={watch('referringDoctor.regulation_body') ?? ''}
569
+ onSelect={(provider) => {
570
+ setValue('referringDoctor.display', provider.person?.display ?? '', { shouldDirty: true });
571
+ setValue('referringDoctor.identification_number', provider.licenseNumber ?? '');
572
+ setValue('referringDoctor.regulation_body', provider.licenseBody ?? '');
573
+ }}
574
+ onLicenseNumberChange={(value) =>
575
+ setValue('referringDoctor.identification_number', value, { shouldDirty: true })
576
+ }
577
+ onRegulationBodyChange={(value) =>
578
+ setValue('referringDoctor.regulation_body', value, { shouldDirty: true })
579
+ }
580
+ invalid={Boolean(errors.referringDoctor?.regulation_body)}
581
+ invalidText={errors.referringDoctor?.regulation_body?.message}
582
+ />
583
+ </FormGroup>
584
+
585
+ <FormGroup legendText={t('peerReviewers', 'Peer reviewers')}>
586
+ <Stack gap={4}>
587
+ {peerReviewers.fields.map((reviewer, index) => (
588
+ <Layer key={reviewer.id} className={styles.rowCard}>
589
+ <div className={styles.searchRow}>
590
+ <ProviderSearch
591
+ idx={index + 1}
592
+ editable
593
+ selectedDisplay={watch(`peerReviewers.${index}.display`) ?? ''}
594
+ selectedLicenseNumber={watch(`peerReviewers.${index}.identification_number`) ?? ''}
595
+ selectedRegulationBody={watch(`peerReviewers.${index}.regulation_body`) ?? ''}
596
+ onSelect={(provider) => {
597
+ setValue(`peerReviewers.${index}.display`, provider.person?.display ?? '');
598
+ setValue(`peerReviewers.${index}.identification_number`, provider.licenseNumber ?? '');
599
+ setValue(`peerReviewers.${index}.regulation_body`, provider.licenseBody ?? '');
600
+ }}
601
+ onLicenseNumberChange={(value) =>
602
+ setValue(`peerReviewers.${index}.identification_number`, value)
603
+ }
604
+ onRegulationBodyChange={(value) => setValue(`peerReviewers.${index}.regulation_body`, value)}
605
+ invalid={Boolean(
606
+ errors.peerReviewers?.[index]?.identification_number ||
607
+ errors.peerReviewers?.[index]?.regulation_body,
608
+ )}
609
+ invalidText={
610
+ errors.peerReviewers?.[index]?.identification_number?.message ??
611
+ errors.peerReviewers?.[index]?.regulation_body?.message
612
+ }
613
+ />
614
+ <RemoveButton label={t('remove', 'Remove')} onClick={() => peerReviewers.remove(index)} />
615
+ </div>
616
+ </Layer>
617
+ ))}
618
+ <AddButton onClick={() => peerReviewers.append({ ...emptyDoctor })}>
619
+ {t('addPeerReviewer', '+ Add peer reviewer')}
620
+ </AddButton>
621
+ </Stack>
622
+ </FormGroup>
623
+
624
+ {/* Clinical information */}
625
+ <FormGroup legendText={t('clinicalInformation', 'Clinical information')}>
626
+ <Stack gap={5}>
627
+ <div>
628
+ <p className={styles.subTitle}>{t('diagnosesLabel', 'Diagnoses')}</p>
629
+ <Stack gap={4}>
630
+ {diagnoses.fields.map((diagnosis, index) => (
631
+ <div key={diagnosis.id} className={styles.searchRow}>
632
+ <Controller
633
+ control={control}
634
+ name={`diagnoses.${index}.icd11_code`}
635
+ render={({ field }) => (
636
+ <DiagnosisSearch
637
+ id={`overseas-diagnosis-${index}`}
638
+ value={field.value}
639
+ display={watch(`diagnoses.${index}.description`) ?? ''}
640
+ onChange={(icdCode, display) => {
641
+ field.onChange(icdCode);
642
+ setValue(`diagnoses.${index}.description`, display);
643
+ }}
644
+ invalid={Boolean(errors.diagnoses?.[index]?.icd11_code)}
645
+ invalidText={errors.diagnoses?.[index]?.icd11_code?.message}
646
+ />
647
+ )}
648
+ />
649
+ <RemoveButton label={t('remove', 'Remove')} onClick={() => diagnoses.remove(index)} />
650
+ </div>
651
+ ))}
652
+ <AddButton onClick={() => diagnoses.append({ icd11_code: '', description: '' })}>
653
+ {t('addDiagnosis', '+ Add diagnosis')}
654
+ </AddButton>
655
+ </Stack>
656
+ </div>
657
+
658
+ <div>
659
+ <p className={styles.subTitle}>{t('plannedProcedures', 'Planned procedures')}</p>
660
+ <Stack gap={4}>
661
+ {plannedProcedures.fields.map((procedure, index) => (
662
+ <div key={procedure.id} className={styles.procedureRow}>
663
+ <Controller
664
+ control={control}
665
+ name={`plannedProcedures.${index}.procedure_code`}
666
+ render={({ field }) => (
667
+ <TextInput
668
+ id={`overseas-procedure-code-${index}`}
669
+ labelText={t('procedureCode', 'Procedure code')}
670
+ invalid={Boolean(errors.plannedProcedures?.[index]?.procedure_code)}
671
+ invalidText={errors.plannedProcedures?.[index]?.procedure_code?.message}
672
+ {...field}
673
+ />
674
+ )}
675
+ />
676
+ <Controller
677
+ control={control}
678
+ name={`plannedProcedures.${index}.description`}
679
+ render={({ field }) => (
680
+ <TextInput
681
+ id={`overseas-procedure-description-${index}`}
682
+ labelText={t('description', 'Description')}
683
+ invalid={Boolean(errors.plannedProcedures?.[index]?.description)}
684
+ invalidText={errors.plannedProcedures?.[index]?.description?.message}
685
+ {...field}
686
+ />
687
+ )}
688
+ />
689
+ <RemoveButton label={t('remove', 'Remove')} onClick={() => plannedProcedures.remove(index)} />
690
+ </div>
691
+ ))}
692
+ <AddButton onClick={() => plannedProcedures.append({ procedure_code: '', description: '' })}>
693
+ {t('addProcedure', '+ Add procedure')}
694
+ </AddButton>
695
+ </Stack>
696
+ </div>
697
+
698
+ <Controller
699
+ control={control}
700
+ name="clinicalNotes"
701
+ render={({ field }) => (
702
+ <TextArea
703
+ id="overseas-clinical-notes"
704
+ labelText={t('clinicalNotes', 'Clinical notes')}
705
+ rows={4}
706
+ {...field}
707
+ />
708
+ )}
709
+ />
710
+ </Stack>
711
+ </FormGroup>
712
+
713
+ {/* Caregiver */}
714
+ <FormGroup legendText={t('caregiverOptional', 'Caregiver (optional)')}>
715
+ <div className={styles.threeColumns}>
716
+ <Controller
717
+ control={control}
718
+ name="caregiver.full_name"
719
+ render={({ field }) => (
720
+ <TextInput
721
+ id="overseas-caregiver-name"
722
+ labelText={t('fullName', 'Full name')}
723
+ invalid={Boolean(errors.caregiver?.full_name)}
724
+ invalidText={errors.caregiver?.full_name?.message}
725
+ {...field}
726
+ />
727
+ )}
728
+ />
729
+ <Controller
730
+ control={control}
731
+ name="caregiver.relationship"
732
+ render={({ field }) => (
733
+ <Select
734
+ id="overseas-caregiver-relationship"
735
+ labelText={t('relationship', 'Relationship')}
736
+ invalid={Boolean(errors.caregiver?.relationship)}
737
+ invalidText={errors.caregiver?.relationship?.message}
738
+ {...field}>
739
+ <SelectItem value="" text={t('selectRelationship', 'Select relationship')} />
740
+ {CAREGIVER_RELATIONSHIPS.map((value) => (
741
+ <SelectItem key={value} value={value} text={humanize(value)} />
742
+ ))}
743
+ </Select>
744
+ )}
745
+ />
746
+ <Controller
747
+ control={control}
748
+ name="caregiver.phone_number"
749
+ render={({ field }) => (
750
+ <TextInput
751
+ id="overseas-caregiver-phone"
752
+ type="tel"
753
+ labelText={t('phoneNumber', 'Phone number')}
754
+ placeholder="+2547..."
755
+ invalid={Boolean(errors.caregiver?.phone_number)}
756
+ invalidText={errors.caregiver?.phone_number?.message}
757
+ {...field}
758
+ />
759
+ )}
760
+ />
761
+ </div>
762
+ </FormGroup>
763
+
764
+ {/* Attachments: one file per document type, sent in this order */}
765
+ <FormGroup legendText={t('attachments', 'Attachments')}>
766
+ <Stack gap={4}>
767
+ {OVERSEAS_REFERRAL_DOCUMENTS.map(({ document_type, document_title }) => (
768
+ <Controller
769
+ key={document_type}
770
+ control={control}
771
+ name={`attachments.${document_type}`}
772
+ render={({ field }) => (
773
+ <FileUploader
774
+ labelTitle={document_title}
775
+ labelDescription={t('attachmentHint', 'PDF or image')}
776
+ accept={['.pdf', '.png', '.jpg', '.jpeg']}
777
+ buttonLabel={t('addFile', 'Add file')}
778
+ buttonKind="tertiary"
779
+ size="sm"
780
+ filenameStatus="edit"
781
+ disabled={isSubmitting}
782
+ onChange={(event) => field.onChange((event.target as HTMLInputElement).files?.[0] ?? null)}
783
+ onDelete={() => field.onChange(null)}
784
+ />
785
+ )}
786
+ />
787
+ ))}
788
+ </Stack>
789
+ </FormGroup>
790
+
791
+ {submitError && (
792
+ <InlineNotification
793
+ kind="error"
794
+ lowContrast
795
+ title={t('overseasReferralFailed', 'Could not submit the referral')}
796
+ subtitle={submitError}
797
+ onClose={() => setSubmitError(null)}
798
+ />
799
+ )}
800
+ </Stack>
801
+ </div>
802
+
803
+ <ButtonSet className={classNames({ [styles.tablet]: isTablet, [styles.desktop]: !isTablet })}>
804
+ <Button className={styles.button} kind="secondary" onClick={() => closeWorkspace()}>
805
+ {t('cancel', 'Cancel')}
806
+ </Button>
807
+ <Button className={styles.button} kind="primary" type="submit" disabled={!canSubmit}>
808
+ {isSubmitting ? (
809
+ <InlineLoading description={t('submitting', 'Submitting...')} />
810
+ ) : (
811
+ t('submitToSha', 'Submit to SHA')
812
+ )}
813
+ </Button>
814
+ </ButtonSet>
815
+ </Form>
816
+ </Workspace2>
817
+ );
818
+ };
819
+
820
+ const AddButton: React.FC<{ onClick: () => void; children: React.ReactNode }> = ({ onClick, children }) => (
821
+ <div>
822
+ <Button kind="tertiary" size="sm" onClick={onClick}>
823
+ {children}
824
+ </Button>
825
+ </div>
826
+ );
827
+
828
+ const RemoveButton: React.FC<{ label: string; onClick: () => void }> = ({ label, onClick }) => (
829
+ <Button
830
+ kind="danger--ghost"
831
+ size="md"
832
+ renderIcon={TrashCan}
833
+ iconDescription={label}
834
+ hasIconOnly
835
+ onClick={onClick}
836
+ className={styles.removeButton}
837
+ />
838
+ );
839
+
840
+ export default OverseasReferralForm;