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

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

Conversation

UnderKoen
Copy link
Contributor

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 02827c4
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/66fece018724300008a6d25b
😎 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.29 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/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/usePreviewTransactions.js 1.64 kB 0%
static/js/AppliedFilters.js 20.96 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/narrow.js 81.98 kB 0%
static/js/wide.js 225.26 kB 0%
static/js/ReportRouter.js 1.5 MB 0%
static/js/index.js 3.31 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.19 MB → 1.19 MB (+6 B) +0.00%
Changeset
File Δ Size
packages/loot-core/src/server/accounts/rules.ts 📈 +8 B (+0.03%) 30.08 kB → 30.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.19 MB → 1.19 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 variable declarations in the getRulesForPayee function, and modifying the NewRuleEntity interface to restrict the stage and conditionsOp properties to specific values, thereby improving overall type constraints in the codebase.

Changes

Files Change Summary
packages/loot-core/src/server/accounts/rules.ts Enhanced type safety by adding type annotations to the Rule and RuleIndexer classes, updating method signatures, and modifying property types including stage, actions, and conditions.
packages/loot-core/src/server/accounts/transaction-rules.ts Changed the declaration of rules variable in getRulesForPayee function from Set to Set<Rule>, enforcing stricter type constraints.
packages/loot-core/src/types/models/rule.d.ts Modified the NewRuleEntity interface by updating the stage property to a union type (`'pre'

Possibly related PRs

  • 🧪 improving rules test e2e stability #3512: This PR enhances the stability of end-to-end tests related to the "rules" component, which includes modifications to the Rule and RuleIndexer classes that are also present in the main PR, indicating a direct connection in terms of functionality and testing.

Suggested labels

sparkles: Merged

Suggested reviewers

  • MatissJanis

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.

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.

3 participants