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

Fix: Added import id for YNAB #626

Merged
merged 5 commits into from
Dec 5, 2024

Conversation

abirstolov
Copy link

@abirstolov abirstolov commented Nov 23, 2024

In order to avoid duplicate inserted when a payee is changed, an import_id is added to the YNAB transaction

Fix #625

Summary by CodeRabbit

  • New Features

    • Enhanced transaction handling with the introduction of a new property for import IDs.
    • Added a new function to generate import IDs based on transaction details.
    • Introduced a function to compare transactions based on their import IDs.
  • Bug Fixes

    • Improved error handling in transaction creation to notify users when no transactions exist.
  • Tests

    • Added a new test case for the isSameTransaction function to verify behavior with different payees.

Abir Stolov added 2 commits November 23, 2024 22:41
In order to avoid duplicate inserted when a payee is changed, an import_id is added
Copy link
Collaborator

@baruchiro baruchiro left a comment

Choose a reason for hiding this comment

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

@brafdlog Please comment, I'm not familiar with YNAB

Comment on lines +129 to +135
function buildImportId(transaction: EnrichedTransaction): string {
return `${transaction.date.substring(0, 10)}${transaction.chargedAmount}${transaction.description}`.substring(
0,
MAX_YNAB_IMPORT_ID_LENGTH,
);
}

Copy link
Collaborator

Choose a reason for hiding this comment

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

Why are you not using the calculateTransactionHash function on packages/main/src/backend/transactions/transactions.ts?

Copy link
Author

Choose a reason for hiding this comment

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

because YNAB import_id is 36 characters max and should be unique
calculateTransactionHash is variable length and truncated will miss some information

Copy link

coderabbitai bot commented Nov 26, 2024

Walkthrough

The changes in this pull request enhance the functionality of the YNAB integration by adding new transaction handling features and improving error management. A new test suite for the isSameTransaction function has been introduced, verifying its behavior when comparing transactions with different payee names but identical import IDs. Additionally, the ynab.ts file has been modified to include new methods for building import IDs and checking their equality, alongside improved error handling in transaction creation.

Changes

File Change Summary
packages/main/src/backend/export/outputVendors/ynab/ynab.test.ts Added a new test suite for isSameTransaction, focusing on transactions with different payees but the same import ID.
packages/main/src/backend/export/outputVendors/ynab/ynab.ts Introduced MAX_YNAB_IMPORT_ID_LENGTH, updated createTransactions to include import_id, added buildImportId and isSameImportId functions, and enhanced error handling.

Assessment against linked issues

