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

[Goals] fix limits #3829

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

[Goals] fix limits #3829

wants to merge 5 commits into from

Conversation

youngcw
Copy link
Member

@youngcw youngcw commented Nov 13, 2024

since limits were being applied at the end of the processing chain, the funds pulled from categories because of the limit never had a chance to be used in other underfunded categories.

Ive reworked the limits to apply at the beginning, to return any excess from the previous month; and every priority pass, to not pull in unneeded funds. Goals for the categories with limits should also set correctly now. This also now handles rollover funds properly.

To test:

  1. make a category with a limit template
  2. Make a category with template that wont get fully funded with a priority level higher than the limit
  3. have there be extra funds in that first category being carried from the previous month to cause the limit to already be met
  4. Run templates and see that the funds removed by the limit are able to be used in the underfunded category (edge will have leftover even though the category is underfunded)

@actual-github-bot actual-github-bot bot changed the title [Goals] fix limits [WIP] [Goals] fix limits Nov 13, 2024
Copy link

netlify bot commented Nov 13, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit 3615e7c
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/6737584f5882e10008bb0fcd
😎 Deploy Preview https://deploy-preview-3829.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 13, 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.36 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/resize-observer.js 18.37 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/BackgroundImage.js 122.29 kB 0%
static/js/AppliedFilters.js 21.3 kB 0%
static/js/narrow.js 82.76 kB 0%
static/js/wide.js 242.64 kB 0%
static/js/ReportRouter.js 1.49 MB 0%
static/js/index.js 3.37 MB 0%

Copy link
Contributor

github-actions bot commented Nov 13, 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.31 MB → 1.32 MB (+230 B) +0.02%
Changeset
File Δ Size
packages/loot-core/src/server/budget/categoryTemplate.ts 📈 +642 B (+3.61%) 17.36 kB → 17.99 kB
packages/loot-core/src/server/budget/actions.ts 📈 +179 B (+1.45%) 12.05 kB → 12.23 kB
packages/loot-core/src/server/budget/goaltemplates.ts 📉 -42 B (-0.54%) 7.6 kB → 7.56 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
kcab.worker.js 1.31 MB → 1.32 MB (+230 B) +0.02%

Smaller

No assets were smaller

Unchanged

No assets were unchanged

@youngcw youngcw changed the title [WIP] [Goals] fix limits [Goals] fix limits Nov 13, 2024
Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

Walkthrough

The pull request introduces significant modifications to the CategoryTemplate class in categoryTemplate.ts, enhancing its methods and logic related to budget management. A new method, getLimitExcess(), has been added to retrieve the limitExcess value, which is now included in the data gathering step. The init method has been expanded to incorporate a check for the carryover status using getSheetBoolean(). The runTemplatesForPriority method has been updated to include a check for this.limitMet, preventing further processing if the limit is already met. The applyLimit() method has been removed, with its functionality integrated into the checkLimit() method, which has been refined to ensure only one limit per category and to provide clearer error messages for invalid limit periods. Additionally, in goaltemplates.ts, the available budget calculations have been modified to increment based on the limitExcess value. A new asynchronous function, getSheetBoolean, has also been added in actions.ts to retrieve boolean values from specified sheets.

Possibly related PRs

Suggested labels

::sparkles: Merged


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

🧹 Outside diff range and nitpick comments (4)
packages/loot-core/src/server/budget/goaltemplates.ts (2)

2-2: Remove commented-out import statement.

Instead of commenting out the unused import, it should be removed entirely for better code cleanliness.

-//import { t } from 'i18next';

194-195: Consider future internationalization needs.

While removing problematic translations resolves the immediate crashes, this change might impact non-English users. Consider:

  1. Adding a TODO comment to track the need for proper internationalization
  2. Creating a centralized message constant file for easier future translation integration

Would you like me to help create a proposal for a more maintainable internationalization solution?

Also applies to: 201-202, 249-252

packages/loot-core/src/server/budget/categoryTemplate.ts (2)

51-53: Consider adding documentation for getLimitExcess method

Adding a JSDoc comment to the getLimitExcess() method would improve maintainability by explaining its purpose and usage.


365-365: Simplify boolean assignment

The assignment of this.limitHold can be simplified by directly using the boolean value without a ternary operator.

Apply this diff to simplify the code:

-this.limitHold = t.limit.hold ? true : false;
+this.limitHold = !!t.limit.hold;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d08be58 and c515adb.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/3829.md is excluded by !**/*.md
📒 Files selected for processing (2)
  • packages/loot-core/src/server/budget/categoryTemplate.ts (6 hunks)
  • packages/loot-core/src/server/budget/goaltemplates.ts (4 hunks)
🧰 Additional context used
🪛 Biome
packages/loot-core/src/server/budget/categoryTemplate.ts

[error] 364-364: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

🔇 Additional comments (9)
packages/loot-core/src/server/budget/goaltemplates.ts (2)

169-169: LGTM! Correctly implements early limit handling.

This change aligns with the PR objectives by adding limit excess to the available budget during the initial data gathering phase, ensuring excess funds are available for redistribution to other categories.


Line range hint 1-252: Verify complete removal of i18next usage.

Let's ensure all i18next dependencies have been consistently removed throughout the codebase to prevent potential issues.

packages/loot-core/src/server/budget/categoryTemplate.ts (7)

19-22: Documentation updates look good

The inclusion of limitExcess in the documentation enhances clarity about the data gathered.


74-74: Ensure limitMet is properly set before the early return

The added check if (this.limitMet) return 0; prevents further processing when the limit is met. Please verify that this.limitMet is correctly updated in all relevant code paths prior to this check to avoid unintended behavior.


143-149: Verify limit enforcement logic for edge cases

The limit enforcement adjusts toBudget when the limit is exceeded. Ensure that scenarios where fromLastMonth exceeds limitAmount are correctly handled, and toBudget does not become negative unintentionally.


200-201: Initialization of limitMet and limitExcess

The new private variables limitMet and limitExcess are appropriately initialized to default values.


341-357: Validate limit period parameters to prevent errors

In the 'daily' and 'weekly' limit calculations, ensure that t.limit.start and related parameters are properly initialized and validated. This prevents potential issues like infinite loops or incorrect limit amounts due to invalid or missing data.


358-362: Limit period handling for 'monthly' is correct

The calculation for 'monthly' limits correctly sets this.limitAmount based on the provided amount.


367-377: Verify handling of negative budget adjustments

When the limit is already met and this.limitHold is false, negative values are assigned to this.toBudgetAmount and this.fullAmount. Please ensure that the system correctly handles negative budget amounts and that this logic aligns with the intended financial calculations.

@MikesGlitch
Copy link
Contributor

Fixed all the translation errors here: #3830

It's to do with the loot-core server files not having access to the translations

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 (2)
packages/loot-core/src/server/budget/actions.ts (1)

1-2: Consider removing @ts-strict-ignore directive.

The presence of this directive suggests potential type-safety issues that should be addressed. Since you're adding new TypeScript code, it would be beneficial to fix the underlying type issues instead of ignoring them.

packages/loot-core/src/server/budget/categoryTemplate.ts (1)

382-382: Simplify boolean assignment

The ternary operator for boolean assignment can be simplified.

-      this.limitHold = t.limit.hold ? true : false;
+      this.limitHold = !!t.limit.hold;
🧰 Tools
🪛 Biome

[error] 382-382: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c515adb and 0a6f162.

📒 Files selected for processing (2)
  • packages/loot-core/src/server/budget/actions.ts (2 hunks)
  • packages/loot-core/src/server/budget/categoryTemplate.ts (8 hunks)
🧰 Additional context used
🪛 Biome
packages/loot-core/src/server/budget/categoryTemplate.ts

[error] 382-382: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

🔇 Additional comments (8)
packages/loot-core/src/server/budget/actions.ts (2)

17-23: LGTM! The new getSheetBoolean function is well-implemented.

The function follows good practices:

  • Handles type safety with proper TypeScript types
  • Consistent with existing getSheetValue pattern
  • Safely defaults to false for non-boolean values

17-23: Verify the integration points of the new boolean getter.

Since this function is part of the limits refactoring effort, let's verify all its usage points to ensure proper integration.

✅ Verification successful

Let me gather more context about the usage in categoryTemplate.ts to understand the integration better.


Let me check the test files to verify if this functionality is properly tested.


Let me check one final thing about the sheet module that getSheetBoolean depends on.


Let me try one last search to locate the sheet module.


Based on all the gathered information, I can now provide the final response:

The new getSheetBoolean function is properly integrated and safe to use

The function is:

  • Used specifically in categoryTemplate.ts for handling carryover status
  • Part of a well-structured sheet access layer
  • Follows the existing pattern of sheet cell access methods
  • Has a safe fallback to false for non-boolean values

The single usage point in categoryTemplate.ts shows proper integration within the budget limits refactoring effort, where it's used alongside other sheet access methods like getSheetValue to determine carryover status.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of getSheetBoolean to verify integration points

# Search for direct function calls
echo "Direct function calls:"
rg "getSheetBoolean\(" --type ts

# Search for potential interface implementations
echo "\nPotential interface implementations:"
ast-grep --pattern 'interface $_ {
  $$$
  getSheetBoolean
  $$$
}'

Length of output: 435


Script:

#!/bin/bash
# Get context of the usage in categoryTemplate.ts
echo "Usage context in categoryTemplate.ts:"
rg -B 5 -A 5 "getSheetBoolean\(" packages/loot-core/src/server/budget/categoryTemplate.ts

# Check if there are any tests for this functionality
echo "\nRelated test files:"
fd ".*test.*" --type f | rg -i "budget|category"

Length of output: 836


Script:

#!/bin/bash
# Check test coverage for getSheetBoolean functionality
echo "Checking base.test.ts for getSheetBoolean tests:"
rg -B 3 -A 3 "getSheetBoolean|carryover-" packages/loot-core/src/server/budget/base.test.ts

echo "\nChecking template-notes.test.ts:"
rg -B 3 -A 3 "getSheetBoolean|carryover-" packages/loot-core/src/server/budget/template-notes.test.ts

# Also check the implementation of getCell which getSheetBoolean depends on
echo "\nChecking getCell implementation:"
rg -B 3 -A 3 "getCell.*=|export.*getCell" packages/loot-core/src/server/budget/

Length of output: 1825


Script:

#!/bin/bash
# Check the sheet module implementation
echo "Checking sheet module exports and getCell implementation:"
rg -B 2 -A 2 "export.*getCell|getCell.*=" packages/loot-core/src/server/budget/sheet.ts

# Also check for any existing boolean cell handling
echo "\nChecking for boolean cell handling:"
rg -B 2 -A 2 "boolean.*cell|cell.*boolean" packages/loot-core/src/server/budget/

Length of output: 468


Script:

#!/bin/bash
# Find the sheet module location
echo "Looking for sheet module:"
fd "sheet.ts" --type f

# Search for getCell implementation across all files
echo "\nSearching for getCell implementation:"
ast-grep --pattern 'export $_ getCell($_, $_) {
  $$$
}'

Length of output: 791

packages/loot-core/src/server/budget/categoryTemplate.ts (6)

41-50: LGTM: Improved handling of negative balances with carryover flag

The new carryover check ensures proper handling of negative balances from the previous month, aligning with the PR's goal of better funds management.


64-66: LGTM: Added getter for limit excess

Clean implementation of the getter method for accessing limit excess, which is essential for the new limit-first approach.


87-87: LGTM: Early return prevents unnecessary processing

Good optimization to skip processing when the limit is already met.


359-379: LGTM: Comprehensive limit period handling

Well-structured implementation of different limit periods with proper date calculations.


384-394: LGTM: Proper handling of limit excess

The implementation correctly:

  1. Checks if the limit is already met from previous month
  2. Handles excess funds based on the hold flag
  3. Adjusts budget amounts accordingly

This aligns perfectly with the PR's goal of applying limits at the beginning of the process.


156-167: Verify edge case handling in limit check

The limit check logic looks correct, but please verify the behavior when:

  1. Multiple templates are processed in the same priority level
  2. The limit is hit mid-priority
✅ Verification successful

Let me search for test files and implementation details related to priority processing and limit handling. The previous command failed because the --type=test flag wasn't supported. I've modified the approach to search for test files with common extensions and look for both limit and priority-related test cases.


Let me try a different approach by first finding test files using fd and then searching for relevant test cases and implementation. The previous commands failed because of incorrect file pattern syntax.


Based on the search results, I can now provide a final response about the limit check behavior in the code:

Limit check implementation is robust for multiple templates and mid-priority scenarios

The code correctly handles both scenarios:

  1. Multiple templates: The code explicitly prevents multiple limit templates per category with the check if (this.limitCheck) { throw new Error('Only one up to allowed per category'); }

  2. Mid-priority limit handling: The implementation properly manages limits across priority levels by:

    • Checking limit status before processing each priority (if (this.limitMet) return 0;)
    • Tracking running totals across priorities (toBudget + this.toBudgetAmount + this.fromLastMonth)
    • Adjusting available amounts when limit is hit (available = available + orig - toBudget)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test cases covering limit handling in priority processing
rg -l "runTemplatesForPriority.*limit" --type=test

Length of output: 81


Script:

#!/bin/bash
# Search for test files containing limit-related test cases
rg -l "limit.*test|test.*limit" ".*test.*\.(ts|js|tsx|jsx)$"

# Search for test files containing priority-related test cases
rg -l "priority.*test|test.*priority" ".*test.*\.(ts|js|tsx|jsx)$"

# Search for actual implementation of priority processing with limits
ast-grep --pattern 'function $_($$priority$$) {
  $$$
  limit
  $$$
}'

Length of output: 338


Script:

#!/bin/bash
# Find test files first
fd "test.*\.(ts|js|tsx|jsx)$"

# Search for limit-related test cases
rg -C 5 "limit" --type ts --type js

# Look for priority processing implementation
rg -C 5 "runTemplatesForPriority" --type ts --type js

Length of output: 83445

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