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] Add types to amount utils #4207

Merged
merged 2 commits into from
Jan 21, 2025
Merged

Conversation

joel-jeremy
Copy link
Contributor

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

Add type to the the amount utils to clarify what's the difference between amount, integer amount, and currency.

The components that accept amounts need to be updated to use these types to make it clear which types of amounts they need, but that's for another PR.

@actual-github-bot actual-github-bot bot changed the title [TypeScript] Add types to amount utils [WIP] [TypeScript] Add types to amount utils Jan 20, 2025
Copy link

netlify bot commented Jan 20, 2025

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit 501e3db
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/678e92166d39cd0008f508cc
😎 Deploy Preview https://deploy-preview-4207.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] [TypeScript] Add types to amount utils [TypeScript] Add types to amount utils Jan 20, 2025
Copy link
Contributor

Bundle Stats — desktop-client

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

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

Total

Files count Total bundle size % Changed
15 6.69 MB → 6.69 MB (+1.83 kB) +0.03%
Changeset
File Δ Size
home/runner/work/actual/actual/packages/loot-core/src/shared/util.ts 📈 +151 B (+2.23%) 6.61 kB → 6.75 kB
locale/nl.json 📈 +1.35 kB (+2.19%) 61.53 kB → 62.88 kB
src/components/reports/graphs/AreaGraph.tsx 📈 +40 B (+0.45%) 8.77 kB → 8.81 kB
locale/pt-BR.json 📈 +325 B (+0.29%) 107.81 kB → 108.13 kB
src/components/reports/reports/SpendingCard.tsx 📈 +5 B (+0.12%) 3.98 kB → 3.98 kB
src/components/modals/ImportTransactionsModal/Transaction.tsx 📉 -24 B (-0.28%) 8.26 kB → 8.24 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/nl.js 61.53 kB → 62.88 kB (+1.35 kB) +2.19%
static/js/pt-BR.js 107.81 kB → 108.13 kB (+325 B) +0.29%
static/js/index.js 4.28 MB → 4.28 MB (+127 B) +0.00%
static/js/ReportRouter.js 1.59 MB → 1.59 MB (+45 B) +0.00%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/useAccountPreviewTransactions.js 1.63 kB 0%
static/js/AppliedFilters.js 10.52 kB 0%
static/js/en.js 98.94 kB 0%
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/wide.js 101.22 kB 0%
static/js/en-GB.js 97.97 kB 0%
static/js/workbox-window.prod.es5.js 5.69 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/narrow.js 84.83 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/uk.js 118.39 kB 0%

Copy link
Contributor

Bundle Stats — loot-core

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

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

Total

Files count Total bundle size % Changed
1 1.33 MB 0%
Changeset
File Δ Size
packages/loot-core/src/shared/util.ts 📈 +131 B (+1.19%) 10.73 kB → 10.86 kB
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
kcab.worker.js 1.33 MB 0%

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Walkthrough

This pull request encompasses changes across multiple components and utility files in the desktop client, focusing primarily on type safety and consistent handling of monetary values. The modifications span the Transaction component, graph-related components (AreaGraph and BarGraph), SpendingCard, and the core utility functions in util.ts. The changes involve refining type definitions for monetary values, ensuring that numeric properties are strictly typed as numbers, and implementing fallback mechanisms for handling potentially undefined or null amounts. These updates aim to improve type consistency and prevent potential rendering or calculation errors by providing default values and more precise type constraints.

Possibly related PRs

Suggested Labels

sparkles:, typescript, type-safety, bugfix

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

Test coverage needed for critical currency conversion functions

The verification reveals that these currency conversion functions are extensively used across the codebase for critical financial operations, but lack dedicated test coverage. This poses a significant risk as these functions handle core financial calculations and data transformations.

Key areas requiring test coverage:

  • Core conversion functions in shared/util.ts
  • Edge cases for parsing user input
  • Number format handling across different locales
  • Boundary conditions for safe number handling
🔗 Analysis chain

Line range hint 332-433: Verify test coverage for currency conversion edge cases.

The type changes and currency conversion functions are critical parts of the system. Please ensure:

  1. Comprehensive test coverage for edge cases (empty strings, invalid formats, etc.)
  2. Documentation of expected formats and error conditions
  3. Migration guide for consumers of these functions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing tests
rg -t ts -t js "describe.*currency|test.*currency|it.*currency" -g "!node_modules"

# Search for usages that might be affected by the type changes
rg "currencyTo(Amount|Integer)|amountToCurrency|integerToCurrency" -g "!node_modules"

Length of output: 25126

🧰 Tools
🪛 Biome (1.9.4)

[error] 410-410: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 422-422: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🧹 Nitpick comments (1)
packages/loot-core/src/shared/util.ts (1)

332-345: Consider using branded types for stronger type safety.

While the type definitions are well-documented, they could be more restrictive to prevent mixing different types of amounts. Consider using branded types to make them nominally unique:

export type Amount = number & { readonly __brand: unique symbol };
export type IntegerAmount = number & { readonly __brand: unique symbol };
export type CurrencyAmount = string & { readonly __brand: unique symbol };

// Helper functions to create branded types
export const Amount = (n: number) => n as Amount;
export const IntegerAmount = (n: number) => n as IntegerAmount;
export const CurrencyAmount = (s: string) => s as CurrencyAmount;

This would prevent accidentally passing an Amount where an IntegerAmount is expected, and vice versa.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dd2b0a8 and 501e3db.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/4207.md is excluded by !**/*.md
📒 Files selected for processing (5)
  • packages/desktop-client/src/components/modals/ImportTransactionsModal/Transaction.tsx (3 hunks)
  • packages/desktop-client/src/components/reports/graphs/AreaGraph.tsx (2 hunks)
  • packages/desktop-client/src/components/reports/graphs/BarGraph.tsx (1 hunks)
  • packages/desktop-client/src/components/reports/reports/SpendingCard.tsx (1 hunks)
  • packages/loot-core/src/shared/util.ts (2 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/desktop-client/src/components/modals/ImportTransactionsModal/Transaction.tsx (2)
Learnt from: MatissJanis
PR: actualbudget/actual#3570
File: packages/desktop-client/src/components/modals/ImportTransactionsModal/Transaction.tsx:83-90
Timestamp: 2024-11-10T16:45:25.627Z
Learning: In the `Transaction` component in `Transaction.tsx`, both `rawTransaction` and `transaction` should be included in the dependency arrays of `useMemo` hooks, even though `transaction` derives from `rawTransaction`.
Learnt from: MatissJanis
PR: actualbudget/actual#3570
File: packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.ts:120-130
Timestamp: 2024-11-10T16:45:25.627Z
Learning: Avoid overcomplicating the `ImportTransaction` type; prefer to keep it simple.
🪛 Biome (1.9.4)
packages/loot-core/src/shared/util.ts

[error] 410-410: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 422-422: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

⏰ 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 (6)
packages/desktop-client/src/components/reports/reports/SpendingCard.tsx (1)

139-139: LGTM! Good defensive programming.

The addition of the || 0 fallback ensures type safety and prevents potential rendering issues when difference is undefined.

packages/desktop-client/src/components/reports/graphs/BarGraph.tsx (1)

53-59: Verify impact of stricter type constraints.

The type changes from number | string to number improve type safety but could break existing code that passes string values.

Let's verify all usages to ensure they comply with the new type constraints:

✅ Verification successful

Type constraints in BarGraph.tsx are correctly enforced

The change from number | string to number aligns with the actual usage patterns in the codebase:

  • All arithmetic operations treat these properties as numbers
  • String conversions happen at the presentation layer using integerToAmount or integerToCurrency
  • No direct string assignments found that would break with the new type constraints
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any string assignments to these properties
ast-grep --pattern 'payload: {
  $$$
  totalAssets: $_str,
  $$$
}' -l ts,tsx

# Also check for direct property assignments
rg -A 2 'payload\.(totalAssets|totalDebts|netAssets|netDebts|totalTotals|networth|totalChange)\s*=' --type ts --type tsx

Length of output: 343


Script:

#!/bin/bash
# Search for object literal assignments
ast-grep --pattern 'payload: {
  $$$
  totalAssets: $_str,
  $$$
}'

# Search for property assignments and usages
rg '(payload\.)?(totalAssets|totalDebts|netAssets|netDebts|totalTotals|networth|totalChange)\s*(=|:)' -t typescript -t tsx

# Search for variable declarations of these properties
ast-grep --pattern 'const { totalAssets, totalDebts, netAssets, netDebts, totalTotals, networth, totalChange } = $_'

Length of output: 348


Script:

#!/bin/bash
# Search for property assignments and usages with correct file type
rg '(payload\.)?(totalAssets|totalDebts|netAssets|netDebts|totalTotals|networth|totalChange)\s*(=|:)' -t ts -B 2 -A 2

# Search for interface definitions and type assignments
rg 'interface.*PayloadItem|type.*PayloadItem' -t ts -B 2 -A 10

# Look for any arithmetic operations with these properties
rg '(totalAssets|totalDebts|netAssets|netDebts|totalTotals|networth|totalChange)\s*[+\-*/]' -t ts

