All files / apps/host/src/screens/LazyLoadTimeOff index.tsx

72.13% Statements 44/61
68.51% Branches 37/54
47.36% Functions 9/19
79.24% Lines 42/53

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                                                                  2x             2x 10x 10x 10x 10x     10x     10x                         10x   10x           10x           10x         10x       10x 8x   8x     10x 8x   8x                   10x   10x   8x             10x 8x         10x   3x       3x 1x       2x                         10x   10x         10x 2x   2x 2x   2x   2x                       2x       10x           10x         10x                                                                   2x          
import React, { useCallback, useMemo, useRef, useState } from 'react';
import ErrorBoundary from 'react-native-error-boundary';
import Toast from 'react-native-toast-message';
import { StyleSheet, Text, View } from 'react-native';
 
import { useFocusEffect } from '@react-navigation/native';
 
import { SCREENS } from '@repo/constants/screens';
 
import { useGetEmployees, useGetExtraUsers, useGetHolidays, useGetMeInfo } from '@repo/hooks';
import { useEnableOldUI } from '@repo/hooks/flags';
 
import { EmailOption, TimeOffFormType } from '@repo/types/form';
 
import { mergeDateAndTimeToISO } from '@repo/utils/date';
import { getErrorMessage } from '@repo/utils/error';
 
import { FallbackError } from '@/components/FallbackError';
import { FallbackLoadRemote } from '@/components/FallbackLoadRemote';
import { LoadingSlider } from '@/components/LoadingSlider';
 
import { useAuth } from '@/contexts/AuthContext';
 
import { useBlockBackNavigationWhileSubmitting } from '@/hooks/useBlockNavigation';
import { useCreateRequest } from '@/hooks/useRequest';
 
import type { AppStackScreenProps } from '@/types/navigation';
import type { TimeOffRequestParams } from '@/types/request';
import { UserInfoBase, UserRole } from '@/types/user';
 
import { basicAuthHttps } from '@/services/mainHttpClient';
import { sentryService } from '@/services/sentryService';
 
const TimeOffRemote = React.lazy(
  // @ts-ignore
  () => import('timeOff/TimeOff'),
);
 
type LazyLoadTimeOffScreenProps = AppStackScreenProps<typeof SCREENS.TIME_OFF>;
 
export const LazyLoadTimeOffScreen = ({ navigation }: LazyLoadTimeOffScreenProps) => {
  const { user } = useAuth();
  const { value: enableOldUI } = useEnableOldUI(user?.email);
  const [isOnBehalf, setIsOnBehalf] = useState<boolean>(false);
  const handleChange = () => setIsOnBehalf((prev: boolean) => !prev);
 
  // Ref to store the close modals function from TimeOff component
  const closeModalsRef = useRef<(() => void) | null>(null);
 
  // Close modals when screen loses focus (e.g., when navigating away via notification)
  useFocusEffect(
    useCallback(() => {
      return () => {
        // This runs when the screen loses focus
        closeModalsRef.current?.();
      };
    }, []),
  );
 
  const {
    data: meInfo,
    isLoading: isLoadingMeInfo,
    isError: isGetMeInfoError,
  } = useGetMeInfo<UserInfoBase>();
 
  const isManager = meInfo?.groups?.includes(UserRole.ON_BEHALF_MANAGER) || false;
 
  const {
    data: employees,
    isLoading: isLoadingEmployees,
    isError: isGetEmployeesError,
  } = useGetEmployees();
 
  const {
    data: currentYearHolidays,
    isLoading: isLoadingHolidaysForCurrentYear,
    isError: isGetHolidaysErrorForCurrentYear,
  } = useGetHolidays(new Date().getFullYear(), { httpClient: basicAuthHttps });
  const {
    data: nextYearHolidays,
    isLoading: isLoadingHolidaysForNextYear,
    isError: isGetHolidaysErrorForNextYear,
  } = useGetHolidays(new Date().getFullYear() + 1, {
    httpClient: basicAuthHttps,
  });
 
  const holidays = useMemo(() => {
    Iif (!currentYearHolidays && !nextYearHolidays) return [];
 
    return [...(currentYearHolidays?.holidays ?? []), ...(nextYearHolidays?.holidays ?? [])];
  }, [currentYearHolidays, nextYearHolidays]);
 
  const makeUpWorkdays = useMemo(() => {
    Iif (!currentYearHolidays && !nextYearHolidays) return [];
 
    return [
      ...(currentYearHolidays?.makeUpWorkdays ?? []),
      ...(nextYearHolidays?.makeUpWorkdays ?? []),
    ];
  }, [currentYearHolidays, nextYearHolidays]);
 
  const {
    data: extraUsers,
    isLoading: isLoadingExtraUsers,
    isError: isErrorExtraUsers,
  } = useGetExtraUsers(!isOnBehalf);
 
  const extraUsersOptions = useMemo(
    () =>
      extraUsers?.map(item => ({
        id: item.id,
        name: item.name,
      })) || [],
    [extraUsers],
  );
 
  const employeeOptions: EmailOption[] = useMemo(() => {
    return (employees || [])
      .map(e => ({ email: e.id, name: e.name, avatar: e.avatar }))
      .filter(e => e.email !== meInfo?.email);
  }, [employees, meInfo?.email]);
 
  const { mutate, isPending: isSubmitting } = useCreateRequest(
    () => {
      Toast.show({
        type: 'success',
        text1: 'Time off request created successfully',
      });
      if (enableOldUI) {
        navigation.navigate(SCREENS.BOTTOM_TAB, {
          screen: isOnBehalf ? SCREENS.HOME : SCREENS.MY_REQUEST,
        });
      } else {
        navigation.navigate(SCREENS.HOME_V2);
      }
    },
    (error: unknown) => {
      const apiMessage = getErrorMessage(error);
      Toast.show({
        type: 'error',
        text1: 'Failed to create time off request',
        ...(apiMessage && { text2: apiMessage }),
      });
    },
  );
 
  useBlockBackNavigationWhileSubmitting(navigation, isSubmitting);
 
  const handleBack = () => {
    if (isSubmitting) return;
    navigation.goBack();
  };
 
  const handleSubmit = (formData: TimeOffFormType) => {
    Iif (!formData.endDate || !formData.startDate) return;
 
    const isoStartTime = mergeDateAndTimeToISO(formData.startDate, formData.startTime);
    const isoEndTime = mergeDateAndTimeToISO(formData.endDate, formData.endTime);
 
    Iif (!isoStartTime || !isoEndTime) return;
 
    const dataToSubmit: TimeOffRequestParams = {
      category: 'time-off',
      to: formData.to,
      cc: formData.cc,
      ...(formData.user && isOnBehalf && { requester: formData.user }),
      data: {
        start: isoStartTime,
        end: isoEndTime,
        note: formData.note,
      },
    };
 
    mutate(dataToSubmit);
  };
 
  const isError =
    isGetMeInfoError ||
    isErrorExtraUsers ||
    isGetEmployeesError ||
    isGetHolidaysErrorForCurrentYear ||
    isGetHolidaysErrorForNextYear;
  const isLoading =
    isLoadingMeInfo ||
    isLoadingEmployees ||
    isLoadingHolidaysForCurrentYear ||
    isLoadingHolidaysForNextYear;
 
  return (
    <View style={styles.container}>
      {isError && <Text>Something went wrong</Text>}
      {isLoading ? (
        <LoadingSlider />
      ) : (
        <ErrorBoundary
          FallbackComponent={FallbackError}
          onError={error => sentryService.captureException(error)}
        >
          <React.Suspense fallback={<FallbackLoadRemote />}>
            <TimeOffRemote
              isOnBehalf={isOnBehalf}
              isManager={isManager}
              isLoading={isLoadingExtraUsers}
              extraUsers={extraUsersOptions}
              employees={employeeOptions}
              isSubmitting={isSubmitting}
              holidays={holidays}
              makeUpWorkdays={makeUpWorkdays}
              onBehalfChange={handleChange}
              onBack={handleBack}
              onSubmit={handleSubmit}
              onScreenBlur={(closeModals: () => void) => {
                closeModalsRef.current = closeModals;
              }}
            />
          </React.Suspense>
        </ErrorBoundary>
      )}
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});