From 2ba510adac8e3fc30eaa81167680904573955984 Mon Sep 17 00:00:00 2001 From: Alexander Zhirov Date: Sat, 3 Jun 2023 21:27:07 +0300 Subject: [PATCH] v0.0.6 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit + Запросы объеденины в соответствующие модули + Оптимизация кода --- dub.json | 5 +- js/script.js | 545 +++++++++--------- public/style.css | 6 +- source/daster.d | 60 +- source/requests/addnumber.d | 18 - source/requests/delnumber.d | 24 - source/requests/delsms.d | 19 - source/requests/editnumber.d | 15 - source/requests/groupnumbers.d | 11 - source/requests/listsgroups.d | 10 - source/requests/listsms.d | 10 - source/requests/numbers.d | 113 ++++ source/requests/sms.d | 39 ++ source/requests/smsnumbers.d | 15 - source/requests/updatenumber.d | 42 -- source/requests/viewsms.d | 12 - source/requests/writenumber.d | 42 -- source/{data.d => sql.d} | 2 +- source/version_.d | 2 +- ...-numbers-list.dt => list_number_groups.dt} | 2 - views/{sms-numbers.dt => list_sms_groups.dt} | 0 views/{edit-number.dt => number.dt} | 0 views/{view-sms.dt => sms.dt} | 0 23 files changed, 462 insertions(+), 530 deletions(-) delete mode 100644 source/requests/addnumber.d delete mode 100644 source/requests/delnumber.d delete mode 100644 source/requests/delsms.d delete mode 100644 source/requests/editnumber.d delete mode 100644 source/requests/groupnumbers.d delete mode 100644 source/requests/listsgroups.d delete mode 100644 source/requests/listsms.d create mode 100644 source/requests/numbers.d create mode 100644 source/requests/sms.d delete mode 100644 source/requests/smsnumbers.d delete mode 100644 source/requests/updatenumber.d delete mode 100644 source/requests/viewsms.d delete mode 100644 source/requests/writenumber.d rename source/{data.d => sql.d} (99%) rename views/{group-numbers-list.dt => list_number_groups.dt} (96%) rename views/{sms-numbers.dt => list_sms_groups.dt} (100%) rename views/{edit-number.dt => number.dt} (100%) rename views/{view-sms.dt => sms.dt} (100%) diff --git a/dub.json b/dub.json index 4575027..dcc38e8 100644 --- a/dub.json +++ b/dub.json @@ -7,8 +7,7 @@ "vibe-d": "~>0.9", "singlog": "~>0.3.2", "arsd-official:postgres": "~>10.9.10", - "readconf": "~>0.3.1", - "datefmt": "1.0.4" + "readconf": "~>0.3.1" }, "buildTypes": { "debug": { @@ -26,7 +25,7 @@ } }, "description": "Dialplan Asterisk - веб-сервер для управления обработкой вызовов Asterisk", - "license": "proprietary", + "license": "GPL-2.0", "name": "daster", "targetPath": "bin", "targetType": "executable" diff --git a/js/script.js b/js/script.js index 663b217..d6c60f0 100644 --- a/js/script.js +++ b/js/script.js @@ -4,58 +4,50 @@ var sms = []; $(document).ready(function () { noticer = new Noticer; + let tabs = { + 0: () => { showListNumbers($("#accordion-numbers .ui-accordion-content-active")) }, + 1: () => { showListSMS($("#accordion-sms .ui-accordion-content-active")) }, + 2: () => {}, + 3: () => {} + }; + + let groups = { + 0: () => { generateListGroupNumbers($("#accordion-numbers .ui-accordion-content-active")) }, + 1: () => { generateListGroupSMS($("#accordion-sms .ui-accordion-content-active")) }, + 2: () => { noticer.success('Вкладка "USSD"') }, + 3: () => { noticer.success('Вкладка "Сервер"') } + }; + $("button").button(); - $("#tabs").tabs({ - activate: function( event, ui ) { - ({ - 0: () => { showNumbers($("#accordion-numbers .ui-accordion-content-active")) }, - 1: () => { showSMS($("#accordion-sms .ui-accordion-content-active")) }, - 2: () => {}, - 3: () => {} - })[$(this).tabs( "option", "active" )](); - - $("#add-number").button( "option", "disabled", $(this).tabs( "option", "active" ) > 0 ); - } - }); - $("#update").button("option", "icon", "ui-icon-refresh"); $("#add-number").button("option", "icon", "ui-icon-plusthick"); $("#logout").button("option", "icon", "ui-icon-power"); + $("#tabs").tabs({ + activate: function( event, ui ) { + tabs[$(this).tabs( "option", "active" )](); + $("#add-number").button( "option", "disabled", $(this).tabs( "option", "active" ) > 0 ); + } + }); + $("#update").click(() => { - ({ - 0: () => { generateGroupNumbers($("#accordion-numbers .ui-accordion-content-active")) }, - 1: () => { generateListSMS($("#accordion-sms .ui-accordion-content-active")) }, - 2: () => { noticer.success('Вкладка "USSD"') }, - 3: () => { noticer.success('Вкладка "Сервер"') } - })[$("#tabs").tabs( "option", "active" )]() + groups[$("#tabs").tabs( "option", "active" )]() }); $("#add-number").click(() => { addNumber($("#accordion-numbers .ui-accordion-content-active")) }); - $("body").fadeTo(500, 1); - $("#search").on("input", function () { - ({ - 0: () => { showNumbers($("#accordion-numbers .ui-accordion-content-active")) }, - 1: () => { showSMS($("#accordion-sms .ui-accordion-content-active")) }, - 2: () => {}, - 3: () => {} - })[$("#tabs").tabs( "option", "active" )]() + tabs[$("#tabs").tabs( "option", "active" )]() }).keydown(function (e) { - e.key == "Escape" && ($(this).val(""), ({ - 0: () => { showNumbers($("#accordion-numbers .ui-accordion-content-active")) }, - 1: () => { showSMS($("#accordion-sms .ui-accordion-content-active")) }, - 2: () => {}, - 3: () => {} - })[$("#tabs").tabs( "option", "active" )]() - ) + e.key == "Escape" && ($(this).val(""), tabs[$("#tabs").tabs( "option", "active" )]()) }); loadNumbers(); loadSMS(); + + $("body").fadeTo(500, 1); }) async function request(query, type, queryData = {}) { @@ -89,23 +81,259 @@ function isNumeric(value) { return /^-?\d+$/.test(value); } +function divNotFoundNumbers() { + let notFound = $('.notFoundNumbers'); + let divTable = $('.body-rows'); + let divNotFound = $('
'); + + divNotFound.css({ + "color": "#333", + "text-align": "center", + "padding": "20px 0 20px 0" + }); + + this.push = function(text = 'Нет номеров') { + divTable.append(divNotFound.html(text)); + } + + this.remove = function() { + notFound.remove(); + } +} + +/************************************************************************************ + + Обработка таблицы с номерами телефонов + +************************************************************************************/ + function loadNumbers() { - request('listsgroups', 'text').then(data => { - data.error ? noticer.error(data.message) : generateListsGroups(data); + request('listnumbergroups', 'text').then(data => { + data.error ? noticer.error(data.message) : generateListNumberGroups(data); }).catch(error => { noticer.error(error.message); }); } +function generateListNumberGroups(data) { + if (!$(data).children().length) { + $("#tabs-numbers").html('

Номера телефонов отсутствуют

'); + 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('

Номера телефонов отсутствуют

'); + return; + } + + request('listgroupnumbers', 'json', { group: panel.data("group-name") }).then(data => { + if (isJSON(data) && JSON.parse(data).error) + noticer.error(JSON.parse(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 = $(``); + row.append(`${j.number}`); + row.append(`${j.list}`); + row.append(`${j.all_cc}`); + row.append(`${j.white_cc}`); + row.append(`${j.black_cc}`); + row.append(`${j.comment}`); + 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('smsnumbers', 'text').then(data => { - data.error ? noticer.error(data.message) : generateListsSMSNumber(data); + request('listsmsgroups', 'text').then(data => { + data.error ? noticer.error(data.message) : generateListSMSGroups(data); }).catch(error => { noticer.error(error.message); }); } -function generateListsSMSNumber(data) { +function generateListSMSGroups(data) { if (!$(data).children().length) { $("#tabs-sms").html('

SMS отсутствуют

'); return; @@ -115,34 +343,34 @@ function generateListsSMSNumber(data) { $("#accordion-sms").accordion({ heightStyle: "content", create: function( event, ui ) { - generateListSMS(ui.panel); + generateListGroupSMS(ui.panel); }, beforeActivate: function( event, ui ) { - generateListSMS(ui.newPanel); + generateListGroupSMS(ui.newPanel); } }) } -function generateListSMS(panel) { +function generateListGroupSMS(panel) { if (!$("#accordion-sms").children().length) { noticer.warning("SMS отсутствуют"); $("#tabs-sms").html('

SMS отсутствуют

'); return; } - request('listsms', 'json', { to: panel.data("to") }).then(data => { + request('listgroupsms', 'json', { to: panel.data("to") }).then(data => { if (isJSON(data) && JSON.parse(data).error) noticer.error(JSON.parse(data).message); else { sms = data; - showSMS(panel); + showListSMS(panel); } }).catch(error => { noticer.error(error.message); }); } -function showSMS(panel, data = sms.filter(e => e.from.includes($("#search").val()))) { +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) => { @@ -219,232 +447,7 @@ function delSMS(panel, currentWindow) { noticer.error(data.message); else { noticer.success(`SMS от ${from} было удалено`); - generateListSMS(panel); - currentWindow.dialog("close"); - } - }).catch(error => { - noticer.error(error.message); - }); -} - -function generateListsGroups(data) { - if (!$(data).children().length) { - $("#tabs-numbers").html('

Номера телефонов отсутствуют

'); - return; - } - - $("#tabs-numbers").html(data); - $("#accordion-numbers").accordion({ - heightStyle: "content", - create: function( event, ui ) { - generateGroupNumbers(ui.panel); - }, - beforeActivate: function( event, ui ) { - generateGroupNumbers(ui.newPanel); - } - }); -} - -function generateGroupNumbers(panel) { - if (!$("#accordion-numbers").children().length) { - noticer.warning("Номера телефонов отсутствуют"); - $("#tabs-numbers").html('

Номера телефонов отсутствуют

'); - return; - } - - request('groupnumbers', 'json', { group: panel.data("group-name") }).then(data => { - if (isJSON(data) && JSON.parse(data).error) - noticer.error(JSON.parse(data).message); - else { - numbers = data; - showNumbers(panel); - } - }).catch(error => { - noticer.error(error.message); - }); -} - -function showNumbers(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 = $(``); - row.append(`${j.number}`); - row.append(`${j.list}`); - row.append(`${j.all_cc}`); - row.append(`${j.white_cc}`); - row.append(`${j.black_cc}`); - row.append(`${j.comment}`); - body.append(row); - - row.click(function() { - editNumber(panel, $(this).data('number')); - }); - }); - - if (!body.children().length) - (new divNotFoundNumbers).push(); -} - - -function divNotFoundNumbers() { - let notFound = $('.failNumbers'); - let divTable = $('.body-rows'); - let divFound = $('
'); - - divFound.css({ - "color": "#333", - "text-align": "center", - "padding": "20px 0 20px 0" - }); - - this.push = function(text = 'Нет номеров') { - divTable.append(divFound.html(text)); - } - - this.remove = function() { - notFound.remove(); - } -} - -function editNumber(panel, number) { - request('editnumber', 'text', {number: number}).then(data => { - if (isJSON(data) && JSON.parse(data).error) - noticer.error(JSON.parse(data).message); - else { - showEditNumber(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 showEditNumber(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} был обновлен`); - 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); + generateListGroupSMS(panel); currentWindow.dialog("close"); } }).catch(error => { diff --git a/public/style.css b/public/style.css index e790245..fe99a79 100644 --- a/public/style.css +++ b/public/style.css @@ -78,8 +78,12 @@ input { table-layout: fixed; } +div.group-content { + height: 55vh; +} + div.body-rows { - max-height: 55vh; + height: calc(100% - 55px); overflow-x: auto; border: 1px solid #c5c5c5; border-top: 0; diff --git a/source/daster.d b/source/daster.d index 5958e03..c4b5181 100644 --- a/source/daster.d +++ b/source/daster.d @@ -16,17 +16,8 @@ import verinfo; import pgdb; import structures; -import requests.listsgroups; -import requests.groupnumbers; -import requests.editnumber; -import requests.updatenumber; -import requests.addnumber; -import requests.delnumber; -import requests.writenumber; -import requests.smsnumbers; -import requests.listsms; -import requests.viewsms; -import requests.delsms; +import requests.numbers; +import requests.sms; static ServerInfo serverInfo; @@ -82,15 +73,16 @@ int main(string[] args) { } rc.read(flagSettings); - rcAsteriskDB(); - auto webHost = rcWebHost(); + auto webHost = rcWebHost(); serverInfo = ServerInfo(webHost.title); if (webHost.loglevel != -1) log.level(webHost.loglevel); if (webHost.logoutput) log.output(webHost.logoutput); if (webHost.logfile.length) log.file(webHost.logfile); + rcAsteriskDB(); + auto router = new URLRouter; router.post("/", &postReq); router.get("/", &getReq); @@ -176,45 +168,47 @@ void postReq(HTTPServerRequest req, HTTPServerResponse res) { // return; // } + log.d("json request: " ~ jsr.to!string); + switch (query) { - case "listsgroups": - listsGroups(req, res); - break; - case "groupnumbers": - groupNumbers(req, res); - break; // case "authorization": // authorization(req, res); // break; // case "logout": // logout(req, res); // break; + case "listnumbergroups": + getListNumberGroups(req, res); + break; + case "listgroupnumbers": + getListGroupNumbers(req, res); + break; + case "viewnumber": + getViewNumber(req, res); + break; case "addnumber": - addNumber(req, res); + getAddNumber(req, res); break; case "writenumber": - writeNumber(req, res); - break; - case "editnumber": - editNumber(req, res); + sendWriteNumber(req, res); break; case "updatenumber": - updateNumber(req, res); + sendUpdateNumber(req, res); break; case "delnumber": - delNumber(req, res); + sendDelNumber(req, res); break; - case "smsnumbers": - smsNumbers(req, res); + case "listsmsgroups": + getListSMSGroups(req, res); break; - case "listsms": - listSMS(req, res); + case "listgroupsms": + getListGroupSMS(req, res); break; case "viewsms": - viewSMS(req, res); + getViewSMS(req, res); break; case "delsms": - delSMS(req, res); + sendDelSMS(req, res); break; default: res.redirect("/"); @@ -260,7 +254,7 @@ void rcAsteriskDB() { " password=" ~ asteriskDB["password"] ); } catch (Exception e) { - log.c(e); + log.c(e.msg); exit(1); } } diff --git a/source/requests/addnumber.d b/source/requests/addnumber.d deleted file mode 100644 index 2117b22..0000000 --- a/source/requests/addnumber.d +++ /dev/null @@ -1,18 +0,0 @@ -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); -} diff --git a/source/requests/delnumber.d b/source/requests/delnumber.d deleted file mode 100644 index 1f26183..0000000 --- a/source/requests/delnumber.d +++ /dev/null @@ -1,24 +0,0 @@ -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(); -} diff --git a/source/requests/delsms.d b/source/requests/delsms.d deleted file mode 100644 index 02a2cce..0000000 --- a/source/requests/delsms.d +++ /dev/null @@ -1,19 +0,0 @@ -module requests.delsms; - -import vibe.vibe; -import response; -import structures; -import data; -import singlog; - -void delSMS(HTTPServerRequest req, HTTPServerResponse res) { - auto jsr = req.json; - int idsms = jsr["id"].get!int; - - if (!sqlDeleteSMS(idsms)) { - res.send(true, "Не удалось удалить SMS"); - return; - } - - res.send(); -} diff --git a/source/requests/editnumber.d b/source/requests/editnumber.d deleted file mode 100644 index 719027b..0000000 --- a/source/requests/editnumber.d +++ /dev/null @@ -1,15 +0,0 @@ -module requests.editnumber; - -import vibe.vibe; -import response; -import data; -import singlog; - -void editNumber(HTTPServerRequest req, HTTPServerResponse res) { - auto jsr = req.json; - bool edit = true; - auto dataNumber = sqlGetDataNumber(jsr["number"].get!string); - auto groups = sqlGetGroups(); - auto lists = sqlGetLists(); - render!("edit-number.dt", edit, dataNumber, groups, lists)(res); -} diff --git a/source/requests/groupnumbers.d b/source/requests/groupnumbers.d deleted file mode 100644 index 6163e2b..0000000 --- a/source/requests/groupnumbers.d +++ /dev/null @@ -1,11 +0,0 @@ -module requests.groupnumbers; - -import vibe.vibe; -import response; -import data; -import singlog; - -void groupNumbers(HTTPServerRequest req, HTTPServerResponse res) { - auto jsr = req.json; - res.writeJsonBody(sqlGetListNumbers(jsr["group"].get!string).serializeToJson()); -} diff --git a/source/requests/listsgroups.d b/source/requests/listsgroups.d deleted file mode 100644 index 2512743..0000000 --- a/source/requests/listsgroups.d +++ /dev/null @@ -1,10 +0,0 @@ -module requests.listsgroups; - -import vibe.vibe; -import response; -import data; - -void listsGroups(HTTPServerRequest req, HTTPServerResponse res) { - auto listGroups = sqlGetListGroups(); - render!("group-numbers-list.dt", listGroups)(res); -} diff --git a/source/requests/listsms.d b/source/requests/listsms.d deleted file mode 100644 index 07af810..0000000 --- a/source/requests/listsms.d +++ /dev/null @@ -1,10 +0,0 @@ -module requests.listsms; - -import vibe.vibe; -import response; -import data; - -void listSMS(HTTPServerRequest req, HTTPServerResponse res) { - auto jsr = req.json; - res.writeJsonBody(sqlGetListSMS(jsr["to"].get!string).serializeToJson()); -} \ No newline at end of file diff --git a/source/requests/numbers.d b/source/requests/numbers.d new file mode 100644 index 0000000..24fa4d7 --- /dev/null +++ b/source/requests/numbers.d @@ -0,0 +1,113 @@ +module requests.numbers; + +import vibe.vibe; +import response; +import structures; +import sql; +import singlog; + +import std.regex; + +// Получить список всех групп номеров +void getListNumberGroups(HTTPServerRequest req, HTTPServerResponse res) { + auto listGroups = sqlGetListGroups(); + render!("list_number_groups.dt", listGroups)(res); +} + +// Получить список номеров конкретной группы +void getListGroupNumbers(HTTPServerRequest req, HTTPServerResponse res) { + auto jsr = req.json; + res.writeJsonBody(sqlGetListNumbers(jsr["group"].get!string).serializeToJson()); +} + +// Добавление номера телефона +void getAddNumber(HTTPServerRequest req, HTTPServerResponse res) { + auto jsr = req.json; + bool edit = false; + NumberDB dataNumber; + dataNumber.group = jsr["group"].get!string; + auto groups = sqlGetGroups(); + auto lists = sqlGetLists(); + render!("number.dt", edit, dataNumber, groups, lists)(res); +} + +// Просмотр номера телефона +void getViewNumber(HTTPServerRequest req, HTTPServerResponse res) { + auto jsr = req.json; + bool edit = true; + auto dataNumber = sqlGetDataNumber(jsr["number"].get!string); + auto groups = sqlGetGroups(); + auto lists = sqlGetLists(); + render!("number.dt", edit, dataNumber, groups, lists)(res); +} + +// Обновить номер телефона +void sendUpdateNumber(HTTPServerRequest req, HTTPServerResponse res) { + NumberDB number = deserializeJson!NumberDB(req.json); + + if (!checkNumber(number, res)) + return; + + if (!sqlUpdateNumber(number)) { + res.send(true, "Не удалось обновить номер"); + return; + } + res.send(); +} + +// Записать номер телефона +void sendWriteNumber(HTTPServerRequest req, HTTPServerResponse res) { + NumberDB number = deserializeJson!NumberDB(req.json); + + if (!checkNumber(number, res)) + return; + + if (!sqlInsertNumber(number)) { + res.send(true, "Не удалось записать номер"); + return; + } + res.send(); +} + +// Удалить номера телефона +void sendDelNumber(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(); +} + +// Проверка номера перед изменением +bool checkNumber(NumberDB number, HTTPServerResponse res) { + if (!number.number.matchFirst(regex(r"^\+7\d{10}$", "g"))) { + res.send(true, "Номер не соответствует формату +7XXXXXXXXXX"); + return false; + } + + if (number.all_cc < 0) { + res.send(true, "Общее количество звонков не может быть отрицательным"); + return false; + } + + if (number.white_cc < 0) { + res.send(true, "Белое количество звонков не может быть отрицательным"); + return false; + } + + if (number.black_cc < 0) { + res.send(true, "Черное количество звонков не может быть отрицательным"); + return false; + } + + return true; +} diff --git a/source/requests/sms.d b/source/requests/sms.d new file mode 100644 index 0000000..254793b --- /dev/null +++ b/source/requests/sms.d @@ -0,0 +1,39 @@ +module requests.sms; + +import vibe.vibe; +import response; +import structures; +import sql; +import singlog; + +// Получить список всех групп SMS +void getListSMSGroups(HTTPServerRequest req, HTTPServerResponse res) { + auto numbers = sqlGetSMSNumbers(); + render!("list_sms_groups.dt", numbers)(res); +} + +// Получить список SMS конкретной группы +void getListGroupSMS(HTTPServerRequest req, HTTPServerResponse res) { + auto jsr = req.json; + res.writeJsonBody(sqlGetListSMS(jsr["to"].get!string).serializeToJson()); +} + +// Просмотр SMS +void getViewSMS(HTTPServerRequest req, HTTPServerResponse res) { + auto jsr = req.json; + auto dataSMS = sqlGetSMS(jsr["id"].to!int); + render!("sms.dt", dataSMS)(res); +} + +// Удалить SMS +void sendDelSMS(HTTPServerRequest req, HTTPServerResponse res) { + auto jsr = req.json; + int idsms = jsr["id"].get!int; + + if (!sqlDeleteSMS(idsms)) { + res.send(true, "Не удалось удалить SMS"); + return; + } + + res.send(); +} diff --git a/source/requests/smsnumbers.d b/source/requests/smsnumbers.d deleted file mode 100644 index 1ead955..0000000 --- a/source/requests/smsnumbers.d +++ /dev/null @@ -1,15 +0,0 @@ -module requests.smsnumbers; - -import vibe.vibe; -import response; -import data; -import singlog; - -void smsNumbers(HTTPServerRequest req, HTTPServerResponse res) { - // auto jsr = req.json; - // bool edit = true; - // auto dataNumber = sqlGetDataNumber(jsr["number"].get!string); - // auto groups = sqlGetGroups(); - auto numbers = sqlGetSMSNumbers(); - render!("sms-numbers.dt", numbers)(res); -} diff --git a/source/requests/updatenumber.d b/source/requests/updatenumber.d deleted file mode 100644 index a2c8338..0000000 --- a/source/requests/updatenumber.d +++ /dev/null @@ -1,42 +0,0 @@ -module requests.updatenumber; - -import vibe.vibe; -import response; -import data; -import singlog; -import structures; - -import std.regex; - -void updateNumber(HTTPServerRequest req, HTTPServerResponse res) { - NumberDB number = deserializeJson!NumberDB(req.json); - - // const string pattern_number = r"^\+7\d{10}$"; - // auto regular_number = regex(pattern_number, "g"); - - if (!number.number.matchFirst(regex(r"^\+7\d{10}$", "g"))) { - res.send(true, "Номер не соответствует формату +7XXXXXXXXXX"); - return; - } - - if (number.all_cc < 0) { - res.send(true, "Общее количество звонков не может быть отрицательным"); - return; - } - - if (number.white_cc < 0) { - res.send(true, "Белое количество звонков не может быть отрицательным"); - return; - } - - if (number.black_cc < 0) { - res.send(true, "Черное количество звонков не может быть отрицательным"); - return; - } - - if (!sqlUpdateNumber(number)) { - res.send(true, "Не удалось обновить номер"); - return; - } - res.send(); -} diff --git a/source/requests/viewsms.d b/source/requests/viewsms.d deleted file mode 100644 index 414af84..0000000 --- a/source/requests/viewsms.d +++ /dev/null @@ -1,12 +0,0 @@ -module requests.viewsms; - -import vibe.vibe; -import response; -import data; -import singlog; - -void viewSMS(HTTPServerRequest req, HTTPServerResponse res) { - auto jsr = req.json; - auto dataSMS = sqlGetSMS(jsr["id"].to!int); - render!("view-sms.dt", dataSMS)(res); -} diff --git a/source/requests/writenumber.d b/source/requests/writenumber.d deleted file mode 100644 index 44f67c5..0000000 --- a/source/requests/writenumber.d +++ /dev/null @@ -1,42 +0,0 @@ -module requests.writenumber; - -import vibe.vibe; -import response; -import structures; -import data; -import singlog; - -import std.regex; - -void writeNumber(HTTPServerRequest req, HTTPServerResponse res) { - NumberDB number = deserializeJson!NumberDB(req.json); - - // const string pattern_number = r"^\+7\d{10}$"; - // auto regular_number = regex(r"^\+7\d{10}$", "g"); - - if (!number.number.matchFirst(regex(r"^\+7\d{10}$", "g"))) { - res.send(true, "Номер не соответствует формату +7XXXXXXXXXX"); - return; - } - - if (number.all_cc < 0) { - res.send(true, "Общее количество звонков не может быть отрицательным"); - return; - } - - if (number.white_cc < 0) { - res.send(true, "Белое количество звонков не может быть отрицательным"); - return; - } - - if (number.black_cc < 0) { - res.send(true, "Черное количество звонков не может быть отрицательным"); - return; - } - - if (!sqlInsertNumber(number)) { - res.send(true, "Не удалось записать номер"); - return; - } - res.send(); -} diff --git a/source/data.d b/source/sql.d similarity index 99% rename from source/data.d rename to source/sql.d index 4121a59..f4ccd69 100644 --- a/source/data.d +++ b/source/sql.d @@ -1,4 +1,4 @@ -module data; +module sql; import pgdb; import singlog; diff --git a/source/version_.d b/source/version_.d index d33ae86..fd2e40b 100644 --- a/source/version_.d +++ b/source/version_.d @@ -1,3 +1,3 @@ module version_; -enum dasterVersion = "v0.0.5"; +enum dasterVersion = "v0.0.6"; diff --git a/views/group-numbers-list.dt b/views/list_number_groups.dt similarity index 96% rename from views/group-numbers-list.dt rename to views/list_number_groups.dt index d5cc975..67052e8 100644 --- a/views/group-numbers-list.dt +++ b/views/list_number_groups.dt @@ -1,5 +1,3 @@ -- import structures; - div#accordion-numbers - foreach (group; listGroups) h3 #{group.comment} diff --git a/views/sms-numbers.dt b/views/list_sms_groups.dt similarity index 100% rename from views/sms-numbers.dt rename to views/list_sms_groups.dt diff --git a/views/edit-number.dt b/views/number.dt similarity index 100% rename from views/edit-number.dt rename to views/number.dt diff --git a/views/view-sms.dt b/views/sms.dt similarity index 100% rename from views/view-sms.dt rename to views/sms.dt