Skip to content

Decompose MoneyRequestConfirmationList into view-model hooks#88720

Merged
marcochavezf merged 13 commits intoExpensify:mainfrom
callstack-internal:decompose-MoneyRequestConfirmationList
Apr 30, 2026
Merged

Decompose MoneyRequestConfirmationList into view-model hooks#88720
marcochavezf merged 13 commits intoExpensify:mainfrom
callstack-internal:decompose-MoneyRequestConfirmationList

Conversation

@OlimpiaZurek
Copy link
Copy Markdown
Contributor

@OlimpiaZurek OlimpiaZurek commented Apr 24, 2026

Explanation of Change

MoneyRequestConfirmationList had grown to ~1,211 lines, mixing rendering with business logic for policy/category/tag fetching, distance/tax/amount derivation, split-share dispatch, validation, error translation, and section building. This PR extracts that logic into focused hooks and one component:

  • useFormErrorManagement — owns form-error state + translated errorMessage, replacing the inline fallback ladder
  • useConfirmationValidation / useConfirmAction — own the validate+submit path, including delegate-access gating and split-bill fan-out
  • useSplitParticipants — owns split rows and onSplitShareChange dispatch, so the parent no longer derives the callback
  • useConfirmationSections — owns the SelectionList section data; parent no longer imports Section or section helpers
  • useTransactionReportForConfirmation — fetches the thread report via useOnyx with a narrow .type-only selector
  • usePolicyCategoriesForConfirmation / usePolicyTagsForConfirmation — own the collection subs (draft + real), eliminating parent re-renders on every POLICY_CATEGORIES / POLICY_TAGS fire
  • useDistanceRequestState / useTaxAmount / useConfirmationAmount / useConfirmationCtaText — own their respective derivation chains
    - useReceiptTraining — owns test-receipt detection + product-training tooltip wiring; parent no longer calls useProductTrainingContext
    ConfirmationFooterContent — renders the CTA + error surface as a dedicated subtree, replacing the inline listFooterContent JSX

Dead code removed: unused translate/useLocalize, duplicate routeError, inline onSplitShareChange and errorMessage memos, and parent imports of setIndividualShare, convertToBackendAmount, getIOUConfirmationOptionsFromPayeePersonalDetail, isSelectedManagerMcTest, useProductTrainingContext, and Section.

The net result is MoneyRequestConfirmationList going from ~1,211 lines to ~625 lines, with data subscriptions and action logic owned by the hooks that have the right data access

Fixed Issues

$ #88725
PROPOSAL:

Tests

  • Verify that no errors appear in the JS console
  1. Open an expense chat, then FAB → Create expense → Manual
  2. Enter an amount and select a participant; verify the confirmation screen opens
  3. Verify all fields render correctly: amount, merchant, category, tag, tax, attendees, description, date, billable toggle, and receipt preview (when present)
  4. Tap the confirm CTA and verify the expense is created on the correct report with correct data

Offline tests

QA Steps

// TODO: These must be filled out, or the issue title must include "[No QA]."

same as tests

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 24, 2026

@OlimpiaZurek OlimpiaZurek marked this pull request as ready for review April 24, 2026 14:03
@OlimpiaZurek OlimpiaZurek requested review from a team as code owners April 24, 2026 14:03
@melvin-bot melvin-bot Bot requested review from marcochavezf and trjExpensify and removed request for a team April 24, 2026 14:03
@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented Apr 24, 2026

@marcochavezf Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@trjExpensify trjExpensify removed their request for review April 24, 2026 14:43
@trjExpensify
Copy link
Copy Markdown
Contributor

PR doesn’t need product input as a refactor PR. Unassigning and unsubscribing myself.

@mountiny
Copy link
Copy Markdown
Contributor

@codex review

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR refactors MoneyRequestConfirmationList by extracting its business logic, Onyx subscriptions, validation, derivations, and footer rendering into dedicated hooks and a footer component—aiming to reduce component size and limit re-renders in the Create Expense confirmation flow.

