Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.24 KB | None | 0 0
  1. import { Injectable } from '@angular/core';
  2. import { BehaviorSubject, Observable } from 'rxjs';
  3. import { NodeType } from '@core/const/NodeTypes';
  4. import { EmailNode } from '@core/models/email.class';
  5. import { StateNode } from '@core/models/state.class';
  6. import { FetchNode } from '@core/models/fetch.class';
  7. import { BaseNode } from '@core/models/baseNode.class';
  8. import { StartNode } from '@core/models/start.class';
  9. import { EndNode } from '@core/models/end.class';
  10. import * as uuid from 'uuid';
  11. import { HttpClient, HttpHeaders } from '@angular/common/http';
  12. import { environment } from 'src/environments/environment';
  13. import { URIS } from '@core/const/Uris';
  14. import { ListTypes } from '@core/const/ListTypes';
  15. import { CronExpression } from '@core/models/cronExpression.class';
  16. import { FetchType } from '@core/models/fetchType.class';
  17.  
  18. const httpOptions = {
  19. headers: new HttpHeaders({
  20. 'content-type': 'application/json',
  21. })
  22. };
  23. @Injectable({
  24. providedIn: 'root'
  25. })
  26. export class DefinitionService {
  27.  
  28. constructor(private httpClient: HttpClient) {
  29. this.setInitialProcessDefinitionStructure();
  30. }
  31.  
  32. previousProcessDefinitionJSON: String = '';
  33. processDefinitionNodes: BehaviorSubject<Array<BaseNode>> = new BehaviorSubject([]);
  34. processDefinitionName: String = '';
  35. processDefinitionRootId: String = '';
  36. processDefinitionId: String = '';
  37. processDefinitionVersion: String = '';
  38. availableTemplateIdsBasedOnFetchTypes: { [key: string]: Array<any> } = {};
  39. startNode: StartNode;
  40. endNode: EndNode;
  41.  
  42. setInitialProcessDefinitionStructure(): void {
  43. this.startNode = new StartNode(uuid.v4(), this.getNodeName(NodeType.START));
  44. this.endNode = new EndNode(uuid.v4(), this.getNodeName(NodeType.END));
  45. const baseNodes = [this.startNode, this.endNode];
  46. this.processDefinitionNodes.next(baseNodes);
  47. this.processDefinitionName = '';
  48. this.processDefinitionRootId = '';
  49. this.processDefinitionId = '';
  50. this.previousProcessDefinitionJSON = '';
  51. }
  52.  
  53. getProcessDefinitionNodes(): Observable<Array<BaseNode>> {
  54. return this.processDefinitionNodes.asObservable();
  55. }
  56.  
  57. setProcessDefinitionToEdit(data: any): Promise<boolean> {
  58. this.setInitialProcessDefinitionStructure();
  59. this.processDefinitionId = data.id;
  60. this.processDefinitionName = data.name;
  61. this.processDefinitionRootId = data.rootProcessId;
  62. this.processDefinitionVersion = data.version;
  63. const ids = data.nodes.map(node => node.templateId);
  64. return new Promise((resolve, reject) => {
  65. this.getTemplateTypesByTemplateIds(ids)
  66. .then(templatesTypes => {
  67. if (Object.keys(templatesTypes).length !== 0) {
  68. const nodes = data.nodes.map(node => (
  69. {
  70. ...node,
  71. exportNodeTemplate: {
  72. type: templatesTypes[node.templateId].type,
  73. name: templatesTypes[node.templateId].name,
  74. id: node.templateId,
  75. },
  76. }
  77. ));
  78. this.setNodesFromProcessDefinition(nodes);
  79. }
  80. this.previousProcessDefinitionJSON = this.parseProcessToProperJson(this.processDefinitionNodes.getValue());
  81. resolve(true);
  82. })
  83. .catch(error => {
  84. console.warn(error);
  85. reject(false);
  86. });
  87. });
  88. }
  89.  
  90. setNodesFromProcessDefinition(nodes: Array<any> = []) {
  91. let position = 0;
  92. nodes.forEach(node => {
  93. let newNode;
  94. const id = uuid.v4();
  95. switch (node.exportNodeTemplate.type) {
  96. case NodeType.START:
  97. case NodeType.START_TIMER: {
  98. const expression = {
  99. type: node.arguments.type || null,
  100. dateTime: node.arguments.dateTime ? new Date(node.arguments.dateTime) : null,
  101. unit: node.arguments.unit || null,
  102. frequency: node.arguments.frequency || null,
  103. weekday: node.arguments.weekday || null,
  104. };
  105. const hasExpression = Object.keys(expression).some(expKey => expression[expKey]);
  106. this.startNode.name = node.name;
  107. this.startNode.trigger = hasExpression ? new CronExpression(expression) : null;
  108. break;
  109. }
  110. case NodeType.EMAIL: {
  111. newNode = new EmailNode(id, node.name, node.arguments.recipient, node.arguments.subject, node.arguments.message);
  112. break;
  113. }
  114. case NodeType.FETCH: {
  115. newNode = new FetchNode(
  116. id, node.name,
  117. new FetchType(node.exportNodeTemplate.id, node.exportNodeTemplate.name, node.exportNodeTemplate.type),
  118. node.arguments.queryString, node.arguments.selectedId);
  119. break;
  120. }
  121. case NodeType.STATE: {
  122. const timeInMilliseconds = node.arguments.timeInMilliseconds !== '' ? node.arguments.timeInMilliseconds : null;
  123. newNode = new StateNode(id, node.name, node.arguments.unit, timeInMilliseconds);
  124. break;
  125. }
  126. }
  127. if (newNode !== undefined) {
  128. this.addNewNode(newNode, position++);
  129. }
  130. });
  131. }
  132.  
  133. getTemplateStructureForNode(node: BaseNode, types: any, nextNodeId: string): any {
  134. const id = ((types.length > 1) && NodeType.FETCH === node.getType()) ?
  135. types.find(subtype => subtype.name === node['type'].name).id :
  136. types[0].id;
  137. return {
  138. 'name': node.name,
  139. 'templateId': id,
  140. 'referenceKey': node.id,
  141. 'arguments': {}
  142. // 'arguments': node.serializeToExport(nextNodeId),
  143. };
  144. }
  145.  
  146. getTemplateTypesByTemplateType(type: string): Promise<any> {
  147. return this.httpClient.get(environment.backendBase + URIS.NODE_TYPES_GET_ALL_BY_TYPE(type)).toPromise();
  148. }
  149.  
  150. getTemplateTypesByTemplateIds(ids: Array<string>): Promise<any> {
  151. return this.httpClient.post(environment.backendBase + URIS.NODE_TYPES_GET_TYPES_BY_ID, JSON.stringify(ids), httpOptions).toPromise();
  152. }
  153.  
  154. getTemplateForType(node: BaseNode, nextNodeId: string): Promise<any> {
  155. const type = (NodeType.START === node.getType() && node['type']) ? node['type'] : node.getType();
  156. return new Promise((resolve, reject) => {
  157. if (this.availableTemplateIdsBasedOnFetchTypes[type]) {
  158. const types = this.availableTemplateIdsBasedOnFetchTypes[type];
  159. resolve(this.getTemplateStructureForNode(node, types, nextNodeId));
  160. } else {
  161. this.getTemplateTypesByTemplateType(type)
  162. .then((types: any) => {
  163. this.availableTemplateIdsBasedOnFetchTypes[type] = types;
  164. resolve(this.getTemplateStructureForNode(node, types, nextNodeId));
  165. })
  166. .catch(error => console.warn(error));
  167. }
  168. });
  169. }
  170.  
  171. parseNodesFromProcessDefinition(): Promise<any> {
  172. const nodes = this.processDefinitionNodes.getValue();
  173. const sortedNodes = [
  174. nodes.find(node => NodeType.START === node.getType()),
  175. ...nodes.filter(node => ![NodeType.START, NodeType.END].includes(node.getType())),
  176. nodes.find(node => NodeType.END === node.getType()),
  177. ];
  178. return Promise.all(sortedNodes.map(node => {
  179. // const nextNodeId = this.getNextNodeId(node, sortedNodes);
  180. this.getTemplateForType(node, '1');
  181. console.log(this.getTemplateForType(node, '1'));
  182. }
  183. ));
  184. }
  185.  
  186. private getNextNodeId(node: BaseNode, nodes: Array<any>) {
  187. const currentIndex = nodes.indexOf(node);
  188. if (currentIndex >= 0 && currentIndex < nodes.length - 1) {
  189. console.log(nodes[currentIndex + 1].id);
  190. return nodes[currentIndex + 1].id;
  191. }
  192. }
  193.  
  194. saveProcessDefinition(name: String): Promise<any> {
  195. if (!this.processDefinitionName) {
  196. this.processDefinitionName = name;
  197. }
  198. return new Promise((resolve, reject) => {
  199. this.parseNodesFromProcessDefinition()
  200. .then(nodes => {
  201. const data = {
  202. 'rootProcessId': this.processDefinitionRootId,
  203. 'name': this.processDefinitionName,
  204. 'nodes': nodes,
  205. };
  206. this.httpClient.post(environment.backendBase + URIS.SAVE_PROCESS, JSON.stringify(data), httpOptions)
  207. .toPromise()
  208. .then((data: any) => {
  209. this.processDefinitionRootId = data.rootProcessId;
  210. this.processDefinitionVersion = data.version;
  211. this.processDefinitionId = data.id;
  212. this.previousProcessDefinitionJSON = this.parseProcessToProperJson(this.processDefinitionNodes.getValue());
  213. resolve({ id: this.processDefinitionId, version: this.processDefinitionVersion });
  214. });
  215. })
  216. .catch(error => console.warn(error));
  217. });
  218. }
  219.  
  220. parseProcessToProperJson(process: Array<BaseNode>): string {
  221. const nodesWithoutId = process.map(item => ({ ...item, id: 0 }));
  222. return JSON.stringify(nodesWithoutId);
  223. }
  224.  
  225. getProcessDefinitionByVersionId(id: string): Promise<any> {
  226. return this.httpClient.get(environment.backendBase + URIS.GET_DEFINITION_BY_ID(id), httpOptions).toPromise();
  227. }
  228.  
  229. getProcessDetailsByVersionId(id: string): Promise<any> {
  230. return this.httpClient.get(environment.backendBase + URIS.GET_DEFINITION_DETAILS(id), httpOptions).toPromise();
  231. }
  232.  
  233. stopProcessDefinition(id: string): Promise<any> {
  234. return this.httpClient.put(environment.backendBase + URIS.STOP_PROCESS(id), {}, httpOptions).toPromise();
  235. }
  236.  
  237. startProcessDefinition(id: String): Promise<any> {
  238. return this.httpClient.put(environment.backendBase + URIS.START_PROCESS(id), {}, httpOptions).toPromise();
  239. }
  240.  
  241. exportProcessDefinitionById(id: String) {
  242. return new Promise((resolve, reject) => {
  243. this.httpClient.head(environment.backendBase + URIS.EXPORT_PROCESS_DEFINITION(id)).toPromise()
  244. .then(() =>
  245. resolve(
  246. this.httpClient.get(environment.backendBase + URIS.EXPORT_PROCESS_DEFINITION(id), { observe: 'response' }).toPromise()
  247. )
  248. )
  249. .catch(error => {
  250. console.warn(error);
  251. reject(error);
  252. });
  253. });
  254. }
  255.  
  256. deleteProcessDefinition(id: string): Promise<any> {
  257. return this.httpClient.delete(environment.backendBase + URIS.GET_DEFINITION_BY_ID(id), httpOptions).toPromise();
  258. }
  259.  
  260. dropNode(nodeType: string, oldPosition: number, newPosition: number, isNew: boolean): void {
  261. if (isNew) {
  262. if (nodeType) {
  263. let newNode;
  264. const nodeId = uuid.v4();
  265. let nodeName = this.getNodeName(nodeType);
  266. nodeName = this.setUniqueNodeName(this.processDefinitionNodes, nodeName);
  267. switch (nodeType) {
  268. case (NodeType.EMAIL): newNode = new EmailNode(nodeId, nodeName); break;
  269. case (NodeType.STATE): newNode = new StateNode(nodeId, nodeName); break;
  270. case (NodeType.FETCH): newNode = new FetchNode(nodeId, nodeName); break;
  271. }
  272. this.addNewNode(newNode, newPosition);
  273. }
  274. } else {
  275. this.replaceNodes(oldPosition, newPosition);
  276. }
  277. }
  278.  
  279. wasProcessDefinitionUpdated(): Boolean {
  280. const currentPD = this.processDefinitionNodes.getValue();
  281. return this.parseProcessToProperJson(currentPD) !== this.previousProcessDefinitionJSON;
  282. }
  283.  
  284. getNodeNamesByType(type, toIndex = this.processDefinitionNodes.getValue().length) {
  285. return this.processDefinitionNodes.getValue().filter(node => node.getType() === type).slice(0, toIndex);
  286. }
  287.  
  288. getLastFetchIndex(nodeId: string): number {
  289. const currentNodes = this.processDefinitionNodes.getValue();
  290. const currentNodeIndex = currentNodes.findIndex(node => node.id === nodeId);
  291. return currentNodes.slice(0, currentNodeIndex).filter(node => node.getType() === NodeType.FETCH).length;
  292. }
  293.  
  294. getFetchedDataIdByName(name: String, toIndex = this.processDefinitionNodes.getValue().length): string {
  295. const node = this.processDefinitionNodes.getValue()
  296. .filter(innerNode => NodeType.FETCH === innerNode.getType())
  297. .slice(0, toIndex)
  298. .find(innerNode =>
  299. innerNode.name === name
  300. );
  301. return node && node['type'] ? node['type']['id'] : '';
  302. }
  303.  
  304. isThereANodeWithTheSameName(nodes, currentNodeName, newNodeName) {
  305. return nodes.value.filter(node => (!node.name.startsWith(currentNodeName))).map(node => node.name).includes(newNodeName);
  306. }
  307.  
  308. setUniqueNodeName(nodes, nodeName) {
  309. const nodeNumbers = [];
  310. nodes.value.filter(node => (node.name.startsWith(nodeName))).forEach(node => {
  311. const index = node.name.lastIndexOf('-');
  312. const numberOfNode = parseInt(node.name.substr(index + 1, node.name.length), 10);
  313. if (!isNaN(numberOfNode)) {
  314. nodeNumbers.push(numberOfNode);
  315. }
  316. });
  317. return nodeNumbers.length === 0 ? nodeName + '-1' : nodeName + '-' + (Math.max(...nodeNumbers) + 1);
  318. }
  319.  
  320. getNodeName(nodeType: string): string {
  321. return Object.keys(NodeType).find(key => NodeType[key] === nodeType).toLowerCase();
  322. }
  323.  
  324. addNewNode(node: BaseNode, newPosition): void {
  325. const oldTableStart = this.processDefinitionNodes.getValue().slice(0, newPosition);
  326. const oldTableEnd = this.processDefinitionNodes.getValue().slice(newPosition);
  327. const newTable = [...oldTableStart, node, ...oldTableEnd];
  328. this.processDefinitionNodes.next(newTable);
  329. }
  330.  
  331. replaceNodes(oldPosition: number, newPosition: number): void {
  332. const currentNodes = this.processDefinitionNodes.getValue();
  333. const nodeToReplace = currentNodes.splice(oldPosition, 1);
  334. this.processDefinitionNodes.next(currentNodes);
  335. this.addNewNode(nodeToReplace[0], newPosition);
  336. }
  337.  
  338. removeNode(nodeId: string) {
  339. const newNodes = this.processDefinitionNodes.getValue().filter(node => node.id !== nodeId);
  340. this.processDefinitionNodes.next(newNodes);
  341. }
  342.  
  343. getProcessesList(currentPage: number, numberOfItems: number, listType: ListTypes): Promise<any> {
  344. const ENDPOINT = this.getEndPoint(listType);
  345. return this.httpClient.get(
  346. environment.backendBase + ENDPOINT + `?page=${currentPage}&size=${numberOfItems}`, httpOptions).toPromise();
  347. }
  348.  
  349. private getEndPoint(listType: ListTypes) {
  350. let ENDPOINT = '';
  351. switch (listType) {
  352. case ListTypes.ACTIVE_PROCESSES: {
  353. ENDPOINT = URIS.ACTIVE_PROCESSES;
  354. break;
  355. }
  356. case ListTypes.SAVED_PROCESSES: {
  357. ENDPOINT = URIS.SAVED_PROCESSES;
  358. break;
  359. }
  360. }
  361. return ENDPOINT;
  362. }
  363. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement