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 #123

Merged

Conversation

JustARatherRidiculouslyLongUsername
Copy link
Contributor

@JustARatherRidiculouslyLongUsername JustARatherRidiculouslyLongUsername commented Jan 28, 2025

Clickup

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced HTTP response handling in helper functions to support both 200 and 201 status codes
    • Added integration settings posting functionality for workspaces
  • Configuration Updates

    • Introduced new environment variable for integration settings API configuration in QuickBooks Desktop project
  • Backend Improvements

    • Expanded workspace onboarding process with additional integration settings management

Copy link

coderabbitai bot commented Jan 28, 2025

Walkthrough

This pull request introduces enhancements to integration settings and HTTP request handling across multiple files. The changes include expanding response handling in the post_request function to support both 200 and 201 status codes, adding a new function post_to_integration_settings in the workspaces tasks module, and introducing a new environment variable for integration settings in the QuickBooks Desktop API project settings.

Changes

File Change Summary
apps/fyle/helpers.py Modified post_request function to return response body for both 200 and 201 HTTP status codes
apps/workspaces/serializers.py Added call to post_to_integration_settings in AdvancedSettingSerializer.create() method
apps/workspaces/tasks.py Added new post_to_integration_settings function to post integration settings for a workspace
quickbooks_desktop_api/settings.py Added new environment variable INTEGRATIONS_SETTINGS_API
quickbooks_desktop_api/tests/settings.py Added new environment variable INTEGRATIONS_SETTINGS_API

Sequence Diagram

sequenceDiagram
    participant Serializer as AdvancedSettingSerializer
    participant Tasks as WorkspaceTasks
    participant API as Integration Settings API

    Serializer->>Tasks: post_to_integration_settings(workspace_id, True)
    Tasks->>Tasks: Retrieve refresh token
    Tasks->>Tasks: Construct integration settings payload
    Tasks->>API: POST integration settings
    alt Successful Response
        API-->>Tasks: Create integration record
        Tasks-->>Serializer: Log success
    else Error
        Tasks-->>Serializer: Log error
    end
Loading

Possibly related PRs

Suggested labels

deploy, size/L

Suggested reviewers

  • ashwin1111

Poem

🐰 Hopping through code with glee,
Integration settings now set free!
HTTP responses dancing bright,
Two-oh-one joins two-hundred's might,
A rabbit's leap of tech delight! 🚀

✨ 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.

@github-actions github-actions bot added the size/S Small PR label Jan 28, 2025
Copy link

Tests Skipped Failures Errors Time
67 0 💤 0 ❌ 0 🔥 9.045s ⏱️

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: 3

🧹 Nitpick comments (4)
quickbooks_desktop_api/tests/settings.py (1)

249-249: Consider adding a default value or validation for the environment variable.

The INTEGRATIONS_SETTINGS_API environment variable is critical for the integration settings functionality. Consider either:

  1. Adding a default value, or
  2. Adding validation at startup to ensure the variable is set
-INTEGRATIONS_SETTINGS_API = os.environ.get('INTEGRATIONS_SETTINGS_API')
+INTEGRATIONS_SETTINGS_API = os.environ.get('INTEGRATIONS_SETTINGS_API') or 'http://localhost:8000/api/v1'
apps/workspaces/tasks.py (2)

175-178: Add return type hint to the function signature.

The function signature should specify its return type for better type safety.

-def post_to_integration_settings(workspace_id: int, active: bool):
+def post_to_integration_settings(workspace_id: int, active: bool) -> None:

186-186: Consider using a constant for the datetime format string.

The datetime format string is hardcoded. Consider moving it to a constant for better maintainability.

+DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
+
 def post_to_integration_settings(workspace_id: int, active: bool):
     # ...
-    'connected_at': datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
+    'connected_at': datetime.now().strftime(DATETIME_FORMAT)
quickbooks_desktop_api/settings.py (1)

271-271: Add validation and documentation for the new environment variable.

While the implementation is secure using environment variables, consider these improvements:

  1. Add a comment describing the expected value and format
  2. Add URL validation or provide a default value to prevent None
+# API endpoint for integration settings (e.g., https://api.example.com/settings)
-INTEGRATIONS_SETTINGS_API = os.environ.get('INTEGRATIONS_SETTINGS_API')
+INTEGRATIONS_SETTINGS_API = os.environ.get('INTEGRATIONS_SETTINGS_API', '').strip()
+if not INTEGRATIONS_SETTINGS_API:
+    raise ValueError('INTEGRATIONS_SETTINGS_API environment variable is required')
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4565138 and 8f9fe42.

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

31-31: LGTM! Good practice to accept 201 status code.

The modification to accept both 200 and 201 status codes aligns with HTTP standards, where 201 is the appropriate response code for successful POST requests that create new resources.

Comment on lines +189 to +195
try:
post_request(url, json.dumps(payload), refresh_token)
org_id = Workspace.objects.get(id=workspace_id).org_id
logger.info(f'New integration record: Fyle Quickbooks Desktop (IIF) Integration (ACCOUNTING) | {workspace_id = } | {org_id = }')

except Exception as error:
logger.error(error)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling and logging.

The error handling could be improved in several ways:

  1. The except clause is too broad - consider catching specific exceptions
  2. The error log should include the workspace_id for better debugging
     try:
         post_request(url, json.dumps(payload), refresh_token)
         org_id = Workspace.objects.get(id=workspace_id).org_id
         logger.info(f'New integration record: Fyle Quickbooks Desktop (IIF) Integration (ACCOUNTING) | {workspace_id = } | {org_id = }')
 
-    except Exception as error:
-        logger.error(error)
+    except requests.RequestException as error:
+        logger.error(f'Failed to post integration settings for workspace {workspace_id}: {error}')
+    except Workspace.DoesNotExist:
+        logger.error(f'Workspace {workspace_id} not found while posting integration settings')
+    except Exception as error:
+        logger.error(f'Unexpected error while posting integration settings for workspace {workspace_id}: {error}')
📝 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
try:
post_request(url, json.dumps(payload), refresh_token)
org_id = Workspace.objects.get(id=workspace_id).org_id
logger.info(f'New integration record: Fyle Quickbooks Desktop (IIF) Integration (ACCOUNTING) | {workspace_id = } | {org_id = }')
except Exception as error:
logger.error(error)
try:
post_request(url, json.dumps(payload), refresh_token)
org_id = Workspace.objects.get(id=workspace_id).org_id
logger.info(f'New integration record: Fyle Quickbooks Desktop (IIF) Integration (ACCOUNTING) | {workspace_id = } | {org_id = }')
except requests.RequestException as error:
logger.error(f'Failed to post integration settings for workspace {workspace_id}: {error}')
except Workspace.DoesNotExist:
logger.error(f'Workspace {workspace_id} not found while posting integration settings')
except Exception as error:
logger.error(f'Unexpected error while posting integration settings for workspace {workspace_id}: {error}')

@@ -225,5 +226,5 @@ def create(self, validated_data):
workspace.onboarding_state = 'COMPLETE'
workspace.save()
async_task('apps.workspaces.tasks.async_create_admin_subcriptions', workspace_id)

post_to_integration_settings(workspace_id, True)
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Add error handling for the integration settings API call

The race condition concern can be dismissed as the integration settings update is independent of admin subscriptions. However, the error handling concern remains valid:

  • Consider wrapping post_to_integration_settings call in a try-except block to handle potential API failures gracefully
  • Log any errors to help with debugging integration issues
  • Optionally, notify the user if the integration settings update fails
🔗 Analysis chain

Consider error handling and execution order.

Two potential issues to consider:

  1. The function call could fail silently as exceptions are caught in the function. Consider handling errors at this level.
  2. The function is called after an async task which could lead to race conditions if the integration settings depend on the admin subscriptions.

Run this script to check if there are any dependencies between admin subscriptions and integration settings:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any code that shows dependencies between admin subscriptions and integration settings
rg -l "admin.*subscriptions.*integration.*settings|integration.*settings.*admin.*subscriptions" --type py

Length of output: 107


Script:

#!/bin/bash
# Find implementation of post_to_integration_settings
ast-grep --pattern 'def post_to_integration_settings'

