fix: cache hotel response

This commit is contained in:
Simon Emanuelsson
2024-12-17 16:18:46 +01:00
parent 13a164242f
commit 1deab000bd
38 changed files with 339 additions and 246 deletions

View File

@@ -9,6 +9,7 @@ import type {
} from "@/types/components/hotelReservation/enterDetails/details" } from "@/types/components/hotelReservation/enterDetails/details"
import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter" import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter"
import type { SelectRateSearchParams } from "@/types/components/hotelReservation/selectRate/selectRate" import type { SelectRateSearchParams } from "@/types/components/hotelReservation/selectRate/selectRate"
import { CurrencyEnum } from "@/types/enums/currency"
import { PackageTypeEnum } from "@/types/enums/packages" import { PackageTypeEnum } from "@/types/enums/packages"
import type { RoomPrice, RoomRate } from "@/types/stores/enter-details" import type { RoomPrice, RoomRate } from "@/types/stores/enter-details"
@@ -47,12 +48,12 @@ export const roomRate: RoomRate = {
localPrice: { localPrice: {
pricePerNight: 1508, pricePerNight: 1508,
pricePerStay: 1508, pricePerStay: 1508,
currency: "SEK", currency: CurrencyEnum.SEK,
}, },
requestedPrice: { requestedPrice: {
pricePerNight: 132, pricePerNight: 132,
pricePerStay: 132, pricePerStay: 132,
currency: "EUR", currency: CurrencyEnum.EUR,
}, },
}, },
publicRate: { publicRate: {
@@ -60,12 +61,12 @@ export const roomRate: RoomRate = {
localPrice: { localPrice: {
pricePerNight: 1525, pricePerNight: 1525,
pricePerStay: 1525, pricePerStay: 1525,
currency: "SEK", currency: CurrencyEnum.SEK,
}, },
requestedPrice: { requestedPrice: {
pricePerNight: 133, pricePerNight: 133,
pricePerStay: 133, pricePerStay: 133,
currency: "EUR", currency: CurrencyEnum.EUR,
}, },
}, },
} }

View File

@@ -10,8 +10,8 @@ import { protectedServerActionProcedure } from "@/server/trpc"
import { editProfileSchema } from "@/components/Forms/Edit/Profile/schema" import { editProfileSchema } from "@/components/Forms/Edit/Profile/schema"
import { countriesMap } from "@/components/TempDesignSystem/Form/Country/countries" import { countriesMap } from "@/components/TempDesignSystem/Form/Country/countries"
import { getIntl } from "@/i18n" import { getIntl } from "@/i18n"
import { phoneValidator } from "@/utils/phoneValidator"
import { getMembership } from "@/utils/user" import { getMembership } from "@/utils/user"
import { phoneValidator } from "@/utils/zod/phoneValidator"
import { Status } from "@/types/components/myPages/myProfile/edit" import { Status } from "@/types/components/myPages/myProfile/edit"

View File

@@ -12,8 +12,6 @@ export default async function BookingConfirmationPage({
setLang(params.lang) setLang(params.lang)
void getBookingConfirmation(searchParams.confirmationNumber) void getBookingConfirmation(searchParams.confirmationNumber)
return ( return (
<BookingConfirmation <BookingConfirmation confirmationNumber={searchParams.confirmationNumber} />
confirmationNumber={searchParams.confirmationNumber}
/>
) )
} }

View File

