diff --git a/mongodb/richieste_inviate_circuiti.mongodb b/mongodb/richieste_inviate_circuiti.mongodb index a045894..e04d8f0 100644 --- a/mongodb/richieste_inviate_circuiti.mongodb +++ b/mongodb/richieste_inviate_circuiti.mongodb @@ -2,18 +2,6 @@ use('test_FreePlanet'); let passo1 = [ - { - $match: { - idapp: "13", - "profile.mycircuits": { - $elemMatch: { - circuitname: { - $eq: "Riso Rovigo", - }, - }, - }, - }, - }, { $lookup: { from: "circuits", @@ -49,62 +37,6 @@ let passo1 = ]; -let passo1b = [ - { - $lookup: { - from: "accounts", - as: "account", - let: { - username: "$username", - idapp: "$idapp", - circuitId: "$circuit._id", - }, - pipeline: [ - { - $match: { - $expr: { - $and: [ - { - $eq: [ - "$$username", - "$username", - ], - }, - { - $eq: [ - "$$idapp", - "$idapp", - ], - }, - { - $eq: [ - "$$circuitId", - "$circuitId", - ], - }, - ], - }, - }, - }, - ], - }, - }, - { - $unwind: "$account", - }, - { - $match: { - idapp: "13", - }, - }, - { - $sort: { - desc: 1, - }, - }, - -]; - let passo1c = [ { $match: { @@ -122,6 +54,7 @@ let passo1c = [ let passo2 = [ { $project: { + name: 1, 'req_users': 1, }, }, @@ -238,9 +171,10 @@ if (test) { } else { // aggregation = [...aggregation, ...passo1]; aggregation = [...aggregation, ...passo1]; - // aggregation = [...aggregation, ...passo1b]; - // aggregation = [...aggregation, ...passo1c]; - // aggregation = [...aggregation, ...passo2]; + // aggregation = [...aggregation, ...passo1b]; + aggregation = [...aggregation, ...passo1c]; + aggregation = [...aggregation, ...passo2]; + aggregation = [...aggregation, ...passo2b]; } db.circuits.aggregate(aggregation); diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 8e7694c..039db5f 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -16,7 +16,7 @@ const CryptoJS = require('crypto-js'); const Url = require('url-parse'); -const {ObjectID} = require('mongodb'); +const { ObjectID } = require('mongodb'); const shared_consts = require('./shared_nodejs'); @@ -68,7 +68,7 @@ const textlang = { 'partecipanti a Cena': 'partecipanti a Cena', 'partecipanti a Cena Condivisa': 'partecipanti a Cena Condivisa', 'TESTO_ASSISTENZA': '👉 Per entrare nel Sito\n\n' + - '👉 Hai dimenticato la password?\n\n', + '👉 Hai dimenticato la password?\n\n', 'BENVENUTO': 'Benvenut@', 'TUE_NAVI': 'Ecco le tue Navi programmate', 'HAI_I_7_REQUISITI': 'PRIMI PASSI OK!\nHai i Primi Requisiti per Entrare nella Lista !', @@ -139,7 +139,7 @@ const textlang = { 'partecipanti a Pranzo': 'partecipanti a Pranzo', 'partecipanti a Cena': 'partecipanti a Cena', 'TESTO_ASSISTENZA': 'Para entrar en el sitio:\n%s\n\n' + - '¿Olvidó su contraseña para acceder al sitio?\nhttps://freeplanet.app/requestresetpwd\n\n', + '¿Olvidó su contraseña para acceder al sitio?\nhttps://freeplanet.app/requestresetpwd\n\n', 'BENVENUTO': 'Bienvenido', 'TUE_NAVI': 'Aquí están sus naves programadas', 'HAI_I_7_REQUISITI': '¡LOS PRIMEROS PASOS ESTÁN BIEN!\nTiene los primeros 7 requisitos para entrar en la lista de embarque!', @@ -204,7 +204,7 @@ const textlang = { 'partecipanti a Pranzo': 'partecipanti a Pranzo', 'partecipanti a Cena': 'partecipanti a Cena', 'TESTO_ASSISTENZA': 'To enter the Site:\n%s\n\nForgot your password to access the site?\n' + - 'https://freeplanet.app/requestresetpwd\nChat AYNI BOT (this one):\nhttps://t.me/notevoleaynibot\n\n', + 'https://freeplanet.app/requestresetpwd\nChat AYNI BOT (this one):\nhttps://t.me/notevoleaynibot\n\n', 'BENVENUTO': 'Welcome', 'TUE_NAVI': 'Here are your programmed ships', 'HAI_I_7_REQUISITI': 'FIRST STEPS OK!\nYou have the First 7 Requirements to Enter the Boarding List!', @@ -270,7 +270,7 @@ const textlang = { 'partecipanti a Pranzo': 'partecipanti a Pranzo', 'partecipanti a Cena': 'partecipanti a Cena', 'TESTO_ASSISTENZA': 'Pour entrer sur le site:\n%s\n\n' + - 'Vous avez oublié votre mot de passe pour accéder au site ?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n', + 'Vous avez oublié votre mot de passe pour accéder au site ?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n', 'BENVENUTO': 'Bienvenue', 'TUE_NAVI': 'Voici vos navires programmés', 'HAI_I_7_REQUISITI': 'PREMIÈRES ÉTAPES OK!\nvous avez les 7 premiers Requis pour Entrer dans la liste d\'embarquement!', @@ -338,7 +338,7 @@ const textlang = { 'partecipanti a Pranzo': 'partecipanti a Pranzo', 'partecipanti a Cena': 'partecipanti a Cena', 'TESTO_ASSISTENZA': 'Para entrar no site:\n%s\n\n' + - 'Esqueceu sua senha para acessar o site?\nhttps://freeplanet.app/requestresetpwd\n\n', + 'Esqueceu sua senha para acessar o site?\nhttps://freeplanet.app/requestresetpwd\n\n', 'BENVENUTO': 'Bem-vindo', 'TUE_NAVI': 'Aqui estão os seus navios programados', 'HAI_I_7_REQUISITI': 'PRIMEIROS PASSOS OK!\nVocê tem os 7 primeiros requisitos para entrar na lista de embarque!', @@ -527,31 +527,31 @@ module.exports = { } }, - getHostname: function() { + getHostname: function () { return os.hostname(); }, - testing: function() { + testing: function () { return (process.env.TESTING_ON === '1'); }, - mylog: function(...args) { + mylog: function (...args) { if (!this.testing()) console.log(args); }, - mylogoff: function(...args) { + mylogoff: function (...args) { // doing nothing }, - mylogshow: function(...args) { + mylogshow: function (...args) { console.log(args); }, - mylogserr: function(...args) { + mylogserr: function (...args) { console.error(args); }, - allfieldSendMsg: function() { + allfieldSendMsg: function () { return [ 'userId', 'source', @@ -566,7 +566,7 @@ module.exports = { 'options']; }, - allfieldSendNotif: function() { + allfieldSendNotif: function () { return [ 'type', 'userId', @@ -590,7 +590,7 @@ module.exports = { 'status']; }, - allfieldTodo: function() { + allfieldTodo: function () { return [ 'userId', 'pos', @@ -618,16 +618,16 @@ module.exports = { 'themebgcolor']; }, - allfieldMyEvent: function() { + allfieldMyEvent: function () { return ['userId']; }, - allfieldTodoWithId: function() { + allfieldTodoWithId: function () { return ['_id', ...this.allfieldTodo()]; }, // #TODO Projects++ Add fields ... - allfieldProject: function() { + allfieldProject: function () { return [ 'idapp', 'userId', @@ -669,7 +669,7 @@ module.exports = { 'view']; }, - allfieldBooking: function() { + allfieldBooking: function () { return [ 'idapp', 'userId', @@ -685,7 +685,7 @@ module.exports = { 'booked']; }, - allfieldBookingChange: function() { + allfieldBookingChange: function () { return [ 'numpeople', 'numpeopleLunch', @@ -698,7 +698,7 @@ module.exports = { 'booked']; }, - allfieldProjectWithId: function() { + allfieldProjectWithId: function () { return ['_id', ...this.allfieldProject()]; }, @@ -714,7 +714,7 @@ module.exports = { return myrec._doc; }, - sendBackNotif: function(subscription, payload) { + sendBackNotif: function (subscription, payload) { // console.log('sendBackNotif:', subscription, payload); @@ -730,24 +730,24 @@ module.exports = { // Pass object into sendNotification return webpush.sendNotification(subscription._doc, JSON.stringify(payload), - pushOptions). - catch((err) => { - if (err.statusCode === 410) { - // Gone: is not valid anymore (Expired probably!), so I have to delete from my db - return Subscription.findOneAndRemove({_id: subscription._id}); - } else { - console.log('Subscription is no longer valid: ', err); - } - }).then((ris) => { + pushOptions). + catch((err) => { + if (err.statusCode === 410) { + // Gone: is not valid anymore (Expired probably!), so I have to delete from my db + return Subscription.findOneAndRemove({ _id: subscription._id }); + } else { + console.log('Subscription is no longer valid: ', err); + } + }).then((ris) => { - }). - // console.log('sendNotification', ris); - catch(err => { - console.error(err); - }); + }). + // console.log('sendNotification', ris); + catch(err => { + console.error(err); + }); }, - sendNotificationToUser: async function(userId, title, content, openUrl, openUrl2, tag, actions, id) { + sendNotificationToUser: async function (userId, title, content, openUrl, openUrl2, tag, actions, id) { content = this.convertHTMLtoText(content); @@ -770,7 +770,7 @@ module.exports = { try { - return await Subscription.find({userId}, (err, subscriptions) => { + return await Subscription.find({ userId }, (err, subscriptions) => { if (err) { console.error(`Error occurred while getting subscriptions`); // res.status(500).json({ @@ -800,11 +800,11 @@ module.exports = { const audience = parsedUrl.protocol + '//' + parsedUrl.hostname; const vapidHeaders = webpush.getVapidHeaders( - audience, - process.env.VAPI_KEY_SUBJECT, - process.env.PUBLIC_VAPI_KEY, - process.env.PRIVATE_VAPI_KEY, - 'aes128gcm', + audience, + process.env.VAPI_KEY_SUBJECT, + process.env.PUBLIC_VAPI_KEY, + process.env.PRIVATE_VAPI_KEY, + 'aes128gcm', ); const pushOptions = { @@ -818,14 +818,14 @@ module.exports = { }; console.log('************ INVIO WEBPUSH.SENDNOTIFICATION N° ', - conta, '/', trovati, 'A', subscription.browser); + conta, '/', trovati, 'A', subscription.browser); const pushPayload = JSON.stringify(payload); webpush.sendNotification( - pushSubscription, - pushPayload, - pushOptions, + pushSubscription, + pushPayload, + pushOptions, ).then((value) => { // console.log('Invio Push', value); resolve({ @@ -837,7 +837,7 @@ module.exports = { console.error('err Push', err.body); // Cancella dal DB la notifica Push, visto che da errore! (sarà scaduto) - const ris = await Subscription.deleteOne({_id: subscription._id}); + const ris = await Subscription.deleteOne({ _id: subscription._id }); reject({ status: false, @@ -875,14 +875,14 @@ module.exports = { }; }, - sendNotificationByUsername: async function(idapp, username, cmd, telegram, usernameOrig) { + sendNotificationByUsername: async function (idapp, username, cmd, telegram, usernameOrig) { - var {User} = require('../models/user'); - const {SendNotif} = require('../models/sendnotif'); + var { User } = require('../models/user'); + const { SendNotif } = require('../models/sendnotif'); const telegrambot = require('../telegram/telegrambot'); - const user = await User.findOne({idapp, username}, {_id: 1, username: 1, lang: 1}).lean(); + const user = await User.findOne({ idapp, username }, { _id: 1, username: 1, lang: 1 }).lean(); if (!user) return; @@ -927,14 +927,14 @@ module.exports = { }, - sendNotifAndMsgTelegram: async function(idapp, userId, objmsg, telegram, msgextrateleg) { + sendNotifAndMsgTelegram: async function (idapp, userId, objmsg, telegram, msgextrateleg) { if (userId) { await this.sendNotificationToUser(userId, objmsg.title, objmsg.descr, objmsg.openUrl, '', objmsg.tag, objmsg.actions); } if (telegram) { - var {User} = require('../models/user'); + var { User } = require('../models/user'); const telegrambot = require('../telegram/telegrambot'); const idtelegram = await User.TelegIdById(idapp, userId); @@ -944,17 +944,17 @@ module.exports = { } }, - sendNotifGroupByUsername: async function( - cmd, idapp, usernameOrig, usernameDest, username_action, groupname, myrecgroup, isAdmin, username_worked) { + sendNotifGroupByUsername: async function ( + cmd, idapp, usernameOrig, usernameDest, username_action, groupname, myrecgroup, isAdmin, username_worked) { - const {SendNotif} = require('../models/sendnotif'); - const {User} = require('../models/user'); + const { SendNotif } = require('../models/sendnotif'); + const { User } = require('../models/user'); const telegrambot = require('../telegram/telegrambot'); const req = this.getReqByPar(idapp, usernameOrig); - const user = await User.findOne({idapp, username: usernameDest}, - {_id: 1, lang: 1}); + const user = await User.findOne({ idapp, username: usernameDest }, + { _id: 1, lang: 1 }); if (user) { let lang = user.lang; @@ -991,7 +991,7 @@ module.exports = { // paramsObj.options = MessageOptions.Notify_OnlyToNotifinApp + MessageOptions.Notify_ByBotTelegram; const myuserdata = await User.getUserShortDataByUsername(idapp, username_action); telegrambot.askConfirmationUser(idapp, shared_consts.CallFunz.RICHIESTA_GRUPPO, myuserdata, usernameDest, groupname, - myrecgroup._id); + myrecgroup._id); onlysave = false; } else if (cmd === shared_consts.GROUPSCMD.BLOCK_USER) { typeid = shared_consts.TypeNotifs.ID_GROUP_BLOCK_USER; @@ -1013,18 +1013,18 @@ module.exports = { }, - sendNotifCircuitByUsername: async function( - cmd, idapp, usernameOrig, usernameDest, username_action, - circuitname, path, myreccircuit, isAdmin, username_worked, extrarec) { + sendNotifCircuitByUsername: async function ( + cmd, idapp, usernameOrig, usernameDest, username_action, + circuitname, path, myreccircuit, isAdmin, username_worked, extrarec) { - const {SendNotif} = require('../models/sendnotif'); - const {User} = require('../models/user'); + const { SendNotif } = require('../models/sendnotif'); + const { User } = require('../models/user'); const telegrambot = require('../telegram/telegrambot'); const req = this.getReqByPar(idapp, usernameOrig); - const user = await User.findOne({idapp, username: usernameDest}, - {_id: 1, lang: 1}); + const user = await User.findOne({ idapp, username: usernameDest }, + { _id: 1, lang: 1 }); try { if (user) { @@ -1065,7 +1065,7 @@ module.exports = { // paramsObj.options = MessageOptions.Notify_OnlyToNotifinApp + MessageOptions.Notify_ByBotTelegram; const myuserdata = await User.getUserShortDataByUsername(idapp, username_action); telegrambot.askConfirmationUser(idapp, shared_consts.CallFunz.RICHIESTA_CIRCUIT, myuserdata, usernameDest, circuitname, - myreccircuit._id); + myreccircuit._id); onlysave = false; } else if (cmd === shared_consts.CIRCUITCMD.ADDADMIN) { typeid = shared_consts.TypeNotifs.ID_CIRCUIT_ADDED_ADMIN; @@ -1098,12 +1098,12 @@ module.exports = { }, - sendNotificationByGroupname: async function(idapp, usernameOrig, groupname, cmd, value, telegram, username_action) { + sendNotificationByGroupname: async function (idapp, usernameOrig, groupname, cmd, value, telegram, username_action) { - const {MyGroup} = require('../models/mygroup'); - const {User} = require('../models/user'); + const { MyGroup } = require('../models/mygroup'); + const { User } = require('../models/user'); - const group = await MyGroup.findOne({idapp, groupname}, {_id: 1, admins: 1, createdBy: 1}).lean(); + const group = await MyGroup.findOne({ idapp, groupname }, { _id: 1, admins: 1, createdBy: 1 }).lean(); if (!group) return; @@ -1135,11 +1135,11 @@ module.exports = { }, - sendNotificationByCircuit: async function(idapp, usernameOrig, circuitname, cmd, value, telegram, username_action, extrarec) { + sendNotificationByCircuit: async function (idapp, usernameOrig, circuitname, cmd, value, telegram, username_action, extrarec) { - const {Circuit} = require('../models/circuit'); + const { Circuit } = require('../models/circuit'); - const circuit = await Circuit.findOne({idapp, name: circuitname}, {_id: 1, admins: 1, createdBy: 1, path: 1}).lean(); + const circuit = await Circuit.findOne({ idapp, name: circuitname }, { _id: 1, admins: 1, createdBy: 1, path: 1 }).lean(); if (!circuit) return; @@ -1152,28 +1152,28 @@ module.exports = { let inviato = false; if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REQ || cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT || cmd === - shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) { + shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) { let recnotif = null; if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REQ) { recnotif = await this.sendNotifCircuitByUsername(shared_consts.CIRCUITCMD.SENDCOINS_REQ_SENT, idapp, extrarec.dest, usernameOrig, - username_action, circuitname, circuit.path, null, - false, '', extrarec); + username_action, circuitname, circuit.path, null, + false, '', extrarec); } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) { await this.sendNotifCircuitByUsername(shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT_SENT, idapp, extrarec.dest, usernameOrig, - username_action, circuitname, circuit.path, null, - false, '', extrarec); + username_action, circuitname, circuit.path, null, + false, '', extrarec); } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) { await this.sendNotifCircuitByUsername(shared_consts.CIRCUITCMD.SENDCOINS_REFUSE_SENT, idapp, extrarec.dest, usernameOrig, - username_action, circuitname, circuit.path, null, - false, '', extrarec); + username_action, circuitname, circuit.path, null, + false, '', extrarec); } if (recnotif) extrarec.notifIdToUpdate = recnotif._id; ris = await this.sendNotifCircuitByUsername(cmd, idapp, usernameOrig, extrarec.dest, username_action, circuitname, circuit.path, - null, - false, '', extrarec); + null, + false, '', extrarec); extrarec.notifIdToUpdate = ''; @@ -1189,7 +1189,7 @@ module.exports = { giainviato = true; await this.sendNotifCircuitByUsername(cmd, idapp, usernameOrig, singleadmin.username, username_action, circuitname, - circuit.path, circuit, true, '', extrarec); + circuit.path, circuit, true, '', extrarec); inviato = true; } } catch (e) { @@ -1200,18 +1200,18 @@ module.exports = { if (!giainviato && cmd !== shared_consts.CIRCUITCMD.REQ) { // SEND TO THE USER DEST THE NOTIFICATION ris = await this.sendNotifCircuitByUsername(cmd, idapp, usernameOrig, usernameOrig, username_action, circuitname, circuit.path, - null, - false, '', extrarec); + null, + false, '', extrarec); if (ris) inviato = true; } } - return {ris, inviato}; + return { ris, inviato }; } catch (e) { console.error('sendNotificationByCircuit: ', e); - return {ris: null, inviato: false}; + return { ris: null, inviato: false }; } }, @@ -1271,22 +1271,22 @@ module.exports = { */ sendNotifToAdmin(title, msg, tag = '') { - const {User} = require('../models/user'); + const { User } = require('../models/user'); // console.log('nomeapp 1: ' , this.getNomeAppByIdApp(1)); // console.log('nomeapp 2: ' , this.getNomeAppByIdApp(2)); - User.find({username: 'paoloar77', idapp: '1'}).then(async (arrusers) => { + User.find({ username: 'paoloar77', idapp: '1' }).then(async (arrusers) => { if (arrusers !== null) { for (const user of arrusers) { await this.sendNotificationToUser(user._id, title, msg, '/', '', tag, []). - then(ris => { - if (ris) { + then(ris => { + if (ris) { - } else { - // already sent the error on calling sendNotificationToUser - } - }); + } else { + // already sent the error on calling sendNotificationToUser + } + }); } } }); @@ -1307,11 +1307,11 @@ module.exports = { return { exit: true, ret: res.status(404). - send({code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER}), + send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }), }; } } else { - return {exit: false, ret: false}; + return { exit: false, ret: false }; } }, @@ -1355,7 +1355,7 @@ module.exports = { return msg; }, - getNomeAppByIdApp: function(idapp) { + getNomeAppByIdApp: function (idapp) { const myapp = this.MYAPPS.find(item => item.idapp === idapp); if (myapp) @@ -1364,13 +1364,13 @@ module.exports = { return ''; }, - getTimeExpReg: async function(idapp, username) { - var {User} = require('../models/user'); + getTimeExpReg: async function (idapp, username) { + var { User } = require('../models/user'); return await User.createNewReqRegistrationGetLink(idapp, username); }, - getLinkRegByIdAppAndMsgStrutt: function(idapp, msg, rec) { + getLinkRegByIdAppAndMsgStrutt: function (idapp, msg, rec) { let myapp = this.getHostByIdApp(idapp); if (myapp) { @@ -1380,12 +1380,12 @@ module.exports = { return myapp; }, - getHostByIdApp: function(idapp) { + getHostByIdApp: function (idapp) { const myapp = this.MYAPPS.find(item => item.idapp === idapp); if (myapp) { let siteport = (myapp.portapp && myapp.portapp !== '0') ? (':' + - myapp.portapp) : ''; + myapp.portapp) : ''; if (process.env.NODE_ENV === 'test') return myapp.host_test + siteport; @@ -1396,12 +1396,12 @@ module.exports = { return ''; }, - getLinkUserProfile: function(idapp, username) { + getLinkUserProfile: function (idapp, username) { return this.getHostByIdApp(idapp) + '/my/' + username; }, - getLinkUserTelegram: async function(idapp, username, myuser) { - var {User} = require('../models/user'); + getLinkUserTelegram: async function (idapp, username, myuser) { + var { User } = require('../models/user'); let u_tg = ''; if (myuser) @@ -1417,11 +1417,11 @@ module.exports = { return ''; }, - getLinkEditUserProfile: function(idapp) { + getLinkEditUserProfile: function (idapp) { return this.getHostByIdApp(idapp) + '/editprofile'; }, - getConfSiteOptionEnabledByIdApp: function(idapp, option) { + getConfSiteOptionEnabledByIdApp: function (idapp, option) { const myapp = this.MYAPPS.find(item => item.idapp === idapp); if (myapp) { @@ -1436,7 +1436,7 @@ module.exports = { return false; }, - getConfParamSiteByIdApp: function(idapp, field) { + getConfParamSiteByIdApp: function (idapp, field) { const myapp = this.MYAPPS.find(item => item.idapp === idapp); if (myapp) { @@ -1451,23 +1451,23 @@ module.exports = { return false; }, - isAbilitaNave: function(idapp) { + isAbilitaNave: function (idapp) { const myapp = this.MYAPPS.find(item => item.idapp === idapp); return myapp.abilitanave; }, - removeLastSlashFromPath: function(myString) { + removeLastSlashFromPath: function (myString) { let regex = /\/$/; let result = myString.replace(regex, ""); return result; }, - getdirByIdApp: function(idapp, dirmain = false) { + getdirByIdApp: function (idapp, dirmain = false) { let mypath = ''; const myapp = - this.MYAPPS.find(item => item.idapp === idapp); + this.MYAPPS.find(item => item.idapp === idapp); if (myapp) { if (process.env.NODE_ENV === 'test') mypath = (myapp) ? myapp.dir_test : ''; @@ -1484,7 +1484,7 @@ module.exports = { return this.removeLastSlashFromPath(mypath); }, - getAdminEmailByIdApp: function(idapp) { + getAdminEmailByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (myapp) return myapp.adminemail; @@ -1492,7 +1492,7 @@ module.exports = { return ''; }, - getreplyToEmailByIdApp: function(idapp) { + getreplyToEmailByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (myapp) return myapp.replyTo; @@ -1500,7 +1500,7 @@ module.exports = { return ''; }, - getpathregByIdApp: function(idapp, lang) { + getpathregByIdApp: function (idapp, lang) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (myapp) { const addstr = myapp.pathreg_add ? myapp.pathreg_add : ''; @@ -1511,7 +1511,7 @@ module.exports = { } }, - getAskToVerifyReg: function(idapp) { + getAskToVerifyReg: function (idapp) { return this.getConfSiteOptionEnabledByIdApp(idapp, shared_consts.ConfSite.Need_Aportador_On_DataReg_To_Verify_Reg); }, @@ -1520,7 +1520,7 @@ module.exports = { return (manag !== this.getAdminEmailByIdApp(idapp)) && (manag !== ''); }, - getManagerEmailByIdApp: function(idapp) { + getManagerEmailByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (myapp) return !!myapp.manageremail ? myapp.manageremail : ''; @@ -1528,17 +1528,17 @@ module.exports = { return ''; }, - getEmailByIdApp: function(idapp) { + getEmailByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); return (myapp) ? myapp.email_from : ''; }, - getPwdByIdApp: function(idapp) { + getPwdByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); return (myapp) ? this.decryptdata(myapp.email_pwd) : ''; }, - getTelegramBotNameByIdApp: function(idapp) { + getTelegramBotNameByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (process.env.NODE_ENV === 'test') return (myapp) ? myapp.telegram_bot_name_test : ''; @@ -1546,18 +1546,18 @@ module.exports = { return (myapp) ? myapp.telegram_bot_name : ''; }, - getTelegramSupportChat: function(idapp) { + getTelegramSupportChat: function (idapp) { try { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); return (myapp && myapp.telegram_support_chat) - ? myapp.telegram_support_chat - : ''; + ? myapp.telegram_support_chat + : ''; } catch (e) { return ''; } }, - getTelegramKeyByIdApp: function(idapp) { + getTelegramKeyByIdApp: function (idapp) { const myapp = this.MYAPPS.find((item) => item.idapp === idapp); if (process.env.NODE_ENV === 'test') return (myapp) ? myapp.telegram_key_test : ''; @@ -1565,7 +1565,38 @@ module.exports = { return (myapp) ? myapp.telegram_key : ''; }, - getLookup: function(params, num, pass_proj) { + getLookupPipeLine(params, proj) { + + let myquery = [ + { + $lookup: { + from: params.lk_tab, + let: { username: '$' + params.lk_LF, idapp: params.idapp }, + pipeline: [ + { + $match: + { + $expr: + { + $and: + [ + { $eq: ['$'+params.lk_FF, '$$'+params.lk_FF] }, + { $eq: ['$idapp', '$$idapp'] }, + ], + }, + }, + }, + ], + as: params.lk_as, + }, + }, + { $project: proj }, + ]; + + return myquery; + }, + + getLookup: function (params, num, pass_proj) { const query = []; if (!params) @@ -1574,9 +1605,9 @@ module.exports = { let mylkLF = params.lk_LF; if (params.af_objId_tab) { const myobj = {}; - myobj['myId' + num] = {'$toObjectId': '$' + params.lk_LF}; + myobj['myId' + num] = { '$toObjectId': '$' + params.lk_LF }; query.push( - {'$addFields': myobj}, + { '$addFields': myobj }, ); mylkLF = 'myId' + num; } else { @@ -1589,33 +1620,33 @@ module.exports = { proj = pass_proj; } query.push( - { - $lookup: { - from: params.lk_tab, - localField: mylkLF, // field in my collection - foreignField: params.lk_FF, // field in the 'from' collection - as: params.lk_as, + { + $lookup: { + from: params.lk_tab, + localField: mylkLF, // field in my collection + foreignField: params.lk_FF, // field in the 'from' collection + as: params.lk_as, + }, + }, + { + $replaceRoot: { + newRoot: { + $mergeObjects: [ + { + $arrayElemAt: [ + '$' + params.lk_as, 0], + }, '$$ROOT'], }, }, - { - $replaceRoot: { - newRoot: { - $mergeObjects: [ - { - $arrayElemAt: [ - '$' + params.lk_as, 0], - }, '$$ROOT'], - }, - }, - }, - {$project: proj}, + }, + { $project: proj }, ); } return query; }, - getFilterParam: function(filter, fieldsearch) { + getFilterParam: function (filter, fieldsearch) { let myregexp = {}; myregexp = new RegExp(filter.trim().replace(' ', '|'), 'ig'); @@ -1629,7 +1660,7 @@ module.exports = { } else if (rec.type === this.FieldType.string) { data[rec.field] = myregexp; } else if ((rec.type === this.FieldType.number) || - (rec.type === this.FieldType.hours)) { + (rec.type === this.FieldType.hours)) { data[rec.field] = parseFloat(filter.trim()); } if (data) @@ -1638,14 +1669,14 @@ module.exports = { if (myfilters.length > 0) { query = [ - {$match: {$or: myfilters}}, + { $match: { $or: myfilters } }, ]; } return query; }, - addQueryIdMatch: function(params) { + addQueryIdMatch: function (params) { myquery = {}; @@ -1679,7 +1710,7 @@ module.exports = { return myquery; }, - getQueryTable: async function(idapp, params, user) { + getQueryTable: async function (idapp, params, user) { if (typeof params.startRow !== 'number') { throw new Error('startRow must be number'); @@ -1710,47 +1741,47 @@ module.exports = { if (params.filterand) { if (params.filterand.includes( - shared_consts.FILTER_EXTRALIST_NOT_REGISTERED)) - filtriadded.push({registered: false}); + shared_consts.FILTER_EXTRALIST_NOT_REGISTERED)) + filtriadded.push({ registered: false }); if (params.filterand.includes( - shared_consts.FILTER_EXTRALIST_NOT_CONTACTED)) { - filtriadded.push({contacted: {$exists: false}}); + shared_consts.FILTER_EXTRALIST_NOT_CONTACTED)) { + filtriadded.push({ contacted: { $exists: false } }); } if (params.filterand.includes(shared_consts.FILTER_EXTRALIST_WITH_NOTE)) filtriadded.push({ - 'note': {$exists: true}, - '$expr': {'$gt': [{'$strLenCP': '$note'}, 1]}, + 'note': { $exists: true }, + '$expr': { '$gt': [{ '$strLenCP': '$note' }, 1] }, }); if (params.filterand.includes(shared_consts.FILTER_QUALIFIED)) - filtriadded.push({'profile.qualified': true}); + filtriadded.push({ 'profile.qualified': true }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_ZOOM)) - filtriadded.push({'profile.saw_zoom_presentation': false}); + filtriadded.push({ 'profile.saw_zoom_presentation': false }); if (params.filterand.includes(shared_consts.FILTER_ASK_ZOOM_VISTO)) - filtriadded.push({'profile.ask_zoom_partecipato': false}); + filtriadded.push({ 'profile.ask_zoom_partecipato': false }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_INVITANTE)) filtriadded.push({ - aportador_solidario: {$exists: false}, + aportador_solidario: { $exists: false }, }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_TELEGRAM_ID)) - filtriadded.push({'profile.teleg_id': {$lt: 1}}); + filtriadded.push({ 'profile.teleg_id': { $lt: 1 } }); if (params.filterand.includes(shared_consts.FILTER_USER_SI_TELEGRAM_ID)) - filtriadded.push({'profile.teleg_id': {$gt: 1}}); + filtriadded.push({ 'profile.teleg_id': { $gt: 1 } }); if (params.filterand.includes( - shared_consts.FILTER_USER_CODICE_AUTH_TELEGRAM)) - filtriadded.push({'profile.teleg_checkcode': {$gt: 1}}); + shared_consts.FILTER_USER_CODICE_AUTH_TELEGRAM)) + filtriadded.push({ 'profile.teleg_checkcode': { $gt: 1 } }); if (params.filterand.includes( - shared_consts.FILTER_USER_NO_EMAIL_VERIFICATA)) - filtriadded.push({verified_email: false}); + shared_consts.FILTER_USER_NO_EMAIL_VERIFICATA)) + filtriadded.push({ verified_email: false }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_VERIFIED_APORTADOR)) filtriadded.push({ - verified_by_aportador: {$exists: false}, + verified_by_aportador: { $exists: false }, }); if (params.filterand.includes(shared_consts.FILTER_USER_WITHOUT_USERNAME_TELEGRAM)) filtriadded.push({ $or: [ - {'profile.username_telegram': {$exists: false}}, - {'profile.username_telegram': {$exists: true, $eq: ''}}], + { 'profile.username_telegram': { $exists: false } }, + { 'profile.username_telegram': { $exists: true, $eq: '' } }], }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_DREAM)) @@ -1760,67 +1791,67 @@ module.exports = { }, }); if (params.filterand.includes(shared_consts.FILTER_USER_TELEGRAM_BLOCKED)) - filtriadded.push({'profile.teleg_id_old': {$gt: 1}}); + filtriadded.push({ 'profile.teleg_id_old': { $gt: 1 } }); if (params.filterand.includes(shared_consts.FILTER_ATTIVI)) filtriadded.push({ $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], }); // Hours if (params.filterand.includes(shared_consts.FILTER_HOURS_ALL)) filtriadded.push( - { - idapp, - todoId: params.codeId, - $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], - }, + { + idapp, + todoId: params.codeId, + $or: [ + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], + }, ); else if (params.filterand.includes(shared_consts.FILTER_HOURS_MYLIST)) filtriadded.push( - { - idapp, - userId: params.userId, - todoId: params.codeId, - $or: [ - {deleted: {$exists: false}}, - {deleted: {$exists: true, $eq: false}}], - }, + { + idapp, + userId: params.userId, + todoId: params.codeId, + $or: [ + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }], + }, ); if (params.filterand.includes(shared_consts.FILTER_NASCOSTI)) filtriadded.push({ - deleted: {$exists: true, $eq: true}, + deleted: { $exists: true, $eq: true }, }); if (params.filterand.includes(shared_consts.FILTER_NAVI_NON_PRESENTI)) filtriadded.push({ - navinonpresenti: {$exists: true, $eq: true}, + navinonpresenti: { $exists: true, $eq: true }, $or: [ - {subaccount: {$exists: false}}, - {subaccount: {$exists: true, $eq: false}}], + { subaccount: { $exists: false } }, + { subaccount: { $exists: true, $eq: false } }], }); // Iscritti Conacreis if (params.filterand.includes(shared_consts.FILTER_REPORTED)) filtriadded.push( - {reported: {$exists: true, $eq: true}}, + { reported: { $exists: true, $eq: true } }, ); if (params.filterand.includes( - shared_consts.FILTER_TO_MAKE_MEMBERSHIP_CARD)) + shared_consts.FILTER_TO_MAKE_MEMBERSHIP_CARD)) filtriadded.push({ $or: [ - {codiceConacreis: {$exists: false}}, - {codiceConacreis: {$exists: true, $eq: ''}}], + { codiceConacreis: { $exists: false } }, + { codiceConacreis: { $exists: true, $eq: '' } }], }); if (params.filterand.includes(shared_consts.FILTER_MEMBERSHIP_CARD_OK)) filtriadded.push({ - codiceConacreis: {$exists: true}, - '$expr': {'$gt': [{'$strLenCP': '$codiceConacreis'}, 0]}, + codiceConacreis: { $exists: true }, + '$expr': { '$gt': [{ '$strLenCP': '$codiceConacreis' }, 0] }, }); } @@ -1832,7 +1863,7 @@ module.exports = { myfilter['userId'] = ObjectID(myfilter['userId']); } if (myfilter['_idOBJ']) { - filtriadded.push({_id: ObjectID(myfilter['_idOBJ'])}); + filtriadded.push({ _id: ObjectID(myfilter['_idOBJ']) }); } else if (myfilter['dateTimeStart']) { const gte = myfilter['dateTimeStart'].$gte; const lte = myfilter['dateTimeStart'].$lte; @@ -1856,7 +1887,7 @@ module.exports = { for (const [key, value] of Object.entries(params.filter_gte[ind])) { if (value > 0) { let condition = {}; - condition[key] = {$gte: value}; + condition[key] = { $gte: value }; filtriadded.push(condition); } } @@ -1869,7 +1900,7 @@ module.exports = { if (params.options) { if (this.isBitActive(params.options, - shared_consts.OPTIONS_SEARCH_ONLY_FULL_WORDS)) { + shared_consts.OPTIONS_SEARCH_ONLY_FULL_WORDS)) { } } @@ -1881,11 +1912,11 @@ module.exports = { if (filtriadded) { if (filtriadded.length > 0) - query.push({$match: {$and: filtriadded}}); + query.push({ $match: { $and: filtriadded } }); } if (idapp > 0) { - query.push({$match: {idapp}}); + query.push({ $match: { idapp } }); } // console.log('QUERYMATCH', query[0].$match.or); @@ -1893,7 +1924,7 @@ module.exports = { if (params.sortBy) { // maybe we want to sort by blog title or something - const mysort = {$sort: params.sortBy}; + const mysort = { $sort: params.sortBy }; // console.log('sortBy', params.sortBy); // console.table(mysort); query.push(mysort); @@ -1909,40 +1940,40 @@ module.exports = { if (myq) query.push(myq); - query.push({$project: {req_users: 1}}); + query.push({ $project: { req_users: 1 } }); const qa1 = this.getLookup( - { - lk_tab: 'users', - lk_LF: 'req_users.username', - lk_FF: 'username', - lk_as: 'user', - }, 0, { - 'user.idapp': 1, - 'user.username': 1, - 'user.profile.img': 1, - 'user.profile.qualifica': 1, - }); + { + lk_tab: 'users', + lk_LF: 'req_users.username', + lk_FF: 'username', + lk_as: 'user', + }, 0, { + 'user.idapp': 1, + 'user.username': 1, + 'user.profile.img': 1, + 'user.profile.qualifica': 1, + }); if (qa1) query = [...query, ...qa1]; - query.push({$unwind: '$user'}); - + query.push({ $unwind: '$user' }); + query.push({ $match: { $and: [ - {'user.idapp': params.idapp}, + { 'user.idapp': params.idapp }, ], }, }); - + query.push({ - $replaceRoot: { - newRoot: '$user', - }, - }, + $replaceRoot: { + newRoot: '$user', + }, + }, ); } else if (params.querytype === shared_consts.QUERYTYPE_REFUSED_USER_GRP || params.querytype === - shared_consts.QUERYTYPE_REFUSED_USER_CIRCUIT) { + shared_consts.QUERYTYPE_REFUSED_USER_CIRCUIT) { /* const myq = this.addQueryIdMatch(params); @@ -1950,21 +1981,29 @@ module.exports = { query.push(myq); */ - query.push({$project: {refused_users: 1}}); - const qa1 = this.getLookup( - { - lk_tab: 'users', - lk_LF: 'refused_users.username', - lk_FF: 'username', - lk_as: 'user', - }, 0, { - 'user.idapp': 1, - 'user.username': 1, - 'user.profile.img': 1, - 'user.profile.qualifica': 1, - }); + const myq = this.addQueryIdMatch(params); + if (myq) + query.push(myq); + + query.push({ $project: { refused_users: 1 } }); + query.push({ $unwind: '$refused_users' }); + const qa1 = this.getLookupPipeLine( + { + lk_tab: 'users', + lk_LF: 'refused_users.username', + lk_FF: 'username', + lk_as: 'user', + idapp, + }, { + 'user.idapp': 1, + 'user.username': 1, + 'user.name': 1, + 'user.surname': 1, + 'user.profile.img': 1, + 'user.profile.qualifica': 1, + }); if (qa1) query = [...query, ...qa1]; - query.push({$unwind: '$user'}); + query.push({ $unwind: '$user' }); /* query.push({ $match: { @@ -1976,15 +2015,15 @@ module.exports = { */ query.push({ - $replaceRoot: { - newRoot: '$user', - }, - }, + $replaceRoot: { + newRoot: '$user', + }, + }, ); } else if (params.querytype === shared_consts.QUERYTYPE_LIST_MOVEMENTS) { - const {Movement} = require('../models/movement'); + const { Movement } = require('../models/movement'); const myquery = await Movement.getQueryMovsByCircuitId(params.idapp, params.username, params.myid); @@ -1992,7 +2031,7 @@ module.exports = { } else if (params.querytype === shared_consts.QUERYTYPE_LIST_ALLMOVEMENTS) { - const {Movement} = require('../models/movement'); + const { Movement } = require('../models/movement'); const myquery = await Movement.getQueryAllUsersMovsByCircuitId(params.idapp, params.myid); @@ -2010,18 +2049,18 @@ module.exports = { let proj = params.lookup2 ? params.lookup2.lk_proj : null; if (params.proj0) { - query.push({$project: params.proj0}); + query.push({ $project: params.proj0 }); } if (params.unwind0) { - query.push({$unwind: params.unwind0}); + query.push({ $unwind: params.unwind0 }); } const q1 = this.getLookup(params.lookup1, 1, proj); if (q1) query = [...query, ...q1]; if (params.unwind1) { - query.push({$unwind: params.unwind1}); + query.push({ $unwind: params.unwind1 }); } const q2 = this.getLookup(params.lookup2, 2, proj); @@ -2038,7 +2077,7 @@ module.exports = { if (params.filtersearch2) { if (params.filtersearch2.length > 0) { - query.push({$match: {$and: params.filtersearch2}}); + query.push({ $match: { $and: params.filtersearch2 } }); } } @@ -2063,15 +2102,15 @@ module.exports = { // Cerca tra i gruppi di ogni record, se combaciano almeno 1 condition = { 'profile.mygroups': - { - $elemMatch: { - groupname: {$in: arraygroups}, - }, + { + $elemMatch: { + groupname: { $in: arraygroups }, + }, - }, + }, }; - query.push({$match: {$and: [condition]}}); + query.push({ $match: { $and: [condition] } }); } else if (myfilter['pub_to_share'] === shared_consts.PUBTOSHARE.ONLY_TABLE_FOLLOW && params.table === 'circuits') { let arraycircuits = []; @@ -2084,15 +2123,15 @@ module.exports = { // Cerca tra i gruppi di ogni record, se combaciano almeno 1 condition = { 'profile.mycircuits': - { - $elemMatch: { - circuitname: {$in: arraycircuits}, - }, + { + $elemMatch: { + circuitname: { $in: arraycircuits }, + }, - }, + }, }; - query.push({$match: {$and: [condition]}}); + query.push({ $match: { $and: [condition] } }); } else if (shared_consts.TABLES_ENABLE_GETREC_BYID.includes(params.table)) { // Rimuovi dalla query quelli non visibili @@ -2106,26 +2145,26 @@ module.exports = { // Cerca tra i gruppi di ogni record, se combaciano almeno 1 condition = { 'profile.mygroups': - { - $elemMatch: { - groupname: {$in: arraygroups}, - }, + { + $elemMatch: { + groupname: { $in: arraygroups }, + }, - }, + }, }; query.push( + { + $match: { - $match: - { - $or: [ - { - $and: [condition, {pub_to_share: 1}], - }, - {$or: [{pub_to_share: {$exists: false}}, {pub_to_share: {$exists: true, $eq: shared_consts.PUBTOSHARE.ALL}}]}, - ], - }, + $or: [ + { + $and: [condition, { pub_to_share: 1 }], + }, + { $or: [{ pub_to_share: { $exists: false } }, { pub_to_share: { $exists: true, $eq: shared_consts.PUBTOSHARE.ALL } }] }, + ], }, + }, ); } @@ -2135,19 +2174,19 @@ module.exports = { if (params.filtersearch3or) { if (params.filtersearch3or.length > 0) { - query.push({$match: {$or: params.filtersearch3or}}); + query.push({ $match: { $or: params.filtersearch3or } }); } } if (params.filtersearch3and) { if (params.filtersearch3and.length > 0) { - query.push({$match: {$and: params.filtersearch3and}}); + query.push({ $match: { $and: params.filtersearch3and } }); } } if (params.filter && params.fieldsearch_last) { const querytemp = this.getFilterParam(params.filter, - params.fieldsearch_last); + params.fieldsearch_last); if (querytemp) { query = [...query, ...querytemp]; } @@ -2174,7 +2213,7 @@ module.exports = { ], }, ]; - query.push({$match: {$and: filter}}); + query.push({ $match: { $and: filter } }); } // } } @@ -2186,22 +2225,22 @@ module.exports = { } query.push( - { - $group: { - _id: null, - // get a count of every result that matches until now - count: {$sum: 1}, - // keep our results for the next operation - results: {$push: '$$ROOT'}, - }, + { + $group: { + _id: null, + // get a count of every result that matches until now + count: { $sum: 1 }, + // keep our results for the next operation + results: { $push: '$$ROOT' }, }, - // and finally trim the results to within the range given by start/endRow - { - $project: { - count: 1, - rows: {$slice: ['$results', params.startRow, numrowend]}, - }, + }, + // and finally trim the results to within the range given by start/endRow + { + $project: { + count: 1, + rows: { $slice: ['$results', params.startRow, numrowend] }, }, + }, ); // console.log('query', query); @@ -2231,9 +2270,9 @@ module.exports = { // console.table(ris.rows); // console.log('ROW ', ris.count); - return ({count: ris.count, rows: ris.rows}); + return ({ count: ris.count, rows: ris.rows }); } else { - return ({count: 0, rows: []}); + return ({ count: 0, rows: [] }); } } catch (e) { console.log('error', e); @@ -2536,10 +2575,10 @@ module.exports = { if (mydate) { // console.log('getstrDate', mytimestamp) return this.getWeekDayByLang(mydate, lang) + ' ' + - this.appendLeadingZeroes(mydate.getDate()) + '/' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + ' ORE ' + - this.appendLeadingZeroes(mydate.getHours()) + ':' + - this.appendLeadingZeroes(mydate.getMinutes()); + this.appendLeadingZeroes(mydate.getDate()) + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + ' ORE ' + + this.appendLeadingZeroes(mydate.getHours()) + ':' + + this.appendLeadingZeroes(mydate.getMinutes()); } else { return ''; } @@ -2549,8 +2588,8 @@ module.exports = { if (mydate) { // console.log('getstrDate', mytimestamp) return this.getWeekDayByLang(mydate, lang).substring(0, 3) + ' ' + - this.appendLeadingZeroes(mydate.getDate()) + '/' + - this.appendLeadingZeroes(mydate.getMonth() + 1); + this.appendLeadingZeroes(mydate.getDate()) + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1); } else { return ''; } @@ -2560,8 +2599,8 @@ module.exports = { if (mydate) { // console.log('getstrDate', mytimestamp) return this.appendLeadingZeroes(mydate.getDate()) + '/' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + - this.appendLeadingZeroes(mydate.getFullYear()); + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + + this.appendLeadingZeroes(mydate.getFullYear()); } else { return ''; } @@ -2571,8 +2610,8 @@ module.exports = { if (mydate) { // console.log('getstrDate', mytimestamp) return mydate.getFullYear() + '-' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + - this.appendLeadingZeroes(mydate.getDate()); + this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + + this.appendLeadingZeroes(mydate.getDate()); } else { return ''; } @@ -2582,8 +2621,8 @@ module.exports = { if (mydate) { // console.log('getstrDate', mytimestamp) return mydate.getUTCFullYear() + '-' + - this.appendLeadingZeroes(mydate.getUTCMonth() + 1) + '-' + - this.appendLeadingZeroes(mydate.getUTCDate()); + this.appendLeadingZeroes(mydate.getUTCMonth() + 1) + '-' + + this.appendLeadingZeroes(mydate.getUTCDate()); } else { return ''; } @@ -2593,9 +2632,9 @@ module.exports = { if (mydate) { // console.log('getstrDate', mytimestamp) return this.getWeekDayByLang(mydate, lang) + ' ' + - this.appendLeadingZeroes(mydate.getDate()) + '/' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + - mydate.getFullYear(); + this.appendLeadingZeroes(mydate.getDate()) + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + + mydate.getFullYear(); } else { return ''; } @@ -2605,9 +2644,9 @@ module.exports = { if (mydate) { // console.log('getstrDate', mytimestamp) return this.getWeekDayByLangTot(mydate, lang) + ' ' + - this.appendLeadingZeroes(mydate.getDate()) + '/' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + - mydate.getFullYear(); + this.appendLeadingZeroes(mydate.getDate()) + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + + mydate.getFullYear(); } else { return ''; } @@ -2617,9 +2656,9 @@ module.exports = { if (mydate) { // console.log('getstrDate', mytimestamp) return mydate.getFullYear() + '-' + - this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + - this.appendLeadingZeroes(mydate.getDate()) + ' (' + - this.getWeekDayByLang(mydate, lang) + ')'; + this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + + this.appendLeadingZeroes(mydate.getDate()) + ' (' + + this.getWeekDayByLang(mydate, lang) + ')'; } else { return ''; } @@ -2653,7 +2692,7 @@ module.exports = { }, getHash(mystr) { - return CryptoJS.SHA512(mystr, {outputLength: 256}).toString(); + return CryptoJS.SHA512(mystr, { outputLength: 256 }).toString(); }, encrypt(msg, pass) { @@ -2713,7 +2752,7 @@ module.exports = { // const bytes = CryptoJS.AES.decrypt(mydatacrypted.toString(), process.env.SECRK); // return JSON.parse(bytes.toString(CryptoJS.enc.Utf8)); return this.decrypt(mydatacrypted, process.env.SECRK). - toString(CryptoJS.enc.Utf8); + toString(CryptoJS.enc.Utf8); }, BoolToInt(mybool) { @@ -2732,7 +2771,7 @@ module.exports = { try { mystr = this.getstrDateTimeShort(new Date(), 'it') + ': ' + mystr; - const stream = fs.createWriteStream(filename, {flags: 'a'}); + const stream = fs.createWriteStream(filename, { flags: 'a' }); stream.write('\n' + mystr); stream.end(); } catch (e) { @@ -2789,7 +2828,7 @@ module.exports = { move(oldPath, newPath, callback) { - fs.rename(oldPath, newPath, function(err) { + fs.rename(oldPath, newPath, function (err) { if (err) { if (err.code === 'EXDEV') { copy(); @@ -2811,7 +2850,7 @@ module.exports = { readStream.on('error', callback); writeStream.on('error', callback); - readStream.on('close', function() { + readStream.on('close', function () { console.log('cancella file già copiato', oldPath); fs.unlink(oldPath, callback); }); @@ -2828,22 +2867,22 @@ module.exports = { }); }, - extractFileName: function(filename) { + extractFileName: function (filename) { return path.basename(filename); }, - extractFilePath: function(filename) { + extractFilePath: function (filename) { return path.dirname(filename); }, delete(mypath, alsothumb, callback) { - fs.unlink(mypath, function(err) { + fs.unlink(mypath, function (err) { if (alsothumb) { try { let img_small = path.dirname(mypath) + '/' + - server_constants.PREFIX_IMG_SMALL + path.basename(mypath); - fs.unlink(img_small, function(err) { + server_constants.PREFIX_IMG_SMALL + path.basename(mypath); + fs.unlink(img_small, function (err) { if (err) console.log('Errore durante la Cancellazione del file', mypath); else @@ -2866,7 +2905,7 @@ module.exports = { mkdirpath(dirPath) { if (!fs.existsSync(dirPath)) { try { - fs.mkdirSync(dirPath, {recursive: true}); + fs.mkdirSync(dirPath, { recursive: true }); } catch (e) { if (dirPath !== path.dirname(dirPath)) { const myname = path.dirname(dirPath); @@ -2961,7 +3000,7 @@ module.exports = { NotifyIfDelRecord(table) { if ((table === 'users') || (table === 'extralist') || - (table === 'groups') || (table === 'graduatorias')) { + (table === 'groups') || (table === 'graduatorias')) { return true; } @@ -3068,8 +3107,8 @@ module.exports = { for (i = 0, len = str.length; i < len; i++) { code = str.charCodeAt(i); if (!(code > 47 && code < 58) && // numeric (0-9) - !(code > 64 && code < 91) && // upper alpha (A-Z) - !(code > 96 && code < 123)) { // lower alpha (a-z) + !(code > 64 && code < 91) && // upper alpha (A-Z) + !(code > 96 && code < 123)) { // lower alpha (a-z) return false; } } @@ -3082,11 +3121,11 @@ module.exports = { for (i = 0, len = str.length; i < len; i++) { code = str.charCodeAt(i); if (!(code > 47 && code < 58) && // numeric (0-9) - !(code > 63 && code < 91) && // upper alpha (A-Z) // e @ - (code !== 46) && // . (punto) - (code !== 95) && // _ - (code !== 45) && // - - !(code > 96 && code < 123)) { // lower alpha (a-z) + !(code > 63 && code < 91) && // upper alpha (A-Z) // e @ + (code !== 46) && // . (punto) + (code !== 95) && // _ + (code !== 45) && // - + !(code > 96 && code < 123)) { // lower alpha (a-z) return false; } } @@ -3113,7 +3152,7 @@ module.exports = { for (const r of queryObj[i]) { range_arr = r.split('-'); query_arr.push({ - price: {$gt: range_arr[0], $lt: range_arr[1]}, + price: { $gt: range_arr[0], $lt: range_arr[1] }, }); } } @@ -3121,17 +3160,17 @@ module.exports = { if (queryObj[i].constructor === String) { range_arr = queryObj[i].split('-'); query_arr.push({ - price: {$gt: range_arr[0], $lt: range_arr[1]}, + price: { $gt: range_arr[0], $lt: range_arr[1] }, }); } - Object.assign(query, {$or: query_arr}); + Object.assign(query, { $or: query_arr }); delete query[i]; continue; } query[i] = queryObj[i]; } } - return {query, order}; + return { query, order }; }, dateToEpoch(thedate) { @@ -3278,25 +3317,25 @@ module.exports = { return msg; }, - getUserInfoMsg: function(idapp, myuser, usernametelegram = '', name_telegram = '', - surname_telegram = '') { + getUserInfoMsg: function (idapp, myuser, usernametelegram = '', name_telegram = '', + surname_telegram = '') { let msg = ''; try { const name = myuser.username + - (myuser.name ? ` (${myuser.name} ${myuser.surname})` : ''); + (myuser.name ? ` (${myuser.name} ${myuser.surname})` : ''); const linkuserprof = this.getHostByIdApp(idapp) + '/my/' + - myuser.username; + myuser.username; msg = `
Username: ${name}
Profilo su APP: ${linkuserprof}
Email: ${myuser.email}`; let u_tg = myuser.profile && myuser.profile.hasOwnProperty('username_telegram') ? myuser.profile.username_telegram : usernametelegram; let name_tg = myuser.profile && myuser.profile.hasOwnProperty('firstname_telegram') - ? myuser.profile.firstname_telegram - : name_telegram; + ? myuser.profile.firstname_telegram + : name_telegram; let surname_tg = myuser.profile && myuser.profile.hasOwnProperty('lastname_telegram') - ? myuser.profile.lastname_telegram - : surname_telegram; + ? myuser.profile.lastname_telegram + : surname_telegram; if (u_tg) { msg += `
Profilo su Telegram [${name_tg} ${surname_tg}]:
https://t.me/${u_tg}`; @@ -3308,19 +3347,19 @@ module.exports = { return msg; }, - getlinkRelativeRequestNewPassword: function(idapp, email, tokenforgot) { + getlinkRelativeRequestNewPassword: function (idapp, email, tokenforgot) { const strlinkreg = process.env.LINK_UPDATE_PASSWORD + - `?idapp=${idapp}&email=${email}&tokenforgot=${tokenforgot}`; + `?idapp=${idapp}&email=${email}&tokenforgot=${tokenforgot}`; return strlinkreg; }, - getlinkRequestNewPassword: function(idapp, email, tokenforgot) { + getlinkRequestNewPassword: function (idapp, email, tokenforgot) { const strlinkreg = this.getHostByIdApp(idapp) + this.getlinkRelativeRequestNewPassword(idapp, email, tokenforgot); return strlinkreg; }, - execScript: function(idapp, msg, script, testo) { - const {exec} = require('child_process'); + execScript: function (idapp, msg, script, testo) { + const { exec } = require('child_process'); const telegrambot = require('../telegram/telegrambot'); const idchat = msg.chat.id;