Changes:

  • Added a suite of confirmation-focused hooks (policy categories/tags, report subscription, validation/confirm action, amount/tax/distance derivations, split participants, receipt training, section building, and form-error management).
  • Introduced ConfirmationFooterContent as a dedicated CTA + error surface subtree.
  • Updated MoneyRequestConfirmationList to consume the new hooks/components and removed inlined logic/imports accordingly.

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/components/MoneyRequestConfirmationList/hooks/useTransactionReportForConfirmation.ts Adds a narrowed report subscription (type-only selector) for confirmation logic.
src/components/MoneyRequestConfirmationList/hooks/useTaxAmount.ts Extracts tax code/value selection and tax amount derivation into a hook.
src/components/MoneyRequestConfirmationList/hooks/useSplitParticipants.tsx Extracts split participant row construction and split share dispatch/reset UI.
src/components/MoneyRequestConfirmationList/hooks/useReceiptTraining.ts Extracts test-receipt/test-drive/Manager McTest training tooltip state.
src/components/MoneyRequestConfirmationList/hooks/usePolicyTagsForConfirmation.ts Extracts policy-tag Onyx subscription + derived tag list ordering.
src/components/MoneyRequestConfirmationList/hooks/usePolicyCategoriesForConfirmation.ts Extracts real/draft policy categories subscriptions with fallback.
src/components/MoneyRequestConfirmationList/hooks/useFormErrorManagement.ts Centralizes form error state, debouncing, violation clearing, and error message derivation.
src/components/MoneyRequestConfirmationList/hooks/useDistanceRequestState.ts Extracts distance request rate/unit/currency derivation and recalculation flags.
src/components/MoneyRequestConfirmationList/hooks/useConfirmationValidation.ts Extracts pure validation checks into a reusable hook returning structured results.
src/components/MoneyRequestConfirmationList/hooks/useConfirmationSections.ts Extracts SelectionList section-building (split vs non-split) into a hook.
src/components/MoneyRequestConfirmationList/hooks/useConfirmationCtaText.ts Extracts confirm CTA label derivation into a hook returning dropdown options.
src/components/MoneyRequestConfirmationList/hooks/useConfirmationAmount.ts Extracts confirmation amount formatting + per-attendee calculation logic.
src/components/MoneyRequestConfirmationList/hooks/useConfirmAction.ts Extracts confirm click handler (invoice routing, validate, confirm/send-money side effects).
src/components/MoneyRequestConfirmationList/ConfirmationFooterContent.tsx Adds a dedicated footer component for CTA + error rendering and tooltip wiring.
src/components/MoneyRequestConfirmationList.tsx Wires the extracted hooks/components into the main confirmation list and removes inlined logic.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +133 to +134
const isSplitModified = !!transaction?.splitShares && Object.keys(transaction.splitShares).some((key) => transaction.splitShares?.[Number(key) ?? -1]?.isModified);

Copy link

Copilot AI Apr 24, 2026

Choose a reason for hiding this comment

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

isSplitModified is computed on every render via Object.keys(...).some(...). In the original component this was memoized; keeping it un-memoized here can reintroduce avoidable work during typing in split inputs. Consider restoring useMemo keyed off transaction?.splitShares (or deriving it inside the existing splitParticipants memo).

Suggested change
const isSplitModified = !!transaction?.splitShares && Object.keys(transaction.splitShares).some((key) => transaction.splitShares?.[Number(key) ?? -1]?.isModified);
const isSplitModified = useMemo(() => {
if (!transaction?.splitShares) {
return false;
}
return Object.keys(transaction.splitShares).some((key) => transaction.splitShares?.[Number(key) ?? -1]?.isModified);
}, [transaction?.splitShares]);

Copilot uses AI. Check for mistakes.
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.

No needed as react compiler memoizes this automatically

Comment on lines +13 to +21
type UseConfirmationSectionsParams = {
isTypeSplit: boolean;
shouldHideToSection: boolean;
canEditParticipant: boolean;
payeePersonalDetails: OnyxEntry<OnyxTypes.PersonalDetails> | CurrentUserPersonalDetails;
splitParticipants: MoneyRequestConfirmationListItem[];
selectedParticipants: Participant[];
getSplitSectionHeader: () => React.JSX.Element;
};
Copy link

Copilot AI Apr 24, 2026

Choose a reason for hiding this comment

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

UseConfirmationSectionsParams references React.JSX.Element but this module doesn’t import React, which will fail TypeScript compilation under strict (no global React namespace). Import React as a type (or switch the type to JSX.Element).

Copilot uses AI. Check for mistakes.
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.

Fixed

@mountiny mountiny requested a review from mkhutornyi April 24, 2026 15:08
@mountiny
Copy link
Copy Markdown
Contributor

@mkhutornyi all yours

@chatgpt-codex-connector
Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@MelvinBot
Copy link
Copy Markdown
Contributor

Code Review

Clean decomposition overall — the hook boundaries are well-chosen and the validation/action split is a nice improvement. Two issues to flag:

1. footerContent is now always truthy (behavioral regression)

The original useMemo returned undefined when isReadOnly=true. Now footerContent is always <ConfirmationFooterContent ... /> — a React element that's truthy even when the component renders null.

This breaks two checks in BaseSelectionListWithSections:

  • Line 96: !footerContent && safeAreaPaddingBottomStyle — safe area padding is now never applied when isReadOnly=true
  • Line 413: {!!footerContent && ...} — the footer wrapper now always renders (with an empty child)

Fix: Conditionally render in the parent instead:

footerContent={
    isReadOnly ? undefined : (
        <ConfirmationFooterContent ... />
    )
}

And remove the isReadOnly prop/check from ConfirmationFooterContent.

2. getSplitSectionHeader lost its useCallback wrapper

In useSplitParticipants, getSplitSectionHeader is now a plain function (not wrapped in useCallback). Since it's a dependency of useConfirmationSections's useMemo, sections recompute on every render — defeating the memoization.

Fix: Wrap it in useCallback with the same deps the original had (isSplitModified, shouldShowReadOnlySplits, transaction, translate, relevant styles).

@mkhutornyi
Copy link
Copy Markdown
Contributor

mkhutornyi commented Apr 26, 2026

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified there are no new alerts related to the canBeMissing param for useOnyx
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
android.mov
Android: mWeb Chrome
iOS: HybridApp
ios.mov
iOS: mWeb Safari
msafari.mov
MacOS: Chrome / Safari
web.mov

Copy link
Copy Markdown
Contributor

@mkhutornyi mkhutornyi left a comment

Choose a reason for hiding this comment

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

Please remove all manual memoizations in components and new hooks

Comment thread src/components/MoneyRequestConfirmationList.tsx
Comment thread src/components/MoneyRequestConfirmationList.tsx
Comment thread src/components/MoneyRequestConfirmationList.tsx
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a4653a0d51

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/components/MoneyRequestConfirmationList.tsx
@mkhutornyi
Copy link
Copy Markdown
Contributor

We should have unit tests for all new hooks.
@MelvinBot suggest code changes

@MelvinBot
Copy link
Copy Markdown
Contributor

Regression & Consistency Audit

I did a line-by-line comparison of every extracted hook against the original MoneyRequestConfirmationList.tsx. Core logic is faithfully preserved — all 19 validation checks, the confirm/PAY branching, distance/tax/amount computations, and split participant building produce identical results. Three issues found:

Correction to my earlier review

My earlier comment about footerContent always being truthy was wrong — the PR already guards it with isReadOnly ? undefined : <ConfirmationFooterContent ... /> at MoneyRequestConfirmationList.tsx:463. That issue does not exist. Apologies for the noise.


1. getSplitSectionHeader lost its useCallback (still valid from earlier review)

In useSplitParticipants.tsx:101, getSplitSectionHeader is a plain function that creates a new reference every render. It flows into useConfirmationSections.ts as a useMemo dependency, defeating that memoization.

Fix: Wrap in useCallback with deps [isSplitModified, shouldShowReadOnlySplits, transaction, translate, styles.*].

2. memo() removed from MoneyRequestConfirmationList export

The original had export default memo(MoneyRequestConfirmationList). The PR changes it to a bare export at MoneyRequestConfirmationList.tsx:617. This is a large component in a user-facing flow — every parent re-render now triggers a full re-render of this tree regardless of prop changes.