# Find the async task call context
rg -B 5 -A 5 "post_to_integration_settings\(workspace_id, True\)" --type py

# Find any integration settings related code
rg "integration.*settings" --type py

Length of output: 1153

@@ -268,6 +268,7 @@
FYLE_TOKEN_URI = os.environ.get('FYLE_TOKEN_URI')
FYLE_CLIENT_ID = os.environ.get('FYLE_CLIENT_ID')
FYLE_CLIENT_SECRET = os.environ.get('FYLE_CLIENT_SECRET')
INTEGRATIONS_SETTINGS_API = os.environ.get('INTEGRATIONS_SETTINGS_API')
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Environment variable INTEGRATIONS_SETTINGS_API needs proper documentation and default handling

The variable is used in production code but lacks proper setup guidance:

  • Add the variable to environment example files (.env.example)
  • Consider adding a default value or explicit error handling in os.environ.get('INTEGRATIONS_SETTINGS_API')
  • Document the expected value format since it's used to construct API URLs in apps/workspaces/tasks.py
🔗 Analysis chain

Verify environment variable setup across environments.

Ensure the new environment variable is properly configured.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if INTEGRATIONS_SETTINGS_API is documented and configured

# Check if variable is documented in README or similar files
echo "Checking documentation for INTEGRATIONS_SETTINGS_API..."
fd -t f -e md -e env -e env.example | xargs rg -i "INTEGRATIONS_SETTINGS_API"

# Check if variable is used in the codebase
echo "Checking usage in codebase..."
rg "INTEGRATIONS_SETTINGS_API" -t python

Length of output: 339


Script:

#!/bin/bash
# Search for the environment variable in Python files
echo "Checking Python files..."
rg "INTEGRATIONS_SETTINGS_API" -g "*.py"

# Search in environment and configuration files
echo -e "\nChecking configuration files..."
fd -e env -e env.example -e env.sample -e yaml -e yml | xargs rg -i "INTEGRATIONS_SETTINGS_API"

# Search for related settings patterns
echo -e "\nChecking for related patterns..."
rg "SETTINGS_API|INTEGRATION.*API" -g "*.py" -g "*.env*" -g "*.yml" -g "*.yaml"

Length of output: 1071

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)
quickbooks_desktop_api/tests/settings.py (1)

249-249: Consider adding a default value for the environment variable.

To prevent potential NoneType errors if the environment variable is not set, consider providing a default value or adding validation.

-INTEGRATIONS_SETTINGS_API = os.environ.get('INTEGRATIONS_SETTINGS_API')
+INTEGRATIONS_SETTINGS_API = os.environ.get('INTEGRATIONS_SETTINGS_API', 'http://localhost:8000')
apps/workspaces/tasks.py (2)

186-186: Use ISO format method for datetime formatting.

Instead of using a hardcoded format string, use the built-in isoformat() method for consistent ISO 8601 formatting.

-        'connected_at': datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
+        'connected_at': datetime.now(timezone.utc).isoformat()

194-195: Enhance error logging with more context.

Include workspace details in the error log to help with debugging.

-        logger.error(error)
+        logger.error(
+            'Failed to post integration settings for workspace %d: %s',
+            workspace_id,
+            error
+        )
quickbooks_desktop_api/settings.py (1)

271-271: Add default value and validation for the integration settings API URL.

Consider these improvements for robustness:

  1. Add a default value to prevent None when the environment variable isn't set
  2. Validate the URL format
  3. Document the purpose and expected format of this setting
-INTEGRATIONS_SETTINGS_API = os.environ.get('INTEGRATIONS_SETTINGS_API')
+# URL for the Integration Settings API endpoint
+INTEGRATIONS_SETTINGS_API = os.environ.get('INTEGRATIONS_SETTINGS_API', 'http://localhost:8000/api/integrations/settings')
+
+# Validate URL format
+if INTEGRATIONS_SETTINGS_API and not INTEGRATIONS_SETTINGS_API.startswith(('http://', 'https://')):
+    raise ValueError('INTEGRATIONS_SETTINGS_API must be a valid HTTP(S) URL')
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4565138 and 8f9fe42.

📒 Files selected for processing (5)
  • apps/fyle/helpers.py (1 hunks)
  • apps/workspaces/serializers.py (2 hunks)
  • apps/workspaces/tasks.py (1 hunks)
  • quickbooks_desktop_api/settings.py (1 hunks)
  • quickbooks_desktop_api/tests/settings.py (1 hunks)
🔇 Additional comments (2)
apps/fyle/helpers.py (1)

31-31: LGTM! Good enhancement to handle resource creation responses.

The condition now correctly handles both 200 (OK) and 201 (Created) status codes, following HTTP standards.

quickbooks_desktop_api/settings.py (1)

271-271: Verify security considerations for the new API integration.

Let's check the usage patterns and security configurations for this new integration:

✅ Verification successful

Security implementation for integration settings API appears adequate

The integration is properly secured with:

  • Bearer token authentication
  • Standard Django security middleware stack
  • Non-sensitive data handling
  • Proper request headers
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze security considerations for the new integration settings API

# Check for usage patterns and potential security issues
echo "Checking usage patterns and security configurations..."

# 1. Find all references to INTEGRATIONS_SETTINGS_API
echo "Files referencing INTEGRATIONS_SETTINGS_API:"
rg "INTEGRATIONS_SETTINGS_API"

# 2. Check for proper SSL/HTTPS usage in production settings
echo -e "\nChecking for SSL/HTTPS enforcement:"
rg -B2 -A2 "SECURE_SSL_REDIRECT|SECURE_PROXY_SSL_HEADER|SECURE_HSTS"

# 3. Look for request handling with this API
echo -e "\nAnalyzing API request patterns:"
rg -B2 -A2 "requests?.post.*INTEGRATIONS_SETTINGS_API"

# 4. Check for sensitive data handling
echo -e "\nChecking sensitive data handling:"
rg -B2 -A2 "\.post.*INTEGRATIONS_SETTINGS_API.*data"

Length of output: 997


Script:

#!/bin/bash

# Get context around the API usage in tasks.py
echo "Checking API usage context in tasks.py:"
rg -B10 -A10 "INTEGRATIONS_SETTINGS_API" "apps/workspaces/tasks.py"

# Check for SSL configurations in common Django settings
echo -e "\nChecking SSL configurations in settings files:"
rg "SECURE_|SSL_|HTTPS" "quickbooks_desktop_api/settings.py"

# Look for HTTP client configurations
echo -e "\nChecking HTTP client configurations:"
rg -B3 -A3 "requests\.(get|post|put|patch|delete).*INTEGRATIONS_SETTINGS_API" .
rg -B3 -A3 "verify\s*=\s*(False|True)" .

Length of output: 1352


Script:

#!/bin/bash

# Check for post_request implementation
echo "Looking for post_request implementation:"
rg -B5 -A10 "def post_request" .

# Check for middleware and request handling configurations
echo -e "\nChecking middleware configurations:"
rg "MIDDLEWARE" "quickbooks_desktop_api/settings.py" -A 10

Length of output: 1676

@@ -225,5 +226,5 @@ def create(self, validated_data):
workspace.onboarding_state = 'COMPLETE'
workspace.save()
async_task('apps.workspaces.tasks.async_create_admin_subcriptions', workspace_id)

post_to_integration_settings(workspace_id, True)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for integration settings post.

Consider wrapping the call in a try-except block to prevent onboarding completion from failing if the integration settings post fails.

-            post_to_integration_settings(workspace_id, True)
+            try:
+                post_to_integration_settings(workspace_id, True)
+            except Exception as error:
+                logger.error(
+                    'Failed to post integration settings during onboarding completion for workspace %d: %s',
+                    workspace_id,
+                    error
+                )
📝 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
post_to_integration_settings(workspace_id, True)
try:
post_to_integration_settings(workspace_id, True)
except Exception as error:
logger.error(
'Failed to post integration settings during onboarding completion for workspace %d: %s',
workspace_id,
error
)

@JustARatherRidiculouslyLongUsername
Copy link
Contributor Author

Reverted this, moving to #127

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.

3 participants