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

Extract budget category related server handlers from main.ts to server/budget/app.ts #4442

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

Conversation

joel-jeremy
Copy link
Contributor

@joel-jeremy joel-jeremy commented Feb 24, 2025

Related to #1113

@actual-github-bot actual-github-bot bot changed the title Extract budget category related server handlers from main.ts to server/budger/app.ts [WIP] Extract budget category related server handlers from main.ts to server/budger/app.ts Feb 24, 2025
Copy link

netlify bot commented Feb 24, 2025

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit a263e7e
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67bc418a8a03d10008a44d7b
😎 Deploy Preview https://deploy-preview-4442.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.

@joel-jeremy joel-jeremy changed the title [WIP] Extract budget category related server handlers from main.ts to server/budger/app.ts Extract budget category related server handlers from main.ts to server/budger/app.ts Feb 24, 2025
Copy link

netlify bot commented Feb 24, 2025

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit cb9a201
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67c7658371a8bb00083b1c5c
😎 Deploy Preview https://deploy-preview-4442.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 Feb 24, 2025

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
18 8.09 MB → 8.09 MB (-101 B) -0.00%
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
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/ReportRouter.js 1.59 MB → 1.59 MB (+67 B) +0.00%

Smaller

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

Unchanged

Asset File Size % Changed
static/js/es.js 58.26 kB 0%
static/js/de.js 115.52 kB 0%
static/js/AppliedFilters.js 10.87 kB 0%
static/js/useAccountPreviewTransactions.js 1.69 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/nl.js 97.97 kB 0%
static/js/en.js 103.78 kB 0%
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/narrow.js 88.98 kB 0%
static/js/pt-BR.js 110.52 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/fr.js 116.48 kB 0%
static/js/uk.js 111.06 kB 0%
static/js/en-GB.js 96.66 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/wide.js 103.22 kB 0%

Copy link
Contributor

github-actions bot commented Feb 24, 2025

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.83 MB → 1.83 MB (+1.34 kB) +0.07%
Changeset
File Δ Size
packages/loot-core/src/server/budget/app.ts 📈 +8.43 kB (+413.31%) 2.04 kB → 10.47 kB
packages/loot-core/src/server/models.ts 📈 +931 B (+40.57%) 2.24 kB → 3.15 kB
packages/loot-core/src/server/api.ts 📈 +143 B (+0.66%) 21.1 kB → 21.24 kB
packages/loot-core/src/mocks/budget.ts 📉 -8 B (-0.03%) 29.39 kB → 29.38 kB
packages/loot-core/src/server/db/index.ts 📉 -119 B (-0.57%) 20.35 kB → 20.23 kB
packages/loot-core/src/server/main.ts 📉 -7.89 kB (-17.52%) 45.06 kB → 37.16 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
kcab.worker.js 1.83 MB → 1.83 MB (+1.34 kB) +0.07%

Smaller

No assets were smaller

Unchanged

No assets were unchanged

Copy link
Contributor

coderabbitai bot commented Feb 24, 2025

Walkthrough

The changes update various aspects of the budget management functionality. In the test budget module, the code now assigns a boolean value directly to isIncome instead of converting it to an integer. In the application module, a new BudgetHandlers interface is introduced along with multiple asynchronous functions that handle the creation, updating, moving, and deletion of categories and category groups, as well as retrieving budget-related data. Database functions have been updated with explicit return type annotations for improved type safety. Several existing handlers for budget operations have been removed from the main module, and the import path for BudgetHandlers has been updated in the types file. Additionally, an older declaration of BudgetHandlers has been removed from its previous location in the codebase.

