Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function ($) {
- /**
- * Services Company
- */
- service.company = {
- /*
- * Variables
- *
- *
- */
- metadataPir: [],
- separator: "/",
- prefixes: [],
- passwordLength: 8,
- genUserOptions: {},
- advValidationOptions: {},
- optSimulateApiUser: {},
- /********************************/
- test: function () {
- var container = $("#dt_service_company_container");
- container.load(Routing.generate('service.list', {'draw': true}));
- container.show();
- },
- /**
- * Listado de ubicaciones
- */
- list: function () {
- var id_table = "dt_service_company_location";
- var table = $('#' + id_table);
- var container = $("#dt_service_company_container");
- var url_crear = Routing.generate('service.form');
- var dt = table.DataTable({
- serverSide: true,
- processing: true,
- autoWidth: true,
- ajax: Routing.generate('service.list'),
- order: [[0, "desc"]],
- pageLength: 20,
- sDom: datatables.dt_sDom_full,
- oLanguage: datatables.dt_oLanguage,
- lengthMenu: datatables.dt_lengthMenu,
- columns: [
- {
- data: "id",
- visible: false,
- title: "id"
- },
- {data: "codService", title: "Código servicio"},
- {data: "customer", title: "Customer"},
- {data: "typeService", title: "Tipo servicio"},
- {data: "description", title: "Descripción"},
- {data: "idState.state", title: "Estado"},
- ],
- oTableTools: {
- aButtons: []
- },
- buttons: [
- {
- text: '<i class="fa fa-refresh"></i>',
- action: function (e, dt, node, config) {
- dt.ajax.reload();
- }
- },
- {
- text: '<i class="fa fa-plus"></i>',
- action: function (e, dt, node, config) {
- window.location.href = '#' + url_crear;
- }
- },
- {text: '<i class="fa fa-file-excel-o"></i>',
- action: function (e, dt, node, config) {
- var url = Routing.generate('location.editor', {
- search: dt.search(),
- draw: 'excel'
- });
- window.open(url, '_blank');
- }
- }
- ],
- preDrawCallback: function () {
- if (!datatables.dt_responsiveHelper) {
- datatables.dt_responsiveHelper = new ResponsiveDatatablesHelper(table, datatables.dt_breakpointDefinition);
- }
- },
- drawCallback: function (oSettings) {
- datatables.dt_responsiveHelper.respond();
- $('.dataTables_processing', table.closest(".dataTables_wrapper")).show();
- },
- initComplete: function (settings, json) {
- container.show();
- }
- });
- $("#" + id_table + " tbody").on("dblclick", "tr", function (event) {
- var id = dt.row(this).data().id;
- var url = Routing.generate('service.form', {
- id: id
- });
- if (id) {
- window.location.href = '#' + url;
- }
- });
- $("#" + id_table + " tbody").on("mousedown", "tr", function (event) {
- var id = dt.row(this).data().id;
- var url = Routing.generate('service.form', {
- id: id
- });
- if ('mousedown' === event.type && 2 === event.which) {
- var href = window.location.href;
- var hrefPart = href.split('#')[0] + '#' + url;
- window.open(hrefPart, '_blank');
- }
- });
- },
- /**
- * Guarda un formulario de ubicaciones
- */
- saveForm: function ()
- {
- $(".masmovil-ajax-form").unbind('submit');
- $(".masmovil-ajax-form").submit(function (e) {
- console.log('submit');
- e.preventDefault();
- $(".masmovil-ajax-submit").button('loading');
- var submitdata = $(this).serialize();
- var isValid = service.company.advancedValidation($(this));
- if (isValid === true) {
- $.ajax({
- url: e.currentTarget.action,
- type: 'post',
- dataType: 'json',
- data: submitdata,
- success: function (data) {
- masmovil.form.success(data);
- window.location.href = '#' + Routing.generate('service.form', {
- id: data.id
- });
- }
- }).fail(function (jqXHR, textStatus, error) {
- masmovil.form.fail(jqXHR, textStatus, error);
- });
- } else {
- service.company.showValidationErrors(isValid);
- masmovil.form.fail(false, isValid.title, isValid.error);
- }
- });
- },
- setAdvacedValidation: function (validation) {
- servcomp = service.company;
- if (servcomp.isJSON(validation)) {
- servcomp.advValidationOptions = validation;
- // console.log(servcomp.advValidationOptions);
- }
- },
- advancedValidation: function (form) {
- var arrayOptions = service.company.advValidationOptions;
- if (!$.isEmptyObject(arrayOptions)) {
- var isValid = true;
- for (index in arrayOptions) {
- var options = arrayOptions[index];
- switch (options.type) {
- case 'percent':
- var textProfile = $(options.profileId).find("option:selected").text();
- var valueProfile = $(options.profileId).val();
- if (textProfile == "A medida" || valueProfile == "") {
- var sum = 0;
- $(options.classtarget).each(function (i, element) {
- if ($(this).val() != "") {
- sum += parseInt($(this).val());
- }
- });
- if (options.totalpercent == sum) {
- if (isValid === false) {
- isValid = true;
- }
- } else {
- isValid = {
- 'isValid': false,
- 'title': 'Atención.',
- 'error': 'Los porcentajes no suman ' + options.totalpercent,
- 'classtarget': options.classtarget,
- 'classErrorText': ''
- };
- }
- }
- break;
- case 'pw_blocks':
- nodeSrc = $(options.Nodes_ids.src).val();
- nodeDst = $(options.Nodes_ids.dst).val();
- nodeDstBackup = $(options.Nodes_ids.dstbackup).val();
- interfSrc = $(options.Interfaces_ids.src).val();
- interfDst = $(options.Interfaces_ids.dst).val();
- if (nodeSrc != nodeDst) {
- if ((nodeDstBackup == nodeDst) && (nodeDstBackup == nodeSrc)) {
- isValid = {
- 'isValid': false,
- 'title': 'Atención.',
- 'error': ' Error en la configuración. Por favor, revise las configuraciones remarcadas.',
- 'classtarget': options.genericPwError,
- 'classErrorText': ''
- };
- }
- } else {
- if (interfSrc == interfDst) {
- isValid = {
- 'isValid': false,
- 'title': 'Atención.',
- 'error': 'No pueden coincidir las configuraciones de Src y Dst',
- 'classtarget': options.classSrcEqualDstError,
- 'classErrorText': ''
- };
- }
- }
- break;
- }
- }
- return isValid;
- } else {
- return true;
- }
- },
- generateModal: function (action, options) {
- options || (options = {});
- if (options.hasOwnProperty("idModal")) {
- var modal = $(options.idModal);
- } else {
- var modal = $("#genericModal");
- }
- var title = modal.find('#modal-title');
- var body = modal.find('#modal-body');
- if (!options.hasOwnProperty("title")) {
- options.title = "Alerta del sistema.";
- }
- if (!options.hasOwnProperty("body")) {
- options.body = "";
- }
- if (options.hasOwnProperty("size")) {
- switch (options.size) {
- case 'large':
- modal.find(".modal-dialog").removeClass("modal-lg");
- modal.find(".modal-dialog").removeClass("modal-sm");
- modal.find(".modal-dialog").addClass("modal-lg");
- break;
- case 'small':
- modal.find(".modal-dialog").removeClass("modal-lg");
- modal.find(".modal-dialog").removeClass("modal-sm");
- modal.find(".modal-dialog").addClass("modal-sm");
- break;
- }
- }
- title.html(options.title);
- body.html(options.body);
- switch (action) {
- case 'show':
- modal.modal('show');
- break;
- case 'clear':
- console.log(body.html());
- body.html("");
- console.log(body.html());
- modal.modal('hide');
- break;
- }
- return modal;
- },
- showValidationErrors: function (options) {
- var errorClass = "state-error";
- $("." + errorClass).removeClass(errorClass);
- var label = $(options.classtarget).parent('label');
- label.each(function () {
- $(this).addClass(errorClass);
- });
- },
- /***********************************************************/
- simulateApiUser: function (mode, options) {
- var form = $("#service_form");
- switch (mode) {
- case 'initialize':
- if (options.hasOwnProperty("idAccessType")) {
- if (options.hasOwnProperty("typeAuxForm") && options.hasOwnProperty("modalOptions")) {
- $('#service_apiValidate').show();
- $('#service_save').hide();
- service.company.optSimulateApiUser = options;
- $('#service_apiValidate').on('click', function () {
- var isValid = service.company.advancedValidation(form);
- console.log(isValid);
- isValid = true;
- if (isValid === true) {
- service.company.simulateApiUser('validate', {});
- } else {
- service.company.showValidationErrors(isValid);
- masmovil.form.fail(false, isValid.title, isValid.error);
- }
- });
- } else {
- console.log('"options.typeAuxForm" is not defined.');
- }
- } else {
- console.log();
- }
- break;
- case 'validate':
- var simulateOptions = service.company.optSimulateApiUser;
- var accesstype = $(simulateOptions.idAccessType);
- if (accesstype.val() != "") {
- var accesstypeVal = accesstype.find("option:selected").text();
- var typeAuxForm = simulateOptions.typeAuxForm;
- var patt = new RegExp("^PPPoE");
- if (patt.test(accesstypeVal)) {
- if (typeAuxForm === 1 || typeAuxForm === 2) {
- var submitdata = form.serialize();
- $.ajax({
- url: Routing.generate('service.apiradius.simulate', {
- typeAuxForm: typeAuxForm
- }),
- type: 'post',
- // dataType: 'json',
- // async: false,
- data: submitdata,
- success: function (response) {
- var modalOptions = simulateOptions.modalOptions;
- modalOptions.body = service.company.processApiResponse(response,modalOptions.subtitle);
- modal = service.company.generateModal("show",modalOptions);
- modal.find('.actions').on('click',function(){
- var action = $(this).data('action');
- if (action == "ok") {
- form.trigger('submit');
- modal.modal('hide');
- }else if(action == "cancel"){
- service.company.generateModal("clear",modalOptions)
- }
- });
- }
- }).fail(function (jqXHR, textStatus, error) {
- masmovil.form.fail(jqXHR, textStatus, error);
- });
- }
- } else {
- // form.unbind('submit');
- form.trigger('submit');
- // console.log();
- }
- } else {
- // masmovil.form.fail(jqXHR, textStatus, error);
- }
- break;
- }
- },
- processApiResponse: function (response, subtitle) {
- var out = "";
- out += "<p class='alert alert-warning'>";
- out += " <i class='fa fa-warning'></i> " + subtitle;
- out += "</p>";
- // console.log(response);
- var content = response.replace(/\//g, "");
- content = content.replace(/{/g, "");
- content = content.replace(/\"/g, "");
- content = content.split('\\n');
- out += "<ul class='list-group'>";
- for (cont in content) {
- out += "<li class='list-group-item'>";
- out += content[cont];
- out += "</li>";
- }
- out += "</ul>";
- return out;
- },
- loadAux: function () {
- if ($("#service_category").length && $("#service_category").val() != "") {
- service.company.ajaxGetForm(service.company.setParametersAux());
- }
- $("#service_category").on('change', function () {
- service.company.ajaxGetForm(service.company.setParametersAux());
- });
- },
- setParametersAux: function () {
- var parameters = new Object();
- parameters.category = ($("#service_category").length) ? $("#service_category").val() : null;
- parameters.idGestion = ($("#service_idGestion").length) ? $("#service_idGestion").val() : null;
- parameters.idInet = ($("#service_idInet").length) ? $("#service_idInet").val() : null;
- parameters.idVpn = ($("#service_idVpn").length) ? $("#service_idVpn").val() : null;
- parameters.idPw = ($("#service_idPw").length) ? $("#service_idPw").val() : null;
- return parameters;
- },
- ajaxGetForm: function (parameters) {
- $.ajax({
- type: "GET",
- url: Routing.generate('service.generate.form', parameters),
- success: function (html) {
- $("#service_form_aux").html(html);
- }
- });
- },
- initPir: function (metadata) {
- service.company.metadataPir = metadata;
- initValue = $("#" + metadata.id_hidden_pir).val();
- if (initValue != "") {
- var processValue = service.company.processPir(initValue);
- $("." + metadata.class_pir).each(function (i, element) {
- $(this).attr('name', '');
- $(this).val(processValue[i]);
- });
- }
- },
- watchPir: function () {
- metadataPir = service.company.metadataPir;
- $("." + metadataPir.class_pir).change(function () {
- var inputValues = [];
- $("." + metadataPir.class_pir).each(function () {
- inputValues.push($(this).val());
- });
- var hiddenValue = service.company.processPir(inputValues);
- $("#" + metadataPir.id_hidden_pir).val(hiddenValue);
- });
- },
- processPir: function (value) {
- separator = service.company.separator;
- if (Array.isArray(value)) {
- //Mergue interface values in the hidden field
- return value.join(separator);
- } else if (value != "") {
- //Split hidden value to a interface values
- return value.split(separator);
- } else {
- return array();
- }
- },
- watchNode: function (target_id, replace_id) {
- $(target_id).on('change', function (element) {
- var category_id = $('#service_category').val();
- service.company.getInterface($(this), category_id, replace_id);
- });
- },
- getInterface: function (idNode, category_id, target_id) {
- var parameters = new Object();
- parameters.idNode = idNode.val();
- parameters.category_id = category_id;
- if (typeof idNode.data('targetfield') !== 'undefined') {
- parameters.field_name = idNode.data('targetfield');
- }
- $.ajax({
- type: "GET",
- url: Routing.generate('service.load.interface', parameters),
- success: function (html) {
- $(target_id).replaceWith(html);
- }
- });
- },
- /*********************DISABLE FIELDS BY ACCESS TECNOLOGY ******************************/
- initAccessTecnology: function (origin, data, ModeAnd) {
- ModeAnd || (ModeAnd = false);
- var options = {'ModeAnd': ModeAnd, 'GenCredentials': false};
- var value = $(origin).val();
- if (value !== "") {
- service.company.controlStateFields($(origin + " option:selected").text(), data, options);
- }
- },
- watchAccessTecnology: function (origin, data, ModeAnd) {
- ModeAnd || (ModeAnd = false);
- var options = {'ModeAnd': ModeAnd, 'GenCredentials': true};
- $(origin).on('change', function () {
- if ($(this).val() !== "") {
- service.company.controlStateFields($(this).find("option:selected").text(), data, options);
- }
- });
- },
- controlStateFields: function (value, data, options) {
- if (service.company.isJSON(data)) {
- for (item in data) {
- var actions = {};
- if (data[item].hasOwnProperty('regexIndex')) {
- if (data[item].hasOwnProperty('idPrefix')) {
- actions.prefix = data[item]['idPrefix'];
- } else {
- actions.prefix = "";
- }
- var patt = new RegExp(data[item]['regexIndex']);
- if (patt.test(value)) {
- actions.enable = data[item]['ifIs']['enable'];
- actions.disable = data[item]['ifIsNot']['enable'];
- if (options.ModeAnd) {
- actions = service.company.andAction(true, data[item], actions);
- }
- if (options.GenCredentials) {
- if (actions.enable.indexOf("username") != "-1") {
- service.company.genUser({'mode': 'gen'});
- }
- if (actions.enable.indexOf("password") != "-1") {
- $(actions.prefix + 'password').val(service.company.genPassword(8));
- }
- }
- } else {
- actions.enable = data[item]['ifIsNot']['enable'];
- actions.disable = data[item]['ifIs']['enable'];
- if (options.ModeAnd) {
- actions = service.company.andAction(false, data[item], actions);
- }
- }
- }
- service.company.makeStatusActions(actions);
- }
- }
- },
- andAction: function (parent_status, data, actions) {
- var enable = Array.from(actions.enable);
- var disable = Array.from(actions.disable);
- if (parent_status) {
- // if(data['ifIs'].hasOwnProperty('AndConditions')){
- // var conditional = data['ifIs']['AndConditions'];
- // }
- if (data['ifIsNot'].hasOwnProperty('AndConditions')) {
- var conditional = data['ifIsNot']['AndConditions'];
- for (index in conditional) {
- disable.push(conditional[index]['target']);
- }
- }
- } else {
- if (data['ifIsNot'].hasOwnProperty('AndConditions')) {
- var conditional = data['ifIsNot']['AndConditions'];
- for (index in conditional) {
- value = $(data['idPrefix'] + index + " option:selected").text();
- comparative = conditional[index]['comparative'];
- if (comparative) {
- if (value == conditional[index]['value']) {
- enable.push(conditional[index]['target']);
- } else {
- disable.push(conditional[index]['target']);
- }
- } else {
- if (value != conditional[index]['value']) {
- enable.push(conditional[index]['target']);
- } else {
- disable.push(conditional[index]['target']);
- }
- }
- }
- }
- }
- actions.enable = enable;
- actions.disable = disable;
- return actions;
- },
- makeStatusActions: function (actions) {
- if (actions.prefix) {
- for (item in actions.disable) {
- $(actions.prefix + "" + actions.disable[item]).prop("disabled", true);
- }
- for (item in actions.enable) {
- var enabledElem = $(actions.prefix + "" + actions.enable[item]);
- enabledElem.prop("disabled", false);
- if (actions.enable[item] == "password" && enabledElem.val() == "") {
- enabledElem.val(service.company.genPassword(service.company.passwordLength));
- }
- }
- }
- },
- /*************************************************************/
- /*********************GESTION CPE*****************************/
- initGestionCPE: function (origin, target) {
- var value = $(origin).val();
- if (value == 1) {
- $(target).prop("disabled", false);
- } else {
- $(target).prop("disabled", true);
- }
- },
- watchGestionCPE: function (origin, target) {
- $(origin).on('change', function () {
- var value = $(this).val();
- if (value == 1) {
- $(target).prop("disabled", false);
- } else {
- $(target).prop("disabled", true);
- }
- });
- },
- /*********************************************************/
- initProfile: function (origin, target_class, prefix) {
- var text = $(origin).find("option:selected").text();
- var value = $(origin).val();
- if (text == "A medida" || value == "") {
- $(target_class).each(function (i, element) {
- if (value == "") {
- $(this).prop("readonly", true);
- } else {
- $(this).prop("readonly", false);
- }
- });
- } else {
- var percents = service.company.getPercents(value, prefix);
- $(target_class).each(function (i, element) {
- $(this).prop("readonly", true);
- });
- }
- },
- watchProfile: function (origin, target_class, prefix) {
- $(origin).on('change', function () {
- var text = $(this).find("option:selected").text();
- var value = $(this).val();
- if (text == "A medida" || value == "") {
- $(target_class).each(function (i, element) {
- $(this).prop("readonly", false);
- $(this).val('');
- });
- } else {
- var percents = service.company.getPercents(value, prefix);
- $(target_class).each(function (i, element) {
- $(this).prop("readonly", true);
- });
- }
- });
- },
- getPercents: function (profile_id, prefix) {
- var parameters = new Object();
- parameters.profile_id = profile_id;
- $.ajax({
- type: "GET",
- url: Routing.generate('service.profiles.get', parameters),
- success: function (response) {
- for (var property in response) {
- $("#" + prefix + property).val(response[property]);
- }
- }
- });
- },
- genPassword: function (longitud)
- {
- var password = "";
- $.ajax({
- type: "GET",
- async: false,
- url: Routing.generate('service.password.gen', {
- lengthPass: longitud
- }),
- success: function (response) {
- password = response;
- }
- });
- return password;
- },
- /*
- *
- * Format Inet: $servicecode_$ACT/BCK_$bw_$VoIP@masmovil-ggcc
- * Format VPN: $vrf_$sede_$ACT/BCK_$bw_$qos
- */
- genUser: function (options) {
- if (options.hasOwnProperty('mode')) {
- if (options.mode == "init" && options.hasOwnProperty('type')) {
- service.company.genUserOptions = options;
- } else {
- var type = service.company.genUserOptions.type;
- var user = new Array();
- for (index in type.originIds) {
- if (typeof type.originIds[index] === 'string') {
- var element = $(type.originIds[index]);
- if (service.company.getValueField(element)) {
- user.push(service.company.getValueField(element));
- }
- } else {
- var element = $(type.originIds[index].id);
- var textValue = type.originIds[index].textValue;
- var value = service.company.getValueField(element, textValue);
- if (type.originIds[index].hasOwnProperty('type')) {
- typeField = type.originIds[index].type;
- switch (typeField) {
- case 'checkbox':
- if (value) {
- var valueTrue = type.originIds[index].valueTrue
- if (valueTrue != "") {
- user.push(valueTrue);
- }
- } else {
- valueFalse = type.originIds[index].valueFalse;
- if (valueFalse != "") {
- user.push(valueFalse);
- }
- }
- break;
- case 'select':
- if (value == "A medida") {
- user.push('CUSTOM');
- } else if (value != "") {
- user.push(value);
- }
- break;
- }
- } else {
- }
- }
- }
- var initOptions = service.company.genUserOptions;
- if (initOptions.hasOwnProperty('target') && initOptions.target != "") {
- var out = user.join(initOptions.separator);
- $(initOptions.target).val(out);
- }
- }
- }
- },
- /***********************************************************/
- tagsInput: function (origin) {
- $(origin).tagsinput();
- $(".bootstrap-tagsinput input").attr('placeholder', '999.999.999.999/99');
- $(origin).on('beforeItemAdd', function (event) {
- var regexIpLen = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$/;
- if (!regexIpLen.test(event.item)) {
- var error = {
- 'title': 'Atención.',
- 'error': 'Formato de prefijo incorrecto (IP/Len). ',
- };
- masmovil.form.fail(false, error.title, error.error);
- event.cancel = true;
- }
- // event.item: contains the item
- // event.cancel: set to true to prevent the item getting added
- // event.cancel = true;
- });
- },
- /***********************************************************/
- getValueField: function (element, textValue) {
- textValue || (textValue = false);
- var tag = element.prop("tagName");
- switch (tag) {
- case 'SELECT':
- if (element.val() != "") {
- if (textValue) {
- return element.find("option:selected").text();
- } else {
- return element.val();
- }
- }
- return false;
- break;
- case 'INPUT':
- type = element.attr('type');
- switch (type) {
- case 'hidden':
- case 'text':
- case 'number':
- if (element.val() != "") {
- return element.val();
- }
- return false;
- break;
- case 'checkbox':
- return element.prop('checked');
- break;
- }
- break;
- }
- return null;
- },
- isJSON: function (item) {
- item = typeof item !== "string"
- ? JSON.stringify(item)
- : item;
- try {
- item = JSON.parse(item);
- } catch (e) {
- return false;
- }
- if (typeof item === "object" && item !== null) {
- return true;
- }
- return false;
- },
- hasJSONProperty: function (index, object) {
- for (item in object) {
- if (object[item].hasOwnProperty('regexIndex')) {
- var patt = new RegExp(object[item]['regexIndex']);
- if (patt.test(index)) {
- return object[item];
- } else {
- return false;
- }
- } else {
- if (object.hasOwnProperty(item)) {
- return object.hasOwnProperty(item);
- } else {
- return false;
- }
- }
- }
- },
- };
- })(jQuery);
Add Comment
Please, Sign In to add comment