Skip to content
Open
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
29 changes: 29 additions & 0 deletions src/libs/PolicyUtils/getPolicyList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/** Lists the workspaces of a policy collection once per Onyx snapshot, so per-item loops don't copy the collection each time. */
import type {Policy} from '@src/types/onyx';

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

const policyListByCollection = new WeakMap<NonNullable<OnyxCollection<Policy>>, readonly Policy[]>();

/** Every caller of the same snapshot gets the same array, so it is read-only. */
function getPolicyList(policies: OnyxCollection<Policy>): readonly Policy[] {
if (!policies) {
return [];
}

const cachedPolicyList = policyListByCollection.get(policies);
if (cachedPolicyList) {
return cachedPolicyList;
}

const policyList = Object.values(policies).filter((policy): policy is Policy => !!policy);

// Onyx freezes each snapshot and replaces it on change, so only a frozen collection is safe to cache.
if (Object.isFrozen(policies)) {
policyListByCollection.set(policies, policyList);
}
return policyList;
}

// eslint-disable-next-line import/prefer-default-export -- PolicyUtils/index.ts re-exports its modules with `export *`, which skips default exports.
export {getPolicyList};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Rename the single-export module to getPolicyList.ts

CONSISTENCY-9 in .claude/skills/app-coding-standards/rules/consistency-9-file-naming.md requires newly added source files to be named after their primary export. This module exports only getPolicyList, so policyList.ts violates that convention and does not qualify for the multi-export utilities exception. Rename it to getPolicyList.ts and update the barrel re-export so the helper is discoverable under its exported name.

AGENTS.md reference: AGENTS.md:L7-L9

Useful? React with 👍 / 👎.

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.

Renamed to getPolicyList.ts.