@@ -15,7 +15,7 @@ import type {
CategorizedFilters, CategorizedFilters,
Filter, Filter,
} from "@/types/components/hotelReservation/selectHotel/hotelFilters" } from "@/types/components/hotelReservation/selectHotel/hotelFilters"
import type { HotelsAvailabilityItem } from "@/server/routers/hotels/output" import type { HotelsAvailabilityItem } from "@/types/trpc/routers/hotel/availability"
const hotelSurroundingsFilterNames = [ const hotelSurroundingsFilterNames = [
"Hotel surroundings", "Hotel surroundings",

View File

@@ -28,14 +28,11 @@ export default async function SelectRatePage({
}: PageArgs<LangParams & { section: string }, SelectRateSearchParams>) { }: PageArgs<LangParams & { section: string }, SelectRateSearchParams>) {
setLang(params.lang) setLang(params.lang)
const searchDetails = await getHotelSearchDetails({ searchParams }) const searchDetails = await getHotelSearchDetails({ searchParams })
if (!searchDetails) { if (!searchDetails?.hotel) {
return notFound()
}
const { hotel, adultsInRoom, childrenInRoom, selectHotelParams } = searchDetails
if (!hotel) {
return notFound() return notFound()
} }
const { hotel, adultsInRoom, childrenInRoom, selectHotelParams } =
searchDetails
const hotelData = await getHotel({ const hotelData = await getHotel({
hotelId: hotel.id, hotelId: hotel.id,

View File

@@ -27,8 +27,8 @@ export default async function BookingWidgetPage({
}) })
const hotelPageParams = { const hotelPageParams = {
hotel: hotelData?.data?.id || "", hotel: hotelData?.hotel?.id || "",
city: hotelData?.data?.attributes?.cityName || "", city: hotelData?.hotel?.cityName || "",
} }
return <BookingWidget bookingWidgetSearchParams={hotelPageParams} /> return <BookingWidget bookingWidgetSearchParams={hotelPageParams} />

View File

@@ -10,7 +10,7 @@ import {
} from "@/types/components/hotelPage/sidepeek/parking" } from "@/types/components/hotelPage/sidepeek/parking"
export default async function ParkingPrices({ export default async function ParkingPrices({
currency, currency = "",
freeParking, freeParking,
pricing, pricing,
}: ParkingPricesProps) { }: ParkingPricesProps) {

View File

@@ -125,10 +125,10 @@ export default async function HotelPage({ hotelId }: HotelPageProps) {
const trackingPageData = getTrackingPageData( const trackingPageData = getTrackingPageData(
hotelPageData.system, hotelPageData.system,
hotelData.data.attributes, hotelData.hotel,
lang lang
) )
const trackingHotelData = getTrackingHotelData(hotelData.data) const trackingHotelData = getTrackingHotelData(hotelData.hotel)
return ( return (
<div className={styles.pageContainer}> <div className={styles.pageContainer}>

View File

@@ -35,7 +35,7 @@ export function getTrackingPageData(
return tracking return tracking
} }
export function getTrackingHotelData(hotelData: HotelData["data"]) { export function getTrackingHotelData(hotelData: HotelData["hotel"]) {
const tracking: TrackingSDKHotelInfo = { const tracking: TrackingSDKHotelInfo = {
hotelID: hotelData.id, hotelID: hotelData.id,
} }

View File

@@ -1,7 +1,7 @@
import { z } from "zod" import { z } from "zod"
import { passwordValidator } from "@/utils/passwordValidator" import { passwordValidator } from "@/utils/zod/passwordValidator"
import { phoneValidator } from "@/utils/phoneValidator" import { phoneValidator } from "@/utils/zod/phoneValidator"
const countryRequiredMsg = "Country is required" const countryRequiredMsg = "Country is required"
export const editProfileSchema = z export const editProfileSchema = z

View File

@@ -1,7 +1,7 @@
import { z } from "zod" import { z } from "zod"
import { passwordValidator } from "@/utils/passwordValidator" import { passwordValidator } from "@/utils/zod/passwordValidator"
import { phoneValidator } from "@/utils/phoneValidator" import { phoneValidator } from "@/utils/zod/phoneValidator"
const countryRequiredMsg = "Country is required" const countryRequiredMsg = "Country is required"
export const signUpSchema = z.object({ export const signUpSchema = z.object({

View File

@@ -22,9 +22,8 @@ export default async function BookingConfirmation({
confirmationNumber, confirmationNumber,
}: BookingConfirmationProps) { }: BookingConfirmationProps) {
const lang = getLang() const lang = getLang()
const { booking, hotel, room } = await getBookingConfirmation( const { booking, hotel, room } =
confirmationNumber await getBookingConfirmation(confirmationNumber)
)
const arrivalDate = new Date(booking.checkInDate) const arrivalDate = new Date(booking.checkInDate)
const departureDate = new Date(booking.checkOutDate) const departureDate = new Date(booking.checkOutDate)

View File

@@ -2,7 +2,7 @@ import { z } from "zod"
import { dt } from "@/lib/dt" import { dt } from "@/lib/dt"
import { phoneValidator } from "@/utils/phoneValidator" import { phoneValidator } from "@/utils/zod/phoneValidator"
// stringMatcher regex is copied from current web as specified by requirements. // stringMatcher regex is copied from current web as specified by requirements.
const stringMatcher = const stringMatcher =

View File

@@ -31,10 +31,6 @@ import {
type TrackingSDKPageData, type TrackingSDKPageData,
} from "@/types/components/tracking" } from "@/types/components/tracking"
function isValidHotelData(hotel: NullableHotelData): hotel is HotelData {
return hotel != null
}
export async function SelectHotelMapContainer({ export async function SelectHotelMapContainer({
searchParams, searchParams,
isAlternativeHotels, isAlternativeHotels,
@@ -89,7 +85,7 @@ export async function SelectHotelMapContainer({
const [hotels] = await fetchAvailableHotelsPromise const [hotels] = await fetchAvailableHotelsPromise
const validHotels = hotels?.filter(isValidHotelData) || [] const validHotels = (hotels?.filter(Boolean) as HotelData[]) || []
const hotelPins = getHotelPins(validHotels) const hotelPins = getHotelPins(validHotels)
const filterList = getFiltersFromHotels(validHotels) const filterList = getFiltersFromHotels(validHotels)

View File

@@ -66,7 +66,7 @@ export default async function HotelInfoCard({
{ {
address: hotel.address.streetAddress, address: hotel.address.streetAddress,
city: hotel.address.city, city: hotel.address.city,
distanceToCityCentreInKm: getSingleDecimal( distanceToCityCenterInKm: getSingleDecimal(
hotel.location.distanceToCentre / 1000 hotel.location.distanceToCentre / 1000
), ),
} }

View File

@@ -12,13 +12,13 @@ import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import styles from "./selectedRoomPanel.module.css" import styles from "./selectedRoomPanel.module.css"
import type { Room } from "@/types/components/hotelReservation/selectRate/selectRate" import type { Room as SelectedRateRoom } from "@/types/components/hotelReservation/selectRate/selectRate"
import type { RoomData } from "@/types/hotel" import type { Room } from "@/types/hotel"
interface SelectedRoomPanelProps { interface SelectedRoomPanelProps {
roomIndex: number roomIndex: number
room: Room room: SelectedRateRoom
roomCategories: RoomData[] roomCategories: Room[]
} }
export default function SelectedRoomPanel({ export default function SelectedRoomPanel({

View File

@@ -14,7 +14,7 @@ import {
} from "@/components/Icons" } from "@/components/Icons"
import AriaInputWithLabel from "@/components/TempDesignSystem/Form/Input/AriaInputWithLabel" import AriaInputWithLabel from "@/components/TempDesignSystem/Form/Input/AriaInputWithLabel"
import Caption from "@/components/TempDesignSystem/Text/Caption" import Caption from "@/components/TempDesignSystem/Text/Caption"
import { passwordValidators } from "@/utils/passwordValidator" import { passwordValidators } from "@/utils/zod/passwordValidator"
import Button from "../../Button" import Button from "../../Button"
import { type IconProps, type NewPasswordProps } from "./newPassword" import { type IconProps, type NewPasswordProps } from "./newPassword"

View File

@@ -2,7 +2,7 @@ import { z } from "zod"
import { ChildBedTypeEnum } from "@/constants/booking" import { ChildBedTypeEnum } from "@/constants/booking"
import { phoneValidator } from "@/utils/phoneValidator" import { phoneValidator } from "@/utils/zod/phoneValidator"
// MUTATION // MUTATION
export const createBookingSchema = z export const createBookingSchema = z

View File

@@ -7,7 +7,7 @@ import { productTypeSchema } from "./schemas/availability/productType"
import { citySchema } from "./schemas/city" import { citySchema } from "./schemas/city"
import { import {
attributesSchema, attributesSchema,
includesSchema, includedSchema,
relationshipsSchema as hotelRelationshipsSchema, relationshipsSchema as hotelRelationshipsSchema,
} from "./schemas/hotel" } from "./schemas/hotel"
import { locationCitySchema } from "./schemas/location/city" import { locationCitySchema } from "./schemas/location/city"
@@ -18,7 +18,13 @@ import { relationshipsSchema } from "./schemas/relationships"
import { roomConfigurationSchema } from "./schemas/roomAvailability/configuration" import { roomConfigurationSchema } from "./schemas/roomAvailability/configuration"
import { rateDefinitionSchema } from "./schemas/roomAvailability/rateDefinition" import { rateDefinitionSchema } from "./schemas/roomAvailability/rateDefinition"
import type { AdditionalData, City, NearbyHotel, Restaurant, Room } from "@/types/hotel" import type {
AdditionalData,
City,
NearbyHotel,
Restaurant,
Room,
} from "@/types/hotel"
// NOTE: Find schema at: https://aks-test.scandichotels.com/hotel/swagger/v1/index.html // NOTE: Find schema at: https://aks-test.scandichotels.com/hotel/swagger/v1/index.html
export const hotelSchema = z export const hotelSchema = z
@@ -38,10 +44,13 @@ export const hotelSchema = z
}), }),
// NOTE: We can pass an "include" param to the hotel API to retrieve // NOTE: We can pass an "include" param to the hotel API to retrieve
// additional data for an individual hotel. // additional data for an individual hotel.
included: includesSchema, included: includedSchema,
}) })
.transform(({ data: { attributes, ...data }, included }) => { .transform(({ data: { attributes, ...data }, included }) => {
const additionalData = included.find((inc): inc is AdditionalData => inc!.type === "additionalData") const additionalData =
included.find(
(inc): inc is AdditionalData => inc!.type === "additionalData"
) ?? ({} as AdditionalData)
const cities = included.filter((inc): inc is City => inc!.type === "cities") const cities = included.filter((inc): inc is City => inc!.type === "cities")
const nearbyHotels = included.filter( const nearbyHotels = included.filter(
(inc): inc is NearbyHotel => inc!.type === "hotels" (inc): inc is NearbyHotel => inc!.type === "hotels"
@@ -262,4 +271,4 @@ export const getNearbyHotelIdsSchema = z
}) })
), ),
}) })
.transform((data) => data.data.map((hotel) => hotel.id)) .transform((data) => data.data.map((hotel) => hotel.id))

View File

@@ -1,4 +1,7 @@
import { unstable_cache } from "next/cache"
import { ApiLang } from "@/constants/languages" import { ApiLang } from "@/constants/languages"
import { env } from "@/env/server"
import * as api from "@/lib/api" import * as api from "@/lib/api"
import { dt } from "@/lib/dt" import { dt } from "@/lib/dt"
import { badRequestError } from "@/server/errors/trpc" import { badRequestError } from "@/server/errors/trpc"
@@ -15,6 +18,8 @@ import { cache } from "@/utils/cache"
import { getHotelPageUrl } from "../contentstack/hotelPage/utils" import { getHotelPageUrl } from "../contentstack/hotelPage/utils"
import { getVerifiedUser, parsedUser } from "../user/query" import { getVerifiedUser, parsedUser } from "../user/query"
import { additionalDataSchema } from "./schemas/additionalData"
import { meetingRoomsSchema } from "./schemas/meetingRoom"
import { import {
breakfastPackageInputSchema, breakfastPackageInputSchema,
cityCoordinatesInputSchema, cityCoordinatesInputSchema,
@@ -54,133 +59,144 @@ import type { BedTypeSelection } from "@/types/components/hotelReservation/enter
import { BreakfastPackageEnum } from "@/types/enums/breakfast" import { BreakfastPackageEnum } from "@/types/enums/breakfast"
import { HotelTypeEnum } from "@/types/enums/hotelType" import { HotelTypeEnum } from "@/types/enums/hotelType"
import type { RequestOptionsWithOutBody } from "@/types/fetch" import type { RequestOptionsWithOutBody } from "@/types/fetch"
import type { HotelInput } from "@/types/trpc/routers/hotel/hotel"
import type { HotelData } from "@/types/hotel" import type { HotelData } from "@/types/hotel"
import type { HotelPageUrl } from "@/types/trpc/routers/contentstack/hotelPage" import type { HotelPageUrl } from "@/types/trpc/routers/contentstack/hotelPage"
import { CityLocation } from "@/types/trpc/routers/hotel/locations" import type { HotelInput } from "@/types/trpc/routers/hotel/hotel"
import { meetingRoomsSchema } from "./schemas/meetingRoom" import type { CityLocation } from "@/types/trpc/routers/hotel/locations"
import { env } from "@/env/server"
import { additionalDataSchema } from "./schemas/additionalData"
export const getHotel = cache( export const getHotel = cache(
async (input: HotelInput, serviceToken: string) => { async (input: HotelInput, serviceToken: string) => {
const { hotelId, isCardOnlyPayment, language } = input const callable = unstable_cache(
/** async function (
* Since API expects the params appended and not just hotelId: HotelInput["hotelId"],
* a comma separated string we need to initialize the language: HotelInput["language"],
* SearchParams with a sequence of pairs isCardOnlyPayment?: HotelInput["isCardOnlyPayment"]
* (include=City&include=NearbyHotels&include=Restaurants etc.) ) {
**/ /**
const params = new URLSearchParams([ * Since API expects the params appended and not just
["hotelId", hotelId], * a comma separated string we need to initialize the
["include", "AdditionalData"], * SearchParams with a sequence of pairs
["include", "City"], * (include=City&include=NearbyHotels&include=Restaurants etc.)
["include", "NearbyHotels"], **/
["include", "Restaurants"], const params = new URLSearchParams([
["include", "RoomCategories"], ["include", "AdditionalData"],
["language", toApiLang(language)], ["include", "City"],
]) ["include", "NearbyHotels"],
metrics.hotel.counter.add(1, { ["include", "Restaurants"],
hotelId, ["include", "RoomCategories"],
language, ["language", toApiLang(language)],
}) ])
console.info( metrics.hotel.counter.add(1, {
"api.hotels.hotelData start", hotelId,
JSON.stringify({ query: { hotelId, params } }) language,
) })
console.info(
"api.hotels.hotelData start",
JSON.stringify({ query: { hotelId, params } })
)
const apiResponse = await api.get( const apiResponse = await api.get(
api.endpoints.v1.Hotel.Hotels.hotel(hotelId), api.endpoints.v1.Hotel.Hotels.hotel(hotelId),
{ {
headers: { headers: {
Authorization: `Bearer ${serviceToken}`, Authorization: `Bearer ${serviceToken}`,
}, },
// needs to clear default option as only // needs to clear default option as only
// cache or next.revalidate is permitted // cache or next.revalidate is permitted
cache: undefined, cache: undefined,
next: { next: {
revalidate: env.CACHE_TIME_HOTELDATA, revalidate: env.CACHE_TIME_HOTELS,
tags: [`${language}:hotel:${hotelId}`], tags: [`${language}:hotel:${hotelId}`],
}, },
},
params
)
if (!apiResponse.ok) {
const text = await apiResponse.text()
console.log({ text })
metrics.hotel.fail.add(1, {
hotelId,
language,
error_type: "http_error",
error: JSON.stringify({
status: apiResponse.status,
statusText: apiResponse.statusText,
text,
}),
})
console.error(
"api.hotels.hotelData error",
JSON.stringify({
query: { hotelId, params },
error: {
status: apiResponse.status,
statusText: apiResponse.statusText,
text,
}, },
params
)
if (!apiResponse.ok) {
const text = await apiResponse.text()
metrics.hotel.fail.add(1, {
hotelId,
language,
error_type: "http_error",
error: JSON.stringify({
status: apiResponse.status,
statusText: apiResponse.statusText,
text,
}),
})
console.error(
"api.hotels.hotelData error",
JSON.stringify({
query: { hotelId, params },
error: {
status: apiResponse.status,
statusText: apiResponse.statusText,
text,
},
})
)
return null
}
const apiJson = await apiResponse.json()
const validateHotelData = hotelSchema.safeParse(apiJson)
if (!validateHotelData.success) {
metrics.hotel.fail.add(1, {
hotelId,
language,
error_type: "validation_error",
error: JSON.stringify(validateHotelData.error),
})
console.error(
"api.hotels.hotelData validation error",
JSON.stringify({
query: { hotelId, params },
error: validateHotelData.error,
})
)
throw badRequestError()
}
metrics.hotel.success.add(1, {
hotelId,
language,
}) })
) console.info(
return null "api.hotels.hotelData success",
} JSON.stringify({
query: { hotelId, params: params },
})
)
const hotelData = validateHotelData.data
const apiJson = await apiResponse.json() if (isCardOnlyPayment) {
const validateHotelData = hotelSchema.safeParse(apiJson) hotelData.hotel.merchantInformationData.alternatePaymentOptions = []
}
if (!validateHotelData.success) { const gallery = hotelData.additionalData?.gallery
metrics.hotel.fail.add(1, { if (gallery) {
hotelId, const smallerImages = gallery.smallerImages
language, const hotelGalleryImages =
error_type: "validation_error", hotelData.hotel.hotelType === HotelTypeEnum.Signature
error: JSON.stringify(validateHotelData.error), ? smallerImages.slice(0, 10)
}) : smallerImages.slice(0, 6)
hotelData.hotel.galleryImages = hotelGalleryImages
}
console.error( return hotelData
"api.hotels.hotelData validation error", },
JSON.stringify({ [`${input.language}:hotel:${input.hotelId}:${!!input.isCardOnlyPayment}`],
query: { hotelId, params }, {
error: validateHotelData.error, revalidate: env.CACHE_TIME_HOTELS,
}) tags: [
) `${input.language}:hotel:${input.hotelId}:${!!input.isCardOnlyPayment}`,
throw badRequestError() ],
} }
metrics.hotel.success.add(1, {
hotelId,
language,
})
console.info(
"api.hotels.hotelData success",
JSON.stringify({
query: { hotelId, params: params },
})
) )
const hotelData = validateHotelData.data
if (isCardOnlyPayment) { return callable(input.hotelId, input.language, input.isCardOnlyPayment)
hotelData.hotel.merchantInformationData.alternatePaymentOptions = []
}
const gallery = hotelData.additionalData?.gallery
if (gallery) {
const smallerImages = gallery.smallerImages
const hotelGalleryImages =
hotelData.hotel.hotelType === HotelTypeEnum.Signature
? smallerImages.slice(0, 10)
: smallerImages.slice(0, 6)
hotelData.hotel.galleryImages = hotelGalleryImages
}
return hotelData
} }
) )
@@ -731,9 +747,9 @@ export const hotelQueryRouter = router({
type: matchingRoom.mainBed.type, type: matchingRoom.mainBed.type,
extraBed: matchingRoom.fixedExtraBed extraBed: matchingRoom.fixedExtraBed
? { ? {
type: matchingRoom.fixedExtraBed.type, type: matchingRoom.fixedExtraBed.type,
description: matchingRoom.fixedExtraBed.description, description: matchingRoom.fixedExtraBed.description,
} }
: undefined, : undefined,
} }
} }
@@ -861,7 +877,10 @@ export const hotelQueryRouter = router({
} }
const cityId = locations const cityId = locations
.filter((loc): loc is CityLocation => "type" in loc && loc.type === "cities") .filter(
(loc): loc is CityLocation =>
"type" in loc && loc.type === "cities"
)
.find((loc) => loc.cityIdentifier === locationFilter.city)?.id .find((loc) => loc.cityIdentifier === locationFilter.city)?.id
if (!cityId) { if (!cityId) {
@@ -973,7 +992,10 @@ export const hotelQueryRouter = router({
const hotels = await Promise.all( const hotels = await Promise.all(
hotelsToFetch.map(async (hotelId) => { hotelsToFetch.map(async (hotelId) => {
const [hotelData, url] = await Promise.all([ const [hotelData, url] = await Promise.all([
getHotel({ hotelId, language }, ctx.serviceToken), getHotel(
{ hotelId, isCardOnlyPayment: false, language },
ctx.serviceToken
),
getHotelPageUrl(language, hotelId), getHotelPageUrl(language, hotelId),
]) ])
@@ -1000,7 +1022,8 @@ export const hotelQueryRouter = router({
) )
return hotels.filter( return hotels.filter(
(hotel): hotel is { data: HotelData; url: HotelPageUrl } => !!hotel.data (hotel): hotel is { data: HotelData; url: HotelPageUrl } =>
!!hotel.data
) )
}), }),
}), }),
@@ -1096,7 +1119,7 @@ export const hotelQueryRouter = router({
Authorization: `Bearer ${ctx.serviceToken}`, Authorization: `Bearer ${ctx.serviceToken}`,
}, },
next: { next: {
revalidate: TWENTYFOUR_HOURS, revalidate: env.CACHE_TIME_HOTELS,
}, },
} }

View File

@@ -9,5 +9,5 @@ export const childrenSchema = z.object({
export const occupancySchema = z.object({ export const occupancySchema = z.object({
adults: z.number(), adults: z.number(),
children: z.array(childrenSchema), children: z.array(childrenSchema).default([]),
}) })

View File

@@ -1,5 +1,7 @@
import { z } from "zod" import { z } from "zod"
import { nullableNumberValidator } from "@/utils/zod/numberValidator"
import { addressSchema } from "./hotel/address" import { addressSchema } from "./hotel/address"
import { contactInformationSchema } from "./hotel/contactInformation" import { contactInformationSchema } from "./hotel/contactInformation"
import { hotelContentSchema } from "./hotel/content" import { hotelContentSchema } from "./hotel/content"
@@ -17,8 +19,8 @@ import { rewardNightSchema } from "./hotel/rewardNight"
import { socialMediaSchema } from "./hotel/socialMedia" import { socialMediaSchema } from "./hotel/socialMedia"
import { specialAlertsSchema } from "./hotel/specialAlerts" import { specialAlertsSchema } from "./hotel/specialAlerts"
import { specialNeedGroupSchema } from "./hotel/specialNeedGroups" import { specialNeedGroupSchema } from "./hotel/specialNeedGroups"
import { imageSchema } from "./image"
import { facilitySchema } from "./additionalData" import { facilitySchema } from "./additionalData"
import { imageSchema } from "./image"
export const attributesSchema = z.object({ export const attributesSchema = z.object({
accessibilityElevatorPitchText: z.string().optional(), accessibilityElevatorPitchText: z.string().optional(),
@@ -51,13 +53,23 @@ export const attributesSchema = z.object({
socialMedia: socialMediaSchema, socialMedia: socialMediaSchema,
specialAlerts: specialAlertsSchema, specialAlerts: specialAlertsSchema,
specialNeedGroups: z.array(specialNeedGroupSchema), specialNeedGroups: z.array(specialNeedGroupSchema),
vat: z.number(), vat: nullableNumberValidator,
}) })
export const includesSchema = z export const includedSchema = z
.array(includeSchema) .array(includeSchema)
.default([]) .default([])
.transform((data) => data.filter((item) => !!item)) .transform((data) =>
data.filter((item) => {
if (item) {
if ("isPublished" in item && item.isPublished === false) {
return false
}
return true
}
return false
})
)
const relationshipSchema = z.object({ const relationshipSchema = z.object({
links: z.object({ links: z.object({

View File

@@ -2,70 +2,92 @@ import { z } from "zod"
import { imageSchema } from "@/server/routers/hotels/schemas/image" import { imageSchema } from "@/server/routers/hotels/schemas/image"
import {
nullableIntValidator,
nullableNumberValidator,
} from "@/utils/zod/numberValidator"
import {
nullableStringUrlValidator,
nullableStringValidator,
} from "@/utils/zod/stringValidator"
import { specialAlertsSchema } from "../specialAlerts"
import { CurrencyEnum } from "@/types/enums/currency" import { CurrencyEnum } from "@/types/enums/currency"
const descriptionSchema = z.object({
medium: nullableStringValidator,
short: nullableStringValidator,
})
const textSchema = z.object({
descriptions: descriptionSchema,
facilityInformation: nullableStringValidator,
meetingDescription: descriptionSchema.optional(),
surroundingInformation: nullableStringValidator,
})
const contentSchema = z.object({ const contentSchema = z.object({
images: z.array(imageSchema).default([]), images: z.array(imageSchema).default([]),
texts: z.object({ texts: textSchema,
descriptions: z.object({ })
medium: z.string().default(""),
short: z.string().default(""), const restaurantPriceSchema = z.object({
}), amount: nullableNumberValidator,
}), currency: z.nativeEnum(CurrencyEnum).default(CurrencyEnum.SEK),
}) })
const externalBreakfastSchema = z.object({ const externalBreakfastSchema = z.object({
isAvailable: z.boolean().default(false), isAvailable: z.boolean().default(false),
localPriceForExternalGuests: z.object({ localPriceForExternalGuests: restaurantPriceSchema.optional(),
amount: z.number().default(0), requestedPriceForExternalGuests: restaurantPriceSchema.optional(),
currency: z.nativeEnum(CurrencyEnum).default(CurrencyEnum.SEK),
}),
}) })
const menuItemSchema = z.object({ const menuItemSchema = z.object({
name: z.string(), name: nullableStringValidator,
url: z.string().url(), url: nullableStringUrlValidator,
}) })
const daySchema = z.object({ export const openingHoursDetailsSchema = z.object({
alwaysOpen: z.boolean().default(false), alwaysOpen: z.boolean().default(false),
closingTime: z.string().default(""), closingTime: nullableStringValidator,
isClosed: z.boolean().default(false), isClosed: z.boolean().default(false),
openingTime: z.string().default(""), openingTime: nullableStringValidator,
sortOrder: z.number().int().default(0), sortOrder: nullableIntValidator,
})
export const openingHoursSchema = z.object({
friday: openingHoursDetailsSchema.optional(),
isActive: z.boolean().default(false),
monday: openingHoursDetailsSchema.optional(),
name: nullableStringValidator,
saturday: openingHoursDetailsSchema.optional(),
sunday: openingHoursDetailsSchema.optional(),
thursday: openingHoursDetailsSchema.optional(),
tuesday: openingHoursDetailsSchema.optional(),
wednesday: openingHoursDetailsSchema.optional(),
}) })
const openingDetailsSchema = z.object({ const openingDetailsSchema = z.object({
alternateOpeningHours: z.object({ alternateOpeningHours: openingHoursSchema.optional(),
isActive: z.boolean().default(false), openingHours: openingHoursSchema,
}), ordinary: openingHoursSchema.optional(),
openingHours: z.object({ weekends: openingHoursSchema.optional(),
friday: daySchema,
isActive: z.boolean().default(false),
monday: daySchema,
name: z.string().default(""),
saturday: daySchema,
sunday: daySchema,
thursday: daySchema,
tuesday: daySchema,
wednesday: daySchema,
}),
}) })
export const restaurantsSchema = z.object({ export const restaurantsSchema = z.object({
attributes: z.object({ attributes: z.object({
bookTableUrl: z.string().default(""), bookTableUrl: nullableStringValidator,
content: contentSchema, content: contentSchema,
// When using .email().default("") is not sufficent
// so .optional also needs to be chained
email: z.string().email().optional(), email: z.string().email().optional(),
externalBreakfast: externalBreakfastSchema, externalBreakfast: externalBreakfastSchema,
isPublished: z.boolean().default(false), isPublished: z.boolean().default(false),
menus: z.array(menuItemSchema).default([]), menus: z.array(menuItemSchema).default([]),
name: z.string().default(""), name: z.string().default(""),
openingDetails: z.array(openingDetailsSchema).default([]), openingDetails: z.array(openingDetailsSchema).default([]),
phoneNumber: z.string().optional(),
restaurantPage: z.boolean().default(false), restaurantPage: z.boolean().default(false),
specialAlerts: z.array(z.object({})).default([]), specialAlerts: specialAlertsSchema,
}), }),
id: z.string(), id: z.string(),
type: z.literal("restaurants"), type: z.literal("restaurants"),

View File

@@ -2,15 +2,17 @@ import { z } from "zod"
import { dt } from "@/lib/dt" import { dt } from "@/lib/dt"
import { nullableStringValidator } from "@/utils/zod/stringValidator"
import { AlertTypeEnum } from "@/types/enums/alert" import { AlertTypeEnum } from "@/types/enums/alert"
const specialAlertSchema = z.object({ const specialAlertSchema = z.object({
description: z.string().optional(), description: nullableStringValidator,
displayInBookingFlow: z.boolean(), displayInBookingFlow: z.boolean().default(false),
endDate: z.string().optional(), endDate: nullableStringValidator,
startDate: z.string().optional(), startDate: nullableStringValidator,
title: z.string().optional(), title: nullableStringValidator,
type: z.string(), type: nullableStringValidator,
}) })
export const specialAlertsSchema = z export const specialAlertsSchema = z

View File

@@ -5,17 +5,19 @@ import { productSchema } from "./product"
import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter" import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter"
export const roomConfigurationSchema = z.object({ export const roomConfigurationSchema = z.object({
features: z.array( features: z
z.object({ .array(
inventory: z.number(), z.object({
code: z.enum([ inventory: z.number(),
RoomPackageCodeEnum.PET_ROOM, code: z.enum([
RoomPackageCodeEnum.ALLERGY_ROOM, RoomPackageCodeEnum.PET_ROOM,
RoomPackageCodeEnum.ACCESSIBILITY_ROOM, RoomPackageCodeEnum.ALLERGY_ROOM,
]), RoomPackageCodeEnum.ACCESSIBILITY_ROOM,
}) ]),
), })
products: z.array(productSchema), )
.default([]),
products: z.array(productSchema).default([]),
roomsLeft: z.number(), roomsLeft: z.number(),
roomType: z.string(), roomType: z.string(),
roomTypeCode: z.string(), roomTypeCode: z.string(),

View File

@@ -4,17 +4,17 @@ import { calculateRoomSummary } from "./helper"
import type { import type {
RoomPackageCodeEnum, RoomPackageCodeEnum,
RoomPackageData, RoomPackages,
} from "@/types/components/hotelReservation/selectRate/roomFilter" } from "@/types/components/hotelReservation/selectRate/roomFilter"
import type { import type {
Rate, Rate,
RateCode, RateCode,
} from "@/types/components/hotelReservation/selectRate/selectRate" } from "@/types/components/hotelReservation/selectRate/selectRate"
import type { RoomConfiguration } from "@/server/routers/hotels/output" import type { RoomConfiguration } from "@/types/trpc/routers/hotel/roomAvailability"
export interface RateSummaryParams { export interface RateSummaryParams {
getFilteredRooms: (roomIndex: number) => RoomConfiguration[] getFilteredRooms: (roomIndex: number) => RoomConfiguration[]
availablePackages: RoomPackageData availablePackages: RoomPackages
roomCategories: Array<{ name: string; roomTypes: Array<{ code: string }> }> roomCategories: Array<{ name: string; roomTypes: Array<{ code: string }> }>
selectedPackagesByRoom: Record<number, RoomPackageCodeEnum[]> selectedPackagesByRoom: Record<number, RoomPackageCodeEnum[]>
} }

View File

@@ -10,7 +10,7 @@ import type {
import type { import type {
RoomConfiguration, RoomConfiguration,
RoomsAvailability, RoomsAvailability,
} from "@/server/routers/hotels/output" } from "@/types/trpc/routers/hotel/roomAvailability"
interface RoomFilteringState { interface RoomFilteringState {
selectedPackagesByRoom: Record<number, RoomPackageCodes[]> selectedPackagesByRoom: Record<number, RoomPackageCodes[]>

View File

@@ -1,3 +1,3 @@
import { passwordValidators } from "@/utils/passwordValidator" import type { passwordValidators } from "@/utils/zod/passwordValidator"
export type PasswordValidatorKey = keyof typeof passwordValidators export type PasswordValidatorKey = keyof typeof passwordValidators

View File

@@ -1,9 +1,5 @@
import type {
Hotel,
Restaurant,
RestaurantOpeningHours,
} from "@/types/hotel"
import type { ParkingAmenityProps } from "./parking" import type { ParkingAmenityProps } from "./parking"
import type { Hotel, Restaurant, RestaurantOpeningHours } from "@/types/hotel"
export type AmenitiesSidePeekProps = { export type AmenitiesSidePeekProps = {
amenitiesList: Hotel["detailedFacilities"] amenitiesList: Hotel["detailedFacilities"]

View File

@@ -8,7 +8,6 @@ import type {
import type { packagePriceSchema } from "@/server/routers/hotels/schemas/packages" import type { packagePriceSchema } from "@/server/routers/hotels/schemas/packages"
import type { RoomPriceSchema } from "./flexibilityOption" import type { RoomPriceSchema } from "./flexibilityOption"
import type { RoomPackageCodes, RoomPackages } from "./roomFilter" import type { RoomPackageCodes, RoomPackages } from "./roomFilter"
import type { RateCode } from "./selectRate"
export type RoomCardProps = { export type RoomCardProps = {
hotelId: string hotelId: string
@@ -19,7 +18,6 @@ export type RoomCardProps = {
selectedPackages: RoomPackageCodes[] selectedPackages: RoomPackageCodes[]
roomListIndex: number roomListIndex: number
packages: RoomPackages | undefined packages: RoomPackages | undefined
handleSelectRate: React.Dispatch<React.SetStateAction<RateCode | undefined>>
} }
type RoomPackagePriceSchema = z.output<typeof packagePriceSchema> type RoomPackagePriceSchema = z.output<typeof packagePriceSchema>

View File

@@ -1,17 +1,15 @@
import type { Room } from "@/types/hotel"
import type { RoomsAvailability } from "@/types/trpc/routers/hotel/roomAvailability"
import type { import type {
DefaultFilterOptions, DefaultFilterOptions,
RoomPackage,
RoomPackageCodes, RoomPackageCodes,
RoomPackages, RoomPackages,
} from "./roomFilter" } from "./roomFilter"
import type { Room } from "@/types/hotel"
import type { RoomsAvailability } from "@/types/trpc/routers/hotel/roomAvailability"
export interface RoomTypeListProps { export interface RoomTypeListProps {
roomsAvailability: RoomsAvailability roomsAvailability: RoomsAvailability
roomCategories: Room[] roomCategories: Room[]
availablePackages: RoomPackage | undefined availablePackages: RoomPackages | undefined
selectedPackages: RoomPackageCodes[] selectedPackages: RoomPackageCodes[]
hotelType: string | undefined hotelType: string | undefined
roomListIndex: number roomListIndex: number
@@ -27,7 +25,7 @@ export interface SelectRateProps {
export interface RoomSelectionPanelProps { export interface RoomSelectionPanelProps {
roomCategories: Room[] roomCategories: Room[]
availablePackages: RoomPackage[] availablePackages: RoomPackages
selectedPackages: RoomPackageCodes[] selectedPackages: RoomPackageCodes[]
hotelType: string | undefined hotelType: string | undefined
defaultPackages: DefaultFilterOptions[] defaultPackages: DefaultFilterOptions[]

8
types/enums/currency.ts Normal file
View File

@@ -0,0 +1,8 @@
export enum CurrencyEnum {
DKK = "DKK",
EUR = "EUR",
NOK = "NOK",
PLN = "PLN",
SEK = "SEK",
Unknown = "Unknown",
}

View File

@@ -7,18 +7,20 @@ import type { addressSchema } from "@/server/routers/hotels/schemas/hotel/addres
import type { hotelContentSchema } from "@/server/routers/hotels/schemas/hotel/content" import type { hotelContentSchema } from "@/server/routers/hotels/schemas/hotel/content"
import type { detailedFacilitiesSchema } from "@/server/routers/hotels/schemas/hotel/detailedFacility" import type { detailedFacilitiesSchema } from "@/server/routers/hotels/schemas/hotel/detailedFacility"
import type { checkinSchema } from "@/server/routers/hotels/schemas/hotel/facts" import type { checkinSchema } from "@/server/routers/hotels/schemas/hotel/facts"
import type { healthFacilitySchema } from "@/server/routers/hotels/schemas/hotel/healthFacilities"
import type { nearbyHotelsSchema } from "@/server/routers/hotels/schemas/hotel/include/nearbyHotels" import type { nearbyHotelsSchema } from "@/server/routers/hotels/schemas/hotel/include/nearbyHotels"
import type { restaurantsSchema } from "@/server/routers/hotels/schemas/hotel/include/restaurants" import type {
openingHoursDetailsSchema,
openingHoursSchema,
restaurantsSchema,
} from "@/server/routers/hotels/schemas/hotel/include/restaurants"
import type { transformRoomCategories } from "@/server/routers/hotels/schemas/hotel/include/roomCategories" import type { transformRoomCategories } from "@/server/routers/hotels/schemas/hotel/include/roomCategories"
import type { locationSchema } from "@/server/routers/hotels/schemas/hotel/location" import type { locationSchema } from "@/server/routers/hotels/schemas/hotel/location"
import type { parkingSchema } from "@/server/routers/hotels/schemas/hotel/parking" import type { parkingSchema } from "@/server/routers/hotels/schemas/hotel/parking"
import type { pointOfInterestSchema } from "@/server/routers/hotels/schemas/hotel/poi" import type { pointOfInterestSchema } from "@/server/routers/hotels/schemas/hotel/poi"
import type { ratingsSchema } from "@/server/routers/hotels/schemas/hotel/rating" import type { ratingsSchema } from "@/server/routers/hotels/schemas/hotel/rating"
import type { imageSchema } from "@/server/routers/hotels/schemas/image" import type { imageSchema } from "@/server/routers/hotels/schemas/image"
import { restaurantOpeningHoursSchema } from "@/server/routers/hotels/schemas/restaurants"
import { healthFacilitySchema } from "@/server/routers/hotels/schemas/hotel/healthFacilities"
import type { import type {
additionalDataSchema,
extraPageSchema, extraPageSchema,
facilitySchema, facilitySchema,
transformAdditionalData, transformAdditionalData,
@@ -45,9 +47,12 @@ export type NearbyHotel = Pick<NearbyHotelsSchema, "id" | "type"> &
export type Parking = z.output<typeof parkingSchema> export type Parking = z.output<typeof parkingSchema>
export type PointOfInterest = z.output<typeof pointOfInterestSchema> export type PointOfInterest = z.output<typeof pointOfInterestSchema>
type RestaurantSchema = z.output<typeof restaurantsSchema> type RestaurantSchema = z.output<typeof restaurantsSchema>
export type RestaurantOpeningHours = z.output<typeof restaurantOpeningHoursSchema>
export type Restaurant = Pick<RestaurantSchema, "id" | "type"> & export type Restaurant = Pick<RestaurantSchema, "id" | "type"> &
RestaurantSchema["attributes"] RestaurantSchema["attributes"]
export type RestaurantOpeningHours = z.output<typeof openingHoursSchema>
export type RestaurantOpeningHoursDay = z.output<
typeof openingHoursDetailsSchema
>
export type Room = ReturnType<typeof transformRoomCategories> export type Room = ReturnType<typeof transformRoomCategories>
export type HotelMapContentProps = { export type HotelMapContentProps = {

View File

@@ -7,3 +7,6 @@ import type { productTypePriceSchema } from "@/server/routers/hotels/schemas/pro
export type HotelsAvailability = z.output<typeof hotelsAvailabilitySchema> export type HotelsAvailability = z.output<typeof hotelsAvailabilitySchema>
export type ProductType = z.output<typeof productTypeSchema> export type ProductType = z.output<typeof productTypeSchema>
export type ProductTypePrices = z.output<typeof productTypePriceSchema> export type ProductTypePrices = z.output<typeof productTypePriceSchema>
export type HotelsAvailabilityItem =
HotelsAvailability["data"][number]["attributes"]

View File

@@ -0,0 +1,12 @@
import { z } from "zod"
export const nullableNumberValidator = z
.number()
.nullish()
.transform((num) => (typeof num === "number" ? num : 0))
export const nullableIntValidator = z
.number()
.int()
.nullish()
.transform((num) => (typeof num === "number" ? num : 0))

View File

@@ -0,0 +1,12 @@
import { z } from "zod"
export const nullableStringValidator = z
.string()
.nullish()
.transform((str) => (str ? str : ""))
export const nullableStringUrlValidator = z
.string()
.url()
.nullish()
.transform((str) => (str ? str : ""))