Merged in chore/refactor-trpc-booking-routes (pull request #3510)
feat(BOOK-750): refactor booking endpoints * WIP * wip * wip * parse dates in UTC * wip * no more errors * Merge branch 'master' of bitbucket.org:scandic-swap/web into chore/refactor-trpc-booking-routes * . * cleanup * import named z from zod * fix(BOOK-750): updateBooking api endpoint expects dateOnly, we passed ISO date Approved-by: Anton Gunnarsson
This commit is contained in:
@@ -30,20 +30,6 @@ export const cancelBookingsInput = z.object({
|
||||
language: z.nativeEnum(Lang),
|
||||
})
|
||||
|
||||
export const guaranteeBookingInput = z.object({
|
||||
card: z
|
||||
.object({
|
||||
alias: z.string(),
|
||||
expiryDate: z.string(),
|
||||
cardType: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
language: z.nativeEnum(Lang).transform((val) => langToApiLang[val]),
|
||||
success: z.string().nullable(),
|
||||
error: z.string().nullable(),
|
||||
cancel: z.string().nullable(),
|
||||
})
|
||||
|
||||
export const createRefIdInput = z.object({
|
||||
confirmationNumber: z
|
||||
.string()
|
||||
@@ -63,7 +49,7 @@ export const updateBookingInput = z.object({
|
||||
countryCode: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
language: z.nativeEnum(Lang).transform((val) => langToApiLang[val]),
|
||||
language: z.nativeEnum(Lang),
|
||||
})
|
||||
|
||||
// Query
|
||||
@@ -85,7 +71,4 @@ export const findBookingInput = z.object({
|
||||
})
|
||||
|
||||
export type LinkedReservationsInput = z.input<typeof getLinkedReservationsInput>
|
||||
|
||||
export const getBookingStatusInput = z.object({
|
||||
lang: z.nativeEnum(Lang).optional(),
|
||||
})
|
||||
export type { CreateBookingInput } from "./mutation/createBookingRoute/schema"
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { Lang } from "@scandic-hotels/common/constants/language"
|
||||
|
||||
import { createRefIdPlugin } from "../../../plugins/refIdToConfirmationNumber"
|
||||
import { safeProtectedServiceProcedure } from "../../../procedures"
|
||||
import { addPackageToBooking } from "../../../services/booking/addPackageToBooking"
|
||||
|
||||
const addPackageInput = z.object({
|
||||
ancillaryComment: z.string(),
|
||||
ancillaryDeliveryTime: z.string().nullish(),
|
||||
packages: z.array(
|
||||
z.object({
|
||||
code: z.string(),
|
||||
quantity: z.number(),
|
||||
comment: z.string().optional(),
|
||||
})
|
||||
),
|
||||
language: z.nativeEnum(Lang),
|
||||
})
|
||||
const refIdPlugin = createRefIdPlugin()
|
||||
|
||||
export const addPackagesRoute = safeProtectedServiceProcedure
|
||||
.input(addPackageInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.use(async ({ ctx, next }) => {
|
||||
const token = await ctx.getScandicUserToken()
|
||||
return next({
|
||||
ctx: {
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.mutation(async function ({ ctx, input }) {
|
||||
const { confirmationNumber } = ctx
|
||||
const { language, refId, ...body } = input
|
||||
|
||||
return await addPackageToBooking(
|
||||
{ confirmationNumber, lang: language, ...body },
|
||||
ctx.token ?? ctx.serviceToken
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
import { createLogger } from "@scandic-hotels/common/logger/createLogger"
|
||||
|
||||
import { createRefIdPlugin } from "../../../plugins/refIdToConfirmationNumber"
|
||||
import { safeProtectedServiceProcedure } from "../../../procedures"
|
||||
import { cancelBooking } from "../../../services/booking/cancelBooking"
|
||||
import { cancelBookingsInput } from "../input"
|
||||
|
||||
const bookingLogger = createLogger("trpc.booking.cancelBooking")
|
||||
const refIdPlugin = createRefIdPlugin()
|
||||
export const cancelBookingRoute = safeProtectedServiceProcedure
|
||||
.input(cancelBookingsInput)
|
||||
.concat(refIdPlugin.toConfirmationNumbers)
|
||||
.use(async ({ ctx, next }) => {
|
||||
const token = await ctx.getScandicUserToken()
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.mutation(async function ({ ctx, input }) {
|
||||
const { confirmationNumbers } = ctx
|
||||
const { language } = input
|
||||
|
||||
const token = ctx.token ?? ctx.serviceToken
|
||||
const responses = await Promise.allSettled(
|
||||
confirmationNumbers.map((confirmationNumber) =>
|
||||
cancelBooking({ confirmationNumber, language }, token)
|
||||
)
|
||||
)
|
||||
|
||||
const cancelledRoomsSuccessfully: (string | null)[] = []
|
||||
for (const [idx, response] of responses.entries()) {
|
||||
if (response.status === "fulfilled") {
|
||||
if (response.value) {
|
||||
cancelledRoomsSuccessfully.push(confirmationNumbers[idx])
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
bookingLogger.error(
|
||||
`Cancelling booking failed for confirmationNumber: ${confirmationNumbers[idx]}`,
|
||||
response.reason
|
||||
)
|
||||
}
|
||||
|
||||
cancelledRoomsSuccessfully.push(null)
|
||||
}
|
||||
|
||||
return cancelledRoomsSuccessfully
|
||||
})
|
||||
@@ -1,95 +0,0 @@
|
||||
import "server-only"
|
||||
|
||||
import { PaymentMethodEnum } from "@scandic-hotels/common/constants/paymentMethod"
|
||||
import { createCounter } from "@scandic-hotels/common/telemetry"
|
||||
|
||||
import * as api from "../../../../api"
|
||||
import { safeProtectedServiceProcedure } from "../../../../procedures"
|
||||
import { encrypt } from "../../../../utils/encryption"
|
||||
import { createBookingInput, createBookingSchema } from "./schema"
|
||||
|
||||
export const create = safeProtectedServiceProcedure
|
||||
.input(createBookingInput)
|
||||
.use(async ({ ctx, next }) => {
|
||||
const token = await ctx.getScandicUserToken()
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.mutation(async function ({ ctx, input }) {
|
||||
const { language, ...inputWithoutLang } = input
|
||||
const { rooms, ...loggableInput } = inputWithoutLang
|
||||
|
||||
const createBookingCounter = createCounter("trpc.booking.create")
|
||||
|
||||
const metricsCreateBooking = createBookingCounter.init({
|
||||
language,
|
||||
...loggableInput,
|
||||
rooms: inputWithoutLang.rooms.map(({ guest, ...room }) => {
|
||||
const { becomeMember, membershipNumber } = guest
|
||||
return { ...room, guest: { becomeMember, membershipNumber } }
|
||||
}),
|
||||
})
|
||||
|
||||
metricsCreateBooking.start()
|
||||
const headers = {
|
||||
Authorization: `Bearer ${ctx.token ?? ctx.serviceToken}`,
|
||||
}
|
||||
|
||||
const includePartnerSpecific =
|
||||
inputWithoutLang.payment?.paymentMethod ===
|
||||
PaymentMethodEnum.PartnerPoints
|
||||
if (includePartnerSpecific) {
|
||||
const session = await ctx.auth()
|
||||
const token = session?.token.access_token
|
||||
if (!token) {
|
||||
throw new Error(
|
||||
"Cannot create booking with partner points without partner token"
|
||||
)
|
||||
}
|
||||
|
||||
inputWithoutLang.partnerSpecific = {
|
||||
eurobonusAccessToken: session?.token.access_token,
|
||||
}
|
||||
}
|
||||
|
||||
const apiResponse = await api.post(
|
||||
api.endpoints.v1.Booking.bookings,
|
||||
{
|
||||
headers,
|
||||
body: inputWithoutLang,
|
||||
},
|
||||
{ language }
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsCreateBooking.httpError(apiResponse)
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
if ("errors" in apiJson && apiJson.errors.length) {
|
||||
const error = apiJson.errors[0]
|
||||
return { error: true, cause: error.code } as const
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const verifiedData = createBookingSchema.safeParse(apiJson)
|
||||
if (!verifiedData.success) {
|
||||
metricsCreateBooking.validationError(verifiedData.error)
|
||||
return null
|
||||
}
|
||||
|
||||
metricsCreateBooking.success()
|
||||
|
||||
const expire = Math.floor(Date.now() / 1000) + 60 // 1 minute expiry
|
||||
|
||||
return {
|
||||
booking: verifiedData.data,
|
||||
sig: encrypt(expire.toString()),
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
import "server-only"
|
||||
|
||||
import { PaymentMethodEnum } from "@scandic-hotels/common/constants/paymentMethod"
|
||||
|
||||
import { safeProtectedServiceProcedure } from "../../../../procedures"
|
||||
import { createBooking } from "../../../../services/booking/createBooking"
|
||||
import { encrypt } from "../../../../utils/encryption"
|
||||
import { createBookingInput } from "./schema"
|
||||
export const createBookingRoute = safeProtectedServiceProcedure
|
||||
.input(createBookingInput)
|
||||
.use(async ({ ctx, next }) => {
|
||||
const token = await ctx.getScandicUserToken()
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.mutation(async function ({ ctx, input }) {
|
||||
if (input.payment?.paymentMethod === PaymentMethodEnum.PartnerPoints) {
|
||||
const session = await ctx.auth()
|
||||
const token = session?.token.access_token
|
||||
if (!token) {
|
||||
throw new Error(
|
||||
"Cannot create booking with partner points without partner token"
|
||||
)
|
||||
}
|
||||
|
||||
input.partnerSpecific = {
|
||||
eurobonusAccessToken: session?.token.access_token,
|
||||
}
|
||||
}
|
||||
|
||||
const booking = await createBooking(input, ctx.token ?? ctx.serviceToken)
|
||||
if ("error" in booking) {
|
||||
return { ...booking }
|
||||
}
|
||||
|
||||
const expire = Math.floor(Date.now() / 1000) + 60 // 1 minute expiry
|
||||
|
||||
return {
|
||||
booking,
|
||||
sig: encrypt(expire.toString()),
|
||||
}
|
||||
})
|
||||
@@ -1,11 +1,31 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { Lang } from "@scandic-hotels/common/constants/language"
|
||||
import { PaymentMethodEnum } from "@scandic-hotels/common/constants/paymentMethod"
|
||||
|
||||
import { langToApiLang } from "../../../../constants/apiLang"
|
||||
import { ChildBedTypeEnum } from "../../../../enums/childBedTypeEnum"
|
||||
import { calculateRefId } from "../../../../utils/refId"
|
||||
import { guestSchema } from "../../output"
|
||||
|
||||
const paymentSchema = z.object({
|
||||
paymentMethod: z.nativeEnum(PaymentMethodEnum),
|
||||
card: z
|
||||
.object({
|
||||
alias: z.string(),
|
||||
expiryDate: z.string(),
|
||||
cardType: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
cardHolder: z
|
||||
.object({
|
||||
email: z.string().email(),
|
||||
name: z.string(),
|
||||
phoneCountryCode: z.string(),
|
||||
phoneSubscriber: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
success: z.string(),
|
||||
error: z.string(),
|
||||
cancel: z.string(),
|
||||
})
|
||||
|
||||
const roomsSchema = z
|
||||
.array(
|
||||
@@ -75,28 +95,6 @@ const roomsSchema = z
|
||||
})
|
||||
})
|
||||
|
||||
const paymentSchema = z.object({
|
||||
paymentMethod: z.string(),
|
||||
card: z
|
||||
.object({
|
||||
alias: z.string(),
|
||||
expiryDate: z.string(),
|
||||
cardType: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
cardHolder: z
|
||||
.object({
|
||||
email: z.string().email(),
|
||||
name: z.string(),
|
||||
phoneCountryCode: z.string(),
|
||||
phoneSubscriber: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
success: z.string(),
|
||||
error: z.string(),
|
||||
cancel: z.string(),
|
||||
})
|
||||
|
||||
export type CreateBookingInput = z.input<typeof createBookingInput>
|
||||
export const createBookingInput = z.object({
|
||||
hotelId: z.string(),
|
||||
@@ -104,78 +102,10 @@ export const createBookingInput = z.object({
|
||||
checkOutDate: z.string(),
|
||||
rooms: roomsSchema,
|
||||
payment: paymentSchema.optional(),
|
||||
language: z.nativeEnum(Lang).transform((val) => langToApiLang[val]),
|
||||
language: z.nativeEnum(Lang),
|
||||
partnerSpecific: z
|
||||
.object({
|
||||
eurobonusAccessToken: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
|
||||
export const createBookingSchema = z
|
||||
.object({
|
||||
data: z.object({
|
||||
attributes: z.object({
|
||||
reservationStatus: z.string(),
|
||||
guest: guestSchema.optional(),
|
||||
paymentUrl: z.string().nullable().optional(),
|
||||
paymentMethod: z.string().nullable().optional(),
|
||||
rooms: z
|
||||
.array(
|
||||
z.object({
|
||||
confirmationNumber: z.string(),
|
||||
cancellationNumber: z.string().nullable(),
|
||||
priceChangedMetadata: z
|
||||
.object({
|
||||
roomPrice: z.number(),
|
||||
totalPrice: z.number(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
})
|
||||
)
|
||||
.default([]),
|
||||
errors: z
|
||||
.array(
|
||||
z.object({
|
||||
confirmationNumber: z.string().nullable().optional(),
|
||||
errorCode: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
meta: z
|
||||
.record(z.string(), z.union([z.string(), z.number()]))
|
||||
.nullable()
|
||||
.optional(),
|
||||
})
|
||||
)
|
||||
.default([]),
|
||||
}),
|
||||
type: z.string(),
|
||||
id: z.string(),
|
||||
links: z.object({
|
||||
self: z.object({
|
||||
href: z.string().url(),
|
||||
meta: z.object({
|
||||
method: z.string(),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.transform((d) => ({
|
||||
id: d.data.id,
|
||||
links: d.data.links,
|
||||
type: d.data.type,
|
||||
reservationStatus: d.data.attributes.reservationStatus,
|
||||
paymentUrl: d.data.attributes.paymentUrl,
|
||||
paymentMethod: d.data.attributes.paymentMethod,
|
||||
rooms: d.data.attributes.rooms.map((room) => {
|
||||
const lastName = d.data.attributes.guest?.lastName ?? ""
|
||||
return {
|
||||
...room,
|
||||
refId: calculateRefId(room.confirmationNumber, lastName),
|
||||
}
|
||||
}),
|
||||
errors: d.data.attributes.errors,
|
||||
guest: d.data.attributes.guest,
|
||||
}))
|
||||
export type CreateBookingSchema = z.infer<typeof createBookingSchema>
|
||||
@@ -0,0 +1,19 @@
|
||||
import { serverErrorByStatus } from "../../../errors"
|
||||
import { serviceProcedure } from "../../../procedures"
|
||||
import { encrypt } from "../../../utils/encryption"
|
||||
import { createRefIdInput } from "../input"
|
||||
|
||||
export const createRefIdRoute = serviceProcedure
|
||||
.input(createRefIdInput)
|
||||
.mutation(async function ({ input }) {
|
||||
const { confirmationNumber, lastName } = input
|
||||
const encryptedRefId = encrypt(`${confirmationNumber},${lastName}`)
|
||||
|
||||
if (!encryptedRefId) {
|
||||
throw serverErrorByStatus(422, "Was not able to encrypt ref id")
|
||||
}
|
||||
|
||||
return {
|
||||
refId: encryptedRefId,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { Lang } from "@scandic-hotels/common/constants/language"
|
||||
|
||||
import { createRefIdPlugin } from "../../../plugins/refIdToConfirmationNumber"
|
||||
import { safeProtectedServiceProcedure } from "../../../procedures"
|
||||
import { guaranteeBooking } from "../../../services/booking/guaranteeBooking"
|
||||
|
||||
const guaranteeBookingInput = z.object({
|
||||
card: z
|
||||
.object({
|
||||
alias: z.string(),
|
||||
expiryDate: z.string(),
|
||||
cardType: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
language: z.nativeEnum(Lang),
|
||||
success: z.string().nullable(),
|
||||
error: z.string().nullable(),
|
||||
cancel: z.string().nullable(),
|
||||
})
|
||||
|
||||
const refIdPlugin = createRefIdPlugin()
|
||||
export const guaranteeBookingRoute = safeProtectedServiceProcedure
|
||||
.input(guaranteeBookingInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.use(async ({ ctx, next }) => {
|
||||
const token = await ctx.getScandicUserToken()
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.mutation(async function ({ ctx, input }) {
|
||||
const { confirmationNumber } = ctx
|
||||
const { language, refId, ...body } = input
|
||||
|
||||
const token = ctx.token ?? ctx.serviceToken
|
||||
|
||||
return guaranteeBooking({ confirmationNumber, language, ...body }, token)
|
||||
})
|
||||
@@ -1,226 +1,34 @@
|
||||
import { createLogger } from "@scandic-hotels/common/logger/createLogger"
|
||||
import { dt } from "@scandic-hotels/common/dt"
|
||||
import { createCounter } from "@scandic-hotels/common/telemetry"
|
||||
|
||||
import { router } from "../../.."
|
||||
import * as api from "../../../api"
|
||||
import { createRefIdPlugin } from "../../../plugins/refIdToConfirmationNumber"
|
||||
import { safeProtectedServiceProcedure } from "../../../procedures"
|
||||
import { updateBooking } from "../../../services/booking/updateBooking"
|
||||
import {
|
||||
addPackageInput,
|
||||
cancelBookingsInput,
|
||||
guaranteeBookingInput,
|
||||
removePackageInput,
|
||||
resendConfirmationInput,
|
||||
updateBookingInput,
|
||||
} from "../input"
|
||||
import { bookingConfirmationSchema } from "../output"
|
||||
import { cancelBooking } from "../utils"
|
||||
import { createBookingSchema } from "./create/schema"
|
||||
import { create } from "./create"
|
||||
import { addPackagesRoute } from "./addPackagesRoute"
|
||||
import { cancelBookingRoute } from "./cancelBookingRoute"
|
||||
import { createBookingRoute } from "./createBookingRoute"
|
||||
import { createRefIdRoute } from "./createRefIdRoute"
|
||||
import { guaranteeBookingRoute } from "./guaranteeBookingRoute"
|
||||
import { priceChangeRoute } from "./priceChangeRoute"
|
||||
import { validatePartnerPayment } from "./validatePartnerPayment"
|
||||
|
||||
const refIdPlugin = createRefIdPlugin()
|
||||
const bookingLogger = createLogger("trpc.booking")
|
||||
|
||||
export const bookingMutationRouter = router({
|
||||
create,
|
||||
create: createBookingRoute,
|
||||
createRefId: createRefIdRoute,
|
||||
validatePartnerPayment,
|
||||
priceChange: safeProtectedServiceProcedure
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.use(async ({ ctx, next }) => {
|
||||
const token = await ctx.getScandicUserToken()
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.mutation(async function ({ ctx }) {
|
||||
const { confirmationNumber } = ctx
|
||||
|
||||
const priceChangeCounter = createCounter("trpc.booking.price-change")
|
||||
const metricsPriceChange = priceChangeCounter.init({ confirmationNumber })
|
||||
|
||||
metricsPriceChange.start()
|
||||
|
||||
const token = ctx.token ?? ctx.serviceToken
|
||||
const headers = {
|
||||
Authorization: `Bearer ${token}`,
|
||||
}
|
||||
|
||||
const apiResponse = await api.put(
|
||||
api.endpoints.v1.Booking.priceChange(confirmationNumber),
|
||||
{
|
||||
headers,
|
||||
}
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsPriceChange.httpError(apiResponse)
|
||||
return null
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const verifiedData = createBookingSchema.safeParse(apiJson)
|
||||
if (!verifiedData.success) {
|
||||
metricsPriceChange.validationError(verifiedData.error)
|
||||
return null
|
||||
}
|
||||
|
||||
metricsPriceChange.success()
|
||||
|
||||
return verifiedData.data
|
||||
}),
|
||||
cancel: safeProtectedServiceProcedure
|
||||
.input(cancelBookingsInput)
|
||||
.concat(refIdPlugin.toConfirmationNumbers)
|
||||
.use(async ({ ctx, next }) => {
|
||||
const token = await ctx.getScandicUserToken()
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.mutation(async function ({ ctx, input }) {
|
||||
const { confirmationNumbers } = ctx
|
||||
const { language } = input
|
||||
|
||||
const token = ctx.token ?? ctx.serviceToken
|
||||
const responses = await Promise.allSettled(
|
||||
confirmationNumbers.map((confirmationNumber) =>
|
||||
cancelBooking(confirmationNumber, language, token)
|
||||
)
|
||||
)
|
||||
|
||||
const cancelledRoomsSuccessfully: (string | null)[] = []
|
||||
for (const [idx, response] of responses.entries()) {
|
||||
if (response.status === "fulfilled") {
|
||||
if (response.value) {
|
||||
cancelledRoomsSuccessfully.push(confirmationNumbers[idx])
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
bookingLogger.error(
|
||||
`Cancelling booking failed for confirmationNumber: ${confirmationNumbers[idx]}`,
|
||||
response.reason
|
||||
)
|
||||
}
|
||||
|
||||
cancelledRoomsSuccessfully.push(null)
|
||||
}
|
||||
|
||||
return cancelledRoomsSuccessfully
|
||||
}),
|
||||
packages: safeProtectedServiceProcedure
|
||||
.input(addPackageInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.use(async ({ ctx, next }) => {
|
||||
const token = await ctx.getScandicUserToken()
|
||||
return next({
|
||||
ctx: {
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.mutation(async function ({ ctx, input }) {
|
||||
const { confirmationNumber } = ctx
|
||||
const { language, refId, ...body } = input
|
||||
|
||||
const addPackageCounter = createCounter("trpc.booking.package.add")
|
||||
const metricsAddPackage = addPackageCounter.init({
|
||||
confirmationNumber,
|
||||
language,
|
||||
})
|
||||
|
||||
metricsAddPackage.start()
|
||||
|
||||
const token = ctx.token ?? ctx.serviceToken
|
||||
const headers = {
|
||||
Authorization: `Bearer ${token}`,
|
||||
}
|
||||
|
||||
const apiResponse = await api.post(
|
||||
api.endpoints.v1.Booking.packages(confirmationNumber),
|
||||
{
|
||||
headers,
|
||||
body: body,
|
||||
},
|
||||
{ language }
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsAddPackage.httpError(apiResponse)
|
||||
return null
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const verifiedData = createBookingSchema.safeParse(apiJson)
|
||||
if (!verifiedData.success) {
|
||||
metricsAddPackage.validationError(verifiedData.error)
|
||||
return null
|
||||
}
|
||||
|
||||
metricsAddPackage.success()
|
||||
|
||||
return verifiedData.data
|
||||
}),
|
||||
guarantee: safeProtectedServiceProcedure
|
||||
.input(guaranteeBookingInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.use(async ({ ctx, next }) => {
|
||||
const token = await ctx.getScandicUserToken()
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.mutation(async function ({ ctx, input }) {
|
||||
const { confirmationNumber } = ctx
|
||||
const { language, refId, ...body } = input
|
||||
|
||||
const guaranteeBookingCounter = createCounter("trpc.booking.guarantee")
|
||||
const metricsGuaranteeBooking = guaranteeBookingCounter.init({
|
||||
confirmationNumber,
|
||||
language,
|
||||
})
|
||||
|
||||
metricsGuaranteeBooking.start()
|
||||
|
||||
const token = ctx.token ?? ctx.serviceToken
|
||||
const headers = {
|
||||
Authorization: `Bearer ${token}`,
|
||||
}
|
||||
|
||||
const apiResponse = await api.put(
|
||||
api.endpoints.v1.Booking.guarantee(confirmationNumber),
|
||||
{
|
||||
headers,
|
||||
body: body,
|
||||
},
|
||||
{ language }
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsGuaranteeBooking.httpError(apiResponse)
|
||||
return null
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const verifiedData = createBookingSchema.safeParse(apiJson)
|
||||
if (!verifiedData.success) {
|
||||
metricsGuaranteeBooking.validationError(verifiedData.error)
|
||||
return null
|
||||
}
|
||||
|
||||
metricsGuaranteeBooking.success()
|
||||
|
||||
return verifiedData.data
|
||||
}),
|
||||
priceChange: priceChangeRoute,
|
||||
cancel: cancelBookingRoute,
|
||||
packages: addPackagesRoute,
|
||||
guarantee: guaranteeBookingRoute,
|
||||
update: safeProtectedServiceProcedure
|
||||
.input(updateBookingInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
@@ -235,43 +43,21 @@ export const bookingMutationRouter = router({
|
||||
})
|
||||
.mutation(async function ({ ctx, input }) {
|
||||
const { confirmationNumber } = ctx
|
||||
const { language, refId, ...body } = input
|
||||
|
||||
const updateBookingCounter = createCounter("trpc.booking.update")
|
||||
const metricsUpdateBooking = updateBookingCounter.init({
|
||||
confirmationNumber,
|
||||
language,
|
||||
})
|
||||
|
||||
metricsUpdateBooking.start()
|
||||
const { language, refId, ...rest } = input
|
||||
const token = ctx.token ?? ctx.serviceToken
|
||||
const apiResponse = await api.put(
|
||||
api.endpoints.v1.Booking.booking(confirmationNumber),
|
||||
|
||||
return updateBooking(
|
||||
{
|
||||
body,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
confirmationNumber,
|
||||
lang: language,
|
||||
checkInDate: rest.checkInDate ? dt.utc(rest.checkInDate) : undefined,
|
||||
checkOutDate: rest.checkOutDate
|
||||
? dt.utc(rest.checkOutDate)
|
||||
: undefined,
|
||||
guest: rest.guest,
|
||||
},
|
||||
{ language }
|
||||
token
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsUpdateBooking.httpError(apiResponse)
|
||||
return null
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
|
||||
const verifiedData = bookingConfirmationSchema.safeParse(apiJson)
|
||||
if (!verifiedData.success) {
|
||||
metricsUpdateBooking.validationError(verifiedData.error)
|
||||
return null
|
||||
}
|
||||
|
||||
metricsUpdateBooking.success()
|
||||
|
||||
return verifiedData.data
|
||||
}),
|
||||
removePackage: safeProtectedServiceProcedure
|
||||
.input(removePackageInput)
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createRefIdPlugin } from "../../../plugins/refIdToConfirmationNumber"
|
||||
import { safeProtectedServiceProcedure } from "../../../procedures"
|
||||
import { priceChange } from "../../../services/booking/priceChange"
|
||||
const refIdPlugin = createRefIdPlugin()
|
||||
|
||||
export const priceChangeRoute = safeProtectedServiceProcedure
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.use(async ({ ctx, next }) => {
|
||||
const token = await ctx.getScandicUserToken()
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.mutation(async function ({ ctx }) {
|
||||
const { confirmationNumber } = ctx
|
||||
|
||||
return await priceChange(
|
||||
{ confirmationNumber },
|
||||
ctx.token ?? ctx.serviceToken
|
||||
)
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import "server-only"
|
||||
|
||||
import z from "zod"
|
||||
import { z } from "zod"
|
||||
|
||||
import { createCounter } from "@scandic-hotels/common/telemetry"
|
||||
|
||||
|
||||
@@ -1,242 +0,0 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { CurrencyEnum } from "@scandic-hotels/common/constants/currency"
|
||||
import { dt } from "@scandic-hotels/common/dt"
|
||||
import { nullableArrayObjectValidator } from "@scandic-hotels/common/utils/zod/arrayValidator"
|
||||
import {
|
||||
nullableStringEmailValidator,
|
||||
nullableStringValidator,
|
||||
} from "@scandic-hotels/common/utils/zod/stringValidator"
|
||||
|
||||
import { BookingStatusEnum } from "../../enums/bookingStatus"
|
||||
import { BreakfastPackageEnum } from "../../enums/breakfast"
|
||||
import { ChildBedTypeEnum } from "../../enums/childBedTypeEnum"
|
||||
import { calculateRefId } from "../../utils/refId"
|
||||
|
||||
export const guestSchema = z.object({
|
||||
email: nullableStringEmailValidator,
|
||||
firstName: nullableStringValidator,
|
||||
lastName: nullableStringValidator,
|
||||
membershipNumber: nullableStringValidator,
|
||||
phoneNumber: nullableStringValidator,
|
||||
countryCode: nullableStringValidator,
|
||||
})
|
||||
|
||||
export type Guest = z.output<typeof guestSchema>
|
||||
|
||||
// QUERY
|
||||
const childBedPreferencesSchema = z.object({
|
||||
bedType: z.nativeEnum(ChildBedTypeEnum),
|
||||
quantity: z.number().int(),
|
||||
code: z.string().nullable().default(""),
|
||||
})
|
||||
|
||||
const priceSchema = z.object({
|
||||
currency: z.nativeEnum(CurrencyEnum).default(CurrencyEnum.Unknown),
|
||||
totalPrice: z.number().nullish(),
|
||||
totalUnit: z.number().int().nullish(),
|
||||
unit: z.number().int().nullish(),
|
||||
unitPrice: z.number(),
|
||||
})
|
||||
|
||||
export const packageSchema = z
|
||||
.object({
|
||||
code: nullableStringValidator,
|
||||
comment: z.string().nullish(),
|
||||
description: nullableStringValidator,
|
||||
price: priceSchema,
|
||||
type: z.string().nullish(),
|
||||
})
|
||||
.transform((packageData) => ({
|
||||
code: packageData.code,
|
||||
comment: packageData.comment,
|
||||
currency: packageData.price.currency,
|
||||
description: packageData.description,
|
||||
totalPrice: packageData.price.totalPrice ?? 0,
|
||||
totalUnit: packageData.price.totalUnit ?? 0,
|
||||
type: packageData.type,
|
||||
unit: packageData.price.unit ?? 0,
|
||||
unitPrice: packageData.price.unitPrice,
|
||||
}))
|
||||
|
||||
const ancillarySchema = z
|
||||
.object({
|
||||
comment: z.string().default(""),
|
||||
deliveryTime: z.string().default(""),
|
||||
})
|
||||
.nullable()
|
||||
.default({
|
||||
comment: "",
|
||||
deliveryTime: "",
|
||||
})
|
||||
|
||||
const rateDefinitionSchema = z.object({
|
||||
breakfastIncluded: z.boolean().default(false),
|
||||
cancellationRule: z.string().nullable().default(""),
|
||||
cancellationText: z.string().nullable().default(""),
|
||||
generalTerms: z.array(z.string()).default([]),
|
||||
isMemberRate: z.boolean().default(false),
|
||||
mustBeGuaranteed: z.boolean().default(false),
|
||||
rateCode: z.string().default(""),
|
||||
title: z.string().nullable().default(""),
|
||||
isCampaignRate: z.boolean().default(false),
|
||||
})
|
||||
|
||||
export const linkedReservationSchema = z.object({
|
||||
confirmationNumber: z.string().default(""),
|
||||
hotelId: z.string().default(""),
|
||||
checkinDate: z.string(),
|
||||
checkoutDate: z.string(),
|
||||
cancellationNumber: nullableStringValidator,
|
||||
roomTypeCode: z.string().default(""),
|
||||
adults: z.number().int(),
|
||||
children: z.number().int(),
|
||||
profileId: z.string().default(""),
|
||||
})
|
||||
|
||||
const linksSchema = z.object({
|
||||
addAncillary: z
|
||||
.object({
|
||||
href: z.string(),
|
||||
meta: z.object({
|
||||
method: z.string(),
|
||||
}),
|
||||
})
|
||||
.nullable(),
|
||||
cancel: z
|
||||
.object({
|
||||
href: z.string(),
|
||||
meta: z.object({
|
||||
method: z.string(),
|
||||
}),
|
||||
})
|
||||
.nullable(),
|
||||
guarantee: z
|
||||
.object({
|
||||
href: z.string(),
|
||||
meta: z.object({
|
||||
method: z.string(),
|
||||
}),
|
||||
})
|
||||
.nullable(),
|
||||
modify: z
|
||||
.object({
|
||||
href: z.string(),
|
||||
meta: z.object({
|
||||
method: z.string(),
|
||||
}),
|
||||
})
|
||||
.nullable(),
|
||||
self: z
|
||||
.object({
|
||||
href: z.string(),
|
||||
meta: z.object({
|
||||
method: z.string(),
|
||||
}),
|
||||
})
|
||||
.nullable(),
|
||||
})
|
||||
|
||||
export const bookingConfirmationSchema = z
|
||||
.object({
|
||||
data: z.object({
|
||||
attributes: z.object({
|
||||
adults: z.number().int(),
|
||||
ancillary: ancillarySchema,
|
||||
bookingType: z.string().optional(),
|
||||
cancelationNumber: z.string().nullable().default(""),
|
||||
checkInDate: z.string().refine((val) => dt(val).isValid()),
|
||||
checkOutDate: z.string().refine((val) => dt(val).isValid()),
|
||||
childBedPreferences: z.array(childBedPreferencesSchema).default([]),
|
||||
childrenAges: z.array(z.number().int()).default([]),
|
||||
canChangeDate: z.boolean(),
|
||||
bookingCode: z.string().nullable(),
|
||||
cheques: z.number(),
|
||||
vouchers: z.number(),
|
||||
guaranteeInfo: z
|
||||
.object({
|
||||
maskedCard: z.string(),
|
||||
cardType: z.string(),
|
||||
paymentMethod: z.string(),
|
||||
paymentMethodDescription: z.string(),
|
||||
})
|
||||
.nullish(),
|
||||
computedReservationStatus: z.string().nullable().default(""),
|
||||
confirmationNumber: nullableStringValidator,
|
||||
createDateTime: z.string().refine((val) => dt(val).isValid()),
|
||||
currencyCode: z.nativeEnum(CurrencyEnum),
|
||||
guest: guestSchema,
|
||||
linkedReservations: nullableArrayObjectValidator(
|
||||
linkedReservationSchema
|
||||
),
|
||||
hotelId: z.string(),
|
||||
mainRoom: z.boolean(),
|
||||
multiRoom: z.boolean(),
|
||||
packages: z.array(packageSchema).default([]),
|
||||
rateDefinition: rateDefinitionSchema,
|
||||
reservationStatus: z.string().nullable().default(""),
|
||||
roomPoints: z.number(),
|
||||
roomPointType: z
|
||||
.enum(["Scandic", "EuroBonus"])
|
||||
.nullable()
|
||||
.default(null)
|
||||
.catch(null),
|
||||
roomPrice: z.number(),
|
||||
roomTypeCode: z.string().default(""),
|
||||
totalPoints: z.number(),
|
||||
totalPrice: z.number(),
|
||||
totalPriceExVat: z.number(),
|
||||
vatAmount: z.number(),
|
||||
vatPercentage: z.number(),
|
||||
}),
|
||||
id: z.string(),
|
||||
type: z.literal("booking"),
|
||||
links: linksSchema,
|
||||
}),
|
||||
})
|
||||
.transform(({ data }) => ({
|
||||
...data.attributes,
|
||||
refId: calculateRefId(
|
||||
data.attributes.confirmationNumber,
|
||||
data.attributes.guest.lastName
|
||||
),
|
||||
linkedReservations: data.attributes.linkedReservations.map(
|
||||
(linkedReservation) => {
|
||||
/**
|
||||
* We lazy load linked reservations in the client.
|
||||
* The problem is that we need to load the reservation in order to
|
||||
* calculate the refId for the reservation as the refId uses the guest's
|
||||
* lastname in it. Ideally we should pass a promise to the React
|
||||
* component that uses `use()` to resolve it. But right now we use tRPC
|
||||
* in the client. That tRPC endpoint only uses the confirmationNumber
|
||||
* from the refId. So that means we can pass whatever as the lastname
|
||||
* here, because it is actually never read. We should change this ASAP.
|
||||
*/
|
||||
return {
|
||||
...linkedReservation,
|
||||
refId: calculateRefId(
|
||||
linkedReservation.confirmationNumber,
|
||||
"" // TODO: Empty lastname here, see comment above
|
||||
),
|
||||
}
|
||||
}
|
||||
),
|
||||
packages: data.attributes.packages.filter((p) => p.type !== "Ancillary"),
|
||||
ancillaries: data.attributes.packages.filter((p) => p.type === "Ancillary"),
|
||||
extraBedTypes: data.attributes.childBedPreferences,
|
||||
showAncillaries:
|
||||
!!(
|
||||
data.links.addAncillary ||
|
||||
data.attributes.packages.some(
|
||||
(p) =>
|
||||
p.type === "Ancillary" ||
|
||||
p.code === BreakfastPackageEnum.ANCILLARY_REGULAR_BREAKFAST
|
||||
)
|
||||
) && data.attributes.reservationStatus !== BookingStatusEnum.Cancelled,
|
||||
isCancelable: !!data.links.cancel,
|
||||
isModifiable: !!data.links.modify,
|
||||
isGuaranteeable: !!data.links.guarantee,
|
||||
canModifyAncillaries: !!data.links.addAncillary,
|
||||
// Typo from API
|
||||
cancellationNumber: data.attributes.cancelationNumber,
|
||||
}))
|
||||
@@ -1,319 +1,12 @@
|
||||
import { createCounter } from "@scandic-hotels/common/telemetry"
|
||||
|
||||
import { router } from "../.."
|
||||
import * as api from "../../api"
|
||||
import {
|
||||
badRequestError,
|
||||
extractResponseDetails,
|
||||
notFoundError,
|
||||
serverErrorByStatus,
|
||||
} from "../../errors"
|
||||
import { createRefIdPlugin } from "../../plugins/refIdToConfirmationNumber"
|
||||
import {
|
||||
safeProtectedServiceProcedure,
|
||||
serviceProcedure,
|
||||
} from "../../procedures"
|
||||
import { toApiLang } from "../../utils"
|
||||
import { encrypt } from "../../utils/encryption"
|
||||
import { isValidSession } from "../../utils/session"
|
||||
import { getHotelPageUrls } from "../contentstack/hotelPage/utils"
|
||||
import { getHotel } from "../hotels/services/getHotel"
|
||||
import { createBookingSchema } from "./mutation/create/schema"
|
||||
import { getHotelRoom } from "./helpers"
|
||||
import {
|
||||
createRefIdInput,
|
||||
findBookingInput,
|
||||
getBookingInput,
|
||||
getBookingStatusInput,
|
||||
getLinkedReservationsInput,
|
||||
} from "./input"
|
||||
import { findBooking, getBooking } from "./utils"
|
||||
|
||||
const refIdPlugin = createRefIdPlugin()
|
||||
import { findBookingRoute } from "./query/findBookingRoute"
|
||||
import { getBookingRoute } from "./query/getBookingRoute"
|
||||
import { getBookingStatusRoute } from "./query/getBookingStatusRoute"
|
||||
import { getLinkedReservationsRoute } from "./query/getLinkedReservationsRoute"
|
||||
|
||||
export const bookingQueryRouter = router({
|
||||
get: safeProtectedServiceProcedure
|
||||
.input(getBookingInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.use(async ({ ctx, input, next }) => {
|
||||
const lang = input.lang ?? ctx.lang
|
||||
const token = await ctx.getScandicUserToken()
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
lang,
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.query(async function ({ ctx }) {
|
||||
const { confirmationNumber, lang, token, serviceToken } = ctx
|
||||
|
||||
const getBookingCounter = createCounter("trpc.booking.get")
|
||||
const metricsGetBooking = getBookingCounter.init({ confirmationNumber })
|
||||
|
||||
metricsGetBooking.start()
|
||||
|
||||
const booking = await getBooking(
|
||||
confirmationNumber,
|
||||
lang,
|
||||
token ?? serviceToken
|
||||
)
|
||||
|
||||
if (!booking) {
|
||||
metricsGetBooking.dataError(
|
||||
`Fail to get booking data for ${confirmationNumber}`,
|
||||
{ confirmationNumber }
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
const [hotelData, hotelPages] = await Promise.all([
|
||||
getHotel(
|
||||
{
|
||||
hotelId: booking.hotelId,
|
||||
isCardOnlyPayment: false,
|
||||
language: lang,
|
||||
},
|
||||
serviceToken
|
||||
),
|
||||
getHotelPageUrls(lang),
|
||||
])
|
||||
const hotelPage = hotelPages.find(
|
||||
(page) => page.hotelId === booking.hotelId
|
||||
)
|
||||
|
||||
if (!hotelData) {
|
||||
metricsGetBooking.dataError(
|
||||
`Failed to get hotel data for ${booking.hotelId}`,
|
||||
{
|
||||
hotelId: booking.hotelId,
|
||||
}
|
||||
)
|
||||
throw notFoundError({
|
||||
message: "Hotel data not found",
|
||||
errorDetails: { hotelId: booking.hotelId },
|
||||
})
|
||||
}
|
||||
|
||||
metricsGetBooking.success()
|
||||
|
||||
return {
|
||||
...hotelData,
|
||||
url: hotelPage?.url || null,
|
||||
booking,
|
||||
room: getHotelRoom(hotelData.roomCategories, booking.roomTypeCode),
|
||||
}
|
||||
}),
|
||||
findBooking: safeProtectedServiceProcedure
|
||||
.input(findBookingInput)
|
||||
.use(async ({ ctx, input, next }) => {
|
||||
const lang = input.lang ?? ctx.lang
|
||||
const token = isValidSession(ctx.session)
|
||||
? ctx.session.token.access_token
|
||||
: ctx.serviceToken
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
lang,
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.query(async function ({
|
||||
ctx,
|
||||
input: { confirmationNumber, lastName, firstName, email },
|
||||
}) {
|
||||
const { lang, token, serviceToken } = ctx
|
||||
const findBookingCounter = createCounter("trpc.booking.findBooking")
|
||||
const metricsFindBooking = findBookingCounter.init({ confirmationNumber })
|
||||
|
||||
metricsFindBooking.start()
|
||||
|
||||
const booking = await findBooking(
|
||||
confirmationNumber,
|
||||
lang,
|
||||
token,
|
||||
lastName,
|
||||
firstName,
|
||||
email
|
||||
)
|
||||
|
||||
if (!booking) {
|
||||
metricsFindBooking.dataError(
|
||||
`Fail to find booking data for ${confirmationNumber}`,
|
||||
{ confirmationNumber }
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
const [hotelData, hotelPages] = await Promise.all([
|
||||
getHotel(
|
||||
{
|
||||
hotelId: booking.hotelId,
|
||||
isCardOnlyPayment: false,
|
||||
language: lang,
|
||||
},
|
||||
serviceToken
|
||||
),
|
||||
getHotelPageUrls(lang),
|
||||
])
|
||||
const hotelPage = hotelPages.find(
|
||||
(page) => page.hotelId === booking.hotelId
|
||||
)
|
||||
|
||||
if (!hotelData) {
|
||||
metricsFindBooking.dataError(
|
||||
`Failed to find hotel data for ${booking.hotelId}`,
|
||||
{
|
||||
hotelId: booking.hotelId,
|
||||
}
|
||||
)
|
||||
|
||||
throw notFoundError({
|
||||
message: "Hotel data not found",
|
||||
errorDetails: { hotelId: booking.hotelId },
|
||||
})
|
||||
}
|
||||
|
||||
metricsFindBooking.success()
|
||||
|
||||
return {
|
||||
...hotelData,
|
||||
url: hotelPage?.url || null,
|
||||
booking,
|
||||
room: getHotelRoom(hotelData.roomCategories, booking.roomTypeCode),
|
||||
}
|
||||
}),
|
||||
linkedReservations: safeProtectedServiceProcedure
|
||||
.input(getLinkedReservationsInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.use(async ({ ctx, input, next }) => {
|
||||
const lang = input.lang ?? ctx.lang
|
||||
const token = isValidSession(ctx.session)
|
||||
? ctx.session.token.access_token
|
||||
: ctx.serviceToken
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
lang,
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.query(async function ({ ctx }) {
|
||||
const { confirmationNumber, lang, token } = ctx
|
||||
|
||||
const getLinkedReservationsCounter = createCounter(
|
||||
"trpc.booking.linkedReservations"
|
||||
)
|
||||
const metricsGetLinkedReservations = getLinkedReservationsCounter.init({
|
||||
confirmationNumber,
|
||||
})
|
||||
|
||||
metricsGetLinkedReservations.start()
|
||||
|
||||
const booking = await getBooking(confirmationNumber, lang, token)
|
||||
|
||||
if (!booking) {
|
||||
return []
|
||||
}
|
||||
|
||||
const linkedReservationsResults = await Promise.allSettled(
|
||||
booking.linkedReservations.map((linkedReservation) =>
|
||||
getBooking(linkedReservation.confirmationNumber, lang, token)
|
||||
)
|
||||
)
|
||||
|
||||
const linkedReservations = []
|
||||
for (const linkedReservationsResult of linkedReservationsResults) {
|
||||
if (linkedReservationsResult.status === "fulfilled") {
|
||||
if (linkedReservationsResult.value) {
|
||||
linkedReservations.push(linkedReservationsResult.value)
|
||||
} else {
|
||||
metricsGetLinkedReservations.dataError(
|
||||
`Unexpected value for linked reservation`
|
||||
)
|
||||
}
|
||||
} else {
|
||||
metricsGetLinkedReservations.dataError(
|
||||
`Failed to get linked reservation`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
metricsGetLinkedReservations.success()
|
||||
|
||||
return linkedReservations
|
||||
}),
|
||||
status: serviceProcedure
|
||||
.input(getBookingStatusInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.query(async function ({ ctx, input }) {
|
||||
const lang = input.lang ?? ctx.lang
|
||||
const { confirmationNumber } = ctx
|
||||
const language = toApiLang(lang)
|
||||
|
||||
const getBookingStatusCounter = createCounter("trpc.booking.status")
|
||||
const metricsGetBookingStatus = getBookingStatusCounter.init({
|
||||
confirmationNumber,
|
||||
})
|
||||
|
||||
metricsGetBookingStatus.start()
|
||||
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v1.Booking.status(confirmationNumber),
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${ctx.serviceToken}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
language,
|
||||
}
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsGetBookingStatus.httpError(apiResponse)
|
||||
throw serverErrorByStatus(
|
||||
apiResponse.status,
|
||||
await extractResponseDetails(apiResponse),
|
||||
"getBookingStatus failed"
|
||||
)
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const verifiedData = createBookingSchema.safeParse(apiJson)
|
||||
if (!verifiedData.success) {
|
||||
metricsGetBookingStatus.validationError(verifiedData.error)
|
||||
|
||||
throw badRequestError({
|
||||
message: "Invalid booking data",
|
||||
errorDetails: verifiedData.error.formErrors,
|
||||
})
|
||||
}
|
||||
|
||||
metricsGetBookingStatus.success()
|
||||
|
||||
const expire = Math.floor(Date.now() / 1000) + 60 // 1 minute expiry
|
||||
|
||||
return {
|
||||
booking: verifiedData.data,
|
||||
sig: encrypt(expire.toString()),
|
||||
}
|
||||
}),
|
||||
createRefId: serviceProcedure
|
||||
.input(createRefIdInput)
|
||||
.mutation(async function ({ input }) {
|
||||
const { confirmationNumber, lastName } = input
|
||||
const encryptedRefId = encrypt(`${confirmationNumber},${lastName}`)
|
||||
|
||||
if (!encryptedRefId) {
|
||||
throw serverErrorByStatus(422, "Was not able to encrypt ref id")
|
||||
}
|
||||
|
||||
return {
|
||||
refId: encryptedRefId,
|
||||
}
|
||||
}),
|
||||
get: getBookingRoute,
|
||||
findBooking: findBookingRoute,
|
||||
linkedReservations: getLinkedReservationsRoute,
|
||||
status: getBookingStatusRoute,
|
||||
})
|
||||
|
||||
87
packages/trpc/lib/routers/booking/query/findBookingRoute.ts
Normal file
87
packages/trpc/lib/routers/booking/query/findBookingRoute.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { createCounter } from "@scandic-hotels/common/telemetry"
|
||||
|
||||
import { notFoundError } from "../../../errors"
|
||||
import { safeProtectedServiceProcedure } from "../../../procedures"
|
||||
import { findBooking } from "../../../services/booking/findBooking"
|
||||
import { isValidSession } from "../../../utils/session"
|
||||
import { getHotelPageUrls } from "../../contentstack/hotelPage/utils"
|
||||
import { getHotel } from "../../hotels/services/getHotel"
|
||||
import { getHotelRoom } from "../helpers"
|
||||
import { findBookingInput } from "../input"
|
||||
|
||||
export const findBookingRoute = safeProtectedServiceProcedure
|
||||
.input(findBookingInput)
|
||||
.use(async ({ ctx, input, next }) => {
|
||||
const lang = input.lang ?? ctx.lang
|
||||
const token = isValidSession(ctx.session)
|
||||
? ctx.session.token.access_token
|
||||
: ctx.serviceToken
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
lang,
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.query(async function ({
|
||||
ctx,
|
||||
input: { confirmationNumber, lastName, firstName, email },
|
||||
}) {
|
||||
const { lang, token, serviceToken } = ctx
|
||||
const findBookingCounter = createCounter("trpc.booking.findBooking")
|
||||
const metricsFindBooking = findBookingCounter.init({ confirmationNumber })
|
||||
|
||||
metricsFindBooking.start()
|
||||
|
||||
const booking = await findBooking(
|
||||
{ confirmationNumber, lang, lastName, firstName, email },
|
||||
token
|
||||
)
|
||||
|
||||
if (!booking) {
|
||||
metricsFindBooking.dataError(
|
||||
`Fail to find booking data for ${confirmationNumber}`,
|
||||
{ confirmationNumber }
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
const [hotelData, hotelPages] = await Promise.all([
|
||||
getHotel(
|
||||
{
|
||||
hotelId: booking.hotelId,
|
||||
isCardOnlyPayment: false,
|
||||
language: lang,
|
||||
},
|
||||
serviceToken
|
||||
),
|
||||
getHotelPageUrls(lang),
|
||||
])
|
||||
const hotelPage = hotelPages.find(
|
||||
(page) => page.hotelId === booking.hotelId
|
||||
)
|
||||
|
||||
if (!hotelData) {
|
||||
metricsFindBooking.dataError(
|
||||
`Failed to find hotel data for ${booking.hotelId}`,
|
||||
{
|
||||
hotelId: booking.hotelId,
|
||||
}
|
||||
)
|
||||
|
||||
throw notFoundError({
|
||||
message: "Hotel data not found",
|
||||
errorDetails: { hotelId: booking.hotelId },
|
||||
})
|
||||
}
|
||||
|
||||
metricsFindBooking.success()
|
||||
|
||||
return {
|
||||
...hotelData,
|
||||
url: hotelPage?.url || null,
|
||||
booking,
|
||||
room: getHotelRoom(hotelData.roomCategories, booking.roomTypeCode),
|
||||
}
|
||||
})
|
||||
84
packages/trpc/lib/routers/booking/query/getBookingRoute.ts
Normal file
84
packages/trpc/lib/routers/booking/query/getBookingRoute.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { createCounter } from "@scandic-hotels/common/telemetry"
|
||||
|
||||
import { notFoundError } from "../../../errors"
|
||||
import { createRefIdPlugin } from "../../../plugins/refIdToConfirmationNumber"
|
||||
import { safeProtectedServiceProcedure } from "../../../procedures"
|
||||
import { getBooking } from "../../../services/booking/getBooking"
|
||||
import { getHotelPageUrls } from "../../contentstack/hotelPage/utils"
|
||||
import { getHotel } from "../../hotels/services/getHotel"
|
||||
import { getHotelRoom } from "../helpers"
|
||||
import { getBookingInput } from "../input"
|
||||
|
||||
const refIdPlugin = createRefIdPlugin()
|
||||
export const getBookingRoute = safeProtectedServiceProcedure
|
||||
.input(getBookingInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.use(async ({ ctx, input, next }) => {
|
||||
const lang = input.lang ?? ctx.lang
|
||||
const token = await ctx.getScandicUserToken()
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
lang,
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.query(async function ({ ctx }) {
|
||||
const { confirmationNumber, lang, token, serviceToken } = ctx
|
||||
|
||||
const getBookingCounter = createCounter("trpc.booking.get")
|
||||
const metricsGetBooking = getBookingCounter.init({ confirmationNumber })
|
||||
|
||||
metricsGetBooking.start()
|
||||
|
||||
const booking = await getBooking(
|
||||
{ confirmationNumber, lang },
|
||||
token ?? serviceToken
|
||||
)
|
||||
|
||||
if (!booking) {
|
||||
metricsGetBooking.dataError(
|
||||
`Fail to get booking data for ${confirmationNumber}`,
|
||||
{ confirmationNumber }
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
const [hotelData, hotelPages] = await Promise.all([
|
||||
getHotel(
|
||||
{
|
||||
hotelId: booking.hotelId,
|
||||
isCardOnlyPayment: false,
|
||||
language: lang,
|
||||
},
|
||||
serviceToken
|
||||
),
|
||||
getHotelPageUrls(lang),
|
||||
])
|
||||
const hotelPage = hotelPages.find(
|
||||
(page) => page.hotelId === booking.hotelId
|
||||
)
|
||||
|
||||
if (!hotelData) {
|
||||
metricsGetBooking.dataError(
|
||||
`Failed to get hotel data for ${booking.hotelId}`,
|
||||
{
|
||||
hotelId: booking.hotelId,
|
||||
}
|
||||
)
|
||||
throw notFoundError({
|
||||
message: "Hotel data not found",
|
||||
errorDetails: { hotelId: booking.hotelId },
|
||||
})
|
||||
}
|
||||
|
||||
metricsGetBooking.success()
|
||||
|
||||
return {
|
||||
...hotelData,
|
||||
url: hotelPage?.url || null,
|
||||
booking,
|
||||
room: getHotelRoom(hotelData.roomCategories, booking.roomTypeCode),
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from "zod"
|
||||
|
||||
import { Lang } from "@scandic-hotels/common/constants/language"
|
||||
|
||||
import { createRefIdPlugin } from "../../../plugins/refIdToConfirmationNumber"
|
||||
import { safeProtectedServiceProcedure } from "../../../procedures"
|
||||
import { getBookingStatus } from "../../../services/booking/getBookingStatus"
|
||||
import { encrypt } from "../../../utils/encryption"
|
||||
|
||||
const getBookingStatusInput = z.object({
|
||||
lang: z.nativeEnum(Lang).optional(),
|
||||
})
|
||||
|
||||
const refIdPlugin = createRefIdPlugin()
|
||||
export const getBookingStatusRoute = safeProtectedServiceProcedure
|
||||
.input(getBookingStatusInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.query(async function ({ ctx, input }) {
|
||||
const lang = input.lang ?? ctx.lang
|
||||
const { confirmationNumber } = ctx
|
||||
|
||||
const booking = await getBookingStatus(
|
||||
{ confirmationNumber, lang },
|
||||
ctx.serviceToken
|
||||
)
|
||||
|
||||
const expire = Math.floor(Date.now() / 1000) + 60 // 1 minute expiry
|
||||
|
||||
return {
|
||||
booking,
|
||||
sig: encrypt(expire.toString()),
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { createRefIdPlugin } from "../../../plugins/refIdToConfirmationNumber"
|
||||
import { safeProtectedServiceProcedure } from "../../../procedures"
|
||||
import { getLinkedReservations } from "../../../services/booking/linkedReservations"
|
||||
import { isValidSession } from "../../../utils/session"
|
||||
import { getLinkedReservationsInput } from "../input"
|
||||
|
||||
const refIdPlugin = createRefIdPlugin()
|
||||
export const getLinkedReservationsRoute = safeProtectedServiceProcedure
|
||||
.input(getLinkedReservationsInput)
|
||||
.concat(refIdPlugin.toConfirmationNumber)
|
||||
.use(async ({ ctx, input, next }) => {
|
||||
const lang = input.lang ?? ctx.lang
|
||||
const token = isValidSession(ctx.session)
|
||||
? ctx.session.token.access_token
|
||||
: ctx.serviceToken
|
||||
|
||||
return next({
|
||||
ctx: {
|
||||
lang,
|
||||
token,
|
||||
},
|
||||
})
|
||||
})
|
||||
.query(async function ({ ctx }) {
|
||||
const { confirmationNumber, lang, token } = ctx
|
||||
|
||||
return getLinkedReservations(
|
||||
{
|
||||
confirmationNumber,
|
||||
lang,
|
||||
},
|
||||
token
|
||||
)
|
||||
})
|
||||
@@ -1,171 +0,0 @@
|
||||
import { createCounter } from "@scandic-hotels/common/telemetry"
|
||||
|
||||
import * as api from "../../api"
|
||||
import {
|
||||
badRequestError,
|
||||
extractResponseDetails,
|
||||
serverErrorByStatus,
|
||||
} from "../../errors"
|
||||
import { toApiLang } from "../../utils"
|
||||
import { createBookingSchema } from "./mutation/create/schema"
|
||||
import { bookingConfirmationSchema } from "./output"
|
||||
|
||||
import type { Lang } from "@scandic-hotels/common/constants/language"
|
||||
|
||||
export async function getBooking(
|
||||
confirmationNumber: string,
|
||||
lang: Lang,
|
||||
token: string
|
||||
) {
|
||||
const getBookingCounter = createCounter("booking.get")
|
||||
const metricsGetBooking = getBookingCounter.init({ confirmationNumber })
|
||||
|
||||
metricsGetBooking.start()
|
||||
|
||||
const apiResponse = await api.get(
|
||||
api.endpoints.v1.Booking.booking(confirmationNumber),
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
{ language: toApiLang(lang) }
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsGetBooking.httpError(apiResponse)
|
||||
|
||||
// If the booking is not found, return null.
|
||||
// This scenario is expected to happen when a logged in user trying to access a booking that doesn't belong to them.
|
||||
if (apiResponse.status === 404) {
|
||||
return null
|
||||
}
|
||||
|
||||
throw serverErrorByStatus(
|
||||
apiResponse.status,
|
||||
await extractResponseDetails(apiResponse),
|
||||
"getBooking failed"
|
||||
)
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const booking = bookingConfirmationSchema.safeParse(apiJson)
|
||||
if (!booking.success) {
|
||||
metricsGetBooking.validationError(booking.error)
|
||||
throw badRequestError()
|
||||
}
|
||||
|
||||
metricsGetBooking.success()
|
||||
|
||||
return booking.data
|
||||
}
|
||||
|
||||
export async function findBooking(
|
||||
confirmationNumber: string,
|
||||
lang: Lang,
|
||||
token: string,
|
||||
lastName?: string,
|
||||
firstName?: string,
|
||||
email?: string
|
||||
) {
|
||||
const findBookingCounter = createCounter("booking.find")
|
||||
const metricsGetBooking = findBookingCounter.init({
|
||||
confirmationNumber,
|
||||
lastName,
|
||||
firstName,
|
||||
email,
|
||||
})
|
||||
|
||||
metricsGetBooking.start()
|
||||
|
||||
const apiResponse = await api.post(
|
||||
api.endpoints.v1.Booking.find(confirmationNumber),
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: {
|
||||
lastName,
|
||||
firstName,
|
||||
email,
|
||||
},
|
||||
},
|
||||
{ language: toApiLang(lang) }
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsGetBooking.httpError(apiResponse)
|
||||
|
||||
// If the booking is not found, return null.
|
||||
// This scenario is expected to happen when a logged in user trying to access a booking that doesn't belong to them.
|
||||
if (apiResponse.status === 400 || apiResponse.status === 404) {
|
||||
return null
|
||||
}
|
||||
|
||||
throw serverErrorByStatus(
|
||||
apiResponse.status,
|
||||
await extractResponseDetails(apiResponse),
|
||||
"findBooking failed"
|
||||
)
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const booking = bookingConfirmationSchema.safeParse(apiJson)
|
||||
if (!booking.success) {
|
||||
metricsGetBooking.validationError(booking.error)
|
||||
throw badRequestError()
|
||||
}
|
||||
|
||||
metricsGetBooking.success()
|
||||
|
||||
return booking.data
|
||||
}
|
||||
|
||||
export async function cancelBooking(
|
||||
confirmationNumber: string,
|
||||
language: Lang,
|
||||
token: string
|
||||
) {
|
||||
const cancelBookingCounter = createCounter("booking.cancel")
|
||||
const metricsCancelBooking = cancelBookingCounter.init({
|
||||
confirmationNumber,
|
||||
language,
|
||||
})
|
||||
|
||||
metricsCancelBooking.start()
|
||||
|
||||
const headers = {
|
||||
Authorization: `Bearer ${token}`,
|
||||
}
|
||||
|
||||
const booking = await getBooking(confirmationNumber, language, token)
|
||||
if (!booking) {
|
||||
metricsCancelBooking.noDataError({ confirmationNumber })
|
||||
return null
|
||||
}
|
||||
const { firstName, lastName, email } = booking.guest
|
||||
const apiResponse = await api.remove(
|
||||
api.endpoints.v1.Booking.cancel(confirmationNumber),
|
||||
{
|
||||
headers,
|
||||
body: { firstName, lastName, email },
|
||||
},
|
||||
{ language: toApiLang(language) }
|
||||
)
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
await metricsCancelBooking.httpError(apiResponse)
|
||||
return null
|
||||
}
|
||||
|
||||
const apiJson = await apiResponse.json()
|
||||
const verifiedData = createBookingSchema.safeParse(apiJson)
|
||||
if (!verifiedData.success) {
|
||||
metricsCancelBooking.validationError(verifiedData.error)
|
||||
return null
|
||||
}
|
||||
|
||||
metricsCancelBooking.success()
|
||||
|
||||
return verifiedData.data
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import z from "zod"
|
||||
import { z } from "zod"
|
||||
|
||||
import { AlertTypeEnum } from "@scandic-hotels/common/constants/alert"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user