93 lines
2.8 KiB
TypeScript
93 lines
2.8 KiB
TypeScript
import { z } from "zod"
|
|
|
|
import { Lang } from "@scandic-hotels/common/constants/language"
|
|
import { createCounter } from "@scandic-hotels/common/telemetry"
|
|
|
|
import { safeProtectedProcedure } from "../../../procedures"
|
|
import { isValidSession } from "../../../utils/session"
|
|
import { getFriendsMembership } from "../helpers"
|
|
import { getPreviousStays, getVerifiedUser } from "../utils"
|
|
|
|
import type { LoginType } from "@scandic-hotels/common/constants/loginType"
|
|
|
|
import type { TrackingUserData } from "../../types"
|
|
|
|
export const userTrackingInput = z.object({
|
|
lang: z.nativeEnum(Lang).optional(),
|
|
})
|
|
export const userTrackingInfo = safeProtectedProcedure
|
|
.input(userTrackingInput)
|
|
.query(async function ({ ctx, input }) {
|
|
const { lang } = input
|
|
const language = lang || ctx.lang
|
|
|
|
const userTrackingInfoCounter = createCounter("user", "userTrackingInfo")
|
|
const metricsUserTrackingInfo = userTrackingInfoCounter.init()
|
|
|
|
metricsUserTrackingInfo.start()
|
|
|
|
const notLoggedInUserTrackingData: TrackingUserData = {
|
|
loginStatus: "Non-logged in",
|
|
}
|
|
|
|
if (!isValidSession(ctx.session)) {
|
|
metricsUserTrackingInfo.success({
|
|
reason: "invalid session",
|
|
data: notLoggedInUserTrackingData,
|
|
})
|
|
return notLoggedInUserTrackingData
|
|
}
|
|
|
|
try {
|
|
const verifiedUserData = await getVerifiedUser({ session: ctx.session })
|
|
|
|
if (
|
|
!verifiedUserData ||
|
|
"error" in verifiedUserData ||
|
|
!verifiedUserData.data.loyalty
|
|
) {
|
|
metricsUserTrackingInfo.success({
|
|
reason: "invalid user data",
|
|
data: notLoggedInUserTrackingData,
|
|
})
|
|
return notLoggedInUserTrackingData
|
|
}
|
|
|
|
const previousStaysData = await getPreviousStays(
|
|
ctx.session.token.access_token,
|
|
1,
|
|
language
|
|
)
|
|
if (!previousStaysData) {
|
|
metricsUserTrackingInfo.success({
|
|
reason: "no previous stays data",
|
|
data: notLoggedInUserTrackingData,
|
|
})
|
|
return notLoggedInUserTrackingData
|
|
}
|
|
|
|
const membership = getFriendsMembership(verifiedUserData.data.loyalty)
|
|
|
|
const loggedInUserTrackingData: TrackingUserData = {
|
|
loginStatus: "logged in",
|
|
loginType: ctx.session.token.loginType as LoginType,
|
|
memberId: verifiedUserData.data.profileId,
|
|
membershipNumber: membership?.membershipNumber,
|
|
memberLevel: membership?.membershipLevel,
|
|
noOfNightsStayed: previousStaysData.links?.totalCount ?? 0,
|
|
totalPointsAvailableToSpend: membership?.currentPoints,
|
|
loginAction: "login success",
|
|
}
|
|
|
|
metricsUserTrackingInfo.success({
|
|
reason: "valid logged in",
|
|
data: loggedInUserTrackingData,
|
|
})
|
|
|
|
return loggedInUserTrackingData
|
|
} catch (error) {
|
|
metricsUserTrackingInfo.fail(error)
|
|
return notLoggedInUserTrackingData
|
|
}
|
|
})
|