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: exchange rate for ccp #706

Closed
wants to merge 7 commits into from
Closed

fix: exchange rate for ccp #706

wants to merge 7 commits into from

Conversation

anishfyle
Copy link
Contributor

@anishfyle anishfyle commented Dec 16, 2024

Description

Clickup

  • app.clickup.com/t/fixExchangeRate

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced handling of multi-currency transactions for credit card purchases and bills.
    • Improved error handling for transactions during closed accounting periods.
  • Bug Fixes

    • Ensured correct application of exchange rates for all relevant transactions.
  • Refactor

    • Streamlined logic for constructing financial payloads, improving overall readability.

Copy link

coderabbitai bot commented Dec 16, 2024

Walkthrough

The pull request introduces significant modifications to the QBOConnector class in the QuickBooks Online integration utility. Key changes focus on improving multi-currency transaction handling by incorporating exchange rate checks and calculations in the purchase_object_payload and __construct_bill methods. Additionally, error handling has been refined for transactions within closed accounting periods, ensuring compliance by adjusting transaction dates as necessary. These updates enhance the accuracy and robustness of financial transaction processing with QuickBooks Online.

Changes

File Change Summary
apps/quickbooks_online/utils.py - Enhanced multi-currency support in purchase_object_payload and __construct_bill methods
- Added exchange rate fetching and application logic
- Improved error handling for closed accounting periods in post_bill and post_credit_card_purchase methods
- Updated method signatures for clarity

Poem

🐰 Hopping through QuickBooks with glee,

Exchange rates dancing, currency free!

Transactions leap, no period can bind,

Accuracy and precision intertwined.

A rabbit's code, precise and bright! 💸

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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.

@github-actions github-actions bot added the size/S Small PR label Dec 16, 2024
@anishfyle anishfyle requested a review from Hrishabh17 December 16, 2024 10:52
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: 1

🧹 Nitpick comments (2)
apps/quickbooks_online/utils.py (2)

1052-1054: Consider caching 'general_settings' and 'qbo_home_currency' in the constructor

The variables general_settings and qbo_home_currency are fetched here but may be used across multiple methods. To reduce redundant database queries and improve performance, consider initializing them once in the __init__ method and storing them as instance variables.


1070-1070: Simplify exchange rate retrieval using get() method

You can simplify the retrieval of the exchange rate by using the get() method with a default value.

Apply this diff:

-        credit_card_purchase_payload['ExchangeRate'] = exchange_rate['Rate'] if "Rate" in exchange_rate else 1
+        credit_card_purchase_payload['ExchangeRate'] = exchange_rate.get('Rate', 1)
🧰 Tools
🪛 Ruff (0.8.2)

1070-1070: Use exchange_rate.get('Rate', 1) instead of an if block

Replace with exchange_rate.get('Rate', 1)

(SIM401)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 215d3fc and c8e8a1c.

