LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
Webhook integrations on pipelines (#549)
ali8f71aeeb66ef
diff --git a/backend/api/deployment_helper.py b/backend/api/deployment_helper.pyindex e9831ad7a..bc2b8aeff 100644--- a/backend/api/deployment_helper.py+++ b/backend/api/deployment_helper.py@@ -13,6 +13,7 @@ from api.exceptions import ()from api.key_helper import KeyHelperfrom api.models import APIDeployment, APIKey+from api.notification import APINotificationfrom api.serializers import APIExecutionResponseSerializerfrom django.core.files.uploadedfile import UploadedFilefrom django.db import connection@@ -22,6 +23,7 @@ from rest_framework.utils.serializer_helpers import ReturnDictfrom workflow_manager.endpoint.destination import DestinationConnectorfrom workflow_manager.endpoint.source import SourceConnectorfrom workflow_manager.workflow.dto import ExecutionResponse+from workflow_manager.workflow.enums import ExecutionStatusfrom workflow_manager.workflow.models.workflow import Workflowfrom workflow_manager.workflow.workflow_helper import WorkflowHelper@@ -141,8 +143,9 @@ class DeploymentHelper(BaseAPIKeyValidator):logger.info("Deleted the deployment instance")raise ApiKeyCreateException()- @staticmethod+ @classmethoddef execute_workflow(+ cls,organization_name: str,api: APIDeployment,file_objs: list[UploadedFile],@@ -180,11 +183,18 @@ class DeploymentHelper(BaseAPIKeyValidator):result.status_api = DeploymentHelper.construct_status_endpoint(api_endpoint=api.api_endpoint, execution_id=execution_id)- except Exception:+ cls._send_notification(api=api, result=result)+ except Exception as error:DestinationConnector.delete_api_storage_dir(workflow_id=workflow_id, execution_id=execution_id)- raise+ result = ExecutionResponse(+ workflow_id=workflow_id,+ execution_id=execution_id,+ execution_status=ExecutionStatus.ERROR.value,+ error=str(error),+ )+ cls._send_notification(api=api, result=result)return APIExecutionResponseSerializer(result).data@staticmethod@@ -201,3 +211,15 @@ class DeploymentHelper(BaseAPIKeyValidator):execution_id=execution_id)return execution_response++ @staticmethod+ def _send_notification(api: APIDeployment, result: ExecutionResponse) -> None:+ """Sends a notification for the pipeline.+ Args:+ api (APIDeployment): APIDeployment to send notification for++ Returns:+ None+ """+ api_notification = APINotification(api=api, result=result)+ api_notification.send()diff --git a/backend/api/notification.py b/backend/api/notification.pynew file mode 100644index 000000000..6702ab801--- /dev/null+++ b/backend/api/notification.py@@ -0,0 +1,35 @@+import logging++from api.models import APIDeployment+from notification.helper import NotificationHelper+from notification.models import Notification+from pipeline.dto import PipelineStatusPayload+from workflow_manager.workflow.dto import ExecutionResponse++logger = logging.getLogger(__name__)+++class APINotification:+ def __init__(self, api: APIDeployment, result: ExecutionResponse) -> None:+ self.notifications = Notification.objects.filter(api=api, is_active=True)+ self.api = api+ self.result = result++ def send(self):+ if not self.notifications.count():+ logger.info(f"No notifications found for api {self.api}")+ return+ logger.info(f"Sending api status notification for api {self.api}")++ payload_dto = PipelineStatusPayload(+ type="API",+ pipeline_id=self.api.id,+ pipeline_name=self.api.api_name,+ status=self.result.execution_status,+ execution_id=self.result.execution_id,+ error_message=self.result.error,+ )++ NotificationHelper.send_notification(+ notifications=self.notifications, payload=payload_dto.to_dict()+ )diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.pyindex ee6297442..a435ce034 100644--- a/backend/backend/settings/base.py+++ b/backend/backend/settings/base.py@@ -169,6 +169,7 @@ CELERY_BROKER_URL = get_required_setting()INDEXING_FLAG_TTL = int(get_required_setting("INDEXING_FLAG_TTL"))+NOTIFICATION_TIMEOUT = int(get_required_setting("NOTIFICATION_TIMEOUT", "5"))# Flag to Enable django adminADMIN_ENABLED = False@@ -245,6 +246,7 @@ TENANT_APPS = ("prompt_studio.prompt_studio_document_manager","prompt_studio.prompt_studio_index_manager","usage",+ "notification",)INSTALLED_APPS = list(SHARED_APPS) + [diff --git a/backend/backend/urls.py b/backend/backend/urls.pyindex e8b2e1a17..de1efb150 100644--- a/backend/backend/urls.py+++ b/backend/backend/urls.py@@ -59,6 +59,7 @@ urlpatterns = [UrlPathConstants.PROMPT_STUDIO,include("prompt_studio.prompt_studio_index_manager.urls"),),+ path("notifications/", include("notification.urls")),]diff --git a/backend/notification/__init__.py b/backend/notification/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/backend/notification/apps.py b/backend/notification/apps.pynew file mode 100644index 000000000..24a58ddc6--- /dev/null+++ b/backend/notification/apps.py@@ -0,0 +1,6 @@+from django.apps import AppConfig+++class NotificationConfig(AppConfig):+ default_auto_field = "django.db.models.BigAutoField"+ name = "notification"diff --git a/backend/notification/constants.py b/backend/notification/constants.pynew file mode 100644index 000000000..c106997d3--- /dev/null+++ b/backend/notification/constants.py@@ -0,0 +1,5 @@+class NotificationUrlConstant:+ """Constants for Notification Urls."""++ PIPELINE_UID = "pipeline_uuid"+ API_UID = "api_uuid"diff --git a/backend/notification/enums.py b/backend/notification/enums.pynew file mode 100644index 000000000..991b08cac--- /dev/null+++ b/backend/notification/enums.py@@ -0,0 +1,38 @@+from enum import Enum+++class NotificationType(Enum):+ WEBHOOK = "WEBHOOK"+ # Add other notification types as needed+ # Example EMAIL = 'EMAIL'++ def get_valid_platforms(self):+ if self == NotificationType.WEBHOOK:+ return [PlatformType.SLACK.value, PlatformType.API.value]+ return []++ @classmethod+ def choices(cls):+ return [(e.value, e.name.replace("_", " ").capitalize()) for e in cls]+++class AuthorizationType(Enum):+ BEARER = "BEARER"+ API_KEY = "API_KEY"+ CUSTOM_HEADER = "CUSTOM_HEADER"+ NONE = "NONE"++ @classmethod+ def choices(cls):+ return [(e.value, e.name.replace("_", " ").capitalize()) for e in cls]+++class PlatformType(Enum):+ SLACK = "SLACK"+ API = "API"+ # Add other platforms as needed+ # Example TEAMS = 'TEAMS'++ @classmethod+ def choices(cls):+ return [(e.value, e.name.replace("_", " ").capitalize()) for e in cls]diff --git a/backend/notification/helper.py b/backend/notification/helper.pynew file mode 100644index 000000000..71bd25992--- /dev/null+++ b/backend/notification/helper.py@@ -0,0 +1,48 @@+import logging+from typing import Any++from notification.enums import NotificationType, PlatformType+from notification.models import Notification+from notification.provider.notification_provider import NotificationProvider+from notification.provider.registry import get_notification_provider++logger = logging.getLogger(__name__)+++class NotificationHelper:+ @classmethod+ def send_notification(cls, notifications: list[Notification], payload: Any) -> None:+ """Send notification Sends notifications using the appropriate provider+ based on the notification type and platform.++ This method iterates through a list of `Notification` objects, determines the+ appropriate notification provider based on the notification's type and+ platform, and sends the notification with the provided payload. If an error+ occurs due to an invalid notification type or platform, it logs the error.++ Args:+ notifications (list[Notification]): A list of `Notification` instances to+ be processed and sent.+ payload (Any): The data to be sent with the notification. This can be any+ format expected by the provider++ Returns:+ None+ """+ for notification in notifications:+ notification_type = NotificationType(notification.notification_type)+ platform_type = PlatformType(notification.platform)+ try:+ notification_provider = get_notification_provider(+ notification_type, platform_type+ )+ notifier: NotificationProvider = notification_provider(+ notification=notification, payload=payload+ )+ notifier.send()+ logger.info(f"Sending notification to {notification}")+ except ValueError as e:+ logger.error(+ f"Error in notification type {notification_type} and platform "+ f"{platform_type} for notification {notification}: {e}"+ )diff --git a/backend/notification/migrations/0001_initial.py b/backend/notification/migrations/0001_initial.pynew file mode 100644index 000000000..b2c27a737--- /dev/null+++ b/backend/notification/migrations/0001_initial.py@@ -0,0 +1,122 @@+# Generated by Django 4.2.1 on 2024-08-07 08:48++import uuid++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):++ initial = True++ dependencies = [+ ("pipeline", "0002_alter_pipeline_last_run_status"),+ ("api", "0001_initial"),+ ]++ operations = [+ migrations.CreateModel(+ name="Notification",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("modified_at", models.DateTimeField(auto_now=True)),+ (+ "id",+ models.UUIDField(+ default=uuid.uuid4,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "name",+ models.CharField(+ db_comment="Name of the notification.",+ default="Notification",+ max_length=255,+ ),+ ),+ ("url", models.URLField(null=True)),+ (+ "authorization_key",+ models.CharField(blank=True, max_length=255, null=True),+ ),+ (+ "authorization_header",+ models.CharField(blank=True, max_length=255, null=True),+ ),+ (+ "authorization_type",+ models.CharField(+ choices=[+ ("BEARER", "Bearer"),+ ("API_KEY", "Api key"),+ ("CUSTOM_HEADER", "Custom header"),+ ("NONE", "None"),+ ],+ default="NONE",+ max_length=50,+ ),+ ),+ ("max_retries", models.IntegerField(default=0)),+ (+ "platform",+ models.CharField(+ blank=True,+ choices=[("SLACK", "Slack"), ("API", "Api")],+ max_length=50,+ null=True,+ ),+ ),+ (+ "notification_type",+ models.CharField(+ choices=[("WEBHOOK", "Webhook")],+ default="WEBHOOK",+ max_length=50,+ ),+ ),+ (+ "is_active",+ models.BooleanField(+ db_comment="Flag indicating whether the notification is active or not.",+ default=True,+ ),+ ),+ (+ "api",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="notifications",+ to="api.apideployment",+ ),+ ),+ (+ "pipeline",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="notifications",+ to="pipeline.pipeline",+ ),+ ),+ ],+ ),+ migrations.AddConstraint(+ model_name="notification",+ constraint=models.UniqueConstraint(+ fields=("name", "pipeline"), name="unique_name_pipeline"+ ),+ ),+ migrations.AddConstraint(+ model_name="notification",+ constraint=models.UniqueConstraint(+ fields=("name", "api"), name="unique_name_api"+ ),+ ),+ ]diff --git a/backend/notification/migrations/__init__.py b/backend/notification/migrations/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/backend/notification/models.py b/backend/notification/models.pynew file mode 100644index 000000000..121ac0599--- /dev/null+++ b/backend/notification/models.py@@ -0,0 +1,91 @@+import uuid++from api.models import APIDeployment+from django.db import models+from pipeline.models import Pipeline+from utils.models.base_model import BaseModel++from .enums import AuthorizationType, NotificationType, PlatformType++NOTIFICATION_NAME_MAX_LENGTH = 255+++class Notification(BaseModel):+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)+ name = models.CharField(+ max_length=NOTIFICATION_NAME_MAX_LENGTH,+ db_comment="Name of the notification.",+ default="Notification",+ )+ url = models.URLField(null=True) # URL for webhook or other endpoints+ authorization_key = models.CharField(+ max_length=255, blank=True, null=True+ ) # Authorization Key or API Key+ authorization_header = models.CharField(+ max_length=255, blank=True, null=True+ ) # Header Name for custom headers+ authorization_type = models.CharField(+ max_length=50,+ choices=AuthorizationType.choices(),+ default=AuthorizationType.NONE.value,+ )+ max_retries = models.IntegerField(+ default=0+ ) # Maximum number of times to retry webhook+ platform = models.CharField(+ max_length=50,+ choices=PlatformType.choices(),+ blank=True,+ null=True,+ )+ notification_type = models.CharField(+ max_length=50,+ choices=NotificationType.choices(),+ default=NotificationType.WEBHOOK.value,+ )+ is_active = models.BooleanField(+ default=True,+ db_comment="Flag indicating whether the notification is active or not.",+ )+ # Foreign keys to specific models+ pipeline = models.ForeignKey(+ Pipeline,+ on_delete=models.CASCADE,+ related_name="notifications",+ null=True,+ blank=True,+ )+ api = models.ForeignKey(+ APIDeployment,+ on_delete=models.CASCADE,+ related_name="notifications",+ null=True,+ blank=True,+ )++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["name", "pipeline"], name="unique_name_pipeline"+ ),+ models.UniqueConstraint(fields=["name", "api"], name="unique_name_api"),+ ]++ def save(self, *args, **kwargs):+ # Validation for platforms+ valid_platforms = NotificationType(self.notification_type).get_valid_platforms()+ if self.platform and self.platform not in valid_platforms:+ raise ValueError(+ f"Invalid platform '{self.platform}' for notification type "+ f"'{self.notification_type}'. "+ f"Valid options are: {', '.join(valid_platforms)}."+ )++ # Allow saving only if the platform is valid or not required+ super().save(*args, **kwargs)++ def __str__(self):+ return (+ f"Notification {self.id}: (Type: {self.notification_type}, "+ f"Platform: {self.platform}, Url: {self.url}))"+ )diff --git a/backend/notification/provider/__init__.py b/backend/notification/provider/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/backend/notification/provider/notification_provider.py b/backend/notification/provider/notification_provider.pynew file mode 100644index 000000000..dbfeba284--- /dev/null+++ b/backend/notification/provider/notification_provider.py@@ -0,0 +1,28 @@+from abc import ABC, abstractmethod++from django.conf import settings+from notification.models import Notification+++class NotificationProvider(ABC):+ NOTIFICATION_TIMEOUT = settings.NOTIFICATION_TIMEOUT+ RETRY_DELAY = 10 # Seconds++ def __init__(self, notification: Notification, payload):+ self.payload = payload+ self.notification = notification++ @abstractmethod+ def send(self):+ """Method to be overridden in child classes for sending the+ notification."""+ raise NotImplementedError("Subclasses should implement this method.")++ def validate(self):+ """Method to validate the notification data."""+ pass++ @abstractmethod+ def get_headers(self):+ """Method to get the headers for the notification."""+ raise NotImplementedError("Subclasses should implement this method.")diff --git a/backend/notification/provider/registry.py b/backend/notification/provider/registry.pynew file mode 100644index 000000000..f746c32a3--- /dev/null+++ b/backend/notification/provider/registry.py@@ -0,0 +1,54 @@+from notification.enums import NotificationType, PlatformType+from notification.provider.notification_provider import NotificationProvider+from notification.provider.webhook.api_webhook import APIWebhook+from notification.provider.webhook.slack_webhook import SlackWebhook++REGISTRY = {+ NotificationType.WEBHOOK: {+ PlatformType.SLACK: SlackWebhook,+ PlatformType.API: APIWebhook,+ # Add other platform-specific classes here+ },+ # Add other notification types and classes here+}+++def get_notification_provider(+ notification_type: NotificationType, platform_type: PlatformType+) -> NotificationProvider:+ """Get Notification provider based on notification type and platform type+ It uses the REGISTRY to map the combination of notification type and+ platform type to the corresponding NotificationProvider class.++ If the provided combination is not found in the REGISTRY, a ValueError is raised.++ Note:+ This function assumes that the REGISTRY dictionary is correctly populated+ with the appropriate NotificationProvider classes for each combination of+ notification type and platform type.++ See Also:+ - NotificationType+ - PlatformType+ - NotificationProvider+ - REGISTRY++ Parameters:+ notification_type (NotificationType): The type of notification.+ platform_type (PlatformType): The platform/provider type for the notification.++ Returns:+ NotificationProvider: The appropriate NotificationProvider class for+ the given combination.++ Raises:+ ValueError: If the provided combination is not found in the REGISTRY.+ """+ if notification_type not in REGISTRY:+ raise ValueError(f"Unsupported notification type: {notification_type}")++ platform_registry = REGISTRY[notification_type]+ if platform_type not in platform_registry:+ raise ValueError(f"Unsupported platform type: {platform_type}")++ return platform_registry[platform_type]diff --git a/backend/notification/provider/webhook/__init__.py b/backend/notification/provider/webhook/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/backend/notification/provider/webhook/api_webhook.py b/backend/notification/provider/webhook/api_webhook.pynew file mode 100644index 000000000..dc53231d9--- /dev/null+++ b/backend/notification/provider/webhook/api_webhook.py@@ -0,0 +1,13 @@+from notification.provider.webhook.webhook import Webhook+++class APIWebhook(Webhook):+ def send(self):+ """Send the API webhook notification."""+ super().send()++ def get_headers(self):+ """API-specific headers."""+ headers = super().get_headers()+ headers["Content-Type"] = "application/json"+ return headersdiff --git a/backend/notification/provider/webhook/slack_webhook.py b/backend/notification/provider/webhook/slack_webhook.pynew file mode 100644index 000000000..b529d510a--- /dev/null+++ b/backend/notification/provider/webhook/slack_webhook.py@@ -0,0 +1,60 @@+import logging++from notification.provider.webhook.webhook import Webhook++logger = logging.getLogger(__name__)+++class SlackWebhook(Webhook):+ def send(self):+ """Send the Slack webhook notification."""+ formatted_payload = self.format_payload()+ self.payload = formatted_payload+ super().send()++ def get_headers(self):+ """Slack-specific headers."""+ headers = super().get_headers()+ headers["Content-Type"] = "application/json"+ return headers++ def format_payload(self) -> dict:+ """Format the payload to match Slack's expected structure."""+ if "text" not in self.payload:+ # Construct a basic Slack message with 'text' field+ formatted_payload = {+ "text": "Notification",+ "blocks": self.create_blocks_from_payload(),+ }+ else:+ # If 'text' is already present, format accordingly+ formatted_payload = {+ "text": self.payload.pop("text"),+ "blocks": self.create_blocks_from_payload(),+ }+ return formatted_payload++ def create_blocks_from_payload(self) -> list:+ """Create Slack blocks from the given payload."""+ blocks = []+ # Header+ blocks.append(+ {+ "type": "section",+ "text": {"type": "mrkdwn", "text": "*Unstract Update:*"},+ }+ )+ # Add a divider for separation+ blocks.append({"type": "divider"})+ # Add each key-value pair to the blocks+ for key, value in self.payload.items():+ formatted_key = key.replace("_", " ").title()+ blocks.append(+ {+ "type": "section",+ "text": {"type": "mrkdwn", "text": f"*{formatted_key}:* {value}"},+ }+ )+ # Footer+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": "*---*"}})+ return blocksdiff --git a/backend/notification/provider/webhook/webhook.py b/backend/notification/provider/webhook/webhook.pynew file mode 100644index 000000000..e90f06238--- /dev/null+++ b/backend/notification/provider/webhook/webhook.py@@ -0,0 +1,156 @@+# notifications.py++import logging+from typing import Any, Optional++import requests+from celery import shared_task+from notification.enums import AuthorizationType+from notification.provider.notification_provider import NotificationProvider++logger = logging.getLogger(__name__)+++class WebhookNotificationArg:+ MAX_RETRIES = "max_retries"+ RETRY_DELAY = "retry_delay"+++class HeaderConstants:+ APPLICATION_JSON = "application/json"+++class Webhook(NotificationProvider):+ def send(self):+ """Send the webhook notification."""+ try:+ headers = self.get_headers()+ self.validate()+ except ValueError as e:+ logger.error(f"Error validating notification {self.notification} :: {e}")+ return+ send_webhook_notification.apply_async(+ (self.notification.url, self.payload, headers, self.NOTIFICATION_TIMEOUT),+ kwargs={+ WebhookNotificationArg.MAX_RETRIES: self.notification.max_retries,+ WebhookNotificationArg.RETRY_DELAY: self.RETRY_DELAY,+ },+ )++ def validate(self):+ """Validate notification.++ Returns:+ _type_: None+ """+ if not self.notification.url:+ raise ValueError("Webhook URL is required.")+ if not self.payload:+ raise ValueError("Payload is required.")+ return super().validate()++ def get_headers(self):+ """+ Get the headers for the notification based on the authorization type and key.+ Raises:+ ValueError: _description_++ Returns:+ dict[str, str]: A dictionary containing the headers.+ """+ headers = {}+ try:+ authorization_type = AuthorizationType(+ self.notification.authorization_type.upper()+ )+ except ValueError:+ raise ValueError(+ "Unsupported authorization type: "+ f"{self.notification.authorization_type}"+ )+ authorization_key = self.notification.authorization_key+ authorization_header = self.notification.authorization_header++ header_formats = {+ AuthorizationType.BEARER: lambda key: {+ "Authorization": f"Bearer {key}",+ "Content-Type": HeaderConstants.APPLICATION_JSON,+ },+ AuthorizationType.API_KEY: lambda key: {+ "Authorization": key,+ "Content-Type": HeaderConstants.APPLICATION_JSON,+ },+ AuthorizationType.CUSTOM_HEADER: lambda key: {+ authorization_header: key,+ "Content-Type": HeaderConstants.APPLICATION_JSON,+ },+ AuthorizationType.NONE: lambda _: {+ "Content-Type": HeaderConstants.APPLICATION_JSON,+ },+ }++ if authorization_type not in header_formats:+ raise ValueError(f"Unsupported authorization type: {authorization_type}")++ headers = header_formats[authorization_type](authorization_key)++ # Check if custom header type has required details+ if authorization_type == AuthorizationType.CUSTOM_HEADER:+ if not authorization_header or not authorization_key:+ raise ValueError(+ "Custom header or key missing for custom authorization."+ )+ return headers+++@shared_task(bind=True, name="send_webhook_notification")+def send_webhook_notification(+ self,+ url: str,+ payload: Any,+ headers: Any = None,+ timeout: int = 10,+ max_retries: Optional[int] = None,+ retry_delay: int = 10,+):+ """Celery task to send a webhook with retries and error handling.++ Args:+ url (str): The URL to which the webhook should be sent.+ payload (dict): The payload to be sent in the webhook request.+ headers (dict, optional): Optional headers to include in the request.+ Defaults to None.+ timeout (int, optional): The request timeout in seconds. Defaults to 10.+ max_retries (int, optional): The maximum number of retries allowed.+ Defaults to None.+ retry_delay (int, optional): The delay between retries in seconds.+ Defaults to 10.++ Returns:+ None+ """+ try:+ response = requests.post(url, json=payload, headers=headers, timeout=timeout)+ response.raise_for_status()+ if not (200 <= response.status_code < 300):+ logger.error(+ f"Request to {url} failed with status code {response.status_code}. "+ f"Response: {response.text}"+ )+ except requests.exceptions.RequestException as exc:+ if max_retries is not None:+ if self.request.retries < max_retries:+ logger.warning(+ f"Request to {url} failed. Retrying in {retry_delay} seconds. "+ f"Attempt {self.request.retries + 1}/{max_retries}. Error: {exc}"+ )+ raise self.retry(exc=exc, countdown=retry_delay)+ else:+ logger.error(+ f"Failed to send webhook to {url} after {max_retries} attempts. "+ f"Error: {exc}"+ )+ return None+ else:+ logger.error(f"Webhook request to {url} failed with error: {exc}")+ return Nonediff --git a/backend/notification/serializers.py b/backend/notification/serializers.pynew file mode 100644index 000000000..c274ba32f--- /dev/null+++ b/backend/notification/serializers.py@@ -0,0 +1,78 @@+from rest_framework import serializers++from .enums import AuthorizationType, NotificationType, PlatformType+from .models import Notification+++class NotificationSerializer(serializers.ModelSerializer):+ notification_type = serializers.ChoiceField(choices=NotificationType.choices())+ authorization_type = serializers.ChoiceField(choices=AuthorizationType.choices())+ platform = serializers.ChoiceField(choices=PlatformType.choices(), required=False)+ max_retries = serializers.IntegerField(+ max_value=4, min_value=0, default=0, required=False+ )++ class Meta:+ model = Notification+ fields = "__all__"++ def validate(self, data):+ """Validate the data for the NotificationSerializer."""+ # General validation for the relationship between api and pipeline+ self._validate_api_or_pipeline(data)+ return data++ def _validate_api_or_pipeline(self, data):+ """Ensure either 'api' or 'pipeline' is provided, but not both."""+ api = data.get("api", getattr(self.instance, "api", None))+ pipeline = data.get("pipeline", getattr(self.instance, "pipeline", None))+ if api and pipeline:+ raise serializers.ValidationError(+ "Only one of 'api' or 'pipeline' can be provided."+ )++ if not api and not pipeline:+ raise serializers.ValidationError(+ "Either 'api' or 'pipeline' must be provided."+ )++ def validate_platform(self, value):+ """Validate the platform field based on the notification_type."""+ notification_type = self.initial_data.get(+ "notification_type", getattr(self.instance, "notification_type", None)+ )+ if not notification_type:+ raise serializers.ValidationError("Notification type must be provided.")++ valid_platforms = NotificationType(notification_type).get_valid_platforms()+ if value and value not in valid_platforms:+ raise serializers.ValidationError(+ f"Invalid platform '{value}' for notification type "+ f"'{notification_type}'. "+ f"Valid options are: {', '.join(valid_platforms)}."+ )+ return value++ def validate_name(self, value):+ """Check uniqueness of the name with respect to either 'api' or+ 'pipeline'."""+ api = self.initial_data.get("api", getattr(self.instance, "api", None))+ pipeline = self.initial_data.get(+ "pipeline", getattr(self.instance, "pipeline", None)+ )++ queryset = Notification.objects.filter(name=value)+ if self.instance:+ queryset = queryset.exclude(id=self.instance.id)++ if api and queryset.filter(api=api).exists():+ raise serializers.ValidationError(+ "A notification with this name and API already exists.",+ code="unique_api",+ )+ elif pipeline and queryset.filter(pipeline=pipeline).exists():+ raise serializers.ValidationError(+ "A notification with this name and pipeline already exists.",+ code="unique_pipeline",+ )+ return valuediff --git a/backend/notification/urls.py b/backend/notification/urls.pynew file mode 100644index 000000000..2e356b400--- /dev/null+++ b/backend/notification/urls.py@@ -0,0 +1,27 @@+from django.urls import path+from rest_framework.urlpatterns import format_suffix_patterns++from .views import NotificationViewSet++notification_list = NotificationViewSet.as_view({"get": "list", "post": "create"})+notification_detail = NotificationViewSet.as_view(+ {+ "get": "retrieve",+ "put": "update",+ "patch": "partial_update",+ "delete": "destroy",+ }+)++urlpatterns = format_suffix_patterns(+ [+ path("", notification_list, name="notification-list"),+ path("<uuid:pk>/", notification_detail, name="notification-detail"),+ path(+ "pipeline/<uuid:pipeline_uuid>/",+ notification_list,+ name="pipeline-notification-list",+ ),+ path("api/<uuid:api_uuid>/", notification_list, name="api-notification-list"),+ ]+)diff --git a/backend/notification/views.py b/backend/notification/views.pynew file mode 100644index 000000000..beb5e75a2--- /dev/null+++ b/backend/notification/views.py@@ -0,0 +1,36 @@+from api.deployment_helper import DeploymentHelper+from api.exceptions import APINotFound+from notification.constants import NotificationUrlConstant+from pipeline.exceptions import PipelineNotFound+from pipeline.models import Pipeline+from pipeline.pipeline_processor import PipelineProcessor+from rest_framework import viewsets++from .models import Notification+from .serializers import NotificationSerializer+++class NotificationViewSet(viewsets.ModelViewSet):+ serializer_class = NotificationSerializer++ def get_queryset(self):+ queryset = Notification.objects.all()+ pipeline_uuid = self.kwargs.get(NotificationUrlConstant.PIPELINE_UID)+ api_uuid = self.kwargs.get(NotificationUrlConstant.API_UID)++ if pipeline_uuid:+ try:+ pipeline = PipelineProcessor.fetch_pipeline(+ pipeline_id=pipeline_uuid, check_active=False+ )+ queryset = queryset.filter(pipeline=pipeline)+ except Pipeline.DoesNotExist:+ raise PipelineNotFound()++ elif api_uuid:+ api = DeploymentHelper.get_api_by_id(api_id=api_uuid)+ if not api:+ raise APINotFound()+ queryset = queryset.filter(api=api)++ return querysetdiff --git a/backend/pipeline/dto.py b/backend/pipeline/dto.pynew file mode 100644index 000000000..3ed83bf30--- /dev/null+++ b/backend/pipeline/dto.py@@ -0,0 +1,33 @@+from typing import Any, Optional+++class PipelineStatusPayload:+ def __init__(+ self,+ type: str,+ pipeline_id: str,+ pipeline_name: str,+ status: str,+ execution_id: Optional[str] = None,+ error_message: Optional[str] = None,+ ):+ self.type = type+ self.pipeline_id = pipeline_id+ self.pipeline_name = pipeline_name+ self.status = status+ self.execution_id = execution_id+ self.error_message = error_message++ def to_dict(self) -> dict[str, Any]:+ """Convert the payload DTO to a dictionary."""+ payload = {+ "type": self.type,+ "pipeline_id": str(self.pipeline_id),+ "pipeline_name": self.pipeline_name,+ "status": self.status,+ }+ if self.execution_id:+ payload["execution_id"] = str(self.execution_id)+ if self.error_message:+ payload["error_message"] = self.error_message+ return payloaddiff --git a/backend/pipeline/notification.py b/backend/pipeline/notification.pynew file mode 100644index 000000000..bc08f63a4--- /dev/null+++ b/backend/pipeline/notification.py@@ -0,0 +1,44 @@+import logging+from typing import Optional++from notification.helper import NotificationHelper+from notification.models import Notification+from pipeline.dto import PipelineStatusPayload+from pipeline.models import Pipeline++logger = logging.getLogger(__name__)+++class PipelineNotification:+ def __init__(+ self,+ pipeline: Pipeline,+ execution_id: Optional[str] = None,+ error_message: Optional[str] = None,+ ) -> None:+ self.notifications = Notification.objects.filter(+ pipeline=pipeline, is_active=True+ )+ self.pipeline = pipeline+ self.error_message = error_message+ self.execution_id = execution_id++ def send(self):+ if not self.notifications.count():+ logger.info(f"No notifications found for pipeline {self.pipeline}")+ return+ logger.info(+ f"Sending pipeline status notification for pipeline {self.pipeline}"+ )+ payload_dto = PipelineStatusPayload(+ type=self.pipeline.pipeline_type,+ pipeline_id=str(self.pipeline.id),+ pipeline_name=self.pipeline.pipeline_name,+ status=self.pipeline.last_run_status,+ execution_id=self.execution_id,+ error_message=self.error_message,+ )++ NotificationHelper.send_notification(+ notifications=self.notifications, payload=payload_dto.to_dict()+ )diff --git a/backend/pipeline/pipeline_processor.py b/backend/pipeline/pipeline_processor.pyindex 5a84ef665..0fb42abb1 100644--- a/backend/pipeline/pipeline_processor.py+++ b/backend/pipeline/pipeline_processor.py@@ -4,6 +4,7 @@ from typing import Optionalfrom django.utils import timezonefrom pipeline.exceptions import InactivePipelineErrorfrom pipeline.models import Pipeline+from pipeline.notification import PipelineNotificationlogger = logging.getLogger(__name__)@@ -70,11 +71,31 @@ class PipelineProcessor:pipeline.save()return pipeline+ @staticmethod+ def _send_notification(+ pipeline: Pipeline,+ execution_id: Optional[str] = None,+ error_message: Optional[str] = None,+ ) -> None:+ """Sends a notification for the pipeline.+ Args:+ pipeline (Pipeline): Pipeline to send notification for++ Returns:+ None+ """+ pipeline_notification = PipelineNotification(+ pipeline=pipeline, execution_id=execution_id, error_message=error_message+ )+ pipeline_notification.send()+@staticmethoddef update_pipeline(pipeline_guid: Optional[str],status: tuple[str, str],is_active: Optional[bool] = None,+ execution_id: Optional[str] = None,+ error_message: Optional[str] = None,) -> None:if not pipeline_guid:return@@ -83,7 +104,10 @@ class PipelineProcessor:pipeline: Pipeline = PipelineProcessor.fetch_pipeline(pipeline_id=pipeline_guid, check_active=check_active)- PipelineProcessor._update_pipeline_status(+ pipeline = PipelineProcessor._update_pipeline_status(pipeline=pipeline, is_end=True, status=status, is_active=is_active)+ PipelineProcessor._send_notification(+ pipeline=pipeline, execution_id=execution_id, error_message=error_message+ )logger.info(f"Updated pipeline {pipeline_guid} status: {status}")diff --git a/backend/sample.env b/backend/sample.envindex ff4ca0927..4b62cec17 100644--- a/backend/sample.env+++ b/backend/sample.env@@ -144,6 +144,9 @@ CELERY_BROKER_URL = "redis://unstract-redis:6379"# Indexing flag to prevent re-indexINDEXING_FLAG_TTL=1800+# Notification Timeout in Seconds+NOTIFICATION_TIMEOUT=5+# Path where public and private tools are registered# with a YAML and JSONsTOOL_REGISTRY_CONFIG_PATH="/data/tool_registry_config"diff --git a/backend/scheduler/tasks.py b/backend/scheduler/tasks.pyindex 05f5f8c67..5b5a590ba 100644--- a/backend/scheduler/tasks.py+++ b/backend/scheduler/tasks.py@@ -110,6 +110,7 @@ def execute_pipeline_task()returnlogger.info(f"Executing workflow: {workflow}")+ PipelineProcessor.initialize_pipeline_sync(pipeline_id=pipepline_id)PipelineProcessor.update_pipeline(pipepline_id, Pipeline.PipelineStatus.INPROGRESS)diff --git a/backend/utils/notification/__init__.py b/backend/utils/notification/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/backend/workflow_manager/workflow/execution.py b/backend/workflow_manager/workflow/execution.pyindex 81b94a236..94f4bcddb 100644--- a/backend/workflow_manager/workflow/execution.py+++ b/backend/workflow_manager/workflow/execution.py@@ -290,7 +290,7 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):file_name: str,single_step: bool,file_history: Optional[FileHistory] = None,- ) -> bool:+ ) -> tuple[bool, bool]:"""Executes the input file.Args:@@ -300,10 +300,12 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):file_history (Optional[FileHistory], optional):The file history object. Defaults to None.Returns:- bool: Flag indicating whether the file was executed.+ tuple[bool, bool]: Flag indicating whether the file was executed+ and skipped."""execution_type = ExecutionType.COMPLETEis_executed = False+ is_skipped = Falseif single_step:execution_type = ExecutionType.STEPif not (file_history and file_history.is_completed()):@@ -315,8 +317,9 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):f"Skipping file {file_name} as it is already processed.""Clear the cache to process it again")+ is_skipped = Trueself._handle_execution_type(execution_type)- return is_executed+ return is_executed, is_skippeddef execute_uncached_input(self, file_name: str, single_step: bool) -> None:"""Executes the uncached input file.diff --git a/backend/workflow_manager/workflow/workflow_helper.py b/backend/workflow_manager/workflow/workflow_helper.pyindex 9f4e434cc..e8c1444ba 100644--- a/backend/workflow_manager/workflow/workflow_helper.py+++ b/backend/workflow_manager/workflow/workflow_helper.py@@ -116,6 +116,7 @@ class WorkflowHelper:) -> WorkflowExecution:input_files = source.list_files_from_source()total_files = len(input_files)+ error_message = Noneprocessed_files = 0error_raised = 0execution_service.publish_initial_workflow_logs(total_files)@@ -145,8 +146,13 @@ class WorkflowHelper:ExecutionStatus.STOPPED, error=str(exception))break- if error_raised and error_raised == total_files:- execution_service.update_execution(ExecutionStatus.ERROR)+ except Exception as error:+ error_message = str(error)+ error_raised += 1+ if error_raised and error_raised >= processed_files:+ execution_service.update_execution(+ ExecutionStatus.ERROR, error=error_message+ )else:execution_service.update_execution(ExecutionStatus.COMPLETED)@@ -290,6 +296,19 @@ class WorkflowHelper:mode=workflow_execution.execution_mode,result=destination.api_results,)+ except Exception as e:+ logger.error(f"Error executing workflow {workflow}: {e}")+ WorkflowHelper._update_pipeline_status(+ pipeline_id=pipeline_id, workflow_execution=workflow_execution+ )+ return ExecutionResponse(+ str(workflow.id),+ str(workflow_execution.id),+ workflow_execution.status,+ log_id=str(execution_service.execution_log_id),+ error=workflow_execution.error_message,+ mode=workflow_execution.execution_mode,+ )finally:destination.delete_execution_directory()@@ -302,11 +321,16 @@ class WorkflowHelper:# Update pipeline statusif workflow_execution.status != ExecutionStatus.ERROR.value:PipelineProcessor.update_pipeline(- pipeline_id, Pipeline.PipelineStatus.SUCCESS+ pipeline_id,+ Pipeline.PipelineStatus.SUCCESS,+ execution_id=workflow_execution.id,)else:PipelineProcessor.update_pipeline(- pipeline_id, Pipeline.PipelineStatus.FAILURE+ pipeline_id,+ Pipeline.PipelineStatus.FAILURE,+ execution_id=workflow_execution.id,+ error_message=workflow_execution.error_message,)# Expected exception since API deployments are not tracked in Pipelineexcept Pipeline.DoesNotExist:diff --git a/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx b/frontend/src/components/deployments/api-deployment/ApiDeployment.jsxindex b060c62a4..a3f2ef762 100644--- a/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx+++ b/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx@@ -7,6 +7,7 @@ import {KeyOutlined,CloudDownloadOutlined,FileSearchOutlined,+ NotificationOutlined,} from "@ant-design/icons";import { Button, Dropdown, Space, Switch, Tooltip, Typography } from "antd";import { useEffect, useState } from "react";@@ -27,6 +28,7 @@ import { LogsModal } from "../../pipelines-or-deployments/log-modal/LogsModal.jsimport { fetchExecutionLogs } from "../../pipelines-or-deployments/log-modal/fetchExecutionLogs";import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate.js";import usePipelineHelper from "../../../hooks/usePipelineHelper.js";+import { NotificationModal } from "../../pipelines-or-deployments/notification-modal/NotificationModal.jsx";function ApiDeployment() {const { sessionDetails } = useSessionStore();@@ -51,6 +53,7 @@ function ApiDeployment() {const axiosPrivate = useAxiosPrivate();const { getApiKeys, downloadPostmanCollection, copyUrl } =usePipelineHelper();+ const [openNotificationModal, setOpenNotificationModal] = useState(false);const handleFetchLogs = (page, pageSize) => {fetchExecutionLogs(@@ -352,6 +355,23 @@ function ApiDeployment() {</Space>),},+ {+ key: "7",+ label: (+ <Space+ direction="horizontal"+ className="action-items"+ onClick={() => setOpenNotificationModal(true)}+ >+ <div>+ <NotificationOutlined />+ </div>+ <div>+ <Typography.Text>Setup Notifications</Typography.Text>+ </div>+ </Space>+ ),+ },];return (@@ -401,6 +421,12 @@ function ApiDeployment() {totalLogs={executionLogsTotalCount}fetchExecutionLogs={handleFetchLogs}/>+ <NotificationModal+ open={openNotificationModal}+ setOpen={setOpenNotificationModal}+ type={deploymentApiTypes.api}+ id={selectedRow?.id}+ /></>);}diff --git a/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.jsx b/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.jsxindex 56bd3e7fe..2d6446b62 100644--- a/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.jsx+++ b/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.jsx@@ -155,6 +155,18 @@ const EtlTaskDeploy = ({});};+ const updatePipelineTable = (pipeline) => {+ setTableData((prev) => {+ const index = prev.findIndex((item) => item?.id === pipeline?.id);+ if (index !== -1) {+ const newData = [...prev];+ newData[index] = { ...newData[index], ...pipeline };+ return newData;+ }+ return prev;+ });+ };+const updatePipeline = () => {const body = formDetails;body["pipeline_type"] = type.toUpperCase();@@ -171,7 +183,7 @@ const EtlTaskDeploy = ({setLoading(true);axiosPrivate(requestOptions).then((res) => {- addPipeline(res?.data);+ updatePipelineTable(res?.data);setOpen(false);clearFormDetails();setAlertDetails({diff --git a/frontend/src/components/pipelines-or-deployments/notification-modal/CreateNotification.jsx b/frontend/src/components/pipelines-or-deployments/notification-modal/CreateNotification.jsxnew file mode 100644index 000000000..ac60bc90f--- /dev/null+++ b/frontend/src/components/pipelines-or-deployments/notification-modal/CreateNotification.jsx@@ -0,0 +1,205 @@+import { Button, Form, Input, Select, Space } from "antd";+import PropTypes from "prop-types";+import { getBackendErrorDetail } from "../../../helpers/GetStaticData";+import { useEffect, useState } from "react";++const DEFAULT_FORM_DETAILS = {+ name: "",+ authorization_type: "BEARER",+ notification_type: "WEBHOOK",+ platform: "SLACK",+ authorization_header: "",+ authorization_key: "",+ is_active: false,+ max_retries: 0,+ pipeline: "",+ api: "",+ url: "",+};++const NOTIFICATION_TYPE_ITEMS = [+ {+ value: "WEBHOOK",+ label: "WEBHOOK",+ },+];++const PLATFORM_TYPES = [+ {+ value: "SLACK",+ label: "SLACK",+ },+ {+ value: "API",+ label: "API",+ },+];++const AUTHORIZATION_TYPES = [+ {+ value: "BEARER",+ label: "BEARER",+ },+ {+ value: "API_KEY",+ label: "API_KEY",+ },+ {+ value: "CUSTOM_HEADER",+ label: "CUSTOM_HEADER",+ },+ {+ value: "NONE",+ label: "NONE",+ },+];++function CreateNotification({+ setIsForm,+ type,+ id,+ isLoading,+ handleSubmit,+ handleUpdate,+ editDetails,+}) {+ const [form] = Form.useForm();+ const [formDetails, setFormDetails] = useState(DEFAULT_FORM_DETAILS);+ const [backendErrors, setBackendErrors] = useState(null);+ const [resetForm, setResetForm] = useState(false);++ useEffect(() => {+ if (editDetails) {+ setFormDetails(editDetails);+ setResetForm(true);+ }+ }, [editDetails]);++ useEffect(() => {+ if (resetForm) {+ form.resetFields();+ setResetForm(false);+ }+ }, [formDetails]);++ const handleInputChange = (changedValues, allValues) => {+ setFormDetails({ ...formDetails, ...allValues });+ const changedFieldName = Object.keys(changedValues)[0];+ form.setFields([+ {+ name: changedFieldName,+ errors: [],+ },+ ]);+ setBackendErrors((prevErrors) => {+ if (prevErrors) {+ const updatedErrors = prevErrors.errors.filter(+ (error) => error.attr !== changedFieldName+ );+ return { ...prevErrors, errors: updatedErrors };+ }+ return null;+ });+ };++ const triggerSubmit = () => {+ const body = { ...formDetails };+ body[type] = id;++ if (editDetails) {+ handleUpdate(body, editDetails?.id);+ } else {+ handleSubmit(body);+ }+ };++ const formItems = [+ {+ label: "Name",+ name: "name",+ rules: [{ required: true, message: "Please enter name" }],+ component: <Input />,+ },+ {+ label: "Url",+ name: "url",+ rules: [{ required: true, message: "Please enter URL" }],+ component: <Input />,+ },+ {+ label: "Notification Type",+ name: "notification_type",+ component: <Select options={NOTIFICATION_TYPE_ITEMS} />,+ },+ {+ label: "Platform",+ name: "platform",+ component: <Select options={PLATFORM_TYPES} />,+ },+ {+ label: "Authorization Type",+ name: "authorization_type",+ component: <Select options={AUTHORIZATION_TYPES} />,+ },+ {+ label: "Authorization Header",+ name: "authorization_header",+ component: <Input />,+ },+ {+ label: "Authorization Key",+ name: "authorization_key",+ component: <Input />,+ },+ {+ label: "Max Retries",+ name: "max_retries",+ component: <Input type="number" />,+ },+ ];++ return (+ <Form+ form={form}+ layout="vertical"+ initialValues={formDetails}+ onValuesChange={handleInputChange}+ onFinish={triggerSubmit}+ >+ {formItems.map(({ label, name, rules, component }) => (+ <Form.Item+ key={name}+ label={label}+ name={name}+ rules={rules}+ validateStatus={+ getBackendErrorDetail(name, backendErrors) ? "error" : ""+ }+ help={getBackendErrorDetail(name, backendErrors)}+ >+ {component}+ </Form.Item>+ ))}+ <Form.Item className="display-flex-right">+ <Space>+ <Button onClick={() => setIsForm(false)}>Cancel</Button>+ <Button type="primary" htmlType="submit" loading={isLoading}>+ {editDetails ? "Update" : "Create"} Notification+ </Button>+ </Space>+ </Form.Item>+ </Form>+ );+}++CreateNotification.propTypes = {+ setIsForm: PropTypes.func.isRequired,+ type: PropTypes.string.isRequired,+ id: PropTypes.string.isRequired,+ isLoading: PropTypes.bool.isRequired,+ handleSubmit: PropTypes.func.isRequired,+ handleUpdate: PropTypes.func.isRequired,+ editDetails: PropTypes.object,+};++export { CreateNotification };diff --git a/frontend/src/components/pipelines-or-deployments/notification-modal/DisplayNotifications.jsx b/frontend/src/components/pipelines-or-deployments/notification-modal/DisplayNotifications.jsxnew file mode 100644index 000000000..e52bd653f--- /dev/null+++ b/frontend/src/components/pipelines-or-deployments/notification-modal/DisplayNotifications.jsx@@ -0,0 +1,112 @@+import PropTypes from "prop-types";+import SpaceWrapper from "../../widgets/space-wrapper/SpaceWrapper";+import { Button, Space, Switch, Table, Tooltip } from "antd";+import { DeleteOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons";+import { SpinnerLoader } from "../../widgets/spinner-loader/SpinnerLoader";+import { ConfirmModal } from "../../widgets/confirm-modal/ConfirmModal";++function DisplayNotifications({+ setIsForm,+ rows,+ isLoading,+ updateStatus,+ handleDelete,+ setEditDetails,+}) {+ const columns = [+ {+ title: "Name",+ dataIndex: "name",+ key: "name",+ },+ {+ title: "Type",+ dataIndex: "notification_type",+ key: "notification_type",+ },+ {+ title: "Active",+ key: "is_active",+ dataIndex: "is_active",+ align: "center",+ render: (_, record) => (+ <Switch+ size="small"+ defaultChecked={record?.is_active}+ onChange={() => updateStatus(record)}+ />+ ),+ },+ {+ title: "Actions",+ key: "pipeline_id",+ align: "center",+ render: (_, record) => (+ <>+ <Space className="actions">+ <Tooltip title="edit" className="cursorPointer">+ <Button+ type="text"+ size="small"+ onClick={() => handleEdit(record)}+ >+ <EditOutlined />+ </Button>+ </Tooltip>+ </Space>+ <Space className="actions">+ <Tooltip title="delete" className="cursorPointer">+ <ConfirmModal+ handleConfirm={() => handleDelete(record?.id, record?.name)}+ content="Are you sure you want to delete?"+ >+ <Button type="text" size="small">+ <DeleteOutlined />+ </Button>+ </ConfirmModal>+ </Tooltip>+ </Space>+ </>+ ),+ },+ ];++ const handleEdit = (record) => {+ setIsForm(true);+ setEditDetails(record);+ };++ return (+ <SpaceWrapper>+ <div className="display-flex-right">+ <Button+ type="primary"+ icon={<PlusOutlined />}+ onClick={() => setIsForm(true)}+ >+ Create Notification+ </Button>+ </div>+ <Table+ columns={columns}+ dataSource={rows}+ loading={{+ indicator: <SpinnerLoader />,+ spinning: isLoading,+ }}+ pagination={{ pageSize: 5 }}+ />+ </SpaceWrapper>+ );+}++DisplayNotifications.propTypes = {+ setIsForm: PropTypes.func.isRequired,+ rows: PropTypes.array,+ isLoading: PropTypes.bool.isRequired,+ updateStatus: PropTypes.func.isRequired,+ handleDelete: PropTypes.func.isRequired,+ setEditDetails: PropTypes.func.isRequired,+};++export { DisplayNotifications };diff --git a/frontend/src/components/pipelines-or-deployments/notification-modal/NotificationModal.jsx b/frontend/src/components/pipelines-or-deployments/notification-modal/NotificationModal.jsxnew file mode 100644index 000000000..0e0f7a571--- /dev/null+++ b/frontend/src/components/pipelines-or-deployments/notification-modal/NotificationModal.jsx@@ -0,0 +1,183 @@+import { Modal } from "antd";+import PropTypes from "prop-types";+import { useEffect, useState } from "react";+import { CreateNotification } from "./CreateNotification";+import { DisplayNotifications } from "./DisplayNotifications";+import { pipelineService } from "../pipeline-service";+import { useAlertStore } from "../../../store/alert-store";+import { useExceptionHandler } from "../../../hooks/useExceptionHandler";++function NotificationModal({ open, setOpen, type, id }) {+ const [isForm, setIsForm] = useState(false);+ const [rows, setRows] = useState([]);+ const [isTableLoading, setIsTableLoading] = useState(false);+ const [isFormSubmitLoading, setIsFormSubmitLoading] = useState(false);+ const [editDetails, setEditDetails] = useState(null);+ const pipelineApiService = pipelineService();+ const { setAlertDetails } = useAlertStore();+ const handleException = useExceptionHandler();++ useEffect(() => {+ if (!id || !open) {+ setIsForm(false);+ setRows([]);+ return;+ }++ setIsTableLoading(true);+ pipelineApiService+ .getNotifications(type, id)+ .then((res) => {+ setRows(res?.data || []);+ })+ .catch((err) => {+ setAlertDetails(handleException(err));+ })+ .finally(() => {+ setIsTableLoading(false);+ });+ }, [id, open]);++ useEffect(() => {+ if (!isForm && editDetails) {+ setEditDetails(null);+ }+ }, [isForm]);++ const updateStatus = (record) => {+ const isActive = !record?.is_active;++ const body = {+ ...record,+ ...{+ is_active: isActive,+ },+ };++ handleUpdate(body, record?.id);+ };++ const handleSubmit = (body) => {+ setIsFormSubmitLoading(true);+ pipelineApiService+ .createNotification(body)+ .then((res) => {+ addNewRow(res?.data);+ setIsForm(false);+ setAlertDetails({+ type: "success",+ content: `Successfully created notification: ${body?.name}`,+ });+ })+ .catch((err) => {+ setAlertDetails(handleException(err));+ })+ .finally(() => {+ setIsFormSubmitLoading(false);+ });+ };++ const handleUpdate = (body, id) => {+ setIsFormSubmitLoading(true);+ pipelineApiService+ .updateNotification(body, id)+ .then((res) => {+ updateRow(res?.data);+ setIsForm(false);+ setAlertDetails({+ type: "success",+ content: `Successfully updated notification: ${body?.name}`,+ });+ })+ .catch((err) => {+ setAlertDetails(handleException(err));+ })+ .finally(() => {+ setIsFormSubmitLoading(false);+ });+ };++ const handleDelete = (id, name) => {+ pipelineApiService+ .deleteNotification(id)+ .then(() => {+ removeRow(id);+ setAlertDetails({+ type: "success",+ content: `Successfully delete: ${name}`,+ });+ })+ .catch((err) => {+ setAlertDetails(handleException(err));+ });+ };++ const addNewRow = (newRow) => {+ setRows((prev) => {+ const prevData = [...prev];+ prevData.push(newRow);+ return prevData;+ });+ };++ const updateRow = (updatedRow) => {+ setRows((prev) => {+ const updatedRows = [...prev];+ const index = updatedRows.findIndex(+ (item) => item?.id === updatedRow?.id+ );+ if (index !== -1) {+ updatedRows[index] = updatedRow;+ }+ return updatedRows;+ });+ };++ const removeRow = (id) => {+ setRows((prev) => {+ return prev.filter((item) => item?.id !== id);+ });+ };++ return (+ <Modal+ title="Setup Notifications"+ open={open}+ onCancel={() => setOpen(false)}+ centered+ footer={null}+ maskClosable={false}+ >+ {isForm ? (+ <CreateNotification+ setIsForm={setIsForm}+ addNewRow={addNewRow}+ type={type}+ id={id}+ isLoading={isFormSubmitLoading}+ handleSubmit={handleSubmit}+ handleUpdate={handleUpdate}+ editDetails={editDetails}+ />+ ) : (+ <DisplayNotifications+ setIsForm={setIsForm}+ rows={rows}+ isLoading={isTableLoading}+ updateStatus={updateStatus}+ handleDelete={handleDelete}+ setEditDetails={setEditDetails}+ />+ )}+ </Modal>+ );+}++NotificationModal.propTypes = {+ open: PropTypes.bool.isRequired,+ setOpen: PropTypes.func.isRequired,+ type: PropTypes.string.isRequired,+ id: PropTypes.string,+};++export { NotificationModal };diff --git a/frontend/src/components/pipelines-or-deployments/pipeline-service.js b/frontend/src/components/pipelines-or-deployments/pipeline-service.jsindex 30f1bdd3d..3ba04ae6f 100644--- a/frontend/src/components/pipelines-or-deployments/pipeline-service.js+++ b/frontend/src/components/pipelines-or-deployments/pipeline-service.js@@ -54,6 +54,39 @@ function pipelineService() {};return axiosPrivate(requestOptions);},+ getNotifications: (type, id) => {+ const requestOptions = {+ method: "GET",+ url: `${path}/notifications/${type}/${id}/`,+ };+ return axiosPrivate(requestOptions);+ },+ createNotification: (body) => {+ const requestOptions = {+ method: "POST",+ url: `${path}/notifications/`,+ headers: requestHeaders,+ data: body,+ };+ return axiosPrivate(requestOptions);+ },+ updateNotification: (body, id) => {+ const requestOptions = {+ method: "PUT",+ url: `${path}/notifications/${id}/`,+ headers: requestHeaders,+ data: body,+ };+ return axiosPrivate(requestOptions);+ },+ deleteNotification: (id) => {+ const requestOptions = {+ method: "DELETE",+ url: `${path}/notifications/${id}/`,+ headers: requestHeaders,+ };+ return axiosPrivate(requestOptions);+ },};}diff --git a/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx b/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsxindex 78fab027f..d379cce4b 100644--- a/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx+++ b/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx@@ -6,6 +6,8 @@ import {HighlightOutlined,FileSearchOutlined,ReloadOutlined,+ NotificationOutlined,+ EditOutlined,KeyOutlined,CloudDownloadOutlined,CopyOutlined,@@ -41,6 +43,7 @@ import { useExceptionHandler } from "../../../hooks/useExceptionHandler.jsx";import { pipelineService } from "../pipeline-service.js";import { ManageKeys } from "../../deployments/manage-keys/ManageKeys.jsx";import usePipelineHelper from "../../../hooks/usePipelineHelper.js";+import { NotificationModal } from "../notification-modal/NotificationModal.jsx";function Pipelines({ type }) {const [tableData, setTableData] = useState([]);@@ -62,6 +65,7 @@ function Pipelines({ type }) {const pipelineApiService = pipelineService();const { getApiKeys, downloadPostmanCollection, copyUrl } =usePipelineHelper();+ const [openNotificationModal, setOpenNotificationModal] = useState(false);const handleFetchLogs = (page, pageSize) => {fetchExecutionLogs(@@ -299,6 +303,23 @@ function Pipelines({ type }) {const actionItems = [{key: "1",+ label: (+ <Space+ direction="horizontal"+ className="action-items"+ onClick={() => openAddModal(true)}+ >+ <div>+ <EditOutlined />+ </div>+ <div>+ <Typography.Text>Edit</Typography.Text>+ </div>+ </Space>+ ),+ },+ {+ key: "2",label: (<Spacedirection="horizontal"@@ -311,7 +332,7 @@ function Pipelines({ type }) {),},{- key: "2",+ key: "3",label: (<Spacedirection="horizontal"@@ -331,7 +352,7 @@ function Pipelines({ type }) {),},{- key: "3",+ key: "4",label: (<Spacedirection="horizontal"@@ -346,7 +367,7 @@ function Pipelines({ type }) {),},{- key: "4",+ key: "5",label: (<Spacedirection="horizontal"@@ -370,7 +391,7 @@ function Pipelines({ type }) {),},{- key: "5",+ key: "6",label: (<Spacedirection="horizontal"@@ -383,7 +404,7 @@ function Pipelines({ type }) {),},{- key: "6",+ key: "7",label: (<Spacedirection="horizontal"@@ -396,7 +417,7 @@ function Pipelines({ type }) {),},{- key: "7",+ key: "8",label: (<Spacedirection="horizontal"@@ -412,6 +433,19 @@ function Pipelines({ type }) {</Space>),},+ {+ key: "9",+ label: (+ <Space+ direction="horizontal"+ className="action-items"+ onClick={() => setOpenNotificationModal(true)}+ >+ <NotificationOutlined />+ <Typography.Text>Setup Notifications</Typography.Text>+ </Space>+ ),+ },];const columns = [@@ -606,6 +640,12 @@ function Pipelines({ type }) {apiService={pipelineApiService}type={deploymentApiTypes.pipeline}/>+ <NotificationModal+ open={openNotificationModal}+ setOpen={setOpenNotificationModal}+ type={deploymentApiTypes.pipeline}+ id={selectedPorD?.id}+ /></div>);}