export function getLandingPageParticipations()

in support-frontend/assets/helpers/abTests/landingPageAbTests.ts [117:193]


export function getLandingPageParticipations(
	countryGroupId: CountryGroupId = CountryGroup.detect(),
	path: string = window.location.pathname,
	tests: LandingPageTest[] = getSettings().landingPageTests ?? [],
	mvtId: number = getMvtId(),
	queryString: string = window.location.search,
): LandingPageParticipationsResult {
	// Is the participation forced in the url querystring?
	const urlParticipations = getParticipationFromQueryString(queryString);
	if (urlParticipations) {
		const variant = getLandingPageVariant(urlParticipations, tests);
		return {
			participations: urlParticipations,
			variant,
		};
	}

	// Is there already a participation in session storage?
	const sessionParticipations = getSessionParticipations(
		LANDING_PAGE_PARTICIPATIONS_KEY,
	);
	if (
		sessionParticipations &&
		Object.entries(sessionParticipations).length > 0
	) {
		const variant = getLandingPageVariant(sessionParticipations, tests);
		return {
			participations: sessionParticipations,
			variant,
		};
	} else {
		// No participation in session storage, assign user to a test + variant
		const test = tests
			.filter((test) => test.status == 'Live')
			.find((test) => {
				const targetedCountryGroups =
					test.regionTargeting?.targetedCountryGroups ?? [];
				if (targetedCountryGroups.length === 0) {
					return true;
				} // no targeting
				else {
					return targetedCountryGroups.includes(countryGroupId);
				}
			});

		// Only track participation if user is on the landing page
		const trackParticipation = isLandingPage(path);

		if (test) {
			const idx = randomNumber(mvtId, test.name) % test.variants.length;
			const variant = test.variants[idx];

			if (variant) {
				const participations = {
					[test.name]: variant.name,
				};
				// Record the participation in session storage so that we can track it from the checkout
				setSessionParticipations(
					participations,
					LANDING_PAGE_PARTICIPATIONS_KEY,
				);

				return {
					participations: trackParticipation ? participations : {},
					variant,
				};
			}
		}
		// No test found, use the fallback
		return {
			participations: trackParticipation
				? { FALLBACK_LANDING_PAGE: fallBackLandingPageSelection.name }
				: ({} as Participations),
			variant: fallBackLandingPageSelection,
		};
	}
}