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
5 changes: 5 additions & 0 deletions src/libs/PolicyUtils/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,10 @@ function canCreateExpensesOnPolicy(policy: OnyxInputOrEntry<Policy>, login?: str
return canRoleCreateExpenses(getPolicyRole(policy, login, false) ?? policy?.role);
}

function canCreateRoomsOnPolicy(policy: OnyxInputOrEntry<Policy>, login: string): boolean {
return canMemberWrite(policy, login, CONST.POLICY.POLICY_FEATURE.ROOMS);
}

/** Whether the submitter's role lets them submit their own report. Non-group policies always allow it. */
function canSubmitOwnReportOnPolicy(policy: OnyxInputOrEntry<Policy>, submitterLogin?: string): boolean {
return !isGroupPolicy(policy) || canCreateExpensesOnPolicy(policy, submitterLogin);
Expand Down Expand Up @@ -418,6 +422,7 @@ export {
canRolePay,
canRoleCreateExpenses,
canCreateExpensesOnPolicy,
canCreateRoomsOnPolicy,
canSubmitOwnReportOnPolicy,
PAYER_ROLES,
isPolicyApprover,
Expand Down
6 changes: 2 additions & 4 deletions src/libs/PolicyUtils/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import type {ValueOf} from 'type-fest';
import {hasAccountingConnections} from './connections';
import {getPerDiemCustomUnit, isPerDiemEligiblePolicy} from './customUnits';
import {isTimeTrackingEnabled} from './features';
import {canCreateExpensesOnPolicy, canEditWorkspaceSettings, canMemberWrite, getPolicyRole, isPolicyAdmin, isPolicyOwner, isPolicyUser} from './permissions';
import {canCreateExpensesOnPolicy, canCreateRoomsOnPolicy, canEditWorkspaceSettings, getPolicyRole, isPolicyAdmin, isPolicyOwner, isPolicyUser} from './permissions';
import {isArchivedPolicy, isControlPolicy, isGroupPolicy, isPaidGroupPolicy, isSubmitPolicy} from './policyType';

type WorkspaceDetails = {
Expand Down Expand Up @@ -147,9 +147,7 @@ function createInvoiceConfigurationTextSelector(translate: LocaleContextProps['t
* Get the active group policies where the current user can create policy rooms.
*/
function getPoliciesForRoomCreation(policies: OnyxCollection<Policy> | null, currentUserLogin: string | undefined): Policy[] {
return getActivePolicies(policies, currentUserLogin).filter(
(policy) => policy.type !== CONST.POLICY.TYPE.PERSONAL && canMemberWrite(policy, currentUserLogin ?? '', CONST.POLICY.POLICY_FEATURE.ROOMS),
);
return getActivePolicies(policies, currentUserLogin).filter((policy) => policy.type !== CONST.POLICY.TYPE.PERSONAL && canCreateRoomsOnPolicy(policy, currentUserLogin ?? ''));
}

function getOwnedPaidPolicies(policies: OnyxCollection<Policy> | null, currentUserAccountID: number | undefined): Policy[] {
Expand Down
7 changes: 7 additions & 0 deletions src/libs/ReportActionsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ import getReportURLForCurrentContext from './Navigation/helpers/getReportURLForC
import {getIsOffline, subscribe as subscribeNetworkState} from './NetworkState';
import Parser from './Parser';
import {arePersonalDetailsMissing, getEffectiveDisplayName, temporaryGetDisplayNameOrDefault} from './PersonalDetailsUtils';
import {canCreateRoomsOnPolicy} from './PolicyUtils/permissions';
import stripFollowupListFromHtml from './ReportActionFollowupUtils/stripFollowupListFromHtml';
import {getOriginalMessage, getReportActionHtml, getReportActionMessage, getReportActionText, getTextFromHtml} from './ReportActionMessageUtils';
import {isActionOfType, isDynamicExternalWorkflowApproveFailedAction, isModifiedExpenseAction, isMoneyRequestAction} from './ReportActionTypeGuards';
Expand Down Expand Up @@ -1740,6 +1741,8 @@ function shouldReportActionBeVisible(
isSupportTicketReport = false,
reportActions?: OnyxEntry<ReportActions>,
isInvoice?: boolean,
policy?: OnyxEntry<Policy>,
currentUserEmail?: string,
): boolean {
if (!reportAction) {
return false;
Expand Down Expand Up @@ -1804,6 +1807,10 @@ function shouldReportActionBeVisible(
return false;
}

if (isActionableReportMentionWhisper(reportAction) && policy && !canCreateRoomsOnPolicy(policy, currentUserEmail ?? '')) {
return false;
}

if (isTripPreview(reportAction) || isTravelUpdate(reportAction) || isTravelNudge(reportAction)) {
return true;
}
Expand Down
95 changes: 90 additions & 5 deletions src/libs/actions/OnyxDerived/configs/visibleReportActions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
isActionableReportMentionWhisper,
isActionableWhisperRequiringWritePermission,
isActionOfType,
isConciergeCategoryOptions,
Expand All @@ -11,14 +12,19 @@ import createOnyxDerivedValueConfig from '@userActions/OnyxDerived/createOnyxDer

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {ReportAction, ReportActions} from '@src/types/onyx';
import type {Policy, ReportAction, ReportActions} from '@src/types/onyx';
import type {VisibleReportActionsDerivedValue} from '@src/types/onyx/DerivedValues';

import type {OnyxEntry} from 'react-native-onyx';

/**
* Returns true if the action's visibility depends on runtime context that can't be cached,
* such as write permissions, policy settings, the type of its report, or sibling actions.
*/
function shouldSkipCachingAction(action: ReportAction): boolean {
if (isActionableReportMentionWhisper(action)) {
return false;
}
// A payment action hidden outside invoices depends on its report's type. The cache doesn't pass a reportID, so it
// can't tell that the report is an invoice and would hide the action there.
return (
Expand All @@ -35,6 +41,8 @@ function shouldSkipCachingAction(action: ReportAction): boolean {
* a removed action is absent from `reportActions`, so it drops out of the result.
*/
function computeReportVisibility(
policy: OnyxEntry<Policy>,
currentUserEmail: string | undefined,
reportActions: ReportActions,
currentUserAccountID: number | undefined,
isSupportTicketReport: boolean,
Expand All @@ -54,6 +62,22 @@ function computeReportVisibility(
if (shouldSkipCachingAction(action)) {
continue;
}
if (isActionableReportMentionWhisper(action)) {
// Write permission is still checked at runtime in isReportActionVisible, so pass true here to run the remaining visibility checks (deleted, resolved, targeted, room-creation permission) against the snapshot.
reportVisibility[action.reportActionID] = shouldReportActionBeVisible(
action,
actionID,
true,
currentUserAccountID,
undefined,
false,
undefined,
undefined,
policy,
currentUserEmail,
);
continue;
Comment thread
ShridharGoel marked this conversation as resolved.
Resolved
}
// A replacement ticket has its own active survey, so the original ticket's survey is stale.
if (isReplacedSupportTicket && isActionOfType(action, CONST.REPORT.ACTIONS.TYPE.SUPPORT_SURVEY)) {
reportVisibility[action.reportActionID] = false;
Expand All @@ -65,26 +89,70 @@ function computeReportVisibility(
return reportVisibility;
}

/**
* Updates cached visibility only for `ACTIONABLE_REPORT_MENTION_WHISPER` entries on a report when
* only its policy changed, avoiding a full recompute of every action on the policy.
*/
function updateReportMentionWhispersVisibility(
policy: OnyxEntry<Policy>,
currentUserEmail: string | undefined,
reportActions: ReportActions,
currentUserAccountID: number | undefined,
currentReportVisibility: Record<string, boolean> | undefined,
): Record<string, boolean> | undefined {
let nextReportVisibility = currentReportVisibility;

for (const [actionID, action] of Object.entries(reportActions)) {
if (!action || actionID !== action.reportActionID || !isActionableReportMentionWhisper(action)) {
continue;
}
const isVisible = shouldReportActionBeVisible(action, actionID, true, currentUserAccountID, undefined, false, undefined, undefined, policy, currentUserEmail);
if (nextReportVisibility?.[action.reportActionID] === isVisible) {
continue;
}
if (!nextReportVisibility || nextReportVisibility === currentReportVisibility) {
nextReportVisibility = {...currentReportVisibility};
}
nextReportVisibility[action.reportActionID] = isVisible;
}

return nextReportVisibility;
}

export default createOnyxDerivedValueConfig({
key: ONYXKEYS.DERIVED.VISIBLE_REPORT_ACTIONS,
// Note: REPORT dependency is needed both to trigger recompute when reports change
// (for UNREPORTED_TRANSACTION/MOVED_TRANSACTION visibility) AND to provide the current
// report collection to the visibility check, avoiding stale data from global connections.
// SESSION dependency is needed for whisper targeting when user changes.
dependencies: [ONYXKEYS.COLLECTION.REPORT_ACTIONS, ONYXKEYS.SESSION, ONYXKEYS.COLLECTION.REPORT, ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS],
compute: ([allReportActions, session, allReports, allReportNameValuePairs], {sourceValues, currentValue, triggeredKeys}): VisibleReportActionsDerivedValue => {
// POLICY dependency is needed so room-creation whispers recompute when a policy member's role changes.
dependencies: [ONYXKEYS.COLLECTION.REPORT_ACTIONS, ONYXKEYS.SESSION, ONYXKEYS.COLLECTION.REPORT, ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, ONYXKEYS.COLLECTION.POLICY],
compute: ([allReportActions, session, allReports, allReportNameValuePairs, allPolicies], {sourceValues, currentValue, triggeredKeys}): VisibleReportActionsDerivedValue => {
if (!allReportActions) {
return {};
}

const currentUserAccountID = session?.accountID;
const currentUserEmail = session?.email;
const reportActionsUpdates = sourceValues?.[ONYXKEYS.COLLECTION.REPORT_ACTIONS];
const reportUpdates = sourceValues?.[ONYXKEYS.COLLECTION.REPORT];
const reportNameValuePairsUpdates = sourceValues?.[ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS];
const policyUpdates = sourceValues?.[ONYXKEYS.COLLECTION.POLICY];

// A report only changes its own actions' visibility, through its support ticket type, so only changed reports are recomputed.
// SESSION is read from triggeredKeys so a session cleared to `undefined` still forces a full recompute.
const isIncremental = !!(reportActionsUpdates ?? reportUpdates ?? reportNameValuePairsUpdates) && !triggeredKeys?.has(ONYXKEYS.SESSION) && !!currentValue;
const isIncremental = !!(reportActionsUpdates ?? reportUpdates ?? reportNameValuePairsUpdates ?? policyUpdates) && !triggeredKeys?.has(ONYXKEYS.SESSION) && !!currentValue;

const changedPolicyIDs = policyUpdates ? new Set(Object.keys(policyUpdates).map((key) => key.replace(ONYXKEYS.COLLECTION.POLICY, ''))) : undefined;
const policyChangedReportIDs =

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.

This recomputes every report on a workspace whenever any field on that workspace changes. Workspace data changes often: category and tag edits, member list loads, and reconnects that resend every workspace. For an admin of a large workspace, that means rechecking thousands of expense reports to update one rare whisper type.

reportAttributes.ts has the same dependency and guards against this. It only recomputes reports when a relevant workspace field changed. See reportAttributes.ts.

Can you do one of these?

  • Recompute only when the fields that affect room permission change: role, the current user's employeeList entry, type, or archived state.
  • When only a workspace changed, update just the ACTIONABLE_REPORT_MENTION_WHISPER entries, not whole reports.

AI-assisted draft, reviewed and approved by @flodnv

isIncremental && changedPolicyIDs && changedPolicyIDs.size > 0
? Object.keys(allReportActions)
.map((key) => key.replace(ONYXKEYS.COLLECTION.REPORT_ACTIONS, ''))
.filter((reportID) => {
const policyID = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]?.policyID;
return !!policyID && changedPolicyIDs.has(policyID);
})
: [];

const result: VisibleReportActionsDerivedValue = isIncremental ? {...currentValue} : {};
const reportIDsToProcess = isIncremental
Expand All @@ -108,9 +176,26 @@ export default createOnyxDerivedValueConfig({
}

const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
const policy = report?.policyID ? allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`] : undefined;
const isSupportTicketReport = isSupportTicket(report);
const isReplacedSupportTicket = isSupportTicketReport && !!allReportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${reportID}`]?.reopenedAsReportID;
result[reportID] = computeReportVisibility(reportActions, currentUserAccountID, isSupportTicketReport, isReplacedSupportTicket);
result[reportID] = computeReportVisibility(policy, currentUserEmail, reportActions, currentUserAccountID, isSupportTicketReport, isReplacedSupportTicket);
}

for (const reportID of policyChangedReportIDs) {
if (reportIDsToProcess.has(reportID)) {
continue;
}
const reportActions = allReportActions[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`];
if (!reportActions) {
continue;
}
const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
const policy = report?.policyID ? allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`] : undefined;
const nextReportVisibility = updateReportMentionWhispersVisibility(policy, currentUserEmail, reportActions, currentUserAccountID, result[reportID]);
if (nextReportVisibility) {
result[reportID] = nextReportVisibility;
}
}

return result;
Expand Down
5 changes: 2 additions & 3 deletions src/pages/workspace/rooms/WorkspaceRoomCreatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ import usePolicy from '@hooks/usePolicy';

import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types';
import type {SettingsNavigatorParamList} from '@libs/Navigation/types';
import {canMemberWrite} from '@libs/PolicyUtils';
import {canCreateRoomsOnPolicy} from '@libs/PolicyUtils';

import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper';
import WorkspaceNewRoomPage from '@pages/workspace/WorkspaceNewRoomPage';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type SCREENS from '@src/SCREENS';

Expand All @@ -22,7 +21,7 @@ function WorkspaceRoomCreatePage({route}: WorkspaceRoomCreatePageProps) {
return (
<AccessOrNotFoundWrapper
policyID={route.params.policyID}
shouldBeBlocked={!canMemberWrite(policy, session?.email ?? '', CONST.POLICY.POLICY_FEATURE.ROOMS)}
shouldBeBlocked={!canCreateRoomsOnPolicy(policy, session?.email ?? '')}
>
<WorkspaceNewRoomPage policyID={route.params.policyID} />
</AccessOrNotFoundWrapper>
Expand Down
4 changes: 2 additions & 2 deletions src/pages/workspace/rooms/WorkspaceRoomsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {openReport} from '@libs/actions/Report';
import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute';
import Navigation from '@libs/Navigation/Navigation';
import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types';
import {canMemberWrite, isArchivedPolicy, isPolicyAdmin} from '@libs/PolicyUtils';
import {canCreateRoomsOnPolicy, isArchivedPolicy, isPolicyAdmin} from '@libs/PolicyUtils';
import {getReportName} from '@libs/ReportNameUtils';
import {getParticipantsAccountIDsForDisplay} from '@libs/ReportUtils';

Expand Down Expand Up @@ -159,7 +159,7 @@ function WorkspaceRoomsPage({route}: WorkspaceRoomsPageProps) {
setPagination({queryKey: roomsQueryKey, pageNumber: pageNumber + 1});
};

const canCreateRooms = canMemberWrite(policy, session?.email ?? '', CONST.POLICY.POLICY_FEATURE.ROOMS);
const canCreateRooms = canCreateRoomsOnPolicy(policy, session?.email ?? '');

const roomsTableHeader =
shouldUseNarrowLayout && canCreateRooms ? (
Expand Down
Loading
Loading