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
2 changes: 2 additions & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,8 @@
"moveElemsAttrsToGroup",
"removeHiddenElems",
"moveGroupAttrsToElems",
"Dtype",
"Areport",
"mple",
"Selec"
],
Expand Down
73 changes: 58 additions & 15 deletions src/libs/ReportUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
import {getForReportAction, getMovedReportID} from './ModifiedExpenseMessage';
import getStateFromPath from './Navigation/helpers/getStateFromPath';
import {isFullScreenName} from './Navigation/helpers/isNavigatorName';
import isSearchTopmostFullScreenRoute from './Navigation/helpers/isSearchTopmostFullScreenRoute';
import {linkingConfig} from './Navigation/linkingConfig';
import Navigation, {navigationRef} from './Navigation/Navigation';
import type {MoneyRequestNavigatorParamList, ReportsSplitNavigatorParamList} from './Navigation/types';
Expand Down Expand Up @@ -928,7 +929,7 @@
const parsedReportActionMessageCache: Record<string, string> = {};

let conciergeReportID: OnyxEntry<string>;
Onyx.connect({

Check warning on line 932 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.CONCIERGE_REPORT_ID,
callback: (value) => {
conciergeReportID = value;
Expand All @@ -936,7 +937,7 @@
});

const defaultAvatarBuildingIconTestID = 'SvgDefaultAvatarBuilding Icon';
Onyx.connect({

Check warning on line 940 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.SESSION,
callback: (value) => {
// When signed out, val is undefined
Expand All @@ -954,7 +955,7 @@
let allPersonalDetails: OnyxEntry<PersonalDetailsList>;
let allPersonalDetailLogins: string[];
let currentUserPersonalDetails: OnyxEntry<PersonalDetails>;
Onyx.connect({

Check warning on line 958 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (value) => {
if (currentUserAccountID) {
Expand All @@ -966,14 +967,14 @@
});

let allReportsDraft: OnyxCollection<Report>;
Onyx.connect({

Check warning on line 970 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT_DRAFT,
waitForCollectionCallback: true,
callback: (value) => (allReportsDraft = value),
});

let allPolicies: OnyxCollection<Policy>;
Onyx.connect({

Check warning on line 977 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.POLICY,
waitForCollectionCallback: true,
callback: (value) => (allPolicies = value),
Expand All @@ -981,7 +982,7 @@

let allReports: OnyxCollection<Report>;
let reportsByPolicyID: ReportByPolicyMap;
Onyx.connect({

Check warning on line 985 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (value) => {
Expand Down Expand Up @@ -1024,14 +1025,14 @@
});

let allBetas: OnyxEntry<Beta[]>;
Onyx.connect({

Check warning on line 1028 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.BETAS,
callback: (value) => (allBetas = value),
});

let allTransactions: OnyxCollection<Transaction> = {};
let reportsTransactions: Record<string, Transaction[]> = {};
Onyx.connect({

Check warning on line 1035 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -1057,7 +1058,7 @@
});

let allReportActions: OnyxCollection<ReportActions>;
Onyx.connect({

Check warning on line 1061 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
waitForCollectionCallback: true,
callback: (actions) => {
Expand All @@ -1070,7 +1071,7 @@

let allReportMetadata: OnyxCollection<ReportMetadata>;
const allReportMetadataKeyValue: Record<string, ReportMetadata> = {};
Onyx.connect({

Check warning on line 1074 in src/libs/ReportUtils.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT_METADATA,
waitForCollectionCallback: true,
callback: (value) => {
Expand Down Expand Up @@ -6459,12 +6460,8 @@

function getMovedTransactionMessage(report: OnyxEntry<Report>) {
const reportName = getReportName(report) ?? report?.reportName ?? '';
const reportUrl = `${environmentURL}/r/${report?.reportID}`;
const message = translateLocal('iou.movedTransaction', {
reportUrl,
reportName,
});
return message;
const reportUrl = getReportURLForCurrentContext(report?.reportID);
return translateLocal('iou.movedTransaction', {reportUrl, reportName});
}

function getUnreportedTransactionMessage() {
Expand All @@ -6489,8 +6486,8 @@
const toPolicyName = getPolicyNameByID(toPolicyID);
return translateLocal('iou.movedAction', {
shouldHideMovedReportUrl: !isDM(report),
movedReportUrl: `${environmentURL}/r/${movedReportID}`,
newParentReportUrl: `${environmentURL}/r/${newParentReportID}`,
movedReportUrl: getReportURLForCurrentContext(movedReportID),
newParentReportUrl: getReportURLForCurrentContext(newParentReportID),
toPolicyName,
});
}
Expand Down Expand Up @@ -6814,8 +6811,8 @@
const movedActionMessage = [
{
html: shouldHideMovedReportUrl
? `moved this <a href='${CONST.NEW_EXPENSIFY_URL}r/${movedReportID}' target='_blank' rel='noreferrer noopener'>report</a> to the <a href='${CONST.NEW_EXPENSIFY_URL}r/${newParentReportID}' target='_blank' rel='noreferrer noopener'>${policyName}</a> workspace`
: `moved this report to the <a href='${CONST.NEW_EXPENSIFY_URL}r/${newParentReportID}' target='_blank' rel='noreferrer noopener'>${policyName}</a> workspace`,
? `moved this <a href='${getReportURLForCurrentContext(movedReportID)}' target='_blank' rel='noreferrer noopener'>report</a> to the <a href='${getReportURLForCurrentContext(newParentReportID)}' target='_blank' rel='noreferrer noopener'>${policyName}</a> workspace`
: `moved this report to the <a href='${getReportURLForCurrentContext(newParentReportID)}' target='_blank' rel='noreferrer noopener'>${policyName}</a> workspace`,
text: `moved this report to the ${policyName} workspace`,
type: CONST.REPORT.MESSAGE.TYPE.COMMENT,
},
Expand Down Expand Up @@ -6902,11 +6899,8 @@
targetReportID: string,
): ReportAction {
const reportName = allReports?.[targetReportID]?.reportName ?? '';
const url = `${environmentURL}/r/${targetReportID}`;
const [actionText, messageHtml] =
type === CONST.REPORT.ACTIONS.TYPE.MOVED_TRANSACTION
? [`moved this expense to ${reportName}`, `moved this expense to <a href='${url}' target='_blank' rel='noreferrer noopener'>${reportName}</a>`]
: ['moved this expense to your personal space', 'moved this expense to your personal space'];
const url = getReportURLForCurrentContext(targetReportID);
const [actionText, messageHtml] = [`moved this expense to ${reportName}`, `moved this expense to <a href='${url}' target='_blank' rel='noreferrer noopener'>${reportName}</a>`];

return {
actionName: type,
Expand Down Expand Up @@ -11940,6 +11934,54 @@
return (report.visibility === CONST.REPORT.VISIBILITY.RESTRICTED || hasAccessPolicyExpenseChat) && isPolicyEmployee;
}

function getReportURLForCurrentContext(reportID: string | undefined): string {
if (!reportID) {
return `${environmentURL}/r/`;
}
const isInSearchContext = isSearchTopmostFullScreenRoute();
if (!isInSearchContext) {
return `${environmentURL}/${ROUTES.REPORT_WITH_ID.getRoute(reportID)}`;
}

// Navigation can return routes with a leading slash or missing when still mounting.
// Normalize everything to match the path shape used by ROUTES helpers.
const normalizeRoute = (route?: string) => {
if (!route) {
return undefined;
}
return route.startsWith('/') ? route.substring(1) : route;
};

const activeRoute = normalizeRoute(Navigation.getActiveRoute());

let backToRoute: string | undefined;

if (activeRoute) {
const [, queryString = ''] = activeRoute.split('?');
if (queryString) {
const params = new URLSearchParams(queryString);
const encodedBackTo = params.get('backTo');
if (encodedBackTo) {
// Prefer the backTo param when present; it points to the exact search state we left.
backToRoute = normalizeRoute(decodeURIComponent(encodedBackTo));
}
}

if (!backToRoute && activeRoute.startsWith(ROUTES.SEARCH_ROOT.route)) {
// Otherwise keep the current search route (preserves tab + filters) as the return target.
backToRoute = activeRoute;
}
}

if (!backToRoute?.startsWith(ROUTES.SEARCH_ROOT.route)) {
// Fall back to the generic search home when we can't recover a valid route.
backToRoute = ROUTES.SEARCH_ROOT.route;
}

const relativePath = ROUTES.SEARCH_MONEY_REQUEST_REPORT.getRoute({reportID, backTo: backToRoute});
return `${environmentURL}/${relativePath}`;
}

export {
areAllRequestsBeingSmartScanned,
buildOptimisticAddCommentReportAction,
Expand Down Expand Up @@ -12331,6 +12373,7 @@
isWorkspaceThread,
isMoneyRequestReportEligibleForMerge,
getReportStatusTranslation,
getReportURLForCurrentContext,
getReportStatusColorStyle,
getMovedActionMessage,
excludeParticipantsForDisplay,
Expand Down
72 changes: 72 additions & 0 deletions tests/unit/ReportUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ import useReportIsArchived from '@hooks/useReportIsArchived';
import {putOnHold} from '@libs/actions/IOU';
import type {OnboardingTaskLinks} from '@libs/actions/Welcome/OnboardingFlow';
import DateUtils from '@libs/DateUtils';
import {getEnvironmentURL} from '@libs/Environment/Environment';
import getBase62ReportID from '@libs/getBase62ReportID';
import {translateLocal} from '@libs/Localize';
import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute';
import Navigation from '@libs/Navigation/Navigation';
import {getOriginalMessage, isWhisperAction} from '@libs/ReportActionsUtils';
import {
buildOptimisticChatReport,
Expand Down Expand Up @@ -56,6 +59,7 @@ import {
getReportIDFromLink,
getReportName,
getReportStatusTranslation,
getReportURLForCurrentContext,
getSearchReportName,
getWorkspaceIcon,
getWorkspaceNameUpdatedMessage,
Expand Down Expand Up @@ -92,6 +96,7 @@ import {buildOptimisticTransaction} from '@libs/TransactionUtils';
import CONST from '@src/CONST';
import IntlStore from '@src/languages/IntlStore';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {
Beta,
OnyxInputOrEntry,
Expand Down Expand Up @@ -142,6 +147,8 @@ import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';
// Be sure to include the mocked permissions library or else the beta tests won't work
jest.mock('@libs/Permissions');

jest.mock('@libs/Navigation/helpers/isSearchTopmostFullScreenRoute', () => jest.fn());

jest.mock('@libs/Navigation/Navigation', () => ({
setNavigationActionToMicrotaskQueue: jest.fn(),
navigate: jest.fn(),
Expand Down Expand Up @@ -7299,6 +7306,71 @@ describe('ReportUtils', () => {
});
});

describe('getReportURLForCurrentContext', () => {
const flushPromises = () =>
new Promise<void>((resolve) => {
setImmediate(resolve);
});
const mockIsSearchTopmostFullScreenRoute = jest.mocked(isSearchTopmostFullScreenRoute);
let environmentURL: string;

beforeAll(async () => {
environmentURL = await getEnvironmentURL();
await flushPromises();
});

afterAll(() => {
mockIsSearchTopmostFullScreenRoute.mockRestore();
});

const mockGetActiveRoute = Navigation.getActiveRoute as jest.Mock;

beforeEach(() => {
mockIsSearchTopmostFullScreenRoute.mockReset();
mockIsSearchTopmostFullScreenRoute.mockReturnValue(false);
mockGetActiveRoute.mockReset();
mockGetActiveRoute.mockReturnValue('search?q=type:report');
});

it('returns report route when not in search context', () => {
const reportID = '123';
expect(getReportURLForCurrentContext(reportID)).toBe(`${environmentURL}/${ROUTES.REPORT_WITH_ID.getRoute(reportID)}`);
});

it('returns search route when in search context', () => {
const reportID = '456';
mockIsSearchTopmostFullScreenRoute.mockReturnValue(true);
const encodedBackTo = 'search%3Fq%3Dtype%3Areport';
mockGetActiveRoute.mockReturnValue(`search/r/999?backTo=${encodedBackTo}`);
expect(getReportURLForCurrentContext(reportID)).toBe(`${environmentURL}/${ROUTES.SEARCH_MONEY_REQUEST_REPORT.getRoute({reportID, backTo: 'search?q=type:report'})}`);
});

it('uses current search route when no backTo parameter is present', () => {
const reportID = '111';
mockIsSearchTopmostFullScreenRoute.mockReturnValue(true);
mockGetActiveRoute.mockReturnValue('search?q=type:invoice');
expect(getReportURLForCurrentContext(reportID)).toBe(`${environmentURL}/${ROUTES.SEARCH_MONEY_REQUEST_REPORT.getRoute({reportID, backTo: 'search?q=type:invoice'})}`);
});

it('normalizes leading slash in search routes', () => {
const reportID = '222';
mockIsSearchTopmostFullScreenRoute.mockReturnValue(true);
mockGetActiveRoute.mockReturnValue('/search?q=type:card');
expect(getReportURLForCurrentContext(reportID)).toBe(`${environmentURL}/${ROUTES.SEARCH_MONEY_REQUEST_REPORT.getRoute({reportID, backTo: 'search?q=type:card'})}`);
});

it('falls back to default search route when current route is unavailable', () => {
const reportID = '789';
mockIsSearchTopmostFullScreenRoute.mockReturnValue(true);
mockGetActiveRoute.mockReturnValue('');
expect(getReportURLForCurrentContext(reportID)).toBe(`${environmentURL}/${ROUTES.SEARCH_MONEY_REQUEST_REPORT.getRoute({reportID, backTo: ROUTES.SEARCH_ROOT.route})}`);
});

it('falls back to the base report path when reportID is missing', () => {
expect(getReportURLForCurrentContext(undefined)).toBe(`${environmentURL}/r/`);
});
});

describe('requiresManualSubmission', () => {
it('should return true when manual submit is enabled', () => {
const report: Report = {
Expand Down
Loading