Objective Addressed Explanation
Ensure no new transaction is added when the payee changes (#625)

🐰 In the garden where transactions play,
A new test blooms to keep bugs at bay.
With import IDs shining bright,
We’ll ensure YNAB stays just right!
Hopping through code, we dance and cheer,
For every change brings us near! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 008131c and df479a8.

📒 Files selected for processing (1)
  • packages/main/src/backend/export/outputVendors/ynab/ynab.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/main/src/backend/export/outputVendors/ynab/ynab.test.ts

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

@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: 5

🧹 Outside diff range and nitpick comments (2)
packages/main/src/backend/export/outputVendors/ynab/ynab.test.ts (1)

11-31: Rename misleading variable transferTransactionFromYnab.

The variable name suggests it's a transfer transaction, but the object represents a regular transaction from YNAB. This could be confusing, especially when compared to the actual transfer transaction test case below.

Consider renaming to something more accurate:

-      const transferTransactionFromYnab: TransactionDetail = {
+      const existingYnabTransaction: TransactionDetail = {
packages/main/src/backend/export/outputVendors/ynab/ynab.ts (1)

208-209: Simplify and clarify the complex return condition for better readability.

The current return statement in isSameTransaction is complex and could be refactored to enhance clarity and maintainability.

Break down the conditions into meaningful variables:

 export function isSameTransaction(
   transactionToCreate: ynab.SaveTransaction,
   transactionFromYnab: ynab.TransactionDetail,
 ) {
   const isATransferTransaction = !!transactionFromYnab.transfer_account_id;
   const isTransactionsImportIdEqual = isSameImportId(transactionToCreate, transactionFromYnab);
+  const isSamePayeeName = areStringsEqualIgnoreCaseAndWhitespace(
+    transactionToCreate.payee_name,
+    transactionFromYnab.payee_name,
+  );
+  const isSameAccountId = transactionToCreate.account_id === transactionFromYnab.account_id;
+  const isSameDate = transactionToCreate.date === transactionFromYnab.date;
+  const amountDifferenceIsSmall =
+    transactionToCreate.amount != null &&
+    transactionFromYnab.amount != null &&
+    Math.abs(transactionToCreate.amount - transactionFromYnab.amount) < 1000;

-  return (
-    transactionToCreate.account_id === transactionFromYnab.account_id &&
-    transactionToCreate.date === transactionFromYnab.date &&
-    // @ts-expect-error error TS18049: 'transactionToCreate.amount' is possibly 'null' or 'undefined'
-    Math.abs(transactionToCreate.amount - transactionFromYnab.amount) < 1000 &&
-    (areStringsEqualIgnoreCaseAndWhitespace(transactionToCreate.payee_name, transactionFromYnab.payee_name) ||
-      isATransferTransaction ||
-      isTransactionsImportIdEqual)
-  );
+  return (
+    isSameAccountId &&
+    isSameDate &&
+    amountDifferenceIsSmall &&
+    (isSamePayeeName || isATransferTransaction || isTransactionsImportIdEqual)
+  );
 }

This refactoring enhances readability and makes future maintenance easier.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6ca612f and bdc593f.

📒 Files selected for processing (2)
  • packages/main/src/backend/export/outputVendors/ynab/ynab.test.ts (1 hunks)
  • packages/main/src/backend/export/outputVendors/ynab/ynab.ts (4 hunks)
🔇 Additional comments (1)
packages/main/src/backend/export/outputVendors/ynab/ynab.test.ts (1)

9-44: LGTM! Test suite effectively validates the import_id matching.

The new test suite directly addresses the PR objective of preventing duplicate transactions when payees are modified in YNAB. The test case effectively validates that transactions with different payee names are considered identical when they share the same import_id.

A few observations worth noting:

  1. The test data setup is comprehensive, including all necessary fields for both YNAB and financial account transactions
  2. The test follows the existing patterns in the codebase
  3. The assertion is clear and focused on the specific behavior being tested

Comment on lines +335 to +340
function isSameImportId(
transactionToCreate: ynab.SaveTransaction,
transactionFromYnab: ynab.TransactionDetail,
): boolean {
return !!transactionToCreate.import_id && transactionToCreate.import_id === transactionFromYnab.import_id;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure safe comparison of import_id by validating both values.

In isSameImportId, comparing import_ids without checking if they are null or undefined might lead to unexpected behavior.

Update the function to handle potential null or undefined values:

 function isSameImportId(
   transactionToCreate: ynab.SaveTransaction,
   transactionFromYnab: ynab.TransactionDetail,
 ): boolean {
-  return !!transactionToCreate.import_id && transactionToCreate.import_id === transactionFromYnab.import_id;
+  return (
+    transactionToCreate.import_id != null &&
+    transactionFromYnab.import_id != null &&
+    transactionToCreate.import_id === transactionFromYnab.import_id
+  );
 }

This change ensures that the comparison only occurs when both import_ids are valid strings.

📝 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
function isSameImportId(
transactionToCreate: ynab.SaveTransaction,
transactionFromYnab: ynab.TransactionDetail,
): boolean {
return !!transactionToCreate.import_id && transactionToCreate.import_id === transactionFromYnab.import_id;
}
function isSameImportId(
transactionToCreate: ynab.SaveTransaction,
transactionFromYnab: ynab.TransactionDetail,
): boolean {
return (
transactionToCreate.import_id != null &&
transactionFromYnab.import_id != null &&
transactionToCreate.import_id === transactionFromYnab.import_id
);
}

@@ -119,12 +119,20 @@ function convertTransactionToYnabFormat(originalTransaction: EnrichedTransaction
category_id: getYnabCategoryIdFromCategoryName(originalTransaction.category),
memo: originalTransaction.memo,
cleared: ynab.SaveTransaction.ClearedEnum.Cleared,
import_id: buildImportId(originalTransaction), // [date][amount][description]
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure import_id follows YNAB's recommended format for uniqueness.

The current import_id generation may lead to collisions due to truncation and similarity in transaction data. YNAB recommends using the format YNAB:[milliunit_amount]:[iso_date]:[occurrence] to ensure uniqueness.

Consider updating the buildImportId function to match this format. Here's how you might adjust it:

 import_id: buildImportId(originalTransaction),

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +129 to +134
function buildImportId(transaction: EnrichedTransaction): string {
return `${transaction.date.substring(0, 10)}${transaction.chargedAmount}${transaction.description}`.substring(
0,
MAX_YNAB_IMPORT_ID_LENGTH,
);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve uniqueness of import_id by adopting YNAB's standard format.

Concatenating date, amount, and description can cause collisions when different transactions produce the same truncated string. To enhance uniqueness within the character limit, it's advisable to follow YNAB's suggested pattern.

Here's a revised implementation:

+import crypto from 'crypto';

 function buildImportId(transaction: EnrichedTransaction): string {
-  return `${transaction.date.substring(0, 10)}${transaction.chargedAmount}${transaction.description}`.substring(
-    0,
-    MAX_YNAB_IMPORT_ID_LENGTH,
-  );
+  const amount = Math.round(transaction.chargedAmount * 1000);
+  const date = transaction.date.substring(0, 10);
+  const occurrence = '1'; // Or calculate occurrence if necessary
+  return `YNAB:${amount}:${date}:${occurrence}`.substring(0, MAX_YNAB_IMPORT_ID_LENGTH);
 }

If you need to handle multiple occurrences, you can increment the occurrence value accordingly.

📝 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
function buildImportId(transaction: EnrichedTransaction): string {
return `${transaction.date.substring(0, 10)}${transaction.chargedAmount}${transaction.description}`.substring(
0,
MAX_YNAB_IMPORT_ID_LENGTH,
);
}
function buildImportId(transaction: EnrichedTransaction): string {
const amount = Math.round(transaction.chargedAmount * 1000);
const date = transaction.date.substring(0, 10);
const occurrence = '1'; // Or calculate occurrence if necessary
return `YNAB:${amount}:${date}:${occurrence}`.substring(0, MAX_YNAB_IMPORT_ID_LENGTH);
}

Comment on lines 205 to 207
Math.abs(transactionToCreate.amount - transactionFromYnab.amount) < 1000 &&
// In a transfer transaction the payee name changes, but we still consider this the same transaction
(areStringsEqualIgnoreCaseAndWhitespace(transactionToCreate.payee_name, transactionFromYnab.payee_name) ||
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential null or undefined amounts instead of suppressing TypeScript errors.

Using @ts-expect-error suppresses TypeScript's helpful checks and may hide runtime issues if transactionToCreate.amount is null or undefined.

Consider modifying the code to handle these cases explicitly:

-// @ts-expect-error error TS18049: 'transactionToCreate.amount' is possibly 'null' or 'undefined'
-Math.abs(transactionToCreate.amount - transactionFromYnab.amount) < 1000 &&
+const amountDifferenceIsSmall =
+  transactionToCreate.amount != null &&
+  transactionFromYnab.amount != null &&
+  Math.abs(transactionToCreate.amount - transactionFromYnab.amount) < 1000;
+
+return (
+  transactionToCreate.account_id === transactionFromYnab.account_id &&
+  transactionToCreate.date === transactionFromYnab.date &&
+  amountDifferenceIsSmall &&
+  (areStringsEqualIgnoreCaseAndWhitespace(transactionToCreate.payee_name, transactionFromYnab.payee_name) ||
+    isATransferTransaction ||
+    isTransactionsImportIdEqual)
+);

This approach ensures that you handle null or undefined values safely without suppressing errors.

Committable suggestion skipped: line range outside the PR's diff.

@baruchiro
Copy link
Collaborator

@abirstolov we're just trying the @coderabbitai service, please read its comments carefully and let us know if it was relevant comments.

Copy link

coderabbitai bot commented Nov 27, 2024

Tip

For best results, initiate chat on the files or code changes.

@baruchiro: Thank you for introducing me to the team. I hope my comments are helpful. If you or @abirstolov have any questions or need further assistance, please feel free to reach out.

Copy link
Owner

@brafdlog brafdlog left a comment

Choose a reason for hiding this comment

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

Looks good, thanks @abirstolov
See comments

@abirstolov abirstolov changed the title Added import id for YNAB Fix: Added import id for YNAB Nov 30, 2024
@brafdlog
Copy link
Owner

brafdlog commented Dec 1, 2024

@abirstolov did you check this version locally to see that it doesn't create duplicates of existing transactions?
Logically it shouldn't, but I want a sanity check before merging

@abirstolov abirstolov closed this Dec 3, 2024
@abirstolov abirstolov reopened this Dec 3, 2024
@baruchiro
Copy link
Collaborator

@abirstolov if you need any help with GitHub talk with us on Discord

@abirstolov
Copy link
Author

@baruchiro I have tested that case, for the same transaction with a different payee - it didn't add a duplicate, and for a different transaction it did add.

@brafdlog brafdlog merged commit 97f0909 into brafdlog:master Dec 5, 2024
19 checks passed
Copy link
Contributor

github-actions bot commented Dec 6, 2024

🎉 This PR is included in version 2.4.2 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

YNAB transaction reinserted if payee has changed
3 participants