Skip to content

Commit

Permalink
create webhook subscription after connection is complete
Browse files Browse the repository at this point in the history
  • Loading branch information
NileshPant1999 committed Dec 15, 2023
1 parent 264889e commit b376516
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 48 deletions.
24 changes: 22 additions & 2 deletions apps/travelperk/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from django.conf import settings


from apps.travelperk.models import TravelperkCredential
from connectors.travelperk.core.client import Travelperk
from apps.travelperk.models import TravelperkCredential, TravelPerk
from connectors.travelperk import Travelperk


logger = logging.getLogger(__name__)
Expand All @@ -26,3 +26,23 @@ def __init__(self, credentials_object: TravelperkCredential, org_id: int):

credentials_object.refresh_token = self.connection.refresh_token
credentials_object.save()


def create_webhook(self, data: dict):
"""
Create Webhook in Travelperk
:param data: Webhook Data
:return: Webhook Data
"""

response = self.connection.webhooks.create(data)
if response:
TravelPerk.objects.update_or_create(
org_id=self.org_id,
defaults={
'webhook_id': response['id'],
'webhook_enabled': response['enabled']
}
)

return response
23 changes: 23 additions & 0 deletions apps/travelperk/migrations/0006_auto_20231214_1927.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 3.1.14 on 2023-12-14 19:27

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('travelperk', '0005_invoice_invoicelineitem_travelperkcredential'),
]

operations = [
migrations.AddField(
model_name='travelperk',
name='webhook_enabled',
field=models.BooleanField(help_text='If Webhook Is Enabled', null=True),
),
migrations.AddField(
model_name='travelperk',
name='webhook_subscription_id',
field=models.CharField(help_text='Webhook Subscription Id', max_length=255, null=True),
),
]
4 changes: 2 additions & 2 deletions apps/travelperk/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ class Meta:
db_table = 'travelperk_credentials'


from django.db import models

class InvoiceLineItem(models.Model):
"""
Travelperk Invoice Line Item Model
Expand Down Expand Up @@ -103,6 +101,8 @@ class TravelPerk(models.Model):
is_s3_connected = models.BooleanField(null=True, help_text='If S3 Is Connectoed')
is_travelperk_connected = models.BooleanField(null=True, help_text='If Travelperk Is Connected')
travelperk_connection_id = models.IntegerField(null=True, help_text='Travelperk Connection Id')
webhook_subscription_id = models.CharField(max_length=255, null=True, help_text='Webhook Subscription Id')
webhook_enabled = models.BooleanField(null=True, help_text='If Webhook Is Enabled')
created_at = models.DateTimeField(auto_now_add=True, help_text='Created at datetime')
updated_at = models.DateTimeField(auto_now=True, help_text='Updated at datetime')

Expand Down
65 changes: 23 additions & 42 deletions apps/travelperk/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,16 @@
from rest_framework.response import Response
from rest_framework.views import status

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json

from workato import Workato
from workato.exceptions import *

from apps.names import TRAVELPERK
from apps.orgs.models import Org
from apps.orgs.actions import create_connection_in_workato, upload_properties, post_folder, post_package
from apps.travelperk.serializers import TravelperkSerializer, TravelPerkConfigurationSerializer
from apps.travelperk.models import TravelPerk, TravelPerkConfiguration
from apps.travelperk.models import TravelPerk, TravelPerkConfiguration, TravelperkCredential
from apps.travelperk.actions import connect_travelperk
from connectors.travelperk import exceptions as travelperk_exc
from apps.travelperk.connector import TravelperkConnector

from .helpers import get_refresh_token_using_auth_code

Expand Down Expand Up @@ -225,53 +220,39 @@ class ConnectTravelperkView(generics.CreateAPIView):
"""

def post(self, request, *args, **kwargs):

try:
connector = Workato()
org = Org.objects.get(id=kwargs['org_id'])
travelperk = TravelPerk.objects.get(org_id=org.id)

refresh_token = get_refresh_token_using_auth_code(request.data.get('code'), kwargs['org_id'])

properties_payload = {
'properties': {
'TRAVELPERK_REFRESH_TOKEN': refresh_token
}
}

data = {
"input": {
"key": "***"

if refresh_token:
travelperk_credential = TravelperkCredential.objects.get(org=org)
travelperk_connection = TravelperkConnector(travelperk_credential, kwargs['org_id'])

travelperk_webhook_data = {
'name': 'travelperk webhook invoice',
'url': 'https://webhook.site/e4ac2898-209f-4dd2-88cf-738dea95ecdc',
'secret': 'some secret',
'events': [
'invoice.issued'
]
}
}

upload_properties(org.managed_user_id, properties_payload)

travelperk_connection = create_connection_in_workato(org.id, TRAVELPERK['connection'], org.managed_user_id, data)
if 'authorization_status' in travelperk_connection and travelperk_connection['authorization_status'] == 'success':
travelperk.is_connected = True
travelperk.save()

recipes = connector.recipes.get(org.managed_user_id)['result']
travelperk_configuration, _ = TravelPerkConfiguration.objects.update_or_create(
org_id=org.id,
recipe_id=recipes[0]['id'],
created_webhook = travelperk_connection.create_webhook(travelperk_webhook_data)
print('created_webhook', created_webhook)
TravelPerk.objects.update_or_create(
org=org,
defaults={
'recipe_data': recipes[0]['code'],
'is_recipe_enabled': True
'webhook_id': created_webhook['id'],
}
)
connector.recipes.post(org.managed_user_id, travelperk_configuration.recipe_id, None, 'start')

return Response(
data=travelperk_connection,
data=created_webhook,
status=status.HTTP_200_OK
)

return Response(
data='Something went wrong while connecting to travelperk',
status=status.HTTP_400_BAD_REQUEST
)

except Exception as exception:
except Exception:
error = traceback.format_exc()
logger.error(error)

Expand Down
3 changes: 1 addition & 2 deletions connectors/travelperk/apis/api_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,7 @@ def _delete_request(self, api_url: str) -> Dict:
)

if response.status_code == 200:
result = json.loads(response.text)
return result
return response.text

elif response.status_code == 400:
raise BadRequestError('Something wrong with the request body', response.text)
Expand Down

0 comments on commit b376516

Please sign in to comment.