All files / apps/roomBooking/src/screens/ChooseTime/hook useChooseTime.ts

98.25% Statements 225/229
90.69% Branches 156/172
97.82% Functions 45/46
99.52% Lines 209/210

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 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472                                                                1x   1x 60x 60x 60x 60x 60x         60x 42x   10x       8x 8x   8x   7x   7x     8x   6x 4x   3x   1x       3x   2x                         2x     2x 1x   1x             1x           60x 60x 60x 60x   60x 60x   60x 60x   60x 60x   60x 60x       60x   60x 42x 42x 42x   60x 42x 42x 42x     60x 60x 42x 13x   42x     60x 60x 60x   60x 60x 45x     60x 42x 42x 42x 42x 2x       60x   60x 15x   15x 15x 15x   335x         15x 15x 15x   319x             60x 45x   15x 15x 15x     15x 15x   15x   15x       15x 7x 7x 7x 7x 7x     8x 5x 5x     3x 2x 2x 2x 2x 2x     1x 1x 1x   1x 1x 1x                   60x   60x 45x 19x     60x 42x   42x 42x     42x   948x       42x     42x 42x     42x   930x     80x   42x       60x 44x       60x   4x 4x 4x 1x   3x           60x 3x   3x 1x   3x 2x       60x   6x 6x 5x   5x   5x 5x   5x 3x 3x   3x   3x 1x 1x 2x 1x 1x   1x   3x   2x       2x   2x 1x 1x   2x     5x           60x   6x 6x 5x   5x   5x 5x   5x 3x         3x   3x       1x 1x 2x 1x 1x   1x   3x   2x       2x   2x 1x 1x   2x     5x           60x 45x 33x 33x     12x 12x   12x   12x     12x   4x     12x 12x 8x 8x   8x       8x   2x   2x 2x         12x               60x                                
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
 
import { useQueryClient } from '@tanstack/react-query';
 
import { useWebSocketListener } from '@repo/hooks';
 
import { timeToMinutes } from '@repo/utils/date';
 
import {
  MeetingRoomBookedItem,
  QUERY_KEYS,
  useMeetingRoomsBooked,
} from '@/hooks/useRoom';
 
import {
  useRoomBookingActionsSelector,
  useRoomBookingStateSelector,
} from '../../RoomBooking/context';
import { useRoomBookingRuntime } from '../../RoomBooking/runtime';
import {
  getBookedRanges,
  getDefaultTimes,
  HOURS_DATA,
  MINUTES_DATA,
  minutesToTime,
  PickerItem,
} from '../utils';
 
interface UseChooseTimeProps {
  activeTimeTab: 'start' | 'end';
}
 
let globalLastSelectedDateKey: string | null = null;
 
