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: PATCH /integrations on export errors and token expiry #442

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

Conversation

JustARatherRidiculouslyLongUsername
Copy link
Contributor

  • feat: PATCH /integrations on export errors

  • feat: patch /integrations on token expiry (feat: patch /integrations on token expiry #436)

  • feat: patch /integrations on token expiry

  • fix: move patch_integration_settings to apps/workspaces/actions.py

Avoids a circular import between actions.py and tasks.py

* feat: PATCH `/integrations` on export errors

* feat: patch `/integrations` on token expiry (#436)

* feat: patch `/integrations` on token expiry

* fix: move `patch_integration_settings` to `apps/workspaces/actions.py`

Avoids a circular import between actions.py and tasks.py

* test: unit test `/integrations` patch calls (#437)

* test: unit test `/integrations` patch calls

* fix: token expiry logic (#440)

* fix: token expiry logic

* fix: rename invalidate_token to invalidate_xero_credentials

* test: unit test updates for comment fixes (#441)
Copy link

coderabbitai bot commented Feb 14, 2025

Walkthrough

This pull request enhances error handling across multiple modules by adding calls to invalidate stale Xero credentials and update integration settings when specific authentication errors occur. New functions such as patch_request, patch_integration_settings, and invalidate_xero_credentials are introduced, with their respective invocations added to exception handling blocks in several components. Additional tests are included to verify the new behavior and payload structure.

Changes

File(s) Change Summary
apps/exceptions.py
apps/mappings/actions.py
apps/mappings/exceptions.py
apps/workspaces/actions.py
apps/xero/exceptions.py
apps/xero/queue.py
apps/xero/tasks.py
Integrated calls to invalidate_xero_credentials in exception handling blocks to mark expired or invalid Xero tokens as soon as related errors are caught.
apps/workspaces/helpers.py
apps/workspaces/actions.py
apps/xero/exceptions.py
Added patch_integration_settings to update workspace integration settings via PATCH API calls. The function is invoked during Xero connection flows to indicate token status and error counts.
apps/fyle/helpers.py Introduced a new patch_request function to send HTTP PATCH requests, constructing headers appropriately and handling responses similar to the existing post_request.
tests/test_exceptions.py
tests/test_workspaces/test_actions.py
tests/test_workspaces/test_views.py
tests/test_xero/test_exceptions.py
New tests validate that the exception handling decorators correctly invoke invalidate_xero_credentials and that patch_integration_settings constructs the proper payload under different scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CX as connect_xero()
    participant P as PatchIntegrationSettings()
    participant I as InvalidateXeroCredentials()
    participant X as Xero API

    U->>CX: Initiate Xero connection
    CX->>CX: Generate refresh token
    CX->>P: Call patch_integration_settings(workspace_id, is_token_expired=False)
    P-->>CX: Integration settings updated

    alt Exception Occurs
      CX->>X: Request company details
      X-->>CX: Error response (e.g., UnsuccessfulAuthentication)
      CX->>I: Call invalidate_xero_credentials(workspace_id)
      I-->>CX: Credentials marked as expired
    end
Loading
sequenceDiagram
    participant V as View Decorator
    participant F as Decorated Function
    participant I as InvalidateXeroCredentials()

    V->>F: Invoke function with workspace_id
    F-->>V: Raise UnsuccessfulAuthentication exception
    V->>I: Catch exception and call invalidate_xero_credentials(workspace_id)
    I-->>V: Credentials invalidated
    V-->>V: Return error response
Loading

Suggested reviewers

  • ashwin1111
  • ruuushhh

Poem

Hop along through lines of code,
I’m a bunny with a happy node.
Tokens invalidated with a joyful twist,
And integration settings no longer missed!
Through patches and tests we prance with cheer,
CodeRabbit hops to a bug-free frontier!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3e234ee and 6a1f55e.

📒 Files selected for processing (1)
  • apps/workspaces/views.py (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: pytest
🔇 Additional comments (3)
apps/workspaces/views.py (3)

4-4: LGTM! Import added as part of refactoring.

The import of post_to_integration_settings aligns with the PR objective of preventing circular imports between actions.py and tasks.py.


156-156: Consider addressing the TODO comment.

The comment suggests merging this view with ConnectXeroView. This would help reduce code duplication and centralize Xero connection management.

Would you like me to propose a refactored implementation that merges these views?


122-122:

❓ Verification inconclusive

LGTM! Verify error handling.

The call to post_to_integration_settings is correctly placed after successful Xero connection. Since this is part of error handling improvements, let's verify the error cases.

Let's check if there are any unhandled error cases in the post_to_integration_settings function:


🏁 Script executed:

#!/bin/bash
# Description: Check error handling in post_to_integration_settings
ast-grep --pattern 'def post_to_integration_settings($$$)' -l python

Length of output: 415


LGTM! Verify error handling.

The call to post_to_integration_settings is correctly positioned after the successful Xero connection and correctly passes the workspace_id. However, our initial automated search for the function’s definition did not yield clear results on how error cases are handled in its implementation. Please manually verify that post_to_integration_settings includes robust error handling (e.g., using try/except blocks or equivalent mechanisms) to ensure that any failures within that function do not inadvertently impact the overall integration flow.

  • Action: Confirm that error cases within post_to_integration_settings trigger proper alerts or fallback procedures.
✨ 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

PR description must contain a link to a ClickUp (case-insensitive)

Copy link

Tests Skipped Failures Errors Time
169 0 💤 0 ❌ 0 🔥 1m 12s ⏱️

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 (7)
tests/test_xero/test_exceptions.py (2)

6-21: Improve test function implementation.

A few suggestions to enhance the test:

  1. The db fixture is imported but not used.
  2. The test function name could be more descriptive (e.g., test_handle_xero_exceptions_invalidates_credentials).
  3. Consider verifying that the exception is propagated to ensure the decorator's behavior is fully tested.

Apply this diff to improve the test:

-def test_handle_view_exceptions(mocker, db):
+def test_handle_xero_exceptions_invalidates_credentials(mocker):
     workspace_id = 1
     task_log_id = 1
 
     mocked_invalidate_call = MagicMock()
     mocker.patch('apps.xero.exceptions.invalidate_xero_credentials', side_effect=mocked_invalidate_call)
 
     @handle_xero_exceptions(payment=False)
     def func(expense_group_id: int, task_log_id: int, xero_connection):
         raise NoPrivilegeError('Invalid Token')
 
-    func(workspace_id, task_log_id, MagicMock())
+    with pytest.raises(NoPrivilegeError, match='Invalid Token'):
+        func(workspace_id, task_log_id, MagicMock())
 
     args, _ = mocked_invalidate_call.call_args
 
     assert args[0] == workspace_id

23-31: Consider parameterizing similar test cases.

The two test cases are very similar and could be parameterized using pytest.mark.parametrize to reduce code duplication and make it easier to add more test cases.

Here's how you could refactor the tests:

+import pytest
+
+@pytest.mark.parametrize('payment,func_params', [
+    (False, {'expense_group_id': 1, 'task_log_id': 1, 'xero_connection': MagicMock()}),
+    (True, {'bill': MagicMock(), 'workspace_id': 1, 'task_log': MagicMock()}),
+])
+def test_handle_xero_exceptions_invalidates_credentials(mocker, payment, func_params):
+    workspace_id = func_params.get('workspace_id', func_params['expense_group_id'])
+
+    mocked_invalidate_call = MagicMock()
+    mocker.patch('apps.xero.exceptions.invalidate_xero_credentials', side_effect=mocked_invalidate_call)
+
+    @handle_xero_exceptions(payment=payment)
+    def func(**kwargs):
+        raise NoPrivilegeError('Invalid Token')
+
+    with pytest.raises(NoPrivilegeError, match='Invalid Token'):
+        func(**func_params)
+
+    args, _ = mocked_invalidate_call.call_args
+    assert args[0] == workspace_id
apps/workspaces/helpers.py (1)

10-31: Consider adding type hints and improving error handling.

The function implementation is good, but could benefit from:

  1. Type hints for the is_token_expired parameter
  2. More specific exception handling

Apply this diff to add type hints and improve error handling:

-def patch_integration_settings(workspace_id: int, errors: int = None, is_token_expired = None):
+def patch_integration_settings(workspace_id: int, errors: int = None, is_token_expired: bool = None):
     try:
         patch_request(url, payload, refresh_token)
-    except Exception as error:
+    except (ConnectionError, TimeoutError) as error:
         logger.error(error, exc_info=True)
+    except Exception as error:
+        logger.error(f'Unexpected error while patching integration settings for {workspace_id = }')
+        logger.error(error, exc_info=True)
tests/test_workspaces/test_actions.py (1)

9-52: Consider adding negative test cases and improving test structure.

While the test covers the main scenarios well, consider:

  1. Adding negative test cases (e.g., API failures)
  2. Using pytest parametrize for cleaner test structure

Here's how you could refactor using parametrize:

import pytest
from unittest.mock import MagicMock

@pytest.mark.django_db(databases=['default'])
@pytest.mark.parametrize('errors,is_token_expired,expected_payload', [
    (7, None, {'errors_count': 7, 'tpa_name': 'Fyle Xero Integration'}),
    (None, True, {'is_token_expired': True, 'tpa_name': 'Fyle Xero Integration'}),
    (241, True, {
        'errors_count': 241,
        'is_token_expired': True,
        'tpa_name': 'Fyle Xero Integration'
    })
])
def test_patch_integration_settings(mocker, errors, is_token_expired, expected_payload):
    workspace_id = 1
    mocked_patch = MagicMock()
    mocker.patch('apps.fyle.helpers.requests.patch', side_effect=mocked_patch)

    patch_integration_settings(
        workspace_id,
        errors=errors,
        is_token_expired=is_token_expired
    )

    _, kwargs = mocked_patch.call_args
    actual_payload = json.loads(kwargs['data'])
    assert actual_payload == expected_payload
apps/fyle/helpers.py (1)

41-60: Add type hints for consistency.

The new patch_request function should include type hints to match the style of other functions in the file.

Apply this diff to add type hints:

-def patch_request(url, body, refresh_token=None):
+def patch_request(url: str, body: dict, refresh_token: Union[str, None] = None) -> dict:
tests/test_workspaces/test_views.py (1)

131-134: Fix boolean comparison in assertion.

The assertion uses an equality comparison with False which is not Pythonic.

-    assert kwargs['is_token_expired'] == False
+    assert not kwargs['is_token_expired']
🧰 Tools
🪛 Ruff (0.8.2)

134-134: Avoid equality comparisons to False; use if not kwargs['is_token_expired']: for false checks

Replace with not kwargs['is_token_expired']

(E712)

apps/xero/tasks.py (1)

834-834: Consider consolidating error handling logic.

The same error handling pattern (logging + credential invalidation) is repeated in three locations. Consider extracting this into a helper function to maintain DRY principles.

def handle_xero_auth_error(workspace_id: int, context: str):
    """
    Handle Xero authentication error
    :param workspace_id: Workspace ID
    :param context: Context where the error occurred
    """
    logger.info(
        "Xero refresh token expired for workspace_id %s during %s",
        workspace_id,
        context
    )
    invalidate_xero_credentials(workspace_id)

Also applies to: 932-932, 963-963

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2a82e8d and 3e234ee.

📒 Files selected for processing (13)
  • apps/exceptions.py (3 hunks)
  • apps/fyle/helpers.py (1 hunks)
  • apps/mappings/actions.py (2 hunks)
  • apps/mappings/exceptions.py (3 hunks)
  • apps/workspaces/actions.py (3 hunks)
  • apps/workspaces/helpers.py (1 hunks)
  • apps/xero/exceptions.py (3 hunks)
  • apps/xero/queue.py (3 hunks)
  • apps/xero/tasks.py (4 hunks)
  • tests/test_exceptions.py (1 hunks)
  • tests/test_workspaces/test_actions.py (1 hunks)
  • tests/test_workspaces/test_views.py (2 hunks)
  • tests/test_xero/test_exceptions.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
tests/test_workspaces/test_views.py

134-134: Avoid equality comparisons to False; use if not kwargs['is_token_expired']: for false checks

Replace with not kwargs['is_token_expired']

(E712)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: pytest
🔇 Additional comments (17)
tests/test_xero/test_exceptions.py (1)

1-4: Add test case for UnsuccessfulAuthentication exception.

The AI summary mentions testing for UnsuccessfulAuthentication exception, but this test case is missing from the implementation.

Would you like me to generate the additional test case for handling the UnsuccessfulAuthentication exception?

tests/test_exceptions.py (1)

6-20: LGTM! Well-structured test for exception handling.

The test effectively validates that the handle_view_exceptions decorator properly handles UnsuccessfulAuthentication and calls invalidate_xero_credentials with the correct workspace ID.

apps/mappings/actions.py (1)

49-51: LGTM! Good error handling for authentication failures.

The addition of invalidate_xero_credentials call in the UnsuccessfulAuthentication exception handler aligns well with the PR's objective of handling token expiry.

apps/exceptions.py (2)

47-57: LGTM! Proper handling of Xero token expiry.

The code correctly invalidates Xero credentials when token-related exceptions occur, ensuring proper cleanup of expired tokens.


71-81: LGTM! Comprehensive handling of authentication failures.

The code properly handles various authentication-related exceptions by invalidating Xero credentials and returning appropriate error messages.

apps/mappings/exceptions.py (2)

59-62: LGTM! Proper handling of Xero token expiry in import exceptions.

The code correctly invalidates Xero credentials when token-related exceptions occur during imports.


118-130: LGTM! Comprehensive error handling for import exceptions v2.

The code properly handles various Xero authentication failures by invalidating credentials and updating import logs.

apps/workspaces/actions.py (2)

99-100: LGTM! Proper update of integration settings.

The code correctly updates integration settings after refreshing the Xero token.


123-128: LGTM! Proper error handling during company info retrieval.

The code correctly invalidates Xero credentials when authentication fails during company information retrieval.

apps/xero/exceptions.py (3)

20-20: LGTM!

The new imports are correctly added and align with the PR objectives for handling token expiry and integration settings updates.


48-48: LGTM!

The patch_integration_settings call is correctly placed after updating the last export details, ensuring the integration settings are updated with the latest error count.


194-201:

❓ Verification inconclusive

Verify the order of operations in error handling.

The code correctly invalidates credentials first, but consider whether setting country to None should happen before or after invalidating credentials.


🏁 Script executed:

#!/bin/bash
# Search for similar patterns in error handling
rg -A 5 "invalidate_xero_credentials.*\n.*country\s*=\s*None" || rg -A 5 "country\s*=\s*None.*\n.*invalidate_xero_credentials"

Length of output: 511


Review: Confirm the Order of Credential Invalidation vs. Country Update

The error handler currently calls invalidate_xero_credentials(workspace_id) before retrieving and modifying the XeroCredentials (setting country to None and saving the change). Please double-check whether updating the country field should occur before invalidating the credentials—in case the invalidation process resets or supersedes that update—or if the present ordering correctly reflects the intended business logic.

  • The snippet in apps/xero/exceptions.py (lines 194–201) shows:
    • First: Invalidate credentials.
    • Then: Retrieve, modify (country = None), and save the credentials.
    • Finally: Log the exception message.

If the intention is to have a clean slate before updating, consider reordering those operations; otherwise, if this sequence is deliberate, please confirm that it aligns with the overall error-handling strategy.

tests/test_workspaces/test_views.py (1)

118-119: LGTM!

The mock setup for patch_integration_settings is correctly implemented using mock.MagicMock().

apps/xero/queue.py (3)

6-6: LGTM!

The import for invalidate_xero_credentials is correctly added.


185-185: LGTM!

The credential invalidation is correctly placed in the error handling block for bill creation.


263-263: LGTM!

The credential invalidation is correctly placed in the error handling block for bank transaction creation.

apps/xero/tasks.py (1)

22-22: LGTM!

The import for invalidate_xero_credentials is correctly added.

Comment on lines +33 to +44
def invalidate_xero_credentials(workspace_id):
try:
xero_credentials = XeroCredentials.get_active_xero_credentials(workspace_id)
if xero_credentials:
if not xero_credentials.is_expired:
patch_integration_settings(workspace_id, is_token_expired=True)
xero_credentials.refresh_token = None
xero_credentials.is_expired = True
xero_credentials.save()
except XeroCredentials.DoesNotExist as error:
logger.error(f'Xero credentials not found for {workspace_id = }:', )
logger.error(error, exc_info=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

Fix error message formatting and improve error handling.

The f-string in the error message has an invalid syntax, and the error handling could be more specific.

Apply this diff to fix the issues:

 def invalidate_xero_credentials(workspace_id):
     try:
         xero_credentials = XeroCredentials.get_active_xero_credentials(workspace_id)
         if xero_credentials:
             if not xero_credentials.is_expired:
                 patch_integration_settings(workspace_id, is_token_expired=True)
             xero_credentials.refresh_token = None
             xero_credentials.is_expired = True
             xero_credentials.save()
     except XeroCredentials.DoesNotExist as error:
-        logger.error(f'Xero credentials not found for {workspace_id = }:', )
+        logger.error(f'Xero credentials not found for workspace_id: {workspace_id}')
         logger.error(error, exc_info=True)
+    except Exception as error:
+        logger.error(f'Unexpected error while invalidating Xero credentials for workspace_id: {workspace_id}')
+        logger.error(error, exc_info=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
def invalidate_xero_credentials(workspace_id):
try:
xero_credentials = XeroCredentials.get_active_xero_credentials(workspace_id)
if xero_credentials:
if not xero_credentials.is_expired:
patch_integration_settings(workspace_id, is_token_expired=True)
xero_credentials.refresh_token = None
xero_credentials.is_expired = True
xero_credentials.save()
except XeroCredentials.DoesNotExist as error:
logger.error(f'Xero credentials not found for {workspace_id = }:', )
logger.error(error, exc_info=True)
def invalidate_xero_credentials(workspace_id):
try:
xero_credentials = XeroCredentials.get_active_xero_credentials(workspace_id)
if xero_credentials:
if not xero_credentials.is_expired:
patch_integration_settings(workspace_id, is_token_expired=True)
xero_credentials.refresh_token = None
xero_credentials.is_expired = True
xero_credentials.save()
except XeroCredentials.DoesNotExist as error:
logger.error(f'Xero credentials not found for workspace_id: {workspace_id}')
logger.error(error, exc_info=True)
except Exception as error:
logger.error(f'Unexpected error while invalidating Xero credentials for workspace_id: {workspace_id}')
logger.error(error, exc_info=True)

Copy link

PR description must contain a link to a ClickUp (case-insensitive)

Copy link

Tests Skipped Failures Errors Time
169 0 💤 0 ❌ 0 🔥 1m 11s ⏱️

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

Successfully merging this pull request may close these issues.

1 participant