fix: refetch data for confirmation number to avoid booking already completed * fix: refetch data for confirmation number to avoid booking already completed Approved-by: Christian Andolf
82 lines
2.2 KiB
TypeScript
82 lines
2.2 KiB
TypeScript
import { useRouter } from "next/navigation"
|
|
import { useCallback, useEffect, useState } from "react"
|
|
import { useIntl } from "react-intl"
|
|
|
|
import { BookingStatusEnum } from "@/constants/booking"
|
|
import { trpc } from "@/lib/trpc/client"
|
|
|
|
import { toast } from "@/components/TempDesignSystem/Toasts"
|
|
import { useHandleBookingStatus } from "@/hooks/booking/useHandleBookingStatus"
|
|
|
|
const maxRetries = 15
|
|
const retryInterval = 2000
|
|
|
|
export function useGuaranteeBooking({
|
|
confirmationNumber,
|
|
handleBookingCompleted = () => {},
|
|
}: {
|
|
confirmationNumber: string
|
|
handleBookingCompleted?: () => void
|
|
}) {
|
|
const intl = useIntl()
|
|
const router = useRouter()
|
|
const [isPollingForBookingStatus, setIsPollingForBookingStatus] =
|
|
useState(false)
|
|
|
|
const handlePaymentError = useCallback(() => {
|
|
toast.error(
|
|
intl.formatMessage({
|
|
id: "We had an issue guaranteeing your booking. Please try again.",
|
|
})
|
|
)
|
|
}, [intl])
|
|
const utils = trpc.useUtils()
|
|
const guaranteeBooking = trpc.booking.guarantee.useMutation({
|
|
onSuccess: (result, variables) => {
|
|
if (result) {
|
|
if (result.reservationStatus == BookingStatusEnum.BookingCompleted) {
|
|
handleBookingCompleted()
|
|
} else {
|
|
setIsPollingForBookingStatus(true)
|
|
utils.booking.status.invalidate({
|
|
confirmationNumber: variables.confirmationNumber,
|
|
})
|
|
}
|
|
} else {
|
|
handlePaymentError()
|
|
}
|
|
},
|
|
onError: () => {
|
|
toast.error(
|
|
intl.formatMessage({
|
|
id: "Something went wrong!",
|
|
})
|
|
)
|
|
},
|
|
})
|
|
|
|
const bookingStatus = useHandleBookingStatus({
|
|
confirmationNumber,
|
|
expectedStatuses: [BookingStatusEnum.BookingCompleted],
|
|
maxRetries,
|
|
retryInterval,
|
|
enabled: isPollingForBookingStatus,
|
|
})
|
|
|
|
useEffect(() => {
|
|
if (bookingStatus?.data?.paymentUrl) {
|
|
router.push(bookingStatus.data.paymentUrl)
|
|
} else if (bookingStatus.isTimeout) {
|
|
handlePaymentError()
|
|
}
|
|
}, [bookingStatus, router, handlePaymentError])
|
|
|
|
const isLoading =
|
|
guaranteeBooking.isPending ||
|
|
(isPollingForBookingStatus &&
|
|
!bookingStatus.data?.paymentUrl &&
|
|
!bookingStatus.isTimeout)
|
|
|
|
return { guaranteeBooking, isLoading }
|
|
}
|