diff --git a/packages/react-native/src/lib/common/setup.ts b/packages/react-native/src/lib/common/setup.ts index f4addc7..77058af 100644 --- a/packages/react-native/src/lib/common/setup.ts +++ b/packages/react-native/src/lib/common/setup.ts @@ -89,14 +89,14 @@ async function syncUserStateIfExpired( configInput: { appUrl: string; workspaceId: string }, logger: ReturnType, existingConfig?: TConfig, -): Promise> { +): Promise { const userState = existingConfig?.user; if (userState && !userState.expiresAt) { - return ok(userState); + return userState; } if (userState?.expiresAt && !isNowExpired(userState.expiresAt)) { - return ok(userState); + return userState; } logger.debug("Person state expired. Syncing."); @@ -110,24 +110,20 @@ async function syncUserStateIfExpired( }, }); if (updatesResponse.ok) { - return ok(updatesResponse.data.state); + return updatesResponse.data.state; } logger.error( `Error updating user state: ${updatesResponse.error.code} - ${updatesResponse.error.responseMessage ?? ""}`, ); - return err({ - code: "network_error", - message: "Error updating user state", - status: 500, - url: new URL( - `${configInput.appUrl}/api/v2/client/${configInput.workspaceId}/user`, - ), - responseMessage: "Unknown error", - } as const); + // A failed sync must not stop setup: keep the saved user and try again in 30 minutes. + return { + ...userState, + expiresAt: new Date(Date.now() + 30 * 60000), + }; } - return ok(DEFAULT_USER_STATE_NO_USER_ID); + return DEFAULT_USER_STATE_NO_USER_ID; } // Helper: Update app config with synced states @@ -313,7 +309,6 @@ export const setup = async ( if (shouldSyncConfig(existingConfig, resolvedInput)) { logger.debug("Configuration fits setup parameters."); let workspace: TWorkspaceState | undefined; - let userState: TUserState | undefined; try { const workspaceResult = await syncWorkspaceStateIfExpired( @@ -328,18 +323,12 @@ export const setup = async ( return err(workspaceResult.error); } - const userStateResult = await syncUserStateIfExpired( + const userState = await syncUserStateIfExpired( resolvedInput, logger, existingConfig, ); - if (userStateResult.ok) { - userState = userStateResult.data; - } else { - return err(userStateResult.error); - } - updateAppConfigWithSyncedStates( appConfig, workspace, diff --git a/packages/react-native/src/lib/common/tests/setup.test.ts b/packages/react-native/src/lib/common/tests/setup.test.ts index f70b44c..f5c60be 100644 --- a/packages/react-native/src/lib/common/tests/setup.test.ts +++ b/packages/react-native/src/lib/common/tests/setup.test.ts @@ -9,6 +9,7 @@ import { test, vi, } from "vitest"; +import { CommandQueue } from "@/lib/common/command-queue"; import { RN_ASYNC_STORAGE_KEY, RNConfig } from "@/lib/common/config"; import { addCleanupEventListeners, @@ -25,9 +26,13 @@ import { } from "@/lib/common/setup"; import type * as CommonUtilsModule from "@/lib/common/utils"; import { filterSurveys, isNowExpired } from "@/lib/common/utils"; +import { trackAction } from "@/lib/survey/action"; +import { SurveyStore } from "@/lib/survey/store"; import { DEFAULT_USER_STATE_NO_USER_ID } from "@/lib/user/state"; import { sendUpdatesToBackend } from "@/lib/user/update"; import { fetchWorkspaceState } from "@/lib/workspace/state"; +import type { TUserState, TWorkspaceState } from "@/types/config"; +import type { TSurvey } from "@/types/survey"; // 1) Mock AsyncStorage vi.mock("@react-native-async-storage/async-storage", () => ({ @@ -88,6 +93,11 @@ vi.mock("@/lib/user/update", () => ({ sendUpdatesToBackend: vi.fn(), })); +// 8) Mock netinfo, which the survey action module imports +vi.mock("@react-native-community/netinfo", () => ({ + fetch: vi.fn(), +})); + describe("setup.ts", () => { let getInstanceConfigMock: MockInstance<() => Promise>; let getInstanceLoggerMock: MockInstance<() => Logger>; @@ -468,58 +478,171 @@ describe("setup.ts", () => { expect(sendUpdatesToBackend).not.toHaveBeenCalled(); }); - test("returns an error when user sync fails", async () => { - const mockConfig = { - get: vi.fn().mockReturnValue({ + test("finishes setup with the saved user when the user sync fails, so track can show a survey", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + try { + const now = new Date("2026-01-01T12:00:00Z"); + vi.setSystemTime(now); + + const survey = { + id: "survey_1", + displayPercentage: null, + triggers: [{ actionClass: { name: "checkout" } }], + } as unknown as TSurvey; + const savedUser: TUserState = { + data: { + userId: "user_abc", + contactId: "contact_abc", + segments: ["segment_1"], + displays: [], + responses: [], + lastDisplayAt: null, + }, + expiresAt: new Date(now.getTime() - 5000), + }; + let storedConfig = { workspaceId: "env_123", appUrl: "https://my.url", workspace: { - data: { surveys: [] }, - expiresAt: new Date(Date.now() + 60_000), + data: { surveys: [survey], actionClasses: [] }, + expiresAt: new Date(now.getTime() + 60_000), }, - user: { - data: { - userId: "user_abc", - contactId: null, - segments: [], - displays: [], - responses: [], - lastDisplayAt: null, - }, - expiresAt: new Date(Date.now() - 5000), + user: savedUser, + filteredSurveys: [], + status: { value: "success", expiresAt: null }, + }; + const mockConfig = { + get: vi.fn(() => storedConfig), + update: vi.fn((next: typeof storedConfig) => { + storedConfig = next; + }), + }; + + getInstanceConfigMock.mockReturnValue( + mockConfig as unknown as Promise, + ); + const actual = + await vi.importActual("@/lib/common/utils"); + (isNowExpired as unknown as Mock).mockImplementation( + actual.isNowExpired, + ); + (filterSurveys as unknown as Mock).mockImplementation( + (workspace: TWorkspaceState) => workspace.data.surveys, + ); + (sendUpdatesToBackend as unknown as Mock).mockResolvedValueOnce({ + ok: false, + error: { code: "network_error", message: "User sync failed" }, + }); + + const result = await setup({ + workspaceId: "env_123", + appUrl: "https://my.url", + }); + + expect(result.ok).toBe(true); + expect(sendUpdatesToBackend).toHaveBeenCalledTimes(1); + // The saved user is kept and its expiry is pushed 30 min ahead. + expect(storedConfig.user).toEqual({ + data: savedUser.data, + expiresAt: new Date(now.getTime() + 30 * 60_000), + }); + + const queue = new CommandQueue(); + queue.add(trackAction, true, "checkout"); + await queue.wait(); + + expect(SurveyStore.getInstance().getSurvey()).toBe(survey); + } finally { + SurveyStore.getInstance().resetSurvey(); + (isNowExpired as unknown as Mock).mockReset(); + vi.useRealTimers(); + } + }); + + describe("saved user state at setup", () => { + const now = new Date("2026-01-01T12:00:00Z"); + + const setupWithSavedUser = async (user: TUserState) => { + let storedConfig = { + workspaceId: "env_123", + appUrl: "https://my.url", + workspace: { + data: { surveys: [], actionClasses: [] }, + expiresAt: new Date(now.getTime() + 60_000), }, + user, filteredSurveys: [], status: { value: "success", expiresAt: null }, - }), - update: vi.fn(), + }; + getInstanceConfigMock.mockReturnValue({ + get: vi.fn(() => storedConfig), + update: vi.fn((next: typeof storedConfig) => { + storedConfig = next; + }), + } as unknown as Promise); + const actual = + await vi.importActual("@/lib/common/utils"); + (isNowExpired as unknown as Mock).mockImplementation( + actual.isNowExpired, + ); + (filterSurveys as unknown as Mock).mockReturnValue([]); + + const result = await setup({ + workspaceId: "env_123", + appUrl: "https://my.url", + }); + return { result, storedUser: storedConfig.user }; }; - getInstanceConfigMock.mockReturnValue( - mockConfig as unknown as Promise, - ); - (isNowExpired as unknown as Mock) - .mockReturnValueOnce(false) - .mockReturnValueOnce(true); - (sendUpdatesToBackend as unknown as Mock).mockResolvedValueOnce({ - ok: false, - error: { - code: "network_error", - message: "User sync failed", - }, + beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(now); }); - const result = await setup({ - environmentId: "env_123", - appUrl: "https://my.url", + afterEach(() => { + (isNowExpired as unknown as Mock).mockReset(); + vi.useRealTimers(); }); - expect(result.ok).toBe(false); - if (!result.ok) { - expect(result.error.code).toBe("network_error"); - expect("message" in result.error && result.error.message).toBe( - "Error updating user state", - ); - } + test("keeps a saved user that hasn't expired, without syncing it", async () => { + const savedUser: TUserState = { + data: { + userId: "user_abc", + contactId: "contact_abc", + segments: ["segment_1"], + displays: [], + responses: [], + lastDisplayAt: null, + }, + expiresAt: new Date(now.getTime() + 5000), + }; + + const { result, storedUser } = await setupWithSavedUser(savedUser); + + expect(result.ok).toBe(true); + expect(sendUpdatesToBackend).not.toHaveBeenCalled(); + expect(storedUser).toEqual(savedUser); + }); + + test("resets an expired saved user without a userId to the default, without syncing", async () => { + const savedUser: TUserState = { + data: { + userId: null, + contactId: null, + segments: [], + displays: [], + responses: [], + lastDisplayAt: null, + }, + expiresAt: new Date(now.getTime() - 5000), + }; + + const { result, storedUser } = await setupWithSavedUser(savedUser); + + expect(result.ok).toBe(true); + expect(sendUpdatesToBackend).not.toHaveBeenCalled(); + expect(storedUser).toEqual(DEFAULT_USER_STATE_NO_USER_ID); + }); }); test("resets config if no valid config found, fetches workspace state, sets default user", async () => {