Merged in monorepo-step-1 (pull request #1080)
Migrate to a monorepo setup - step 1 * Move web to subfolder /apps/scandic-web * Yarn + transitive deps - Move to yarn - design-system package removed for now since yarn doesn't support the parameter for token (ie project currently broken) - Add missing transitive dependencies as Yarn otherwise prevents these imports - VS Code doesn't pick up TS path aliases unless you open /apps/scandic-web instead of root (will be fixed with monorepo) * Pin framer-motion to temporarily fix typing issue https://github.com/adobe/react-spectrum/issues/7494 * Pin zod to avoid typ error There seems to have been a breaking change in the types returned by zod where error is now returned as undefined instead of missing in the type. We should just handle this but to avoid merge conflicts just pin the dependency for now. * Pin react-intl version Pin version of react-intl to avoid tiny type issue where formatMessage does not accept a generic any more. This will be fixed in a future commit, but to avoid merge conflicts just pin for now. * Pin typescript version Temporarily pin version as newer versions as stricter and results in a type error. Will be fixed in future commit after merge. * Setup workspaces * Add design-system as a monorepo package * Remove unused env var DESIGN_SYSTEM_ACCESS_TOKEN * Fix husky for monorepo setup * Update netlify.toml * Add lint script to root package.json * Add stub readme * Fix react-intl formatMessage types * Test netlify.toml in root * Remove root toml * Update netlify.toml publish path * Remove package-lock.json * Update build for branch/preview builds Approved-by: Linus Flood
This commit is contained in:
committed by
Linus Flood
parent
667cab6fb6
commit
80100e7631
5
apps/scandic-web/server/routers/hotels/index.ts
Normal file
5
apps/scandic-web/server/routers/hotels/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { mergeRouters } from "@/server/trpc"
|
||||
|
||||
import { hotelQueryRouter } from "./query"
|
||||
|
||||
export const hotelsRouter = mergeRouters(hotelQueryRouter)
|
||||
142
apps/scandic-web/server/routers/hotels/input.ts
Normal file
142
apps/scandic-web/server/routers/hotels/input.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { Lang } from "@/constants/languages"
|
||||
|
||||
import { ChildBedMapEnum } from "@/types/components/bookingWidget/enums"
|
||||
import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter"
|
||||
import { Country } from "@/types/enums/country"
|
||||
|
||||
export const hotelsAvailabilityInputSchema = z.object({
|
||||
cityId: z.string(),
|
||||
roomStayStartDate: z.string(),
|
||||
roomStayEndDate: z.string(),
|
||||
adults: z.number(),
|
||||
children: z.string().optional(),
|
||||
bookingCode: z.string().optional().default(""),
|
||||
})
|
||||
|
||||
export const getHotelsByHotelIdsAvailabilityInputSchema = z.object({
|
||||
hotelIds: z.array(z.number()),
|
||||
roomStayStartDate: z.string(),
|
||||
roomStayEndDate: z.string(),
|
||||
adults: z.number(),
|
||||
children: z.string().optional(),
|
||||
bookingCode: z.string().optional().default(""),
|
||||
})
|
||||
|
||||
export const roomsCombinedAvailabilityInputSchema = z.object({
|
||||
hotelId: z.number(),
|
||||
roomStayStartDate: z.string(),
|
||||
roomStayEndDate: z.string(),
|
||||
uniqueAdultsCount: z.array(z.number()),
|
||||
childArray: z
|
||||
.array(
|
||||
z.object({
|
||||
bed: z.nativeEnum(ChildBedMapEnum),
|
||||
age: z.number(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
bookingCode: z.string().optional(),
|
||||
rateCode: z.string().optional(),
|
||||
lang: z.nativeEnum(Lang),
|
||||
})
|
||||
|
||||
export const selectedRoomAvailabilityInputSchema = z.object({
|
||||
hotelId: z.string(),
|
||||
roomStayStartDate: z.string(),
|
||||
roomStayEndDate: z.string(),
|
||||
adults: z.number(),
|
||||
children: z.string().optional(),
|
||||
bookingCode: z.string().optional(),
|
||||
rateCode: z.string(),
|
||||
roomTypeCode: z.string(),
|
||||
packageCodes: z.array(z.nativeEnum(RoomPackageCodeEnum)).optional(),
|
||||
})
|
||||
|
||||
export type GetSelectedRoomAvailabilityInput = z.input<
|
||||
typeof selectedRoomAvailabilityInputSchema
|
||||
>
|
||||
|
||||
export const ratesInputSchema = z.object({
|
||||
hotelId: z.string(),
|
||||
})
|
||||
|
||||
export const hotelInputSchema = z.object({
|
||||
hotelId: z.string(),
|
||||
isCardOnlyPayment: z.boolean(),
|
||||
language: z.nativeEnum(Lang),
|
||||
})
|
||||
|
||||
export const getHotelsByCSFilterInput = z.object({
|
||||
locationFilter: z
|
||||
.object({
|
||||
city: z.string().nullable(),
|
||||
country: z.nativeEnum(Country).nullable(),
|
||||
excluded: z.array(z.string()),
|
||||
})
|
||||
.nullable(),
|
||||
hotelsToInclude: z.array(z.string()),
|
||||
})
|
||||
export interface GetHotelsByCSFilterInput
|
||||
extends z.infer<typeof getHotelsByCSFilterInput> {}
|
||||
|
||||
export const nearbyHotelIdsInput = z.object({
|
||||
hotelId: z.string(),
|
||||
})
|
||||
|
||||
export const breakfastPackageInputSchema = z.object({
|
||||
adults: z.number().min(1, { message: "at least one adult is required" }),
|
||||
fromDate: z
|
||||
.string()
|
||||
.min(1, { message: "fromDate is required" })
|
||||
.pipe(z.coerce.date()),
|
||||
hotelId: z.string().min(1, { message: "hotelId is required" }),
|
||||
toDate: z
|
||||
.string()
|
||||
.min(1, { message: "toDate is required" })
|
||||
.pipe(z.coerce.date()),
|
||||
})
|
||||
|
||||
export const ancillaryPackageInputSchema = z.object({
|
||||
fromDate: z
|
||||
.string()
|
||||
.min(1, { message: "fromDate is required" })
|
||||
.pipe(z.coerce.date()),
|
||||
hotelId: z.string().min(1, { message: "hotelId is required" }),
|
||||
toDate: z.string().pipe(z.coerce.date()).optional(),
|
||||
})
|
||||
|
||||
export const roomPackagesInputSchema = z.object({
|
||||
hotelId: z.string(),
|
||||
startDate: z.string(),
|
||||
endDate: z.string(),
|
||||
adults: z.number(),
|
||||
children: z.number().optional().default(0),
|
||||
packageCodes: z.array(z.string()).optional().default([]),
|
||||
lang: z.nativeEnum(Lang),
|
||||
})
|
||||
export const cityCoordinatesInputSchema = z.object({
|
||||
city: z.string(),
|
||||
hotel: z.object({
|
||||
address: z.string().optional(),
|
||||
}),
|
||||
})
|
||||
|
||||
export const getMeetingRoomsInputSchema = z.object({
|
||||
hotelId: z.string(),
|
||||
language: z.string(),
|
||||
})
|
||||
|
||||
export const getAdditionalDataInputSchema = z.object({
|
||||
hotelId: z.string(),
|
||||
language: z.string(),
|
||||
})
|
||||
|
||||
export const getHotelsByCountryInput = z.object({
|
||||
country: z.nativeEnum(Country),
|
||||
})
|
||||
|
||||
export const getHotelsByCityIdentifierInput = z.object({
|
||||
cityIdentifier: z.string(),
|
||||
})
|
||||
87
apps/scandic-web/server/routers/hotels/metrics.ts
Normal file
87
apps/scandic-web/server/routers/hotels/metrics.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { metrics as opentelemetryMetrics } from "@opentelemetry/api"
|
||||
|
||||
const meter = opentelemetryMetrics.getMeter("trpc.hotels")
|
||||
export const metrics = {
|
||||
additionalData: {
|
||||
counter: meter.createCounter("trpc.hotels.additionalData"),
|
||||
fail: meter.createCounter("trpc.hotels.additionalData-fail"),
|
||||
success: meter.createCounter("trpc.hotels.additionalData-success"),
|
||||
},
|
||||
breakfastPackage: {
|
||||
counter: meter.createCounter("trpc.package.breakfast"),
|
||||
fail: meter.createCounter("trpc.package.breakfast-fail"),
|
||||
success: meter.createCounter("trpc.package.breakfast-success"),
|
||||
},
|
||||
ancillaryPackage: {
|
||||
counter: meter.createCounter("trpc.package.ancillary"),
|
||||
fail: meter.createCounter("trpc.package.ancillary-fail"),
|
||||
success: meter.createCounter("trpc.package.ancillary-success"),
|
||||
},
|
||||
hotel: {
|
||||
counter: meter.createCounter("trpc.hotel.get"),
|
||||
fail: meter.createCounter("trpc.hotel.get-fail"),
|
||||
success: meter.createCounter("trpc.hotel.get-success"),
|
||||
},
|
||||
hotels: {
|
||||
counter: meter.createCounter("trpc.hotel.hotels.get"),
|
||||
fail: meter.createCounter("trpc.hotel.hotels.get-fail"),
|
||||
success: meter.createCounter("trpc.hotel.hotels.get-success"),
|
||||
},
|
||||
hotelIds: {
|
||||
counter: meter.createCounter("trpc.hotel.hotel-ids.get"),
|
||||
fail: meter.createCounter("trpc.hotel.hotel-ids.get-fail"),
|
||||
success: meter.createCounter("trpc.hotel.hotel-ids.get-success"),
|
||||
},
|
||||
hotelsAvailability: {
|
||||
counter: meter.createCounter("trpc.hotel.availability.hotels"),
|
||||
fail: meter.createCounter("trpc.hotel.availability.hotels-fail"),
|
||||
success: meter.createCounter("trpc.hotel.availability.hotels-success"),
|
||||
},
|
||||
hotelsAvailabilityBookingCode: {
|
||||
counter: meter.createCounter("trpc.hotel.availability.hotels-booking-code"),
|
||||
fail: meter.createCounter(
|
||||
"trpc.hotel.availability.hotels-booking-code-fail"
|
||||
),
|
||||
success: meter.createCounter(
|
||||
"trpc.hotel.availability.hotels-booking-code-success"
|
||||
),
|
||||
},
|
||||
hotelsByHotelIdAvailability: {
|
||||
counter: meter.createCounter("trpc.hotel.availability.hotels-by-hotel-id"),
|
||||
fail: meter.createCounter(
|
||||
"trpc.hotel.availability.hotels-by-hotel-id-fail"
|
||||
),
|
||||
success: meter.createCounter(
|
||||
"trpc.hotel.availability.hotels-by-hotel-id-success"
|
||||
),
|
||||
},
|
||||
meetingRooms: {
|
||||
counter: meter.createCounter("trpc.hotels.meetingRooms"),
|
||||
fail: meter.createCounter("trpc.hotels.meetingRooms-fail"),
|
||||
success: meter.createCounter("trpc.hotels.meetingRooms-success"),
|
||||
},
|
||||
nearbyHotelIds: {
|
||||
counter: meter.createCounter("trpc.hotel.nearby-hotel-ids.get"),
|
||||
fail: meter.createCounter("trpc.hotel.nearby-hotel-ids.get-fail"),
|
||||
success: meter.createCounter("trpc.hotel.nearby-hotel-ids.get-success"),
|
||||
},
|
||||
packages: {
|
||||
counter: meter.createCounter("trpc.hotel.packages.get"),
|
||||
fail: meter.createCounter("trpc.hotel.packages.get-fail"),
|
||||
success: meter.createCounter("trpc.hotel.packages.get-success"),
|
||||
},
|
||||
roomsCombinedAvailability: {
|
||||
counter: meter.createCounter("trpc.hotel.roomsCombinedAvailability.rooms"),
|
||||
fail: meter.createCounter(
|
||||
"trpc.hotel.roomsCombinedAvailability.rooms-fail"
|
||||
),
|
||||
success: meter.createCounter(
|
||||
"trpc.hotel.roomsCombinedAvailability.rooms-success"
|
||||
),
|
||||
},
|
||||
selectedRoomAvailability: {
|
||||
counter: meter.createCounter("trpc.hotel.availability.room"),
|
||||
fail: meter.createCounter("trpc.hotel.availability.room-fail"),
|
||||
success: meter.createCounter("trpc.hotel.availability.room-success"),
|
||||
},
|
||||
}
|
||||
432
apps/scandic-web/server/routers/hotels/output.ts
Normal file
432
apps/scandic-web/server/routers/hotels/output.ts
Normal file
@@ -0,0 +1,432 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { toLang } from "@/server/utils"
|
||||
|
||||
import { occupancySchema } from "./schemas/availability/occupancy"
|
||||
import { productTypeSchema } from "./schemas/availability/productType"
|
||||
import { citySchema } from "./schemas/city"
|
||||
import {
|
||||
attributesSchema,
|
||||
includedSchema,
|
||||
relationshipsSchema as hotelRelationshipsSchema,
|
||||
} from "./schemas/hotel"
|
||||
import { locationCitySchema } from "./schemas/location/city"
|
||||
import { locationHotelSchema } from "./schemas/location/hotel"
|
||||
import {
|
||||
ancillaryPackageSchema,
|
||||
breakfastPackageSchema,
|
||||
packageSchema,
|
||||
} from "./schemas/packages"
|
||||
import { rateSchema } from "./schemas/rate"
|
||||
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 {
|
||||
Product,
|
||||
RateDefinition,
|
||||
} from "@/types/trpc/routers/hotel/roomAvailability"
|
||||
|
||||
// NOTE: Find schema at: https://aks-test.scandichotels.com/hotel/swagger/v1/index.html
|
||||
export const hotelSchema = z
|
||||
.object({
|
||||
data: z.object({
|
||||
attributes: attributesSchema,
|
||||
id: z.string(),
|
||||
language: z.string().transform((val) => {
|
||||
const lang = toLang(val)
|
||||
if (!lang) {
|
||||
throw new Error("Invalid language")
|
||||
}
|
||||
return lang
|
||||
}),
|
||||
relationships: hotelRelationshipsSchema,
|
||||
type: z.literal("hotels"), // No enum here but the standard return appears to be "hotels".
|
||||
}),
|
||||
// NOTE: We can pass an "include" param to the hotel API to retrieve
|
||||
// additional data for an individual hotel.
|
||||
included: includedSchema,
|
||||
})
|
||||
.transform(({ data: { attributes, ...data }, included }) => {
|
||||
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"
|
||||
)
|
||||
const restaurants = included.filter(
|
||||
(inc): inc is Restaurant => inc!.type === "restaurants"
|
||||
)
|
||||
const roomCategories = included.filter(
|
||||
(inc): inc is Room => inc!.type === "roomcategories"
|
||||
)
|
||||
return {
|
||||
additionalData,
|
||||
cities,
|
||||
hotel: {
|
||||
...data,
|
||||
...attributes,
|
||||
},
|
||||
nearbyHotels,
|
||||
restaurants,
|
||||
roomCategories,
|
||||
}
|
||||
})
|
||||
|
||||
export const hotelsAvailabilitySchema = z.object({
|
||||
data: z.array(
|
||||
z.object({
|
||||
attributes: z.object({
|
||||
checkInDate: z.string(),
|
||||
checkOutDate: z.string(),
|
||||
hotelId: z.number(),
|
||||
occupancy: occupancySchema,
|
||||
productType: productTypeSchema,
|
||||
status: z.string(),
|
||||
}),
|
||||
relationships: relationshipsSchema.optional(),
|
||||
type: z.string().optional(),
|
||||
})
|
||||
),
|
||||
})
|
||||
|
||||
function everyRateHasBreakfastIncluded(
|
||||
product: Product,
|
||||
rateDefinitions: RateDefinition[],
|
||||
userType: "member" | "public"
|
||||
) {
|
||||
const rateDefinition = rateDefinitions.find(
|
||||
(rd) => rd.rateCode === product.productType[userType]?.rateCode
|
||||
)
|
||||
if (!rateDefinition) {
|
||||
return false
|
||||
}
|
||||
return rateDefinition.breakfastIncluded
|
||||
}
|
||||
|
||||
function getRate(rate: RateDefinition | undefined) {
|
||||
if (!rate) {
|
||||
return null
|
||||
}
|
||||
switch (rate.cancellationRule) {
|
||||
case "CancellableBefore6PM":
|
||||
return "flex"
|
||||
case "Changeable":
|
||||
return "change"
|
||||
case "NotCancellable":
|
||||
return "save"
|
||||
default:
|
||||
console.info(`Should never happen!`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is used for custom sorting further down
|
||||
* to guarantee correct order of rates
|
||||
*/
|
||||
const cancellationRules = {
|
||||
CancellableBefore6PM: 2,
|
||||
Changeable: 1,
|
||||
NotCancellable: 0,
|
||||
} as const
|
||||
|
||||
export const roomsAvailabilitySchema = z
|
||||
.object({
|
||||
data: z.object({
|
||||
attributes: z.object({
|
||||
checkInDate: z.string(),
|
||||
checkOutDate: z.string(),
|
||||
hotelId: z.number(),
|
||||
mustBeGuaranteed: z.boolean().optional(),
|
||||
occupancy: occupancySchema.optional(),
|
||||
rateDefinitions: z.array(rateDefinitionSchema),
|
||||
roomConfigurations: z.array(roomConfigurationSchema),
|
||||
}),
|
||||
relationships: relationshipsSchema.optional(),
|
||||
type: z.string().optional(),
|
||||
}),
|
||||
})
|
||||
.transform((o) => {
|
||||
const cancellationRuleLookup = o.data.attributes.rateDefinitions.reduce(
|
||||
(acc, val) => {
|
||||
// @ts-expect-error - index of cancellationRule TS
|
||||
acc[val.rateCode] = cancellationRules[val.cancellationRule]
|
||||
return acc
|
||||
},
|
||||
{}
|
||||
)
|
||||
|
||||
o.data.attributes.roomConfigurations =
|
||||
o.data.attributes.roomConfigurations.map((room) => {
|
||||
if (room.products.length) {
|
||||
room.breakfastIncludedInAllRatesMember = room.products.every(
|
||||
(product) =>
|
||||
everyRateHasBreakfastIncluded(
|
||||
product,
|
||||
o.data.attributes.rateDefinitions,
|
||||
"member"
|
||||
)
|
||||
)
|
||||
room.breakfastIncludedInAllRatesPublic = room.products.every(
|
||||
(product) =>
|
||||
everyRateHasBreakfastIncluded(
|
||||
product,
|
||||
o.data.attributes.rateDefinitions,
|
||||
"public"
|
||||
)
|
||||
)
|
||||
|
||||
room.products = room.products.map((product) => {
|
||||
const publicRateDefinition = o.data.attributes.rateDefinitions.find(
|
||||
(rate) =>
|
||||
product.productType.public.rateCode
|
||||
? rate.rateCode === product.productType.public.rateCode
|
||||
: rate.rateCode === product.productType.public.oldRateCode
|
||||
)
|
||||
const publicRate = getRate(publicRateDefinition)
|
||||
const memberRateDefinition = o.data.attributes.rateDefinitions.find(
|
||||
(rate) =>
|
||||
product.productType.member?.rateCode
|
||||
? rate.rateCode === product.productType.member?.rateCode
|
||||
: rate.rateCode === product.productType.member?.oldRateCode
|
||||
)
|
||||
const memberRate = getRate(memberRateDefinition)
|
||||
|
||||
if (publicRate) {
|
||||
product.productType.public.rate = publicRate
|
||||
}
|
||||
if (memberRate && product.productType.member) {
|
||||
product.productType.member.rate = memberRate
|
||||
}
|
||||
|
||||
return product
|
||||
})
|
||||
}
|
||||
|
||||
// CancellationRule is the same for public and member per product
|
||||
// Sorting to guarantee order based on rate
|
||||
room.products = room.products.sort(
|
||||
(a, b) =>
|
||||
// @ts-expect-error - index
|
||||
cancellationRuleLookup[a.productType.public.rateCode] -
|
||||
// @ts-expect-error - index
|
||||
cancellationRuleLookup[b.productType.public.rateCode]
|
||||
)
|
||||
|
||||
return room
|
||||
})
|
||||
|
||||
return o.data.attributes
|
||||
})
|
||||
|
||||
export const ratesSchema = z.array(rateSchema)
|
||||
|
||||
export const citiesByCountrySchema = z.object({
|
||||
data: z.array(
|
||||
citySchema.transform((data) => {
|
||||
return {
|
||||
...data.attributes,
|
||||
id: data.id,
|
||||
type: data.type,
|
||||
}
|
||||
})
|
||||
),
|
||||
})
|
||||
|
||||
export const countriesSchema = z.object({
|
||||
data: z
|
||||
.array(
|
||||
z.object({
|
||||
attributes: z.object({
|
||||
currency: z.string().default("N/A"),
|
||||
name: z.string(),
|
||||
}),
|
||||
hotelInformationSystemId: z.number().optional(),
|
||||
id: z.string().optional().default(""),
|
||||
language: z.string().optional(),
|
||||
type: z.literal("countries"),
|
||||
})
|
||||
)
|
||||
.transform((data) => {
|
||||
return data.map((country) => {
|
||||
return {
|
||||
...country.attributes,
|
||||
hotelInformationSystemId: country.hotelInformationSystemId,
|
||||
id: country.id,
|
||||
language: country.language,
|
||||
type: country.type,
|
||||
}
|
||||
})
|
||||
}),
|
||||
})
|
||||
|
||||
export const citiesSchema = z
|
||||
.object({
|
||||
data: z.array(citySchema),
|
||||
})
|
||||
.transform(({ data }) => {
|
||||
if (data.length) {
|
||||
const city = data[0]
|
||||
return {
|
||||
...city.attributes,
|
||||
id: city.id,
|
||||
type: city.type,
|
||||
}
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
export const locationsSchema = z.object({
|
||||
data: z
|
||||
.array(
|
||||
z
|
||||
.discriminatedUnion("type", [locationCitySchema, locationHotelSchema])
|
||||
.transform((location) => {
|
||||
if (location.type === "cities") {
|
||||
return {
|
||||
...location.attributes,
|
||||
country: location?.country ?? "",
|
||||
id: location.id,
|
||||
type: location.type,
|
||||
}
|
||||
}
|
||||
return {
|
||||
...location.attributes,
|
||||
id: location.id,
|
||||
relationships: {
|
||||
city: {
|
||||
cityIdentifier: "",
|
||||
ianaTimeZoneId: "",
|
||||
id: "",
|
||||
isPublished: false,
|
||||
keywords: [],
|
||||
name: "",
|
||||
timeZoneId: "",
|
||||
type: "cities",
|
||||
url: location?.relationships?.city?.links?.related ?? "",
|
||||
},
|
||||
},
|
||||
type: location.type,
|
||||
}
|
||||
})
|
||||
)
|
||||
.transform((data) =>
|
||||
data
|
||||
.filter((node) => !!node)
|
||||
.sort((a, b) => {
|
||||
if (a.type === b.type) {
|
||||
return a.name.localeCompare(b.name)
|
||||
} else {
|
||||
return a.type === "cities" ? -1 : 1
|
||||
}
|
||||
})
|
||||
),
|
||||
})
|
||||
|
||||
export const breakfastPackagesSchema = z
|
||||
.object({
|
||||
data: z.object({
|
||||
attributes: z.object({
|
||||
hotelId: z.number(),
|
||||
packages: z.array(breakfastPackageSchema),
|
||||
}),
|
||||
type: z.literal("breakfastpackage"),
|
||||
}),
|
||||
})
|
||||
.transform(({ data }) =>
|
||||
data.attributes.packages.filter((pkg) => pkg.code?.match(/^(BRF\d+)$/gm))
|
||||
)
|
||||
|
||||
export const ancillaryPackagesSchema = z
|
||||
.object({
|
||||
data: z.object({
|
||||
attributes: z.object({
|
||||
ancillaries: z.array(ancillaryPackageSchema),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.transform(({ data }) =>
|
||||
data.attributes.ancillaries
|
||||
.map((ancillary) => ({
|
||||
categoryName: ancillary.categoryName,
|
||||
ancillaryContent: ancillary.ancillaryContent
|
||||
.filter((item) => item.status === "Available")
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
description: item.descriptions.html,
|
||||
imageUrl: item.images[0]?.imageSizes.small,
|
||||
price: {
|
||||
total: parseInt(item.variants.ancillary.price.totalPrice),
|
||||
currency: item.variants.ancillary.price.currency,
|
||||
},
|
||||
points: item.variants.ancillaryLoyalty?.points,
|
||||
loyaltyCode: item.variants.ancillaryLoyalty?.code,
|
||||
requiresDeliveryTime: item.requiresDeliveryTime,
|
||||
})),
|
||||
}))
|
||||
.filter((ancillary) => ancillary.ancillaryContent.length > 0)
|
||||
)
|
||||
|
||||
export const packagesSchema = z
|
||||
.object({
|
||||
data: z
|
||||
.object({
|
||||
attributes: z.object({
|
||||
hotelId: z.number(),
|
||||
packages: z.array(packageSchema).default([]),
|
||||
}),
|
||||
relationships: z
|
||||
.object({
|
||||
links: z.array(
|
||||
z.object({
|
||||
type: z.string(),
|
||||
url: z.string(),
|
||||
})
|
||||
),
|
||||
})
|
||||
.optional(),
|
||||
type: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.transform(({ data }) => data?.attributes.packages)
|
||||
|
||||
export const getHotelIdsSchema = z
|
||||
.object({
|
||||
data: z.array(
|
||||
z.object({
|
||||
attributes: z.object({
|
||||
isPublished: z.boolean(),
|
||||
}),
|
||||
id: z.string(),
|
||||
})
|
||||
),
|
||||
})
|
||||
.transform(({ data }) => {
|
||||
const filteredHotels = data.filter(
|
||||
(hotel) => !!hotel.attributes.isPublished
|
||||
)
|
||||
return filteredHotels.map((hotel) => hotel.id)
|
||||
})
|
||||
|
||||
export const getNearbyHotelIdsSchema = z
|
||||
.object({
|
||||
data: z.array(
|
||||
z.object({
|
||||
// We only care about the hotel id
|
||||
id: z.string(),
|
||||
})
|
||||
),
|
||||
})
|
||||
.transform((data) => data.data.map((hotel) => hotel.id))
|
||||
1787
apps/scandic-web/server/routers/hotels/query.ts
Normal file
1787
apps/scandic-web/server/routers/hotels/query.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { ChildBedTypeEnum } from "@/constants/booking"
|
||||
|
||||
export const childrenSchema = z.object({
|
||||
age: z.number(),
|
||||
bedType: z.nativeEnum(ChildBedTypeEnum),
|
||||
})
|
||||
|
||||
export const occupancySchema = z.object({
|
||||
adults: z.number(),
|
||||
children: z.array(childrenSchema).default([]),
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { productTypePriceSchema } from "../productTypePrice"
|
||||
|
||||
export const productTypeSchema = z
|
||||
.object({
|
||||
public: productTypePriceSchema.optional(),
|
||||
member: productTypePriceSchema.optional(),
|
||||
})
|
||||
.optional()
|
||||
14
apps/scandic-web/server/routers/hotels/schemas/city.ts
Normal file
14
apps/scandic-web/server/routers/hotels/schemas/city.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const citySchema = z.object({
|
||||
attributes: z.object({
|
||||
cityIdentifier: z.string().default(""),
|
||||
ianaTimeZoneId: z.string().default(""),
|
||||
isPublished: z.boolean().default(false),
|
||||
keywords: z.array(z.string()).default([]),
|
||||
name: z.string(),
|
||||
timeZoneId: z.string().default(""),
|
||||
}),
|
||||
id: z.string(),
|
||||
type: z.literal("cities"),
|
||||
})
|
||||
92
apps/scandic-web/server/routers/hotels/schemas/hotel.ts
Normal file
92
apps/scandic-web/server/routers/hotels/schemas/hotel.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import {
|
||||
nullableArrayObjectValidator,
|
||||
nullableArrayStringValidator,
|
||||
} from "@/utils/zod/arrayValidator"
|
||||
import { nullableNumberValidator } from "@/utils/zod/numberValidator"
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
import { addressSchema } from "./hotel/address"
|
||||
import { contactInformationSchema } from "./hotel/contactInformation"
|
||||
import { hotelContentSchema } from "./hotel/content"
|
||||
import { detailedFacilitiesSchema } from "./hotel/detailedFacility"
|
||||
import { hotelFactsSchema } from "./hotel/facts"
|
||||
import { healthFacilitiesSchema } from "./hotel/healthFacilities"
|
||||
import { displayWebPageSchema } from "./hotel/include/additionalData/displayWebPage"
|
||||
import { facilitySchema } from "./hotel/include/additionalData/facility"
|
||||
import { gallerySchema } from "./hotel/include/additionalData/gallery"
|
||||
import { includeSchema } from "./hotel/include/include"
|
||||
import { locationSchema } from "./hotel/location"
|
||||
import { merchantInformationSchema } from "./hotel/merchantInformation"
|
||||
import { parkingSchema } from "./hotel/parking"
|
||||
import { pointOfInterestsSchema } from "./hotel/poi"
|
||||
import { ratingsSchema } from "./hotel/rating"
|
||||
import { rewardNightSchema } from "./hotel/rewardNight"
|
||||
import { socialMediaSchema } from "./hotel/socialMedia"
|
||||
import { specialAlertsSchema } from "./hotel/specialAlerts"
|
||||
import { imageSchema } from "./image"
|
||||
|
||||
export const attributesSchema = z.object({
|
||||
address: addressSchema,
|
||||
cityId: nullableStringValidator,
|
||||
cityName: nullableStringValidator,
|
||||
conferencesAndMeetings: facilitySchema.nullish(),
|
||||
contactInformation: contactInformationSchema,
|
||||
countryCode: nullableStringValidator,
|
||||
detailedFacilities: detailedFacilitiesSchema,
|
||||
displayWebPage: displayWebPageSchema,
|
||||
gallery: gallerySchema.nullish(),
|
||||
galleryImages: z
|
||||
.array(imageSchema)
|
||||
.nullish()
|
||||
.transform((arr) => (arr ? arr.filter(Boolean) : [])),
|
||||
healthAndWellness: facilitySchema.nullish(),
|
||||
healthFacilities: healthFacilitiesSchema,
|
||||
hotelContent: hotelContentSchema,
|
||||
hotelFacts: hotelFactsSchema,
|
||||
hotelType: nullableStringValidator,
|
||||
isActive: z.boolean(),
|
||||
isPublished: z.boolean(),
|
||||
keywords: nullableArrayStringValidator,
|
||||
location: locationSchema,
|
||||
merchantInformationData: merchantInformationSchema,
|
||||
name: nullableStringValidator,
|
||||
operaId: nullableStringValidator,
|
||||
parking: nullableArrayObjectValidator(parkingSchema),
|
||||
pointsOfInterest: pointOfInterestsSchema,
|
||||
ratings: ratingsSchema,
|
||||
restaurantImages: facilitySchema.nullish(),
|
||||
rewardNight: rewardNightSchema,
|
||||
socialMedia: socialMediaSchema,
|
||||
specialAlerts: specialAlertsSchema,
|
||||
vat: nullableNumberValidator,
|
||||
})
|
||||
|
||||
export const includedSchema = z
|
||||
.array(includeSchema)
|
||||
.default([])
|
||||
.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({
|
||||
related: z.string(),
|
||||
}),
|
||||
})
|
||||
|
||||
export const relationshipsSchema = z.object({
|
||||
meetingRooms: relationshipSchema,
|
||||
nearbyHotels: relationshipSchema,
|
||||
restaurants: relationshipSchema,
|
||||
roomCategories: relationshipSchema,
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
export const addressSchema = z.object({
|
||||
city: nullableStringValidator,
|
||||
country: nullableStringValidator,
|
||||
streetAddress: nullableStringValidator,
|
||||
zipCode: nullableStringValidator,
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import {
|
||||
nullableStringEmailValidator,
|
||||
nullableStringValidator,
|
||||
} from "@/utils/zod/stringValidator"
|
||||
|
||||
export const contactInformationSchema = z.object({
|
||||
email: nullableStringEmailValidator,
|
||||
faxNumber: nullableStringValidator,
|
||||
phoneNumber: nullableStringValidator,
|
||||
websiteUrl: nullableStringValidator,
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
import { imageSchema } from "../image"
|
||||
import { restaurantsOverviewPageSchema } from "./include/additionalData/restaurantsOverviewPage"
|
||||
|
||||
const descriptionSchema = z
|
||||
.object({
|
||||
medium: nullableStringValidator,
|
||||
short: nullableStringValidator,
|
||||
})
|
||||
.nullish()
|
||||
|
||||
const textsSchema = z.object({
|
||||
descriptions: descriptionSchema,
|
||||
facilityInformation: nullableStringValidator,
|
||||
meetingDescription: descriptionSchema,
|
||||
surroundingInformation: nullableStringValidator,
|
||||
})
|
||||
|
||||
export const hotelContentSchema = z.object({
|
||||
images: imageSchema,
|
||||
restaurantsOverviewPage: restaurantsOverviewPageSchema,
|
||||
texts: textsSchema,
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
import slugify from "slugify"
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableArrayObjectValidator } from "@/utils/zod/arrayValidator"
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
import { FacilityEnum } from "@/types/enums/facilities"
|
||||
|
||||
const rawDetailedFacilitySchema = z.object({
|
||||
filter: nullableStringValidator,
|
||||
icon: nullableStringValidator,
|
||||
id: z.nativeEnum(FacilityEnum),
|
||||
name: nullableStringValidator,
|
||||
public: z.boolean(),
|
||||
sortOrder: z.number(),
|
||||
})
|
||||
|
||||
function transformDetailedFacility(
|
||||
data: z.output<typeof rawDetailedFacilitySchema>
|
||||
) {
|
||||
return {
|
||||
...data,
|
||||
slug: slugify(data.name, { lower: true, strict: true }),
|
||||
}
|
||||
}
|
||||
|
||||
export const detailedFacilitySchema = rawDetailedFacilitySchema.transform(
|
||||
transformDetailedFacility
|
||||
)
|
||||
|
||||
export const detailedFacilitiesSchema = nullableArrayObjectValidator(
|
||||
rawDetailedFacilitySchema
|
||||
).transform((facilities) =>
|
||||
facilities
|
||||
.sort((a, b) => b.sortOrder - a.sortOrder)
|
||||
.map(transformDetailedFacility)
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
export const checkinSchema = z.object({
|
||||
checkInTime: nullableStringValidator,
|
||||
checkOutTime: nullableStringValidator,
|
||||
onlineCheckout: z.boolean(),
|
||||
onlineCheckOutAvailableFrom: nullableStringValidator,
|
||||
})
|
||||
|
||||
const ecoLabelsSchema = z.object({
|
||||
euEcoLabel: z.boolean(),
|
||||
greenGlobeLabel: z.boolean(),
|
||||
nordicEcoLabel: z.boolean(),
|
||||
svanenEcoLabelCertificateNumber: nullableStringValidator,
|
||||
})
|
||||
|
||||
const interiorSchema = z.object({
|
||||
numberOfBeds: z.number(),
|
||||
numberOfCribs: z.number(),
|
||||
numberOfFloors: z.number(),
|
||||
numberOfRooms: z.object({
|
||||
connected: z.number(),
|
||||
forAllergics: z.number(),
|
||||
forDisabled: z.number(),
|
||||
nonSmoking: z.number(),
|
||||
pet: z.number(),
|
||||
withExtraBeds: z.number(),
|
||||
total: z.number(),
|
||||
}),
|
||||
})
|
||||
|
||||
const receptionHoursSchema = z.object({
|
||||
alwaysOpen: z.boolean(),
|
||||
closingTime: nullableStringValidator,
|
||||
isClosed: z.boolean(),
|
||||
openingTime: nullableStringValidator,
|
||||
})
|
||||
|
||||
export const hotelFactsSchema = z.object({
|
||||
checkin: checkinSchema,
|
||||
ecoLabels: ecoLabelsSchema,
|
||||
interior: interiorSchema,
|
||||
receptionHours: receptionHoursSchema,
|
||||
yearBuilt: nullableStringValidator,
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableArrayObjectValidator } from "@/utils/zod/arrayValidator"
|
||||
import { nullableNumberValidator } from "@/utils/zod/numberValidator"
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
import { imageSchema } from "../image"
|
||||
|
||||
const healthFacilitiesOpenHoursSchema = z.object({
|
||||
alwaysOpen: z.boolean(),
|
||||
closingTime: nullableStringValidator,
|
||||
isClosed: z.boolean(),
|
||||
openingTime: nullableStringValidator,
|
||||
sortOrder: nullableNumberValidator,
|
||||
})
|
||||
|
||||
const descriptionSchema = z
|
||||
.object({
|
||||
medium: nullableStringValidator,
|
||||
short: nullableStringValidator,
|
||||
})
|
||||
.nullish()
|
||||
|
||||
const detailsSchema = z.object({
|
||||
name: nullableStringValidator,
|
||||
type: nullableStringValidator,
|
||||
value: nullableStringValidator,
|
||||
})
|
||||
|
||||
const textsSchema = z.object({
|
||||
descriptions: descriptionSchema,
|
||||
facilityInformation: nullableStringValidator,
|
||||
meetingDescription: descriptionSchema,
|
||||
surroundingInformation: nullableStringValidator,
|
||||
})
|
||||
|
||||
export const healthFacilitySchema = z.object({
|
||||
content: z.object({
|
||||
images: z
|
||||
.array(imageSchema)
|
||||
.nullish()
|
||||
.transform((arr) => (arr ? arr.filter(Boolean) : [])),
|
||||
texts: textsSchema,
|
||||
}),
|
||||
details: nullableArrayObjectValidator(detailsSchema),
|
||||
openingDetails: z.object({
|
||||
manualOpeningHours: nullableStringValidator,
|
||||
openingHours: z.object({
|
||||
ordinary: healthFacilitiesOpenHoursSchema,
|
||||
weekends: healthFacilitiesOpenHoursSchema,
|
||||
}),
|
||||
useManualOpeningHours: z
|
||||
.boolean()
|
||||
.nullish()
|
||||
.transform((b) => !!b),
|
||||
}),
|
||||
type: nullableStringValidator,
|
||||
})
|
||||
|
||||
export const healthFacilitiesSchema =
|
||||
nullableArrayObjectValidator(healthFacilitySchema)
|
||||
@@ -0,0 +1,48 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableArrayObjectValidator } from "@/utils/zod/arrayValidator"
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
import { displayWebPageSchema } from "./additionalData/displayWebPage"
|
||||
import { facilitySchema } from "./additionalData/facility"
|
||||
import { gallerySchema } from "./additionalData/gallery"
|
||||
import { restaurantsOverviewPageSchema } from "./additionalData/restaurantsOverviewPage"
|
||||
import { specialNeedGroupSchema } from "./additionalData/specialNeedGroups"
|
||||
|
||||
export const extraPageSchema = z.object({
|
||||
elevatorPitch: nullableStringValidator,
|
||||
mainBody: nullableStringValidator,
|
||||
nameInUrl: nullableStringValidator,
|
||||
})
|
||||
|
||||
export const additionalDataSchema = z.object({
|
||||
attributes: z.object({
|
||||
accessibility: facilitySchema.nullish(),
|
||||
conferencesAndMeetings: facilitySchema.nullish(),
|
||||
displayWebPage: displayWebPageSchema,
|
||||
gallery: gallerySchema.nullish(),
|
||||
healthAndFitness: extraPageSchema,
|
||||
healthAndWellness: facilitySchema.nullish(),
|
||||
hotelParking: extraPageSchema,
|
||||
hotelRoomElevatorPitchText: nullableStringValidator,
|
||||
hotelSpecialNeeds: extraPageSchema,
|
||||
id: nullableStringValidator,
|
||||
meetingRooms: extraPageSchema,
|
||||
name: nullableStringValidator,
|
||||
parkingImages: facilitySchema.nullish(),
|
||||
restaurantImages: facilitySchema.nullish(),
|
||||
restaurantsOverviewPage: restaurantsOverviewPageSchema,
|
||||
specialNeedGroups: nullableArrayObjectValidator(specialNeedGroupSchema),
|
||||
}),
|
||||
type: z.literal("additionalData"),
|
||||
})
|
||||
|
||||
export function transformAdditionalData(
|
||||
data: z.output<typeof additionalDataSchema>
|
||||
) {
|
||||
return {
|
||||
...data.attributes,
|
||||
id: data.attributes.id,
|
||||
type: data.type,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const displayWebPageSchema = z.object({
|
||||
healthGym: z.boolean(),
|
||||
meetingRoom: z.boolean(),
|
||||
parking: z.boolean(),
|
||||
specialNeeds: z.boolean(),
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { imageSchema } from "@/server/routers/hotels/schemas/image"
|
||||
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
export const facilitySchema = z.object({
|
||||
headingText: nullableStringValidator,
|
||||
heroImages: z
|
||||
.array(imageSchema)
|
||||
.nullish()
|
||||
.transform((arr) => (arr ? arr.filter(Boolean) : [])),
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { imageSchema } from "@/server/routers/hotels/schemas/image"
|
||||
|
||||
const imagesSchema = z
|
||||
.array(imageSchema)
|
||||
.nullish()
|
||||
.transform((arr) => (arr ? arr.filter(Boolean) : []))
|
||||
|
||||
export const gallerySchema = z.object({
|
||||
heroImages: imagesSchema,
|
||||
smallerImages: imagesSchema,
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
export const restaurantsOverviewPageSchema = z.object({
|
||||
restaurantsContentDescriptionMedium: nullableStringValidator,
|
||||
restaurantsContentDescriptionShort: nullableStringValidator,
|
||||
restaurantsOverviewPageLink: nullableStringValidator,
|
||||
restaurantsOverviewPageLinkText: nullableStringValidator,
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableArrayObjectValidator } from "@/utils/zod/arrayValidator"
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
const specialNeedSchema = z.object({
|
||||
details: nullableStringValidator,
|
||||
name: nullableStringValidator,
|
||||
})
|
||||
|
||||
export const specialNeedGroupSchema = z.object({
|
||||
name: nullableStringValidator,
|
||||
specialNeeds: nullableArrayObjectValidator(specialNeedSchema),
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { citySchema } from "@/server/routers/hotels/schemas/city"
|
||||
import { nearbyHotelsSchema } from "@/server/routers/hotels/schemas/hotel/include/nearbyHotels"
|
||||
import { restaurantsSchema } from "@/server/routers/hotels/schemas/hotel/include/restaurants"
|
||||
import {
|
||||
roomCategoriesSchema,
|
||||
transformRoomCategories,
|
||||
} from "@/server/routers/hotels/schemas/hotel/include/roomCategories"
|
||||
|
||||
import { additionalDataSchema, transformAdditionalData } from "./additionalData"
|
||||
|
||||
export const includeSchema = z
|
||||
.discriminatedUnion("type", [
|
||||
additionalDataSchema,
|
||||
citySchema,
|
||||
nearbyHotelsSchema,
|
||||
restaurantsSchema,
|
||||
roomCategoriesSchema,
|
||||
])
|
||||
.transform((data) => {
|
||||
switch (data.type) {
|
||||
case "additionalData":
|
||||
return transformAdditionalData(data)
|
||||
case "cities":
|
||||
case "hotels":
|
||||
case "restaurants":
|
||||
return {
|
||||
...data.attributes,
|
||||
id: data.id,
|
||||
type: data.type,
|
||||
}
|
||||
case "roomcategories":
|
||||
return transformRoomCategories(data)
|
||||
default:
|
||||
return null
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { attributesSchema } from "@/server/routers/hotels/schemas/hotel"
|
||||
|
||||
export const nearbyHotelsSchema = z.object({
|
||||
attributes: z.lazy(() =>
|
||||
z
|
||||
.object({
|
||||
displayWebPage: z
|
||||
.object({
|
||||
healthGym: z.boolean().default(false),
|
||||
meetingRoom: z.boolean().default(false),
|
||||
parking: z.boolean().default(false),
|
||||
specialNeeds: z.boolean().default(false),
|
||||
})
|
||||
.default({
|
||||
healthGym: false,
|
||||
meetingRoom: false,
|
||||
parking: false,
|
||||
specialNeeds: false,
|
||||
}),
|
||||
})
|
||||
.merge(
|
||||
attributesSchema.pick({
|
||||
address: true,
|
||||
cityId: true,
|
||||
cityName: true,
|
||||
detailedFacilities: true,
|
||||
hotelContent: true,
|
||||
isActive: true,
|
||||
isPublished: true,
|
||||
location: true,
|
||||
name: true,
|
||||
operaId: true,
|
||||
ratings: true,
|
||||
})
|
||||
)
|
||||
),
|
||||
id: z.string(),
|
||||
type: z.literal("hotels"),
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
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: textSchema,
|
||||
})
|
||||
|
||||
const restaurantPriceSchema = z.object({
|
||||
amount: nullableNumberValidator,
|
||||
currency: z.nativeEnum(CurrencyEnum).default(CurrencyEnum.SEK),
|
||||
})
|
||||
|
||||
const externalBreakfastSchema = z.object({
|
||||
isAvailable: z.boolean().default(false),
|
||||
localPriceForExternalGuests: restaurantPriceSchema.optional(),
|
||||
requestedPriceForExternalGuests: restaurantPriceSchema.optional(),
|
||||
})
|
||||
|
||||
const menuItemSchema = z.object({
|
||||
name: nullableStringValidator,
|
||||
url: nullableStringUrlValidator,
|
||||
})
|
||||
|
||||
export const openingHoursDetailsSchema = z.object({
|
||||
alwaysOpen: z.boolean().default(false),
|
||||
closingTime: nullableStringValidator,
|
||||
isClosed: z.boolean().default(false),
|
||||
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: openingHoursSchema.optional(),
|
||||
openingHours: openingHoursSchema,
|
||||
ordinary: openingHoursSchema.optional(),
|
||||
weekends: openingHoursSchema.optional(),
|
||||
})
|
||||
|
||||
export const restaurantsSchema = z.object({
|
||||
attributes: z.object({
|
||||
bookTableUrl: nullableStringValidator,
|
||||
content: contentSchema,
|
||||
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),
|
||||
elevatorPitch: z.string().optional(),
|
||||
nameInUrl: z.string().optional(),
|
||||
mainBody: z.string().optional(),
|
||||
specialAlerts: specialAlertsSchema,
|
||||
}),
|
||||
id: z.string(),
|
||||
type: z.literal("restaurants"),
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { imageSchema } from "@/server/routers/hotels/schemas/image"
|
||||
|
||||
import { nullableArrayObjectValidator } from "@/utils/zod/arrayValidator"
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
const minMaxSchema = z.object({
|
||||
max: z.number(),
|
||||
min: z.number(),
|
||||
})
|
||||
|
||||
const bedTypeSchema = z.object({
|
||||
description: nullableStringValidator,
|
||||
type: nullableStringValidator,
|
||||
widthRange: minMaxSchema,
|
||||
})
|
||||
|
||||
const occupancySchema = z.object({
|
||||
adults: z.number(),
|
||||
children: z.number(),
|
||||
total: z.number(),
|
||||
})
|
||||
|
||||
const roomContentSchema = z.object({
|
||||
images: z
|
||||
.array(imageSchema)
|
||||
.nullish()
|
||||
.transform((arr) => (arr ? arr.filter(Boolean) : [])),
|
||||
texts: z.object({
|
||||
descriptions: z.object({
|
||||
medium: nullableStringValidator,
|
||||
short: nullableStringValidator,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
|
||||
const roomTypesSchema = z.object({
|
||||
code: nullableStringValidator,
|
||||
description: nullableStringValidator,
|
||||
fixedExtraBed: bedTypeSchema,
|
||||
isLackingCribs: z.boolean(),
|
||||
isLackingExtraBeds: z.boolean(),
|
||||
mainBed: bedTypeSchema,
|
||||
name: nullableStringValidator,
|
||||
occupancy: occupancySchema,
|
||||
roomCount: z.number(),
|
||||
roomSize: minMaxSchema,
|
||||
})
|
||||
|
||||
const roomFacilitiesSchema = z.object({
|
||||
availableInAllRooms: z.boolean(),
|
||||
icon: z.string().optional(),
|
||||
isUniqueSellingPoint: z.boolean(),
|
||||
name: z.string(),
|
||||
sortOrder: z.number(),
|
||||
})
|
||||
|
||||
export const roomCategoriesSchema = z.object({
|
||||
attributes: z.object({
|
||||
content: roomContentSchema,
|
||||
name: nullableStringValidator,
|
||||
occupancy: minMaxSchema,
|
||||
roomFacilities: nullableArrayObjectValidator(roomFacilitiesSchema),
|
||||
roomSize: minMaxSchema,
|
||||
roomTypes: nullableArrayObjectValidator(roomTypesSchema),
|
||||
sortOrder: z.number(),
|
||||
}),
|
||||
id: z.string(),
|
||||
type: z.literal("roomcategories"),
|
||||
})
|
||||
|
||||
export function transformRoomCategories(
|
||||
data: z.output<typeof roomCategoriesSchema>
|
||||
) {
|
||||
return {
|
||||
descriptions: data.attributes.content.texts.descriptions,
|
||||
id: data.id,
|
||||
images: data.attributes.content.images,
|
||||
name: data.attributes.name,
|
||||
occupancy: data.attributes.occupancy,
|
||||
roomFacilities: data.attributes.roomFacilities,
|
||||
roomSize: data.attributes.roomSize,
|
||||
roomTypes: data.attributes.roomTypes,
|
||||
sortOrder: data.attributes.sortOrder,
|
||||
type: data.type,
|
||||
totalOccupancy:
|
||||
data.attributes.occupancy.min === data.attributes.occupancy.max
|
||||
? {
|
||||
max: data.attributes.occupancy.max,
|
||||
range: `${data.attributes.occupancy.max}`,
|
||||
}
|
||||
: {
|
||||
max: data.attributes.occupancy.max,
|
||||
range: `${data.attributes.occupancy.min}-${data.attributes.occupancy.max}`,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const locationSchema = z.object({
|
||||
distanceToCentre: z.number(),
|
||||
latitude: z.number(),
|
||||
longitude: z.number(),
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
import type { PaymentMethodEnum } from "@/constants/booking"
|
||||
|
||||
export const merchantInformationSchema = z.object({
|
||||
alternatePaymentOptions: z
|
||||
.record(z.string(), z.boolean())
|
||||
.transform((val) => {
|
||||
return Object.entries(val)
|
||||
.filter(([_, enabled]) => enabled)
|
||||
.map(([key]) => key)
|
||||
.filter((key): key is PaymentMethodEnum => !!key)
|
||||
}),
|
||||
cards: z.record(z.string(), z.boolean()).transform((val) => {
|
||||
return Object.entries(val)
|
||||
.filter(([_, enabled]) => enabled)
|
||||
.map(([key]) => key)
|
||||
.filter((key): key is PaymentMethodEnum => !!key)
|
||||
}),
|
||||
webMerchantId: nullableStringValidator,
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableArrayObjectValidator } from "@/utils/zod/arrayValidator"
|
||||
import { nullableNumberValidator } from "@/utils/zod/numberValidator"
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
const periodSchema = z.object({
|
||||
amount: nullableNumberValidator,
|
||||
endTime: nullableStringValidator,
|
||||
period: nullableStringValidator,
|
||||
startTime: nullableStringValidator,
|
||||
})
|
||||
|
||||
const currencySchema = z
|
||||
.object({
|
||||
currency: nullableStringValidator,
|
||||
ordinary: nullableArrayObjectValidator(periodSchema),
|
||||
range: z
|
||||
.object({
|
||||
min: nullableNumberValidator,
|
||||
max: nullableNumberValidator,
|
||||
})
|
||||
.nullish(),
|
||||
weekend: nullableArrayObjectValidator(periodSchema),
|
||||
})
|
||||
.nullish()
|
||||
|
||||
const pricingSchema = z.object({
|
||||
freeParking: z.boolean(),
|
||||
localCurrency: currencySchema,
|
||||
paymentType: nullableStringValidator,
|
||||
requestedCurrency: currencySchema,
|
||||
})
|
||||
|
||||
export const parkingSchema = z.object({
|
||||
address: nullableStringValidator,
|
||||
canMakeReservation: z.boolean(),
|
||||
distanceToHotel: nullableNumberValidator,
|
||||
externalParkingUrl: nullableStringValidator,
|
||||
name: nullableStringValidator,
|
||||
numberOfChargingSpaces: nullableNumberValidator,
|
||||
numberOfParkingSpots: nullableNumberValidator,
|
||||
pricing: pricingSchema,
|
||||
type: nullableStringValidator,
|
||||
})
|
||||
35
apps/scandic-web/server/routers/hotels/schemas/hotel/poi.ts
Normal file
35
apps/scandic-web/server/routers/hotels/schemas/hotel/poi.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableNumberValidator } from "@/utils/zod/numberValidator"
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
import { getPoiGroupByCategoryName } from "../../utils"
|
||||
import { locationSchema } from "./location"
|
||||
|
||||
export const pointOfInterestSchema = z
|
||||
.object({
|
||||
category: z.object({
|
||||
name: nullableStringValidator,
|
||||
}),
|
||||
distance: nullableNumberValidator,
|
||||
location: locationSchema,
|
||||
name: nullableStringValidator,
|
||||
})
|
||||
.transform((poi) => ({
|
||||
categoryName: poi.category.name,
|
||||
coordinates: {
|
||||
lat: poi.location.latitude,
|
||||
lng: poi.location.longitude,
|
||||
},
|
||||
distance: poi.distance,
|
||||
group: getPoiGroupByCategoryName(poi.category.name),
|
||||
name: poi.name,
|
||||
}))
|
||||
|
||||
export const pointOfInterestsSchema = z
|
||||
.array(pointOfInterestSchema)
|
||||
.nullish()
|
||||
.transform((arr) => (arr ? arr.filter(Boolean) : []))
|
||||
.transform((pois) =>
|
||||
pois.sort((a, b) => (a.distance ?? 0) - (b.distance ?? 0))
|
||||
)
|
||||
@@ -0,0 +1,57 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableArrayObjectValidator } from "@/utils/zod/arrayValidator"
|
||||
import {
|
||||
nullableStringUrlValidator,
|
||||
nullableStringValidator,
|
||||
} from "@/utils/zod/stringValidator"
|
||||
|
||||
const awardSchema = z.object({
|
||||
displayName: nullableStringValidator,
|
||||
images: z
|
||||
.object({
|
||||
large: nullableStringValidator,
|
||||
medium: nullableStringValidator,
|
||||
small: nullableStringValidator,
|
||||
})
|
||||
.nullish()
|
||||
.transform((obj) =>
|
||||
obj
|
||||
? obj
|
||||
: {
|
||||
small: "",
|
||||
medium: "",
|
||||
large: "",
|
||||
}
|
||||
),
|
||||
})
|
||||
|
||||
const reviewsSchema = z
|
||||
.object({
|
||||
widgetHtmlTagId: nullableStringValidator,
|
||||
widgetScriptEmbedUrlIframe: nullableStringValidator,
|
||||
widgetScriptEmbedUrlJavaScript: nullableStringValidator,
|
||||
})
|
||||
.nullish()
|
||||
.transform((obj) =>
|
||||
obj
|
||||
? obj
|
||||
: {
|
||||
widgetHtmlTagId: "",
|
||||
widgetScriptEmbedUrlIframe: "",
|
||||
widgetScriptEmbedUrlJavaScript: "",
|
||||
}
|
||||
)
|
||||
|
||||
export const ratingsSchema = z
|
||||
.object({
|
||||
tripAdvisor: z.object({
|
||||
awards: nullableArrayObjectValidator(awardSchema),
|
||||
numberOfReviews: z.number(),
|
||||
rating: z.number(),
|
||||
ratingImageUrl: nullableStringUrlValidator,
|
||||
reviews: reviewsSchema,
|
||||
webUrl: nullableStringUrlValidator,
|
||||
}),
|
||||
})
|
||||
.optional()
|
||||
@@ -0,0 +1,12 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
export const rewardNightSchema = z.object({
|
||||
campaign: z.object({
|
||||
end: nullableStringValidator,
|
||||
points: z.number(),
|
||||
start: nullableStringValidator,
|
||||
}),
|
||||
points: z.number(),
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
export const socialMediaSchema = z.object({
|
||||
facebook: nullableStringValidator,
|
||||
instagram: nullableStringValidator,
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
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: nullableStringValidator,
|
||||
displayInBookingFlow: z.boolean().default(false),
|
||||
endDate: nullableStringValidator,
|
||||
startDate: nullableStringValidator,
|
||||
title: nullableStringValidator,
|
||||
type: nullableStringValidator,
|
||||
})
|
||||
|
||||
export const specialAlertsSchema = z
|
||||
.array(specialAlertSchema)
|
||||
.nullish()
|
||||
.transform((arr) => (arr ? arr.filter(Boolean) : []))
|
||||
.transform((data) => {
|
||||
const now = dt().utc().format("YYYY-MM-DD")
|
||||
const filteredAlerts = data.filter((alert) => {
|
||||
const shouldShowNow =
|
||||
alert.startDate && alert.endDate
|
||||
? alert.startDate <= now && alert.endDate >= now
|
||||
: true
|
||||
const hasText = alert.description || alert.title
|
||||
return shouldShowNow && hasText
|
||||
})
|
||||
return filteredAlerts.map((alert, idx) => ({
|
||||
heading: alert.title || null,
|
||||
id: `alert-${alert.type}-${idx}`,
|
||||
text: alert.description || null,
|
||||
type: AlertTypeEnum.Info,
|
||||
displayInBookingFlow: alert.displayInBookingFlow,
|
||||
}))
|
||||
})
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const hotelFilterSchema = z.object({
|
||||
hotelFacilities: z.array(z.string()),
|
||||
hotelSurroundings: z.array(z.string()),
|
||||
roomFacilities: z.array(z.string()),
|
||||
})
|
||||
45
apps/scandic-web/server/routers/hotels/schemas/image.ts
Normal file
45
apps/scandic-web/server/routers/hotels/schemas/image.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { nullableStringValidator } from "@/utils/zod/stringValidator"
|
||||
|
||||
export const imageSizesSchema = z.object({
|
||||
large: nullableStringValidator,
|
||||
medium: nullableStringValidator,
|
||||
small: nullableStringValidator,
|
||||
tiny: nullableStringValidator,
|
||||
})
|
||||
|
||||
export const imageMetaDataSchema = z.object({
|
||||
altText: nullableStringValidator,
|
||||
altText_En: nullableStringValidator,
|
||||
copyRight: nullableStringValidator,
|
||||
title: nullableStringValidator,
|
||||
})
|
||||
|
||||
const DEFAULT_IMAGE_OBJ = {
|
||||
metaData: {
|
||||
altText: "Default image",
|
||||
altText_En: "Default image",
|
||||
copyRight: "Default image",
|
||||
title: "Default image",
|
||||
},
|
||||
imageSizes: {
|
||||
tiny: "https://placehold.co/1280x720",
|
||||
small: "https://placehold.co/1280x720",
|
||||
medium: "https://placehold.co/1280x720",
|
||||
large: "https://placehold.co/1280x720",
|
||||
},
|
||||
}
|
||||
|
||||
export const imageSchema = z
|
||||
.object({
|
||||
imageSizes: imageSizesSchema,
|
||||
metaData: imageMetaDataSchema,
|
||||
})
|
||||
.nullish()
|
||||
.transform((val) => {
|
||||
if (!val) {
|
||||
return DEFAULT_IMAGE_OBJ
|
||||
}
|
||||
return val
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const locationCitySchema = z.object({
|
||||
attributes: z.object({
|
||||
cityIdentifier: z.string().optional(),
|
||||
keyWords: z.array(z.string()).optional(),
|
||||
name: z.string().optional().default(""),
|
||||
}),
|
||||
country: z.string().optional().default(""),
|
||||
id: z.string().optional().default(""),
|
||||
type: z.literal("cities"),
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const locationHotelSchema = z.object({
|
||||
attributes: z.object({
|
||||
distanceToCentre: z.number().optional(),
|
||||
images: z
|
||||
.object({
|
||||
large: z.string().optional(),
|
||||
medium: z.string().optional(),
|
||||
small: z.string().optional(),
|
||||
tiny: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
keyWords: z.array(z.string()).optional(),
|
||||
name: z.string().optional().default(""),
|
||||
operaId: z.string().optional(),
|
||||
}),
|
||||
id: z.string().optional().default(""),
|
||||
relationships: z
|
||||
.object({
|
||||
city: z
|
||||
.object({
|
||||
links: z
|
||||
.object({
|
||||
related: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.optional(),
|
||||
type: z.literal("hotels"),
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { imageSchema } from "./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(),
|
||||
})
|
||||
),
|
||||
})
|
||||
63
apps/scandic-web/server/routers/hotels/schemas/packages.ts
Normal file
63
apps/scandic-web/server/routers/hotels/schemas/packages.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { imageSizesSchema } from "./image"
|
||||
|
||||
import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter"
|
||||
import { PackageTypeEnum } from "@/types/enums/packages"
|
||||
|
||||
// TODO: Remove optional and default when the API change has been deployed
|
||||
export const packagePriceSchema = z
|
||||
.object({
|
||||
currency: z.string().default("N/A"),
|
||||
price: z.string(),
|
||||
totalPrice: z.string(),
|
||||
})
|
||||
.optional()
|
||||
.default({
|
||||
currency: "N/A",
|
||||
price: "0",
|
||||
totalPrice: "0",
|
||||
})
|
||||
|
||||
const inventorySchema = z.object({
|
||||
date: z.string(),
|
||||
total: z.number(),
|
||||
available: z.number(),
|
||||
})
|
||||
|
||||
export const ancillaryContentSchema = z.object({
|
||||
status: z.string(),
|
||||
id: z.string(),
|
||||
variants: z.object({
|
||||
ancillary: z.object({ id: z.string(), price: packagePriceSchema }),
|
||||
ancillaryLoyalty: z
|
||||
.object({ points: z.number(), code: z.string() })
|
||||
.optional(),
|
||||
}),
|
||||
title: z.string(),
|
||||
descriptions: z.object({ html: z.string() }),
|
||||
images: z.array(z.object({ imageSizes: imageSizesSchema })),
|
||||
requiresDeliveryTime: z.boolean(),
|
||||
})
|
||||
|
||||
export const packageSchema = z.object({
|
||||
code: z.nativeEnum(RoomPackageCodeEnum),
|
||||
description: z.string(),
|
||||
inventories: z.array(inventorySchema),
|
||||
itemCode: z.string().default(""),
|
||||
localPrice: packagePriceSchema,
|
||||
requestedPrice: packagePriceSchema,
|
||||
})
|
||||
|
||||
export const breakfastPackageSchema = z.object({
|
||||
code: z.string(),
|
||||
description: z.string(),
|
||||
localPrice: packagePriceSchema,
|
||||
requestedPrice: packagePriceSchema,
|
||||
packageType: z.literal(PackageTypeEnum.BreakfastAdult),
|
||||
})
|
||||
|
||||
export const ancillaryPackageSchema = z.object({
|
||||
categoryName: z.string(),
|
||||
ancillaryContent: z.array(ancillaryContentSchema),
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { CurrencyEnum } from "@/types/enums/currency"
|
||||
|
||||
export const priceSchema = z.object({
|
||||
currency: z.nativeEnum(CurrencyEnum),
|
||||
pricePerNight: z.coerce.number(),
|
||||
pricePerStay: z.coerce.number(),
|
||||
})
|
||||
|
||||
export const productTypePriceSchema = z.object({
|
||||
localPrice: priceSchema,
|
||||
rateCode: z.string(),
|
||||
rateType: z.string().optional(),
|
||||
requestedPrice: priceSchema.optional(),
|
||||
// This is only used when a product is filtered out
|
||||
// so that we can still map out the correct titles a.so.
|
||||
oldRateCode: z.string().default(""),
|
||||
// Used to set the rate that we use to chose
|
||||
// titles etc.
|
||||
rate: z.string().default(""),
|
||||
})
|
||||
21
apps/scandic-web/server/routers/hotels/schemas/rate.ts
Normal file
21
apps/scandic-web/server/routers/hotels/schemas/rate.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const flexibilityPrice = z.object({
|
||||
member: z.number(),
|
||||
standard: z.number(),
|
||||
})
|
||||
|
||||
export const rateSchema = z.object({
|
||||
breakfastIncluded: z.boolean(),
|
||||
description: z.string(),
|
||||
id: z.number(),
|
||||
imageSrc: z.string(),
|
||||
name: z.string(),
|
||||
prices: z.object({
|
||||
currency: z.string(),
|
||||
freeCancellation: flexibilityPrice,
|
||||
freeRebooking: flexibilityPrice,
|
||||
nonRefundable: flexibilityPrice,
|
||||
}),
|
||||
size: z.string(),
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const relationshipsSchema = z.object({
|
||||
links: z.array(
|
||||
z.object({
|
||||
type: z.string(),
|
||||
url: z.string().url(),
|
||||
})
|
||||
),
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { imageSchema } from "./image"
|
||||
import { specialAlertsSchema } from "./specialAlerts"
|
||||
|
||||
const restaurantPriceSchema = z.object({
|
||||
currency: z.string(),
|
||||
amount: z.number(),
|
||||
})
|
||||
export const restaurantDaySchema = z.object({
|
||||
sortOrder: z.number(),
|
||||
alwaysOpen: z.boolean(),
|
||||
isClosed: z.boolean(),
|
||||
openingTime: z.string(),
|
||||
closingTime: z.string(),
|
||||
})
|
||||
export const restaurantOpeningHoursSchema = z.object({
|
||||
isActive: z.boolean(),
|
||||
name: z.string().optional(),
|
||||
monday: restaurantDaySchema.optional(),
|
||||
tuesday: restaurantDaySchema.optional(),
|
||||
wednesday: restaurantDaySchema.optional(),
|
||||
thursday: restaurantDaySchema.optional(),
|
||||
friday: restaurantDaySchema.optional(),
|
||||
saturday: restaurantDaySchema.optional(),
|
||||
sunday: restaurantDaySchema.optional(),
|
||||
})
|
||||
|
||||
const restaurantOpeningDetailSchema = z.object({
|
||||
openingHours: restaurantOpeningHoursSchema,
|
||||
alternateOpeningHours: restaurantOpeningHoursSchema.optional(),
|
||||
})
|
||||
|
||||
export const restaurantSchema = z
|
||||
.object({
|
||||
attributes: z.object({
|
||||
name: z.string(),
|
||||
isPublished: z.boolean().default(false),
|
||||
restaurantPage: z.boolean(),
|
||||
email: z.string().optional(),
|
||||
phoneNumber: z.string().optional(),
|
||||
externalBreakfast: z
|
||||
.object({
|
||||
isAvailable: z.boolean(),
|
||||
localPriceForExternalGuests: restaurantPriceSchema.optional(),
|
||||
requestedPriceForExternalGuests: restaurantPriceSchema.optional(),
|
||||
})
|
||||
.optional(),
|
||||
menus: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
url: z.string(),
|
||||
})
|
||||
)
|
||||
.default([]),
|
||||
openingDetails: z.array(restaurantOpeningDetailSchema).default([]),
|
||||
content: z.object({
|
||||
images: z.array(imageSchema),
|
||||
texts: z.object({
|
||||
descriptions: z.object({
|
||||
short: z.string().default(""),
|
||||
medium: z.string().default(""),
|
||||
}),
|
||||
}),
|
||||
bookTableUrl: z.string().optional(),
|
||||
specialAlerts: specialAlertsSchema,
|
||||
}),
|
||||
}),
|
||||
id: z.string(),
|
||||
type: z.literal("restaurants"),
|
||||
})
|
||||
.transform(({ attributes, id, type }) => ({ ...attributes, id, type }))
|
||||
|
||||
export const getRestaurantsSchema = z
|
||||
.object({
|
||||
data: z.array(restaurantSchema),
|
||||
})
|
||||
.transform(({ data }) => {
|
||||
return data.filter((item) => !!item.isPublished)
|
||||
})
|
||||
122
apps/scandic-web/server/routers/hotels/schemas/room.ts
Normal file
122
apps/scandic-web/server/routers/hotels/schemas/room.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { BedTypeEnum, ExtraBedTypeEnum } from "@/constants/booking"
|
||||
|
||||
import { imageSchema } from "./image"
|
||||
|
||||
const roomContentSchema = z.object({
|
||||
images: z.array(imageSchema),
|
||||
texts: z.object({
|
||||
descriptions: z.object({
|
||||
short: z.string().optional(),
|
||||
medium: z.string().optional(),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
|
||||
const roomTypesSchema = z.object({
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
code: z.string(),
|
||||
roomCount: z.number(),
|
||||
mainBed: z
|
||||
.object({
|
||||
type: z.string(),
|
||||
description: z.string(),
|
||||
widthRange: z.object({
|
||||
min: z.number(),
|
||||
max: z.number(),
|
||||
}),
|
||||
})
|
||||
.transform((data) => ({
|
||||
type:
|
||||
data.type in BedTypeEnum
|
||||
? (data.type as BedTypeEnum)
|
||||
: BedTypeEnum.Other,
|
||||
description: data.description,
|
||||
widthRange: data.widthRange,
|
||||
})),
|
||||
fixedExtraBed: z
|
||||
.object({
|
||||
type: z.string(),
|
||||
description: z.string().optional(),
|
||||
widthRange: z.object({
|
||||
min: z.number(),
|
||||
max: z.number(),
|
||||
}),
|
||||
})
|
||||
.transform((data) => {
|
||||
return data.type in ExtraBedTypeEnum
|
||||
? {
|
||||
type: data.type as ExtraBedTypeEnum,
|
||||
description: data.description,
|
||||
}
|
||||
: undefined
|
||||
}),
|
||||
roomSize: z.object({
|
||||
min: z.number(),
|
||||
max: z.number(),
|
||||
}),
|
||||
occupancy: z.object({
|
||||
total: z.number(),
|
||||
adults: z.number(),
|
||||
children: z.number(),
|
||||
}),
|
||||
isLackingCribs: z.boolean(),
|
||||
isLackingExtraBeds: z.boolean(),
|
||||
})
|
||||
|
||||
const roomFacilitiesSchema = z.object({
|
||||
availableInAllRooms: z.boolean(),
|
||||
name: z.string(),
|
||||
isUniqueSellingPoint: z.boolean(),
|
||||
sortOrder: z.number(),
|
||||
icon: z.string().optional(),
|
||||
})
|
||||
|
||||
export const roomSchema = z
|
||||
.object({
|
||||
attributes: z.object({
|
||||
name: z.string(),
|
||||
sortOrder: z.number(),
|
||||
content: roomContentSchema,
|
||||
roomTypes: z.array(roomTypesSchema),
|
||||
roomFacilities: z.array(roomFacilitiesSchema),
|
||||
occupancy: z.object({
|
||||
min: z.number(),
|
||||
max: z.number(),
|
||||
}),
|
||||
roomSize: z.object({
|
||||
min: z.number(),
|
||||
max: z.number(),
|
||||
}),
|
||||
}),
|
||||
id: z.string(),
|
||||
type: z.literal("roomcategories"),
|
||||
})
|
||||
.transform((data) => {
|
||||
return {
|
||||
descriptions: data.attributes.content.texts.descriptions,
|
||||
id: data.id,
|
||||
images: data.attributes.content.images,
|
||||
name: data.attributes.name,
|
||||
occupancy: data.attributes.occupancy,
|
||||
totalOccupancy:
|
||||
data.attributes.occupancy.min === data.attributes.occupancy.max
|
||||
? {
|
||||
max: data.attributes.occupancy.max,
|
||||
range: `${data.attributes.occupancy.max}`,
|
||||
}
|
||||
: {
|
||||
max: data.attributes.occupancy.max,
|
||||
range: `${data.attributes.occupancy.min}-${data.attributes.occupancy.max}`,
|
||||
},
|
||||
roomSize: data.attributes.roomSize,
|
||||
roomTypes: data.attributes.roomTypes,
|
||||
sortOrder: data.attributes.sortOrder,
|
||||
type: data.type,
|
||||
roomFacilities: data.attributes.roomFacilities,
|
||||
}
|
||||
})
|
||||
|
||||
export type RoomType = Pick<z.output<typeof roomSchema>, "roomTypes" | "name">
|
||||
@@ -0,0 +1,83 @@
|
||||
import deepmerge from "deepmerge"
|
||||
import { z } from "zod"
|
||||
|
||||
import { productSchema } from "./product"
|
||||
|
||||
import { AvailabilityEnum } from "@/types/components/hotelReservation/selectHotel/selectHotel"
|
||||
import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter"
|
||||
|
||||
export const roomConfigurationSchema = z
|
||||
.object({
|
||||
breakfastIncludedInAllRatesMember: z.boolean().default(false),
|
||||
breakfastIncludedInAllRatesPublic: z.boolean().default(false),
|
||||
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(),
|
||||
status: z.string(),
|
||||
})
|
||||
.transform((data) => {
|
||||
if (data.products.length) {
|
||||
const someProductsMissAtLeastOneRateCode = data.products.some(
|
||||
({ productType }) =>
|
||||
!productType.public.rateCode || !productType.member?.rateCode
|
||||
)
|
||||
if (someProductsMissAtLeastOneRateCode) {
|
||||
data.products = data.products.map((product) => {
|
||||
if (
|
||||
product.productType.public.rateCode &&
|
||||
product.productType.member?.rateCode
|
||||
) {
|
||||
return product
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset both rateCodes if one is missing to show `No prices available` for the same reason as
|
||||
* mentioned above.
|
||||
*
|
||||
* TODO: (Maybe) notify somewhere that this happened
|
||||
*/
|
||||
return deepmerge(product, {
|
||||
productType: {
|
||||
member: {
|
||||
rateCode: "",
|
||||
oldRateCode: product.productType.member?.rateCode,
|
||||
},
|
||||
public: {
|
||||
rateCode: "",
|
||||
oldRateCode: product.productType.public.rateCode,
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* When all products miss at least one rateCode (member or public), we change the status to NotAvailable
|
||||
* since we cannot as of now (31 january) guarantee the flow with missing rateCodes.
|
||||
*
|
||||
* TODO: (Maybe) notify somewhere that this happened
|
||||
*/
|
||||
const allProductsMissAtLeastOneRateCode = data.products.every(
|
||||
({ productType }) =>
|
||||
!productType.public.rateCode || !productType.member?.rateCode
|
||||
)
|
||||
if (allProductsMissAtLeastOneRateCode) {
|
||||
data.status = AvailabilityEnum.NotAvailable
|
||||
}
|
||||
}
|
||||
|
||||
return data
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { productTypePriceSchema } from "../productTypePrice"
|
||||
|
||||
import { CurrencyEnum } from "@/types/enums/currency"
|
||||
|
||||
export const productSchema = z.object({
|
||||
productType: z.object({
|
||||
member: productTypePriceSchema.optional(),
|
||||
public: productTypePriceSchema.default({
|
||||
localPrice: {
|
||||
currency: CurrencyEnum.SEK,
|
||||
pricePerNight: 0,
|
||||
pricePerStay: 0,
|
||||
},
|
||||
rateCode: "",
|
||||
rateType: "",
|
||||
requestedPrice: undefined,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const rateDefinitionSchema = z.object({
|
||||
breakfastIncluded: z.boolean(),
|
||||
cancellationRule: z.string(),
|
||||
cancellationText: z.string(),
|
||||
generalTerms: z.array(z.string()),
|
||||
mustBeGuaranteed: z.boolean(),
|
||||
rateCode: z.string(),
|
||||
rateType: z.string().optional(),
|
||||
title: z.string(),
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { dt } from "@/lib/dt"
|
||||
|
||||
import { AlertTypeEnum } from "@/types/enums/alert"
|
||||
|
||||
const specialAlertSchema = z.object({
|
||||
type: z.string(),
|
||||
title: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
displayInBookingFlow: z.boolean(),
|
||||
startDate: z.string().optional(),
|
||||
endDate: z.string().optional(),
|
||||
})
|
||||
|
||||
export const specialAlertsSchema = z
|
||||
.array(specialAlertSchema)
|
||||
.transform((data) => {
|
||||
const now = dt().utc().format("YYYY-MM-DD")
|
||||
const filteredAlerts = data.filter((alert) => {
|
||||
let shouldShowNow = true
|
||||
|
||||
if (alert.startDate && alert.startDate > now) {
|
||||
shouldShowNow = false
|
||||
}
|
||||
if (alert.endDate && alert.endDate < now) {
|
||||
shouldShowNow = false
|
||||
}
|
||||
const hasText = alert.description || alert.title
|
||||
return shouldShowNow && hasText
|
||||
})
|
||||
return filteredAlerts.map((alert, idx) => ({
|
||||
id: `alert-${alert.type}-${idx}`,
|
||||
type: AlertTypeEnum.Info,
|
||||
heading: alert.title || null,
|
||||
text: alert.description || null,
|
||||
}))
|
||||
})
|
||||
.default([])
|
||||
104
apps/scandic-web/server/routers/hotels/telemetry.ts
Normal file
104
apps/scandic-web/server/routers/hotels/telemetry.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { metrics } from "@opentelemetry/api"
|
||||
|
||||
const meter = metrics.getMeter("trpc.hotels")
|
||||
export const getHotelCounter = meter.createCounter("trpc.hotel.get")
|
||||
export const getHotelSuccessCounter = meter.createCounter(
|
||||
"trpc.hotel.get-success"
|
||||
)
|
||||
export const getHotelFailCounter = meter.createCounter("trpc.hotel.get-fail")
|
||||
|
||||
export const getPackagesCounter = meter.createCounter("trpc.hotel.packages.get")
|
||||
export const getPackagesSuccessCounter = meter.createCounter(
|
||||
"trpc.hotel.packages.get-success"
|
||||
)
|
||||
export const getPackagesFailCounter = meter.createCounter(
|
||||
"trpc.hotel.packages.get-fail"
|
||||
)
|
||||
|
||||
export const hotelsAvailabilityCounter = meter.createCounter(
|
||||
"trpc.hotel.availability.hotels"
|
||||
)
|
||||
export const hotelsAvailabilitySuccessCounter = meter.createCounter(
|
||||
"trpc.hotel.availability.hotels-success"
|
||||
)
|
||||
export const hotelsAvailabilityFailCounter = meter.createCounter(
|
||||
"trpc.hotel.availability.hotels-fail"
|
||||
)
|
||||
|
||||
export const hotelsByHotelIdAvailabilityCounter = meter.createCounter(
|
||||
"trpc.hotel.availability.hotels-by-hotel-id"
|
||||
)
|
||||
export const hotelsByHotelIdAvailabilitySuccessCounter = meter.createCounter(
|
||||
"trpc.hotel.availability.hotels-by-hotel-id-success"
|
||||
)
|
||||
export const hotelsByHotelIdAvailabilityFailCounter = meter.createCounter(
|
||||
"trpc.hotel.availability.hotels-by-hotel-id-fail"
|
||||
)
|
||||
|
||||
export const selectedRoomAvailabilityCounter = meter.createCounter(
|
||||
"trpc.hotel.availability.room"
|
||||
)
|
||||
export const selectedRoomAvailabilitySuccessCounter = meter.createCounter(
|
||||
"trpc.hotel.availability.room-success"
|
||||
)
|
||||
export const selectedRoomAvailabilityFailCounter = meter.createCounter(
|
||||
"trpc.hotel.availability.room-fail"
|
||||
)
|
||||
|
||||
export const breakfastPackagesCounter = meter.createCounter(
|
||||
"trpc.package.breakfast"
|
||||
)
|
||||
export const breakfastPackagesSuccessCounter = meter.createCounter(
|
||||
"trpc.package.breakfast-success"
|
||||
)
|
||||
export const breakfastPackagesFailCounter = meter.createCounter(
|
||||
"trpc.package.breakfast-fail"
|
||||
)
|
||||
|
||||
export const getHotelsCounter = meter.createCounter("trpc.hotel.hotels.get")
|
||||
export const getHotelsSuccessCounter = meter.createCounter(
|
||||
"trpc.hotel.hotels.get-success"
|
||||
)
|
||||
export const getHotelsFailCounter = meter.createCounter(
|
||||
"trpc.hotel.hotels.get-fail"
|
||||
)
|
||||
|
||||
export const getHotelIdsCounter = meter.createCounter(
|
||||
"trpc.hotel.hotel-ids.get"
|
||||
)
|
||||
export const getHotelIdsSuccessCounter = meter.createCounter(
|
||||
"trpc.hotel.hotel-ids.get-success"
|
||||
)
|
||||
export const getHotelIdsFailCounter = meter.createCounter(
|
||||
"trpc.hotel.hotel-ids.get-fail"
|
||||
)
|
||||
|
||||
export const nearbyHotelIdsCounter = meter.createCounter(
|
||||
"trpc.hotel.nearby-hotel-ids.get"
|
||||
)
|
||||
export const nearbyHotelIdsSuccessCounter = meter.createCounter(
|
||||
"trpc.hotel.nearby-hotel-ids.get-success"
|
||||
)
|
||||
export const nearbyHotelIdsFailCounter = meter.createCounter(
|
||||
"trpc.hotel.nearby-hotel-ids.get-fail"
|
||||
)
|
||||
|
||||
export const meetingRoomsCounter = meter.createCounter(
|
||||
"trpc.hotels.meetingRooms"
|
||||
)
|
||||
export const meetingRoomsSuccessCounter = meter.createCounter(
|
||||
"trpc.hotels.meetingRooms-success"
|
||||
)
|
||||
export const meetingRoomsFailCounter = meter.createCounter(
|
||||
"trpc.hotels.meetingRooms-fail"
|
||||
)
|
||||
|
||||
export const additionalDataCounter = meter.createCounter(
|
||||
"trpc.hotels.additionalData"
|
||||
)
|
||||
export const additionalDataSuccessCounter = meter.createCounter(
|
||||
"trpc.hotels.additionalData-success"
|
||||
)
|
||||
export const additionalDataFailCounter = meter.createCounter(
|
||||
"trpc.hotels.additionalData-fail"
|
||||
)
|
||||
1628
apps/scandic-web/server/routers/hotels/tempHotelData.json
Normal file
1628
apps/scandic-web/server/routers/hotels/tempHotelData.json
Normal file
File diff suppressed because it is too large
Load Diff
104
apps/scandic-web/server/routers/hotels/tempRatesData.json
Normal file
104
apps/scandic-web/server/routers/hotels/tempRatesData.json
Normal file
@@ -0,0 +1,104 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Cabin",
|
||||
"description": "Stylish, peaceful and air-conditioned room. The rooms have small clerestory windows.",
|
||||
"size": "17 - 24 m² (1 - 2 persons)",
|
||||
"imageSrc": "https://www.scandichotels.se/imageVault/publishedmedia/xnmqnmz6mz0uhuat0917/scandic-helsinki-hub-room-standard-KR-7.jpg",
|
||||
"breakfastIncluded": false,
|
||||
"prices": {
|
||||
"currency": "SEK",
|
||||
"nonRefundable": {
|
||||
"standard": 2315,
|
||||
"member": 2247
|
||||
},
|
||||
"freeRebooking": { "standard": 2437, "member": 2365 },
|
||||
"freeCancellation": { "standard": 2620, "member": 2542 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Standard",
|
||||
"description": "Stylish, peaceful and air-conditioned room. The rooms have small clerestory windows.",
|
||||
"size": "19 - 30 m² (1 - 2 persons)",
|
||||
"imageSrc": "https://www.scandichotels.se/imageVault/publishedmedia/xnmqnmz6mz0uhuat0917/scandic-helsinki-hub-room-standard-KR-7.jpg",
|
||||
"breakfastIncluded": false,
|
||||
"prices": {
|
||||
"currency": "SEK",
|
||||
"nonRefundable": {
|
||||
"standard": 2315,
|
||||
"member": 2247
|
||||
},
|
||||
"freeRebooking": { "standard": 2437, "member": 2365 },
|
||||
"freeCancellation": { "standard": 2620, "member": 2542 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "Superior",
|
||||
"description": "Stylish, peaceful and air-conditioned room. The rooms have small clerestory windows.",
|
||||
"size": "22 - 40 m² (1 - 3 persons)",
|
||||
"imageSrc": "https://www.scandichotels.se/imageVault/publishedmedia/xnmqnmz6mz0uhuat0917/scandic-helsinki-hub-room-standard-KR-7.jpg",
|
||||
"breakfastIncluded": false,
|
||||
"prices": {
|
||||
"currency": "SEK",
|
||||
"nonRefundable": {
|
||||
"standard": 2315,
|
||||
"member": 2247
|
||||
},
|
||||
"freeRebooking": { "standard": 2437, "member": 2365 },
|
||||
"freeCancellation": { "standard": 2620, "member": 2542 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"name": "Superior Family",
|
||||
"description": "Stylish, peaceful and air-conditioned room. The rooms have small clerestory windows.",
|
||||
"size": "29 - 49 m² (3 - 4 persons)",
|
||||
"imageSrc": "https://www.scandichotels.se/imageVault/publishedmedia/xnmqnmz6mz0uhuat0917/scandic-helsinki-hub-room-standard-KR-7.jpg",
|
||||
"breakfastIncluded": false,
|
||||
"prices": {
|
||||
"currency": "SEK",
|
||||
"nonRefundable": {
|
||||
"standard": 2315,
|
||||
"member": 2247
|
||||
},
|
||||
"freeRebooking": { "standard": 2437, "member": 2365 },
|
||||
"freeCancellation": { "standard": 2620, "member": 2542 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"name": "Superior PLUS",
|
||||
"description": "Stylish, peaceful and air-conditioned room. The rooms have small clerestory windows.",
|
||||
"size": "21 - 28 m² (2 - 3 persons)",
|
||||
"imageSrc": "https://www.scandichotels.se/imageVault/publishedmedia/xnmqnmz6mz0uhuat0917/scandic-helsinki-hub-room-standard-KR-7.jpg",
|
||||
"breakfastIncluded": false,
|
||||
"prices": {
|
||||
"currency": "SEK",
|
||||
"nonRefundable": {
|
||||
"standard": 2315,
|
||||
"member": 2247
|
||||
},
|
||||
"freeRebooking": { "standard": 2437, "member": 2365 },
|
||||
"freeCancellation": { "standard": 2620, "member": 2542 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"name": "Junior Suite",
|
||||
"description": "Stylish, peaceful and air-conditioned room. The rooms have small clerestory windows.",
|
||||
"size": "35 - 43 m² (2 - 4 persons)",
|
||||
"imageSrc": "https://www.scandichotels.se/imageVault/publishedmedia/xnmqnmz6mz0uhuat0917/scandic-helsinki-hub-room-standard-KR-7.jpg",
|
||||
"breakfastIncluded": false,
|
||||
"prices": {
|
||||
"currency": "SEK",
|
||||
"nonRefundable": {
|
||||
"standard": 2315,
|
||||
"member": 2247
|
||||
},
|
||||
"freeRebooking": { "standard": 2437, "member": 2365 },
|
||||
"freeCancellation": { "standard": 2620, "member": 2542 }
|
||||
}
|
||||
}
|
||||
]
|
||||
500
apps/scandic-web/server/routers/hotels/utils.ts
Normal file
500
apps/scandic-web/server/routers/hotels/utils.ts
Normal file
@@ -0,0 +1,500 @@
|
||||
import deepmerge from "deepmerge"
|
||||
import { unstable_cache } from "next/cache"
|
||||
|
||||
import { Lang } from "@/constants/languages"
|
||||
import { env } from "@/env/server"
|
||||
import * as api from "@/lib/api"
|
||||
import { toApiLang } from "@/server/utils"
|
||||
|
||||
import { getHotelPageUrls } from "../contentstack/hotelPage/utils"
|
||||
import { metrics } from "./metrics"
|
||||
import {
|
||||
citiesByCountrySchema,
|
||||
citiesSchema,
|
||||
countriesSchema,
|
||||
getHotelIdsSchema,
|
||||
locationsSchema,
|
||||
} from "./output"
|
||||
import { getHotel } from "./query"
|
||||
|
||||
import { PointOfInterestGroupEnum } from "@/types/enums/pointOfInterest"
|
||||
import type { RequestOptionsWithOutBody } from "@/types/fetch"
|
||||
import type { HotelDataWithUrl } from "@/types/hotel"
|
||||
import type {
|
||||
CitiesGroupedByCountry,
|
||||
CityLocation,
|
||||
HotelLocation,
|
||||
} from "@/types/trpc/routers/hotel/locations"
|
||||
import type { Endpoint } from "@/lib/api/endpoints"
|
||||
|
||||
export function getPoiGroupByCategoryName(category: string | undefined) {
|
||||
if (!category) return PointOfInterestGroupEnum.LOCATION
|
||||
switch (category) {
|
||||
case "Airport":
|
||||
case "Bus terminal":
|
||||
case "Transportations":
|
||||
return PointOfInterestGroupEnum.PUBLIC_TRANSPORT
|
||||
case "Amusement park":
|
||||
case "Museum":
|
||||
case "Sports":
|
||||
case "Theatre":
|
||||
case "Tourist":
|
||||
case "Zoo":
|
||||
return PointOfInterestGroupEnum.ATTRACTIONS
|
||||
case "Nearby companies":
|
||||
case "Fair":
|
||||
return PointOfInterestGroupEnum.BUSINESS
|
||||
case "Parking / Garage":
|
||||
return PointOfInterestGroupEnum.PARKING
|
||||
case "Shopping":
|
||||
case "Restaurant":
|
||||
return PointOfInterestGroupEnum.SHOPPING_DINING
|
||||
case "Hospital":
|
||||
default:
|
||||
return PointOfInterestGroupEnum.LOCATION
|
||||
}
|
||||
}
|
||||
|
||||
export const locationsAffix = "locations"
|
||||
|
||||
export const TWENTYFOUR_HOURS = 60 * 60 * 24
|
||||
export async function getCity(
|
||||
cityUrl: string,
|
||||
options: RequestOptionsWithOutBody,
|
||||
lang: Lang,
|
||||
relationshipCity: HotelLocation["relationships"]["city"]
|
||||
) {
|
||||
return unstable_cache(
|
||||
async function (locationCityUrl: string) {
|
||||
const url = new URL(locationCityUrl)
|
||||
const cityResponse = await api.get(
|
||||
url.pathname as Endpoint,
|
||||
options,
|
||||
url.searchParams
|
||||
)
|
||||
|
||||
if (!cityResponse.ok) {
|
||||
return null
|
||||
}
|
||||
|
||||
const cityJson = await cityResponse.json()
|
||||
const city = citiesSchema.safeParse(cityJson)
|
||||
if (!city.success) {
|
||||
console.info(`Validation of city failed`)
|
||||
console.info(`cityUrl: ${locationCityUrl}`)
|
||||
console.error(city.error)
|
||||
return null
|
||||
}
|
||||
|
||||
return city.data
|
||||
},
|
||||
[cityUrl, `${lang}:${relationshipCity}`],
|
||||
{ revalidate: TWENTYFOUR_HOURS }
|
||||
)(cityUrl)
|
||||
}
|
||||
|
||||
export async function getCountries(
|
||||
options: RequestOptionsWithOutBody,
|
||||
params: URLSearchParams,
|
||||
lang: Lang
|
||||
) {
|
||||
return unstable_cache(
|
||||
async function (searchParams) {
|
||||
const countryResponse = await api.get(
|
||||
api.endpoints.v1.Hotel.countries,
|
||||
options,
|
||||
searchParams
|
||||
)
|
||||
|
||||
if (!countryResponse.ok) {
|
||||
return null
|
||||
}
|
||||
|
||||
const countriesJson = await countryResponse.json()
|
||||
const countries = countriesSchema.safeParse(countriesJson)
|
||||
if (!countries.success) {
|
||||
console.info(`Validation for countries failed`)
|
||||
console.error(countries.error)
|
||||
return null
|
||||
}
|
||||
|
||||
return countries.data
|
||||
},
|
||||
[`${lang}:${locationsAffix}:countries`, params.toString()],
|
||||
{ revalidate: TWENTYFOUR_HOURS }
|
||||
)(params)
|
||||
}
|
||||
|
||||
export async function getCitiesByCountry(
|
||||
countries: string[],
|
||||
options: RequestOptionsWithOutBody,
|
||||
params: URLSearchParams,
|
||||
lang: Lang,
|
||||
onlyPublished = false, // false by default as it might be used in other places
|
||||
affix: string = locationsAffix
|
||||
) {
|
||||
return unstable_cache(
|
||||
async function (
|
||||
searchParams: URLSearchParams,
|
||||
searchedCountries: string[]
|
||||
) {
|
||||
const citiesGroupedByCountry: CitiesGroupedByCountry = {}
|
||||
|
||||
await Promise.all(
|
||||
searchedCountries.map(async (country) => {
|
||||
const countryResponse = await api.get(
|
||||
api.endpoints.v1.Hotel.Cities.country(country),
|
||||
options,
|
||||
searchParams
|
||||
)
|
||||
|
||||
if (!countryResponse.ok) {
|
||||
return null
|
||||
}
|
||||
|
||||
const countryJson = await countryResponse.json()
|
||||
const citiesByCountry = citiesByCountrySchema.safeParse(countryJson)
|
||||
if (!citiesByCountry.success) {
|
||||
console.info(`Failed to validate Cities by Country payload`)
|
||||
console.error(citiesByCountry.error)
|
||||
return null
|
||||
}
|
||||
|
||||
const cities = onlyPublished
|
||||
? citiesByCountry.data.data.filter((city) => city.isPublished)
|
||||
: citiesByCountry.data.data
|
||||
citiesGroupedByCountry[country] = cities
|
||||
return true
|
||||
})
|
||||
)
|
||||
|
||||
return citiesGroupedByCountry
|
||||
},
|
||||
[
|
||||
`${lang}:${affix}:cities-by-country`,
|
||||
params.toString(),
|
||||
JSON.stringify(countries),
|
||||
],
|
||||
{ revalidate: TWENTYFOUR_HOURS }
|
||||
)(params, countries)
|
||||
}
|
||||
|
||||
export async function getLocations(
|
||||
lang: Lang,
|
||||
options: RequestOptionsWithOutBody,
|
||||
params: URLSearchParams,
|
||||
citiesByCountry: CitiesGroupedByCountry | null
|
||||
) {
|
||||
return unstable_cache(
|
||||
async function (
|
||||
searchParams: URLSearchParams,
|
||||
groupedCitiesByCountry: CitiesGroupedByCountry | null
|
||||
) {
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v1.Hotel.locations,
|
||||
options,
|
||||
searchParams
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
if (apiResponse.status === 401) {
|
||||
return { error: true, cause: "unauthorized" } as const
|
||||
} else if (apiResponse.status === 403) {
|
||||
return { error: true, cause: "forbidden" } as const
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const verifiedLocations = locationsSchema.safeParse(apiJson)
|
||||
if (!verifiedLocations.success) {
|
||||
console.info(`Locations Verification Failed`)
|
||||
console.error(verifiedLocations.error)
|
||||
return null
|
||||
}
|
||||
|
||||
return await Promise.all(
|
||||
verifiedLocations.data.data.map(async (location) => {
|
||||
if (location.type === "cities") {
|
||||
if (groupedCitiesByCountry) {
|
||||
const country = Object.keys(groupedCitiesByCountry).find(
|
||||
(country) => {
|
||||
if (
|
||||
groupedCitiesByCountry[country].find(
|
||||
(loc) => loc.name === location.name
|
||||
)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
)
|
||||
if (country) {
|
||||
return {
|
||||
...location,
|
||||
country,
|
||||
}
|
||||
} else {
|
||||
console.info(
|
||||
`Location cannot be found in any of the countries cities`
|
||||
)
|
||||
console.info(location)
|
||||
}
|
||||
}
|
||||
} else if (location.type === "hotels") {
|
||||
if (location.relationships.city?.url) {
|
||||
const city = await getCity(
|
||||
location.relationships.city.url,
|
||||
options,
|
||||
lang,
|
||||
location.relationships.city
|
||||
)
|
||||
if (city) {
|
||||
return deepmerge(location, {
|
||||
relationships: {
|
||||
city,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return location
|
||||
})
|
||||
)
|
||||
},
|
||||
[
|
||||
`${lang}:${locationsAffix}`,
|
||||
params.toString(),
|
||||
JSON.stringify(citiesByCountry),
|
||||
],
|
||||
{ revalidate: TWENTYFOUR_HOURS }
|
||||
)(params, citiesByCountry)
|
||||
}
|
||||
|
||||
export async function getHotelIdsByCityId(
|
||||
cityId: string,
|
||||
options: RequestOptionsWithOutBody,
|
||||
params: URLSearchParams
|
||||
) {
|
||||
return unstable_cache(
|
||||
async function (params: URLSearchParams) {
|
||||
metrics.hotelIds.counter.add(1, { params: params.toString() })
|
||||
console.info(
|
||||
"api.hotel.hotel-ids start",
|
||||
JSON.stringify({ params: params.toString() })
|
||||
)
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v1.Hotel.hotels,
|
||||
options,
|
||||
params
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
const responseMessage = await apiResponse.text()
|
||||
metrics.hotelIds.fail.add(1, {
|
||||
params: params.toString(),
|
||||
error_type: "http_error",
|
||||
error: responseMessage,
|
||||
})
|
||||
console.error(
|
||||
"api.hotel.hotel-ids fetch error",
|
||||
JSON.stringify({
|
||||
params: params.toString(),
|
||||
error: {
|
||||
status: apiResponse.status,
|
||||
statusText: apiResponse.statusText,
|
||||
text: responseMessage,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const validatedHotelIds = getHotelIdsSchema.safeParse(apiJson)
|
||||
if (!validatedHotelIds.success) {
|
||||
metrics.hotelIds.fail.add(1, {
|
||||
params: params.toString(),
|
||||
error_type: "validation_error",
|
||||
error: JSON.stringify(validatedHotelIds.error),
|
||||
})
|
||||
console.error(
|
||||
"api.hotel.hotel-ids validation error",
|
||||
JSON.stringify({
|
||||
params: params.toString(),
|
||||
error: validatedHotelIds.error,
|
||||
})
|
||||
)
|
||||
return []
|
||||
}
|
||||
|
||||
metrics.hotelIds.success.add(1, { cityId })
|
||||
console.info(
|
||||
"api.hotel.hotel-ids success",
|
||||
JSON.stringify({
|
||||
params: params.toString(),
|
||||
response: validatedHotelIds.data,
|
||||
})
|
||||
)
|
||||
|
||||
return validatedHotelIds.data
|
||||
},
|
||||
[`hotelsByCityId`, params.toString()],
|
||||
{ revalidate: env.CACHE_TIME_HOTELS }
|
||||
)(params)
|
||||
}
|
||||
|
||||
export async function getHotelIdsByCountry(
|
||||
country: string,
|
||||
options: RequestOptionsWithOutBody,
|
||||
params: URLSearchParams
|
||||
) {
|
||||
return unstable_cache(
|
||||
async function (params: URLSearchParams) {
|
||||
metrics.hotelIds.counter.add(1, { country })
|
||||
console.info(
|
||||
"api.hotel.hotel-ids start",
|
||||
JSON.stringify({ query: { country } })
|
||||
)
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v1.Hotel.hotels,
|
||||
options,
|
||||
params
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
const responseMessage = await apiResponse.text()
|
||||
metrics.hotelIds.fail.add(1, {
|
||||
country,
|
||||
error_type: "http_error",
|
||||
error: responseMessage,
|
||||
})
|
||||
console.error(
|
||||
"api.hotel.hotel-ids fetch error",
|
||||
JSON.stringify({
|
||||
query: { country },
|
||||
error: {
|
||||
status: apiResponse.status,
|
||||
statusText: apiResponse.statusText,
|
||||
text: responseMessage,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const validatedHotelIds = getHotelIdsSchema.safeParse(apiJson)
|
||||
if (!validatedHotelIds.success) {
|
||||
metrics.hotelIds.fail.add(1, {
|
||||
country,
|
||||
error_type: "validation_error",
|
||||
error: JSON.stringify(validatedHotelIds.error),
|
||||
})
|
||||
console.error(
|
||||
"api.hotel.hotel-ids validation error",
|
||||
JSON.stringify({
|
||||
query: { country },
|
||||
error: validatedHotelIds.error,
|
||||
})
|
||||
)
|
||||
return []
|
||||
}
|
||||
|
||||
metrics.hotelIds.success.add(1, { country })
|
||||
console.info(
|
||||
"api.hotel.hotel-ids success",
|
||||
JSON.stringify({ query: { country } })
|
||||
)
|
||||
|
||||
return validatedHotelIds.data
|
||||
},
|
||||
[`hotelsByCountry`, params.toString()],
|
||||
{ revalidate: env.CACHE_TIME_HOTELS }
|
||||
)(params)
|
||||
}
|
||||
|
||||
export async function getHotelIdsByCityIdentifier(
|
||||
cityIdentifier: string,
|
||||
serviceToken: string
|
||||
) {
|
||||
const apiLang = toApiLang(Lang.en)
|
||||
const city = await getCityByCityIdentifier(cityIdentifier, serviceToken)
|
||||
|
||||
if (!city) {
|
||||
return []
|
||||
}
|
||||
|
||||
const hotelIdsParams = new URLSearchParams({
|
||||
language: apiLang,
|
||||
city: city.id,
|
||||
})
|
||||
const options: RequestOptionsWithOutBody = {
|
||||
// needs to clear default option as only
|
||||
// cache or next.revalidate is permitted
|
||||
cache: undefined,
|
||||
headers: {
|
||||
Authorization: `Bearer ${serviceToken}`,
|
||||
},
|
||||
next: {
|
||||
revalidate: env.CACHE_TIME_HOTELS,
|
||||
},
|
||||
}
|
||||
const hotelIds = await getHotelIdsByCityId(city.id, options, hotelIdsParams)
|
||||
return hotelIds
|
||||
}
|
||||
|
||||
export async function getCityByCityIdentifier(
|
||||
cityIdentifier: string,
|
||||
serviceToken: string
|
||||
) {
|
||||
const lang = Lang.en
|
||||
const apiLang = toApiLang(lang)
|
||||
const options: RequestOptionsWithOutBody = {
|
||||
// needs to clear default option as only
|
||||
// cache or next.revalidate is permitted
|
||||
cache: undefined,
|
||||
headers: {
|
||||
Authorization: `Bearer ${serviceToken}`,
|
||||
},
|
||||
next: {
|
||||
revalidate: env.CACHE_TIME_HOTELS,
|
||||
},
|
||||
}
|
||||
const params = new URLSearchParams({
|
||||
language: apiLang,
|
||||
})
|
||||
const locations = await getLocations(lang, options, params, null)
|
||||
if (!locations || "error" in locations) {
|
||||
return null
|
||||
}
|
||||
|
||||
const city = locations
|
||||
.filter((loc): loc is CityLocation => loc.type === "cities")
|
||||
.find((loc) => loc.cityIdentifier === cityIdentifier)
|
||||
|
||||
return city ?? null
|
||||
}
|
||||
|
||||
export async function getHotelsByHotelIds(
|
||||
hotelIds: string[],
|
||||
lang: Lang,
|
||||
serviceToken: string
|
||||
) {
|
||||
const hotelPages = await getHotelPageUrls(lang)
|
||||
const hotels = await Promise.all(
|
||||
hotelIds.map(async (hotelId) => {
|
||||
const hotelData = await getHotel(
|
||||
{ hotelId, language: lang, isCardOnlyPayment: false },
|
||||
serviceToken
|
||||
)
|
||||
const hotelPage = hotelPages.find((page) => page.hotelId === hotelId)
|
||||
return hotelData ? { ...hotelData, url: hotelPage?.url ?? null } : null
|
||||
})
|
||||
)
|
||||
|
||||
return hotels.filter((hotel): hotel is HotelDataWithUrl => !!hotel)
|
||||
}
|
||||
Reference in New Issue
Block a user