-
Notifications
You must be signed in to change notification settings - Fork 0
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
feat: POST to integrations settings API on onboarding completion #123
Conversation
WalkthroughThis pull request introduces enhancements to integration settings and HTTP request handling across multiple files. The changes include expanding response handling in the Changes
Sequence DiagramsequenceDiagram
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
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
✨ Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
There was a problem hiding this 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:
- Adding a default value, or
- 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:
- Add a comment describing the expected value and format
- 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
📒 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.
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) |
There was a problem hiding this comment.
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:
- The except clause is too broad - consider catching specific exceptions
- 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.
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) |
There was a problem hiding this comment.
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:
- The function call could fail silently as exceptions are caught in the function. Consider handling errors at this level.
- 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') |
There was a problem hiding this comment.
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
There was a problem hiding this 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:
- Add a default value to prevent
None
when the environment variable isn't set- Validate the URL format
- 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
📒 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 10Length 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) |
There was a problem hiding this comment.
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.
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 | |
) |
427bd54
into
master
Reverted this, moving to #127 |
Clickup
https://app.clickup.com/t/86cxm0f85
Summary by CodeRabbit
Release Notes
New Features
Configuration Updates
Backend Improvements