Merged in feat/sw-2864-move-hotels-router-to-trpc-package (pull request #2410)
feat (SW-2864): Move booking router to trpc package * Add env to trpc package * Add eslint to trpc package * Apply lint rules * Use direct imports from trpc package * Add lint-staged config to trpc * Move lang enum to common * Restructure trpc package folder structure * WIP first step * update internal imports in trpc * Fix most errors in scandic-web Just 100 left... * Move Props type out of trpc * Fix CategorizedFilters types * Move more schemas in hotel router * Fix deps * fix getNonContentstackUrls * Fix import error * Fix entry error handling * Fix generateMetadata metrics * Fix alertType enum * Fix duplicated types * lint:fix * Merge branch 'master' into feat/sw-2863-move-contentstack-router-to-trpc-package * Fix broken imports * Move booking router to trpc package * Merge branch 'master' into feat/sw-2864-move-hotels-router-to-trpc-package Approved-by: Linus Flood
This commit is contained in:
@@ -91,7 +91,6 @@ export const metadataQueryRouter = router({
|
||||
}
|
||||
|
||||
let data: unknown = null
|
||||
|
||||
switch (ctx.contentType) {
|
||||
case PageContentTypeEnum.accountPage:
|
||||
const accountPageResponse = await fetchMetadata<{
|
||||
|
||||
13
packages/trpc/lib/routers/hotels/helpers.ts
Normal file
13
packages/trpc/lib/routers/hotels/helpers.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { bedTypeMap } from "../../constants/bedTypeMap"
|
||||
|
||||
import type { Child } from "../../types/child"
|
||||
|
||||
export function generateChildrenString(children: Child[]): string {
|
||||
return `[${children
|
||||
.map((child) => {
|
||||
const age = child.age
|
||||
const bedType = bedTypeMap[parseInt(child.bed.toString())]
|
||||
return `${age}:${bedType}`
|
||||
})
|
||||
.join(",")}]`
|
||||
}
|
||||
4
packages/trpc/lib/routers/hotels/index.ts
Normal file
4
packages/trpc/lib/routers/hotels/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { mergeRouters } from "../.."
|
||||
import { hotelQueryRouter } from "./query"
|
||||
|
||||
export const hotelsRouter = mergeRouters(hotelQueryRouter)
|
||||
1183
packages/trpc/lib/routers/hotels/query.ts
Normal file
1183
packages/trpc/lib/routers/hotels/query.ts
Normal file
File diff suppressed because it is too large
Load Diff
49
packages/trpc/lib/routers/hotels/schemas/meetingRoom.ts
Normal file
49
packages/trpc/lib/routers/hotels/schemas/meetingRoom.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { imageSchema } from "@scandic-hotels/trpc/routers/hotels/schemas/image"
|
||||
|
||||
export const meetingRoomsSchema = z.object({
|
||||
data: z.array(
|
||||
z.object({
|
||||
attributes: z.object({
|
||||
name: z.string(),
|
||||
email: z.string().optional(),
|
||||
phoneNumber: z.string(),
|
||||
size: z.number(),
|
||||
doorWidth: z.number(),
|
||||
doorHeight: z.number(),
|
||||
length: z.number(),
|
||||
width: z.number(),
|
||||
height: z.number(),
|
||||
floorNumber: z.number(),
|
||||
content: z.object({
|
||||
images: z.array(imageSchema),
|
||||
texts: z.object({
|
||||
facilityInformation: z.string().optional(),
|
||||
surroundingInformation: z.string().optional(),
|
||||
descriptions: z.object({
|
||||
short: z.string().optional(),
|
||||
medium: z.string().optional(),
|
||||
}),
|
||||
meetingDescription: z
|
||||
.object({
|
||||
short: z.string().optional(),
|
||||
medium: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
}),
|
||||
}),
|
||||
seatings: z.array(
|
||||
z.object({
|
||||
type: z.string(),
|
||||
capacity: z.number(),
|
||||
})
|
||||
),
|
||||
lighting: z.string(),
|
||||
sortOrder: z.number().optional(),
|
||||
}),
|
||||
id: z.string(),
|
||||
type: z.string(),
|
||||
})
|
||||
),
|
||||
})
|
||||
@@ -1,17 +1,31 @@
|
||||
import deepmerge from "deepmerge"
|
||||
import stringify from "json-stable-stringify-without-jsonify"
|
||||
|
||||
import { Lang } from "@scandic-hotels/common/constants/language"
|
||||
import { selectRate } from "@scandic-hotels/common/constants/routes/hotelReservation"
|
||||
import { getCacheClient } from "@scandic-hotels/common/dataCache"
|
||||
import { createCounter } from "@scandic-hotels/common/telemetry"
|
||||
import { chunk } from "@scandic-hotels/common/utils/chunk"
|
||||
import {
|
||||
hotelsAvailabilitySchema,
|
||||
packagesSchema,
|
||||
roomFeaturesSchema,
|
||||
roomsAvailabilitySchema,
|
||||
} from "@scandic-hotels/trpc/routers/hotels/output"
|
||||
import { sortRoomConfigs } from "@scandic-hotels/trpc/utils/sortRoomConfigs"
|
||||
|
||||
import { env } from "../../../env/server"
|
||||
import * as api from "../../api"
|
||||
import { REDEMPTION } from "../../constants/booking"
|
||||
import { cache } from "../../DUPLICATED/cache"
|
||||
import { BookingErrorCodeEnum } from "../../enums/bookingErrorCode"
|
||||
import { HotelTypeEnum } from "../../enums/hotelType"
|
||||
import { RoomPackageCodeEnum } from "../../enums/roomFilter"
|
||||
import { AvailabilityEnum } from "../../enums/selectHotel"
|
||||
import { badRequestError } from "../../errors"
|
||||
import { toApiLang } from "../../utils"
|
||||
import { getHotelPageUrls } from "../contentstack/hotelPage/utils"
|
||||
import { generateChildrenString } from "./helpers"
|
||||
import {
|
||||
citiesByCountrySchema,
|
||||
citiesSchema,
|
||||
@@ -21,14 +35,32 @@ import {
|
||||
locationsSchema,
|
||||
} from "./output"
|
||||
|
||||
import type { Room as RoomCategory } from "@scandic-hotels/trpc/types/hotel"
|
||||
import type {
|
||||
Product,
|
||||
Products,
|
||||
RateDefinition,
|
||||
RedemptionsProduct,
|
||||
RoomConfiguration,
|
||||
} from "@scandic-hotels/trpc/types/roomAvailability"
|
||||
import type { z } from "zod"
|
||||
|
||||
import type { Endpoint } from "../../api/endpoints"
|
||||
import type {
|
||||
HotelsAvailabilityInputSchema,
|
||||
HotelsByHotelIdsAvailabilityInputSchema,
|
||||
RoomsAvailabilityExtendedInputSchema,
|
||||
RoomsAvailabilityInputRoom,
|
||||
RoomsAvailabilityOutputSchema,
|
||||
} from "../../types/availability"
|
||||
import type { BedTypeSelection } from "../../types/bedTypeSelection"
|
||||
import type { DestinationPagesHotelData, HotelInput } from "../../types/hotel"
|
||||
import type {
|
||||
CitiesGroupedByCountry,
|
||||
CityLocation,
|
||||
} from "../../types/locations"
|
||||
import type { PackagesOutput } from "../../types/packages"
|
||||
import type { RoomFeaturesInput } from "./input"
|
||||
import type { Cities } from "./output"
|
||||
|
||||
export const locationsAffix = "locations"
|
||||
@@ -594,3 +626,712 @@ export async function getCity({
|
||||
"1d"
|
||||
)
|
||||
}
|
||||
|
||||
export const TWENTYFOUR_HOURS = 60 * 60 * 24
|
||||
|
||||
function findProduct(product: Products, rateDefinition: RateDefinition) {
|
||||
if ("corporateCheque" in product) {
|
||||
return product.corporateCheque.rateCode === rateDefinition.rateCode
|
||||
}
|
||||
|
||||
if (("member" in product && product.member) || "public" in product) {
|
||||
let isMemberRate = false
|
||||
if (product.member) {
|
||||
isMemberRate = product.member.rateCode === rateDefinition.rateCode
|
||||
}
|
||||
let isPublicRate = false
|
||||
if (product.public) {
|
||||
isPublicRate = product.public.rateCode === rateDefinition.rateCode
|
||||
}
|
||||
return isMemberRate || isPublicRate
|
||||
}
|
||||
|
||||
if ("voucher" in product) {
|
||||
return product.voucher.rateCode === rateDefinition.rateCode
|
||||
}
|
||||
|
||||
if (Array.isArray(product)) {
|
||||
return product.find(
|
||||
(r) => r.redemption.rateCode === rateDefinition.rateCode
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getHotelsAvailabilityByCity(
|
||||
input: HotelsAvailabilityInputSchema,
|
||||
apiLang: string,
|
||||
token: string, // Either service token or user access token in case of redemption search
|
||||
userPoints: number = 0
|
||||
) {
|
||||
const {
|
||||
cityId,
|
||||
roomStayStartDate,
|
||||
roomStayEndDate,
|
||||
adults,
|
||||
children,
|
||||
bookingCode,
|
||||
redemption,
|
||||
} = input
|
||||
|
||||
const params: Record<string, string | number> = {
|
||||
roomStayStartDate,
|
||||
roomStayEndDate,
|
||||
adults,
|
||||
...(children && { children }),
|
||||
...(bookingCode && { bookingCode }),
|
||||
...(redemption ? { isRedemption: "true" } : {}),
|
||||
language: apiLang,
|
||||
}
|
||||
|
||||
const getHotelsAvailabilityByCityCounter = createCounter(
|
||||
"hotel",
|
||||
"getHotelsAvailabilityByCity"
|
||||
)
|
||||
const metricsGetHotelsAvailabilityByCity =
|
||||
getHotelsAvailabilityByCityCounter.init({
|
||||
apiLang,
|
||||
cityId,
|
||||
roomStayStartDate,
|
||||
roomStayEndDate,
|
||||
adults,
|
||||
children,
|
||||
bookingCode,
|
||||
redemption,
|
||||
})
|
||||
|
||||
metricsGetHotelsAvailabilityByCity.start()
|
||||
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v1.Availability.city(cityId),
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
params
|
||||
)
|
||||
if (!apiResponse.ok) {
|
||||
await metricsGetHotelsAvailabilityByCity.httpError(apiResponse)
|
||||
throw new Error("Failed to fetch hotels availability by city")
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const validateAvailabilityData = hotelsAvailabilitySchema.safeParse(apiJson)
|
||||
if (!validateAvailabilityData.success) {
|
||||
metricsGetHotelsAvailabilityByCity.validationError(
|
||||
validateAvailabilityData.error
|
||||
)
|
||||
throw badRequestError()
|
||||
}
|
||||
|
||||
if (redemption) {
|
||||
validateAvailabilityData.data.data.forEach((data) => {
|
||||
data.attributes.productType?.redemptions?.forEach((r) => {
|
||||
r.hasEnoughPoints = userPoints >= r.localPrice.pointsPerStay
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const result = {
|
||||
availability: validateAvailabilityData.data.data.flatMap(
|
||||
(hotels) => hotels.attributes
|
||||
),
|
||||
}
|
||||
|
||||
metricsGetHotelsAvailabilityByCity.success()
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
export async function getHotelsAvailabilityByHotelIds(
|
||||
input: HotelsByHotelIdsAvailabilityInputSchema,
|
||||
apiLang: string,
|
||||
serviceToken: string
|
||||
) {
|
||||
const {
|
||||
hotelIds,
|
||||
roomStayStartDate,
|
||||
roomStayEndDate,
|
||||
adults,
|
||||
children,
|
||||
bookingCode,
|
||||
} = input
|
||||
|
||||
const params = new URLSearchParams([
|
||||
["roomStayStartDate", roomStayStartDate],
|
||||
["roomStayEndDate", roomStayEndDate],
|
||||
["adults", adults.toString()],
|
||||
["children", children ?? ""],
|
||||
["bookingCode", bookingCode],
|
||||
["language", apiLang],
|
||||
])
|
||||
|
||||
const getHotelsAvailabilityByHotelIdsCounter = createCounter(
|
||||
"hotel",
|
||||
"getHotelsAvailabilityByHotelIds"
|
||||
)
|
||||
const metricsGetHotelsAvailabilityByHotelIds =
|
||||
getHotelsAvailabilityByHotelIdsCounter.init({
|
||||
apiLang,
|
||||
hotelIds,
|
||||
roomStayStartDate,
|
||||
roomStayEndDate,
|
||||
adults,
|
||||
children,
|
||||
bookingCode,
|
||||
})
|
||||
|
||||
metricsGetHotelsAvailabilityByHotelIds.start()
|
||||
|
||||
const cacheClient = await getCacheClient()
|
||||
|
||||
const result = cacheClient.cacheOrGet(
|
||||
`${apiLang}:hotels:availability:${hotelIds.join(",")}:${roomStayStartDate}:${roomStayEndDate}:${adults}:${children}:${bookingCode}`,
|
||||
async () => {
|
||||
/**
|
||||
* Since API expects the params appended and not just
|
||||
* a comma separated string we need to initialize the
|
||||
* SearchParams with a sequence of pairs
|
||||
* (hotelIds=810&hotelIds=879&hotelIds=222 etc.)
|
||||
**/
|
||||
|
||||
hotelIds.forEach((hotelId) =>
|
||||
params.append("hotelIds", hotelId.toString())
|
||||
)
|
||||
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v1.Availability.hotels(),
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${serviceToken}`,
|
||||
},
|
||||
},
|
||||
params
|
||||
)
|
||||
if (!apiResponse.ok) {
|
||||
await metricsGetHotelsAvailabilityByHotelIds.httpError(apiResponse)
|
||||
throw new Error("Failed to fetch hotels availability by hotelIds")
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const validateAvailabilityData =
|
||||
hotelsAvailabilitySchema.safeParse(apiJson)
|
||||
if (!validateAvailabilityData.success) {
|
||||
metricsGetHotelsAvailabilityByHotelIds.validationError(
|
||||
validateAvailabilityData.error
|
||||
)
|
||||
throw badRequestError()
|
||||
}
|
||||
|
||||
return {
|
||||
availability: validateAvailabilityData.data.data.flatMap(
|
||||
(hotels) => hotels.attributes
|
||||
),
|
||||
}
|
||||
},
|
||||
env.CACHE_TIME_CITY_SEARCH
|
||||
)
|
||||
|
||||
metricsGetHotelsAvailabilityByHotelIds.success()
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
async function getRoomFeaturesInventory(
|
||||
input: RoomFeaturesInput,
|
||||
token: string
|
||||
) {
|
||||
const {
|
||||
adults,
|
||||
childrenInRoom,
|
||||
endDate,
|
||||
hotelId,
|
||||
roomFeatureCodes,
|
||||
startDate,
|
||||
} = input
|
||||
|
||||
const params = {
|
||||
adults,
|
||||
hotelId,
|
||||
roomFeatureCode: roomFeatureCodes,
|
||||
roomStayEndDate: endDate,
|
||||
roomStayStartDate: startDate,
|
||||
...(childrenInRoom?.length && {
|
||||
children: generateChildrenString(childrenInRoom),
|
||||
}),
|
||||
}
|
||||
|
||||
const getRoomFeaturesInventoryCounter = createCounter(
|
||||
"hotel",
|
||||
"getRoomFeaturesInventory"
|
||||
)
|
||||
const metricsGetRoomFeaturesInventory =
|
||||
getRoomFeaturesInventoryCounter.init(params)
|
||||
|
||||
metricsGetRoomFeaturesInventory.start()
|
||||
|
||||
const cacheClient = await getCacheClient()
|
||||
|
||||
const result = cacheClient.cacheOrGet(
|
||||
stringify(input),
|
||||
async function () {
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v1.Availability.roomFeatures(hotelId),
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
params
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsGetRoomFeaturesInventory.httpError(apiResponse)
|
||||
return null
|
||||
}
|
||||
|
||||
const data = await apiResponse.json()
|
||||
const validatedRoomFeaturesData = roomFeaturesSchema.safeParse(data)
|
||||
if (!validatedRoomFeaturesData.success) {
|
||||
metricsGetRoomFeaturesInventory.validationError(
|
||||
validatedRoomFeaturesData.error
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
return validatedRoomFeaturesData.data
|
||||
},
|
||||
"5m"
|
||||
)
|
||||
|
||||
metricsGetRoomFeaturesInventory.success()
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
export async function getPackages(input: PackagesOutput, serviceToken: string) {
|
||||
const { adults, children, endDate, hotelId, lang, packageCodes, startDate } =
|
||||
input
|
||||
|
||||
const getPackagesCounter = createCounter("hotel", "getPackages")
|
||||
const metricsGetPackages = getPackagesCounter.init({
|
||||
input,
|
||||
})
|
||||
|
||||
metricsGetPackages.start()
|
||||
|
||||
const cacheClient = await getCacheClient()
|
||||
|
||||
const result = cacheClient.cacheOrGet(
|
||||
stringify(input),
|
||||
async function () {
|
||||
const apiLang = toApiLang(lang)
|
||||
|
||||
const searchParams = new URLSearchParams({
|
||||
adults: adults.toString(),
|
||||
children: children.toString(),
|
||||
endDate,
|
||||
language: apiLang,
|
||||
startDate,
|
||||
})
|
||||
|
||||
packageCodes.forEach((code) => {
|
||||
searchParams.append("packageCodes", code)
|
||||
})
|
||||
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v1.Package.Packages.hotel(hotelId),
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${serviceToken}`,
|
||||
},
|
||||
},
|
||||
searchParams
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsGetPackages.httpError(apiResponse)
|
||||
return null
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const validatedPackagesData = packagesSchema.safeParse(apiJson)
|
||||
if (!validatedPackagesData.success) {
|
||||
metricsGetPackages.validationError(validatedPackagesData.error)
|
||||
return null
|
||||
}
|
||||
|
||||
return validatedPackagesData.data
|
||||
},
|
||||
"3h"
|
||||
)
|
||||
|
||||
metricsGetPackages.success()
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
export async function getRoomsAvailability(
|
||||
input: RoomsAvailabilityOutputSchema,
|
||||
token: string,
|
||||
serviceToken: string,
|
||||
userPoints: number | undefined
|
||||
) {
|
||||
const {
|
||||
booking: { bookingCode, fromDate, hotelId, rooms, searchType, toDate },
|
||||
lang,
|
||||
} = input
|
||||
|
||||
const redemption = searchType === REDEMPTION
|
||||
|
||||
const getRoomsAvailabilityCounter = createCounter(
|
||||
"hotel",
|
||||
"getRoomsAvailability"
|
||||
)
|
||||
const metricsGetRoomsAvailability = getRoomsAvailabilityCounter.init({
|
||||
input,
|
||||
redemption,
|
||||
})
|
||||
|
||||
metricsGetRoomsAvailability.start()
|
||||
|
||||
const apiLang = toApiLang(lang)
|
||||
|
||||
const baseCacheKey = {
|
||||
bookingCode,
|
||||
fromDate,
|
||||
hotelId,
|
||||
lang,
|
||||
searchType,
|
||||
toDate,
|
||||
}
|
||||
|
||||
const cacheClient = await getCacheClient()
|
||||
const availabilityResponses = await Promise.allSettled(
|
||||
rooms.map((room: RoomsAvailabilityInputRoom) => {
|
||||
const cacheKey = {
|
||||
...baseCacheKey,
|
||||
room,
|
||||
}
|
||||
const result = cacheClient.cacheOrGet(
|
||||
stringify(cacheKey),
|
||||
async function () {
|
||||
{
|
||||
const params = {
|
||||
adults: room.adults,
|
||||
language: apiLang,
|
||||
roomStayStartDate: fromDate,
|
||||
roomStayEndDate: toDate,
|
||||
...(room.childrenInRoom?.length && {
|
||||
children: generateChildrenString(room.childrenInRoom),
|
||||
}),
|
||||
...(room.bookingCode && { bookingCode: room.bookingCode }),
|
||||
...(redemption && { isRedemption: "true" }),
|
||||
}
|
||||
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v1.Availability.hotel(hotelId),
|
||||
{
|
||||
cache: undefined, // overwrite default
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
params
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsGetRoomsAvailability.httpError(apiResponse)
|
||||
const text = await apiResponse.text()
|
||||
return { error: "http_error", details: text }
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const validateAvailabilityData =
|
||||
roomsAvailabilitySchema.safeParse(apiJson)
|
||||
if (!validateAvailabilityData.success) {
|
||||
metricsGetRoomsAvailability.validationError(
|
||||
validateAvailabilityData.error
|
||||
)
|
||||
|
||||
return {
|
||||
error: "validation_error",
|
||||
details: validateAvailabilityData.error,
|
||||
}
|
||||
}
|
||||
|
||||
if (redemption) {
|
||||
for (const roomConfig of validateAvailabilityData.data
|
||||
.roomConfigurations) {
|
||||
for (const product of roomConfig.redemptions) {
|
||||
if (userPoints) {
|
||||
product.redemption.hasEnoughPoints =
|
||||
userPoints >= product.redemption.localPrice.pointsPerStay
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const roomFeatures = await getPackages(
|
||||
{
|
||||
adults: room.adults,
|
||||
children: room.childrenInRoom?.length || 0,
|
||||
endDate: input.booking.toDate,
|
||||
hotelId: input.booking.hotelId,
|
||||
lang,
|
||||
packageCodes: [
|
||||
RoomPackageCodeEnum.ACCESSIBILITY_ROOM,
|
||||
RoomPackageCodeEnum.ALLERGY_ROOM,
|
||||
RoomPackageCodeEnum.PET_ROOM,
|
||||
],
|
||||
startDate: input.booking.fromDate,
|
||||
},
|
||||
serviceToken
|
||||
)
|
||||
|
||||
if (roomFeatures) {
|
||||
validateAvailabilityData.data.packages = roomFeatures
|
||||
}
|
||||
|
||||
// Fetch packages
|
||||
if (room.packages?.length) {
|
||||
const roomFeaturesInventory = await getRoomFeaturesInventory(
|
||||
{
|
||||
adults: room.adults,
|
||||
childrenInRoom: room.childrenInRoom,
|
||||
endDate: input.booking.toDate,
|
||||
hotelId: input.booking.hotelId,
|
||||
lang,
|
||||
roomFeatureCodes: room.packages,
|
||||
startDate: input.booking.fromDate,
|
||||
},
|
||||
serviceToken
|
||||
)
|
||||
|
||||
if (roomFeaturesInventory) {
|
||||
const features = roomFeaturesInventory.reduce<
|
||||
Record<string, number>
|
||||
>((fts, feat) => {
|
||||
fts[feat.roomTypeCode] = feat.features?.[0]?.inventory ?? 0
|
||||
return fts
|
||||
}, {})
|
||||
|
||||
const updatedRoomConfigurations =
|
||||
validateAvailabilityData.data.roomConfigurations
|
||||
// This filter is needed since we can get availability
|
||||
// back from roomFeatures yet the availability call
|
||||
// says there are no rooms left...
|
||||
.filter((rc) => rc.roomsLeft)
|
||||
.filter((rc) => features?.[rc.roomTypeCode])
|
||||
.map((rc) => ({
|
||||
...rc,
|
||||
roomsLeft: features[rc.roomTypeCode],
|
||||
status: AvailabilityEnum.Available,
|
||||
}))
|
||||
|
||||
validateAvailabilityData.data.roomConfigurations =
|
||||
updatedRoomConfigurations
|
||||
}
|
||||
}
|
||||
|
||||
return validateAvailabilityData.data
|
||||
}
|
||||
},
|
||||
"1m"
|
||||
)
|
||||
|
||||
return result
|
||||
})
|
||||
)
|
||||
|
||||
const data = availabilityResponses.map((availability) => {
|
||||
if (availability.status === "fulfilled") {
|
||||
return availability.value
|
||||
}
|
||||
return {
|
||||
details: availability.reason,
|
||||
error: "request_failure",
|
||||
}
|
||||
})
|
||||
|
||||
metricsGetRoomsAvailability.success()
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
export function getSelectedRoomAvailability(
|
||||
rateCode: string,
|
||||
rateDefinitions: RateDefinition[],
|
||||
roomConfigurations: RoomConfiguration[],
|
||||
roomTypeCode: string,
|
||||
userPoints: number | undefined
|
||||
) {
|
||||
const rateDefinition = rateDefinitions.find((rd) => rd.rateCode === rateCode)
|
||||
if (!rateDefinition) {
|
||||
return null
|
||||
}
|
||||
|
||||
const selectedRoom = roomConfigurations.find(
|
||||
(room) =>
|
||||
room.roomTypeCode === roomTypeCode &&
|
||||
room.products.find((product) => findProduct(product, rateDefinition))
|
||||
)
|
||||
|
||||
if (!selectedRoom) {
|
||||
return null
|
||||
}
|
||||
|
||||
let product: Product | RedemptionsProduct | undefined =
|
||||
selectedRoom.products.find((product) =>
|
||||
findProduct(product, rateDefinition)
|
||||
)
|
||||
|
||||
if (!product) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (Array.isArray(product)) {
|
||||
const redemptionProduct = userPoints
|
||||
? product.find(
|
||||
(r) =>
|
||||
r.redemption.rateCode === rateDefinition.rateCode &&
|
||||
r.redemption.localPrice.pointsPerStay <= userPoints
|
||||
)
|
||||
: undefined
|
||||
if (!redemptionProduct) {
|
||||
return null
|
||||
}
|
||||
product = redemptionProduct
|
||||
}
|
||||
|
||||
return {
|
||||
rateDefinition,
|
||||
rateDefinitions,
|
||||
rooms: roomConfigurations,
|
||||
product,
|
||||
selectedRoom,
|
||||
}
|
||||
}
|
||||
|
||||
export function getBedTypes(
|
||||
rooms: RoomConfiguration[],
|
||||
roomType: string,
|
||||
roomCategories?: RoomCategory[]
|
||||
) {
|
||||
if (!roomCategories) {
|
||||
return []
|
||||
}
|
||||
|
||||
return rooms
|
||||
.filter(
|
||||
(room) => room.status === AvailabilityEnum.Available || room.roomsLeft > 0
|
||||
)
|
||||
.filter((room) => room.roomType === roomType)
|
||||
.map((availRoom) => {
|
||||
const matchingRoom = roomCategories
|
||||
?.find((room) =>
|
||||
room.roomTypes
|
||||
.map((roomType) => roomType.code)
|
||||
.includes(availRoom.roomTypeCode)
|
||||
)
|
||||
?.roomTypes.find((roomType) => roomType.code === availRoom.roomTypeCode)
|
||||
|
||||
if (matchingRoom) {
|
||||
return {
|
||||
description: matchingRoom.description,
|
||||
size: matchingRoom.mainBed.widthRange,
|
||||
value: matchingRoom.code,
|
||||
type: matchingRoom.mainBed.type,
|
||||
roomsLeft: availRoom.roomsLeft,
|
||||
extraBed: matchingRoom.fixedExtraBed
|
||||
? {
|
||||
type: matchingRoom.fixedExtraBed.type,
|
||||
description: matchingRoom.fixedExtraBed.description,
|
||||
}
|
||||
: undefined,
|
||||
}
|
||||
}
|
||||
})
|
||||
.filter((bed): bed is BedTypeSelection => Boolean(bed))
|
||||
}
|
||||
|
||||
export function mergeRoomTypes(roomConfigurations: RoomConfiguration[]) {
|
||||
// Initial sort to guarantee if one bed is NotAvailable and whereas
|
||||
// the other is Available to make sure data is added to the correct
|
||||
// roomConfig
|
||||
roomConfigurations.sort(sortRoomConfigs)
|
||||
|
||||
const roomConfigs = new Map<string, RoomConfiguration>()
|
||||
for (const roomConfig of roomConfigurations) {
|
||||
if (roomConfigs.has(roomConfig.roomType)) {
|
||||
const currentRoomConf = roomConfigs.get(roomConfig.roomType)
|
||||
if (currentRoomConf) {
|
||||
currentRoomConf.features = roomConfig.features.reduce(
|
||||
(feats, feature) => {
|
||||
const currentFeatureIndex = feats.findIndex(
|
||||
(f) => f.code === feature.code
|
||||
)
|
||||
if (currentFeatureIndex !== -1) {
|
||||
feats[currentFeatureIndex].inventory =
|
||||
feats[currentFeatureIndex].inventory + feature.inventory
|
||||
} else {
|
||||
feats.push(feature)
|
||||
}
|
||||
return feats
|
||||
},
|
||||
currentRoomConf.features
|
||||
)
|
||||
currentRoomConf.roomsLeft =
|
||||
currentRoomConf.roomsLeft + roomConfig.roomsLeft
|
||||
roomConfigs.set(currentRoomConf.roomType, currentRoomConf)
|
||||
}
|
||||
} else {
|
||||
roomConfigs.set(roomConfig.roomType, roomConfig)
|
||||
}
|
||||
}
|
||||
return Array.from(roomConfigs.values())
|
||||
}
|
||||
|
||||
export function selectRateRedirectURL(
|
||||
input: RoomsAvailabilityExtendedInputSchema,
|
||||
selectedRooms: boolean[]
|
||||
) {
|
||||
const searchParams = new URLSearchParams({
|
||||
errorCode: BookingErrorCodeEnum.AvailabilityError,
|
||||
fromdate: input.booking.fromDate,
|
||||
hotel: input.booking.hotelId,
|
||||
todate: input.booking.toDate,
|
||||
})
|
||||
if (input.booking.searchType) {
|
||||
searchParams.set("searchtype", input.booking.searchType)
|
||||
}
|
||||
for (const [idx, room] of input.booking.rooms.entries()) {
|
||||
searchParams.set(`room[${idx}].adults`, room.adults.toString())
|
||||
|
||||
if (selectedRooms[idx]) {
|
||||
if (room.counterRateCode) {
|
||||
searchParams.set(`room[${idx}].counterratecode`, room.counterRateCode)
|
||||
}
|
||||
searchParams.set(`room[${idx}].ratecode`, room.rateCode)
|
||||
searchParams.set(`room[${idx}].roomtype`, room.roomTypeCode)
|
||||
} else {
|
||||
if (!searchParams.has("modifyRateIndex")) {
|
||||
searchParams.set("modifyRateIndex", idx.toString())
|
||||
}
|
||||
}
|
||||
if (room.bookingCode) {
|
||||
searchParams.set(`room[${idx}].bookingCode`, room.bookingCode)
|
||||
}
|
||||
if (room.packages) {
|
||||
searchParams.set(`room[${idx}].packages`, room.packages.join(","))
|
||||
}
|
||||
if (room.childrenInRoom?.length) {
|
||||
for (const [i, kid] of room.childrenInRoom.entries()) {
|
||||
searchParams.set(`room[${idx}].child[${i}].age`, kid.age.toString())
|
||||
searchParams.set(`room[${idx}].child[${i}].bed`, kid.bed.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return `${selectRate(input.lang)}?${searchParams.toString()}`
|
||||
}
|
||||
|
||||
47
packages/trpc/lib/routers/user/helpers.ts
Normal file
47
packages/trpc/lib/routers/user/helpers.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import type {
|
||||
Membership,
|
||||
NativeFriendsMembership,
|
||||
UserLoyalty,
|
||||
} from "../../types/user"
|
||||
|
||||
export enum scandicMembershipTypes {
|
||||
SCANDIC_NATIVE = "SCANDIC_NATIVE",
|
||||
SAS_EB = "SAS_EB",
|
||||
}
|
||||
|
||||
export function isScandicNativeMembership(
|
||||
membership: Membership
|
||||
): membership is NativeFriendsMembership {
|
||||
return membership.type === scandicMembershipTypes.SCANDIC_NATIVE
|
||||
}
|
||||
|
||||
export function getFriendsMembership(userLoyalty: UserLoyalty) {
|
||||
const { memberships, ...loyalty } = userLoyalty
|
||||
|
||||
const friendsMembership = memberships.find(isScandicNativeMembership)
|
||||
|
||||
if (!friendsMembership) return null
|
||||
|
||||
const pointExpiration = loyalty.pointExpirations
|
||||
.sort(
|
||||
(a, b) => new Date(a.expires).getTime() - new Date(b.expires).getTime()
|
||||
)
|
||||
.at(0)
|
||||
|
||||
// Map to the same format that was used with Profile V1 to avoid larger changes for now.
|
||||
const result = {
|
||||
membershipType: friendsMembership.type,
|
||||
membershipNumber: friendsMembership.membershipNumber,
|
||||
membershipLevel: loyalty.tier,
|
||||
nextLevel: friendsMembership.nextTier,
|
||||
currentPoints: loyalty.points.spendable,
|
||||
expirationDate: loyalty.tierExpires,
|
||||
nightsToTopTier: friendsMembership.nightsToTopTier,
|
||||
pointsRequiredToNextlevel: friendsMembership.pointsToNextTier,
|
||||
tierExpirationDate: loyalty.tierExpires,
|
||||
pointsExpiryDate: pointExpiration?.expires,
|
||||
pointsToExpire: pointExpiration?.points,
|
||||
memberSince: friendsMembership.memberSince,
|
||||
}
|
||||
return result
|
||||
}
|
||||
145
packages/trpc/lib/routers/user/output.ts
Normal file
145
packages/trpc/lib/routers/user/output.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { countriesMap } from "../../constants/countries"
|
||||
import { getFriendsMembership } from "./helpers"
|
||||
|
||||
const scandicFriendsTier = z.enum(["L1", "L2", "L3", "L4", "L5", "L6", "L7"])
|
||||
const sasEurobonusTier = z.enum(["EBB", "EBS", "EBG", "EBD", "EBP"])
|
||||
|
||||
const commonMembershipSchema = z.object({
|
||||
membershipNumber: z.string(),
|
||||
tierExpires: z.string().nullish().default(null),
|
||||
memberSince: z.string().nullish(),
|
||||
})
|
||||
|
||||
// This prevents validation errors if the API returns an unhandled membership type
|
||||
const otherMembershipSchema = z
|
||||
.object({
|
||||
// This ensures that `type` won't widen into "string", losing the literal types, when used in a union
|
||||
type: z.string().refine((val): val is string & {} => true),
|
||||
})
|
||||
.merge(commonMembershipSchema)
|
||||
|
||||
export const sasMembershipSchema = z
|
||||
.object({
|
||||
type: z.literal("SAS_EB"),
|
||||
tier: sasEurobonusTier,
|
||||
nextTier: sasEurobonusTier.nullish(),
|
||||
spendablePoints: z.number().nullish(),
|
||||
boostedByScandic: z.boolean().nullish(),
|
||||
boostedTier: sasEurobonusTier.nullish(),
|
||||
boostedTierExpires: z.string().nullish().default(null),
|
||||
})
|
||||
.merge(commonMembershipSchema)
|
||||
.transform((response) => {
|
||||
return {
|
||||
...response,
|
||||
tierExpires:
|
||||
// SAS API returns 1900-01-01 for non-expiring tiers
|
||||
response.tierExpires === "1900-01-01" ? null : response.tierExpires,
|
||||
}
|
||||
})
|
||||
|
||||
export const friendsMembershipSchema = z
|
||||
.object({
|
||||
type: z.literal("SCANDIC_NATIVE"),
|
||||
tier: scandicFriendsTier,
|
||||
nextTier: scandicFriendsTier.nullish(),
|
||||
pointsToNextTier: z.number().nullish(),
|
||||
nightsToTopTier: z.number().nullish(),
|
||||
})
|
||||
.merge(commonMembershipSchema)
|
||||
|
||||
export const membershipSchema = z.union([
|
||||
friendsMembershipSchema,
|
||||
sasMembershipSchema,
|
||||
otherMembershipSchema,
|
||||
])
|
||||
|
||||
const pointExpirationSchema = z.object({
|
||||
points: z.number().int(),
|
||||
expires: z.string(),
|
||||
})
|
||||
|
||||
export const userLoyaltySchema = z.object({
|
||||
memberships: z.array(membershipSchema),
|
||||
points: z.object({
|
||||
spendable: z.number().int(),
|
||||
earned: z.number().int(),
|
||||
spent: z.number().int(),
|
||||
}),
|
||||
tier: scandicFriendsTier,
|
||||
tierExpires: z.string(),
|
||||
tierBoostedBy: z.string().nullish(),
|
||||
pointExpirations: z.array(pointExpirationSchema),
|
||||
})
|
||||
|
||||
export const getUserSchema = z
|
||||
.object({
|
||||
data: z.object({
|
||||
attributes: z.object({
|
||||
dateOfBirth: z.string().optional().default("1900-01-01"),
|
||||
email: z.string().email(),
|
||||
firstName: z.string(),
|
||||
language: z
|
||||
.string()
|
||||
// Preserve Profile v1 formatting for now so it matches ApiLang enum
|
||||
.transform((s) => s.charAt(0).toUpperCase() + s.slice(1))
|
||||
.optional(),
|
||||
lastName: z.string(),
|
||||
phoneNumber: z.string().optional(),
|
||||
profileId: z.string(),
|
||||
membershipNumber: z.string(),
|
||||
address: z
|
||||
.object({
|
||||
city: z.string().optional(),
|
||||
country: z.string().optional(),
|
||||
countryCode: z.nativeEnum(countriesMap).optional(),
|
||||
streetAddress: z.string().optional(),
|
||||
zipCode: z.string().optional(),
|
||||
})
|
||||
.optional()
|
||||
.nullable(),
|
||||
loyalty: userLoyaltySchema.optional(),
|
||||
}),
|
||||
type: z.string(),
|
||||
}),
|
||||
})
|
||||
.transform((apiResponse) => {
|
||||
return {
|
||||
...apiResponse.data.attributes,
|
||||
membership: apiResponse.data.attributes.loyalty
|
||||
? getFriendsMembership(apiResponse.data.attributes.loyalty)
|
||||
: null,
|
||||
name: `${apiResponse.data.attributes.firstName} ${apiResponse.data.attributes.lastName}`,
|
||||
}
|
||||
})
|
||||
|
||||
export const creditCardSchema = z
|
||||
.object({
|
||||
attribute: z.object({
|
||||
cardName: z.string().optional(),
|
||||
alias: z.string(),
|
||||
truncatedNumber: z.string().transform((s) => s.slice(-4)),
|
||||
expirationDate: z.string(),
|
||||
cardType: z
|
||||
.string()
|
||||
.transform((s) => s.charAt(0).toLowerCase() + s.slice(1)),
|
||||
}),
|
||||
id: z.string(),
|
||||
type: z.string(),
|
||||
})
|
||||
.transform((apiResponse) => {
|
||||
return {
|
||||
id: apiResponse.id,
|
||||
type: apiResponse.attribute.cardType,
|
||||
truncatedNumber: apiResponse.attribute.truncatedNumber,
|
||||
alias: apiResponse.attribute.alias,
|
||||
expirationDate: apiResponse.attribute.expirationDate,
|
||||
cardType: apiResponse.attribute.cardType,
|
||||
}
|
||||
})
|
||||
|
||||
export const creditCardsSchema = z.object({
|
||||
data: z.array(creditCardSchema),
|
||||
})
|
||||
79
packages/trpc/lib/routers/user/utils.ts
Normal file
79
packages/trpc/lib/routers/user/utils.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { createCounter } from "@scandic-hotels/common/telemetry"
|
||||
|
||||
import * as api from "../../api"
|
||||
import { cache } from "../../DUPLICATED/cache"
|
||||
import { getUserSchema } from "./output"
|
||||
|
||||
import type { Session } from "next-auth"
|
||||
|
||||
export const getVerifiedUser = cache(
|
||||
async ({
|
||||
session,
|
||||
includeExtendedPartnerData,
|
||||
}: {
|
||||
session: Session
|
||||
includeExtendedPartnerData?: boolean
|
||||
}) => {
|
||||
const getVerifiedUserCounter = createCounter("user", "getVerifiedUser")
|
||||
const metricsGetVerifiedUser = getVerifiedUserCounter.init()
|
||||
|
||||
metricsGetVerifiedUser.start()
|
||||
|
||||
const now = Date.now()
|
||||
if (session.token.expires_at && session.token.expires_at < now) {
|
||||
metricsGetVerifiedUser.dataError(`Token expired`)
|
||||
return { error: true, cause: "token_expired" } as const
|
||||
}
|
||||
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v2.Profile.profile,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${session.token.access_token}`,
|
||||
},
|
||||
},
|
||||
includeExtendedPartnerData
|
||||
? { includes: "extendedPartnerInformation" }
|
||||
: {}
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsGetVerifiedUser.httpError(apiResponse)
|
||||
|
||||
if (apiResponse.status === 401) {
|
||||
return { error: true, cause: "unauthorized" } as const
|
||||
} else if (apiResponse.status === 403) {
|
||||
return { error: true, cause: "forbidden" } as const
|
||||
} else if (apiResponse.status === 404) {
|
||||
return { error: true, cause: "notfound" } as const
|
||||
}
|
||||
|
||||
return {
|
||||
error: true,
|
||||
cause: "unknown",
|
||||
status: apiResponse.status,
|
||||
} as const
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
if (!apiJson.data?.attributes) {
|
||||
metricsGetVerifiedUser.dataError(
|
||||
`Missing data attributes in API response`,
|
||||
{
|
||||
data: apiJson,
|
||||
}
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
const verifiedData = getUserSchema.safeParse(apiJson)
|
||||
if (!verifiedData.success) {
|
||||
metricsGetVerifiedUser.validationError(verifiedData.error)
|
||||
return null
|
||||
}
|
||||
|
||||
metricsGetVerifiedUser.success()
|
||||
|
||||
return verifiedData
|
||||
}
|
||||
)
|
||||
Reference in New Issue
Block a user