All files / utils useReservationTimer.ts

70.37% Statements 19/27
50% Branches 7/14
66.66% Functions 6/9
76% Lines 19/25

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            47x   47x   47x 47x 47x 47x     47x 47x         47x     47x     47x 47x         47x       47x 47x         47x 47x         47x           47x                
import type { SelectedAppointmentProvider } from "@/types/ProvideInjectTypes";
import type { Ref } from "vue";
 
import { computed, inject, onBeforeUnmount, onMounted, ref } from "vue";
 
export function useReservationTimer() {
  const { appointment } = inject<SelectedAppointmentProvider>("appointment")!;
 
  const reservationStartMs = inject<Ref<number | null>>("reservationStartMs")!;
 
  const reservationDurationMinutes = computed<number | undefined>(() => {
    const raw: unknown = (appointment.value as any)?.scope?.reservationDuration;
    const n = raw as number | undefined;
    return Number.isFinite(n) ? n : undefined;
  });
 
  const deadlineMs = computed<number | null>(() => {
    Iif (
      reservationStartMs.value == null ||
      reservationDurationMinutes.value == null
    )
      return null;
    return reservationStartMs.value + reservationDurationMinutes.value * 60_000;
  });
 
  const nowMs = ref<number>(Date.now());
  let timer: number | undefined;
 
  onMounted(() => {
    timer = window.setInterval(() => {
      nowMs.value = Date.now();
    }, 1000);
  });
 
  onBeforeUnmount(() => {
    if (timer) window.clearInterval(timer);
  });
 
  const remainingMs = computed<number | null>(() =>
    deadlineMs.value == null
      ? null
      : Math.max(0, deadlineMs.value - nowMs.value)
  );
 
  const isExpired = computed<boolean>(
    () => remainingMs.value !== null && remainingMs.value <= 0
  );
 
  // Nachfolgendes kann für späteres Ticket ZMSKVR-501 zur Anzeige des restlichen Timers verwendet werden
 
  const timeLeftString = computed<string>(() => {
    if (remainingMs.value == null) return "";
    const totalSeconds = Math.floor(remainingMs.value / 1000);
    return `${totalSeconds} Sekunden`;
  });
 
  return {
    isExpired,
    remainingMs,
    deadlineMs,
    nowMs,
    timeLeftString,
  };
}