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

Update and Create Employee on Webhook trigger from bamboohr #124

Merged
merged 9 commits into from
Jan 3, 2024
Merged
18 changes: 18 additions & 0 deletions apps/bamboohr/migrations/0007_bamboohr_webhook_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 3.1.14 on 2024-01-02 16:10

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('bamboohr', '0006_bamboohr_is_credentials_expired'),
]

operations = [
migrations.AddField(
model_name='bamboohr',
name='webhook_id',
field=models.IntegerField(help_text='ID of the webhook created by BambooHr', null=True),
),
]
1 change: 1 addition & 0 deletions apps/bamboohr/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class BambooHr(models.Model):
updated_at = models.DateTimeField(auto_now=True, help_text='Updated at datetime')
employee_exported_at = models.DateTimeField(auto_now_add=True, help_text='Employee exported to Fyle at datetime')
is_credentials_expired = models.BooleanField(default=False, help_text='BambooHr Credential Status')
webhook_id = models.IntegerField(null=True, help_text='ID of the webhook created by BambooHr')

class Meta:
db_table = 'bamboohr'
Expand Down
30 changes: 28 additions & 2 deletions apps/bamboohr/signals.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,39 @@

from django.db.models.signals import pre_save
from django.db.models.signals import pre_save, post_save, pre_delete
from django.dispatch import receiver
from admin_settings.settings import API_URL

from workato import Workato
from apps.bamboohr.models import BambooHrConfiguration

from bamboosdk.bamboohrsdk import BambooHrSDK
from apps.bamboohr.models import BambooHrConfiguration, BambooHr
from apps.orgs.models import Org

@receiver(pre_save, sender=BambooHrConfiguration)
def run_pre_save_configuration_triggers(sender, instance: BambooHrConfiguration, **kwargs):
connector = Workato()
org = Org.objects.get(id=instance.org_id)
connector.recipes.post(org.managed_user_id, instance.recipe_id, None, 'stop')


@receiver(post_save, sender=BambooHr)
def run_post_save_bamboohr_triggers(sender, instance: BambooHr, **kwargs):

bamboohrsdk = BambooHrSDK(api_token=instance.api_token, sub_domain=instance.sub_domain)
Copy link
Contributor

Choose a reason for hiding this comment

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

do all these only when webhook_id is null


webhook_payload = {
'postFields': {
'firstName': 'firstName',
'lastName': 'lastName',
'department': 'department',
'workEmail': 'workEmail',
'status': 'status'
},
'name': instance.org.name,
'monitorFields': ['firstName', 'lastName', 'department', 'workEmail', 'status'],
'url': API_URL + f'/orgs/{instance.org.id}/bamboohr/webhook_callback/',
'format': 'json'
}

response = bamboohrsdk.webhook.post(payload=webhook_payload)
BambooHr.objects.filter(id=instance.id).update(webhook_id=int(response['id']))
28 changes: 28 additions & 0 deletions apps/bamboohr/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,31 @@ def refresh_employees(org_id: int, user: User):
bambooHrImporter = BambooHrEmployeeImport(org_id=org_id, user=user)
bambooHrImporter.sync_employees()

def update_employee(org_id: int, user: User, payload: dict):

"""
Update employee in fyle when employee in Bamboohr is added or updated
"""
bamboohr = BambooHr.objects.get(org_id__in=[org_id], is_credentials_expired=False)
bamboohr_importer = BambooHrEmployeeImport(org_id=org_id, user=user)

employee_payload = {'employees': []}
payload = payload['employees'][0]
employee = {}
employee['id'] = payload['id']
employee['firstName'] = payload['fields']['firstName']['value']
employee['lastName'] = payload['fields']['lastName']['value']
for field in payload['changedFields']:
employee[field] = payload['fields'][field]['value']

employee_payload['employees'].append(employee)

bamboohr_importer.upsert_employees(employees=employee_payload)

hrms_employees = DestinationAttribute.objects.filter(
attribute_type='EMPLOYEE',
org_id=org_id,
updated_at__gte=bamboohr.employee_exported_at,
).order_by('value', 'id')
bamboohr_importer.import_departments(hrms_employees=hrms_employees)
bamboohr_importer.fyle_employee_import(hrms_employees=hrms_employees)
3 changes: 2 additions & 1 deletion apps/bamboohr/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from django.urls import path

from .views import PostFolder, PostPackage, BambooHrConnection, BambooHrView, BambooHrConfigurationView, \
DisconnectView, SyncEmployeesView, HealthCheck
DisconnectView, SyncEmployeesView, HealthCheck, WebhookCallbackAPIView

app_name = 'bamboohr'

urlpatterns = [
path('webhook_callback/', WebhookCallbackAPIView.as_view(), name='webhook-callback'),
path('health_check/', HealthCheck.as_view(), name='health-check'),
path('', BambooHrView.as_view(), name='bamboohr'),
path('packages/', PostPackage.as_view(), name='package'),
Expand Down
35 changes: 21 additions & 14 deletions apps/bamboohr/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,24 @@ def get(self, request, *args, **kwargs):
status=status.HTTP_404_NOT_FOUND
)


class WebhookCallbackAPIView(generics.CreateAPIView):

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

org_id = kwargs['org_id']
user = self.request.user
payload = request.data

async_task('apps.bamboohr.tasks.update_employee', org_id, user, payload)

return Response(
{
'status': 'success'
},
status=status.HTTP_201_CREATED
)

class BambooHrView(generics.ListAPIView):
serializer_class = BambooHrSerializer

Expand Down Expand Up @@ -195,17 +213,11 @@ class DisconnectView(generics.CreateAPIView):

def post(self, request, *args, **kwargs):
try:
configuration = BambooHrConfiguration.objects.get(org__id=kwargs['org_id'])
bamboohr = BambooHr.objects.filter(org__id=kwargs['org_id']).first()

connection = disconnect_bamboohr(kwargs['org_id'], configuration, bamboohr)

# in case of an error response
if isinstance(connection, Response):
return connection

bambamboohrsdk = BambooHrSDK(api_token=bamboohr.api_token, sub_domain=bamboohr.sub_domain)
response = bambamboohrsdk.webhook.delete(id=bamboohr.webhook_id)
return Response(
data=connection,
data=response,
status=status.HTTP_200_OK
)
except BambooHr.DoesNotExist:
Expand All @@ -215,11 +227,6 @@ def post(self, request, *args, **kwargs):
},
status = status.HTTP_404_NOT_FOUND
)
except BambooHrConfiguration.DoesNotExist:
return Response(
data={'message': 'BambooHr Configuration does not exist for this Workspace'},
status=status.HTTP_404_NOT_FOUND
)


class SyncEmployeesView(generics.UpdateAPIView):
Expand Down
3 changes: 1 addition & 2 deletions bamboosdk/api/api_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,7 @@ def _delete_request(self, module_api_path):
url= self.API_BASE_URL.format(self.__sub_domain) + module_api_path
response = requests.delete(url=url, headers=self.headers)
if response.status_code == 200:
result = json.loads(response.text)
return result
return {'message':'Web hook has been deleted'}

if response.status_code == 403:
error_msg = json.loads(response.text)
Expand Down
17 changes: 11 additions & 6 deletions fyle_employee_imports/bamboo_hr.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,23 @@ def sync_hrms_employees(self):
def upsert_employees(self, employees: Dict):
attributes = []
for employee in employees['employees']:
supervisor = [employee['supervisorEmail']]
active_status = True if employee['status'] == 'Active' else False
supervisor = [employee.get('supervisorEmail', None)]
active_status = True if employee.get('status', None) == 'Active' else False

display_name = employee.get('displayName', None)
if not display_name:
display_name = employee['firstName'] + ' ' + employee['lastName']

detail = {
'email': employee['workEmail'] if employee['workEmail'] else None,
'department_name': employee['department'] if employee['department'] else None,
'full_name': employee['displayName'] if employee['displayName'] else None,
'email': employee.get('workEmail', None),
'department_name': employee.get('department', None),
'full_name': display_name,
'approver_emails': supervisor,
}

attributes.append({
'attribute_type': 'EMPLOYEE',
'value': employee['displayName'],
'value': display_name,
'destination_id': employee['id'],
'detail': detail,
'active': active_status
Expand Down
3 changes: 1 addition & 2 deletions fyle_employee_imports/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ def get_employee_and_approver_payload(self, hrms_employees):

def fyle_employee_import(self, hrms_employees):
fyle_employee_payload, employee_approver_payload = self.get_employee_and_approver_payload(hrms_employees)

if fyle_employee_payload:
self.platform_connection.bulk_post_employees(employees_payload=fyle_employee_payload)

Expand All @@ -141,6 +140,6 @@ def sync_employees(self):
org_id=self.org_id,
updated_at__gte=self.bamboohr.employee_exported_at,
).order_by('value', 'id')

self.import_departments(hrms_employees)
self.fyle_employee_import(hrms_employees)
Loading