1 change: 1 addition & 0 deletions src/libs/PolicyUtils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export * from './errors';
export * from './approvals';
export * from './payments';
export * from './policy';
export * from './getPolicyList';
export * from './navigation';
export * from './members';
export * from './expensifyTeam';
Expand Down
5 changes: 3 additions & 2 deletions src/libs/ReportSecondaryActionUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
canMemberWrite,
getConnectedIntegration,
getCorrectedAutoReportingFrequency,
getPolicyList,
getReimbursementChoice,
isSubmittingToSelf,
getValidConnectedIntegration,
Expand Down Expand Up @@ -717,8 +718,8 @@ function isChangeWorkspaceAction(report: Report, policies: OnyxCollection<Policy
// Find available policies - stop early once we find 2 or after checking all
let firstAvailablePolicy: Policy | undefined;
let availablePoliciesCount = 0;
for (const policy of Object.values(policies ?? {})) {
if (!policy || !isWorkspaceEligibleForReportChange(submitterLogin, policy, report)) {
for (const policy of getPolicyList(policies)) {
if (!isWorkspaceEligibleForReportChange(submitterLogin, policy, report)) {
continue;
}

Expand Down
5 changes: 2 additions & 3 deletions src/libs/SearchUIUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ import {
canSendInvoice,
getCleanedTagName,
getCommaSeparatedTagNameWithSanitizedColons,
getPolicyList,
isSubmittingToSelf,
getTagGLCode,
getValidConnectedIntegration,
Expand Down Expand Up @@ -8462,9 +8463,7 @@ function canChangeWorkspaceOfSearchReport({
const submitterLogin = getLoginByAccountID(report.ownerAccountID, personalDetails);
return (
isChangeWorkspaceAction(reportToCheck, policies, currentUserLogin ?? '', submitterLogin, reportActions) &&
Object.values(policies ?? {}).some(
(policy) => !!policy && policy.id !== report.policyID && canBulkMoveReportToPolicy(report, reportTransactions, policy, submitterLogin, currentUserLogin),
)
getPolicyList(policies).some((policy) => policy.id !== report.policyID && canBulkMoveReportToPolicy(report, reportTransactions, policy, submitterLogin, currentUserLogin))
);
}

Expand Down
106 changes: 106 additions & 0 deletions tests/unit/PolicyListTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import {act, renderHook} from '@testing-library/react-native';

import useOnyx from '@hooks/useOnyx';

import {getPolicyList} from '@libs/PolicyUtils';

import ONYXKEYS from '@src/ONYXKEYS';
import type {Policy} from '@src/types/onyx';

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

import Onyx from 'react-native-onyx';

import createRandomPolicy from '../utils/collections/policies';
import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct';

describe('getPolicyList', () => {
it('returns the workspaces of a collection and skips empty entries', () => {
// Given an empty entry, which the OnyxCollection type allows even though Onyx drops removed members from snapshots
const firstPolicy = createRandomPolicy(1);
const secondPolicy = createRandomPolicy(2);
const policies: OnyxCollection<Policy> = {
[`${ONYXKEYS.COLLECTION.POLICY}1`]: firstPolicy,
[`${ONYXKEYS.COLLECTION.POLICY}2`]: secondPolicy,
[`${ONYXKEYS.COLLECTION.POLICY}3`]: undefined,
};

// When the workspaces are listed
const policyList = getPolicyList(policies);

// Then only real workspaces come back, so callers skip their own empty checks
expect(policyList).toEqual([firstPolicy, secondPolicy]);
});

it('returns an empty list when there is no collection', () => {
// Given no policy collection yet, as before Onyx loads it
// When the workspaces are listed
// Then callers can still loop over the result
expect(getPolicyList(undefined)).toEqual([]);
});

it('reuses the list for the same frozen collection', () => {
// Given a frozen collection, which is how Onyx hands out each collection snapshot
const policies: OnyxCollection<Policy> = Object.freeze({[`${ONYXKEYS.COLLECTION.POLICY}1`]: createRandomPolicy(1), [`${ONYXKEYS.COLLECTION.POLICY}2`]: createRandomPolicy(2)});

// When the workspaces are listed twice, like once per selected report
const firstList = getPolicyList(policies);
const secondList = getPolicyList(policies);

// Then the second call returns the same array instead of copying the collection again
expect(secondList).toBe(firstList);
});

it('lists a new collection snapshot fresh', () => {
// Given a frozen snapshot that was already listed, and a newer snapshot after a workspace changed
const firstPolicy = createRandomPolicy(1);
const oldPolicies: OnyxCollection<Policy> = Object.freeze({[`${ONYXKEYS.COLLECTION.POLICY}1`]: firstPolicy});
const oldList = getPolicyList(oldPolicies);
const changedPolicy = {...firstPolicy, name: 'Renamed workspace'};
const newPolicies: OnyxCollection<Policy> = Object.freeze({[`${ONYXKEYS.COLLECTION.POLICY}1`]: changedPolicy});

// When the newer snapshot is listed
const newList = getPolicyList(newPolicies);

// Then it reflects the change, because the cache is tied to the collection object
expect(newList).not.toBe(oldList);
expect(newList).toEqual([changedPolicy]);
});

it('does not cache a collection that is not frozen', () => {
// Given a plain object that its owner can still change after the first call
const policies: Record<string, Policy | undefined> = {[`${ONYXKEYS.COLLECTION.POLICY}1`]: createRandomPolicy(1)};
const firstList = getPolicyList(policies);

// When a workspace is added to the same object and it is listed again
const addedPolicy = createRandomPolicy(2);
policies[`${ONYXKEYS.COLLECTION.POLICY}2`] = addedPolicy;
const secondList = getPolicyList(policies);

// Then the new workspace shows up, because only frozen collections are safe to cache
expect(secondList).toContain(addedPolicy);
expect(secondList).not.toBe(firstList);
});

it('reuses the list for the collection useOnyx returns', async () => {
// Given workspaces stored in Onyx and read with useOnyx, the way the Spend bulk actions read them
Onyx.init({keys: ONYXKEYS});
await act(async () => {
await Onyx.clear();
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}1`, createRandomPolicy(1));
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}2`, createRandomPolicy(2));
});
const {result} = renderHook(() => useOnyx(ONYXKEYS.COLLECTION.POLICY));
await waitForBatchedUpdatesWithAct();
const policies = result.current[0];

// When the workspaces are listed twice, like once per selected report
const firstList = getPolicyList(policies);
const secondList = getPolicyList(policies);

// Then the same array comes back, which only holds while Onyx keeps freezing collection snapshots
expect(Object.keys(policies ?? {})).toHaveLength(2);
expect(Object.isFrozen(policies)).toBe(true);
expect(secondList).toBe(firstList);
});
});
Loading