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

74.76% Statements 80/107
57.3% Branches 51/89
64.28% Functions 18/28
82.6% Lines 76/92

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                                                                                      3x                     3x 14x 14x 14x   14x 14x   14x   14x   14x   14x               14x           14x           14x           14x       14x 7x 7x     14x 7x 7x           14x 2x     14x 2x     14x       14x   1x         1x 1x                                 14x   14x 1x   1x 1x   1x   1x                   1x     14x         14x 13x   4x 2x   2x 2x             2x 2x   2x             14x 7x 7x 1x 1x 1x                       14x 8x   1x 1x   1x   1x 1x               1x   1x 1x   1x           1x   1x   1x 1x   1x                                               14x 14x       14x           14x         14x                                                               3x          
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 { useGetHolidays } from '@repo/hooks';
import { useEnableOldUI } from '@repo/hooks/flags';
 
import { RoomBookingFormType } 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 { useChat } from '@/contexts/ChatContext';
 
import { useBlockBackNavigationWhileSubmitting } from '@/hooks/useBlockNavigation';
import { useCreateRequest } from '@/hooks/useRequest';
import { useGetMeetingRooms, useGetMeetingRoomsBooked } from '@/hooks/useRoom';
import { useWebSocketListener } from '@/hooks/useWebSocket';
 
import type { AppStackScreenProps } from '@/types/navigation';
import {
  RequestCategory,
  RequestStatus,
  RoomBookingRequestParams,
  WsChanel,
  WsType,
} from '@/types/request';
 
import { basicAuthHttps } from '@/services/mainHttpClient';
import { sentryService } from '@/services/sentryService';
 
type LazyLoadRoomBookingScreenProps = AppStackScreenProps<typeof SCREENS.BOOK_ROOM>;
 
const RoomBookingRemote = React.lazy(
  // @ts-ignore
  () => import('roomBooking/RoomBooking'),
);
 
type BookedRoom = {
  room: string;
  start: string;
  end: string;
};
 
export const LazyLoadRoomBookingScreen = ({ navigation }: LazyLoadRoomBookingScreenProps) => {
  const { user } = useAuth();
  const { setFabOffset } = useChat();
  const { value: enableOldUI } = useEnableOldUI(user?.email);
 
  const [roomId, setRoomId] = useState<string | null>(null);
  const [date, setDate] = useState<Date | null>(null);
 
  const [allBookedRoom, setAllBookedRoom] = useState<BookedRoom[]>([]);
 
  const { lastMessage } = useWebSocketListener();
 
  const closeModalsRef = useRef<(() => void) | null>(null);
 
  useFocusEffect(
    useCallback(() => {
      return () => {
        closeModalsRef.current?.();
      };
    }, []),
  );
 
  const { data: rooms, isLoading: isLoadingRooms, isError: isRoomsError } = useGetMeetingRooms();
 
  const {
    data: roomsBooked,
    isLoading: isLoadingRoomsBooked,
    isError: isRoomsBookedError,
  } = useGetMeetingRoomsBooked();
 
  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 onChangeRoom = (selectedRoomId: string) => {
    setRoomId(selectedRoomId);
  };
 
  const onChangeDate = (selectedDate?: Date) => {
    selectedDate && setDate(selectedDate);
  };
 
  const handleBack = () => {
    navigation.goBack();
  };
 
  const { mutate, isPending: isSubmitting } = useCreateRequest(
    () => {
      Toast.show({
        type: 'success',
        text1: 'Room booking request created successfully',
      });
 
      if (enableOldUI) {
        navigation.navigate(SCREENS.BOTTOM_TAB, {
          screen: SCREENS.MY_REQUEST,
        });
      } else E{
        navigation.navigate(SCREENS.HOME_V2);
      }
    },
    (error: unknown) => {
      const apiMessage = getErrorMessage(error);
      Toast.show({
        type: 'error',
        text1: 'Failed to create room booking request',
        ...(apiMessage && { text2: apiMessage }),
      });
    },
  );
 
  useBlockBackNavigationWhileSubmitting(navigation, isSubmitting);
 
  const handleSubmit = (formData: RoomBookingFormType) => {
    Iif (!formData.date) return;
 
    const isoStartTime = mergeDateAndTimeToISO(formData.date, formData.startTime);
    const isoEndTime = mergeDateAndTimeToISO(formData.date, formData.endTime);
 
    Iif (!isoStartTime || !isoEndTime) return;
 
    const dataToSubmit: RoomBookingRequestParams = {
      category: RequestCategory.BOOK_ROOM,
      data: {
        room: formData.room,
        start: isoStartTime,
        end: isoEndTime,
        note: formData.note,
      },
    };
 
    mutate(dataToSubmit);
  };
 
  const formatRooms = (rooms || []).map(room => ({
    label: room.id,
    value: room.id,
  }));
 
  const getBookedRanges = () => {
    if (!roomId || !date) return [];
 
    return allBookedRoom
      .filter(item => item.room === roomId)
      .filter(item => {
        const start = new Date(item.start);
        return (
          start.getFullYear() === date.getFullYear() &&
          start.getMonth() === date.getMonth() &&
          start.getDate() === date.getDate()
        );
      })
      .map(item => {
        const start = new Date(item.start);
        const end = new Date(item.end);
 
        return {
          start: start.getHours() * 60 + start.getMinutes(),
          end: end.getHours() * 60 + end.getMinutes(),
        };
      });
  };
 
  useEffect(() => {
    Eif (roomsBooked) {
      roomsBooked.map(item => {
        const { data } = item;
        const { room, start, end } = data;
        setAllBookedRoom(prev => [
          ...prev,
          {
            room,
            start,
            end,
          },
        ]);
      });
    }
  }, [roomsBooked]);
 
  useEffect(() => {
    if (!lastMessage) return;
 
    Iif (lastMessage.type !== WsType.BROADCAST) return;
    Iif (lastMessage.channel !== WsChanel.ROOM_BOOKING) return;
 
    const payload = lastMessage.payload;
 
    const { data: bookingDataWhenCreated } = payload || {};
    Iif (!bookingDataWhenCreated) return;
 
    const {
      room,
      start,
      end,
      status,
      data: bookingDataWhenRejected,
    } = bookingDataWhenCreated || {};
 
    Eif (status === RequestStatus.APPROVE) {
      Iif (!room || !start || !end) return;
 
      const booking: BookedRoom = {
        room,
        start,
        end,
      };
 
      setAllBookedRoom(prev => {
        const exists =
          prev.length > 0 && prev.some(b => b.room === room && b.start === start && b.end === end);
 
        Iif (exists) return prev;
        return [...prev, booking];
      });
      return;
    }
 
    const {
      room: roomWhenRejected,
      start: startWhenRejected,
      end: endWhenRejected,
    } = bookingDataWhenRejected || {};
 
    if (status === RequestStatus.REJECT) {
      if (!roomWhenRejected || !startWhenRejected || !endWhenRejected) return;
 
      setAllBookedRoom(prev =>
        prev.filter(
          b =>
            b.room !== roomWhenRejected &&
            b.start !== startWhenRejected &&
            b.end !== endWhenRejected,
        ),
      );
      return;
    }
  }, [lastMessage]);
 
  useEffect(() => {
    setFabOffset(20);
  }, [setFabOffset]);
 
  const isError =
    isRoomsError ||
    isRoomsBookedError ||
    isGetHolidaysErrorForCurrentYear ||
    isGetHolidaysErrorForNextYear;
 
  const isLoading =
    isLoadingRooms ||
    isLoadingRoomsBooked ||
    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 />}>
            <RoomBookingRemote
              rooms={formatRooms}
              isSubmitting={isSubmitting}
              holidays={holidays}
              makeUpWorkdays={makeUpWorkdays}
              onBack={handleBack}
              onSubmit={handleSubmit}
              onChangeRoom={onChangeRoom}
              onChangeDate={onChangeDate}
              bookedRanges={getBookedRanges()}
              onScreenBlur={(closeModals: () => void) => {
                closeModalsRef.current = closeModals;
              }}
            />
          </React.Suspense>
        </ErrorBoundary>
      )}
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});