Redesign alert template modal (#9364)

* Redesign alert template modal

* Check if alert is used in an other template

* Fix selectbox while creating new template

* Use 'pre' font family for alert template textarea

* Remove limit

* Remove and try to mimic bootstrap-select with select2 lib
This commit is contained in:
CrazyMax
2018-10-25 22:31:12 +02:00
committed by Tony Murray
parent 47557cb8dc
commit 00b752a862
9 changed files with 133 additions and 303 deletions

View File

@@ -33,44 +33,29 @@ if (!LegacyAuth::user()->hasGlobalAdmin()) {
}
$template_id = 0;
$template_newid = 0;
$create = true;
$name = mres($vars['name']);
if (isset($vars['template']) && empty(view(['template' => $vars['template']], [])->__toString())) {
$message = 'Template failed to be parsed, please check the syntax';
} elseif (!empty($name)) {
if ((isset($vars['template_id']) && is_numeric($vars['template_id'])) && (isset($vars['rule_id']) && $vars['rule_id'])) {
//Update the template/rule mapping
if (is_array($vars['rule_id'])) {
$vars['rule_id'] = implode(",", $vars['rule_id']);
}
if (substr($vars['rule_id'], 0, 1) != ",") {
$vars['rule_id'] = ",".$vars['rule_id'];
}
if (substr($vars['rule_id'], -1, 1) != ",") {
$vars['rule_id'] .= ",";
}
if (dbUpdate(array('rule_id' => mres($vars['rule_id']), 'name' => $name), "alert_templates", "id = ?", array($vars['template_id'])) >= 0) {
$message = "Updated template and rule id mapping";
} else {
$message ="Failed to update the template and rule id mapping";
}
} elseif ($vars['template'] && is_numeric($vars['template_id'])) {
//Update template-text
if (dbUpdate(array('template' => $vars['template'], 'name' => $name, 'title' => $vars['title'], 'title_rec' => $vars['title_rec']), "alert_templates", "id = ?", array($vars['template_id'])) >= 0) {
if ($vars['template'] && is_numeric($vars['template_id'])) {
// Update template
$create = false;
$template_id = $vars['template_id'];
if (!dbUpdate(array('template' => $vars['template'], 'name' => $name, 'title' => $vars['title'], 'title_rec' => $vars['title_rec']), "alert_templates", "id = ?", array($template_id)) >= 0) {
$status = 'ok';
$message = "Alert template updated";
} else {
$message = "Failed to update the template";
}
} elseif ($vars['template']) {
//Create new template
// Create template
if ($name != 'Default Alert Template') {
$template_id = dbInsert(array('template' => $vars['template'], 'name' => $name, 'title' => $vars['title'], 'title_rec' => $vars['title_rec']), "alert_templates");
if ($template_id != false) {
$template_newid = dbInsert(array('template' => $vars['template'], 'name' => $name, 'title' => $vars['title'], 'title_rec' => $vars['title_rec']), "alert_templates");
if ($template_newid != false) {
$template_id = $template_newid;
$status = 'ok';
$message = "Alert template has been created.";
} else {
$message = "Could not create alert template";
}
@@ -80,10 +65,29 @@ if (isset($vars['template']) && empty(view(['template' => $vars['template']], []
} else {
$message = "We could not work out what you wanted to do!";
}
if ($status == 'ok') {
$alertRulesOk = true;
dbDelete('alert_template_map', 'alert_templates_id = ?', array($template_id));
$rules = explode(',', $vars['rules']);
if ($rules !== false) {
foreach ($rules as $rule_id) {
if (!dbInsert(array('alert_rule_id' => $rule_id, 'alert_templates_id' => $template_id), 'alert_template_map')) {
$alertRulesOk = false;
}
}
}
if ($alertRulesOk) {
$status = 'ok';
$message = 'Alert template has been ' . ($create ? 'created' : 'updated') . ' and attached rules have been updated.';
} else {
$status = 'warning';
$message = 'Alert template has been ' . ($create ? 'created' : 'updated') . ' but some attached rules have not been updated.';
}
}
} else {
$message = "You haven't given your template a name, it feels sad :( - $name";
$message = "You haven't given name to your template";
}
$response = array('status' => $status, 'message' => $message, 'newid' => $template_id);
$response = array('status' => $status, 'message' => $message, 'newid' => $template_newid);
echo _json_encode($response);

View File

@@ -1,73 +0,0 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
if (!LegacyAuth::user()->hasGlobalAdmin()) {
$response = array(
'status' => 'error',
'message' => 'Need to be admin',
);
echo _json_encode($response);
exit;
}
$status = 'error';
$message = 'Ops. Something happened. Enable debug and check librenms.log';
set_debug(true);
if (!is_numeric($_POST['template_id'])) {
$message = 'ERROR: No template selected';
} else {
$rules = preg_split('/,/', $_POST['rule_id']);
$ids = [];
foreach (dbFetchRows('SELECT `alert_rule_id` FROM `alert_template_map` WHERE `alert_templates_id` = ?', array($_POST['template_id'])) as $rule) {
$old_rules[] = $rule['alert_rule_id'];
}
foreach ($rules as $rule_id) {
$db_id = dbInsert(array('alert_rule_id' => $rule_id, 'alert_templates_id' =>$_POST['template_id']), 'alert_template_map');
if ($db_id > 0) {
$ids[] = $db_id;
$new_rules[] = $rule_id;
} else {
$status = 'error';
$message = 'Alert rules have not been attached to this template.';
}
}
if (!empty($ids)) {
dbDelete('alert_template_map', 'id NOT IN ' . dbGenPlaceholders(count($ids)) . ' AND alert_templates_id =?', array_merge($ids, [$_POST['template_id']]));
$status = 'ok';
$message = "Alert rules have been attached to this template.";
}
}//end if
//$old_rules = array_diff($old_rules, $new_rules);
foreach ($old_rules as $rule) {
$rule_name[] = dbFetchCell("SELECT `name` FROM `alert_rules` WHERE `id` = ". $rule);
}
foreach ($new_rules as $template) {
$template_name[] = dbFetchCell("SELECT `name` FROM `alert_templates` WHERE `id` = ". $_POST['template_id']);
$nrule_name[] = dbFetchCell("SELECT `name` FROM `alert_rules` WHERE `id` = ". $template);
}
$response = array(
'status' => $status,
'message' => $message,
'new_rules' => $new_rules,
'nrule_name' => $nrule_name,
'old_rules' => $old_rules,
'rule_name' => $rule_name,
'template_name' => $template_name
);
echo _json_encode($response);

View File

@@ -28,6 +28,7 @@ if (!is_numeric($vars['alert_id'])) {
dbDelete('alert_device_map', 'rule_id=?', [$vars['alert_id']]);
dbDelete('alert_group_map', 'rule_id=?', [$vars['alert_id']]);
dbDelete('alert_transport_map', 'rule_id=?', [$vars['alert_id']]);
dbDelete('alert_template_map', 'alert_rule_id=?', [$vars['alert_id']]);
echo 'Alert rule has been deleted.';
exit;
} else {

View File

@@ -25,6 +25,7 @@ if (!is_numeric($_POST['template_id'])) {
exit;
} else {
if (dbDelete('alert_templates', '`id` = ?', array($_POST['template_id']))) {
dbDelete('alert_template_map', 'alert_templates_id = ?', array($_POST['template_id']));
echo 'Alert template has been deleted.';
exit;
} else {

View File

@@ -19,17 +19,41 @@ if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}
$template_id = ($vars['template_id']);
$template_id = $vars['template_id'];
$template_edit = is_numeric($template_id) && $template_id > 0;
if (is_numeric($template_id) && $template_id > 0) {
$template = dbFetchRow('SELECT * FROM `alert_templates` WHERE `id` = ? LIMIT 1', array($template_id));
$output = array(
$rules = [];
$output = array(
'template' => '',
'name' => '',
'title' => '',
'title_rec' => '',
'type' => '',
'rules' => $rules,
);
if ($template_edit) {
$template = dbFetchRow('SELECT * FROM `alert_templates` WHERE `id` = ? LIMIT 1', [$template_id]);
$output = [
'template' => $template['template'],
'name' => $template['name'],
'title' => $template['title'],
'title_rec' => $template['title_rec'],
'type' => $template['type'],
);
header('Content-type: application/json');
echo _json_encode($output);
'type' => $template['type']
];
}
foreach (dbFetchRows("SELECT `id`,`rule`,`name` FROM `alert_rules`", []) as $rule) {
$is_selected = $template_edit ? dbFetchCell("SELECT `alert_templates_id` FROM `alert_template_map` WHERE `alert_rule_id` = ? AND `alert_templates_id` = ?", [$rule['id'], $template_id]) : null;
$is_available = dbFetchCell("SELECT `alert_templates_id` FROM `alert_template_map` WHERE `alert_rule_id` = ?", [$rule['id']]);
$rules[] = [
'id' => $rule['id'],
'name' => $rule['name'],
'selected' => isset($is_selected),
'used' => isset($is_available) ? dbFetchCell("SELECT `name` FROM `alert_templates` WHERE `id` = ?", [$is_available]) : '',
];
}
$output['rules'] = $rules;
header('Content-type: application/json');
echo _json_encode($output);

View File

@@ -1,32 +0,0 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
use LibreNMS\Authentication\LegacyAuth;
if (!LegacyAuth::user()->hasGlobalAdmin()) {
header('Content-type: text/plain');
die('ERROR: You need to be admin');
}
$template_id = ($_POST['template_id']);
if (is_numeric($template_id) && $template_id > 0) {
foreach (dbFetchRows('SELECT `alert_rule_id` FROM `alert_template_map` WHERE `alert_templates_id` = ?', array($template_id)) as $rule) {
$rules[] = $rule['alert_rule_id'];
}
$output = array('rule_id' => $rules);
header('Content-type: application/json');
echo _json_encode($output);
}

View File

@@ -35,7 +35,11 @@ if (!LegacyAuth::user()->hasGlobalAdmin()) {
</div>
<div class="form-group">
<label for="template">Template: </label>
<textarea class="form-control" id="template" name="template" rows="15"></textarea>
<textarea class="form-control" id="template" name="template" style="font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;" rows="15"></textarea>
</div>
<div class="form-group">
<label for="rules_list">Attach template to rules: </label>
<select id="rules_list" name="rules_list[]" class="form-control" multiple="multiple"></select>
</div>
<div class="form-group">
<label for="title">Alert title: </label>
@@ -53,8 +57,8 @@ if (!LegacyAuth::user()->hasGlobalAdmin()) {
</div>
</div>
</div>
<script>
<script type="text/javascript">
$('#alert-template').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var template_id = $('#template_id').val();
@@ -66,23 +70,55 @@ $('#alert-template').on('show.bs.modal', function (event) {
$('#name').prop("disabled",true);
}
$('#create-template').text('Update template');
$.ajax({
type: "POST",
url: "ajax_form.php",
data: { type: "parse-alert-template", template_id: template_id },
dataType: "json",
success: function(output) {
$('#template').val(output['template']);
$('#name').val(output['name']);
$('#title').val(output['title']);
$('#title_rec').val(output['title_rec']);
if(output['template'].indexOf("{/if}")>=0){
toastr.info('The old template syntax is no longer supported. Please see https://docs.librenms.org/Alerting/Old_Templates/');
$('#convert-template').show();
}
}
});
}
$.ajax({
type: "POST",
url: "ajax_form.php",
data: { type: "parse-alert-template", template_id: template_id },
dataType: "json",
success: function(output) {
$('#template').val(output['template']);
$('#name').val(output['name']);
$('#title').val(output['title']);
$('#title_rec').val(output['title_rec']);
var selected_rules = [];
$.each(output.rules, function(i, rule) {
var ruleElem = $('<option>', {
value: rule.id,
text : rule.name
}).attr('data-usedby', '');
if (rule.selected) {
selected_rules.push(parseInt(rule.id));
} else if (rule.used !== '') {
ruleElem.attr('data-usedby', rule.used).prop("disabled", true);
}
$('#rules_list').append(ruleElem);
});
$('#rules_list').select2({
theme: "bootstrap",
dropdownAutoWidth : true,
width: "auto",
allowClear: true,
placeholder: "Nothing selected",
templateResult: function(data) {
if (data.id && data.element.dataset.usedby !== '') {
return $(
'<span>' + data.text + ' <span class="label label-default">Used in template "' + data.element.dataset.usedby + '"</span></span>'
);
} else if (data.id && data.selected) {
return $(
'<span><i class="fa fa-check"></i> ' + data.text + '</span>'
);
}
return data.text;
}
}).val(selected_rules).trigger("change");
if(output['template'].indexOf("{/if}")>=0){
toastr.info('The old template syntax is no longer supported. Please see https://docs.librenms.org/Alerting/Old_Templates/');
$('#convert-template').show();
}
}
});
});
$('#alert-template').on('hide.bs.modal', function(event) {
@@ -91,6 +127,7 @@ $('#alert-template').on('hide.bs.modal', function(event) {
$('#line').val('');
$('#value').val('');
$('#name').val('');
$('#rules_list').find('option').remove().end().select2('destroy');
$('#create-template').text('Create template');
$('#default-template').val('0');
$('#reset-default').remove();
@@ -101,12 +138,19 @@ $('#alert-template').on('hide.bs.modal', function(event) {
$('#create-template').click('', function(e) {
e.preventDefault();
var rules_items = [];
$('#rules_list :selected').each(function(i, selectedElement) {
rules_items.push($(selectedElement).val());
});
var template = $("#template").val();
var template_id = $("#template_id").val();
var name = $("#name").val();
var title = $("#title").val();
var title_rec = $("#title_rec").val();
alertTemplateAjaxOps(template, name, template_id, title, title_rec);
alertTemplateAjaxOps(template, name, template_id, title, title_rec, rules_items.join(','));
});
$('#convert-template').click('', function(e) {
@@ -134,24 +178,20 @@ $('#convert-template').click('', function(e) {
});
});
function alertTemplateAjaxOps(template, name, template_id, title, title_rec)
{
function alertTemplateAjaxOps(template, name, template_id, title, title_rec, rules) {
$.ajax({
type: "POST",
url: "ajax_form.php",
data: { type: "alert-templates", template: template, name: name, template_id: template_id, title: title, title_rec: title_rec},
data: { type: "alert-templates", template: template, name: name, template_id: template_id, title: title, title_rec: title_rec, rules: rules},
dataType: "json",
success: function(output) {
console.log(output);
if(output.status == 'ok') {
toastr.success(output.message);
$("#alert-template").modal('hide');
if(template_id != null && template_id != '') {
$('#templatetable tbody tr').each(function (i, row) {
if ($(row).children().eq(0).text() == template_id) {
$(row).children().eq(1).text(name);
// We found our match so stop looping through the table
return false;
}
});
@@ -167,7 +207,5 @@ function alertTemplateAjaxOps(template, name, template_id, title, title_rec)
toastr.error('An error occurred updating this alert template.');
}
});
}
</script>

View File

@@ -1,129 +0,0 @@
<?php
/*
* LibreNMS
*
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
* Copyright (c) 2018 TheGreatDoc <https://github.com/thegreatdoc/>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
use LibreNMS\Authentication\LegacyAuth;
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}
?>
<div class="modal fade" id="attach-alert-template" tabindex="-1" role="dialog" aria-labelledby="Attach" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h5 class="modal-title" id="Attach">Attach template to rules...</h5>
</div>
<div class="modal-body">
<p>Please select the rules that you would like to assign this template to.</p>
<form class="form-group">
<div class="form-group">
<label for="rules_list">Select rules</label>
<select multiple="multiple" class="form-control" id="rules_list" name="rules_list" size="10">
<option>--Clear Rules--</option>
<?php
foreach (dbFetchRows("SELECT `id`,`rule`,`name` FROM `alert_rules`", array()) as $rule) {
$is_avail = dbFetchCell("SELECT `alert_templates_id` FROM `alert_template_map` WHERE `alert_rule_id` = ?", [$rule['id']]);
if (!isset($is_avail)) {
echo '<option value="' . $rule['id'] . '">' . $rule['name'] . '</option>';
} else {
$template = dbFetchCell("SELECT `name` FROM `alert_templates` WHERE `id` = ?", [$is_avail]);
echo '<option value="' . $rule['id'] . '" disabled>' . $rule['name'] . ' - Used in template: ' . $template . '</option>';
}
}
?>
</select>
</div>
</form>
<span id="template_error"></span><br />
</div>
<div class="modal-footer">
<form role="form" class="attach_rule_form">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger danger" id="alert-template-attach" data-target="alert-template-attach">Attach</button>
<input type="hidden" name="template_id" id="template_id" value="">
<input type="hidden" name="confirm" id="confirm" value="yes">
</form>
</div>
</div>
</div>
</div>
<script>
$('#attach-alert-template').on('show.bs.modal', function(e) {
var template_id = $('#template_id').val();
$.ajax({
type: "POST",
url: "ajax_form.php",
data: { type: "parse-template-rules", template_id: template_id },
dataType: "json",
success: function(output) {
selected_items = [];
$.each( output.rule_id, function( i, elem) {
elem = parseInt(elem);
selected_items.push(elem);
$("#rules_list option[value='"+ elem + "']").attr('disabled', false);
});
$('#rules_list').val(selected_items);
}
});
});
$('#attach-alert-template').on('hide.bs.modal', function(e) {
$('#rules_list').val([]);
$('template_id').val('');
});
$('#alert-template-attach').click('', function(event) {
event.preventDefault();
var template_id = $("#template_id").val();
var items = [];
$('#rules_list :selected').each(function(i, selectedElement) {
items.push($(selectedElement).val());
});
var rules = items.join(',');
$.ajax({
type: 'POST',
url: 'ajax_form.php',
data: { type: "attach-alert-template", template_id: template_id, rule_id: rules },
dataType: "json",
success: function(data) {
if (data.status == 'ok') {
toastr.success(data.message);
$("#attach-alert-template").modal('hide');
$.each( data.old_rules, function(index, itemData){
if (itemData != "--Clear Rules--") {
$("#rules_list option[value=" + itemData + "]").prop('disabled', false).text(data.rule_name[index]);
}
});
$.each( data.new_rules, function(index, itemData){
if (itemData != "--Clear Rules--") {
$("#rules_list option[value=" + itemData + "]").prop('disabled', true).text(data.nrule_name[index] + ' - Used in template:' + data.template_name[index]);
}
});
} else {
//$('#template_error').html('<div class="alert alert-danger">'+msg+'</div>');
toastr.error(data.message);
}
},
error: function(data) {
//$("#template_error").html('<div class="alert alert-danger">The alert rules could not be attached to this template.</div>');
toastr.error(data.message);
}
});
});
</script>

View File

@@ -6,7 +6,6 @@ $no_refresh = true;
require_once 'includes/modal/alert_template.inc.php';
require_once 'includes/modal/delete_alert_template.inc.php';
require_once 'includes/modal/attach_alert_template.inc.php';
?>
<div class="table-responsive">
<table id="templatetable" class="table table-hover table-condensed" width="100%">
@@ -64,9 +63,9 @@ $(document).ready(function() {
"commands": function(column, row) {
var response = '';
if(row.id == 0) {
response = "<button type=\"button\" class=\"btn btn-xs btn-primary command-edit\" data-toggle='modal' data-target='#alert-template' data-template_id=\"" + row.id + "\" data-template_action='edit' name='edit-alert-template'><i class=\"fa fa-pencil\" aria-hidden=\"true\"></i></button> " + "<button type=\"button\" class=\"btn btn-xs btn-danger command-delete\" disabled=\"disabled\"><i class=\"fa fa-trash-o\" aria-hidden=\"true\"></i></button> " + "<button type='button' class='btn btn-warning btn-xs command-attach' disabled=\"disabled\"><i class='fa fa-th-list' aria-hidden='true'></i></button>";
response = "<button type=\"button\" class=\"btn btn-xs btn-primary command-edit\" data-toggle='modal' data-target='#alert-template' data-template_id=\"" + row.id + "\" data-template_action='edit' name='edit-alert-template'><i class=\"fa fa-pencil\" aria-hidden=\"true\"></i></button> " + "<button type=\"button\" class=\"btn btn-xs btn-danger command-delete\" disabled=\"disabled\"><i class=\"fa fa-trash-o\" aria-hidden=\"true\"></i></button>";
} else {
response = "<button type=\"button\" class=\"btn btn-xs btn-primary command-edit\" data-toggle='modal' data-target='#alert-template' data-template_id=\"" + row.id + "\" data-template_action='edit' name='edit-alert-template'><i class=\"fa fa-pencil\" aria-hidden=\"true\"></i></button> " + "<button type=\"button\" class=\"btn btn-xs btn-danger command-delete\" data-toggle=\"modal\" data-target='#confirm-delete-alert-template' data-template_id=\"" + row.id + "\" name='delete-alert-template'><i class=\"fa fa-trash-o\" aria-hidden=\"true\"></i></button> " + "<button type='button' class='btn btn-warning btn-xs command-attach' data-toggle='modal' data-target='#attach-alert-template' data-template_id='" + row.id + "' name='attach-alert-template'><i class='fa fa-th-list' aria-hidden='true'></i></button>";
response = "<button type=\"button\" class=\"btn btn-xs btn-primary command-edit\" data-toggle='modal' data-target='#alert-template' data-template_id=\"" + row.id + "\" data-template_action='edit' name='edit-alert-template'><i class=\"fa fa-pencil\" aria-hidden=\"true\"></i></button> " + "<button type=\"button\" class=\"btn btn-xs btn-danger command-delete\" data-toggle=\"modal\" data-target='#confirm-delete-alert-template' data-template_id=\"" + row.id + "\" name='delete-alert-template'><i class=\"fa fa-trash-o\" aria-hidden=\"true\"></i></button>";
}
return response;
}
@@ -86,9 +85,6 @@ $(document).ready(function() {
}).end().find(".command-delete").on("click", function(e) {
$('#template_id').val($(this).data("template_id"));
$('#confirm-delete-alert-template').modal('show');
}).end().find(".command-attach").on("click", function(e) {
$('#template_id').val($(this).data("template_id"));
$('#attach-alert-template').modal('show');
});
});
});