📒 Files selected for processing (1)
  • apps/quickbooks_online/utils.py (3 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
apps/quickbooks_online/utils.py

1070-1070: Use exchange_rate.get('Rate', 1) instead of an if block

Replace with exchange_rate.get('Rate', 1)

(SIM401)

apps/quickbooks_online/utils.py Outdated Show resolved Hide resolved
Copy link

Tests Skipped Failures Errors Time
268 0 💤 0 ❌ 0 🔥 59.257s ⏱️

@anishfyle anishfyle removed the request for review from Hrishabh17 December 16, 2024 11:57
@github-actions github-actions bot added size/XS Extra Small PR and removed size/S Small PR labels Dec 16, 2024
Copy link

Tests Skipped Failures Errors Time
268 0 💤 0 ❌ 0 🔥 44.974s ⏱️

@anishfyle anishfyle requested a review from ruuushhh December 16, 2024 12:23
@github-actions github-actions bot added size/S Small PR and removed size/XS Extra Small PR labels Dec 16, 2024
@anishfyle anishfyle requested a review from ashwin1111 December 16, 2024 12:24
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: 1

🧹 Nitpick comments (1)
apps/quickbooks_online/utils.py (1)

1051-1077: Add docstring parameters and return type

The method's docstring is missing parameter and return type documentation.

Apply this diff to improve the documentation:

     def __construct_credit_card_purchase(self, credit_card_purchase: CreditCardPurchase, credit_card_purchase_lineitems: List[CreditCardPurchaseLineitem]) -> Dict:
         """
         Create a credit card purchase
-        :param credit_card_purchase: credit card purchase object extracted from database
-        :return: constructed credit card purchase
+        Args:
+            credit_card_purchase: Credit card purchase object extracted from database
+            credit_card_purchase_lineitems: List of credit card purchase line items
+        Returns:
+            Dict: Constructed credit card purchase payload for QBO API
+        Raises:
+            Exception: If exchange rate is not found for the given currency
         """
🧰 Tools
🪛 Ruff (0.8.2)

1074-1074: Use exchange_rate.get('Rate', 1) instead of an if block

Replace with exchange_rate.get('Rate', 1)

(SIM401)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c8e8a1c and e48baf4.

📒 Files selected for processing (1)
  • apps/quickbooks_online/utils.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
apps/quickbooks_online/utils.py

1074-1074: Use exchange_rate.get('Rate', 1) instead of an if block

Replace with exchange_rate.get('Rate', 1)

(SIM401)

🔇 Additional comments (1)
apps/quickbooks_online/utils.py (1)

1072-1074: 🛠️ Refactor suggestion

Improve exchange rate handling

The exchange rate handling can be improved in two ways:

  1. Use dict.get() for cleaner code
  2. Add error handling for missing exchange rates

Apply this diff to improve the exchange rate handling:

         if general_settings.is_multi_currency_allowed and fyle_home_currency != qbo_home_currency and qbo_home_currency:
             exchange_rate = self.connection.exchange_rates.get_by_source(source_currency_code=fyle_home_currency)
-            credit_card_purchase_payload['ExchangeRate'] = exchange_rate['Rate'] if "Rate" in exchange_rate else 1
+            if not exchange_rate:
+                raise Exception(f'Exchange rate not found for currency {fyle_home_currency}')
+            credit_card_purchase_payload['ExchangeRate'] = exchange_rate.get('Rate', 1)

Likely invalid or redundant comment.

🧰 Tools
🪛 Ruff (0.8.2)

1074-1074: Use exchange_rate.get('Rate', 1) instead of an if block

Replace with exchange_rate.get('Rate', 1)

(SIM401)

apps/quickbooks_online/utils.py Outdated Show resolved Hide resolved
Copy link

Tests Skipped Failures Errors Time
268 0 💤 4 ❌ 0 🔥 58.437s ⏱️

@github-actions github-actions bot added size/XS Extra Small PR and removed size/S Small PR labels Dec 17, 2024
Copy link

Tests Skipped Failures Errors Time
268 0 💤 0 ❌ 0 🔥 59.100s ⏱️

@anishfyle anishfyle added the deploy Triggers deployment of active branch to Staging label Dec 17, 2024
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: 0

🧹 Nitpick comments (1)
apps/quickbooks_online/utils.py (1)

735-736: Refactor to eliminate code duplication when handling exchange rates

The logic for fetching the exchange rate, assigning it to the payload, and saving it to the object is duplicated in both purchase_object_payload and __construct_bill methods. Refactor this logic into a separate helper method to enhance maintainability and adhere to the DRY (Don't Repeat Yourself) principle.

Consider creating a helper method like set_exchange_rate:

def set_exchange_rate(self, source_currency_code):
    exchange_rate = self.connection.exchange_rates.get_by_source(source_currency_code=source_currency_code)
    if not exchange_rate:
        raise Exception(f'Exchange rate not found for currency {source_currency_code}')
    return exchange_rate['Rate'] if "Rate" in exchange_rate else 1

Then update the original methods:

In purchase_object_payload:

-            exchange_rate = self.connection.exchange_rates.get_by_source(source_currency_code=purchase_object.currency)
-            purchase_object_payload['ExchangeRate'] = exchange_rate['Rate'] if "Rate" in exchange_rate else 1
+            purchase_object_payload['ExchangeRate'] = self.set_exchange_rate(purchase_object.currency)
             purchase_object.exchange_rate = purchase_object_payload['ExchangeRate']
             purchase_object.save(update_fields=['exchange_rate'])

In __construct_bill:

-            exchange_rate = self.connection.exchange_rates.get_by_source(source_currency_code=fyle_home_currency)
-            bill_payload['ExchangeRate'] = exchange_rate['Rate'] if "Rate" in exchange_rate else 1
+            bill_payload['ExchangeRate'] = self.set_exchange_rate(fyle_home_currency)
             bill.exchange_rate = bill_payload['ExchangeRate']
             bill.save(update_fields=['exchange_rate'])

Also applies to: 737-738

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b10d25f and 0d58d50.

📒 Files selected for processing (1)
  • apps/quickbooks_online/utils.py (1 hunks)
🔇 Additional comments (2)
apps/quickbooks_online/utils.py (2)

735-736: Add error handling for missing exchange rates

If self.connection.exchange_rates.get_by_source returns None, accessing exchange_rate['Rate'] will raise an exception. Ensure that you handle the case where exchange_rate might be None to prevent runtime errors.

Apply this diff to add error handling:

             exchange_rate = self.connection.exchange_rates.get_by_source(source_currency_code=purchase_object.currency)
+            if not exchange_rate:
+                raise Exception(f'Exchange rate not found for currency {purchase_object.currency}')
             purchase_object_payload['ExchangeRate'] = exchange_rate['Rate'] if "Rate" in exchange_rate else 1
             purchase_object.exchange_rate = purchase_object_payload['ExchangeRate']

737-738: Add error handling for missing exchange rates

Similarly, in the __construct_bill method, handle the case where exchange_rate might be None to prevent runtime errors when accessing exchange_rate['Rate'].

Apply this diff to add error handling:

             exchange_rate = self.connection.exchange_rates.get_by_source(source_currency_code=fyle_home_currency)
+            if not exchange_rate:
+                raise Exception(f'Exchange rate not found for currency {fyle_home_currency}')
             bill_payload['ExchangeRate'] = exchange_rate['Rate'] if "Rate" in exchange_rate else 1
             bill.exchange_rate = bill_payload['ExchangeRate']

Copy link

Tests Skipped Failures Errors Time
268 0 💤 0 ❌ 0 🔥 54.433s ⏱️

@anishfyle anishfyle closed this Dec 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deploy Triggers deployment of active branch to Staging size/XS Extra Small PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant