All files / src/stock-locations location-admin-form.component.tsx

73.07% Statements 19/26
52.63% Branches 10/19
50% Functions 4/8
76% Lines 19/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164                                          1x                               1x           14x   14x 14x     14x           14x                   14x 3x 3x   3x       3x 3x 3x 3x       14x         14x                       34x                               11x                                                                                                    
import React, { useState } from 'react';
import { z } from 'zod';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  Button,
  FilterableMultiSelect,
  FormGroup,
  InlineNotification,
  ModalBody,
  ModalFooter,
  ModalHeader,
  Stack,
  TextInput,
} from '@carbon/react';
import { getCoreTranslation } from '@openmrs/esm-framework';
import { useTranslation } from 'react-i18next';
import { type locationData } from '../stock-items/types';
import { useLocationTags } from './stock-locations-table.resource';
import styles from './stock-locations-table.scss';
 
const LocationAdministrationSchema = z.object({
  name: z.string().max(255),
});
 
interface LocationAdministrationFormProps {
  close: () => void;
  handleCreateQuestion: (formData: locationData) => Promise<void>;
  handleDeleteBedTag?: () => void;
  headerTitle: string;
  initialData: locationData;
}
 
interface ErrorType {
  message: string;
}
 
const LocationAdministrationForm: React.FC<LocationAdministrationFormProps> = ({
  close,
  handleCreateQuestion,
  headerTitle,
  initialData,
}) => {
  const { t } = useTranslation();
 
  const [showErrorNotification, setShowErrorNotification] = useState(false);
  const [formStateError, setFormStateError] = useState('');
 
  // Location tag types
  const { locationTagList: Tags } = useLocationTags();
 
  const {
    handleSubmit,
    control,
    getValues,
    formState: { isDirty, isSubmitting },
  } = useForm<locationData>({
    mode: 'all',
    resolver: zodResolver(LocationAdministrationSchema),
    defaultValues: {
      name: initialData.name || '',
      tags: initialData.tags || [],
    },
  });
 
  const onSubmit = (formData: locationData) => {
    const formDataFormSubmission = getValues();
    const locationTagsUuid = formDataFormSubmission?.tags?.['selectedItems']?.map((tag) => tag.uuid) ?? [];
 
    const payload = {
      name: formDataFormSubmission.name,
      tags: locationTagsUuid,
    };
    const result = LocationAdministrationSchema.safeParse(formData);
    Eif (result.success) {
      setShowErrorNotification(false);
      return handleCreateQuestion(payload);
    }
  };
 
  const onError = (error: { [key: string]: ErrorType }) => {
    setFormStateError(Object.entries(error)[0][1].message);
    setShowErrorNotification(true);
  };
 
  return (
    <>
      <ModalHeader closeModal={close} title={headerTitle} />
      <ModalBody hasScrollingContent>
        <form id="stock-location-form" onSubmit={handleSubmit(onSubmit, onError)}>
          <Stack gap={3}>
            <FormGroup legendText={''}>
              <Controller
                name="name"
                control={control}
                rules={{ required: true }}
                render={({ field, fieldState }) => (
                  <>
                    <TextInput
                      id="location"
                      labelText={t('locationName', 'Location name')}
                      placeholder={t('locationPlaceholder', 'Add a location')}
                      invalidText={fieldState.error?.message}
                      {...field}
                    />
                  </>
                )}
              />
              <div className={styles.loaderContainer}>
                <Controller
                  name="tags"
                  control={control}
                  render={({ field }) => (
                    <FilterableMultiSelect
                      id="tag"
                      titleText={t('selectTags', 'Select tags')}
                      helperText={t('selectTagsHelper', 'Select one or more tags for this location')}
                      items={Tags ?? []}
                      {...field}
                      itemToString={(item) => {
                        if (item && typeof item === 'object' && 'display' in item) {
                          return (item as { display: string }).display;
                        }
                        return '';
                      }}
                      selectionFeedback="top-after-reopen"
                    />
                  )}
                />
              </div>
            </FormGroup>
 
            {showErrorNotification && (
              <InlineNotification
                lowContrast
                title={t('error', 'Error')}
                style={{ minWidth: '100%', margin: '0rem', padding: '0rem' }}
                role="alert"
                kind="error"
                subtitle={
                  t('pleaseFillField', '{{message}}', {
                    message: formStateError,
                  }) + '.'
                }
                onClose={() => setShowErrorNotification(false)}
              />
            )}
          </Stack>
        </form>
      </ModalBody>
      <ModalFooter>
        <Button onClick={close} kind="secondary">
          {getCoreTranslation('cancel')}
        </Button>
        <Button disabled={!isDirty || isSubmitting} type="submit" form="stock-location-form">
          <span>{t('save', 'Save')}</span>
        </Button>
      </ModalFooter>
    </>
  );
};
 
export default LocationAdministrationForm;