diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d1a292940ae..b4585105870 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -373,6 +373,7 @@ jobs: --sql-check supabase/tests/storefront_order_claim_loop_ordering.sql --sql-check supabase/tests/mcp_search_option_windows.sql --sql-check supabase/tests/mcp_search_option_windows_guard.sql --sql-check supabase/migrations/tests/connector_owner_creation_limit.sql + --sql-check supabase/migrations/tests/piggyvest_transfer_outbox_claims_authorization_index.sql - name: Run migration replay regression test run: pnpm --filter @baci/web exec vitest run src/lib/agentic/order-private-schema-usage-migration.test.ts - name: Test Cache Invalidation Outbox SQL diff --git a/apps/mobile-storefront/components/ui/use-address-prediction-select.test.ts b/apps/mobile-storefront/components/ui/use-address-prediction-select.test.ts new file mode 100644 index 00000000000..4cb93a0755a --- /dev/null +++ b/apps/mobile-storefront/components/ui/use-address-prediction-select.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it, jest } from '@jest/globals'; +import { act, renderHook } from '@testing-library/react-native'; +import type { MutableRefObject } from 'react'; +import type { PlacePrediction } from './AddressAutocomplete.types'; + +const mockFetchPlaceDetails = jest.fn<() => Promise<{ ok: true }>>(); +const mockApplyPlaceSelection = jest.fn<() => void>(); + +jest.mock('./AddressAutocomplete.api', () => ({ + fetchPlaceDetails: mockFetchPlaceDetails, +})); +jest.mock('./apply-place-selection', () => ({ + applyPlaceSelection: mockApplyPlaceSelection, +})); + +// Deferred require: the mocks above must initialize before the hook module +// loads, otherwise the mock factories capture uninitialized bindings. +const { usePredictionSelectHandler } = + require('./use-address-prediction-select') as typeof import('./use-address-prediction-select'); + +function setup() { + const isMountedRef = { current: true } as MutableRefObject; + const latestQueryRef = { current: '' } as MutableRefObject; + return { + isMountedRef, + latestQueryRef, + onChangeText: jest.fn(), + onSelect: jest.fn(), + setInternalValue: jest.fn(), + setIsLoading: jest.fn(), + setPredictions: jest.fn(), + setSessionToken: jest.fn(), + }; +} + +const prediction = { + mainText: '221B Baker Street', + placeId: 'place-1', + secondaryText: 'London', +} as PlacePrediction; + +describe('usePredictionSelectHandler identity', () => { + it('keeps a stable handler across unrelated re-renders', () => { + const deps = setup(); + const { result, rerender } = renderHook( + ({ sessionToken }: { sessionToken: string }) => + usePredictionSelectHandler({ ...deps, sessionToken }), + { initialProps: { sessionToken: 'session-a' } } + ); + const first = result.current; + + // Unrelated re-render (new props object, same values): the + // suggestions-portal effect depends on this identity, so it must not + // tear down and restart portal tracking. + rerender({ sessionToken: 'session-a' }); + + expect(result.current).toBe(first); + }); + + it('keeps the same handler when the session token changes', () => { + const deps = setup(); + const { result, rerender } = renderHook( + ({ sessionToken }: { sessionToken: string }) => + usePredictionSelectHandler({ ...deps, sessionToken }), + { initialProps: { sessionToken: 'session-a' } } + ); + const first = result.current; + + rerender({ sessionToken: 'session-b' }); + + expect(result.current).toBe(first); + }); + + it('invokes the latest session token after a token change', async () => { + mockFetchPlaceDetails.mockResolvedValue({ ok: true }); + const deps = setup(); + const { result, rerender } = renderHook( + ({ sessionToken }: { sessionToken: string }) => + usePredictionSelectHandler({ ...deps, sessionToken }), + { initialProps: { sessionToken: 'session-a' } } + ); + + rerender({ sessionToken: 'session-b' }); + + await act(async () => { + await result.current(prediction); + }); + + expect(mockFetchPlaceDetails).toHaveBeenCalledWith({ + prediction, + sessionToken: 'session-b', + }); + expect(mockApplyPlaceSelection).toHaveBeenCalledWith( + expect.objectContaining({ details: { ok: true } }) + ); + }); +}); diff --git a/apps/mobile-storefront/components/ui/use-address-prediction-select.ts b/apps/mobile-storefront/components/ui/use-address-prediction-select.ts index ab2d5d08bd3..1da43abe4a7 100644 --- a/apps/mobile-storefront/components/ui/use-address-prediction-select.ts +++ b/apps/mobile-storefront/components/ui/use-address-prediction-select.ts @@ -1,4 +1,4 @@ -import { type MutableRefObject, useCallback } from 'react'; +import { type MutableRefObject, useLayoutEffect, useRef } from 'react'; import { Keyboard } from 'react-native'; import { fetchPlaceDetails } from './AddressAutocomplete.api'; import type { @@ -20,9 +20,12 @@ type PredictionSelectDeps = { }; /** - * Stable prediction-select handler: the suggestions-portal effect depends - * on its identity, so an inline closure would re-run the portal on every - * render. + * Prediction-select handler: the suggestions-portal effect depends on its + * identity. Stable by construction through a latest-values ref (same + * pattern as use-savings-first-card-checkout): no manual useCallback + * (prohibited in this repo) and no dependence on React Compiler + * memoization, which is a performance optimization rather than a + * semantic guarantee for this effect dependency. */ export function usePredictionSelectHandler({ isMountedRef, @@ -35,30 +38,23 @@ export function usePredictionSelectHandler({ setPredictions, setSessionToken, }: PredictionSelectDeps) { - return useCallback( - async (prediction: PlacePrediction) => { - Keyboard.dismiss(); - latestQueryRef.current = prediction.mainText; - setInternalValue(prediction.mainText); - onChangeText?.(prediction.mainText); - setPredictions([]); - if (isMountedRef.current) { - setIsLoading(true); - } - - const details = await fetchPlaceDetails({ prediction, sessionToken }); - applyPlaceSelection({ - details, - isMountedRef, - onSelect, - setIsLoading, - setPredictions, - setSessionToken, - }); - }, - // Refs and state setters are stable at the call site, so only the - // callbacks and session token can retrigger this handler. - [ + const latestRef = useRef({ + isMountedRef, + latestQueryRef, + onChangeText, + onSelect, + sessionToken, + setInternalValue, + setIsLoading, + setPredictions, + setSessionToken, + }); + // Post-commit sync only: writing ref.current during render risks an + // abandoned concurrent render leaving uncommitted values behind for the + // stable handler to read at tap time. Layout effects flush before paint, + // so no user event can observe a stale snapshot. + useLayoutEffect(() => { + latestRef.current = { isMountedRef, latestQueryRef, onChangeText, @@ -68,6 +64,36 @@ export function usePredictionSelectHandler({ setIsLoading, setPredictions, setSessionToken, - ] - ); + }; + }); + const stableRef = useRef< + ((prediction: PlacePrediction) => Promise) | null + >(null); + if (stableRef.current === null) { + stableRef.current = async (prediction: PlacePrediction) => { + const latest = latestRef.current; + Keyboard.dismiss(); + latest.latestQueryRef.current = prediction.mainText; + latest.setInternalValue(prediction.mainText); + latest.onChangeText?.(prediction.mainText); + latest.setPredictions([]); + if (latest.isMountedRef.current) { + latest.setIsLoading(true); + } + + const details = await fetchPlaceDetails({ + prediction, + sessionToken: latest.sessionToken, + }); + applyPlaceSelection({ + details, + isMountedRef: latest.isMountedRef, + onSelect: latest.onSelect, + setIsLoading: latest.setIsLoading, + setPredictions: latest.setPredictions, + setSessionToken: latest.setSessionToken, + }); + }; + } + return stableRef.current; } diff --git a/apps/mobile-storefront/hooks/use-savings-notification-inbox.delivery.test.ts b/apps/mobile-storefront/hooks/use-savings-notification-inbox.delivery.test.ts new file mode 100644 index 00000000000..3fe5dd13e13 --- /dev/null +++ b/apps/mobile-storefront/hooks/use-savings-notification-inbox.delivery.test.ts @@ -0,0 +1,241 @@ +import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import { act, renderHook, waitFor } from '@testing-library/react-native'; + +type Inbox = Awaited< + ReturnType< + typeof import('@/services/savings-notification-inbox')['fetchSavingsNotificationInbox'] + > +>; +const mockFetchInbox = jest.fn<() => Promise>(); +const mockMarkAvailable = + jest.fn< + (scope: { + apiOrigin: string; + merchantId: string; + userId: string; + }) => Promise + >(); +const mockClearAvailable = + jest.fn< + (scope: { + apiOrigin: string; + merchantId: string; + userId: string; + }) => Promise + >(); +const mockSuppressSavingsReminderNotification = + jest.fn<() => Promise>(); +const mockGetRegisteredPushToken = + jest.fn<(userId: string, merchantId: string) => Promise>(); + +jest.mock('@/services/savings-notification-inbox', () => ({ + fetchSavingsNotificationInbox: mockFetchInbox, + markSavingsNotificationRead: jest.fn(), + updateSavingsNotificationPreferences: jest.fn(), +})); +jest.mock('@/services/savings-notification-capability', () => ({ + savingsNotificationCapability: { + clearAvailable: mockClearAvailable, + markAvailable: mockMarkAvailable, + }, +})); +jest.mock('@/env', () => ({ EXPO_PUBLIC_API_URL: 'https://api.baci.test' })); +jest.mock('@/services/savings-reminder-notifications', () => ({ + suppressSavingsReminderNotification: mockSuppressSavingsReminderNotification, +})); +jest.mock('@/lib/push-token-storage', () => ({ + getRegisteredPushToken: mockGetRegisteredPushToken, +})); +const mockAuthState: { + merchantId: string | null; + user: { id: string } | null; +} = { + merchantId: '00000000-0000-4000-8000-000000000010', + user: { id: 'user-a' }, +}; +jest.mock('@/stores/auth-store', () => ({ + useAuthStore: { getState: () => mockAuthState }, +})); + +const { useSavingsNotificationInbox } = + require('./use-savings-notification-inbox') as typeof import('./use-savings-notification-inbox'); + +const merchantId = '00000000-0000-4000-8000-000000000010'; +const notificationId = '00000000-0000-4000-8000-000000000001'; +const goalId = '00000000-0000-4000-8000-000000000002'; +const preferences = { + encouragementEnabled: true, + interestAlertsEnabled: true, + quietHoursEnd: '08:00', + quietHoursStart: '22:00', + timeZone: 'Africa/Lagos', + weeklySummaryEnabled: false, +}; + +const inbox = { + deliveryEnabled: true, + notifications: [ + { + body: 'Your savings interest has been credited.', + createdAt: '2026-09-25T10:00:00.000Z', + goalId, + id: notificationId, + readAt: null, + title: 'Interest credited', + type: 'savings_interest_credited', + }, + ], + preferences, +}; + +describe('useSavingsNotificationInbox server-delivery suppression', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockAuthState.merchantId = '00000000-0000-4000-8000-000000000010'; + mockAuthState.user = { id: 'user-a' }; + mockFetchInbox.mockResolvedValue(inbox); + mockMarkAvailable.mockResolvedValue(); + mockClearAvailable.mockResolvedValue(); + mockSuppressSavingsReminderNotification.mockResolvedValue(false); + mockGetRegisteredPushToken.mockResolvedValue('ExponentPushToken[ok]'); + }); + + it('preserves local reminders when a successful inbox says delivery is disabled', async () => { + mockFetchInbox.mockResolvedValueOnce({ ...inbox, deliveryEnabled: false }); + const { result } = renderHook(() => + useSavingsNotificationInbox({ + enabled: true, + merchantId, + userId: 'user-a', + }) + ); + + await waitFor(() => expect(result.current.notifications).toHaveLength(1)); + + expect(mockMarkAvailable).not.toHaveBeenCalled(); + expect(mockSuppressSavingsReminderNotification).not.toHaveBeenCalled(); + expect(mockClearAvailable).toHaveBeenCalledWith({ + apiOrigin: 'https://api.baci.test', + merchantId, + userId: 'user-a', + }); + }); + + it('keeps local reminders when delivery is enabled but this device never registered', async () => { + mockGetRegisteredPushToken.mockResolvedValue(null); + const { result } = renderHook(() => + useSavingsNotificationInbox({ + enabled: true, + merchantId, + userId: 'user-a', + }) + ); + + await waitFor(() => expect(result.current.notifications).toHaveLength(1)); + await waitFor(() => + expect(mockGetRegisteredPushToken).toHaveBeenCalledWith( + 'user-a', + merchantId + ) + ); + + expect(mockMarkAvailable).not.toHaveBeenCalled(); + expect(mockSuppressSavingsReminderNotification).not.toHaveBeenCalled(); + expect(mockClearAvailable).toHaveBeenCalledWith({ + apiOrigin: 'https://api.baci.test', + merchantId, + userId: 'user-a', + }); + }); + + it('skips clearing local reminders when the account changes while markAvailable is in flight', async () => { + let resolveFirstMark!: () => void; + const firstMark = new Promise((resolve) => { + resolveFirstMark = resolve; + }); + mockMarkAvailable + .mockImplementationOnce(() => firstMark) + .mockImplementation(() => new Promise(() => {})); + const { rerender } = renderHook( + ({ activeUserId }: { activeUserId: string }) => + useSavingsNotificationInbox({ + enabled: true, + merchantId, + userId: activeUserId, + }), + { initialProps: { activeUserId: 'user-a' } } + ); + await waitFor(() => + expect(mockMarkAvailable).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'user-a' }) + ) + ); + + rerender({ activeUserId: 'user-b' }); + await waitFor(() => + expect(mockMarkAvailable).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'user-b' }) + ) + ); + + await act(async () => { + resolveFirstMark(); + await firstMark; + }); + + expect(mockSuppressSavingsReminderNotification).not.toHaveBeenCalled(); + }); + + it('suppresses local reminders with the captured scope once server delivery is confirmed', async () => { + const { result } = renderHook(() => + useSavingsNotificationInbox({ + enabled: true, + merchantId, + userId: 'user-a', + }) + ); + + await waitFor(() => expect(result.current.notifications).toHaveLength(1)); + await waitFor(() => + expect(mockSuppressSavingsReminderNotification).toHaveBeenCalledWith({ + merchantId, + userId: 'user-a', + }) + ); + + expect(mockMarkAvailable).toHaveBeenCalledWith({ + apiOrigin: 'https://api.baci.test', + merchantId, + userId: 'user-a', + }); + }); + + it('skips suppression when inbox props disagree with the auth store', async () => { + // Stale props during an account switch: the hook still renders user-a + // while the store already moved to user-b. + mockAuthState.user = { id: 'user-b' }; + const { result } = renderHook(() => + useSavingsNotificationInbox({ + enabled: true, + merchantId, + userId: 'user-a', + }) + ); + + await waitFor(() => expect(result.current.notifications).toHaveLength(1)); + await waitFor(() => + expect(mockMarkAvailable).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'user-a' }) + ) + ); + // Flush the markAvailable continuation, then assert it skipped the + // mistargeted suppression (clearAvailable also untouched: the registered + // device path was taken, not the fallback branch). + await act(async () => { + await Promise.resolve(); + await Promise.resolve(); + }); + expect(mockSuppressSavingsReminderNotification).not.toHaveBeenCalled(); + expect(mockClearAvailable).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/mobile-storefront/hooks/use-savings-notification-inbox.test.ts b/apps/mobile-storefront/hooks/use-savings-notification-inbox.test.ts index 7a88244da9d..9a50327ed36 100644 --- a/apps/mobile-storefront/hooks/use-savings-notification-inbox.test.ts +++ b/apps/mobile-storefront/hooks/use-savings-notification-inbox.test.ts @@ -25,7 +25,8 @@ const mockClearAvailable = userId: string; }) => Promise >(); -const mockCancelSavingsReminderNotification = jest.fn<() => Promise>(); +const mockSuppressSavingsReminderNotification = + jest.fn<() => Promise>(); const mockGetRegisteredPushToken = jest.fn<(userId: string, merchantId: string) => Promise>(); @@ -42,7 +43,7 @@ jest.mock('@/services/savings-notification-capability', () => ({ })); jest.mock('@/env', () => ({ EXPO_PUBLIC_API_URL: 'https://api.baci.test' })); jest.mock('@/services/savings-reminder-notifications', () => ({ - cancelSavingsReminderNotification: mockCancelSavingsReminderNotification, + suppressSavingsReminderNotification: mockSuppressSavingsReminderNotification, })); jest.mock('@/lib/push-token-storage', () => ({ getRegisteredPushToken: mockGetRegisteredPushToken, @@ -87,7 +88,7 @@ describe('useSavingsNotificationInbox', () => { mockUpdatePreferences.mockResolvedValue({ success: true }); mockMarkAvailable.mockResolvedValue(); mockClearAvailable.mockResolvedValue(); - mockCancelSavingsReminderNotification.mockResolvedValue(false); + mockSuppressSavingsReminderNotification.mockResolvedValue(false); mockGetRegisteredPushToken.mockResolvedValue('ExponentPushToken[ok]'); }); @@ -180,54 +181,6 @@ describe('useSavingsNotificationInbox', () => { expect(mockMarkAvailable).toHaveBeenCalledTimes(1); }); - it('preserves local reminders when a successful inbox says delivery is disabled', async () => { - mockFetchInbox.mockResolvedValueOnce({ ...inbox, deliveryEnabled: false }); - const { result } = renderHook(() => - useSavingsNotificationInbox({ - enabled: true, - merchantId, - userId: 'user-a', - }) - ); - - await waitFor(() => expect(result.current.notifications).toHaveLength(1)); - - expect(mockMarkAvailable).not.toHaveBeenCalled(); - expect(mockCancelSavingsReminderNotification).not.toHaveBeenCalled(); - expect(mockClearAvailable).toHaveBeenCalledWith({ - apiOrigin: 'https://api.baci.test', - merchantId, - userId: 'user-a', - }); - }); - - it('keeps local reminders when delivery is enabled but this device never registered', async () => { - mockGetRegisteredPushToken.mockResolvedValue(null); - const { result } = renderHook(() => - useSavingsNotificationInbox({ - enabled: true, - merchantId, - userId: 'user-a', - }) - ); - - await waitFor(() => expect(result.current.notifications).toHaveLength(1)); - await waitFor(() => - expect(mockGetRegisteredPushToken).toHaveBeenCalledWith( - 'user-a', - merchantId - ) - ); - - expect(mockMarkAvailable).not.toHaveBeenCalled(); - expect(mockCancelSavingsReminderNotification).not.toHaveBeenCalled(); - expect(mockClearAvailable).toHaveBeenCalledWith({ - apiOrigin: 'https://api.baci.test', - merchantId, - userId: 'user-a', - }); - }); - it('hides the previous account inbox immediately when the account changes', async () => { const accountBInbox = { ...inbox, @@ -262,42 +215,4 @@ describe('useSavingsNotificationInbox', () => { ) ); }); - - it('skips clearing local reminders when the account changes while markAvailable is in flight', async () => { - let resolveFirstMark!: () => void; - const firstMark = new Promise((resolve) => { - resolveFirstMark = resolve; - }); - mockMarkAvailable - .mockImplementationOnce(() => firstMark) - .mockImplementation(() => new Promise(() => {})); - const { rerender } = renderHook( - ({ activeUserId }: { activeUserId: string }) => - useSavingsNotificationInbox({ - enabled: true, - merchantId, - userId: activeUserId, - }), - { initialProps: { activeUserId: 'user-a' } } - ); - await waitFor(() => - expect(mockMarkAvailable).toHaveBeenCalledWith( - expect.objectContaining({ userId: 'user-a' }) - ) - ); - - rerender({ activeUserId: 'user-b' }); - await waitFor(() => - expect(mockMarkAvailable).toHaveBeenCalledWith( - expect.objectContaining({ userId: 'user-b' }) - ) - ); - - await act(async () => { - resolveFirstMark(); - await firstMark; - }); - - expect(mockCancelSavingsReminderNotification).not.toHaveBeenCalled(); - }); }); diff --git a/apps/mobile-storefront/hooks/use-savings-notification-inbox.ts b/apps/mobile-storefront/hooks/use-savings-notification-inbox.ts index ef1e47be020..d3f53ae50bf 100644 --- a/apps/mobile-storefront/hooks/use-savings-notification-inbox.ts +++ b/apps/mobile-storefront/hooks/use-savings-notification-inbox.ts @@ -1,5 +1,8 @@ import { useEffect, useRef, useState } from 'react'; import { EXPO_PUBLIC_API_URL } from '@/env'; +import { CONFIG } from '@/lib/config'; +import { createLogger } from '@/lib/logger'; +import { pickMerchantId } from '@/lib/pick-merchant-id'; import { getRegisteredPushToken } from '@/lib/push-token-storage'; import type { SavingsNotification, @@ -13,7 +16,10 @@ import { markSavingsNotificationRead, updateSavingsNotificationPreferences, } from '@/services/savings-notification-inbox'; -import { cancelSavingsReminderNotification } from '@/services/savings-reminder-notifications'; +import { suppressSavingsReminderNotification } from '@/services/savings-reminder-notifications'; +import { useAuthStore } from '@/stores/auth-store'; + +const log = createLogger('SavingsNotificationInbox'); type InboxState = { error: string | null; @@ -108,7 +114,7 @@ export function useSavingsNotificationInbox({ }; // deliveryEnabled is server-global; this device may still have no // confirmed token (e.g. the token RPC failed). Only switch to - // server delivery — and cancel the local reminder — after this + // server delivery — and suppress the local reminder — after this // user/device registration is confirmed, else the customer gets // neither local nor remote reminders. void (async () => { @@ -123,11 +129,33 @@ export function useSavingsNotificationInbox({ .markAvailable(capabilityScope) .then(() => { // The account may have switched during the markAvailable - // await: cancel resolves its scope fresh, so recheck before - // clearing — otherwise this continuation would wipe the new - // account's local reminders before it has server delivery. + // await, so recheck before clearing — otherwise this + // continuation would wipe the new account's local reminders + // before it has server delivery. Suppress (not cancel) with + // the captured scope: the retained pending requests let + // local reminders re-arm if server delivery is later lost. if (!active || scopeRef.current !== scope) return; - return cancelSavingsReminderNotification(); + // Props/store agreement: suppression targets the captured + // props scope, but schedule/activate resolve from the auth + // store. On divergence (stale props mid-switch) skip rather + // than mistarget — a no-op suppression would leave duplicate + // local plus server reminders. + const { merchantId: storeMerchantId, user: storeUser } = + useAuthStore.getState(); + if ( + storeUser?.id !== activeUserId || + pickMerchantId(storeMerchantId, CONFIG.MERCHANT_ID) !== + activeMerchantId + ) { + log.debug( + 'Skipping savings reminder suppression: inbox props disagree with auth store' + ); + return; + } + return suppressSavingsReminderNotification({ + merchantId: activeMerchantId, + userId: activeUserId, + }); }) .catch(() => undefined); } else { diff --git a/apps/mobile-storefront/services/savings-reminder-activation.ts b/apps/mobile-storefront/services/savings-reminder-activation.ts new file mode 100644 index 00000000000..de75fee1f7c --- /dev/null +++ b/apps/mobile-storefront/services/savings-reminder-activation.ts @@ -0,0 +1,157 @@ +import { EXPO_PUBLIC_API_URL } from '@/env'; +import { CONFIG } from '@/lib/config'; +import { listSavingsGoals } from '@/lib/customer-savings'; +import { createLogger } from '@/lib/logger'; +import { pickMerchantId } from '@/lib/pick-merchant-id'; +import { savingsNotificationCapability } from '@/services/savings-notification-capability'; +import { useAuthStore } from '@/stores/auth-store'; +import { retireTerminalGoalReminders } from './savings-reminder-goal-reconciliation'; +import { + ensureSavingsReminderChannel, + hasSavingsReminderPermission, + loadNotificationsModule, +} from './savings-reminder-native'; +import { + disposeUnscopedSavingsReminders, + scheduleRecurringSavingsReminder, + suppressStoredSavingsReminderNotification, +} from './savings-reminder-scheduling'; +import { + type SavingsReminderScope, + savingsReminderStorage, +} from './savings-reminder-storage'; + +const log = createLogger('SavingsReminderActivation'); + +function resolveReminderScope(): SavingsReminderScope | null { + const { merchantId, user } = useAuthStore.getState(); + // Lazy require: a static import would cycle (the notifications module + // re-exports activation), so resolve through the single canonical helper + // at call time instead of duplicating its fallback logic. + const { buildReminderScope } = + require('./savings-reminder-notifications') as typeof import('./savings-reminder-notifications'); + return buildReminderScope(user?.id, merchantId); +} + +function hasServerSavingsNotificationCapability() { + const { merchantId, user } = useAuthStore.getState(); + const resolvedMerchantId = pickMerchantId(merchantId, CONFIG.MERCHANT_ID); + if (!resolvedMerchantId || !user?.id) return Promise.resolve(false); + return savingsNotificationCapability.isAvailable({ + apiOrigin: EXPO_PUBLIC_API_URL, + merchantId: resolvedMerchantId, + userId: user.id, + }); +} + +/** + * Snapshots terminal goal IDs for reminder reconciliation. Runs outside the + * reminder mutex so a slow network never blocks scheduling and cancellation. + * Fail-safe: a failed lookup yields an empty set, keeping every record. + */ +async function fetchTerminalGoalIds( + scope: SavingsReminderScope +): Promise> { + try { + const { goals } = await listSavingsGoals({ + merchantId: scope.merchantId, + }); + return new Set( + goals + .filter( + (goal) => + goal.status === 'completed' || + goal.status === 'cancelled' || + goal.status === 'spent' + ) + .map((goal) => goal.id) + ); + } catch (error) { + log.debug('Unable to reconcile savings reminders with goal state', error); + return new Set(); + } +} + +export function activateDueSavingsReminderNotification() { + const scope = resolveReminderScope(); + if (!scope) return Promise.resolve(null); + return (async () => { + // Gate the fetch on stored records only: users with no local reminders + // skip the goals request entirely, but retirement must still run when + // arming is impossible (a revoked permission must not strand a live + // notification for a finished goal). Probe failure falls back to + // fetching; the activation fails downstream as before. + const probe = await savingsReminderStorage.read(scope).catch(() => null); + const terminalGoalIds = + probe === null || probe.length + ? await fetchTerminalGoalIds(scope) + : new Set(); + return savingsReminderStorage.runExclusive(() => + activateDueReminders(scope, terminalGoalIds) + ); + })(); +} + +async function activateDueReminders( + scope: SavingsReminderScope, + terminalGoalIds: ReadonlySet +) { + const notifications = loadNotificationsModule(); + await disposeUnscopedSavingsReminders(notifications); + // Abort on mid-fetch account change: the snapshot belongs to the old + // account, and the auth-change effect refires activation with a fresh + // snapshot for the new one. Continuing would arm unreconciled records. + const current = resolveReminderScope(); + if ( + !current || + current.userId !== scope.userId || + current.merchantId !== scope.merchantId + ) + return null; + const records = await savingsReminderStorage.read(current); + // Retire on every path (server-owned included): terminal goals must not + // accumulate, and this runs before the permission gates so revoked + // permission cannot strand a live notification for a finished goal. + const live = await retireTerminalGoalReminders( + notifications, + current, + records, + terminalGoalIds + ); + if (await hasServerSavingsNotificationCapability()) { + // Suppress, not cancel: the pending requests must survive so local + // reminders re-arm if server delivery is later lost. + await suppressStoredSavingsReminderNotification(notifications, current); + return null; + } + if (!live.length) return null; + // Retirement still runs before arming (never backgrounded): arming first + // would briefly give completed goals live notifications that an app kill + // could leave behind. + if (!notifications || !(await hasSavingsReminderPermission(notifications))) + return null; + await ensureSavingsReminderChannel(notifications); + // Records already converted to a live OS notification keep their retained + // pending request — only due requests without a live notification arm now. + const due = live.filter( + ({ notificationId, pending }) => + !notificationId && pending && pending.scheduledAt.getTime() <= Date.now() + ); + if (!due.length) return null; + let notificationId: string | null = null; + let failure: unknown; + for (const { pending } of due) { + if (!pending) continue; + try { + notificationId = await scheduleRecurringSavingsReminder({ + notifications, + request: pending, + scope: current, + }); + } catch (error) { + failure = error; + } + } + if (failure) throw failure; + return notificationId; +} diff --git a/apps/mobile-storefront/services/savings-reminder-goal-reconciliation.ts b/apps/mobile-storefront/services/savings-reminder-goal-reconciliation.ts new file mode 100644 index 00000000000..a0b79bb5f1e --- /dev/null +++ b/apps/mobile-storefront/services/savings-reminder-goal-reconciliation.ts @@ -0,0 +1,36 @@ +import { + cancelStoredSavingsReminderNotification, + type NotificationsModule, +} from './savings-reminder-scheduling'; +import type { + ReminderRecord, + SavingsReminderScope, +} from './savings-reminder-storage'; + +/** + * Destroys records whose goals reached a terminal state, cancelling their + * live OS notifications. Takes a pre-fetched snapshot: the goals lookup + * runs outside the reminder mutex (see activateDueSavingsReminderNotification) + * so a slow network never blocks scheduling and cancellation. Anything not + * in the terminal set is kept untouched. + */ +export async function retireTerminalGoalReminders( + notifications: NotificationsModule | null, + scope: SavingsReminderScope, + records: ReminderRecord[], + terminalGoalIds: ReadonlySet +): Promise { + const live: ReminderRecord[] = []; + for (const record of records) { + if (!terminalGoalIds.has(record.goalId)) { + live.push(record); + continue; + } + await cancelStoredSavingsReminderNotification( + notifications, + scope, + record.goalId + ); + } + return live; +} diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.activation.test.ts b/apps/mobile-storefront/services/savings-reminder-notifications.activation.test.ts new file mode 100644 index 00000000000..33885350e53 --- /dev/null +++ b/apps/mobile-storefront/services/savings-reminder-notifications.activation.test.ts @@ -0,0 +1,239 @@ +import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import AsyncStorage from '@react-native-async-storage/async-storage'; + +const mockCancelScheduledNotificationAsync = jest.fn(async () => undefined); +const mockGetPermissionsAsync = jest.fn(async () => ({ status: 'granted' })); +const mockRequestPermissionsAsync = jest.fn(async () => ({ + status: 'granted', +})); +const mockScheduleNotificationAsync = jest.fn(async () => 'notification-id'); +const mockSetNotificationChannelAsync = jest.fn(async () => undefined); + +jest.mock('react-native', () => ({ Platform: { OS: 'android' } })); +jest.mock('expo-notifications', () => ({ + AndroidImportance: { DEFAULT: 'default' }, + SchedulableTriggerInputTypes: { WEEKLY: 'weekly' }, + cancelScheduledNotificationAsync: mockCancelScheduledNotificationAsync, + getPermissionsAsync: mockGetPermissionsAsync, + requestPermissionsAsync: mockRequestPermissionsAsync, + scheduleNotificationAsync: mockScheduleNotificationAsync, + setNotificationChannelAsync: mockSetNotificationChannelAsync, +})); +jest.mock('@/lib/storage', () => { + const storage = require('@react-native-async-storage/async-storage'); + return { asyncStorage: storage.default ?? storage }; +}); +jest.mock('@/lib/logger', () => ({ + createLogger: () => ({ debug: jest.fn() }), +})); +jest.mock('@/env', () => ({ EXPO_PUBLIC_API_URL: 'https://api.baci.test' })); +jest.mock('@/lib/config', () => ({ + CONFIG: { MERCHANT_ID: '00000000-0000-4000-8000-000000000010' }, +})); +const mockAuthState: { + merchantId: string | null; + user: { id: string } | null; +} = { + merchantId: '00000000-0000-4000-8000-000000000010', + user: { id: 'user-a' }, +}; +jest.mock('@/stores/auth-store', () => ({ + useAuthStore: { getState: () => mockAuthState }, +})); +// Goal reconciliation is covered in the retention suite; here it resolves no +// goals so every record is kept (and the API-client graph stays unloaded). +jest.mock('@/lib/customer-savings', () => ({ + listSavingsGoals: jest.fn(async () => ({ + goals: [], + summary: { activeGoalCount: 0, savingsBalance: 0 }, + })), +})); + +const { + activateDueSavingsReminderNotification, + scheduleSavingsReminderNotification, + suppressSavingsReminderNotification, +} = + require('./savings-reminder-notifications') as typeof import('./savings-reminder-notifications'); +const { savingsNotificationCapability } = + require('./savings-notification-capability') as typeof import('./savings-notification-capability'); + +describe('savings reminder activation and server capability', () => { + beforeEach(async () => { + jest.clearAllMocks(); + mockGetPermissionsAsync.mockResolvedValue({ status: 'granted' }); + mockAuthState.merchantId = '00000000-0000-4000-8000-000000000010'; + mockAuthState.user = { id: 'user-a' }; + await AsyncStorage.clear(); + }); + + it('activates both pending goals on boot without replacing the first', async () => { + for (const goalId of ['goal-1', 'goal-2']) { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId, + goalTitle: 'Phone', + scheduledAt: new Date(2099, 0, 1), + }); + } + const now = jest + .spyOn(Date, 'now') + .mockReturnValue(new Date(2100, 0, 1).getTime()); + try { + await activateDueSavingsReminderNotification(); + expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(2); + expect(mockCancelScheduledNotificationAsync).not.toHaveBeenCalled(); + } finally { + now.mockRestore(); + } + }); + + it('retains pendings while cancelling live notifications for server-push', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }); + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-2', + goalTitle: 'Phone', + scheduledAt: new Date(2099, 0, 1), + }); + await savingsNotificationCapability.markAvailable({ + apiOrigin: 'https://api.baci.test', + merchantId: '00000000-0000-4000-8000-000000000010', + userId: 'user-a', + }); + await activateDueSavingsReminderNotification(); + // The live OS notification is cancelled, but both pendings survive so + // local reminders re-arm if server delivery is later lost. + expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledTimes(1); + expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); + expect( + (await AsyncStorage.getAllKeys()) + .filter((key) => key.startsWith('baci:savings-reminder-goal:')) + .sort() + ).toEqual([ + 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1', + 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-2', + ]); + await expect( + AsyncStorage.getItem( + 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1' + ) + ).resolves.toContain('Phone'); + }); + + it('serializes overlapping activations so each due goal is scheduled once', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + scheduledAt: new Date(2099, 0, 1), + }); + const now = jest + .spyOn(Date, 'now') + .mockReturnValue(new Date(2100, 0, 1).getTime()); + try { + await Promise.all([ + activateDueSavingsReminderNotification(), + activateDueSavingsReminderNotification(), + ]); + expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); + } finally { + now.mockRestore(); + } + }); + + it('keeps legacy local reminders active before the inbox capability is established', async () => { + await Promise.all([ + AsyncStorage.setItem( + 'baci:savings-reminder-notification-id', + 'legacy-reminder' + ), + AsyncStorage.setItem('baci:savings-reminder-goal-id', 'goal-1'), + ]); + + await expect( + scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }) + ).resolves.toBe('notification-id'); + + expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( + 'legacy-reminder' + ); + expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); + expect(mockGetPermissionsAsync).toHaveBeenCalledTimes(1); + }); + + it('retires stale device reminders only after an authenticated inbox capability success', async () => { + await Promise.all([ + AsyncStorage.setItem( + 'baci:savings-reminder-notification-id', + 'legacy-reminder' + ), + AsyncStorage.setItem('baci:savings-reminder-goal-id', 'goal-1'), + ]); + + await savingsNotificationCapability.markAvailable({ + apiOrigin: 'https://api.baci.test', + merchantId: '00000000-0000-4000-8000-000000000010', + userId: 'user-a', + }); + + expect(mockGetPermissionsAsync).not.toHaveBeenCalled(); + expect(mockRequestPermissionsAsync).not.toHaveBeenCalled(); + + await expect( + scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }) + ).resolves.toBeNull(); + expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( + 'legacy-reminder' + ); + expect(mockScheduleNotificationAsync).not.toHaveBeenCalled(); + }); + + it('suppresses live reminders while retaining pendings for a later rollback', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }); + expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); + + await expect(suppressSavingsReminderNotification()).resolves.toBe(true); + expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( + 'notification-id' + ); + const key = + 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1'; + const suppressed = JSON.parse( + (await AsyncStorage.getItem(key)) ?? '{}' + ) as Record; + expect(suppressed.notificationId).toBeUndefined(); + expect(suppressed.pending).toEqual( + expect.objectContaining({ goalId: 'goal-1' }) + ); + + // Rollback path: activation re-arms the retained pending request. + mockScheduleNotificationAsync.mockResolvedValueOnce('rearmed-id'); + await expect(activateDueSavingsReminderNotification()).resolves.toBe( + 'rearmed-id' + ); + }); +}); diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.retention-fetch.test.ts b/apps/mobile-storefront/services/savings-reminder-notifications.retention-fetch.test.ts new file mode 100644 index 00000000000..6a7afa3b0b9 --- /dev/null +++ b/apps/mobile-storefront/services/savings-reminder-notifications.retention-fetch.test.ts @@ -0,0 +1,186 @@ +import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import AsyncStorage from '@react-native-async-storage/async-storage'; +import type { PermissionStatus } from 'expo-notifications'; +import type { SavingsGoal } from '@/schemas/customer-savings'; + +type GoalsResponse = { + goals: SavingsGoal[]; + summary: { activeGoalCount: number; savingsBalance: number }; +}; + +const mockListSavingsGoals = jest.fn<() => Promise>(); + +jest.mock('react-native', () => ({ Platform: { OS: 'android' } })); +jest.mock('expo-notifications', () => ({ + AndroidImportance: { DEFAULT: 'default' }, + SchedulableTriggerInputTypes: { + DAILY: 'daily', + MONTHLY: 'monthly', + WEEKLY: 'weekly', + }, + cancelScheduledNotificationAsync: jest.fn(async () => undefined), + getPermissionsAsync: jest.fn(async () => ({ status: 'granted' })), + requestPermissionsAsync: jest.fn(async () => ({ status: 'granted' })), + scheduleNotificationAsync: jest.fn(async () => 'notification-id'), + setNotificationChannelAsync: jest.fn(async () => null), +})); +jest.mock('@/lib/storage', () => { + const storage = require('@react-native-async-storage/async-storage'); + return { asyncStorage: storage.default ?? storage }; +}); +jest.mock('@/lib/logger', () => ({ + createLogger: () => ({ debug: jest.fn() }), +})); +jest.mock('@/env', () => ({ EXPO_PUBLIC_API_URL: 'https://api.baci.test' })); +jest.mock('@/lib/config', () => ({ + CONFIG: { MERCHANT_ID: '00000000-0000-4000-8000-000000000010' }, +})); +const mockAuthState: { + merchantId: string | null; + user: { id: string } | null; +} = { + merchantId: '00000000-0000-4000-8000-000000000010', + user: { id: 'user-a' }, +}; +jest.mock('@/stores/auth-store', () => ({ + useAuthStore: { getState: () => mockAuthState }, +})); +jest.mock('@/lib/customer-savings', () => ({ + listSavingsGoals: mockListSavingsGoals, +})); + +const { + activateDueSavingsReminderNotification, + scheduleSavingsReminderNotification, + suppressSavingsReminderNotification, +} = + require('./savings-reminder-notifications') as typeof import('./savings-reminder-notifications'); +const mockNotifications = require('expo-notifications') as jest.Mocked< + typeof import('expo-notifications') +>; + +function goalFixture(id: string, status: SavingsGoal['status']): SavingsGoal { + return { + breakFeePercent: 0, + contributionAmount: 500, + contributionFrequency: 'weekly', + currentAmount: 100, + id, + maturityDate: '2026-12-31', + productId: 'product-1', + sourceMode: 'manual', + startDate: '2026-01-01', + status, + targetAmount: 1000, + title: 'Phone', + variantId: null, + }; +} + +function scheduledGoalIds(): Array { + return mockNotifications.scheduleNotificationAsync.mock.calls.map( + (call) => + (call[0] as { content: { data: { goalId?: string } } }).content.data + .goalId + ); +} + +describe('savings reminder fetch gating', () => { + beforeEach(async () => { + jest.clearAllMocks(); + mockAuthState.merchantId = '00000000-0000-4000-8000-000000000010'; + mockAuthState.user = { id: 'user-a' }; + // clearAllMocks keeps implementations: restore granted permission or the + // denied override leaks into later tests. + mockNotifications.getPermissionsAsync.mockResolvedValue({ + canAskAgain: true, + expires: 'never', + granted: true, + status: 'granted' as PermissionStatus, + }); + await AsyncStorage.clear(); + mockListSavingsGoals.mockResolvedValue({ + goals: [], + summary: { activeGoalCount: 0, savingsBalance: 0 }, + }); + }); + + it('retires terminal goals even when local arming is impossible', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + mockNotifications.getPermissionsAsync.mockResolvedValue({ + canAskAgain: true, + expires: 'never', + granted: false, + status: 'denied' as PermissionStatus, + }); + mockListSavingsGoals.mockResolvedValue({ + goals: [goalFixture('goal-1', 'completed')], + summary: { activeGoalCount: 0, savingsBalance: 100 }, + }); + + await activateDueSavingsReminderNotification(); + + // The fetch runs for retirement (not arming): the finished goal's live + // notification is cancelled and its record destroyed, with nothing + // (re)scheduled while permission is revoked. + expect(mockListSavingsGoals).toHaveBeenCalledTimes(1); + expect( + mockNotifications.cancelScheduledNotificationAsync + ).toHaveBeenCalledWith('notification-id'); + expect(scheduledGoalIds()).toEqual(['goal-1']); + await activateDueSavingsReminderNotification(); + expect(scheduledGoalIds()).toEqual(['goal-1']); + }); + + it('skips the goals fetch when no reminder records exist', async () => { + await activateDueSavingsReminderNotification(); + + expect(mockListSavingsGoals).not.toHaveBeenCalled(); + }); + + it('aborts activation when the account changes mid-fetch', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + // user-b holds a due retained pending for a goal this snapshot never + // lists; arming it unreconciled would remind for a possibly finished goal. + mockAuthState.user = { id: 'user-b' }; + await scheduleSavingsReminderNotification({ + contributionAmount: 700, + frequency: 'weekly', + goalId: 'goal-9', + goalTitle: 'Tablet', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + await suppressSavingsReminderNotification(); + mockAuthState.user = { id: 'user-a' }; + + let resolveGoals!: (value: GoalsResponse) => void; + const gate = new Promise((resolve) => { + resolveGoals = resolve; + }); + mockListSavingsGoals.mockReturnValueOnce(gate); + const activation = activateDueSavingsReminderNotification(); + mockAuthState.user = { id: 'user-b' }; + resolveGoals({ + goals: [goalFixture('goal-1', 'active')], + summary: { activeGoalCount: 1, savingsBalance: 100 }, + }); + await activation; + + // Aborted: nothing armed beyond the two initial schedules (user-b gets a + // fresh activation with its own snapshot from the auth-change effect). + expect(scheduledGoalIds()).toEqual(['goal-1', 'goal-9']); + expect(mockListSavingsGoals).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.retention-reconciliation.test.ts b/apps/mobile-storefront/services/savings-reminder-notifications.retention-reconciliation.test.ts new file mode 100644 index 00000000000..b00a4fd49d3 --- /dev/null +++ b/apps/mobile-storefront/services/savings-reminder-notifications.retention-reconciliation.test.ts @@ -0,0 +1,218 @@ +import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import AsyncStorage from '@react-native-async-storage/async-storage'; +import type { SavingsGoal } from '@/schemas/customer-savings'; + +type GoalsResponse = { + goals: SavingsGoal[]; + summary: { activeGoalCount: number; savingsBalance: number }; +}; + +const mockListSavingsGoals = jest.fn<() => Promise>(); + +jest.mock('react-native', () => ({ Platform: { OS: 'android' } })); +jest.mock('expo-notifications', () => ({ + AndroidImportance: { DEFAULT: 'default' }, + SchedulableTriggerInputTypes: { + DAILY: 'daily', + MONTHLY: 'monthly', + WEEKLY: 'weekly', + }, + cancelScheduledNotificationAsync: jest.fn(async () => undefined), + getPermissionsAsync: jest.fn(async () => ({ status: 'granted' })), + requestPermissionsAsync: jest.fn(async () => ({ status: 'granted' })), + scheduleNotificationAsync: jest.fn(async () => 'notification-id'), + setNotificationChannelAsync: jest.fn(async () => null), +})); +jest.mock('@/lib/storage', () => { + const storage = require('@react-native-async-storage/async-storage'); + return { asyncStorage: storage.default ?? storage }; +}); +jest.mock('@/lib/logger', () => ({ + createLogger: () => ({ debug: jest.fn() }), +})); +jest.mock('@/env', () => ({ EXPO_PUBLIC_API_URL: 'https://api.baci.test' })); +jest.mock('@/lib/config', () => ({ + CONFIG: { MERCHANT_ID: '00000000-0000-4000-8000-000000000010' }, +})); +jest.mock('@/stores/auth-store', () => ({ + useAuthStore: { + getState: () => ({ + merchantId: '00000000-0000-4000-8000-000000000010', + user: { id: 'user-a' }, + }), + }, +})); +jest.mock('@/lib/customer-savings', () => ({ + listSavingsGoals: mockListSavingsGoals, +})); + +const { + activateDueSavingsReminderNotification, + scheduleSavingsReminderNotification, + suppressSavingsReminderNotification, +} = + require('./savings-reminder-notifications') as typeof import('./savings-reminder-notifications'); +const { savingsNotificationCapability } = + require('./savings-notification-capability') as typeof import('./savings-notification-capability'); +const mockNotifications = require('expo-notifications') as jest.Mocked< + typeof import('expo-notifications') +>; + +const merchantId = '00000000-0000-4000-8000-000000000010'; +const capabilityScope = { + apiOrigin: 'https://api.baci.test', + merchantId, + userId: 'user-a', +}; + +function goalFixture(id: string, status: SavingsGoal['status']): SavingsGoal { + return { + breakFeePercent: 0, + contributionAmount: 500, + contributionFrequency: 'weekly', + currentAmount: 100, + id, + maturityDate: '2026-12-31', + productId: 'product-1', + sourceMode: 'manual', + startDate: '2026-01-01', + status, + targetAmount: 1000, + title: 'Phone', + variantId: null, + }; +} + +function scheduledGoalIds(): Array { + return mockNotifications.scheduleNotificationAsync.mock.calls.map( + (call) => + (call[0] as { content: { data: { goalId?: string } } }).content.data + .goalId + ); +} + +describe('savings reminder terminal-goal reconciliation', () => { + beforeEach(async () => { + jest.clearAllMocks(); + await AsyncStorage.clear(); + mockListSavingsGoals.mockResolvedValue({ + goals: [], + summary: { activeGoalCount: 0, savingsBalance: 0 }, + }); + }); + + it('retires reminders for goals completed by server auto-debit before re-arming', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + await scheduleSavingsReminderNotification({ + contributionAmount: 700, + frequency: 'weekly', + goalId: 'goal-2', + goalTitle: 'Laptop', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + await suppressSavingsReminderNotification(); + mockListSavingsGoals.mockResolvedValue({ + goals: [ + goalFixture('goal-1', 'completed'), + goalFixture('goal-2', 'active'), + ], + summary: { activeGoalCount: 1, savingsBalance: 100 }, + }); + + await activateDueSavingsReminderNotification(); + + expect(scheduledGoalIds()).toEqual(['goal-1', 'goal-2', 'goal-2']); + + // The completed goal stays retired on later activations. + await activateDueSavingsReminderNotification(); + expect(scheduledGoalIds()).toEqual(['goal-1', 'goal-2', 'goal-2']); + }); + + it('keeps all reminders when goal reconciliation fails', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + await suppressSavingsReminderNotification(); + mockListSavingsGoals.mockRejectedValue(new Error('offline')); + + await activateDueSavingsReminderNotification(); + + expect(scheduledGoalIds()).toEqual(['goal-1', 'goal-1']); + }); + + it('retires terminal goals on the server-owned path instead of retaining them', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + await scheduleSavingsReminderNotification({ + contributionAmount: 700, + frequency: 'weekly', + goalId: 'goal-2', + goalTitle: 'Laptop', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + await savingsNotificationCapability.markAvailable(capabilityScope); + mockListSavingsGoals.mockResolvedValue({ + goals: [ + goalFixture('goal-1', 'completed'), + goalFixture('goal-2', 'active'), + ], + summary: { activeGoalCount: 1, savingsBalance: 100 }, + }); + + await activateDueSavingsReminderNotification(); + + // goal-1 destroyed (live cancelled); goal-2 suppressed (live cancelled, + // pending kept) with nothing scheduled while the server owns delivery. + expect( + mockNotifications.cancelScheduledNotificationAsync + ).toHaveBeenCalledTimes(2); + expect(mockNotifications.scheduleNotificationAsync).toHaveBeenCalledTimes( + 2 + ); + const keys = (await AsyncStorage.getAllKeys()).filter((key) => + key.startsWith('baci:savings-reminder-goal:') + ); + expect(keys.filter((key) => key.includes('goal-1'))).toEqual([]); + expect(keys.filter((key) => key.includes('goal-2'))).toHaveLength(1); + }); + + it('retires live notifications for goals completed while locally active', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + mockListSavingsGoals.mockResolvedValue({ + goals: [goalFixture('goal-1', 'completed')], + summary: { activeGoalCount: 0, savingsBalance: 100 }, + }); + + await activateDueSavingsReminderNotification(); + + expect( + mockNotifications.cancelScheduledNotificationAsync + ).toHaveBeenCalledWith('notification-id'); + expect(scheduledGoalIds()).toEqual(['goal-1']); + + // The record is destroyed, so later activations stay silent. + await activateDueSavingsReminderNotification(); + expect(scheduledGoalIds()).toEqual(['goal-1']); + }); +}); diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts b/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts new file mode 100644 index 00000000000..cad99e4cff8 --- /dev/null +++ b/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts @@ -0,0 +1,172 @@ +import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import AsyncStorage from '@react-native-async-storage/async-storage'; +import type { SavingsGoal } from '@/schemas/customer-savings'; + +type GoalsResponse = { + goals: SavingsGoal[]; + summary: { activeGoalCount: number; savingsBalance: number }; +}; + +const mockListSavingsGoals = jest.fn<() => Promise>(); + +jest.mock('react-native', () => ({ Platform: { OS: 'android' } })); +jest.mock('expo-notifications', () => ({ + AndroidImportance: { DEFAULT: 'default' }, + SchedulableTriggerInputTypes: { + DAILY: 'daily', + MONTHLY: 'monthly', + WEEKLY: 'weekly', + }, + cancelScheduledNotificationAsync: jest.fn(async () => undefined), + getPermissionsAsync: jest.fn(async () => ({ status: 'granted' })), + requestPermissionsAsync: jest.fn(async () => ({ status: 'granted' })), + scheduleNotificationAsync: jest.fn(async () => 'notification-id'), + setNotificationChannelAsync: jest.fn(async () => null), +})); +jest.mock('@/lib/storage', () => { + const storage = require('@react-native-async-storage/async-storage'); + return { asyncStorage: storage.default ?? storage }; +}); +jest.mock('@/lib/logger', () => ({ + createLogger: () => ({ debug: jest.fn() }), +})); +jest.mock('@/env', () => ({ EXPO_PUBLIC_API_URL: 'https://api.baci.test' })); +jest.mock('@/lib/config', () => ({ + CONFIG: { MERCHANT_ID: '00000000-0000-4000-8000-000000000010' }, +})); +jest.mock('@/stores/auth-store', () => ({ + useAuthStore: { + getState: () => ({ + merchantId: '00000000-0000-4000-8000-000000000010', + user: { id: 'user-a' }, + }), + }, +})); +jest.mock('@/lib/customer-savings', () => ({ + listSavingsGoals: mockListSavingsGoals, +})); + +const { + activateDueSavingsReminderNotification, + scheduleSavingsReminderNotification, +} = + require('./savings-reminder-notifications') as typeof import('./savings-reminder-notifications'); +const { savingsNotificationCapability } = + require('./savings-notification-capability') as typeof import('./savings-notification-capability'); +const mockNotifications = require('expo-notifications') as jest.Mocked< + typeof import('expo-notifications') +>; + +const merchantId = '00000000-0000-4000-8000-000000000010'; +const capabilityScope = { + apiOrigin: 'https://api.baci.test', + merchantId, + userId: 'user-a', +}; + +function scheduledGoalIds(): Array { + return mockNotifications.scheduleNotificationAsync.mock.calls.map( + (call) => + (call[0] as { content: { data: { goalId?: string } } }).content.data + .goalId + ); +} + +describe('savings reminder retention across server-delivery transitions', () => { + beforeEach(async () => { + jest.clearAllMocks(); + await AsyncStorage.clear(); + mockListSavingsGoals.mockResolvedValue({ + goals: [], + summary: { activeGoalCount: 0, savingsBalance: 0 }, + }); + }); + + it('re-arms retained pendings after server delivery is enabled and then lost', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + expect(scheduledGoalIds()).toEqual(['goal-1']); + + await savingsNotificationCapability.markAvailable(capabilityScope); + await activateDueSavingsReminderNotification(); + + // Live OS notification cancelled, but nothing re-scheduled while the + // server owns delivery — and the pending request must survive. + expect( + mockNotifications.cancelScheduledNotificationAsync + ).toHaveBeenCalledWith('notification-id'); + expect(scheduledGoalIds()).toEqual(['goal-1']); + + await savingsNotificationCapability.clearAvailable(capabilityScope); + await activateDueSavingsReminderNotification(); + + expect(scheduledGoalIds()).toEqual(['goal-1', 'goal-1']); + }); + + it('persists new requests scheduled while capability is available', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + + await savingsNotificationCapability.markAvailable(capabilityScope); + // No live schedule while the server owns delivery — but the request is + // persisted as a pending so a later rollback can re-arm it. + await expect( + scheduleSavingsReminderNotification({ + contributionAmount: 700, + frequency: 'weekly', + goalId: 'goal-2', + goalTitle: 'Laptop', + }) + ).resolves.toBeNull(); + + await savingsNotificationCapability.clearAvailable(capabilityScope); + await activateDueSavingsReminderNotification(); + + expect(scheduledGoalIds()).toHaveLength(3); + expect(scheduledGoalIds().filter((id) => id === 'goal-1')).toHaveLength(2); + expect(scheduledGoalIds()).toContain('goal-2'); + }); + + it('preserves the live notification ID when suppression fails during a server-owned update', async () => { + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + scheduledAt: new Date(2020, 5, 8, 9, 30), + }); + await savingsNotificationCapability.markAvailable(capabilityScope); + mockNotifications.cancelScheduledNotificationAsync.mockRejectedValueOnce( + new Error('os busy') + ); + + await scheduleSavingsReminderNotification({ + contributionAmount: 700, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }); + + const { savingsReminderStorage } = + require('./savings-reminder-storage') as typeof import('./savings-reminder-storage'); + const { buildReminderScope } = + require('./savings-reminder-notifications') as typeof import('./savings-reminder-notifications'); + const scope = buildReminderScope('user-a', merchantId); + if (!scope) throw new Error('test scope must resolve'); + const [record] = await savingsReminderStorage.read(scope, 'goal-1'); + // The live ID survives (the OS notification is still real) while the + // pending carries the updated request. + expect(record.notificationId).toBe('notification-id'); + expect(record.pending?.contributionAmount).toBe(700); + }); +}); diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.scoping.test.ts b/apps/mobile-storefront/services/savings-reminder-notifications.scoping.test.ts new file mode 100644 index 00000000000..d069b0a0fcd --- /dev/null +++ b/apps/mobile-storefront/services/savings-reminder-notifications.scoping.test.ts @@ -0,0 +1,279 @@ +import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import AsyncStorage from '@react-native-async-storage/async-storage'; + +const mockCancelScheduledNotificationAsync = jest.fn(async () => undefined); +const mockGetPermissionsAsync = jest.fn(async () => ({ status: 'granted' })); +const mockRequestPermissionsAsync = jest.fn(async () => ({ + status: 'granted', +})); +const mockScheduleNotificationAsync = jest.fn(async () => 'notification-id'); +const mockSetNotificationChannelAsync = jest.fn(async () => undefined); + +jest.mock('react-native', () => ({ Platform: { OS: 'android' } })); +jest.mock('expo-notifications', () => ({ + AndroidImportance: { DEFAULT: 'default' }, + SchedulableTriggerInputTypes: { WEEKLY: 'weekly' }, + cancelScheduledNotificationAsync: mockCancelScheduledNotificationAsync, + getPermissionsAsync: mockGetPermissionsAsync, + requestPermissionsAsync: mockRequestPermissionsAsync, + scheduleNotificationAsync: mockScheduleNotificationAsync, + setNotificationChannelAsync: mockSetNotificationChannelAsync, +})); +jest.mock('@/lib/storage', () => { + const storage = require('@react-native-async-storage/async-storage'); + return { asyncStorage: storage.default ?? storage }; +}); +jest.mock('@/lib/logger', () => ({ + createLogger: () => ({ debug: jest.fn() }), +})); +jest.mock('@/env', () => ({ EXPO_PUBLIC_API_URL: 'https://api.baci.test' })); +jest.mock('@/lib/config', () => ({ + CONFIG: { MERCHANT_ID: '00000000-0000-4000-8000-000000000010' }, +})); +const mockAuthState: { + merchantId: string | null; + user: { id: string } | null; +} = { + merchantId: '00000000-0000-4000-8000-000000000010', + user: { id: 'user-a' }, +}; +jest.mock('@/stores/auth-store', () => ({ + useAuthStore: { getState: () => mockAuthState }, +})); +// Goal reconciliation is covered in the retention suite; here it resolves no +// goals so every record is kept (and the API-client graph stays unloaded). +jest.mock('@/lib/customer-savings', () => ({ + listSavingsGoals: jest.fn(async () => ({ + goals: [], + summary: { activeGoalCount: 0, savingsBalance: 0 }, + })), +})); + +const { + activateDueSavingsReminderNotification, + buildReminderScope, + cancelSavingsReminderNotification, + cancelScopeSavingsReminders, + scheduleSavingsReminderNotification, +} = + require('./savings-reminder-notifications') as typeof import('./savings-reminder-notifications'); + +describe('savings reminder auth scoping and cleanup', () => { + beforeEach(async () => { + jest.clearAllMocks(); + mockGetPermissionsAsync.mockResolvedValue({ status: 'granted' }); + mockAuthState.merchantId = '00000000-0000-4000-8000-000000000010'; + mockAuthState.user = { id: 'user-a' }; + await AsyncStorage.clear(); + }); + + it('never activates or cancels another account’s scoped reminders', async () => { + mockScheduleNotificationAsync.mockResolvedValueOnce('user-a-live'); + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }); + mockAuthState.user = { id: 'user-b' }; + + await expect(activateDueSavingsReminderNotification()).resolves.toBeNull(); + expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); + await cancelSavingsReminderNotification('goal-1'); + expect(mockCancelScheduledNotificationAsync).not.toHaveBeenCalledWith( + 'user-a-live' + ); + // user-a's record is untouched and still keyed to its own scope. + await expect( + AsyncStorage.getItem( + 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1' + ) + ).resolves.toContain('user-a-live'); + }); + + it('cancels pre-scope OS notifications and drops the records without adopting them', async () => { + await AsyncStorage.setItem( + 'baci:savings-reminder-goal:goal-old', + JSON.stringify({ notificationId: 'legacy-live' }) + ); + + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }); + + expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( + 'legacy-live' + ); + await expect( + AsyncStorage.getItem('baci:savings-reminder-goal:goal-old') + ).resolves.toBeNull(); + // The legacy goal was not adopted into the current scope. + expect(await AsyncStorage.getAllKeys()).toEqual([ + 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1', + ]); + }); + + it('retains pre-scope records when native cancellation fails so a later run can retry', async () => { + await AsyncStorage.setItem( + 'baci:savings-reminder-goal:goal-old', + JSON.stringify({ notificationId: 'legacy-live' }) + ); + mockCancelScheduledNotificationAsync.mockRejectedValueOnce( + new Error('notifications unavailable') + ); + + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }); + + expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( + 'legacy-live' + ); + // The cancellation ID survives the failure — the live OS notification + // is still reachable for the next entry-point run. + await expect( + AsyncStorage.getItem('baci:savings-reminder-goal:goal-old') + ).resolves.toContain('legacy-live'); + + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }); + + await expect( + AsyncStorage.getItem('baci:savings-reminder-goal:goal-old') + ).resolves.toBeNull(); + }); + + it('retires a prior scope’s live notifications and re-arms them for sign-back-in', async () => { + mockScheduleNotificationAsync.mockResolvedValueOnce('prior-live'); + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }); + const scope = buildReminderScope( + 'user-a', + '00000000-0000-4000-8000-000000000010' + ); + expect(scope).not.toBeNull(); + if (!scope) throw new Error('expected a reminder scope'); + + await expect(cancelScopeSavingsReminders(scope)).resolves.toBe(true); + expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( + 'prior-live' + ); + + // Re-armed: the cancelled notificationId is cleared but the retained + // pending request survives, so activation reschedules on return. + const raw = await AsyncStorage.getItem( + 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1' + ); + expect(raw).toContain('goal-1'); + const rearmed = JSON.parse(raw ?? '{}') as Record; + expect(rearmed.notificationId).toBeUndefined(); + expect(rearmed.pending).toEqual( + expect.objectContaining({ goalId: 'goal-1' }) + ); + mockScheduleNotificationAsync.mockResolvedValueOnce('resumed-live'); + await expect(activateDueSavingsReminderNotification()).resolves.toBe( + 'resumed-live' + ); + }); + + it('retains the notification ID when scoped cancellation fails so a later cleanup can retry', async () => { + mockScheduleNotificationAsync.mockResolvedValueOnce('prior-live'); + await scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-1', + goalTitle: 'Phone', + }); + const scope = buildReminderScope( + 'user-a', + '00000000-0000-4000-8000-000000000010' + ); + expect(scope).not.toBeNull(); + if (!scope) throw new Error('expected a reminder scope'); + + mockCancelScheduledNotificationAsync.mockRejectedValueOnce( + new Error('bridge down') + ); + await expect(cancelScopeSavingsReminders(scope)).resolves.toBe(false); + + // The live recurring notification keeps its ID: it is still + // cancellable and sign-back-in must not re-arm a duplicate. + const key = + 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1'; + const retained = JSON.parse( + (await AsyncStorage.getItem(key)) ?? '{}' + ) as Record; + expect(retained.notificationId).toBe('prior-live'); + await expect(activateDueSavingsReminderNotification()).resolves.toBeNull(); + expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); + + // A later cleanup retries the same live ID and re-arms on success. + await expect(cancelScopeSavingsReminders(scope)).resolves.toBe(true); + expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( + 'prior-live' + ); + const rearmed = JSON.parse( + (await AsyncStorage.getItem(key)) ?? '{}' + ) as Record; + expect(rearmed.notificationId).toBeUndefined(); + expect(rearmed.pending).toEqual( + expect.objectContaining({ goalId: 'goal-1' }) + ); + }); + + it('pins a queued schedule to the submitting account across a switch', async () => { + const { savingsReminderStorage } = + require('./savings-reminder-storage') as typeof import('./savings-reminder-storage'); + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const blocked = savingsReminderStorage.runExclusive(() => gate); + mockAuthState.user = { id: 'user-a' }; + const scheduled = scheduleSavingsReminderNotification({ + contributionAmount: 500, + frequency: 'weekly', + goalId: 'goal-a', + goalTitle: 'A phone', + }); + // The account switches while the schedule waits behind the earlier op. + mockAuthState.user = { id: 'user-b' }; + release(); + await blocked; + await expect(scheduled).resolves.toBe('notification-id'); + + const merchantId = '00000000-0000-4000-8000-000000000010'; + expect( + await AsyncStorage.getItem( + `baci:savings-reminder-goal:user-a:${merchantId}:goal-a` + ) + ).not.toBeNull(); + expect( + await AsyncStorage.getItem( + `baci:savings-reminder-goal:user-b:${merchantId}:goal-a` + ) + ).toBeNull(); + expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); + expect(mockScheduleNotificationAsync).toHaveBeenCalledWith( + expect.objectContaining({ + content: expect.objectContaining({ + body: expect.stringContaining('A phone'), + }), + }) + ); + }); +}); diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.test.ts b/apps/mobile-storefront/services/savings-reminder-notifications.test.ts index 92d695aa8dd..2c545a3f389 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.test.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.test.ts @@ -40,20 +40,23 @@ const mockAuthState: { jest.mock('@/stores/auth-store', () => ({ useAuthStore: { getState: () => mockAuthState }, })); +// Goal reconciliation is covered in the retention suite; here it resolves no +// goals so every record is kept (and the API-client graph stays unloaded). +jest.mock('@/lib/customer-savings', () => ({ + listSavingsGoals: jest.fn(async () => ({ + goals: [], + summary: { activeGoalCount: 0, savingsBalance: 0 }, + })), +})); const { - buildReminderScope, - cancelSavingsReminderNotification, - cancelScopeSavingsReminders, activateDueSavingsReminderNotification, + cancelSavingsReminderNotification, scheduleSavingsReminderNotification, - suppressSavingsReminderNotification, } = require('./savings-reminder-notifications') as typeof import('./savings-reminder-notifications'); -const { savingsNotificationCapability } = - require('./savings-notification-capability') as typeof import('./savings-notification-capability'); -describe('savings reminder notification capability', () => { +describe('savings reminder scheduling and cancellation', () => { beforeEach(async () => { jest.clearAllMocks(); mockGetPermissionsAsync.mockResolvedValue({ status: 'granted' }); @@ -120,32 +123,7 @@ describe('savings reminder notification capability', () => { ).resolves.toContain('user-b-live'); }); - it('activates both pending goals on boot without replacing the first', async () => { - for (const goalId of ['goal-1', 'goal-2']) { - await scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId, - goalTitle: 'Phone', - scheduledAt: new Date(2099, 0, 1), - }); - } - const now = jest - .spyOn(Date, 'now') - .mockReturnValue(new Date(2100, 0, 1).getTime()); - try { - await activateDueSavingsReminderNotification(); - expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(2); - expect(mockCancelScheduledNotificationAsync).not.toHaveBeenCalled(); - } finally { - now.mockRestore(); - } - }); - - it.each([ - 'cancel-all', - 'server-push', - ])('clears scheduled and pending goals for %s', async (reason) => { + it('clears scheduled and pending goals for cancel-all', async () => { await scheduleSavingsReminderNotification({ contributionAmount: 500, frequency: 'weekly', @@ -159,14 +137,7 @@ describe('savings reminder notification capability', () => { goalTitle: 'Phone', scheduledAt: new Date(2099, 0, 1), }); - if (reason === 'server-push') { - await savingsNotificationCapability.markAvailable({ - apiOrigin: 'https://api.baci.test', - merchantId: '00000000-0000-4000-8000-000000000010', - userId: 'user-a', - }); - await activateDueSavingsReminderNotification(); - } else await cancelSavingsReminderNotification(); + await cancelSavingsReminderNotification(); expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledTimes(1); expect( (await AsyncStorage.getAllKeys()).filter((key) => @@ -175,85 +146,6 @@ describe('savings reminder notification capability', () => { ).toEqual([]); }); - it('serializes overlapping activations so each due goal is scheduled once', async () => { - await scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-1', - goalTitle: 'Phone', - scheduledAt: new Date(2099, 0, 1), - }); - const now = jest - .spyOn(Date, 'now') - .mockReturnValue(new Date(2100, 0, 1).getTime()); - try { - await Promise.all([ - activateDueSavingsReminderNotification(), - activateDueSavingsReminderNotification(), - ]); - expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); - } finally { - now.mockRestore(); - } - }); - - it('keeps legacy local reminders active before the inbox capability is established', async () => { - await Promise.all([ - AsyncStorage.setItem( - 'baci:savings-reminder-notification-id', - 'legacy-reminder' - ), - AsyncStorage.setItem('baci:savings-reminder-goal-id', 'goal-1'), - ]); - - await expect( - scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-1', - goalTitle: 'Phone', - }) - ).resolves.toBe('notification-id'); - - expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( - 'legacy-reminder' - ); - expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); - expect(mockGetPermissionsAsync).toHaveBeenCalledTimes(1); - }); - - it('retires stale device reminders only after an authenticated inbox capability success', async () => { - await Promise.all([ - AsyncStorage.setItem( - 'baci:savings-reminder-notification-id', - 'legacy-reminder' - ), - AsyncStorage.setItem('baci:savings-reminder-goal-id', 'goal-1'), - ]); - - await savingsNotificationCapability.markAvailable({ - apiOrigin: 'https://api.baci.test', - merchantId: '00000000-0000-4000-8000-000000000010', - userId: 'user-a', - }); - - expect(mockGetPermissionsAsync).not.toHaveBeenCalled(); - expect(mockRequestPermissionsAsync).not.toHaveBeenCalled(); - - await expect( - scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-1', - goalTitle: 'Phone', - }) - ).resolves.toBeNull(); - expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( - 'legacy-reminder' - ); - expect(mockScheduleNotificationAsync).not.toHaveBeenCalled(); - }); - it('does not request permission while activating a due local reminder', async () => { // Pre-scope legacy keys are disposed, never adopted: seed a scoped // pending record through the public API instead. @@ -306,174 +198,6 @@ describe('savings reminder notification capability', () => { expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledTimes(2); }); - it('never activates or cancels another account’s scoped reminders', async () => { - mockScheduleNotificationAsync.mockResolvedValueOnce('user-a-live'); - await scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-1', - goalTitle: 'Phone', - }); - mockAuthState.user = { id: 'user-b' }; - - await expect(activateDueSavingsReminderNotification()).resolves.toBeNull(); - expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); - await cancelSavingsReminderNotification('goal-1'); - expect(mockCancelScheduledNotificationAsync).not.toHaveBeenCalledWith( - 'user-a-live' - ); - // user-a's record is untouched and still keyed to its own scope. - await expect( - AsyncStorage.getItem( - 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1' - ) - ).resolves.toContain('user-a-live'); - }); - - it('cancels pre-scope OS notifications and drops the records without adopting them', async () => { - await AsyncStorage.setItem( - 'baci:savings-reminder-goal:goal-old', - JSON.stringify({ notificationId: 'legacy-live' }) - ); - - await scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-1', - goalTitle: 'Phone', - }); - - expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( - 'legacy-live' - ); - await expect( - AsyncStorage.getItem('baci:savings-reminder-goal:goal-old') - ).resolves.toBeNull(); - // The legacy goal was not adopted into the current scope. - expect(await AsyncStorage.getAllKeys()).toEqual([ - 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1', - ]); - }); - - it('retains pre-scope records when native cancellation fails so a later run can retry', async () => { - await AsyncStorage.setItem( - 'baci:savings-reminder-goal:goal-old', - JSON.stringify({ notificationId: 'legacy-live' }) - ); - mockCancelScheduledNotificationAsync.mockRejectedValueOnce( - new Error('notifications unavailable') - ); - - await scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-1', - goalTitle: 'Phone', - }); - - expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( - 'legacy-live' - ); - // The cancellation ID survives the failure — the live OS notification - // is still reachable for the next entry-point run. - await expect( - AsyncStorage.getItem('baci:savings-reminder-goal:goal-old') - ).resolves.toContain('legacy-live'); - - await scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-1', - goalTitle: 'Phone', - }); - - await expect( - AsyncStorage.getItem('baci:savings-reminder-goal:goal-old') - ).resolves.toBeNull(); - }); - - it('retires a prior scope’s live notifications and re-arms them for sign-back-in', async () => { - mockScheduleNotificationAsync.mockResolvedValueOnce('prior-live'); - await scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-1', - goalTitle: 'Phone', - }); - const scope = buildReminderScope( - 'user-a', - '00000000-0000-4000-8000-000000000010' - ); - expect(scope).not.toBeNull(); - if (!scope) throw new Error('expected a reminder scope'); - - await expect(cancelScopeSavingsReminders(scope)).resolves.toBe(true); - expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( - 'prior-live' - ); - - // Re-armed: the cancelled notificationId is cleared but the retained - // pending request survives, so activation reschedules on return. - const raw = await AsyncStorage.getItem( - 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1' - ); - expect(raw).toContain('goal-1'); - const rearmed = JSON.parse(raw ?? '{}') as Record; - expect(rearmed.notificationId).toBeUndefined(); - expect(rearmed.pending).toEqual( - expect.objectContaining({ goalId: 'goal-1' }) - ); - mockScheduleNotificationAsync.mockResolvedValueOnce('resumed-live'); - await expect(activateDueSavingsReminderNotification()).resolves.toBe( - 'resumed-live' - ); - }); - - it('retains the notification ID when scoped cancellation fails so a later cleanup can retry', async () => { - mockScheduleNotificationAsync.mockResolvedValueOnce('prior-live'); - await scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-1', - goalTitle: 'Phone', - }); - const scope = buildReminderScope( - 'user-a', - '00000000-0000-4000-8000-000000000010' - ); - expect(scope).not.toBeNull(); - if (!scope) throw new Error('expected a reminder scope'); - - mockCancelScheduledNotificationAsync.mockRejectedValueOnce( - new Error('bridge down') - ); - await expect(cancelScopeSavingsReminders(scope)).resolves.toBe(false); - - // The live recurring notification keeps its ID: it is still - // cancellable and sign-back-in must not re-arm a duplicate. - const key = - 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1'; - const retained = JSON.parse( - (await AsyncStorage.getItem(key)) ?? '{}' - ) as Record; - expect(retained.notificationId).toBe('prior-live'); - await expect(activateDueSavingsReminderNotification()).resolves.toBeNull(); - expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); - - // A later cleanup retries the same live ID and re-arms on success. - await expect(cancelScopeSavingsReminders(scope)).resolves.toBe(true); - expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( - 'prior-live' - ); - const rearmed = JSON.parse( - (await AsyncStorage.getItem(key)) ?? '{}' - ) as Record; - expect(rearmed.notificationId).toBeUndefined(); - expect(rearmed.pending).toEqual( - expect.objectContaining({ goalId: 'goal-1' }) - ); - }); - it('fails closed when no account is signed in', async () => { mockAuthState.user = null; @@ -493,78 +217,6 @@ describe('savings reminder notification capability', () => { expect(await AsyncStorage.getAllKeys()).toEqual([]); }); - it('pins a queued schedule to the submitting account across a switch', async () => { - const { savingsReminderStorage } = - require('./savings-reminder-storage') as typeof import('./savings-reminder-storage'); - let release!: () => void; - const gate = new Promise((resolve) => { - release = resolve; - }); - const blocked = savingsReminderStorage.runExclusive(() => gate); - mockAuthState.user = { id: 'user-a' }; - const scheduled = scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-a', - goalTitle: 'A phone', - }); - // The account switches while the schedule waits behind the earlier op. - mockAuthState.user = { id: 'user-b' }; - release(); - await blocked; - await expect(scheduled).resolves.toBe('notification-id'); - - const merchantId = '00000000-0000-4000-8000-000000000010'; - expect( - await AsyncStorage.getItem( - `baci:savings-reminder-goal:user-a:${merchantId}:goal-a` - ) - ).not.toBeNull(); - expect( - await AsyncStorage.getItem( - `baci:savings-reminder-goal:user-b:${merchantId}:goal-a` - ) - ).toBeNull(); - expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); - expect(mockScheduleNotificationAsync).toHaveBeenCalledWith( - expect.objectContaining({ - content: expect.objectContaining({ - body: expect.stringContaining('A phone'), - }), - }) - ); - }); - - it('suppresses live reminders while retaining pendings for a later rollback', async () => { - await scheduleSavingsReminderNotification({ - contributionAmount: 500, - frequency: 'weekly', - goalId: 'goal-1', - goalTitle: 'Phone', - }); - expect(mockScheduleNotificationAsync).toHaveBeenCalledTimes(1); - - await expect(suppressSavingsReminderNotification()).resolves.toBe(true); - expect(mockCancelScheduledNotificationAsync).toHaveBeenCalledWith( - 'notification-id' - ); - const key = - 'baci:savings-reminder-goal:user-a:00000000-0000-4000-8000-000000000010:goal-1'; - const suppressed = JSON.parse( - (await AsyncStorage.getItem(key)) ?? '{}' - ) as Record; - expect(suppressed.notificationId).toBeUndefined(); - expect(suppressed.pending).toEqual( - expect.objectContaining({ goalId: 'goal-1' }) - ); - - // Rollback path: activation re-arms the retained pending request. - mockScheduleNotificationAsync.mockResolvedValueOnce('rearmed-id'); - await expect(activateDueSavingsReminderNotification()).resolves.toBe( - 'rearmed-id' - ); - }); - it('cancels the native notification when persistence fails', async () => { const setItem = jest .spyOn(AsyncStorage, 'setItem') diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.triggers.test.ts b/apps/mobile-storefront/services/savings-reminder-notifications.triggers.test.ts index 227361ba1cb..3ad9bef1176 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.triggers.test.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.triggers.test.ts @@ -34,6 +34,14 @@ jest.mock('@/stores/auth-store', () => ({ }), }, })); +// Goal reconciliation is covered in the retention suite; here it resolves no +// goals so every record is kept (and the API-client graph stays unloaded). +jest.mock('@/lib/customer-savings', () => ({ + listSavingsGoals: jest.fn(async () => ({ + goals: [], + summary: { activeGoalCount: 0, savingsBalance: 0 }, + })), +})); const { activateDueSavingsReminderNotification, diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.ts b/apps/mobile-storefront/services/savings-reminder-notifications.ts index e8d8d036d30..7bc3468dcae 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.ts @@ -7,7 +7,6 @@ import { useAuthStore } from '@/stores/auth-store'; import { ensureSavingsReminderChannel, ensureSavingsReminderPermissions, - hasSavingsReminderPermission, loadNotificationsModule, } from './savings-reminder-native'; import { @@ -23,6 +22,7 @@ import { savingsReminderStorage, } from './savings-reminder-storage'; +export { activateDueSavingsReminderNotification } from './savings-reminder-activation'; export type { SavingsReminderScope }; /** @@ -58,16 +58,6 @@ function hasServerSavingsNotificationCapabilityFor(scope: { }); } -function hasServerSavingsNotificationCapability() { - const { merchantId, user } = useAuthStore.getState(); - const resolvedMerchantId = pickMerchantId(merchantId, CONFIG.MERCHANT_ID); - if (!resolvedMerchantId || !user?.id) return Promise.resolve(false); - return hasServerSavingsNotificationCapabilityFor({ - merchantId: resolvedMerchantId, - userId: user.id, - }); -} - export function cancelSavingsReminderNotification( goalId?: string, captured?: { merchantId: string; userId: string } @@ -131,48 +121,6 @@ export function cancelScopeSavingsReminders(scope: SavingsReminderScope) { }); } -export function activateDueSavingsReminderNotification() { - return savingsReminderStorage.runExclusive(activateDueReminders); -} - -async function activateDueReminders() { - const scope = resolveReminderScope(); - if (!scope) return null; - const notifications = loadNotificationsModule(); - await disposeUnscopedSavingsReminders(notifications); - if (await hasServerSavingsNotificationCapability()) { - await cancelStoredSavingsReminderNotification(notifications, scope); - return null; - } - const records = await savingsReminderStorage.read(scope); - // Records already converted to a live OS notification keep their retained - // pending request — only due requests without a live notification arm now. - const due = records.filter( - ({ notificationId, pending }) => - !notificationId && pending && pending.scheduledAt.getTime() <= Date.now() - ); - if (!due.length) return null; - if (!notifications || !(await hasSavingsReminderPermission(notifications))) - return null; - await ensureSavingsReminderChannel(notifications); - let notificationId: string | null = null; - let failure: unknown; - for (const { pending } of due) { - if (!pending) continue; - try { - notificationId = await scheduleRecurringSavingsReminder({ - notifications, - request: pending, - scope, - }); - } catch (error) { - failure = error; - } - } - if (failure) throw failure; - return notificationId; -} - export function scheduleSavingsReminderNotification({ contributionAmount, frequency, @@ -235,7 +183,22 @@ async function scheduleReminder( const notifications = loadNotificationsModule(); await disposeUnscopedSavingsReminders(notifications); if (await hasServerSavingsNotificationCapabilityFor(scope)) { - await cancelStoredSavingsReminderNotification(notifications, scope); + // Suppress, not cancel: pre-existing pendings must survive so local + // reminders re-arm if server delivery is later lost. + await suppressStoredSavingsReminderNotification(notifications, scope); + // Persist the incoming request as a pending (no live schedule) so a + // later loss of server delivery can still re-arm this goal; an update + // overwrites the previous pending for the goal. Preserve a retained + // live ID: when suppression's OS cancel fails, the notification is + // still real and must stay trackable. + const [existing] = await savingsReminderStorage.read(scope, request.goalId); + await savingsReminderStorage.write({ + goalId: request.goalId, + merchantId: scope.merchantId, + notificationId: existing?.notificationId, + pending: request, + userId: scope.userId, + }); return null; } if ( diff --git a/apps/web/tools/db/expected-savings-runtime-pending-sources.test-support.ts b/apps/web/tools/db/expected-savings-runtime-pending-sources.test-support.ts index c0a78c4a7a2..8b2473d93c2 100644 --- a/apps/web/tools/db/expected-savings-runtime-pending-sources.test-support.ts +++ b/apps/web/tools/db/expected-savings-runtime-pending-sources.test-support.ts @@ -244,4 +244,9 @@ export const EXPECTED_SAVINGS_RUNTIME_PENDING_SOURCES = [ 'supabase/migrations/20261006120000_cancel_plan_intent_fk_indexes.sql', sha256: 'c3c73608d4fa2d8faf30e84ecfc3173663d1996ed8038ed848985303e492ad43', }, + { + repositoryPath: + 'supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql', + sha256: '71b15d50589d66f8dbdaa38ad9b5844a3fe110422e41b48b8ce3a5393a2b8391', + }, ] as const; diff --git a/apps/web/tools/db/supabase-history-replay-savings-runtime-pending-sources.ts b/apps/web/tools/db/supabase-history-replay-savings-runtime-pending-sources.ts index bca60b31a59..c425b80ae1c 100644 --- a/apps/web/tools/db/supabase-history-replay-savings-runtime-pending-sources.ts +++ b/apps/web/tools/db/supabase-history-replay-savings-runtime-pending-sources.ts @@ -47,4 +47,5 @@ f520b9bbb2c9b1a06ed1867622b9674945851a39255f729cfc0cd996a26558f3 20261004171000_ 0dbc0417125c73285dbb36b7396c64bbb627a290e3142b8494168884597ea100 20261006080000_push_delivery_retry_backoff.sql 6428757f62d6039c4f96259a7dec6499fac7ec31909b4e98dae5faa095a2ca23 20261006081000_staging_wallet_restriction_state.sql 686f2d9209e359af2ca3793f60faf1d246d4d156649e9521edf2be9a7476bf97 20261006081500_plan_transfer_restricted_destination.sql -c3c73608d4fa2d8faf30e84ecfc3173663d1996ed8038ed848985303e492ad43 20261006120000_cancel_plan_intent_fk_indexes.sql`; +c3c73608d4fa2d8faf30e84ecfc3173663d1996ed8038ed848985303e492ad43 20261006120000_cancel_plan_intent_fk_indexes.sql +71b15d50589d66f8dbdaa38ad9b5844a3fe110422e41b48b8ce3a5393a2b8391 20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql`; diff --git a/supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql b/supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql new file mode 100644 index 00000000000..dcb5d502e4d --- /dev/null +++ b/supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql @@ -0,0 +1,21 @@ +-- disable-transaction +-- Follow-up to 20260926110300_piggyvest_transfer_outbox_submission: the +-- outbox claims table carries an authorization_id foreign key with no +-- supporting index, so parent authorization updates/deletes must scan the +-- entire claims table as submission history grows. +-- Production deploys split this marked migration into top-level statements +-- so PostgreSQL can build the index without blocking submission writes. +-- Retry cleanup must also be top-level: DROP INDEX CONCURRENTLY cannot run +-- inside a DO/transaction block, and normal DROP INDEX takes an ACCESS +-- EXCLUSIVE table lock. The drop also clears a leftover INVALID index from +-- an interrupted concurrent build so the CREATE below rebuilds instead of +-- skipping on the name. Rebuild-on-rerun is intentional: the DROP cannot be +-- conditioned on validity in top-level SQL, and the plain CREATE (no IF NOT +-- EXISTS) fails loudly rather than silently skipping if two deploys race. +DROP INDEX CONCURRENTLY IF EXISTS public.piggyvest_transfer_outbox_claims_authorization_idx; + +CREATE INDEX CONCURRENTLY piggyvest_transfer_outbox_claims_authorization_idx + ON public.piggyvest_transfer_outbox_submission_claims USING btree (authorization_id); + +COMMENT ON INDEX public.piggyvest_transfer_outbox_claims_authorization_idx IS + 'Supports authorization parent-row updates/deletes without scanning piggyvest_transfer_outbox_submission_claims history.'; diff --git a/supabase/migrations/tests/piggyvest_transfer_outbox_claims_authorization_index.sql b/supabase/migrations/tests/piggyvest_transfer_outbox_claims_authorization_index.sql new file mode 100644 index 00000000000..fecadcd1c06 --- /dev/null +++ b/supabase/migrations/tests/piggyvest_transfer_outbox_claims_authorization_index.sql @@ -0,0 +1,33 @@ +-- Regression test for 20261007120000: the outbox claims table must carry a +-- valid, ready btree index on authorization_id so parent authorization +-- updates/deletes stay index-backed as submission history grows. +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_catalog.pg_index AS index_state + JOIN pg_catalog.pg_class AS index_class + ON index_class.oid = index_state.indexrelid + JOIN pg_catalog.pg_class AS table_class + ON table_class.oid = index_state.indrelid + JOIN pg_catalog.pg_namespace AS table_schema + ON table_schema.oid = table_class.relnamespace + JOIN pg_catalog.pg_attribute AS indexed_column + ON indexed_column.attrelid = table_class.oid + AND indexed_column.attname = 'authorization_id' + JOIN pg_catalog.pg_am AS index_method + ON index_method.oid = index_class.relam + WHERE table_schema.nspname = 'public' + AND table_class.relname = 'piggyvest_transfer_outbox_submission_claims' + AND index_class.relname = 'piggyvest_transfer_outbox_claims_authorization_idx' + AND index_state.indisvalid + AND index_state.indisready + AND index_method.amname = 'btree' + AND index_state.indpred IS NULL + AND index_state.indnatts = 1 + AND index_state.indkey[0] = indexed_column.attnum + ) THEN + RAISE EXCEPTION 'piggyvest_transfer_outbox_submission_claims.authorization_id is not backed by a valid ready index'; + END IF; +END; +$$;