<commit_before>ManageIQ.angular.app.service('mwAddDatasourceService', MwAddDatasourceService);

MwAddDatasourceService.$inject = ['$http', '$q'];

function MwAddDatasourceService($http, $q) {

   var datasources = [
    {id: 'H2', label: 'H2', name: 'H2DS', jndiName: 'java:/H2DS',
      driverName: 'h2', driverModuleName: 'com.h2database.h2', driverClass: 'org.h2.Driver',
      connectionUrl: ':mem:test;DB_CLOSE_DELAY=-1'},
    {id : 'POSTGRES', label: 'Postgres', name: 'PostgresDS', jndiName: 'java:/PostgresDS',
      driverName: 'postresql', driverModuleName: 'org.postgresql', driverClass: 'org.postgresql.Driver',
      connectionUrl: '://localhost:5432/postgresdb'},
    {id: 'MSSQL', label: 'Microsoft SQL Server', name: 'MSSQLDS', jndiName: 'java:/MSSQLDS',
      driverName: 'sqlserver', driverModuleName: 'com.microsoft',
      driverClass: 'com.microsoft.sqlserver.jdbc.SQLServerDriver',
      connectionUrl: '://localhost:1433;DatabaseName=MyDatabase'},
    {id: 'ORACLE', label: 'Oracle', name: 'OracleDS', jndiName: 'java:/OracleDS',
      driverName: 'oracle', driverModuleName: 'com.oracle', driverClass: 'oracle.jdbc.driver.OracleDriver',
      connectionUrl: ':thin:@localhost:1521:orcalesid'},
    {id: 'DB2', label: 'IBM DB2', name: 'DB2DS', jndiName: 'java:/DB2DS',
      driverName: 'ibmdb2', driverModuleName: 'com.ibm', driverClass: 'COM.ibm.db2.jdbc.app.DB2Driver',
      connectionUrl: '://db2'},
    {id: 'SYBASE', label: 'Sybase', name: 'SybaseDS', jndiName: 'java:/SybaseDB',
      driverName: 'sybase', driverModuleName: 'com.sybase', driverClass: 'com.sybase.jdbc.SybDriver',
      connectionUrl: ':Tds:localhost:5000/mydatabase?JCONNECT_VERSION=6'},
    {id: 'MYSQL', label: 'MySql', name: 'MySqlDS', jndiName: 'java:/MySqlDS',
      driverName: 'mysql', driverModuleName: 'com.mysql', driverClass: 'com.mysql.jdbc.Driver',
      connectionUrl: '://localhost:3306/mysqldb'}
  ];

  this.getDatasources = function() {
    return Object.freeze(datasources);
  };

  this.determineConnectionUrl = function (dsSelection) {
    var PREFIX = 'jdbc:';
    var driverName = dsSelection.driverName;

    return PREFIX + driverName + dsSelection.connectionUrl;
  };

  this.sendAddDatasource = function(payload) {
    var errorMsg = _('Error running add_datasource on this server.');
    var deferred = $q.defer();

    $http.post('/middleware_server/add_datasource', angular.toJson(payload))
      .then(
        function (response) { // success
          var data = response.data;

          if (data.status === 'ok') {
            deferred.resolve(data.msg);
          } else {
            deferred.reject(data.msg);
          }
        })
      .catch(function () {
        deferred.reject(errorMsg);
      })
      .finally(function () {
        // we should already be resolved and promises can only fire once
        deferred.resolve(data.msg);
      });
    return deferred.promise;

  }
}

<commit_msg>Adding MariaDB datasource option to the wizard.<commit_after>ManageIQ.angular.app.service('mwAddDatasourceService', MwAddDatasourceService);

MwAddDatasourceService.$inject = ['$http', '$q'];

function MwAddDatasourceService($http, $q) {

   var datasources = [
    {id: 'H2', label: 'H2', name: 'H2DS', jndiName: 'java:/H2DS',
      driverName: 'h2', driverModuleName: 'com.h2database.h2', driverClass: 'org.h2.Driver',
      connectionUrl: ':mem:test;DB_CLOSE_DELAY=-1'},
    {id : 'POSTGRES', label: 'Postgres', name: 'PostgresDS', jndiName: 'java:/PostgresDS',
      driverName: 'postresql', driverModuleName: 'org.postgresql', driverClass: 'org.postgresql.Driver',
      connectionUrl: '://localhost:5432/postgresdb'},
    {id: 'MSSQL', label: 'Microsoft SQL Server', name: 'MSSQLDS', jndiName: 'java:/MSSQLDS',
      driverName: 'sqlserver', driverModuleName: 'com.microsoft',
      driverClass: 'com.microsoft.sqlserver.jdbc.SQLServerDriver',
      connectionUrl: '://localhost:1433;DatabaseName=MyDatabase'},
    {id: 'ORACLE', label: 'Oracle', name: 'OracleDS', jndiName: 'java:/OracleDS',
      driverName: 'oracle', driverModuleName: 'com.oracle', driverClass: 'oracle.jdbc.driver.OracleDriver',
      connectionUrl: ':thin:@localhost:1521:oraclesid'},
    {id: 'DB2', label: 'IBM DB2', name: 'DB2DS', jndiName: 'java:/DB2DS',
      driverName: 'ibmdb2', driverModuleName: 'com.ibm', driverClass: 'COM.ibm.db2.jdbc.app.DB2Driver',
      connectionUrl: '://db2'},
    {id: 'SYBASE', label: 'Sybase', name: 'SybaseDS', jndiName: 'java:/SybaseDB',
      driverName: 'sybase', driverModuleName: 'com.sybase', driverClass: 'com.sybase.jdbc.SybDriver',
      connectionUrl: ':Tds:localhost:5000/mydatabase?JCONNECT_VERSION=6'},
     {id: 'MARIADB', label: 'MariaDB', name: 'MariaDBDS', jndiName: 'java:/MariaDBDS',
       driverName: 'mariadb', driverModuleName: 'org.mariadb', driverClass: 'org.mariadb.jdbc.Driver',
       connectionUrl: '://localhost:3306/db_name'},
    {id: 'MYSQL', label: 'MySql', name: 'MySqlDS', jndiName: 'java:/MySqlDS',
      driverName: 'mysql', driverModuleName: 'com.mysql', driverClass: 'com.mysql.jdbc.Driver',
      connectionUrl: '://localhost:3306/db_name'}
  ];

  this.getDatasources = function() {
    return Object.freeze(datasources);
  };

  this.determineConnectionUrl = function (dsSelection) {
    var PREFIX = 'jdbc:';
    var driverName = dsSelection.driverName;

    return PREFIX + driverName + dsSelection.connectionUrl;
  };

  this.sendAddDatasource = function(payload) {
    var errorMsg = _('Error running add_datasource on this server.');
    var deferred = $q.defer();

    $http.post('/middleware_server/add_datasource', angular.toJson(payload))
      .then(
        function (response) { // success
          var data = response.data;

          if (data.status === 'ok') {
            deferred.resolve(data.msg);
          } else {
            deferred.reject(data.msg);
          }
        })
      .catch(function () {
        deferred.reject(errorMsg);
      })
      .finally(function () {
        // we should already be resolved and promises can only fire once
        deferred.resolve(data.msg);
      });
    return deferred.promise;

  }
}

<|endoftext|>


<commit_before>/**
 * Adding queues, when creating queues from the user interface
 */
function addQueue(createdFrom) {
    var queue = document.getElementById("queue");

    var error = "";

    if ("" == queue.value) {
        error = "Queue name cannot be empty.\n";
    } else if (!isValidQueueName(queue.value)) {
        error = "Queue name cannot contain any of following symbols ~!@#;%^*()+={}|\<>\"'/, and space \n";
    } else if (isContainTmpPrefix(queue.value)) {
        error = "Queue name cannot start with tmp_ prefix.\n";
    }
    if (error != "") {
        CARBON.showErrorDialog(error);
        return;
    }
    addQueueAndAssignPermissions(queue.value, createdFrom);
}

/**
 * Validating queue names, when creating queues from user interface
 */
