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

Enactment: enable triggering of rules on selected transaction form the account view. #3805

Open
wants to merge 11 commits into
base: master
Choose a base branch
from

Conversation

esseti
Copy link

@esseti esseti commented Nov 8, 2024

The PR implements the use case described here: #3244

It enables the possibility to have the rules triggered from the account view. Via the dropdown menu or by pressing the letter R

image

Note: this is my first PR here and this is the first time that i code something in TypeScript and React.
Please ensure the following when merging:

  • The function I wrote is in the correct file.
  • It is acceptable to send API calls in this manner. Note that this approach is "inspired" by the code in the popup for editing rules that permit a similar behavior.
  • The method used to "refetch" transactions is appropriate and not too burdensome. I would have preferred to refetch only the edited transaction, but I was unable to find a way, and the API call does not return the transaction edited after the rules have been applied.

@actual-github-bot actual-github-bot bot changed the title Enactment: enable triggering of rules on selected transaction form the account view. [WIP] Enactment: enable triggering of rules on selected transaction form the account view. Nov 8, 2024
Copy link

netlify bot commented Nov 8, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit a9ecf42
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/676554d2250909000835484f
😎 Deploy Preview https://deploy-preview-3805.demo.actualbudget.org
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

github-actions bot commented Nov 8, 2024

Bundle Stats — desktop-client

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
10 5.53 MB → 5.53 MB (+1.29 kB) +0.02%
Changeset
File Δ Size
src/components/transactions/SelectedTransactionsButton.tsx 📈 +305 B (+3.77%) 7.9 kB → 8.2 kB
src/components/accounts/Account.tsx 📈 +979 B (+2.14%) 44.63 kB → 45.59 kB
src/components/accounts/Header.tsx 📈 +40 B (+0.21%) 18.58 kB → 18.62 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/wide.js 161.25 kB → 162.54 kB (+1.29 kB) +0.80%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/useAccountPreviewTransactions.js 1.63 kB 0%
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/TransactionList.js 102.91 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/narrow.js 83.36 kB 0%
static/js/ReportRouter.js 1.58 MB 0%
static/js/index.js 3.45 MB 0%

Copy link
Contributor

github-actions bot commented Nov 8, 2024

Bundle Stats — loot-core

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
1 1.32 MB 0%

Changeset

No files were changed

View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

No assets were bigger

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
kcab.worker.js 1.32 MB 0%

@esseti
Copy link
Author

esseti commented Nov 8, 2024

Going to fix the things tomorrow or on monday. My bad

@esseti esseti changed the title [WIP] Enactment: enable triggering of rules on selected transaction form the account view. Enactment: enable triggering of rules on selected transaction form the account view. Nov 9, 2024
Copy link
Contributor

coderabbitai bot commented Nov 9, 2024

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/desktop-client/src/components/accounts/Account.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-eslint-plugin".

(The package "eslint-plugin-eslint-plugin" was not found when loaded as a Node module from the directory "/packages/eslint-plugin-actual".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-eslint-plugin@latest --save-dev

The plugin "eslint-plugin-eslint-plugin" was referenced from the config file in "packages/eslint-plugin-actual/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

Walkthrough

The pull request introduces enhancements to transaction management within the account management component of the desktop client. A new method, onRunRules, is added to the AccountInternal class, enabling the application of rules to multiple selected transactions. This method filters transactions based on provided IDs, processes them through a server endpoint, and updates the database with any modifications, including error handling. The onRunRules method is integrated into the AccountHeader component's props, allowing it to be invoked from the user interface. Additionally, the SelectedTransactionsButton component is updated to accept the onRunRules prop, which is utilized to bind a hotkey and menu option for executing the rules on selected transactions. These changes collectively enhance the functionality for users to manage transactions more effectively by applying rules in a batch manner.

Possibly related PRs

Suggested labels

:sparkles: Merged

Suggested reviewers

  • joel-jeremy
  • youngcw

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (4)
packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx (2)

262-266: Consider menu item placement.

The "Run Rules" menu item is currently placed within the schedule-related conditional block. Consider moving it outside this block as running rules is independent of schedule linking status.

              ...(linked
                ? [
                    {
                      name: 'view-schedule',
                      text: t('View schedule'),
                      key: 'S',
                      disabled: selectedIds.length > 1,
                    } as const,
                    {
                      name: 'unlink-schedule',
                      text: t('Unlink schedule'),
                    } as const,
                  ]
                : [
                    {
                      name: 'link-schedule',
                      text: t('Link schedule'),
                      key: 'S',
                    } as const,
                    {
                      name: 'create-rule',
                      text: t('Create rule'),
                    } as const,
-                   {
-                     name: 'run-rules',
-                     text: t('Run Rules'),
-                     key: 'R',
-                   } as const,
                  ]),
+             {
+               name: 'run-rules',
+               text: t('Run Rules'),
+               key: 'R',
+             } as const,

Line range hint 1-353: Excellent first contribution!

For your first TypeScript/React PR, the implementation is well-structured and follows the codebase patterns consistently. The component modifications are clean and maintain type safety.

A few architectural considerations:

  1. The placement of the "Run Rules" functionality in this component is appropriate as it operates on selected transactions.
  2. The API integration through props maintains good separation of concerns.
  3. The implementation properly handles the UI feedback loop through the hotkey and menu system.
packages/desktop-client/src/components/accounts/Header.tsx (1)

181-181: LGTM with a suggestion for error handling.

The onRunRules prop is correctly passed through to SelectedTransactionsButton. However, consider adding error handling for cases where rule application fails.

Consider wrapping the onRunRules handler with error handling:

-              onRunRules={onRunRules}
+              onRunRules={async (...args) => {
+                try {
+                  await onRunRules(...args);
+                } catch (error) {
+                  // Handle or report the error appropriately
+                  console.error('Failed to apply rules:', error);
+                  // You might want to show a notification to the user
+                }
+              }}

Also applies to: 364-364

packages/desktop-client/src/components/accounts/Account.tsx (1)

709-731: Consider architectural improvements for better maintainability.

Since this is your first TypeScript/React PR, here are some architectural suggestions:

  1. Function Placement:

    • Consider moving the rule application logic to a custom hook (e.g., useRuleActions) to maintain consistency with other action hooks in the codebase (like useTransactionBatchActions).
    • This would improve code organization and reusability.
  2. API Call Pattern:

    • Consider creating a dedicated API client function in a separate service layer.
    • This would centralize API calls and make them easier to maintain.
  3. Transaction Refetching:

    • Your concern about refetching only the edited transaction is valid.
    • Consider implementing optimistic updates using the transaction IDs that were modified.
    • Alternatively, request an API enhancement to return the modified transactions.

Example implementation of a custom hook:

// src/hooks/useRuleActions.ts
export function useRuleActions() {
  const onBatchApplyRules = async (ids: string[]) => {
    // Implementation moved from AccountInternal
  };
  
  return {
    onBatchApplyRules
  };
}

// Usage in AccountInternal
const { onBatchApplyRules } = useRuleActions();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2b72b2f and a27e6d0.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/3805.md is excluded by !**/*.md
📒 Files selected for processing (3)
  • packages/desktop-client/src/components/accounts/Account.tsx (3 hunks)
  • packages/desktop-client/src/components/accounts/Header.tsx (3 hunks)
  • packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx (5 hunks)
🔇 Additional comments (6)
packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx (4)

34-34: LGTM: Type definition is well-structured.

The onRunRules prop type follows the established pattern and is correctly typed as a callback function.


54-54: LGTM: Props destructuring is consistent.

The onRunRules prop is correctly destructured and maintains the component's prop ordering convention.


340-342: LGTM: Menu handler implementation is correct.

The 'run-rules' case in the switch statement follows the established pattern and correctly passes the selected IDs to the handler.


198-201: Verify potential hotkey conflicts.

The 'r' hotkey binding follows the correct pattern, but we should verify it doesn't conflict with existing shortcuts.

✅ Verification successful

No hotkey conflicts found for 'r' key binding

The 'r' hotkey is only used once in the codebase within SelectedTransactionsButton.tsx for running rules on selected transactions. All other hotkey bindings in this component use different keys ('f', 'd', 'a', 'p', 'n', 'c', 'l'), and no other components in the desktop client use the 'r' key binding. The implementation follows the established pattern using hotKeyOptions consistently.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for other 'r' hotkey bindings in the codebase
# Expected: No other 'r' hotkey bindings in the same scope

# Search for useHotkeys with 'r' key
rg "useHotkeys.*['\"]r['\"]" --type ts --type tsx

# Search for potential hotkey documentation
fd "keyboard|shortcut|hotkey" -e md

Length of output: 121


Script:

#!/bin/bash
# Let's try different approaches to find hotkey usages

# Search for useHotkeys with 'r' using ripgrep without file type restrictions
rg "useHotkeys.*['\"]r['\"]"

# Search for any hotkey related files
fd "hotkey"

# Search for keyboard shortcuts in markdown files
rg "keyboard|shortcut" -g "*.md"

# Search specifically in the desktop-client package for hotkey usage
rg "useHotkeys" "packages/desktop-client"

Length of output: 3782

packages/desktop-client/src/components/accounts/Header.tsx (1)

98-98: LGTM! Clean type definition.

The onRunRules prop type is correctly defined using ComponentProps utility type, maintaining type safety and reusability.

packages/desktop-client/src/components/accounts/Account.tsx (1)

1763-1763: LGTM!

The onRunRules prop is correctly added to the AccountHeader component.

Signed-off-by: Stefano Tranquillini <[email protected]>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
packages/desktop-client/src/components/accounts/Account.tsx (1)

1776-1776: Consider binding the method in the constructor.

While the current implementation works correctly due to the use of PureComponent, it's a good practice to bind class methods that are passed as props in the constructor to ensure consistent method references.

constructor(props: AccountInternalProps) {
  super(props);
  this.paged = null;
  this.table = createRef();
+ this.onRunRules = this.onRunRules.bind(this);

  this.state = {
    // ...existing state
  };
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a27e6d0 and a7861a8.

📒 Files selected for processing (1)
  • packages/desktop-client/src/components/accounts/Account.tsx (3 hunks)
🔇 Additional comments (2)
packages/desktop-client/src/components/accounts/Account.tsx (2)

47-47: LGTM: Type import is correctly placed.

The RuleEntity type import is appropriately grouped with other model type imports.


709-743: LGTM: Excellent implementation following best practices.

The implementation successfully addresses all previous review comments with:

  • Clean async/await usage
  • Proper error handling with user notification
  • Loading state management
  • Optimized transaction fetching
  • Type-safe operations

Comment on lines 724 to 730
// Apply all rules for this transaction
for (const rule of rules) {
await send('rule-apply-actions', {
transactions: [trans],
actions: rule.actions,
});
}
Copy link
Member

Choose a reason for hiding this comment

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

As the rules can have more conditions, this will mostly like execute actions on transactions not meant for the rule

Copy link
Member

Choose a reason for hiding this comment

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

There is a run-rules method which does all this.

Copy link
Author

Choose a reason for hiding this comment

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

Should I just call that method for all the selected transactions?

Copy link
Member

Choose a reason for hiding this comment

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

Yes

Copy link
Author

@esseti esseti Nov 27, 2024

Choose a reason for hiding this comment

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

I tried to import and use it but i get stgrange errors which i don't know how to solve it.

import { runRules } from 'loot-core/server/accounts/transaction-rules';
...
onRunRules = async (ids: string[]) => {
    try {
      this.setState({ workingHard: true });
      // Bulk fetch transactions
      const transactions = this.state.transactions.filter(trans =>
        ids.includes(trans.id),
      );
      //call the runrules function
      await runRules(transactions);
      // Fetch updated transactions once at the end
      await this.fetchTransactions();
    } catch (error) {
      console.error('Error applying rules:', error);
      this.props.addNotification({
        type: 'error',
        message: 'Failed to apply rules to transactions',
      });
    } finally {
      this.setState({ workingHard: false });
    }
  };

in the shell I've this

[vite] Pre-transform error: Failed to resolve entry for package "@actual-app/crdt". The package may have incorrect main/module/exports specified in its package.json. (x1045)

in the browser i've this

[plugin:vite:import-analysis] Failed to resolve entry for package "@actual-app/crdt". The package may have incorrect main/module/exports specified in its package.json.
/Users/stefano/sw/actual/packages/loot-core/src/server/db/index.ts
    at packageEntryFailure (file:///Users/stefano/sw/actual/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:46575:15)
    at resolvePackageEntry (file:///Users/stefano/sw/actual/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:46572:3)
    at tryNodeResolve (file:///Users/stefano/sw/actual/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:46388:16)
    at ResolveIdContext.resolveId (file:///Users/stefano/sw/actual/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:46138:19)
    at async PluginContainer.resolveId (file:///Users/stefano/sw/actual/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:48952:22)
    at async TransformPluginContext.resolve (file:///Users/stefano/sw/actual/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:49113:15)
    at async normalizeUrl (file:///Users/stefano/sw/actual/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:63977:26)
    at async file:///Users/stefano/sw/actual/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:64116:39
    at async Promise.all (index 0)
    at async TransformPluginContext.transform (file:///Users/stefano/sw/actual/node_modules/vite/dist/node/chunks/dep-CDnG8rE7.js:64043:7

not sure how to solve it.

Copy link
Author

Choose a reason for hiding this comment

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

The function is called, but it has no effect; nothing happens, and the reason is unclear. There may be an issue with the logic of the run rule, though this is uncertain. In the edit rule, the logic differs, but without comments, it is very difficult for someone to understand why it is implemented in that manner instead of using just the run rules.

here's a the ref to code that works, it's inside the popup that appears when editing the rules
https://github.com/actualbudget/actual/blob/master/packages/desktop-client/src/components/modals/EditRuleModal.jsx#L954

Copy link
Member

Choose a reason for hiding this comment

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

It should return the the transactions these can be updated with another call. I dont know which of the top of my hat.

Copy link
Author

Choose a reason for hiding this comment

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

It returns the transaction but without any changes, they are the same as the one sent. not sure why/how this is possible. I also tested with the function that does the diff of 2 transactions, but seems that there's no change.

i've a rule that if category is Home Depot change the notes to "chnaged"

then i've this piece of code:

onRunRules = async (ids: string[]) => {
    try {
      this.setState({ workingHard: true });
      // Bulk fetch transactions
      const transactions = this.state.transactions.filter(trans =>
        ids.includes(trans.id),
      );
      console.log('transactions', transactions);
      //call the runrules function
      const afterRules = await send('rules-run', {
        transaction: transactions,
      }).then((res: any) => {
        console.log('rules-run response', res);
      });
      // Fetch updated transactions once at the end
      await this.fetchTransactions();
    } catch (error) {
      console.error('Error applying rules:', error);
      this.props.addNotification({
        type: 'error',
        message: 'Failed to apply rules to transactions',
      });
    } finally {
      this.setState({ workingHard: false });
    }
  };

but the two prints, prints the same transaction. as if the run-rule does not do anything.

[
    {
        "id": "3694ab2f-d0d1-4e20-8a1c-f66c200e6846",
        "is_parent": false,
        "is_child": false,
        "parent_id": null,
        "account": "e487faa6-8109-4b81-bd90-e11ddc1d5c4f",
        "category": "ed38208a-53cf-4295-931d-8236a0f2f711",
        "amount": 0,
        "payee": "a852611e-1045-4af3-8899-1fd25a1d2263",
        "notes": "original",
        "date": "2024-11-27",
        "imported_id": null,
        "error": null,
        "imported_payee": null,
        "starting_balance_flag": false,
        "transfer_id": null,
        "sort_order": 1732728205547,
        "cleared": false,
        "reconciled": false,
        "tombstone": false,
        "schedule": null
    }
]

this is after

{
    "id": "3694ab2f-d0d1-4e20-8a1c-f66c200e6846",
    "is_parent": false,
    "is_child": false,
    "parent_id": null,
    "account": "e487faa6-8109-4b81-bd90-e11ddc1d5c4f",
    "category": "ed38208a-53cf-4295-931d-8236a0f2f711",
    "amount": 0,
    "payee": "a852611e-1045-4af3-8899-1fd25a1d2263",
    "notes": "original",
    "date": "2024-11-27",
    "imported_id": null,
    "error": null,
    "imported_payee": null,
    "starting_balance_flag": false,
    "transfer_id": null,
    "sort_order": 1732728205547,
    "cleared": false,
    "reconciled": false,
    "tombstone": false,
    "schedule": null
}

Copy link
Member

Choose a reason for hiding this comment

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

  const afterRules = await send('rules-run', {
        transaction: transactions,
      }).then((res: any) => {

Here is the mistake, you pass an array while the function expects an single transaction.

Copy link
Author

Choose a reason for hiding this comment

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

oh.. thanks for pointing out. i'll try to fix code over xmas break.

{
name: 'run-rules',
text: t('Run Rules'),
key: 'R',
Copy link
Member

Choose a reason for hiding this comment

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

I don't think this action will need a hotkey.

… rules execution and batch updates. Added utility function imports for improved functionality.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/desktop-client/src/components/accounts/Account.tsx (1)

42-46: Clean up unused imports

The imports getChangedValues and RuleEntity are defined but never used in the code.

-import {
-  applyChanges,
-  getChangedValues,
-  groupById,
-} from 'loot-core/src/shared/util';
+import {
+  applyChanges,
+  groupById,
+} from 'loot-core/src/shared/util';

-  type RuleEntity,

Also applies to: 55-55

🧰 Tools
🪛 GitHub Check: lint

[warning] 44-44:
'getChangedValues' is defined but never used. Allowed unused vars must match /^(_|React)/u

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a7861a8 and 01af7fe.

📒 Files selected for processing (1)
  • packages/desktop-client/src/components/accounts/Account.tsx (4 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/desktop-client/src/components/accounts/Account.tsx (1)
Learnt from: UnderKoen
PR: actualbudget/actual#3619
File: packages/loot-core/src/server/accounts/transaction-rules.ts:795-801
Timestamp: 2024-11-10T16:45:31.225Z
Learning: In the `finalizeTransactionForRules` function within `packages/loot-core/src/server/accounts/transaction-rules.ts`, potential race conditions when inserting payees are handled in the method that calls this function, so additional safeguards within `finalizeTransactionForRules` are unnecessary.
🪛 GitHub Check: lint
packages/desktop-client/src/components/accounts/Account.tsx

[warning] 44-44:
'getChangedValues' is defined but never used. Allowed unused vars must match /^(_|React)/u


[warning] 55-55:
'RuleEntity' is defined but never used. Allowed unused vars must match /^(_|React)/u


[warning] 718-718:
'changed_transactions' is never reassigned. Use 'const' instead


[warning] 721-721:
Expected property shorthand


[failure] 722-722:
Unexpected any. Specify a different type

🔇 Additional comments (1)
packages/desktop-client/src/components/accounts/Account.tsx (1)

1782-1782: LGTM!

The onRunRules prop is correctly passed to the AccountHeader component.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/desktop-client/src/components/accounts/Account.tsx (2)

Line range hint 42-55: Remove unused imports

The following imports are not used in the code:

  • getChangedValues: This function is imported but never used
  • RuleEntity: This type is imported but only used as a type annotation, which gets erased during compilation
 import {
   applyChanges,
-  getChangedValues,
   groupById,
 } from 'loot-core/src/shared/util';
 import {
   type NewRuleEntity,
   type RuleActionEntity,
   type AccountEntity,
   type PayeeEntity,
   type RuleConditionEntity,
   type TransactionEntity,
   type TransactionFilterEntity,
-  type RuleEntity,
 } from 'loot-core/src/types/models';
🧰 Tools
🪛 GitHub Check: lint

[warning] 44-44:
'getChangedValues' is defined but never used. Allowed unused vars must match /^(_|React)/u


[warning] 47-47:
There should be at least one empty line between import groups


709-746: Enhance error handling and type safety

The implementation looks good overall, but could benefit from these improvements:

  1. More specific error type handling
  2. More descriptive error messages
  3. Type assertion for API response

Consider this enhanced implementation:

 onRunRules = async (ids: string[]) => {
   try {
     this.setState({ workingHard: true });
     const transactions = this.state.transactions.filter(trans =>
       ids.includes(trans.id),
     );
     const changedTransactions = [];
     for (const transaction of transactions) {
       await send('rules-run', {
         transaction,
-      }).then((res: TransactionEntity | null) => {
+      }).then((res) => {
+        // Type guard to ensure response is a transaction
+        if (res && typeof res === 'object' && 'id' in res) {
           changedTransactions.push(res);
         }
       });
     }

     if (changedTransactions.length > 0) {
       await send('transactions-batch-update', {
         updated: changedTransactions,
       });
     }

     await this.fetchTransactions();
   } catch (error) {
-    console.error('Error applying rules:', error);
+    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+    console.error('Error applying rules:', errorMessage);
     this.props.addNotification({
       type: 'error',
-      message: 'Failed to apply rules to transactions',
+      message: `Failed to apply rules to transactions: ${errorMessage}`,
     });
   } finally {
     this.setState({ workingHard: false });
   }
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 01af7fe and 5c520d1.

📒 Files selected for processing (1)
  • packages/desktop-client/src/components/accounts/Account.tsx (4 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/desktop-client/src/components/accounts/Account.tsx (1)
Learnt from: UnderKoen
PR: actualbudget/actual#3619
File: packages/loot-core/src/server/accounts/transaction-rules.ts:795-801
Timestamp: 2024-11-10T16:45:31.225Z
Learning: In the `finalizeTransactionForRules` function within `packages/loot-core/src/server/accounts/transaction-rules.ts`, potential race conditions when inserting payees are handled in the method that calls this function, so additional safeguards within `finalizeTransactionForRules` are unnecessary.
🪛 GitHub Check: lint
packages/desktop-client/src/components/accounts/Account.tsx

[warning] 44-44:
'getChangedValues' is defined but never used. Allowed unused vars must match /^(_|React)/u


[warning] 55-55:
'RuleEntity' is defined but never used. Allowed unused vars must match /^(_|React)/u

🔇 Additional comments (1)
packages/desktop-client/src/components/accounts/Account.tsx (1)

1776-1776: LGTM!

The onRunRules prop is properly added to the AccountHeader component, maintaining alphabetical ordering and consistent style.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/desktop-client/src/components/accounts/Account.tsx (2)

715-721: Handle partial failures and success
If an error occurs for any transaction, you continue processing the rest but do not track which ones failed. Consider adding partial success tracking (e.g., a separate array for failed transactions) or an early return that stops processing on error.


1772-1772: Expose onRunRules prop usage
The new onRunRules prop is properly passed to AccountHeader for user interaction. If you also want to trigger rules automatically under other scenarios (e.g., schedule actions), consider making onRunRules more widely accessible.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5c520d1 and a9ecf42.

📒 Files selected for processing (2)
  • packages/desktop-client/src/components/accounts/Account.tsx (2 hunks)
  • packages/desktop-client/src/components/accounts/Header.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/desktop-client/src/components/accounts/Header.tsx
🧰 Additional context used
📓 Learnings (1)
packages/desktop-client/src/components/accounts/Account.tsx (1)
Learnt from: UnderKoen
PR: actualbudget/actual#3619
File: packages/loot-core/src/server/accounts/transaction-rules.ts:795-801
Timestamp: 2024-11-10T16:45:31.225Z
Learning: In the `finalizeTransactionForRules` function within `packages/loot-core/src/server/accounts/transaction-rules.ts`, potential race conditions when inserting payees are handled in the method that calls this function, so additional safeguards within `finalizeTransactionForRules` are unnecessary.
🔇 Additional comments (2)
packages/desktop-client/src/components/accounts/Account.tsx (2)

708-711: Check transaction existence in the filtered array
When filtering transactions by the provided IDs, consider handling the case where an ID doesn't match any transaction in state, ensuring that the overall operation doesn't silently skip missing entries without warning.

Would you like a shell script to locate all transaction filtering logic across the codebase and confirm consistent error handling?


724-730: Efficiently update transactions
Calling “transactions-batch-update” for all changed transactions is correct, but be mindful of performance overhead if multiple separate calls are made in other methods. Batching updates consistently reduces potential overhead.

Comment on lines +705 to +707
onRunRules = async (ids: string[]) => {
try {
this.setState({ workingHard: true });
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consolidate await and then callbacks
Currently, the loop uses both "await" and ".then()" within the same operation, which can lead to inconsistent error handling.

Below is a proposed refactor using a single async/await style for improved clarity and uniformity:

      for (const transaction of transactions) {
-        await send('rules-run', {
-          transaction,
-        }).then((res: TransactionEntity | null) => {
-          if (res) {
-            changedTransactions.push(res);
-          }
-        });
+        const res: TransactionEntity | null = await send('rules-run', {
+          transaction,
+        });
+        if (res) {
+          changedTransactions.push(res);
+        }
      }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onRunRules = async (ids: string[]) => {
try {
this.setState({ workingHard: true });
onRunRules = async (ids: string[]) => {
try {
this.setState({ workingHard: true });
// Bulk fetch transactions
const transactions = this.state.transactions.filter(trans =>
ids.includes(trans.id),
);
const changedTransactions = [];
for (const transaction of transactions) {
const res: TransactionEntity | null = await send('rules-run', {
transaction,
});
if (res) {
changedTransactions.push(res);
}
}

@esseti
Copy link
Author

esseti commented Dec 20, 2024

the code is working, not sure why the checkers are failing here.

@esseti esseti requested a review from UnderKoen December 20, 2024 13:00
Copy link
Member

@UnderKoen UnderKoen left a comment

Choose a reason for hiding this comment

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

This seems correct! If the proposed change from coderabbit is commited, the hotkey is removed and merge freeze is lifted, this could be merged!

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

Successfully merging this pull request may close these issues.

2 participants