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
18 changes: 17 additions & 1 deletion src/libs/actions/IOU/TrackExpense.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2163,7 +2163,16 @@ function categorizeTrackedExpense(trackedExpenseParams: TrackedExpenseParams) {
}

function shareTrackedExpense(trackedExpenseParams: TrackedExpenseParams) {
const {onyxData: trackedExpenseOnyxData, reportInformation, transactionParams, policyParams, createdWorkspaceParams, accountantParams, currentUserAccountID} = trackedExpenseParams;
const {
onyxData: trackedExpenseOnyxData,
reportInformation,
transactionParams,
policyParams,
createdWorkspaceParams,
accountantParams,
currentUserAccountID,
reportActionsList,
} = trackedExpenseParams;

const policyID = policyParams?.policyID;
const chatReportID = reportInformation?.chatReportID;
Expand Down Expand Up @@ -2231,6 +2240,9 @@ function shareTrackedExpense(trackedExpenseParams: TrackedExpenseParams) {
CONST.POLICY.ROLE.ADMIN,
formatPhoneNumber,
currentUserAccountID,
undefined,
undefined,
reportActionsList,
);
onyxData.optimisticData?.push(...addAccountantToWorkspaceOptimisticData);
onyxData.successData?.push(...addAccountantToWorkspaceSuccessData);
Expand Down Expand Up @@ -2312,6 +2324,7 @@ function trackExpense(params: CreateTrackExpenseParams) {
isSelfTourViewed,
defaultWorkspaceName,
previousOdometerDraft,
reportActionsList,
} = params;
const {participant, payeeAccountID, payeeEmail} = participantParams;
const {policy, policyCategories, policyTagList} = policyData;
Expand Down Expand Up @@ -2358,6 +2371,8 @@ function trackExpense(params: CreateTrackExpenseParams) {
report,
isDraftPolicy,
action,
// Strip reportActionsList from retryParams to keep the serialized error JSON small.
reportActionsList: undefined,
participantParams: {
participant,
payeeAccountID,
Expand Down Expand Up @@ -2597,6 +2612,7 @@ function trackExpense(params: CreateTrackExpenseParams) {
accountantParams,
currentUserAccountID: currentUserAccountIDParam,
currentUserEmail: currentUserEmailParam,
reportActionsList,
};
shareTrackedExpense(trackedExpenseParams);
break;
Expand Down
4 changes: 3 additions & 1 deletion src/libs/actions/IOU/types/CreateTrackExpenseParams.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type {OnyxEntry} from 'react-native-onyx';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import type {IOUAction} from '@src/CONST';
import type * as OnyxTypes from '@src/types/onyx';
import type {Accountant} from '@src/types/onyx/IOU';
Expand Down Expand Up @@ -34,6 +34,8 @@ type CreateTrackExpenseParams = {
isSelfTourViewed: boolean;
defaultWorkspaceName?: string;
previousOdometerDraft?: OnyxEntry<OnyxTypes.OdometerDraft>;
// TODO: Remove optional (?) once all callers are updated in follow-up PRs of https://github.com/Expensify/App/issues/66578
reportActionsList?: OnyxCollection<OnyxTypes.ReportActions>;
};

export type {CreateTrackExpenseParams, TrackExpenseAccountantParams};
4 changes: 3 additions & 1 deletion src/libs/actions/IOU/types/TrackedExpenseParams.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type {OnyxEntry} from 'react-native-onyx';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import type {CreateWorkspaceParams} from '@libs/API/parameters';
import type {BuildPolicyDataKeys} from '@userActions/Policy/Policy';
import type ONYXKEYS from '@src/ONYXKEYS';
Expand Down Expand Up @@ -66,6 +66,8 @@ type TrackedExpenseParams = {
accountantParams?: TrackExpenseAccountantParams;
currentUserAccountID: number;
currentUserEmail?: string;
// TODO: Remove optional (?) once all callers are updated in follow-up PRs of https://github.com/Expensify/App/issues/66578
reportActionsList?: OnyxCollection<OnyxTypes.ReportActions>;
};

export type {TrackedExpenseParams, TrackedExpensePolicyParams, TrackedExpenseTransactionParams, TrackedExpenseReportInformation, BuildOnyxDataForTrackExpenseKeys};
1 change: 1 addition & 0 deletions src/libs/actions/Policy/Policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3054,6 +3054,7 @@ function buildPolicyData(options: BuildPolicyDataOptions): OnyxData<BuildPolicyD
policyID,
{[adminParticipant.login]: adminParticipant.accountID ?? CONST.DEFAULT_NUMBER_ID},
currentUserAccountIDParam,
// reportActionsList is intentionally undefined. See https://github.com/Expensify/App/pull/88312#issuecomment-4286942084
undefined,
hasOutstandingChildRequest,
);
Expand Down
3 changes: 1 addition & 2 deletions src/libs/actions/Report/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7665,8 +7665,7 @@ function changeReportPolicyAndInviteSubmitter({
formatPhoneNumber: LocaleContextProps['formatPhoneNumber'];
isReportLastVisibleArchived: boolean | undefined;
reportNextStep: OnyxEntry<ReportNextStepDeprecated>;
// TODO: Remove optional (?) once all callers are updated in follow-up PRs of https://github.com/Expensify/App/issues/66578
reportActionsList?: OnyxCollection<ReportActions>;
reportActionsList: OnyxCollection<ReportActions>;
}) {
if (!report.reportID || !policy?.id || report.policyID === policy.id || !isExpenseReport(report) || !report.ownerAccountID) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {hasSeenTourSelector} from '@selectors/Onboarding';
import {useEffect, useRef, useState} from 'react';
import type {OnyxEntry} from 'react-native-onyx';
import useActivePolicy from '@hooks/useActivePolicy';
import useAllPolicyExpenseChatReportActions from '@hooks/useAllPolicyExpenseChatReportActions';
import useLastWorkspaceNumber from '@hooks/useLastWorkspaceNumber';
import useLocalize from '@hooks/useLocalize';
import useOnboardingTaskInformation from '@hooks/useOnboardingTaskInformation';
Expand Down Expand Up @@ -183,6 +184,7 @@ function useExpenseSubmission(params: UseExpenseSubmissionParams) {
const [recentlyUsedDestinations] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_DESTINATIONS}${policyID}`);
const lastWorkspaceNumber = useLastWorkspaceNumber();
const activePolicy = useActivePolicy();
const policyExpenseChatReportActions = useAllPolicyExpenseChatReportActions();

// Reports
const [selfDMReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${findSelfDMReportID()}`);
Expand Down Expand Up @@ -536,6 +538,7 @@ function useExpenseSubmission(params: UseExpenseSubmissionParams) {
isSelfTourViewed,
defaultWorkspaceName: generateDefaultWorkspaceName(email, lastWorkspaceNumber, translate),
previousOdometerDraft: odometerDraft,
reportActionsList: policyExpenseChatReportActions,

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 Preserve the report-actions fallback until loaded

When this confirmation screen mounts before useAllPolicyExpenseChatReportActions() has received the report-actions collection, the hook returns {} rather than undefined; passing that empty object here makes createPolicyExpenseChats() choose the explicit empty map over its reportActionsList ?? deprecatedAllReportActions fallback. In the share-with-accountant path where the accountant is newly added but already has an archived policy expense chat, that skips the REPORT_PREVIEW actions and leaves the nested expense reports archived. Please pass undefined until the collection is actually loaded, or otherwise let the callee fall back.

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.

@DylanDylann, thoughts on this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This comment is about the function being triggered before the data is loaded. If that's a problem, using onyx.connect as before would also cause the same issue. However, I don't think we need to worry about this because the function needs to be triggered by user actions. Therefore, it shouldn't be executed during the initial phase when the data hasn't been loaded yet

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@Gonals Back to you

});
}
}
Expand Down
167 changes: 167 additions & 0 deletions tests/actions/IOUTest/TrackExpenseTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,173 @@ describe('actions/IOU/TrackExpense', () => {
expect(announceChat?.writeCapability).toBe(CONST.REPORT.WRITE_CAPABILITIES.ADMINS);
});

it('share with accountant not archived existing expense report via the explicit reportActionsList param (not the deprecated onyx fallback)', async () => {
// Given a policy without the accountant + an existing (orphaned) archived expense chat for the accountant + an archived nested expense report.
// The REPORT_PREVIEW action that links the chat to the expense report is supplied via the explicit reportActionsList,
// not seeded into ONYXKEYS.COLLECTION.REPORT_ACTIONS. Proves the explicit param wins over the deprecatedAllReportActions Onyx fallback.
const accountant: Required<Accountant> = {login: VIT_EMAIL, accountID: VIT_ACCOUNT_ID};
const policy: Policy = {...createRandomPolicy(1), id: 'ABC', employeeList: {}};
const selfDMReport: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.SELF_DM),
reportID: '10',
};
const ownPolicyExpenseChat: Report = {
...createRandomReport(1, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT),
reportID: '123',
policyID: policy.id,
type: CONST.REPORT.TYPE.CHAT,
isOwnPolicyExpenseChat: true,
};
// Orphaned policy expense chat for the accountant: the accountant was removed from the workspace but the chat still exists.
const accountantExpenseChatID = '777';
const accountantExpenseChat: Report = {
...createRandomReport(2, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT),
reportID: accountantExpenseChatID,
policyID: policy.id,
ownerAccountID: accountant.accountID,
type: CONST.REPORT.TYPE.CHAT,
};
const archivedExpenseReportID = '888';
const transaction: Transaction = {...createRandomTransaction(1), transactionID: '555'};

