Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

Added cron selector and edit Task/ETL pipeline (#155)

Siddhiqfec8edef693b
diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.py
index b8e1fd669..6b9df69a0 100644
--- a/backend/backend/settings/base.py
+++ b/backend/backend/settings/base.py
@@ -205,7 +205,6 @@ TENANT_APPS = (
"workflow_manager.workflow",
"tool_instance",
"pipeline",
- "cron_expression_generator",
"platform_settings",
"api",
"prompt_studio.prompt_profile_manager",
diff --git a/backend/backend/urls.py b/backend/backend/urls.py
index 2a3beb0c0..888e14464 100644
--- a/backend/backend/urls.py
+++ b/backend/backend/urls.py
@@ -28,7 +28,6 @@ urlpatterns = [
path("", include("adapter_processor.urls")),
path("", include("file_management.urls")),
path("", include("tool_instance.urls")),
- path("", include("cron_expression_generator.urls")),
path("", include("pipeline.urls")),
path("", include("apps.urls")),
path("workflow/", include("workflow_manager.urls")),
diff --git a/backend/cron_expression_generator/__init__.py b/backend/cron_expression_generator/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/backend/cron_expression_generator/constants.py b/backend/cron_expression_generator/constants.py
deleted file mode 100644
index 77c33c2aa..000000000
--- a/backend/cron_expression_generator/constants.py
+++ /dev/null
@@ -1,7 +0,0 @@
-class CronKeys:
- CRON_STRING = "cron_string"
- FREQUENCY = "frequency"
- SUMMARY = "summary"
- # For caching
- CRON_CACHE_STATUS = "is_cleared"
- ORG_ID = "org_id"
diff --git a/backend/cron_expression_generator/descriptor.py b/backend/cron_expression_generator/descriptor.py
deleted file mode 100644
index 6b1aace6d..000000000
--- a/backend/cron_expression_generator/descriptor.py
+++ /dev/null
@@ -1,33 +0,0 @@
-import logging
-
-from cron_descriptor import CasingTypeEnum, ExpressionDescriptor, FormatException
-from cron_expression_generator.exceptions import CronDescriptionError
-
-logger = logging.getLogger(__name__)
-
-
-class CronDescriptor:
- """Describes a cron deterministically with `cron-expression-description`"""
-
- @staticmethod
- def describe_cron(cron: str) -> str:
- """Given a cron string, gives a human readable summary of it.
-
- Args:
- cron (str): Cron to summarize
-
- Returns:
- str: Human readable summary of the cron string
- """
- summary = ""
- logger.info(f"Describing cron: {cron}")
- try:
- descriptor = ExpressionDescriptor(
- expression=cron,
- casing_type=CasingTypeEnum.Sentence,
- use_24hour_time_format=True,
- )
- summary = descriptor.get_full_description()
- except FormatException:
- raise CronDescriptionError("Incorrect cron string format")
- return summary
diff --git a/backend/cron_expression_generator/exceptions.py b/backend/cron_expression_generator/exceptions.py
deleted file mode 100644
index ad3f4cba6..000000000
--- a/backend/cron_expression_generator/exceptions.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from rest_framework.exceptions import APIException
-
-
-class CronGenerationError(APIException):
- status_code = 424
- default_detail = "Error generating schedule."
-
-
-class CronDescriptionError(APIException):
- status_code = 500
- default_detail = "Error while summarizing schedule."
diff --git a/backend/cron_expression_generator/generator.py b/backend/cron_expression_generator/generator.py
deleted file mode 100644
index c20ccd826..000000000
--- a/backend/cron_expression_generator/generator.py
+++ /dev/null
@@ -1,59 +0,0 @@
-import logging
-from typing import Optional
-
-from backend.exceptions import LLMHelperError
-from unstract.core.llm_helper.enums import LLMResult, PromptContext
-from unstract.core.llm_helper.llm_helper import LLMHelper
-from unstract.core.llm_helper.models import LLMResponse
-
-logger = logging.getLogger(__name__)
-
-
-class CronGenerator:
- """Uses LLM to generate a cron string for a user input of frequency."""
-
- @staticmethod
- def generate_cron(frequency: str, cache_key_prefix: Optional[str] = None) -> str:
- """Generates cron for a user provided description of frequency.
-
- Uses LLM to prefix the user input with a prompt template and generate cron
-
- Args:
- frequency (str): User provided input
- cache_key (Optional[str], optional): Key to cache against. Defaults to None.
-
- Returns:
- str: Generated cron string
- """
- cron_response: LLMResponse
- logging.info(f"Generating cron for '{frequency}'")
- use_cache = True
- if cache_key_prefix is None:
- use_cache = False
- cron_llm = LLMHelper(
- cache_key_prefix=cache_key_prefix,
- prompt_context=PromptContext.GENERATE_CRON_STRING,
- )
- cron_response = cron_llm.get_response_from_llm(
- prompt=frequency, use_cache=use_cache
- )
- if use_cache is False:
- logging.info(
- f"Cron generation LLM call - Elapsed: {cron_response.time_taken:.3f}s"
- )
- if cron_response.result.value == LLMResult.NOK.value:
- raise LLMHelperError(cron_response.output)
- output: str = cron_response.output
- return output
-
- @staticmethod
- def clear_cron_cache(cache_key_prefix: str) -> bool:
- cleared_count = 0
- cron_llm = LLMHelper(
- cache_key_prefix=cache_key_prefix,
- prompt_context=PromptContext.GENERATE_CRON_STRING,
- )
- cleared_count = cron_llm.clear_cache()
- if cleared_count == -1:
- return False
- return True
diff --git a/backend/cron_expression_generator/serializer.py b/backend/cron_expression_generator/serializer.py
deleted file mode 100644
index 70cb22fc3..000000000
--- a/backend/cron_expression_generator/serializer.py
+++ /dev/null
@@ -1,12 +0,0 @@
-import logging
-
-from backend.constants import FieldLengthConstants as FLC
-from rest_framework import serializers
-
-logger = logging.getLogger(__name__)
-
-
-class CronGenerateSerializer(serializers.Serializer):
- frequency = serializers.CharField(max_length=FLC.CRON_LENGTH, required=False)
- cron_string = serializers.CharField(max_length=FLC.CRON_LENGTH, required=False)
- summary = serializers.CharField(max_length=FLC.CRON_LENGTH, required=False)
diff --git a/backend/cron_expression_generator/urls.py b/backend/cron_expression_generator/urls.py
deleted file mode 100644
index c0e05c482..000000000
--- a/backend/cron_expression_generator/urls.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from cron_expression_generator.views import CronViewSet
-from django.urls import path
-from rest_framework.urlpatterns import format_suffix_patterns
-
-cron_generate = CronViewSet.as_view({"post": "generate"})
-cron_clear_cache = CronViewSet.as_view({"get": "clear_cron_cache"})
-
-urlpatterns = format_suffix_patterns(
- [
- path("cron/generate/", cron_generate, name="cron-generate"),
- path("cron/clear-cache/", cron_clear_cache, name="cron-clear-cache"),
- ]
-)
diff --git a/backend/cron_expression_generator/views.py b/backend/cron_expression_generator/views.py
deleted file mode 100644
index 897dc084d..000000000
--- a/backend/cron_expression_generator/views.py
+++ /dev/null
@@ -1,64 +0,0 @@
-import logging
-
-from cron_expression_generator.constants import CronKeys
-from cron_expression_generator.descriptor import CronDescriptor
-from cron_expression_generator.exceptions import (
- CronDescriptionError,
- CronGenerationError,
-)
-from cron_expression_generator.generator import CronGenerator
-from cron_expression_generator.serializer import CronGenerateSerializer
-from rest_framework import status, viewsets
-from rest_framework.request import Request
-from rest_framework.response import Response
-from rest_framework.versioning import URLPathVersioning
-
-logger = logging.getLogger(__name__)
-
-
-class CronViewSet(viewsets.GenericViewSet, viewsets.mixins.CreateModelMixin):
- versioning_class = URLPathVersioning
- serializer_class = CronGenerateSerializer
-
- def generate(self, request: Request) -> Response:
- """For an input of `frequency`, generates the cron string and summary.
-
- For an input of `cron_string`, generates the summary alone.
- """
- serializer = self.get_serializer(data=request.data)
- serializer.is_valid(raise_exception=True)
- frequency_from_user = serializer.validated_data.get(CronKeys.FREQUENCY)
- cron_string = serializer.validated_data.get(CronKeys.CRON_STRING)
- if frequency_from_user:
- cache_key_prefix = request.org_id
- try:
- cron_string = CronGenerator.generate_cron(
- frequency=frequency_from_user, cache_key_prefix=cache_key_prefix
- )
- serializer.validated_data[CronKeys.CRON_STRING] = cron_string
- except Exception as e:
- logger.error(
- f"Error generating cron for input: '{frequency_from_user}'"
- f", error: {e}"
- )
- raise CronGenerationError()
-
- if cron_string:
- try:
- serializer.validated_data[
- CronKeys.SUMMARY
- ] = CronDescriptor.describe_cron(cron=cron_string)
- except Exception as e:
- logger.error(
- f"Error describing cron for input: '{cron_string}', error: {e}"
- )
- raise CronDescriptionError()
- return Response(serializer.validated_data, status=status.HTTP_200_OK)
-
- def clear_cron_cache(self, request: Request) -> Response:
- """Clears the cache used for cron generation."""
- cache_key_prefix = request.query_params.get(CronKeys.ORG_ID, request.org_id)
- is_cleared = CronGenerator.clear_cron_cache(cache_key_prefix=cache_key_prefix)
- return Response(
- {CronKeys.CRON_CACHE_STATUS: is_cleared}, status=status.HTTP_200_OK
- )
diff --git a/backend/pipeline/constants.py b/backend/pipeline/constants.py
index 42211de6d..970a3f277 100644
--- a/backend/pipeline/constants.py
+++ b/backend/pipeline/constants.py
@@ -47,7 +47,7 @@ class PipelineKey:
CRON_DATA = "cron_data"
WORKFLOW_NAME = "workflow_name"
WORKFLOW_ID = "workflow_id"
- CRON_SUMMARY = "cron_summary"
+ CRON_STRING = "cron_string"
PIPELINE_ID = "pipeline_id"
diff --git a/backend/pipeline/serializers/crud.py b/backend/pipeline/serializers/crud.py
index 07c2f781a..3a3fdf721 100644
--- a/backend/pipeline/serializers/crud.py
+++ b/backend/pipeline/serializers/crud.py
@@ -5,17 +5,11 @@ from typing import Any
from connector.connector_instance_helper import ConnectorInstanceHelper
from connector.models import ConnectorInstance
from connector_processor.connector_processor import ConnectorProcessor
-from cron_expression_generator.constants import CronKeys
-from cron_expression_generator.descriptor import CronDescriptor
-from cron_expression_generator.exceptions import CronDescriptionError
from pipeline.constants import PipelineConstants as PC
from pipeline.constants import PipelineKey as PK
from pipeline.models import Pipeline
-from rest_framework.exceptions import ValidationError
-from rest_framework.serializers import UUIDField
from scheduler.helper import SchedulerHelper
from utils.serializer_utils import SerializerUtils
-from workflow_manager.workflow.constants import WorkflowKey
from backend.serializers import AuditSerializer
from unstract.connectors.connectorkit import Connectorkit
@@ -24,21 +18,10 @@ logger = logging.getLogger(__name__)
class PipelineSerializer(AuditSerializer):
- workflow_id = UUIDField(write_only=True)
class Meta:
model = Pipeline
fields = "__all__"
- extra_kwargs = {
- PK.WORKFLOW: {
- "required": False,
- },
- }
-
- def to_internal_value(self, data: dict[str, str]) -> OrderedDict[str, str]:
- if WorkflowKey.WF_ID in data:
- data[PK.WORKFLOW] = data[WorkflowKey.WF_ID]
- return super().to_internal_value(data) # type: ignore
def create(self, validated_data: dict[str, Any]) -> Any:
# TODO: Deduce pipeline type based on WF?
@@ -54,34 +37,6 @@ class PipelineSerializer(AuditSerializer):
)
return pipeline
- def validate_cron_string(self, value: str) -> str:
- try:
- CronDescriptor.describe_cron(value)
- except CronDescriptionError:
- raise ValidationError("Cron schedule is of invalid format")
- return value
-
- def _add_cron_summary(
- self, repr: OrderedDict[str, Any]
- ) -> OrderedDict[str, Any]:
- """Adds cron_summary in place if cron_string is present as a separate
- JSON.
-
- Args:
- repr (OrderedDict[str, Any]): Dict that has to be returned to
- the user
-
- Returns:
- OrderedDict[str, Any]: repr with the cron string and its summary
- """
- cron_string = repr.pop(CronKeys.CRON_STRING)
- if cron_string:
- repr[PK.CRON_DATA] = {
- CronKeys.CRON_STRING: cron_string,
- PK.CRON_SUMMARY: CronDescriptor.describe_cron(cron_string),
- }
- return repr
-
def _get_name_and_icon(
self, connectors: list[Any], connector_id: Any
) -> Any:
@@ -138,7 +93,7 @@ class PipelineSerializer(AuditSerializer):
)
repr[PK.WORKFLOW_ID] = workflow.id
repr[PK.WORKFLOW_NAME] = workflow.workflow_name
- repr = self._add_cron_summary(repr=repr)
+ repr[PK.CRON_STRING] = repr.pop(PK.CRON_STRING)
repr = self._add_connector_data(
repr=repr,
connector_instance_list=connector_instance_list,
diff --git a/backend/pipeline/views.py b/backend/pipeline/views.py
index 4f003dddc..34c1fb05d 100644
--- a/backend/pipeline/views.py
+++ b/backend/pipeline/views.py
@@ -2,7 +2,6 @@ import logging
from typing import Any, Optional
from account.custom_exceptions import DuplicateData
-from cron_expression_generator.constants import CronKeys
from django.db import IntegrityError
from django.db.models import QuerySet
from drf_yasg import openapi
@@ -14,7 +13,6 @@ from pipeline.constants import (
PipelineExecutionKey,
)
from pipeline.constants import PipelineKey as PK
-from pipeline.exceptions import MandatoryCronSchedule, MandatoryWorkflowId
from pipeline.manager import PipelineManager
from pipeline.models import Pipeline
from pipeline.pipeline_processor import PipelineProcessor
@@ -31,7 +29,6 @@ from scheduler.helper import SchedulerHelper
from workflow_manager.workflow.constants import (
WorkflowExecutionKey as WFExecKey,
)
-from workflow_manager.workflow.constants import WorkflowKey
logger = logging.getLogger(__name__)
@@ -96,14 +93,6 @@ class PipelineViewSet(viewsets.ModelViewSet):
return Response(data=response_data, status=status.HTTP_200_OK)
def create(self, request: Request) -> Response:
- workflow_id = request.data.get(WorkflowKey.WF_ID)
- cron_string = request.data.get(CronKeys.CRON_STRING)
- # TODO: Remove these checks once ValidationError is handled properly
- if not workflow_id:
- raise MandatoryWorkflowId()
- if not cron_string:
- raise MandatoryCronSchedule()
-
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
diff --git a/backend/scheduler/constants.py b/backend/scheduler/constants.py
index 30067f8c9..b7c33ac49 100644
--- a/backend/scheduler/constants.py
+++ b/backend/scheduler/constants.py
@@ -6,6 +6,7 @@ class SchedulerConstants:
NAME = "name"
JOB_KWARGS = "job_kwargs"
SCHEDULER_KWARGS = "scheduler_kwargs"
+ CRON_STRING = "cron_string"
# Default strings
DEFAULT_CRON_STRING = "0 9 * * 1"
diff --git a/backend/scheduler/helper.py b/backend/scheduler/helper.py
index 7d4aa1c84..110b5398e 100644
--- a/backend/scheduler/helper.py
+++ b/backend/scheduler/helper.py
@@ -1,6 +1,5 @@
import logging
-from cron_expression_generator.constants import CronKeys
from django.core.exceptions import ValidationError
from scheduler import views
from scheduler.constants import SchedulerConstants as SC
@@ -20,7 +19,7 @@ class SchedulerHelper:
name = f"Pipeline job-{pipeline_id}"
job_serialize_data = {
SC.ID: pipeline_id,
- CronKeys.CRON_STRING: cron_string,
+ SC.CRON_STRING: cron_string,
SC.NAME: name,
}
try:
diff --git a/frontend/package.json b/frontend/package.json
index 4a1771e61..66bf3e84b 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -17,6 +17,7 @@
"antd": "^5.5.1",
"axios": "^1.4.0",
"cron-validator": "^1.3.1",
+ "cronstrue": "^2.48.0",
"emoji-picker-react": "^4.8.0",
"emoji-regex": "^10.3.0",
"escape-html": "^1.0.3",
@@ -32,6 +33,7 @@
"react-dnd": "^16.0.1",
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^18.2.0",
+ "react-js-cron": "^5.0.1",
"react-router-dom": "^6.11.2",
"react-scripts": "5.0.1",
"react-social-login-buttons": "^3.9.1",
diff --git a/frontend/src/components/cron-generator/CronGenerator.jsx b/frontend/src/components/cron-generator/CronGenerator.jsx
new file mode 100644
index 000000000..938567132
--- /dev/null
+++ b/frontend/src/components/cron-generator/CronGenerator.jsx
@@ -0,0 +1,38 @@
+import { useState } from "react";
+import { Modal } from "antd";
+import { Cron } from "react-js-cron";
+import "react-js-cron/dist/styles.css";
+import PropTypes from "prop-types";
+
+function CronGenerator({ open, showCronGenerator, setCronValue }) {
+ const [cronState, setCronState] = useState("0 * * * *");
+ const handleCancel = () => {
+ showCronGenerator(false);
+ };
+
+ const updateCron = () => {
+ setCronValue(cronState);
+ handleCancel();
+ };
+
+ return (
+ <Modal
+ title="Choose Cron schedule"
+ open={open}
+ maskClosable={false}
+ closable={false}
+ onCancel={handleCancel}
+ onOk={updateCron}
+ >
+ <Cron value={cronState} setValue={setCronState} />
+ </Modal>
+ );
+}
+
+CronGenerator.propTypes = {
+ open: PropTypes.bool.isRequired,
+ showCronGenerator: PropTypes.func.isRequired,
+ setCronValue: PropTypes.func.isRequired,
+};
+
+export default CronGenerator;
diff --git a/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.css b/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.css
index 0785b4c1c..d267eac3f 100644
--- a/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.css
+++ b/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.css
@@ -1 +1,28 @@
/* Styles for EtlTaskDeploy */
+.ant-form .ant-form-item{
+ margin-bottom: 12px;
+}
+
+.cron-string-div {
+ display: flex;
+}
+
+.cron-string-div .cron-string-input {
+ width: 75%;
+}
+
+.cron-string-div .cron-string-btn {
+ width: 20%;
+ margin-left: 5%;
+}
+
+.cron-summary-div {
+ border: solid 1px #cccccc;
+ padding: 4px 8px;
+ border-radius: 5px;
+}
+
+.summary-text {
+ font-size: 10px;
+ opacity: 0.6;
+}
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.jsx
index 1444c1971..60bc8a609 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
@@ -1,34 +1,22 @@
-import { InfoCircleOutlined, ScheduleOutlined } from "@ant-design/icons";
-import { Input, Modal, Select, Space, Tooltip } from "antd";
-import Typography from "antd/es/typography/Typography";
-import { isValidCron } from "cron-validator";
+import { Form, Input, Modal, Select, Space, Typography, Button } from "antd";
import PropTypes from "prop-types";
import { useEffect, useState } from "react";
+import { ScheduleOutlined, ClockCircleOutlined } from "@ant-design/icons";
+import cronstrue from "cronstrue";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate.js";
import { useAlertStore } from "../../../store/alert-store";
import { useSessionStore } from "../../../store/session-store";
-import { CustomButton } from "../../widgets/custom-button/CustomButton.jsx";
-import SpaceWrapper from "../../widgets/space-wrapper/SpaceWrapper.jsx";
-import { SpinnerLoader } from "../../widgets/spinner-loader/SpinnerLoader.jsx";
+import CronGenerator from "../../cron-generator/CronGenerator.jsx";
import { workflowService } from "../../workflows/workflow/workflow-service.js";
import "./EtlTaskDeploy.css";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler.jsx";
import { useWorkflowStore } from "../../../store/workflow-store.js";
-
-const days = [
- "Monday",
- "Tuesday",
- "Wednesday",
- "Thursday",
- "Friday",
- "Saturday",
- "Sunday",
-];
+import { getBackendErrorDetail } from "../../../helpers/GetStaticData.js";
const defaultFromDetails = {
pipeline_name: "",
- workflow_id: "",
+ workflow: "",
cron_string: "",
};
@@ -39,8 +27,11 @@ const EtlTaskDeploy = ({
title,
setTableData,
workflowId,
+ isEdit,
+ selectedRow = {},
setDeploymentName,
}) => {
+ const [form] = Form.useForm();
const workflowStore = useWorkflowStore();
const { updateWorkflow } = workflowStore;
const { sessionDetails } = useSessionStore();
@@ -51,20 +42,26 @@ const EtlTaskDeploy = ({
const { Option } = Select;
const [workflowList, setWorkflowList] = useState([]);
- const [formDetails, setFormDetails] = useState({ ...defaultFromDetails });
- const [frequency, setFrequency] = useState("");
- const [summary, setSummary] = useState("");
- const [isGenerateCronLoading, setGenerateCronString] = useState(false);
- const [isSummaryLoading, setSummaryLoading] = useState(false);
- const [isCronStringValid, setCronStringValid] = useState(true);
+ const [formDetails, setFormDetails] = useState(
+ isEdit ? { ...selectedRow } : { ...defaultFromDetails }
+ );
const [isLoading, setLoading] = useState(false);
+ const [openCronGenerator, setOpenCronGenerator] = useState(false);
+ const [backendErrors, setBackendErrors] = useState(null);
+ const [summary, setSummary] = useState(null);
useEffect(() => {
if (workflowId) {
- setFormDetails({ ...formDetails, workflow_id: workflowId });
+ setFormDetails({ ...formDetails, workflow: workflowId });
}
}, [workflowId]);
+ useEffect(() => {
+ if (formDetails?.cron_string) {
+ setSummary(cronstrue.toString(formDetails.cron_string));
+ }
+ }, [formDetails]);
+
const getWorkflowList = () => {
workflowApiService
.getWorkflowList()
@@ -75,6 +72,27 @@ const EtlTaskDeploy = ({
console.error("Unable to get workflow list");
});
};
+
+ 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 getWorkflows = () => {
const connectorType = type === "task" ? "FILESYSTEM" : "DATABASE";
workflowApiService
@@ -99,159 +117,64 @@ const EtlTaskDeploy = ({
}
}, [type]);
- const onChangeHandler = (propertyName, value) => {
- const body = {
- [propertyName]: value,
- };
- setFormDetails({ ...formDetails, ...body });
+ const clearFormDetails = () => {
+ setFormDetails({ ...defaultFromDetails });
};
- useEffect(() => {
- if (open) {
- // Set default value for the form fields
- setRandomFrequency();
- }
- }, [open]);
-
- useEffect(() => {
- const cronString = formDetails?.cron_string || "";
- if (cronString?.length === 0 || isValidCron(cronString)) {
- setCronStringValid(true);
- return;
- }
- setCronStringValid(false);
- }, [formDetails?.cron_string]);
-
- useEffect(() => {
- const cronString = formDetails?.cron_string || "";
- if (
- isCronStringValid &&
- cronString?.length > 0 &&
- isValidCron(cronString)
- ) {
- handleSummaryGeneration();
- }
- }, [isCronStringValid, formDetails?.cron_string]);
-
- const setRandomFrequency = () => {
- // Generate a random number between 0 (inclusive) and 7 (exclusive)
- const randomNumber = Math.floor(Math.random() * 7);
-
- const randomFrequency = `Every ${days[randomNumber]} at 9:00 AM`;
- setFrequency(randomFrequency);
+ const showCronGenerator = () => {
+ setOpenCronGenerator(true);
};
- const clearFormDetails = () => {
- setFrequency("");
- setSummary("");
- setFormDetails({ ...defaultFromDetails });
+ const setCronValue = (value) => {
+ const updatedValues = { ["cron_string"]: value };
+ setFormDetails({ ...formDetails, ...updatedValues });
};
const handleCancel = () => {
setOpen(false);
};
- const handleGenerateCronString = () => {
- if (!frequency) {
- return;
- }
-
- const body = {
- frequency,
- };
- const requestOptions = {
- method: "POST",
- url: `/api/v1/unstract/${sessionDetails.orgId}/cron/generate/`,
- headers: {
- "Content-Type": "application/json",
- "X-CSRFToken": sessionDetails?.csrfToken,
- },
- data: body,
- };
-
- const newFormDetails = { ...formDetails };
-
- setGenerateCronString(true);
- axiosPrivate(requestOptions)
- .then((res) => {
- const data = res?.data;
- newFormDetails["cron_string"] = data?.cron_string;
- })
- .catch((err) => {
- const msg = "Failed to generate the cron schedule.";
- setAlertDetails(handleException(err, msg));
- })
- .finally(() => {
- setFormDetails({ ...formDetails, ...newFormDetails });
- setGenerateCronString(false);
- });
+ const addPipeline = (pipeline) => {
+ setTableData((prev) => {
+ const prevData = [...prev];
+ prevData.push(pipeline);
+ return prevData;
+ });
};
- const handleSummaryGeneration = () => {
- const cronString = formDetails?.cron_string;
- if (!cronString) {
- return;
- }
-
- const body = {
- cron_string: cronString,
- };
+ const updatePipeline = () => {
+ const body = formDetails;
+ body["pipeline_type"] = type.toUpperCase();
const requestOptions = {
- method: "POST",
- url: `/api/v1/unstract/${sessionDetails.orgId}/cron/generate/`,
+ method: "PUT",
+ url: `/api/v1/unstract/${sessionDetails?.orgId}/pipeline/${body?.id}/`,
headers: {
"Content-Type": "application/json",
"X-CSRFToken": sessionDetails?.csrfToken,
},
data: body,
};
-
- setSummaryLoading(true);
- setSummary("");
+ setLoading(true);
axiosPrivate(requestOptions)
.then((res) => {
- const data = res?.data;
- setSummary(data?.summary);
+ addPipeline(res?.data);
+ setOpen(false);
+ clearFormDetails();
+ setAlertDetails({
+ type: "success",
+ content: "Pipeline Updated Successfully",
+ });
})
.catch((err) => {
- const msg = "No data.";
- setAlertDetails(handleException(err, msg));
+ setAlertDetails(handleException(err, "", setBackendErrors));
})
.finally(() => {
- setSummaryLoading(false);
+ setLoading(false);
});
};
- const addPipeline = (pipeline) => {
- setTableData((prev) => {
- const prevData = [...prev];
- prevData.push(pipeline);
- return prevData;
- });
- };
-
const createPipeline = () => {
- if (
- !formDetails?.pipeline_name ||
- !formDetails?.workflow_id ||
- !formDetails?.cron_string
- ) {
- setAlertDetails({
- type: "error",
- content: "Please enter all the fields.",
- });
- return;
- }
-
- if (!isValidCron(formDetails?.cron_string)) {
- setAlertDetails({
- type: "error",
- content: "Invalid cron schedule.",
- });
- return;
- }
-
const body = formDetails;
body["pipeline_type"] = type.toUpperCase();
@@ -283,7 +206,7 @@ const EtlTaskDeploy = ({
});
})
.catch((err) => {
- setAlertDetails(handleException(err));
+ setAlertDetails(handleException(err, "", setBackendErrors));
})
.finally(() => {
setLoading(false);
@@ -293,12 +216,12 @@ const EtlTaskDeploy = ({
return (
<>
<Modal
- title={title}
+ title={isEdit ? `Update ${title}` : `Add ${title}`}
centered
open={open}
- onOk={createPipeline}
+ onOk={isEdit ? updatePipeline : createPipeline}
onCancel={handleCancel}
- okText="Save and Deploy"
+ okText={isEdit ? "Update and Deploy" : "Save and Deploy"}
okButtonProps={{
loading: isLoading,
}}
@@ -306,98 +229,96 @@ const EtlTaskDeploy = ({
closable={true}
maskClosable={false}
>
- <SpaceWrapper>
- <SpaceWrapper direction="vertical" style={{ width: "100%" }}>
- <Typography>Display Name</Typography>
- <Input
- placeholder="Name"
- name="pipeline_name"
- onChange={(e) => onChangeHandler("pipeline_name", e.target.value)}
- value={formDetails.pipeline_name || ""}
- ></Input>
- </SpaceWrapper>
+ <Form
+ form={form}
+ name="myForm"
+ layout="vertical"
+ initialValues={formDetails}
+ onValuesChange={handleInputChange}
+ >
+ <Form.Item
+ label="Display Name"
+ name="pipeline_name"
+ rules={[{ required: true, message: "Please enter display name" }]}
+ validateStatus={
+ getBackendErrorDetail("pipeline_name", backendErrors)
+ ? "error"
+ : ""
+ }
+ help={getBackendErrorDetail("pipeline_name", backendErrors)}
+ >
+ <Input placeholder="Name" />
+ </Form.Item>
+
{!workflowId && (
- <SpaceWrapper>
- <Typography>Workflow</Typography>
- <Select
- placeholder="select workflow"
- style={{
- width: "100%",
- }}
- onChange={(value) => onChangeHandler("workflow_id", value)}
- name="workflow_id"
- value={formDetails.workflow_id || ""}
- >
+ <Form.Item
+ label="Workflow"
+ name="workflow"
+ rules={[{ required: true, message: "Please select an workflow" }]}
+ validateStatus={
+ getBackendErrorDetail("workflow", backendErrors) ? "error" : ""
+ }
+ help={getBackendErrorDetail("workflow", backendErrors)}
+ >
+ <Select>
{workflowList.map((workflow) => {
return (
- <Option value={workflow.id} key={workflow.id}>
+ <Option value={workflow.id} key={workflow.workflow_name}>
{workflow.workflow_name}
</Option>
);
})}
</Select>
- </SpaceWrapper>
+ </Form.Item>
)}
- <SpaceWrapper>
- <Typography>
- Frequency of runs
- <Tooltip title="This feature is currently in the experimental phase. Please provide a plain English description of the schedule you have in mind, and I will generate an appropriate Cron schedule for you. You can also directly edit the Cron schedule if it's generated incorrectly.">
- <InfoCircleOutlined
- style={{ marginLeft: "8px", color: "#5A5A5A" }}
- />
- </Tooltip>
- </Typography>
- <Input.TextArea
- rows={3}
- placeholder="Frequency"
- name="frequency"
- onChange={(e) => setFrequency(e.target.value)}
- value={frequency || ""}
- />
- <div className="display-flex-right">
- <CustomButton
+ <Form.Item
+ label="Cron Schedule"
+ name="cron_string"
+ rules={[
+ {
+ required: true,
+ message: "Please add cron schedule",
+ },
+ ]}
+ validateStatus={
+ getBackendErrorDetail("cron_string", backendErrors) ? "error" : ""
+ }
+ help={getBackendErrorDetail("cron_string", backendErrors)}
+ >
+ <div className="cron-string-div">
+ <Input
+ readOnly={true}
+ disabled={true}
+ value={formDetails?.cron_string}
+ className="cron-string-input"
+ />
+ <Button
type="primary"
- onClick={handleGenerateCronString}
- loading={isGenerateCronLoading}
- >
- Generate Cron Schedule
- </CustomButton>
+ onClick={showCronGenerator}
+ icon={<ScheduleOutlined />}
+ className="cron-string-btn"
+ />
</div>
- </SpaceWrapper>
- <SpaceWrapper>
- <Typography>Cron Schedule</Typography>
- <Input
- placeholder="Cron Schedule"
- name="cron_string"
- value={formDetails?.cron_string || ""}
- onChange={(e) => onChangeHandler("cron_string", e.target.value)}
- status={isCronStringValid === false && "error"}
- />
- </SpaceWrapper>
+ </Form.Item>
<Space>
- <div
- style={{
- border: "solid 1px #cccccc",
- padding: "4px 8px",
- borderRadius: "5px",
- }}
- >
- <ScheduleOutlined />
+ <div className="cron-summary-div">
+ <ClockCircleOutlined />
</div>
<div>
- {isSummaryLoading ? (
- <SpinnerLoader />
- ) : (
- <Typography.Text style={{ fontSize: "10px", opacity: 0.6 }}>
- {isCronStringValid && summary
- ? summary
- : "Summary not available."}
- </Typography.Text>
- )}
+ <Typography.Text className="summary-text">
+ {summary ? summary : "Summary not available."}
+ </Typography.Text>
</div>
</Space>
- </SpaceWrapper>
+ </Form>
</Modal>
+ {openCronGenerator && (
+ <CronGenerator
+ open={openCronGenerator}
+ showCronGenerator={setOpenCronGenerator}
+ setCronValue={setCronValue}
+ />
+ )}
</>
);
};
@@ -408,6 +329,8 @@ EtlTaskDeploy.propTypes = {
title: PropTypes.string.isRequired,
setTableData: PropTypes.func,
workflowId: PropTypes.string,
+ isEdit: PropTypes.bool,
+ selectedRow: PropTypes.object,
setDeploymentName: PropTypes.func,
};
export { EtlTaskDeploy };
diff --git a/frontend/src/components/pipelines-or-deployments/pipelines-or-deployments/PipelinesOrDeployments.jsx b/frontend/src/components/pipelines-or-deployments/pipelines-or-deployments/PipelinesOrDeployments.jsx
index 1c61136b2..698277502 100644
--- a/frontend/src/components/pipelines-or-deployments/pipelines-or-deployments/PipelinesOrDeployments.jsx
+++ b/frontend/src/components/pipelines-or-deployments/pipelines-or-deployments/PipelinesOrDeployments.jsx
@@ -3,7 +3,6 @@ import {
DeleteOutlined,
EditOutlined,
EllipsisOutlined,
- EyeOutlined,
InfoCircleOutlined,
PlusOutlined,
SyncOutlined,
@@ -67,19 +66,6 @@ function PipelinesOrDeployments({ type }) {
},
{
key: "3",
- label: (
- <Space direction="horizontal" className="action-items">
- <div>
- <EyeOutlined />
- </div>
- <div>
- <Typography.Text>View Logs</Typography.Text>
- </div>
- </Space>
- ),
- },
- {
- key: "4",
label: (
<Space direction="horizontal" className="action-items">
<div>
@@ -92,7 +78,7 @@ function PipelinesOrDeployments({ type }) {
),
},
{
- key: "5",
+ key: "4",
label: (
<Space direction="horizontal" className="action-items">
<div>
@@ -105,7 +91,7 @@ function PipelinesOrDeployments({ type }) {
),
},
{
- key: "6",
+ key: "5",
label: (
<Space
direction="horizontal"
diff --git a/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx b/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx
index 39d74f77e..9ca1532a2 100644
--- a/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx
+++ b/frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx
@@ -3,13 +3,13 @@ import {
DeleteOutlined,
EditOutlined,
EllipsisOutlined,
- EyeOutlined,
SyncOutlined,
HighlightOutlined,
} from "@ant-design/icons";
import { Dropdown, Image, Space, Switch, Typography } from "antd";
import PropTypes from "prop-types";
import { useEffect, useState } from "react";
+import cronstrue from "cronstrue";
import { deploymentsStaticContent } from "../../../helpers/GetStaticData";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate.js";
@@ -34,11 +34,17 @@ function Pipelines({ type }) {
const { setAlertDetails } = useAlertStore();
const axiosPrivate = useAxiosPrivate();
const handleException = useExceptionHandler();
+ const [isEdit, setIsEdit] = useState(false);
useEffect(() => {
getPipelineList();
}, [type]);
+ const openAddModal = (edit) => {
+ setIsEdit(edit);
+ setOpenEtlOrTaskModal(true);
+ };
+
const getPipelineList = () => {
setTableLoading(true);
const requestOptions = {
@@ -220,7 +226,11 @@ function Pipelines({ type }) {
{
key: "1",
label: (
- <Space direction="horizontal" className="action-items">
+ <Space
+ direction="horizontal"
+ className="action-items"
+ onClick={() => openAddModal(true)}
+ >
<div>
<EditOutlined />
</div>
@@ -249,19 +259,6 @@ function Pipelines({ type }) {
},
{
key: "3",
- label: (
- <Space direction="horizontal" className="action-items">
- <div>
- <EyeOutlined />
- </div>
- <div>
- <Typography.Text>View Logs</Typography.Text>
- </div>
- </Space>
- ),
- },
- {
- key: "4",
label: (
<Space
direction="horizontal"
@@ -278,7 +275,7 @@ function Pipelines({ type }) {
),
},
{
- key: "5",
+ key: "4",
label: (
<Space
direction="horizontal"
@@ -295,7 +292,7 @@ function Pipelines({ type }) {
),
},
{
- key: "6",
+ key: "5",
label: (
<Space
direction="horizontal"
@@ -400,7 +397,7 @@ function Pipelines({ type }) {
render: (_, record) => (
<div>
<Typography.Text className="p-or-d-typography" strong>
- {record?.cron_data?.cron_summary}
+ {cronstrue.toString(record?.cron_string)}
</Typography.Text>
</div>
),
@@ -434,9 +431,6 @@ function Pipelines({ type }) {
),
},
];
- const openAddModal = () => {
- setOpenEtlOrTaskModal(true);
- };
return (
<>
@@ -448,13 +442,18 @@ function Pipelines({ type }) {
isTableLoading={tableLoading}
openAddModal={openAddModal}
/>
- <EtlTaskDeploy
- open={openEtlOrTaskModal}
- setOpen={setOpenEtlOrTaskModal}
- setTableData={setTableData}
- type={type}
- title={deploymentsStaticContent[type].modalTitle}
- />
+ {openEtlOrTaskModal && (
+ <EtlTaskDeploy
+ open={openEtlOrTaskModal}
+ setOpen={setOpenEtlOrTaskModal}
+ setTableData={setTableData}
+ type={type}
+ title={deploymentsStaticContent[type].modalTitle}
+ isEdit={isEdit}
+ selectedRow={selectedPorD}
+ setSelectedRow={setSelectedPorD}
+ />
+ )}
<DeleteModal
open={openDeleteModal}
setOpen={setOpenDeleteModal}