Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Expense details - Violation is not displayed on description field when opening IOU details. #56405

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

Krishna2323
Copy link
Contributor

@Krishna2323 Krishna2323 commented Feb 5, 2025

Explanation of Change

Fixed Issues

$ #56310
PROPOSAL:

Tests

  1. Create an IOU request in the workspace chat with a category (Advertising)
  2. Go to Reports page
  3. Go to workspace settings page > Categories
  4. Disable the category you have selected on step 2
  5. Return to Reports page
  6. Click on Review button of the money request
  7. Verify violation is displayed on Category field on the first visit to the IOU details page
  • Verify that no errors appear in the JS console

Offline tests

  • Violation is returned from backend so this can't be tested on offline.

QA Steps

  1. Create an IOU request in the workspace chat with a category (Advertising)
  2. Go to Reports page
  3. Go to workspace settings page > Categories
  4. Disable the category you have selected on step 2
  5. Return to Reports page
  6. Click on Review button of the money request
  7. Verify violation is displayed on Category field on the first visit to the IOU details page
  • 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
    • MacOS: Desktop
  • 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 verified the translation was requested/reviewed 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.js 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 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.
  • 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_native.mp4
Android: mWeb Chrome
android_chrome.mp4
iOS: Native
ios_native.mp4
iOS: mWeb Safari
ios_safari.mp4
MacOS: Chrome / Safari
web_chrome.mp4
MacOS: Desktop
desktop_app.mp4

…d when opening IOU details.

Signed-off-by: krishna2323 <[email protected]>
@rojiphil
Copy link
Contributor

rojiphil commented Feb 5, 2025

@Krishna2323 We need to fix typescript check errors

Signed-off-by: krishna2323 <[email protected]>
@Krishna2323
Copy link
Contributor Author

Krishna2323 commented Feb 5, 2025

@rojiphil, the jest test fail is not related to this PR.

@Krishna2323 Krishna2323 marked this pull request as ready for review February 5, 2025 15:01
@Krishna2323 Krishna2323 requested a review from a team as a code owner February 5, 2025 15:01
@melvin-bot melvin-bot bot requested a review from jjcoffee February 5, 2025 15:01
Copy link

melvin-bot bot commented Feb 5, 2025

@jjcoffee 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]

@melvin-bot melvin-bot bot removed the request for review from a team February 5, 2025 15:01
@Krishna2323
Copy link
Contributor Author

@rojiphil, checklist completed.

@Krishna2323
Copy link
Contributor Author

cc: @mjasikowski

@rojiphil
Copy link
Contributor

rojiphil commented Feb 5, 2025

@jjcoffee Please note that I am reviewing this as this is part of a regression fix

@rojiphil
Copy link
Contributor

rojiphil commented Feb 5, 2025

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 tests pass on all platforms & I tested again on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • 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 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

MacOS: Chrome / Safari
56405-web-chrome-001.mp4
56405-web-chrome-002.mp4
MacOS: Desktop
56405-desktop-001.mp4
Android: Native
56405-android-native-001.mp4
Android: mWeb Chrome
56405-mweb-chrome-001.mp4
iOS: Native
56405-ios-native-001.mp4
iOS: mWeb Safari
56405-mweb-safari-001.mp4

@rojiphil
Copy link
Contributor

rojiphil commented Feb 5, 2025

@rojiphil, the jest test fail is not related to this PR.

@Krishna2323 The unit tests failure looks completely unrelated to our PR but I also don’t find the tests failure in any of the recent PRs. Can you please double check on this?

@Krishna2323
Copy link
Contributor Author

@rojiphil, merging main fixed the failing test.

Copy link
Contributor

@rojiphil rojiphil left a comment

Choose a reason for hiding this comment

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

Thanks @Krishna2323 for the quick fix.
Changes LGTM and works well.
@mjasikowski All yours for review. Thanks.

Copy link
Contributor

@roryabraham roryabraham left a comment

Choose a reason for hiding this comment

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

This implementation looks pretty inefficient. We don't need to subscribe to all transaction violations while we're looking at only one transaction:

