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 4 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 4d0d193
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67bcaf87c31b390008a7a56d
😎 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
17 7 MB → 7 MB (+225 B) +0.00%
Changeset
File Δ Size
locale/fr.json 📈 +225 B (+0.26%) 84.49 kB → 84.71 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/fr.js 84.49 kB → 84.71 kB (+225 B) +0.26%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/de.js 115.06 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/en-GB.js 99.33 kB 0%
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/en.js 103.19 kB 0%
static/js/uk.js 111.11 kB 0%
static/js/nl.js 98.45 kB 0%
static/js/narrow.js 85.76 kB 0%
static/js/pt-BR.js 113.53 kB 0%
static/js/useAccountPreviewTransactions.js 1.69 kB 0%
static/js/AppliedFilters.js 10.79 kB 0%
static/js/wide.js 102.9 kB 0%
static/js/ReportRouter.js 1.59 MB 0%
static/js/index.js 4.35 MB 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.34 MB → 1.34 MB (+464 B) +0.03%
Changeset
File Δ Size
packages/loot-core/src/server/budget/app.ts 📈 +8.37 kB (+410.24%) 2.04 kB → 10.41 kB
packages/loot-core/src/server/models.ts 📈 +1013 B (+44.14%) 2.24 kB → 3.23 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.38 kB → 29.37 kB
packages/loot-core/src/server/db/index.ts 📉 -119 B (-0.57%) 20.54 kB → 20.42 kB
packages/loot-core/src/server/main.ts 📉 -7.89 kB (-17.33%) 45.54 kB → 37.65 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
kcab.worker.js 1.34 MB → 1.34 MB (+464 B) +0.03%

Smaller

No assets were smaller

Unchanged

No assets were unchanged

Copy link
Contributor

coderabbitai bot commented Feb 24, 2025

Warning

Rate limit exceeded

@joel-jeremy has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 2 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between ac8fded and 4d0d193.

📒 Files selected for processing (1)
  • packages/loot-core/src/server/models.ts (3 hunks)

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

  • [Goals]: Handle tracking budget income categories #4300 - The changes in the main PR, which modify the handling of the isIncome property in the createTestBudget function, are related to the changes in the retrieved PR that also involve the is_income property in the CategoryTemplate class's init method, affecting how income categories are processed.
  • [TypeScript] Make db.runQuery generic to make it easy to type DB query results #4247 - The changes in the main PR, specifically the modifications to the createCategory function in packages/loot-core/src/server/budget/app.ts, are related to the changes in the retrieved PR, which also modifies the createCategory function in packages/loot-core/src/server/budget/base.ts, as both PRs involve updates to the same function's implementation.
  • Extract budget related server handlers from main.ts to server/budget/app.ts #4419 - The changes in the main PR, which simplify the assignment of the isIncome property in the createTestBudget function, are related to the modifications in the retrieved PR that involve the createCategory function in the BudgetHandlers interface, as both PRs deal with category management and the handling of the isIncome property.

Suggested labels

:sparkles: Merged

Suggested reviewers

  • MikesGlitch

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: 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 92
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 130
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.

Comment on lines +305 to +349
async function deleteCategory({
id,
transferId,
}: {
id: CategoryEntity['id'];
transferId: CategoryEntity['id'];
}): Promise<{ error?: 'no-categories' | 'category-type' }> {
let result = {};
await batchMessages(async () => {
const row = await db.first(
'SELECT is_income FROM categories WHERE id = ?',
[id],
);
if (!row) {
result = { error: 'no-categories' };
return;
}

const transfer =
transferId &&
(await db.first('SELECT is_income FROM categories WHERE id = ?', [
transferId,
]));

if (!row || (transferId && !transfer)) {
result = { error: 'no-categories' };
return;
} else if (transferId && row.is_income !== transfer.is_income) {
result = { error: 'category-type' };
return;
}

// Update spreadsheet values if it's an expense category
// TODO: We should do this for income too if it's a reflect budget
if (row.is_income === 0) {
if (transferId) {
await budget.doTransfer([id], transferId);
}
}

await db.deleteCategory({ id }, transferId);
});

return result;
}
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

Add validation for transferId parameter.

The deleteCategory function should validate transferId before using it.

Add validation at the start of the function:

 async function deleteCategory({
   id,
   transferId,
 }: {
   id: CategoryEntity['id'];
   transferId: CategoryEntity['id'];
 }): Promise<{ error?: 'no-categories' | 'category-type' }> {
+  if (transferId && typeof transferId !== 'number') {
+    throw APIError('Invalid transferId parameter');
+  }
   let result = {};
   await batchMessages(async () => {
     // ... rest of the function
📝 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
async function deleteCategory({
id,
transferId,
}: {
id: CategoryEntity['id'];
transferId: CategoryEntity['id'];
}): Promise<{ error?: 'no-categories' | 'category-type' }> {
let result = {};
await batchMessages(async () => {
const row = await db.first(
'SELECT is_income FROM categories WHERE id = ?',
[id],
);
if (!row) {
result = { error: 'no-categories' };
return;
}
const transfer =
transferId &&
(await db.first('SELECT is_income FROM categories WHERE id = ?', [
transferId,
]));
if (!row || (transferId && !transfer)) {
result = { error: 'no-categories' };
return;
} else if (transferId && row.is_income !== transfer.is_income) {
result = { error: 'category-type' };
return;
}
// Update spreadsheet values if it's an expense category
// TODO: We should do this for income too if it's a reflect budget
if (row.is_income === 0) {
if (transferId) {
await budget.doTransfer([id], transferId);
}
}
await db.deleteCategory({ id }, transferId);
});
return result;
}
async function deleteCategory({
id,
transferId,
}: {
id: CategoryEntity['id'];
transferId: CategoryEntity['id'];
}): Promise<{ error?: 'no-categories' | 'category-type' }> {
if (transferId && typeof transferId !== 'number') {
throw APIError('Invalid transferId parameter');
}
let result = {};
await batchMessages(async () => {
const row = await db.first(
'SELECT is_income FROM categories WHERE id = ?',
[id],
);
if (!row) {
result = { error: 'no-categories' };
return;
}
const transfer =
transferId &&
(await db.first('SELECT is_income FROM categories WHERE id = ?', [
transferId,
]));
if (!row || (transferId && !transfer)) {
result = { error: 'no-categories' };
return;
} else if (transferId && row.is_income !== transfer.is_income) {
result = { error: 'category-type' };
return;
}
// Update spreadsheet values if it's an expense category
// TODO: We should do this for income too if it's a reflect budget
if (row.is_income === 0) {
if (transferId) {
await budget.doTransfer([id], transferId);
}
}
await db.deleteCategory({ id }, transferId);
});
return result;
}

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.

1 participant