All files / apps/roomBooking/src/screens RoomBooking.tsx

100% Statements 54/54
100% Branches 31/31
100% Functions 11/11
100% Lines 51/51

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                                                                                      1x                       28x 28x 28x   28x 28x 28x 28x   28x 1x 1x 1x 1x               28x                     28x 28x 28x   28x 26x   20x 20x       20x           20x   2x   2x 2x     20x 18x 18x           18x 2x 2x                         28x 14x 11x 1x       28x   1x         28x   2x 1x           28x 14x       28x 26x 26x     26x     28x 26x   26x     28x                                                                                                                                                                                                            
import { useCallback, useEffect, useMemo, useRef } from 'react';
import React from 'react';
import { useForm } from 'react-hook-form';
 
import { Button } from '@repo/ui/components/Button';
import { FormDatePicker } from '@repo/ui/components/Form/FormDatePicker';
import { FormInput } from '@repo/ui/components/Form/FormInput';
import { FormSelect } from '@repo/ui/components/Form/FormSelect';
import { InputDatePickerRef } from '@repo/ui/components/InputDatePicker';
import { SelectRef } from '@repo/ui/components/Select';
import { WrapperRequest } from '@repo/ui/components/WrapperRequest';
import { ClockIcon } from '@repo/ui/icons/Clock';
import { MapIcon } from '@repo/ui/icons/Map';
import { useTheme } from '@repo/ui/themes/ThemeContext';
 
import { DAILY_TIME_SLOTS } from '@repo/constants/time';
 
import { useRequestForm } from '@repo/hooks/request';
 
import { RoomBookingFormType, TimeRange } from '@repo/types/form';
 
import { getBlockedRoomSlots, isToday, timeToMinutes } from '@repo/utils/date';
 
import { REQUEST_FORM_FIELD_RULES } from '@repo/validation/fieldRules';
import { validateRoomBookingForm } from '@repo/validation/requestForms';
 
interface Props {
  rooms?: {
    label: string;
    value: string;
  }[];
  isSubmitting?: boolean;
  bookedRanges: TimeRange[];
  holidays?: string[];
  makeUpWorkdays?: string[];
  onSubmit: (data: RoomBookingFormType) => void;
  onBehalfChange: () => void;
  onBack: () => void;
  onChangeRoom: (roomId: string) => void;
  onChangeDate: (date: Date) => void;
  onScreenBlur?: (closeModals: () => void) => void;
}
 