Possibly related PRs

  • [TypeScript] Make db.runQuery generic to make it easy to type DB query results #4247 - The changes in the main PR, specifically the modification of the createCategory function to simplify the assignment of the isIncome property, are related to the changes in the retrieved PR, which also involves updates to the createCategory function, particularly in how it handles database queries and type safety.
  • [Goals]: Handle tracking budget income categories #4300 - The changes in the main PR, which modify the assignment of the isIncome property in the createTestBudget function, are related to the changes in the retrieved PR that involve handling income categories in the init method of the CategoryTemplate class, as both involve the is_income property and its implications on budget processing.

Suggested labels

:sparkles: Merged

Suggested reviewers

  • youngcw
  • matt-fidd
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
  • @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

🧹 Nitpick comments (8)
packages/loot-core/src/server/budget/app.ts (8)

17-53: Consider grouping or splitting the interface
This interface houses many budget-related handlers in one place. If it grows further, consider grouping related handlers or splitting them into smaller interfaces to maintain readability.


146-198: Large function with repetitive array pushes
The repeated pattern of pushing cell values could be extracted into a helper function to reduce duplication and improve clarity, especially as more values get added.


200-244: Similar logic to envelopeBudgetMonth
This function’s structure largely mirrors envelopeBudgetMonth. Refactor common code to a shared utility to minimize duplication and improve maintainability.


269-287: Use robust error identification
Catching a unique constraint violation by checking the error message text is fragile. If possible, use a dedicated error code or numeric identifier to minimize false positives.


303-347: Refactor for clarity
This deletion logic (checking category existence, transferring items, deleting) is lengthy. Consider breaking it into smaller helper functions to handle separate responsibilities more cleanly.


353-367: Validate group name
You may consider validating the uniqueness of the group name or verifying it doesn’t conflict with existing groups.


385-406: Consistent with deleteCategory
This function handles optional transfer similarly. Ensure the transfer group is valid and consistent with the group’s income/expense type if that becomes a requirement.


408-435: Performance consideration
Scanning all months for non-zero budget allocations is acceptable for typical use. If the set of months grows significantly, consider caching or partial queries for better performance.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f413fa0 and 857e2f3.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/4442.md is excluded by !**/*.md
📒 Files selected for processing (6)
  • packages/loot-core/src/mocks/budget.ts (1 hunks)
  • packages/loot-core/src/server/budget/app.ts (2 hunks)
  • packages/loot-core/src/server/budget/types/handlers.d.ts (0 hunks)
  • packages/loot-core/src/server/db/index.ts (3 hunks)
  • packages/loot-core/src/server/main.ts (0 hunks)
  • packages/loot-core/src/types/handlers.d.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/loot-core/src/server/budget/types/handlers.d.ts
  • packages/loot-core/src/server/main.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Wait for Netlify build to finish
  • GitHub Check: Analyze
🔇 Additional comments (14)
packages/loot-core/src/types/handlers.d.ts (1)

3-3: LGTM! Import path updated correctly.

The import path for BudgetHandlers has been updated to reflect its new location in server/budget/app.ts, which aligns with the PR's objective of moving budget category related server handlers.

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

706-706: LGTM! Simplified boolean assignment.

The code now directly assigns the boolean value to isIncome instead of converting it to an integer, which is a cleaner approach.

packages/loot-core/src/server/db/index.ts (2)

354-382: LGTM! Enhanced type safety for insertCategoryGroup.

The function now has an explicit return type Promise<CategoryGroupEntity['id']> and properly typed variables, which improves type safety and code clarity.


411-464: LGTM! Enhanced type safety for insertCategory.

The function now has an explicit return type Promise<CategoryEntity['id']> and properly typed variables, which improves type safety and code clarity.

packages/loot-core/src/server/budget/app.ts (10)

1-9: Imports look good
No issues found with these new import statements.


13-16: No revision needed
These lines solely introduce new module imports or whitespace. Nothing further to address.


120-134: Consistent method registration
All newly added method registrations properly distinguish between read-only and mutating operations by wrapping only the latter with undoable. Good job preserving consistency.


135-140: Check for empty results
If no categories exist, this function currently returns empty arrays for grouped and list. That behavior might be acceptable, but consider whether a special response or additional error handling is needed if the database call fails unexpectedly.


142-144: Consider error boundary
Returning await budget.createAllBudgets() is straightforward, but if budget creation fails, ensure the caller handles the exception gracefully.


246-267: Verify group identity
Currently, only the presence of groupId is checked before inserting a new category. For added robustness, consider verifying that the referenced group actually exists and is valid.


289-301: All good
This moveCategory function cleanly calls db.moveCategory within batchMessages, ensuring batched updates.


349-351: All good
Straightforward retrieval of category groups from the database.


369-371: No immediate concerns
Calling db.updateCategoryGroup(group) directly is concise and consistent with your existing pattern.


373-383: All good
Moving the category group remains consistent with the pattern of wrapping DB interactions in batchMessages.

@joel-jeremy joel-jeremy changed the title Extract budget category related server handlers from main.ts to server/budger/app.ts Extract budget category related server handlers from main.ts to server/budget/app.ts Feb 24, 2025
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: 3

🧹 Nitpick comments (2)
packages/loot-core/src/server/budget/app.ts (2)

137-142: Consider adding error handling for database operations.

The getCategories function should handle potential database errors.

Consider wrapping the database calls in try-catch:

 async function getCategories() {
+  try {
     return {
       grouped: await getCategoryGroups(),
       list: (await db.getCategories()).map(categoryModel.fromDb),
     };
+  } catch (error) {
+    throw APIError('Failed to fetch categories', error);
+  }
 }

412-439: Add documentation for the isCategoryTransferRequired function.

The function's purpose and return value should be documented.

Add JSDoc documentation:

+/**
+ * Checks if a category needs to be transferred before deletion.
+ * @param {Object} params - The parameters object
+ * @param {number} params.id - The category ID to check
+ * @returns {Promise<boolean>} True if the category has transactions or non-zero budget values
+ */
 async function isCategoryTransferRequired({
   id,
 }: {
   id: CategoryEntity['id'];
 })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 857e2f3 and ac8fded.

📒 Files selected for processing (4)
  • packages/loot-core/src/server/api.ts (2 hunks)
  • packages/loot-core/src/server/budget/app.ts (2 hunks)
  • packages/loot-core/src/server/db/index.ts (4 hunks)
  • packages/loot-core/src/server/models.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/loot-core/src/server/db/index.ts
🧰 Additional context used
🪛 GitHub Check: typecheck
packages/loot-core/src/server/models.ts

[failure] 89-89:
Type '{ [k: string]: any; }' is missing the following properties from type 'DbCategory': id, name, is_income, cat_group, and 3 more.


[failure] 122-122:
Type '{ [k: string]: any; }' is missing the following properties from type 'DbCategoryGroup': id, name, is_income, sort_order, and 2 more.

🪛 GitHub Actions: Test
packages/loot-core/src/server/models.ts

[error] 89-89: Type '{ [k: string]: any; }' is missing the following properties from type 'DbCategory': id, name, is_income, cat_group, and 3 more.

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Functional
  • GitHub Check: Visual regression
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Analyze
🔇 Additional comments (5)
packages/loot-core/src/server/api.ts (2)

36-36: LGTM! Improved model separation with renamed import.

The renaming of categoryGroupModel to serverCategoryGroupModel improves clarity by explicitly indicating its server-side usage.


358-359: LGTM! Enhanced data transformation with proper model conversion.

The changes properly transform database entities to server models using the dedicated conversion method.

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

131-150: LGTM! Well-structured category group transformation.

The fromDb method properly handles the transformation of category groups and their associated categories.

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

18-54: LGTM! Well-defined comprehensive budget handlers interface.

The BudgetHandlers interface provides a clear contract for all budget-related operations.


271-289: LGTM! Robust error handling for category updates.

The updateCategory function properly handles unique constraint violations and other errors.

Comment on lines 85 to 99
toDb(
category: CategoryEntity,
{ update }: { update?: boolean } = {},
): DbCategory {
return update
? convertForUpdate(schema, schemaConfig, 'categories', category)
: convertForInsert(schema, schemaConfig, 'categories', category);
},
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix type safety issues in toDb method.

The method needs proper type handling to satisfy the DbCategory interface requirements.

Apply this fix to ensure type safety:

 toDb(
   category: CategoryEntity,
   { update }: { update?: boolean } = {},
 ): DbCategory {
-  return update
+  const result = update
     ? convertForUpdate(schema, schemaConfig, 'categories', category)
     : convertForInsert(schema, schemaConfig, 'categories', category);
+  return result as DbCategory;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
toDb(
category: CategoryEntity,
{ update }: { update?: boolean } = {},
): DbCategory {
return update
? convertForUpdate(schema, schemaConfig, 'categories', category)
: convertForInsert(schema, schemaConfig, 'categories', category);
},
toDb(
category: CategoryEntity,
{ update }: { update?: boolean } = {},
): DbCategory {
const result = update
? convertForUpdate(schema, schemaConfig, 'categories', category)
: convertForInsert(schema, schemaConfig, 'categories', category);
return result as DbCategory;
},
🧰 Tools
🪛 GitHub Check: typecheck

[failure] 89-89:
Type '{ [k: string]: any; }' is missing the following properties from type 'DbCategory': id, name, is_income, cat_group, and 3 more.

🪛 GitHub Actions: Test

[error] 89-89: Type '{ [k: string]: any; }' is missing the following properties from type 'DbCategory': id, name, is_income, cat_group, and 3 more.

Comment on lines 118 to 144
toDb(
categoryGroup: CategoryGroupEntity,
{ update }: { update?: boolean } = {},
): DbCategoryGroup {
return update
? convertForUpdate(schema, schemaConfig, 'category_groups', categoryGroup)
: convertForInsert(
schema,
schemaConfig,
'category_groups',
categoryGroup,
);
},
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix type safety issues in categoryGroupModel.toDb method.

Similar to categoryModel, this method needs proper type handling.

Apply this fix:

 toDb(
   categoryGroup: CategoryGroupEntity,
   { update }: { update?: boolean } = {},
 ): DbCategoryGroup {
-  return update
+  const result = update
     ? convertForUpdate(schema, schemaConfig, 'category_groups', categoryGroup)
     : convertForInsert(
         schema,
         schemaConfig,
         'category_groups',
         categoryGroup,
       );
+  return result as DbCategoryGroup;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
toDb(
categoryGroup: CategoryGroupEntity,
{ update }: { update?: boolean } = {},
): DbCategoryGroup {
return update
? convertForUpdate(schema, schemaConfig, 'category_groups', categoryGroup)
: convertForInsert(
schema,
schemaConfig,
'category_groups',
categoryGroup,
);
},
toDb(
categoryGroup: CategoryGroupEntity,
{ update }: { update?: boolean } = {},
): DbCategoryGroup {
const result = update
? convertForUpdate(schema, schemaConfig, 'category_groups', categoryGroup)
: convertForInsert(
schema,
schemaConfig,
'category_groups',
categoryGroup,
);
return result as DbCategoryGroup;
},
🧰 Tools
🪛 GitHub Check: typecheck

[failure] 122-122:
Type '{ [k: string]: any; }' is missing the following properties from type 'DbCategoryGroup': id, name, is_income, sort_order, and 2 more.

@matt-fidd
Copy link
Contributor

Looks like the category autocomplete's aren't working. To repro try transferring money from one category to another, or deleting a funded category and transferring to another.

There are some tests failing too

@joel-jeremy joel-jeremy force-pushed the server-budget-category-handlers branch 2 times, most recently from d6fa68d to c816e80 Compare March 4, 2025 19:20
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 (11)
packages/loot-core/src/server/models.ts (2)

90-107: New toDb and fromDb methods increase clarity.

The separation between the domain entity (CategoryEntity) and the DB representation (DbCategory) is consistent. Consider adding basic type or field checks after the conversion for stronger guarantees, especially for fields like name, cat_group, etc.


125-164: Ensure category references belong to the correct group.

Filtering by cat_group === categoryGroup.id in fromDb protects against unrelated categories. Since the query presumably already limits categories to this group, the filter is likely redundant. Removing it might reduce overhead. However, retaining it is safer if the data constraints are uncertain.

packages/loot-core/src/server/budget/app.ts (9)

14-17: Base, cleanup-template, and goaltemplates usage.

Bringing in these modules helps isolate specific budget-related operations. This separation aligns well with the PR's objective to refactor budget logic out of main.ts. Check that all references to older budget code have been removed or properly migrated.


136-142: getCategories method returns grouped and list formats.

Returning both grouped and flat lists is convenient for UIs, but be mindful of performance overhead with large data sets. If expansions grow, consider lazy-loading or pagination.


144-146: getBudgetBounds usage.

budget.createAllBudgets() can be an expensive call if it calculates across large datasets. Monitor performance in production to ensure it scales for many months/categories.


148-200: envelopeBudgetMonth function handles multi-group iteration.

Collecting budget values from the spreadsheet for each group and category is thorough. Consider caching repeated calls to value(...) or sheet.getCellValue(...) if performance becomes an issue at scale.


271-291: updateCategory handles unique constraint errors.

Gracefully returning { error: { type: 'category-exists' } } is user friendly. Consider adding more context to the error, such as which name conflicts.


359-363: getCategoryGroups returns properly converted entities.

The code fetches DB rows, then transforms them to domain entities. Ensure local testing includes category groups with no categories to confirm robust conversion logic.


365-379: createCategoryGroup normalizes inputs.

As with createCategory, booleans are coerced to integers. This is consistent. If category group naming collisions are possible, consider handling or explicitly ignoring them.


385-395: moveCategoryGroup function uses batchMessages.

Like moveCategory, batch operations help keep synchronization events consistent. Double-check that targetId is valid to avoid potential ordering conflicts.


420-447: isCategoryTransferRequired checks transactions and budget cells.

This thorough approach ensures that categories with existing transactions or non-zero budget values cannot be deleted without a transfer. Confirm that tombstoned transactions or archived months are handled as intended in all edge cases.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f46ae4 and f27ee4e.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/4442.md is excluded by !**/*.md
📒 Files selected for processing (8)
  • packages/loot-core/src/mocks/budget.ts (1 hunks)
  • packages/loot-core/src/server/api.ts (2 hunks)
  • packages/loot-core/src/server/budget/app.ts (2 hunks)
  • packages/loot-core/src/server/budget/types/handlers.d.ts (0 hunks)
  • packages/loot-core/src/server/db/index.ts (7 hunks)
  • packages/loot-core/src/server/main.ts (0 hunks)
  • packages/loot-core/src/server/models.ts (4 hunks)
  • packages/loot-core/src/types/handlers.d.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/loot-core/src/server/main.ts
  • packages/loot-core/src/server/budget/types/handlers.d.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/loot-core/src/types/handlers.d.ts
  • packages/loot-core/src/mocks/budget.ts
  • packages/loot-core/src/server/api.ts
  • packages/loot-core/src/server/db/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Visual regression
  • GitHub Check: Functional
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: build (windows-latest)
🔇 Additional comments (12)
packages/loot-core/src/server/models.ts (4)

7-13: Imports look good.

These imports from ./aql and ./db help cleanly separate concerns for database conversion utilities and DB types. Ensure there are no circular dependencies resulting from these additions, and verify that the schema references in schema & schemaConfig remain stable when used elsewhere.


76-89: Check for omitted sort_order in the returned object.

sort_order is destructured and discarded. If DbCategory requires sort_order, it might cause type or functional discrepancies. Confirm that it's genuinely optional in DbCategory or consider preserving it if required.


112-124: Validate that is_income is only optional for insert.

is_income is checked only on update in the requiredFields call. Confirm whether new category groups also require is_income. If it’s essential for newly created groups, ensure it’s validated consistently.


60-72:

❓ Verification inconclusive

Confirm that required fields match the DbAccount definition.

Casting Partial<DbAccount> to DbAccount requires validating all mandatory fields. The call to requiredFields only checks 'name', 'offbudget', and 'closed'. Confirm whether DbAccount has additional compulsory properties (e.g., id), and ensure their presence.

Run the following script to look for properties declared in DbAccount that might not be enforced by requiredFields:


🏁 Script executed:

#!/bin/bash
# Searching for DbAccount interface definition and listing its fields:
ast-grep --pattern $'interface DbAccount {\n  $$$\n}' 

Length of output: 52


It appears that our initial ast-grep search did not return any output, which makes it difficult to determine if there are additional mandatory fields in the DbAccount interface (such as an id property) that are not being validated by our requiredFields call. Please run the above command to search for the DbAccount interface definition using ripgrep. Once we have the output, we can confirm whether the list of required fields in the validate() method is complete.

Action Required:

  • Review the output of the above script: Ensure that the DbAccount interface does not specify additional compulsory properties besides 'name', 'offbudget', and 'closed'.
  • Update the code if necessary: If extra mandatory fields are found (e.g., id), update the requiredFields call accordingly.

🏁 Script executed:

#!/bin/bash
# Use ripgrep to locate the definition of DbAccount within the repository.
rg "interface DbAccount" -n .

Length of output: 31


Manual Verification Required: Confirm Additional Mandatory Fields in DbAccount

The automated searches for the DbAccount definition using both ast-grep and rg did not yield any output. This makes it unclear whether DbAccount includes additional mandatory properties—such as id—that are not validated by the current requiredFields call. Please manually verify the complete definition of DbAccount in the codebase and ensure that all required fields are being checked within the validate() method in packages/loot-core/src/server/models.ts.

  • Action Items:
    • Manually locate the complete definition of DbAccount in your repository.
    • Confirm if the interface (or type) includes any mandatory properties beyond 'name', 'offbudget', and 'closed'.
    • Update the requiredFields call accordingly if additional required properties are found.
packages/loot-core/src/server/budget/app.ts (8)

1-10: Imports promote modular design.

Importing utilities from monthUtils, db, and sheet fosters a well-organized codebase. Verify that these dependencies don't produce cyclical imports and confirm monthUtils.sheetForMonth usage won't break when invoked across different modules.


18-54: New BudgetHandlers interface centralizes budget-related methods.

Centralizing these methods under one interface clarifies usage and fosters maintainability. Confirm that external calls referencing old handler names (from main.ts) have been updated accordingly to avoid runtime errors.


121-135: Registering new budget category endpoints with app.method.

These lines allow the server to expose new and refactored budget endpoints. Ensure test coverage on each method, especially for corner cases.


248-269: createCategory enforces groupId existence.

This ensures categories cannot exist without a group. Good job on validating user input and normalizing booleans into integers for is_income/hidden. More advanced validation logic (e.g., checking group existence) can further prevent orphaned records.


293-305: moveCategory grouping logic.

batchMessages usage is a solid approach for ensuring only one group-level message is emitted for a sequence of category moves. Confirm that reordering logic with targetId is stable across different edge cases (e.g., targetId equals id).


307-357: deleteCategory handles is_income matching and optional transfer.

The function carefully checks if the target category has the same is_income type. This is crucial for preventing invalid merges. Confirm that the UI properly prompts the user to handle transfers for categories with budget history or leftover amounts.


381-383: updateCategoryGroup delegates to categoryGroupModel.toDb.

This is consistent with the earlier patterns. Confirm that changes requiring update-only validations (e.g., is_income) are tested if needed for partial updates.


397-418: deleteCategoryGroup handles group-wide category transfers.

This logic merges categories into another group if transferId is provided. Confirm that any transactions tied to the old group remain valid. Testing with partial group merges is recommended.

Comment on lines +202 to +246
async function trackingBudgetMonth({ month }: { month: string }) {
const groups = await db.getCategoriesGrouped();
const sheetName = monthUtils.sheetForMonth(month);

function value(name: string) {
const v = sheet.getCellValue(sheetName, name);
return { value: v === '' ? 0 : v, name: resolveName(sheetName, name) };
}

let values = [
value('total-budgeted'),
value('total-budget-income'),
value('total-saved'),
value('total-income'),
value('total-spent'),
value('real-saved'),
value('total-leftover'),
];

for (const group of groups) {
values = values.concat([
value(`group-budget-${group.id}`),
value(`group-sum-amount-${group.id}`),
value(`group-leftover-${group.id}`),
]);

const categories = group.categories ?? [];

for (const cat of categories) {
values = values.concat([
value(`budget-${cat.id}`),
value(`sum-amount-${cat.id}`),
value(`leftover-${cat.id}`),
value(`goal-${cat.id}`),
value(`long-goal-${cat.id}`),
]);

if (!group.is_income) {
values.push(value(`carryover-${cat.id}`));
}
}
}

return values;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

trackingBudgetMonth function similarly iterates across groups.

Much like envelopeBudgetMonth, repeated calls to value(...) might be expensive. If real-time usage is needed, confirm that the overhead is acceptable or implement caching.

@joel-jeremy joel-jeremy force-pushed the server-budget-category-handlers branch from f27ee4e to cb9a201 Compare March 4, 2025 20:41
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

🧹 Nitpick comments (6)
packages/loot-core/src/server/models.ts (2)

90-99: Robust conversion to DB.
Calling convertForUpdate or convertForInsert based on the update flag is a clean way to handle DB writes. Consider adding light error-handling if these conversion functions may throw.


125-144: toDb method for category groups.
Your approach mirrors categoryModel.toDb, promoting consistency. As with categories, consider minimal error-handling if the conversion fails instead of letting it bubble unhandled.

packages/loot-core/src/server/budget/app.ts (4)

248-269: createCategory with minimal validation.
Checking groupId is required, but consider disallowing empty or whitespace-only name.trim() as it may lead to placeholder or default naming issues.


271-291: updateCategory handles unique constraint errors.
Catching and returning an error object is a neat approach to handle DB conflicts. Complement it with checks for empty or invalid category names, mirroring recommendations in createCategory.


307-357: deleteCategory with partial transfer logic.
This function handles the expense category transfer but leaves a TODO for income categories. Ensure the code covers all relevant scenarios or provide a fallback to avoid data inconsistencies.

Would you like help implementing that TODO for income categories?


365-379: createCategoryGroup.
As with categories, consider stricter validation (e.g., trim name, etc.) if you want to prevent accidental blank group names.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f27ee4e and cb9a201.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/4442.md is excluded by !**/*.md
📒 Files selected for processing (8)
  • packages/loot-core/src/mocks/budget.ts (1 hunks)
  • packages/loot-core/src/server/api.ts (2 hunks)
  • packages/loot-core/src/server/budget/app.ts (2 hunks)
  • packages/loot-core/src/server/budget/types/handlers.d.ts (0 hunks)
  • packages/loot-core/src/server/db/index.ts (7 hunks)
  • packages/loot-core/src/server/main.ts (0 hunks)
  • packages/loot-core/src/server/models.ts (4 hunks)
  • packages/loot-core/src/types/handlers.d.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/loot-core/src/server/main.ts
  • packages/loot-core/src/server/budget/types/handlers.d.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/loot-core/src/mocks/budget.ts
  • packages/loot-core/src/server/api.ts
  • packages/loot-core/src/types/handlers.d.ts
  • packages/loot-core/src/server/db/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Functional
  • GitHub Check: Visual regression
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (21)
packages/loot-core/src/server/models.ts (8)

7-14: Imports look appropriate.
The new imports from './aql' and './db' provide clarity and consolidate the conversion methods and types in one place. This organization helps maintain cleaner code.


60-63: Partial type validation for DbAccount.
Casting account directly to DbAccount after using requiredFields is a concise approach, but be mindful that any additional or removed fields in the future might not raise compile-time issues if requiredFields is not updated accordingly. Overall, this aligns well with your type-safety checks.

Also applies to: 71-71


76-79: Consistent approach for Partial.
Similar to the account validation, the use of Partial<DbCategory> here ensures that only necessary fields are validated, which matches the optional update flow.


88-89: Omission of sort_order.
Excluding sort_order from the returned object may be intentional, but verify whether downstream logic or UI relies on this property.


100-107: Straightforward DB-to-entity conversion.
Using convertFromSelect to map DbCategory to CategoryEntity is consistent and clear. This helps keep model logic centralized.


112-112: Validate method for DbCategoryGroup.
Enforcing required fields through requiredFields for both insert and update is consistent with the category model’s pattern.

Also applies to: 114-114


123-124: Filtering out sort_order again.
Like in categoryModel, ensure omitting sort_order here is truly intended and doesn't break ordering logic in the UI or reporting.


146-163: Transforming DB groups back to entities.
Leveraging convertFromSelect for the main group data and then mapping categories is a neat separation of concerns. Good job keeping the logic consistent across models.

packages/loot-core/src/server/budget/app.ts (13)

1-14: Refactored imports.
These import statements consolidate references to db, models, sheet, and various utilities. The structure indicates that budget-specific logic is properly isolated here, which aligns with the PR’s goal of organizing budget code.


18-54: New BudgetHandlers interface.
Defining all budget operations within a single interface clarifies code organization and fosters discoverability. This structure should simplify future maintenance.


121-134: Registering budget methods.
Binding your new and existing functions to app.method in a single location is consistent with the rest of the codebase and helps keep the route definitions tidy.


136-142: getCategories returns immediate domain objects.
Converting from DB via categoryModel.fromDb at the server layer ensures that clients (or other layers) receive only domain-level data. This is a clean separation of concerns.


144-146: Straightforward getBudgetBounds.
Simply returning budget.createAllBudgets() keeps the logic minimal. Verify that any errors from createAllBudgets() are acceptable to bubble up rather than being handled at this level.


148-200: Repeated spreadsheet lookups (envelopeBudgetMonth).
This function calls sheet.getCellValue repeatedly. If performance becomes critical, consider batching retrievals or caching results.


202-246: Parallel logic for trackingBudgetMonth.
Like envelopeBudgetMonth, this function also makes multiple sheet.getCellValue calls in a loop, potentially impacting performance under heavy loads.


293-305: moveCategory.
This is a clean, focused wrapper that delegates logic to db.moveCategory. Maintaining segregation of DB queries promotes modular design.


359-363: getCategoryGroups returns domain objects.
Calling categoryGroupModel.fromDb ensures the response is domain-centric, which is consistent with getCategories.


381-383: updateCategoryGroup.
This straightforward method is consistent with the rest of the CRUD operations, delegating conversions to the model for type safety.


385-395: moveCategoryGroup.
This block method is similarly minimal, matching the pattern in moveCategory.


397-418: deleteCategoryGroup with optional transfer.
Transferring all categories in the group prior to deletion is a pragmatic approach. This logic prevents orphaned categories or incomplete references.


420-447: isCategoryTransferRequired checks usage across transactions and budget values.
Efficiently scanning transactions first, then checking budget months is a logical approach. Ensure the coverage aligns with any new budget concepts or additional references that could also force transfers.

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