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
6 changes: 2 additions & 4 deletions src/libs/actions/IOU/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,7 @@
};

let allPersonalDetails: OnyxTypes.PersonalDetailsList = {};
Onyx.connect({

Check warning on line 814 in src/libs/actions/IOU/index.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) => {
allPersonalDetails = value ?? {};
Expand Down Expand Up @@ -907,7 +907,7 @@
};

let allTransactions: NonNullable<OnyxCollection<OnyxTypes.Transaction>> = {};
Onyx.connect({

Check warning on line 910 in src/libs/actions/IOU/index.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 @@ -921,7 +921,7 @@
});

let allTransactionDrafts: NonNullable<OnyxCollection<OnyxTypes.Transaction>> = {};
Onyx.connect({

Check warning on line 924 in src/libs/actions/IOU/index.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_DRAFT,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -930,7 +930,7 @@
});

let allTransactionViolations: NonNullable<OnyxCollection<OnyxTypes.TransactionViolations>> = {};
Onyx.connect({

Check warning on line 933 in src/libs/actions/IOU/index.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_VIOLATIONS,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -944,7 +944,7 @@
});

let allPolicyTags: OnyxCollection<OnyxTypes.PolicyTagLists> = {};
Onyx.connect({

Check warning on line 947 in src/libs/actions/IOU/index.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_TAGS,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -957,7 +957,7 @@
});

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

Check warning on line 960 in src/libs/actions/IOU/index.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 All @@ -966,7 +966,7 @@
});

