+ Реализовано: обновление/добавление/удаление номера
+ Добавлена кнопка обновления активной вкладки
- Доработать проверки на обновление/добавление/удаление номера
This commit is contained in:
Alexander Zhirov 2023-06-02 00:36:21 +03:00
parent c0290cd753
commit de17e88d37
13 changed files with 283 additions and 56 deletions

View File

@ -6,23 +6,32 @@ $(document).ready(function () {
$("button").button(); $("button").button();
$("#tabs").tabs(); $("#tabs").tabs();
// $(".addNumber").click(() => { $("#update").button("option", "icon", "ui-icon-refresh");
// numberAdd() $("#add-number").button("option", "icon", "ui-icon-plusthick");
// }); $("#logout").button("option", "icon", "ui-icon-power");
// За каждым индексом закреплена функция для выполнения действия
// на активной вкладке при нажатии на кнопку обновления
$("#update").click(() => {
({
0: () => { generateGroupNumbers($("#accordion-numbers .ui-accordion-content-active")) },
1: () => { noticer.success('Вкладка "SMS"') },
2: () => { noticer.success('Вкладка "USSD"') },
3: () => { noticer.success('Вкладка "Сервер"') }
})[$("#tabs").tabs( "option", "active" )]()
});
$("#add-number").click(() => {
addNumber($("#accordion-numbers .ui-accordion-content-active"))
});
$("body").fadeTo(500, 1); $("body").fadeTo(500, 1);
$(".search").on("input", function () { $("#search").on("input", function () {
showNumbers( showNumbers(
$("#accordion-numbers .ui-accordion-content-active"), $("#accordion-numbers .ui-accordion-content-active"),
numbers.filter(e => e.number.includes($(this).val())) numbers.filter(e => e.number.includes($(this).val()))
) )
}).on("focus", function () {
if ($(this).val())
showNumbers(
$("#accordion-numbers .ui-accordion-content-active"),
numbers.filter(e => e.number.includes($(this).val()))
);
}).keydown(function (e) { }).keydown(function (e) {
e.key == "Escape" && ($(this).val(""), showNumbers($("#accordion-numbers .ui-accordion-content-active"))) e.key == "Escape" && ($(this).val(""), showNumbers($("#accordion-numbers .ui-accordion-content-active")))
}); });
@ -91,7 +100,7 @@ function generateGroupNumbers(panel) {
}); });
} }
function showNumbers(panel, data = numbers) { function showNumbers(panel, data = numbers.filter(e => e.number.includes($("#search").val()))) {
(new divNotFoundNumbers).remove(); (new divNotFoundNumbers).remove();
let body = panel.find('.body').html(''); let body = panel.find('.body').html('');
$(data).each((i, j) => { $(data).each((i, j) => {
@ -105,7 +114,7 @@ function showNumbers(panel, data = numbers) {
body.append(row); body.append(row);
row.click(function() { row.click(function() {
numberEdit($(this).data('number')); editNumber(panel, $(this).data('number'));
}); });
}); });
@ -134,7 +143,7 @@ function divNotFoundNumbers() {
} }
} }
function numberEdit(number) { function editNumber(panel, number) {
request('editnumber', 'text', {number: number}).then(data => { request('editnumber', 'text', {number: number}).then(data => {
if (isJSON(data) && JSON.parse(data).error) if (isJSON(data) && JSON.parse(data).error)
noticer.error(JSON.parse(data).message); noticer.error(JSON.parse(data).message);
@ -145,7 +154,7 @@ function numberEdit(number) {
text: "Сохранить", text: "Сохранить",
icon: "ui-icon-check", icon: "ui-icon-check",
click: function() { click: function() {
actionNumber($(this), 'update'); actionNumber(panel, $(this), 'updatenumber');
} }
}, },
{ {
@ -153,7 +162,7 @@ function numberEdit(number) {
text: "Удалить", text: "Удалить",
icon: "ui-icon-trash", icon: "ui-icon-trash",
click: function() { click: function() {
// removeNumber($(this)); delNumber(panel, $(this));
} }
} }
], `Редактирование номера ${number}`); ], `Редактирование номера ${number}`);
@ -170,8 +179,6 @@ function showEditNumber(data, actionButton, title) {
title: title, title: title,
height: 'auto', height: 'auto',
width: 'auto', width: 'auto',
maxHeight: 500,
minHeight: 50,
resizable: false, resizable: false,
modal: true, modal: true,
show: { effect: "fade", duration: 500 }, show: { effect: "fade", duration: 500 },
@ -195,7 +202,10 @@ function showEditNumber(data, actionButton, title) {
}); });
} }
function actionNumber(currentWindow, query) { function actionNumber(panel, currentWindow, query) {
// Только числа, начинающие с >0 или только 0
let regexp = /^(?=\d)(\d|([^0]\d+))$/g;
let number = $('#number-number').val(); let number = $('#number-number').val();
let group = $('#number-group').val(); let group = $('#number-group').val();
let list = $('#number-list').val(); let list = $('#number-list').val();
@ -203,5 +213,75 @@ function actionNumber(currentWindow, query) {
let white_cc = $('#number-white-cc').val(); let white_cc = $('#number-white-cc').val();
let black_cc = $('#number-black-cc').val(); let black_cc = $('#number-black-cc').val();
let comment = $('#number-comment').val(); let comment = $('#number-comment').val();
let error = false;
if (!number.length) { noticer.warning('Номер не может быть пуст'); error = true; }
if (all_cc.match(regexp) === null) { noticer.warning("Не верно указано общее количество звонков"); error = true; }
if (white_cc.match(regexp) === null) { noticer.warning("Не верно указано белое количество звонков"); error = true; }
if (black_cc.match(regexp) === null) { 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} был обновлен`);
generateGroupNumbers(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 {
showEditNumber(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} был удален`);
generateGroupNumbers(panel);
currentWindow.dialog("close");
}
}).catch(error => {
noticer.error(error.message);
});
}

