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

[TypeScript] Make db.first generic to make it easy to type DB query results #4248

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

Conversation

joel-jeremy
Copy link
Contributor

@joel-jeremy joel-jeremy commented Jan 28, 2025

Follow up to #4247

  • db.runQuery
  • db.first
  • db.firstSync
  • db.all
  • db.select
  • db.selectWithSchema
  • db.selectFirstWithSchema

@actual-github-bot actual-github-bot bot changed the title [TypeScript] Make db.first generic to make it easy to type DB query results [WIP] [TypeScript] Make db.first generic to make it easy to type DB query results Jan 28, 2025
@joel-jeremy joel-jeremy changed the base branch from master to ts-runQuery-new January 28, 2025 06:49
Copy link

netlify bot commented Jan 28, 2025

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit 8752f32
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67b4ed53464ba600080d0d88
😎 Deploy Preview https://deploy-preview-4248.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 Jan 28, 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 6.93 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 99.42 kB 0%
static/js/en.js 100.54 kB 0%
static/js/de.js 111.72 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/nl.js 98.54 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/fr.js 72.19 kB 0%
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/pt-BR.js 106.43 kB 0%
static/js/uk.js 111.11 kB 0%
static/js/AppliedFilters.js 10.52 kB 0%
static/js/useAccountPreviewTransactions.js 1.69 kB 0%
static/js/narrow.js 85.57 kB 0%
static/js/wide.js 102.8 kB 0%
static/js/ReportRouter.js 1.59 MB 0%
static/js/index.js 4.31 MB 0%

Copy link
Contributor

github-actions bot commented Jan 28, 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.33 MB → 1.33 MB (+24 B) +0.00%
Changeset
File Δ Size
packages/loot-core/src/server/budget/goalsSchedule.ts 📈 +12 B (+0.15%) 7.71 kB → 7.72 kB
packages/loot-core/src/server/accounts/transaction-rules.ts 📈 +25 B (+0.08%) 31.97 kB → 32 kB
packages/loot-core/src/mocks/budget.ts 📈 +10 B (+0.03%) 29.38 kB → 29.39 kB
packages/loot-core/src/server/db/index.ts 📉 -193 B (-0.92%) 20.52 kB → 20.33 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
kcab.worker.js 1.33 MB → 1.33 MB (+24 B) +0.00%

Smaller

No assets were smaller

Unchanged

No assets were unchanged

Copy link
Contributor

github-actions bot commented Feb 5, 2025

👋 Hi! It looks like this PR has not had any changes for a week now. Would you like someone to review this PR? If so - please remove the "[WIP]" prefix from the PR title. That will let the community know that this PR is open for a review.

@github-actions github-actions bot added the Stale label Feb 5, 2025
Copy link
Contributor

This PR was closed because it has been stalled for 5 days with no activity.

@github-actions github-actions bot closed this Feb 11, 2025
@joel-jeremy joel-jeremy reopened this Feb 11, 2025
@joel-jeremy joel-jeremy removed the Stale label Feb 11, 2025
Base automatically changed from ts-runQuery-new to master February 18, 2025 20:14
@joel-jeremy joel-jeremy changed the title [WIP] [TypeScript] Make db.first generic to make it easy to type DB query results [TypeScript] Make db.first generic to make it easy to type DB query results Feb 18, 2025
Copy link
Contributor

coderabbitai bot commented Feb 18, 2025

Walkthrough

This pull request introduces extensive type safety improvements across the codebase by enhancing how database query functions are utilized. Numerous updates add explicit type annotations and generic parameters to methods such as db.first and db.runQuery across modules handling budgets, accounts, payees, transfers, schedules, and reports. The changes consistently specify expected return types (using constructs like Pick<...>) to ensure that the data retrieved from the database conforms precisely to the defined types in the new schema (e.g., db.DbAccount, db.DbPayee, etc.). These modifications address both regular application logic and tests, enhancing clarity without altering the core functionality or error handling routines.

Possibly related PRs

Suggested labels

:sparkles: Merged

Suggested reviewers

  • youngcw
  • matt-fidd

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cab24df and bd930e7.

⛔ Files ignored due to path filters (2)
  • upcoming-release-notes/4247.md is excluded by !**/*.md
  • upcoming-release-notes/4248.md is excluded by !**/*.md
