daster/js/script.js

692 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var numbers = [];
var sms = [];
var ussd = [];
$(document).ready(function () {
noticer = new Noticer;
let tabs = {
0: () => { loadNumbers() },
1: () => { loadSMS() },
2: () => { loadUSSD() },
3: () => { loadServerInfo() }
};
let lists = {
0: () => { showListNumbers($("#accordion-numbers .ui-accordion-content-active")) },
1: () => { showListSMS($("#accordion-sms .ui-accordion-content-active")) },
2: () => { showListUSSD($("#accordion-ussd .ui-accordion-content-active")) },
3: () => {}
};
let groups = {
0: () => { generateListGroupNumbers($("#accordion-numbers .ui-accordion-content-active")) },
1: () => { generateListGroupSMS($("#accordion-sms .ui-accordion-content-active")) },
2: () => { generateListGroupUSSD($("#accordion-ussd .ui-accordion-content-active")) },
3: () => {}
};
$("button").button();
$("#update-tab").button("option", "icon", "ui-icon-refresh");
$("#update-group").button("option", "icon", "ui-icon-arrowrefresh-1-s");
$("#add-number").button("option", "icon", "ui-icon-plusthick");
$("#logout").button("option", "icon", "ui-icon-power");
$("#tabs").tabs({
activate: function( event, ui ) {
lists[$(this).tabs( "option", "active" )]();
$("#add-number").button( "option", "disabled", $(this).tabs( "option", "active" ) > 0 );
$("#update-group").button( "option", "disabled", $(this).tabs( "option", "active" ) > 2 );
}
});
$("#update-tab").click(() => {
tabs[$("#tabs").tabs( "option", "active" )]()
});
$("#update-group").click(() => {
groups[$("#tabs").tabs( "option", "active" )]()
});
$("#add-number").click(() => {
addNumber($("#accordion-numbers .ui-accordion-content-active"))
});
$("#search").on("input", function () {
lists[$("#tabs").tabs( "option", "active" )]()
}).keydown(function (e) {
e.key == "Escape" && ($(this).val(""), lists[$("#tabs").tabs( "option", "active" )]())
});
$("#logout").click(() => {
request('logout', 'json').then(data => {
data.error ? noticer.error(data.message) : (window.location.href = ".");
}).catch(error => {
noticer.error(error.message);
});
});
loadNumbers();
loadSMS();
loadUSSD();
loadServerInfo();
$("body").fadeTo(500, 1);
})
async function request(query, type, queryData = {}) {
let response = await fetch('.', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({
...queryData,
query: query
})
});
if (!response.ok)
throw new Error(`Произошла неизвестаня ошибка: ${response.status}`);
const data = await response[type]();
return data;
}
function isJSON(str) {
try {
return (JSON.parse(str) && !!str);
} catch (e) {
return false;
}
}
function isNumeric(value) {
return /^-?\d+$/.test(value);
}
function divNotFoundNumbers(text = '') {
let notFound = $('.notFoundNumbers');
let divTable = $('.body-rows');
let divNotFound = $(`<div class="notFoundNumbers">${text}</div>`);
divNotFound.css({
"color": "#333",
"text-align": "center",
"padding": "20px 0 20px 0"
});
this.push = function() {
divTable.append(divNotFound);
}
this.remove = function() {
notFound.remove();
}
}
function pEmpty(text) {
return $(`<p>${text}</p>`).css('text-align', 'center');
}
/************************************************************************************
Обработка таблицы с номерами телефонов
************************************************************************************/
function loadNumbers() {
request('listnumbergroups', 'text').then(data => {
if (isJSON(data) && JSON.parse(data).error)
noticer.error(JSON.parse(data).message);
else
generateListNumberGroups(data);
}).catch(error => {
noticer.error(error.message);
});
}
function generateListNumberGroups(data) {
if (!$(data).children().length) {
$("#tabs-numbers").html(pEmpty('Номера телефонов отсутствуют'));
return;
}
$("#tabs-numbers").html(data);
$("#accordion-numbers").accordion({
heightStyle: "content",
create: function( event, ui ) {
generateListGroupNumbers(ui.panel);
},
beforeActivate: function( event, ui ) {
generateListGroupNumbers(ui.newPanel);
}
});
}
function generateListGroupNumbers(panel) {
if (!$("#accordion-numbers").children().length) {
noticer.warning("Номера телефонов отсутствуют");
$("#tabs-numbers").html(pEmpty('Номера телефонов отсутствуют'));
return;
}
request('listgroupnumbers', 'json', { group: panel.data("group-name") }).then(data => {
if (data.error)
noticer.error(data.message);
else {
numbers = data;
showListNumbers(panel);
}
}).catch(error => {
noticer.error(error.message);
});
}
function showListNumbers(panel, data = numbers.filter(e => e.number.includes($("#search").val()))) {
(new divNotFoundNumbers).remove();
let body = panel.find('.body').html('');
$(data).each((i, j) => {
let row = $(`<tr class="row" data-number="${j.number}"></tr>`);
row.append(`<td>${j.number}</td>`);
row.append(`<td>${j.list}</td>`);
row.append(`<td>${j.all_cc}</td>`);
row.append(`<td>${j.white_cc}</td>`);
row.append(`<td>${j.black_cc}</td>`);
row.append(`<td>${j.comment}</td>`);
body.append(row);
row.click(function() {
viewNumber(panel, $(this).data('number'));
});
});
if (!body.children().length)
(new divNotFoundNumbers('Нет номеров')).push();
}
function viewNumber(panel, number) {
request('viewnumber', 'text', {number: number}).then(data => {
if (isJSON(data) && JSON.parse(data).error)
noticer.error(JSON.parse(data).message);
else {
showViewNumber(data, [
{
id: "btn-save",
text: "Сохранить",
icon: "ui-icon-check",
click: function() {
actionNumber(panel, $(this), 'updatenumber');
}
},
{
id: "btn-delete",
text: "Удалить",
icon: "ui-icon-trash",
click: function() {
delNumber(panel, $(this));
}
}
], `Редактирование номера ${number}`);
}
}).catch(error => {
noticer.error(error.message);
});
}
function showViewNumber(data, actionButton, title) {
let form = $(data);
form.appendTo('body').dialog({
title: title,
height: 'auto',
width: 'auto',
resizable: false,
modal: true,
show: { effect: "fade", duration: 500 },
close: function(event, ui) {
$(this).dialog('destroy').remove()
},
buttons: [
...actionButton,
{
text: "Отмена",
icon: "ui-icon-cancel",
click: function() {
$(this).dialog("close");
}
}
]
});
$('#number-group, #number-list').selectmenu({
width: 200
});
}
function actionNumber(panel, currentWindow, query) {
let pattern_number = /^\+7\d{10}$/g;
let number = $('#number-number').val();
let group = $('#number-group').val();
let list = $('#number-list').val();
let all_cc = $('#number-all-cc').val();
let white_cc = $('#number-white-cc').val();
let black_cc = $('#number-black-cc').val();
let comment = $('#number-comment').val();
let error = false;
if (number.match(pattern_number) === null) { noticer.warning("Номер не соответствует формату +7XXXXXXXXXX"); error = true; }
if (!isNumeric(all_cc)) { noticer.warning("Общее количество звонков должно быть числом"); error = true; }
if (all_cc < 0) { noticer.warning("Общее количество звонков не может быть отрицательным"); error = true; }
if (!isNumeric(white_cc)) { noticer.warning("Белое количество звонков должно быть числом"); error = true; }
if (white_cc < 0) { noticer.warning("Белое количество звонков не может быть отрицательным"); error = true; }
if (!isNumeric(black_cc)) { noticer.warning("Черное количество звонков должно быть числом"); error = true; }
if (black_cc < 0) { noticer.warning("Черное количество звонков не может быть отрицательным"); error = true; }
if (error) return;
request(query, 'json', {
number: number,
group: group,
list: list,
all_cc: parseInt(all_cc),
white_cc: parseInt(white_cc),
black_cc: parseInt(black_cc),
comment: comment
}).then(data => {
if (data.error)
noticer.error(data.message);
else
{
query == 'write' ? noticer.success(`Номер ${number} был добавлен`) : noticer.success(`Номер ${number} был обновлен`);
generateListGroupNumbers(panel);
currentWindow.dialog("close");
}
}).catch(error => {
noticer.error(error.message);
});
}
function addNumber(panel) {
request('addnumber', 'text', { group: panel.data("group-name") }).then(data => {
if (isJSON(data) && JSON.parse(data).error)
noticer.error(JSON.parse(data).message);
else {
showViewNumber(data, [{
id: "btnSave",
text: "Добавить",
icon: "ui-icon-check",
click: function() {
actionNumber(panel, $(this), 'writenumber');
}
}], "Добавление нового номера");
}
}).catch(error => {
noticer.error(error.message);
});
}
function delNumber(panel, currentWindow) {
let number = $('#number-number').val();
let error = false;
if (!number.length) { noticer.warning('Номер не может быть пуст'); error = true; }
if (error) return;
request('delnumber', 'json', {
number: number
}).then(data => {
if (data.error)
noticer.error(data.message);
else {
noticer.success(`Номер ${number} был удален`);
generateListGroupNumbers(panel);
currentWindow.dialog("close");
}
}).catch(error => {
noticer.error(error.message);
});
}
/************************************************************************************
Обработка таблицы с SMS
************************************************************************************/
function loadSMS() {
request('listsmsgroups', 'text').then(data => {
if (isJSON(data) && JSON.parse(data).error)
noticer.error(JSON.parse(data).message);
else
generateListSMSGroups(data);
}).catch(error => {
noticer.error(error.message);
});
}
function generateListSMSGroups(data) {
if (!$(data).children().length) {
$("#tabs-sms").html(pEmpty('SMS отсутствуют'));
return;
}
$("#tabs-sms").html(data);
$("#accordion-sms").accordion({
heightStyle: "content",
create: function( event, ui ) {
generateListGroupSMS(ui.panel);
},
beforeActivate: function( event, ui ) {
generateListGroupSMS(ui.newPanel);
}
})
}
function generateListGroupSMS(panel) {
if (!$("#accordion-sms").children().length) {
noticer.warning("SMS отсутствуют");
$("#tabs-sms").html(pEmpty('SMS отсутствуют'));
return;
}
request('listgroupsms', 'json', { to: panel.data("to") }).then(data => {
if (data.error)
noticer.error(data.message);
else {
sms = data;
showListSMS(panel);
}
}).catch(error => {
noticer.error(error.message);
});
}
function showListSMS(panel, data = sms.filter(e => e.from.includes($("#search").val()))) {
(new divNotFoundNumbers).remove();
let body = panel.find('.body').html('');
$(data).each((i, j) => {
let row = $(`<tr class="row" data-sms-id="${j.id}"></tr>`);
row.append(`<td class="sms-content-width">${j.date}</td>`);
row.append(`<td class="sms-content-width">${j.from}</td>`);
row.append(`<td>${j.text}</td>`);
body.append(row);
row.click(function() {
viewSMS(panel, $(this).data('sms-id'), j.from);
});
});
if (!body.children().length)
(new divNotFoundNumbers('Нет SMS')).push();
}
function viewSMS(panel, id, number) {
request('viewsms', 'text', {id: id}).then(data => {
if (isJSON(data) && JSON.parse(data).error)
noticer.error(JSON.parse(data).message);
else {
showViewSMS(data, [
{
id: "btn-delete",
text: "Удалить",
icon: "ui-icon-trash",
click: function() {
delSMS(panel, $(this));
}
}
], `SMS от ${number}`);
}
}).catch(error => {
noticer.error(error.message);
});
}
function showViewSMS(data, actionButton, title) {
let form = $(data);
form.appendTo('body').dialog({
title: title,
height: 'auto',
width: 'auto',
resizable: false,
modal: true,
show: { effect: "fade", duration: 500 },
close: function(event, ui) {
$(this).dialog('destroy').remove()
},
buttons: [
...actionButton,
{
text: "Отмена",
icon: "ui-icon-cancel",
click: function() {
$(this).dialog("close");
}
}
]
});
}
function delSMS(panel, currentWindow) {
let id = $('#sms-content').data('id');
let from = $('#sms-content').data('from');
request('delsms', 'json', {
id: id
}).then(data => {
if (data.error)
noticer.error(data.message);
else {
noticer.success(`SMS от ${from} было удалено`);
generateListGroupSMS(panel);
currentWindow.dialog("close");
}
}).catch(error => {
noticer.error(error.message);
});
}
/************************************************************************************
Обработка таблицы с USSD
************************************************************************************/
function loadUSSD() {
request('listussdgroups', 'text').then(data => {
if (isJSON(data) && JSON.parse(data).error)
noticer.error(JSON.parse(data).message);
else
generateListUSSDGroups(data);
}).catch(error => {
noticer.error(error.message);
});
}
function generateListUSSDGroups(data) {
if (!$(data).children().length) {
$("#tabs-ussd").html(pEmpty('USSD отсутствуют'));
return;
}
$("#tabs-ussd").html(data);
$("#accordion-ussd").accordion({
heightStyle: "content",
create: function( event, ui ) {
generateListGroupUSSD(ui.panel);
},
beforeActivate: function( event, ui ) {
generateListGroupUSSD(ui.newPanel);
}
})
}
function generateListGroupUSSD(panel) {
if (!$("#accordion-ussd").children().length) {
noticer.warning("USSD отсутствуют");
$("#tabs-ussd").html(pEmpty('USSD отсутствуют'));
return;
}
request('listgroupussd', 'json', { to: panel.data("to") }).then(data => {
if (data.error)
noticer.error(data.message);
else {
ussd = data;
showListUSSD(panel);
}
}).catch(error => {
noticer.error(error.message);
});
}
function showListUSSD(panel, data = ussd) {
(new divNotFoundNumbers).remove();
let body = panel.find('.body').html('');
$(data).each((i, j) => {
let row = $(`<tr class="row" data-ussd-id="${j.id}"></tr>`);
row.append(`<td class="ussd-content-width">${j.date}</td>`);
row.append(`<td class="ussd-content-width-type">${j.type_comment}</td>`);
row.append(`<td>${j.text}</td>`);
body.append(row);
row.click(function() {
viewUSSD(panel, $(this).data('ussd-id'), j.type_comment);
});
});
if (!body.children().length)
(new divNotFoundNumbers('Нет USSD')).push();
}
function viewUSSD(panel, id, type) {
request('viewussd', 'text', {id: id}).then(data => {
if (isJSON(data) && JSON.parse(data).error)
noticer.error(JSON.parse(data).message);
else {
showViewUSSD(data, [
{
id: "btn-delete",
text: "Удалить",
icon: "ui-icon-trash",
click: function() {
delUSSD(panel, $(this));
}
}
], `USSD: ${type}`);
}
}).catch(error => {
noticer.error(error.message);
});
}
function showViewUSSD(data, actionButton, title) {
let form = $(data);
form.appendTo('body').dialog({
title: title,
height: 'auto',
width: 'auto',
resizable: false,
modal: true,
show: { effect: "fade", duration: 500 },
close: function(event, ui) {
$(this).dialog('destroy').remove()
},
buttons: [
...actionButton,
{
text: "Отмена",
icon: "ui-icon-cancel",
click: function() {
$(this).dialog("close");
}
}
]
});
}
function delUSSD(panel, currentWindow) {
let id = $('#ussd-content').data('id');
request('delussd', 'json', {
id: id
}).then(data => {
if (data.error)
noticer.error(data.message);
else {
noticer.success(`USSD было удалено`);
generateListGroupUSSD(panel);
currentWindow.dialog("close");
}
}).catch(error => {
noticer.error(error.message);
});
}
/************************************************************************************
Обработка таблицы информации о сервере
************************************************************************************/
function loadServerInfo() {
request('serverinfo', 'text').then(data => {
if (isJSON(data) && JSON.parse(data).error)
noticer.error(JSON.parse(data).message);
else
showServerInfo(data);
}).catch(error => {
noticer.error(error.message);
});
}
function showServerInfo(data) {
$("#tabs-server").html(data);
$("#server-external-number-on").checkboxradio();
$("#server-transparent-mode").checkboxradio();
$("#server-button").button({ icon: "ui-icon-disk", disabled: true });
$(".server-input").on("change paste cut keydown", () => {
if ($("#server-button").button( "option", "disabled")) {
noticer.warning('Некоторые параметры сервера были изменены');
$("#server-button").button( "option", "disabled", false);
}
});
$("#server-button").click(() => {
writeServerInfo();
});
}
function writeServerInfo() {
let pattern_number = /^\+7\d{10}$/g;
let internal_number = $("#server-internal-number").val();
let external_number = $("#server-external-number").val();
let external_number_on = $("#server-external-number-on").is(":checked");
let transparent_mode = $("#server-transparent-mode").is(":checked");
let error = false;
if (external_number.match(pattern_number) === null) { noticer.warning("Внешний номер не соответствует формату +7XXXXXXXXXX"); error = true; }
if (error) return;
request('writeserverinfo', 'json', {
internal_number: internal_number,
external_number: external_number,
external_number_on: external_number_on,
transparent_mode: transparent_mode
}).then(data => {
data.error ?
noticer.error(data.message) :
$("#server-button").button( "option", "disabled", true) && noticer.success("Параметры сервера были сохранены")
}).catch(error => {
noticer.error(error.message);
});
}