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

enhance: add more action rule templating helpers #4243

Merged
merged 2 commits into from
Jan 28, 2025

Conversation

UnderKoen
Copy link
Member

Part of #3606

Adds the following helpers:

  • replace value pattern replacement mimics js replace. When pattern is not as /regex/flags it just uses raw value as opposed to {{regex ...
  • replaceAll value pattern replacement mimics js replaceAll
  • addDays date days add x days to the day
  • subDays date days
  • addWeeks date weeks
  • subWeeks date weeks
  • addMonths date months
  • subMonths date months
  • addYears date years
  • subYears date years
  • setDay date day Overflows are handled, 0 will set to last day of month before
  • concat args.. joins all arguments together

@actual-github-bot actual-github-bot bot changed the title enhance: add more action rule templating helpers [WIP] enhance: add more action rule templating helpers Jan 26, 2025
Copy link

netlify bot commented Jan 26, 2025

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit bdd483d
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67964d531dbf740008ad1252
😎 Deploy Preview https://deploy-preview-4243.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.

@UnderKoen UnderKoen changed the title [WIP] enhance: add more action rule templating helpers enhance: add more action rule templating helpers Jan 26, 2025
Copy link
Contributor

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
15 6.68 MB → 6.7 MB (+22.93 kB) +0.34%
Changeset
File Δ Size
node_modules/clsx/dist/clsx.js 🆕 +509 B 0 B → 509 B
node_modules/clsx/dist/clsx.js?commonjs-module 🆕 +27 B 0 B → 27 B
locale/nl.json 📈 +21.18 kB (+36.15%) 58.58 kB → 79.76 kB
home/runner/work/actual/actual/packages/loot-core/src/server/accounts/rules.ts 📈 +1.9 kB (+16.09%) 11.84 kB → 13.74 kB
locale/en.json 📈 +31 B (+0.03%) 99.31 kB → 99.34 kB
node_modules/react-grid-layout/build/ReactGridLayout.js 📉 -1 B (-0.00%) 24.96 kB → 24.96 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/components/WidthProvider.js 📉 -1 B (-0.02%) 5.22 kB → 5.22 kB
locale/uk.json 📉 -80 B (-0.07%) 111.19 kB → 111.11 kB
locale/pt-BR.json 📉 -97 B (-0.09%) 103.38 kB → 103.29 kB
locale/en-GB.json 📉 -104 B (-0.11%) 92.98 kB → 92.87 kB
node_modules/clsx/dist/clsx.mjs 🔥 -368 B (-100%) 368 B → 0 B
node_modules/clsx/dist/clsx.mjs?commonjs-proxy 🔥 -64 B (-100%) 64 B → 0 B
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/nl.js 58.58 kB → 79.76 kB (+21.18 kB) +36.15%
static/js/index.js 4.28 MB → 4.29 MB (+2.07 kB) +0.05%
static/js/en.js 99.31 kB → 99.34 kB (+31 B) +0.03%

Smaller

Asset File Size % Changed
static/js/en-GB.js 92.98 kB → 92.87 kB (-104 B) -0.11%
static/js/pt-BR.js 103.38 kB → 103.29 kB (-97 B) -0.09%
static/js/uk.js 111.19 kB → 111.11 kB (-80 B) -0.07%
static/js/ReportRouter.js 1.59 MB → 1.59 MB (-67 B) -0.00%

Unchanged

Asset File Size % Changed
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/AppliedFilters.js 10.52 kB 0%
static/js/useAccountPreviewTransactions.js 1.69 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/narrow.js 84.94 kB 0%
static/js/wide.js 102.8 kB 0%

Copy link
Contributor

Bundle Stats — loot-core

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
1 1.33 MB → 1.33 MB (+734 B) +0.05%
Changeset
File Δ Size
packages/loot-core/src/server/accounts/rules.ts 📈 +2.13 kB (+6.57%) 32.43 kB → 34.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.33 MB → 1.33 MB (+734 B) +0.05%

Smaller

No assets were smaller

Unchanged

No assets were unchanged

Copy link
Contributor

coderabbitai bot commented Jan 26, 2025

Walkthrough

The pull request introduces new test cases and helper functions in the rules.test.ts and rules.ts files, focusing on expanding the templating and date manipulation capabilities. The changes include adding new test cases for string replacement, regex operations, and date-related helpers such as addDays, subDays, addMonths, subMonths, addYears, subYears, and setDay. The modifications also introduce a concat helper for string concatenation. The regex helper functionality has been refactored to improve modularity, allowing more flexible handling of regex operations. These changes enhance the test coverage and functionality of the Action and Condition classes without altering their existing core logic.

Possibly related PRs

Suggested labels

sparkles: Merged

Suggested reviewers

  • youngcw
  • matt-fidd
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
packages/loot-core/src/server/accounts/rules.ts (3)

Line range hint 54-79: Consider enhancing type safety and error handling in regexHelper.

The implementation is well-structured, but could benefit from:

  1. TypeScript type annotations for the function parameters
  2. Try-catch block for regex compilation
  3. Validation for empty strings
 function regexHelper(
-    mapRegex: (regex: string, flags: string) => string | RegExp,
-    mapNonRegex: (value: string) => string | RegExp,
-    apply: (value: string, regex: string | RegExp, replace: string) => string,
+    mapRegex: (regex: string, flags: string) => RegExp,
+    mapNonRegex: (value: string) => string | RegExp,
+    apply: (value: string, regex: string | RegExp, replace: string) => string,
   ) {
     return (value: unknown, regex: unknown, replace: unknown) => {
       if (value == null) {
         return null;
       }
 
-      if (typeof regex !== 'string' || typeof replace !== 'string') {
+      if (!regex || typeof regex !== 'string' || !replace || typeof replace !== 'string') {
         return '';
       }
 
       let regexp: string | RegExp;
       const match = regexTest.exec(regex);
       // Regex is in format /regex/flags
       if (match) {
-        regexp = mapRegex(match[1], match[2]);
+        try {
+          regexp = mapRegex(match[1], match[2]);
+        } catch (e) {
+          console.warn('Invalid regex pattern:', e);
+          return String(value);
+        }
       } else {
         regexp = mapNonRegex(regex);
       }
 
       return apply(String(value), regexp, replace);
     };
   }

81-96: Add JSDoc documentation for the regex-based helpers.

Consider adding JSDoc documentation to improve IDE support and code clarity:

 const helpers = {
+  /**
+   * Replaces text using regex or literal string patterns.
+   * @param {string} value - The input string
+   * @param {string} regex - Pattern in /regex/flags format or literal string
+   * @param {string} replace - Replacement string
+   * @returns {string} The modified string
+   */
   regex: regexHelper(
     (regex, flags) => new RegExp(regex, flags),
     value => new RegExp(value),
     (value, regex, replace) => value.replace(regex, replace),
   ),
+  /**
+   * Replaces first occurrence using regex or literal string.
+   * @param {string} value - The input string
+   * @param {string} regex - Pattern in /regex/flags format or literal string
+   * @param {string} replace - Replacement string
+   * @returns {string} The modified string
+   */
   replace: regexHelper(
     (regex, flags) => new RegExp(regex, flags),
     value => value,
     (value, regex, replace) => value.replace(regex, replace),
   ),
+  /**
+   * Replaces all occurrences using regex or literal string.
+   * @param {string} value - The input string
+   * @param {string} regex - Pattern in /regex/flags format or literal string
+   * @param {string} replace - Replacement string
+   * @returns {string} The modified string
+   */
   replaceAll: regexHelper(
     (regex, flags) => new RegExp(regex, flags),
     value => value,
     (value, regex, replace) => value.replaceAll(regex, replace),
   ),

153-153: Enhance the concat helper with types and documentation.

Add type safety and documentation to improve code clarity:

+  /**
+   * Concatenates multiple values into a single string.
+   * @param {...unknown[]} args - Values to concatenate
+   * @returns {string} The concatenated string
+   */
-  concat: (...args: unknown[]) => args.slice(0, -1).join(''),
+  concat: (...args: unknown[]): string => {
+    const values = args.slice(0, -1);
+    return values.map(String).join('');
+  },
packages/loot-core/src/server/accounts/rules.test.ts (3)

362-374: Add more test cases for regex helpers.

Consider adding tests for:

  1. Invalid regex patterns
  2. Empty strings
  3. Special characters in replacement
// Add these test cases
testHelper('{{replace notes "/[/" "a"}}', 'Sarah Condition'); // Invalid regex
testHelper('{{replace notes "" "a"}}', 'Sarah Condition'); // Empty pattern
testHelper('{{replace notes "a" "$&"}}', 'S$&r$&h Condition'); // Special replacement

430-441: Add edge cases for date manipulation helpers.

Consider adding tests for:

  1. Invalid dates
  2. Month/year boundaries
  3. Leap years
// Add these test cases
testHelper('{{addDays "invalid" 5}}', ''); // Invalid date
testHelper('{{addDays "2002-01-31" 1}}', '2002-02-01'); // Month boundary
testHelper('{{addMonths "2002-01-31" 1}}', '2002-02-28'); // Date overflow
testHelper('{{addDays "2004-02-28" 1}}', '2004-02-29'); // Leap year
testHelper('{{addDays "2004-02-29" 1}}', '2004-03-01'); // Leap year boundary

453-454: Add edge cases for concat helper.

Consider adding tests for:

  1. Non-string values
  2. Empty strings
  3. Null/undefined values
// Add these test cases
testHelper('{{concat "A" 123 true null undefined}}', 'A123true'); // Mixed types
testHelper('{{concat "" "" ""}}', ''); // Empty strings
testHelper('{{concat null undefined}}', 'nullundefined'); // Null/undefined
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f09f4af and bdd483d.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/4243.md is excluded by !**/*.md
📒 Files selected for processing (2)
  • packages/loot-core/src/server/accounts/rules.test.ts (2 hunks)
  • packages/loot-core/src/server/accounts/rules.ts (4 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/loot-core/src/server/accounts/rules.test.ts (1)
Learnt from: jfdoming
PR: actualbudget/actual#3641
File: packages/loot-core/src/server/accounts/rules.test.ts:524-536
Timestamp: 2024-11-10T16:45:25.627Z
Learning: In `packages/loot-core/src/server/accounts/rules.test.ts`, prefer explicit action definitions over refactoring similar actions into loops or helper functions, even when actions are similar.
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Visual regression
  • GitHub Check: Functional
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)

@UnderKoen UnderKoen merged commit d1c3b9b into master Jan 28, 2025
20 checks passed
@UnderKoen UnderKoen deleted the UnderKoen/more-helpers branch January 28, 2025 18:09
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