diff --git a/src/Expensify.tsx b/src/Expensify.tsx
index 463f0d9adc7e..245c3a6a2c26 100644
--- a/src/Expensify.tsx
+++ b/src/Expensify.tsx
@@ -17,6 +17,7 @@ import CONST from './CONST';
import DeepLinkHandler from './DeepLinkHandler';
import DelegateAccessHandler from './DelegateAccessHandler';
import FullstoryInitHandler from './FullstoryInitHandler';
+import FullstoryUserContextHandler from './FullstoryUserContextHandler';
import GlobalModals from './GlobalModals';
import useDebugShortcut from './hooks/useDebugShortcut';
import useIsAuthenticated from './hooks/useIsAuthenticated';
@@ -288,6 +289,7 @@ function Expensify() {
+
{/* Wait for the initial URL to resolve before mounting NavigationRoot, because its initialState
diff --git a/src/FullstoryUserContextHandler.tsx b/src/FullstoryUserContextHandler.tsx
new file mode 100644
index 000000000000..6eab47517857
--- /dev/null
+++ b/src/FullstoryUserContextHandler.tsx
@@ -0,0 +1,120 @@
+import {useEffect, useRef} from 'react';
+
+import useOnyx from './hooks/useOnyx';
+import getEnvironment from './libs/Environment/getEnvironment';
+import FS from './libs/Fullstory';
+import {buildFullstoryUserVars, getComparableFullstoryUserVars} from './libs/Fullstory/utils';
+import {shallowCompare} from './libs/ObjectUtils';
+import ONYXKEYS from './ONYXKEYS';
+
+const SESSION_URL_RETRY_DELAY_MS = 250;
+const MAX_SESSION_URL_RETRY_ATTEMPTS = 20;
+
+function FullstoryUserContextHandler() {
+ const [account] = useOnyx(ONYXKEYS.ACCOUNT);
+ const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID);
+ const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED);
+ const [onboarding] = useOnyx(ONYXKEYS.NVP_ONBOARDING);
+ const [onboardingCompanySize] = useOnyx(ONYXKEYS.ONBOARDING_COMPANY_SIZE);
+ const [onboardingLastVisitedPath] = useOnyx(ONYXKEYS.ONBOARDING_LAST_VISITED_PATH);
+ const [onboardingPurposeSelected] = useOnyx(ONYXKEYS.ONBOARDING_PURPOSE_SELECTED);
+ const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
+ const [session] = useOnyx(ONYXKEYS.SESSION);
+ const [userMetadata] = useOnyx(ONYXKEYS.USER_METADATA);
+
+ const activePolicy = activePolicyID ? policies?.[`${ONYXKEYS.COLLECTION.POLICY}${activePolicyID}`] : undefined;
+
+ const previousUserVars = useRef | undefined>(undefined);
+ const previousAccountID = useRef(undefined);
+ const sessionURLRetryAttempts = useRef(0);
+
+ useEffect(() => {
+ if (!userMetadata?.accountID) {
+ return;
+ }
+
+ let didCancel = false;
+ let retryTimeoutID: ReturnType | undefined;
+
+ const syncUserVars = () => {
+ getEnvironment()
+ .then((envName) => {
+ if (didCancel || !FS.shouldInitialize(userMetadata, envName)) {
+ return;
+ }
+
+ // Use the session URL only as a readiness signal so this handler waits for the existing FullStory init path.
+ return FS.getSessionURL().then((sessionURL) => {
+ if (didCancel) {
+ return;
+ }
+
+ if (!sessionURL) {
+ sessionURLRetryAttempts.current += 1;
+ if (sessionURLRetryAttempts.current >= MAX_SESSION_URL_RETRY_ATTEMPTS) {
+ return;
+ }
+
+ retryTimeoutID = setTimeout(syncUserVars, SESSION_URL_RETRY_DELAY_MS);
+ return;
+ }
+
+ sessionURLRetryAttempts.current = 0;
+
+ if (previousAccountID.current !== userMetadata.accountID) {
+ previousAccountID.current = userMetadata.accountID;
+ previousUserVars.current = undefined;
+ }
+
+ const userVars = buildFullstoryUserVars({
+ account,
+ activePolicy,
+ introSelected,
+ onboarding,
+ onboardingCompanySize,
+ onboardingLastVisitedPath,
+ onboardingPurposeSelected,
+ policies,
+ session,
+ userMetadata,
+ });
+
+ const comparableUserVars = getComparableFullstoryUserVars(userVars);
+
+ if (shallowCompare(previousUserVars.current, comparableUserVars)) {
+ return;
+ }
+
+ previousUserVars.current = comparableUserVars;
+ FS.setUserVars(userVars);
+ });
+ })
+ .catch(() => {
+ if (didCancel) {
+ return;
+ }
+
+ sessionURLRetryAttempts.current += 1;
+ if (sessionURLRetryAttempts.current >= MAX_SESSION_URL_RETRY_ATTEMPTS) {
+ return;
+ }
+
+ retryTimeoutID = setTimeout(syncUserVars, SESSION_URL_RETRY_DELAY_MS);
+ });
+ };
+
+ syncUserVars();
+
+ return () => {
+ didCancel = true;
+ sessionURLRetryAttempts.current = 0;
+ if (retryTimeoutID) {
+ clearTimeout(retryTimeoutID);
+ }
+ };
+ }, [account, activePolicy, introSelected, onboarding, onboardingCompanySize, onboardingLastVisitedPath, onboardingPurposeSelected, policies, session, userMetadata]);
+
+ return null;
+}
+
+export default FullstoryUserContextHandler;
diff --git a/src/libs/Fullstory/common.ts b/src/libs/Fullstory/common.ts
index 0419440d03fc..46bc7bc5d53e 100644
--- a/src/libs/Fullstory/common.ts
+++ b/src/libs/Fullstory/common.ts
@@ -32,6 +32,12 @@ const allowedReportChatTypes = new Set>([
const allowedReportTypes = new Set>([CONST.REPORT.TYPE.IOU, CONST.REPORT.TYPE.EXPENSE, CONST.REPORT.TYPE.INVOICE]);
+type FullstoryPropertyValue = string | number | boolean | Date | null | undefined;
+
+type NormalizeFullstoryPropertiesForNativeOptions = {
+ preserveKeys?: readonly string[];
+};
+
const getChatFSClass: GetChatFSClass = (report) => {
if (!report) {
return CONST.FULLSTORY.CLASS.UNMASK;
@@ -76,4 +82,38 @@ const shouldInitializeFullstory: ShouldInitialize = (userMetadata, envName) => {
return true;
};
-export {getChatFSClass, shouldInitializeFullstory};
+function normalizeFullstoryPropertiesForNative(
+ properties: Record,
+ {preserveKeys = []}: NormalizeFullstoryPropertiesForNativeOptions = {},
+): Record {
+ const normalizedProperties: Record = {};
+ const preservedKeys = new Set(preserveKeys);
+
+ for (const [key, value] of Object.entries(properties)) {
+ if (value === undefined || value === null) {
+ continue;
+ }
+
+ if (preservedKeys.has(key)) {
+ normalizedProperties[key] = value instanceof Date ? value.toISOString() : value;
+ continue;
+ }
+
+ if (value instanceof Date) {
+ normalizedProperties[`${key}_date`] = value.toISOString();
+ continue;
+ }
+
+ if (typeof value === 'string') {
+ normalizedProperties[`${key}_str`] = value;
+ } else if (typeof value === 'number') {
+ normalizedProperties[`${key}_real`] = value;
+ } else if (typeof value === 'boolean') {
+ normalizedProperties[`${key}_bool`] = value;
+ }
+ }
+
+ return normalizedProperties;
+}
+
+export {getChatFSClass, normalizeFullstoryPropertiesForNative, shouldInitializeFullstory};
diff --git a/src/libs/Fullstory/index.native.ts b/src/libs/Fullstory/index.native.ts
index 2442afc993cf..e1b507c9f4ea 100644
--- a/src/libs/Fullstory/index.native.ts
+++ b/src/libs/Fullstory/index.native.ts
@@ -4,7 +4,9 @@ import FullStory, {FSPage} from '@fullstory/react-native';
import type {Fullstory} from './types';
-import {getChatFSClass, shouldInitializeFullstory} from './common';
+import {getChatFSClass, normalizeFullstoryPropertiesForNative, shouldInitializeFullstory} from './common';
+
+let isFullstoryTrackingEnabled = false;
const FS: Fullstory = {
Page: FSPage,
@@ -20,8 +22,7 @@ const FS: Fullstory = {
consent: (shouldConsent) => FullStory.consent(shouldConsent),
identify: (userMetadata, envName) => {
- const localMetadata = userMetadata;
- localMetadata.environment = envName;
+ const localMetadata = {...userMetadata, environment: envName};
FullStory.identify(String(localMetadata.accountID), localMetadata);
},
@@ -36,6 +37,7 @@ const FS: Fullstory = {
// We only use FullStory in production environment. We need to check this here
// after the init function since this function is also called on updates for
// UserMetadata onyx key.
+ isFullstoryTrackingEnabled = false;
getEnvironment().then((envName: string) => {
if (!FS.shouldInitialize(userMetadata, envName)) {
return;
@@ -44,6 +46,7 @@ const FS: Fullstory = {
FullStory.restart();
FullStory.consent(true);
FS.identify(userMetadata, envName);
+ isFullstoryTrackingEnabled = true;
});
} catch (e) {
// error handler
@@ -60,8 +63,12 @@ const FS: Fullstory = {
return FullStory.getCurrentSessionURL();
},
- event: (eventName, eventProperties = {}) => {
- FullStory.event(eventName, eventProperties);
+ event: (eventName, eventProperties) => {
+ if (!isFullstoryTrackingEnabled) {
+ return;
+ }
+
+ FullStory.event(eventName, normalizeFullstoryPropertiesForNative(eventProperties ?? {}));
},
log: (level, message) => {
@@ -75,7 +82,11 @@ const FS: Fullstory = {
},
setUserVars: (userVars) => {
- FullStory.setUserVars(userVars);
+ FullStory.setUserVars(
+ normalizeFullstoryPropertiesForNative(userVars, {
+ preserveKeys: ['displayName', 'email'],
+ }),
+ );
},
resetIdleTimer: () => {
diff --git a/src/libs/Fullstory/index.ts b/src/libs/Fullstory/index.ts
index 41339ec4b215..28171b6b8609 100644
--- a/src/libs/Fullstory/index.ts
+++ b/src/libs/Fullstory/index.ts
@@ -106,11 +106,11 @@ const FS: Fullstory = {
return FullStory('getSessionAsync', {format: 'url'});
},
- event: (eventName, eventProperties = {}) => {
+ event: (eventName, eventProperties) => {
if (!isInitialized()) {
return;
}
- FullStory(CONST.FULLSTORY.OPERATION.TRACK_EVENT, {name: eventName, properties: eventProperties});
+ FullStory(CONST.FULLSTORY.OPERATION.TRACK_EVENT, {name: eventName, properties: eventProperties ?? {}});
},
log: (level, message) => {
diff --git a/src/libs/Fullstory/types.ts b/src/libs/Fullstory/types.ts
index 133534479c61..b003f93cae57 100644
--- a/src/libs/Fullstory/types.ts
+++ b/src/libs/Fullstory/types.ts
@@ -8,6 +8,138 @@ type FSClass = ValueOf;
type PropertiesWithoutPageName = Record & {pageName?: never};
+/* eslint-disable @typescript-eslint/naming-convention -- FullStory schema uses external snake_case keys. */
+type FullstoryUserVars = {
+ user_type_path?: string;
+ account_type?: 'personal' | 'business';
+ user_status?: 'new' | 'returning';
+ has_completed_onboarding?: boolean;
+ onb_step?: 'registration' | 'accounting' | 'completed';
+ user_role?: 'admin' | 'auditor' | 'member';
+ workspace_state?: 'has_workspaces' | 'no_workspaces';
+ workspace_count?: number;
+ workspace_member_count?: number;
+ free_trial_end_date?: Date;
+ days_till_trial_end?: number;
+ free_trial_status?: 'active' | 'expiring_soon' | 'expired' | 'expired_last30days';
+ plan_type?: 'collect' | 'control';
+ paid_member?: boolean;
+ auth_method?: 'email' | 'google' | 'apple';
+ reg_method?: 'Google signup' | 'email/phone signup';
+ login_status?: 'success' | 'failure';
+};
+
+type FullstoryEventPropertiesMap = {
+ Page_viewed: {
+ screen_name: string;
+ entry_point?: string;
+ onb_step?: FullstoryUserVars['onb_step'];
+ };
+ Component_viewed: {
+ screen_name: string;
+ location?: string;
+ component_name?: string;
+ onb_step?: FullstoryUserVars['onb_step'];
+ };
+ Component_closed: {
+ screen_name: string;
+ location?: string;
+ component_name?: string;
+ onb_step?: FullstoryUserVars['onb_step'];
+ };
+ clickable_action: {
+ screen_name?: string;
+ location?: string;
+ component_name?: string;
+ onb_step?: FullstoryUserVars['onb_step'];
+ element_label?: string;
+ checked_box?: boolean;
+ toggle_switch_on?: boolean;
+ result_type?: string;
+ action_status?: string;
+ position?: number;
+ };
+ Input_field: {
+ screen_name?: string;
+ location?: string;
+ component_name?: string;
+ onb_step?: FullstoryUserVars['onb_step'];
+ input_field_name?: string;
+ input_field_type?: string;
+ input_field_status?: string;
+ };
+ Error_message: {
+ screen_name?: string;
+ location?: string;
+ component_name?: string;
+ onb_step?: FullstoryUserVars['onb_step'];
+ error_location?: string;
+ error_code?: string;
+ error_message?: string;
+ error_type?: string;
+ };
+ Search_submitted: {
+ screen_name?: string;
+ result_type?: string;
+ search_results_count?: number;
+ search_type?: string;
+ };
+ Chat_opened: {
+ screen_name?: string;
+ chat_type?: 'Full-page chat' | 'side-panel chat';
+ };
+ Login_submitted: {
+ action_status?: string;
+ };
+ sign_up: {
+ entry_point?: string;
+ action_status?: string;
+ };
+ File_upload_started: {
+ upload_method?: string;
+ };
+ File_upload_completed: {
+ upload_success?: boolean;
+ };
+ Concierge_message_sent: {
+ has_attachment?: boolean;
+ attachment_count?: number;
+ attachment_types?: string;
+ upload_method?: string;
+ };
+ Chatbot_response_received: {
+ error_type?: string;
+ };
+ Expense_created: {
+ expense_type?: string;
+ expense_creation_method?: string;
+ amount_range?: string;
+ };
+ Report_created: {
+ expense_count?: number;
+ report_type?: string;
+ };
+ Report_submitted: {
+ expense_count?: number;
+ report_type?: string;
+ approver_count?: number;
+ };
+ Bank_account_added: {
+ bank_account_type?: string;
+ card_connection_method?: string;
+ bank_region?: string;
+ };
+ Card_added: {
+ card_connection_method?: string;
+ card_type?: string;
+ card_provider?: string;
+ card_country?: string;
+ };
+};
+
+type FullstoryEventName = keyof FullstoryEventPropertiesMap;
+/* eslint-enable @typescript-eslint/naming-convention */
+
/**
* Represents the common FSPage class signature that will be used in both platform implementations.
*/
@@ -88,7 +220,7 @@ type Fullstory = {
/**
* Sends a custom event to FullStory.
*/
- event: (eventName: string, eventProperties?: Record) => void;
+ event: (eventName: TEventName, eventProperties?: FullstoryEventPropertiesMap[TEventName]) => void;
/**
* Sends a log message to FullStory with the specified log level.
@@ -98,7 +230,7 @@ type Fullstory = {
/**
* Updates user properties without re-identifying.
*/
- setUserVars: (userVars: Record) => void;
+ setUserVars: (userVars: FullstoryUserVars) => void;
/**
* Resets the idle timer to prevent session timeout.
@@ -149,4 +281,4 @@ type ForwardedFSClassProps = {
forwardedFSClass?: FSClass;
};
-export type {FSPageLike, Fullstory, GetChatFSClass, ForwardedFSClassProps, ShouldInitialize};
+export type {FSPageLike, Fullstory, FullstoryEventName, FullstoryEventPropertiesMap, FullstoryUserVars, GetChatFSClass, ForwardedFSClassProps, ShouldInitialize};
diff --git a/src/libs/Fullstory/utils.ts b/src/libs/Fullstory/utils.ts
new file mode 100644
index 000000000000..bb58c016f19c
--- /dev/null
+++ b/src/libs/Fullstory/utils.ts
@@ -0,0 +1,245 @@
+import {filterObject} from '@libs/ObjectUtils';
+import {getActivePolicies, isControlPolicy} from '@libs/PolicyUtils';
+
+import CONST from '@src/CONST';
+import ROUTES from '@src/ROUTES';
+import type {Account, IntroSelected, Onboarding, Policy, Session, UserMetadata} from '@src/types/onyx';
+
+import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
+import type {ValueOf} from 'type-fest';
+
+import {fromZonedTime} from 'date-fns-tz';
+
+import type {FullstoryEventName, FullstoryEventPropertiesMap, FullstoryUserVars} from './types';
+
+import FS from '.';
+
+const MS_PER_DAY = 1000 * 60 * 60 * 24;
+const EXPIRED_THRESHOLD_DAYS = -30;
+const EXPIRING_SOON_THRESHOLD_DAYS = 14;
+
+type BuildFullstoryUserVarsParams = {
+ account: OnyxEntry;
+ activePolicy: OnyxEntry;
+ introSelected: OnyxEntry;
+ onboarding: OnyxEntry;
+ onboardingCompanySize: OnyxEntry;
+ onboardingLastVisitedPath: OnyxEntry;
+ onboardingPurposeSelected: OnyxEntry>;
+ policies: OnyxCollection | undefined;
+ session: OnyxEntry;
+ userMetadata: OnyxEntry;
+};
+
+function sanitizeSegment(value: string): string {
+ return value
+ .toLowerCase()
+ .replaceAll(/[^a-z0-9]+/g, '_')
+ .replaceAll(/^_+|_+$/g, '');
+}
+
+function getNormalizedOnboardingChoice(choice: OnyxEntry>): string | undefined {
+ if (!choice) {
+ return;
+ }
+
+ const choiceMap: Partial, string>> = {
+ [CONST.ONBOARDING_CHOICES.MANAGE_TEAM]: 'team',
+ [CONST.ONBOARDING_CHOICES.TRACK_BUSINESS]: 'track_business',
+ [CONST.ONBOARDING_CHOICES.TRACK_PERSONAL]: 'track_personal',
+ [CONST.ONBOARDING_CHOICES.PERSONAL_SPEND]: 'personal_spend',
+ [CONST.ONBOARDING_CHOICES.LOOKING_AROUND]: 'looking_around',
+ [CONST.ONBOARDING_CHOICES.EMPLOYER]: 'employer',
+ [CONST.ONBOARDING_CHOICES.CHAT_SPLIT]: 'chat_split',
+ [CONST.ONBOARDING_CHOICES.ADMIN]: 'admin',
+ [CONST.ONBOARDING_CHOICES.SUBMIT]: 'submit',
+ [CONST.ONBOARDING_CHOICES.TEST_DRIVE_RECEIVER]: 'test_drive_receiver',
+ };
+
+ return choiceMap[choice] ?? sanitizeSegment(choice);
+}
+
+function buildUserTypePath(choice: OnyxEntry>, companySize: OnyxEntry, isFromPublicDomain?: boolean): string | undefined {
+ const normalizedChoice = getNormalizedOnboardingChoice(choice);
+ const normalizedCompanySize = companySize ? sanitizeSegment(companySize) : undefined;
+ let domainType: string | undefined;
+ if (isFromPublicDomain !== undefined) {
+ domainType = isFromPublicDomain ? 'public' : 'private';
+ }
+
+ const segments = [normalizedChoice, normalizedCompanySize, domainType].filter(Boolean);
+ if (segments.length === 0) {
+ return;
+ }
+
+ return segments.join('_');
+}
+
+function getDaysTillDate(endDate: Date | undefined): number | undefined {
+ if (!endDate) {
+ return;
+ }
+
+ if (Number.isNaN(endDate.getTime())) {
+ return;
+ }
+
+ const diffInDays = (endDate.getTime() - Date.now()) / MS_PER_DAY;
+ return diffInDays >= 0 ? Math.ceil(diffInDays) : Math.floor(diffInDays);
+}
+
+function getFreeTrialEndDate(dateString: string | undefined): Date | undefined {
+ if (!dateString) {
+ return;
+ }
+
+ const endDate = fromZonedTime(dateString, 'UTC');
+ if (Number.isNaN(endDate.getTime())) {
+ return;
+ }
+
+ return endDate;
+}
+
+function getFreeTrialStatus(daysTillTrialEnd: number | undefined): FullstoryUserVars['free_trial_status'] {
+ if (daysTillTrialEnd === undefined) {
+ return;
+ }
+ if (daysTillTrialEnd < EXPIRED_THRESHOLD_DAYS) {
+ return 'expired';
+ }
+ if (daysTillTrialEnd < 0) {
+ return 'expired_last30days';
+ }
+ if (daysTillTrialEnd <= EXPIRING_SOON_THRESHOLD_DAYS) {
+ return 'expiring_soon';
+ }
+ return 'active';
+}
+
+function getOnboardingStep(onboardingPath: string | undefined, hasCompletedOnboarding?: boolean): FullstoryUserVars['onb_step'] {
+ if (hasCompletedOnboarding) {
+ return 'completed';
+ }
+
+ if (!onboardingPath) {
+ return;
+ }
+
+ const normalizedOnboardingPath = onboardingPath.replace(/^\/+/, '').split('?').at(0);
+
+ if (!normalizedOnboardingPath) {
+ return;
+ }
+
+ if (normalizedOnboardingPath === ROUTES.ONBOARDING_ACCOUNTING.route) {
+ return 'accounting';
+ }
+
+ if (normalizedOnboardingPath === ROUTES.ONBOARDING_ROOT.route || normalizedOnboardingPath.startsWith(`${ROUTES.ONBOARDING_ROOT.route}/`)) {
+ return 'registration';
+ }
+}
+
+function getUserRole(activePolicies: Policy[]): FullstoryUserVars['user_role'] {
+ let userRole: FullstoryUserVars['user_role'] = 'member';
+
+ for (const policy of activePolicies) {
+ if (policy?.role === CONST.POLICY.ROLE.ADMIN) {
+ return 'admin';
+ }
+ if (policy?.role === CONST.POLICY.ROLE.AUDITOR) {
+ userRole = 'auditor';
+ }
+ }
+
+ return userRole;
+}
+
+function getPlanType(policies: Policy[]): FullstoryUserVars['plan_type'] {
+ if (policies.some(isControlPolicy)) {
+ return 'control';
+ }
+ if (policies.some((policy) => policy.type === CONST.POLICY.TYPE.TEAM)) {
+ return 'collect';
+ }
+}
+
+function buildFullstoryUserVars({
+ account,
+ activePolicy,
+ introSelected,
+ onboarding,
+ onboardingCompanySize,
+ onboardingLastVisitedPath,
+ onboardingPurposeSelected,
+ policies,
+ session,
+ userMetadata,
+}: BuildFullstoryUserVarsParams): FullstoryUserVars {
+ const activePolicies = getActivePolicies(policies ?? null, session?.email);
+ const hasCompletedOnboarding = onboarding?.hasCompletedGuidedSetupFlow;
+ const currentOnboardingChoice = introSelected?.choice ?? onboardingPurposeSelected;
+ const companySize = introSelected?.companySize ?? onboardingCompanySize;
+ const freeTrialEndDate = getFreeTrialEndDate(userMetadata?.freeTrialEndDate);
+ const daysTillTrialEnd = getDaysTillDate(freeTrialEndDate);
+ let userStatus: FullstoryUserVars['user_status'];
+
+ if (hasCompletedOnboarding !== undefined) {
+ userStatus = hasCompletedOnboarding ? 'returning' : 'new';
+ }
+
+ /* eslint-disable @typescript-eslint/naming-convention -- FullStory schema uses external snake_case keys. */
+ return filterObject(
+ {
+ user_type_path: buildUserTypePath(currentOnboardingChoice, companySize, account?.isFromPublicDomain),
+ account_type: activePolicies.length > 0 ? 'business' : 'personal',
+ user_status: userStatus,
+ has_completed_onboarding: hasCompletedOnboarding,
+ onb_step: getOnboardingStep(onboardingLastVisitedPath, hasCompletedOnboarding),
+ user_role: getUserRole(activePolicies),
+ workspace_state: activePolicies.length > 0 ? 'has_workspaces' : 'no_workspaces',
+ workspace_count: activePolicies.length,
+ workspace_member_count: activePolicy ? Object.keys(activePolicy.employeeList ?? {}).length : undefined,
+ free_trial_end_date: freeTrialEndDate,
+ days_till_trial_end: daysTillTrialEnd,
+ free_trial_status: getFreeTrialStatus(daysTillTrialEnd),
+ plan_type: getPlanType(activePolicies),
+ paid_member: userMetadata?.paidMember,
+ } satisfies FullstoryUserVars,
+ (_key, value) => value !== undefined,
+ );
+ /* eslint-enable @typescript-eslint/naming-convention */
+}
+
+function trackFullstoryEvent(eventName: TEventName, eventProperties: FullstoryEventPropertiesMap[TEventName]) {
+ FS.event(
+ eventName,
+ filterObject(eventProperties, (_key, value) => value !== undefined),
+ );
+}
+
+function buildPageViewedEvent(screenName: string, currentPath: string, entryPoint?: string): FullstoryEventPropertiesMap['Page_viewed'] {
+ /* eslint-disable @typescript-eslint/naming-convention -- FullStory schema uses external snake_case keys. */
+ return {
+ screen_name: screenName,
+ entry_point: entryPoint,
+ onb_step: getOnboardingStep(currentPath),
+ };
+ /* eslint-enable @typescript-eslint/naming-convention */
+}
+
+/* eslint-disable @typescript-eslint/naming-convention -- The comparable snapshot preserves FullStory's external snake_case field names. */
+type ComparableFullstoryUserVars = Omit & {
+ free_trial_end_date?: string;
+};
+
+function getComparableFullstoryUserVars(userVars: FullstoryUserVars): ComparableFullstoryUserVars {
+ return {
+ ...userVars,
+ free_trial_end_date: userVars.free_trial_end_date?.toISOString(),
+ };
+}
+/* eslint-enable @typescript-eslint/naming-convention */
+
+export {buildFullstoryUserVars, buildPageViewedEvent, getComparableFullstoryUserVars, getOnboardingStep, trackFullstoryEvent};
diff --git a/src/libs/Navigation/NavigationRoot.tsx b/src/libs/Navigation/NavigationRoot.tsx
index cafeb6747695..7cc3f38ba7f0 100644
--- a/src/libs/Navigation/NavigationRoot.tsx
+++ b/src/libs/Navigation/NavigationRoot.tsx
@@ -8,6 +8,7 @@ import useTheme from '@hooks/useTheme';
import useThemePreference from '@hooks/useThemePreference';
import FS from '@libs/Fullstory';
+import {buildPageViewedEvent, trackFullstoryEvent} from '@libs/Fullstory/utils';
import Log from '@libs/Log';
import {setupNavigationFocusReturn, teardownNavigationFocusReturn} from '@libs/NavigationFocusReturn';
import {sanitizeUrlForLogging} from '@libs/sanitizeLogParams';
@@ -59,6 +60,21 @@ type NavigationRootProps = {
onReady: () => void;
};
+let previousFullstoryPath: string | undefined;
+
+function trackFullstoryPageView(state: NavigationState) {
+ const currentPath = getPathFromState(state);
+ const isTransitionRoute = currentPath.startsWith(`/${ROUTES.TRANSITION_BETWEEN_APPS}`);
+ const focusedRouteName = findFocusedRoute(state)?.name;
+ if (!focusedRouteName || isTransitionRoute) {
+ return;
+ }
+
+ new FS.Page(focusedRouteName, {path: currentPath}).start();
+ trackFullstoryEvent('Page_viewed', buildPageViewedEvent(focusedRouteName, currentPath, previousFullstoryPath));
+ previousFullstoryPath = currentPath;
+}
+
/**
* Intercept navigation state changes and log it
*/
@@ -103,11 +119,7 @@ function parseAndLogRoute(state: NavigationState) {
}
}
- // Fullstory Page navigation tracking
- const focusedRouteName = focusedRoute?.name;
- if (focusedRouteName) {
- new FS.Page(focusedRouteName, {path: currentPath}).start();
- }
+ trackFullstoryPageView(state);
}
function NavigationRoot({authenticated, lastVisitedPath, initialUrl, onReady}: NavigationRootProps) {
@@ -227,7 +239,13 @@ function NavigationRoot({authenticated, lastVisitedPath, initialUrl, onReady}: N
// After logout, reset the nav state so a logged-out user can't stay on a protected or
// consumed route.
const hasUserLoggedOut = !authenticated && !!previousAuthenticated;
- if (!hasUserLoggedOut || !navigationRef.isReady()) {
+ if (!hasUserLoggedOut) {
+ return;
+ }
+
+ previousFullstoryPath = undefined;
+
+ if (!navigationRef.isReady()) {
return;
}
@@ -270,6 +288,7 @@ function NavigationRoot({authenticated, lastVisitedPath, initialUrl, onReady}: N
endSpan(CONST.TELEMETRY.SPAN_BOOTSPLASH.NAVIGATION);
onReady();
navigationIntegration.registerNavigationContainer(navigationRef);
+ trackFullstoryPageView(navigationRef.getRootState());
setupNavigationFocusReturn();
}, [onReady]);
diff --git a/tests/unit/FullstoryCommonTest.ts b/tests/unit/FullstoryCommonTest.ts
new file mode 100644
index 000000000000..3afe393cc3e0
--- /dev/null
+++ b/tests/unit/FullstoryCommonTest.ts
@@ -0,0 +1,32 @@
+/* eslint-disable @typescript-eslint/naming-convention -- Test assertions use FullStory's external snake_case keys. */
+import {normalizeFullstoryPropertiesForNative} from '@src/libs/Fullstory/common';
+
+describe('FullstoryCommon', () => {
+ it('normalizes FullStory properties for native V1 APIs', () => {
+ const freeTrialEndDate = new Date('2099-05-31T23:59:59Z');
+
+ expect(
+ normalizeFullstoryPropertiesForNative(
+ {
+ account_type: 'business',
+ workspace_count: 3,
+ paid_member: true,
+ free_trial_end_date: freeTrialEndDate,
+ displayName: 'Jane Doe',
+ email: 'jane@example.com',
+ optional_value: undefined,
+ },
+ {
+ preserveKeys: ['displayName', 'email'],
+ },
+ ),
+ ).toEqual({
+ account_type_str: 'business',
+ workspace_count_real: 3,
+ paid_member_bool: true,
+ free_trial_end_date_date: freeTrialEndDate.toISOString(),
+ displayName: 'Jane Doe',
+ email: 'jane@example.com',
+ });
+ });
+});
diff --git a/tests/unit/FullstoryUtilsTest.ts b/tests/unit/FullstoryUtilsTest.ts
new file mode 100644
index 000000000000..e58635454a1c
--- /dev/null
+++ b/tests/unit/FullstoryUtilsTest.ts
@@ -0,0 +1,103 @@
+/* eslint-disable @typescript-eslint/naming-convention -- Test assertions use FullStory's external snake_case keys. */
+import CONST from '@src/CONST';
+import {buildFullstoryUserVars, buildPageViewedEvent, getOnboardingStep} from '@src/libs/Fullstory/utils';
+import ROUTES from '@src/ROUTES';
+
+import createRandomPolicy from '../utils/collections/policies';
+
+describe('FullstoryUtils', () => {
+ it('builds expected FullStory user vars from onboarding and workspace context', () => {
+ const freeTrialEndDate = new Date('2099-05-31T23:59:59Z');
+
+ const policy = {
+ ...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM, 'Test Workspace'),
+ role: CONST.POLICY.ROLE.ADMIN,
+ pendingAction: undefined,
+ employeeList: {
+ 1: {email: 'a@test.com'},
+ 2: {email: 'b@test.com'},
+ },
+ };
+
+ const userVars = buildFullstoryUserVars({
+ account: {isFromPublicDomain: true},
+ activePolicy: policy,
+ introSelected: {
+ choice: CONST.ONBOARDING_CHOICES.MANAGE_TEAM,
+ companySize: '1-10',
+ },
+ onboarding: {
+ hasCompletedGuidedSetupFlow: false,
+ signupQualifier: CONST.ONBOARDING_SIGNUP_QUALIFIERS.SMB,
+ },
+ onboardingCompanySize: '1-10',
+ onboardingLastVisitedPath: '/onboarding/workspace',
+ onboardingPurposeSelected: CONST.ONBOARDING_CHOICES.MANAGE_TEAM,
+ policies: {
+ [`policy_${policy.id}`]: policy,
+ },
+ session: {email: 'test@test.com'},
+ userMetadata: {
+ freeTrialEndDate: '2099-05-31 23:59:59',
+ paidMember: true,
+ },
+ });
+
+ expect(userVars).toMatchObject({
+ user_type_path: 'team_1_10_public',
+ account_type: 'business',
+ user_status: 'new',
+ has_completed_onboarding: false,
+ onb_step: 'registration',
+ user_role: 'admin',
+ workspace_state: 'has_workspaces',
+ workspace_count: 1,
+ workspace_member_count: 2,
+ free_trial_end_date: freeTrialEndDate,
+ free_trial_status: 'active',
+ plan_type: 'collect',
+ paid_member: true,
+ });
+ expect(userVars.days_till_trial_end).toBeGreaterThan(0);
+ expect(userVars.free_trial_end_date?.toISOString()).toBe('2099-05-31T23:59:59.000Z');
+ });
+
+ it('builds page viewed event metadata', () => {
+ expect(buildPageViewedEvent('OnboardingWorkspaces', ROUTES.ONBOARDING_WORKSPACES.route, ROUTES.HOME)).toEqual({
+ screen_name: 'OnboardingWorkspaces',
+ entry_point: ROUTES.HOME,
+ onb_step: 'registration',
+ });
+ });
+
+ it('returns completed onboarding step when flow is finished', () => {
+ expect(getOnboardingStep('/settings/workspaces', true)).toBe('completed');
+ });
+
+ it('does not treat unrelated paths containing onboarding as registration', () => {
+ expect(getOnboardingStep('/settings/onboarding-foo')).toBeUndefined();
+ });
+
+ it('prefers active policies when deriving the user role', () => {
+ const role = buildFullstoryUserVars({
+ account: {isFromPublicDomain: true},
+ activePolicy: undefined,
+ introSelected: undefined,
+ onboarding: undefined,
+ onboardingCompanySize: undefined,
+ onboardingLastVisitedPath: undefined,
+ onboardingPurposeSelected: undefined,
+ policies: {
+ policy_1: {
+ ...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM, 'Inactive Workspace'),
+ pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
+ role: CONST.POLICY.ROLE.ADMIN,
+ },
+ },
+ session: {email: 'test@test.com'},
+ userMetadata: {},
+ });
+
+ expect(role.user_role).toBe('member');
+ });
+});