All files / apps/mealReservation/src/screens MealReservation.tsx

100% Statements 44/44
100% Branches 33/33
100% Functions 16/16
100% Lines 41/41

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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339                                                                                                  1x                                         21x 21x 21x   21x                                 21x   21x 21x   21x 1x 1x       21x                 21x 3x 3x 3x 1x   3x       21x   1x 1x         21x 9x       21x   21x 9x 1x             21x 9x                 21x   9x             21x   18x             21x 9x       21x   12x     21x   12x       21x                                                                                                                                                                                                                                       21x                                                                  
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { ActivityIndicator, Text, View } from 'react-native';
 
import { Button } from '@repo/ui/components/Button';
import { FormSelect } from '@repo/ui/components/Form/FormSelect';
import { FormSwitch } from '@repo/ui/components/Form/FormSwitch';
import { SelectRef } from '@repo/ui/components/Select';
import { Switch } from '@repo/ui/components/Switch';
import { WrapperRequest } from '@repo/ui/components/WrapperRequest';
import { LocationIcon } from '@repo/ui/icons/Location';
import { UserIcon } from '@repo/ui/icons/User';
import { makeStyles } from '@repo/ui/themes/makeStyles';
import { useTheme } from '@repo/ui/themes/ThemeContext';
 
import { useRequestForm } from '@repo/hooks/request';
 
import { MealReservationFormType } from '@repo/types/form';
 
import { REQUEST_FORM_FIELD_RULES } from '@repo/validation/fieldRules';
import { validateMealReservationForm } from '@repo/validation/requestForms';
 
import { getUpdateTimeMessage } from '../utils/mealReservation';
 
interface Props {
  extraUsers: {
    id: string;
    name: string;
  }[];
  office: string;
  offices: string[];
  breakfast?: boolean;
  lunch?: boolean;
  vegetarian?: boolean;
  isSubmitting?: boolean;
  isManager?: boolean;
  isLoadingRegistration?: boolean;
  submitButtonText?: string;
  hideHeader?: boolean;
  allowEmptyChange?: boolean;
  reallocationDate?: string;
  showReallocationNotice?: boolean;
  onBehalfOff: () => void;
  onSelectUser?: (user: string) => void;
  onBack: () => void;
  onSubmit: (data: MealReservationFormType) => void;
  onScreenBlur?: (closeModals: () => void) => void;
}
 
