· 6 years ago · Sep 23, 2019, 09:46 AM
1(function() {
2 angular
3 .module('app.action.workflowEditBetaActionsConfig', [])
4 .component('ltmsActionWorkflowEditBetaActionsConfig', {
5 templateUrl: "/modules/action/ltms-workflow-rules/html/ltms-workflow-edit-beta-action-config.html",
6
7 bindings: {
8 workflow: "<",
9 mode: "<"
10 },
11 controller: LtmsActionWorkflowEditActionsConfigController
12 })
13
14 LtmsActionWorkflowEditActionsConfigController.$inject = ["Workflows", "LtmsWorkflowDataSource", "$q", "$timeout", "$compile", "$scope", "Brands"];
15
16 function LtmsActionWorkflowEditActionsConfigController(Workflows, LtmsWorkflowDataSource, $q, $timeout, $compile, $scope, Brands) {
17
18 var workflowActionVM = this;
19 var optionsContainerId = null;
20 var optionsBasedOnActions = null;
21 workflowActionVM.requestOptions = {
22 'requestType': 'POST',
23 'urlMarginLeft': '0px',
24 parameters: {
25 'json': {}
26 },
27 authorisation: {
28 'json': {}
29 }
30 };
31 var renderOptionCount = 0; // Form render count so that render should happens single time.
32 var actionList = null;
33 var indexCount = 0;
34 var actionId = null;
35 var authErrorMsg = "";
36 var isAuthData = false;
37 var actionIndexToUpdate = null;
38 var authorisationData = {};
39 workflowActionVM.parameterAuth = true;
40 workflowActionVM.parameterKeyPair = true;
41 var parsedJsonData = {};
42 var apiInsertMode = false
43 var parameterData = {};
44 var apiResponseFlag = false;
45 var paramsJsonFlag = false;
46 var authBearerToknFlag = false;
47 var tokenError;
48 workflowActionVM.selectedOptions = {};
49 // Initially inputbox of parameter's tab has one input.
50 var paramsConfig = {
51 "key": null,
52 "value": null,
53 "index": 0
54 };
55 // To Dynamically render the inputbox for parametes when keypress occure.
56 workflowActionVM.keyPairConfig = [Helpers.deepClone(paramsConfig)];
57 // Varaible for dropdown in response tab for first empty dropdown.
58 var actionConfig = {
59 "key": null,
60 "value": null,
61 "index": 1,
62 "options": []
63 };
64 //To dynamically render the dropdown in response tab.
65 workflowActionVM.configs = [Helpers.deepClone(actionConfig)]
66 workflowActionVM.authorisationTypeName = 'oauth';
67 workflowActionVM.selectedActionUuid = "";
68 // Data to prepare authorisation's tab label and inputbox dynamic.
69 workflowActionVM.authorisationTypeData = {
70 'oauth': [{
71 'label': 'Consumer Key',
72 'keyName': 'app_key',
73 "value": "",
74 'type': 'input'
75 }, {
76 'label': 'Consumer Secret',
77 "value": "",
78 'keyName': 'secret_key',
79 'type': 'input'
80 }, {
81 'label': 'Access Token',
82 "value": "",
83 'keyName': 'oauth_token',
84 'type': 'input'
85 }, {
86 'label': 'Token Secret',
87 "value": "",
88 'keyName': 'user_oauth_token_secret',
89 'type': 'input'
90 }],
91 'bearerToken': [{
92 'label': 'Bearer Token',
93 "value": "",
94 'keyName': 'bearer_token',
95 'type': 'input'
96 }, {
97 'label': 'Token',
98 "value": "",
99 'keyName': 'bearer_token_body',
100 'type': 'multiLine'
101 // To prepare textarea for bearer token
102 }],
103 'basicAuth': [{
104 'label': 'Username',
105 "value": "",
106 'keyName': 'username',
107 'type': 'input'
108 },
109 {
110 'label': 'Password',
111 "value": "",
112 'keyName': 'password',
113 'type': 'input'
114 }
115 ],
116 'digestAuth': [{
117 'label': 'Username',
118 "value": "",
119 'keyName': 'username',
120 'type': 'input'
121 },
122 {
123 'label': 'Password',
124 "value": "",
125 'keyName': 'password',
126 'type': 'input'
127 }
128 ]
129 }
130 // To map authorisation type with dropdown options
131 var authorisationTypeName = {
132 'oauth': 'OAuth1',
133 'bearerToken': 'Bearer Token',
134 'basicAuth': 'Basic Auth',
135 'digestAuth': 'Digest Auth'
136 }
137 // Variable created to add the data of API request in Database
138 var options = {
139 method: "",
140 url: "",
141 authentication_required: "",
142 data: {},
143 should_save_api_response: false,
144 api_response_config: {},
145 authorization: {
146 auth_type: "",
147 body: {}
148 },
149 auth_params: {},
150 parameter_json: false
151 }
152
153 var apiActions = {
154 action_id: "",
155 options: {}
156 }
157
158 $(document).delegate('#lwActionWorkflowActionJsonData , #lwActionWorkflowActionParamsJsonData', 'keydown', function(tab) {
159 var keyCode = tab.keyCode || tab.which;
160
161 if (keyCode == 9) {
162 tab.preventDefault();
163 var start = this.selectionStart;
164 var end = this.selectionEnd;
165
166 // set textarea value to: text before caret + tab + text after caret
167 $(this).val($(this).val().substring(0, start) +
168 "\t" +
169 $(this).val().substring(end));
170
171 // put caret at right position again
172 this.selectionStart =
173 this.selectionEnd = start + 1;
174 }
175 });
176
177 //Method to update the authorisation data when rule already created.
178 function authUpdateData(authType, authData) {
179 setTimeout(function() {
180 $('#lwActionWorkflowBetaActionsList').val(updateOptions.action_id).trigger('change');
181 setupDropdown("lwActionWorkflowActionAuth");
182 }, 10);
183 var authTypeName = _.findKey(authorisationTypeName, function(value) { return value === authType; })
184 var authTypeData = {};
185 authTypeData[authTypeName] = authData;
186 workflowActionVM.authorisationTypeName = authTypeName;
187 workflowActionVM.authorisationTypeData[authType] = authTypeData;
188 for (var key in authData) {
189 if (authTypeName) {
190 _.each(workflowActionVM.authorisationTypeData[authTypeName], function(data) {
191 if (data.keyName == key) {
192 data.value = authData[key] || "";
193 }
194 })
195
196 }
197 }
198 }
199 //Method to visible authorisation data on click of "Authorisation Requied" checkbox.
200 workflowActionVM.authRender = function() {
201 if (workflowActionVM.authRequired) {
202 $('.lw-act-workflow__auth-checkbox-check').trigger('click');
203 workflowActionVM.parametersVisible('auth');
204 setupDropdown("lwActionWorkflowActionAuth");
205 } else {
206 $('#lwActionWorkflowActioncheckParams').trigger('click');
207 }
208 }
209
210 /*
211 Method to retrive data from all three tabs and preparing data to save it in database.
212 Authoridsation Tab : When bearer token has expression ( like "{{api.response}}") , then JSON is required.
213 */
214 function authorisationActionData() {
215 var authTypeName = workflowActionVM.authorisationTypeName;
216 if (actionIndexToUpdate || actionIndexToUpdate == 0) {
217 authorisationData = {};
218 options.authorization.body = {};
219 options.auth_params = {};
220 }
221 if (workflowActionVM.authRequired) {
222 options.authorization.auth_type = authorisationTypeName[workflowActionVM.authorisationTypeName];
223 var authData = Helpers.deepClone(workflowActionVM.authorisationTypeData);
224 for (var i = 0; i < authData[authTypeName].length; i++) {
225
226 if (!(authData[authTypeName][i].keyName == "bearer_token_body")) {
227 authorisationData[authData[authTypeName][i].keyName] = authData[authTypeName][i].value;
228 }
229 }
230 if (authTypeName == 'bearerToken') {
231 if (((/^{{/.test(authorisationData['bearer_token'])) && (/}}$/.test(authorisationData['bearer_token'])))) {
232 try {
233 options.auth_params = JSON.parse(workflowActionVM.requestOptions.authorisation.json);
234
235 if (!_.isEmpty(options.auth_params)) {
236 authBearerToknFlag = false;
237 } else {
238 authBearerToknFlag = true;
239 Helpers.smallAlertBox("Please enter parameters in JSON. ", "", "warn", 5000);
240 }
241 } catch (error) {
242 if (error instanceof SyntaxError) {
243 authBearerToknFlag = true;
244 Helpers.smallAlertBox("There was a syntax error. Please correct it and try again: ", "Please insert responsive token like {{token}}", "warn", 5000);
245 }
246 }
247 } else {
248 authBearerToknFlag = true;
249 Helpers.smallAlertBox("Bearer Token should be in expression.", "For example : {{apiResponse.variableName}}", "warn", 5000);
250 }
251 }
252 }
253 options.authorization.body = authorisationData;
254 options.method = workflowActionVM.requestOptions.requestType;
255 options.url = workflowActionVM.requestOptions.requestUrl;
256 options.authentication_required = workflowActionVM.authRequired;
257 options.should_save_api_response = workflowActionVM.isSaveApi;
258 apiActions.action_id = getActionId();
259 isAuthData = false;
260
261 if (workflowActionVM.authRequired) {
262 for (var key in workflowActionVM.authorisationTypeData) {
263 if (authTypeName == key) {
264 for (var key in options.authorization.body) {
265 if ((options.authorization.body[key] == undefined || options.authorization.body[key] == "")) {
266 if (!(key === 'bearer_token_body')) {
267 isAuthData = true;
268 authErrorMsg = 'Please enter required parameter for authorisation.';
269 }
270 }
271 }
272 if (isAuthData) {
273 Helpers.smallAlertBox("Please enter Authorisation parameters. ", "", "warn", 5000);
274 }
275 }
276 }
277 }
278
279 apiActions.options = options;
280 prepareParamsData();
281 prepareDropdownData();
282 }
283
284 // '' ,'' ,
285 /**
286 * initialiseOnChange: Method which gets invoked everytime whenever any change occur in component.
287 */
288 function initialiseOnChange() {
289 initialiseComponent();
290 // TODO: Populate all the actions which are already set to the workflow.
291
292 // set containerId where options based on selected actions will get populated.
293 setContainerId("lwActionWorkflowBetaActionsOptionsForm");
294 populateAvailableActions();
295 }
296
297 // Setup actions: Populate all the
298 function initialiseComponent() {
299 workflowActionVM.actionsList = [];
300 workflowActionVM.actionsHash = {};
301 Workflows.getWorkflowDataByType(2, function(error, response) {
302 if (!error && (Utils.getProp(response, "code")) == 0 && ("data" in response)) {
303 actionList = Helpers.deepClone((response["data"].length) ? response["data"] : []);
304 resetActionHash();
305 }
306 setupDropdown("lwActionWorkflowBetaActionsList", workflowActionVM.actionsList, "lwActionWorkflowBetaActionsListContainer");
307 });
308 }
309
310 function resetActionHash() {
311 workflowActionVM.actionsList = {};
312 workflowActionVM.actionsList = _.map(actionList, function(action) {
313 // add property id and text as this will be used in select2
314 action["id"] = action["_id"];
315 action["text"] = action["name"];
316 // update workflowActionVM.rulesetHash
317 workflowActionVM.actionsHash[action["_id"]] = action;
318 return action;
319 });
320 }
321
322 function populateAvailableActions() {
323 workflowActionVM.availableActions = Utils.getProp(workflowActionVM, "workflow.actions") ? workflowActionVM.workflow.actions : [];
324 workflowActionVM.availableActions = _.map(workflowActionVM.availableActions, function(action) {
325 action["displayText"] = action["name"] || action["action_id"];
326 return action;
327 });
328 }
329
330 /**
331 * setupDropdown: Method which convert normal select to select2 component
332 * @param {string} id : Id of the select which needs to be converted to select2
333 * @param {array} data : Data for the select2
334 */
335 function setupDropdown(id, data, parentContainerId) {
336 $("#" + id).select2({
337 data: data || [],
338 placeholder: "Select any Action",
339 width: 'resolve',
340 dropdownCssClass: "lw-select__font-roboto",
341 containerCssClass: "lw-select__border-radius-2"
342 });
343 $('#select2-lwActionWorkflowBetaActionResponse-container .select2-selection__placeholder').css('padding-right', '5px');
344 $('#ltmsStudioWorkflowEditModal .select2-selection__arrow b').replaceWith('<i class="fa fa-angle-down" style="color: #708090;padding-top: 45%;font-weight: 900;"></i>');
345 }
346
347 /**
348 * setContainerId: Setter method for the container Id
349 * @param {string} containerId: Id of the container inside which the options needs to be populate/render
350 */
351 function setContainerId(containerId) {
352 optionsContainerId = containerId;
353 }
354
355 /**
356 * setOptionsBasedOnActions: Set options for which form needs to be dynamically render.
357 * @param {string} containerId: Id of the container inside which the options needs to be populate/render
358 */
359 function setOptionsBasedOnActions(options) {
360 optionsBasedOnActions = Helpers.deepClone(options);
361 }
362 /**
363 * setActionId: Set Action Id
364 */
365 function setActionId(id) {
366 actionId = id;
367 }
368
369 /**
370 * getContainerId: Getter method for the container Id
371 * @return {string}
372 */
373 function getContainerId() {
374 return optionsContainerId;
375 }
376
377 /**
378 * getOptionsBasedOnActions: Getter method for the options of selected Actions
379 * @return {object}
380 */
381 function getOptionsBasedOnActions() {
382 return optionsBasedOnActions;
383 }
384
385 /**
386 * getActionId: Get Action Id
387 */
388 function getActionId(id) {
389 return actionId;
390 }
391
392 /*
393 Mehtod to to get value based on action and populating when edit the existing rule (in update mode).
394 @ param : actionId - Action Type , for eg: APIrequest , SMSNotification etc.
395 @ param : index : Defines whether it is in insert mode or update mode.
396 */
397 workflowActionVM.getFormBasedOnAction = function(actionId, index) {
398 indexCount++;
399 var selectedActionSchemaOptions = Utils.getProp(workflowActionVM.actionsHash, actionId + ".schema.options");
400 if ((index == 0 || index)) {
401 selectedActionSchemaOptions["uuid"] = {};
402 selectedActionSchemaOptions["uuid"]["valueToSet"] = workflowActionVM.workflow.actions[index] && workflowActionVM.workflow.actions[index]["uuid"] ? workflowActionVM.workflow.actions[index]["uuid"] : "";
403 workflowActionVM.selectedActionUuid = workflowActionVM.workflow.actions[index] && workflowActionVM.workflow.actions[index]["uuid"] ? workflowActionVM.workflow.actions[index]["uuid"] : "";
404 selectedActionSchemaOptions = mapPrepopulateValue(selectedActionSchemaOptions, index, actionId);
405 } else {
406
407 // This check will resist to renderForm method second time as it triggers second time when action type get change.
408 if (indexCount % 2 != 0) {
409 for (var key in selectedActionSchemaOptions) {
410 delete selectedActionSchemaOptions[key]['valueToSet'];
411 }
412 }
413 }
414 setActionId(actionId);
415
416 $('#lwActionWorkflowBetaActionsRstContainer').addClass('lw-act-workflow__action-container-mid');
417 $('#lwActionWorkflowBetaActionsApiContner').addClass('lw-act-workflow__action-container-mid');
418 if (actionId != 'APIRequest') {
419 setOptionsBasedOnActions(selectedActionSchemaOptions);
420 renderForm(selectedActionSchemaOptions, actionId);
421 workflowActionVM.isAPIRequest = false;
422 } else {
423 getFieldDetails();
424 setupDropdown("lwWorkflowActionMethod");
425 setupDropdown("lwActionWorkflowBetaActionResponse");
426 setOptionsBasedOnActions(selectedActionSchemaOptions);
427 workflowActionVM.isAPIRequest = true;
428 }
429 }
430 /*
431 Method to populate value into respective fields on page while editing the rule.
432 */
433 function mapPrepopulateValue(schemaOption, index, actionId) {
434 workflowActionVM.parameterAuth = true;
435 workflowActionVM.parameterKeyPair = true;
436 workflowActionVM.authRequired = false;
437 var selectedAction = workflowActionVM.workflow.actions[index];
438 updateOptions = selectedAction;
439 if (actionId == 'APIRequest') {
440 prepareUpdateData(updateOptions);
441 } else if (Utils.getProp(selectedAction, "action_id")) {
442 $timeout(function() {
443 $('#lwActionWorkflowBetaActionsList').val(selectedAction["action_id"]).trigger("change");
444 }, 0)
445 var key;
446 for (key in selectedAction.options) {
447 schemaOption[key]["valueToSet"] = selectedAction.options[key];
448 }
449 schemaOption["uuid"]["valueToSet"] = Utils.getProp(selectedAction, "uuid") ? Utils.getProp(selectedAction, "uuid") : "";
450 }
451 return schemaOption;
452 }
453
454 function renderForm(options, selectedAction) {
455 var mainContainerId = getContainerId();
456 var mainContainer = Utils._id(mainContainerId);
457 var optionLength = _.size(options)
458 // $('.lw-act-workflo_.isEmpty(options)w__round-btn-margin').css('margin-top','126px');
459 // Empty the main container whenever the form renders.
460 if ((renderOptionCount == 0)) {
461 mainContainer.innerHTML = "";
462 if (!_.isEmpty(options)) {
463 var elemsPromises = [];
464 if (mainContainer) {
465 for (var key in options) {
466 if (!(optionLength == renderOptionCount)) {
467 var element = null;
468 var container = document.createElement("div");
469 container.id = "lwWorkflowRuleUpdateActionContainer";
470 container.setAttribute("class", "col col-lg-12 col-md-12 col-sm-12 col-xs-12 padding-top-10");
471 switch (options[key]["type"]) {
472 case "string":
473 elemsPromises.push($q(function(resolve, reject) {
474 renderOptionCount++;
475 resolve({ "options": options[key], "dom": getInputBox(key, options[key], container) })
476 }))
477 break;
478 case "boolean":
479 elemsPromises.push($q(function(resolve, reject) {
480 renderOptionCount++;
481 resolve({ "options": options[key], "dom": getCheckbox(key, options[key], container) })
482 }))
483 break;
484 case "list":
485 elemsPromises.push($q(function(resolve, reject) {
486 renderOptionCount++;
487 var dropdownPromise = getDropdown(key, options[key], container, mainContainer);
488 (function(key, options) {
489 dropdownPromise.then(function(res, err) {
490 resolve({ "dom": res, "options": options[key] })
491 })
492 })(key, options)
493 }))
494 break;
495 case "object":
496 elemsPromises.push($q(function(resolve, reject) {
497 renderOptionCount++;
498 resolve({ "options": options[key], "dom": getInputForObject(key, options[key], container) })
499 }))
500 break;
501 case "component":
502 elemsPromises.push($q(function(resolve, reject) {
503 renderOptionCount++;
504 resolve({ "options": options[key], "dom": getComponent(key, options[key], container, mainContainerId) });
505 }))
506 }
507 }
508 }
509 } else {
510 console.log("Container for populating options not present.")
511 }
512
513 $q.all(elemsPromises).then(function(promise) {
514 if ((optionLength == renderOptionCount)) {
515 renderOptionCount = 0;
516 } else if (options.uuid && optionLength == renderOptionCount + 1) {
517 renderOptionCount = 0;
518 }
519 for (var promiseIndex in promise) {
520 var elemProps = promise[promiseIndex];
521 var domElem = elemProps.dom.$$state ? elemProps.dom.$$state.value : elemProps.dom;
522 mainContainer.appendChild(domElem);
523
524 if (domElem.nodeName == "SELECT") {
525 var elementId = domElem.id;
526 $('#' + elementId).on('change', function(event, params) {
527 params = params || { "selected": event.target.value }
528 // Get the 'for' attribute of the element, which contains the option key. Eg. url, method
529 var attribute = document.getElementById(event.target.id).getAttribute("for");
530
531 // Get parent of the hierarchy dropdown
532 var hierarchyElem = $("#" + event.target.id + "_chosen");
533
534 if (Utils.getProp(hierarchyElem, "0")) {
535 //var hierarchyElemParentContainer = hierarchyElem.parent();
536 var container = document.createElement("div");
537 container.id = "hierarchy_container_" + event.target.id + "_{{hierarchy}}";
538 container.setAttribute("class", "col col-lg-12 col-md-12 col-sm-12 col-xs-12 padding-0");
539
540 // Check if hierarchy list already exists. If present then remove.
541 var hierarchyContainer = Utils._id("hierarchy_container_" + event.target.id + "_{{hierarchy}}");
542 if (hierarchyContainer) {
543 hierarchyContainer.remove();
544 }
545
546 // In case of '{{hierarchy}}', need to further fetch the levels.
547 if (params["selected"] != "{{hierarchy}}") {
548 if (params["selected"] = "{{status}}") {
549 hierarchyElem.after(container);
550 getPossibleValue(attribute, optionsBasedOnActions, params["selected"], mainContainer, container)
551
552 }
553 if (params["selected"] = "{{category}}") {
554 hierarchyElem.after(container);
555 getPossibleValue(attribute, optionsBasedOnActions, params["selected"], mainContainer, container)
556
557 }
558 if (params["selected"] = "{{subcategory}}") {
559 hierarchyElem.after(container);
560 getPossibleValue(attribute, optionsBasedOnActions, params["selected"], mainContainer, container)
561
562 }
563 // Update the options for the value
564 optionsBasedOnActions[attribute]["valueToSet"] = params["selected"];
565 } else {
566 // below, the "values" contains the possible value for the dropdown.
567 // The method 'getPossibleValue' will check for next possible value, if avilable then it will render it.
568 getPossibleValue(attribute, optionsBasedOnActions, params["selected"], mainContainer, container);
569 hierarchyElem.after(container);
570 }
571 }
572 })
573
574 $("#" + elementId).chosen({
575 "width": '100%',
576 "inherit_select_classes": true
577 });
578
579 // Prepopulate value if already there
580 if (Utils.getProp(elemProps.options, "valueToSet")) {
581 if (elemProps.options["valueToSet"].indexOf("{{hierarchy.") > -1) {
582 // Get parent of the hierarchy dropdown
583 var hierarchyElem = $("#" + elementId + "_chosen");
584 if (Utils.getProp(hierarchyElem, "0")) {
585 //var hierarchyElemParentContainer = hierarchyElem.parent();
586 var container = document.createElement("div");
587 container.id = "hierarchy_container_" + elementId + "_{{hierarchy}}";
588 container.setAttribute("class", "col col-lg-12 col-md-12 col-sm-12 col-xs-12 padding-0");
589
590 // Check if hierarchy list already exists. If present then remove.
591 var hierarchyContainer = Utils._id("hierarchy_container_" + elementId + "_{{hierarchy}}");
592 if (hierarchyContainer) {
593 hierarchyContainer.remove();
594 }
595
596 // below, the "values" contains the possible value for the dropdown.
597 // The method 'getPossibleValue' will check for next possible value, if avilable then it will render it.
598 //getPossibleValue(key, Helpers.deepClone(options), "{{hierarchy}}", mainContainer, container);
599
600 hierarchyElem.after(container);
601 $("#" + elementId).val("{{hierarchy}}").trigger('chosen:updated').change();
602 }
603 } else {
604 $("#" + elementId).val(elemProps.options["valueToSet"]).trigger('chosen:updated');
605 }
606 } else {
607 console.log('ValueToSet not found in options which need to render.')
608 }
609
610 $('#ltmsStudioWorkflowEditModal .chosen-drop').attr("style", "font-family: Roboto;font-size: 11px !important;font-weight: 400;color: #708090 !important;border-radius: 2px;")
611 $('#ltmsStudioWorkflowEditModal .chosen-single').attr("style", "font-family: Roboto;font-size: 11px !important;font-weight: 400;border-radius: 2px;color: #708090 !important;")
612 }
613 }
614 }.bind(this))
615 }
616
617 $("#" + mainContainerId + " .chosen-container b").replaceWith('<i class="fa fa-angle-down" style="font-weight: 900; margin-top: 45%;margin-left: -9%;"></i>');
618
619 }
620 }
621
622 function getComponent(optionHeader, optionDetail, mainContainer, mainContainerId) {
623 var container = document.createElement('div');
624 container.setAttribute("id", "ltms_workflow_dynamic_component")
625 container.innerHTML = "";
626
627 // START: Header
628
629 var options = {
630 "isRequired": true,
631 "errorMsg": "Atleast one template is required.",
632 "classToRender": "LwComponentRenderer",
633 "componentToRender": "lw-action-template-component",
634 "attributes": {
635 "templateid": optionDetail.valueToSet,
636 "callee": "lw-workflow-template-component",
637 },
638 "keyToUpdate": "templateid",
639 }
640 workflowActionVM.emailNotificationActionTemplateConfig = optionHeader;
641 mainContainer.appendChild(container);
642
643 setTimeout(function() {
644 document.getElementById("ltms_workflow_dynamic_component").innerHTML = "";
645 var label = document.createElement('label')
646 label.setAttribute('class', 'lw-workflow-template-component__label')
647 // label.setAttribute("class", "padding-right-10");
648 label.appendChild(document.createTextNode(optionDetail["name"] || optionHeader));
649 container.appendChild(label);
650 LwComponentRenderer.renderElement("ltms_workflow_dynamic_component", options, $compile, $scope)
651
652 }, 0)
653
654 return mainContainer;
655 }
656
657 //to set the template id for the email notification action
658 LtmsEventListener.on("send-template-id-to-workflow-action-component", function(event) {
659 if (event && event.data && !_.isEmpty(workflowActionVM.emailNotificationActionTemplateConfig)) {
660 optionsBasedOnActions[workflowActionVM.emailNotificationActionTemplateConfig]["valueToSet"] = event.data;
661 }
662 })
663
664 workflowActionVM.setDropdown = function(id, data) {
665 console.log("id", id);
666 console.log("id", data)
667 console.log("id", id)
668 // $timeout(function() {
669 console.log("dropdowm selected");
670 // Reset the element: Remove all the options
671 $("#" + id).empty().trigger('change');
672 // Add default option
673 $("#" + id).append("<option></option>");
674 $("#" + id).select2({
675 data: data || [],
676 placeholder: "Select",
677 // placeholder: "Select " + (type == "Ruleset" ? "" : type),
678 width: 'resolve',
679 dropdownCssClass: "lw-select__font-roboto",
680 containerCssClass: "lw-select__border-radius-2"
681 });
682 $('#select2-lwActionWorkflowBetaActionsOptionsForm .select2-selection__placeholder').css('padding-right', '5px');
683 $('#ltmsStudioWorkflowEditModal .select2-selection__arrow b').replaceWith('<i class="fa fa-angle-down" style="color: #708090;padding-top: 45%;font-weight: 900;"></i>');
684
685 // }, 0);
686 }
687
688 function getPossibleValue(key, attributeOptions, selectedOption, mainContainer, container) {
689 console.log("keyy>>>>>>>>>", key);
690 console.log("selectedOption", selectedOption)
691 var attributeForKey = attributeOptions[key];
692 var availableOptions = attributeForKey["values"];
693 var selectedOptionDetail = _.findWhere(availableOptions, { id: selectedOption });
694 console.log("selectedOptionDetail", selectedOptionDetail.id);
695
696 // console.log("data is availabale", selectedOptionDetail["possible_values"]);
697
698 if (selectedOption == "{{hierarchy}}" && !_.isEmpty(selectedOptionDetail) && selectedOptionDetail["possible_values"]) {
699
700 console.log("data")
701 // Create dropdown dynamically for the possible values
702 selectedOptionDetail["datasource"] = { "expression": selectedOptionDetail["possible_values"], "type": 3, "dataFromExpression": true };
703 console.log("datasource", selectedOptionDetail["datasource"]);
704
705 var promise = getDataFromDataSource(selectedOptionDetail);
706 console.log("pro>>>>>>>>>>>>>>>",promise);
707 promise.then(function(data, error) {
708 var values = [];
709 if (data) {
710
711 // get the lastest key-value from the promise data. This will basically used in case of getting of latest hierarchy.
712 values = prepareHierarchyLevelDetail(data);
713
714 var id = "hierarchy_manager";
715
716 var dropDownPromise = getDropdown(id, {
717 "name": selectedOptionDetail["possible_values"],
718 "values": values
719 }, container, mainContainer);
720
721 dropDownPromise.then(function(res, err) {
722
723 container.append(res);
724
725 var elementId = res.id;
726 console.log("elementId", elementId)
727 $('#' + elementId).on('change', function(event, params) {
728 var attribute = document.getElementById(event.target.id).getAttribute("for");
729 attributeForKey["valueToSet"] = params["selected"];
730 optionsBasedOnActions[key]["valueToSet"] = params["selected"];
731 });
732
733 $("#" + elementId).chosen({
734 "width": '100%',
735 "inherit_select_classes": true
736 });
737 $('#ltmsStudioWorkflowEditModal .chosen-single').attr("style", "font-family: Roboto;font-size: 11px !important;font-weight: 400;color: #708090 !important;border-radius: 2px;")
738 $('#ltmsStudioWorkflowEditModal .chosen-drop').attr("style", "font-family: Roboto;font-size: 11px !important;font-weight: 400;color: #708090 !important;border-radius: 2px;")
739 $("#lwActionWorkflowBetaActionsOptionsForm .chosen-container b").replaceWith('<i class="fa fa-angle-down" style="font-weight: 900; margin-top: 45%;margin-left: -9%;"></i>');
740
741 var hierarchySelect = Utils._id(elementId + "_chosen");
742
743 if (hierarchySelect) {
744 hierarchySelect.setAttribute("style", "width: 100%;padding-bottom: 0px;")
745 }
746
747 $("#" + elementId + "_chosen .chosen-drop").css({ "width": "100%" })
748
749 if (attributeForKey["valueToSet"]) {
750 $('#' + elementId).val(attributeForKey["valueToSet"]).trigger('chosen:updated');
751 }
752
753 })
754 }
755 });
756 }
757
758 ////for status category
759 if (selectedOptionDetail["expression"]) {
760 // statusCategorySubcategoryCustomGroupData();
761 if (selectedOptionDetail["value_type"] == "expression") {
762 console.log("newdataavailable>>>>>>>>>>>>");
763 var promise = getDataFromDataExpression(selectedOptionDetail);
764 console.log("promise>>>>", promise);
765 promise.then(function(data, error) {
766 var values = [];
767 if (data) {
768 console.log("dataaalllcategory",data);
769
770 // get the lastest key-value from the promise data. This will basically used in case of getting of latest hierarchy.
771 // values = prepareHierarchyLevelDetail(data);
772
773 var id = "hierarchy_manager";
774
775 var dropDownPromise = getDropdown(id, {
776 "name": selectedOptionDetail["expression"],
777 "values": values
778 }, container, mainContainer);
779
780 dropDownPromise.then(function(res, err) {
781
782 container.append(res);
783
784 var elementId = res.id;
785 console.log("elementId", elementId)
786 $('#' + elementId).on('change', function(event, params) {
787 var attribute = document.getElementById(event.target.id).getAttribute("for");
788 attributeForKey["valueToSet"] = params["selected"];
789 optionsBasedOnActions[key]["valueToSet"] = params["selected"];
790 });
791
792 $("#" + elementId).chosen({
793 "width": '100%',
794 "inherit_select_classes": true
795 });
796 $('#ltmsStudioWorkflowEditModal .chosen-single').attr("style", "font-family: Roboto;font-size: 11px !important;font-weight: 400;color: #708090 !important;border-radius: 2px;")
797 $('#ltmsStudioWorkflowEditModal .chosen-drop').attr("style", "font-family: Roboto;font-size: 11px !important;font-weight: 400;color: #708090 !important;border-radius: 2px;")
798 $("#lwActionWorkflowBetaActionsOptionsForm .chosen-container b").replaceWith('<i class="fa fa-angle-down" style="font-weight: 900; margin-top: 45%;margin-left: -9%;"></i>');
799
800 var hierarchySelect = Utils._id(elementId + "_chosen");
801
802 if (hierarchySelect) {
803 hierarchySelect.setAttribute("style", "width: 100%;padding-bottom: 0px;")
804 }
805
806 $("#" + elementId + "_chosen .chosen-drop").css({ "width": "100%" })
807
808 if (attributeForKey["valueToSet"]) {
809 $('#' + elementId).val(attributeForKey["valueToSet"]).trigger('chosen:updated');
810 }
811
812 })
813 }
814 });
815 // LtmsWorkflowDataSource.getData({
816 // "type": 3,
817 // "expression": selectedOptionDetail["expression"]
818 // }, function(error, response) {
819
820 // console.log("datasourcestatus>>>>", response);
821 // var displayField = response["displayField"];
822 // // In case of dynamic Id other then uuid, id such as page_name
823 // var idField = Utils.getProp(selectedOptionDetail, "options.field_id");
824 // var data = _.map(response["data"], function(d) {
825
826 // d["id"] = d["uuid"] || d["field_id"];
827 // d["text"] = d[displayField];
828 // console.log("ddddddddd", d["text"])
829 // return {
830 // "id": d["uuid"] || d["field_id"] || d[idField],
831 // "text": d[displayField]
832 // };
833 // });
834 // console.log("iddddddddddd", data);
835 // if (selectedOptionDetail["value_type"] == "expression") {
836 // console.log("dataalllllllllllll>>>>>>>>>>>>>");
837 // workflowActionVM.setDropdown("lwActionWorkflowBetaActionsOptionsForm", data)
838 // };
839 // })
840 // workflowActionVM.setDropdown("lwActionWorkflowBetaActionsList","value", data);
841 // workflowConditionsVM.hasSubLHS = false;
842 // workflowConditionsVM.setDropdown(("lwActionWorkflowConditionRHSList_" + workflowConditionsVM.callee), "value", data, ("lwActionWorkflowConditionRHSListContainer_" + workflowConditionsVM.callee));
843 }
844 }
845 }
846
847 /**;
848 * prepareHierarchyLevelDetail: This method prepare data for the case of latest hierarchy levels
849 * @param {object} data
850 * @return {object} : Array of Objects where id and text will be the key.
851 */
852 function prepareHierarchyLevelDetail(data) {
853 // console.log("datahierarch", data)
854 var detail = [];
855 var keys = Object.keys(data);
856 var lastKey = keys[keys.length - 1];
857 var lastVal = data[lastKey];
858
859 if (lastVal && lastVal.length) {
860 _.each(lastVal, function(val) {
861 // replace spcace with underscore
862 val = val.replace(/ /g, "_");
863 detail.push({
864 "id": "{{hierarchy." + val + ".manager}}",
865 "text": val
866 });
867 })
868 }
869 return detail;
870 }
871
872 function getInputBox(optionHeader, optionDetail, container) {
873 var input = document.createElement("input");
874 container.appendChild(input);
875 input.id = "ltmsWorkflowModalActions_" + optionHeader;
876 input.setAttribute("class", "form-control");
877 input.setAttribute("placeholder", optionDetail["name"]);
878 input.setAttribute("style", "width: 100%;");
879
880 input.value = Utils.getProp(optionDetail, "valueToSet") || "";
881 input.addEventListener("keyup", function(event) {
882 var inputValue = $(this).val();
883
884 // input for key value
885 if (Utils.getProp(optionDetail, "isKeyValue")) {
886 if (!optionsBasedOnActions[optionDetail["fieldToUpdate"]]["valueToSet"]) {
887 optionsBasedOnActions[optionDetail["fieldToUpdate"]]["valueToSet"] = {};
888 }
889
890 if (!optionsBasedOnActions[optionDetail["fieldToUpdate"]]["valueToSet"][optionDetail["index"]]) {
891 optionsBasedOnActions[optionDetail["fieldToUpdate"]]["valueToSet"][optionDetail["index"]] = {};
892 }
893 optionsBasedOnActions[optionDetail["fieldToUpdate"]]["valueToSet"][optionDetail["index"]][optionDetail["dataType"]] = inputValue;
894
895 } else {
896 optionsBasedOnActions[optionHeader]["valueToSet"] = inputValue;
897 }
898 })
899
900 return container;
901 }
902
903 function getCheckbox(optionHeader, optionDetail, container) {
904 var checkbox = document.createElement('input');
905 checkbox.type = "checkbox";
906 checkbox.name = "name";
907 checkbox.value = "value";
908 checkbox.id = "ltmsWorkflowModalActions_" + optionHeader;
909
910 checkbox.addEventListener("change", function(event) {
911 optionsBasedOnActions[optionHeader]["valueToSet"] = $(this).prop("checked");
912 });
913
914 var label = document.createElement('label');
915 label.setAttribute("class", "padding-right-10");
916 label.appendChild(document.createTextNode(optionDetail["name"] || optionHeader));
917
918 container.appendChild(label);
919 container.appendChild(checkbox);
920
921 return container;
922 }
923
924 function getDropdown(optionHeader, optionDetail, container, mainContainer) {
925
926 return $q(function(resolve, reject) {
927 var select = document.createElement("select");
928 select.id = "ltmsWorkflowModalActions_" + optionHeader;
929 console.log("select.id", select.id);
930 $('#' + select.id).text('empty');
931
932 select.setAttribute("class", "lw-select__font-roboto lw-select__border-radius-2 padding-top-10 col-md-10")
933
934 select.setAttribute("for", optionHeader);
935
936 var defaultOption = document.createElement("option");
937 defaultOption.value = '';
938 defaultOption.selected = "selected";
939 defaultOption.disabled = "disabled";
940
941 select.setAttribute("data-placeholder", "Select " + ((optionDetail["name"] && optionDetail["name"] == "{{brand.hierarchy_list}}") ? "Level" : optionDetail["name"] || optionHeader));
942
943 // add default option to select
944 select.appendChild(defaultOption);
945 var promise = fetchOptionDataAndPopulate(optionDetail, select.id);
946
947 promise.then(function(selectItems, error) {
948 _.each(selectItems, function(option) {
949 var slctOptn = document.createElement("option");
950 slctOptn.text = option.text;
951 slctOptn.value = option.id;
952 select.appendChild(slctOptn);
953 });
954 resolve(select);
955 });
956 })
957 }
958
959 /**
960 * fetchOptionDataAndPopulate : This method fetche the data for the dropdown based on the resources.
961 * @param {object} optionDetail : Parameters for the options such as datasource or values
962 * @param {string} elemId : Id of the dropdown in which options needs to be appended.
963 */
964 function fetchOptionDataAndPopulate(optionDetail, elemId) {
965 return ($q(function(resolve, reject) {
966 var options = [];
967 if (optionDetail && optionDetail["values"] && optionDetail["values"].length) {
968 // If contains "values": Hard coded values
969
970 if (_.isObject(optionDetail["values"][0]) && !_.isArray(optionDetail["values"][0])) {
971 options = optionDetail["values"];
972 } else {
973 options = _.map(optionDetail["values"], function(value) {
974 return ({ "id": value, "text": value })
975 });
976 }
977 resolve(options);
978
979 } else if (optionDetail["datasource"]) {
980 // Get the data from some source. Source can be API, dataset or any expression.
981 var promise = getDataFromDataSource(optionDetail);
982 console.log("promisepromisepromise",promise);
983 promise.then(function(value, error) {
984 options = value;
985 if (value) {
986 resolve(options);
987 } else {
988 resolve([]);
989 }
990 });
991 }
992 }));
993 }
994
995
996 ////added by sohel for status and category and subcategory
997 /**
998 * getDataFromDataSource : This method gets the data from some source, where source can be API, dataset or expression
999 * @param {object} optionDetail : Parameters to get the data
1000 */
1001 function getDataFromDataExpression(optionDetail) {
1002 return ($q(function(resolve, reject) {
1003 LtmsWorkflowDataSource.getData({
1004 "type": 3,
1005 "expression": optionDetail["expression"]
1006 }, function(error, response) {
1007 if (error) {
1008 reject('Not able to populate the data due to error.');
1009 } else {
1010 console.log("datasourcestatus>>>>", response);
1011 var displayField = response["displayField"];
1012 // In case of dynamic Id other then uuid, id such as page_name
1013 var idField = Utils.getProp(optionDetail, "options.field_id");
1014 var data = _.map(response["data"], function(d) {
1015
1016 d["id"] = d["uuid"] || d["field_id"];
1017 d["text"] = d[displayField];
1018 console.log("ddddddddd", d["text"])
1019 return {
1020 "id": d["uuid"] || d["field_id"] || d[idField],
1021 "text": d[displayField]
1022 };
1023 resolve(data);
1024 });
1025 console.log("iddddddddddd", data);
1026 if (optionDetail["value_type"] == "expression") {
1027 console.log("dataalllllllllllll>>>>>>>>>>>>>");
1028 workflowActionVM.setDropdown("lwActionWorkflowBetaActionsOptionsForm", data)
1029 }
1030 }
1031 })
1032
1033 }));
1034 }
1035
1036 /**
1037 * getDataFromDataSource : This method gets the data from some source, where source can be API, dataset or expression
1038 * @param {object} optionDetail : Parameters to get the data
1039 */
1040 function getDataFromDataSource(optionDetail) {
1041 return ($q(function(resolve, reject) {
1042 LtmsWorkflowDataSource.getData(optionDetail["datasource"], function(error, data) {
1043 if (error) {
1044 reject('Not able to populate the data due to error.');
1045 } else {
1046 if (Utils.getProp(optionDetail, "datasource.dataFromExpression")) {
1047 // Return data as it is as the getData response.
1048 resolve((Utils.getProp(data, "data")) ? data.data : data);
1049 } else {
1050 var valuesToDisplay = Utils.getProp(optionDetail, "datasource.valuesToDisplay");
1051 if (valuesToDisplay) {
1052 var options = _.map(data, function(option) {
1053
1054 return ({ "id": option[valuesToDisplay["key"]], "text": option[valuesToDisplay["value"]] })
1055 });
1056 resolve(options);
1057 } else {
1058 reject("Field 'valuesToDisplay' needs to be set.");
1059 }
1060 }
1061 }
1062 });
1063 }));
1064 }
1065
1066 function getInputForObject(optionHeader, optionDetail, mainContainer) {
1067
1068 var container = document.createElement('div');
1069 // container.classList.add("display-flex")
1070 var noOfKeyValue = 1;
1071
1072 // START: Header
1073 var label = document.createElement('label')
1074 // label.setAttribute("class", "padding-right-10");
1075 label.appendChild(document.createTextNode(optionDetail["name"] || optionHeader));
1076 container.appendChild(label);
1077
1078 var btnContainer = document.createElement('div');
1079 //btnContainer.setAttribute("style", "display: inline-block;");
1080 btnContainer.setAttribute("class", "padding-left-10");
1081 container.appendChild(btnContainer);
1082
1083 var button = document.createElement("button");
1084 $(button).css({
1085 "margin-top": "10px",
1086 "margin-bottom": "10px",
1087 "margin-left": "-10px"
1088 })
1089
1090 button.setAttribute("class", "btn btn-success btn-sm");
1091 button.innerHTML = "Add";
1092 button.id = "btn_add_" + optionHeader;
1093 btnContainer.appendChild(button);
1094
1095 button.addEventListener('click', function(e) {
1096 var keyValueContainer = document.createElement('div');
1097 container.appendChild(keyValueContainer);
1098 keyValueContainer.classList.add("display-flex");
1099
1100 // console.log("keyValueAdditionalContainer:::", keyValueAdditionalContainer)
1101 prepareKeyValueElement(optionHeader, (++noOfKeyValue), keyValueContainer);
1102 });
1103 // END: Header
1104
1105 // START: Intially there will be only one key value input
1106 var keyValueContainer = document.createElement('div');
1107 container.appendChild(keyValueContainer);
1108 keyValueContainer.classList.add("display-flex");
1109 prepareKeyValueElement(optionHeader, noOfKeyValue, keyValueContainer);
1110
1111 // var keyValueAdditionalContainer = document.createElement('div');
1112 // container.appendChild(keyValueAdditionalContainer);
1113
1114
1115 // END: Intially there will be only one key value input
1116
1117 mainContainer.appendChild(container);
1118
1119 return mainContainer;
1120 }
1121
1122 function prepareKeyValueElement(optionHeader, keyValueIndex, keyValueContainer) {
1123 var keyContainer = document.createElement('div');
1124 //keyContainer.setAttribute("class", "padding-top-10");
1125 //keyContainer.setAttribute("style", "display: inline-block;");
1126 keyValueContainer.appendChild(keyContainer);
1127 keyValueContainer.classList.add("display-flex", "margin-top-10");
1128 getInputBox(optionHeader + "_key_" + keyValueIndex, { "isKeyValue": true, "index": keyValueIndex, "name": "Key", "dataType": "key", "fieldToUpdate": optionHeader }, keyContainer);
1129
1130 var valueContainer = document.createElement('div');
1131 //keyContainer.setAttribute("style", "display: inline-block;");
1132 valueContainer.setAttribute("class", "padding-left-10");
1133 keyValueContainer.appendChild(valueContainer);
1134 getInputBox(optionHeader + "_value_" + keyValueIndex, { "isKeyValue": true, "index": keyValueIndex, "name": "Value", "dataType": "value", "fieldToUpdate": optionHeader }, valueContainer);
1135
1136 var btnContainer = document.createElement('div');
1137 //btnContainer.setAttribute("style", "display: inline-block;");
1138 btnContainer.classList.add("margin-top-5", "padding-left-10");
1139 keyValueContainer.appendChild(btnContainer);
1140 // <a type="button" ng-click="$ctrl.deleteKeyPair(row.key, row.value ,$index)" id="delete">
1141 // <img class="modal-icon" src="assets/trash-can-outline.svg">
1142 // </a>
1143 var deletebtn = document.createElement("a");
1144 var discardIcon = document.createElement("img");
1145 discardIcon.classList.add("modal-icon");
1146 discardIcon.setAttribute("src", "assets/trash-can-outline.svg");
1147 // discardIcon.style.paddingTop = "3px";
1148 deletebtn.appendChild(discardIcon);
1149 // var deletebtn = document.createElement("button");
1150 // deletebtn.setAttribute("class", "btn btn-danger btn-sm");
1151 // deletebtn.innerHTML = "Delete";
1152 deletebtn.id = optionHeader + "_deleteBtn_" + keyValueIndex;
1153 btnContainer.appendChild(deletebtn);
1154
1155 deletebtn.addEventListener('click', function(e) {
1156 $("#ltmsWorkflowModalActions_" + optionHeader + "_key_" + keyValueIndex).remove()
1157 $("#ltmsWorkflowModalActions_" + optionHeader + "_value_" + keyValueIndex).remove()
1158 $("#" + optionHeader + "_deleteBtn_" + keyValueIndex).remove()
1159 });
1160 }
1161
1162 LtmsEventListener.on("reset-workflow-modal", function(event) {
1163 workflowActionVM.resetForm();
1164 });
1165
1166 workflowActionVM.resetForm = function() {
1167 paramsConfig = {
1168 "key": null,
1169 "value": null,
1170 "index": 0
1171 };
1172 actionConfig = {
1173 "key": null,
1174 "value": null,
1175 "index": 1,
1176 "options": []
1177 };
1178 workflowActionVM.requestOptions = {
1179 'requestType': 'POST',
1180 'urlMarginLeft': '0px',
1181 parameters: {
1182 'json': {}
1183 },
1184 authorisation: {
1185 'json': {}
1186 }
1187 };
1188
1189 options = {
1190 method: "",
1191 url: "",
1192 authentication_required: "",
1193 data: {},
1194 should_save_api_response: false,
1195 api_response_config: {},
1196 authorization: {
1197 auth_type: "",
1198 body: {}
1199 },
1200 auth_params: {},
1201 parameter_json: false
1202 }
1203 authorisationData = {};
1204 actionIndexToUpdate = null;
1205 workflowActionVM.selectedOptions = {};
1206 getFieldDetails();
1207 workflowActionVM.requestOptions.authorisation.json = JSON.stringify(new Object);
1208 workflowActionVM.requestOptions.parameters.json = JSON.stringify(new Object);
1209 workflowActionVM.authRequired = false;
1210 $('#lwWorkflowActionauthcheckbox').prop('checked', false);
1211 $('#lwActionWorkflowActioncheckParams').trigger('click');
1212
1213 workflowActionVM.parameterKeyPair = true;
1214
1215 var authTypeName = workflowActionVM.authorisationTypeName;
1216 for (var key in authorisationTypeName) {
1217 for (var i = 0; i < workflowActionVM.authorisationTypeData[key].length; i++) {
1218 if (key == "bearerToken" && workflowActionVM.authorisationTypeData[key][i]['keyName'] == "bearer_token_body") {
1219 workflowActionVM.authorisationTypeData[key][i]['value'] = null;
1220 workflowActionVM.requestOptions.authorisation.json = JSON.stringify(new Object);
1221 } else {
1222 workflowActionVM.authorisationTypeData[key][i]['value'] = "";
1223 }
1224 }
1225 }
1226 var containerId = "lwActionWorkflowBetaActionsListContainer";
1227 var dynamicElementsContainerId = getContainerId();
1228 $('#lwActionWorkflowBetaActionsRstContainer').removeClass('lw-act-workflow__action-container-mid');
1229 $('#lwActionWorkflowBetaActionsApiContner').removeClass('lw-act-workflow__action-container-mid');
1230 $('#' + containerId).trigger("reset");
1231 resetFormById('lwActionWorkflowBetaActionsOptionsForm');
1232 resetFormById(containerId);
1233
1234 setOptionsBasedOnActions(optionsBasedOnActions);
1235 resetActionHash();
1236
1237 // $('#lwActionWorkflowBetaActionsOptionsForm').trigger("reset");
1238
1239 // $("#" + containerId).find(':input').each(function() {
1240 // Remove all the element which gets created dynamically on action selection.
1241 $('#' + dynamicElementsContainerId).empty();
1242
1243 workflowActionVM.isAPIRequest = false;
1244 workflowActionVM.isSaveApi = false;
1245 workflowActionVM.keyPairConfig = [Helpers.deepClone(paramsConfig)];
1246 workflowActionVM.configs = [Helpers.deepClone(actionConfig)];
1247 getFieldDetails();
1248 }
1249
1250 function resetFormById(containerId) {
1251 $("#" + containerId).find(':input').each(function() {
1252
1253 switch (this.type) {
1254 case 'password':
1255 case 'text':
1256 case 'textarea':
1257 case 'file':
1258 case 'date':
1259 case 'number':
1260 case 'tel':
1261 case 'email':
1262 $(this).val('');
1263 var attr = $(this).attr("attrType");
1264 if (attr && attr == 'date') {
1265 $(this).datepicker("setDate", new Date());
1266 }
1267 break;
1268 case 'select':
1269 case 'select-one':
1270 case 'select-multiple':
1271 $(this).val('').trigger("chosen:updated");
1272 $(this).append("<option></option>");
1273 if (this.id == 'lwWorkflowActionMethod') {
1274 $(this).val('POST').trigger("chosen:updated");
1275 setupDropdown("lwWorkflowActionMethod");
1276 } else if (this.id == 'lwActionWorkflowActionAuth') {
1277 workflowActionVM.authorisationTypeName = 'oauth';
1278 $(this).val('oauth').trigger("chosen:updated");
1279 setupDropdown("lwActionWorkflowActionAuth");
1280 }
1281 if (this.id == 'lwActionWorkflowBetaActionsList')
1282 console.log("lwActionWorkflowBetaActionsList>>>>>>", lwActionWorkflowBetaActionsList);
1283 // Update the action dropdown
1284 workflowActionVM.lwActionWorkflowBetaActionsList = null;
1285 setupDropdown("lwActionWorkflowBetaActionsList", workflowActionVM.actionsList, "lwActionWorkflowActionsListContainer");
1286 break;
1287 case 'checkbox':
1288 case 'radio':
1289 this.checked = false;
1290 break;
1291 }
1292 });
1293 }
1294
1295 // Method to convert JSON string to JSON , when input enter in textarea.
1296 function convertToJson() {
1297 try {
1298 options.data = JSON.parse(workflowActionVM.requestOptions.parameters.json);
1299 paramsJsonFlag = false;
1300
1301 } catch (error) {
1302 if (error instanceof SyntaxError) {
1303 paramsJsonFlag = true;
1304 Helpers.smallAlertBox("There was a syntax error. Please correct it and try again: ", error.message, "warn", 3000);
1305 }
1306 }
1307 }
1308
1309 workflowActionVM.addAction = function(actionType) {
1310 authorisationActionData();
1311 apiOption = options;
1312 if (workflowActionVM.isAPIRequest) {
1313 var response = validateAPIRequest(optionsBasedOnActions);
1314 } else {
1315 response = validate(optionsBasedOnActions);
1316 }
1317 if (actionType) {
1318 if (response["isValid"]) {
1319 // TODO: This needs to be happen on save
1320 var apiAction = Helpers.deepClone(apiActions);
1321 apiAction["uuid"] = Utils.getProp(options, "uuid.valueToSet") ? Utils.getProp(options, "uuid.valueToSet") : ""
1322 var action = (workflowActionVM.isAPIRequest) ? apiAction : prepareActionSchema(optionsBasedOnActions);
1323 if (!Utils.getProp(workflowActionVM, "workflow.actions")) {
1324 workflowActionVM["workflow"]["actions"] = [];
1325 }
1326
1327 if (actionIndexToUpdate || actionIndexToUpdate == 0) {
1328 action["uuid"] = workflowActionVM.selectedActionUuid ? workflowActionVM.selectedActionUuid : "";
1329 workflowActionVM.workflow["actions"][actionIndexToUpdate] = action;
1330 } else {
1331 workflowActionVM.workflow["actions"].push(action);
1332 }
1333 workflowActionVM.availableActions = Helpers.deepClone(workflowActionVM.workflow["actions"])
1334 // Reset Form after update.
1335 workflowActionVM.resetForm();
1336 } else {
1337 Helpers.smallAlertBox("Error", response.message, "error", 3000);
1338 }
1339 } else {
1340 Helpers.smallAlertBox("Error", response.message, "error", 3000);
1341 }
1342 }
1343
1344 function validateAPIRequest(options) {
1345 var errorMessage = "";
1346 if (getActionId() == 'APIRequest') {
1347 for (var apiKey in apiOption) {
1348 if (Utils.getProp(options, apiKey + ".required")) {
1349 if (apiOption[apiKey] == undefined || apiOption[apiKey] == null || apiOption[apiKey] == "") {
1350 errorMessage += options[apiKey]["name"] + " is mandatory.<br>";
1351 }
1352 }
1353 }
1354 if (authBearerToknFlag || isAuthData || paramsJsonFlag || apiResponseFlag) {
1355 errorMessage += authErrorMsg;
1356 return { "isValid": false, "message": errorMessage };
1357 }
1358 }
1359
1360 return (errorMessage && errorMessage.length) ? { "isValid": false, "message": errorMessage } : { "isValid": true };
1361 }
1362
1363 function validate(options) {
1364 var errorMessage = "";
1365 var isValueToSetAvailable = false;
1366 var index = 0;
1367 for (var key in options) {
1368 isValueToSetAvailable = (options[key]["valueToSet"] && !(_.isEmpty(options[key]["valueToSet"])));
1369 if (options[key]["required"]) {
1370 // Option is required, now check for value
1371 if (!isValueToSetAvailable) {
1372 // Either "valueToSet" not present in the option or it is empty. "valueToSet" is temporary field, used to capture the value.
1373 errorMessage += options[key]["name"] + " is mandatory.<br>";
1374 }
1375 }
1376 if (isValueToSetAvailable && options[key]["type"] == "object") {
1377 index = 0;
1378 for (index in options[key]["valueToSet"]) {
1379 if (index != "data") {
1380 var keyValuePair = options[key]["valueToSet"][index];
1381 if (!((keyValuePair["key"] && keyValuePair["key"].length) && (keyValuePair["value"] && keyValuePair["value"].length))) {
1382 // If either of the key or value not present
1383 errorMessage += "Invalid key-value.\n";
1384 } else {
1385 var dataKey = keyValuePair["key"];
1386 var dataValue = keyValuePair["value"];
1387 if (!options[key]["valueToSet"]["data"]) {
1388 options[key]["valueToSet"]["data"] = {}
1389 }
1390 options[key]["valueToSet"]["data"][dataKey] = dataValue;
1391 }
1392 }
1393 }
1394 }
1395
1396 }
1397
1398 // errorMessage as null refers Success else Failure
1399 return (errorMessage && errorMessage.length) ? { "isValid": false, "message": errorMessage } : { "isValid": true };
1400 }
1401
1402 function prepareActionSchema(options) {
1403 var actionId = getActionId();
1404 var action = {
1405 "action_id": actionId,
1406 "name": Utils.getProp(workflowActionVM, "actionsHash." + actionId + ".name") || "",
1407 "options": {},
1408 "uuid": Utils.getProp(options, "uuid.valueToSet") ? Utils.getProp(options, "uuid.valueToSet") : ""
1409 };
1410 if (Utils.getProp(options, "uuid.valueToSet")) {
1411 delete options.uuid;
1412 }
1413 var key = null;
1414 var valueToSet = null;
1415 for (key in options) {
1416 valueToSet = Utils.getProp(options, key + ".valueToSet");
1417 // update the action with the option where valueToSet present.
1418 if (valueToSet) {
1419 action["options"][key] = (valueToSet["data"]) ? valueToSet["data"] : valueToSet;
1420 }
1421 }
1422 return action;
1423 }
1424
1425 workflowActionVM.deleteAction = function(actionIndex) {
1426 // splice the specific index from the actions within workflow
1427 workflowActionVM.workflow.actions.splice(actionIndex, 1);
1428 workflowActionVM.availableActions = workflowActionVM.workflow.actions;
1429 }
1430 workflowActionVM.updateAction = function(actionId, index) {
1431 actionIndexToUpdate = index;
1432 indexCount = 0;
1433 workflowActionVM.getFormBasedOnAction(actionId, index);
1434 }
1435 //Method to show or hide JSON or normal view on parameter's tab.
1436 workflowActionVM.parametersVisible = function(parameterName) {
1437 if (parameterName) {
1438 switch (parameterName) {
1439 case 'json':
1440 workflowActionVM.parameterKeyPair = false;
1441 options.parameter_json = true;
1442 break;
1443 case 'keyPair':
1444 workflowActionVM.parameterKeyPair = true;
1445 options.parameter_json = false;
1446 break;
1447 }
1448 }
1449 }
1450 /*
1451 Method to get datails of dropdown options on response tab.
1452 */
1453 function getFieldDetails() {
1454 var parameter = _.filter(Helpers.brandDetail.field_definitions, function(fields) {
1455 return fields.custom_parameter_type == 4;
1456 });
1457 actionConfig.options = parameter;
1458 if (!(actionIndexToUpdate || actionIndexToUpdate == 0)) {
1459 workflowActionVM.configs = [Helpers.deepClone(actionConfig)];
1460 }
1461 }
1462 /*
1463 Method to populate vale of dropdown and value with respect to it while update existing Rule.
1464 @param {object} :updateOptions : data retrive from database to update.
1465 */
1466 function dropdownUpdateData(updateOptions) {
1467 var apiResponseData = updateOptions.api_response_config;
1468 workflowActionVM.configs = [];
1469 workflowActionVM.selectedOptions = {};
1470 var index = 0;
1471 _.each(apiResponseData, function(value, key) {
1472 var dropdownUpdate = Helpers.deepClone(actionConfig);
1473 dropdownUpdate.key = key;
1474 dropdownUpdate.value = value;
1475 dropdownUpdate.index = ++index;
1476 workflowActionVM.selectedOptions[key] = dropdownUpdate.index;
1477 workflowActionVM.configs.push(dropdownUpdate);
1478 });
1479 var backupConfig = Helpers.deepClone(actionConfig)
1480 backupConfig.index = ++index;
1481 workflowActionVM.configs.push(backupConfig);
1482 setTimeout(function() {
1483 $(".lw-act-workflow__select2-class").select2({
1484 placeholder: "Select any Action",
1485 width: '120px',
1486 dropdownCssClass: "lw-select__font-roboto",
1487 containerCssClass: "lw-select__border-radius-2"
1488 });
1489 $('#ltmsStudioWorkflowEditModal .select2-selection__arrow b').replaceWith('<i class="fa fa-angle-down" style="color: #708090;padding-top: 48%;font-weight: 900;"></i>');
1490 }, 0);
1491 }
1492 /*
1493 Method to prepare dropdown selected options and values to save in database (insert Mode).
1494 */
1495 function prepareDropdownData() {
1496 if (workflowActionVM.isSaveApi) {
1497 var jsonObj = {};
1498 _.each(workflowActionVM.configs, function(config) {
1499 if (config.key && config.value) {
1500 jsonObj[config.key] = config.value
1501 }
1502 })
1503 options.api_response_config = jsonObj;
1504 apiResponseFlag = false;
1505 }
1506 if (workflowActionVM.isSaveApi && _.isEmpty(jsonObj)) {
1507 apiResponseFlag = true;
1508 Helpers.smallAlertBox("Responses cannot be empty.", "Please select dropdown for responses.", "warn", 5000);
1509 }
1510 }
1511 /*
1512 Method to remove the dropdown when click on delete icon.
1513 */
1514 workflowActionVM.removeItem = function(field_id) {
1515 delete workflowActionVM.selectedOptions[field_id];
1516 workflowActionVM.configs = _.reject(workflowActionVM.configs, { "key": field_id });
1517 if (!workflowActionVM.configs.length) {
1518 workflowActionVM.configs = [Helpers.deepClone(actionConfig)];
1519 }
1520 }
1521 /*
1522 Method to add options for dropdown and remove option which already selected in previous options
1523 @ param : index : index of dropdown row .
1524 @ param : field : row key of dropdown (selcted option's value)
1525 */
1526 workflowActionVM.addMoreOption = function(index, field_id) {
1527 var values = _.values(workflowActionVM.selectedOptions);
1528 if (values.indexOf(index) < 0) {
1529 workflowActionVM.selectedOptions[field_id] = index;
1530 if (actionConfig.options.length != (workflowActionVM.configs.length)) {
1531 var nactionConfig = Helpers.deepClone(actionConfig);
1532 nactionConfig.index = workflowActionVM.configs.length + 1;
1533 workflowActionVM.configs.push(nactionConfig);
1534 setTimeout(function() {
1535 $(".lw-act-workflow__select2-class").select2({
1536 placeholder: "Select any Action",
1537 width: '120px',
1538 dropdownCssClass: "lw-select__font-roboto",
1539 containerCssClass: "lw-select__border-radius-2"
1540 });
1541 $('#ltmsStudioWorkflowEditModal .select2-selection__arrow b').replaceWith('<i class="fa fa-angle-down" style="color: #708090;padding-top: 48%;font-weight: 900;"></i>');
1542 }, 0);
1543 }
1544 } else {
1545 var mapping = Helpers.deepClone(workflowActionVM.selectedOptions);
1546 _.each(mapping, function(value, key) {
1547 if (index == value) {
1548 delete workflowActionVM.selectedOptions[key]
1549 }
1550 });
1551 workflowActionVM.selectedOptions[field_id] = index;
1552 }
1553 }
1554
1555 // Method to prepare data to update when it is in update mode and populate in repective fields on API request.
1556 function prepareUpdateData(updateOptions) {
1557 console.log("updateResponse");
1558 setTimeout(function() {
1559 $('#lwActionWorkflowBetaActionsList').val(updateOptions.action_id).trigger('change');
1560 setupDropdown("lwActionWorkflowBetaActionsList");
1561 workflowActionVM.lwActionWorkflowBetaActionsList = updateOptions.action_id;
1562 }, 0);
1563 workflowActionVM.requestOptions.parameters.json = JSON.stringify(updateOptions.options.data);
1564 workflowActionVM.requestOptions.authorisation.json = JSON.stringify(updateOptions.options.auth_params);
1565 workflowActionVM.requestOptions.requestType = updateOptions.options.method;
1566 setupDropdown("lwWorkflowActionMethod");
1567 workflowActionVM.requestOptions.urlMarginLeft = '-2px';
1568 workflowActionVM.requestOptions.requestUrl = updateOptions.options.url;
1569 // $('#lwActionWorkflowActionUrl').val(updateOptions.options.url).trigger('change');
1570 dataParamsConfig(updateOptions.options);
1571 workflowActionVM.authRequired = updateOptions.options.authentication_required;
1572 workflowActionVM.isSaveApi = updateOptions.options.should_save_api_response;
1573 if (workflowActionVM.authRequired) {
1574 authUpdateData(updateOptions.options.authorization.auth_type, updateOptions.options.authorization.body);
1575 }
1576 if (workflowActionVM.isSaveApi) {
1577 dropdownUpdateData(updateOptions.options);
1578 }
1579 }
1580 /*
1581 Method to prepare parameter's data when it is update mode and populate the data on parameter's field..
1582 @ params {object} : authData - options object which retrive from databse.
1583 */
1584 function dataParamsConfig(authData) {
1585 var authParamsData = authData.data;
1586 // selectedAction to get data.
1587 var indexParams = 0;
1588 var paramData = {};
1589 var paramsConfigData = [];
1590 for (var key in authParamsData) {
1591 var paramsData = {};
1592 paramsData.key = key;
1593 paramsData.value = authParamsData[key];
1594 paramsData.index = indexParams;
1595 indexParams++;
1596 paramsConfigData.push(paramsData);
1597 }
1598 paramData.key = "";
1599 paramData.value = "";
1600 paramData.index = indexParams;
1601 indexParams++;
1602 paramsConfigData.push(paramData);
1603 workflowActionVM.keyPairConfig = paramsConfigData;
1604 if (authData.parameter_json) {
1605 workflowActionVM.keyPairConfig = [Helpers.deepClone(paramsConfig)];
1606 setTimeout(function() {
1607 $("#lwActionWorkflowActionJsonClick").click();
1608 }, 0);
1609 } else {;;;
1610
1611
1612
1613 setTimeout(function() {
1614 $(lwActionWorkflowActionParamsJsonData).val('');
1615 $("#lwActionWorkflowActionKeyPairClick").click();
1616 }, 0);
1617 }
1618 }
1619
1620 /*
1621 Method to prepare data for parameter tab and save it in database when in insert mode.
1622 */
1623 function prepareParamsData() {
1624 if (workflowActionVM.parameterKeyPair) {
1625 var prepareData = {};
1626 for (var i = 0; i < workflowActionVM.keyPairConfig.length; i++) {
1627 if (!workflowActionVM.keyPairConfig[i].key == "" || !workflowActionVM.keyPairConfig[i].key == null) {
1628 prepareData[workflowActionVM.keyPairConfig[i].key] = workflowActionVM.keyPairConfig[i].value;
1629 }
1630 }
1631 options.data = prepareData;
1632 } else if (!workflowActionVM.parameterKeyPair) {
1633 convertToJson();
1634 }
1635 }
1636 /*
1637 Mehtod to add key - value inputbox in parameter tab dynamically when click on inputbox.
1638 */
1639 workflowActionVM.addKeyPairInput = function(index, field_key, field_value) {
1640 var keyPairBackup = {};
1641 if (index == workflowActionVM.keyPairConfig.length - 1) {
1642 keyPairBackup = Helpers.deepClone(workflowActionVM.keyPairConfig);
1643 keyPairBackup.index = workflowActionVM.keyPairConfig.length;
1644 workflowActionVM.keyPairConfig.push(keyPairBackup);
1645 } else {
1646 workflowActionVM.keyPairConfig[index].key = field_key;
1647 workflowActionVM.keyPairConfig[index].value = field_value;
1648 }
1649 }
1650 /*
1651 Method to delete the inputbox row of key -value when click on delete icon on paramter's tab.
1652 */
1653 workflowActionVM.deleteKeyPair = function(field_key, field_value, indexOfRows) {
1654 $('#lwActionWorflowKeyPair').on('click', '#delete', function(e) {
1655 e.preventDefault();
1656 $(this).parent('div').remove();
1657 });
1658 if (field_key) {
1659 workflowActionVM.keyPairConfig = _.reject(workflowActionVM.keyPairConfig, { "key": field_key });
1660 } else if (field_value) {
1661 workflowActionVM.keyPairConfig = _.reject(workflowActionVM.keyPairConfig, { "value": field_value });
1662 }
1663 if (!field_key && !field_value && ((workflowActionVM.keyPairConfig.length - 1) == indexOfRows)) {
1664 workflowActionVM.keyPairConfig = _.reject(workflowActionVM.keyPairConfig, { "index": workflowActionVM.keyPairConfig[indexOfRows].index });
1665 }
1666 }
1667
1668 this.$onChanges = initialiseOnChange;
1669 }
1670})();