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: csv import with less than 5 columns #3605

Merged
merged 5 commits into from
Oct 9, 2024

Conversation

UnderKoen
Copy link
Member

broken csv before:
CSV import actual issue.csv

@actual-github-bot actual-github-bot bot changed the title fix: csv import with less than 5 columns [WIP] fix: csv import with less than 5 columns Oct 8, 2024
Copy link

netlify bot commented Oct 8, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit 4f0a587
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67062d2b9022570008f7a711
😎 Deploy Preview https://deploy-preview-3605.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

coderabbitai bot commented Oct 8, 2024

Walkthrough

The pull request introduces a new utility function, stripCsvImportTransaction, which is added to the utils.js file. This function processes transaction objects by extracting specific properties and returning a new object that contains the remaining properties. The FieldMappings and ImportTransactionsModal components have been updated to utilize this new function. In FieldMappings, the first transaction is now processed through stripCsvImportTransaction instead of being destructured directly. Similarly, in ImportTransactionsModal, the initial transaction mapping logic has been modified to incorporate this utility function. The changes enhance the handling of transaction data while maintaining the overall structure of the components. No existing functions were altered, and no new public entities were declared outside of the new utility function.

Possibly related PRs

Suggested labels

::sparkles: Merged

Suggested reviewers

  • MatissJanis

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b6b2b9e and 4f0a587.

📒 Files selected for processing (1)
  • packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx
🧰 Additional context used
📓 Learnings (1)
📓 Common learnings
Learnt from: UnderKoen
PR: actualbudget/actual#3605
File: packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx:23-23
Timestamp: 2024-10-08T15:48:20.059Z
Learning: `stripCsvImportTransaction` removes `trx_id` from the transaction to address issues caused by `trx_id` being assigned to an element.

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.

@UnderKoen
Copy link
Member Author

If #3499 is merged I could easily add an regression test for this bug.

Copy link
Contributor

github-actions bot commented Oct 8, 2024

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
9 5.32 MB → 5.32 MB (+157 B) +0.00%
Changeset
File Δ Size
src/components/modals/ImportTransactionsModal/utils.js 📈 +163 B (+3.66%) 4.35 kB → 4.51 kB
src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx 📈 +27 B (+0.09%) 29.74 kB → 29.76 kB
src/components/modals/ImportTransactionsModal/FieldMappings.jsx 📉 -33 B (-0.54%) 6 kB → 5.97 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/index.js 3.34 MB → 3.34 MB (+157 B) +0.00%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/usePreviewTransactions.js 1.64 kB 0%
static/js/AppliedFilters.js 20.96 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/narrow.js 82.55 kB 0%
static/js/wide.js 224.88 kB 0%
static/js/ReportRouter.js 1.51 MB 0%

Copy link
Contributor

github-actions bot commented Oct 8, 2024

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.26 MB → 1.26 MB (+16 B) +0.00%
Changeset
File Δ Size
packages/loot-core/src/server/accounts/rules.ts 📈 +24 B (+0.07%) 33.09 kB → 33.11 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

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

Smaller

No assets were smaller

Unchanged

No assets were unchanged

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

🧹 Outside diff range and nitpick comments (3)
packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx (1)

Line range hint 1-138: Summary: Centralized transaction processing with potential wide-ranging effects.

The changes to this component are minimal but potentially impactful. The introduction of stripCsvImportTransaction centralizes the logic for processing CSV import transactions, which is a good practice for maintainability and consistency. However, this change may affect the structure of the trans object, which is used throughout the component to generate options for various fields.

To ensure the robustness of this change:

  1. Thoroughly test the component with various CSV import scenarios to verify that all necessary transaction properties are preserved after processing.
  2. Update the component's documentation or comments to reflect the new data flow and any changes in the expected structure of the trans object.
  3. Consider adding PropTypes or TypeScript types for the trans object to enforce its structure and catch potential issues early in development.
packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js (1)

189-194: LGTM with suggestions for improvement

The stripCsvImportTransaction function is well-implemented and effectively removes specific properties from the transaction object. However, consider the following suggestions:

  1. Add input validation to handle cases where transaction might be null or undefined.
  2. Consider adding a brief comment explaining why these specific properties are being stripped.

Here's a suggested implementation with these improvements:

/**
 * Strips specific properties from a CSV import transaction.
 * @param {Object} transaction - The transaction object to process.
 * @returns {Object} A new object with the specified properties removed.
 */
export function stripCsvImportTransaction(transaction) {
  if (!transaction || typeof transaction !== 'object') {
    return {};
  }

  // Remove properties used internally during the import process
  const { existing, ignored, selected, selected_merge, trx_id, ...trans } = transaction;

  return trans;
}