Length of output: 29331

packages/desktop-client/src/components/reports/graphs/AreaGraph.tsx (2)

144-146: Improved type checking in customLabel function.

The changes better handle edge cases by:

  1. Explicitly checking for string type
  2. Adding fallback for undefined values
  3. Maintaining consistent number type handling

36-40: Verify impact of stricter type constraints.

Similar to BarGraph.tsx, the type changes from number | string to number improve type safety but could break existing code.

Let's verify all usages:

✅ Verification successful

Type constraints are safe to apply

The stricter type constraints from number | string to number align with the actual usage in the codebase. All property assignments already use numeric values through integerToAmount conversions, and all consumers expect numbers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any string assignments to these properties in AreaGraph
ast-grep --pattern 'payload: {
  $$$
  totalAssets: $_str,
  $$$
}' -l ts,tsx

# Check for direct property assignments
rg -A 2 'payload\.(totalAssets|totalDebts|netAssets|netDebts|totalTotals)\s*=' --type ts --type tsx

Length of output: 322


Script:

#!/bin/bash
# Search for object literals with these properties
ast-grep --pattern 'payload: {
  $$$
  totalAssets: $_,
  $$$
}' --lang typescript

# Search for property assignments and access
rg -t typescript 'payload\.(totalAssets|totalDebts|netAssets|netDebts|totalTotals)' -A 2

# Search for object spread patterns
rg -t typescript '\{\s*totalAssets:|netAssets:|totalDebts:|netDebts:|totalTotals:' -A 2

Length of output: 335


Script:

#!/bin/bash
# Search for any usage of these properties in ts/tsx files
rg "totalAssets|totalDebts|netAssets|netDebts|totalTotals" -g "*.{ts,tsx}" -B 2 -A 2

# Search for object property assignments
ast-grep --pattern '{
  $$$
  totalAssets: $_
}' --lang ts

# Search specifically in AreaGraph.tsx
fd -e tsx -e ts "AreaGraph" --exec cat {}

Length of output: 51961

packages/desktop-client/src/components/modals/ImportTransactionsModal/Transaction.tsx (1)

221-226: Improved null handling and error messages.

The changes enhance type safety and user experience by:

  1. Adding consistent || 0 fallbacks for null values
  2. Making error messages specific to each field
  3. Maintaining type safety with amountToCurrency

Also applies to: 238-243, 274-274

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

371-372: Consider handling edge cases in toRelaxedNumber.

The function assumes currencyToInteger returns a valid number when coerced with || 0. This might hide potential errors.

Comment on lines +420 to 426
export function stringToInteger(str: string): number | null {
const amount = parseInt(str.replace(/[^-0-9.,]/g, ''));
if (!isNaN(amount)) {
return amount;
}
return null;
}
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

Replace global isNaN with Number.isNaN.

The global isNaN function attempts type coercion which can lead to unexpected results. Use Number.isNaN instead for safer number validation.

 export function stringToInteger(str: string): number | null {
   const amount = parseInt(str.replace(/[^-0-9.,]/g, ''));
-  if (!isNaN(amount)) {
+  if (!Number.isNaN(amount)) {
     return amount;
   }
   return null;
 }
📝 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
export function stringToInteger(str: string): number | null {
const amount = parseInt(str.replace(/[^-0-9.,]/g, ''));
if (!isNaN(amount)) {
return amount;
}
return null;
}
export function stringToInteger(str: string): number | null {
const amount = parseInt(str.replace(/[^-0-9.,]/g, ''));
if (!Number.isNaN(amount)) {
return amount;
}
return null;
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 422-422: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

Comment on lines +393 to 410
export function currencyToAmount(
currencyAmount: CurrencyAmount,
): Amount | null {
let amount;
if (getNumberFormat().separatorRegex) {
amount = parseFloat(
str
currencyAmount
.replace(getNumberFormat().regex, '')
.replace(getNumberFormat().separatorRegex, '.'),
);
} else {
amount = parseFloat(
str
currencyAmount
.replace(getNumberFormat().regex, '')
.replace(getNumberFormat().separator, '.'),
);
}
return isNaN(amount) ? null : amount;
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

Improve error handling in currencyToAmount.

The function could benefit from more robust error handling:

  1. Consider throwing an error for invalid formats instead of returning null
  2. Add input validation for empty strings
  3. Document the expected format in JSDoc
 export function currencyToAmount(
   currencyAmount: CurrencyAmount,
 ): Amount | null {
+  if (!currencyAmount?.trim()) {
+    return null;
+  }
   let amount;
   if (getNumberFormat().separatorRegex) {
     amount = parseFloat(
📝 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
export function currencyToAmount(
currencyAmount: CurrencyAmount,
): Amount | null {
let amount;
if (getNumberFormat().separatorRegex) {
amount = parseFloat(
str
currencyAmount
.replace(getNumberFormat().regex, '')
.replace(getNumberFormat().separatorRegex, '.'),
);
} else {
amount = parseFloat(
str
currencyAmount
.replace(getNumberFormat().regex, '')
.replace(getNumberFormat().separator, '.'),
);
}
return isNaN(amount) ? null : amount;
export function currencyToAmount(
currencyAmount: CurrencyAmount,
): Amount | null {
if (!currencyAmount?.trim()) {
return null;
}
let amount;
if (getNumberFormat().separatorRegex) {
amount = parseFloat(
currencyAmount
.replace(getNumberFormat().regex, '')
.replace(getNumberFormat().separatorRegex, '.'),
);
} else {
amount = parseFloat(
currencyAmount
.replace(getNumberFormat().regex, '')
.replace(getNumberFormat().separator, '.'),
);
}
return isNaN(amount) ? null : amount;
🧰 Tools
🪛 Biome (1.9.4)

[error] 410-410: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

Copy link
Contributor

@jfdoming jfdoming left a comment

Choose a reason for hiding this comment

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

This is great!

/**
* The exact amount.
*/
export type Amount = number;
Copy link
Contributor

Choose a reason for hiding this comment

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

Curious about your thoughts on making these branded types so they are not interchangeable? Otherwise correct me if I'm wrong but I think TypeScript would allow substituting IntegerAmount for Amount

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I tried implementing it briefly and it results in a lot of typecheck errors:
image

I think it's a good idea and we should implement it, but we do it in a separate PR. WDYT?

Copy link
Contributor

Choose a reason for hiding this comment

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

Yeah sounds good

@joel-jeremy joel-jeremy merged commit 4850034 into master Jan 21, 2025
20 checks passed
@joel-jeremy joel-jeremy deleted the add-types-to-amount-utils branch January 21, 2025 18:03
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