Merged in monorepo-step-1 (pull request #1080)
Migrate to a monorepo setup - step 1 * Move web to subfolder /apps/scandic-web * Yarn + transitive deps - Move to yarn - design-system package removed for now since yarn doesn't support the parameter for token (ie project currently broken) - Add missing transitive dependencies as Yarn otherwise prevents these imports - VS Code doesn't pick up TS path aliases unless you open /apps/scandic-web instead of root (will be fixed with monorepo) * Pin framer-motion to temporarily fix typing issue https://github.com/adobe/react-spectrum/issues/7494 * Pin zod to avoid typ error There seems to have been a breaking change in the types returned by zod where error is now returned as undefined instead of missing in the type. We should just handle this but to avoid merge conflicts just pin the dependency for now. * Pin react-intl version Pin version of react-intl to avoid tiny type issue where formatMessage does not accept a generic any more. This will be fixed in a future commit, but to avoid merge conflicts just pin for now. * Pin typescript version Temporarily pin version as newer versions as stricter and results in a type error. Will be fixed in future commit after merge. * Setup workspaces * Add design-system as a monorepo package * Remove unused env var DESIGN_SYSTEM_ACCESS_TOKEN * Fix husky for monorepo setup * Update netlify.toml * Add lint script to root package.json * Add stub readme * Fix react-intl formatMessage types * Test netlify.toml in root * Remove root toml * Update netlify.toml publish path * Remove package-lock.json * Update build for branch/preview builds Approved-by: Linus Flood
This commit is contained in:
committed by
Linus Flood
parent
667cab6fb6
commit
80100e7631
@@ -0,0 +1,27 @@
|
||||
import { Suspense } from "react"
|
||||
|
||||
import Breadcrumbs from "@/components/Breadcrumbs"
|
||||
import BreadcrumbsSkeleton from "@/components/TempDesignSystem/Breadcrumbs/BreadcrumbsSkeleton"
|
||||
|
||||
import type { ContentTypeParams, LangParams, PageArgs } from "@/types/params"
|
||||
import { PageContentTypeEnum } from "@/types/requests/contentType"
|
||||
|
||||
const IGNORED_CONTENT_TYPES = [
|
||||
PageContentTypeEnum.hotelPage,
|
||||
PageContentTypeEnum.destinationCityPage,
|
||||
PageContentTypeEnum.destinationCountryPage,
|
||||
]
|
||||
|
||||
export default function PageBreadcrumbs({
|
||||
params,
|
||||
}: PageArgs<LangParams & ContentTypeParams>) {
|
||||
if (IGNORED_CONTENT_TYPES.includes(params.contentType)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<Suspense fallback={<BreadcrumbsSkeleton />}>
|
||||
<Breadcrumbs variant={params.contentType} />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { env } from "@/env/server"
|
||||
|
||||
import CurrentLoadingSpinner from "@/components/Current/LoadingSpinner"
|
||||
import LoadingSpinner from "@/components/LoadingSpinner"
|
||||
|
||||
export default function Loading() {
|
||||
if (env.HIDE_FOR_NEXT_RELEASE) {
|
||||
return <CurrentLoadingSpinner />
|
||||
}
|
||||
return <LoadingSpinner />
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { setPreviewData } from "@/lib/previewContext"
|
||||
|
||||
import InitLivePreview from "@/components/LivePreview"
|
||||
|
||||
import type { PageArgs, UIDParams } from "@/types/params"
|
||||
|
||||
export default function PreviewPage({
|
||||
searchParams,
|
||||
params,
|
||||
}: PageArgs<UIDParams, URLSearchParams>) {
|
||||
const shouldInitializePreview = searchParams.isPreview === "true"
|
||||
|
||||
if (searchParams.live_preview) {
|
||||
setPreviewData({ hash: searchParams.live_preview, uid: params.uid })
|
||||
}
|
||||
|
||||
return shouldInitializePreview ? <InitLivePreview /> : null
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
.layout {
|
||||
display: grid;
|
||||
font-family: var(--typography-Body-Regular-fontFamily);
|
||||
grid-template-rows: auto 1fr;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.container {
|
||||
background-color: var(--Base-Background-Primary-Normal);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import styles from "./layout.module.css"
|
||||
|
||||
import type {
|
||||
ContentTypeParams,
|
||||
LangParams,
|
||||
LayoutArgs,
|
||||
UIDParams,
|
||||
} from "@/types/params"
|
||||
|
||||
export default function ContentTypeLayout({
|
||||
breadcrumbs,
|
||||
preview,
|
||||
children,
|
||||
}: React.PropsWithChildren<
|
||||
LayoutArgs<LangParams & ContentTypeParams & UIDParams> & {
|
||||
breadcrumbs: React.ReactNode
|
||||
preview: React.ReactNode
|
||||
}
|
||||
>) {
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<section className={styles.layout}>
|
||||
{preview}
|
||||
{breadcrumbs}
|
||||
{children}
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import LoadingSpinner from "@/components/LoadingSpinner"
|
||||
|
||||
export default function Loading() {
|
||||
return <LoadingSpinner fullPage />
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { headers } from "next/headers"
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
|
||||
import { overview } from "@/constants/routes/myPages"
|
||||
import { isSignupPage } from "@/constants/routes/signup"
|
||||
import { env } from "@/env/server"
|
||||
import { getHotelPage } from "@/lib/trpc/memoizedRequests"
|
||||
|
||||
import { auth } from "@/auth"
|
||||
import DestinationCityPage from "@/components/ContentType/DestinationPage/DestinationCityPage"
|
||||
import DestinationCountryPage from "@/components/ContentType/DestinationPage/DestinationCountryPage"
|
||||
import DestinationOverviewPage from "@/components/ContentType/DestinationPage/DestinationOverviewPage"
|
||||
import HotelPage from "@/components/ContentType/HotelPage"
|
||||
import HotelSubpage from "@/components/ContentType/HotelSubpage"
|
||||
import LoyaltyPage from "@/components/ContentType/LoyaltyPage"
|
||||
import StartPage from "@/components/ContentType/StartPage"
|
||||
import CollectionPage from "@/components/ContentType/StaticPages/CollectionPage"
|
||||
import ContentPage from "@/components/ContentType/StaticPages/ContentPage"
|
||||
import { getLang } from "@/i18n/serverContext"
|
||||
import { isValidSession } from "@/utils/session"
|
||||
|
||||
import type {
|
||||
ContentTypeParams,
|
||||
LangParams,
|
||||
PageArgs,
|
||||
UIDParams,
|
||||
} from "@/types/params"
|
||||
import { PageContentTypeEnum } from "@/types/requests/contentType"
|
||||
|
||||
export { generateMetadata } from "@/utils/generateMetadata"
|
||||
|
||||
export default async function ContentTypePage({
|
||||
params,
|
||||
searchParams,
|
||||
}: PageArgs<
|
||||
LangParams & ContentTypeParams & UIDParams,
|
||||
{ subpage?: string; filterFromUrl?: string }
|
||||
>) {
|
||||
const pathname = headers().get("x-pathname") || ""
|
||||
|
||||
switch (params.contentType) {
|
||||
case PageContentTypeEnum.collectionPage:
|
||||
return <CollectionPage />
|
||||
case PageContentTypeEnum.contentPage: {
|
||||
const isSignupRoute = isSignupPage(pathname)
|
||||
|
||||
if (isSignupRoute) {
|
||||
if (!env.SHOW_SIGNUP_FLOW) {
|
||||
return notFound()
|
||||
}
|
||||
|
||||
const session = await auth()
|
||||
if (isValidSession(session)) {
|
||||
redirect(overview[getLang()])
|
||||
}
|
||||
}
|
||||
|
||||
return <ContentPage />
|
||||
}
|
||||
case PageContentTypeEnum.loyaltyPage:
|
||||
return <LoyaltyPage />
|
||||
case PageContentTypeEnum.destinationOverviewPage:
|
||||
return <DestinationOverviewPage />
|
||||
case PageContentTypeEnum.destinationCountryPage:
|
||||
return <DestinationCountryPage />
|
||||
case PageContentTypeEnum.destinationCityPage:
|
||||
const filterFromUrl = searchParams.filterFromUrl
|
||||
return <DestinationCityPage filterFromUrl={filterFromUrl} />
|
||||
case PageContentTypeEnum.hotelPage:
|
||||
if (env.HIDE_FOR_NEXT_RELEASE) {
|
||||
return notFound()
|
||||
}
|
||||
const hotelPageData = await getHotelPage()
|
||||
|
||||
if (hotelPageData) {
|
||||
if (searchParams.subpage) {
|
||||
return (
|
||||
<HotelSubpage
|
||||
hotelId={hotelPageData.hotel_page_id}
|
||||
subpage={searchParams.subpage}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return <HotelPage hotelId={hotelPageData.hotel_page_id} />
|
||||
}
|
||||
|
||||
notFound()
|
||||
case PageContentTypeEnum.startPage:
|
||||
if (env.HIDE_FOR_NEXT_RELEASE) {
|
||||
return notFound()
|
||||
}
|
||||
return <StartPage />
|
||||
default:
|
||||
const type: never = params.contentType
|
||||
console.error(`Unsupported content type given: ${type}`)
|
||||
notFound()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { getBookingConfirmation } from "@/lib/trpc/memoizedRequests"
|
||||
|
||||
import BookingConfirmation from "@/components/HotelReservation/BookingConfirmation"
|
||||
|
||||
import type { LangParams, PageArgs } from "@/types/params"
|
||||
|
||||
export default async function BookingConfirmationPage({
|
||||
searchParams,
|
||||
}: PageArgs<LangParams, { confirmationNumber: string }>) {
|
||||
void getBookingConfirmation(searchParams.confirmationNumber)
|
||||
return (
|
||||
<BookingConfirmation confirmationNumber={searchParams.confirmationNumber} />
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
.layout {
|
||||
background-color: var(--Base-Background-Primary-Normal);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import styles from "./layout.module.css"
|
||||
|
||||
import type { LangParams, LayoutArgs } from "@/types/params"
|
||||
|
||||
export default function PaymentCallbackLayout({
|
||||
children,
|
||||
}: React.PropsWithChildren<LayoutArgs<LangParams>>) {
|
||||
return <div className={styles.layout}>{children}</div>
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { redirect } from "next/navigation"
|
||||
|
||||
import {
|
||||
BOOKING_CONFIRMATION_NUMBER,
|
||||
MEMBERSHIP_FAILED_ERROR,
|
||||
PaymentErrorCodeEnum,
|
||||
} from "@/constants/booking"
|
||||
import {
|
||||
bookingConfirmation,
|
||||
details,
|
||||
} from "@/constants/routes/hotelReservation"
|
||||
import { serverClient } from "@/lib/trpc/server"
|
||||
|
||||
import PaymentCallback from "@/components/HotelReservation/EnterDetails/Payment/PaymentCallback"
|
||||
|
||||
import type { LangParams, PageArgs } from "@/types/params"
|
||||
|
||||
export default async function PaymentCallbackPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: PageArgs<
|
||||
LangParams,
|
||||
{
|
||||
status: "error" | "success" | "cancel"
|
||||
confirmationNumber?: string
|
||||
hotel?: string
|
||||
}
|
||||
>) {
|
||||
console.log(`[payment-callback] callback started`)
|
||||
const lang = params.lang
|
||||
const status = searchParams.status
|
||||
const confirmationNumber = searchParams.confirmationNumber
|
||||
|
||||
if (status === "success" && confirmationNumber) {
|
||||
const bookingStatus = await serverClient().booking.status({
|
||||
confirmationNumber,
|
||||
})
|
||||
const membershipFailedError = bookingStatus.errors.find(
|
||||
(e) => e.errorCode === MEMBERSHIP_FAILED_ERROR
|
||||
)
|
||||
|
||||
const errorParam = membershipFailedError
|
||||
? `&errorCode=${membershipFailedError.errorCode}`
|
||||
: ""
|
||||
const confirmationUrl = `${bookingConfirmation(lang)}?${BOOKING_CONFIRMATION_NUMBER}=${confirmationNumber}${errorParam}`
|
||||
|
||||
console.log(`[payment-callback] redirecting to: ${confirmationUrl}`)
|
||||
redirect(confirmationUrl)
|
||||
}
|
||||
|
||||
const returnUrl = details(lang)
|
||||
const searchObject = new URLSearchParams()
|
||||
|
||||
let errorMessage = undefined
|
||||
|
||||
if (confirmationNumber) {
|
||||
try {
|
||||
const bookingStatus = await serverClient().booking.status({
|
||||
confirmationNumber,
|
||||
})
|
||||
|
||||
// TODO: how to handle errors for multiple rooms?
|
||||
const error = bookingStatus.errors.find((e) => e.errorCode)
|
||||
|
||||
errorMessage =
|
||||
error?.description ??
|
||||
`No error message found for booking ${confirmationNumber}, status: ${status}`
|
||||
|
||||
searchObject.set(
|
||||
"errorCode",
|
||||
error
|
||||
? error.errorCode.toString()
|
||||
: PaymentErrorCodeEnum.Failed.toString()
|
||||
)
|
||||
} catch {
|
||||
console.error(
|
||||
`[payment-callback] failed to get booking status for ${confirmationNumber}, status: ${status}`
|
||||
)
|
||||
if (status === "cancel") {
|
||||
searchObject.set("errorCode", PaymentErrorCodeEnum.Cancelled.toString())
|
||||
}
|
||||
if (status === "error") {
|
||||
searchObject.set("errorCode", PaymentErrorCodeEnum.Failed.toString())
|
||||
errorMessage = `Failed to get booking status for ${confirmationNumber}, status: ${status}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PaymentCallback
|
||||
returnUrl={returnUrl.toString()}
|
||||
searchObject={searchObject}
|
||||
status={status}
|
||||
errorMessage={errorMessage}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
.layout {
|
||||
min-height: 100dvh;
|
||||
background-color: var(--Base-Background-Primary-Normal);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 768px) {
|
||||
.layout {
|
||||
z-index: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import styles from "./layout.module.css"
|
||||
|
||||
export default function HotelReservationLayout({
|
||||
children,
|
||||
}: React.PropsWithChildren) {
|
||||
return <div className={styles.layout}>{children}</div>
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
.main {
|
||||
display: grid;
|
||||
background-color: var(--Scandic-Brand-Warm-White);
|
||||
min-height: 100dvh;
|
||||
position: relative;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Suspense } from "react"
|
||||
|
||||
import { SelectHotelMapContainer } from "@/components/HotelReservation/SelectHotel/SelectHotelMap/SelectHotelMapContainer"
|
||||
import { SelectHotelMapContainerSkeleton } from "@/components/HotelReservation/SelectHotel/SelectHotelMap/SelectHotelMapContainerSkeleton"
|
||||
import { MapContainer } from "@/components/MapContainer"
|
||||
|
||||
import styles from "./page.module.css"
|
||||
|
||||
import type { AlternativeHotelsSearchParams } from "@/types/components/hotelReservation/selectHotel/selectHotelSearchParams"
|
||||
import type { LangParams, PageArgs } from "@/types/params"
|
||||
|
||||
export default async function SelectHotelMapPage({
|
||||
searchParams,
|
||||
}: PageArgs<LangParams, AlternativeHotelsSearchParams>) {
|
||||
return (
|
||||
<div className={styles.main}>
|
||||
<MapContainer>
|
||||
<Suspense
|
||||
key={searchParams.hotel}
|
||||
fallback={<SelectHotelMapContainerSkeleton />}
|
||||
>
|
||||
<SelectHotelMapContainer
|
||||
searchParams={searchParams}
|
||||
isAlternativeHotels
|
||||
/>
|
||||
</Suspense>
|
||||
</MapContainer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Suspense } from "react"
|
||||
|
||||
import SelectHotel from "@/components/HotelReservation/SelectHotel"
|
||||
import { SelectHotelSkeleton } from "@/components/HotelReservation/SelectHotel/SelectHotelSkeleton"
|
||||
|
||||
import type { AlternativeHotelsSearchParams } from "@/types/components/hotelReservation/selectHotel/selectHotelSearchParams"
|
||||
import type { LangParams, PageArgs } from "@/types/params"
|
||||
|
||||
export default async function AlternativeHotelsPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: PageArgs<LangParams, AlternativeHotelsSearchParams>) {
|
||||
const roomKey = Object.keys(searchParams)
|
||||
.filter((key) => key.startsWith("room["))
|
||||
.map((key) => searchParams[key])
|
||||
.join("-")
|
||||
|
||||
return (
|
||||
<Suspense
|
||||
key={`${searchParams.hotel}-${searchParams.fromDate}-${searchParams.toDate}-${roomKey}`}
|
||||
fallback={<SelectHotelSkeleton />}
|
||||
>
|
||||
<SelectHotel
|
||||
params={params}
|
||||
searchParams={searchParams}
|
||||
isAlternativeHotels
|
||||
/>
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
.container {
|
||||
display: grid;
|
||||
gap: var(--Spacing-x3) var(--Spacing-x9);
|
||||
}
|
||||
|
||||
.content {
|
||||
width: var(--max-width-page);
|
||||
margin: var(--Spacing-x3) auto 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--Spacing-x4);
|
||||
}
|
||||
|
||||
.header {
|
||||
padding-bottom: var(--Spacing-x3);
|
||||
}
|
||||
|
||||
.summary {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 1367px) {
|
||||
.container {
|
||||
grid-template-columns: 1fr 340px;
|
||||
grid-template-rows: auto 1fr;
|
||||
width: var(--max-width-page);
|
||||
margin: var(--Spacing-x5) auto 0;
|
||||
}
|
||||
|
||||
.content {
|
||||
width: 100%;
|
||||
margin: var(--Spacing-x3) 0 0;
|
||||
}
|
||||
|
||||
.summary {
|
||||
position: static;
|
||||
display: grid;
|
||||
grid-column: 2/3;
|
||||
grid-row: 1/-1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { notFound } from "next/navigation"
|
||||
import { Suspense } from "react"
|
||||
|
||||
import {
|
||||
getBreakfastPackages,
|
||||
getHotel,
|
||||
getPackages,
|
||||
getProfileSafely,
|
||||
getSelectedRoomAvailability,
|
||||
} from "@/lib/trpc/memoizedRequests"
|
||||
|
||||
import BedType from "@/components/HotelReservation/EnterDetails/BedType"
|
||||
import Breakfast from "@/components/HotelReservation/EnterDetails/Breakfast"
|
||||
import Details from "@/components/HotelReservation/EnterDetails/Details"
|
||||
import HotelHeader from "@/components/HotelReservation/EnterDetails/Header"
|
||||
import Payment from "@/components/HotelReservation/EnterDetails/Payment"
|
||||
import SectionAccordion from "@/components/HotelReservation/EnterDetails/SectionAccordion"
|
||||
import SelectedRoom from "@/components/HotelReservation/EnterDetails/SelectedRoom"
|
||||
import DesktopSummary from "@/components/HotelReservation/EnterDetails/Summary/Desktop"
|
||||
import MobileSummary from "@/components/HotelReservation/EnterDetails/Summary/Mobile"
|
||||
import { generateChildrenString } from "@/components/HotelReservation/utils"
|
||||
import Title from "@/components/TempDesignSystem/Text/Title"
|
||||
import { getIntl } from "@/i18n"
|
||||
import EnterDetailsProvider from "@/providers/EnterDetailsProvider"
|
||||
import { convertSearchParamsToObj } from "@/utils/url"
|
||||
|
||||
import styles from "./page.module.css"
|
||||
|
||||
import type { BedTypeSelection } from "@/types/components/hotelReservation/enterDetails/bedType"
|
||||
import type { RoomRate } from "@/types/components/hotelReservation/enterDetails/details"
|
||||
import { type SelectRateSearchParams } from "@/types/components/hotelReservation/selectRate/selectRate"
|
||||
import { StepEnum } from "@/types/enums/step"
|
||||
import type { LangParams, PageArgs } from "@/types/params"
|
||||
import type { Packages } from "@/types/requests/packages"
|
||||
|
||||
export interface RoomData {
|
||||
bedTypes?: BedTypeSelection[]
|
||||
mustBeGuaranteed?: boolean
|
||||
breakfastIncluded?: boolean
|
||||
packages: Packages | null
|
||||
cancellationText: string
|
||||
rateDetails: string[]
|
||||
roomType: string
|
||||
roomRate: RoomRate
|
||||
}
|
||||
|
||||
export default async function DetailsPage({
|
||||
params: { lang },
|
||||
searchParams,
|
||||
}: PageArgs<LangParams, SelectRateSearchParams>) {
|
||||
const intl = await getIntl()
|
||||
const selectRoomParams = new URLSearchParams(searchParams)
|
||||
const booking = convertSearchParamsToObj<SelectRateSearchParams>(searchParams)
|
||||
|
||||
void getProfileSafely()
|
||||
|
||||
const breakfastInput = {
|
||||
adults: 1,
|
||||
fromDate: booking.fromDate,
|
||||
hotelId: booking.hotelId,
|
||||
toDate: booking.toDate,
|
||||
}
|
||||
const breakfastPackages = await getBreakfastPackages(breakfastInput)
|
||||
const roomsData: RoomData[] = []
|
||||
|
||||
for (let room of booking.rooms) {
|
||||
const childrenAsString =
|
||||
room.childrenInRoom && generateChildrenString(room.childrenInRoom)
|
||||
|
||||
const selectedRoomAvailabilityInput = {
|
||||
adults: room.adults,
|
||||
children: childrenAsString,
|
||||
hotelId: booking.hotelId,
|
||||
packageCodes: room.packages,
|
||||
rateCode: room.rateCode,
|
||||
roomStayStartDate: booking.fromDate,
|
||||
roomStayEndDate: booking.toDate,
|
||||
roomTypeCode: room.roomTypeCode,
|
||||
}
|
||||
|
||||
const packages = room.packages
|
||||
? await getPackages({
|
||||
adults: room.adults,
|
||||
children: room.childrenInRoom?.length,
|
||||
endDate: booking.toDate,
|
||||
hotelId: booking.hotelId,
|
||||
packageCodes: room.packages,
|
||||
startDate: booking.fromDate,
|
||||
lang,
|
||||
})
|
||||
: null
|
||||
|
||||
const roomAvailability = await getSelectedRoomAvailability(
|
||||
selectedRoomAvailabilityInput //
|
||||
)
|
||||
|
||||
if (!roomAvailability) {
|
||||
continue // TODO: handle no room availability
|
||||
}
|
||||
|
||||
roomsData.push({
|
||||
bedTypes: roomAvailability.bedTypes,
|
||||
packages,
|
||||
mustBeGuaranteed: roomAvailability.mustBeGuaranteed,
|
||||
breakfastIncluded: roomAvailability.breakfastIncluded,
|
||||
cancellationText: roomAvailability.cancellationText,
|
||||
rateDetails: roomAvailability.rateDetails ?? [],
|
||||
roomType: roomAvailability.selectedRoom.roomType,
|
||||
roomRate: {
|
||||
memberRate: roomAvailability?.memberRate,
|
||||
publicRate: roomAvailability.publicRate,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const isCardOnlyPayment = roomsData.some((room) => room?.mustBeGuaranteed)
|
||||
const hotelData = await getHotel({
|
||||
hotelId: booking.hotelId,
|
||||
isCardOnlyPayment,
|
||||
language: lang,
|
||||
})
|
||||
const user = await getProfileSafely()
|
||||
// const userTrackingData = await getUserTracking()
|
||||
|
||||
if (!hotelData || !roomsData) {
|
||||
return notFound()
|
||||
}
|
||||
|
||||
// const arrivalDate = new Date(booking.fromDate)
|
||||
// const departureDate = new Date(booking.toDate)
|
||||
const hotelAttributes = hotelData.hotel
|
||||
|
||||
// TODO: add tracking
|
||||
// const initialHotelsTrackingData: TrackingSDKHotelInfo = {
|
||||
// searchTerm: searchParams.city,
|
||||
// arrivalDate: format(arrivalDate, "yyyy-MM-dd"),
|
||||
// departureDate: format(departureDate, "yyyy-MM-dd"),
|
||||
// noOfAdults: adults,
|
||||
// noOfChildren: childrenInRoom?.length,
|
||||
// ageOfChildren: childrenInRoom?.map((c) => c.age).join(","),
|
||||
// childBedPreference: childrenInRoom
|
||||
// ?.map((c) => ChildBedMapEnum[c.bed])
|
||||
// .join("|"),
|
||||
// noOfRooms: 1, // // TODO: Handle multiple rooms
|
||||
// duration: differenceInCalendarDays(departureDate, arrivalDate),
|
||||
// leadTime: differenceInCalendarDays(arrivalDate, new Date()),
|
||||
// searchType: "hotel",
|
||||
// bookingTypeofDay: isWeekend(arrivalDate) ? "weekend" : "weekday",
|
||||
// country: hotelAttributes?.address.country,
|
||||
// hotelID: hotelAttributes?.operaId,
|
||||
// region: hotelAttributes?.address.city,
|
||||
// }
|
||||
|
||||
const showBreakfastStep = Boolean(
|
||||
breakfastPackages?.length && !roomsData[0]?.breakfastIncluded
|
||||
)
|
||||
|
||||
return (
|
||||
<EnterDetailsProvider
|
||||
booking={booking}
|
||||
showBreakfastStep={showBreakfastStep}
|
||||
roomsData={roomsData}
|
||||
searchParamsStr={selectRoomParams.toString()}
|
||||
user={user}
|
||||
vat={hotelAttributes.vat}
|
||||
>
|
||||
<main>
|
||||
<HotelHeader hotelData={hotelData} />
|
||||
<div className={styles.container}>
|
||||
<div className={styles.content}>
|
||||
{roomsData.map((room, idx) => (
|
||||
<section key={idx}>
|
||||
{roomsData.length > 1 && (
|
||||
<header className={styles.header}>
|
||||
<Title level="h2" as="h4">
|
||||
{intl.formatMessage({ id: "Room" })} {idx + 1}
|
||||
</Title>
|
||||
</header>
|
||||
)}
|
||||
<SelectedRoom
|
||||
hotelId={booking.hotelId}
|
||||
roomType={room.roomType}
|
||||
roomTypeCode={booking.rooms[idx].roomTypeCode}
|
||||
rateDescription={room.cancellationText}
|
||||
roomIndex={idx}
|
||||
searchParamsStr={selectRoomParams.toString()}
|
||||
/>
|
||||
|
||||
{room.bedTypes ? (
|
||||
<SectionAccordion
|
||||
header={intl.formatMessage({ id: "Select bed" })}
|
||||
label={intl.formatMessage({ id: "Request bedtype" })}
|
||||
step={StepEnum.selectBed}
|
||||
roomIndex={idx}
|
||||
>
|
||||
<BedType bedTypes={room.bedTypes} roomIndex={idx} />
|
||||
</SectionAccordion>
|
||||
) : null}
|
||||
|
||||
{showBreakfastStep ? (
|
||||
<SectionAccordion
|
||||
header={intl.formatMessage({ id: "Food options" })}
|
||||
label={intl.formatMessage({
|
||||
id: "Select breakfast options",
|
||||
})}
|
||||
step={StepEnum.breakfast}
|
||||
roomIndex={idx}
|
||||
>
|
||||
<Breakfast packages={breakfastPackages!} roomIndex={idx} />
|
||||
</SectionAccordion>
|
||||
) : null}
|
||||
|
||||
<SectionAccordion
|
||||
header={intl.formatMessage({ id: "Details" })}
|
||||
step={StepEnum.details}
|
||||
label={intl.formatMessage({ id: "Enter your details" })}
|
||||
roomIndex={idx}
|
||||
>
|
||||
<Details
|
||||
user={idx === 0 ? user : null}
|
||||
memberPrice={{
|
||||
currency:
|
||||
room?.roomRate.memberRate?.localPrice.currency ?? "", // TODO: how to handle undefined,
|
||||
price:
|
||||
room?.roomRate.memberRate?.localPrice.pricePerNight ??
|
||||
0, // TODO: how to handle undefined,
|
||||
}}
|
||||
roomIndex={idx}
|
||||
/>
|
||||
</SectionAccordion>
|
||||
</section>
|
||||
))}
|
||||
<Suspense>
|
||||
<Payment
|
||||
user={user}
|
||||
otherPaymentOptions={
|
||||
hotelAttributes.merchantInformationData
|
||||
.alternatePaymentOptions
|
||||
}
|
||||
supportedCards={hotelAttributes.merchantInformationData.cards}
|
||||
mustBeGuaranteed={isCardOnlyPayment}
|
||||
/>
|
||||
</Suspense>
|
||||
</div>
|
||||
<aside className={styles.summary}>
|
||||
<MobileSummary
|
||||
isMember={!!user}
|
||||
breakfastIncluded={roomsData[0]?.breakfastIncluded ?? false}
|
||||
/>
|
||||
<DesktopSummary
|
||||
isMember={!!user}
|
||||
breakfastIncluded={roomsData[0]?.breakfastIncluded ?? false}
|
||||
/>
|
||||
</aside>
|
||||
</div>
|
||||
</main>
|
||||
</EnterDetailsProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
.layout {
|
||||
background-color: var(--Base-Background-Primary-Normal);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import SidePeek from "@/components/HotelReservation/SidePeek"
|
||||
|
||||
import styles from "./layout.module.css"
|
||||
|
||||
import type { LangParams, LayoutArgs } from "@/types/params"
|
||||
|
||||
export default function HotelReservationLayout({
|
||||
children,
|
||||
}: React.PropsWithChildren<LayoutArgs<LangParams>>) {
|
||||
return (
|
||||
<div className={styles.layout}>
|
||||
{children}
|
||||
<SidePeek />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import LoadingSpinner from "@/components/LoadingSpinner"
|
||||
|
||||
export default function Loading() {
|
||||
return <LoadingSpinner fullPage />
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
.page {
|
||||
background-color: var(--Base-Background-Primary-Normal);
|
||||
min-height: 50dvh;
|
||||
max-width: var(--max-width-page);
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Suspense } from "react"
|
||||
|
||||
import { env } from "@/env/server"
|
||||
|
||||
import TrackingSDK from "@/components/TrackingSDK"
|
||||
|
||||
import styles from "./page.module.css"
|
||||
|
||||
import {
|
||||
TrackingChannelEnum,
|
||||
type TrackingSDKPageData,
|
||||
} from "@/types/components/tracking"
|
||||
import type { LangParams, PageArgs } from "@/types/params"
|
||||
|
||||
export default function HotelReservationPage({ params }: PageArgs<LangParams>) {
|
||||
if (!env.ENABLE_BOOKING_WIDGET_HOTELRESERVATION_PATH) {
|
||||
return null
|
||||
}
|
||||
|
||||
const pageTrackingData: TrackingSDKPageData = {
|
||||
pageId: "hotelreservation",
|
||||
domainLanguage: params.lang,
|
||||
channel: TrackingChannelEnum["hotelreservation"],
|
||||
pageName: "hotelreservation",
|
||||
siteSections: "hotelreservation",
|
||||
pageType: "hotelreservationstartpage",
|
||||
siteVersion: "new-web",
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
New booking flow! Please report errors/issues in Slack.
|
||||
<Suspense fallback={null}>
|
||||
<TrackingSDK pageData={pageTrackingData} />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
.layout {
|
||||
min-height: 100dvh;
|
||||
background-color: var(--Base-Background-Primary-Normal);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 768px) {
|
||||
.layout {
|
||||
z-index: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import styles from "./layout.module.css"
|
||||
|
||||
import type { LangParams, LayoutArgs } from "@/types/params"
|
||||
|
||||
export default function HotelReservationLayout({
|
||||
children,
|
||||
}: React.PropsWithChildren<LayoutArgs<LangParams>>) {
|
||||
return <div className={styles.layout}>{children}</div>
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
.main {
|
||||
display: grid;
|
||||
background-color: var(--Scandic-Brand-Warm-White);
|
||||
min-height: 100dvh;
|
||||
position: relative;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import stringify from "json-stable-stringify-without-jsonify"
|
||||
import { Suspense } from "react"
|
||||
|
||||
import { SelectHotelMapContainer } from "@/components/HotelReservation/SelectHotel/SelectHotelMap/SelectHotelMapContainer"
|
||||
import { SelectHotelMapContainerSkeleton } from "@/components/HotelReservation/SelectHotel/SelectHotelMap/SelectHotelMapContainerSkeleton"
|
||||
import { MapContainer } from "@/components/MapContainer"
|
||||
|
||||
import styles from "./page.module.css"
|
||||
|
||||
import type { SelectHotelSearchParams } from "@/types/components/hotelReservation/selectHotel/selectHotelSearchParams"
|
||||
import type { LangParams, PageArgs } from "@/types/params"
|
||||
|
||||
export default async function SelectHotelMapPage({
|
||||
searchParams,
|
||||
}: PageArgs<LangParams, SelectHotelSearchParams>) {
|
||||
const suspenseKey = stringify(searchParams)
|
||||
|
||||
return (
|
||||
<div className={styles.main}>
|
||||
<MapContainer>
|
||||
<Suspense
|
||||
key={suspenseKey}
|
||||
fallback={<SelectHotelMapContainerSkeleton />}
|
||||
>
|
||||
<SelectHotelMapContainer searchParams={searchParams} />
|
||||
</Suspense>
|
||||
</MapContainer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import stringify from "json-stable-stringify-without-jsonify"
|
||||
import { Suspense } from "react"
|
||||
|
||||
import SelectHotel from "@/components/HotelReservation/SelectHotel"
|
||||
import { SelectHotelSkeleton } from "@/components/HotelReservation/SelectHotel/SelectHotelSkeleton"
|
||||
|
||||
import type { SelectHotelSearchParams } from "@/types/components/hotelReservation/selectHotel/selectHotelSearchParams"
|
||||
import type { LangParams, PageArgs } from "@/types/params"
|
||||
|
||||
export default async function SelectHotelPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: PageArgs<LangParams, SelectHotelSearchParams>) {
|
||||
const suspenseKey = stringify(searchParams)
|
||||
|
||||
return (
|
||||
<Suspense key={suspenseKey} fallback={<SelectHotelSkeleton />}>
|
||||
<SelectHotel params={params} searchParams={searchParams} />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { getHotel } from "@/lib/trpc/memoizedRequests"
|
||||
import { serverClient } from "@/lib/trpc/server"
|
||||
|
||||
import { getLang } from "@/i18n/serverContext"
|
||||
|
||||
import type {
|
||||
AlternativeHotelsAvailabilityInput,
|
||||
AvailabilityInput,
|
||||
} from "@/types/components/hotelReservation/selectHotel/availabilityInput"
|
||||
import type {
|
||||
HotelData,
|
||||
NullableHotelData,
|
||||
} from "@/types/components/hotelReservation/selectHotel/hotelCardListingProps"
|
||||
import type { CategorizedFilters } from "@/types/components/hotelReservation/selectHotel/hotelFilters"
|
||||
import type { DetailedFacility } from "@/types/hotel"
|
||||
import type { HotelsAvailabilityItem } from "@/types/trpc/routers/hotel/availability"
|
||||
|
||||
const hotelSurroundingsFilterNames = [
|
||||
"Hotel surroundings",
|
||||
"Hotel omgivelser",
|
||||
"Hotelumgebung",
|
||||
"Hotellia lähellä",
|
||||
"Hotellomgivelser",
|
||||
"Omgivningar",
|
||||
]
|
||||
|
||||
const hotelFacilitiesFilterNames = [
|
||||
"Hotel facilities",
|
||||
"Hotellfaciliteter",
|
||||
"Hotelfaciliteter",
|
||||
"Hotel faciliteter",
|
||||
"Hotel-Infos",
|
||||
"Hotellin palvelut",
|
||||
]
|
||||
|
||||
export async function fetchAvailableHotels(
|
||||
input: AvailabilityInput
|
||||
): Promise<NullableHotelData[]> {
|
||||
const availableHotels =
|
||||
await serverClient().hotel.availability.hotelsByCity(input)
|
||||
|
||||
if (!availableHotels) return []
|
||||
|
||||
return enhanceHotels(availableHotels)
|
||||
}
|
||||
|
||||
export async function fetchBookingCodeAvailableHotels(
|
||||
input: AvailabilityInput
|
||||
): Promise<NullableHotelData[]> {
|
||||
const availableHotels =
|
||||
await serverClient().hotel.availability.hotelsByCityWithBookingCode(input)
|
||||
|
||||
if (!availableHotels) return []
|
||||
|
||||
return enhanceHotels(availableHotels)
|
||||
}
|
||||
|
||||
export async function fetchAlternativeHotels(
|
||||
hotelId: string,
|
||||
input: AlternativeHotelsAvailabilityInput
|
||||
): Promise<NullableHotelData[]> {
|
||||
const alternativeHotelIds = await serverClient().hotel.nearbyHotelIds({
|
||||
hotelId,
|
||||
})
|
||||
|
||||
if (!alternativeHotelIds) return []
|
||||
|
||||
const availableHotels =
|
||||
await serverClient().hotel.availability.hotelsByHotelIds({
|
||||
...input,
|
||||
hotelIds: alternativeHotelIds,
|
||||
})
|
||||
|
||||
if (!availableHotels) return []
|
||||
|
||||
return enhanceHotels(availableHotels)
|
||||
}
|
||||
|
||||
async function enhanceHotels(hotels: {
|
||||
availability: HotelsAvailabilityItem[]
|
||||
}) {
|
||||
const language = getLang()
|
||||
|
||||
const hotelFetchers = hotels.availability.map(async (hotel) => {
|
||||
const hotelData = await getHotel({
|
||||
hotelId: hotel.hotelId.toString(),
|
||||
isCardOnlyPayment: false,
|
||||
language,
|
||||
})
|
||||
|
||||
if (!hotelData) return { hotelData: null, price: hotel.productType }
|
||||
|
||||
return {
|
||||
hotelData: hotelData.hotel,
|
||||
price: hotel.productType,
|
||||
}
|
||||
})
|
||||
|
||||
return await Promise.all(hotelFetchers)
|
||||
}
|
||||
|
||||
export function getFiltersFromHotels(hotels: HotelData[]): CategorizedFilters {
|
||||
if (hotels.length === 0)
|
||||
return { facilityFilters: [], surroundingsFilters: [] }
|
||||
|
||||
const filters = hotels.flatMap((hotel) => {
|
||||
if (!hotel.hotelData) return []
|
||||
return hotel.hotelData.detailedFacilities
|
||||
})
|
||||
|
||||
const uniqueFilterIds = [...new Set(filters.map((filter) => filter.id))]
|
||||
const filterList: DetailedFacility[] = uniqueFilterIds
|
||||
.map((filterId) => filters.find((filter) => filter.id === filterId))
|
||||
.filter((filter): filter is DetailedFacility => filter !== undefined)
|
||||
.sort((a, b) => b.sortOrder - a.sortOrder)
|
||||
|
||||
return filterList.reduce<CategorizedFilters>(
|
||||
(acc, filter) => {
|
||||
if (filter.filter && hotelSurroundingsFilterNames.includes(filter.filter))
|
||||
return {
|
||||
facilityFilters: acc.facilityFilters,
|
||||
surroundingsFilters: [...acc.surroundingsFilters, filter],
|
||||
}
|
||||
|
||||
if (filter.filter && hotelFacilitiesFilterNames.includes(filter.filter))
|
||||
return {
|
||||
facilityFilters: [...acc.facilityFilters, filter],
|
||||
surroundingsFilters: acc.surroundingsFilters,
|
||||
}
|
||||
|
||||
return acc
|
||||
},
|
||||
{ facilityFilters: [], surroundingsFilters: [] }
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { beforeAll, describe, expect, it } from "@jest/globals"
|
||||
|
||||
import { getValidFromDate, getValidToDate } from "./getValidDates"
|
||||
|
||||
const NOW = new Date("2020-10-01T00:00:00Z")
|
||||
|
||||
describe("getValidFromDate", () => {
|
||||
beforeAll(() => {
|
||||
jest.useFakeTimers({ now: NOW })
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
describe("getValidFromDate", () => {
|
||||
it("returns today when empty string is provided", () => {
|
||||
const actual = getValidFromDate("")
|
||||
expect(actual.toISOString()).toBe("2020-10-01T00:00:00.000Z")
|
||||
})
|
||||
|
||||
it("returns today when undefined is provided", () => {
|
||||
const actual = getValidFromDate(undefined)
|
||||
expect(actual.toISOString()).toBe("2020-10-01T00:00:00.000Z")
|
||||
})
|
||||
|
||||
it("returns given date in utc", () => {
|
||||
const actual = getValidFromDate("2024-01-01")
|
||||
expect(actual.toISOString()).toBe("2024-01-01T00:00:00.000Z")
|
||||
})
|
||||
})
|
||||
|
||||
describe("getValidToDate", () => {
|
||||
it("returns day after fromDate when empty string is provided", () => {
|
||||
const actual = getValidToDate("", NOW)
|
||||
expect(actual.toISOString()).toBe("2020-10-02T00:00:00.000Z")
|
||||
})
|
||||
|
||||
it("returns day after fromDate when undefined is provided", () => {
|
||||
const actual = getValidToDate(undefined, NOW)
|
||||
expect(actual.toISOString()).toBe("2020-10-02T00:00:00.000Z")
|
||||
})
|
||||
|
||||
it("returns given date in utc", () => {
|
||||
const actual = getValidToDate("2024-01-01", NOW)
|
||||
expect(actual.toISOString()).toBe("2024-01-01T00:00:00.000Z")
|
||||
})
|
||||
|
||||
it("fallsback to day after fromDate when given date is before fromDate", () => {
|
||||
const actual = getValidToDate("2020-09-30", NOW)
|
||||
expect(actual.toISOString()).toBe("2020-10-02T00:00:00.000Z")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { dt } from "@/lib/dt"
|
||||
|
||||
import type { Dayjs } from "dayjs"
|
||||
|
||||
/**
|
||||
* Get valid dates from stringFromDate and stringToDate making sure that they are not in the past and chronologically correct
|
||||
* @example const { fromDate, toDate} = getValidDates("2021-01-01", "2021-01-02")
|
||||
*/
|
||||
export function getValidDates(
|
||||
stringFromDate: string | undefined,
|
||||
stringToDate: string | undefined
|
||||
): { fromDate: Dayjs; toDate: Dayjs } {
|
||||
const fromDate = getValidFromDate(stringFromDate)
|
||||
const toDate = getValidToDate(stringToDate, fromDate)
|
||||
|
||||
return { fromDate, toDate }
|
||||
}
|
||||
|
||||
/**
|
||||
* Get valid fromDate from stringFromDate making sure that it is not in the past
|
||||
*/
|
||||
export function getValidFromDate(stringFromDate: string | undefined): Dayjs {
|
||||
const now = dt().utc()
|
||||
if (!stringFromDate) {
|
||||
return now
|
||||
}
|
||||
const toDate = dt(stringFromDate)
|
||||
|
||||
const yesterday = now.subtract(1, "day")
|
||||
if (!toDate.isAfter(yesterday)) {
|
||||
return now
|
||||
}
|
||||
|
||||
return toDate
|
||||
}
|
||||
|
||||
/**
|
||||
* Get valid toDate from stringToDate making sure that it is after fromDate
|
||||
*/
|
||||
export function getValidToDate(
|
||||
stringToDate: string | undefined,
|
||||
fromDate: Dayjs | Date
|
||||
): Dayjs {
|
||||
const tomorrow = dt().utc().add(1, "day")
|
||||
if (!stringToDate) {
|
||||
return tomorrow
|
||||
}
|
||||
|
||||
const toDate = dt(stringToDate)
|
||||
if (toDate.isAfter(fromDate)) {
|
||||
return toDate
|
||||
}
|
||||
|
||||
return tomorrow
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import stringify from "json-stable-stringify-without-jsonify"
|
||||
import { Suspense } from "react"
|
||||
|
||||
import SelectRate from "@/components/HotelReservation/SelectRate"
|
||||
import { HotelInfoCardSkeleton } from "@/components/HotelReservation/SelectRate/HotelInfoCard"
|
||||
import { RoomsContainerSkeleton } from "@/components/HotelReservation/SelectRate/RoomsContainer/RoomsContainerSkeleton"
|
||||
|
||||
import type { SelectRateSearchParams } from "@/types/components/hotelReservation/selectRate/selectRate"
|
||||
import type { LangParams, PageArgs } from "@/types/params"
|
||||
|
||||
export default async function SelectRatePage({
|
||||
params,
|
||||
searchParams,
|
||||
}: PageArgs<LangParams & { section: string }, SelectRateSearchParams>) {
|
||||
const suspenseKey = stringify(searchParams)
|
||||
|
||||
return (
|
||||
<Suspense
|
||||
key={suspenseKey}
|
||||
fallback={
|
||||
<>
|
||||
<HotelInfoCardSkeleton />
|
||||
<RoomsContainerSkeleton />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<SelectRate params={params} searchParams={searchParams} />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { notFound } from "next/navigation"
|
||||
|
||||
import { getLocations } from "@/lib/trpc/memoizedRequests"
|
||||
|
||||
import { generateChildrenString } from "@/components/HotelReservation/utils"
|
||||
import { convertSearchParamsToObj, type SelectHotelParams } from "@/utils/url"
|
||||
|
||||
import type {
|
||||
AlternativeHotelsSearchParams,
|
||||
SelectHotelSearchParams,
|
||||
} from "@/types/components/hotelReservation/selectHotel/selectHotelSearchParams"
|
||||
import type {
|
||||
Child,
|
||||
SelectRateSearchParams,
|
||||
} from "@/types/components/hotelReservation/selectRate/selectRate"
|
||||
import {
|
||||
type HotelLocation,
|
||||
isHotelLocation,
|
||||
type Location,
|
||||
} from "@/types/trpc/routers/hotel/locations"
|
||||
|
||||
interface HotelSearchDetails<T> {
|
||||
city: Location | null
|
||||
hotel: HotelLocation | null
|
||||
selectHotelParams: SelectHotelParams<T> & { city: string | undefined }
|
||||
adultsInRoom: number[]
|
||||
childrenInRoomString?: string
|
||||
childrenInRoom?: Child[]
|
||||
bookingCode?: string
|
||||
}
|
||||
|
||||
export async function getHotelSearchDetails<
|
||||
T extends
|
||||
| SelectHotelSearchParams
|
||||
| SelectRateSearchParams
|
||||
| AlternativeHotelsSearchParams,
|
||||
>(
|
||||
{
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: T & {
|
||||
[key: string]: string
|
||||
}
|
||||
},
|
||||
isAlternativeHotels?: boolean
|
||||
): Promise<HotelSearchDetails<T> | null> {
|
||||
const selectHotelParams = convertSearchParamsToObj<T>(searchParams)
|
||||
|
||||
const locations = await getLocations()
|
||||
|
||||
if (!locations || "error" in locations) return null
|
||||
|
||||
const hotel =
|
||||
("hotelId" in selectHotelParams &&
|
||||
(locations.data.find(
|
||||
(location) =>
|
||||
isHotelLocation(location) &&
|
||||
"operaId" in location &&
|
||||
location.operaId === selectHotelParams.hotelId
|
||||
) as HotelLocation | undefined)) ||
|
||||
null
|
||||
|
||||
if (isAlternativeHotels && !hotel) {
|
||||
return notFound()
|
||||
}
|
||||
|
||||
const cityName = isAlternativeHotels
|
||||
? hotel?.relationships.city.name
|
||||
: "city" in selectHotelParams
|
||||
? (selectHotelParams.city as string | undefined)
|
||||
: undefined
|
||||
|
||||
const city =
|
||||
(typeof cityName === "string" &&
|
||||
locations.data.find(
|
||||
(location) => location.name.toLowerCase() === cityName.toLowerCase()
|
||||
)) ||
|
||||
null
|
||||
|
||||
if (!city && !hotel) return notFound()
|
||||
if (isAlternativeHotels && (!city || !hotel)) return notFound()
|
||||
|
||||
let adultsInRoom: number[] = []
|
||||
let childrenInRoomString: HotelSearchDetails<T>["childrenInRoomString"] =
|
||||
undefined
|
||||
let childrenInRoom: HotelSearchDetails<T>["childrenInRoom"] = undefined
|
||||
|
||||
const { rooms } = selectHotelParams
|
||||
|
||||
if (rooms && rooms.length > 0) {
|
||||
adultsInRoom = rooms.map((room) => room.adults ?? 0)
|
||||
childrenInRoomString = rooms[0].childrenInRoom
|
||||
? generateChildrenString(rooms[0].childrenInRoom)
|
||||
: undefined // TODO: Handle multiple rooms
|
||||
childrenInRoom = rooms[0].childrenInRoom // TODO: Handle multiple rooms
|
||||
}
|
||||
|
||||
return {
|
||||
city,
|
||||
hotel,
|
||||
selectHotelParams: { city: cityName, ...selectHotelParams },
|
||||
adultsInRoom,
|
||||
childrenInRoomString,
|
||||
childrenInRoom,
|
||||
bookingCode: selectHotelParams.bookingCode ?? undefined,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
# Booking flow
|
||||
|
||||
The booking flow is the user journey of booking one or more rooms at our
|
||||
hotels. Everything from choosing the date to payment and confirmation is
|
||||
part of the booking flow.
|
||||
|
||||
## Booking widget
|
||||
|
||||
On most of the pages on the website we have a booking widget. This is where
|
||||
the user starts the booking flow, by filling the form and submit. If they
|
||||
entered a city as the destination they will land on the select hotel page
|
||||
and if they entered a specific hotel they will land on the select rate page.
|
||||
|
||||
## Select hotel
|
||||
|
||||
Lists available hotels based on the search criteria. When the user selects
|
||||
a hotel they land on the select rate page.
|
||||
|
||||
## Select rate, room, breakfast etc
|
||||
|
||||
This is a page with an accordion like design, but every accordion is handled
|
||||
as its own page with its own URL.
|
||||
|
||||
## State management
|
||||
|
||||
The state, like search parameters and selected alternatives, is kept
|
||||
throughout the booking flow in the URL.
|
||||
@@ -0,0 +1,12 @@
|
||||
import { notFound } from "next/navigation"
|
||||
|
||||
import { env } from "@/env/server"
|
||||
|
||||
export default function HotelReservationLayout({
|
||||
children,
|
||||
}: React.PropsWithChildren) {
|
||||
if (!env.ENABLE_BOOKING_FLOW) {
|
||||
return notFound()
|
||||
}
|
||||
return <>{children}</>
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import SidePeek from "@/components/HotelReservation/SidePeek"
|
||||
|
||||
import type { LangParams, LayoutArgs } from "@/types/params"
|
||||
|
||||
export default function HotelReservationLayout({
|
||||
children,
|
||||
}: React.PropsWithChildren<LayoutArgs<LangParams>>) {
|
||||
return (
|
||||
<div>
|
||||
{children}
|
||||
<SidePeek />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import LoadingSpinner from "@/components/LoadingSpinner"
|
||||
|
||||
export default function Loading() {
|
||||
return <LoadingSpinner fullPage />
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Suspense } from "react"
|
||||
|
||||
import { MyStay } from "@/components/HotelReservation/MyStay"
|
||||
import { MyStaySkeleton } from "@/components/HotelReservation/MyStay/myStaySkeleton"
|
||||
|
||||
import type { LangParams, PageArgs } from "@/types/params"
|
||||
|
||||
export default async function MyStayPage({
|
||||
params,
|
||||
}: PageArgs<LangParams & { refId: string }>) {
|
||||
return (
|
||||
<Suspense fallback={<MyStaySkeleton />}>
|
||||
<MyStay reservationId={params.refId} />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
5
apps/scandic-web/app/[lang]/(live)/(public)/loading.tsx
Normal file
5
apps/scandic-web/app/[lang]/(live)/(public)/loading.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import LoadingSpinner from "@/components/LoadingSpinner"
|
||||
|
||||
export default function Loading() {
|
||||
return <LoadingSpinner fullPage />
|
||||
}
|
||||
182
apps/scandic-web/app/[lang]/(live)/(public)/login/route.ts
Normal file
182
apps/scandic-web/app/[lang]/(live)/(public)/login/route.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
import { type NextRequest, NextResponse } from "next/server"
|
||||
import { AuthError } from "next-auth"
|
||||
|
||||
import { Lang } from "@/constants/languages"
|
||||
import { env } from "@/env/server"
|
||||
import { internalServerError } from "@/server/errors/next"
|
||||
import { getPublicURL } from "@/server/utils"
|
||||
|
||||
import { signIn } from "@/auth"
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
context: { params: { lang: Lang } }
|
||||
) {
|
||||
const publicURL = getPublicURL(request)
|
||||
|
||||
let redirectHeaders: Headers | undefined = undefined
|
||||
let redirectTo: string
|
||||
|
||||
const returnUrl = request.headers.get("x-returnurl")
|
||||
const isSeamless = request.headers.get("x-login-source") === "seamless"
|
||||
const isMFA = request.headers.get("x-login-source") === "mfa"
|
||||
const isSeamlessMagicLink =
|
||||
request.headers.get("x-login-source") === "seamless-magiclink"
|
||||
|
||||
console.log(
|
||||
`[login] source: ${request.headers.get("x-login-source") || "normal"}`
|
||||
)
|
||||
|
||||
const redirectToCookieValue = request.cookies.get("redirectTo")?.value // Cookie gets set by authRequired middleware
|
||||
const redirectToSearchParamValue =
|
||||
request.nextUrl.searchParams.get("redirectTo")
|
||||
const redirectToFallback = "/"
|
||||
|
||||
console.log(`[login] redirectTo cookie value: ${redirectToCookieValue}`)
|
||||
console.log(
|
||||
`[login] redirectTo search param value: ${redirectToSearchParamValue}`
|
||||
)
|
||||
|
||||
if (isSeamless || isSeamlessMagicLink || isMFA) {
|
||||
if (returnUrl) {
|
||||
redirectTo = returnUrl
|
||||
} else {
|
||||
console.log(
|
||||
`[login] missing returnUrl, using fallback: ${redirectToFallback}`
|
||||
)
|
||||
redirectTo = redirectToFallback
|
||||
}
|
||||
} else {
|
||||
redirectTo =
|
||||
redirectToCookieValue || redirectToSearchParamValue || redirectToFallback
|
||||
|
||||
// Make relative URL to absolute URL
|
||||
if (redirectTo.startsWith("/")) {
|
||||
console.log(`[login] make redirectTo absolute, from ${redirectTo}`)
|
||||
redirectTo = new URL(redirectTo, publicURL).href
|
||||
console.log(`[login] make redirectTo absolute, to ${redirectTo}`)
|
||||
}
|
||||
|
||||
// Clean up cookie from authRequired middleware
|
||||
redirectHeaders = new Headers()
|
||||
redirectHeaders.append(
|
||||
"set-cookie",
|
||||
"redirectTo=; Expires=Thu, 01 Jan 1970 00:00:00 UTC; Path=/; HttpOnly; SameSite=Lax"
|
||||
)
|
||||
|
||||
try {
|
||||
// Initiate the seamless login flow
|
||||
let redirectUrlValue
|
||||
switch (context.params.lang) {
|
||||
case Lang.da:
|
||||
redirectUrlValue = env.SEAMLESS_LOGIN_DA
|
||||
break
|
||||
case Lang.de:
|
||||
redirectUrlValue = env.SEAMLESS_LOGIN_DE
|
||||
break
|
||||
case Lang.en:
|
||||
redirectUrlValue = env.SEAMLESS_LOGIN_EN
|
||||
break
|
||||
case Lang.fi:
|
||||
redirectUrlValue = env.SEAMLESS_LOGIN_FI
|
||||
break
|
||||
case Lang.no:
|
||||
redirectUrlValue = env.SEAMLESS_LOGIN_NO
|
||||
break
|
||||
case Lang.sv:
|
||||
redirectUrlValue = env.SEAMLESS_LOGIN_SV
|
||||
break
|
||||
}
|
||||
const redirectUrl = new URL(redirectUrlValue)
|
||||
console.log(`[login] creating redirect to seamless login: ${redirectUrl}`)
|
||||
redirectUrl.searchParams.set("returnurl", redirectTo)
|
||||
console.log(
|
||||
`[login] returnurl for seamless login: ${redirectUrl.searchParams.get("returnurl")}`
|
||||
)
|
||||
redirectTo = redirectUrl.toString()
|
||||
|
||||
/** Set cookie with redirect Url to appropriately redirect user when using magic link login */
|
||||
redirectHeaders.append(
|
||||
"set-cookie",
|
||||
"magicLinkRedirectTo=" +
|
||||
redirectTo +
|
||||
"; Max-Age=300; Path=/; HttpOnly; SameSite=Lax"
|
||||
)
|
||||
} catch (e) {
|
||||
console.error(
|
||||
"[login] unable to create URL for seamless login, proceeding without it.",
|
||||
e
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`[login] final redirectUrl: ${redirectTo}`)
|
||||
console.log({ login_env: process.env })
|
||||
|
||||
/** Record<string, any> is next-auth typings */
|
||||
const params: Record<string, any> = {
|
||||
ui_locales: context.params.lang,
|
||||
scope: ["openid", "profile", "booking", "profile_link"],
|
||||
/**
|
||||
* The `acr_values` param is used to make Curity display the proper login
|
||||
* page for Scandic. Without the parameter Curity presents some choices
|
||||
* to the user which we do not want.
|
||||
*/
|
||||
acr_values: "urn:com:scandichotels:scandic",
|
||||
|
||||
/**
|
||||
* Both of the below two params are required to send for initiating login as well
|
||||
* because user might choose to do Email link login.
|
||||
* */
|
||||
// The `for_origin` param is used to make Curity email login functionality working.
|
||||
for_origin: publicURL,
|
||||
// This is new param set for differentiate between the Magic link login of New web and current web
|
||||
version: "2",
|
||||
}
|
||||
|
||||
if (isMFA) {
|
||||
// Append profile_update scope for MFA
|
||||
params.scope.push("profile_update")
|
||||
/**
|
||||
* The below acr value is required as for New Web same Curity Client is used for MFA
|
||||
* while in current web it is being setup using different Curity Client
|
||||
*/
|
||||
params.acr_values = "urn:com:scandichotels:scandic-otp"
|
||||
} else if (isSeamlessMagicLink) {
|
||||
params.acr_values = "urn:com:scandichotels:scandic-email"
|
||||
}
|
||||
params.scope = params.scope.join(" ")
|
||||
/**
|
||||
* Passing `redirect: false` to `signIn` will return the URL instead of
|
||||
* automatically redirecting to it inside of `signIn`.
|
||||
* https://github.com/nextauthjs/next-auth/blob/3c035ec/packages/next-auth/src/lib/actions.ts#L76
|
||||
*/
|
||||
const redirectUrl = await signIn(
|
||||
"curity",
|
||||
{
|
||||
redirectTo,
|
||||
redirect: false,
|
||||
},
|
||||
params
|
||||
)
|
||||
|
||||
if (redirectUrl) {
|
||||
const redirectOpts = {
|
||||
headers: redirectHeaders,
|
||||
}
|
||||
console.log(`[login] redirecting to: ${redirectUrl}`, redirectOpts)
|
||||
return NextResponse.redirect(redirectUrl, redirectOpts)
|
||||
} else {
|
||||
console.error(`[login] missing redirectUrl reponse from signIn()`)
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof AuthError) {
|
||||
console.error({ signInAuthError: error })
|
||||
} else {
|
||||
console.error({ signInError: error })
|
||||
}
|
||||
}
|
||||
|
||||
return internalServerError()
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { type NextRequest, NextResponse } from "next/server"
|
||||
import { AuthError } from "next-auth"
|
||||
|
||||
import { badRequest, internalServerError } from "@/server/errors/next"
|
||||
import { getPublicURL } from "@/server/utils"
|
||||
|
||||
import { signIn } from "@/auth"
|
||||
|
||||
import type { Lang } from "@/constants/languages"
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
context: { params: { lang: Lang } }
|
||||
) {
|
||||
const publicURL = getPublicURL(request)
|
||||
|
||||
const loginKey = request.nextUrl.searchParams.get("loginKey")
|
||||
if (!loginKey) {
|
||||
console.log(
|
||||
`[verifymagiclink] missing required loginKey, aborting bad request`
|
||||
)
|
||||
return badRequest()
|
||||
}
|
||||
|
||||
let redirectTo: string
|
||||
|
||||
console.log(`[verifymagiclink] verifying callback`)
|
||||
|
||||
const redirectToCookieValue = request.cookies.get(
|
||||
"magicLinkRedirectTo"
|
||||
)?.value // Set redirect url from the magicLinkRedirect Cookie which is set when intiating login
|
||||
const redirectToFallback = "/"
|
||||
|
||||
console.log(
|
||||
`[verifymagiclink] magicLinkRedirectTo cookie value: ${redirectToCookieValue}`
|
||||
)
|
||||
|
||||
redirectTo = redirectToCookieValue || redirectToFallback
|
||||
|
||||
// Make relative URL to absolute URL
|
||||
if (redirectTo.startsWith("/")) {
|
||||
console.log(
|
||||
`[verifymagiclink] make redirectTo absolute, from ${redirectTo}`
|
||||
)
|
||||
redirectTo = new URL(redirectTo, publicURL).href
|
||||
console.log(`[verifymagiclink] make redirectTo absolute, to ${redirectTo}`)
|
||||
}
|
||||
|
||||
// Update Seamless login url as Magic link login has a different authenticator in Curity
|
||||
redirectTo = redirectTo.replace("updatelogin", "updateloginemail")
|
||||
|
||||
try {
|
||||
console.log(`[verifymagiclink] final redirectUrl: ${redirectTo}`)
|
||||
|
||||
/**
|
||||
* Passing `redirect: false` to `signIn` will return the URL instead of
|
||||
* automatically redirecting to it inside of `signIn`.
|
||||
* https://github.com/nextauthjs/next-auth/blob/3c035ec/packages/next-auth/src/lib/actions.ts#L76
|
||||
*/
|
||||
const redirectUrl = await signIn(
|
||||
"curity",
|
||||
{
|
||||
redirectTo,
|
||||
redirect: false,
|
||||
},
|
||||
{
|
||||
ui_locales: context.params.lang,
|
||||
scope: ["openid", "profile"].join(" "),
|
||||
loginKey: loginKey,
|
||||
for_origin: publicURL,
|
||||
acr_values: "urn:com:scandichotels:scandic-email",
|
||||
version: "2",
|
||||
}
|
||||
)
|
||||
|
||||
if (redirectUrl) {
|
||||
console.log(`[verifymagiclink] redirecting to: ${redirectUrl}`)
|
||||
return NextResponse.redirect(redirectUrl)
|
||||
} else {
|
||||
console.error(
|
||||
`[verifymagiclink] missing redirectUrl reponse from signIn()`
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof AuthError) {
|
||||
console.error({ signInAuthError: error })
|
||||
} else {
|
||||
console.error({ signInError: error })
|
||||
}
|
||||
}
|
||||
|
||||
return internalServerError()
|
||||
}
|
||||
Reference in New Issue
Block a user