This implementation adds a simple check for the input and includes a brief explanation in the comments.

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

403-403: Approve: Consistent type safety, consider refactoring

This change completes the set of improvements for string comparisons in the eval method, ensuring type safety for the hasTags condition. It's consistent with the changes made for contains and doesNotContain.

Given that this pattern is now repeated three times in the eval method, consider refactoring to reduce duplication:

Consider extracting the string conversion logic into a helper method to reduce code duplication:

private ensureString(value: any): string {
  return `${value}`;
}

// Then in the eval method:
case 'contains':
case 'doesNotContain':
case 'hasTags':
  if (fieldValue === null) {
    return false;
  }
  return this.ensureString(fieldValue).indexOf(this.value) !== -1;

This refactoring would centralize the string conversion logic, making it easier to maintain and modify in the future if needed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 71c208e and 07d5b66.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/3605.md is excluded by !**/*.md
📒 Files selected for processing (4)
  • packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx (2 hunks)
  • packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx (2 hunks)
  • packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js (1 hunks)
  • packages/loot-core/src/server/accounts/rules.ts (2 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx (1)
Learnt from: MatissJanis
PR: actualbudget/actual#3570
File: packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.ts:120-130
Timestamp: 2024-10-05T10:59:08.817Z
Learning: Avoid overcomplicating the `ImportTransaction` type; prefer to keep it simple.
🔇 Additional comments (11)
packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx (2)

23-23: LGTM. Verify impact on component and transaction structure.

The use of stripCsvImportTransaction to process the first transaction simplifies the code and centralizes the logic for transaction processing. However, this change may affect the structure of the trans object and, consequently, the options derived from it.

To ensure the change doesn't introduce unintended side effects, please run the following script:

Additionally, ensure that all properties previously accessed on trans are still available after processing with stripCsvImportTransaction.


9-9: LGTM. Verify the utility function implementation.

The import statement for stripCsvImportTransaction is correctly added. This new utility function seems to be crucial for processing CSV import transactions.

To ensure the utility function is properly implemented, please run the following script:

✅ Verification successful

Verified the implementation of stripCsvImportTransaction in utils.js. The function correctly exports and handles the expected transaction properties.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of stripCsvImportTransaction in utils.js

# Test: Check if the function is exported and its basic structure
ast-grep --lang javascript --pattern 'export function stripCsvImportTransaction($_) { $$$ }' packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js

# Test: Check if the function is handling the expected transaction properties
rg --type js 'function stripCsvImportTransaction' -A 10 packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js

Length of output: 1146

packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js (1)

189-194: Verify usage of new function across the codebase

The addition of stripCsvImportTransaction function is a good utility for processing transaction objects. To ensure its proper integration:

  1. Verify that this function is used consistently where needed in the import process.
  2. Check for any potential side effects in modules that will use this function.

Run the following script to check the usage of stripCsvImportTransaction across the codebase:

This will help identify where the function is being imported and used, allowing us to verify its correct implementation across the codebase.

✅ Verification successful

Function stripCsvImportTransaction is correctly utilized across the codebase

The stripCsvImportTransaction function is properly imported and used in the following modules:

  • ImportTransactionsModal.jsx: Utilizes the function to process transactions effectively.
  • FieldMappings.jsx: Applies the function to handle transaction data accurately.

No unintended side effects or inconsistencies detected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check usage of stripCsvImportTransaction function

# Search for import statements
echo "Checking import statements:"
rg --type js --type jsx "import.*stripCsvImportTransaction.*from.*utils" -g '!utils.js'

# Search for function usage
echo "\nChecking function usage:"
rg --type js --type jsx "stripCsvImportTransaction\(" -g '!utils.js'

Length of output: 344


Script:

#!/bin/bash
# Description: Check usage of stripCsvImportTransaction function

# Search for import statements in .js and .jsx files
echo "Checking import statements:"
rg "import.*stripCsvImportTransaction.*from.*utils" -g "*.js" -g "*.jsx" --ignore-file '!utils.js'

# Search for function usage in .js and .jsx files
echo "\nChecking function usage:"
rg "stripCsvImportTransaction\(" -g "*.js" -g "*.jsx" --ignore-file '!utils.js'

Length of output: 999

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

387-387: Approve: Improved type safety in string comparison

This change enhances the robustness of the contains condition by explicitly converting fieldValue to a string before performing the indexOf check. This prevents potential type errors when fieldValue is not a string, making the code more resilient to unexpected input types.


392-392: Approve: Consistent type safety improvement

This change mirrors the improvement made in the contains case, ensuring type safety for the doesNotContain condition. By converting fieldValue to a string, it prevents potential type errors and maintains consistency in how string comparisons are handled throughout the eval method.


Line range hint 387-403: Summary: Improved type safety in string comparisons

The changes in this file consistently enhance type safety for string comparisons in the eval method of the Condition class. By explicitly converting fieldValue to a string before performing indexOf operations, the code becomes more robust against potential type errors.

These modifications affect the contains, doesNotContain, and hasTags conditions, ensuring consistent behavior across different types of string-based comparisons. The changes are well-considered and improve the overall reliability of the rule evaluation process.

Consider the suggested refactoring to further improve code maintainability by reducing duplication in the string conversion logic.

packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx (5)

Line range hint 1012-1029: Enhanced import logic for reconciliation and forced transaction addition

The onImport function has been updated with more sophisticated logic for handling reconciliation and forced transaction addition. This includes checks for isMatchedTransaction, ignored, and selected_merge properties.

These changes significantly alter the import behavior. Please ensure:

  1. The new logic correctly handles all possible combinations of transaction states.
  2. Edge cases are properly addressed (e.g., what happens if a transaction is both ignored and selected?).
  3. The UI accurately reflects these new states to avoid user confusion.

Consider adding comprehensive unit tests for this function. You can use this script to find related test files:

#!/bin/bash
# Search for test files related to import functionality
rg "import.*test" --type js

Line range hint 1180-1184: UI updates for new reconciliation options

New UI elements have been added to support the enhanced reconciliation functionality:

  1. A checkbox for merging with existing transactions.
  2. Filtered rendering of transactions based on the isMatchedTransaction property.

Please ensure:

  1. The new UI elements are accessible and their purpose is clear to users.
  2. The filtering of transactions in the UI accurately reflects the backend logic.
  3. There are no unintended side effects on the layout or performance of the component.

You can use this script to check for accessibility and performance considerations:

#!/bin/bash
# Search for accessibility attributes and performance optimizations
echo "Accessibility checks:"
rg "aria-|role=" --type js
echo "\nPerformance optimizations:"
rg "React\.memo|useMemo|useCallback" --type js

Also applies to: 1252-1257


Line range hint 1-1352: Summary of changes and suggestions for improvement

This PR introduces significant enhancements to the import process, particularly in handling reconciliation and matched transactions. While these changes add valuable functionality, they also increase the complexity of the ImportTransactionsModal component.

Key points:

  1. New utility function stripCsvImportTransaction for processing CSV imports.
  2. Enhanced logic in getImportPreview and onImport for handling matched and reconciled transactions.
  3. UI updates to reflect new reconciliation options.

To improve maintainability and reduce complexity:

  1. Consider breaking down this large component into smaller, more focused components.
  2. Implement comprehensive unit and integration tests for the new functionality.
  3. Add detailed documentation explaining the new reconciliation process and its various states.
  4. Consider implementing a state management solution (e.g., Redux, MobX) to handle the complex state logic more efficiently.

To ensure these changes don't introduce regressions:

  1. Conduct thorough end-to-end testing of the import process with various file types and edge cases.
  2. Verify performance with large transaction sets.
  3. Ensure backwards compatibility with existing imported data.

You can use this script to identify potential areas for refactoring:

#!/bin/bash
# Find large components and functions that might benefit from refactoring
echo "Large components (>500 lines):"
rg -U "export.*function.*\{" --type js | awk '{print length, $0}' | sort -rn | head -10
echo "\nComplex functions (>50 lines):"
rg -U "function.*\{" --type js | awk '{print length, $0}' | sort -rn | head -10

63-63: Modification in initial mappings derivation

The getInitialMappings function now uses stripCsvImportTransaction to process the first transaction before deriving field mappings.

Please ensure that this change doesn't affect the field detection logic, especially for edge cases. Consider adding unit tests to verify the behavior with various CSV structures.

To verify the impact, you can run the following script:

✅ Verification successful

Verified: stripCsvImportTransaction does not impact field detection logic

The stripCsvImportTransaction function removes specific metadata fields without altering the core transaction data used for field detection.

  • Impact Assessment:
    • Removed fields (existing, ignored, selected, selected_merge, trx_id) are not involved in field detection.
    • Core transaction data remains unaffected, ensuring field detection operates correctly.

No issues found with the current implementation.


🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all usages of getInitialMappings and stripCsvImportTransaction
echo "Usages of getInitialMappings:"
rg "getInitialMappings" --type js
echo "\nUsages of stripCsvImportTransaction:"
rg "stripCsvImportTransaction" --type js

Length of output: 1387


Script:

#!/bin/bash
# Inspect usages of stripCsvImportTransaction in FieldMappings.jsx
rg "stripCsvImportTransaction" packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx

Length of output: 231


Script:

#!/bin/bash
# Retrieve the implementation of stripCsvImportTransaction from utils.js
rg "function stripCsvImportTransaction" packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js -A 10

Length of output: 295


Line range hint 292-295: New logic to skip matched transactions in import preview

A new check has been added to skip transactions that are already matched. This is likely an optimization, but it changes the behavior of the import preview.

Please verify that:

  1. This change doesn't hide important information from the user.
  2. The UI properly indicates when transactions are skipped.
  3. The total count of imported transactions is still accurate.

You can use this script to check for any UI components that might need updating:

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

🧹 Outside diff range and nitpick comments (3)
packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx (1)

Line range hint 1-138: Address PR objective: CSV import with less than 5 columns

While the changes improve code organization, they don't directly address the PR objective of fixing CSV import with less than 5 columns. Consider the following suggestions:

  1. Ensure that stripCsvImportTransaction correctly handles transactions with fewer than 5 columns.
  2. Add error handling or validation for cases where required fields are missing.
  3. Implement the regression test mentioned in the PR description once PR test: csv import e2e tests #3499 is merged.

Would you like assistance in implementing these suggestions or creating a GitHub issue to track them?

packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js (1)

189-194: LGTM! Consider adding input validation and documentation.

The new stripCsvImportTransaction function is well-implemented and serves its purpose of removing specific properties from a transaction object. It's a clean and straightforward utility function that will be useful for processing CSV import transactions.

To further improve the function, consider the following suggestions:

  1. Add input validation to ensure transaction is an object.
  2. Include JSDoc documentation for better code readability and maintainability.

Here's an example of how you could implement these suggestions:

/**
 * Strips specific properties from a CSV import transaction object.
 * @param {Object} transaction - The transaction object to process.
 * @returns {Object} A new object with the specified properties removed.
 * @throws {TypeError} If the input is not an object.
 */