await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${ownPolicyExpenseChat.reportID}`, ownPolicyExpenseChat);
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${accountantExpenseChat.reportID}`, accountantExpenseChat);
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${accountantExpenseChatID}`, {private_isArchived: DateUtils.getDBTime()});
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${archivedExpenseReportID}`, {private_isArchived: DateUtils.getDBTime()});
await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transaction.transactionID}`, transaction);
await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {[accountant.accountID]: accountant});

// Build the REPORT_PREVIEW action OUTSIDE Onyx and pass it explicitly.
// If the implementation falls back to deprecatedAllReportActions (Onyx) instead of using this explicit param,
// the unarchive failure-data entry will not be generated and the assertion below will fail.
const reportPreviewAction: ReportAction = {
reportActionID: 'preview-1',
actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW,
childReportID: archivedExpenseReportID,
created: DateUtils.getDBTime(),
message: [],
} as unknown as ReportAction;
const explicitReportActionsList = {
[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${accountantExpenseChatID}`]: {
[reportPreviewAction.reportActionID]: reportPreviewAction,
},
};

const recentWaypoints = (await getOnyxValue(ONYXKEYS.NVP_RECENT_WAYPOINTS)) ?? [];

// Create the tracked expense first
trackExpense({
report: selfDMReport,
isDraftPolicy: true,
action: CONST.IOU.ACTION.CREATE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {accountID: RORY_ACCOUNT_ID},
},
transactionParams: {
amount: transaction.amount,
currency: transaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: transaction.merchant,
billable: false,
},
isASAPSubmitBetaEnabled: false,
currentUserAccountIDParam: RORY_ACCOUNT_ID,
currentUserEmailParam: RORY_EMAIL,
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
draftTransactionIDs: [transaction.transactionID],
isSelfTourViewed: false,
});
await waitForBatchedUpdates();

const selfDMReportActionsOnyx = await new Promise<OnyxEntry<ReportActions>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${selfDMReport.reportID}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});

const linkedTrackedExpenseReportAction = Object.values(selfDMReportActionsOnyx ?? {}).find((reportAction) => isMoneyRequestAction(reportAction));
const reportActionableTrackExpense = Object.values(selfDMReportActionsOnyx ?? {}).find((reportAction) => isActionableTrackExpense(reportAction));

mockFetch?.pause?.();

