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

Merged
merged 17 commits into from
Jan 12, 2025

Conversation

esseti
Copy link
Contributor

@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 b4b789a
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/6783d16dbe13c600082d64a5
😎 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
18 5.92 MB → 5.92 MB (+4.19 kB) +0.07%
Changeset
File Δ Size
locale/en.json 📈 +3.05 kB (+3.25%) 93.64 kB → 96.69 kB
src/components/transactions/SelectedTransactionsButton.tsx 📈 +179 B (+2.21%) 7.9 kB → 8.07 kB
src/components/accounts/Account.tsx 📈 +952 B (+2.07%) 44.86 kB → 45.79 kB
src/components/accounts/Header.tsx 📈 +40 B (+0.21%) 18.61 kB → 18.65 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/en.js 93.64 kB → 96.69 kB (+3.05 kB) +3.25%
static/js/wide.js 104.78 kB → 105.92 kB (+1.14 kB) +1.09%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/es.js 3.45 kB 0%
static/js/ta.js 17 B 0%
static/js/de.js 4.59 kB 0%
static/js/pl.js 17 B 0%
static/js/fr.js 12.6 kB 0%
static/js/zh-Hant.js 10.13 kB 0%
static/js/useAccountPreviewTransactions.js 1.63 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/AppliedFilters.js 10.24 kB 0%
static/js/uk.js 120.47 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/narrow.js 84.3 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/ReportRouter.js 1.58 MB 0%
static/js/index.js 3.74 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.33 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.33 MB 0%

@esseti
Copy link
Contributor 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

Walkthrough

The pull request introduces a new method onRunRules in the AccountInternal class, which processes selected transactions by filtering them based on provided IDs and sending them to a server for rule application. If any transactions are modified, they are updated in the database, with error handling implemented to log issues and notify users of failures. The onRunRules method is added to the props of the AccountHeader component, enabling its invocation from the user interface. Additionally, the SelectedTransactionsButton component is updated to accept the onRunRules prop, which is used to bind a hotkey and a menu option for executing the rules on selected transactions. These changes enhance transaction management capabilities within the desktop client.

Possibly related PRs

Suggested labels

:sparkles: Merged, :white_check_mark: Approved

Suggested reviewers

  • youngcw

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 77aac50 and b4b789a.

📒 Files selected for processing (1)
  • packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (windows-latest)
  • GitHub Check: Analyze
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (4)
packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx (4)

34-34: LGTM! Type definition is well-placed and consistent.

The onRunRules prop type follows the established pattern and is correctly typed.


54-54: LGTM! Prop destructuring is well-organized.

The onRunRules prop is correctly added and maintains alphabetical ordering.


258-261: LGTM! Menu option is well-structured.

The "Run Rules" menu option is correctly placed and follows the established pattern. Good job on not adding a hotkey, as suggested in the previous review.


335-337: LGTM! Switch case handler is properly implemented.

The 'run-rules' case follows the established pattern and is correctly implemented.


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
Contributor 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
Contributor 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
Contributor 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
Contributor 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
Contributor 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.

@esseti
Copy link
Contributor 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!

@esseti
Copy link
Contributor Author

esseti commented Dec 28, 2024

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

Should I do the code rabbit merge? Because I'm not so fluent in the language to get to know if the changes are correct or not.
I forgot to remove the hotkey.
Last, how do I lift the merge freeze?

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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a9ecf42 and 6f904c5.

📒 Files selected for processing (1)
  • packages/desktop-client/src/components/accounts/Account.tsx (2 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.
🪛 Biome (1.9.4)
packages/desktop-client/src/components/accounts/Account.tsx

[error] 722-722: Shouldn't redeclare 'transactions'. Consider to delete it or rename it.

'transactions' is defined here:

(lint/suspicious/noRedeclare)


[error] 726-726: Shouldn't redeclare 'changedTransactions'. Consider to delete it or rename it.

'changedTransactions' is defined here:

(lint/suspicious/noRedeclare)

🪛 GitHub Check: typecheck
packages/desktop-client/src/components/accounts/Account.tsx

[failure] 709-709:
Cannot redeclare block-scoped variable 'transactions'.


[failure] 712-712:
Cannot redeclare block-scoped variable 'changedTransactions'.


[failure] 722-722:
Cannot redeclare block-scoped variable 'transactions'.


[failure] 726-726:
Cannot redeclare block-scoped variable 'changedTransactions'.

🪛 GitHub Check: lint
packages/desktop-client/src/components/accounts/Account.tsx

[warning] 722-722:
'transactions' is already defined


[warning] 726-726:
'changedTransactions' is already defined

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

1785-1785: LGTM!

The onRunRules prop is correctly added to the AccountHeader component, following the established patterns in the codebase.

@UnderKoen
Copy link
Member

Should I do the code rabbit merge? Because I'm not so fluent in the language to get to know if the changes are correct or not.
I forgot to remove the hotkey.
Last, how do I lift the merge freeze?

Hey @esseti I fixed the code rabbit merge for you.
The merge freeze lifts after a release which just happend so when you remove the hotkey I will merge this for you!

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 (1)
packages/desktop-client/src/components/accounts/Account.tsx (1)

705-740: LGTM! The implementation looks solid and addresses previous concerns.

The implementation:

  • Properly handles async/await flow
  • Processes transactions one at a time as required
  • Includes proper error handling and loading states
  • Updates the database efficiently with batch updates
  • Refetches transactions to ensure UI consistency

A good-to-have improvement would be to add a success notification:

      if (changedTransactions.length > 0) {
        await send('transactions-batch-update', {
          updated: changedTransactions,
        });
+       this.props.addNotification({
+         type: 'success',
+         message: `Successfully applied rules to ${changedTransactions.length} transaction(s)`,
+       });
      }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6f904c5 and a627297.

📒 Files selected for processing (1)
  • packages/desktop-client/src/components/accounts/Account.tsx (2 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.
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Wait for Netlify build to finish
  • GitHub Check: Analyze
🔇 Additional comments (1)
packages/desktop-client/src/components/accounts/Account.tsx (1)

1770-1770: LGTM! Prop addition is consistent with component interface.

The onRunRules prop is correctly added to the AccountHeader component props.

@esseti
Copy link
Contributor Author

esseti commented Jan 10, 2025

Should I do the code rabbit merge? Because I'm not so fluent in the language to get to know if the changes are correct or not.
I forgot to remove the hotkey.
Last, how do I lift the merge freeze?

Hey @esseti I fixed the code rabbit merge for you. The merge freeze lifts after a release which just happend so when you remove the hotkey I will merge this for you!

@UnderKoen : Thanks, i just commited the code that removes the hotkey.

@UnderKoen UnderKoen merged commit a1be1d4 into actualbudget:master Jan 12, 2025
20 checks passed
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