If this is intentional (perhaps relying on the hooks' internal memoization instead), it would be worth noting in the PR description.

3. formErrorRef pattern has a subtle timing difference vs the original

Details

The original useEffect read formError directly from its closure but intentionally excluded it from the dependency array (eslint-disable). This means it always read the stale formError from whenever the effect was last created by another dep change.

The new version in useFormErrorManagement.ts:123-155 uses formErrorRef.current, which reads the latest value. When formError changes in the same render cycle as another dependency (e.g., isFocused), the original reads the old value while the new code reads the current one.

This is an edge case unlikely to cause user-visible bugs, but it's technically not identical behavior.


Everything else checks out: validation order, PAY branch gating, delegate-access checks, distance/rate/tax calculations, per-diem amounts, split share dispatch, CTA text, policy category/tag fallbacks, receipt training detection, and the errorMessage derivation all match the original semantics.

@MelvinBot
Copy link
Copy Markdown
Contributor

Here are suggested unit tests for the new hooks. I've prioritized the hooks with the most logic — useConfirmationValidation, useConfirmAction, useConfirmationAmount, useFormErrorManagement, and useConfirmationCtaText. The thinner wrappers (usePolicyCategoriesForConfirmation, usePolicyTagsForConfirmation, useTransactionReportForConfirmation, useReceiptTraining, useDistanceRequestState, useTaxAmount) can follow similar patterns with Onyx-based setup.

All tests go in tests/unit/hooks/ following the existing convention.

useConfirmationValidation.test.ts — the highest-value tests (pure validation)
import {renderHook} from '@testing-library/react-native';
import useConfirmationValidation from '@components/MoneyRequestConfirmationList/hooks/useConfirmationValidation';
import CONST from '@src/CONST';

// Minimal defaults that pass all validation
const baseParams = {
    transaction: {transactionID: 'txn1', comment: {}, amount: 100} as any,
    transactionReport: undefined,
    transactionID: 'txn1',
    iouType: CONST.IOU.TYPE.SUBMIT as any,
    iouAmount: 100,
    iouMerchant: 'Coffee Shop',
    iouCategory: '',
    iouCurrencyCode: 'USD',
    iouAttendees: [],
    policy: undefined,
    policyTags: undefined,
    policyTagLists: [],
    policyCategories: undefined,
    selectedParticipants: [{accountID: 1}] as any,
    currentUserPersonalDetails: {accountID: 1} as any,
    isEditingSplitBill: false,
    isMerchantRequired: false,
    isMerchantEmpty: false,
    shouldDisplayFieldError: false,
    shouldShowTax: false,
    isDistanceRequest: false,
    isDistanceRequestWithPendingRoute: false,
    isPerDiemRequest: false,
    isTimeRequest: false,
    isNewManualExpenseFlowEnabled: false,
    routeError: undefined,
};

describe('useConfirmationValidation', () => {
    it('returns null when routeError is set', () => {
        const {result} = renderHook(() => useConfirmationValidation({...baseParams, routeError: 'route error'}));
        expect(result.current.validate()).toBeNull();
    });

    it('returns null when transactionID is missing', () => {
        const {result} = renderHook(() => useConfirmationValidation({...baseParams, transactionID: undefined}));
        expect(result.current.validate()).toBeNull();
    });

    it('returns noParticipantSelected when participants are empty', () => {
        const {result} = renderHook(() => useConfirmationValidation({...baseParams, selectedParticipants: []}));
        expect(result.current.validate()).toEqual({errorKey: 'iou.error.noParticipantSelected'});
    });

    it('returns invalidMerchant when merchant exceeds max bytes', () => {
        const longMerchant = 'A'.repeat(CONST.MERCHANT_NAME_MAX_BYTES + 1);
        const {result} = renderHook(() => useConfirmationValidation({...baseParams, iouMerchant: longMerchant}));
        expect(result.current.validate()).toEqual({errorKey: 'iou.error.invalidMerchant'});
    });

    it('returns invalidMerchant when merchant is required but empty', () => {
        const {result} = renderHook(() =>
            useConfirmationValidation({...baseParams, isMerchantRequired: true, isMerchantEmpty: true}),
        );
        expect(result.current.validate()).toEqual({errorKey: 'iou.error.invalidMerchant'});
    });

    it('returns invalidCategoryLength when category exceeds max', () => {
        const longCategory = 'C'.repeat(CONST.API_TRANSACTION_CATEGORY_MAX_LENGTH + 1);
        const {result} = renderHook(() => useConfirmationValidation({...baseParams, iouCategory: longCategory}));
        expect(result.current.validate()).toEqual({errorKey: 'iou.error.invalidCategoryLength'});
    });

    it('returns categoryOutOfPolicy when category is disabled', () => {
        const {result} = renderHook(() =>
            useConfirmationValidation({
                ...baseParams,
                iouCategory: 'Travel',
                policyCategories: {Travel: {enabled: false, name: 'Travel'}} as any,
            }),
        );
        expect(result.current.validate()).toEqual({errorKey: 'violations.categoryOutOfPolicy'});
    });

    it('returns invalidSubrateLength for per-diem with no sub-rates', () => {
        const {result} = renderHook(() =>
            useConfirmationValidation({
                ...baseParams,
                isPerDiemRequest: true,
                transaction: {...baseParams.transaction, comment: {customUnit: {subRates: []}}} as any,
            }),
        );
        expect(result.current.validate()).toEqual({errorKey: 'iou.error.invalidSubrateLength'});
    });

    it('returns distanceAmountTooLarge when distance amount exceeds max', () => {
        const {result} = renderHook(() =>
            useConfirmationValidation({
                ...baseParams,
                isDistanceRequest: true,
                iouAmount: CONST.IOU.MAX_SAFE_AMOUNT + 1,
            }),
        );
        expect(result.current.validate()).toEqual({errorKey: 'iou.error.distanceAmountTooLarge'});
    });

    it('returns genericSmartscanFailureMessage with shouldSetDidConfirmSplit for split with empty fields', () => {
        const {result} = renderHook(() =>
            useConfirmationValidation({
                ...baseParams,
                isEditingSplitBill: true,
                iouAmount: 100,
                // areRequiredFieldsEmpty returns true when transaction has no merchant/amount
                transaction: {transactionID: 'txn1', amount: 0, merchant: '', comment: {}} as any,
                transactionReport: {type: CONST.REPORT.TYPE.IOU} as any,
            }),
        );
        const validationResult = result.current.validate();
        expect(validationResult).toMatchObject({errorKey: 'iou.error.genericSmartscanFailureMessage', shouldSetDidConfirmSplit: true});
    });

    it('returns errorKey: null on successful non-PAY validation', () => {
        const {result} = renderHook(() => useConfirmationValidation(baseParams));
        expect(result.current.validate()).toEqual({errorKey: null});
    });

    it('returns null for PAY type without payment method', () => {
        const {result} = renderHook(() => useConfirmationValidation({...baseParams, iouType: CONST.IOU.TYPE.PAY as any}));
        expect(result.current.validate()).toBeNull();
    });

    it('returns errorKey: null for PAY type with payment method', () => {
        const {result} = renderHook(() => useConfirmationValidation({...baseParams, iouType: CONST.IOU.TYPE.PAY as any}));
        expect(result.current.validate(CONST.IOU.PAYMENT_TYPE.ELSEWHERE as any)).toEqual({errorKey: null});
    });
});
useConfirmAction.test.ts — orchestration branches
import {renderHook, act} from '@testing-library/react-native';
import useConfirmAction from '@components/MoneyRequestConfirmationList/hooks/useConfirmAction';
import CONST from '@src/CONST';

const mockNavigate = jest.fn();
jest.mock('@libs/Navigation/Navigation', () => ({navigate: (...args: unknown[]) => mockNavigate(...args), getActiveRoute: () => '/'}));
jest.mock('@userActions/Policy/Policy', () => ({hasInvoicingDetails: jest.fn(() => true)}));

const baseParams = {
    iouType: CONST.IOU.TYPE.SUBMIT as any,
    policy: undefined,
    transactionID: 'txn1',
    reportID: 'report1',
    routeError: undefined,
    formError: '' as const,
    selectedParticipants: [{accountID: 1}] as any,
    isDelegateAccessRestricted: false,
    validate: jest.fn(() => ({errorKey: null})),
    setFormError: jest.fn(),
    setDidConfirmSplit: jest.fn(),
    showDelegateNoAccessModal: jest.fn(),
    onConfirm: jest.fn(),
    onSendMoney: jest.fn(),
};

describe('useConfirmAction', () => {
    beforeEach(() => jest.clearAllMocks());

    it('calls onConfirm when validation passes for non-PAY type', () => {
        const {result} = renderHook(() => useConfirmAction(baseParams));
        act(() => result.current({paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE as any}));
        expect(baseParams.onConfirm).toHaveBeenCalledWith(baseParams.selectedParticipants);
    });

    it('sets form error when validation returns an error', () => {
        const params = {...baseParams, validate: jest.fn(() => ({errorKey: 'iou.error.invalidMerchant' as const}))};
        const {result} = renderHook(() => useConfirmAction(params));
        act(() => result.current({paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE as any}));
        expect(params.setFormError).toHaveBeenCalledWith('iou.error.invalidMerchant');
        expect(params.onConfirm).not.toHaveBeenCalled();
    });

    it('sets didConfirmSplit when validation result has shouldSetDidConfirmSplit', () => {
        const params = {
            ...baseParams,
            validate: jest.fn(() => ({errorKey: 'iou.error.genericSmartscanFailureMessage' as const, shouldSetDidConfirmSplit: true})),
        };
        const {result} = renderHook(() => useConfirmAction(params));
        act(() => result.current({paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE as any}));
        expect(params.setDidConfirmSplit).toHaveBeenCalledWith(true);
    });

    it('does not call onConfirm when formError is set', () => {
        const params = {...baseParams, formError: 'iou.error.invalidMerchant' as const};
        const {result} = renderHook(() => useConfirmAction(params));
        act(() => result.current({paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE as any}));
        expect(params.onConfirm).not.toHaveBeenCalled();
    });

    it('calls onSendMoney for PAY type with valid payment method', () => {
        const params = {...baseParams, iouType: CONST.IOU.TYPE.PAY as any};
        const {result} = renderHook(() => useConfirmAction(params));
        act(() => result.current({paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE as any}));
        expect(params.onSendMoney).toHaveBeenCalledWith(CONST.IOU.PAYMENT_TYPE.ELSEWHERE);
    });

    it('shows delegate modal for PAY when delegate access restricted', () => {
        const params = {...baseParams, iouType: CONST.IOU.TYPE.PAY as any, isDelegateAccessRestricted: true};
        const {result} = renderHook(() => useConfirmAction(params));
        act(() => result.current({paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE as any}));
        expect(params.showDelegateNoAccessModal).toHaveBeenCalled();
        expect(params.onSendMoney).not.toHaveBeenCalled();
    });
});
useConfirmationCtaText.test.ts — CTA label derivation
import {renderHook} from '@testing-library/react-native';
import useConfirmationCtaText from '@components/MoneyRequestConfirmationList/hooks/useConfirmationCtaText';
import CONST from '@src/CONST';

const baseParams = {
    expensesNumber: 1,
    isTypeInvoice: false,
    isTypeTrackExpense: false,
    isTypeSplit: false,
    isTypeRequest: false,
    iouAmount: 100,
    iouType: CONST.IOU.TYPE.SUBMIT as any,
    policy: undefined,
    formattedAmount: '$1.00',
    receiptPath: '',
    isDistanceRequestWithPendingRoute: false,
    isPerDiemRequest: false,
    isNewManualExpenseFlowEnabled: false,
};

describe('useConfirmationCtaText', () => {
    it('returns createExpenses text for multiple expenses', () => {
        const {result} = renderHook(() => useConfirmationCtaText({...baseParams, expensesNumber: 3}));
        expect(result.current).toHaveLength(1);
        expect(result.current[0].value).toBe(CONST.IOU.TYPE.SUBMIT);
    });

    it('returns splitExpense for split with zero amount', () => {
        const {result} = renderHook(() => useConfirmationCtaText({...baseParams, isTypeSplit: true, iouAmount: 0}));
        expect(result.current[0].text.toLowerCase()).toContain('split');
    });

    it('returns createExpense for track expense', () => {
        const {result} = renderHook(() =>
            useConfirmationCtaText({...baseParams, isTypeTrackExpense: true, iouType: CONST.IOU.TYPE.TRACK as any}),
        );
        expect(result.current[0].text.toLowerCase()).toContain('expense');
    });

    it('returns createExpense when new manual expense flow is enabled', () => {
        const {result} = renderHook(() => useConfirmationCtaText({...baseParams, isNewManualExpenseFlowEnabled: true}));
        expect(result.current[0].text.toLowerCase()).toContain('expense');
    });

    it('capitalizes the first letter', () => {
        const {result} = renderHook(() => useConfirmationCtaText(baseParams));
        expect(result.current[0].text[0]).toBe(result.current[0].text[0].toUpperCase());
    });
});
Lighter hooks — suggested test cases (brief)

useFormErrorManagement.test.ts: Test that shouldDisplayFieldError is false when not editing a split bill, true when hasSmartScanFailed + split with missing fields; test that clearFormErrors clears only matching errors; test errorMessage returns routeError when present, debounced error for split, and undefined for violations.missingAttendees.

useConfirmationAmount.test.ts: Test amount sources — distance overrides iouAmount when shouldCalculateDistanceAmount, per-diem overrides when sub-rates change, and formattedAmount is empty string for pending route.

useConfirmationSections.test.ts: Test split type produces two sections (paidBy + participants), non-split produces one "to" section, and shouldHideToSection produces empty array.

useSplitParticipants.test.tsx: Test returns empty array for non-split; returns read-only rows with amount text for shouldShowReadOnlySplits; returns editable MoneyRequestAmountInput rows otherwise.

useDistanceRequestState.test.ts, useTaxAmount.test.ts: These rely on Onyx subscriptions — use Onyx.merge to set policy drafts and assert derived values.

usePolicyCategoriesForConfirmation.test.ts, usePolicyTagsForConfirmation.test.ts, useTransactionReportForConfirmation.test.ts: These are thin Onyx wrappers — test that they return data from Onyx, with categories falling back to draft when real is null.

useReceiptTraining.test.ts: Test isTestReceipt reflects transaction.receipt.isTestReceipt.


⚠️ I can't push changes to this PR because I didn't open it and I'm not listed as an assignee. To have me make this fix, add me to the PR assignees and then retry your request.

@mkhutornyi
Copy link
Copy Markdown
Contributor

@OlimpiaZurek please add unit tests with the help of Melvin's suggestions.
Otherwise looks good.

@mountiny
Copy link
Copy Markdown
Contributor

Ping me when this is ready @mkhutornyi @OlimpiaZurek

@OlimpiaZurek
Copy link
Copy Markdown
Contributor Author

@vit It’s ready now

mountiny
mountiny previously approved these changes Apr 27, 2026
Copy link
Copy Markdown
Contributor

@mountiny mountiny left a comment

Choose a reason for hiding this comment

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

Minor things but good to address please @OlimpiaZurek

@marcochavezf I will be ooo, can you please handle the pr review?

Comment thread src/components/MoneyRequestConfirmationList/ConfirmationFooterContent.tsx Outdated
Comment on lines +18 to +31
iouType: IOUType;
confirm: (params: PaymentActionParams) => void;
iouCurrencyCode: string;
policyID: string | undefined;
reportID: string;
isConfirmed: boolean | undefined;
isConfirming: boolean | undefined;
isLoadingReceipt: boolean;
splitOrRequestOptions: Array<DropdownOption<string>>;
errorMessage: string | undefined;
expensesNumber: number;
showRemoveExpenseConfirmModal: (() => void) | undefined;
shouldShowProductTrainingTooltip: boolean;
renderProductTrainingTooltip: () => React.ReactElement;
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.

docs

Comment on lines +15 to +28
iouType: IOUType;
policy: OnyxEntry<OnyxTypes.Policy>;
transactionID: string | undefined;
reportID: string;
routeError: boolean | string | null | undefined;
formError: TranslationPaths | '';
selectedParticipants: Participant[];
isDelegateAccessRestricted: boolean;
validate: (paymentType?: PaymentMethodType) => {errorKey: TranslationPaths; shouldSetDidConfirmSplit?: boolean} | {errorKey: null} | null;
setFormError: (error: TranslationPaths | '') => void;
setDidConfirmSplit: (value: boolean) => void;
showDelegateNoAccessModal: () => void;
onConfirm?: (selectedParticipants: Participant[]) => void;
onSendMoney?: (paymentMethod: PaymentMethodType | undefined) => void;
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.

docs

Comment on lines +10 to +17
transaction: OnyxEntry<OnyxTypes.Transaction>;
policy: OnyxEntry<OnyxTypes.Policy>;
policyForMovingExpenses: OnyxEntry<OnyxTypes.Policy> | undefined;
isDistanceRequest: boolean;
isMovingTransactionFromTrackExpense: boolean;
customUnitRateID: string;
distance: number;
previousTransactionCurrency: string | undefined;
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.

docs

Comment on lines +20 to +26
isTypeSplit: boolean;
shouldShowReadOnlySplits: boolean;
payeePersonalDetails: OnyxEntry<OnyxTypes.PersonalDetails> | CurrentUserPersonalDetails;
selectedParticipants: Participant[];
transaction: OnyxEntry<OnyxTypes.Transaction>;
iouAmount: number;
iouCurrencyCode: string | undefined;
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.

docs

currentUserPersonalDetails: CurrentUserPersonalDetails;
isEditingSplitBill: boolean | undefined;
isMerchantRequired: boolean | undefined;
isMerchantEmpty: boolean;
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.

docs

type ValidationResult = {errorKey: TranslationPaths; shouldSetDidConfirmSplit?: boolean} | {errorKey: null};

type UseConfirmationValidationParams = {
transaction: OnyxEntry<OnyxTypes.Transaction>;
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.

docs

type MoneyRequestConfirmationListItem = (Participant & {keyForList: string}) | OptionData;

type UseConfirmationSectionsParams = {
isTypeSplit: boolean;
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.

docs

Comment on lines +9 to +21
expensesNumber: number;
isTypeInvoice: boolean;
isTypeTrackExpense: boolean;
isTypeSplit: boolean;
isTypeRequest: boolean;
iouAmount: number;
iouType: IOUType;
policy: OnyxEntry<OnyxTypes.Policy>;
formattedAmount: string;
receiptPath: string | number;
isDistanceRequestWithPendingRoute: boolean;
isPerDiemRequest: boolean;
isNewManualExpenseFlowEnabled: boolean;
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.

docs

Comment on lines +12 to +24
transaction: OnyxEntry<OnyxTypes.Transaction>;
iouAmount: number;
iouCurrencyCode: string | undefined;
iouAttendees: ReturnType<typeof getAttendees>;
isDistanceRequest: boolean;
isDistanceRequestWithPendingRoute: boolean;
shouldCalculateDistanceAmount: boolean;
distanceRequestAmount: number;
distanceCurrency: string | undefined;
isPerDiemRequest: boolean;
prevCurrency: string | undefined;
currency: string | undefined;
prevSubRates: SubRates;
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.

docs

@marcochavezf
Copy link
Copy Markdown
Contributor

@codex @MelvinBot review

@MelvinBot
Copy link
Copy Markdown
Contributor

Code Review (updated)

Clean decomposition — logic correctness is preserved throughout, and the 1,211→625 line reduction is a meaningful readability win. All CI checks pass, tests cover the critical paths well. Two items to flag:

1. Performance: blanket memoization removal in a high-traffic component

All useMemo, useCallback, and memo() wrappers were removed. This component renders on every expense creation flow, so the cumulative effect matters:

I understand this was done per reviewer request. If this is intentional (relying on React Compiler or hooks-level optimization), it would be worth noting in the PR description for future context. Otherwise, consider re-adding at minimum memo() on the export and memoizing the split participant JSX elements.

2. Test gap: useFormErrorManagement has no tests

This is the most complex hook (debounced state, ref-based effect synchronization, violation-fixed logic, error message computation with multiple fallback paths). The other hooks all have tests. Adding coverage here would significantly improve regression safety.

Nit: routeError type inconsistency

confirmAction.ts:28 and useConfirmationValidation.ts:99 type routeError as boolean | string | null | undefined, but the actual value (from OnyxCommon.Errors) can only be string | null | undefined. useFormErrorManagement.ts:63 already has the correct type.

Everything else — validation order, PAY/split branching, delegate access checks, distance/tax/amount derivations, policy category/tag fallbacks, receipt training, CTA text — checks out.

@marcochavezf
Copy link
Copy Markdown
Contributor

Nit: routeError type inconsistency
confirmAction.ts:28 and useConfirmationValidation.ts:99 type routeError as boolean | string | null | undefined, but the actual value (from OnyxCommon.Errors) can only be string | null | undefined. useFormErrorManagement.ts:63 already has the correct type.

I think this one is valid. Should we pick one of string | null | undefined and apply it to all three files? @OlimpiaZurek wdyt?

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e01a902053

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@OlimpiaZurek
Copy link
Copy Markdown
Contributor Author

Nit: routeError type inconsistency
confirmAction.ts:28 and useConfirmationValidation.ts:99 type routeError as boolean | string | null | undefined, but the actual value (from OnyxCommon.Errors) can only be string | null | undefined. useFormErrorManagement.ts:63 already has the correct type.

I think this one is valid. Should we pick one of string | null | undefined and apply it to all three files? @OlimpiaZurek wdyt?

Agreed, changed

Copy link
Copy Markdown
Contributor

@marcochavezf marcochavezf left a comment

Choose a reason for hiding this comment

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

LGTM

@marcochavezf marcochavezf merged commit c300f98 into Expensify:main Apr 30, 2026
34 checks passed
@github-actions
Copy link
Copy Markdown
Contributor

🚧 @marcochavezf has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify
Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/marcochavezf in version: 9.3.65-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

@MelvinBot
Copy link
Copy Markdown
Contributor

I reviewed the changes in this PR. It is a pure internal refactoring — decomposing MoneyRequestConfirmationList into focused view-model hooks and a sub-component (ConfirmationFooterContent).

There are no user-facing changes: no new features, no removed features, no UI label changes, no navigation changes, and no settings changes. The expense confirmation screen renders and behaves identically before and after this PR.

No help site documentation changes are required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants