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 payees related server handlers from main.ts to server/payees/app.ts #4443

Open
wants to merge 8 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 payees related server handlers from main.ts to server/payees/app.ts [WIP] Extract payees related server handlers from main.ts to server/payees/app.ts Feb 24, 2025
Copy link

netlify bot commented Feb 24, 2025

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit 77d0edc
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67c734dfa65ef30008400f1d
😎 Deploy Preview https://deploy-preview-4443.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 payees related server handlers from main.ts to server/payees/app.ts Extract payees related server handlers from main.ts to server/payees/app.ts Feb 24, 2025
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 7.07 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/en-GB.js 98.67 kB 0%
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/fr.js 90.64 kB 0%
static/js/es.js 60.58 kB 0%
static/js/en.js 103.18 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/de.js 114.35 kB 0%
static/js/uk.js 111.11 kB 0%
static/js/nl.js 97.78 kB 0%
static/js/pt-BR.js 112.83 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/narrow.js 86.23 kB 0%
static/js/useAccountPreviewTransactions.js 1.69 kB 0%
static/js/AppliedFilters.js 10.8 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 (+261 B) +0.02%
Changeset
File Δ Size
packages/loot-core/src/server/payees/app.ts 🆕 +2.36 kB 0 B → 2.36 kB
packages/loot-core/src/server/models.ts 📈 +384 B (+16.73%) 2.24 kB → 2.62 kB
packages/loot-core/src/server/main.ts 📉 -1.65 kB (-3.62%) 45.54 kB → 43.89 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 (+261 B) +0.02%

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 14 minutes and 17 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 88fc27f and 77d0edc.

📒 Files selected for processing (2)
  • packages/loot-core/src/server/payees/app.ts (1 hunks)
  • packages/loot-core/src/server/undo.ts (1 hunks)

Walkthrough

The changes refactor and enhance the payee functionality across several files. In the database module, the insertPayee function now explicitly types the id variable as DbPayee['id'], reinforcing type safety. In main.ts, a new module payeesApp is imported and integrated, while several standalone payee handlers are removed, shifting the responsibility to the modular payeesApp. A new file, app.ts, is introduced to encapsulate all payee-related operations, including creation, retrieval, merging, batch processing, and rule management. Additionally, the Handlers interface is updated in handlers.d.ts to include the new PayeesHandlers type, ensuring that payee operations are properly recognized in the overall handlers declaration.

Possibly related PRs

Suggested Labels

:sparkles: Merged

Suggested Reviewers

  • youngcw
  • matt-fidd

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

🧹 Nitpick comments (4)
packages/loot-core/src/server/payees/app.ts (4)

9-19: Consider explicitly typing function return values.
Explicitly defining the return types of functions used in PayeesHandlers can enhance code clarity and reduce potential confusion.


44-46: Clarify naming for syncGetOrphanedPayees.
The term “sync” could be misinterpreted as synchronous. Consider a more descriptive function name or an explanatory comment.


48-59: Anticipate performance constraints in getPayeeRuleCounts.
Manually iterating over rules can be expensive at scale. Consider delegating the count logic to the database or caching logic if performance becomes a concern.


109-115: Add a docstring for clarity.
A brief docstring explaining getPayeeRules aids future maintainers in understanding the function’s purpose and returned data shape.

📜 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 d2e5234.

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

7-7: Good addition for modular payee handling.
This import cleanly separates payee-related handler logic.


32-33: Interface extension aligns with new PayeesHandlers.
Including PayeesHandlers in Handlers codifies the newly modular payee functionality.

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

519-519: Great improvement in type safety.
Declaring id as DbPayee['id'] helps ensure consistent usage across the codebase.

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

45-45: Modular import promotes better payee separation.
Importing payeesApp is consistent with removing payee-handling logic from this file.


65-65: Verify concurrency usage with batchMessages.
Ensure the code properly handles and sequences batched DB updates to avoid data inconsistencies.


71-71: Importing undo functions is consistent.
These additions support advanced undo/redo operations; looks properly aligned with the existing pattern.


439-439: Consolidation of payee routes.
Combining payeesApp finalizes the modular approach, grouping payee-related endpoints logically.

packages/loot-core/src/server/payees/app.ts (6)

1-8: Imports look consistent.
All the imported modules are used appropriately. No concerns here.


21-30: Well-structured method registrations.
The usage of createApp coupled with method definitions is straightforward and organized. Each method is clearly registered with its key, which aligns with best practices.


32-34: Handle potential DB insertion errors.
Consider adding error handling around db.insertPayee to gracefully report or manage insertion failures.


36-42: Standard retrieval methods look solid.
The getCommonPayees and getPayees functions are concise and appear correct for data retrieval.


61-74: Guard against merging payee into itself.
Verify how the function behaves if mergeIds contains targetId or if a payee does not exist.


100-107: Confirm orphaned payee assumptions.
Ensure db.getOrphanedPayees consistently returns valid IDs and handle any edge cases involving an empty or erroneous outcome.

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

109-116: Consider enhancing type safety in fromDb method.

While the implementation is functionally correct, consider replacing the type assertion with a type guard to ensure type safety at runtime.

-    return convertFromSelect(
+    const converted = convertFromSelect(
       schema,
       schemaConfig,
       'payees',
       payee,
-    ) as PayeeEntity;
+    );
+    if (!isPayeeEntity(converted)) {
+      throw new Error('Invalid PayeeEntity conversion');
+    }
+    return converted;

Consider adding a type guard function:

function isPayeeEntity(obj: unknown): obj is PayeeEntity {
  return obj !== null && typeof obj === 'object' && 'name' in obj;
}

117-123: Consider enhancing type safety in toDb method.

Similar to fromDb, consider adding type guards and error handling for better runtime safety.

-    return (
+    const converted = (
       update
         ? convertForUpdate(schema, schemaConfig, 'payees', payee)
         : convertForInsert(schema, schemaConfig, 'payees', payee)
-    ) as DbPayee;
+    );
+    if (!isDbPayee(converted)) {
+      throw new Error('Invalid DbPayee conversion');
+    }
+    return converted;

Consider adding a type guard function:

function isDbPayee(obj: unknown): obj is DbPayee {
  return obj !== null && typeof obj === 'object' && 'id' in obj;
}

Also, consider adding JSDoc comments to document the conversion process:

/**
 * Converts a PayeeEntity to a DbPayee format
 * @param payee - The payee entity to convert
 * @param options - Options for the conversion
 * @param options.update - If true, converts for update operation, otherwise for insert
 * @returns The converted DbPayee object
 * @throws {Error} If conversion results in invalid DbPayee
 */
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d2e5234 and 8f73264.

📒 Files selected for processing (3)
  • packages/loot-core/src/server/db/index.ts (4 hunks)
  • packages/loot-core/src/server/models.ts (2 hunks)
  • packages/loot-core/src/server/payees/app.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/loot-core/src/server/db/index.ts
  • packages/loot-core/src/server/payees/app.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (windows-latest)
  • GitHub Check: Wait for Netlify build to finish
  • GitHub Check: Analyze
  • GitHub Check: release-notes
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (1)
packages/loot-core/src/server/models.ts (1)

8-15: LGTM!

The new imports are well-organized and provide the necessary utilities for the payee model enhancements.

@matt-fidd
Copy link
Contributor

Looks like per-payee category learning settings aren't working here, they appear to be always disabled and can't be enabled.

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

♻️ Duplicate comments (1)
packages/loot-core/src/server/payees/app.ts (1)

80-98: 🛠️ Refactor suggestion

**Reinforce atomicity for batch changes. **

As noted in past reviews, partially failed batch operations can leave the data in an inconsistent state. Consider introducing a transaction mechanism or a rollback strategy if any individual operation fails.

🧹 Nitpick comments (6)
packages/loot-core/src/server/payees/app.ts (4)

1-10: Favor explicit imports for clarity and maintainability.

While the imports here are consolidated from multiple modules, consider selectively importing only what is necessary (e.g., insertPayee, getPayees) if the underlying modules export multiple functions. This reduces the chance of namespace clashes and clarifies usage.


34-36: Check for input validations.

createPayee does not currently validate name. Consider adding checks to ensure name is not empty or invalid. This can help prevent introducing accidental blank or invalid payees into the database.


38-50: Potential for large data returns on get operations.

getCommonPayees, getPayees, and getOrphanedPayees return arrays that may become large for existing databases. Depending on usage patterns, consider adding pagination or filters to avoid performance bottlenecks for large datasets.


52-63: Be mindful of performance in counting rules.

getPayeeRuleCounts iterates over all rules in memory. If the set of rules grows large, this approach might be slow or memory-intensive. Consider storing this count in the database or indexing it if performance becomes an issue.

packages/desktop-client/src/components/payees/ManagePayees.tsx (1)

106-108: Verify orphaned payees implementation

The filter logic here correctly handles the updated type of orphanedPayees as it only uses the ID field. However, since the orphanedPayees type changed to only include the id field, the mapping expression could be simplified.

Consider simplifying this expression:

- filtered = filtered.filter(p =>
-   orphanedPayees.map(o => o.id).includes(p.id),
- );
+ filtered = filtered.filter(p => 
+   orphanedPayees.some(o => o.id === p.id),
+ );

Using some() instead of map().includes() is more efficient as it stops iteration as soon as a match is found.

packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx (1)

133-136: Simplify orphan ID lookups

