Commit 615516f0 authored by Sergey Antonovich's avatar Sergey Antonovich 🇯🇵

Add new file

parent 570e3184
```javascript
/**
* ==============================================================================================================================================
* Глобальные переменные
* ==============================================================================================================================================
*/
const OPTIONS = {
/**
* TOKEN бота *Обязательно*
*/
TOKEN: '...............ТОКЕН.................',
/**
* Глобальные настройки
*/
host: 'https://synergy.arta.pro',
KEY: '...............КЛЮЧ....Шифрования..............',
superSU: 'Логин:Пароль', // Супер пользователь которому будет доступна БД реестра
DBCode: '...................КОД....РЕЕСТРА...................',
month: {0:'01',1:'02',2:'03',3:'04',4:'05',5:'06',6:'07',7:'08',8:'09',9:'10',10:'11',11:'12'},
/**
* Названия кнопок
*/
events: {
auth: '✨Войти в систему',
cancel: 'Отмена',
send: '❇️ Отправить',
logout: '🔑 Выход из профиля',
holiday: '📆 Кол-во отпускных дней',
userList: '👥 Список пользователей',
bannedList: '☢️ Заблокированные пользователи',
adminList: '🅰️ Список администраторов',
sendAllMess: '✏️ Массовая рассылка записи',
buyCutaway: '✏️ Заказать визитку',
next: 'Дальше',
yes: 'Да',
no: 'Нет',
back: 'Назад',
main: 'Главное меню',
profile: '👤 Мой профиль'
},
/**
* Остальной текст
*/
botText: {
platform: `<b>[Synergy]</b>: `,
workName: {
t1: `Ваша заявка на визитки`
},
t1: `Извините, но команда недоступна 😥`,
t2: `Увы, но вы были заблокированы`,
t3: `Команда была отключена ☹`,
t4: `Ошибка сервера, обратитесь к администратору`,
t5: `Выход с аккаунта отклонен`,
t6: `Не верный логин или пароль 🚫`,
t7: `Сервер не отвечает 🚫`,
t8: `Добро пожаловать - $1!\n<i>Для безопасности ваших данных лучше очистить историю :)</i>`,
t9: `- Введите ваш логин:`,
t10: `- Введите пароль:`,
t11: `Вы вышли с аккаунта`,
t12: `Пожалуйста пройдите авторизацию в Synergy 😄`,
t13: `Вы действительно хотите выйти?`,
t14: `C возвращением 😊\n$1`,
t15: `Привет $1!\nДавайте авторизуемся в Synergy 😇`,
t16: `Извините, но вы уже авторизованы 😅`,
t17: `Данные не доступны 😒, обратитесь к офис-менеджеру.`,
t18: `\nОбщее кол-во доступных отпускных дней: $1`,
t19: `\nНе найдены`,
t20: `Все пользователи:`,
t21: `Заблокированные пользователи:`,
t22: `Администраторы:`,
t23: `$1 отклонена 🚫😔`,
t24: `$1 исполнена ✅😎`,
t25: `Заявка была создана 📄 и отправлена по маршруту 🚀`,
t26: `Подача заявки отменена!`,
t27: `Упс! 🚫\nЧто-то пошло не так и заявка не была отправлена.`,
t28: `Пожалуйста подождите ⏳`,
t29: `Отлично! 😇\n- Выберите другой вид или отправьте заявку`,
t30: `Выберите вид печати`,
t31: `Укажите вашу должность! 😡`,
t32: `Отлично!`,
t33: `Введите вашу должность 💬`,
t34: `Введите контактные данные! 😡`,
t35: `Введите ваши контакты 💬`,
t36: `Введите ваше ФИО! 😡`,
t37: `Введите ваше ФИО 💬`,
t38: `Вы указали - $1 шт.`,
t39: `Введите числовое значение! 😡`,
t40: `Введите кол-во визиток 💬`,
t41: `Выберите хотябы 1 пункт из $1`,
t42: `Выберите языки`,
t43: `Вы выбрали: $1[\\n\\t\\t•]`,
t44: `Сообщение разослано всем авторизованым пользователям 📝`,
t45: `Сообщение не было отправлено, так как пользователи не обнаружены.`,
t46: `Рассылка была отменена! 😟`,
t47: `Предпросмотр: 📋\n`,
t48: `Введите текст 💬`,
t49: `Сначала введите пост`,
t50: `\n<i>ФИО</i>: $1\n<i>Должность</i>: $2\n<i>Департамент</i>: $3\n<i>Доступ к конфигуратору</i>: $4\n<i>Доступ к системе</i>: $5`
}
};
const BotKeyboard = {
/**
* Кнопки для пользователя
* resize_keyboard - Убрать огромные кнопки
* one_time_keyboard - После нажатия спрятать кнопки
* parse_mode: 'HTML' - Вкл. поддержку HTML тэгов *<b>,<i>*
*/
user: {
btns: {
reply_markup: {
keyboard: [
[{text: OPTIONS.events.buyCutaway}],
[{text: OPTIONS.events.holiday}],
[{text: OPTIONS.events.profile}],
[{text: OPTIONS.events.logout}]
],
resize_keyboard:true
},
parse_mode: 'HTML'
}
},
/**
* Кнопки для администратора
*/
admin: {
btns: {
reply_markup: {
keyboard: [
[{text: OPTIONS.events.buyCutaway}],
[{text: OPTIONS.events.holiday}],
[{text: OPTIONS.events.userList}],
[{text: OPTIONS.events.bannedList}],
[{text: OPTIONS.events.adminList}],
[{text: OPTIONS.events.sendAllMess}],
[{text: OPTIONS.events.profile}],
[{text: OPTIONS.events.logout}]
],
resize_keyboard:true
},
parse_mode: 'HTML'
}
},
/**
* Кнопки для гостя
*/
guest: {
btns: {
reply_markup: {
keyboard: [
[{text: OPTIONS.events.auth}]
],
one_time_keyboard:true,
resize_keyboard:true
},
parse_mode: 'HTML'
}
}
}
/**
* ==============================================================================================================================================
* Подключаем модули
* ==============================================================================================================================================
*/
const TBOT = require('node-telegram-bot-api');
const bot = new TBOT(OPTIONS.TOKEN,{polling: true});
//const _ = require('lodash');
const crypto = require('crypto');
const ajax = require('najax');
//const fs = require('fs');
/**
* ==============================================================================================================================================
* Класс для работы с Synergy by yandexphp
* ==============================================================================================================================================
*/
function synergy(superSU){
var formData = false;
var fullFormData = false;
var formUUID = false;
/**
* Подгрузить данные по форме
* @param dataUUID
* @param callback
*/
this.load = function(dataUUID,callback){
var data = api(superSU,'asforms/data/' + dataUUID,function(data){
formData = (data.errorCode != '13' ? data.data : false);
fullFormData = (data.errorCode != '13' ? data : false);
formUUID = dataUUID;
callback();
});
return this;
};
/**
* Сохранить данные по форме
* @param callback
*/
this.save = function(callback){
var save = api(superSU,'asforms/data/save',function(){
if(callback) callback();
},{
uuid: formUUID,
data: '"data":' + JSON.stringify(formData)
}, 'POST');
return (save == '200');
};
/**
*
* @param tableID Получить массив строк дин.таблицы
*/
this.tableData = function(tableID) {
var data = this.getValue(tableID);
var conArr = [];
if(('data' in data) === false) data.data = [];
var b;
data.data.forEach(function (item) {
if (item.id.indexOf('-b') !== -1 && (b = item.id.match(/(.+)\-b(\d+)/))) {
if ((b[2] in conArr) === false) conArr[b[2]] = {};
conArr[b[2]][b[1]] = item;
return;
}
});
for (var i = 0; i < conArr.length; i++) if (conArr[i] == null) conArr.splice(i--, 1);
return conArr;
};
/**
* Установить значение
* 1. Компонент, Значение или Объект, если значение то указать ключ
* 2. Компонент, Таблица, Номер ряда, Значение или Объект, если значение то указать ключ
*/
this.setValue = function(){
var args = {c: arguments[0],vt: arguments[1],ob: arguments[2],v: arguments[3],o: arguments[4]};
if (typeof(args.c) === 'string' && typeof(args.ob) === 'number') {
if (args.ob == 0) args.ob = 1;
formData.forEach(function(item) {
if (item.id == args.vt) {
item.data.forEach(function(bItem) {
if (bItem.id.indexOf(args.c + '-b' + args.ob) !== -1) {
if (typeof(args.v) === 'object')
for (var aItem in args.v) bItem[aItem] = args.v[aItem];
else bItem[(args.o) ? args.o : 'value'] = args.v;
return;
}
});
return;
}
});
} else {
formData.forEach(function(item) {
if (item.id == args.c) {
if (typeof(args.vt) === 'object')
for (var aItem in args.vt) item[aItem] = args.vt[aItem];
else item[(args.ob) ? args.ob : 'value'] = args.vt;
return;
}
});
}
};
/**
* Получить значение либо объект
* 1. Компонент, не обязательный аргумент ключ
* 2. Компонент, Таблица, Номер ряда, не обязательный аргумент ключ
*/
this.getValue = function(){
var data;
var args = {c: arguments[0],ot: arguments[1],b: arguments[2],o: arguments[3]};
if (typeof(args.c) === 'string' && typeof(args.b) === 'number') {
formData.forEach(function(item) {
if (item.id == args.ot) {
item.data.forEach(function(bItem) {
if (bItem.id.indexOf(args.c + '-b' + args.b) !== -1) {
data = (args.o) ? bItem[args.o] : bItem;
return;
}
});
return;
}
});
} else {
formData.forEach(function(item) {
if (item.id == args.c) {
data = (args.ot) ? item[args.ot] : item;
return;
}
});
}
return data;
};
/**
* Получить кол-во строк в дин.таблице
* @param tableID
*/
this.getRowsCount = function(tableID) {
var data = this.getValue(tableID);
if(('data' in data) === false) data.data = [];
var len = 0;
data.data.forEach(function(item) {
var regex = item.id.match(/\-b(\d+)/);
if (regex && parseInt(regex[1]) > len) len++;
});
return len;
};
/**
* Получить данные по форме в ключе "data"
*/
this.getFormData = function(){
return formData;
};
/**
* Получить полные данные по форме
*/
this.getFullFormData = function(){
return fullFormData;
};
/**
* Получить текущий dataUUID формы
*/
this.getFormUUID = function(){
return formUUID;
};
/**
* Получить documentID по dataUUID
* @param dataUUID
*/
this.getDocumentId = function(dataUUID){
return api(superSU,'asforms/data/document?dataUUID=' + dataUUID);
};
/**
* Получить dataUUID по documentID
* @param documentId
*/
this.getDataUUID = function(documentId){
return "" + api(superSU,'formPlayer/getAsfDataUUID?documentID=' + documentId, {}, 'GET', true);
};
/**
* Очистить данные
*/
this.destroy = function() {
formData = formUUID = fullFormData = false;
return this;
};
return this;
}
/**
* ==============================================================================================================================================
* Класс для работы с событиями пользователей
* ==============================================================================================================================================
*/
function users(query,isMessage){
var userChatId = (!isMessage?query.message.chat.id:query.chat.id);
var userMessId = (!isMessage?query.message.message_id:query.message_id);
var userName = (!isMessage?query.message.chat.last_name + ' ' + query.message.chat.first_name:query.chat.last_name + ' ' + query.chat.first_name);
/**
* Авторизация
*/
this.auth = function(){
var login = false;
var pass = false;
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t9,{parse_mode: 'HTML'});
bot.onText(/(.+)/iu, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if(clientID == userChatId && !login){
login = match[1];
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t10,{parse_mode: 'HTML'});
bot.onText(/(.+)/iu, (message, match) => {
clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if(clientID == userChatId && !pass){
pass = match[1];
ajax({
url: OPTIONS.host + "/Synergy/rest/api/person/auth",
type: 'GET',
beforeSend: function(data){data.setRequestHeader("Authorization", "Basic " + Buffer.from(login + ':' + pass).toString('base64'));},
dataType: 'json',
error: function(err){
switch(err.status){
case 401: bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t6,BotKeyboard.guest.btns); break;
case 408: bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t7,{parse_mode:'HTML'}); break;
}
},
success: function(res_profile){
isAuth(userChatId,function(uuid){
var form = new synergy().load(uuid,function(){
var checkRow = isKey(form.tableData('bot_users'),false,[userChatId,encrypt(OPTIONS.KEY, login+':'+pass)]);
if(checkRow){
checkRow['bot_user_status'].key = '1';
checkRow['bot_user_status'].value = 'Аутентифицирован';
form.setValue('reg-tg-name',checkRow['bot_user_tg_name'].value,'value');
form.setValue('reg-name',checkRow['bot_user_name'].value,'value');
form.setValue('reg-status',checkRow['bot_user_status'].key,'value');
form.setValue('reg-access',checkRow['bot_user_access'].key,'value');
form.setValue('reg-type',checkRow['bot_user_type'].key,'value');
form.save();
}else{
var arr = form.getValue('bot_users','data');
var len = form.getRowsCount('bot_users');
len++;
arr.push(
{id: 'bot_user_tg_chatId-b' + len,type: 'textbox',value: "" + userChatId},
{id: 'bot_user_tg_name-b' + len,type: 'textbox',value: "" + userName},
{id: 'bot_user_id-b' + len,type: 'textbox',value: "" + res_profile.userid},
{id: 'bot_user_name-b' + len,type: 'textbox',value: "" + res_profile.lastname + " " + res_profile.firstname},
{id: 'bot_user_data-b' + len,type: 'textbox',value: "" + encrypt(OPTIONS.KEY, login+':'+pass)},
{id: 'bot_user_status-b' + len,type: 'listbox',value: "Аутентифицирован",key:'1'},
{id: 'bot_user_access-b' + len,type: 'listbox',key: '0',value: 'Разрешен'},
{id: 'bot_user_type-b' + len,type: 'listbox',key: '0',value: 'Пользователь'}
);
form.setValue('bot_users',arr,'data');
form.setValue('reg-tg-name',"" + userName,'value');
form.setValue('reg-name',"" + res_profile.lastname + " " + res_profile.firstname,'value');
form.setValue('reg-status','1','value');
form.setValue('reg-access','0','value');
form.setValue('reg-type','0','value');
form.save();
}
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t8.replace('$1',res_profile.lastname + " " + res_profile.firstname),BotKeyboard[(checkRow && checkRow['bot_user_type'].key == '1'?'admin':'user')].btns);
});
},true,true);
}
});
}
});
}
});
}
/**
* Выйти из системы - Да
*/
this.logout_yes = function(){
isAuth(userChatId,function(uuid){
if(!uuid){
command(userChatId).access();
}else{
var form = new synergy().load(uuid,function(){
var dataRow = isKey(form.tableData('bot_users'), 'bot_user_status', 'key', '1');
if(!dataRow) return;
dataRow['bot_user_status'].key = '0';
dataRow['bot_user_status'].value = 'Не аутентифицирован';
form.setValue('reg-name',"none",'value');
form.setValue('reg-status',"" + dataRow['bot_user_status'].key,'value');
form.setValue('reg-access',"" + dataRow['bot_user_access'].key,'value');
form.setValue('reg-type',""+dataRow['bot_user_type'].key,'value');
form.save(function(){
bot.editMessageText(OPTIONS.botText.platform + OPTIONS.botText.t11,{chat_id: userChatId,message_id: userMessId,parse_mode:'HTML'});
bot.sendMessage(userChatId,OPTIONS.botText.t12,BotKeyboard.guest.btns);
});
});
}
},true);
}
/**
* Выйти из системы - Нет
*/
this.logout_no = function(){
bot.editMessageText(OPTIONS.botText.platform + OPTIONS.botText.t5,{chat_id: userChatId,message_id: userMessId,parse_mode:'HTML'});
}
/**
* Подать заявку на визитки
* @param isAuthData
*/
this.buyCutaway = function(isAuthData){
api(isAuthData['bot_user_data'].value,'registry/create_doc?registryCode=' + encodeURIComponent('Заявка__в_АТД__1__на_визитки_'),function(newFormRes){
var form = new synergy(isAuthData['bot_user_data'].value).load(newFormRes.dataUUID,function(){
var langs = [];
var langsArr = [];
var list = [];
api(isAuthData['bot_user_data'].value,'asforms/form/' + form.getFullFormData().form, function(defData){
defData.data.forEach(function(item){
if(item.id == 'cmp-w7tciv'){
item.values.forEach(function(item2){
langs.push([{text:item2.value}]);
langsArr.push(item2.value);
});
} else if (item.id == 'cmp-h9qnlm'){
item.values.forEach(function(item2){
list.push([{text:item2.value}]);
});
}
});
var slt = langs.slice();
slt.push([{text: OPTIONS.events.cancel}]);
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t42,{
reply_markup: {
keyboard: slt
},
resize_keyboard:true,
parse_mode: 'HTML'
});
form.setValue('cmp-w7tciv',{
keys: []
});
var step = 0;
var next = false;
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
match[1] = match[1].replace(/\ ✅/g,'');
var arrIdx = langsArr.indexOf(match[1]);
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 0 && arrIdx !== -1) {
var old = form.getValue('cmp-w7tciv','keys');
(old.indexOf(langsArr[arrIdx]) === -1?old.push(langsArr[arrIdx]):old.splice(old.indexOf(langsArr[arrIdx]),1));
var dublicateOld = old.slice();
form.setValue('cmp-w7tciv',{
keys: old,
values: old
});
var board = langs.slice();
old.forEach(function(item){
var sel = false;
board.forEach(function(item2){
if(item2[0].text == item){
item2[0].text += '';
sel = true;
return;
}
});
if(!sel){
board.forEach(function(item2){
if(item2[0].text.indexOf(item) === -1){
item2[0].text = item2[0].text.replace(/\ ✅/g,'');
return;
}
});
}
});
var text = OPTIONS.botText.t41.replace('$1',langsArr.length);
next = false;
if(old.length > 0){
next = true;
board.push([{text:OPTIONS.events.next}]);
var regex = OPTIONS.botText.t43.match(/\$1\[(.+)\]/);
text = OPTIONS.botText.t43.replace(regex[0],regex[1] + old.join(regex[1])).replace(/\\n/g,'\n').replace(/\\t/g,'\t');
}else{
board.forEach(function(item2){
item2[0].text = item2[0].text.replace(/\ ✅/g,'');
return;
});
}
board.push([{text: OPTIONS.events.cancel}]);
bot.sendMessage(userChatId,OPTIONS.botText.platform + text,{
reply_markup: {
keyboard: board
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 0 && match[1] == OPTIONS.events.next && next) {
step = 1;
next = false;
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t40,{
reply_markup: {
keyboard: [
[{text:OPTIONS.events.cancel}]
]
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 1 && match[1] != OPTIONS.events.next) {
if(!/^[0-9]+/.test(match[1])){
form.setValue('cmp-8antkj','','value');
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t39,{
reply_markup: {
keyboard: [
[{text:OPTIONS.events.cancel}]
]
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}else{
form.setValue('cmp-8antkj',match[1],'value');
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t38.replace('$1',match[1]),{
reply_markup: {
keyboard: [
[{text:OPTIONS.events.next}],
[{text:OPTIONS.events.cancel}]
]
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 1 && form.getValue('cmp-8antkj','value') && match[1] == OPTIONS.events.next) step = 2;
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 2 && match[1] == OPTIONS.events.next) {
step = 3;
api(isAuthData['bot_user_data'].value,'person/auth',function(profile){
var buttons = [[{text:profile.lastname + " " + profile.firstname}],[{text:OPTIONS.events.cancel}]];
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t37,{
reply_markup: {keyboard: buttons},
resize_keyboard:true,
parse_mode: 'HTML'
});
});
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 3 && match[1] != OPTIONS.events.next) {
var regex = match[1].match(/\s{0,}(.*)\s+(.*)\s{0,}/);
if(regex) {
form.setValue('cmp-q8wshu', regex[0], 'value');
bot.sendMessage(userChatId, OPTIONS.botText.platform + OPTIONS.botText.t32, {
reply_markup: {
keyboard: [
[{text: OPTIONS.events.next}],
[{text: OPTIONS.events.cancel}]
]
},
resize_keyboard: true,
parse_mode: 'HTML'
});
}else{
form.setValue('cmp-q8wshu','','value');
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t36,{
reply_markup: {
keyboard: [
[{text:OPTIONS.events.cancel}]
]
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 3 && form.getValue('cmp-q8wshu','value') && match[1] == OPTIONS.events.next) step = 4;
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 4 && match[1] == OPTIONS.events.next) {
step = 5;
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t35,{
reply_markup: {
keyboard: [
[{text:OPTIONS.events.cancel}]
]
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 5 && match[1] != OPTIONS.events.next) {
if(match[1] && match[1].length > 1){
form.setValue('cmp-huayxf',match[1],'value');
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t32,{
reply_markup: {
keyboard: [
[{text:OPTIONS.events.next}],
[{text:OPTIONS.events.cancel}]
]
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}else{
form.setValue('cmp-huayxf','','value');
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t34,{
reply_markup: {
keyboard: [
[{text:OPTIONS.events.cancel}]
]
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 5 && form.getValue('cmp-huayxf','value') && match[1] == OPTIONS.events.next) step = 6;
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 6 && match[1] == OPTIONS.events.next) {
step = 7;
api(isAuthData['bot_user_data'].value,'person/auth',function(profile){
var buttons = [[{text:profile.positions[0].positionName}],[{text:OPTIONS.events.cancel}]];
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t33,{
reply_markup: {keyboard: buttons},
resize_keyboard:true,
parse_mode: 'HTML'
});
});
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 7 && match[1] != OPTIONS.events.next) {
if(match[1] && match[1].length > 1){
form.setValue('cmp-dtfkgy',match[1],'value');
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t32,{
reply_markup: {
keyboard: [
[{text:OPTIONS.events.next}],
[{text:OPTIONS.events.cancel}]
]
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}else{
form.setValue('cmp-dtfkgy','','value');
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t31,{
reply_markup: {
keyboard: [
[{text:OPTIONS.events.cancel}]
]
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 7 && form.getValue('cmp-dtfkgy','value') && match[1] == OPTIONS.events.next) step = 8;
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 8 && match[1] == OPTIONS.events.next) {
step = 9;
var format = list.slice();
format.push([{text:OPTIONS.events.cancel}]);
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t30,{
reply_markup: {
keyboard: format
},
resize_keyboard:true,
parse_mode: 'HTML'
});
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 9) {
var format = list.slice();
format.forEach(function(item){
if(item[0].text == match[1]){
form.setValue('cmp-h9qnlm',{
value: match[1],
key: match[1]
});
format.push([{text:OPTIONS.events.send}],[{text:OPTIONS.events.cancel}]);
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t29,{
reply_markup: {
keyboard: format
},
resize_keyboard:true,
parse_mode: 'HTML'
});
return;
}
});
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && step == 9 && match[1] == OPTIONS.events.send){
step = -1;
api(isAuthData['bot_user_data'].value,'person/auth',function(profile){
form.setValue('from',{
value: "" + profile.lastname + " " + (profile.firstname?profile.firstname.substr(0,1).toLocaleUpperCase() + ". ":" ") + (profile.patronymic?profile.patronymic.substr(0,1).toLocaleUpperCase() + ".":""),
key: profile.userid
});
form.setValue('cmp-qu9ksw',{
value: profile.positions[0].positionName,
key: profile.positions[0].positionID
});
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t28,{parse_mode: 'HTML'});
form.save(function(){
api(isAuthData['bot_user_data'].value,'registry/activate_doc?dataUUID=' + newFormRes.dataUUID,function(response){
var text = OPTIONS.botText.t25;
if(response.errorCode != '0'){
text = OPTIONS.botText.t27;
api(isAuthData['bot_user_data'].value,'registry/delete_doc?dataUUID=' + newFormRes.dataUUID);
}else{
addWorkTable(userChatId,function(){
var date = new Date();
var time = zero(date.getHours()) + ':' + zero(date.getMinutes()) + ':' + zero(date.getSeconds());
date = zero(date.getDate()) + '.' + OPTIONS.month[date.getMonth()] + '.' +date.getFullYear();
return [
{id: 'bot_startDate',type: 'date',value: "" + date,key:date.split('.').reverse().join('-') + ' ' + time},
{id: 'bot_user_id',type: 'textbox',value: "" + profile.userid},
{id: 'bot_workName',type: 'textbox',value: OPTIONS.botText.workName.t1},
{id: 'bot_form',type: 'textbox',value: "" + newFormRes.documentID}
];
});
}
bot.sendMessage(userChatId,OPTIONS.botText.platform + text,BotKeyboard[(isAuthData['bot_user_type'].key == '1'?'admin':'user')].btns);
});
});
});
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if (clientID == isAuthData['bot_user_tg_chatId'].value && match[1] == OPTIONS.events.cancel && step != -1){
step = -1;
api(isAuthData['bot_user_data'].value,'registry/delete_doc?dataUUID=' + newFormRes.dataUUID);
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t26,BotKeyboard[(isAuthData['bot_user_type'].key == '1'?'admin':'user')].btns);
}
});
});
});
});
}
/**
* Массовая рассылка сообщения
* @param {*} isAuthData
*/
this.sendAllMessage = function(isAuthData){
var mess = false;
var preview = false;
var cancel = false;
bot.sendMessage(userChatId,OPTIONS.botText.t48,{
reply_markup: {
keyboard: [
[{text: OPTIONS.events.send}],
[{text: OPTIONS.events.cancel}]
],
resize_keyboard:true
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if(clientID == userChatId && match[1] == OPTIONS.events.cancel){
cancel = true;
bot.sendMessage(userChatId,OPTIONS.botText.t46,BotKeyboard[(isAuthData['bot_user_type'].key == '1'?'admin':'user')].btns);
}
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if(clientID == userChatId && !preview && !mess && !cancel){
if(match[1] == OPTIONS.events.send){
bot.sendMessage(userChatId,OPTIONS.botText.t49);
return;
}
mess = match[1];
preview = true;
bot.sendMessage(userChatId,OPTIONS.botText.t47 + mess,{
reply_markup: {
keyboard: [
[{text: OPTIONS.events.send}],
[{text: OPTIONS.events.cancel}]
],
resize_keyboard:true
},
parse_mode: 'HTML'
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if(clientID == userChatId && preview && mess && !cancel && match[1] == OPTIONS.events.send){
preview = false;
userList(userChatId,'usersID',function(list){
var tmp = [];
list.forEach(function(id){
if(userChatId == id) return;
if(tmp.indexOf(id) === -1){
tmp.push(id);
bot.sendMessage(id,mess);
}
});
bot.sendMessage(userChatId,(tmp.length > 0?OPTIONS.botText.t44:OPTIONS.botText.t45),BotKeyboard[(isAuthData['bot_user_type'].key == '1'?'admin':'user')].btns);
});
}
});
}
});
}
/**
* Мой профиль
*/
this.profile = function(isAuthData){
api(isAuthData['bot_user_data'].value,'person/auth',function(profile){
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.botText.t50
.replace('$1',""+profile.lastname + " " + profile.firstname + " " + profile.patronymic)
.replace('$2',""+profile.positions[0].positionName)
.replace('$3',""+profile.positions[0].departmentName)
.replace('$4',""+(profile.configurator == 'true'?'':'⛔️'))
.replace('$5',""+(profile.access == 'true'?'':'⛔️')),{
reply_markup: {
keyboard: [[{text:OPTIONS.events.main}]],
resize_keyboard:true
},
parse_mode: 'HTML'
});
});
bot.onText(/(.+)/i, (message, match) => {
var clientID = message.hasOwnProperty('chat') ? message.chat.id : message.from.id;
if(clientID == userChatId && match[1] == OPTIONS.events.main){
bot.sendMessage(userChatId,OPTIONS.botText.platform + OPTIONS.events.main,BotKeyboard[(isAuthData['bot_user_type'].key == '1'?'admin':'user')].btns);
return;
}
});
}
return this;
}
/**
* ==============================================================================================================================================
* Быстрые команды
* ==============================================================================================================================================
*/
function command(chatID,options){
var options = (!options?{parse_mode:'HTML'}:options);
this.access = function(){bot.sendMessage(chatID,OPTIONS.botText.platform + OPTIONS.botText.t1,options);}
this.banned = function(){bot.sendMessage(chatID,OPTIONS.botText.platform + OPTIONS.botText.t2,options);}
this.disable = function(){bot.sendMessage(chatID,OPTIONS.botText.platform + OPTIONS.botText.t3,options);}
this.serverError = function(){bot.sendMessage(chatID,OPTIONS.botText.platform + OPTIONS.botText.t4,options);}
return this;
}
/**
* ==============================================================================================================================================
* Функции
* ==============================================================================================================================================
*/
String.prototype.repeat = function(n){return new Array(n + 1).join(this);};
Array.prototype.removeNull = function(){for(var i=0;i<this.length;i++)if(this[i]==null)this.splice(i--,1);return this;};
function zero(val){return val>9?val:"0"+val;}
function log(data){if (typeof(data) != 'string') data = JSON.stringify(data, null, 4);data = data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');var m = 90;var spt = '\x1b[32m\x1b[1m' + '='.repeat(m) + '\n\x1b[0m';var date = new Date();var time = zero(date.getHours()) + ':' + zero(date.getMinutes()) + ':' + zero(date.getSeconds());date = '\x1b[36m\x1b[1m' + zero(date.getDate()) + '.' + OPTIONS.month[date.getMonth()] + '.' +date.getFullYear() + ' ' + time + "\x1b[0m";var dtCenter = '\x1b[32m\x1b[1m' + '='.repeat(Math.round(m - date.length + 9)) + '\x1b[0m ' + date + '\x1b[32m\x1b[1m ==\n';return console.log('\n\n' + spt + dtCenter + spt + '\n\x1b[0m' + data.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {var clr = '\x1b[0m';var cls = (/^"/.test(match)?(/:$/.test(match)?'key':'string'):(/true|false/.test(match)?'boolean':(/null/.test(match)?'null':'number')));switch(cls){case 'number': clr = '\x1b[36m\x1b[1m'; break;case 'boolean': clr = '\x1b[34m\x1b[1m'; break;case 'null': clr = '\x1b[34m\x1b[1m'; break;case 'string': clr = '\x1b[33m\x1b[1m'; break;case 'key': clr = '\x1b[31m\x1b[1m'; break;}return clr + match + '\x1b[0m';}) + '\n\n' + spt + spt + '\n\n');}
function encrypt(key, data){var cipher=crypto.createCipher('aes-256-cbc',key);var crypted=cipher.update(data,'utf-8','hex');crypted+=cipher.final('hex');return crypted;}
function decrypt(key, data){var decipher=crypto.createDecipher('aes-256-cbc',key);var decrypted=decipher.update(data,'hex','utf-8');decrypted+=decipher.final('utf-8');return decrypted;}
function isKey(tableData,id,key,value,isAuthFix,array){var data = false;if(array) data = [];tableData.forEach(function(item){if(id === false){if(item['bot_user_tg_chatId'].value == key[0] && item['bot_user_data'].value == key[1]){if(!array) {data = item;return;}data.push(item);}} else {if (isAuthFix) {if (item[id][key] == value && item['bot_user_status'].key == '1') {if(!array) {data = item;return;}data.push(item);}} else {if (item[id][key] == value) {if(!array) {data = item;return;}data.push(item);}}}});return data;}
function api(authData,method,callback,params,type,dataType){ajax({url: OPTIONS.host + "/Synergy/rest/api/" + method,type: (!type?'GET':type),beforeSend: function(data){data.setRequestHeader("Authorization", "Basic " + Buffer.from((!authData?OPTIONS.superSU:decrypt(OPTIONS.KEY,authData))).toString('base64'));},data: (!params?{}:params),async:false,dataType: (!dataType?'json':dataType), success: callback,error: function(data){log({response: 'Error',body: data});}});}
function isAuth(chatID,callback,getUUID,createDoc){api(false,'registry/data_ext?loadData=true&registryCode=' + OPTIONS.DBCode, function (res) {var doc = false;res.result.forEach(function(item){if(item.fieldValue.user_id == chatID){doc = item.dataUUID;return;}});if(!doc){if(!createDoc){callback(false);}else{api(false,'registry/create_doc?registryCode=' + OPTIONS.DBCode,function(newDoc) {var form = new synergy().load(newDoc.dataUUID, function () {form.setValue('user_id', chatID, 'value');form.save(function(){callback(newDoc.dataUUID);});});});}}else{if(!getUUID) {var form = new synergy().load(doc, function () {callback(isKey(form.tableData('bot_users'), 'bot_user_status', 'key', '1'));});}else{callback(doc);}}});}
function logout(chatData){bot.sendMessage(chatData.chat.id,OPTIONS.botText.platform + OPTIONS.botText.t13,{reply_markup: {inline_keyboard: [[{text: OPTIONS.events.yes,callback_data: 'logout_yes'},{text: OPTIONS.events.no,callback_data: 'logout_no'}]]},parse_mode: 'HTML'});}
function delTGDoc(formData,data){formData.forEach(function(item){if(item.id == 'bot_works'){var bs = data.id.match(/\-b(\d+)/)[1];var tmp = [];item.data.forEach(function(item2,key){var b = item2.id.match(/\-b(\d+)/);if(b && b[1] == bs) delete item.data[key];});item.data.removeNull();return;}});}
function userList(chatID,usersType,callback){isAuth(chatID,function(uuid){var form = new synergy().load(uuid,function(){var users = {users:[],banned:[],admins:[],usersID:[],usersAllID:[]};var rights = isKey(form.tableData('bot_users'),'bot_user_status', 'key', '1')['bot_user_type'].key;if(rights == '1'){api(false,'registry/data_ext?loadData=true&registryCode=' + OPTIONS.DBCode, function (res) {res.result.forEach(function(item){var field = item['fieldValue'];if(field['reg-access'] == '1') users.banned.push(field['reg-tg-name']);else if(field['reg-type'] == '1'){users.admins.push(field['reg-tg-name']);users.users.push("[<i>Admin</i>]: " + field['reg-tg-name']);} else if(field['reg-type'] == '0') users.users.push(field['reg-tg-name']);if(field['reg-access'] == '0') users.usersID.push(field['user_id']);users.usersAllID.push(item['fieldValue']['user_id']);});callback((usersType?users[usersType]:users));});}else{command(chatID).access();}});},true);}
function addWorkTable(chatID,callback){isAuth(chatID,function(uuid){var form = new synergy().load(uuid,function(){if(('data' in form.getValue('bot_works')) === false) form.setValue('bot_works',{data:[]});var arr = form.getValue('bot_works','data');var len = form.getRowsCount('bot_works');len++;var res = callback();if(!Array.isArray(res)) res = [res];res.forEach(function(item){item.id += '-b' + len;arr.push(item);});form.setValue('bot_works',arr,'data');form.save();});},true);}
/**
* ==============================================================================================================================================
* Таймер для бота
* ==============================================================================================================================================
*/
setInterval(function(){
api(false,'registry/data_ext?loadData=true&registryCode=' + OPTIONS.DBCode,function(res){
res.result.forEach(function(doc){
var form = new synergy().load(doc.dataUUID,function(){
if(form.getRowsCount('bot_works') > 0){
var conv = form.tableData('bot_works');
conv.forEach(function(work){
api(false,'docflow/doc/document_info?documentID=' + work.bot_form.value,function(data){
if(data.processing == 'false' && data.activate == 'false'){
res.result.forEach(function(item){
var form2 = new synergy().load(item.dataUUID,function(){
var checkRow = isKey(form2.tableData('bot_users'),'bot_user_id','value',work.bot_user_id.value,true);
if(checkRow) bot.sendMessage(checkRow['bot_user_tg_chatId'].value,OPTIONS.botText.platform + OPTIONS.botText.t23.replace('$1',work.bot_workName.value),{parse_mode: 'HTML'});
});
});
delTGDoc(form.getFormData(),work.bot_form);
form.save();
} else if(data.processing == 'false' && data.activate == 'true'){
res.result.forEach(function(item){
var form2 = new synergy().load(item.dataUUID,function(){
var checkRow = isKey(form2.tableData('bot_users'),'bot_user_id','value',work.bot_user_id.value,true);
if(checkRow) bot.sendMessage(checkRow['bot_user_tg_chatId'].value,OPTIONS.botText.platform + OPTIONS.botText.t24.replace('$1',work.bot_workName.value),{parse_mode: 'HTML'});
});
});
delTGDoc(form.getFormData(),work.bot_form);
form.save();
}
});
});
}
});
});
});
/**
* 900000 - Повторять запросы каждые - 15 минут
*/
},900000);
/**
* ==============================================================================================================================================
* Правила для бота
* ==============================================================================================================================================
*/
bot.onText(/\/start/, message => {
var upChatID = message.chat.id;
isAuth(upChatID,function(data){
if(!data){
bot.sendMessage(upChatID,OPTIONS.botText.t15.replace('$1',message.chat.first_name),BotKeyboard.guest.btns);
}else{
if(data['bot_user_access'].key == 0)
bot.sendMessage(upChatID,OPTIONS.botText.platform + OPTIONS.botText.t14.replace('$1',data.bot_user_name.value),BotKeyboard[(data['bot_user_type'].key=='1'?'admin':'user')].btns);
else command(upChatID).banned();
}
});
});
/**
* inline - кнопки
*/
bot.on('callback_query', query => {
switch(query.data){
case 'logout_yes':
new users(query).logout_yes();
break;
case 'logout_no':
new users(query).logout_no();
break;
default:
try{
//log(query);
}catch(err){
log(err);
bot.answerCallbackQuery({callback_query_id:query.id});
}
}
bot.answerCallbackQuery({callback_query_id:query.id});
});
/**
* Вызов действий по кнопкам в клавиатуре происходит тут
*/
bot.on('message', message => {
var upChatID = message.chat.id;
switch(message.text){
case OPTIONS.events.auth:
isAuth(upChatID,function(data){
if(!data) new users(message,true).auth();
else bot.sendMessage(upChatID,botText.platform + OPTIONS.botText.t16,BotKeyboard[(data['bot_user_type'].key=='1'?'admin':'user')].btns);
});
break;
case OPTIONS.events.logout:
isAuth(upChatID,function(data){
if(!data) command(upChatID).access();
else logout(message);
});
break;
case OPTIONS.events.holiday:
isAuth(upChatID,function(data){
if(!data){
command(upChatID).access();
}else{
api(data['bot_user_data'].value, 'personalrecord/forms/' + data['bot_user_id'].value,function(forms){
forms.forEach(function (item) {
if (item.formCode == 'Отпуска_сотрудников') {
api(data['bot_user_data'].value, 'asforms/data/' + item['data-uuid'], function (res) {
res.data.forEach(function (item) {
if (item.id == 'all_days') {
bot.sendMessage(upChatID, OPTIONS.botText.platform + (!item.value?OPTIONS.botText.t17:OPTIONS.botText.t18.replace('$1',item.value)),{parse_mode:'HTML'});
return;
}
});
});
}
});
});
}
});
break;
case OPTIONS.events.userList:
isAuth(upChatID,function(data) {
if(!data || data['bot_user_type'].key == '0' || data['bot_user_access'].key == '1') command(upChatID).access();
else
userList(upChatID,'users', function (list) {
var text = OPTIONS.botText.t20;
if(list.length < 1) text += OPTIONS.botText.t19;
list.forEach(function(item,k){
text += "\n<b>" + (k+1) + ".</b> " + item;
});
bot.sendMessage(message.chat.id,text,{parse_mode: 'HTML'});
});
});
break;
case OPTIONS.events.bannedList:
isAuth(upChatID,function(data) {
if(!data || data['bot_user_type'].key == '0' || data['bot_user_access'].key == '1') command(upChatID).access();
else userList(upChatID,'banned', function (list) {
var text = OPTIONS.botText.t21;
if(list.length < 1) text += OPTIONS.botText.t19;
list.forEach(function(item,k){
text += "\n<b>" + (k+1) + ".</b> " + item;
});
bot.sendMessage(message.chat.id,text,{parse_mode: 'HTML'});
});
});
break;
case OPTIONS.events.adminList:
isAuth(upChatID,function(data) {
if(!data || data['bot_user_type'].key == '0' || data['bot_user_access'].key == '1') command(upChatID).access();
else userList(upChatID,'admins', function (list) {
var text = OPTIONS.botText.t22;
if(list.length < 1) text += OPTIONS.botText.t19;
list.forEach(function(item,k){
text += "\n<b>" + (k+1) + ".</b> " + item;
});
bot.sendMessage(message.chat.id,text,{parse_mode: 'HTML'});
});
});
break;
case OPTIONS.events.sendAllMess:
isAuth(upChatID,function(data) {
if(!data || data['bot_user_type'].key == '0' || data['bot_user_access'].key == '1') command(upChatID).access();
else new users(message,true).sendAllMessage(data);
});
break;
case OPTIONS.events.buyCutaway:
isAuth(upChatID,function(data) {
if(!data || data['bot_user_access'].key == '1') command(upChatID).access();
else new users(message,true).buyCutaway(data);
});
break;
case OPTIONS.events.profile:
isAuth(upChatID,function(data) {
if(!data) command(upChatID).access();
else new users(message,true).profile(data);
});
break;
default: try{/* log('Not method...'); */}catch(err){log(err);}
}
});
```
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment