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

refactor: fill in basic types in rules.ts #3365

Merged
merged 10 commits into from
Oct 8, 2024

Conversation

UnderKoen
Copy link
Member

No description provided.

@actual-github-bot actual-github-bot bot changed the title refactor: fill in basic types in rules.ts [WIP] refactor: fill in basic types in rules.ts Sep 4, 2024
Copy link

netlify bot commented Sep 4, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit 6f015ab
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/6705a07b7a39430008a8b3a5
😎 Deploy Preview https://deploy-preview-3365.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 Sep 4, 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
9 5.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
static/js/AppliedFilters.js 20.96 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/usePreviewTransactions.js 1.64 kB 0%
static/js/narrow.js 82.55 kB 0%
static/js/wide.js 224.88 kB 0%
static/js/ReportRouter.js 1.51 MB 0%
static/js/index.js 3.34 MB 0%

Copy link
Contributor

github-actions bot commented Sep 4, 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.26 MB → 1.26 MB (+6 B) +0.00%
Changeset
File Δ Size
packages/loot-core/src/server/accounts/rules.ts 📈 +8 B (+0.02%) 33.08 kB → 33.09 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
kcab.worker.js 1.26 MB → 1.26 MB (+6 B) +0.00%

Smaller

No assets were smaller

Unchanged

No assets were unchanged

@UnderKoen UnderKoen changed the title [WIP] refactor: fill in basic types in rules.ts refactor: fill in basic types in rules.ts Sep 8, 2024
Copy link
Contributor

@jfdoming jfdoming left a comment

Choose a reason for hiding this comment

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

Thanks for working on this!

packages/loot-core/src/server/accounts/rules.ts Outdated Show resolved Hide resolved
packages/loot-core/src/server/accounts/rules.ts Outdated Show resolved Hide resolved
packages/loot-core/src/server/accounts/rules.ts Outdated Show resolved Hide resolved
Copy link
Contributor

coderabbitai bot commented Sep 25, 2024

Walkthrough

The pull request introduces several modifications across multiple files, primarily focusing on enhancing type safety through explicit type annotations and structural changes in classes and interfaces. Key updates include refining type definitions in the Rule and RuleIndexer classes, updating method signatures, and modifying property types such as stage, actions, and conditions. Additionally, the NewRuleEntity interface was updated to restrict the stage and conditionsOp properties to specific values, thereby improving overall type constraints in the codebase. The getRulesForPayee function also saw a change where the rules variable was explicitly typed as a Set<Rule>, enforcing stricter type constraints.

Possibly related PRs

  • feat(rules): templating actions #3305: This PR introduces templating actions within rules, which relates to the changes in the Rule and RuleIndexer classes in the main PR that enhance type safety and structure, particularly in how rules are defined and executed.
  • Fix regression in case sensitivity for is/matches operator #3399: This PR addresses a bug fix related to the is and matches operators, which are likely used in conjunction with the Rule class, making it relevant to the changes in the main PR that enhance the functionality of rules.
  • 🧪 improving rules test e2e stability #3512: This PR focuses on improving the stability of end-to-end tests for the rules component, which is directly related to the modifications made in the main PR that enhance the structure and type safety of the Rule and RuleIndexer classes.

Suggested labels

sparkles: Merged

Suggested reviewers

  • youngcw
  • joel-jeremy

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

🧹 Outside diff range and nitpick comments (3)
packages/loot-core/src/types/models/rule.d.ts (1)

4-5: Summary of changes to NewRuleEntity

The modifications to the NewRuleEntity interface enhance type safety and standardize logical operations:

  1. The stage property now uses a union type ('pre' | null | 'post') instead of a generic string, providing clearer intent and restricting possible values.
  2. The conditionsOp property has been updated from 'any' | 'and' to 'or' | 'and', standardizing logical operators.

These changes improve code quality and maintainability. However, they may require updates in other parts of the codebase, including rule processing logic, user interfaces, and potentially data migration for existing rules. Please ensure thorough testing and consider the need for a migration strategy if existing data might be affected.

Consider the following architectural implications:

  1. Ensure that any serialization/deserialization of rule entities (e.g., for API communication or storage) is updated to handle the new type constraints.
  2. If there's a database schema for storing rules, it may need to be updated to reflect these changes.
  3. Review any documentation or API contracts that might be affected by these type changes.
packages/loot-core/src/server/accounts/rules.ts (2)

761-761: Consider adding a type annotation to the object parameter in evalConditions.

Adding a type annotation enhances type safety and helps catch errors at compile time.

Consider updating the method signature:

-  evalConditions(object): boolean {
+  evalConditions(object: Record<string, unknown>): boolean {

882-882: Suggest typing the object parameter in getApplicableRules.

Including a type annotation for object improves type safety and code clarity.

Consider changing the method signature to:

-  getApplicableRules(object): Set<Rule> {
+  getApplicableRules(object: Record<string, unknown>): Set<Rule> {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 88a7432 and 820b506.

🔇 Files ignored due to path filters (1)
  • upcoming-release-notes/3365.md is excluded by !**/*.md
📒 Files selected for processing (4)
  • packages/desktop-client/src/components/accounts/Account.tsx (1 hunks)
  • packages/loot-core/src/server/accounts/rules.ts (13 hunks)
  • packages/loot-core/src/server/accounts/transaction-rules.ts (1 hunks)
  • packages/loot-core/src/types/models/rule.d.ts (1 hunks)
🧰 Additional context used
Biome
packages/loot-core/src/server/accounts/rules.ts

[error] 1044-1045: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

🔇 Additional comments not posted (6)
packages/loot-core/src/types/models/rule.d.ts (1)

5-5: Updated logical operators for conditionsOp.

The change from 'any' | 'and' to 'or' | 'and' standardizes the logical operators used in rule conditions. This is a good improvement for clarity and consistency.

However, this change may have some implications:

  1. Existing rules using 'any' might need to be migrated to use 'or'.
  2. Rule processing logic may need to be updated to handle 'or' instead of 'any'.
  3. User interfaces for rule creation/editing might require updates.

To ensure a smooth transition, please run the following verification steps:

#!/bin/bash
# Description: Check for usage of 'any' in rule conditions and rule processing logic

# Search for 'any' usage in rule conditions
echo "Searching for 'any' usage in rule conditions:"
rg --type typescript "conditionsOp.*['\"](any|or)['\"]" -A 5

# Search for rule processing logic that might need updates
echo "Searching for rule processing logic:"
rg --type typescript "(evaluateRule|processRule|applyRule)" -A 10

Additionally, please ensure that:

  1. A migration plan is in place for existing rules using 'any'.
  2. The UI for rule creation/editing is updated to reflect this change.
  3. Documentation is updated to explain the use of 'or' instead of 'any' in rule conditions.
packages/loot-core/src/server/accounts/transaction-rules.ts (1)

570-570: Improved type safety with explicit Set<Rule> annotation

The change from Set to Set<Rule> enhances type safety and code clarity. This explicit type annotation ensures that only Rule objects can be added to the set, which aligns with TypeScript best practices and improves code maintainability.

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

1193-1193: LGTM. Verify impact on rule processing.

The change to set stage: null for a new rule looks good. This likely indicates that the rule is in an initial or undefined stage when created.

Please verify that setting stage to null doesn't negatively impact rule processing or display in other parts of the application. Run the following script to check for any dependencies on the stage property:

✅ Verification successful

Verified Change Does Not Negatively Impact Rule Processing

The usage of stage includes checks for null values and proper error handling. Setting stage: null is handled appropriately in both backend and frontend components, ensuring that rule processing and display function as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of 'stage' property in rule-related code
rg --type typescript --type javascript 'rule.*\.stage' -g '!*test*'

Length of output: 104


Script:

#!/bin/bash
# Search for usage of 'stage' property in rule-related code with corrected file types
rg --type ts --type js 'rule.*\.stage' -g '!*test*'

Length of output: 1003

packages/loot-core/src/server/accounts/rules.ts (3)

26-26: Great use of TypeScript's asserts for type narrowing.

The addition of asserts test in the function signature enhances type safety by informing the compiler that test is asserted to be truthy, which improves code reliability.


729-730: Explicitly typing actions and conditions improves code clarity.

Defining actions: Action[]; and conditions: Condition[]; makes the code more readable and maintainable by clearly specifying the expected types.


732-733: Confirm handling of optional id and nullable stage properties.

Making id optional (id?: string;) and allowing stage to be null (stage: 'pre' | null | 'post';) is acceptable. Please ensure that all usages of these properties properly handle undefined and null values to prevent potential runtime errors.

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/loot-core/src/server/accounts/rules.ts (1)

Line range hint 890-1020: LGTM with suggestion: Comprehensive type annotations added to utility functions.

The addition of type annotations to computeScore, _rankRules, rankRules, and migrateIds functions significantly enhances type safety and code clarity. These annotations will help prevent type-related errors and improve code maintainability.

However, there's a minor improvement that can be made:

In the iterateIds function, consider replacing the void | boolean return type of the callback function with boolean | undefined. This change addresses the static analysis hint and improves type clarity:

 export function iterateIds(
   rules: Rule[],
   fieldName: string,
-  func: (rule: Rule, id: string) => void | boolean,
+  func: (rule: Rule, id: string) => boolean | undefined,
 ): void {
   // ... rest of the function
 }

This change maintains the same functionality while avoiding the use of void in a union type, which can be confusing and is flagged by static analysis tools.

🧰 Tools
🪛 Biome

[error] 1019-1020: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 820b506 and b4869bb.

📒 Files selected for processing (3)
  • packages/loot-core/src/server/accounts/rules.ts (13 hunks)
  • packages/loot-core/src/server/accounts/transaction-rules.ts (1 hunks)
  • packages/loot-core/src/types/models/rule.d.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/loot-core/src/server/accounts/transaction-rules.ts
  • packages/loot-core/src/types/models/rule.d.ts
🧰 Additional context used
📓 Learnings (1)
📓 Common learnings
Learnt from: UnderKoen
PR: actualbudget/actual#3365
File: packages/loot-core/src/types/models/rule.d.ts:4-4
Timestamp: 2024-10-02T08:45:11.136Z
Learning: In `packages/loot-core/src/server/accounts/transaction-rules.ts`, the `stage` property can have legacy values `'cleanup'` and `'modify'`, which are converted to `'pre'`. The type remains `string` to accommodate these values and ensure correct usage.
🪛 Biome
packages/loot-core/src/server/accounts/rules.ts

[error] 1019-1020: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

🔇 Additional comments (7)
packages/loot-core/src/server/accounts/rules.ts (7)

27-31: LGTM: Improved type safety with imports and assert function update.

The addition of RuleConditionEntity and RuleEntity imports, along with the type annotations for the assert function, enhances the overall type safety of the code. These changes are well-implemented and align with best practices for TypeScript.


706-710: LGTM: Appropriate type annotations added to Rule class properties.

The type annotations added to the Rule class properties enhance type safety and clarity. The stage property type ('pre' | null | 'post') correctly aligns with the retrieved learning about legacy values, which mentions that 'cleanup' and 'modify' are converted to 'pre'. This implementation ensures correct usage while accommodating legacy values.


720-726: LGTM: Constructor parameters properly typed and aligned with class properties.

The type annotations added to the constructor parameters are consistent with the class property types, improving type safety. Making the stage parameter optional with a default value of null is a good practice, allowing flexibility in rule creation while maintaining type consistency.


736-736: LGTM: Appropriate return type added to evalConditions method.

Adding the boolean return type to the evalConditions method improves type safety and code clarity. This change helps developers understand the expected output of the method without needing to examine its implementation.


773-777: LGTM: Proper return types added to getId and serialize methods.

The addition of return type annotations to the getId and serialize methods enhances type safety and code clarity:

  • The string | undefined return type for getId correctly reflects that the id property is optional.
  • The RuleEntity return type for serialize aligns with the imported type, ensuring consistency between the serialized output and the expected shape of a rule entity.

These changes improve the overall type correctness of the Rule class.


789-791: LGTM: Appropriate type annotations added to RuleIndexer class properties.

The type annotations added to the RuleIndexer class properties enhance type safety and code clarity:

  • field: string correctly specifies that the field is a string.
  • method?: string indicates that the method is an optional string property.
  • rules: Map<string, Set<Rule>> provides a clear structure for the rules storage.

These type annotations will help prevent type-related errors and improve code maintainability.


Line range hint 799-857: LGTM: Comprehensive type annotations added to RuleIndexer methods.

The addition of type annotations to the RuleIndexer class methods significantly enhances type safety and code clarity:

  1. getIndex, getIndexForValue, and getKey methods now have clear input and output types.
  2. The use of unknown for generic input in methods like getIndexForValue and getKey is appropriate, allowing for type-safe handling of various inputs.
  3. getIndexes, index, and remove methods now clearly specify that they work with Rule objects.
  4. The getApplicableRules method's return type Set<Rule> clearly indicates the expected output.

These type annotations will help catch potential type-related errors early and improve the overall robustness of the RuleIndexer class.

@MikesGlitch MikesGlitch self-assigned this Oct 8, 2024
Copy link
Contributor

@MikesGlitch MikesGlitch left a comment

Choose a reason for hiding this comment

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

This is a nice improvement! Apologies for it taking so long to get a review.

Can you resolve the conflict? I'm happy to approve this once done 👍

…ules

# Conflicts:
#	packages/loot-core/src/server/accounts/rules.ts
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/loot-core/src/server/accounts/rules.ts (1)

Line range hint 879-1110: LGTM: Improved type safety for RuleIndexer and utility functions.

The addition of explicit type annotations to the RuleIndexer class and utility functions significantly enhances the overall type safety and clarity of the code.

However, there's a minor improvement we can make:

In the iterateIds function (lines 1109-1110), consider replacing void with undefined in the union type of the func parameter. This change addresses a potential confusion in the type definition:

func: (rule: Rule, id: string) => boolean | undefined,

This modification aligns with best practices for union types in TypeScript.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b4869bb and 6f015ab.

📒 Files selected for processing (2)
  • packages/loot-core/src/server/accounts/rules.ts (14 hunks)
  • packages/loot-core/src/types/models/rule.d.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/loot-core/src/types/models/rule.d.ts
🧰 Additional context used
📓 Learnings (1)
📓 Common learnings
Learnt from: UnderKoen
PR: actualbudget/actual#3365
File: packages/loot-core/src/types/models/rule.d.ts:4-4
Timestamp: 2024-10-08T15:46:15.739Z
Learning: In `packages/loot-core/src/server/accounts/transaction-rules.ts`, the `stage` property can have legacy values `'cleanup'` and `'modify'`, which are converted to `'pre'`. The type remains `string` to accommodate these values and ensure correct usage.
Learnt from: UnderKoen
PR: actualbudget/actual#3365
File: packages/loot-core/src/types/models/rule.d.ts:4-4
Timestamp: 2024-10-02T08:45:11.136Z
Learning: In `packages/loot-core/src/server/accounts/transaction-rules.ts`, the `stage` property can have legacy values `'cleanup'` and `'modify'`, which are converted to `'pre'`. The type remains `string` to accommodate these values and ensure correct usage.
🪛 Biome
packages/loot-core/src/server/accounts/rules.ts

[error] 1109-1110: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

🔇 Additional comments (7)
packages/loot-core/src/server/accounts/rules.ts (7)

30-31: LGTM: New imports added for type definitions.

The addition of RuleConditionEntity and RuleEntity imports from the models file is appropriate for enhancing type safety in this module.


90-93: LGTM: Improved type safety for assert function.

The assert function now has explicit parameter types and uses the asserts keyword in its return type, which is the correct approach for assertion functions in TypeScript.


796-800: LGTM: Improved type definitions for Rule class properties.

The explicit typing of the Rule class properties enhances type safety. The stage property type ('pre' | null | 'post') is consistent with the retrieved learnings about legacy values being converted to 'pre'.


810-816: LGTM: Constructor parameters properly typed.

The Rule constructor parameters are now properly typed, maintaining consistency with the property definitions. The optional stage parameter with a default value of null is well-implemented.


Line range hint 826-863: LGTM: Enhanced type safety for Rule class methods.

The addition of return types and the use of generics in the Rule class methods significantly improves type safety and code clarity. The execActions method's generic implementation is particularly well done, allowing for flexible usage while maintaining strong typing.


Line range hint 867-876: LGTM: Proper return type for serialize method.

The serialize method now correctly specifies its return type as RuleEntity, which enhances type safety when working with serialized rule data.


Line range hint 1-1160: Excellent work on enhancing type safety throughout the file!

This refactoring significantly improves the type definitions in rules.ts. The changes consistently apply TypeScript best practices, enhancing code clarity, maintainability, and reducing the potential for type-related errors. The explicit typing of class properties, method parameters, and return types will greatly aid in catching potential issues early in the development process.

The only minor suggestion is the adjustment to the iterateIds function parameter type, which has been noted in a previous comment.

Overall, this is a very well-executed refactoring that substantially improves the codebase.

Copy link
Contributor

@MikesGlitch MikesGlitch left a comment

Choose a reason for hiding this comment

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

Nice work!

@MikesGlitch MikesGlitch merged commit 1485d9c into actualbudget:master Oct 8, 2024
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.

4 participants