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: POST to integrations settings API on onboarding completion #243

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

Conversation

JustARatherRidiculouslyLongUsername
Copy link
Contributor

@JustARatherRidiculouslyLongUsername JustARatherRidiculouslyLongUsername commented Jan 31, 2025

Clickup

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced HTTP response handling to accept both 200 and 201 status codes as successful.
    • Added integration settings post-trigger for workspace advanced settings.
    • Introduced a script for backfilling integration settings for completed workspaces.
  • Configuration

    • Introduced new environment variable INTEGRATIONS_SETTINGS_API for integration settings configuration.
  • Backend Improvements

    • Implemented additional logging and error handling for integration settings processing.

These changes enhance system flexibility and integration capabilities with minimal user-facing impact.

Copy link

coderabbitai bot commented Jan 31, 2025

Walkthrough

The pull request introduces enhancements to the workspace integration settings and HTTP request handling. A modification in the Fyle helpers expands successful HTTP response criteria, while the workspaces module adds a new trigger for posting integration settings. The changes include updating the post_request function to accept both 200 and 201 status codes, adding a new method to post integration settings, and introducing a new environment variable for configuration.

Changes

File Change Summary
apps/fyle/helpers.py Modified post_request function to accept both 200 and 201 HTTP status codes as successful responses
apps/workspaces/serializers.py Added call to AdvancedSettingsTriggers.post_to_integration_settings() after workspace onboarding state update
apps/workspaces/triggers.py Added new imports and post_to_integration_settings() static method to AdvancedSettingsTriggers class
sage_desktop_api/settings.py Introduced new environment variable INTEGRATIONS_SETTINGS_API
sage_desktop_api/tests/settings.py Added INTEGRATIONS_SETTINGS_API environment variable

Possibly related PRs

  • feat: backfill integration records #244: The changes in the main PR are directly related to the modifications in the post_to_integration_settings method, which is invoked in both the main PR and the retrieved PR's script for processing workspaces.

Suggested reviewers

  • ruuushhh

Poem

🐰 Hopping through code with glee,
Integration settings now set free!
Status codes dance, 200 and 201,
Workspace triggers, a new journey's begun!
Rabbit's code hops with might and main! 🚀


📜 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 d029a7d and fda37ef.

📒 Files selected for processing (2)
  • apps/workspaces/triggers.py (2 hunks)
  • scripts/python/002_backfill_integrations.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • scripts/python/002_backfill_integrations.py
  • apps/workspaces/triggers.py

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

Tests Skipped Failures Errors Time
157 0 💤 0 ❌ 0 🔥 12.355s ⏱️

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 (3)
apps/workspaces/triggers.py (2)

16-17: Consider using getLogger with name

The logger configuration could be improved by using __name__ instead of hardcoding the logger name.

-logger = logging.getLogger(__name__)
-logger.level = logging.INFO
+logger = logging.getLogger(__name__)

Note: Let the logging configuration in settings.py handle the log level.


80-101: Add error details to log message

The error handling could be improved by including more details in the error log.

         except Exception as error:
-            logger.error(error)
+            logger.error('Failed to post integration settings for workspace %s - %s', workspace_id, str(error))

Also, consider adding type hints for better code maintainability:

     @staticmethod
-    def post_to_integration_settings(workspace_id: int, active: bool):
+    def post_to_integration_settings(workspace_id: int, active: bool) -> None:
apps/workspaces/serializers.py (1)

429-429: Consider handling potential exceptions

The call to post_to_integration_settings could fail, but the exception handling is delegated to the trigger method. Consider wrapping this call in a try-except block to ensure workspace completion isn't affected by integration settings failures.

             workspace.save()
             async_task('apps.workspaces.tasks.async_create_admin_subcriptions', workspace.id)
-            AdvancedSettingsTriggers.post_to_integration_settings(workspace_id, True)
+            try:
+                AdvancedSettingsTriggers.post_to_integration_settings(workspace_id, True)
+            except Exception as error:
+                logger.error('Failed to post integration settings during workspace completion: %s', str(error))
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 70bedcd and 848e22a.

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

181-181: LGTM!

The addition of the INTEGRATIONS_SETTINGS_API environment variable is appropriate and follows the existing pattern in the settings file.

sage_desktop_api/settings.py (1)

259-259: LGTM!

The addition of the INTEGRATIONS_SETTINGS_API environment variable is consistent with the test settings and follows the project's environment variable pattern.

apps/fyle/helpers.py (1)

129-129: LGTM! The status code check enhancement is appropriate.

The change to accept both 200 (OK) and 201 (Created) status codes is a good improvement, as it properly handles the standard HTTP response codes for successful POST requests. This aligns well with the PR's objective of posting to the integrations settings API.

}

try:
post_request(url, json.dumps(payload), refresh_token)
Copy link
Contributor