const RoomBooking = ({
  rooms = [],
  isSubmitting,
  bookedRanges,
  holidays = [],
  makeUpWorkdays = [],
  onSubmit,
  onBack,
  onChangeRoom,
  onChangeDate,
  onScreenBlur,
}: Props) => {
  const { theme } = useTheme();
  const methods = useForm<RoomBookingFormType>();
  const { control, setValue, watch } = methods;
 
  const datePickerRef = useRef<InputDatePickerRef>(null);
  const roomSelectRef = useRef<SelectRef>(null);
  const startTimeSelectRef = useRef<SelectRef>(null);
  const endTimeSelectRef = useRef<SelectRef>(null);
 
  const closeModals = useCallback(() => {
    datePickerRef.current?.close();
    roomSelectRef.current?.close();
    startTimeSelectRef.current?.close();
    endTimeSelectRef.current?.close();
  }, []);
 
  const {
    handlePressBack,
    handleSendRequest,
    createClearErrorCallback,
    disabledDates,
  } = useRequestForm({
    methods,
    onBack,
    onSubmit,
    onScreenBlur,
    closeModals,
    holidays,
    makeUpWorkdays,
    validateBeforeSubmit: validateRoomBookingForm,
  });
 
  const selectedDate = watch('date');
  const startTime = watch('startTime');
  const endTime = watch('endTime');
 
  useEffect(() => {
    if (!selectedDate || isSubmitting) return;
 
    const now = new Date();
    const minMinutes = isToday(selectedDate)
      ? now.getHours() * 60 + now.getMinutes()
      : undefined;
 
    const disabledStartSlots = getBlockedRoomSlots(
      selectedDate,
      bookedRanges,
      minMinutes,
    );
 
    if (
      startTime &&
      disabledStartSlots.some(slot => slot.value === startTime)
    ) {
      createClearErrorCallback('startTime')();
      setValue('startTime', '');
    }
 
    if (endTime && startTime) {
      const startMinutes = timeToMinutes(startTime);
      const disabledEndSlots = getBlockedRoomSlots(
        selectedDate,
        bookedRanges,
        startMinutes,
      );
 
      if (disabledEndSlots.some(slot => slot.value === endTime)) {
        createClearErrorCallback('endTime')();
        setValue('endTime', '');
      }
    }
  }, [
    selectedDate,
    startTime,
    endTime,
    bookedRanges,
    createClearErrorCallback,
    setValue,
    isSubmitting,
  ]);
 
  useEffect(() => {
    if (isSubmitting) return;
    if (!startTime) {
      setValue('endTime', '');
    }
  }, [setValue, startTime, isSubmitting]);
 
  const handleRoomChange = useCallback(
    (val: string) => {
      onChangeRoom(val);
    },
    [onChangeRoom],
  );
 
  const handleDateConfirm = useCallback(
    (val: Date | null | { startDate: Date | null; endDate: Date | null }) => {
      if (val instanceof Date) {
        onChangeDate(val);
      }
    },
    [onChangeDate],
  );
 
  const handleNoteChange = useMemo(
    () => createClearErrorCallback('note'),
    [createClearErrorCallback],
  );
 
  const disabledStartSlots = useMemo(() => {
    const now = new Date();
    const minMinutes = isToday(selectedDate)
      ? now.getHours() * 60 + now.getMinutes()
      : undefined;
    return getBlockedRoomSlots(selectedDate, bookedRanges, minMinutes);
  }, [selectedDate, bookedRanges]);
 
  const disabledEndSlots = useMemo(() => {
    const startMinutes = startTime ? timeToMinutes(startTime) : undefined;
 
    return getBlockedRoomSlots(selectedDate, bookedRanges, startMinutes);
  }, [selectedDate, startTime, bookedRanges]);
 
  return (
    <WrapperRequest
      title="Room Booking"
      onBack={handlePressBack}
      disabled={isSubmitting}
      footerComponent={
        <Button
          onPress={handleSendRequest}
          isLoading={isSubmitting}
          accessibilityLabel="Submit Request"
          accessibilityRole="button"
          accessibilityHint="Sends a room booking request for the selected room and time"
          testID="submit-button"
        >
          Submit Request
        </Button>
      }
    >
      <FormSelect
        ref={roomSelectRef}
        control={control}
        name="room"
        rules={REQUEST_FORM_FIELD_RULES.roomBooking.room}
        label="Room"
        options={rooms}
        disabled={isSubmitting}
        placeholder="Select room"
        leftIcon={
          <MapIcon
            width={theme.metrics.iconSize[24]}
            height={theme.metrics.iconSize[24]}
            color={theme.colors.icon.active}
          />
        }
        testID="room-select"
        onChange={handleRoomChange}
      />
      <FormDatePicker
        ref={datePickerRef}
        control={control}
        name="date"
        rules={REQUEST_FORM_FIELD_RULES.roomBooking.date}
        mode="single"
        minDate={new Date()}
        disabledDates={disabledDates}
        disabled={isSubmitting}
        testID="date-select"
        onConfirm={handleDateConfirm}
      />
      <FormSelect
        ref={startTimeSelectRef}
        control={control}
        name="startTime"
        rules={REQUEST_FORM_FIELD_RULES.roomBooking.startTime}
        label="Start Time"
        options={DAILY_TIME_SLOTS}
        optionsDisabled={disabledStartSlots}
        disabled={isSubmitting}
        placeholder="Select time"
        leftIcon={
          <ClockIcon
            width={theme.metrics.iconSize[24]}
            height={theme.metrics.iconSize[24]}
            color={theme.colors.icon.active}
          />
        }
        testID="start-time-select"
      />
      <FormSelect
        ref={endTimeSelectRef}
        control={control}
        name="endTime"
        rules={REQUEST_FORM_FIELD_RULES.roomBooking.endTime}
        label="End Time"
        options={DAILY_TIME_SLOTS}
        disabled={isSubmitting || !startTime}
        optionsDisabled={disabledEndSlots}
        placeholder="Select time"
        leftIcon={
          <ClockIcon
            width={theme.metrics.iconSize[24]}
            height={theme.metrics.iconSize[24]}
            color={theme.colors.icon.active}
          />
        }
        testID="end-time-select"
      />
      <FormInput
        control={control}
        name="note"
        rules={REQUEST_FORM_FIELD_RULES.roomBooking.note}
        placeholder="Type something"
        label="Reason"
        disabled={isSubmitting}
        testID="reason-input"
        onChangeText={handleNoteChange}
      />
    </WrapperRequest>
  );
};
 
export default RoomBooking;