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"
import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter"
import type { SelectRateSearchParams } from "@/types/components/hotelReservation/selectRate/selectRate"
import { CurrencyEnum } from "@/types/enums/currency"
import { PackageTypeEnum } from "@/types/enums/packages"
import type { RoomPrice, RoomRate } from "@/types/stores/enter-details"
@@ -47,12 +48,12 @@ export const roomRate: RoomRate = {
localPrice: {
pricePerNight: 1508,
pricePerStay: 1508,
currency: "SEK",
currency: CurrencyEnum.SEK,
},
requestedPrice: {
pricePerNight: 132,
pricePerStay: 132,
currency: "EUR",
currency: CurrencyEnum.EUR,
},
},
publicRate: {
@@ -60,12 +61,12 @@ export const roomRate: RoomRate = {
localPrice: {
pricePerNight: 1525,
pricePerStay: 1525,
currency: "SEK",
currency: CurrencyEnum.SEK,
},
requestedPrice: {
pricePerNight: 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 { countriesMap } from "@/components/TempDesignSystem/Form/Country/countries"
import { getIntl } from "@/i18n"
import { phoneValidator } from "@/utils/phoneValidator"
import { getMembership } from "@/utils/user"
import { phoneValidator } from "@/utils/zod/phoneValidator"
import { Status } from "@/types/components/myPages/myProfile/edit"

View File

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

View File

@@ -15,7 +15,7 @@ import type {
CategorizedFilters,
Filter,
} 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 = [
"Hotel surroundings",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,7 +2,7 @@ import { z } from "zod"
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.
const stringMatcher =

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -7,7 +7,7 @@ import { productTypeSchema } from "./schemas/availability/productType"
import { citySchema } from "./schemas/city"
import {
attributesSchema,
includesSchema,
includedSchema,
relationshipsSchema as hotelRelationshipsSchema,
} from "./schemas/hotel"
import { locationCitySchema } from "./schemas/location/city"
@@ -18,7 +18,13 @@ import { relationshipsSchema } from "./schemas/relationships"
import { roomConfigurationSchema } from "./schemas/roomAvailability/configuration"
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
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
// additional data for an individual hotel.
included: includesSchema,
included: includedSchema,
})
.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 nearbyHotels = included.filter(
(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 { env } from "@/env/server"
import * as api from "@/lib/api"
import { dt } from "@/lib/dt"
import { badRequestError } from "@/server/errors/trpc"
@@ -15,6 +18,8 @@ import { cache } from "@/utils/cache"
import { getHotelPageUrl } from "../contentstack/hotelPage/utils"
import { getVerifiedUser, parsedUser } from "../user/query"
import { additionalDataSchema } from "./schemas/additionalData"
import { meetingRoomsSchema } from "./schemas/meetingRoom"
import {
breakfastPackageInputSchema,
cityCoordinatesInputSchema,
@@ -54,133 +59,144 @@ import type { BedTypeSelection } from "@/types/components/hotelReservation/enter
import { BreakfastPackageEnum } from "@/types/enums/breakfast"
import { HotelTypeEnum } from "@/types/enums/hotelType"
import type { RequestOptionsWithOutBody } from "@/types/fetch"
import type { HotelInput } from "@/types/trpc/routers/hotel/hotel"
import type { HotelData } from "@/types/hotel"
import type { HotelPageUrl } from "@/types/trpc/routers/contentstack/hotelPage"
import { CityLocation } from "@/types/trpc/routers/hotel/locations"
import { meetingRoomsSchema } from "./schemas/meetingRoom"
import { env } from "@/env/server"
import { additionalDataSchema } from "./schemas/additionalData"
import type { HotelInput } from "@/types/trpc/routers/hotel/hotel"
import type { CityLocation } from "@/types/trpc/routers/hotel/locations"
export const getHotel = cache(
async (input: HotelInput, serviceToken: string) => {
const { hotelId, isCardOnlyPayment, language } = input
/**
* Since API expects the params appended and not just
* a comma separated string we need to initialize the
* SearchParams with a sequence of pairs
* (include=City&include=NearbyHotels&include=Restaurants etc.)
**/
const params = new URLSearchParams([
["hotelId", hotelId],
["include", "AdditionalData"],
["include", "City"],
["include", "NearbyHotels"],
["include", "Restaurants"],
["include", "RoomCategories"],
["language", toApiLang(language)],
])
metrics.hotel.counter.add(1, {
hotelId,
language,
})
console.info(
"api.hotels.hotelData start",
JSON.stringify({ query: { hotelId, params } })
)
const callable = unstable_cache(
async function (
hotelId: HotelInput["hotelId"],
language: HotelInput["language"],
isCardOnlyPayment?: HotelInput["isCardOnlyPayment"]
) {
/**
* Since API expects the params appended and not just
* a comma separated string we need to initialize the
* SearchParams with a sequence of pairs
* (include=City&include=NearbyHotels&include=Restaurants etc.)
**/
const params = new URLSearchParams([
["include", "AdditionalData"],
["include", "City"],
["include", "NearbyHotels"],
["include", "Restaurants"],
["include", "RoomCategories"],
["language", toApiLang(language)],
])
metrics.hotel.counter.add(1, {
hotelId,
language,
})
console.info(
"api.hotels.hotelData start",
JSON.stringify({ query: { hotelId, params } })
)
const apiResponse = await api.get(
api.endpoints.v1.Hotel.Hotels.hotel(hotelId),
{
headers: {
Authorization: `Bearer ${serviceToken}`,
},
// needs to clear default option as only
// cache or next.revalidate is permitted
cache: undefined,
next: {
revalidate: env.CACHE_TIME_HOTELDATA,
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,
const apiResponse = await api.get(
api.endpoints.v1.Hotel.Hotels.hotel(hotelId),
{
headers: {
Authorization: `Bearer ${serviceToken}`,
},
// needs to clear default option as only
// cache or next.revalidate is permitted
cache: undefined,
next: {
revalidate: env.CACHE_TIME_HOTELS,
tags: [`${language}:hotel:${hotelId}`],
},
},
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,
})
)
return null
}
console.info(
"api.hotels.hotelData success",
JSON.stringify({
query: { hotelId, params: params },
})
)
const hotelData = validateHotelData.data
const apiJson = await apiResponse.json()
const validateHotelData = hotelSchema.safeParse(apiJson)
if (isCardOnlyPayment) {
hotelData.hotel.merchantInformationData.alternatePaymentOptions = []
}
if (!validateHotelData.success) {
metrics.hotel.fail.add(1, {
hotelId,
language,
error_type: "validation_error",
error: JSON.stringify(validateHotelData.error),
})
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
}
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(
"api.hotels.hotelData success",
JSON.stringify({
query: { hotelId, params: params },
})
return hotelData
},
[`${input.language}:hotel:${input.hotelId}:${!!input.isCardOnlyPayment}`],
{
revalidate: env.CACHE_TIME_HOTELS,
tags: [
`${input.language}:hotel:${input.hotelId}:${!!input.isCardOnlyPayment}`,
],
}
)
const hotelData = validateHotelData.data
if (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
return callable(input.hotelId, input.language, input.isCardOnlyPayment)
}
)
@@ -731,9 +747,9 @@ export const hotelQueryRouter = router({
type: matchingRoom.mainBed.type,
extraBed: matchingRoom.fixedExtraBed
? {
type: matchingRoom.fixedExtraBed.type,
description: matchingRoom.fixedExtraBed.description,
}
type: matchingRoom.fixedExtraBed.type,
description: matchingRoom.fixedExtraBed.description,
}
: undefined,
}
}
@@ -861,7 +877,10 @@ export const hotelQueryRouter = router({
}
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
if (!cityId) {
@@ -973,7 +992,10 @@ export const hotelQueryRouter = router({
const hotels = await Promise.all(
hotelsToFetch.map(async (hotelId) => {
const [hotelData, url] = await Promise.all([
getHotel({ hotelId, language }, ctx.serviceToken),
getHotel(
{ hotelId, isCardOnlyPayment: false, language },
ctx.serviceToken
),
getHotelPageUrl(language, hotelId),
])
@@ -1000,7 +1022,8 @@ export const hotelQueryRouter = router({
)
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}`,
},
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({
adults: z.number(),
children: z.array(childrenSchema),
children: z.array(childrenSchema).default([]),
})

View File

@@ -1,5 +1,7 @@
import { z } from "zod"
import { nullableNumberValidator } from "@/utils/zod/numberValidator"
import { addressSchema } from "./hotel/address"
import { contactInformationSchema } from "./hotel/contactInformation"
import { hotelContentSchema } from "./hotel/content"
@@ -17,8 +19,8 @@ import { rewardNightSchema } from "./hotel/rewardNight"
import { socialMediaSchema } from "./hotel/socialMedia"
import { specialAlertsSchema } from "./hotel/specialAlerts"
import { specialNeedGroupSchema } from "./hotel/specialNeedGroups"
import { imageSchema } from "./image"
import { facilitySchema } from "./additionalData"
import { imageSchema } from "./image"
export const attributesSchema = z.object({
accessibilityElevatorPitchText: z.string().optional(),
@@ -51,13 +53,23 @@ export const attributesSchema = z.object({
socialMedia: socialMediaSchema,
specialAlerts: specialAlertsSchema,
specialNeedGroups: z.array(specialNeedGroupSchema),
vat: z.number(),
vat: nullableNumberValidator,
})
export const includesSchema = z
export const includedSchema = z
.array(includeSchema)
.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({
links: z.object({

View File

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

View File

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

View File

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

View File

@@ -4,17 +4,17 @@ import { calculateRoomSummary } from "./helper"
import type {
RoomPackageCodeEnum,
RoomPackageData,
RoomPackages,
} from "@/types/components/hotelReservation/selectRate/roomFilter"
import type {
Rate,
RateCode,
} 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 {
getFilteredRooms: (roomIndex: number) => RoomConfiguration[]
availablePackages: RoomPackageData
availablePackages: RoomPackages
roomCategories: Array<{ name: string; roomTypes: Array<{ code: string }> }>
selectedPackagesByRoom: Record<number, RoomPackageCodeEnum[]>
}

View File

@@ -10,7 +10,7 @@ import type {
import type {
RoomConfiguration,
RoomsAvailability,
} from "@/server/routers/hotels/output"
} from "@/types/trpc/routers/hotel/roomAvailability"
interface RoomFilteringState {
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

View File

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

View File

@@ -8,7 +8,6 @@ import type {
import type { packagePriceSchema } from "@/server/routers/hotels/schemas/packages"
import type { RoomPriceSchema } from "./flexibilityOption"
import type { RoomPackageCodes, RoomPackages } from "./roomFilter"
import type { RateCode } from "./selectRate"
export type RoomCardProps = {
hotelId: string
@@ -19,7 +18,6 @@ export type RoomCardProps = {
selectedPackages: RoomPackageCodes[]
roomListIndex: number
packages: RoomPackages | undefined
handleSelectRate: React.Dispatch<React.SetStateAction<RateCode | undefined>>
}
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 {
DefaultFilterOptions,
RoomPackage,
RoomPackageCodes,
RoomPackages,
} from "./roomFilter"
import type { Room } from "@/types/hotel"
import type { RoomsAvailability } from "@/types/trpc/routers/hotel/roomAvailability"
export interface RoomTypeListProps {
roomsAvailability: RoomsAvailability
roomCategories: Room[]
availablePackages: RoomPackage | undefined
availablePackages: RoomPackages | undefined
selectedPackages: RoomPackageCodes[]
hotelType: string | undefined
roomListIndex: number
@@ -27,7 +25,7 @@ export interface SelectRateProps {
export interface RoomSelectionPanelProps {
roomCategories: Room[]
availablePackages: RoomPackage[]
availablePackages: RoomPackages
selectedPackages: RoomPackageCodes[]
hotelType: string | undefined
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 { detailedFacilitiesSchema } from "@/server/routers/hotels/schemas/hotel/detailedFacility"
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 { 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 { locationSchema } from "@/server/routers/hotels/schemas/hotel/location"
import type { parkingSchema } from "@/server/routers/hotels/schemas/hotel/parking"
import type { pointOfInterestSchema } from "@/server/routers/hotels/schemas/hotel/poi"
import type { ratingsSchema } from "@/server/routers/hotels/schemas/hotel/rating"
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 {
additionalDataSchema,
extraPageSchema,
facilitySchema,
transformAdditionalData,
@@ -45,9 +47,12 @@ export type NearbyHotel = Pick<NearbyHotelsSchema, "id" | "type"> &
export type Parking = z.output<typeof parkingSchema>
export type PointOfInterest = z.output<typeof pointOfInterestSchema>
type RestaurantSchema = z.output<typeof restaurantsSchema>
export type RestaurantOpeningHours = z.output<typeof restaurantOpeningHoursSchema>
export type Restaurant = Pick<RestaurantSchema, "id" | "type"> &
RestaurantSchema["attributes"]
export type RestaurantOpeningHours = z.output<typeof openingHoursSchema>
export type RestaurantOpeningHoursDay = z.output<
typeof openingHoursDetailsSchema
>
export type Room = ReturnType<typeof transformRoomCategories>
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 ProductType = z.output<typeof productTypeSchema>
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 : ""))