// When sharing the tracked expense with the accountant, passing the explicit reportActionsList
trackExpense({
report: ownPolicyExpenseChat,
isDraftPolicy: false,
action: CONST.IOU.ACTION.SHARE,
participantParams: {
payeeEmail: RORY_EMAIL,
payeeAccountID: RORY_ACCOUNT_ID,
participant: {reportID: ownPolicyExpenseChat.reportID, isPolicyExpenseChat: true},
},
policyParams: {
policy,
},
transactionParams: {
amount: transaction.amount,
currency: transaction.currency,
created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING),
merchant: transaction.merchant,
billable: false,
actionableWhisperReportActionID: reportActionableTrackExpense?.reportActionID,
linkedTrackedExpenseReportAction,
linkedTrackedExpenseReportID: selfDMReport.reportID,
},
accountantParams: {
accountant,
},
reportActionsList: explicitReportActionsList,
isASAPSubmitBetaEnabled: false,
currentUserAccountIDParam: RORY_ACCOUNT_ID,
currentUserEmailParam: RORY_EMAIL,
introSelected: undefined,
quickAction: undefined,
recentWaypoints,
betas: [CONST.BETAS.ALL],
draftTransactionIDs: [],
isSelfTourViewed: false,
});
await waitForBatchedUpdates();

// Then the orphaned accountant expense chat AND the nested expense report should both be optimistically not archived
const accountantChatNvpAfter = await new Promise<OnyxEntry<{private_isArchived?: string | null}>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${accountantExpenseChatID}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});
const expenseReportNvpAfter = await new Promise<OnyxEntry<{private_isArchived?: string | null}>>((resolve) => {
const connection = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${archivedExpenseReportID}`,
waitForCollectionCallback: false,
callback: (value) => {
Onyx.disconnect(connection);
resolve(value);
},
});
});

await mockFetch?.resume?.();

expect(accountantChatNvpAfter?.private_isArchived).toBeFalsy();
expect(expenseReportNvpAfter?.private_isArchived).toBeFalsy();
});

/**
* Creates default trackExpense parameters - only override what's needed for each test
*/
Expand Down
8 changes: 8 additions & 0 deletions tests/actions/ReportTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3424,6 +3424,7 @@ describe('actions/Report', () => {
formatPhoneNumber: TestHelper.formatPhoneNumber,
isReportLastVisibleArchived: undefined,
reportNextStep: undefined,
reportActionsList: {},
});
await waitForBatchedUpdates();

Expand Down Expand Up @@ -3511,6 +3512,7 @@ describe('actions/Report', () => {
formatPhoneNumber: TestHelper.formatPhoneNumber,
isReportLastVisibleArchived: false,
reportNextStep: undefined,
reportActionsList: {},
});
await waitForBatchedUpdates();

Expand Down Expand Up @@ -3553,6 +3555,7 @@ describe('actions/Report', () => {
formatPhoneNumber: TestHelper.formatPhoneNumber,
isReportLastVisibleArchived: undefined,
reportNextStep: undefined,
reportActionsList: {},
});
await waitForBatchedUpdates();

Expand Down Expand Up @@ -3581,6 +3584,7 @@ describe('actions/Report', () => {
formatPhoneNumber: TestHelper.formatPhoneNumber,
isReportLastVisibleArchived: undefined,
reportNextStep: undefined,
reportActionsList: {},
});
await waitForBatchedUpdates();

Expand Down Expand Up @@ -3608,6 +3612,7 @@ describe('actions/Report', () => {
formatPhoneNumber: TestHelper.formatPhoneNumber,
isReportLastVisibleArchived: undefined,
reportNextStep: undefined,
reportActionsList: {},
});
await waitForBatchedUpdates();

Expand Down Expand Up @@ -3635,6 +3640,7 @@ describe('actions/Report', () => {
formatPhoneNumber: TestHelper.formatPhoneNumber,
isReportLastVisibleArchived: undefined,
reportNextStep: undefined,
reportActionsList: {},
});
await waitForBatchedUpdates();

Expand Down Expand Up @@ -3664,6 +3670,7 @@ describe('actions/Report', () => {
formatPhoneNumber: TestHelper.formatPhoneNumber,
isReportLastVisibleArchived: undefined,
reportNextStep: undefined,
reportActionsList: {},
});
await waitForBatchedUpdates();

Expand Down Expand Up @@ -3714,6 +3721,7 @@ describe('actions/Report', () => {
formatPhoneNumber: TestHelper.formatPhoneNumber,
isReportLastVisibleArchived: false,
reportNextStep: undefined,
reportActionsList: {},
});
await waitForBatchedUpdates();

Expand Down
Loading