From b7e277dfb98f44672170af2150210576b70a8e54 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 09:42:14 +0000 Subject: [PATCH] feat(push): open any in-app screen a nudge links, track the nudge, credit push opens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A push link outside the known paths opens the way a Universal Link does (plain paths, own params kept, campaign params dropped), except screens a push must never open (signup, recovery, settings, 3DS…). Admins can point an automated nudge at a new screen without an app release. - Push Notification Opened carries nudge_key and nudge_version. - utm_medium=push gets its own attribution channel, and a push open updates the last touch. - Push token registration (and refresh) sends the device time zone, for nudge quiet hours, and the app version. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015YMpaeA4SmeQ3jcQFNe11J --- hooks/__tests__/usePushNotifications.test.ts | 48 ++++++++++++- hooks/usePushNotifications.ts | 71 ++++++++++++++++++-- lib/api.ts | 13 +++- lib/attribution.ts | 3 + lib/registerForPushNotifications.ts | 24 ++++++- 5 files changed, 150 insertions(+), 9 deletions(-) diff --git a/hooks/__tests__/usePushNotifications.test.ts b/hooks/__tests__/usePushNotifications.test.ts index c2a17c1a6..58b0bb3a5 100644 --- a/hooks/__tests__/usePushNotifications.test.ts +++ b/hooks/__tests__/usePushNotifications.test.ts @@ -12,6 +12,7 @@ jest.mock('@react-native-firebase/messaging', () => () => ({ onTokenRefresh: jes jest.mock('@/lib/api', () => ({ registerPushToken: jest.fn() })); jest.mock('@/lib/registerForPushNotifications', () => ({ registerForPushNotificationsAsync: jest.fn(), + pushDeviceInfo: jest.fn(() => ({})), })); jest.mock('@/lib/analytics', () => ({ track: jest.fn() })); // Both zustand stores the hook imports persist through MMKV, whose native @@ -144,8 +145,26 @@ describe('routeForLink', () => { ); }); - it('returns nothing for a link it cannot place, rather than guessing', () => { - expect(routeForLink(link('/some/unknown/screen'))).toBeUndefined(); + it('opens any other in-app path the way a Universal Link would', () => { + // An admin can point an automated nudge at a screen this map does not + // list; it opens without an app release, keeping its own params but not + // the campaign's. + expect(routeForLink(link('/coins'))).toEqual('/coins'); + expect(routeForLink(link('/deposit?method=bank&utm_source=deposit_sepa'))).toEqual({ + pathname: '/deposit', + params: { method: 'bank' }, + }); + }); + + it('refuses the screens a push must never open by path', () => { + expect(routeForLink(link('/settings/delete-account'))).toBeUndefined(); + expect(routeForLink(link('/signup'))).toBeUndefined(); + expect(routeForLink(link('/recovery'))).toBeUndefined(); + expect(routeForLink(link('/card/3ds/abc'))).toBeUndefined(); + }); + + it('returns nothing for a link it cannot read, rather than guessing', () => { + expect(routeForLink(link('/a b'))).toBeUndefined(); expect(routeForLink('not a url')).toBeUndefined(); expect(routeForLink(undefined)).toBeUndefined(); }); @@ -410,6 +429,31 @@ describe('handleNotificationResponse', () => { expect(navigate).toHaveBeenCalledWith(path.CARD_INFO); }); + it('records the automated nudge and version the push came from', () => { + handleNotificationResponse( + iosResponseFor('n-nudge', { + type: 'no-deposit-reminder', + stage: '1', + nudge_key: 'no-deposit-reminder-1', + nudge_version: '3', + utm_source: 'reminder_1', + utm_medium: 'push', + utm_campaign: 'solid_engagement', + link: link('/?utm_source=reminder_1'), + }), + jest.fn(), + ); + + expect(track).toHaveBeenCalledWith( + TRACKING_EVENTS.PUSH_NOTIFICATION_OPENED, + expect.objectContaining({ + notification_type: 'no-deposit-reminder', + nudge_key: 'no-deposit-reminder-1', + nudge_version: '3', + }), + ); + }); + it('records the open with its type and campaign', () => { handleNotificationResponse( iosResponseFor('n1', { diff --git a/hooks/usePushNotifications.ts b/hooks/usePushNotifications.ts index 9932285c9..98cf01996 100644 --- a/hooks/usePushNotifications.ts +++ b/hooks/usePushNotifications.ts @@ -11,7 +11,10 @@ import { TRACKING_EVENTS } from '@/constants/tracking-events'; import { track } from '@/lib/analytics'; import { registerPushToken } from '@/lib/api'; import { pushNotificationData } from '@/lib/pushNotificationData'; -import { registerForPushNotificationsAsync } from '@/lib/registerForPushNotifications'; +import { + pushDeviceInfo, + registerForPushNotificationsAsync, +} from '@/lib/registerForPushNotifications'; import { SUPPORT_PUSH_TYPE } from '@/lib/support/focus'; import { VaultType } from '@/lib/types'; import { useAttributionStore } from '@/store/useAttributionStore'; @@ -78,6 +81,13 @@ type NotificationData = { * pushes, whose destination is one transaction and cannot be a static URL. */ link?: string; + /** + * The automated nudge the push belongs to (Growth → Automated nudges) and + * the version of it that was sent, so an open can be credited to the exact + * copy an admin saved. + */ + nudge_key?: string; + nudge_version?: string; }; /** @@ -117,6 +127,52 @@ const ROUTE_BY_LINK_PATH: Record = { /** Vaults `/savings?vault=` may open: the savings screen's own selector values. */ const LINKABLE_VAULTS: readonly string[] = Object.values(VaultType); +/** + * Screens a push link never opens by path, even though the router knows them: + * signup, recovery and onboarding (a signed-in user has no business there), + * the permission and scanner screens, and settings, where a mistyped link must + * not land someone on account deletion. A path here falls back to `type`. + */ +const PUSH_LINK_DENIED_PREFIXES: readonly string[] = [ + '/signup', + '/onboarding', + '/welcome', + '/recovery', + '/passkey-not-supported', + '/notifications', + '/rescue-token', + '/qr-scanner', + '/extensions', + '/settings', + '/agent', + '/card/3ds', +]; + +/** A plain in-app path: segments of letters, digits and `-._~`, no `//`. */ +const PUSH_LINK_PATH = /^\/(?:[A-Za-z0-9\-._~]+\/?)*$/; + +/** A query param an in-app route may read; campaign params stay with attribution. */ +const PUSH_LINK_PARAM = /^[A-Za-z][A-Za-z0-9_]{0,39}$/; + +/** + * Any other in-app path, the way a Universal Link would open it + * (`redirectSystemPath`), so a nudge an admin points at a new screen opens it + * without an app release. Only plain paths outside the denied ones, and only + * short non-campaign params ride along. + */ +function anyInAppRoute(url: URL, pathname: string): Href | undefined { + if (!PUSH_LINK_PATH.test(pathname)) return undefined; + if (PUSH_LINK_DENIED_PREFIXES.some(p => pathname === p || pathname.startsWith(`${p}/`))) { + return undefined; + } + const params: Record = {}; + url.searchParams.forEach((value, key) => { + if (key.startsWith('utm_') || !PUSH_LINK_PARAM.test(key) || value.length > 200) return; + params[key] = value; + }); + return (Object.keys(params).length > 0 ? { pathname, params } : pathname) as Href; +} + /** `/rewards/ai-api?key=`: a key id, which is a 24-hex Mongo id. */ const LINKABLE_AI_API_KEY = /^[a-f0-9]{24}$/i; @@ -193,7 +249,7 @@ function routeForLink(link?: string): Href | undefined { if (action) return { pathname: '/', params: homeLinkParamsFor(action) } as Href; } - return ROUTE_BY_LINK_PATH[pathname]; + return ROUTE_BY_LINK_PATH[pathname] ?? anyInAppRoute(url, pathname); } catch { return undefined; } @@ -309,12 +365,16 @@ function recordOpen(data?: NotificationData) { const { utm_source, utm_medium, utm_campaign, type } = data ?? {}; if (utm_source || utm_campaign) { - useAttributionStore.getState().updateAttribution({ + const attribution = useAttributionStore.getState(); + attribution.updateAttribution({ utm_source, utm_medium, utm_campaign, attribution_captured_at: Date.now(), }); + // The push is the newest touch: `last_touch_utm_*` on later events + // should name it, not whatever link the user came through before. + attribution.saveLastTouchAttribution({ utm_source, utm_medium, utm_campaign }); } track(TRACKING_EVENTS.PUSH_NOTIFICATION_OPENED, { @@ -326,6 +386,9 @@ function recordOpen(data?: NotificationData) { // means either a spend push (which never has one) or a notification sent // before links existed, and both route on `type` instead. push_link: data?.link, + // The automated nudge and the saved version of it that was sent. + ...(data?.nudge_key && { nudge_key: data.nudge_key }), + ...(data?.nudge_version && { nudge_version: data.nudge_version }), // Card spend only: which outcome, and for a decline why and the fix the push // led with — what turns "opened a decline push" into "opened, then fixed it". ...(data?.status && { status: data.status }), @@ -469,7 +532,7 @@ export function usePushNotifications() { // Re-register token whenever FCM refreshes it (e.g., app reinstall, token expiry) const unsubscribeTokenRefresh = messaging().onTokenRefresh(async (newToken: string) => { try { - await registerPushToken(newToken, Platform.OS as 'ios' | 'android'); + await registerPushToken(newToken, Platform.OS as 'ios' | 'android', pushDeviceInfo()); } catch (error) { console.warn('Failed to register refreshed push token:', error); } diff --git a/lib/api.ts b/lib/api.ts index d2eccb307..03f703023 100644 --- a/lib/api.ts +++ b/lib/api.ts @@ -5933,7 +5933,16 @@ export const ensureWebhookSubscription = async (): Promise { +/** + * Register this device's push token. `timezone` (the device's IANA zone) lets + * marketing nudges wait out the user's quiet hours; `appVersion` lets the + * backend tell which builds a token belongs to. Older backends ignore both. + */ +export const registerPushToken = async ( + token: string, + platform: string, + device: { timezone?: string; appVersion?: string } = {}, +) => { const jwt = getJWTToken(); const response = await fetch(`${EXPO_PUBLIC_FLASH_API_BASE_URL}/accounts/v1/users/push-token`, { method: 'POST', @@ -5943,7 +5952,7 @@ export const registerPushToken = async (token: string, platform: string) => { ...(jwt ? { Authorization: `Bearer ${jwt}` } : {}), }, credentials: 'include', - body: JSON.stringify({ token, platform }), + body: JSON.stringify({ token, platform, ...device }), }); if (!response.ok) throw response; return response.json(); diff --git a/lib/attribution.ts b/lib/attribution.ts index 1ad6b003c..489d2a165 100644 --- a/lib/attribution.ts +++ b/lib/attribution.ts @@ -283,6 +283,7 @@ export type AttributionChannel = | 'paid_social' | 'social' | 'email' + | 'push' | 'referral' | 'direct' | 'other'; @@ -318,6 +319,8 @@ export const getAttributionChannel = (data: Partial): Attributi if (medium.includes('social') || medium.includes('organic_social')) return 'social'; if (medium.includes('email')) return 'email'; + // Our own pushes stamp utm_medium=push (backend push-attribution.constants). + if (medium === 'push') return 'push'; if (medium.includes('organic')) return 'organic'; } diff --git a/lib/registerForPushNotifications.ts b/lib/registerForPushNotifications.ts index 9bdf05075..044ba4948 100644 --- a/lib/registerForPushNotifications.ts +++ b/lib/registerForPushNotifications.ts @@ -1,10 +1,32 @@ import { Platform } from 'react-native'; +import * as Application from 'expo-application'; import * as Device from 'expo-device'; import * as Notifications from 'expo-notifications'; import messaging from '@react-native-firebase/messaging'; import { registerPushToken } from '@/lib/api'; +/** The device's IANA time zone, e.g. "Europe/Lisbon", when the runtime knows it. */ +function deviceTimezone(): string | undefined { + try { + const zone = Intl.DateTimeFormat().resolvedOptions().timeZone; + return zone && /^[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)*$/.test(zone) ? zone : undefined; + } catch { + return undefined; + } +} + +/** + * What the backend stores with a push token: the device's time zone (marketing + * nudges wait out quiet hours in it) and the app build. + */ +export function pushDeviceInfo(): { timezone?: string; appVersion?: string } { + return { + timezone: deviceTimezone(), + appVersion: Application.nativeApplicationVersion ?? undefined, + }; +} + interface RegisterForPushNotificationsOptions { /** Whether an undetermined/denied permission should trigger the system prompt. */ requestPermission?: boolean; @@ -45,7 +67,7 @@ export async function registerForPushNotificationsAsync({ // Persist token to backend (best-effort — don't block on failure) const platform = Platform.OS as 'ios' | 'android'; - await registerPushToken(fcmToken, platform); + await registerPushToken(fcmToken, platform, pushDeviceInfo()); return fcmToken; } catch (e: unknown) {