View File

@ -25,9 +25,9 @@ div.div-header {
/* HEADER */ /* HEADER */
/* div.div-add { div.main-button {
margin-right: 20px margin-right: 20px
} */ }
div.div-search { div.div-search {
display: flex; display: flex;
@ -107,10 +107,16 @@ td {
background: #fff; background: #fff;
} }
tr.row {
border-top: 1px solid #fff;
}
tr.row:hover, tr.row:nth-child(even):hover { tr.row:hover, tr.row:nth-child(even):hover {
background-color: #c5c5c5; background-color: #f6f6f6;
color: #fff; color: #003eff;
cursor: pointer; cursor: pointer;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid #c5c5c5;
} }
/* EDIT NUMBER */ /* EDIT NUMBER */
@ -148,6 +154,10 @@ tr.row:hover, tr.row:nth-child(even):hover {
justify-content: center; justify-content: center;
} }
.comment-name {
padding: 15px 0 5px 0;
}
.comment-content { .comment-content {
width: 100%; width: 100%;
height: 100%; height: 100%;

View File

@ -19,6 +19,10 @@ import structures;
import requests.listsgroups; import requests.listsgroups;
import requests.groupnumbers; import requests.groupnumbers;
import requests.editnumber; import requests.editnumber;
import requests.updatenumber;
import requests.addnumber;
import requests.delnumber;
import requests.writenumber;
static ServerInfo serverInfo; static ServerInfo serverInfo;
@ -181,24 +185,21 @@ void postReq(HTTPServerRequest req, HTTPServerResponse res) {
// case "logout": // case "logout":
// logout(req, res); // logout(req, res);
// break; // break;
// case "numbers": case "addnumber":
// numbers(req, res); addNumber(req, res);
// break; break;
// case "add": case "writenumber":
// addNumber(req, res); writeNumber(req, res);
// break; break;
// case "write":
// writeNumber(req, res);
// break;
case "editnumber": case "editnumber":
editNumber(req, res); editNumber(req, res);
break; break;
// case "update": case "updatenumber":
// updateNumber(req, res); updateNumber(req, res);
// break; break;
// case "remove": case "delnumber":
// removeNumber(req, res); delNumber(req, res);
// break; break;
default: default:
res.redirect("/"); res.redirect("/");
} }

View File

@ -6,7 +6,7 @@ import structures;
import std.conv; import std.conv;
GroupDB[] getListGroups() { GroupDB[] sqlGetListGroups() {
GroupDB[] groups; GroupDB[] groups;
try { try {
auto queryResult = pgsql.sql( auto queryResult = pgsql.sql(
@ -31,7 +31,7 @@ GroupDB[] getListGroups() {
return groups; return groups;
} }
NumberDB[] getListNumbers(string group) { NumberDB[] sqlGetListNumbers(string group) {
NumberDB[] numbers; NumberDB[] numbers;
try { try {
auto queryResult = pgsql.sql( auto queryResult = pgsql.sql(
@ -44,7 +44,8 @@ NumberDB[] getListNumbers(string group) {
dan.da_comment dan.da_comment
from da_numbers dan from da_numbers dan
left join da_lists dal on dal.da_name = dan.da_list left join da_lists dal on dal.da_name = dan.da_list
where dan.da_group = ?", where dan.da_group = ?
order by dan.da_number",
group group
); );
foreach (row; queryResult) { foreach (row; queryResult) {
@ -66,7 +67,7 @@ NumberDB[] getListNumbers(string group) {
return numbers; return numbers;
} }
NumberDB getDataNumber(string number) { NumberDB sqlGetDataNumber(string number) {
NumberDB data; NumberDB data;
try { try {
auto queryResult = pgsql.sql( auto queryResult = pgsql.sql(
@ -98,7 +99,7 @@ NumberDB getDataNumber(string number) {
return data; return data;
} }
GroupDB[] getGroups() { GroupDB[] sqlGetGroups() {
GroupDB[] groups; GroupDB[] groups;
try { try {
auto queryResult = pgsql.sql( auto queryResult = pgsql.sql(
@ -119,7 +120,7 @@ GroupDB[] getGroups() {
return groups; return groups;
} }
ListDB[] getLists() { ListDB[] sqlGetLists() {
ListDB[] lists; ListDB[] lists;
try { try {
auto queryResult = pgsql.sql( auto queryResult = pgsql.sql(
@ -139,3 +140,63 @@ ListDB[] getLists() {
return lists; return lists;
} }
bool sqlUpdateNumber(NumberDB number) {
try {
pgsql.sql(
"update da_numbers set
da_group = ?,
da_list = ?,
da_all_cc = ?,
da_white_cc = ?,
da_black_cc = ?,
da_comment = ?
where da_number = ?",
number.group,
number.list,
number.all_cc,
number.white_cc,
number.black_cc,
number.comment,
number.number
);
} catch (Exception e) {
log.e("Ошибка обновления номера в БД. " ~ e.msg);
return false;
}
return true;
}
bool sqlDeleteNumber(string number) {
try {
pgsql.sql(
"delete from da_numbers where da_number = ?", number
);
} catch (Exception e) {
log.e("Ошибка удаления номера в БД. " ~ e.msg);
return false;
}
return true;
}
bool sqlInsertNumber(NumberDB number) {
try {
pgsql.sql(
"insert into da_numbers
(da_number, da_group, da_list, da_all_cc, da_white_cc, da_black_cc, da_comment)
values
(?, ?, ?, ?, ?, ?, ?)",
number.number,
number.group,
number.list,
number.all_cc,
number.white_cc,
number.black_cc,
number.comment
);
} catch (Exception e) {
log.error("Ошибка добавления номера телефона в БД. " ~ e.msg);
return false;
}
return true;
}

View File

@ -0,0 +1,18 @@
module requests.addnumber;
import vibe.vibe;
import response;
import structures;
import data;
import singlog;
void addNumber(HTTPServerRequest req, HTTPServerResponse res) {
auto jsr = req.json;
bool edit = false;
NumberDB dataNumber;
dataNumber.group = jsr["group"].get!string;
// auto dataNumber = sqlGetDataNumber(jsr["number"].get!string);
auto groups = sqlGetGroups();
auto lists = sqlGetLists();
render!("edit-number.dt", edit, dataNumber, groups, lists)(res);
}

View File

@ -0,0 +1,24 @@
module requests.delnumber;
import vibe.vibe;
import response;
import structures;
import data;
import singlog;
void delNumber(HTTPServerRequest req, HTTPServerResponse res) {
auto jsr = req.json;
string number = jsr["number"].get!string;
if (!number.length) {
res.send(true, "Номер не может быть пуст");
return;
}
if (!sqlDeleteNumber(number)) {
res.send(true, "Не удалось удалить номер");
return;
}
res.send();
}

View File

@ -8,8 +8,8 @@ import singlog;
void editNumber(HTTPServerRequest req, HTTPServerResponse res) { void editNumber(HTTPServerRequest req, HTTPServerResponse res) {
auto jsr = req.json; auto jsr = req.json;
bool edit = true; bool edit = true;
auto dataNumber = getDataNumber(jsr["number"].get!string); auto dataNumber = sqlGetDataNumber(jsr["number"].get!string);
auto groups = getGroups(); auto groups = sqlGetGroups();
auto lists = getLists(); auto lists = sqlGetLists();
render!("edit-number.dt", edit, dataNumber, groups, lists)(res); render!("edit-number.dt", edit, dataNumber, groups, lists)(res);
} }

View File

@ -7,5 +7,5 @@ import singlog;
void groupNumbers(HTTPServerRequest req, HTTPServerResponse res) { void groupNumbers(HTTPServerRequest req, HTTPServerResponse res) {
auto jsr = req.json; auto jsr = req.json;
res.writeJsonBody(getListNumbers(jsr["group"].get!string).serializeToJson()); res.writeJsonBody(sqlGetListNumbers(jsr["group"].get!string).serializeToJson());
} }

View File

@ -5,6 +5,6 @@ import response;
import data; import data;
void listsGroups(HTTPServerRequest req, HTTPServerResponse res) { void listsGroups(HTTPServerRequest req, HTTPServerResponse res) {
auto listGroups = getListGroups(); auto listGroups = sqlGetListGroups();
render!("group-numbers-list.dt", listGroups)(res); render!("group-numbers-list.dt", listGroups)(res);
} }

View File

@ -0,0 +1,16 @@
module requests.updatenumber;
import vibe.vibe;
import response;
import data;
import singlog;
import structures;
void updateNumber(HTTPServerRequest req, HTTPServerResponse res) {
NumberDB number = deserializeJson!NumberDB(req.json);
if (!sqlUpdateNumber(number)) {
res.send(true, "Не удалось обновить номер");
return;
}
res.send();
}

View File

@ -0,0 +1,16 @@
module requests.writenumber;
import vibe.vibe;
import response;
import structures;
import data;
import singlog;
void writeNumber(HTTPServerRequest req, HTTPServerResponse res) {
NumberDB number = deserializeJson!NumberDB(req.json);
if (!sqlInsertNumber(number)) {
res.send(true, "Не удалось записать номер");
return;
}
res.send();
}

View File

@ -1,3 +1,3 @@
module version_; module version_;
enum dasterVersion = "v0.0.2"; enum dasterVersion = "v0.0.4";

View File

@ -10,15 +10,16 @@ head
script(src='script.js') script(src='script.js')
body body
div.div-header div.div-header
// div.div-add div.div-update.main-button
// button.addNumber Добавить номер button#update
div.div-add.main-button
button#add-number Добавить номер
div.div-search div.div-search
input.input-focus.search(name='search', type='text', value='', placeholder='Найти номер') input.input-focus#search(name='search', type='text', value='', placeholder='Найти номер')
// div.div-user Вы вошли как #{user.name} // div.div-user Вы вошли как #{user.name}
div.div-user Вы вошли как Александр div.div-user
div.div-button div.div-logout
button Выход button#logout Выход
// button(onclick='logout()') Выход
div.content div.content
div#tabs div#tabs
ul ul