const MealReservation = ({
  extraUsers,
  office,
  offices,
  breakfast = false,
  lunch = false,
  vegetarian = false,
  isSubmitting = false,
  isManager = false,
  isLoadingRegistration = false,
  submitButtonText = 'Submit Request',
  hideHeader = false,
  allowEmptyChange = false,
  reallocationDate,
  showReallocationNotice = false,
  onBehalfOff,
  onSelectUser,
  onBack,
  onSubmit,
  onScreenBlur,
}: Props) => {
  const { theme } = useTheme();
  const styles = useStyles();
  const [isOnBehalf, setIsOnBehalf] = useState(false);
 
  const methods = useForm<MealReservationFormType>({
    defaultValues: {
      breakfast: breakfast,
      lunch: lunch,
      vegetarian: vegetarian,
      office: office,
      user: undefined,
    },
  });
 
  const {
    control,
    getValues,
    reset,
    setValue,
    watch,
    formState: { isDirty },
  } = methods;
 
  const userSelectRef = useRef<SelectRef>(null);
  const officeSelectRef = useRef<SelectRef>(null);
 
  const closeModals = useCallback(() => {
    userSelectRef.current?.close();
    officeSelectRef.current?.close();
  }, []);
 
  const { handlePressBack, handleSendRequest, createClearErrorCallback } =
    useRequestForm({
      methods,
      onBack,
      onSubmit,
      onScreenBlur,
      closeModals,
      validateBeforeSubmit: validateMealReservationForm,
    });
 
  const toggleOnBehalf = useCallback(() => {
    setIsOnBehalf((prev: boolean) => {
      const next = !prev;
      if (prev && !next) {
        onBehalfOff();
      }
      return next;
    });
  }, [onBehalfOff]);
 
  const handleUserChange = useCallback(
    (data: string) => {
      createClearErrorCallback('user')();
      onSelectUser?.(data);
    },
    [createClearErrorCallback, onSelectUser],
  );
 
  const handleOfficeChange = useMemo(
    () => createClearErrorCallback('office'),
    [createClearErrorCallback],
  );
 
  const lunchValue = watch('lunch');
 
  useEffect(() => {
    if (!lunchValue) {
      setValue('vegetarian', false, {
        shouldDirty: true,
        shouldTouch: false,
      });
    }
  }, [lunchValue, setValue]);
 
  useEffect(() => {
    reset({
      breakfast,
      lunch,
      vegetarian,
      office,
      user: getValues('user'),
    });
  }, [breakfast, getValues, lunch, office, reset, vegetarian]);
 
  const userOptions = useMemo(
    () =>
      extraUsers.map(e => ({
        label: e.name,
        value: e.id,
      })),
    [extraUsers],
  );
 
  const officeOptions = useMemo(
    () =>
      offices.map(o => ({
        label: o,
        value: o,
      })),
    [offices],
  );
 
  const submitDisabled = useMemo(
    () => (allowEmptyChange ? false : !isDirty),
    [allowEmptyChange, isDirty],
  );
 
  const userRules = useMemo(
    () =>
      isOnBehalf ? REQUEST_FORM_FIELD_RULES.mealReservation.user : undefined,
    [isOnBehalf],
  );
  const officeRules = useMemo(
    () =>
      isOnBehalf ? REQUEST_FORM_FIELD_RULES.mealReservation.office : undefined,
    [isOnBehalf],
  );
 
  return (
    <>
      {isLoadingRegistration && (
        <View style={styles.overlay}>
          <ActivityIndicator color={theme.colors.icon.active} />
        </View>
      )}
      <WrapperRequest
        title="Meal Reservation"
        onBack={handlePressBack}
        disabled={isSubmitting}
        hideHeader={hideHeader}
        footerComponent={
          <Button
            onPress={handleSendRequest}
            isLoading={isSubmitting}
            disabled={submitDisabled}
            accessibilityLabel="Submit Request"
            accessibilityRole="button"
            accessibilityHint="Sends a meal reservation request"
            testID="submit-button"
          >
            {submitButtonText}
          </Button>
        }
      >
        {isManager && (
          <>
            <Switch
              label="On behalf of an employee else"
              value={isOnBehalf}
              testID="on-behalf-switch"
              onValueChange={toggleOnBehalf}
              disabled={isSubmitting}
            />
            {isOnBehalf && (
              <View>
                <FormSelect
                  ref={userSelectRef}
                  control={control}
                  name="user"
                  rules={userRules}
                  label="On behalf of"
                  testID="on-behalf-off-select"
                  options={userOptions}
                  disabled={isSubmitting}
                  onChange={handleUserChange}
                  leftIcon={
                    <UserIcon
                      width={theme.metrics.iconSize[24]}
                      height={theme.metrics.iconSize[24]}
                      color={theme.colors.icon.active}
                    />
                  }
                />
                <FormSelect
                  ref={officeSelectRef}
                  control={control}
                  name="office"
                  rules={officeRules}
                  label="Location"
                  testID="location-select"
                  options={officeOptions}
                  disabled={isSubmitting}
                  onChange={handleOfficeChange}
                  leftIcon={
                    <LocationIcon
                      width={theme.metrics.iconSize[24]}
                      height={theme.metrics.iconSize[24]}
                      color={theme.colors.icon.active}
                    />
                  }
                />
              </View>
            )}
          </>
        )}
        <View style={styles.mealGroup}>
          <Text style={styles.subTitle}>Breakfast</Text>
          <FormSwitch
            control={control}
            name="breakfast"
            label="Fuel me up for today"
            testID="breakfast-registration-switch"
            disabled={isSubmitting}
          />
        </View>
        <View style={styles.mealGroup}>
          <Text style={styles.subTitle}>Lunch</Text>
          <FormSwitch
            control={control}
            name="lunch"
            label="Save me a seat for lunch"
            testID="lunch-registration-switch"
            disabled={isSubmitting}
          />
          <FormSwitch
            control={control}
            name="vegetarian"
            label="Vegetarian (On lunar 1st and 15th)"
            testID="vegetarian-registration-switch"
            disabled={isSubmitting || !lunchValue}
          />
        </View>
        {reallocationDate && showReallocationNotice && (
          <View style={styles.infoBox}>
            <Text style={styles.infoText}>
              {getUpdateTimeMessage(reallocationDate)}
            </Text>
          </View>
        )}
      </WrapperRequest>
    </>
  );
};
 
const useStyles = makeStyles(theme => ({
  subTitle: {
    fontSize: theme.metrics.textSize[20],
    color: theme.colors.text.error,
  },
  mealGroup: {
    marginTop: theme.metrics.spacing[4],
    gap: theme.metrics.spacing[2],
  },
  infoBox: {
    marginTop: theme.metrics.spacing[4],
    padding: theme.metrics.spacing[4],
    borderRadius: theme.metrics.borderRadius[4],
    backgroundColor: theme.colors.background.tertiary,
  },
  infoText: {
    fontSize: theme.metrics.textSize[16],
    color: theme.colors.text.primary,
  },
  overlay: {
    position: 'absolute',
    top: theme.metrics.spacing[0],
    bottom: theme.metrics.spacing[0],
    left: theme.metrics.spacing[0],
    right: theme.metrics.spacing[0],
    backgroundColor: theme.colors.background.overlay,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 9999,
  },
}));
 
export default MealReservation;