Since orphans now only contain ID fields, the current implementation using map().includes() is functional but can be optimized.

Consider simplifying these lookups:

- const targetIdIsOrphan = orphans.map(o => o.id).includes(targetId);
- const mergeIdsOrphans = mergeIds.filter(m =>
-   orphans.map(o => o.id).includes(m),
- );
+ const targetIdIsOrphan = orphans.some(o => o.id === targetId);
+ const mergeIdsOrphans = mergeIds.filter(m =>
+   orphans.some(o => o.id === m),
+ );

Using some() is more efficient as it stops iteration as soon as a match is found.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1e57e8d and 88fc27f.

📒 Files selected for processing (5)
  • packages/desktop-client/src/components/payees/ManagePayees.tsx (1 hunks)
  • packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx (1 hunks)
  • packages/loot-core/src/server/payees/app.ts (1 hunks)
  • packages/loot-core/src/shared/util.ts (2 hunks)
  • packages/loot-core/src/types/server-handlers.d.ts (1 hunks)
⏰ 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)
🔇 Additional comments (11)
packages/loot-core/src/server/payees/app.ts (5)

11-21: Great use of a dedicated handlers type.

defining PayeesHandlers provides clarity around the shape of payees-related operations and makes it easier to keep track of available endpoints.


23-33: Modular payees app setup looks solid.

Exporting app as the primary interface ensures a clear delineation of payee-specific behavior. This is aligned with the PR's goal of extracting payee logic out of main.ts.


65-78: Undo mechanism integrates well, but watch for partial failures.

withUndo is a strong approach to revert merges if needed. However, if partial failures occur during db.mergePayees, ensure proper rollback or error handling is in place to avoid inconsistent states.


100-107: Efficient approach to checking orphaned payees.

checkOrphanedPayees is straightforward and uses Set for quick lookups. This is efficient for fairly large lists of IDs.


109-115: Serialization of rules is clear and consistent.

Returning rule.serialize() ensures a uniform structure and hides internal details from consumers. This helps maintain a stable contract for payee rules.

packages/loot-core/src/types/server-handlers.d.ts (1)

7-7: Removal of payee references in server-handlers aligns with the new modular payees app.

This change cleans up the interface by deferring payee operations to the dedicated PayeesHandlers. This promotes better separation of concerns.

packages/desktop-client/src/components/payees/ManagePayees.tsx (1)

73-73: Type restriction improves type safety

The type change from PayeeEntity[] to Array<Pick<PayeeEntity, 'id'>> restricts the orphanedPayees property to only include the id field of payee entities. This is a good optimization that aligns with how orphaned payees are actually used in the component (only the IDs are necessary as seen on line 107).

packages/loot-core/src/shared/util.ts (2)

48-48: Type refinement for deleted items improves data efficiency

Changing deleted: Partial<T>[] to deleted: Pick<T, 'id'>[] in the Diff type definition ensures that deleted items only contain the ID field, which is all that's needed for deletion operations. This is a good optimization that reduces the memory footprint when handling deletions.


132-134: Implementation aligns with type definition

The implementation of diffItems has been updated to match the refined type definition, ensuring that deleted items only include the ID field. This change is consistent with the type change on line 48 and provides a more efficient data structure for deleted items.

packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx (2)

30-30: State type update for consistency

The state type for orphans has been updated to match the prop type change in ManagePayees.tsx. This ensures type consistency between components and aligns with the data optimization pattern used throughout the payee management components.


127-129:

❓ Verification inconclusive

Verify payees update behavior

The removal of await dispatch(getPayees()); after updating payees with payees-batch-change changes the component's behavior. The component now relies on the applyChanges function to update the orphans state locally without refetching all payees from the server.

Make sure this change is intentional and doesn't lead to stale data. This adjustment might be related to performance optimization, but ensure that payee data remains in sync between components.


🏁 Script executed:

#!/bin/bash
# Check for other instances where getPayees() is called after batch changes
rg -A 3 "payees-batch-change" --glob "*.ts*"

Length of output: 1729


Action Required: Confirm Local Sync is Sufficient After Batch Update

In the file packages/desktop-client/src/components/payees/ManagePayeesWithData.tsx, the batch update now executes:

await send('payees-batch-change', changes);
setOrphans(applyChanges(changes, orphans));

The previous call to dispatch(getPayees()) has been removed, so the component now relies on applyChanges to update the local orphan state without refetching all payees from the server. Our grep search for "payees-batch-change" confirms that no subsequent getPayees() call exists in the client code, which suggests that this change is intentional and likely aimed at optimizing performance.

Please verify that:

  • The local state update using applyChanges sufficiently synchronizes the payee data across components.
  • There is no risk of stale data due to the absence of a full refetch, particularly if other parts of the application depend on more comprehensive payee data.

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