let allReportNameValuePairs: OnyxCollection<OnyxTypes.ReportNameValuePairs>;
Onyx.connect({

Check warning on line 969 in src/libs/actions/IOU/index.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_NAME_VALUE_PAIRS,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -976,7 +976,7 @@

let userAccountID = -1;
let currentUserEmail = '';
Onyx.connect({

Check warning on line 979 in src/libs/actions/IOU/index.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) => {
currentUserEmail = value?.email ?? '';
Expand All @@ -985,7 +985,7 @@
});

let deprecatedCurrentUserPersonalDetails: OnyxEntry<OnyxTypes.PersonalDetails>;
Onyx.connect({

Check warning on line 988 in src/libs/actions/IOU/index.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) => {
deprecatedCurrentUserPersonalDetails = value?.[userAccountID] ?? undefined;
Expand All @@ -993,7 +993,7 @@
});

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

Check warning on line 996 in src/libs/actions/IOU/index.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 Down Expand Up @@ -1225,7 +1225,7 @@
newIouRequestType,
report,
parentReport,
currentDate = '',
currentDate,
lastSelectedDistanceRates,
currentUserPersonalDetails,
hasOnlyPersonalPolicies,
Expand All @@ -1235,9 +1235,7 @@
const newTransactionID = CONST.IOU.OPTIMISTIC_TRANSACTION_ID;
const currency = policy?.outputCurrency ?? personalPolicy?.outputCurrency ?? CONST.CURRENCY.USD;

// Disabling this line since currentDate can be an empty string
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const created = currentDate || format(new Date(), 'yyyy-MM-dd');
const created = currentDate ?? format(new Date(), 'yyyy-MM-dd');

// We remove draft transactions created during multi scanning if there are some
removeDraftTransactions(true, draftTransactions);
Expand Down
36 changes: 17 additions & 19 deletions src/pages/iou/request/IOURequestStartPage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {useFocusEffect} from '@react-navigation/native';
import {iouRequestPolicyCollectionSelector} from '@selectors/Policy';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {Keyboard, View} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';
import DragAndDropProvider from '@components/DragAndDrop/Provider';
import FocusTrapContainerElement from '@components/FocusTrap/FocusTrapContainerElement';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
Expand All @@ -25,7 +27,6 @@ import getPlatform from '@libs/getPlatform';
import type Platform from '@libs/getPlatform/types';
import Navigation from '@libs/Navigation/Navigation';
import OnyxTabNavigator, {TabScreenWithFocusTrapWrapper, TopTab} from '@libs/Navigation/OnyxTabNavigator';
import {getIsUserSubmittedExpenseOrScannedReceipt} from '@libs/OptionsListUtils';
import {
getActivePoliciesWithExpenseChatAndPerDiemEnabledAndHasRates,
getActivePoliciesWithExpenseChatAndTimeEnabled,
Expand All @@ -41,7 +42,7 @@ import {initMoneyRequest} from '@userActions/IOU';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type SCREENS from '@src/SCREENS';
import type {SelectedTabRequest} from '@src/types/onyx';
import type {DismissedProductTraining, SelectedTabRequest} from '@src/types/onyx';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue';
import IOURequestStepAmount from './step/IOURequestStepAmount';
Expand All @@ -60,6 +61,11 @@ type IOURequestStartPageProps = WithWritableReportOrNotFoundProps<typeof SCREENS
const platform = getPlatform(true);
const isWeb = ([CONST.PLATFORM.WEB, CONST.PLATFORM.MOBILE_WEB] as Platform[]).includes(platform);

// Tab indices for IOURequestStartPage
const PER_DIEM_TAB_INDEX = 2;

const isTestReceiptTooltipDismissedSelector = (nvp: OnyxEntry<DismissedProductTraining>): boolean => !!nvp?.[CONST.PRODUCT_TRAINING_TOOLTIP_NAMES.SCAN_TEST_TOOLTIP];

function IOURequestStartPage({
route,
route: {
Expand All @@ -77,18 +83,22 @@ function IOURequestStartPage({
const [parentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${report?.parentReportID}`);
const policy = usePolicy(report?.policyID);
const [lastSelectedTab, selectedTabResult] = useOnyx(`${ONYXKEYS.COLLECTION.SELECTED_TAB}${CONST.TAB.IOU_REQUEST_TYPE}`);
const [selectedTab, setSelectedTab] = useState(lastSelectedTab);
// Derive selectedTab directly instead of using state
const selectedTab = lastSelectedTab;

const isLoadingSelectedTab = shouldUseTab ? isLoadingOnyxValue(selectedTabResult) : false;
const [transaction, transactionResult] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${getNonEmptyStringOnyxID(route?.params.transactionID)}`);
const isLoadingTransaction = isLoadingOnyxValue(transactionResult);
const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {
selector: iouRequestPolicyCollectionSelector,
});

const [lastSelectedDistanceRates] = useOnyx(ONYXKEYS.NVP_LAST_SELECTED_DISTANCE_RATES);
const [draftTransactions] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT);
const [isMultiScanEnabled, setIsMultiScanEnabled] = useState(false);
const [currentDate] = useOnyx(ONYXKEYS.CURRENT_DATE);
const {isOffline} = useNetwork();
const [nvpDismissedProductTraining] = useOnyx(ONYXKEYS.NVP_DISMISSED_PRODUCT_TRAINING);
const [hasUserSubmittedExpenseOrScannedReceipt] = useOnyx(ONYXKEYS.NVP_DISMISSED_PRODUCT_TRAINING, {selector: isTestReceiptTooltipDismissedSelector});
const hasOnlyPersonalPolicies = useMemo(() => hasOnlyPersonalPoliciesUtil(allPolicies), [allPolicies]);

const perDiemInputRef = useRef<AnimatedTextInputRef | null>(null);
Expand All @@ -109,8 +119,7 @@ function IOURequestStartPage({
// We requestAnimationFrame since the function is called in the animate block in the web implementation
// which fixes a locked animation glitch when swiping between tabs, and aligns with the native implementation internal delay
requestAnimationFrame(() => {
// 2 - PerDiem
if (index !== 2) {
if (index !== PER_DIEM_TAB_INDEX) {
return;
}
perDiemInputRef.current?.focus?.();
Expand Down Expand Up @@ -164,13 +173,6 @@ function IOURequestStartPage({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

useEffect(() => {
if (isLoadingSelectedTab || selectedTab) {
return;
}
setSelectedTab(lastSelectedTab);
}, [isLoadingSelectedTab, selectedTab, lastSelectedTab]);

const navigateBack = () => {
Navigation.closeRHPFlow();
};
Expand Down Expand Up @@ -219,7 +221,6 @@ function IOURequestStartPage({

const onTabSelected = useCallback(
(newIouType: IOURequestType) => {

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.

❌ CONSISTENCY-3 (docs)

This Tab.setSelectedTab(CONST.TAB.IOU_REQUEST_TYPE, newIouType) call is redundant. OnyxTabNavigator already calls Tab.setSelectedTab(id, newSelectedTab) in its screenListeners.state handler (OnyxTabNavigator.tsx line 190) before invoking the onTabSelected callback (line 192). This means by the time onTabSelected runs, the Onyx key is already updated. The duplicate call triggers a second Onyx.merge for the same key with the same value on every tab switch, which is unnecessary work.

Remove the Tab.setSelectedTab call from onTabSelected since OnyxTabNavigator already handles persisting the selected tab:

const onTabSelected = useCallback(
    (newIouType: IOURequestType) => {
        resetIOUTypeIfChanged(newIouType);
    },
    [resetIOUTypeIfChanged],
);

Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

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.

Good catch — removed the duplicate Tab.setSelectedTab call. OnyxTabNavigator already persists the selected tab before invoking onTabSelected, so our call was redundant.

setSelectedTab(newIouType);
resetIOUTypeIfChanged(newIouType);
},
[resetIOUTypeIfChanged],
Expand Down Expand Up @@ -256,10 +257,7 @@ function IOURequestStartPage({
const {shouldShowProductTrainingTooltip, renderProductTrainingTooltip} = useProductTrainingContext(
CONST.PRODUCT_TRAINING_TOOLTIP_NAMES.SCAN_TEST_TOOLTIP,
// The test receipt image is served via our server on web so it requires internet connection
!getIsUserSubmittedExpenseOrScannedReceipt(nvpDismissedProductTraining) &&
isBetaEnabled(CONST.BETAS.NEWDOT_MANAGER_MCTEST) &&
selectedTab === CONST.TAB_REQUEST.SCAN &&
!(isOffline && isWeb),
!hasUserSubmittedExpenseOrScannedReceipt && isBetaEnabled(CONST.BETAS.NEWDOT_MANAGER_MCTEST) && selectedTab === CONST.TAB_REQUEST.SCAN && !(isOffline && isWeb),
{
onConfirm: () => {
setTestReceiptAndNavigateRef?.current?.();
Expand Down
5 changes: 2 additions & 3 deletions src/pages/iou/request/step/IOURequestStepConfirmation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,6 @@ function IOURequestStepConfirmation({
const draftPolicyID = getIOURequestPolicyID(initialTransaction, reportDraft);
const [policyDraft] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_DRAFTS}${draftPolicyID}`);
const [policyReal] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${realPolicyID}`);
const [reportDrafts] = useOnyx(ONYXKEYS.COLLECTION.REPORT_DRAFT);
const [gpsDraftDetails] = useOnyx(ONYXKEYS.GPS_DRAFT_DETAILS);
const [betas] = useOnyx(ONYXKEYS.BETAS);

Expand Down Expand Up @@ -312,9 +311,9 @@ function IOURequestStepConfirmation({
const privateIsArchived = privateIsArchivedMap[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${participant.reportID}`];
return participant.accountID
? getParticipantsOption(participant, personalDetails)
: getReportOption(participant, privateIsArchived, policy, currentUserPersonalDetails.accountID, personalDetails, reportAttributesDerived, reportDrafts);
: getReportOption(participant, privateIsArchived, policy, currentUserPersonalDetails.accountID, personalDetails, reportAttributesDerived);
}) ?? [],
[transaction?.participants, iouType, personalDetails, reportAttributesDerived, reportDrafts, privateIsArchivedMap, policy, currentUserPersonalDetails.accountID],
[transaction?.participants, iouType, personalDetails, reportAttributesDerived, privateIsArchivedMap, policy, currentUserPersonalDetails.accountID],
Comment on lines +314 to +316

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 Recompute participants when report drafts change

Dropping reportDrafts from this memoized participants computation means updates to ONYXKEYS.COLLECTION.REPORT_DRAFT no longer invalidate the list, even though getReportOption() resolves destination data through draft reports. In flows where a destination is initially a draft report (optimistic) and then gets updated/promoted while the confirmation page is open, the row can stay stale (including draft-derived display/disabled state) until some unrelated dependency changes.

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.

This removal was intentional (originally done by @OlimpiaZurek in the first draft). getReportOption calls getReportOrDraftReport internally, which falls back to the module-level allReportsDraft variable (populated via Onyx.connect in ReportUtils.ts) when the param is not passed. All other callers of getReportOption across the codebase already omit this parameter and rely on the same fallback.

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 removal was intentional (originally done by @OlimpiaZurek in the first draft). getReportOption calls getReportOrDraftReport internally, which falls back to the module-level allReportsDraft variable (populated via Onyx.connect in ReportUtils.ts) when the param is not passed. All other callers of getReportOption across the codebase already omit this parameter and rely on the same fallback.

@BartekObudzinski That goes against our efforts to remove impure functions. We should not rely on the module level onyx.connect in this case. Can you please raise a revert as we will eventually remove the module level subscription

);
const isPolicyExpenseChat = useMemo(() => participants?.some((participant) => participant.isPolicyExpenseChat), [participants]);
const shouldGenerateTransactionThreadReport = !isBetaEnabled(CONST.BETAS.NO_OPTIMISTIC_TRANSACTION_THREADS);
Expand Down
35 changes: 35 additions & 0 deletions src/selectors/Policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,40 @@ const groupPaidPoliciesWithExpenseChatEnabledSelector = (policies: OnyxCollectio

const shouldRedirectToExpensifyClassicSelector = (policies: OnyxCollection<Policy>) => areAllGroupPoliciesExpenseChatDisabled(policies);

const iouRequestPolicyCollectionSelector = (policies: OnyxCollection<Policy>): OnyxCollection<Policy> => {
Comment thread
Julesssss marked this conversation as resolved.
Resolved
if (!policies) {
return {};
}

const result: Record<string, Policy> = {};

for (const [id, policyItem] of Object.entries(policies)) {
if (!policyItem) {
continue;
}

result[id] = {
id: policyItem.id,
type: policyItem.type,
name: policyItem.name,
pendingAction: policyItem.pendingAction,
isPolicyExpenseChatEnabled: policyItem.isPolicyExpenseChatEnabled,
role: policyItem.role,
chatReportIDAdmins: policyItem.chatReportIDAdmins,
employeeList: policyItem.employeeList,
arePerDiemRatesEnabled: policyItem.arePerDiemRatesEnabled,
customUnits: policyItem.customUnits,
units: policyItem.units,
isJoinRequestPending: policyItem.isJoinRequestPending,
errors: policyItem.errors,
owner: policyItem.owner,
areInvoicesEnabled: policyItem.areInvoicesEnabled,
} as Policy;
}

return result;
};

export {
activePolicySelector,
createAllPolicyReportFieldsSelector,
Expand All @@ -96,5 +130,6 @@ export {
policyTimeTrackingSelector,
hasMultipleOutputCurrenciesSelector,
groupPaidPoliciesWithExpenseChatEnabledSelector,
iouRequestPolicyCollectionSelector,
shouldRedirectToExpensifyClassicSelector,
};
Loading