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-settings-api on export errors #712

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

Conversation

JustARatherRidiculouslyLongUsername
Copy link
Contributor

@JustARatherRidiculouslyLongUsername JustARatherRidiculouslyLongUsername commented Feb 4, 2025

Description

Send a PATCH request to integrations-settings-api and update the integrations table to record all integration errors. This will be used in the admin tasks page to show a task to resolve these errors

Clickup

https://app.clickup.com/t/86cxhftgj

Summary by CodeRabbit

  • New Features

    • Introduced a new, partial update mechanism for integration settings that allows for more precise modifications.
    • Enhanced the system’s response to export errors by automatically fine-tuning integration settings for improved stability and performance.
    • Added detailed task logging for various financial operations, improving tracking capabilities.
  • Tests

    • Introduced a test to validate the behavior of the update mechanism when processing failed task logs.

Copy link

coderabbitai bot commented Feb 4, 2025

Walkthrough

This pull request introduces new patch functionalities. A new function, patch_request, is added in apps/fyle/helpers.py to support HTTP PATCH requests with optional refresh token handling. Additionally, a new function, patch_integration_settings, is implemented in apps/workspaces/tasks.py to update integration settings using patch requests, incorporating error logging. The update_last_export_details function in apps/netsuite/actions.py now calls the new patch function to handle integration updates post-export. A new logging structure for task statuses is also introduced in the test fixtures.

Changes

File(s) Change Summary
apps/fyle/helpers.py Added new patch_request function to send HTTP PATCH requests with optional refresh token for authorization headers.
apps/workspaces/tasks.py Added new patch_integration_settings function that retrieves the refresh token, constructs the API URL, and logs errors on failure.
apps/netsuite/actions.py Imported patch_integration_settings and updated update_last_export_details to call it, passing workspace ID and error count.
tests/test_netsuite/fixtures.py Added task_logs section in the data dictionary for enhanced logging of task statuses during financial operations.
tests/test_netsuite/test_actions.py Introduced test_update_last_export_details to validate behavior of update_last_export_details with mock task logs.

Suggested labels

deploy, size/XL

Suggested reviewers

  • ruuushhh
  • Hrishabh17

Poem

I'm a little rabbit, hopping through the code,
Found a patch so neat on this digital road!
With patch_request and settings in stride,
We update with grace and a bunny-like pride.
Hoppin' in code, side by side!
🐇✨

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ 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

github-actions bot commented Feb 4, 2025

Tests Skipped Failures Errors Time
236 0 💤 0 ❌ 0 🔥 23.818s ⏱️

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/fyle/helpers.py (1)

100-122: LGTM! Consider refactoring to reduce code duplication.

The patch_request function is well implemented, but there's significant code duplication with the post_request function. Consider refactoring both functions to use a common helper.

Here's a suggested refactoring:

+def _make_request(method, url, body, refresh_token=None):
+    """
+    Create a HTTP request.
+    """
+    access_token = None
+    api_headers = {
+        'Content-Type': 'application/json',
+    }
+    if refresh_token:
+        access_token = get_access_token(refresh_token)
+        api_headers['Authorization'] = 'Bearer {0}'.format(access_token)
+
+    response = getattr(requests, method)(
+        url,
+        headers=api_headers,
+        data=json.dumps(body)
+    )
+
+    if response.status_code in [200, 201]:
+        return json.loads(response.text)
+    else:
+        raise Exception(response.text)
+
 def post_request(url, body, refresh_token=None):
-    """
-    Create a HTTP post request.
-    """
-    access_token = None
-    api_headers = {
-        'Content-Type': 'application/json',
-    }
-    if refresh_token:
-        access_token = get_access_token(refresh_token)
-
-        api_headers['Authorization'] = 'Bearer {0}'.format(access_token)
-
-    response = requests.post(
-        url,
-        headers=api_headers,
-        data=json.dumps(body)
-    )
-
-    if response.status_code in [200, 201]:
-        return json.loads(response.text)
-    else:
-        raise Exception(response.text)
+    return _make_request('post', url, body, refresh_token)

 def patch_request(url, body, refresh_token=None):