diff --git a/src/components/BrokenConnectionDescription.tsx b/src/components/BrokenConnectionDescription.tsx
index a61a7a3f976..480283a6024 100644
--- a/src/components/BrokenConnectionDescription.tsx
+++ b/src/components/BrokenConnectionDescription.tsx
@@ -5,7 +5,7 @@ import useLocalize from '@hooks/useLocalize';
 import useThemeStyles from '@hooks/useThemeStyles';
 import {isInstantSubmitEnabled, isPolicyAdmin as isPolicyAdminPolicyUtils} from '@libs/PolicyUtils';
 import {isCurrentUserSubmitter, isProcessingReport, isReportApproved, isReportManuallyReimbursed} from '@libs/ReportUtils';
-import {getTransactionViolations} from '@libs/TransactionUtils';
+import {isViolationDismissed} from '@libs/TransactionUtils';
 import Navigation from '@navigation/Navigation';
 import CONST from '@src/CONST';
 import ONYXKEYS from '@src/ONYXKEYS';
@@ -26,8 +26,9 @@ type BrokenConnectionDescriptionProps = {
 function BrokenConnectionDescription({transactionID, policy, report}: BrokenConnectionDescriptionProps) {
     const styles = useThemeStyles();
     const {translate} = useLocalize();
-    const [allTransactionViolations] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}`);
-    const transactionViolations = getTransactionViolations(transactionID, allTransactionViolations);
+    const [transactionViolations] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, {
+        selector: (violations) => (violations ?? []).filter((violation) => !isViolationDismissed(transactionID, violation)),
+    });
 
     const brokenConnection530Error = transactionViolations?.find((violation) => violation.data?.rterType === CONST.RTER_VIOLATION_TYPES.BROKEN_CARD_CONNECTION_530);
     const brokenConnectionError = transactionViolations?.find((violation) => violation.data?.rterType === CONST.RTER_VIOLATION_TYPES.BROKEN_CARD_CONNECTION);

Edit: I found a lot of ways to improve this code and to make it more efficient. Here's a full diff:

Full diff
diff --git a/src/components/BrokenConnectionDescription.tsx b/src/components/BrokenConnectionDescription.tsx
index a61a7a3f976..786e9831b99 100644
--- a/src/components/BrokenConnectionDescription.tsx
+++ b/src/components/BrokenConnectionDescription.tsx
@@ -5,7 +5,7 @@ import useLocalize from '@hooks/useLocalize';
 import useThemeStyles from '@hooks/useThemeStyles';
 import {isInstantSubmitEnabled, isPolicyAdmin as isPolicyAdminPolicyUtils} from '@libs/PolicyUtils';
 import {isCurrentUserSubmitter, isProcessingReport, isReportApproved, isReportManuallyReimbursed} from '@libs/ReportUtils';
-import {getTransactionViolations} from '@libs/TransactionUtils';
+import {isViolationDismissed} from '@libs/TransactionUtils';
 import Navigation from '@navigation/Navigation';
 import CONST from '@src/CONST';
 import ONYXKEYS from '@src/ONYXKEYS';
@@ -26,8 +26,15 @@ type BrokenConnectionDescriptionProps = {
 function BrokenConnectionDescription({transactionID, policy, report}: BrokenConnectionDescriptionProps) {
     const styles = useThemeStyles();
     const {translate} = useLocalize();
-    const [allTransactionViolations] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}`);
-    const transactionViolations = getTransactionViolations(transactionID, allTransactionViolations);
+    const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`);
+    const [transactionViolations] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, {
+        selector: (violations) => {
+            if (!transaction) {
+                return [];
+            }
+            return (violations ?? []).filter((violation) => !isViolationDismissed(transaction, violation));
+        },
+    });
 
     const brokenConnection530Error = transactionViolations?.find((violation) => violation.data?.rterType === CONST.RTER_VIOLATION_TYPES.BROKEN_CARD_CONNECTION_530);
     const brokenConnectionError = transactionViolations?.find((violation) => violation.data?.rterType === CONST.RTER_VIOLATION_TYPES.BROKEN_CARD_CONNECTION);
diff --git a/src/components/MoneyRequestHeader.tsx b/src/components/MoneyRequestHeader.tsx
index 684335d3d27..68f3a7ecc76 100644
--- a/src/components/MoneyRequestHeader.tsx
+++ b/src/components/MoneyRequestHeader.tsx
@@ -15,7 +15,6 @@ import {getOriginalMessage, isMoneyRequestAction} from '@libs/ReportActionsUtils
 import {isCurrentUserSubmitter} from '@libs/ReportUtils';
 import {
     allHavePendingRTERViolation,
-    getTransactionViolations,
     hasPendingRTERViolation,
     hasReceipt,
     isDuplicate as isDuplicateTransactionUtils,
@@ -23,6 +22,7 @@ import {
     isOnHold as isOnHoldTransactionUtils,
     isPending,
     isReceiptBeingScanned,
+    isViolationDismissed,
     shouldShowBrokenConnectionViolation as shouldShowBrokenConnectionViolationTransactionUtils,
 } from '@libs/TransactionUtils';
 import variables from '@styles/variables';
@@ -67,7 +67,14 @@ function MoneyRequestHeader({report, parentReportAction, policy, onBackButtonPre
             isMoneyRequestAction(parentReportAction) ? getOriginalMessage(parentReportAction)?.IOUTransactionID ?? CONST.DEFAULT_NUMBER_ID : CONST.DEFAULT_NUMBER_ID
         }`,
     );
-    const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
+    const [transactionViolations] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transaction?.transactionID ?? '-1'}`, {
+        selector: (violations) => {
+            if (!transaction) {
+                return [];
+            }
+            return (violations ?? []).filter((violation) => !isViolationDismissed(transaction, violation));
+        },
+    });
     const [dismissedHoldUseExplanation, dismissedHoldUseExplanationResult] = useOnyx(ONYXKEYS.NVP_DISMISSED_HOLD_USE_EXPLANATION, {initialValue: true});
     const [isLoadingReportData] = useOnyx(ONYXKEYS.IS_LOADING_REPORT_DATA);
     const isLoadingHoldUseExplained = isLoadingOnyxValue(dismissedHoldUseExplanationResult);
@@ -122,7 +129,7 @@ function MoneyRequestHeader({report, parentReportAction, policy, onBackButtonPre
                 ),
             };
         }
-        if (hasPendingRTERViolation(getTransactionViolations(transaction?.transactionID, allTransactionViolations))) {
+        if (hasPendingRTERViolation(transactionViolations)) {
             return {icon: getStatusIcon(Expensicons.Hourglass), description: translate('iou.pendingMatchWithCreditCardDescription')};
         }
         if (isScanning) {
diff --git a/src/libs/TransactionUtils/index.ts b/src/libs/TransactionUtils/index.ts
index 63f91557e47..4c407696f93 100644
--- a/src/libs/TransactionUtils/index.ts
+++ b/src/libs/TransactionUtils/index.ts
@@ -770,7 +770,12 @@ function getTransactionViolations(transactionID: string | undefined, transaction
     if (!transactionID || !transactionViolations) {
         return null;
     }
-    return transactionViolations?.[ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + transactionID]?.filter((violation) => !isViolationDismissed(transactionID, violation)) ?? null;
+    const transaction = getTransaction(transactionID);
+    if (!transaction) {
+        return null;
+    }
+    const violations = transactionViolations?.[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`] ?? [];
+    return violations.filter((violation) => !isViolationDismissed(transaction, violation));
 }
 
 /**
@@ -918,14 +923,18 @@ function isDuplicate(transactionID: string | undefined, checkDismissed = false):
         (violation: TransactionViolation) => violation.name === CONST.VIOLATIONS.DUPLICATED_TRANSACTION,
     );
 
-    const hasDuplicatedViolation = !!duplicateViolation;
+    const hasDuplicateViolation = !!duplicateViolation;
     if (!checkDismissed) {
         return !!duplicateViolation;
     }
 
-    const didDismissedViolation = isViolationDismissed(transactionID, duplicateViolation);
+    const transaction = getTransaction(transactionID);
+    if (!transaction) {
+        return false;
+    }
 
-    return hasDuplicatedViolation && !didDismissedViolation;
+    const didDismissViolation = hasDuplicateViolation ? isViolationDismissed(transaction, duplicateViolation) : false;
+    return hasDuplicateViolation && !didDismissViolation;
 }
 
 /**
@@ -947,17 +956,14 @@ function isOnHoldByTransactionID(transactionID: string | undefined | null): bool
         return false;
     }
 
-    return isOnHold(allTransactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]);
+    return isOnHold(getTransaction(transactionID));
 }
 
 /**
  * Checks if a violation is dismissed for the given transaction
  */
-function isViolationDismissed(transactionID: string | undefined, violation: TransactionViolation | undefined): boolean {
-    if (!transactionID || !violation) {
-        return false;
-    }
-    return allTransactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]?.comment?.dismissedViolations?.[violation.name]?.[currentUserEmail] === `${currentUserAccountID}`;
+function isViolationDismissed(transaction: Transaction, violation: TransactionViolation): boolean {
+    return transaction.comment?.dismissedViolations?.[violation.name]?.[currentUserEmail] === currentUserAccountID;
 }
 
 /**
@@ -968,14 +974,15 @@ function hasViolation(transactionID: string | undefined, transactionViolations:
         return false;
     }
     const transaction = getTransaction(transactionID);
-    if (isExpensifyCardTransaction(transaction) && isPending(transaction)) {
+    if (!transaction || (isExpensifyCardTransaction(transaction) && isPending(transaction))) {
         return false;
     }
-    return !!transactionViolations?.[ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + transactionID]?.some(
-        (violation: TransactionViolation) =>
+    const violations = transactionViolations?.[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`] ?? [];
+    return violations.some(
+        (violation) =>
             violation.type === CONST.VIOLATION_TYPES.VIOLATION &&
             (showInReview === undefined || showInReview === (violation.showInReview ?? false)) &&
-            !isViolationDismissed(transactionID, violation),
+            !isViolationDismissed(transaction, violation),
     );
 }
 
@@ -987,14 +994,15 @@ function hasNoticeTypeViolation(transactionID: string | undefined, transactionVi
         return false;
     }
     const transaction = getTransaction(transactionID);
-    if (isExpensifyCardTransaction(transaction) && isPending(transaction)) {
+    if (!transaction || (isExpensifyCardTransaction(transaction) && isPending(transaction))) {
         return false;
     }
-    return !!transactionViolations?.[ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + transactionID]?.some(
-        (violation: TransactionViolation) =>
+    const violations = transactionViolations?.[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`] ?? [];
+    return violations.some(
+        (violation) =>
             violation.type === CONST.VIOLATION_TYPES.NOTICE &&
             (showInReview === undefined || showInReview === (violation.showInReview ?? false)) &&
-            !isViolationDismissed(transactionID, violation),
+            !isViolationDismissed(transaction, violation),
     );
 }
 
@@ -1006,19 +1014,19 @@ function hasWarningTypeViolation(transactionID: string | undefined, transactionV
         return false;
     }
     const transaction = getTransaction(transactionID);
-    if (isExpensifyCardTransaction(transaction) && isPending(transaction)) {
+    if (!transaction || (isExpensifyCardTransaction(transaction) && isPending(transaction))) {
         return false;
     }
-    const violations = transactionViolations?.[ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + transactionID];
-    const warningTypeViolations =
-        violations?.filter(
-            (violation: TransactionViolation) =>
-                violation.type === CONST.VIOLATION_TYPES.WARNING &&
-                (showInReview === undefined || showInReview === (violation.showInReview ?? false)) &&
-                !isViolationDismissed(transactionID, violation),
-        ) ?? [];
-
-    const hasOnlyDupeDetectionViolation = warningTypeViolations?.every((violation: TransactionViolation) => violation.name === CONST.VIOLATIONS.DUPLICATED_TRANSACTION);
+    const violations = transactionViolations?.[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`] ?? [];
+    const warningTypeViolations = violations.filter(
+        (violation: TransactionViolation) =>
+            violation.type === CONST.VIOLATION_TYPES.WARNING &&
+            (showInReview === undefined || showInReview === (violation.showInReview ?? false)) &&
+            !isViolationDismissed(transaction, violation),
+    );
+
+    const hasOnlyDupeDetectionViolation =
+        warningTypeViolations.length > 0 && warningTypeViolations.every((violation: TransactionViolation) => violation.name === CONST.VIOLATIONS.DUPLICATED_TRANSACTION);
     if (hasOnlyDupeDetectionViolation) {
         return false;
     }
@@ -1146,11 +1154,10 @@ type FieldsToChange = {
 };
 
 function removeSettledAndApprovedTransactions(transactionIDs: string[]): string[] {
-    return transactionIDs.filter(
-        (transactionID) =>
-            !isSettled(allTransactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]?.reportID) &&
-            !isReportIDApproved(allTransactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]?.reportID),
-    );
+    return transactionIDs.filter((transactionID) => {
+        const reportID = getTransaction(transactionID)?.reportID;
+        return !isSettled(reportID) && !isReportIDApproved(reportID);
+    });
 }
 
 /**
@@ -1337,7 +1344,7 @@ function getTransactionID(threadReportID?: string): string | undefined {
 }
 
 function buildNewTransactionAfterReviewingDuplicates(reviewDuplicateTransaction: OnyxEntry<ReviewDuplicates>): Partial<Transaction> {
-    const originalTransaction = allTransactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${reviewDuplicateTransaction?.transactionID}`] ?? undefined;
+    const originalTransaction = getTransaction(reviewDuplicateTransaction?.transactionID);
     const {duplicates, ...restReviewDuplicateTransaction} = reviewDuplicateTransaction ?? {};
 
     return {
diff --git a/tests/unit/ViolationUtilsTest.ts b/tests/unit/ViolationUtilsTest.ts
index 335cc644ec6..596c6a64fbc 100644
--- a/tests/unit/ViolationUtilsTest.ts
+++ b/tests/unit/ViolationUtilsTest.ts
@@ -402,8 +402,8 @@ describe('getViolations', () => {
 
         await Onyx.multiSet({...transactionCollectionDataSet});
 
-        const isSmartScanDismissed = isViolationDismissed(transaction.transactionID, smartScanFailedViolation);
-        const isDuplicateViolationDismissed = isViolationDismissed(transaction.transactionID, duplicatedTransactionViolation);
+        const isSmartScanDismissed = isViolationDismissed(transaction, smartScanFailedViolation);
+        const isDuplicateViolationDismissed = isViolationDismissed(transaction, duplicatedTransactionViolation);
 
         expect(isSmartScanDismissed).toBeTruthy();
         expect(isDuplicateViolationDismissed).toBeFalsy();

Signed-off-by: krishna2323 <[email protected]>
Signed-off-by: krishna2323 <[email protected]>
Signed-off-by: krishna2323 <[email protected]>
import ONYXKEYS from '@src/ONYXKEYS';
import type {TransactionViolations} from '@src/types/onyx';

function useTransactionViolations(transactionID?: string): TransactionViolations | undefined {
Copy link
Contributor

Choose a reason for hiding this comment

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

Rather that | undefined, why not just return an empty array if there are no violations?

diff --git a/src/hooks/useTransactionViolations.ts b/src/hooks/useTransactionViolations.ts
index 463d8af2730..a99adfbe1c4 100644
--- a/src/hooks/useTransactionViolations.ts
+++ b/src/hooks/useTransactionViolations.ts
@@ -3,8 +3,8 @@ import {getTransaction, isViolationDismissed} from '@libs/TransactionUtils';
 import ONYXKEYS from '@src/ONYXKEYS';
 import type {TransactionViolations} from '@src/types/onyx';
 
-function useTransactionViolations(transactionID?: string): TransactionViolations | undefined {
-    const [transactionViolations] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, {
+function useTransactionViolations(transactionID?: string): TransactionViolations {
+    const [transactionViolations = []] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, {
         selector: (violations) => {
             const transaction = getTransaction(transactionID);
             if (!transaction) {

Copy link
Contributor Author

Choose a reason for hiding this comment

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

updated to use | undefined and return and empty array incase of no violations.

function useTransactionViolations(transactionID?: string): TransactionViolations | undefined {
const [transactionViolations] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, {
selector: (violations) => {
const transaction = getTransaction(transactionID);
Copy link
Contributor

Choose a reason for hiding this comment

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

Thinking about this carefully, one concern I have with this implementation is that there's nothing that will re-run this selector when the transaction changes. You're getting an up-to-date version of the transaction in the selector only when the violations change, not when the transaction changes. You could fix this like so:

diff --git a/src/hooks/useTransactionViolations.ts b/src/hooks/useTransactionViolations.ts
index 463d8af2730..6d856261201 100644
--- a/src/hooks/useTransactionViolations.ts
+++ b/src/hooks/useTransactionViolations.ts
@@ -1,19 +1,13 @@
+import {useMemo} from 'react';
 import {useOnyx} from 'react-native-onyx';
-import {getTransaction, isViolationDismissed} from '@libs/TransactionUtils';
+import {isViolationDismissed} from '@libs/TransactionUtils';
 import ONYXKEYS from '@src/ONYXKEYS';
 import type {TransactionViolations} from '@src/types/onyx';
 
-function useTransactionViolations(transactionID?: string): TransactionViolations | undefined {
-    const [transactionViolations] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, {
-        selector: (violations) => {
-            const transaction = getTransaction(transactionID);
-            if (!transaction) {
-                return [];
-            }
-            return (violations ?? []).filter((violation) => !isViolationDismissed(transaction, violation));
-        },
-    });
-    return transactionViolations;
+function useTransactionViolations(transactionID?: string): TransactionViolations {
+    const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`);
+    const [transactionViolations = []] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`);
+    return useMemo(() => transactionViolations.filter((violation) => !isViolationDismissed(transaction, violation)), [transaction, transactionViolations]);
 }
 
 export default useTransactionViolations;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

🧠 thanks for the catch🙌🏻, updated the hook.

@@ -133,6 +133,7 @@ function MoneyReportHeader({policy, report: moneyRequestReport, transactionThrea
const isOnHold = isOnHoldTransactionUtils(transaction);
const isDeletedParentAction = !!requestParentReportAction && isDeletedAction(requestParentReportAction);
const isDuplicate = isDuplicateTransactionUtils(transaction?.transactionID);
const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
Copy link
Contributor

Choose a reason for hiding this comment

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

NAB because we need to get this merged and CP'd, but we could also optimize this to only select the violations for the transactions that we care about, so the component doesn't re-render if other violations change:

diff --git a/src/components/MoneyReportHeader.tsx b/src/components/MoneyReportHeader.tsx
index 45585a03b14..f157668ee44 100644
--- a/src/components/MoneyReportHeader.tsx
+++ b/src/components/MoneyReportHeader.tsx
@@ -133,7 +133,6 @@ function MoneyReportHeader({policy, report: moneyRequestReport, transactionThrea
     const isOnHold = isOnHoldTransactionUtils(transaction);
     const isDeletedParentAction = !!requestParentReportAction && isDeletedAction(requestParentReportAction);
     const isDuplicate = isDuplicateTransactionUtils(transaction?.transactionID);
-    const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
 
     // Only the requestor can delete the request, admins can only edit it.
     const isActionOwner =
@@ -151,8 +150,12 @@ function MoneyReportHeader({policy, report: moneyRequestReport, transactionThrea
         return !!transactions && transactions.length > 0 && transactions.every((t) => isExpensifyCardTransaction(t) && isPending(t));
     }, [transactions]);
     const transactionIDs = transactions?.map((t) => t.transactionID) ?? [];
-    const hasAllPendingRTERViolations = allHavePendingRTERViolation(transactionIDs, allTransactionViolations);
-    const shouldShowBrokenConnectionViolation = shouldShowBrokenConnectionViolationTransactionUtils(transactionIDs, moneyRequestReport, policy, allTransactionViolations);
+    const [violations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS, {
+        selector: (allTransactions) =>
+            Object.fromEntries(Object.entries(allTransactions ?? {}).filter(([key]) => transactionIDs.includes(key.replace(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS, '')))),
+    });
+    const hasAllPendingRTERViolations = allHavePendingRTERViolation(transactionIDs, violations);
+    const shouldShowBrokenConnectionViolation = shouldShowBrokenConnectionViolationTransactionUtils(transactionIDs, moneyRequestReport, policy, violations);
     const hasOnlyHeldExpenses = hasOnlyHeldExpensesReportUtils(moneyRequestReport?.reportID);
     const isPayAtEndExpense = isPayAtEndExpenseTransactionUtils(transaction);
     const isArchivedReport = isArchivedReportWithID(moneyRequestReport?.reportID);

Copy link
Contributor

Choose a reason for hiding this comment

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

Quite a lot of optimizations have gone in here and I think we can optimize this too.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@rojiphil I have updated this. Please review and let me know if there's something left. Thanks.

@@ -113,7 +113,8 @@ function MoneyRequestPreviewContent({
const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`);
const [walletTerms] = useOnyx(ONYXKEYS.WALLET_TERMS);
const [allViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
const transactionViolations = getTransactionViolations(transaction?.transactionID);
const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
Copy link
Contributor

Choose a reason for hiding this comment

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

This is the same collection as the previous line?

Copy link
Contributor

Choose a reason for hiding this comment

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

Yeah. A cleanup can be done here.

Copy link
Contributor

Choose a reason for hiding this comment

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

This is the main remaining thing I want to see addressed before this PR is merged

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@rojiphil I have updated this. Please review and let me know if there's something left. Thanks.

Copy link
Contributor

@rojiphil rojiphil left a comment

Choose a reason for hiding this comment

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

@Krishna2323 Thanks for the changes. I have left some comments. Please have a look.

const hasViolations = hasViolationTransactionUtils(transaction?.transactionID, allViolations, true);
const hasNoticeTypeViolations = hasNoticeTypeViolationTransactionUtils(transaction?.transactionID, allViolations, true) && isPaidGroupPolicy(iouReport);
const hasWarningTypeViolations = hasWarningTypeViolationTransactionUtils(transaction?.transactionID, allViolations, true);
const hasViolations = hasViolationTransactionUtils(transaction, violations, true);
Copy link
Contributor

Choose a reason for hiding this comment

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

Why didn't we pass transaction?.transactionID?

@@ -6920,7 +6920,7 @@ function hasViolations(
reportTransactions?: SearchTransaction[],
): boolean {
const transactions = reportTransactions ?? getReportTransactions(reportID);
return transactions.some((transaction) => hasViolation(transaction.transactionID, transactionViolations, shouldShowInReview));
return transactions.some((transaction) => hasViolation(transaction, transactionViolations, shouldShowInReview));
Copy link
Contributor

Choose a reason for hiding this comment

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

Same question. Why not transaction.transactionID?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@rojiphil, the util function hasViolation requires the transaction object for passing it to isExpensifyCardTransaction, isPending & isViolationDismissed so it's preferred to pass the transaction directly.

@@ -112,8 +112,11 @@ function MoneyRequestPreviewContent({
const transactionID = isMoneyRequestAction ? getOriginalMessage(action)?.IOUTransactionID : undefined;
const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`);
const [walletTerms] = useOnyx(ONYXKEYS.WALLET_TERMS);
const [allViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
const transactionViolations = getTransactionViolations(transaction?.transactionID);
const [violations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS, {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we not use transactionViolations instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You mean the naming?

Copy link
Contributor

Choose a reason for hiding this comment

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

No. I meant reuse const transactionViolations = useTransactionViolations(transaction?.transactionID); instead of violations.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@rojiphil, we need OnyxCollection for hasViolationTransactionUtils, hasNoticeTypeViolationTransactionUtils & hasWarningTypeViolationTransactionUtils.

Copy link
Contributor

Choose a reason for hiding this comment

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

Got it. Thanks.

@luacmartins
Copy link
Contributor

This is a large diff to CP straight to staging at this point in the regression tests. I think we should just revert the offending PR.

Copy link
Contributor

@rojiphil rojiphil left a comment

Choose a reason for hiding this comment

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

@mjasikowski @roryabraham @luacmartins The changes LGTM and works well. I think it is safe to merge but leave the final decision to you all. Thanks.

56405-web-safari-004.mp4

@mjasikowski
Copy link
Contributor

@rojiphil there's a bunch of conflicts now, you'll need to merge main and resolve

@rojiphil
Copy link
Contributor

there's a bunch of conflicts now, you'll need to merge main and resolve

@Krishna2323 I guess this is largely due to the revert. Can we include the original feature implementation here along with the changes for this here. And we can also tag the feature issue in this PR.

@mjasikowski
Copy link
Contributor

@rojiphil yes, you can include the original (be sure to link to the original PR too). After the conflicts are resolved @rojiphil please re-test.

@luacmartins
Copy link
Contributor

Yes, we reverted the original PR so we need to reimplement those changes.

@Krishna2323
Copy link
Contributor Author

@rojiphil I will re-implement the changes in the original PR today.

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.

5 participants