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

85.05% Statements 74/87
75.3% Branches 61/81
79.16% Functions 19/24
87.01% Lines 67/77

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                                                                          2x             2x     13x 13x 13x 13x 13x 13x 13x 1x 1x       13x     13x 11x                           13x   13x           13x   13x     13x   13x           13x                   13x             13x           13x                 13x 12x 1x         11x                       13x 12x 12x   12x     2x 2x 2x 2x 2x     1x 1x 1x         13x       13x 10x 1x 1x 1x       13x   13x                           13x     1x       1x     1x 1x               13x   13x         13x   13x       13x 1x             1x     13x                 13x       13x 13x     13x                                                       1x                 2x          
import React, { useCallback, useEffect, 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 { useGetExtraUsers } from '@repo/hooks';
 
import { MealReservationFormType } from '@repo/types/form';
 
import { getErrorMessage } from '@repo/utils/error';
import { useBlockBackNavigation } from '@repo/utils/useBlockBackNavigation';
 
import { FallbackError } from '@/components/FallbackError';
import { LoadingSlider } from '@/components/LoadingSlider';
 
import { useAuth } from '@/contexts/AuthContext';
import { useChatActionsSelector } from '@/contexts/ChatContext';
 
import { useRegistrationData } from '@/hooks/useRegistrationData';
import {
  useGetMyRequests,
  useGetUserRequests,
  useMealReservationRequest,
} from '@/hooks/useRequest';
import { useGetRooms } from '@/hooks/useRoom';
 
import type { AppStackScreenProps } from '@/types/navigation';
import type { MealReservationRequestParams, ReallocationData } from '@/types/request';
import { RequestCategory, RequestStatus } from '@/types/request';
import { UserRole } from '@/types/user';
 
import { sentryService } from '@/services/sentryService';
 
const MealReservationRemote = React.lazy(
  // @ts-ignore
  () => import('mealReservation/MealReservation'),
);
 
type LazyLoadMealReservationScreenProps = AppStackScreenProps<typeof SCREENS.MEAL_RESERVATION>;
 
export const LazyLoadMealReservationScreen = ({
  navigation,
}: LazyLoadMealReservationScreenProps) => {
  const { user } = useAuth();
  const setFabOffset = useChatActionsSelector(a => a.setFabOffset);
  const [id, setId] = useState<string>(user?.email || '');
  const [isOnBehalf, setIsOnBehalf] = useState(false);
  const handleChange = (useId: string) => setId(useId);
  const handleOnBehalfOn = () => setIsOnBehalf(true);
  const handleOnBehalfOff = () => {
    setIsOnBehalf(false);
    setId(user?.email || '');
  };
 
  // Ref to store the close modals function from MealReservation component
  const closeModalsRef = useRef<(() => void) | null>(null);
 
  // Sync id with user?.email when it becomes available
  React.useEffect(() => {
    Iif (user?.email && !id) {
      setId(user.email);
    }
  }, [user?.email, id]);
 
  // Close modals when screen loses focus (e.g., when navigating away via notification)
  const {
    meInfo,
    registration,
    isLoading: isLoadingData,
    isError: isDataError,
    isLoadingRegistration,
    isRegistrationError,
    refetchMeInfo,
  } = useRegistrationData(id);
 
  const isManager = meInfo?.groups?.includes(UserRole.ON_BEHALF_MANAGER) || false;
 
  const {
    data: extraUsers,
    isLoading: isLoadingExtraUsers,
    isError: isErrorExtraUsers,
  } = useGetExtraUsers(!isManager);
 
  const { data: rooms, isLoading: isLoadingRooms, isError: isRoomsError } = useGetRooms(!isManager);
 
  // Always load rooms for reallocation notice destination-office lookup
  const { data: allRooms } = useGetRooms(false);
 
  const selectedUserId = isOnBehalf && id !== user?.email ? id : undefined;
 
  const {
    data: myApprovedRequests,
    isLoading: isLoadingMyApproved,
    refetch: refetchMyApprovedRequests,
  } = useGetMyRequests({
    status: RequestStatus.APPROVE,
    limit: 20,
    disabled: isOnBehalf,
  });
 
  const {
    data: myPendingRequests,
    isLoading: isLoadingMyPending,
    refetch: refetchMyPendingRequests,
  } = useGetMyRequests({
    status: RequestStatus.PENDING,
    limit: 20,
    disabled: isOnBehalf,
  });
 
  const { data: onBehalfApprovedRequests, isLoading: isLoadingOnBehalfApproved } =
    useGetUserRequests(selectedUserId ?? '', {
      status: RequestStatus.APPROVE,
      limit: 20,
      disabled: !selectedUserId,
    });
 
  const { data: onBehalfPendingRequests, isLoading: isLoadingOnBehalfPending } = useGetUserRequests(
    selectedUserId ?? '',
    {
      status: RequestStatus.PENDING,
      limit: 20,
      disabled: !selectedUserId,
    },
  );
 
  const reallocationItems = useMemo(() => {
    if (isOnBehalf) {
      return [
        ...(onBehalfApprovedRequests?.pages?.[0]?.data?.items ?? []),
        ...(onBehalfPendingRequests?.pages?.[0]?.data?.items ?? []),
      ];
    }
    return [
      ...(myApprovedRequests?.pages?.[0]?.data?.items ?? []),
      ...(myPendingRequests?.pages?.[0]?.data?.items ?? []),
    ];
  }, [
    isOnBehalf,
    myApprovedRequests,
    myPendingRequests,
    onBehalfApprovedRequests,
    onBehalfPendingRequests,
  ]);
 
  const latestOfficeToOfficeReallocation = useMemo(() => {
    const items = reallocationItems;
    const now = Date.now();
 
    return (
      items
        .filter(item => {
          Iif (item.category !== RequestCategory.REALLOCATION) return false;
          const data = item.data as ReallocationData;
          Iif (!data?.origin || !data?.dest) return false;
          Iif (data.origin === 'Home' || data.dest === 'Home') return false;
          return data.time ? new Date(data.time).getTime() > now : false;
        })
        .sort((a, b) => {
          const aTime = new Date((a.data as ReallocationData).time ?? 0).getTime();
          const bTime = new Date((b.data as ReallocationData).time ?? 0).getTime();
          return aTime - bTime; // nearest future first
        })[0] ?? null
    );
  }, [reallocationItems]);
 
  const pendingReallocationDate = latestOfficeToOfficeReallocation
    ? (latestOfficeToOfficeReallocation.data as ReallocationData).time
    : undefined;
 
  const pendingDestOffice = useMemo(() => {
    if (!latestOfficeToOfficeReallocation) return undefined;
    const destRoomId = (latestOfficeToOfficeReallocation.data as ReallocationData).dest;
    const roomsList = allRooms ?? rooms ?? [];
    return roomsList.find(r => r.id === destRoomId)?.office ?? registration?.office;
  }, [latestOfficeToOfficeReallocation, allRooms, rooms, registration?.office]);
 
  const showRegistrationNotice =
    !!latestOfficeToOfficeReallocation && !!(registration?.breakfast || registration?.lunch);
 
  useFocusEffect(
    useCallback(() => {
      refetchMeInfo();
      if (!isOnBehalf) {
        refetchMyApprovedRequests();
        refetchMyPendingRequests();
      }
      return () => {
        // This runs when the screen loses focus
        closeModalsRef.current?.();
      };
    }, [refetchMeInfo, refetchMyApprovedRequests, refetchMyPendingRequests, isOnBehalf]),
  );
 
  const { mutate, isPending: isSubmitting } = useMealReservationRequest(
    id,
    () => {
      Toast.show({
        type: 'success',
        text1: 'Meal reservation request created successfully',
      });
      navigation.navigate(SCREENS.HOME);
    },
    (error: unknown) => {
      const apiMessage = getErrorMessage(error);
      Toast.show({
        type: 'error',
        text1: 'Failed to create meal reservation request',
        ...(apiMessage && { text2: apiMessage }),
      });
    },
  );
 
  useBlockBackNavigation(isSubmitting, { navigation });
 
  const extraUsersOptions = (extraUsers || []).map((item: { id: string; name: string }) => ({
    id: item.id,
    name: item.name,
  }));
 
  const offices = [...new Set((rooms || []).map(item => item.office).filter(Boolean))];
 
  const handleBack = () => {
    navigation.goBack();
  };
 
  const handleSubmit = (formData: MealReservationFormType) => {
    const dataToSubmit: MealReservationRequestParams = {
      breakfast: formData.breakfast,
      lunch: formData.lunch,
      vegetarian: formData.vegetarian,
      ...(formData.office && id !== user?.email && { office: formData.office }),
      ...(formData.user && id !== user?.email && { user: formData.user }),
    };
    mutate(dataToSubmit);
  };
 
  const isLoading = [
    isLoadingData,
    isLoadingExtraUsers,
    isLoadingRooms,
    isLoadingRegistration,
    isOnBehalf
      ? isLoadingOnBehalfApproved || isLoadingOnBehalfPending
      : isLoadingMyApproved || isLoadingMyPending,
  ].some(Boolean);
  const isError = [isDataError, isErrorExtraUsers, isRoomsError, !!isRegistrationError].some(
    Boolean,
  );
 
  useEffect(() => {
    setFabOffset(20);
  }, [setFabOffset]);
 
  return (
    <View style={styles.container}>
      {isError && <Text>Something went wrong</Text>}
      <ErrorBoundary
        FallbackComponent={FallbackError}
        onError={error => sentryService.captureException(error)}
      >
        <React.Suspense fallback={<LoadingSlider />}>
          <MealReservationRemote
            extraUsers={extraUsersOptions}
            office={registration?.office}
            offices={offices}
            breakfast={registration?.breakfast}
            lunch={registration?.lunch}
            vegetarian={registration?.vegetarian}
            isManager={isManager}
            isSubmitting={isSubmitting}
            isLoadingRegistration={isLoading}
            allowEmptyChange={false}
            pendingReallocationDate={pendingReallocationDate}
            showRegistrationNotice={showRegistrationNotice}
            noticeOffice={pendingDestOffice}
            onBehalfOff={handleOnBehalfOff}
            onBehalfOn={handleOnBehalfOn}
            onSelectUser={handleChange}
            onBack={handleBack}
            onSubmit={handleSubmit}
            onScreenBlur={(closeModals: () => void) => {
              closeModalsRef.current = closeModals;
            }}
          />
        </React.Suspense>
      </ErrorBoundary>
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});