-    """
-    Create a HTTP patch request.
-    """
-    access_token = None
-    api_headers = {
-        'Content-Type': 'application/json',
-    }
-    if refresh_token:
-        access_token = get_access_token(refresh_token)
-
-        api_headers['Authorization'] = 'Bearer {0}'.format(access_token)
-
-    response = requests.patch(
-        url,
-        headers=api_headers,
-        data=json.dumps(body)
-    )
-
-    if response.status_code in [200, 201]:
-        return json.loads(response.text)
-    else:
-        raise Exception(response.text)
+    return _make_request('patch', url, body, refresh_token)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a8c8d49 and 8988de2.

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

5-5: LGTM! The integration of error logging is well placed.

The patch_integration_settings call is appropriately placed after saving the last_export_detail, ensuring that error counts are updated after processing is complete.

Also applies to: 26-26

apps/workspaces/tasks.py (1)

10-10: LGTM! Well-structured error logging implementation.

The patch_integration_settings function is well implemented with proper error handling and logging. The function correctly retrieves the refresh token and constructs the payload for updating integration errors.

Also applies to: 231-245

@github-actions github-actions bot added size/M Medium PR and removed size/S Small PR labels Feb 4, 2025
Copy link

github-actions bot commented Feb 4, 2025

Tests Skipped Failures Errors Time
237 0 💤 0 ❌ 0 🔥 23.571s ⏱️

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 (4)
tests/test_netsuite/test_actions.py (3)

3-3: Remove unused import.

The ANY import from unittest.mock is not used in the test file.

-from unittest.mock import ANY, MagicMock
+from unittest.mock import MagicMock
🧰 Tools
🪛 Ruff (0.8.2)

3-3: unittest.mock.ANY imported but unused

Remove unused import: unittest.mock.ANY

(F401)


9-14: LGTM! Clear and descriptive docstring.

The docstring effectively explains the test's purpose and expected behavior.

Remove trailing whitespace in the docstring:

-    should do a patch request to integrations settings api to 
+    should do a patch request to integrations settings api to

16-34: Consider enhancing test coverage.

While the test effectively verifies the payload, consider adding these assertions to make it more comprehensive:

  1. Verify the URL and headers of the patch request
  2. Assert that LastExportDetail was updated correctly
  3. Verify that all TaskLogs were processed

Here's how you could enhance the test:

 update_last_export_details(workspace_id)

 failed_count = len([i for i in mock_task_logs if i['status'] in ('FAILED', 'FATAL')])
 expected_payload = {'errors_count': failed_count, 'tpa_name': 'Fyle Netsuite Integration'}

 _, kwargs =  mocked_patch.call_args
+url = kwargs['url']
 actual_payload = json.loads(kwargs['data'])

 assert actual_payload == expected_payload
+assert url == 'https://integrations-settings.fyle.tech/api/workspaces/1/integrations'
+assert kwargs['headers'] == {'Content-Type': 'application/json'}
+
+# Verify LastExportDetail was updated
+last_export = LastExportDetail.objects.get(workspace_id=workspace_id)
+assert last_export.last_exported_at is not None
+
+# Verify all TaskLogs were processed
+assert TaskLog.objects.filter(workspace_id=workspace_id).count() == len(mock_task_logs)
tests/test_netsuite/fixtures.py (1)

7666-7687: LGTM! The task logs data structure is well-organized.

The task logs mock data covers key scenarios including both successful and failed operations.

Consider adding more metadata fields that could be useful for debugging like:

  • timestamp
  • error message/details
  • user/context info
  • correlation IDs
 'task_logs': [
     {
         'type': 'CREATING_BILL',
-        'status': 'FAILED'
+        'status': 'FAILED',
+        'timestamp': '2025-02-10T10:00:00Z',
+        'error_details': 'Connection timeout',
+        'user': 'test_user',
+        'correlation_id': 'abc-123'
     },
     ...
 ]
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8988de2 and 1c854c9.

📒 Files selected for processing (2)
  • tests/test_netsuite/fixtures.py (1 hunks)
  • tests/test_netsuite/test_actions.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
tests/test_netsuite/test_actions.py

3-3: unittest.mock.ANY imported but unused

Remove unused import: unittest.mock.ANY

(F401)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: pytest

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

Successfully merging this pull request may close these issues.

2 participants