Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { BehaviorSubject, Observable } from 'rxjs';
- import { NodeType } from '@core/const/NodeTypes';
- import { EmailNode } from '@core/models/email.class';
- import { StateNode } from '@core/models/state.class';
- import { FetchNode } from '@core/models/fetch.class';
- import { BaseNode } from '@core/models/baseNode.class';
- import { StartNode } from '@core/models/start.class';
- import { EndNode } from '@core/models/end.class';
- import * as uuid from 'uuid';
- import { HttpClient, HttpHeaders } from '@angular/common/http';
- import { environment } from 'src/environments/environment';
- import { URIS } from '@core/const/Uris';
- import { ListTypes } from '@core/const/ListTypes';
- import { CronExpression } from '@core/models/cronExpression.class';
- import { FetchType } from '@core/models/fetchType.class';
- const httpOptions = {
- headers: new HttpHeaders({
- 'content-type': 'application/json',
- })
- };
- @Injectable({
- providedIn: 'root'
- })
- export class DefinitionService {
- constructor(private httpClient: HttpClient) {
- this.setInitialProcessDefinitionStructure();
- }
- previousProcessDefinitionJSON: String = '';
- processDefinitionNodes: BehaviorSubject<Array<BaseNode>> = new BehaviorSubject([]);
- processDefinitionName: String = '';
- processDefinitionRootId: String = '';
- processDefinitionId: String = '';
- processDefinitionVersion: String = '';
- availableTemplateIdsBasedOnFetchTypes: { [key: string]: Array<any> } = {};
- startNode: StartNode;
- endNode: EndNode;
- setInitialProcessDefinitionStructure(): void {
- this.startNode = new StartNode(uuid.v4(), this.getNodeName(NodeType.START));
- this.endNode = new EndNode(uuid.v4(), this.getNodeName(NodeType.END));
- const baseNodes = [this.startNode, this.endNode];
- this.processDefinitionNodes.next(baseNodes);
- this.processDefinitionName = '';
- this.processDefinitionRootId = '';
- this.processDefinitionId = '';
- this.previousProcessDefinitionJSON = '';
- }
- getProcessDefinitionNodes(): Observable<Array<BaseNode>> {
- return this.processDefinitionNodes.asObservable();
- }
- setProcessDefinitionToEdit(data: any): Promise<boolean> {
- this.setInitialProcessDefinitionStructure();
- this.processDefinitionId = data.id;
- this.processDefinitionName = data.name;
- this.processDefinitionRootId = data.rootProcessId;
- this.processDefinitionVersion = data.version;
- const ids = data.nodes.map(node => node.templateId);
- return new Promise((resolve, reject) => {
- this.getTemplateTypesByTemplateIds(ids)
- .then(templatesTypes => {
- if (Object.keys(templatesTypes).length !== 0) {
- const nodes = data.nodes.map(node => (
- {
- ...node,
- exportNodeTemplate: {
- type: templatesTypes[node.templateId].type,
- name: templatesTypes[node.templateId].name,
- id: node.templateId,
- },
- }
- ));
- this.setNodesFromProcessDefinition(nodes);
- }
- this.previousProcessDefinitionJSON = this.parseProcessToProperJson(this.processDefinitionNodes.getValue());
- resolve(true);
- })
- .catch(error => {
- console.warn(error);
- reject(false);
- });
- });
- }
- setNodesFromProcessDefinition(nodes: Array<any> = []) {
- let position = 0;
- nodes.forEach(node => {
- let newNode;
- const id = uuid.v4();
- switch (node.exportNodeTemplate.type) {
- case NodeType.START:
- case NodeType.START_TIMER: {
- const expression = {
- type: node.arguments.type || null,
- dateTime: node.arguments.dateTime ? new Date(node.arguments.dateTime) : null,
- unit: node.arguments.unit || null,
- frequency: node.arguments.frequency || null,
- weekday: node.arguments.weekday || null,
- };
- const hasExpression = Object.keys(expression).some(expKey => expression[expKey]);
- this.startNode.name = node.name;
- this.startNode.trigger = hasExpression ? new CronExpression(expression) : null;
- break;
- }
- case NodeType.EMAIL: {
- newNode = new EmailNode(id, node.name, node.arguments.recipient, node.arguments.subject, node.arguments.message);
- break;
- }
- case NodeType.FETCH: {
- newNode = new FetchNode(
- id, node.name,
- new FetchType(node.exportNodeTemplate.id, node.exportNodeTemplate.name, node.exportNodeTemplate.type),
- node.arguments.queryString, node.arguments.selectedId);
- break;
- }
- case NodeType.STATE: {
- const timeInMilliseconds = node.arguments.timeInMilliseconds !== '' ? node.arguments.timeInMilliseconds : null;
- newNode = new StateNode(id, node.name, node.arguments.unit, timeInMilliseconds);
- break;
- }
- }
- if (newNode !== undefined) {
- this.addNewNode(newNode, position++);
- }
- });
- }
- getTemplateStructureForNode(node: BaseNode, types: any, nextNodeId: string): any {
- const id = ((types.length > 1) && NodeType.FETCH === node.getType()) ?
- types.find(subtype => subtype.name === node['type'].name).id :
- types[0].id;
- return {
- 'name': node.name,
- 'templateId': id,
- 'referenceKey': node.id,
- 'arguments': {}
- // 'arguments': node.serializeToExport(nextNodeId),
- };
- }
- getTemplateTypesByTemplateType(type: string): Promise<any> {
- return this.httpClient.get(environment.backendBase + URIS.NODE_TYPES_GET_ALL_BY_TYPE(type)).toPromise();
- }
- getTemplateTypesByTemplateIds(ids: Array<string>): Promise<any> {
- return this.httpClient.post(environment.backendBase + URIS.NODE_TYPES_GET_TYPES_BY_ID, JSON.stringify(ids), httpOptions).toPromise();
- }
- getTemplateForType(node: BaseNode, nextNodeId: string): Promise<any> {
- const type = (NodeType.START === node.getType() && node['type']) ? node['type'] : node.getType();
- return new Promise((resolve, reject) => {
- if (this.availableTemplateIdsBasedOnFetchTypes[type]) {
- const types = this.availableTemplateIdsBasedOnFetchTypes[type];
- resolve(this.getTemplateStructureForNode(node, types, nextNodeId));
- } else {
- this.getTemplateTypesByTemplateType(type)
- .then((types: any) => {
- this.availableTemplateIdsBasedOnFetchTypes[type] = types;
- resolve(this.getTemplateStructureForNode(node, types, nextNodeId));
- })
- .catch(error => console.warn(error));
- }
- });
- }
- parseNodesFromProcessDefinition(): Promise<any> {
- const nodes = this.processDefinitionNodes.getValue();
- const sortedNodes = [
- nodes.find(node => NodeType.START === node.getType()),
- ...nodes.filter(node => ![NodeType.START, NodeType.END].includes(node.getType())),
- nodes.find(node => NodeType.END === node.getType()),
- ];
- return Promise.all(sortedNodes.map(node => {
- // const nextNodeId = this.getNextNodeId(node, sortedNodes);
- this.getTemplateForType(node, '1');
- console.log(this.getTemplateForType(node, '1'));
- }
- ));
- }
- private getNextNodeId(node: BaseNode, nodes: Array<any>) {
- const currentIndex = nodes.indexOf(node);
- if (currentIndex >= 0 && currentIndex < nodes.length - 1) {
- console.log(nodes[currentIndex + 1].id);
- return nodes[currentIndex + 1].id;
- }
- }
- saveProcessDefinition(name: String): Promise<any> {
- if (!this.processDefinitionName) {
- this.processDefinitionName = name;
- }
- return new Promise((resolve, reject) => {
- this.parseNodesFromProcessDefinition()
- .then(nodes => {
- const data = {
- 'rootProcessId': this.processDefinitionRootId,
- 'name': this.processDefinitionName,
- 'nodes': nodes,
- };
- this.httpClient.post(environment.backendBase + URIS.SAVE_PROCESS, JSON.stringify(data), httpOptions)
- .toPromise()
- .then((data: any) => {
- this.processDefinitionRootId = data.rootProcessId;
- this.processDefinitionVersion = data.version;
- this.processDefinitionId = data.id;
- this.previousProcessDefinitionJSON = this.parseProcessToProperJson(this.processDefinitionNodes.getValue());
- resolve({ id: this.processDefinitionId, version: this.processDefinitionVersion });
- });
- })
- .catch(error => console.warn(error));
- });
- }
- parseProcessToProperJson(process: Array<BaseNode>): string {
- const nodesWithoutId = process.map(item => ({ ...item, id: 0 }));
- return JSON.stringify(nodesWithoutId);
- }
- getProcessDefinitionByVersionId(id: string): Promise<any> {
- return this.httpClient.get(environment.backendBase + URIS.GET_DEFINITION_BY_ID(id), httpOptions).toPromise();
- }
- getProcessDetailsByVersionId(id: string): Promise<any> {
- return this.httpClient.get(environment.backendBase + URIS.GET_DEFINITION_DETAILS(id), httpOptions).toPromise();
- }
- stopProcessDefinition(id: string): Promise<any> {
- return this.httpClient.put(environment.backendBase + URIS.STOP_PROCESS(id), {}, httpOptions).toPromise();
- }
- startProcessDefinition(id: String): Promise<any> {
- return this.httpClient.put(environment.backendBase + URIS.START_PROCESS(id), {}, httpOptions).toPromise();
- }
- exportProcessDefinitionById(id: String) {
- return new Promise((resolve, reject) => {
- this.httpClient.head(environment.backendBase + URIS.EXPORT_PROCESS_DEFINITION(id)).toPromise()
- .then(() =>
- resolve(
- this.httpClient.get(environment.backendBase + URIS.EXPORT_PROCESS_DEFINITION(id), { observe: 'response' }).toPromise()
- )
- )
- .catch(error => {
- console.warn(error);
- reject(error);
- });
- });
- }
- deleteProcessDefinition(id: string): Promise<any> {
- return this.httpClient.delete(environment.backendBase + URIS.GET_DEFINITION_BY_ID(id), httpOptions).toPromise();
- }
- dropNode(nodeType: string, oldPosition: number, newPosition: number, isNew: boolean): void {
- if (isNew) {
- if (nodeType) {
- let newNode;
- const nodeId = uuid.v4();
- let nodeName = this.getNodeName(nodeType);
- nodeName = this.setUniqueNodeName(this.processDefinitionNodes, nodeName);
- switch (nodeType) {
- case (NodeType.EMAIL): newNode = new EmailNode(nodeId, nodeName); break;
- case (NodeType.STATE): newNode = new StateNode(nodeId, nodeName); break;
- case (NodeType.FETCH): newNode = new FetchNode(nodeId, nodeName); break;
- }
- this.addNewNode(newNode, newPosition);
- }
- } else {
- this.replaceNodes(oldPosition, newPosition);
- }
- }
- wasProcessDefinitionUpdated(): Boolean {
- const currentPD = this.processDefinitionNodes.getValue();
- return this.parseProcessToProperJson(currentPD) !== this.previousProcessDefinitionJSON;
- }
- getNodeNamesByType(type, toIndex = this.processDefinitionNodes.getValue().length) {
- return this.processDefinitionNodes.getValue().filter(node => node.getType() === type).slice(0, toIndex);
- }
- getLastFetchIndex(nodeId: string): number {
- const currentNodes = this.processDefinitionNodes.getValue();
- const currentNodeIndex = currentNodes.findIndex(node => node.id === nodeId);
- return currentNodes.slice(0, currentNodeIndex).filter(node => node.getType() === NodeType.FETCH).length;
- }
- getFetchedDataIdByName(name: String, toIndex = this.processDefinitionNodes.getValue().length): string {
- const node = this.processDefinitionNodes.getValue()
- .filter(innerNode => NodeType.FETCH === innerNode.getType())
- .slice(0, toIndex)
- .find(innerNode =>
- innerNode.name === name
- );
- return node && node['type'] ? node['type']['id'] : '';
- }
- isThereANodeWithTheSameName(nodes, currentNodeName, newNodeName) {
- return nodes.value.filter(node => (!node.name.startsWith(currentNodeName))).map(node => node.name).includes(newNodeName);
- }
- setUniqueNodeName(nodes, nodeName) {
- const nodeNumbers = [];
- nodes.value.filter(node => (node.name.startsWith(nodeName))).forEach(node => {
- const index = node.name.lastIndexOf('-');
- const numberOfNode = parseInt(node.name.substr(index + 1, node.name.length), 10);
- if (!isNaN(numberOfNode)) {
- nodeNumbers.push(numberOfNode);
- }
- });
- return nodeNumbers.length === 0 ? nodeName + '-1' : nodeName + '-' + (Math.max(...nodeNumbers) + 1);
- }
- getNodeName(nodeType: string): string {
- return Object.keys(NodeType).find(key => NodeType[key] === nodeType).toLowerCase();
- }
- addNewNode(node: BaseNode, newPosition): void {
- const oldTableStart = this.processDefinitionNodes.getValue().slice(0, newPosition);
- const oldTableEnd = this.processDefinitionNodes.getValue().slice(newPosition);
- const newTable = [...oldTableStart, node, ...oldTableEnd];
- this.processDefinitionNodes.next(newTable);
- }
- replaceNodes(oldPosition: number, newPosition: number): void {
- const currentNodes = this.processDefinitionNodes.getValue();
- const nodeToReplace = currentNodes.splice(oldPosition, 1);
- this.processDefinitionNodes.next(currentNodes);
- this.addNewNode(nodeToReplace[0], newPosition);
- }
- removeNode(nodeId: string) {
- const newNodes = this.processDefinitionNodes.getValue().filter(node => node.id !== nodeId);
- this.processDefinitionNodes.next(newNodes);
- }
- getProcessesList(currentPage: number, numberOfItems: number, listType: ListTypes): Promise<any> {
- const ENDPOINT = this.getEndPoint(listType);
- return this.httpClient.get(
- environment.backendBase + ENDPOINT + `?page=${currentPage}&size=${numberOfItems}`, httpOptions).toPromise();
- }
- private getEndPoint(listType: ListTypes) {
- let ENDPOINT = '';
- switch (listType) {
- case ListTypes.ACTIVE_PROCESSES: {
- ENDPOINT = URIS.ACTIVE_PROCESSES;
- break;
- }
- case ListTypes.SAVED_PROCESSES: {
- ENDPOINT = URIS.SAVED_PROCESSES;
- break;
- }
- }
- return ENDPOINT;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement