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

feat: add support for exchange rate ccp #699

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

Conversation

anishfyle
Copy link
Contributor

@anishfyle anishfyle commented Nov 26, 2024

Description

  • add support for exchange rate for foreign currency, having CCP as export type

Clickup

Summary by CodeRabbit

  • New Features

    • Introduced an exchange_rate field to the credit card purchase model for better handling of foreign currency transactions.
    • Enhanced currency handling and tax calculations during the creation of purchase objects, bills, and credit card purchases.
  • Bug Fixes

    • Improved error handling for transactions in closed accounting periods.
  • Chores

    • Updated PostgreSQL database dump metadata to reflect the latest version changes.

Copy link

coderabbitai bot commented Nov 26, 2024

Walkthrough

This pull request introduces a new field, exchange_rate, to the CreditCardPurchase model in the quickbooks_online application. The field is a nullable FloatField that stores the exchange rate for credit card purchases. Additionally, the QBOConnector class is updated to enhance currency exchange rate handling and error management during purchase object creation. The database dump metadata is also updated to reflect a new version of PostgreSQL and the pg_dump tool.

Changes

File Change Summary
apps/quickbooks_online/migrations/0017_creditcardpurchase_exchange_rate.py Added exchange_rate field to creditcardpurchase model as a nullable FloatField.
apps/quickbooks_online/models.py Introduced exchange_rate field to CreditCardPurchase model; updated create_credit_card_purchase method to include exchange_rate from associated expense.
apps/quickbooks_online/utils.py Enhanced QBOConnector methods to handle currency exchange rates in transactions; refined error handling for closed accounting periods.
tests/sql_fixtures/reset_db_fixtures/reset_db.sql Updated PostgreSQL database dump metadata version from 15.9 to 15.10 and pg_dump tool version from 15.8 to 15.10.

Possibly related PRs

  • feat: auto enable accounting period #692: Involves modifications to the handling of accounting periods, which may relate to how transactions, including credit card purchases, are processed in the system.

Suggested labels

size/S

Suggested reviewers

  • ruuushhh

Poem

🐇 In the meadow where bunnies play,
A new field blooms, bright as the day.
Exchange rates dance, a currency waltz,
QuickBooks sings, with no faults.
Hops of joy, we celebrate,
Changes made, oh, how great! 🌼


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.

@github-actions github-actions bot added the size/S Small PR label Nov 26, 2024
Copy link

Tests Skipped Failures Errors Time
261 0 💤 4 ❌ 4 🔥 59.299s ⏱️

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

🧹 Outside diff range and nitpick comments (4)
apps/quickbooks_online/migrations/0017_creditcardpurchase_exchange_rate.py (1)

16-16: Enhance the help text description

The current help text could be more descriptive to better explain the purpose and context of this field.

Consider updating the help text to be more specific:

- help_text='Exchange rate'
+ help_text='Exchange rate used for converting foreign currency transactions to the base currency'
apps/quickbooks_online/models.py (1)

654-654: Consider adding exchange rate validation

While the implementation correctly uses the expense's exchange rate, consider adding validation to ensure the exchange rate is positive when present.

 def create_credit_card_purchase(expense_group: ExpenseGroup, map_merchant_to_vendor: bool):
     description = expense_group.description
     expense = expense_group.expenses.first()
+    if expense.exchange_rate is not None and expense.exchange_rate <= 0:
+        raise ValueError("Exchange rate must be positive when present")
apps/quickbooks_online/utils.py (2)

733-733: Simplify exchange rate retrieval using .get() method

Use exchange_rate.get('Rate', 1) instead of the conditional expression for cleaner and more Pythonic code.

Apply this diff:

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

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

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

(SIM401)


745-745: Replace list comprehension with a for loop for side-effect operations

Using a list comprehension for its side effects is not recommended. Replace it with a standard for loop for better readability and adherence to best practices.

Apply this diff:

-[line['ItemBasedExpenseLineDetail'].pop('TaxAmount') for line in purchase_object_payload['Line'] if 'ItemBasedExpenseLineDetail' in line]
+for line in purchase_object_payload['Line']:
+    if 'ItemBasedExpenseLineDetail' in line:
+        line['ItemBasedExpenseLineDetail'].pop('TaxAmount', None)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9eeb58d and cfdcbf0.

📒 Files selected for processing (4)
  • apps/quickbooks_online/migrations/0017_creditcardpurchase_exchange_rate.py (1 hunks)
  • apps/quickbooks_online/models.py (2 hunks)
  • apps/quickbooks_online/utils.py (2 hunks)
  • tests/sql_fixtures/reset_db_fixtures/reset_db.sql (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/sql_fixtures/reset_db_fixtures/reset_db.sql
🧰 Additional context used
🪛 Ruff (0.8.0)
apps/quickbooks_online/utils.py

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

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

(SIM401)

🔇 Additional comments (3)
apps/quickbooks_online/models.py (2)

602-602: LGTM: Exchange rate field properly defined

The exchange_rate field is appropriately defined as a nullable FloatField with clear help text, which aligns well with the PR's objective of supporting foreign currency transactions.


Line range hint 602-654: Verify exchange rate implementation completeness

Let's verify the complete implementation of the exchange rate feature.

✅ Verification successful

Let me gather more specific information about the exchange rate implementation.


Based on the gathered information, I can now provide the final response:

Exchange rate implementation is complete and properly handled

The exchange rate feature is fully implemented with:

  • Model fields properly defined in both Bill and CreditCardPurchase models
  • Proper migration files (0013 and 0017) for both models
  • Complete exchange rate handling in QBO utils:
    • Fetches exchange rates from QBO API for foreign currency transactions
    • Updates the models with the fetched rates
    • Handles both Bill and CreditCardPurchase scenarios
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for exchange rate related code and migrations

# Check for migration file
echo "Checking for migration file..."
fd ".*exchange_rate.*\.py$" apps/quickbooks_online/migrations/

# Check for exchange rate usage in other files
echo "Checking exchange rate usage in other files..."
rg "exchange_rate" --type python

# Check for any QBO API related files that might need updates
echo "Checking QBO API related files..."
fd "qbo.*\.py$" apps/quickbooks_online/

Length of output: 629


Script:

#!/bin/bash
# Check exchange rate usage with proper context
rg "exchange_rate" -t py -A 3 -B 3

# Check the content of the migration files
echo "Content of exchange rate migration files:"
cat apps/quickbooks_online/migrations/0013_bill_exchange_rate.py
cat apps/quickbooks_online/migrations/0017_creditcardpurchase_exchange_rate.py

# Check QBO expense model and serializer for exchange rate handling
echo "QBO expense related files:"
rg "exchange_rate" apps/quickbooks_online/serializers.py

Length of output: 7340

apps/quickbooks_online/utils.py (1)

731-733: Ensure exception handling when fetching exchange rates

Verify that the get_by_source method handles cases where the exchange rate is unavailable or the API call fails, to prevent unexpected exceptions.

🧰 Tools
🪛 Ruff (0.8.0)

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

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

(SIM401)

Comment on lines +13 to +17
migrations.AddField(
model_name='creditcardpurchase',
name='exchange_rate',
field=models.FloatField(help_text='Exchange rate', null=True),
),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider using DecimalField instead of FloatField for exchange rates

Using FloatField for exchange rates can lead to precision issues in financial calculations due to floating-point arithmetic limitations. This is particularly important for currency-related operations where exact precision is crucial.

Consider modifying the field definition to use DecimalField:

- field=models.FloatField(help_text='Exchange rate', null=True),
+ field=models.DecimalField(
+     max_digits=10,
+     decimal_places=6,
+     help_text='Exchange rate used for currency conversion',
+     null=True
+ ),
📝 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
migrations.AddField(
model_name='creditcardpurchase',
name='exchange_rate',
field=models.FloatField(help_text='Exchange rate', null=True),
),
migrations.AddField(
model_name='creditcardpurchase',
name='exchange_rate',
field=models.DecimalField(
max_digits=10,
decimal_places=6,
help_text='Exchange rate used for currency conversion',
null=True
),
),

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

Successfully merging this pull request may close these issues.

1 participant