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 5 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 a7861a8
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/6730ae54c8bd5100087c1ba9
😎 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.34 MB → 5.35 MB (+1.16 kB) +0.02%
Changeset
File Δ Size
node_modules/clsx/dist/clsx.mjs 🆕 +368 B 0 B → 368 B
node_modules/clsx/dist/clsx.mjs?commonjs-proxy 🆕 +64 B 0 B → 64 B
src/components/transactions/SelectedTransactionsButton.tsx 📈 +305 B (+3.77%) 7.9 kB → 8.2 kB
src/components/accounts/Account.tsx 📈 +942 B (+2.08%) 44.32 kB → 45.24 kB
src/components/accounts/Header.tsx 📈 +40 B (+0.21%) 18.34 kB → 18.38 kB
node_modules/react-grid-layout/build/components/WidthProvider.js 📈 +1 B (+0.02%) 5.22 kB → 5.22 kB
node_modules/react-grid-layout/build/GridItem.js 📈 +1 B (+0.00%) 21.49 kB → 21.49 kB
node_modules/react-grid-layout/build/ReactGridLayout.js 📈 +1 B (+0.00%) 24.96 kB → 24.96 kB
node_modules/clsx/dist/clsx.js 🔥 -509 B (-100%) 509 B → 0 B
node_modules/clsx/dist/clsx.js?commonjs-module 🔥 -27 B (-100%) 27 B → 0 B
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/wide.js 239.81 kB → 241.07 kB (+1.26 kB) +0.52%
static/js/ReportRouter.js 1.5 MB → 1.5 MB (+67 B) +0.00%

Smaller

Asset File Size % Changed
static/js/index.js 3.35 MB → 3.35 MB (-168 B) -0.00%

Unchanged

Asset File Size % Changed
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/AppliedFilters.js 21.3 kB 0%
static/js/usePreviewTransactions.js 1.64 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/narrow.js 82.57 kB 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.27 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.27 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

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, allowing for the application of rules to multiple selected transactions. This method filters transactions based on provided IDs, retrieves relevant rules associated with each transaction's payee, and applies those rules sequentially, including error handling and transaction list updates. The onRunRules method is integrated into the AccountHeader component's props, enabling 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. A new type declaration for RuleEntity is also introduced to handle rules related to 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

  • youngcw
  • MikesGlitch

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 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 +720 to +722
const rules = (await send('payees-get-rules', {
id: trans.payee,
})) as RuleEntity[];
Copy link
Member

Choose a reason for hiding this comment

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

Not all rules are based on payee so this wouldn't include all rules applicable

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
Member

Choose a reason for hiding this comment

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

you can execute it with send('rules-run') I think

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
}

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

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