Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ function ValidateCodeActionContent({
handleSubmitForm,
clearError,
sendValidateCode,
validateCodeReasonCode,
isLoading,
threeDotsMenuItems = [],
onThreeDotsButtonPress = () => {},
Expand All @@ -46,10 +47,12 @@ function ValidateCodeActionContent({
}
firstRenderRef.current = false;

// The validateCode is account-level, so skip sending if one was already requested within the resend window (e.g. a page reload)
// The validateCode is account-level, so skip sending if one was already requested within the resend window (e.g. a page reload).
// When this screen declares a reason, only suppress if the recent request was for the same flow.
const requestedAt = validateCodeAction?.lastValidateCodeRequestedAt;
const sentRecently = !!requestedAt && Date.now() - requestedAt < CONST.REQUEST_CODE_DELAY * CONST.MILLISECONDS_PER_SECOND;
if (sentRecently) {
const sentRecentlyForSameReason = sentRecently && (!validateCodeReasonCode || validateCodeAction?.lastValidateCodeReason === validateCodeReasonCode);
if (sentRecentlyForSameReason) {
return;
}

Expand Down
4 changes: 4 additions & 0 deletions src/components/ValidateCodeActionModal/type.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type {PopoverMenuItem} from '@components/PopoverMenu';

import type {Errors, PendingAction} from '@src/types/onyx/OnyxCommon';
import type {ValidateCodeReason} from '@src/types/onyx/VerifyValidateCodeAction';

type ValidateCodeActionContentProps = {
/** Title of the modal */
Expand Down Expand Up @@ -33,6 +34,9 @@ type ValidateCodeActionContentProps = {
/** Function is called when validate code modal is mounted and on validateCode resend */
sendValidateCode: () => void;

/** When set, a recent request only suppresses the mount-time send if it was for this same reason */
validateCodeReasonCode?: ValidateCodeReason;

/** Whether the form is loading or not */
isLoading?: boolean;

Expand Down
22 changes: 20 additions & 2 deletions src/libs/actions/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ function requestValidateCodeAction(params?: ResendValidateCodeParams) {
key: ONYXKEYS.VALIDATE_ACTION_CODE,
value: {
lastValidateCodeRequestedAt: requestedAt,
lastValidateCodeReason: params?.reasonCode ?? null,
isLoading: true,
pendingFields: {
actionVerified: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
Expand Down Expand Up @@ -557,6 +558,7 @@ function requestValidateCodeAction(params?: ResendValidateCodeParams) {
key: ONYXKEYS.VALIDATE_ACTION_CODE,
value: {
lastValidateCodeRequestedAt: null,
lastValidateCodeReason: null,
isLoading: false,
errorFields: {
actionVerified: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('contacts.genericFailureMessages.requestContactMethodValidateCode'),
Expand Down Expand Up @@ -601,7 +603,7 @@ function validateSecondaryLogin(contactMethod: string, validateCode: string) {
},
},
];
const successData: Array<OnyxUpdate<typeof ONYXKEYS.LOGINS | typeof ONYXKEYS.ACCOUNT>> = [
const successData: Array<OnyxUpdate<typeof ONYXKEYS.LOGINS | typeof ONYXKEYS.ACCOUNT | typeof ONYXKEYS.VALIDATE_ACTION_CODE>> = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.LOGINS,
Expand All @@ -625,6 +627,14 @@ function validateSecondaryLogin(contactMethod: string, validateCode: string) {
validated: true,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.VALIDATE_ACTION_CODE,
value: {
lastValidateCodeRequestedAt: null,
lastValidateCodeReason: null,
Comment on lines +630 to +635

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear the global request stamp only for account validation

When validateSecondaryLogin() is invoked from DynamicContactMethodDetailsPage, the code being validated was sent by requestContactMethodValidateCode() and is tracked on the login, not by VALIDATE_ACTION_CODE. Unconditionally clearing this global stamp therefore erases any unrelated recent account-level code request; returning to that account-code flow within the resend window makes ValidateCodeActionContent send another email instead of deduplicating it. Restrict this cleanup to the VerifyAccountPageBase use case, such as through a caller-controlled flag.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The impact is small and it would make the code more complicated, so I think it's fine to leave as is

},
},
];

const failureData: Array<OnyxUpdate<typeof ONYXKEYS.LOGINS | typeof ONYXKEYS.ACCOUNT>> = [
Expand Down Expand Up @@ -1675,7 +1685,7 @@ function verifyAddSecondaryLoginCode(validateCode: string) {
},
];

const successData: Array<OnyxUpdate<typeof ONYXKEYS.PENDING_CONTACT_ACTION>> = [
const successData: Array<OnyxUpdate<typeof ONYXKEYS.PENDING_CONTACT_ACTION | typeof ONYXKEYS.VALIDATE_ACTION_CODE>> = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PENDING_CONTACT_ACTION,
Expand All @@ -1684,6 +1694,14 @@ function verifyAddSecondaryLoginCode(validateCode: string) {
isLoading: false,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.VALIDATE_ACTION_CODE,
value: {
lastValidateCodeRequestedAt: null,
lastValidateCodeReason: null,
},
},
];

const failureData: Array<OnyxUpdate<typeof ONYXKEYS.PENDING_CONTACT_ACTION>> = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ function DynamicNewContactMethodConfirmValidateCodePage() {
<ValidateCodeActionContent
title={translate('delegate.makeSureItIsYou')}
sendValidateCode={() => requestValidateCodeAction({reasonCode: COMMON_CONST.VALIDATE_CODE_REASONS.ADD_CONTACT_METHOD})}
validateCodeReasonCode={COMMON_CONST.VALIDATE_CODE_REASONS.ADD_CONTACT_METHOD}
descriptionPrimary={translate('contacts.enterSecurityCode', contactMethod)}
validateCodeActionErrorField="addedLogin"
validateError={validateCodeError}
Expand Down
1 change: 1 addition & 0 deletions src/pages/settings/VerifyAccountPageBase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ function VerifyAccountPageBase({navigateBackTo, navigateForwardTo, handleClose,
descriptionPrimary={translate('contacts.featureRequiresValidate')}
descriptionSecondary={translate('contacts.enterSecurityCode', contactMethod)}
sendValidateCode={sendValidateCode}
validateCodeReasonCode={COMMON_CONST.VALIDATE_CODE_REASONS.VALIDATE_ACCOUNT}
validateCodeActionErrorField="validateLogin"
validatePendingAction={loginData?.pendingFields?.validateCodeSent}
handleSubmitForm={handleSubmitForm}
Expand Down
10 changes: 10 additions & 0 deletions src/types/onyx/VerifyValidateCodeAction.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import type {CONST} from 'expensify-common';
import type {ValueOf} from 'type-fest';

import type * as OnyxCommon from './OnyxCommon';

/** The flow a validateCode was requested for */
type ValidateCodeReason = ValueOf<typeof CONST.VALIDATE_CODE_REASONS>;

/** Model of action to receive validateCode */
type VerifyValidateCodeAction = OnyxCommon.OnyxValueWithOfflineFeedback<
{
/** Epoch-ms timestamp of when the validateCode was last requested for any validateCode flow */
lastValidateCodeRequestedAt?: number;

/** The flow the last validateCode was requested for */
lastValidateCodeReason?: ValidateCodeReason | null;

/** Field-specific server side errors keyed by microtime */
errorFields?: OnyxCommon.ErrorFields;

Expand All @@ -16,3 +25,4 @@ type VerifyValidateCodeAction = OnyxCommon.OnyxValueWithOfflineFeedback<
>;

export default VerifyValidateCodeAction;
export type {ValidateCodeReason};
79 changes: 76 additions & 3 deletions tests/actions/UserTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {NewLogin} from '@src/types/onyx';
import {CONST as COMMON_CONST} from 'expensify-common';
import Onyx from 'react-native-onyx';

import * as DeviceActions from '../../src/libs/actions/Device';
import redirectToSignIn from '../../src/libs/actions/SignInRedirect';
import * as UserActions from '../../src/libs/actions/User';
import createMock from '../utils/createMock';
Expand Down Expand Up @@ -254,7 +255,7 @@ describe('actions/User', () => {
const onyxData = mockAPI.write.mock.calls.at(0)?.[2];
const successData = onyxData?.successData ?? [];

expect(successData).toHaveLength(1);
expect(successData).toHaveLength(2);
expect(successData.at(0)).toEqual({
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PENDING_CONTACT_ACTION,
Expand All @@ -263,6 +264,14 @@ describe('actions/User', () => {
isLoading: false,
},
});
expect(successData.at(1)).toEqual({
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.VALIDATE_ACTION_CODE,
value: {
lastValidateCodeRequestedAt: null,
lastValidateCodeReason: null,
},
});
});

it('should have correct failureData structure', async () => {
Expand Down Expand Up @@ -346,8 +355,25 @@ describe('actions/User', () => {
const anyNumber: unknown = expect.any(Number);

expect(mockAPI.write.mock.calls.at(0)?.[0]).toBe(WRITE_COMMANDS.RESEND_VALIDATE_CODE);
expect(optimisticUpdate?.value).toEqual(expect.objectContaining({lastValidateCodeRequestedAt: anyNumber}));
expect(failureUpdate?.value).toEqual(expect.objectContaining({lastValidateCodeRequestedAt: null}));
expect(optimisticUpdate?.value).toEqual(expect.objectContaining({lastValidateCodeRequestedAt: anyNumber, lastValidateCodeReason: null}));
expect(failureUpdate?.value).toEqual(expect.objectContaining({lastValidateCodeRequestedAt: null, lastValidateCodeReason: null}));
});
});

it('should store the reason atomically with the timestamp when a reasonCode is provided', () => {
UserActions.requestValidateCodeAction({reasonCode: COMMON_CONST.VALIDATE_CODE_REASONS.ADD_CONTACT_METHOD});

return waitForBatchedUpdates().then(() => {
const onyxData = mockAPI.write.mock.calls.at(0)?.[2];
const optimisticUpdate = onyxData?.optimisticData?.find((update) => update.key === ONYXKEYS.VALIDATE_ACTION_CODE);
const anyNumber: unknown = expect.any(Number);

expect(optimisticUpdate?.value).toEqual(
expect.objectContaining({
lastValidateCodeRequestedAt: anyNumber,
lastValidateCodeReason: COMMON_CONST.VALIDATE_CODE_REASONS.ADD_CONTACT_METHOD,
}),
);
});
});

Expand Down Expand Up @@ -377,6 +403,53 @@ describe('actions/User', () => {
});
});

describe('validateSecondaryLogin', () => {
beforeEach(() => {
jest.spyOn(DeviceActions, 'getDeviceInfoWithID').mockResolvedValue('{"deviceID":"test-device"}');
});

afterEach(() => {
jest.restoreAllMocks();
});

it('should clear the validate-code stamp in successData alongside validated: true', async () => {
const contactMethod = 'test@example.com';
const validateCode = '123456';

UserActions.validateSecondaryLogin(contactMethod, validateCode);
await waitForBatchedUpdates();

const onyxData = mockAPI.write.mock.calls.at(0)?.[2];
const successData = onyxData?.successData ?? [];
const validateActionCodeUpdate = successData.find((update) => update.key === ONYXKEYS.VALIDATE_ACTION_CODE);
const accountUpdate = successData.find((update) => update.key === ONYXKEYS.ACCOUNT);

expect(validateActionCodeUpdate).toEqual({
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.VALIDATE_ACTION_CODE,
value: {
lastValidateCodeRequestedAt: null,
lastValidateCodeReason: null,
},
});
expect(accountUpdate?.value).toEqual(expect.objectContaining({validated: true}));
});

it('should not clear the validate-code stamp in failureData', async () => {
const contactMethod = 'test@example.com';
const validateCode = '123456';

UserActions.validateSecondaryLogin(contactMethod, validateCode);
await waitForBatchedUpdates();

const onyxData = mockAPI.write.mock.calls.at(0)?.[2];
const failureData = onyxData?.failureData ?? [];
const validateActionCodeUpdate = failureData.find((update) => update.key === ONYXKEYS.VALIDATE_ACTION_CODE);

expect(validateActionCodeUpdate).toBeUndefined();
});
});

describe('addNewContactMethod', () => {
it('should call API.write with correct parameters when validateCode is provided', async () => {
// Given a contact method and validate code
Expand Down
103 changes: 103 additions & 0 deletions tests/ui/ValidateCodeActionContentTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import {render} from '@testing-library/react-native';

import ComposeProviders from '@components/ComposeProviders';
import {LocaleContextProvider} from '@components/LocaleContextProvider';
import ValidateCodeActionContent from '@components/ValidateCodeActionModal/ValidateCodeActionContent';

import ONYXKEYS from '@src/ONYXKEYS';

import type {ValueOf} from 'type-fest';

import {CONST as COMMON_CONST} from 'expensify-common';
import Onyx from 'react-native-onyx';

import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';

jest.mock('@components/ValidateCodeActionModal/ValidateCodeForm', () => 'ValidateCodeForm');

const defaultProps = {
title: 'Validate',
descriptionPrimary: 'Enter the code',
validateCodeActionErrorField: 'addedLogin',
handleSubmitForm: () => {},
clearError: () => {},
};

function renderValidateCodeActionContent(sendValidateCode: jest.Mock, validateCodeReasonCode?: ValueOf<typeof COMMON_CONST.VALIDATE_CODE_REASONS>) {
return render(
<ComposeProviders components={[LocaleContextProvider]}>
<ValidateCodeActionContent
{...defaultProps}
sendValidateCode={sendValidateCode}
validateCodeReasonCode={validateCodeReasonCode}
/>
</ComposeProviders>,
);
}

describe('ValidateCodeActionContent', () => {
beforeAll(() => {
Onyx.init({
keys: ONYXKEYS,
});
});

beforeEach(() => {
jest.clearAllMocks();
return Onyx.clear().then(waitForBatchedUpdates);
});

it('sends a code when a recent request was for a different reason', async () => {
const sendValidateCode = jest.fn();

await Onyx.merge(ONYXKEYS.VALIDATE_ACTION_CODE, {
lastValidateCodeRequestedAt: Date.now(),
lastValidateCodeReason: COMMON_CONST.VALIDATE_CODE_REASONS.VALIDATE_ACCOUNT,
});
await waitForBatchedUpdates();

renderValidateCodeActionContent(sendValidateCode, COMMON_CONST.VALIDATE_CODE_REASONS.ADD_CONTACT_METHOD);
await waitForBatchedUpdates();

expect(sendValidateCode).toHaveBeenCalledTimes(1);
});

it('does not resend when a recent request was for the same reason', async () => {
const sendValidateCode = jest.fn();

await Onyx.merge(ONYXKEYS.VALIDATE_ACTION_CODE, {
lastValidateCodeRequestedAt: Date.now(),
lastValidateCodeReason: COMMON_CONST.VALIDATE_CODE_REASONS.ADD_CONTACT_METHOD,
});
await waitForBatchedUpdates();

renderValidateCodeActionContent(sendValidateCode, COMMON_CONST.VALIDATE_CODE_REASONS.ADD_CONTACT_METHOD);
await waitForBatchedUpdates();

expect(sendValidateCode).not.toHaveBeenCalled();
});

it('sends a code when nothing was requested recently', async () => {
const sendValidateCode = jest.fn();

renderValidateCodeActionContent(sendValidateCode, COMMON_CONST.VALIDATE_CODE_REASONS.ADD_CONTACT_METHOD);
await waitForBatchedUpdates();

expect(sendValidateCode).toHaveBeenCalledTimes(1);
});

it('does not resend when no reason is declared and a code was requested recently', async () => {
const sendValidateCode = jest.fn();

await Onyx.merge(ONYXKEYS.VALIDATE_ACTION_CODE, {
lastValidateCodeRequestedAt: Date.now(),
lastValidateCodeReason: COMMON_CONST.VALIDATE_CODE_REASONS.VALIDATE_ACCOUNT,
});
await waitForBatchedUpdates();

renderValidateCodeActionContent(sendValidateCode);
await waitForBatchedUpdates();

expect(sendValidateCode).not.toHaveBeenCalled();
});
});
Loading