Feat/SW-1370/Guarantee my stay ancillaries * feat(SW-1370): guarantee for ancillaries * feat(SW-1370): remove console log * feat(SW-1370): add translations * feat(SW-1370): small fix * feat(SW-1370): fix must be guaranteed * feat(SW-1370): fix logic and comments pr * feat(SW-1370): fix comments pr * feat(SW-1370): fix comments pr * feat(SW-1370): add translation * feat(SW-1370): add translation and fix pr comment * feat(SW-1370): fix pr comment * feat(SW-1370): fix encoding path refId issue * feat(SW-1370): refactor AddAncillaryStore usage and introduce context provider * feat(SW-1370): refactor * feat(SW-1370): refactor ancillaries * feat(SW-1370): fix merge Approved-by: Simon.Emanuelsson
79 lines
2.1 KiB
TypeScript
79 lines
2.1 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 guaranteeBooking = trpc.booking.guarantee.useMutation({
|
|
onSuccess: (result) => {
|
|
if (result) {
|
|
if (result.reservationStatus == BookingStatusEnum.BookingCompleted) {
|
|
handleBookingCompleted()
|
|
} else {
|
|
setIsPollingForBookingStatus(true)
|
|
}
|
|
} 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, intl, handlePaymentError])
|
|
|
|
const isLoading =
|
|
guaranteeBooking.isPending ||
|
|
(isPollingForBookingStatus &&
|
|
!bookingStatus.data?.paymentUrl &&
|
|
!bookingStatus.isTimeout)
|
|
|
|
return { guaranteeBooking, isLoading }
|
|
}
|