export const useChooseTime = ({ activeTimeTab }: UseChooseTimeProps) => {
  const queryClient = useQueryClient();
  const runtime = useRoomBookingRuntime();
  const getAccessToken = runtime?.actions?.getAccessToken;
  const wsUrl = runtime?.state?.wsUrl;
  const { lastMessage } = useWebSocketListener({
    url: wsUrl,
    getToken: getAccessToken,
  });
 
  useEffect(() => {
    if (!lastMessage) return;
 
    if (
      lastMessage.type === 'broadcast' &&
      lastMessage.channel === 'ticket_room_booking'
    ) {
      const payload = lastMessage.payload;
      const bookingData = payload?.data;
 
      if (!bookingData) return;
 
      const { room, start, end, status } = bookingData;
 
      queryClient.setQueryData(
        [QUERY_KEYS.MEETING_ROOMS_BOOKED],
        (oldData: MeetingRoomBookedItem[] | undefined) => {
          if (!oldData || !Array.isArray(oldData)) return [];
 
          if (status === 'approved') {
            if (!room || !start || !end) return oldData;
 
            const isAlreadyExists = oldData.some(
              item =>
                item.data?.room === room &&
                item.data?.start === start &&
                item.data?.end === end,
            );
            if (isAlreadyExists) return oldData;
 
            const newBookingItem: MeetingRoomBookedItem = {
              id: payload.id || String(Date.now()),
              category: 'BOOK_ROOM',
              status: 'approved',
              requester: payload.by || bookingData.user || '',
              data: {
                room,
                start,
                end,
                note: bookingData.note || '',
              },
            };
 
            return [...oldData, newBookingItem];
          }
 
          if (status === 'rejected' || status === 'canceled') {
            return oldData.filter(
              item =>
                !(
                  item.data?.room === room &&
                  item.data?.start === start &&
                  item.data?.end === end
                ),
            );
          }
          return oldData;
        },
      );
    }
  }, [lastMessage, queryClient]);
 
  const formDate = useRoomBookingStateSelector(state => state.form.date);
  const formRoom = useRoomBookingStateSelector(state => state.form.room);
  const startTime = useRoomBookingStateSelector(state => state.form.startTime);
  const endTime = useRoomBookingStateSelector(state => state.form.endTime);
 
  const changeStartTime = useRoomBookingActionsSelector(
    actions => actions.changeStartTime,
  );
  const changeEndTime = useRoomBookingActionsSelector(
    actions => actions.changeEndTime,
  );
  const setTimeConflict = useRoomBookingActionsSelector(
    actions => actions.setTimeConflict,
  );
  const setTimeUpdating = useRoomBookingActionsSelector(
    actions => actions.setTimeUpdating,
  );
 
  const { meetingRoomsBooked, isLoadingMeetingRoomsBooked } =
    useMeetingRoomsBooked();
 
  const [hourPickerValue, setHourPickerValue] = useState(() => {
    const activeTimeVal = activeTimeTab === 'start' ? startTime : endTime;
    const hour = activeTimeVal ? activeTimeVal.split(':')[0] : '08';
    return `${hour}-2`;
  });
  const [minutePickerValue, setMinutePickerValue] = useState(() => {
    const activeTimeVal = activeTimeTab === 'start' ? startTime : endTime;
    const minute = activeTimeVal ? activeTimeVal.split(':')[1] : '00';
    return `${minute}-5`;
  });
 
  const [isReady, setIsReady] = useState(false);
  useEffect(() => {
    const timer = setTimeout(() => {
      setIsReady(true);
    }, 50);
    return () => clearTimeout(timer);
  }, []);
 
  const hourTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const minuteTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const valueChangingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
 
  const stateRef = useRef({ startTime, endTime, activeTimeTab });
  useEffect(() => {
    stateRef.current = { startTime, endTime, activeTimeTab };
  }, [startTime, endTime, activeTimeTab]);
 
  useEffect(() => {
    return () => {
      if (hourTimeoutRef.current) clearTimeout(hourTimeoutRef.current);
      if (minuteTimeoutRef.current) clearTimeout(minuteTimeoutRef.current);
      if (valueChangingTimeoutRef.current)
        clearTimeout(valueChangingTimeoutRef.current);
    };
  }, []);
 
  const previousDateRef = useRef<string | null>(globalLastSelectedDateKey);
 
  const syncPickerValues = useCallback((timeStr: string) => {
    const [h, m] = timeStr.split(':');
 
    setHourPickerValue(prev => {
      const cluster = prev.split('-')[1] ?? '0';
      return (
        HOURS_DATA.find(
          item => item.label === h && item.value.endsWith(`-${cluster}`),
        )?.value ?? prev
      );
    });
 
    setMinutePickerValue(prev => {
      const cluster = prev.split('-')[1] ?? '0';
      return (
        MINUTES_DATA.find(
          item => item.label === m && item.value.endsWith(`-${cluster}`),
        )?.value ?? prev
      );
    });
  }, []);
 
  // useEffect quản lý việc tự động thiết lập và cập nhật thời gian theo ngày được chọn
  useEffect(() => {
    if (!formDate) return;
 
    const currentDate = new Date(formDate);
    const currentDateKey = currentDate.toDateString();
    const previousDateKey = previousDateRef.current;
 
    // Cập nhật giá trị cho cả Ref cục bộ và biến Global ngoài Component
    previousDateRef.current = currentDateKey;
    globalLastSelectedDateKey = currentDateKey;
 
    const today = new Date();
    const isToday =
      currentDate.getDate() === today.getDate() &&
      currentDate.getMonth() === today.getMonth() &&
      currentDate.getFullYear() === today.getFullYear();
 
    if (!startTime || !endTime) {
      const { start, end } = getDefaultTimes(currentDate);
      changeStartTime(start);
      changeEndTime(end);
      syncPickerValues(start);
      return;
    }
 
    if (previousDateKey === currentDateKey) {
      syncPickerValues(startTime);
      return;
    }
 
    if (isToday) {
      const { start, end } = getDefaultTimes(currentDate);
      changeStartTime(start);
      changeEndTime(end);
      syncPickerValues(start);
      return;
    }
 
    const defaultStartMins = 480;
    const defaultStartStr = minutesToTime(defaultStartMins);
    const defaultEndStr = minutesToTime(defaultStartMins + 30);
 
    changeStartTime(defaultStartStr);
    changeEndTime(defaultEndStr);
    syncPickerValues(defaultStartStr);
  }, [
    formDate,
    startTime,
    endTime,
    changeStartTime,
    changeEndTime,
    syncPickerValues,
  ]);
 
  const activeTime = activeTimeTab === 'start' ? startTime : endTime;
 
  const [selectedHour, selectedMinute] = useMemo(() => {
    if (!activeTime) return ['08', '00'];
    return activeTime.split(':');
  }, [activeTime]);
 
  useEffect(() => {
    Iif (!selectedHour || !selectedMinute) return;
 
    setHourPickerValue(prev => {
      const currentCluster = prev.split('-')[1] ?? '0';
 
      const matched =
        HOURS_DATA.find(
          item =>
            item.label === selectedHour &&
            item.value.endsWith(`-${currentCluster}`),
        )?.value ?? HOURS_DATA.find(item => item.label === selectedHour)?.value;
 
      return matched ?? prev;
    });
 
    setMinutePickerValue(prev => {
      const currentCluster = prev.split('-')[1] ?? '0';
 
      const matched =
        MINUTES_DATA.find(
          item =>
            item.label === selectedMinute &&
            item.value.endsWith(`-${currentCluster}`),
        )?.value ??
        MINUTES_DATA.find(item => item.label === selectedMinute)?.value;
 
      return matched ?? prev;
    });
  }, [activeTimeTab, selectedHour, selectedMinute]);
 
  const bookedRanges = useMemo(
    () => getBookedRanges(meetingRoomsBooked, formDate, formRoom),
    [meetingRoomsBooked, formDate, formRoom],
  );
 
  const checkIsTimeSlotBooked = useCallback(
    (hourStr: string, minuteStr: string, isEndTime: boolean) => {
      const targetMins = parseInt(hourStr, 10) * 60 + parseInt(minuteStr, 10);
      return bookedRanges.some(range => {
        if (isEndTime) {
          return targetMins > range.start && targetMins <= range.end;
        }
        return targetMins >= range.start && targetMins < range.end;
      });
    },
    [bookedRanges],
  );
 
  const handleValueChanging = useCallback(() => {
    setTimeUpdating(true);
 
    if (valueChangingTimeoutRef.current) {
      clearTimeout(valueChangingTimeoutRef.current);
    }
    valueChangingTimeoutRef.current = setTimeout(() => {
      setTimeUpdating(false);
    }, 200);
  }, [setTimeUpdating]);
 
  const handleHourChange = useCallback(
    ({ item }: { item: PickerItem }) => {
      const [newHour, cluster] = item.value.split('-');
      if (!newHour || !cluster) return;
      setHourPickerValue(item.value);
 
      Iif (hourTimeoutRef.current) clearTimeout(hourTimeoutRef.current);
 
      hourTimeoutRef.current = setTimeout(() => {
        const { startTime: curStart, activeTimeTab: tab } = stateRef.current;
 
        if (tab === 'start') {
          const [, m] = (curStart || '08:00').split(':');
          const startMins = Math.max(480, timeToMinutes(`${newHour}:${m}`));
 
          let endMins = startMins + 30;
 
          if (newHour === '17' && (m === '30' || m === '45')) {
            endMins = 1065;
            changeStartTime(minutesToTime(startMins));
          } else if (endMins > 1065) {
            endMins = 1065;
            changeStartTime(minutesToTime(1050));
          } else {
            changeStartTime(minutesToTime(startMins));
          }
          changeEndTime(minutesToTime(endMins));
        } else {
          const endMins = Math.min(
            1065,
            timeToMinutes(`${newHour}:${selectedMinute}`),
          );
          let startMins = timeToMinutes(curStart || '08:00');
 
          if (endMins <= startMins) {
            startMins = Math.max(480, endMins - 30);
            changeStartTime(minutesToTime(startMins));
          }
          changeEndTime(minutesToTime(endMins));
        }
 
        setTimeUpdating(false);
      }, 80);
    },
    [changeStartTime, changeEndTime, selectedMinute, setTimeUpdating],
  );
 
  const handleMinuteChange = useCallback(
    ({ item }: { item: PickerItem }) => {
      const [newMinute, cluster] = item.value.split('-');
      if (!newMinute || !cluster) return;
      setMinutePickerValue(item.value);
 
      Iif (minuteTimeoutRef.current) clearTimeout(minuteTimeoutRef.current);
 
      minuteTimeoutRef.current = setTimeout(() => {
        const { startTime: curStart, activeTimeTab: tab } = stateRef.current;
 
        if (tab === 'start') {
          const startMins = Math.max(
            480,
            timeToMinutes(`${selectedHour}:${newMinute}`),
          );
 
          let endMins = startMins + 30;
 
          if (
            selectedHour === '17' &&
            (newMinute === '30' || newMinute === '45')
          ) {
            endMins = 1065;
            changeStartTime(minutesToTime(startMins));
          } else if (endMins > 1065) {
            endMins = 1065;
            changeStartTime(minutesToTime(1050));
          } else {
            changeStartTime(minutesToTime(startMins));
          }
          changeEndTime(minutesToTime(endMins));
        } else {
          const endMins = Math.min(
            1065,
            timeToMinutes(`${selectedHour}:${newMinute}`),
          );
          let startMins = timeToMinutes(curStart || '08:00');
 
          if (endMins <= startMins) {
            startMins = Math.max(480, endMins - 30);
            changeStartTime(minutesToTime(startMins));
          }
          changeEndTime(minutesToTime(endMins));
        }
 
        setTimeUpdating(false);
      }, 80);
    },
    [changeStartTime, changeEndTime, selectedHour, setTimeUpdating],
  );
 
  useEffect(() => {
    if (!startTime || !endTime) {
      setTimeConflict(false);
      return;
    }
 
    const currentStartMins = timeToMinutes(startTime);
    const currentEndMins = timeToMinutes(endTime);
 
    const isSameOrInvalidTime = currentStartMins >= currentEndMins;
 
    const isOvertimeConflict = startTime === '17:30' || startTime === '17:45';
 
    const hasRoomConflict =
      bookedRanges.length > 0 &&
      bookedRanges.some(
        range => currentStartMins < range.end && currentEndMins > range.start,
      );
 
    let hasPastConflict = false;
    if (formDate) {
      const selectedDate = new Date(formDate);
      const today = new Date();
      const isToday =
        selectedDate.getDate() === today.getDate() &&
        selectedDate.getMonth() === today.getMonth() &&
        selectedDate.getFullYear() === today.getFullYear();
 
      if (isToday) {
        const currentMins =
          Math.ceil((today.getHours() * 60 + today.getMinutes()) / 30) * 30;
 
        Eif (currentStartMins < currentMins) {
          hasPastConflict = true;
        }
      }
    }
 
    setTimeConflict(
      hasRoomConflict ||
        hasPastConflict ||
        isOvertimeConflict ||
        isSameOrInvalidTime,
    );
  }, [startTime, endTime, bookedRanges, formDate, setTimeConflict]);
 
  return {
    startTime,
    endTime,
    hourPickerValue,
    minutePickerValue,
    isReady,
    isLoadingMeetingRoomsBooked,
    selectedHour,
    selectedMinute,
    handleHourChange,
    handleMinuteChange,
    handleValueChanging,
    checkIsTimeSlotBooked,
    formDate,
  };
};