📒 Files selected for processing (31)
  • packages/loot-core/src/mocks/budget.ts (1 hunks)
  • packages/loot-core/src/server/accounts/link.ts (1 hunks)
  • packages/loot-core/src/server/accounts/payees.ts (2 hunks)
  • packages/loot-core/src/server/accounts/sync.ts (3 hunks)
  • packages/loot-core/src/server/accounts/transaction-rules.test.ts (2 hunks)
  • packages/loot-core/src/server/accounts/transaction-rules.ts (4 hunks)
  • packages/loot-core/src/server/accounts/transfer.test.ts (2 hunks)
  • packages/loot-core/src/server/accounts/transfer.ts (2 hunks)
  • packages/loot-core/src/server/api.ts (1 hunks)
  • packages/loot-core/src/server/budget/actions.ts (2 hunks)
  • packages/loot-core/src/server/budget/base.ts (3 hunks)
  • packages/loot-core/src/server/budget/cleanup-template.ts (3 hunks)
  • packages/loot-core/src/server/budget/goalsSchedule.ts (1 hunks)
  • packages/loot-core/src/server/budget/statements.ts (2 hunks)
  • packages/loot-core/src/server/budget/template-notes.test.ts (2 hunks)
  • packages/loot-core/src/server/dashboard/app.ts (1 hunks)
  • packages/loot-core/src/server/db/index.ts (24 hunks)
  • packages/loot-core/src/server/db/mappings.ts (1 hunks)
  • packages/loot-core/src/server/db/types.d.ts (0 hunks)
  • packages/loot-core/src/server/db/types/index.ts (1 hunks)
  • packages/loot-core/src/server/filters/app.ts (1 hunks)
  • packages/loot-core/src/server/main.test.ts (1 hunks)
  • packages/loot-core/src/server/main.ts (17 hunks)
  • packages/loot-core/src/server/migrate/migrations.test.ts (1 hunks)
  • packages/loot-core/src/server/reports/app.ts (1 hunks)
  • packages/loot-core/src/server/schedules/app.ts (2 hunks)
  • packages/loot-core/src/server/schedules/find-schedules.ts (1 hunks)
  • packages/loot-core/src/server/sync/index.ts (1 hunks)
  • packages/loot-core/src/server/sync/migrate.test.ts (1 hunks)
  • packages/loot-core/src/server/tools/app.ts (1 hunks)
  • packages/loot-core/src/server/update.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/loot-core/src/server/db/types.d.ts
🧰 Additional context used
🧠 Learnings (2)
packages/loot-core/src/server/accounts/sync.ts (1)
Learnt from: matt-fidd
PR: actualbudget/actual#3581
File: packages/loot-core/src/server/accounts/sync.ts:28-46
Timestamp: 2024-11-10T16:45:31.225Z
Learning: Matt prefers to defer adding proper types for transactions interfaces until another PR.
packages/loot-core/src/server/accounts/transaction-rules.test.ts (1)
Learnt from: jfdoming
PR: actualbudget/actual#3641
File: packages/loot-core/src/server/accounts/rules.test.ts:524-536
Timestamp: 2024-11-10T16:45:25.627Z
Learning: In `packages/loot-core/src/server/accounts/rules.test.ts`, prefer explicit action definitions over refactoring similar actions into loops or helper functions, even when actions are similar.
🔇 Additional comments (66)
packages/loot-core/src/server/db/index.ts (19)

18-18: Revisit the usage of CategoryEntity and CategoryGroupEntity.
It's currently unclear if these entities fully align with the raw DB rows. Ensure these imports match the shape of the returned data or consider switching to DbCategory/DbCategoryGroup if that's more accurate.


36-44: Good introduction of strongly typed DB entities.
Importing specific database entity types helps maintain type safety across queries.


46-46: Verify whether re-exporting all types is intentional.
export * may expose internal DB types you don't intend to be public.


87-87: Typed usage of db.first is clear.
Declaring <DbClockMessage> ensures that returned clock data is strongly typed, which improves overall reliability.


110-122: Generic overloads for runQuery are well-designed.
These overloads will help ensure type-safe queries. Just be mindful that the returned shape of rows must match type parameter T.