Choose a reason for hiding this comment

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

we have update post_request behaviour
Remove json.dumps it is handled inside post_request

Copy link

github-actions bot commented Feb 3, 2025

Tests Skipped Failures Errors Time
157 0 💤 0 ❌ 0 🔥 12.979s ⏱️

* feat: backfill integration records

* fix: add error handling and fail count to output
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 (4)
scripts/python/002_backfill_integrations.py (3)

1-7: Add docstring and type hints for better code documentation.

Consider adding a module-level docstring explaining the purpose of this script and type hints for better code maintainability.

+"""
+Backfill script to post integration settings for workspaces with completed onboarding.
+
+This script processes all workspaces with 'COMPLETE' onboarding state and posts their
+integration settings to the integration settings API.
+"""
 import logging
 from apps.workspaces.models import Workspace
 from apps.workspaces.triggers import AdvancedSettingsTriggers

10-21: Consider implementing batch processing for better performance.

For large datasets, processing all workspaces at once could be memory-intensive. Consider implementing batch processing.

-workspaces = Workspace.objects.filter(onboarding_state='COMPLETE')
-for workspace in workspaces:
+BATCH_SIZE = 100
+offset = 0
+
+while True:
+    workspaces = Workspace.objects.filter(
+        onboarding_state='COMPLETE'
+    ).order_by('id')[offset:offset + BATCH_SIZE]
+    
+    if not workspaces:
+        break
+        
+    for workspace in workspaces:
         try:
             logger.info(f"Processing workspace: {workspace.id} | {workspace.name}")
             AdvancedSettingsTriggers.post_to_integration_settings(workspace.id, True)
             processed += 1
         except Exception as e:
             failed += 1
             logger.error(
                 f"Failed to process workspace {workspace.id}: {str(e)}",
                 exc_info=True
             )
+    
+    offset += BATCH_SIZE

23-28: Add more detailed logging for better observability.

The summary could include more details about the failures and processing time.

+start_time = datetime.now()
 logger.info(
 f"""
 Completed backfill. Total: {workspaces.count()}
 Processed: {processed}, Failed: {failed}
+Time taken: {datetime.now() - start_time}
+Success rate: {(processed / workspaces.count() * 100):.2f}%
 """
 )
apps/workspaces/triggers.py (1)

80-102: Enhance error handling and documentation.

The method could benefit from:

  1. More specific error handling
  2. Type hints in docstring
  3. Constants for hardcoded values
     @staticmethod
     def post_to_integration_settings(workspace_id: int, active: bool):
         """
         Post to integration settings
+
+        Args:
+            workspace_id (int): The ID of the workspace
+            active (bool): Flag indicating if the integration is active
+
+        Raises:
+            FyleCredential.DoesNotExist: If credentials are not found
+            requests.RequestException: If the API request fails
         """
+        INTEGRATION_TYPE = 'ACCOUNTING'
+        INTEGRATION_NAME = 'Fyle Sage 300 Integration'
+
         refresh_token = FyleCredential.objects.get(workspace_id=workspace_id).refresh_token
         url = '{}/integrations/'.format(settings.INTEGRATIONS_SETTINGS_API)
         payload = {
             'tpa_id': settings.FYLE_CLIENT_ID,
-            'tpa_name': 'Fyle Sage 300 Integration',
-            'type': 'ACCOUNTING',
+            'tpa_name': INTEGRATION_NAME,
+            'type': INTEGRATION_TYPE,
             'is_active': active,
             'connected_at': datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
         }

         try:
             post_request(url, payload, refresh_token)
             org_id = Workspace.objects.get(id=workspace_id).org_id
             logger.info(f'New integration record: {INTEGRATION_NAME} ({INTEGRATION_TYPE}) | {workspace_id = } | {org_id = }')

-        except Exception as error:
+        except FyleCredential.DoesNotExist as error:
+            logger.error(f'Credentials not found for workspace {workspace_id}: {error}')
+            raise
+        except requests.RequestException as error:
             logger.error(error)
+            raise
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f2da24c and d029a7d.

📒 Files selected for processing (2)
  • apps/workspaces/triggers.py (2 hunks)
  • scripts/python/002_backfill_integrations.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
apps/workspaces/triggers.py

2-2: json imported but unused

Remove unused import: json

(F401)

Comment on lines 1 to 2
from datetime import datetime
import json
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove unused import.

The json import is not being used in this file.

 from datetime import datetime
-import json
 import logging
📝 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
from datetime import datetime
import json
from datetime import datetime
import logging
🧰 Tools
🪛 Ruff (0.8.2)

2-2: json imported but unused

Remove unused import: json

(F401)

Copy link

github-actions bot commented Feb 3, 2025

Tests Skipped Failures Errors Time
157 0 💤 0 ❌ 0 🔥 12.629s ⏱️

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.

2 participants