function isValidQueueName(queueName){
    return !/[~!@#;%^*()+={}|\<>"'/,\s]/g.test(queueName);
}

function isContainTmpPrefix(queueName) {
    return queueName.startsWith("tmp_");
}

function addQueueAndAssignPermissions(queue, createdFrom) {
    var callback =
    {
        success:function(o) {
            if (o.responseText !== undefined) {
                if (o.responseText.indexOf("Error") > -1) {
                    CARBON.showErrorDialog("" + o.responseText, function() {
                        location.href = "../queues/queue_details.jsp"
                    });
                } else {
                    CARBON.showInfoDialog("" + o.responseText, function() {
                        location.href = "../queues/queue_details.jsp"
                    });
                }
            }
        },
        failure:function(o) {
            if (o.responseText !== undefined) {
                alert("Error " + o.status + "\n Following is the message from the server.\n" + o.responseText);
            }
        }
    };
    var request = YAHOO.util.Connect.asyncRequest('POST', "add_queue_and_assign_role_permissions_ajaxprocessor.jsp", callback, "queue=" + encodeURIComponent(queue) + "&type=input");
}

function updatePermissions() {
    var permissionTable = document.getElementById("permissionsTable");
    var rowCount = permissionTable.rows.length;
    var parameters = "";
    for (var i = 1; i < rowCount; i++) {
        /* since there can be special characters in roleNames we need to encode them before send the parameters to backend*/
        var roleName = encodeURIComponent(permissionTable.rows[i].cells[0].innerHTML.replace(/^\s+|\s+$/g, ""));
        var consumeAllowed = permissionTable.rows[i].cells[1].getElementsByTagName("input")[0].checked;
        var publishAllowed = permissionTable.rows[i].cells[2].getElementsByTagName("input")[0].checked;
        if (i == 1) {
            parameters = roleName + "," + consumeAllowed + "," + publishAllowed + ",";
        } else {
            parameters = parameters + roleName + "," + consumeAllowed + "," + publishAllowed + ",";
        }
    }

    var callback =
    {
        success:function(o) {
            if (o.responseText !== undefined) {
                if (o.responseText.indexOf("Error") > -1) {
                    CARBON.showErrorDialog("" + o.responseText, function() {
                        location.href = "../queues/queue_details.jsp"
                    });
                } else {
                    CARBON.showInfoDialog("" + o.responseText, function() {
                        location.href = "../queues/queue_details.jsp"
                    });
                }

            }
        },
        failure:function(o) {
            if (o.responseText !== undefined) {
                alert("Error " + o.status + "\n Following is the message from the server.\n" + o.responseText);
            }
        }
    };
    var request = YAHOO.util.Connect.asyncRequest('POST', "update_queue_role_permissions_ajaxprocessor.jsp", callback, "permissions=" + parameters + "&type=input");
}

function showManageQueueWindow(queueName) {
    var callback =
    {
        success:function(o) {
            if (o.responseText !== undefined) {
                location.href = "../queues/queue_manage.jsp";
            }
        },
        failure:function(o) {
            if (o.responseText !== undefined) {
                alert("Error " + o.status + "\n Following is the message from the server.\n" + o.responseText);
            }
        }
    };
    var request = YAHOO.util.Connect.asyncRequest('POST', "load_queue_details_from_bEnd_ajaxprocessor.jsp", callback, "queueName=" + encodeURIComponent(queueName) + "&type=input");
}

function doDelete(queueName) {

    CARBON.showConfirmationDialog("Are you sure you want to delete " + queueName + " ?", function() {
        $.ajax({
            url: '../queues/queue_delete_ajaxprocessor.jsp?nameOfQueue=' + queueName,
            async: true,
            type: "POST",
            success: function(o) {
                if (o.indexOf("Error") > -1) {
                    CARBON.showErrorDialog("" + o, function() {
                        location.href = 'queue_details.jsp';
                    });
                } else {
                    CARBON.showInfoDialog('Queue ' + queueName + ' successfully deleted.', function() {
                        location.href = 'queue_details.jsp';
                    });
                }
            },
            failure: function(o) {
                if (o.responseText !== undefined) {
                    alert("Error " + o.status + "\n Following is the message from the server.\n" + o.responseText);
                }
            }
        });
    });

}

function doPurge(queueName) {

    CARBON.showConfirmationDialog("Are you sure you want to purge " + queueName + " ?", function() {
        $.ajax({
            url: '../queues/queue_purge_ajaxprocessor.jsp?nameOfQueue=' + queueName,
            async: true,
            type: "POST",
            success: function(o) {
                if (o.indexOf("Error") > -1) {
                    CARBON.showErrorDialog('<%=e.getFaultMessage().getBrokerManagerAdminException().getErrorMessage()%>', function() {
                        location.href = 'queue_details.jsp';
                    });
                } else {
                    CARBON.showInfoDialog('Queue ' + queueName + ' successfully purged.', function() {
                        location.href = 'queue_details.jsp';
                    });
                }
            },
            failure: function(o) {
                if (o.responseText !== undefined) {
                    alert("Error " + o.status + "\n Following is the message from the server.\n" + o.responseText);
                }
            }
        });
    });

}

 function doDeleteDLC(nameOfQueue) {
	 var checkedValues = getCheckedValues();
	 if(checkedValues == null || checkedValues == "" ){
		  var msg = org_wso2_carbon_andes_ui_jsi18n["info.zero.items.selected"]+ " " + org_wso2_carbon_andes_ui_jsi18n["delete"];
		  CARBON.showInfoDialog(msg);
		  return;
	 }
	 CARBON.showConfirmationDialog(org_wso2_carbon_andes_ui_jsi18n["confirmation.delete"], function(){
		 $.ajax({
	 				url:'../queues/dlc_message_delete_ajaxprocessor.jsp?nameOfQueue=' + nameOfQueue,
	 				async:true,
	 				dataType:"html",
	 				data : { msgList : checkedValues },
	 				type: "POST",
	 				success: function() {
       	                	CARBON.showInfoDialog(org_wso2_carbon_andes_ui_jsi18n["info.successful.delete"], function(){
       	                		location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
	                		 });

       	                },

       	             failure: function(transport) {
       	                 CARBON.showErrorDialog(trim(transport.responseText),function(){
       	                	location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
       	                	 return;
	                	      });
       	                }
       	            });
			 });
}

 function deRestoreMessages(nameOfQueue){
	 var checkedValues = getCheckedValues();
	 if(checkedValues == null || checkedValues == ""){
		  var msg = org_wso2_carbon_andes_ui_jsi18n["info.zero.items.selected"]+ " " + org_wso2_carbon_andes_ui_jsi18n["restore"];
		  CARBON.showInfoDialog(msg);
		  return;
	 }
	 CARBON.showConfirmationDialog(org_wso2_carbon_andes_ui_jsi18n["confirmation.restore"], function(){
		 $.ajax({
	 				url:'../queues/dlc_message_restore_ajaxprocessor.jsp?nameOfQueue=' + nameOfQueue,
	 				async:true,
	 				dataType:"html",
	 				data : { msgList : checkedValues },
	 				type: "POST",
	 				success: function(data) {
       	                	data = data.trim();
       	                	var unavailableMessageCount = parseFloat(data);
       	                	if(unavailableMessageCount > 0) {
                                if(unavailableMessageCount == checkedValues.split(",").length) {
                                    CARBON.showInfoDialog(org_wso2_carbon_andes_ui_jsi18n["info.fail.restore"],
                                    function(){
                                        location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                     });
                                }else {
                                     CARBON.showInfoDialog(unavailableMessageCount + " " +org_wso2_carbon_andes_ui_jsi18n[
                                     "info.partial.successful.restore"],function(){
                                        location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                     });
                                }
       	                	}else {
       	                	    CARBON.showInfoDialog(org_wso2_carbon_andes_ui_jsi18n["info.successful.restore"], function(){
                                       	location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                });
       	                	}
       	                },

       	             failure: function(transport) {
       	                 CARBON.showErrorDialog(trim(transport.responseText),function(){
       	                	location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
       	                	 return;
	                	      });
       	                }
       	            });
			 });
 }

function doReRouteMessages(nameOfQueue) {
    var checkedValues = getCheckedValues();
    if (checkedValues == null || checkedValues == "") {
        var msg = org_wso2_carbon_andes_ui_jsi18n["info.zero.items.selected"] + " " + org_wso2_carbon_andes_ui_jsi18n["reRoute"];
        CARBON.showInfoDialog(msg);
        return;
    }

    jQuery.ajax({
        url: "../queues/queue_list_retrieve_ajaxprocessor.jsp?nameOfQueue=" + nameOfQueue,
        type: "POST",
        success: function (data) {
            //Let's say data is something like the following string
            // data = "queue1#queue2";
            //data = data.split("#");
            data = jQuery.trim(data);
            data  = data.split("#");

            var selectElement = '<select id="allQueues" style="font-size: 14px; display: block; margin: 0 auto; margin-top: 10px;">';
            for (var i = 0; i < data.length; i++) {
                selectElement += '<option value="' + data[i] + '">' + data[i] + '</option>';
            }
            selectElement += '</select>';

            CARBON.showPopupDialog("", "Select a queue to route messages ", 100, true,
                function () {
                    var selectedQueue = jQuery('#allQueues').val();

                    CARBON.showConfirmationDialog(org_wso2_carbon_andes_ui_jsi18n["confirmation.reRoute"], function () {
                        $.ajax({
                            url: '../queues/dlc_message_reroute_ajaxprocessor.jsp',
                            async: true,
                            dataType: "html",
                            data : {    nameOfQueue : nameOfQueue,
                                        newQueueName : selectedQueue,
                                        msgList : checkedValues },
                            type: "POST",
                            success: function (data) {
                                data = data.trim();
                                var unavailableMessageCount = parseFloat(data);
                                if(unavailableMessageCount > 0) {
                                       if(unavailableMessageCount == checkedValues.split(",").length) {
                                            CARBON.showInfoDialog(org_wso2_carbon_andes_ui_jsi18n["info.fail.reRoute"],
                                            function(){
                                                location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                             });
                                       }else {
                                            CARBON.showInfoDialog(unavailableMessageCount + " "
                                            + org_wso2_carbon_andes_ui_jsi18n["info.partial.successful.reRoute"],
                                            function(){
                                                location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                            });
                                       }
                                }else {
                                    CARBON.showInfoDialog(org_wso2_carbon_andes_ui_jsi18n["info.successful.reRoute"],
                                    function(){
                                        location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                    });
                                }
                            },

                            failure: function (transport) {
                                CARBON.showErrorDialog(trim(transport.responseText), function () {
                                    location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                    return;
                                });
                            }
                        });
                    });

                } , 300
            );
            $("#popupDialog").after(selectElement);
        },
        failure: function(transport) {
            CARBON.showErrorDialog(trim(transport.responseText),function(){
                location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                return;
            });
        }
    });
}

 function getCheckedValues(){
	 	return $('input[name="checkbox"]:checked').map(
	 			function() {
	 				return this.value;
	 				}).get().join(',');
 }

function validateForm(){
    var msg_count = document.getElementById("num_of_msgs");
    var error = "";

    if(msg_count.value == ""){
        error = "Number of messages field cannot be empty. \n";
    }

    if (error != "") {
        CARBON.showErrorDialog(error,function(){
            location.href = "../queues/queue_message_sender.jsp";
        },function(){
            location.href = "../queues/queue_message_sender.jsp";
        });
    }
}

/**
 * Removes the 'first' and 'last' links in pagination.
 */
function removeFirstAndLastPaginations(){
    $('#workArea').find('table:not([class]) a').each(function () {
        $(this).text($(this).text().replace(/<<first/g, ""));
    });
    $('#workArea').find('table:not([class]) a').each(function () {
        $(this).text($(this).text().replace(/last.>>/g, ""));
    });
    $('#workArea').find('table:not([class]) span').each(function () {
        $(this).text($(this).text().replace(/last>>/g, ""));
    });
    $('#workArea').find('table:not([class]) span').each(function () {
        $(this).text($(this).text().replace(/<<.first/g, ""));
    });
}

/**
 * Gets all the queues in MB.
 * @returns An array of queue names.
 */
function getAllQueues() {
    var queueList = {};
    jQuery.ajax({
        url: "../queues/queue_list_retrieve_ajaxprocessor.jsp?nameOfQueue=" + nameOfQueue,
        type: "POST",
        async: false,
        success: function (data) {
            data = jQuery.trim(data);
            queueList = data.split("#");
        },
        failure: function (transport) {
            CARBON.showErrorDialog(trim(transport.responseText), function () {
                location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                return queueList;
            });
        }
    });

    return queueList;
}
<commit_msg>Send nameOfQueue through post method instead of get<commit_after>/**
 * Adding queues, when creating queues from the user interface
 */
function addQueue(createdFrom) {
    var queue = document.getElementById("queue");

    var error = "";

    if ("" == queue.value) {
        error = "Queue name cannot be empty.\n";
    } else if (!isValidQueueName(queue.value)) {
        error = "Queue name cannot contain any of following symbols ~!@#;%^*()+={}|\<>\"'/, and space \n";
    } else if (isContainTmpPrefix(queue.value)) {
        error = "Queue name cannot start with tmp_ prefix.\n";
    }
    if (error != "") {
        CARBON.showErrorDialog(error);
        return;
    }
    addQueueAndAssignPermissions(queue.value, createdFrom);
}

/**
 * Validating queue names, when creating queues from user interface
 */
function isValidQueueName(queueName){
    return !/[~!@#;%^*()+={}|\<>"'/,\s]/g.test(queueName);
}

function isContainTmpPrefix(queueName) {
    return queueName.startsWith("tmp_");
}

function addQueueAndAssignPermissions(queue, createdFrom) {
    var callback =
    {
        success:function(o) {
            if (o.responseText !== undefined) {
                if (o.responseText.indexOf("Error") > -1) {
                    CARBON.showErrorDialog("" + o.responseText, function() {
                        location.href = "../queues/queue_details.jsp"
                    });
                } else {
                    CARBON.showInfoDialog("" + o.responseText, function() {
                        location.href = "../queues/queue_details.jsp"
                    });
                }
            }
        },
        failure:function(o) {
            if (o.responseText !== undefined) {
                alert("Error " + o.status + "\n Following is the message from the server.\n" + o.responseText);
            }
        }
    };
    var request = YAHOO.util.Connect.asyncRequest('POST', "add_queue_and_assign_role_permissions_ajaxprocessor.jsp", callback, "queue=" + encodeURIComponent(queue) + "&type=input");
}

function updatePermissions() {
    var permissionTable = document.getElementById("permissionsTable");
    var rowCount = permissionTable.rows.length;
    var parameters = "";
    for (var i = 1; i < rowCount; i++) {
        /* since there can be special characters in roleNames we need to encode them before send the parameters to backend*/
        var roleName = encodeURIComponent(permissionTable.rows[i].cells[0].innerHTML.replace(/^\s+|\s+$/g, ""));
        var consumeAllowed = permissionTable.rows[i].cells[1].getElementsByTagName("input")[0].checked;
        var publishAllowed = permissionTable.rows[i].cells[2].getElementsByTagName("input")[0].checked;
        if (i == 1) {
            parameters = roleName + "," + consumeAllowed + "," + publishAllowed + ",";
        } else {
            parameters = parameters + roleName + "," + consumeAllowed + "," + publishAllowed + ",";
        }
    }

    var callback =
    {
        success:function(o) {
            if (o.responseText !== undefined) {
                if (o.responseText.indexOf("Error") > -1) {
                    CARBON.showErrorDialog("" + o.responseText, function() {
                        location.href = "../queues/queue_details.jsp"
                    });
                } else {
                    CARBON.showInfoDialog("" + o.responseText, function() {
                        location.href = "../queues/queue_details.jsp"
                    });
                }

            }
        },
        failure:function(o) {
            if (o.responseText !== undefined) {
                alert("Error " + o.status + "\n Following is the message from the server.\n" + o.responseText);
            }
        }
    };
    var request = YAHOO.util.Connect.asyncRequest('POST', "update_queue_role_permissions_ajaxprocessor.jsp", callback, "permissions=" + parameters + "&type=input");
}

function showManageQueueWindow(queueName) {
    var callback =
    {
        success:function(o) {
            if (o.responseText !== undefined) {
                location.href = "../queues/queue_manage.jsp";
            }
        },
        failure:function(o) {
            if (o.responseText !== undefined) {
                alert("Error " + o.status + "\n Following is the message from the server.\n" + o.responseText);
            }
        }
    };
    var request = YAHOO.util.Connect.asyncRequest('POST', "load_queue_details_from_bEnd_ajaxprocessor.jsp", callback, "queueName=" + encodeURIComponent(queueName) + "&type=input");
}

function doDelete(queueName) {

    CARBON.showConfirmationDialog("Are you sure you want to delete " + queueName + " ?", function() {
        $.ajax({
            url: '../queues/queue_delete_ajaxprocessor.jsp?nameOfQueue=' + queueName,
            async: true,
            type: "POST",
            success: function(o) {
                if (o.indexOf("Error") > -1) {
                    CARBON.showErrorDialog("" + o, function() {
                        location.href = 'queue_details.jsp';
                    });
                } else {
                    CARBON.showInfoDialog('Queue ' + queueName + ' successfully deleted.', function() {
                        location.href = 'queue_details.jsp';
                    });
                }
            },
            failure: function(o) {
                if (o.responseText !== undefined) {
                    alert("Error " + o.status + "\n Following is the message from the server.\n" + o.responseText);
                }
            }
        });
    });

}

function doPurge(queueName) {

    CARBON.showConfirmationDialog("Are you sure you want to purge " + queueName + " ?", function() {
        $.ajax({
            url: '../queues/queue_purge_ajaxprocessor.jsp?nameOfQueue=' + queueName,
            async: true,
            type: "POST",
            success: function(o) {
                if (o.indexOf("Error") > -1) {
                    CARBON.showErrorDialog('<%=e.getFaultMessage().getBrokerManagerAdminException().getErrorMessage()%>', function() {
                        location.href = 'queue_details.jsp';
                    });
                } else {
                    CARBON.showInfoDialog('Queue ' + queueName + ' successfully purged.', function() {
                        location.href = 'queue_details.jsp';
                    });
                }
            },
            failure: function(o) {
                if (o.responseText !== undefined) {
                    alert("Error " + o.status + "\n Following is the message from the server.\n" + o.responseText);
                }
            }
        });
    });

}

 function doDeleteDLC(nameOfQueue) {
	 var checkedValues = getCheckedValues();
	 if(checkedValues == null || checkedValues == "" ){
		  var msg = org_wso2_carbon_andes_ui_jsi18n["info.zero.items.selected"]+ " " + org_wso2_carbon_andes_ui_jsi18n["delete"];
		  CARBON.showInfoDialog(msg);
		  return;
	 }
	 CARBON.showConfirmationDialog(org_wso2_carbon_andes_ui_jsi18n["confirmation.delete"], function(){
		 $.ajax({
	 				url:'../queues/dlc_message_delete_ajaxprocessor.jsp',
	 				async:true,
	 				dataType:"html",
	 				data : { msgList : checkedValues, nameOfQueue : nameOfQueue },
	 				type: "POST",
	 				success: function() {
       	                	CARBON.showInfoDialog(org_wso2_carbon_andes_ui_jsi18n["info.successful.delete"], function(){
       	                		location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
	                		 });

       	                },

       	             failure: function(transport) {
       	                 CARBON.showErrorDialog(trim(transport.responseText),function(){
       	                	location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
       	                	 return;
	                	      });
       	                }
       	            });
			 });
}

 function deRestoreMessages(nameOfQueue){
	 var checkedValues = getCheckedValues();
	 if(checkedValues == null || checkedValues == ""){
		  var msg = org_wso2_carbon_andes_ui_jsi18n["info.zero.items.selected"]+ " " + org_wso2_carbon_andes_ui_jsi18n["restore"];
		  CARBON.showInfoDialog(msg);
		  return;
	 }
	 CARBON.showConfirmationDialog(org_wso2_carbon_andes_ui_jsi18n["confirmation.restore"], function(){
		 $.ajax({
	 				url:'../queues/dlc_message_restore_ajaxprocessor.jsp',
	 				async:true,
	 				dataType:"html",
	 				data : { msgList : checkedValues, nameOfQueue : nameOfQueue },
	 				type: "POST",
	 				success: function(data) {
       	                	data = data.trim();
       	                	var unavailableMessageCount = parseFloat(data);
       	                	if(unavailableMessageCount > 0) {
                                if(unavailableMessageCount == checkedValues.split(",").length) {
                                    CARBON.showInfoDialog(org_wso2_carbon_andes_ui_jsi18n["info.fail.restore"],
                                    function(){
                                        location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                     });
                                }else {
                                     CARBON.showInfoDialog(unavailableMessageCount + " " +org_wso2_carbon_andes_ui_jsi18n[
                                     "info.partial.successful.restore"],function(){
                                        location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                     });
                                }
       	                	}else {
       	                	    CARBON.showInfoDialog(org_wso2_carbon_andes_ui_jsi18n["info.successful.restore"], function(){
                                       	location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                });
       	                	}
       	                },

       	             failure: function(transport) {
       	                 CARBON.showErrorDialog(trim(transport.responseText),function(){
       	                	location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
       	                	 return;
	                	      });
       	                }
       	            });
			 });
 }

function doReRouteMessages(nameOfQueue) {
    var checkedValues = getCheckedValues();
    if (checkedValues == null || checkedValues == "") {
        var msg = org_wso2_carbon_andes_ui_jsi18n["info.zero.items.selected"] + " " + org_wso2_carbon_andes_ui_jsi18n["reRoute"];
        CARBON.showInfoDialog(msg);
        return;
    }

    jQuery.ajax({
        url: "../queues/queue_list_retrieve_ajaxprocessor.jsp",
        data : { nameOfQueue : nameOfQueue },
        type: "POST",
        success: function (data) {
            //Let's say data is something like the following string
            // data = "queue1#queue2";
            //data = data.split("#");
            data = jQuery.trim(data);
            data  = data.split("#");

            var selectElement = '<select id="allQueues" style="font-size: 14px; display: block; margin: 0 auto; margin-top: 10px;">';
            for (var i = 0; i < data.length; i++) {
                selectElement += '<option value="' + data[i] + '">' + data[i] + '</option>';
            }
            selectElement += '</select>';

            CARBON.showPopupDialog("", "Select a queue to route messages ", 100, true,
                function () {
                    var selectedQueue = jQuery('#allQueues').val();

                    CARBON.showConfirmationDialog(org_wso2_carbon_andes_ui_jsi18n["confirmation.reRoute"], function () {
                        $.ajax({
                            url: '../queues/dlc_message_reroute_ajaxprocessor.jsp',
                            async: true,
                            dataType: "html",
                            data : {    nameOfQueue : nameOfQueue,
                                        newQueueName : selectedQueue,
                                        msgList : checkedValues },
                            type: "POST",
                            success: function (data) {
                                data = data.trim();
                                var unavailableMessageCount = parseFloat(data);
                                if(unavailableMessageCount > 0) {
                                       if(unavailableMessageCount == checkedValues.split(",").length) {
                                            CARBON.showInfoDialog(org_wso2_carbon_andes_ui_jsi18n["info.fail.reRoute"],
                                            function(){
                                                location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                             });
                                       }else {
                                            CARBON.showInfoDialog(unavailableMessageCount + " "
                                            + org_wso2_carbon_andes_ui_jsi18n["info.partial.successful.reRoute"],
                                            function(){
                                                location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                            });
                                       }
                                }else {
                                    CARBON.showInfoDialog(org_wso2_carbon_andes_ui_jsi18n["info.successful.reRoute"],
                                    function(){
                                        location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                    });
                                }
                            },

                            failure: function (transport) {
                                CARBON.showErrorDialog(trim(transport.responseText), function () {
                                    location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                                    return;
                                });
                            }
                        });
                    });

                } , 300
            );
            $("#popupDialog").after(selectElement);
        },
        failure: function(transport) {
            CARBON.showErrorDialog(trim(transport.responseText),function(){
                location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                return;
            });
        }
    });
}

 function getCheckedValues(){
	 	return $('input[name="checkbox"]:checked').map(
	 			function() {
	 				return this.value;
	 				}).get().join(',');
 }

function validateForm(){
    var msg_count = document.getElementById("num_of_msgs");
    var error = "";

    if(msg_count.value == ""){
        error = "Number of messages field cannot be empty. \n";
    }

    if (error != "") {
        CARBON.showErrorDialog(error,function(){
            location.href = "../queues/queue_message_sender.jsp";
        },function(){
            location.href = "../queues/queue_message_sender.jsp";
        });
    }
}

/**
 * Removes the 'first' and 'last' links in pagination.
 */
function removeFirstAndLastPaginations(){
    $('#workArea').find('table:not([class]) a').each(function () {
        $(this).text($(this).text().replace(/<<first/g, ""));
    });
    $('#workArea').find('table:not([class]) a').each(function () {
        $(this).text($(this).text().replace(/last.>>/g, ""));
    });
    $('#workArea').find('table:not([class]) span').each(function () {
        $(this).text($(this).text().replace(/last>>/g, ""));
    });
    $('#workArea').find('table:not([class]) span').each(function () {
        $(this).text($(this).text().replace(/<<.first/g, ""));
    });
}

/**
 * Gets all the queues in MB.
 * @returns An array of queue names.
 */
function getAllQueues() {
    var queueList = {};
    jQuery.ajax({
        url: "../queues/queue_list_retrieve_ajaxprocessor.jsp?nameOfQueue=" + nameOfQueue,
        type: "POST",
        async: false,
        success: function (data) {
            data = jQuery.trim(data);
            queueList = data.split("#");
        },
        failure: function (transport) {
            CARBON.showErrorDialog(trim(transport.responseText), function () {
                location.href = "../queues/dlc_messages_list.jsp?nameOfQueue=" + nameOfQueue;
                return queueList;
            });
        }
    });

    return queueList;
}
<|endoftext|>


<commit_before>import './condition_panel_watcher_edit.less';
import template from './condition_panel_watcher_edit.html';

import moment from 'moment';
import {size, has, pick, includes} from 'lodash';

class Chart {
  constructor({name = 'all docs', enabled = true, message = '', xAxis = [], yAxis = [[], []], options} = {}) {
    this.name = name;
    this.enabled = enabled;
    this.message = message;
    this.xAxis = xAxis;
    this.yAxis = yAxis;
    this.options = options || {
      title: {
        display: false,
        text: 'Historical results chart',
      },
    };
  }
}

class ConditionPanelWatcherEdit {
  constructor($http, $log, $scope, watcherEditorChartService) {
    this.$http = $http;
    this.$log = $log;
    this.$scope = $scope;
    this.watcherEditorChartService = watcherEditorChartService;

    this.messages = {
      nodata: 'the selected condition does not return any data',
    };

    this.progress = {
      running: false,
      message: 'LOADING DATA ...',
    };

    this.charts = [];

    this.chartQueryParams = {
      index: ['watcher_aggs_test'],
      // index: watcher._source.search.request.index,
      queryType: 'count',
      over: { type: 'all docs' },
      last: { n: 15, unit: 'minutes' },
      interval: { n: 1, unit: 'minutes' },
      threshold: { n: 10, direction: 'above' },
    };

    this.allDocFields = ['animal', 'random'];

    this.condition = {
      type: {
        handleSelect: (type) => {
          this.$log.debug('select type:', type);
          this._updateChartQueryParamsQueryType(type);
        },
      },
      field: {
        enabled: false,
        handleSelect: (field) => {
          this.$log.debug('select field:', field);
          this._updateChartQueryParamsField(field);
        },
      },
      over: {
        handleSelect: (over) => {
          this.$log.debug('select over:', over);
          if (over.type !== 'top' || !!over.n && !!over.field.length) {
            this._updateChartQueryParamsOver(over);
          }
        },
      },
      threshold: {
        handleSelect: (direction, n) => {
          this.$log.debug('select threshold:', direction, n);
          this._updateChartQueryParamsThreshold(n, direction);
          this._drawChartThreshold(this.activeChart, this.chartQueryParams.threshold.n);
        },
      },
      last: {
        handleSelect: (unit, n) => {
          this.$log.debug('select last:', unit, n);
          this._updateChartQueryParamsLast(n, unit);
        },
      },
    };

    this.$scope.$watch('conditionPanelWatcherEdit.watcher._source.trigger.schedule.later', () => {
      this._updateChartQueryParamsInterval(this.watcher._source.trigger.schedule.later);
    });

    this.$scope.$watch('conditionPanelWatcherEdit.watcher._source.input.search.request.index', () => {
      // this.chartQueryParams.index = this.watcher._source.input.search.request.index;
    });

    this.$scope.$watch('conditionPanelWatcherEdit.chartQueryParams', async () => {
      try {
        await this._fetchChartData();
      } catch (err) {
        this.$log.error(['ConditionPanelWatcherEdit'], `fail: ${err.message}`);
      }
    }, true);
  }

  get activeChart() {
    return this.charts.find((chart) => chart.enabled === true);
  }

  get isAnyActiveChart() {
    return !!this.charts.find((chart) => chart.enabled === true);
  }

  get areMultipleCharts() {
    return this.charts.length > 1;
  }

  _activeChartIndex() {
    return this.charts.findIndex((e) => e.enabled === true);
  }

  _offChartBatch(indicesToExclude = []) {
    this.charts.forEach((chart, i) => {
      if (!indicesToExclude.includes(i)) {
        this._offChart(chart);
      }
    });
  }

  switchToLeftChart() {
    let index = this._activeChartIndex();
    if (index > 0) {
      index -= 1;
      this._offChartBatch([index]);
      this._onChart(this.charts[index]);
    }
  }

  switchToRightChart() {
    let index = this._activeChartIndex();
    if (index < size(this.charts) - 1) {
      index += 1;
      this._offChartBatch([index]);
      this._onChart(this.charts[index]);
    }
  }

  /*
  * Fetch chart data and fill its X and Y axises
  */
  async _fetchChartData() {
    this._toggleConditionBuilderMetricAggOverField();
    const params = pick(this.chartQueryParams, ['index', 'over', 'last', 'interval', 'field', 'threshold']);

    if (this.chartQueryParams.queryType === 'average') {
      params.metricAggType = 'average';
      try {
        await this._queryMetricAgg(params);
        return;
      } catch (err) {
        throw new Error(`average: ${err.message}`);
      }
    }

    if (this.chartQueryParams.queryType === 'sum') {
      params.metricAggType = 'sum';
      try {
        await this._queryMetricAgg(params);
        return;
      } catch (err) {
        throw new Error(`sum: ${err.message}`);
      }
    }

    if (this.chartQueryParams.queryType === 'min') {
      params.metricAggType = 'min';
      try {
        await this._queryMetricAgg(params);
        return;
      } catch (err) {
        throw new Error(`min: ${err.message}`);
      }
    }

    if (this.chartQueryParams.queryType === 'max') {
      params.metricAggType = 'max';
      try {
        await this._queryMetricAgg(params);
        return;
      } catch (err) {
        throw new Error(`max: ${err.message}`);
      }
    }

    try {
      await this._queryCount(params);
    } catch (err) {
      throw new Error(`count: ${err.message}`);
    }
    return null;
  }

  _toggleConditionBuilderMetricAggOverField() {
    if (this.chartQueryParams.queryType === 'count') {
      this.condition.field.enabled = false;
    } else {
      this.condition.field.enabled = true;
    }
  }

  /*
  * @param {integer} n on y axis
  */
  _drawChartThreshold(chart, n) {
    const len = chart.yAxis[0].length;
    chart.yAxis[1] = Array.apply(null, Array(len)).map(Number.prototype.valueOf, n);
  }

  /*
  * @param {string} interval of time: every 1 minutes
  */
  _scheduleModeEveryIsUsed(interval) {
    if (interval.match(/every \d+ (seconds|minutes|hours|days|months|years)/g)) {
      return true;
    }
    return false;
  }

  /*
  * @param {string} interval of time: every 1 minutes
  */
  _updateChartQueryParamsInterval(interval) {
    if (this._scheduleModeEveryIsUsed(interval)) {
      interval = interval.split(' ');
      this.chartQueryParams.interval = {
        n: +interval[1],
        unit: interval[2],
      };
    }
  }

  _updateChartQueryParamsOver(over) {
    this.chartQueryParams.over = pick(over, ['type', 'n', 'field']);
  }

  _updateChartQueryParamsField(field) {
    this.chartQueryParams.field = field;
  }

  _updateChartQueryParamsQueryType(type) {
    this.chartQueryParams.queryType = type;
  }

  _updateChartQueryParamsLast(n, unit) {
    this.chartQueryParams.last = { unit, n: +n };
  }

  _updateChartQueryParamsThreshold(n, direction) {
    this.chartQueryParams.threshold = { direction, n: +n };
  }

  _isDateAggData(esResp) {
    return has(esResp, 'data.aggregations.dateAgg.buckets') && !!esResp.data.aggregations.dateAgg.buckets.length;
  }

  _isBucketAggData(esResp) {
    return has(esResp, 'data.aggregations.bucketAgg.buckets') && !!esResp.data.aggregations.bucketAgg.buckets.length;
  }

  /**
  * Get matric aggregation (sum, min, max, average) of field
  */
  async _queryMetricAgg({ index, over, last, interval, field, threshold, metricAggType }) {
    this._onProgress();

    try {
      let resp;
      try {
        if (metricAggType === 'average') {
          resp = await this.watcherEditorChartService.metricAggAverage({ index, over, last, interval, field });
        } else if (metricAggType === 'sum') {
          resp = await this.watcherEditorChartService.metricAggSum({ index, over, last, interval, field });
        } else if (metricAggType === 'min') {
          resp = await this.watcherEditorChartService.metricAggMin({ index, over, last, interval, field });
        } else if (metricAggType === 'max') {
          resp = await this.watcherEditorChartService.metricAggMax({ index, over, last, interval, field });
        }
      } catch (err) {
        throw new Error(`query ES: ${err.message}`);
      }

      this.charts = [];
      this.$log.debug(`${metricAggType} es resp:`, resp);

      try {
        if (this._isDateAggData(resp)) {
          this.charts.push(new Chart());
          this._updateMetricAggChartWithNewData(this.activeChart, resp.data.aggregations, last, threshold);
          this._onChart(this.activeChart);
        } else if (this._isBucketAggData(resp)) {
          resp.data.aggregations.bucketAgg.buckets.forEach((bucket, i) => {
            this.charts.push(new Chart({enabled: false, name: bucket.key}));
            this._updateMetricAggChartWithNewData(this.charts[i], bucket, last, threshold);
          });
          this._onChart(this.charts[0]);
        } else {
          this._offChart(this.activeChart, this.messages.nodata);
        }
      } catch (err) {
        throw new Error(`update chart data: ${err.message}`);
      }
    } catch (err) {
      this._offChart(this.activeChart, this.messages.nodata);
      this._offProgress();
      throw err;
    }
    this._offProgress();
    return null;
  }

  /**
  * Count documents
  */
  async _queryCount({ index, over, last, interval, field, threshold }) {
    this._onProgress();

    try {
      let resp;
      try {
        resp = await this.watcherEditorChartService.count({ index, over, last, interval, field });
      } catch (err) {
        throw new Error(`query ES: ${err.message}`);
      }

      this.charts = [];
      this.$log.debug('count es resp:', resp);

      try {
        if (this._isDateAggData(resp)) {
          this.charts.push(new Chart());
          this._updateCountChartWithNewData(this.activeChart, resp.data.aggregations, last, threshold);
          this._onChart(this.activeChart);
        } else if (this._isBucketAggData(resp)) {
          resp.data.aggregations.bucketAgg.buckets.forEach((bucket, i) => {
            this.charts.push(new Chart({enabled: false, name: bucket.key}));
            this._updateCountChartWithNewData(this.charts[i], bucket, last, threshold);
          });
          this._onChart(this.charts[0]);
        } else {
          this._offChart(this.activeChart, this.messages.nodata);
        }
      } catch (err) {
        throw new Error(`update chart data: ${err.message}`);
      }
    } catch (err) {
      this._offChart(this.activeChart, this.messages.nodata);
      this._offProgress();
      throw err;
    }
    this._offProgress();
    return null;
  }

  _updateCountChartWithNewData(chart, aggs, last, threshold) {
    this._purgeChartData(chart);
    this._updateChartAxisesForCount(chart, aggs, last.unit);
    this._drawChartThreshold(chart, threshold.n);
  }

  _updateMetricAggChartWithNewData(chart, aggs, last, threshold) {
    this._purgeChartData(chart);
    this._updateChartAxisesForMetricAgg(chart, aggs, last.unit);
    this._drawChartThreshold(chart, threshold.n);
  }

  _onProgress(chart, msg) {
    this.progress.message = msg || 'LOADING DATA ...';
    this.progress.running = true;
  }

  _offProgress(chart, msg) {
    this.progress.message = msg || '';
    this.progress.running = false;
  }

  _onChart(chart, msg) {
    setTimeout(() => {
      this.$scope.$apply(() => {
        chart.message = msg || '';
        chart.enabled = true;
      });
    });
  }

  _offChart(chart, msg) {
    setTimeout(() => {
      this.$scope.$apply(() => {
        chart.message = msg || '';
        chart.enabled = false;
      });
    });
  }

  _updateChartAxisesForCount(chart, aggregations, unit) {
    aggregations.dateAgg.buckets.forEach((bucket) => {
      chart.xAxis.push(this._formatTimeForXAxis(bucket.key, unit));
      chart.yAxis[0].push(bucket.doc_count);
    });
  }

  _updateChartAxisesForMetricAgg(chart, aggregations, unit) {
    aggregations.dateAgg.buckets.forEach((bucket) => {
      chart.xAxis.push(this._formatTimeForXAxis(bucket.key, unit));
      chart.yAxis[0].push(bucket.metricAgg.value);
    });
  }

  _purgeChartData(chart) {
    chart.xAxis = [];
    chart.yAxis[0] = [];
  }

  _purgeAllCharts() {
    this.charts = [];
  }

  /*
  * @return {string} formatted time - April 18, 2018 4:58 PM
  */
  _formatTimeForXAxis(epochTime, unit) {
    let locale = 'LLL';
    if (unit === 'seconds') {
      locale = 'LTS';
    }
    if (unit === 'minutes' || unit === 'hours') {
      locale = 'LT';
    }
    if (unit === 'days' || unit === 'months' || unit === 'years') {
      locale = 'L';
    }
    return moment(epochTime).format(locale);
  }

  _onChartClick() {
    console.log('chart clicked');
  }
}

function conditionPanelWatcherEdit() {
  return {
    template,
    restrict: 'E',
    scope: {
      watcher: '=watcher',
    },
    controller:  ConditionPanelWatcherEdit,
    controllerAs: 'conditionPanelWatcherEdit',
    bindToController: true,
  };
}

export default conditionPanelWatcherEdit;
<commit_msg>Switch on/off chart only if it exists.<commit_after>import './condition_panel_watcher_edit.less';
import template from './condition_panel_watcher_edit.html';

import moment from 'moment';
import {size, has, pick, includes} from 'lodash';

class Chart {
  constructor({name = 'all docs', enabled = true, message = '', xAxis = [], yAxis = [[], []], options} = {}) {
    this.name = name;
    this.enabled = enabled;
    this.message = message;
    this.xAxis = xAxis;
    this.yAxis = yAxis;
    this.options = options || {
      title: {
        display: false,
        text: 'Historical results chart',
      },
    };
  }
}

class ConditionPanelWatcherEdit {
  constructor($http, $log, $scope, watcherEditorChartService) {
    this.$http = $http;
    this.$log = $log;
    this.$scope = $scope;
    this.watcherEditorChartService = watcherEditorChartService;

    this.messages = {
      nodata: 'the selected condition does not return any data',
    };

    this.progress = {
      running: false,
      message: 'LOADING DATA ...',
    };

    this.charts = [];

    this.chartQueryParams = {
      index: ['watcher_aggs_test'],
      // index: watcher._source.search.request.index,
      queryType: 'count',
      over: { type: 'all docs' },
      last: { n: 15, unit: 'minutes' },
      interval: { n: 1, unit: 'minutes' },
      threshold: { n: 10, direction: 'above' },
    };

    this.allDocFields = ['animal', 'random'];

    this.condition = {
      type: {
        handleSelect: (type) => {
          this.$log.debug('select type:', type);
          this._updateChartQueryParamsQueryType(type);
        },
      },
      field: {
        enabled: false,
        handleSelect: (field) => {
          this.$log.debug('select field:', field);
          this._updateChartQueryParamsField(field);
        },
      },
      over: {
        handleSelect: (over) => {
          this.$log.debug('select over:', over);
          if (over.type !== 'top' || !!over.n && !!over.field.length) {
            this._updateChartQueryParamsOver(over);
          }
        },
      },
      threshold: {
        handleSelect: (direction, n) => {
          this.$log.debug('select threshold:', direction, n);
          this._updateChartQueryParamsThreshold(n, direction);
          this._drawChartThreshold(this.activeChart, this.chartQueryParams.threshold.n);
        },
      },
      last: {
        handleSelect: (unit, n) => {
          this.$log.debug('select last:', unit, n);
          this._updateChartQueryParamsLast(n, unit);
        },
      },
    };

    this.$scope.$watch('conditionPanelWatcherEdit.watcher._source.trigger.schedule.later', () => {
      this._updateChartQueryParamsInterval(this.watcher._source.trigger.schedule.later);
    });

    this.$scope.$watch('conditionPanelWatcherEdit.watcher._source.input.search.request.index', () => {
      // this.chartQueryParams.index = this.watcher._source.input.search.request.index;
    });

    this.$scope.$watch('conditionPanelWatcherEdit.chartQueryParams', async () => {
      try {
        await this._fetchChartData();
      } catch (err) {
        this.$log.error(['ConditionPanelWatcherEdit'], `fail: ${err.message}`);
      }
    }, true);
  }

  get activeChart() {
    return this.charts.find((chart) => chart.enabled === true);
  }

  get isAnyActiveChart() {
    return !!this.charts.find((chart) => chart.enabled === true);
  }

  get areMultipleCharts() {
    return this.charts.length > 1;
  }

  _activeChartIndex() {
    return this.charts.findIndex((e) => e.enabled === true);
  }

  _offChartBatch(indicesToExclude = []) {
    this.charts.forEach((chart, i) => {
      if (!indicesToExclude.includes(i)) {
        this._offChart(chart);
      }
    });
  }

  switchToLeftChart() {
    let index = this._activeChartIndex();
    if (index > 0) {
      index -= 1;
      this._offChartBatch([index]);
      this._onChart(this.charts[index]);
    }
  }

  switchToRightChart() {
    let index = this._activeChartIndex();
    if (index < size(this.charts) - 1) {
      index += 1;
      this._offChartBatch([index]);
      this._onChart(this.charts[index]);
    }
  }

  /*
  * Fetch chart data and fill its X and Y axises
  */
  async _fetchChartData() {
    this._toggleConditionBuilderMetricAggOverField();
    const params = pick(this.chartQueryParams, ['index', 'over', 'last', 'interval', 'field', 'threshold']);

    if (this.chartQueryParams.queryType === 'average') {
      params.metricAggType = 'average';
      try {
        await this._queryMetricAgg(params);
        return;
      } catch (err) {
        throw new Error(`average: ${err.message}`);
      }
    }

    if (this.chartQueryParams.queryType === 'sum') {
      params.metricAggType = 'sum';
      try {
        await this._queryMetricAgg(params);
        return;
      } catch (err) {
        throw new Error(`sum: ${err.message}`);
      }
    }

    if (this.chartQueryParams.queryType === 'min') {
      params.metricAggType = 'min';
      try {
        await this._queryMetricAgg(params);
        return;
      } catch (err) {
        throw new Error(`min: ${err.message}`);
      }
    }

    if (this.chartQueryParams.queryType === 'max') {
      params.metricAggType = 'max';
      try {
        await this._queryMetricAgg(params);
        return;
      } catch (err) {
        throw new Error(`max: ${err.message}`);
      }
    }

    try {
      await this._queryCount(params);
    } catch (err) {
      throw new Error(`count: ${err.message}`);
    }
    return null;
  }

  _toggleConditionBuilderMetricAggOverField() {
    if (this.chartQueryParams.queryType === 'count') {
      this.condition.field.enabled = false;
    } else {
      this.condition.field.enabled = true;
    }
  }

  /*
  * @param {integer} n on y axis
  */
  _drawChartThreshold(chart, n) {
    const len = chart.yAxis[0].length;
    chart.yAxis[1] = Array.apply(null, Array(len)).map(Number.prototype.valueOf, n);
  }

  /*
  * @param {string} interval of time: every 1 minutes
  */
  _scheduleModeEveryIsUsed(interval) {
    if (interval.match(/every \d+ (seconds|minutes|hours|days|months|years)/g)) {
      return true;
    }
    return false;
  }

  /*
  * @param {string} interval of time: every 1 minutes
  */
  _updateChartQueryParamsInterval(interval) {
    if (this._scheduleModeEveryIsUsed(interval)) {
      interval = interval.split(' ');
      this.chartQueryParams.interval = {
        n: +interval[1],
        unit: interval[2],
      };
    }
  }

  _updateChartQueryParamsOver(over) {
    this.chartQueryParams.over = pick(over, ['type', 'n', 'field']);
  }

  _updateChartQueryParamsField(field) {
    this.chartQueryParams.field = field;
  }

  _updateChartQueryParamsQueryType(type) {
    this.chartQueryParams.queryType = type;
  }

  _updateChartQueryParamsLast(n, unit) {
    this.chartQueryParams.last = { unit, n: +n };
  }

  _updateChartQueryParamsThreshold(n, direction) {
    this.chartQueryParams.threshold = { direction, n: +n };
  }

  _isDateAggData(esResp) {
    return has(esResp, 'data.aggregations.dateAgg.buckets') && !!esResp.data.aggregations.dateAgg.buckets.length;
  }

  _isBucketAggData(esResp) {
    return has(esResp, 'data.aggregations.bucketAgg.buckets') && !!esResp.data.aggregations.bucketAgg.buckets.length;
  }

  /**
  * Get matric aggregation (sum, min, max, average) of field
  */
  async _queryMetricAgg({ index, over, last, interval, field, threshold, metricAggType }) {
    this._onProgress();

    try {
      let resp;
      try {
        if (metricAggType === 'average') {
          resp = await this.watcherEditorChartService.metricAggAverage({ index, over, last, interval, field });
        } else if (metricAggType === 'sum') {
          resp = await this.watcherEditorChartService.metricAggSum({ index, over, last, interval, field });
        } else if (metricAggType === 'min') {
          resp = await this.watcherEditorChartService.metricAggMin({ index, over, last, interval, field });
        } else if (metricAggType === 'max') {
          resp = await this.watcherEditorChartService.metricAggMax({ index, over, last, interval, field });
        }
      } catch (err) {
        throw new Error(`query ES: ${err.message}`);
      }

      this.charts = [];
      this.$log.debug(`${metricAggType} es resp:`, resp);

      try {
        if (this._isDateAggData(resp)) {
          this.charts.push(new Chart());
          this._updateMetricAggChartWithNewData(this.activeChart, resp.data.aggregations, last, threshold);
          this._onChart(this.activeChart);
        } else if (this._isBucketAggData(resp)) {
          resp.data.aggregations.bucketAgg.buckets.forEach((bucket, i) => {
            this.charts.push(new Chart({enabled: false, name: bucket.key}));
            this._updateMetricAggChartWithNewData(this.charts[i], bucket, last, threshold);
          });
          this._onChart(this.charts[0]);
        } else {
          this._offChart(this.activeChart, this.messages.nodata);
        }
      } catch (err) {
        throw new Error(`update chart data: ${err.message}`);
      }
    } catch (err) {
      this._offChart(this.activeChart, this.messages.nodata);
      this._offProgress();
      throw err;
    }
    this._offProgress();
    return null;
  }

  /**
  * Count documents
  */
  async _queryCount({ index, over, last, interval, field, threshold }) {
    this._onProgress();

    try {
      let resp;
      try {
        resp = await this.watcherEditorChartService.count({ index, over, last, interval, field });
      } catch (err) {
        throw new Error(`query ES: ${err.message}`);
      }

      this.charts = [];
      this.$log.debug('count es resp:', resp);

      try {
        if (this._isDateAggData(resp)) {
          this.charts.push(new Chart());
          this._updateCountChartWithNewData(this.activeChart, resp.data.aggregations, last, threshold);
          this._onChart(this.activeChart);
        } else if (this._isBucketAggData(resp)) {
          resp.data.aggregations.bucketAgg.buckets.forEach((bucket, i) => {
            this.charts.push(new Chart({enabled: false, name: bucket.key}));
            this._updateCountChartWithNewData(this.charts[i], bucket, last, threshold);
          });
          this._onChart(this.charts[0]);
        } else {
          this._offChart(this.activeChart, this.messages.nodata);
        }
      } catch (err) {
        throw new Error(`update chart data: ${err.message}`);
      }
    } catch (err) {
      this._offChart(this.activeChart, this.messages.nodata);
      this._offProgress();
      throw err;
    }
    this._offProgress();
    return null;
  }

  _updateCountChartWithNewData(chart, aggs, last, threshold) {
    this._purgeChartData(chart);
    this._updateChartAxisesForCount(chart, aggs, last.unit);
    this._drawChartThreshold(chart, threshold.n);
  }

  _updateMetricAggChartWithNewData(chart, aggs, last, threshold) {
    this._purgeChartData(chart);
    this._updateChartAxisesForMetricAgg(chart, aggs, last.unit);
    this._drawChartThreshold(chart, threshold.n);
  }

  _onProgress(chart, msg) {
    this.progress.message = msg || 'LOADING DATA ...';
    this.progress.running = true;
  }

  _offProgress(chart, msg) {
    this.progress.message = msg || '';
    this.progress.running = false;
  }

  _onChart(chart, msg) {
    if (chart) {
      setTimeout(() => {
        this.$scope.$apply(() => {
          chart.message = msg || '';
          chart.enabled = true;
        });
      });
    }
  }

  _offChart(chart, msg) {
    if (chart) {
      setTimeout(() => {
        this.$scope.$apply(() => {
          chart.message = msg || '';
          chart.enabled = false;
        });
      });
    }
  }

  _updateChartAxisesForCount(chart, aggregations, unit) {
    aggregations.dateAgg.buckets.forEach((bucket) => {
      chart.xAxis.push(this._formatTimeForXAxis(bucket.key, unit));
      chart.yAxis[0].push(bucket.doc_count);
    });
  }

  _updateChartAxisesForMetricAgg(chart, aggregations, unit) {
    aggregations.dateAgg.buckets.forEach((bucket) => {
      chart.xAxis.push(this._formatTimeForXAxis(bucket.key, unit));
      chart.yAxis[0].push(bucket.metricAgg.value);
    });
  }

  _purgeChartData(chart) {
    chart.xAxis = [];
    chart.yAxis[0] = [];
  }

  _purgeAllCharts() {
    this.charts = [];
  }

  /*
  * @return {string} formatted time - April 18, 2018 4:58 PM
  */
  _formatTimeForXAxis(epochTime, unit) {
    let locale = 'LLL';
    if (unit === 'seconds') {
      locale = 'LTS';
    }
    if (unit === 'minutes' || unit === 'hours') {
      locale = 'LT';
    }
    if (unit === 'days' || unit === 'months' || unit === 'years') {
      locale = 'L';
    }
    return moment(epochTime).format(locale);
  }

  _onChartClick() {
    console.log('chart clicked');
  }
}

function conditionPanelWatcherEdit() {
  return {
    template,
    restrict: 'E',
    scope: {
      watcher: '=watcher',
    },
    controller:  ConditionPanelWatcherEdit,
    controllerAs: 'conditionPanelWatcherEdit',
    bindToController: true,
  };
}

export default conditionPanelWatcherEdit;
<|endoftext|>


<commit_before>define(
    'imcms-link-validator-tab-builder',
    ['imcms-super-admin-tab', 'imcms-i18n-texts', 'imcms-components-builder',
        'imcms-field-wrapper', 'imcms-bem-builder', 'jquery', 'imcms-link-validator-rest-api'],
    function (SuperAdminTab, texts, components, fieldWrapper, BEM, $, linksValidatorRestApi) {

        texts = texts.superAdmin.linkValidator;

        let $startIdInput;
        let $endIdInput;
        let $filterBrokenLinksCheckbox;
        let $resultContainer;

        function showOnlyBrokenLinks() {
        }

        function buildTitleText() {
            return fieldWrapper.wrap(components.texts.titleText('<div>', texts.name))
        }

        function buildFilterOnlyBrokenLinks() {
            return $filterBrokenLinksCheckbox = components.checkboxes.imcmsCheckbox('<div>', {
                text: texts.titleOnlyBrokenLinks,
                click: showOnlyBrokenLinks
            });
        }

        function buildLinkParamsContainer() {

            function buildFieldStartId() {
                return $startIdInput = components.texts.textNumber('<div>', {
                    text: texts.titleStartId,
                    placeholder: '1001'
                });
            }

            function buildFieldEndId() {
                return $endIdInput = components.texts.textNumber('<div>', {
                    text: texts.titleEndId,
                    placeholder: '1001'
                });
            }

            var linkListBuilder = function ($containerResult) {
                this.$containerResult = $containerResult;
                this.linkAppender = this.appendLinks.bind(this);
            };

            function buildLinkUrl(validationLink) {
                let reference;
                let type = validationLink.linkType;
                let loopEntry = validationLink.editLink.loopEntryRef;
                let metaId = validationLink.editLink.metaId;
                let index = validationLink.editLink.index;

                if (type === "TEXT") {
                    if (loopEntry === null) {
                        reference = `text?meta-id=${metaId}&index=${index}`
                    } else {
                        reference = `text?meta-id=${metaId}&index=${index}
                        &loop-index=${loopEntry.loopIndex}&loop-entry-index=${loopEntry.loopEntryIndex}`
                    }
                }
                else if (type === "IMAGE") {
                    if (loopEntry === null) {
                        reference = `image?meta-id=${metaId}&index=${index}`
                    } else {
                        reference = `image?meta-id=${metaId}&index=${index}
                        &loop-index=${loopEntry.loopIndex}&loop-entry-index=${loopEntry.loopEntryIndex}`
                    }
                } else {
                    reference = `page-info?meta-id=${metaId}`
                }
                return reference;
            }

            function buildLinkText(metaId, title, index) {
                return `${metaId}-${title}${index === null ? '' : -index}`;
            }

            linkListBuilder.prototype = {
                isEmpty: true,
                clearList: function () {
                    this.$containerResult.empty();
                    this.isEmpty = true;

                    return this;
                },
                linkToRow: function (validationLink) {
                    let textUrl = buildLinkText(validationLink.editLink.metaId,
                        validationLink.editLink.title,
                        validationLink.editLink.index);
                    let urlBuild = buildLinkUrl(validationLink);
                    return new BEM({
                        block: "link-info-row",
                        elements: {
                            'link-page-alias': $('<div>', {
                                text: validationLink.documentData.alias
                            }),
                            'link-status': $('<div>', {
                                text: validationLink.documentData.documentStatus
                            }),
                            'link-type': $('<div>', {
                                text: validationLink.linkType
                            }),
                            'link-admin': $('<a>', {
                                text: textUrl,
                                href: urlBuild
                            }),
                            'link-name':
                                $('<a>', {
                                    text: validationLink.url,
                                    href: validationLink.url
                                }),
                            'link-host-found':
                                validationLink.hostFound
                                    ? components.controls.check()
                                    : components.controls.remove(),
                            'link-host-reachable':
                                validationLink.hostReachable
                                    ? components.controls.check()
                                    : components.controls.remove(),
                            'link-page-found':
                                validationLink.pageFound
                                    ? components.controls.check()
                                    : components.controls.remove()
                        }
                    }).buildBlockStructure("<div>");
                },
                prepareTitleRow: function () {
                    let titleRow = new BEM({
                        block: 'link-title-row',
                        elements: {
                            'page-alias': $('<div>', {text: texts.linkInfoRow.pageAlias}),
                            'status': $('<div>', {text: texts.linkInfoRow.status}),
                            'type': $('<div>', {text: texts.linkInfoRow.type}),
                            'admin': $('<div>', {text: texts.linkInfoRow.admin}),
                            'link': $('<div>', {text: texts.linkInfoRow.link}),
                            'host-found': $('<div>', {text: texts.linkInfoRow.hostFound}),
                            'host-reachable': $('<div>', {text: texts.linkInfoRow.hostReachable}),
                            'page-found': $('<div>', {text: texts.linkInfoRow.pageFound})
                        }
                    }).buildBlockStructure('<div>', {
                        'class': 'link-title'
                    });
                    this.$containerResult.append(titleRow);
                    return this;
                },
                rowsAddToList: function (linkRows) {
                    this.$containerResult.css('display', 'inline-block').append(linkRows);
                    return this;
                },
                appendLinks: function (validationLinks) {
                    this.prepareTitleRow()
                        .rowsAddToList(validationLinks.map(this.linkToRow));
                }
            };

            function listValidationLinks() {
                var linksValidationParams = {
                    filterBrokenLinks: $filterBrokenLinksCheckbox.isChecked(),
                    startDocumentId: $startIdInput.getInput().val(),
                    endDocumentId: $endIdInput.getInput().val()
                };
                var tableBuilder = new linkListBuilder($resultContainer).clearList();
                linksValidatorRestApi.validate(linksValidationParams).done(tableBuilder.linkAppender);
            }

            function buildValidationButton() {
                let $button = components.buttons.positiveButton({
                    text: texts.buttonValidation,
                    click: listValidationLinks
                });

                return components.buttons.buttonsContainer('<div>', [$button]);
            }

            return new BEM({
                block: 'link-params-block',
                elements: {
                    'links-field-start': buildFieldStartId(),
                    'links-field-end': buildFieldEndId(),
                    'button-validation': buildValidationButton()
                }
            }).buildBlockStructure('<div>');
        }

        function buildLinksContainer() {
            return $('<div>', {
                'class': 'table-links',
                style: 'display: none;'
            });
        }

        return new SuperAdminTab(texts.name, [
            buildTitleText(),
            buildLinkParamsContainer(),
            buildFilterOnlyBrokenLinks(),
            $resultContainer = buildLinksContainer()
        ]);
    }
)
;
<commit_msg>IMCMS-334 New design to super admin page: link validator tab - Change placeholder<commit_after>define(
    'imcms-link-validator-tab-builder',
    ['imcms-super-admin-tab', 'imcms-i18n-texts', 'imcms-components-builder',
        'imcms-field-wrapper', 'imcms-bem-builder', 'jquery', 'imcms-link-validator-rest-api'],
    function (SuperAdminTab, texts, components, fieldWrapper, BEM, $, linksValidatorRestApi) {

        texts = texts.superAdmin.linkValidator;

        let $startIdInput;
        let $endIdInput;
        let $filterBrokenLinksCheckbox;
        let $resultContainer;

        function showOnlyBrokenLinks() {
        }

        function buildTitleText() {
            return fieldWrapper.wrap(components.texts.titleText('<div>', texts.name))
        }

        function buildFilterOnlyBrokenLinks() {
            return $filterBrokenLinksCheckbox = components.checkboxes.imcmsCheckbox('<div>', {
                text: texts.titleOnlyBrokenLinks,
                click: showOnlyBrokenLinks
            });
        }

        function buildLinkParamsContainer() {

            function buildFieldStartId() {
                return $startIdInput = components.texts.textNumber('<div>', {
                    text: texts.titleStartId,
                    placeholder: texts.startDocumentId,
                    min: 0
                });
            }

            function buildFieldEndId() {
                return $endIdInput = components.texts.textNumber('<div>', {
                    text: texts.titleEndId,
                    placeholder: texts.endDocumentId,
                    min: 0
                });
            }

            var linkListBuilder = function ($containerResult) {
                this.$containerResult = $containerResult;
                this.linkAppender = this.appendLinks.bind(this);
            };

            function buildLinkUrl(validationLink) {
                let reference;
                let type = validationLink.linkType;
                let loopEntry = validationLink.editLink.loopEntryRef;
                let metaId = validationLink.editLink.metaId;
                let index = validationLink.editLink.index;

                if (type === "TEXT") {
                    if (loopEntry === null) {
                        reference = `text?meta-id=${metaId}&index=${index}`
                    } else {
                        reference = `text?meta-id=${metaId}&index=${index}
                        &loop-index=${loopEntry.loopIndex}&loop-entry-index=${loopEntry.loopEntryIndex}`
                    }
                }
                else if (type === "IMAGE") {
                    if (loopEntry === null) {
                        reference = `image?meta-id=${metaId}&index=${index}`
                    } else {
                        reference = `image?meta-id=${metaId}&index=${index}
                        &loop-index=${loopEntry.loopIndex}&loop-entry-index=${loopEntry.loopEntryIndex}`
                    }
                } else {
                    reference = `page-info?meta-id=${metaId}`
                }
                return reference;
            }

            function buildLinkText(metaId, title, index) {
                return `${metaId}-${title}${index === null ? '' : -index}`;
            }

            linkListBuilder.prototype = {
                isEmpty: true,
                clearList: function () {
                    this.$containerResult.empty();
                    this.isEmpty = true;

                    return this;
                },
                linkToRow: function (validationLink) {
                    let textUrl = buildLinkText(validationLink.editLink.metaId,
                        validationLink.editLink.title,
                        validationLink.editLink.index);
                    let urlBuild = buildLinkUrl(validationLink);
                    return new BEM({
                        block: "link-info-row",
                        elements: {
                            'link-page-alias': $('<div>', {
                                text: validationLink.documentData.alias
                            }),
                            'link-status': $('<div>', {
                                text: validationLink.documentData.documentStatus
                            }),
                            'link-type': $('<div>', {
                                text: validationLink.linkType
                            }),
                            'link-admin': $('<a>', {
                                text: textUrl,
                                href: urlBuild
                            }),
                            'link-name':
                                $('<a>', {
                                    text: validationLink.url,
                                    href: validationLink.url
                                }),
                            'link-host-found':
                                validationLink.hostFound
                                    ? components.controls.check()
                                    : components.controls.remove(),
                            'link-host-reachable':
                                validationLink.hostReachable
                                    ? components.controls.check()
                                    : components.controls.remove(),
                            'link-page-found':
                                validationLink.pageFound
                                    ? components.controls.check()
                                    : components.controls.remove()
                        }
                    }).buildBlockStructure("<div>");
                },
                prepareTitleRow: function () {
                    let titleRow = new BEM({
                        block: 'link-title-row',
                        elements: {
                            'page-alias': $('<div>', {text: texts.linkInfoRow.pageAlias}),
                            'status': $('<div>', {text: texts.linkInfoRow.status}),
                            'type': $('<div>', {text: texts.linkInfoRow.type}),
                            'admin': $('<div>', {text: texts.linkInfoRow.admin}),
                            'link': $('<div>', {text: texts.linkInfoRow.link}),
                            'host-found': $('<div>', {text: texts.linkInfoRow.hostFound}),
                            'host-reachable': $('<div>', {text: texts.linkInfoRow.hostReachable}),
                            'page-found': $('<div>', {text: texts.linkInfoRow.pageFound})
                        }
                    }).buildBlockStructure('<div>', {
                        'class': 'link-title'
                    });
                    this.$containerResult.append(titleRow);
                    return this;
                },
                rowsAddToList: function (linkRows) {
                    this.$containerResult.css('display', 'inline-block').append(linkRows);
                    return this;
                },
                appendLinks: function (validationLinks) {
                    this.prepareTitleRow()
                        .rowsAddToList(validationLinks.map(this.linkToRow));
                }
            };

            function listValidationLinks() {
                var linksValidationParams = {
                    filterBrokenLinks: $filterBrokenLinksCheckbox.isChecked(),
                    startDocumentId: $startIdInput.getInput().val(),
                    endDocumentId: $endIdInput.getInput().val()
                };
                var tableBuilder = new linkListBuilder($resultContainer).clearList();
                linksValidatorRestApi.validate(linksValidationParams).done(tableBuilder.linkAppender);
            }

            function buildValidationButton() {
                let $button = components.buttons.positiveButton({
                    text: texts.buttonValidation,
                    click: listValidationLinks
                });

                return components.buttons.buttonsContainer('<div>', [$button]);
            }

            return new BEM({
                block: 'link-params-block',
                elements: {
                    'links-field-start': buildFieldStartId(),
                    'links-field-end': buildFieldEndId(),
                    'button-validation': buildValidationButton()
                }
            }).buildBlockStructure('<div>');
        }

        function buildLinksContainer() {
            return $('<div>', {
                'class': 'table-links',
                style: 'display: none;'
            });
        }

        return new SuperAdminTab(texts.name, [
            buildTitleText(),
            buildLinkParamsContainer(),
            buildFilterOnlyBrokenLinks(),
            $resultContainer = buildLinksContainer()
        ]);
    }
)
;
<|endoftext|>


<commit_before>define(
    'imcms-link-validator-tab-builder',
    ['imcms-super-admin-tab', 'imcms-i18n-texts', 'imcms-components-builder',
        'imcms-field-wrapper', 'imcms-bem-builder', 'jquery', 'imcms-link-validator-rest-api'],
    function (SuperAdminTab, texts, components, fieldWrapper, BEM, $, linksValidatorRestApi) {

        texts = texts.superAdmin.linkValidator;

        let $startIdInput;
        let $endIdInput;
        let $filterBrokenLinksCheckbox;
        let $resultContainer;

        function showOnlyBrokenLinks() {
        }

        function buildTitleText() {
            return fieldWrapper.wrap(components.texts.titleText('<div>', texts.name))
        }

        function buildFilterOnlyBrokenLinks() {
            return $filterBrokenLinksCheckbox = components.checkboxes.imcmsCheckbox('<div>', {
                text: texts.titleOnlyBrokenLinks,
                click: showOnlyBrokenLinks
            });
        }

        function buildLinkParamsContainer() {

            function buildFieldStartId() {
                return $startIdInput = components.texts.textNumber('<div>', {
                    text: texts.titleStartId,
                    placeholder: 1001
                });
            }

            function buildFieldEndId() {
                return $endIdInput = components.texts.textNumber('<div>', {
                    text: texts.titleEndId,
                    placeholder: 1001
                });
            }

            var linkListBuilder = function ($containerResult) {
                this.$containerResult = $containerResult;
                this.linkAppender = this.appendLinks.bind(this);
            };

            function buildLinkUrl(type, metaId, index) { //todo add loopEntry and check type for image on old admin
                return (type === "TEXT"
                    ? `text?meta-id=${metaId}&index=${index}`
                    : `page-info?meta-id=${metaId}`);
            }

            function buildLinkText(metaId, title, index) {
                return `${metaId}-${title}${index === null ? '' : +-+index}`;
            }

            linkListBuilder.prototype = {
                isEmpty: true,
                clearList: function () {
                    this.$containerResult.empty();
                    this.isEmpty = true;

                    return this;
                },
                linkToRow: function (validationLink) {
                    let textUrl = buildLinkText(validationLink.editLink.metaId,
                        validationLink.editLink.title,
                        validationLink.editLink.index);
                    let urlBuild = buildLinkUrl(validationLink.documentData.type,
                        validationLink.editLink.metaId,
                        validationLink.editLink.index);
                    return new BEM({
                        block: "link-info-row",
                        elements: {
                            'link-page-alias': $('<div>', {
                                text: validationLink.documentData.alias
                            }),
                            'link-status': $('<div>', {
                                text: validationLink.documentData.documentStatus
                            }),
                            'link-type': $('<div>', {
                                text: validationLink.documentData.type
                            }),
                            'link-admin': $('<a>', {
                                text: textUrl,
                                href: urlBuild
                            }),
                            'link-name':
                                $('<a>', {
                                    text: validationLink.url,
                                    href: validationLink.url
                                }),
                            'link-host-found':
                                validationLink.hostFound
                                    ? components.controls.check()
                                    : components.controls.remove(),
                            'link-host-reachable':
                                validationLink.hostReachable
                                    ? components.controls.check()
                                    : components.controls.remove(),
                            'link-page-found':
                                validationLink.pageFound
                                    ? components.controls.check()
                                    : components.controls.remove()
                        }
                    }).buildBlockStructure("<div>");
                },
                prepareTitleRow: function () {
                    let titleRow = new BEM({
                        block: 'link-title-row',
                        elements: {
                            'page-alias': $('<div>', {text: texts.linkInfoRow.pageAlias}),
                            'status': $('<div>', {text: texts.linkInfoRow.status}),
                            'type': $('<div>', {text: texts.linkInfoRow.type}),
                            'admin': $('<div>', {text: texts.linkInfoRow.admin}),
                            'link': $('<div>', {text: texts.linkInfoRow.link}),
                            'host-found': $('<div>', {text: texts.linkInfoRow.hostFound}),
                            'host-reachable': $('<div>', {text: texts.linkInfoRow.hostReachable}),
                            'page-found': $('<div>', {text: texts.linkInfoRow.pageFound})
                        }
                    }).buildBlockStructure('<div>', {
                        'class': 'link-title'
                    });
                    this.$containerResult.append(titleRow);
                    return this;
                },
                rowsAddToList: function (linkRows) {
                    this.$containerResult.css('display', 'inline-block').append(linkRows);
                    return this;
                },
                appendLinks: function (validationLinks) {
                    this.prepareTitleRow()
                        .rowsAddToList(validationLinks.map(this.linkToRow));
                }
            };

            function listValidationLinks() {
                var linksValidationParams = {
                    filterBrokenLinks: $filterBrokenLinksCheckbox.isChecked(),
                    startDocumentId: $startIdInput.getInput().val(),
                    endDocumentId: $endIdInput.getInput().val()
                };
                var tableBuilder = new linkListBuilder($resultContainer).clearList();
                linksValidatorRestApi.validate(linksValidationParams).done(tableBuilder.linkAppender);
            }

            function buildValidationButton() {
                let $button = components.buttons.positiveButton({
                    text: texts.buttonValidation,
                    click: listValidationLinks
                });

                return components.buttons.buttonsContainer('<div>', [$button]);
            }

            return new BEM({
                block: 'link-params-block',
                elements: {
                    'links-field-start': buildFieldStartId(),
                    'links-field-end': buildFieldEndId(),
                    'button-validation': buildValidationButton()
                }
            }).buildBlockStructure('<div>');
        }

        function buildLinksContainer() {
            return $('<div>', {
                'class': 'table-links',
                style: 'display: none;'
            });
        }

        return new SuperAdminTab(texts.name, [
            buildTitleText(),
            buildFilterOnlyBrokenLinks(),
            buildLinkParamsContainer(),
            $resultContainer = buildLinksContainer()
        ]);
    }
);
<commit_msg>IMCMS-334 New design to super admin page: link validator tab - Create edit reference each resource<commit_after>define(
    'imcms-link-validator-tab-builder',
    ['imcms-super-admin-tab', 'imcms-i18n-texts', 'imcms-components-builder',
        'imcms-field-wrapper', 'imcms-bem-builder', 'jquery', 'imcms-link-validator-rest-api'],
    function (SuperAdminTab, texts, components, fieldWrapper, BEM, $, linksValidatorRestApi) {

        texts = texts.superAdmin.linkValidator;

        let $startIdInput;
        let $endIdInput;
        let $filterBrokenLinksCheckbox;
        let $resultContainer;

        function showOnlyBrokenLinks() {
        }

        function buildTitleText() {
            return fieldWrapper.wrap(components.texts.titleText('<div>', texts.name))
        }

        function buildFilterOnlyBrokenLinks() {
            return $filterBrokenLinksCheckbox = components.checkboxes.imcmsCheckbox('<div>', {
                text: texts.titleOnlyBrokenLinks,
                click: showOnlyBrokenLinks
            });
        }

        function buildLinkParamsContainer() {

            function buildFieldStartId() {
                return $startIdInput = components.texts.textNumber('<div>', {
                    text: texts.titleStartId,
                    placeholder: 1001
                });
            }

            function buildFieldEndId() {
                return $endIdInput = components.texts.textNumber('<div>', {
                    text: texts.titleEndId,
                    placeholder: 1001
                });
            }

            var linkListBuilder = function ($containerResult) {
                this.$containerResult = $containerResult;
                this.linkAppender = this.appendLinks.bind(this);
            };

            function buildLinkUrl(validationLink) {
                let reference;
                let type = validationLink.linkType;
                let loop = validationLink.editLink.loopEntryRef;
                let indexLoop = null;
                let entryIndexLoop = null;
                let metaId = validationLink.editLink.metaId;
                let index = validationLink.editLink.index;
                if (loop !== null) {
                    indexLoop = loop.loopIndex;
                    entryIndexLoop = loop.loopEntryIndex;
                }

                if (type === "TEXT") {
                    if (indexLoop === null) {
                        reference = `text?meta-id=${metaId}&index=${index}`
                    } else {
                        reference = `text?meta-id=${metaId}&index=${index}&loop-index=${indexLoop}&loop-entry-index=${entryIndexLoop}`
                    }
                }
                else if (type === "IMAGE") {
                    if (indexLoop === null) {
                        reference = `image?meta-id=${metaId}&index=${index}`
                    } else {
                        reference = `image?meta-id=${metaId}&index=${index}&loop-index=${indexLoop}&loop-entry-index=${entryIndexLoop}`
                    }
                } else {
                    reference = `page-info?meta-id=${metaId}`
                }
                return reference;
            }

            function buildLinkText(metaId, title, index) {
                return `${metaId}-${title}${index === null ? '' : -index}`;
            }

            linkListBuilder.prototype = {
                isEmpty: true,
                clearList: function () {
                    this.$containerResult.empty();
                    this.isEmpty = true;

                    return this;
                },
                linkToRow: function (validationLink) {
                    let textUrl = buildLinkText(validationLink.editLink.metaId,
                        validationLink.editLink.title,
                        validationLink.editLink.index);
                    let urlBuild = buildLinkUrl(validationLink);
                    return new BEM({
                        block: "link-info-row",
                        elements: {
                            'link-page-alias': $('<div>', {
                                text: validationLink.documentData.alias
                            }),
                            'link-status': $('<div>', {
                                text: validationLink.documentData.documentStatus
                            }),
                            'link-type': $('<div>', {
                                text: validationLink.linkType
                            }),
                            'link-admin': $('<a>', {
                                text: textUrl,
                                href: urlBuild
                            }),
                            'link-name':
                                $('<a>', {
                                    text: validationLink.url,
                                    href: validationLink.url
                                }),
                            'link-host-found':
                                validationLink.hostFound
                                    ? components.controls.check()
                                    : components.controls.remove(),
                            'link-host-reachable':
                                validationLink.hostReachable
                                    ? components.controls.check()
                                    : components.controls.remove(),
                            'link-page-found':
                                validationLink.pageFound
                                    ? components.controls.check()
                                    : components.controls.remove()
                        }
                    }).buildBlockStructure("<div>");
                },
                prepareTitleRow: function () {
                    let titleRow = new BEM({
                        block: 'link-title-row',
                        elements: {
                            'page-alias': $('<div>', {text: texts.linkInfoRow.pageAlias}),
                            'status': $('<div>', {text: texts.linkInfoRow.status}),
                            'type': $('<div>', {text: texts.linkInfoRow.type}),
                            'admin': $('<div>', {text: texts.linkInfoRow.admin}),
                            'link': $('<div>', {text: texts.linkInfoRow.link}),
                            'host-found': $('<div>', {text: texts.linkInfoRow.hostFound}),
                            'host-reachable': $('<div>', {text: texts.linkInfoRow.hostReachable}),
                            'page-found': $('<div>', {text: texts.linkInfoRow.pageFound})
                        }
                    }).buildBlockStructure('<div>', {
                        'class': 'link-title'
                    });
                    this.$containerResult.append(titleRow);
                    return this;
                },
                rowsAddToList: function (linkRows) {
                    this.$containerResult.css('display', 'inline-block').append(linkRows);
                    return this;
                },
                appendLinks: function (validationLinks) {
                    this.prepareTitleRow()
                        .rowsAddToList(validationLinks.map(this.linkToRow));
                }
            };

            function listValidationLinks() {
                var linksValidationParams = {
                    filterBrokenLinks: $filterBrokenLinksCheckbox.isChecked(),
                    startDocumentId: $startIdInput.getInput().val(),
                    endDocumentId: $endIdInput.getInput().val()
                };
                var tableBuilder = new linkListBuilder($resultContainer).clearList();
                linksValidatorRestApi.validate(linksValidationParams).done(tableBuilder.linkAppender);
            }

            function buildValidationButton() {
                let $button = components.buttons.positiveButton({
                    text: texts.buttonValidation,
                    click: listValidationLinks
                });

                return components.buttons.buttonsContainer('<div>', [$button]);
            }

            return new BEM({
                block: 'link-params-block',
                elements: {
                    'links-field-start': buildFieldStartId(),
                    'links-field-end': buildFieldEndId(),
                    'button-validation': buildValidationButton()
                }
            }).buildBlockStructure('<div>');
        }

        function buildLinksContainer() {
            return $('<div>', {
                'class': 'table-links',
                style: 'display: none;'
            });
        }

        return new SuperAdminTab(texts.name, [
            buildTitleText(),
            buildFilterOnlyBrokenLinks(),
            buildLinkParamsContainer(),
            $resultContainer = buildLinksContainer()
        ]);
    }
)
;
<|endoftext|>