From a7420a12cf4df871556f82db3965f743b983befa Mon Sep 17 00:00:00 2001 From: ogabasseyy Date: Wed, 7 Oct 2026 21:21:47 +0100 Subject: [PATCH 1/8] =?UTF-8?q?fix(pr3620):=20address=20Codex=20round=20?= =?UTF-8?q?=E2=80=94=20useCallback,=20FK=20index,=20reminder=20suppression?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - P1: drop manual useCallback from usePredictionSelectHandler; plain closure memoized by React Compiler (repo rule AGENTS.md). - P1: follow-up migration indexing piggyvest_transfer_outbox_submission_claims(authorization_id); registered sha256 in replay pending sources + expected support. - P2: inbox server-delivery switch uses suppressSavingsReminderNotification with captured account scope instead of destructive cancel; pin with positive test. --- .../ui/use-address-prediction-select.ts | 51 +++++++------------ .../use-savings-notification-inbox.test.ts | 37 +++++++++++--- .../hooks/use-savings-notification-inbox.ts | 17 ++++--- ...gs-runtime-pending-sources.test-support.ts | 5 ++ ...-replay-savings-runtime-pending-sources.ts | 3 +- ...ansfer_outbox_claims_authorization_idx.sql | 8 +++ 6 files changed, 75 insertions(+), 46 deletions(-) create mode 100644 supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql 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..625d551a1a1 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 } from 'react'; import { Keyboard } from 'react-native'; import { fetchPlaceDetails } from './AddressAutocomplete.api'; import type { @@ -20,9 +20,9 @@ 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. No manual useCallback — React Compiler memoizes this closure + * (manual memoization hooks are prohibited in this repo). */ export function usePredictionSelectHandler({ isMountedRef, @@ -35,39 +35,24 @@ 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); - } + return 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 details = await fetchPlaceDetails({ prediction, sessionToken }); + applyPlaceSelection({ + details, isMountedRef, - latestQueryRef, - onChangeText, onSelect, - sessionToken, - setInternalValue, setIsLoading, setPredictions, setSessionToken, - ] - ); + }); + }; } 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..8d592202226 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]'); }); @@ -193,7 +194,7 @@ describe('useSavingsNotificationInbox', () => { await waitFor(() => expect(result.current.notifications).toHaveLength(1)); expect(mockMarkAvailable).not.toHaveBeenCalled(); - expect(mockCancelSavingsReminderNotification).not.toHaveBeenCalled(); + expect(mockSuppressSavingsReminderNotification).not.toHaveBeenCalled(); expect(mockClearAvailable).toHaveBeenCalledWith({ apiOrigin: 'https://api.baci.test', merchantId, @@ -220,7 +221,7 @@ describe('useSavingsNotificationInbox', () => { ); expect(mockMarkAvailable).not.toHaveBeenCalled(); - expect(mockCancelSavingsReminderNotification).not.toHaveBeenCalled(); + expect(mockSuppressSavingsReminderNotification).not.toHaveBeenCalled(); expect(mockClearAvailable).toHaveBeenCalledWith({ apiOrigin: 'https://api.baci.test', merchantId, @@ -298,6 +299,30 @@ describe('useSavingsNotificationInbox', () => { await firstMark; }); - expect(mockCancelSavingsReminderNotification).not.toHaveBeenCalled(); + 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', + }); }); }); diff --git a/apps/mobile-storefront/hooks/use-savings-notification-inbox.ts b/apps/mobile-storefront/hooks/use-savings-notification-inbox.ts index ef1e47be020..17d27ebae3b 100644 --- a/apps/mobile-storefront/hooks/use-savings-notification-inbox.ts +++ b/apps/mobile-storefront/hooks/use-savings-notification-inbox.ts @@ -13,7 +13,7 @@ import { markSavingsNotificationRead, updateSavingsNotificationPreferences, } from '@/services/savings-notification-inbox'; -import { cancelSavingsReminderNotification } from '@/services/savings-reminder-notifications'; +import { suppressSavingsReminderNotification } from '@/services/savings-reminder-notifications'; type InboxState = { error: string | null; @@ -108,7 +108,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 +123,16 @@ 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(); + return suppressSavingsReminderNotification({ + merchantId: activeMerchantId, + userId: activeUserId, + }); }) .catch(() => undefined); } else { 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..d6d830acefc 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: 'd8525b1860981cca73959a8ccd912cab51ec1e112c25e2298a13bbbe3dffde85', + }, ] 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..558a200fa40 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 +d8525b1860981cca73959a8ccd912cab51ec1e112c25e2298a13bbbe3dffde85 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..82a5c14483c --- /dev/null +++ b/supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql @@ -0,0 +1,8 @@ +-- 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. Migrations are +-- append-only, so the index lands here rather than editing the original +-- migration. +CREATE INDEX IF NOT EXISTS piggyvest_transfer_outbox_claims_authorization_idx + ON public.piggyvest_transfer_outbox_submission_claims (authorization_id); From ec6536ed56311a1ec7d4830b06f7f4d389e8b88b Mon Sep 17 00:00:00 2001 From: ogabasseyy Date: Wed, 7 Oct 2026 21:45:00 +0100 Subject: [PATCH 2/8] =?UTF-8?q?fix(pr3640):=20address=20review=20round=202?= =?UTF-8?q?=20=E2=80=94=20concurrent=20index,=20split=20tests,=20identity?= =?UTF-8?q?=20pin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - P2: build the claims authorization index CONCURRENTLY with top-level retry cleanup + COMMENT (repo feed-migration pattern); re-registered sha256 in replay pending sources. - P1: sql-check regression test asserting a valid ready btree index on claims(authorization_id); registered in ci.yml. Proven to fail without the migration and pass with it on scratch postgres. - P1: split 328-line inbox test file into inbox (218) + delivery (200) companions, both under the 300-line limit. - P1/low: ref-backed stable prediction-select handler (plain closure failed identity under jest: compiler does not memoize it) with regression tests for stability + latest-value invocation. --- .github/workflows/ci.yml | 1 + .../ui/use-address-prediction-select.test.ts | 97 +++++++++ .../ui/use-address-prediction-select.ts | 79 +++++-- ...avings-notification-inbox.delivery.test.ts | 200 ++++++++++++++++++ .../use-savings-notification-inbox.test.ts | 110 ---------- ...gs-runtime-pending-sources.test-support.ts | 2 +- ...-replay-savings-runtime-pending-sources.ts | 2 +- ...ansfer_outbox_claims_authorization_idx.sql | 21 +- ...sfer_outbox_claims_authorization_index.sql | 25 +++ 9 files changed, 398 insertions(+), 139 deletions(-) create mode 100644 apps/mobile-storefront/components/ui/use-address-prediction-select.test.ts create mode 100644 apps/mobile-storefront/hooks/use-savings-notification-inbox.delivery.test.ts create mode 100644 supabase/migrations/tests/piggyvest_transfer_outbox_claims_authorization_index.sql 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 625d551a1a1..640787ee5fc 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 } from 'react'; +import { type MutableRefObject, useRef } from 'react'; import { Keyboard } from 'react-native'; import { fetchPlaceDetails } from './AddressAutocomplete.api'; import type { @@ -21,8 +21,11 @@ type PredictionSelectDeps = { /** * Prediction-select handler: the suggestions-portal effect depends on its - * identity. No manual useCallback — React Compiler memoizes this closure - * (manual memoization hooks are prohibited in this repo). + * 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,24 +38,56 @@ export function usePredictionSelectHandler({ setPredictions, setSessionToken, }: PredictionSelectDeps) { - return 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, - }); + const latestRef = useRef({ + isMountedRef, + latestQueryRef, + onChangeText, + onSelect, + sessionToken, + setInternalValue, + setIsLoading, + setPredictions, + setSessionToken, + }); + latestRef.current = { + isMountedRef, + latestQueryRef, + onChangeText, + onSelect, + sessionToken, + setInternalValue, + 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..07129d846cf --- /dev/null +++ b/apps/mobile-storefront/hooks/use-savings-notification-inbox.delivery.test.ts @@ -0,0 +1,200 @@ +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 { 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(); + 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', + }); + }); +}); 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 8d592202226..9a50327ed36 100644 --- a/apps/mobile-storefront/hooks/use-savings-notification-inbox.test.ts +++ b/apps/mobile-storefront/hooks/use-savings-notification-inbox.test.ts @@ -181,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(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('hides the previous account inbox immediately when the account changes', async () => { const accountBInbox = { ...inbox, @@ -263,66 +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(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', - }); - }); }); 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 d6d830acefc..80c1924ba75 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 @@ -247,6 +247,6 @@ export const EXPECTED_SAVINGS_RUNTIME_PENDING_SOURCES = [ { repositoryPath: 'supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql', - sha256: 'd8525b1860981cca73959a8ccd912cab51ec1e112c25e2298a13bbbe3dffde85', + sha256: 'fa78478d48203484e464fd3d849311e57839a3f214a907608451bfd2100eb945', }, ] 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 558a200fa40..0853933addd 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 @@ -48,4 +48,4 @@ f520b9bbb2c9b1a06ed1867622b9674945851a39255f729cfc0cd996a26558f3 20261004171000_ 6428757f62d6039c4f96259a7dec6499fac7ec31909b4e98dae5faa095a2ca23 20261006081000_staging_wallet_restriction_state.sql 686f2d9209e359af2ca3793f60faf1d246d4d156649e9521edf2be9a7476bf97 20261006081500_plan_transfer_restricted_destination.sql c3c73608d4fa2d8faf30e84ecfc3173663d1996ed8038ed848985303e492ad43 20261006120000_cancel_plan_intent_fk_indexes.sql -d8525b1860981cca73959a8ccd912cab51ec1e112c25e2298a13bbbe3dffde85 20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql`; +fa78478d48203484e464fd3d849311e57839a3f214a907608451bfd2100eb945 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 index 82a5c14483c..7f3b1f22a22 100644 --- a/supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql +++ b/supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql @@ -1,8 +1,19 @@ +-- 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. Migrations are --- append-only, so the index lands here rather than editing the original --- migration. -CREATE INDEX IF NOT EXISTS piggyvest_transfer_outbox_claims_authorization_idx - ON public.piggyvest_transfer_outbox_submission_claims (authorization_id); +-- 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. +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..1b4d1a95c98 --- /dev/null +++ b/supabase/migrations/tests/piggyvest_transfer_outbox_claims_authorization_index.sql @@ -0,0 +1,25 @@ +-- 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 + 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 pg_catalog.pg_get_indexdef(index_class.oid) LIKE '%(authorization_id)%' + ) THEN + RAISE EXCEPTION 'piggyvest_transfer_outbox_submission_claims.authorization_id is not backed by a valid ready index'; + END IF; +END; +$$; From 2424306934d92aa14996d8ba1f73f6398a4094ca Mon Sep 17 00:00:00 2001 From: ogabasseyy Date: Wed, 7 Oct 2026 21:53:35 +0100 Subject: [PATCH 3/8] =?UTF-8?q?fix(pr3640):=20address=20review=20round=203?= =?UTF-8?q?=20=E2=80=94=20effect=20sync,=20exact=20index=20shape?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - medium: move latestRef sync out of render into useLayoutEffect (post-commit, flushes before paint); stableRef lazy-init remains the only render-phase write. - low/P1: regression check now asserts exact index shape — btree via pg_am, indpred IS NULL, single column, authorization_id leading via indkey[0]=attnum. Proven on scratch postgres: passes on the real index; partial, hash, and non-leading decoys rejected. - low: document intentional rebuild-on-rerun in the migration (DROP cannot be validity-conditioned in top-level SQL; plain CREATE fails loudly on double-deploy races). Re-registered sha256. --- .../ui/use-address-prediction-select.ts | 30 +++++++++++-------- ...gs-runtime-pending-sources.test-support.ts | 2 +- ...-replay-savings-runtime-pending-sources.ts | 2 +- ...ansfer_outbox_claims_authorization_idx.sql | 4 ++- ...sfer_outbox_claims_authorization_index.sql | 10 ++++++- 5 files changed, 32 insertions(+), 16 deletions(-) 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 640787ee5fc..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, useRef } from 'react'; +import { type MutableRefObject, useLayoutEffect, useRef } from 'react'; import { Keyboard } from 'react-native'; import { fetchPlaceDetails } from './AddressAutocomplete.api'; import type { @@ -49,17 +49,23 @@ export function usePredictionSelectHandler({ setPredictions, setSessionToken, }); - latestRef.current = { - 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, + onSelect, + sessionToken, + setInternalValue, + setIsLoading, + setPredictions, + setSessionToken, + }; + }); const stableRef = useRef< ((prediction: PlacePrediction) => Promise) | null >(null); 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 80c1924ba75..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 @@ -247,6 +247,6 @@ export const EXPECTED_SAVINGS_RUNTIME_PENDING_SOURCES = [ { repositoryPath: 'supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql', - sha256: 'fa78478d48203484e464fd3d849311e57839a3f214a907608451bfd2100eb945', + 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 0853933addd..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 @@ -48,4 +48,4 @@ f520b9bbb2c9b1a06ed1867622b9674945851a39255f729cfc0cd996a26558f3 20261004171000_ 6428757f62d6039c4f96259a7dec6499fac7ec31909b4e98dae5faa095a2ca23 20261006081000_staging_wallet_restriction_state.sql 686f2d9209e359af2ca3793f60faf1d246d4d156649e9521edf2be9a7476bf97 20261006081500_plan_transfer_restricted_destination.sql c3c73608d4fa2d8faf30e84ecfc3173663d1996ed8038ed848985303e492ad43 20261006120000_cancel_plan_intent_fk_indexes.sql -fa78478d48203484e464fd3d849311e57839a3f214a907608451bfd2100eb945 20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.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 index 7f3b1f22a22..dcb5d502e4d 100644 --- a/supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql +++ b/supabase/migrations/20261007120000_piggyvest_transfer_outbox_claims_authorization_idx.sql @@ -9,7 +9,9 @@ -- 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. +-- 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 diff --git a/supabase/migrations/tests/piggyvest_transfer_outbox_claims_authorization_index.sql b/supabase/migrations/tests/piggyvest_transfer_outbox_claims_authorization_index.sql index 1b4d1a95c98..fecadcd1c06 100644 --- a/supabase/migrations/tests/piggyvest_transfer_outbox_claims_authorization_index.sql +++ b/supabase/migrations/tests/piggyvest_transfer_outbox_claims_authorization_index.sql @@ -12,12 +12,20 @@ BEGIN 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 pg_catalog.pg_get_indexdef(index_class.oid) LIKE '%(authorization_id)%' + 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; From 10434dfc7e0749a805e95fe9b6070ab0656f6e7f Mon Sep 17 00:00:00 2001 From: ogabasseyy Date: Wed, 7 Oct 2026 22:10:56 +0100 Subject: [PATCH 4/8] =?UTF-8?q?fix(pr3640):=20address=20review=20round=204?= =?UTF-8?q?=20=E2=80=94=20retain=20on=20activation,=20reconcile=20goals?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - P1: capability-available branches in activateDueReminders and scheduleReminder now suppress (retain pendings) instead of destroying records, so a later server-delivery loss re-arms. - P2: activation reconciles due records with listSavingsGoals and retires completed/cancelled/spent goals; unlisted goals and lookup failures keep reminders (fail-safe). - Tests: new retention suite (4 tests, 3 proven failing pre-fix); split the outdated cancel-all/server-push case to the new retain-on-server-push contract; empty-goals mocks in the suites that load the real module. --- ...s-reminder-notifications.retention.test.ts | 205 ++++++++++++++++++ .../savings-reminder-notifications.test.ts | 61 +++++- ...gs-reminder-notifications.triggers.test.ts | 8 + .../savings-reminder-notifications.ts | 54 ++++- 4 files changed, 313 insertions(+), 15 deletions(-) create mode 100644 apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts 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..2224f9c8fb7 --- /dev/null +++ b/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts @@ -0,0 +1,205 @@ +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 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('retains existing pendings when a schedule attempt lands 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); + await expect( + scheduleSavingsReminderNotification({ + contributionAmount: 700, + frequency: 'weekly', + goalId: 'goal-2', + goalTitle: 'Laptop', + }) + ).resolves.toBeNull(); + + await savingsNotificationCapability.clearAvailable(capabilityScope); + await activateDueSavingsReminderNotification(); + + // goal-1's retained pending re-arms; goal-2 was never stored because the + // server owned delivery at schedule time. + expect(scheduledGoalIds()).toEqual(['goal-1', 'goal-1']); + }); + + 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']); + }); +}); diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.test.ts b/apps/mobile-storefront/services/savings-reminder-notifications.test.ts index 92d695aa8dd..6f340021c05 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.test.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.test.ts @@ -40,6 +40,14 @@ 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, @@ -142,10 +150,7 @@ describe('savings reminder notification capability', () => { } }); - 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 +164,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,6 +173,45 @@ describe('savings reminder notification capability', () => { ).toEqual([]); }); + 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, 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..ac2a8c3a460 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.ts @@ -1,5 +1,6 @@ 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'; @@ -18,6 +19,7 @@ import { suppressStoredSavingsReminderNotification, } from './savings-reminder-scheduling'; import { + type ReminderRecord, type SavingsReminderRequest, type SavingsReminderScope, savingsReminderStorage, @@ -135,13 +137,56 @@ export function activateDueSavingsReminderNotification() { return savingsReminderStorage.runExclusive(activateDueReminders); } +/** + * Reconciles due records with current goal state before re-arming. A goal + * completed server-side (e.g. auto-debit) bypasses the mobile contribution + * handlers, so its retained pending would otherwise re-arm and remind for a + * finished goal. Terminal-goal records are destroyed; anything unlisted (or + * unreachable on lookup failure) is kept — a failed lookup must never nuke + * reminders. + */ +async function retireTerminalGoalReminders( + notifications: ReturnType, + scope: SavingsReminderScope, + due: ReminderRecord[] +): Promise { + let goals: Awaited>['goals']; + try { + goals = (await listSavingsGoals({ merchantId: scope.merchantId })).goals; + } catch (error) { + log.debug('Unable to reconcile savings reminders with goal state', error); + return due; + } + const statusByGoalId = new Map(goals.map((goal) => [goal.id, goal.status])); + const armed: ReminderRecord[] = []; + for (const record of due) { + const status = statusByGoalId.get(record.goalId); + if ( + status === 'completed' || + status === 'cancelled' || + status === 'spent' + ) { + await cancelStoredSavingsReminderNotification( + notifications, + scope, + record.goalId + ); + continue; + } + armed.push(record); + } + return armed; +} + async function activateDueReminders() { const scope = resolveReminderScope(); if (!scope) return null; const notifications = loadNotificationsModule(); await disposeUnscopedSavingsReminders(notifications); if (await hasServerSavingsNotificationCapability()) { - await cancelStoredSavingsReminderNotification(notifications, scope); + // Suppress, not cancel: the pending requests must survive so local + // reminders re-arm if server delivery is later lost. + await suppressStoredSavingsReminderNotification(notifications, scope); return null; } const records = await savingsReminderStorage.read(scope); @@ -152,12 +197,13 @@ async function activateDueReminders() { !notificationId && pending && pending.scheduledAt.getTime() <= Date.now() ); if (!due.length) return null; + const armed = await retireTerminalGoalReminders(notifications, scope, due); if (!notifications || !(await hasSavingsReminderPermission(notifications))) return null; await ensureSavingsReminderChannel(notifications); let notificationId: string | null = null; let failure: unknown; - for (const { pending } of due) { + for (const { pending } of armed) { if (!pending) continue; try { notificationId = await scheduleRecurringSavingsReminder({ @@ -235,7 +281,9 @@ 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); return null; } if ( From e97f5f2d3c88e6fdfccf4495989340d487e48275 Mon Sep 17 00:00:00 2001 From: ogabasseyy Date: Wed, 7 Oct 2026 22:22:50 +0100 Subject: [PATCH 5/8] =?UTF-8?q?fix(pr3640):=20address=20review=20round=205?= =?UTF-8?q?=20=E2=80=94=20persist-while-suppressed,=20reconcile-all?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - medium/Major: scheduleReminder persists the incoming request as a pending (no live schedule) while server delivery owns reminders, so a later rollback re-arms it; updates overwrite. - Major: retireTerminalGoalReminders now reconciles every stored record (not just due ones), retiring terminal goals that still have live notifications. - low: permission/channel gates moved before the goals fetch so impossible-to-arm runs skip the network; retire-before-arm order kept (backgrounding could strand live notifications on a kill). Deferred terminal cleanup while server-owned noted as intentional and bounded (one record per goal). - Tests: updated persist case + live-terminal retire + gates-first cases (6/6 retention green). --- ...s-reminder-notifications.retention.test.ts | 58 +++++++++++++++++-- .../savings-reminder-notifications.ts | 51 +++++++++++----- 2 files changed, 89 insertions(+), 20 deletions(-) diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts b/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts index 2224f9c8fb7..8fc5796242f 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts @@ -1,5 +1,6 @@ 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 = { @@ -127,7 +128,7 @@ describe('savings reminder retention across server-delivery transitions', () => expect(scheduledGoalIds()).toEqual(['goal-1', 'goal-1']); }); - it('retains existing pendings when a schedule attempt lands while capability is available', async () => { + it('persists new requests scheduled while capability is available', async () => { await scheduleSavingsReminderNotification({ contributionAmount: 500, frequency: 'weekly', @@ -137,6 +138,8 @@ describe('savings reminder retention across server-delivery transitions', () => }); 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, @@ -149,9 +152,9 @@ describe('savings reminder retention across server-delivery transitions', () => await savingsNotificationCapability.clearAvailable(capabilityScope); await activateDueSavingsReminderNotification(); - // goal-1's retained pending re-arms; goal-2 was never stored because the - // server owned delivery at schedule time. - expect(scheduledGoalIds()).toEqual(['goal-1', 'goal-1']); + expect(scheduledGoalIds()).toHaveLength(3); + expect(scheduledGoalIds().filter((id) => id === 'goal-1')).toHaveLength(2); + expect(scheduledGoalIds()).toContain('goal-2'); }); it('retires reminders for goals completed by server auto-debit before re-arming', async () => { @@ -202,4 +205,51 @@ describe('savings reminder retention across server-delivery transitions', () => expect(scheduledGoalIds()).toEqual(['goal-1', 'goal-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']); + }); + + it('skips goal reconciliation 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), + }); + await suppressSavingsReminderNotification(); + mockNotifications.getPermissionsAsync.mockResolvedValue({ + canAskAgain: true, + expires: 'never', + granted: false, + status: 'denied' as PermissionStatus, + }); + + await activateDueSavingsReminderNotification(); + + expect(mockListSavingsGoals).not.toHaveBeenCalled(); + expect(scheduledGoalIds()).toEqual(['goal-1']); + }); }); diff --git a/apps/mobile-storefront/services/savings-reminder-notifications.ts b/apps/mobile-storefront/services/savings-reminder-notifications.ts index ac2a8c3a460..7f8bacec897 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.ts @@ -138,28 +138,29 @@ export function activateDueSavingsReminderNotification() { } /** - * Reconciles due records with current goal state before re-arming. A goal + * Reconciles stored records with current goal state before re-arming. A goal * completed server-side (e.g. auto-debit) bypasses the mobile contribution - * handlers, so its retained pending would otherwise re-arm and remind for a - * finished goal. Terminal-goal records are destroyed; anything unlisted (or + * handlers, so its record — live notification or retained pending — would + * otherwise keep reminding for a finished goal. Terminal-goal records are + * destroyed (live notifications cancelled); anything unlisted (or * unreachable on lookup failure) is kept — a failed lookup must never nuke * reminders. */ async function retireTerminalGoalReminders( notifications: ReturnType, scope: SavingsReminderScope, - due: ReminderRecord[] + records: ReminderRecord[] ): Promise { let goals: Awaited>['goals']; try { goals = (await listSavingsGoals({ merchantId: scope.merchantId })).goals; } catch (error) { log.debug('Unable to reconcile savings reminders with goal state', error); - return due; + return records; } const statusByGoalId = new Map(goals.map((goal) => [goal.id, goal.status])); - const armed: ReminderRecord[] = []; - for (const record of due) { + const live: ReminderRecord[] = []; + for (const record of records) { const status = statusByGoalId.get(record.goalId); if ( status === 'completed' || @@ -173,9 +174,9 @@ async function retireTerminalGoalReminders( ); continue; } - armed.push(record); + live.push(record); } - return armed; + return live; } async function activateDueReminders() { @@ -185,25 +186,34 @@ async function activateDueReminders() { await disposeUnscopedSavingsReminders(notifications); if (await hasServerSavingsNotificationCapability()) { // Suppress, not cancel: the pending requests must survive so local - // reminders re-arm if server delivery is later lost. + // reminders re-arm if server delivery is later lost. Terminal-goal + // retirement is intentionally deferred until a rollback activation; + // retained storage stays bounded to one record per goal. await suppressStoredSavingsReminderNotification(notifications, scope); return null; } const records = await savingsReminderStorage.read(scope); + if (!records.length) return null; + // Local gates before the network: when arming is impossible there is no + // reason to pay for goal reconciliation. 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); + // Reconcile every record, not just due ones: a goal completed while its + // recurring local notification is live must still be retired. + const live = await retireTerminalGoalReminders(notifications, scope, records); // 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( + const due = live.filter( ({ notificationId, pending }) => !notificationId && pending && pending.scheduledAt.getTime() <= Date.now() ); if (!due.length) return null; - const armed = await retireTerminalGoalReminders(notifications, scope, due); - if (!notifications || !(await hasSavingsReminderPermission(notifications))) - return null; - await ensureSavingsReminderChannel(notifications); let notificationId: string | null = null; let failure: unknown; - for (const { pending } of armed) { + for (const { pending } of due) { if (!pending) continue; try { notificationId = await scheduleRecurringSavingsReminder({ @@ -284,6 +294,15 @@ async function scheduleReminder( // 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. + await savingsReminderStorage.write({ + goalId: request.goalId, + merchantId: scope.merchantId, + pending: request, + userId: scope.userId, + }); return null; } if ( From b2a4eff2783267ef155e7c6b57da68a9fbedcf5b Mon Sep 17 00:00:00 2001 From: ogabasseyy Date: Wed, 7 Oct 2026 22:43:38 +0100 Subject: [PATCH 6/8] =?UTF-8?q?fix(pr3640):=20address=20review=20round=206?= =?UTF-8?q?=20=E2=80=94=20activation=20split,=20mutex-free=20fetch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - P1/P2/low: activation extracted to savings-reminder-activation.ts (single export, re-exported for compat); goals snapshot fetched outside runExclusive with arming gates first; scope re-resolved after the network with retirement skipped on account change; scheduling now writes to the current scope (fixed stale-scope write spotted during the move). - P1: reconciliation lives in savings-reminder-goal-reconciliation.ts (single export, snapshot param). - P1: persist-while-suppressed merges into the existing record, preserving a retained live ID when suppression's cancel fails; pinned by a failing-first regression test. - P1: 627-line suite split into scheduling (242), activation (239), scoping (279); service 349 -> 231. All files under 300. --- .../services/savings-reminder-activation.ts | 155 +++++++ .../savings-reminder-goal-reconciliation.ts | 36 ++ ...-reminder-notifications.activation.test.ts | 239 +++++++++++ ...s-reminder-notifications.retention.test.ts | 33 ++ ...ngs-reminder-notifications.scoping.test.ts | 279 +++++++++++++ .../savings-reminder-notifications.test.ts | 389 +----------------- .../savings-reminder-notifications.ts | 116 +----- 7 files changed, 750 insertions(+), 497 deletions(-) create mode 100644 apps/mobile-storefront/services/savings-reminder-activation.ts create mode 100644 apps/mobile-storefront/services/savings-reminder-goal-reconciliation.ts create mode 100644 apps/mobile-storefront/services/savings-reminder-notifications.activation.test.ts create mode 100644 apps/mobile-storefront/services/savings-reminder-notifications.scoping.test.ts 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..8391be015cd --- /dev/null +++ b/apps/mobile-storefront/services/savings-reminder-activation.ts @@ -0,0 +1,155 @@ +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'); + +// Local copy of the notifications module's scope resolution (kept separate +// to avoid a module cycle; must resolve identically to buildReminderScope +// in savings-reminder-notifications.ts). +function resolveReminderScope(): SavingsReminderScope | null { + const { merchantId, user } = useAuthStore.getState(); + const resolvedMerchantId = pickMerchantId(merchantId, CONFIG.MERCHANT_ID); + if (!user?.id || !resolvedMerchantId) return null; + return { merchantId: resolvedMerchantId, userId: user.id }; +} + +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 local arming: when arming is already impossible + // there is no reason to pay for goal reconciliation. The gates run + // again inside the mutex; this outer check only skips the network. + const arming = loadNotificationsModule(); + const canArm = + arming && (await hasSavingsReminderPermission(arming).catch(() => false)); + const terminalGoalIds = canArm + ? await fetchTerminalGoalIds(scope) + : new Set(); + return savingsReminderStorage.runExclusive(() => + activateDueReminders(scope, terminalGoalIds) + ); + })(); +} + +async function activateDueReminders( + scope: SavingsReminderScope, + terminalGoalIds: ReadonlySet +) { + const notifications = loadNotificationsModule(); + await disposeUnscopedSavingsReminders(notifications); + // Re-resolve after the network: operate on the current account, and only + // apply the retirement snapshot when the account didn't change mid-fetch. + const current = resolveReminderScope(); + if (!current) return null; + const retiring = + current.userId === scope.userId && current.merchantId === scope.merchantId + ? terminalGoalIds + : new Set(); + if (await hasServerSavingsNotificationCapability()) { + // Suppress, not cancel: the pending requests must survive so local + // reminders re-arm if server delivery is later lost. Terminal-goal + // retirement is intentionally deferred until a rollback activation; + // retained storage stays bounded to one record per goal. + await suppressStoredSavingsReminderNotification(notifications, current); + return null; + } + const records = await savingsReminderStorage.read(current); + if (!records.length) return null; + // Local gates before arming. 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); + // Reconcile every record, not just due ones: a goal completed while its + // recurring local notification is live must still be retired. + const live = await retireTerminalGoalReminders( + notifications, + current, + records, + retiring + ); + // 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.test.ts b/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts index 8fc5796242f..aca5f380ece 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts @@ -231,6 +231,39 @@ describe('savings reminder retention across server-delivery transitions', () => expect(scheduledGoalIds()).toEqual(['goal-1']); }); + 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); + }); + it('skips goal reconciliation when local arming is impossible', async () => { await scheduleSavingsReminderNotification({ contributionAmount: 500, 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 6f340021c05..2c545a3f389 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.test.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.test.ts @@ -50,18 +50,13 @@ jest.mock('@/lib/customer-savings', () => ({ })); 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' }); @@ -128,28 +123,6 @@ 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('clears scheduled and pending goals for cancel-all', async () => { await scheduleSavingsReminderNotification({ contributionAmount: 500, @@ -173,124 +146,6 @@ describe('savings reminder notification capability', () => { ).toEqual([]); }); - 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('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. @@ -343,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; @@ -530,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.ts b/apps/mobile-storefront/services/savings-reminder-notifications.ts index 7f8bacec897..7bc3468dcae 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.ts @@ -1,6 +1,5 @@ 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'; @@ -8,7 +7,6 @@ import { useAuthStore } from '@/stores/auth-store'; import { ensureSavingsReminderChannel, ensureSavingsReminderPermissions, - hasSavingsReminderPermission, loadNotificationsModule, } from './savings-reminder-native'; import { @@ -19,12 +17,12 @@ import { suppressStoredSavingsReminderNotification, } from './savings-reminder-scheduling'; import { - type ReminderRecord, type SavingsReminderRequest, type SavingsReminderScope, savingsReminderStorage, } from './savings-reminder-storage'; +export { activateDueSavingsReminderNotification } from './savings-reminder-activation'; export type { SavingsReminderScope }; /** @@ -60,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 } @@ -133,102 +121,6 @@ export function cancelScopeSavingsReminders(scope: SavingsReminderScope) { }); } -export function activateDueSavingsReminderNotification() { - return savingsReminderStorage.runExclusive(activateDueReminders); -} - -/** - * Reconciles stored records with current goal state before re-arming. A goal - * completed server-side (e.g. auto-debit) bypasses the mobile contribution - * handlers, so its record — live notification or retained pending — would - * otherwise keep reminding for a finished goal. Terminal-goal records are - * destroyed (live notifications cancelled); anything unlisted (or - * unreachable on lookup failure) is kept — a failed lookup must never nuke - * reminders. - */ -async function retireTerminalGoalReminders( - notifications: ReturnType, - scope: SavingsReminderScope, - records: ReminderRecord[] -): Promise { - let goals: Awaited>['goals']; - try { - goals = (await listSavingsGoals({ merchantId: scope.merchantId })).goals; - } catch (error) { - log.debug('Unable to reconcile savings reminders with goal state', error); - return records; - } - const statusByGoalId = new Map(goals.map((goal) => [goal.id, goal.status])); - const live: ReminderRecord[] = []; - for (const record of records) { - const status = statusByGoalId.get(record.goalId); - if ( - status === 'completed' || - status === 'cancelled' || - status === 'spent' - ) { - await cancelStoredSavingsReminderNotification( - notifications, - scope, - record.goalId - ); - continue; - } - live.push(record); - } - return live; -} - -async function activateDueReminders() { - const scope = resolveReminderScope(); - if (!scope) return null; - const notifications = loadNotificationsModule(); - await disposeUnscopedSavingsReminders(notifications); - if (await hasServerSavingsNotificationCapability()) { - // Suppress, not cancel: the pending requests must survive so local - // reminders re-arm if server delivery is later lost. Terminal-goal - // retirement is intentionally deferred until a rollback activation; - // retained storage stays bounded to one record per goal. - await suppressStoredSavingsReminderNotification(notifications, scope); - return null; - } - const records = await savingsReminderStorage.read(scope); - if (!records.length) return null; - // Local gates before the network: when arming is impossible there is no - // reason to pay for goal reconciliation. 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); - // Reconcile every record, not just due ones: a goal completed while its - // recurring local notification is live must still be retired. - const live = await retireTerminalGoalReminders(notifications, scope, records); - // 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, - }); - } catch (error) { - failure = error; - } - } - if (failure) throw failure; - return notificationId; -} - export function scheduleSavingsReminderNotification({ contributionAmount, frequency, @@ -296,10 +188,14 @@ async function scheduleReminder( 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. + // 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, }); From fefa83a4eaea9b66d79a6dbeca875b388287603b Mon Sep 17 00:00:00 2001 From: ogabasseyy Date: Wed, 7 Oct 2026 23:00:28 +0100 Subject: [PATCH 7/8] =?UTF-8?q?fix(pr3640):=20address=20review=20round=207?= =?UTF-8?q?=20=E2=80=94=20reconcile-all-paths,=20gating,=20parity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - low/P2: retire terminal goals on every activation path (server-owned included) and before the permission gates; abort on mid-fetch account change (auth-change effect refires for the new account); goals fetch gated on stored records so no-reminder users skip it. - low: scope resolution deduplicated via lazy require of the canonical helper (no static cycle, no fallback drift). - low: inbox suppression asserts props/auth-store agreement and skips with a debug log on divergence. - Tests: retention split into transitions (172), reconciliation (218), fetch-gating (175); new server-owned-retire, no-records, mid-switch-abort, and mismatch cases (all observed failing first, incl. fixing a permission-mock leak the split exposed). --- ...avings-notification-inbox.delivery.test.ts | 41 ++++ .../hooks/use-savings-notification-inbox.ts | 23 ++ .../services/savings-reminder-activation.ts | 76 +++--- ...nder-notifications.retention-fetch.test.ts | 175 ++++++++++++++ ...fications.retention-reconciliation.test.ts | 218 ++++++++++++++++++ ...s-reminder-notifications.retention.test.ts | 116 ---------- 6 files changed, 498 insertions(+), 151 deletions(-) create mode 100644 apps/mobile-storefront/services/savings-reminder-notifications.retention-fetch.test.ts create mode 100644 apps/mobile-storefront/services/savings-reminder-notifications.retention-reconciliation.test.ts 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 index 07129d846cf..3fe5dd13e13 100644 --- a/apps/mobile-storefront/hooks/use-savings-notification-inbox.delivery.test.ts +++ b/apps/mobile-storefront/hooks/use-savings-notification-inbox.delivery.test.ts @@ -46,6 +46,16 @@ jest.mock('@/services/savings-reminder-notifications', () => ({ 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'); @@ -81,6 +91,8 @@ const inbox = { 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(); @@ -197,4 +209,33 @@ describe('useSavingsNotificationInbox server-delivery suppression', () => { 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.ts b/apps/mobile-storefront/hooks/use-savings-notification-inbox.ts index 17d27ebae3b..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, @@ -14,6 +17,9 @@ import { updateSavingsNotificationPreferences, } from '@/services/savings-notification-inbox'; import { suppressSavingsReminderNotification } from '@/services/savings-reminder-notifications'; +import { useAuthStore } from '@/stores/auth-store'; + +const log = createLogger('SavingsNotificationInbox'); type InboxState = { error: string | null; @@ -129,6 +135,23 @@ export function useSavingsNotificationInbox({ // the captured scope: the retained pending requests let // local reminders re-arm if server delivery is later lost. if (!active || scopeRef.current !== scope) return; + // 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, diff --git a/apps/mobile-storefront/services/savings-reminder-activation.ts b/apps/mobile-storefront/services/savings-reminder-activation.ts index 8391be015cd..1eba82795d3 100644 --- a/apps/mobile-storefront/services/savings-reminder-activation.ts +++ b/apps/mobile-storefront/services/savings-reminder-activation.ts @@ -23,14 +23,14 @@ import { const log = createLogger('SavingsReminderActivation'); -// Local copy of the notifications module's scope resolution (kept separate -// to avoid a module cycle; must resolve identically to buildReminderScope -// in savings-reminder-notifications.ts). function resolveReminderScope(): SavingsReminderScope | null { const { merchantId, user } = useAuthStore.getState(); - const resolvedMerchantId = pickMerchantId(merchantId, CONFIG.MERCHANT_ID); - if (!user?.id || !resolvedMerchantId) return null; - return { merchantId: resolvedMerchantId, userId: user.id }; + // 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() { @@ -76,15 +76,20 @@ export function activateDueSavingsReminderNotification() { const scope = resolveReminderScope(); if (!scope) return Promise.resolve(null); return (async () => { - // Gate the fetch on local arming: when arming is already impossible - // there is no reason to pay for goal reconciliation. The gates run - // again inside the mutex; this outer check only skips the network. + // Gate the fetch on local arming and on stored records: users with no + // local reminders (or no notification path) skip the goals request + // entirely. The gates run again inside the mutex; these outer checks + // only skip the network. const arming = loadNotificationsModule(); const canArm = arming && (await hasSavingsReminderPermission(arming).catch(() => false)); - const terminalGoalIds = canArm - ? await fetchTerminalGoalIds(scope) - : new Set(); + const probe = canArm + ? await savingsReminderStorage.read(scope).catch(() => null) + : null; + const terminalGoalIds = + canArm && probe?.length + ? await fetchTerminalGoalIds(scope) + : new Set(); return savingsReminderStorage.runExclusive(() => activateDueReminders(scope, terminalGoalIds) ); @@ -97,38 +102,39 @@ async function activateDueReminders( ) { const notifications = loadNotificationsModule(); await disposeUnscopedSavingsReminders(notifications); - // Re-resolve after the network: operate on the current account, and only - // apply the retirement snapshot when the account didn't change mid-fetch. + // 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) return null; - const retiring = - current.userId === scope.userId && current.merchantId === scope.merchantId - ? terminalGoalIds - : new Set(); + 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. Terminal-goal - // retirement is intentionally deferred until a rollback activation; - // retained storage stays bounded to one record per goal. + // reminders re-arm if server delivery is later lost. await suppressStoredSavingsReminderNotification(notifications, current); return null; } - const records = await savingsReminderStorage.read(current); - if (!records.length) return null; - // Local gates before arming. Retirement still runs before arming (never - // backgrounded): arming first would briefly give completed goals live - // notifications that an app kill could leave behind. + 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); - // Reconcile every record, not just due ones: a goal completed while its - // recurring local notification is live must still be retired. - const live = await retireTerminalGoalReminders( - notifications, - current, - records, - retiring - ); // 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( 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..993b05a8d12 --- /dev/null +++ b/apps/mobile-storefront/services/savings-reminder-notifications.retention-fetch.test.ts @@ -0,0 +1,175 @@ +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('skips goal reconciliation 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), + }); + await suppressSavingsReminderNotification(); + mockNotifications.getPermissionsAsync.mockResolvedValue({ + canAskAgain: true, + expires: 'never', + granted: false, + status: 'denied' as PermissionStatus, + }); + + await activateDueSavingsReminderNotification(); + + expect(mockListSavingsGoals).not.toHaveBeenCalled(); + 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 index aca5f380ece..cad99e4cff8 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.retention.test.ts @@ -1,6 +1,5 @@ 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 = { @@ -50,7 +49,6 @@ jest.mock('@/lib/customer-savings', () => ({ const { activateDueSavingsReminderNotification, scheduleSavingsReminderNotification, - suppressSavingsReminderNotification, } = require('./savings-reminder-notifications') as typeof import('./savings-reminder-notifications'); const { savingsNotificationCapability } = @@ -66,24 +64,6 @@ const capabilityScope = { 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) => @@ -157,80 +137,6 @@ describe('savings reminder retention across server-delivery transitions', () => expect(scheduledGoalIds()).toContain('goal-2'); }); - 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 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']); - }); - it('preserves the live notification ID when suppression fails during a server-owned update', async () => { await scheduleSavingsReminderNotification({ contributionAmount: 500, @@ -263,26 +169,4 @@ describe('savings reminder retention across server-delivery transitions', () => expect(record.notificationId).toBe('notification-id'); expect(record.pending?.contributionAmount).toBe(700); }); - - it('skips goal reconciliation 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), - }); - await suppressSavingsReminderNotification(); - mockNotifications.getPermissionsAsync.mockResolvedValue({ - canAskAgain: true, - expires: 'never', - granted: false, - status: 'denied' as PermissionStatus, - }); - - await activateDueSavingsReminderNotification(); - - expect(mockListSavingsGoals).not.toHaveBeenCalled(); - expect(scheduledGoalIds()).toEqual(['goal-1']); - }); }); From 022b54a68a58aa2d6acd2491dc991ceaa87ef431 Mon Sep 17 00:00:00 2001 From: ogabasseyy Date: Wed, 7 Oct 2026 23:08:08 +0100 Subject: [PATCH 8/8] fix(pr3640): retirement runs even when arming is impossible Gate the goals fetch on stored records only, not on the arming gates: a revoked permission must not strand a live notification for a finished goal. Replaces the gates-skip case with a permission-denied terminal-retire pin (fetch runs, live cancelled, record destroyed, nothing scheduled). --- .../services/savings-reminder-activation.ts | 18 +++++++----------- ...inder-notifications.retention-fetch.test.ts | 17 ++++++++++++++--- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/apps/mobile-storefront/services/savings-reminder-activation.ts b/apps/mobile-storefront/services/savings-reminder-activation.ts index 1eba82795d3..de75fee1f7c 100644 --- a/apps/mobile-storefront/services/savings-reminder-activation.ts +++ b/apps/mobile-storefront/services/savings-reminder-activation.ts @@ -76,18 +76,14 @@ export function activateDueSavingsReminderNotification() { const scope = resolveReminderScope(); if (!scope) return Promise.resolve(null); return (async () => { - // Gate the fetch on local arming and on stored records: users with no - // local reminders (or no notification path) skip the goals request - // entirely. The gates run again inside the mutex; these outer checks - // only skip the network. - const arming = loadNotificationsModule(); - const canArm = - arming && (await hasSavingsReminderPermission(arming).catch(() => false)); - const probe = canArm - ? await savingsReminderStorage.read(scope).catch(() => null) - : null; + // 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 = - canArm && probe?.length + probe === null || probe.length ? await fetchTerminalGoalIds(scope) : new Set(); return savingsReminderStorage.runExclusive(() => 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 index 993b05a8d12..6a7afa3b0b9 100644 --- a/apps/mobile-storefront/services/savings-reminder-notifications.retention-fetch.test.ts +++ b/apps/mobile-storefront/services/savings-reminder-notifications.retention-fetch.test.ts @@ -105,7 +105,7 @@ describe('savings reminder fetch gating', () => { }); }); - it('skips goal reconciliation when local arming is impossible', async () => { + it('retires terminal goals even when local arming is impossible', async () => { await scheduleSavingsReminderNotification({ contributionAmount: 500, frequency: 'weekly', @@ -113,17 +113,28 @@ describe('savings reminder fetch gating', () => { goalTitle: 'Phone', scheduledAt: new Date(2020, 5, 8, 9, 30), }); - await suppressSavingsReminderNotification(); 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(); - expect(mockListSavingsGoals).not.toHaveBeenCalled(); + // 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']); });