160-168: Future generic support is a worthwhile improvement.
The all function returning any[] is consistent with your transitional plan; keep the TODO in mind for phase two.


170-173: Ensure proper validation of the data shape.
first<T> is a nice addition for type safety, but confirm queries returning fewer or different columns won't break the assumed shape.


311-318: Misalignment between declared return and actual data.
The TODO indicates it should return DbCategory[] instead of CategoryEntity[]. Confirm the correct type and update accordingly.


320-323: Similarly, clarify the return type for getCategoriesGrouped.
If your final intent is DbCategoryGroup & { categories: DbCategory[] }, consider updating the signature instead of using CategoryGroupEntity.


352-376: Liking the typed fetch with db.first<Pick<DbCategoryGroup, ...>>.
Both checks for existing group and last group sort order are well-handled.


465-469: Move logic appears valid.
The new typed params (DbCategory['id'], DbCategoryGroup['id']) are consistent with the data manipulation.


486-489: Validate the existence of the category ID.
If the record is missing or tombstoned, deleteCategory might fail silently. Ensure upstream code handles that possibility.


509-510: Typed approach to retrieving a single payee.
This matches the callsite expectation for a DbPayee.


513-514: Typed approach to retrieving a single account.
Consistent with your new generics approach in the db.first call.


527-531: Delete logic is suitably typed.
Allowing partial payee objects (just the id) is a good pattern.


557-560: Merging payees is now type-aware.
Excluding transfer payees is well-handled, and typed arrays (DbPayee[]) reduce runtime errors.

Also applies to: 562-562


695-702: moveAccount typed parameters look solid.
Re-sorting logic is consistent with shoveSortOrders, and the typed id fields prevent mixing entity IDs.


724-724: Correct typed retrieval of a single transaction.
Ensuring DbViewTransaction['id'] is used prevents referencing non-view transaction IDs.


733-733: getTransactions type usage is consistent.
Nice job restricting the parameter type to DbTransaction['acct'].

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

16-19: Explicitly typing the row structure is a great improvement.
Declaring <{ value: string }> clarifies the returned object's shape and avoids confusion around immediate destructuring to hash.

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

2-2: LGTM! Type safety improvements.

The changes enhance type safety by:

  1. Using DbSchedule from the database module instead of a separate types file
  2. Explicitly typing the return value of getActiveSchedules as Promise<DbSchedule[]>

Also applies to: 44-44

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

25-30: LGTM! Enhanced type safety with const assertions.

The addition of as const assertions to the mapped arrays:

  1. Makes the tuples immutable
  2. Preserves the literal types of the elements
  3. Prevents accidental modification of the array structure
packages/loot-core/src/server/tools/app.ts (1)

55-55:

❓ Verification inconclusive

Verify tombstone value type consistency across the codebase.

The change from numeric (1) to boolean (true) for the tombstone value might need to be verified for consistency with other database operations.


🏁 Script executed:

#!/bin/bash
# Search for other tombstone value assignments in the codebase
rg -A 2 "tombstone\s*=\s*[01]|tombstone:\s*[01]"

# Search for tombstone comparisons in SQL queries
rg "tombstone\s*=\s*[01]" --type sql

Length of output: 238


Action: Confirm Tombstone Value Consistency Across the Codebase

The update in packages/loot-core/src/server/tools/app.ts (line 55) now sets tombstone to true instead of the previous numeric value 1. Please ensure that:

  • All parts of the codebase—especially database operations and SQL queries—handle tombstone as a boolean rather than a number.
  • No remnants of numeric tombstone assignments or comparisons (e.g., tombstone = 1) remain that could lead to inconsistencies or unexpected behavior.

To further verify this, please run the following script (which disables default ignore filters) to search for any numeric tombstone usage:

Once you’ve confirmed the absence of numeric tombstone references, please ensure that related database operations are tested accordingly.


🏁 Script executed:

[run_scripts]
#!/bin/bash
# Search thoroughly for tombstone assignments to catch both numeric and boolean patterns.
rg --no-ignore -A 3 "tombstone\s*[:=]\s*[01]"
rg --no-ignore "tombstone\s*=\s*[01]" --type sql

Length of output: 369


Action: Verify Tombstone Type Consistency Manually

The change in packages/loot-core/src/server/tools/app.ts now sets tombstone to a boolean (true). Our automated searches for numeric tombstone assignments (e.g., assignments or comparisons using 1) did not return any results. However, because the ripgrep commands were filtered and no files were actually searched, we cannot conclusively rule out the existence of numeric tombstone usage elsewhere in the codebase.

Please verify manually that:

  • All database operations and SQL query conditions reference tombstone as a boolean.
  • No components (including schema definitions or migration scripts) still expect tombstone to be numeric (e.g., 1 instead of true).

Once you confirm that the codebase consistently uses a boolean tombstone value, this issue will be resolved.

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

88-91: LGTM! Type safety improvement.

The addition of Pick<db.DbCustomReport, 'id'> type parameter enhances type safety by explicitly defining the expected return type from the database query.

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

45-48: LGTM! Type safety improvement.

The addition of Pick<db.DbTransactionFilter, 'id'> type parameter enhances type safety by explicitly defining the expected return type from the database query.

packages/loot-core/src/server/sync/migrate.test.ts (1)

82-86: LGTM! Type safety improvement in test code.

The addition of db.DbTransaction type parameter enhances type safety by explicitly defining the expected return type from the database query.

packages/loot-core/src/server/accounts/transfer.test.ts (1)

64-69: LGTM! Enhanced type safety for database queries.

The addition of type parameters <db.DbPayee> to db.first calls improves type safety by explicitly defining the expected return type.

Also applies to: 134-139

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

5-7: LGTM! Excellent use of TypeScript's Pick utility type.

The changes enhance type safety by:

  1. Using Pick to select only the required fields from database types
  2. Explicitly specifying return types for all db.first calls

Also applies to: 12-16, 23-28, 54-57, 61-68

packages/loot-core/src/server/budget/template-notes.test.ts (1)

22-24: LGTM! Improved type consistency in mock functions.

The changes correctly update the type references from Schedule to db.DbSchedule, ensuring that mock data structure matches the database schema.

Also applies to: 247-268

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

1-5: LGTM! Well-documented type definitions.

The comments clearly explain the purpose of these types and their relationship with the database schema.


8-315: LGTM! Comprehensive and well-structured type definitions.

The type definitions are excellent:

  1. Proper use of union types for binary flags (1 | 0)
  2. Clear marking of unused types with comments
  3. Proper handling of nullable fields
  4. Good use of cross-references between types
packages/loot-core/src/server/dashboard/app.ts (1)

147-149: LGTM! Type safety enhancement for dashboard widget positioning.

The type parameter ensures that the query result contains the required position and dimension fields from the dashboard table.

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

24-28: LGTM! Type safety enhancement and query optimization for schedule retrieval.

The changes improve both type safety and performance:

  1. Type parameter ensures the query result contains the required schedule fields.
  2. Query is optimized to select only the needed fields (id and completed) instead of all columns.
packages/loot-core/src/server/main.test.ts (1)

70-72: LGTM! Type safety enhancement for clock message retrieval in tests.

The type parameter ensures type safety for the clock message query result, improving test reliability.

packages/loot-core/src/server/budget/cleanup-template.ts (3)

67-67: Type enhancement improves clarity and safety!

The generic type parameter Pick<db.DbZeroBudget, 'carryover'> clearly indicates that only the 'carryover' property is needed from the query result, which matches its usage in the code.


223-223: Consistent type enhancement maintains codebase uniformity!

The generic type parameter matches the earlier usage, maintaining consistency in type safety across similar database queries.


252-252: Type safety consistently applied across similar queries!

The generic type parameter maintains consistency with previous instances, ensuring uniform type safety across database queries.

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

332-332: Type enhancement ensures precise property access!

The generic type parameter Pick<db.DbViewCategory, 'is_income'> clearly specifies that only the 'is_income' property is needed, which matches its usage in the conditional logic.


364-364: Type safety enhancement matches usage pattern!

The generic type parameter Pick<db.DbZeroBudgetMonth, 'buffered'> accurately reflects that only the 'buffered' property is needed for the calculation.

packages/loot-core/src/server/budget/base.ts (3)

44-44: Type enhancement ensures numeric amount property!

The generic type parameter { amount: number } ensures type safety for the amount calculation, making it clear that a numeric value is expected.


89-89: Type enhancement matches property usage!

The generic type parameter Pick<db.DbTransaction, 'category'> accurately reflects that only the 'category' property is needed for the recomputation.


445-445: Complete transaction type ensures full object access!

The generic type parameter db.DbTransaction appropriately indicates that the full transaction object is needed for date extraction.

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

143-145: Type enhancement precisely specifies required properties!

The generic type parameter Pick<db.DbScheduleNextDate, 'id' | 'base_next_date_ts'> accurately reflects the exact properties needed for the update operations.


171-171: Type enhancement matches minimal property requirement!

The generic type parameter Pick<db.DbSchedule, 'id'> correctly specifies that only the 'id' property is needed for the existence check.

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

97-100: LGTM! Type safety improvement.

The addition of Pick<db.DbCategory, 'is_income'> type parameter enhances type safety by explicitly specifying that only the 'is_income' field is needed from the category record.

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

201-207: LGTM! Type safety improvement.

The addition of Pick<db.DbCrdtMessage, 'timestamp'> type parameter enhances type safety by explicitly specifying that only the 'timestamp' field is needed from the CRDT message record.

packages/loot-core/src/server/accounts/sync.ts (3)

530-532: LGTM! Type safety improvement.

The change from AccountEntity[] to db.DbAccount[] aligns with the new database schema, enhancing type safety.


549-552: LGTM! Type safety improvement.

The addition of <db.DbViewTransaction> type parameter enhances type safety by explicitly specifying the expected transaction record type.


683-684: LGTM! Type safety improvement.

The change from AccountEntity[] to db.DbAccount[] aligns with the new database schema, enhancing type safety.

packages/loot-core/src/server/accounts/transaction-rules.ts (4)

221-224: LGTM! Type safety improvement.

The addition of Pick<db.DbSchedule, 'id'> type parameter enhances type safety by explicitly specifying that only the 'id' field is needed from the schedule record.


280-280: LGTM! Type safety improvement.

The change from Map<string, AccountEntity> to Map<string, db.DbAccount> aligns with the new database schema, enhancing type safety.


630-632: LGTM! Type safety improvement.

The change from AccountEntity[] to db.DbAccount[] aligns with the new database schema, enhancing type safety.


867-867: LGTM! Type safety improvement.

The change from AccountEntity to db.DbAccount aligns with the new database schema, enhancing type safety.

packages/loot-core/src/server/accounts/transaction-rules.test.ts (2)

946-953: LGTM! Type-safe parsing of rule data.

The changes improve type safety by explicitly specifying the return type of the database query and creating a new object with parsed conditions and actions.


979-986: LGTM! Consistent type safety for rule validation.

The changes maintain consistency in type safety by using the same approach for parsing and validating rules with public field names.

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

329-333: LGTM! Type-safe category retrieval.

Good use of Pick to specify that only the is_income field is needed from the category.


340-343: LGTM! Consistent type safety for transfer category.

Maintains consistency with the previous type safety pattern.


422-428: LGTM! Type-safe query result.

Explicitly specifies the count field type for the query result.


576-579: LGTM! Type-safe balance queries.

Good use of type parameters to ensure type safety for balance and count queries.

Also applies to: 584-591


606-609: LGTM! Type-safe account retrieval.

Consistent use of db.DbAccount type for full account information.

Also applies to: 668-671


1104-1117: LGTM! Type-safe account sync query.

Good use of intersection type to combine account data with bank ID.


1165-1178: LGTM! Consistent type safety for batch sync.

Maintains consistency with the account sync query types.


1286-1289: LGTM! Type-safe account unlinking.

Good use of Pick to specify only the needed fields from the account.

Also applies to: 1295-1298


1316-1319: LGTM! Type-safe count and bank queries.

Consistent use of Pick for selecting specific fields.

Also applies to: 1329-1331


2353-2356: LGTM! Type-safe preference retrieval.

Good use of Pick to specify that only the value field is needed from the preference.

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

464-475: LGTM! Type safety improvement for database queries.

The addition of the <db.DbViewTransaction> generic type parameter improves type safety by ensuring the query results match the expected transaction structure.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
packages/loot-core/src/mocks/budget.ts (1)

413-414: ⚠️ Potential issue

Remove incorrect starting_balance_flag.

The starting_balance_flag should only be set for the initial balance transaction, not for regular transactions.

-      starting_balance_flag: true,
🧹 Nitpick comments (10)
packages/loot-core/src/server/db/index.ts (2)

179-183: Consider extending generic support to firstSync.
For consistency, adding a <T> parameter (similar to the async version) would eliminate many manual casts.


198-202: Adding a generic signature would improve maintainability.
Currently returning as any might lead to subtle errors if usage is unclear.

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

7-10: Include 'name' in the returned type or remove it from the query.
You currently fetch id, bank_id, name but your pick only declares 'id' | 'bank_id'. If you plan to use or store name, add it to the pick.

packages/loot-core/src/server/accounts/payees.ts (2)

4-17: Add explicit return type to createPayee function.

The function's return type should be explicitly defined for better type safety.

-export async function createPayee(description) {
+export async function createPayee(description): Promise<number> {

The type parameter Pick<db.DbPayee, 'id'> correctly specifies that only the 'id' field is needed from the query result.


19-37: Add explicit return type to getStartingBalancePayee function.

The function's return type should be explicitly defined for better type safety.

-export async function getStartingBalancePayee() {
+export async function getStartingBalancePayee(): Promise<{
+  id: number;
+  category: number | null;
+}> {

The type parameter db.DbCategory correctly specifies the expected shape of the query results.

packages/loot-core/src/server/migrate/migrations.test.ts (1)

65-67: LGTM! Consider extracting the type for reuse.

The type parameter { sql: string } correctly specifies the shape of the query result. Consider extracting this type to a constant for reuse across both queries.

type SqliteTableInfo = { sql: string };

// Then use it in both queries:
let desc = await db.first<SqliteTableInfo>(...);

Also applies to: 72-74

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

229-229: Fix typo in field name.

The field name show_uncateogorized contains a typo. It should be show_uncategorized.

-  show_uncateogorized: 1 | 0;
+  show_uncategorized: 1 | 0;
packages/loot-core/src/server/schedules/find-schedules.ts (1)

340-343: LGTM! Type safety enhancement for transaction retrieval, with a suggestion.

The type parameter ensures type safety for the transaction view query result.

Consider optimizing the query by selecting only the required fields instead of all columns (SELECT *). This would improve performance and reduce memory usage.

-      'SELECT * FROM v_transactions WHERE account = ? AND parent_id IS NULL ORDER BY date DESC LIMIT 1',
+      'SELECT date FROM v_transactions WHERE account = ? AND parent_id IS NULL ORDER BY date DESC LIMIT 1',
packages/loot-core/src/mocks/budget.ts (2)

1-1: Consider enabling TypeScript strict mode.

The file currently disables strict mode with // @ts-strict-ignore. Consider enabling it to leverage TypeScript's type safety features fully.

-// @ts-strict-ignore
+// TODO: Fix type errors and remove ts-strict-ignore

85-255: Consider refactoring test data generation.

The account filling functions share similar patterns and could benefit from:

  1. Extracting common logic into reusable helper functions
  2. Converting magic numbers into named constants for better maintainability

Example refactor for magic numbers:

const CONSTANTS = {
  INCOME_PROBABILITY: {
    PRIMARY_CHECKING: 0.09,
    CHECKING: 0.04,
    SAVINGS: 0.3
  },
  AMOUNT_RANGES: {
    INCOME: {
      MIN: 50000,
      MAX: 70000
    },
    EXPENSE: {
      MIN: 0,
      MAX: -700
    }
  }
};

Also applies to: 257-303, 305-339, 341-384, 386-421, 423-459

🛑 Comments failed to post (1)
packages/loot-core/src/mocks/budget.ts (1)

462-462: ⚠️ Potential issue

Fix comparison operators in conditions.

Using assignment operators (=) instead of comparison operators (===) in conditions can lead to unexpected behavior.

-  const primaryAccount = accounts.find(a => (a.name = 'Bank of America'));
+  const primaryAccount = accounts.find(a => a.name === 'Bank of America');

Also applies to: 757-757

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