export function stripCsvImportTransaction(transaction) {
  if (typeof transaction !== 'object' || transaction === null) {
    throw new TypeError('Input must be an object');
  }

  const { existing, ignored, selected, selected_merge, trx_id, ...trans } = transaction;

  return trans;
}

These changes would enhance the robustness and clarity of the function without altering its core functionality.

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

Line range hint 1-1006: Consider refactoring for improved maintainability

While the changes in this PR are minimal and focused on fixing the CSV import issue, the overall file is quite large and complex. Consider the following suggestions for future improvements:

  1. Break down the ImportTransactionsModal component into smaller, more manageable sub-components.
  2. Extract utility functions and constants into separate files to reduce the file size and improve readability.
  3. Use custom hooks to manage complex state logic, which could help in separating concerns and make the component easier to test.
  4. Consider using a state management library like Redux or Recoil for handling complex state interactions, especially if this component's state is used in other parts of the application.

These suggestions are not directly related to the current PR but could be considered for future refactoring efforts to improve the overall maintainability of the codebase.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 71c208e and 07d5b66.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/3605.md is excluded by !**/*.md
📒 Files selected for processing (4)
  • packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx (2 hunks)
  • packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx (2 hunks)
  • packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js (1 hunks)
  • packages/loot-core/src/server/accounts/rules.ts (2 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx (1)
Learnt from: MatissJanis
PR: actualbudget/actual#3570
File: packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.ts:120-130
Timestamp: 2024-10-05T10:59:08.817Z
Learning: Avoid overcomplicating the `ImportTransaction` type; prefer to keep it simple.
🔇 Additional comments (9)
packages/desktop-client/src/components/modals/ImportTransactionsModal/FieldMappings.jsx (1)

9-9: LGTM: New utility function import.

The import of stripCsvImportTransaction from the local ./utils module is correctly implemented. This approach promotes good code organization by separating utility functions into a dedicated file.

packages/desktop-client/src/components/modals/ImportTransactionsModal/utils.js (1)

188-194: Good integration with existing utilities.

The placement and implementation of the new stripCsvImportTransaction function integrate well with the existing codebase. It complements other utility functions in this file, such as applyFieldMappings, by providing an additional tool for transaction object manipulation.

To ensure proper usage across the codebase:

Let's verify the usage of this new function:

This will help us confirm that the function is being imported and used correctly in other parts of the application.

✅ Verification successful

Function stripCsvImportTransaction is correctly integrated and utilized.

The stripCsvImportTransaction function is properly imported and used in the following files:

  • FieldMappings.jsx
  • ImportTransactionsModal.jsx

No issues were found with its integration into the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of stripCsvImportTransaction in other files

# Search for import statements
echo "Checking import statements:"
rg --type js "import.*stripCsvImportTransaction.*from.*utils" packages/desktop-client/src

# Search for function usage
echo "\nChecking function usage:"
rg --type js "stripCsvImportTransaction\(" packages/desktop-client/src

Length of output: 881

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

387-387: Improved type safety in string comparison

This change ensures that fieldValue is always converted to a string before the indexOf operation is performed. This is a good defensive programming practice that prevents potential type-related issues, especially if fieldValue could be of a non-string type.


392-392: Consistent type safety improvement

This change applies the same type safety improvement as in the contains case, ensuring fieldValue is converted to a string before the indexOf operation. This maintains consistency in how string comparisons are handled across different conditions.


403-403: Completed type safety improvements

This change completes the pattern of type safety improvements across all relevant cases in the eval method. By consistently converting fieldValue to a string in the hasTags case, we ensure that all string comparisons in this method are handled safely and uniformly.


Line range hint 387-403: Summary of changes: Improved type safety in condition evaluation

These changes collectively enhance the robustness of the eval method in the Condition class. By consistently converting fieldValue to a string using template literals in the contains, doesNotContain, and hasTags cases, the code now handles potential type mismatches more gracefully. This improvement directly addresses the issue mentioned in the PR title regarding CSV import with less than 5 columns, as it allows for more flexible handling of field values that may not always be strings.

The modifications are consistent, well-implemented, and improve the overall reliability of the condition evaluation process. These changes should help prevent potential bugs related to type coercion in string comparisons.

packages/desktop-client/src/components/modals/ImportTransactionsModal/ImportTransactionsModal.jsx (3)

Line range hint 1-1006: Summary of changes and recommendations

The main change in this PR is the introduction of the stripCsvImportTransaction function to process transactions in the getInitialMappings function. This change aims to fix the issue with CSV imports containing less than 5 columns.

Next steps and recommendations:

  1. Thoroughly test the CSV import functionality with various column counts to ensure the fix works as intended and doesn't introduce any regressions.
  2. Consider adding or updating unit tests to cover the new functionality and edge cases.
  3. In future iterations, consider refactoring this large component into smaller, more manageable pieces to improve maintainability.
  4. Update the documentation to reflect any changes in the CSV import behavior, if necessary.

Overall, the changes look good and are focused on addressing the specific issue mentioned in the PR objective.


63-63: Verify CSV import functionality with various column counts

To ensure that the changes effectively address the issue of importing CSV files with less than 5 columns, we should test the import functionality with various CSV files containing different numbers of columns.

Consider adding the following test cases:

  1. CSV file with 3 columns
  2. CSV file with 4 columns
  3. CSV file with 5 columns
  4. CSV file with more than 5 columns

These tests will help verify that the stripCsvImportTransaction function correctly handles different column counts without breaking existing functionality.

If no existing tests are found, consider adding new test cases to cover these scenarios.


63-63: 💡 Codebase verification

Utilize the new stripCsvImportTransaction utility function.

The stripCsvImportTransaction function is now used to process the first transaction before deriving field mappings. This change aligns with the PR objective of fixing CSV imports with less than 5 columns.

However, to ensure this change doesn't introduce any regressions, we should verify its impact on the rest of the codebase.

Let's check for other usages of getInitialMappings:

✅ Verification successful

Correct the shell script to successfully search for getInitialMappings usages.

It appears there was a syntax error in the previous shell script. Please run the following corrected script to search for other usages of getInitialMappings:


Confirmed: getInitialMappings is used only within ImportTransactionsModal.jsx.

No additional usages found, ensuring that the changes remain isolated and should not introduce regressions elsewhere.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other usages of getInitialMappings
rg "getInitialMappings" --type js

Length of output: 120


Script:

#!/bin/bash
# Search for other usages of getInitialMappings
rg "getInitialMappings" --type js

Length of output: 474

@UnderKoen UnderKoen changed the title [WIP] fix: csv import with less than 5 columns fix: csv import with less than 5 columns Oct 8, 2024
Copy link
Contributor

@matt-fidd matt-fidd left a comment

Choose a reason for hiding this comment

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

Thanks for jumping on to this! Just a couple of nits

Co-authored-by: Matt Fiddaman <github@m.fiddaman.uk>
Copy link
Contributor

@matt-fidd matt-fidd left a comment

Choose a reason for hiding this comment

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

Thanks for this!

@matt-fidd matt-fidd merged commit e6024f7 into actualbudget:master Oct 9, 2024
20 checks passed
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