From 3d6455f23ca59a2032926950b51b7c47f2600378 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Fri, 30 May 2025 16:45:01 +0200 Subject: [PATCH] - generazione della raccolta PDF OK !!! --- src/server/models/raccoltacataloghi.js | 1 + src/server/models/user.js | 3042 ++++++++++++------------ src/server/modules/GenPdf.js | 3 +- src/server/router/admin_router.js | 127 +- src/server/router/users_router.js | 2 +- src/server/tools/general.js | 6 +- 6 files changed, 1653 insertions(+), 1528 deletions(-) diff --git a/src/server/models/raccoltacataloghi.js b/src/server/models/raccoltacataloghi.js index 0b480a3..1b0d85d 100755 --- a/src/server/models/raccoltacataloghi.js +++ b/src/server/models/raccoltacataloghi.js @@ -37,6 +37,7 @@ const RaccoltaCataloghiSchema = new Schema({ nomefile_da_generare: String, + pdf_generato: String, pdf_generato_size: String, pdf_generato_stampa: String, data_generato: { diff --git a/src/server/models/user.js b/src/server/models/user.js index 14b2514..9947b9c 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -30,12 +30,11 @@ const i18n = require('i18n'); const shared_consts = require('../tools/shared_nodejs'); - mongoose.Promise = global.Promise; mongoose.level = 'F'; // Resolving error Unknown modifier: $pushAll -mongoose.plugin(schema => { +mongoose.plugin((schema) => { schema.options.usePushEach = true; }); @@ -133,7 +132,8 @@ const UserSchema = new mongoose.Schema({ date_login: { type: Date, }, - }], + }, + ], perm: { type: Number, }, @@ -187,9 +187,10 @@ const UserSchema = new mongoose.Schema({ type: Boolean, }, lastid_newstosent: { - type: String + type: String, }, - aportador_solidario: { // da cancellare + aportador_solidario: { + // da cancellare type: String, }, verified_by_aportador: { @@ -403,38 +404,44 @@ const UserSchema = new mongoose.Schema({ { description: { type: String }, rating: { type: Number }, - }], + }, + ], friends: [ { _id: false, username: { type: String }, date: { type: Date }, - }], // username + }, + ], // username req_friends: [ { _id: false, username: { type: String }, date: { type: Date }, - }], // username + }, + ], // username handshake: [ { _id: false, username: { type: String }, date: { type: Date }, - }], // username + }, + ], // username mygroups: [ { _id: false, groupname: { type: String }, date: { type: Date }, - }], + }, + ], mycircuits: [ { _id: false, circuitname: { type: String }, date: { type: Date }, - }], + }, + ], last_circuitpath: { type: String, }, @@ -454,23 +461,28 @@ const UserSchema = new mongoose.Schema({ notif_idCities: [ { type: Number, - }], + }, + ], notif_provinces: [ { type: String, - }], + }, + ], notif_regions: [ { type: String, - }], + }, + ], notif_sectors: [ { type: Number, - }], + }, + ], notif_sector_goods: [ { type: Number, - }], + }, + ], resid_prov_id: { type: Number, }, @@ -530,8 +542,6 @@ const UserSchema = new mongoose.Schema({ }, }); - - UserSchema.methods.toJSON = function () { const user = this; const userObject = user.toObject(); @@ -548,7 +558,7 @@ UserSchema.methods.generateAuthToken = function (req) { const access = 'auth'; const browser = useragent; - const prova = 'PROVAMSG@1A' + const prova = 'PROVAMSG@1A'; let attiva_scadenza = user.idapp ? tools.getEnableTokenExpiredByIdApp(user.idapp) : false; let token = null; @@ -556,32 +566,41 @@ UserSchema.methods.generateAuthToken = function (req) { let numsec = process.env.TOKEN_LIFE; if (attiva_scadenza) - token = jwt.sign({ _id: prova, smart: user._id.toHexString(), access, un: user.username }, - process.env.SIGNCODE, { expiresIn: numsec }).toString(); + token = jwt + .sign({ _id: prova, smart: user._id.toHexString(), access, un: user.username }, process.env.SIGNCODE, { + expiresIn: numsec, + }) + .toString(); else - token = jwt.sign({ _id: prova, smart: user._id.toHexString(), access, un: user.username }, - process.env.SIGNCODE).toString(); + token = jwt + .sign({ _id: prova, smart: user._id.toHexString(), access, un: user.username }, process.env.SIGNCODE) + .toString(); - const refreshToken = jwt.sign({ _id: prova, smart: user._id.toHexString(), access, un: user.username }, - process.env.SECRK, { expiresIn: process.env.REFRESH_TOKEN_LIFE }).toString(); + const refreshToken = jwt + .sign({ _id: prova, smart: user._id.toHexString(), access, un: user.username }, process.env.SECRK, { + expiresIn: process.env.REFRESH_TOKEN_LIFE, + }) + .toString(); const date_login = new Date(); // CANCELLA IL PRECEDENTE ! user.tokens = user.tokens.filter(function (tok) { - return (tok.access !== access) || - ((tok.access === access) && (tok.browser !== browser)); + return tok.access !== access || (tok.access === access && tok.browser !== browser); }); user.tokens.push({ access, browser, token, date_login, refreshToken }); user.lasttimeonline = new Date(); - return user.save().then(() => { - return { token, refreshToken }; - }).catch(err => { - console.log('Error', err.message); - return { token: '', refreshToken: '' } - }); + return user + .save() + .then(() => { + return { token, refreshToken }; + }) + .catch((err) => { + console.log('Error', err.message); + return { token: '', refreshToken: '' }; + }); }; UserSchema.statics.setOnLine = async function (idapp, username) { @@ -589,23 +608,16 @@ UserSchema.statics.setOnLine = async function (idapp, username) { try { return await User.findOneAndUpdate({ idapp, username }, { $set: { lasttimeonline: new Date() } }); - } catch (e) { - - } - + } catch (e) {} }; - UserSchema.statics.setPermissionsById = function (id, perm) { const user = this; return user.findByIdAndUpdate(id, { $set: { perm } }).then((user) => { - if (user) - return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); - else - return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); + if (user) return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); + else return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); }); - }; UserSchema.statics.setZoomPresenza = async function (idapp, id, presenza) { @@ -615,29 +627,27 @@ UserSchema.statics.setZoomPresenza = async function (idapp, id, presenza) { let allData = {}; allData.myuser = await User.getUserById(idapp, id); - if (!!allData.myuser) - allData.precDataUser = await User.getInfoUser(idapp, - allData.myuser.username); + if (!!allData.myuser) allData.precDataUser = await User.getInfoUser(idapp, allData.myuser.username); - return await User.findByIdAndUpdate(id, - { $set: { 'profile.saw_zoom_presentation': presenza } }).then((rec) => { - if (presenza) { - const messaggio = tools.get__('ZOOM_CONFERMATO'); - telegrambot.sendMsgTelegram(rec.idapp, rec.username, messaggio); - telegrambot.sendMsgTelegramToTheManagersAndZoomeri(idapp, - `L\'utente ${rec.name} ${rec.surname} (${rec.username}) è stato confermato per aver visto lo Zoom di Benvenuto`); - } else { - telegrambot.sendMsgTelegramToTheManagersAndZoomeri(idapp, - `L\'utente ${rec.name} ${rec.surname} (${rec.username}) è stato annullata la sua richiesta per aver visto lo Zoom di Benvenuto! (Non ci risulta)`); - } + return await User.findByIdAndUpdate(id, { $set: { 'profile.saw_zoom_presentation': presenza } }).then((rec) => { + if (presenza) { + const messaggio = tools.get__('ZOOM_CONFERMATO'); + telegrambot.sendMsgTelegram(rec.idapp, rec.username, messaggio); + telegrambot.sendMsgTelegramToTheManagersAndZoomeri( + idapp, + `L\'utente ${rec.name} ${rec.surname} (${rec.username}) è stato confermato per aver visto lo Zoom di Benvenuto` + ); + } else { + telegrambot.sendMsgTelegramToTheManagersAndZoomeri( + idapp, + `L\'utente ${rec.name} ${rec.surname} (${rec.username}) è stato annullata la sua richiesta per aver visto lo Zoom di Benvenuto! (Non ci risulta)` + ); + } - return User.findByIdAndUpdate(id, - { $set: { 'profile.ask_zoom_partecipato': false } }).then((user) => { - - User.checkIfSbloccatiRequisiti(idapp, allData, id); - }); + return User.findByIdAndUpdate(id, { $set: { 'profile.ask_zoom_partecipato': false } }).then((user) => { + User.checkIfSbloccatiRequisiti(idapp, allData, id); }); - + }); }; UserSchema.statics.canHavePower = function (perm) { @@ -645,8 +655,13 @@ UserSchema.statics.canHavePower = function (perm) { try { let consentito = false; - if (User.isAdmin(perm) || User.isManager(perm) || - User.isEditor(perm) || User.isCommerciale(perm) || User.isFacilitatore(perm)) { + if ( + User.isAdmin(perm) || + User.isManager(perm) || + User.isEditor(perm) || + User.isCommerciale(perm) || + User.isFacilitatore(perm) + ) { consentito = true; } @@ -658,8 +673,7 @@ UserSchema.statics.canHavePower = function (perm) { UserSchema.statics.isAdmin = function (perm) { try { - return ((perm & shared_consts.Permissions.Admin) === - shared_consts.Permissions.Admin); + return (perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin; } catch (e) { return false; } @@ -667,8 +681,14 @@ UserSchema.statics.isAdmin = function (perm) { UserSchema.statics.isManager = function (perm) { try { - return ((perm & shared_consts.Permissions.Manager) === - shared_consts.Permissions.Manager); + return (perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager; + } catch (e) { + return false; + } +}; +UserSchema.statics.isCollaboratore = function (perm) { + try { + return User.canHavePower(perm); } catch (e) { return false; } @@ -677,8 +697,7 @@ UserSchema.statics.isManager = function (perm) { UserSchema.statics.isManagerById = async function (id) { try { const ris = await User.findOne({ _id: id }, { perm: 1 }).lean(); - return ((ris.perm & shared_consts.Permissions.Manager) === - shared_consts.Permissions.Manager); + return (ris.perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager; } catch (e) { return false; } @@ -687,8 +706,7 @@ UserSchema.statics.isManagerById = async function (id) { UserSchema.statics.isAdminById = async function (id) { try { const ris = await User.findOne({ _id: id }, { perm: 1 }).lean(); - return ((ris.perm & shared_consts.Permissions.Admin) === - shared_consts.Permissions.Admin); + return (ris.perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin; } catch (e) { return false; } @@ -696,24 +714,21 @@ UserSchema.statics.isAdminById = async function (id) { UserSchema.statics.isEditor = function (perm) { try { - return ((perm & shared_consts.Permissions.Editor) === - shared_consts.Permissions.Editor); + return (perm & shared_consts.Permissions.Editor) === shared_consts.Permissions.Editor; } catch (e) { return false; } }; UserSchema.statics.isCommerciale = function (perm) { try { - return ((perm & shared_consts.Permissions.Commerciale) === - shared_consts.Permissions.Commerciale); + return (perm & shared_consts.Permissions.Commerciale) === shared_consts.Permissions.Commerciale; } catch (e) { return false; } }; UserSchema.statics.isGrafico = function (perm) { try { - return ((perm & shared_consts.Permissions.Grafico) === - shared_consts.Permissions.Grafico); + return (perm & shared_consts.Permissions.Grafico) === shared_consts.Permissions.Grafico; } catch (e) { return false; } @@ -721,8 +736,7 @@ UserSchema.statics.isGrafico = function (perm) { UserSchema.statics.isZoomeri = function (perm) { try { - return ((perm & shared_consts.Permissions.Zoomeri) === - shared_consts.Permissions.Zoomeri); + return (perm & shared_consts.Permissions.Zoomeri) === shared_consts.Permissions.Zoomeri; } catch (e) { return false; } @@ -730,8 +744,7 @@ UserSchema.statics.isZoomeri = function (perm) { UserSchema.statics.isDepartment = function (perm) { try { - return ((perm & shared_consts.Permissions.Zoomeri) === - shared_consts.Permissions.Department); + return (perm & shared_consts.Permissions.Zoomeri) === shared_consts.Permissions.Department; } catch (e) { return false; } @@ -739,8 +752,7 @@ UserSchema.statics.isDepartment = function (perm) { UserSchema.statics.isFacilitatore = function (perm) { try { - return ((perm & shared_consts.Permissions.Facilitatore) === - shared_consts.Permissions.Facilitatore); + return (perm & shared_consts.Permissions.Facilitatore) === shared_consts.Permissions.Facilitatore; } catch (e) { return false; } @@ -775,7 +787,6 @@ UserSchema.statics.findByToken = async function (token, typeaccess, con_auth, wi return { user, code }; } - try { decoded = jwt.verify(token, process.env.SIGNCODE); code = server_constants.RIS_CODE_OK; @@ -797,47 +808,63 @@ UserSchema.statics.findByToken = async function (token, typeaccess, con_auth, wi if (withuser) { const start_find = process.hrtime.bigint(); if (withlean) { - user = await User.findOne({ - _id: decoded.smart, - tokens: { - $elemMatch: { - token, - access: typeaccess, + user = await User.findOne( + { + _id: decoded.smart, + tokens: { + $elemMatch: { + token, + access: typeaccess, + }, }, }, - }, project).lean(); + project + ).lean(); } else { - user = await User.findOne({ - _id: decoded.smart, - tokens: { - $elemMatch: { - token, - access: typeaccess, + user = await User.findOne( + { + _id: decoded.smart, + tokens: { + $elemMatch: { + token, + access: typeaccess, + }, }, }, - }, project); + project + ); } const end_find = process.hrtime.bigint(); // console.log(` User.findOne impiega ${Math.round(Number(end_find - start_find) / 1e6) / 1000} secondi.`); } else { - - project = { perm: 1, _id: 1, idapp: 1, username: 1, deleted: 1, aportador_solidario: 1, aportador_solidario_nome_completo: 1, 'profile.socioresidente': 1 }; + project = { + perm: 1, + _id: 1, + idapp: 1, + username: 1, + deleted: 1, + aportador_solidario: 1, + aportador_solidario_nome_completo: 1, + 'profile.socioresidente': 1, + }; const start_find = process.hrtime.bigint(); - user = await User.findOne({ - _id: decoded.smart, - tokens: { - $elemMatch: { - token, - access: typeaccess, + user = await User.findOne( + { + _id: decoded.smart, + tokens: { + $elemMatch: { + token, + access: typeaccess, + }, }, }, - }, project).lean(); + project + ).lean(); const end_find = process.hrtime.bigint(); // console.log(` User.findOne LEAN impiega ${Math.round(Number(end_find - start_find) / 1e6) / 1000} secondi.`); } - if (user) { const checkExpiry = tools.getEnableTokenExpiredByIdApp(user.idapp); const currentTime = Date.now() / 1000; @@ -865,7 +892,7 @@ UserSchema.statics.findByTokenAnyAccess = function (token) { } return User.findOne({ - '_id': decoded.smart, + _id: decoded.smart, 'tokens.token': token, }).lean(); }; @@ -883,22 +910,17 @@ UserSchema.statics.findByCredentials = async function (idapp, username, password { deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }, { - $and: [ - { deleted: { $exists: true, $eq: true } }, - { subaccount: { $exists: true, $eq: true } }, - ], + $and: [{ deleted: { $exists: true, $eq: true } }, { subaccount: { $exists: true, $eq: true } }], }, ], - }); if (!user) { // Check if with email: user = await User.findOne({ - idapp, email: username.toLowerCase(), - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + idapp, + email: username.toLowerCase(), + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); } @@ -907,9 +929,7 @@ UserSchema.statics.findByCredentials = async function (idapp, username, password user = await User.findOne({ idapp, 'profile.username_telegram': username.toLowerCase(), - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); } @@ -927,7 +947,7 @@ UserSchema.statics.findByCredentials = async function (idapp, username, password } } - const res = await bcrypt.compare(password, pwd) ? user : null; + const res = (await bcrypt.compare(password, pwd)) ? user : null; return res; }; @@ -935,8 +955,7 @@ UserSchema.statics.findByCredentials = async function (idapp, username, password UserSchema.statics.findByUsername = async function (idapp, username, alsoemail, onlyifVerifiedByAportador) { const User = this; - if (!username) - return null; + if (!username) return null; const myreg = ['^', username, '$'].join(''); let regexusername = new RegExp(myreg, 'i'); @@ -947,30 +966,28 @@ UserSchema.statics.findByUsername = async function (idapp, username, alsoemail, idapp: idapp, username: { $regex: regexusername }, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }).then(async (ris) => { - if ((!ris) && (alsoemail)) { - regexemail = new RegExp(['^', username.toLowerCase(), '$'].join(''), 'i'); - - return await User.findOne({ - 'idapp': idapp, - 'email': { $regex: regexemail }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }); - } - return ris; - }).then((rec) => { - if (rec && onlyifVerifiedByAportador) { - if (tools.getAskToVerifyReg(idapp)) { - if (!rec.verified_by_aportador) - return null; + }) + .then(async (ris) => { + if (!ris && alsoemail) { + regexemail = new RegExp(['^', username.toLowerCase(), '$'].join(''), 'i'); + return await User.findOne({ + idapp: idapp, + email: { $regex: regexemail }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }); + } + return ris; + }) + .then((rec) => { + if (rec && onlyifVerifiedByAportador) { + if (tools.getAskToVerifyReg(idapp)) { + if (!rec.verified_by_aportador) return null; + } } - } - return rec; - }); + return rec; + }); }; /** * Find a user by their Telegram username. @@ -998,30 +1015,28 @@ UserSchema.statics.findByUsernameTelegram = async function (idapp, username, als idapp: idapp, 'profile.username_telegram': { $regex: regexusername }, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }).then(async (ris) => { - if ((!ris) && (alsoemail)) { - regexemail = new RegExp(['^', username.toLowerCase(), '$'].join(''), 'i'); - - return await User.findOne({ - 'idapp': idapp, - 'email': { $regex: regexemail }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }); - } - return ris; - }).then((rec) => { - if (rec && onlyifVerifiedByAportador) { - if (tools.getAskToVerifyReg(idapp)) { - if (!rec.verified_by_aportador) - return null; + }) + .then(async (ris) => { + if (!ris && alsoemail) { + regexemail = new RegExp(['^', username.toLowerCase(), '$'].join(''), 'i'); + return await User.findOne({ + idapp: idapp, + email: { $regex: regexemail }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }); + } + return ris; + }) + .then((rec) => { + if (rec && onlyifVerifiedByAportador) { + if (tools.getAskToVerifyReg(idapp)) { + if (!rec.verified_by_aportador) return null; + } } - } - return rec; - }); + return rec; + }); }; UserSchema.statics.getProjectUser = function () { @@ -1068,7 +1083,6 @@ UserSchema.statics.getProjectUser = function () { tokenreg: 1, date_tokenreg: 1, }; - }; UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) { @@ -1076,12 +1090,13 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) let regexp = new RegExp(`^${username}$`, 'i'); - const myrec = await User.findOne({ - 'idapp': idapp, - username: { $regex: regexp }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, - this.getProjectUser(), + const myrec = await User.findOne( + { + idapp: idapp, + username: { $regex: regexp }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + this.getProjectUser() ).lean(); if (myrec) { @@ -1099,12 +1114,13 @@ UserSchema.statics.getUserShortDataByUsernameTelegram = async function (idapp, u let regexp = new RegExp(`^${username_telegram}$`, 'i'); - const myrec = await User.findOne({ - 'idapp': idapp, - 'profile.username_telegram': { $regex: regexp }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, - this.getProjectUser(), + const myrec = await User.findOne( + { + idapp: idapp, + 'profile.username_telegram': { $regex: regexp }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + this.getProjectUser() ).lean(); if (myrec) { @@ -1117,11 +1133,8 @@ UserSchema.statics.getUserShortDataByUsernameTelegram = async function (idapp, u return myrec; }; -UserSchema.statics.getDownlineByUsername = async function ( - idapp, username, includemyself, onlynumber) { - - if (username === undefined) - return null; +UserSchema.statics.getDownlineByUsername = async function (idapp, username, includemyself, onlynumber) { + if (username === undefined) return null; let arrrec = []; @@ -1136,15 +1149,12 @@ UserSchema.statics.getDownlineByUsername = async function ( } return arrrec; - }; UserSchema.statics.getQueryQualified = function () { return [ { - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, { $or: [ @@ -1165,7 +1175,8 @@ UserSchema.statics.getQueryQualified = function () { ], // 'profile.paymenttypes': { "$in": ['paypal'] }, // $where: "this.profile.paymenttypes.length >= 1", - }], + }, + ], }, ]; }; @@ -1173,12 +1184,11 @@ UserSchema.statics.getQueryQualified = function () { UserSchema.statics.isUserQualified7 = async function (idapp, username) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, $and: User.getQueryQualified(), }; @@ -1190,12 +1200,11 @@ UserSchema.statics.isUserQualified7 = async function (idapp, username) { UserSchema.statics.isUserResidente = async function (idapp, username) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, }; const myrec = await User.findOne(myquery); @@ -1204,18 +1213,16 @@ UserSchema.statics.isUserResidente = async function (idapp, username) { } else { return false; } - }; UserSchema.statics.isUserConsiglio = async function (idapp, username) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, }; const myrec = await User.findOne(myquery); @@ -1224,18 +1231,16 @@ UserSchema.statics.isUserConsiglio = async function (idapp, username) { } else { return false; } - }; UserSchema.statics.isUserVisuProjects = async function (idapp, username) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, }; const myrec = await User.findOne(myquery); @@ -1244,18 +1249,16 @@ UserSchema.statics.isUserVisuProjects = async function (idapp, username) { } else { return false; } - }; UserSchema.statics.isUserAlreadyQualified = async function (idapp, username) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, 'profile.qualified': { $exists: true, $eq: true }, }; @@ -1264,16 +1267,14 @@ UserSchema.statics.isUserAlreadyQualified = async function (idapp, username) { return !!myrec; }; -UserSchema.statics.isUserAlreadyQualified_2Invitati = async function ( - idapp, username) { +UserSchema.statics.isUserAlreadyQualified_2Invitati = async function (idapp, username) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, 'profile.qualified_2invitati': { $exists: true, $eq: true }, }; @@ -1285,30 +1286,26 @@ UserSchema.statics.isUserAlreadyQualified_2Invitati = async function ( UserSchema.statics.setUserQualified = async function (idapp, username) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, }; - const myrec = await User.findOneAndUpdate(myquery, - { $set: { 'profile.qualified': true } }, { new: false }); + const myrec = await User.findOneAndUpdate(myquery, { $set: { 'profile.qualified': true } }, { new: false }); return !!myrec; }; -UserSchema.statics.setVerifiedByAportador = async function ( - idapp, username, valuebool) { +UserSchema.statics.setVerifiedByAportador = async function (idapp, username, valuebool) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, }; const userver = await User.findOne(myquery, { verified_by_aportador: 1 }).lean(); @@ -1318,94 +1315,86 @@ UserSchema.statics.setVerifiedByAportador = async function ( scrivi = userver.verified_by_aportador !== valuebool; } if (scrivi) { - const myrec = await User.findOneAndUpdate(myquery, - { $set: { 'verified_by_aportador': valuebool } }, { new: false }); + const myrec = await User.findOneAndUpdate(myquery, { $set: { verified_by_aportador: valuebool } }, { new: false }); return !!myrec; } else { return false; } - }; -UserSchema.statics.setnotask_verif = async function ( - idapp, username, valuebool) { +UserSchema.statics.setnotask_verif = async function (idapp, username, valuebool) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, }; - const myrec = await User.findOneAndUpdate(myquery, - { $set: { 'notask_verif': valuebool } }, { new: false }); + const myrec = await User.findOneAndUpdate(myquery, { $set: { notask_verif: valuebool } }, { new: false }); return !!myrec; }; -UserSchema.statics.setaportador_solidario = async function ( - idapp, username, usernameAportador) { +UserSchema.statics.setaportador_solidario = async function (idapp, username, usernameAportador) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, }; - const myrec = await User.findOneAndUpdate(myquery, - { $set: { 'aportador_solidario': usernameAportador } }, { new: false }); + const myrec = await User.findOneAndUpdate( + myquery, + { $set: { aportador_solidario: usernameAportador } }, + { new: false } + ); return !!myrec; }; -UserSchema.statics.setNewsletterToAll = async function ( - idapp) { +UserSchema.statics.setNewsletterToAll = async function (idapp) { const User = this; - return await User.updateMany({ - idapp, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { $set: { 'news_on': true } }, - { new: false }); + return await User.updateMany( + { + idapp, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { $set: { news_on: true } }, + { new: false } + ); }; -UserSchema.statics.setNewsletter = async function ( - idapp, username, newsletter_on) { +UserSchema.statics.setNewsletter = async function (idapp, username, newsletter_on) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, }; - const myrec = await User.findOneAndUpdate(myquery, - { $set: { 'news_on': newsletter_on } }, { new: false }); + const myrec = await User.findOneAndUpdate(myquery, { $set: { news_on: newsletter_on } }, { new: false }); return !!myrec; }; -UserSchema.statics.setEmailErrata = async function ( - idapp, username, email_errata) { +UserSchema.statics.setEmailErrata = async function (idapp, username, email_errata) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, }; - const myrec = await User.findOneAndUpdate(myquery, - { $set: { email_errata } }, { new: false }); + const myrec = await User.findOneAndUpdate(myquery, { $set: { email_errata } }, { new: false }); return !!myrec; }; @@ -1414,51 +1403,49 @@ UserSchema.statics.isEmailErrata = async function (idapp, username) { const User = this; return await User.findOne({ - idapp, username, + idapp, + username, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }).then((rec) => { - return ((rec) ? rec.email_errata : false); - }).catch((e) => { - return false; - }); + }) + .then((rec) => { + return rec ? rec.email_errata : false; + }) + .catch((e) => { + return false; + }); }; UserSchema.statics.isNewsletterOn = async function (idapp, username) { const User = this; return await User.findOne({ - idapp, username, + idapp, + username, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }).then((rec) => { - return ((rec) ? rec.news_on : false); - }).catch((e) => { - console.error('isNewsletterOn', e); - return false; - }); + }) + .then((rec) => { + return rec ? rec.news_on : false; + }) + .catch((e) => { + console.error('isNewsletterOn', e); + return false; + }); }; - - UserSchema.statics.setVerifiedByAportadorToALL = async function () { - - return await User.updateMany({}, { $set: { 'verified_by_aportador': true } }, - { new: false }); - + return await User.updateMany({}, { $set: { verified_by_aportador: true } }, { new: false }); }; -UserSchema.statics.setUserQualified_2Invitati = async function ( - idapp, username) { +UserSchema.statics.setUserQualified_2Invitati = async function (idapp, username) { const User = this; - if (username === undefined) - return false; + if (username === undefined) return false; const myquery = { - 'idapp': idapp, - 'username': username, + idapp: idapp, + username: username, }; - const myrec = await User.findOneAndUpdate(myquery, - { $set: { 'profile.qualified_2invitati': true } }, { new: false }); + const myrec = await User.findOneAndUpdate(myquery, { $set: { 'profile.qualified_2invitati': true } }, { new: false }); return !!myrec; }; @@ -1505,9 +1492,7 @@ UserSchema.statics.getUsersNationalityQuery = function (idapp) { { $match: { idapp, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, }, { @@ -1523,7 +1508,7 @@ UserSchema.statics.getUsersNationalityQuery = function (idapp) { UserSchema.statics.getindOrderDuplicate = function (idapp) { const User = this; - return User.aggregate(User.getUsersNationalityQuery(idapp)).then(ris => { + return User.aggregate(User.getUsersNationalityQuery(idapp)).then((ris) => { // console.table(ris); return ris; }); @@ -1533,8 +1518,8 @@ UserSchema.statics.findByLinkreg = function (idapp, linkreg) { const User = this; return User.findOne({ - 'linkreg': linkreg, - 'idapp': idapp, + linkreg: linkreg, + idapp: idapp, }); }; @@ -1542,13 +1527,11 @@ UserSchema.statics.AportadorOrig = function (idapp, id) { const User = this; return User.findOne({ - '_id': id, - 'idapp': idapp, + _id: id, + idapp: idapp, }).then((rec) => { - if (rec) - return rec.aportador_iniziale; - else - return ''; + if (rec) return rec.aportador_iniziale; + else return ''; }); }; @@ -1556,10 +1539,10 @@ UserSchema.statics.findByLinkTokenforgot = function (idapp, email, tokenforgot) const User = this; return User.findOne({ - 'email': email, - 'tokenforgot': tokenforgot, - 'date_tokenforgot': { $gte: tools.IncDateNow(-1000 * 60 * 60 * 4) }, // 4 ore fa! - 'idapp': idapp, + email: email, + tokenforgot: tokenforgot, + date_tokenforgot: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 4) }, // 4 ore fa! + idapp: idapp, }); }; @@ -1569,7 +1552,7 @@ UserSchema.statics.findByLinkTokenforgotCode = function (idapp, email, tokenforg return User.findOne({ email, tokenforgot_code, - date_tokenforgot: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 4) }, // 4 ore fa! + date_tokenforgot: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 4) }, // 4 ore fa! idapp, }); }; @@ -1584,11 +1567,10 @@ UserSchema.statics.createNewRequestPwd = function (idapp, email, code) { if (code && code.length === 6) { return User.findByLinkTokenforgotCode(idapp, email, code) .then((user) => { - if (user) - return { ris: true, link: tools.getlinkRelativeRequestNewPassword(idapp, email, user.tokenforgot) }; - else - return { ris: false }; - }).catch((e) => { + if (user) return { ris: true, link: tools.getlinkRelativeRequestNewPassword(idapp, email, user.tokenforgot) }; + else return { ris: false }; + }) + .catch((e) => { console.log(' Err createNewRequestPwd', e.message); res.status(400).send(); }); @@ -1599,18 +1581,25 @@ UserSchema.statics.createNewRequestPwd = function (idapp, email, code) { return { ris: false }; } else { // Creo il tokenforgot - user.tokenforgot = jwt.sign({ _id: 'prova123##', smart: user._id.toHexString() }, process.env.SIGNCODE). - toString(); + user.tokenforgot = jwt + .sign({ _id: 'prova123##', smart: user._id.toHexString() }, process.env.SIGNCODE) + .toString(); user.date_tokenforgot = new Date(); user.tokenforgot_code = 100000 + Math.round(Math.random() * 899999); user.lasttimeonline = new Date(); return await user.save().then(async () => { - await sendemail.sendEmail_RequestNewPassword(user.lang, user, user.email, user.idapp, user.tokenforgot, user.tokenforgot_code); + await sendemail.sendEmail_RequestNewPassword( + user.lang, + user, + user.email, + user.idapp, + user.tokenforgot, + user.tokenforgot_code + ); return { ris: true }; }); } - }); } }; @@ -1630,8 +1619,9 @@ UserSchema.statics.createNewRequestPwdByUsernameAndGetLink = async function (ida }; const prova = 'dasdas1231#11'; // Creo il tokenforgot - user.tokenforgot = jwt.sign({ _id: prova, smart: user._id.toHexString(), ...additionalData }, process.env.SIGNCODE). - toString(); + user.tokenforgot = jwt + .sign({ _id: prova, smart: user._id.toHexString(), ...additionalData }, process.env.SIGNCODE) + .toString(); user.date_tokenforgot = new Date(); user.tokenforgot_code = 100000 + Math.round(Math.random() * 899999); user.lasttimeonline = new Date(); @@ -1643,7 +1633,6 @@ UserSchema.statics.createNewRequestPwdByUsernameAndGetLink = async function (ida } return ''; - }; UserSchema.statics.getifRegTokenIsValid = async function (idapp, tokenreg) { @@ -1653,14 +1642,13 @@ UserSchema.statics.getifRegTokenIsValid = async function (idapp, tokenreg) { const user = await User.findOne({ idapp, - tokenreg: { $regex: regexp } + tokenreg: { $regex: regexp }, }); if (user && user.date_tokenreg) { - return user.date_tokenreg > (new Date().getTime()); + return user.date_tokenreg > new Date().getTime(); } return false; -} - +}; UserSchema.statics.createNewReqRegistrationGetLink = async function (idapp, username) { const User = this; @@ -1675,7 +1663,6 @@ UserSchema.statics.createNewReqRegistrationGetLink = async function (idapp, user if (true) { // Se è scaduto, ne crea uno nuovo // Creo il tokenforgot - /* if (!user.date_tokenreg || (!user.tokenreg) || (user.tokenreg && (user.date_tokenreg < new Date().getTime()))) { @@ -1702,20 +1689,18 @@ UserSchema.statics.createNewReqRegistrationGetLink = async function (idapp, user }); */ - } } return ''; - }; UserSchema.statics.findByEmail = function (idapp, email, onlyifVerifiedByAportador) { const User = this; return User.findOne({ - 'idapp': idapp, - 'email': email, + idapp: idapp, + email: email, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }).then((rec) => { /* if (rec && onlyifVerifiedByAportador) { @@ -1747,9 +1732,7 @@ UserSchema.statics.findByIndex = function (idapp, index) { return User.findOne({ idapp, index, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); } catch (e) { console.error(e.message); @@ -1763,9 +1746,7 @@ UserSchema.statics.findByOldOrder = function (idapp, old_order) { return User.findOne({ idapp, old_order, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); } catch (e) { console.error(e.message); @@ -1773,13 +1754,10 @@ UserSchema.statics.findByOldOrder = function (idapp, old_order) { }; UserSchema.pre('save', async function (next) { - try { if (this.isNew) { try { - const myrec = await User.findOne({ idapp: this.idapp }). - limit(1). - sort({ index: -1 }); + const myrec = await User.findOne({ idapp: this.idapp }).limit(1).sort({ index: -1 }); if (!!myrec) { this.index = myrec._doc.index + 1; @@ -1826,65 +1804,74 @@ UserSchema.methods.removeToken = function (token) { UserSchema.statics.SvuotaTuttiGliAccessiOnlineConToken = async function (idapp) { const User = this; - return await User.updateMany({ idapp }, + return await User.updateMany( + { idapp }, { $pull: { - tokens: - { - $or: [{ refreshToken: { $exists: false } }, - { refreshToken: { $exists: true, $eq: '' } } - ] + tokens: { + $or: [{ refreshToken: { $exists: false } }, { refreshToken: { $exists: true, $eq: '' } }], }, - } - }); - + }, + } + ); }; - UserSchema.statics.getEmailByUsername = async function (idapp, username) { const User = this; return await User.findOne({ - idapp, username, + idapp, + username, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }).then((arrrec) => { - return ((arrrec) ? arrrec.email : ''); - }).catch((e) => { - console.error('getEmailByUsername', e); - }); + }) + .then((arrrec) => { + return arrrec ? arrrec.email : ''; + }) + .catch((e) => { + console.error('getEmailByUsername', e); + }); }; UserSchema.statics.getUsernameById = async function (idapp, id) { const User = this; - return await User.findOne({ - idapp, _id: id, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { username: 1 }).then((myuser) => { - return ((myuser) ? myuser.username : ''); - }).catch((e) => { - - }); + return await User.findOne( + { + idapp, + _id: id, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { username: 1 } + ) + .then((myuser) => { + return myuser ? myuser.username : ''; + }) + .catch((e) => {}); }; UserSchema.statics.getUsernameByEmail = async function (idapp, email) { const User = this; - return await User.findOne({ - idapp, email, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { username: 1 }).then((myuser) => { - return ((myuser) ? myuser.username : ''); - }).catch((e) => { - - }); + return await User.findOne( + { + idapp, + email, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { username: 1 } + ) + .then((myuser) => { + return myuser ? myuser.username : ''; + }) + .catch((e) => {}); }; UserSchema.statics.getUserById = function (idapp, id) { const User = this; return User.findOne({ - idapp, _id: id, + idapp, + _id: id, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); }; @@ -1916,29 +1903,24 @@ UserSchema.statics.getUserByUsernameTelegram = function (idapp, username_telegra }; UserSchema.statics.isMyFriend = async function (idapp, username, myusername) { - const myfriends = await User.getUsernameFriendsByUsername(idapp, myusername); if (myfriends) { return await myfriends.includes(username); } else { return false; } - }; UserSchema.statics.isMyHandShake = async function (idapp, username, myusername) { - const myhandshake = await User.getUsernameHandShakeByUsername(idapp, myusername); if (myhandshake) { return await myhandshake.includes(username); } else { return false; } - }; -UserSchema.statics.getUserProfileByUsername = async function ( - idapp, username, myusername, usaSuperPower, myperm = '') { +UserSchema.statics.getUserProfileByUsername = async function (idapp, username, myusername, usaSuperPower, myperm = '') { const User = this; // If is my Friend, then can show all @@ -1953,7 +1935,7 @@ UserSchema.statics.getUserProfileByUsername = async function ( if (username === myusername) { perm = tools.Perm.PERM_ALL; } else { - if (await User.canHavePower(myperm) && usaSuperPower) { + if ((await User.canHavePower(myperm)) && usaSuperPower) { perm = tools.Perm.PERM_ALL; } } @@ -2010,7 +1992,6 @@ UserSchema.statics.getUserProfileByUsername = async function ( 'useraport.username': 1, 'useraport.profile.img': 1, }; - } else if (perm === tools.Perm.PERM_FRIEND) { whatToShow = { idapp: 1, @@ -2060,7 +2041,6 @@ UserSchema.statics.getUserProfileByUsername = async function ( 'useraport.username': 1, 'useraport.profile.img': 1, }; - } else if (perm === tools.Perm.PERM_ALL) { whatToShow = { idapp: 1, @@ -2105,8 +2085,8 @@ UserSchema.statics.getUserProfileByUsername = async function ( 'profile.calc': 1, 'profile.handshake': 1, 'profile.friends': 1, - 'mycities': 1, - 'comune': 1, + mycities: 1, + comune: 1, email: 1, date_reg: 1, 'useraport.perm': 1, @@ -2119,7 +2099,8 @@ UserSchema.statics.getUserProfileByUsername = async function ( let regexpusername = new RegExp(`^${username}$`, 'i'); const myfind = { - idapp, username: { $regex: regexpusername }, + idapp, + username: { $regex: regexpusername }, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }; @@ -2134,20 +2115,17 @@ UserSchema.statics.getUserProfileByUsername = async function ( }, }, { - '$lookup': { - 'from': 'users', + $lookup: { + from: 'users', let: { - 'idapp': '$idapp', - 'user_name': '$aportador_solidario', + idapp: '$idapp', + user_name: '$aportador_solidario', }, pipeline: [ { - '$match': { - '$expr': { - $and: [ - { $eq: ['$username', '$$user_name'] }, - { $eq: ['$idapp', '$$idapp'] }, - ], + $match: { + $expr: { + $and: [{ $eq: ['$username', '$$user_name'] }, { $eq: ['$idapp', '$$idapp'] }], }, }, }, @@ -2156,22 +2134,18 @@ UserSchema.statics.getUserProfileByUsername = async function ( }, }, { - $unwind: - { + $unwind: { path: '$useraport', preserveNullAndEmptyArrays: true, }, }, { - '$replaceRoot': { - 'newRoot': { - '$mergeObjects': [ + $replaceRoot: { + newRoot: { + $mergeObjects: [ { - '$arrayElemAt': [ - '$mycities', - 0, - ], + $arrayElemAt: ['$mycities', 0], }, '$$ROOT', ], @@ -2179,14 +2153,12 @@ UserSchema.statics.getUserProfileByUsername = async function ( }, }, { $project: whatToShow }, - ]; try { const ris = await User.aggregate(query); if (ris && ris.length > 0) { - ris[0].profile.calc = await User.calcOtherByUser(idapp, ris[0]._id); return ris[0]; } @@ -2206,94 +2178,77 @@ UserSchema.statics.getUserProfileByUsername = async function ( */ - }; -UserSchema.statics.getArrUsernameFromFieldByUsername = async function ( - idapp, username, field, subfield) { - +UserSchema.statics.getArrUsernameFromFieldByUsername = async function (idapp, username, field, subfield) { const myobj = {}; myobj[field + '.' + subfield + '.username'] = 1; - const rec = await User.findOne({ - idapp, 'username': username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, myobj); - - return rec ? rec[field][subfield].map(m => m.username) : []; + const rec = await User.findOne( + { + idapp, + username: username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + myobj + ); + return rec ? rec[field][subfield].map((m) => m.username) : []; }; -UserSchema.statics.getUsernameReqFriendsByUsername = async function ( - idapp, username) { - - return await this.getArrUsernameFromFieldByUsername(idapp, username, 'profile', - 'req_friends'); - +UserSchema.statics.getUsernameReqFriendsByUsername = async function (idapp, username) { + return await this.getArrUsernameFromFieldByUsername(idapp, username, 'profile', 'req_friends'); }; -UserSchema.statics.getUsernameFriendsByUsername = async function ( - idapp, username) { - - return await this.getArrUsernameFromFieldByUsername(idapp, username, 'profile', - 'friends'); - +UserSchema.statics.getUsernameFriendsByUsername = async function (idapp, username) { + return await this.getArrUsernameFromFieldByUsername(idapp, username, 'profile', 'friends'); }; -UserSchema.statics.getUsernameHandShakeByUsername = async function ( - idapp, username) { - - return await this.getArrUsernameFromFieldByUsername(idapp, username, 'profile', - 'handshake'); - +UserSchema.statics.getUsernameHandShakeByUsername = async function (idapp, username) { + return await this.getArrUsernameFromFieldByUsername(idapp, username, 'profile', 'handshake'); }; -UserSchema.statics.getUsernameGroupsByUsername = async function ( - idapp, username) { - - return await this.getArrUsernameFromFieldByUsername(idapp, username, 'profile', - 'mygroups'); - +UserSchema.statics.getUsernameGroupsByUsername = async function (idapp, username) { + return await this.getArrUsernameFromFieldByUsername(idapp, username, 'profile', 'mygroups'); }; -UserSchema.statics.getUsernameCircuitsByUsername = async function ( - idapp, username) { - - return await this.getArrUsernameFromFieldByUsername(idapp, username, 'profile', - 'mycircuits'); - +UserSchema.statics.getUsernameCircuitsByUsername = async function (idapp, username) { + return await this.getArrUsernameFromFieldByUsername(idapp, username, 'profile', 'mycircuits'); }; // Rimuovo l'Amicizia -UserSchema.statics.removeFriend = async function ( - idapp, username, usernameDest) { - return await User.updateOne({ idapp, username }, - { $pull: { 'profile.friends': { username: { $in: [usernameDest] } } } }); +UserSchema.statics.removeFriend = async function (idapp, username, usernameDest) { + return await User.updateOne( + { idapp, username }, + { $pull: { 'profile.friends': { username: { $in: [usernameDest] } } } } + ); }; // Rimuovo l'Amicizia -UserSchema.statics.removeHandShake = async function ( - idapp, username, usernameDest) { - return await User.updateOne({ idapp, username }, - { $pull: { 'profile.handshake': { username: { $in: [usernameDest] } } } }); +UserSchema.statics.removeHandShake = async function (idapp, username, usernameDest) { + return await User.updateOne( + { idapp, username }, + { $pull: { 'profile.handshake': { username: { $in: [usernameDest] } } } } + ); }; // Rimuovo il Gruppo -UserSchema.statics.removeFromMyGroups = async function ( - idapp, username, groupnameDest) { - return await User.updateOne({ idapp, username }, - { $pull: { 'profile.mygroups': { groupname: { $in: [groupnameDest] } } } }); +UserSchema.statics.removeFromMyGroups = async function (idapp, username, groupnameDest) { + return await User.updateOne( + { idapp, username }, + { $pull: { 'profile.mygroups': { groupname: { $in: [groupnameDest] } } } } + ); }; // Rimuovo il Circuito UserSchema.statics.removeFromCircuits = async function (idapp, username, circuitname) { - // Elimina la richiesta (se esiste): update = { $pull: { req_users: { username: { $in: [username] } } } }; await Circuit.updateOne({ idapp, name: circuitname }, update); - const ris = await User.updateOne({ idapp, username }, - { $pull: { 'profile.mycircuits': { circuitname: { $in: [circuitname] } } } }); - + const ris = await User.updateOne( + { idapp, username }, + { $pull: { 'profile.mycircuits': { circuitname: { $in: [circuitname] } } } } + ); const circuitId = await Circuit.getCircuitIdByName(idapp, circuitname); let remove = false; @@ -2303,7 +2258,7 @@ UserSchema.statics.removeFromCircuits = async function (idapp, username, circuit // Invio la notifica agli amministratori del circuito const title = `L\'utente ${username} è uscito dal ${circuitname}`; const msg = ``; - await tools.sendNotifToCircuitsAdmin(idapp, circuit, true, title, msg, '') + await tools.sendNotifToCircuitsAdmin(idapp, circuit, true, title, msg, ''); } // Se il mio account non è stato utilizzato, allora lo cancello anche questo @@ -2323,11 +2278,9 @@ UserSchema.statics.removeFromCircuits = async function (idapp, username, circuit // Aggiungo il Circuito UserSchema.statics.addCircuitToUser = async function (idapp, usernameOrig, circuitname, confido, groupname, contocom) { - let ris = null; if (groupname) { - ris = await MyGroup.addCircuitFromGroup(idapp, groupname, circuitname); // Elimina la richiesta: @@ -2337,23 +2290,27 @@ UserSchema.statics.addCircuitToUser = async function (idapp, usernameOrig, circu // Elimina eventualmente se era bloccato: update = { $pull: { refused_groups: { groupname: { $in: [groupname] } } } }; await Circuit.updateOne({ idapp, name: circuitname }, update); - } else { - // prima di aggiungerlo controlla se esiste già ! let update = { - $addToSet: { // Utilizziamo $addToSet invece di $push per garantire che l'elemento venga aggiunto solo se non esiste già + $addToSet: { + // Utilizziamo $addToSet invece di $push per garantire che l'elemento venga aggiunto solo se non esiste già 'profile.mycircuits': { - $each: [{ - circuitname, - date: new Date(), - }], - } - } + $each: [ + { + circuitname, + date: new Date(), + }, + ], + }, + }, }; - ris = await User.updateOne({ idapp, username: usernameOrig, 'profile.mycircuits': { $not: { $elemMatch: { circuitname } } } }, update); + ris = await User.updateOne( + { idapp, username: usernameOrig, 'profile.mycircuits': { $not: { $elemMatch: { circuitname } } } }, + update + ); if (confido) { // Elimina la richiesta: @@ -2364,7 +2321,6 @@ UserSchema.statics.addCircuitToUser = async function (idapp, usernameOrig, circu // Elimina eventualmente se era bloccato: update = { $pull: { refused_users: { username: { $in: [usernameOrig] } } } }; await Circuit.updateOne({ idapp, name: circuitname }, update); - } await Account.createAccount(idapp, usernameOrig, circuitname, confido, groupname, contocom); @@ -2374,30 +2330,25 @@ UserSchema.statics.addCircuitToUser = async function (idapp, usernameOrig, circu // Rimuovo il Gruppo per Tutti gli Utenti UserSchema.statics.removeAllUsersFromMyGroups = async function (idapp, groupnameDest) { - return await User.updateMany({ idapp }, - { $pull: { 'profile.mygroups': { groupname: { $in: [groupnameDest] } } } }); + return await User.updateMany({ idapp }, { $pull: { 'profile.mygroups': { groupname: { $in: [groupnameDest] } } } }); }; // Rimuovo il Circuito per Tutti gli Utenti UserSchema.statics.removeAllUsersFromMyCircuits = async function (idapp, circuitname) { - return await User.updateMany({ idapp }, - { $pull: { 'profile.mycircuits': { circuitname: { $in: [circuitname] } } } }); + return await User.updateMany({ idapp }, { $pull: { 'profile.mycircuits': { circuitname: { $in: [circuitname] } } } }); }; // Rimuovo la Richiesta di Amicizia -UserSchema.statics.removeReqFriend = async function ( - idapp, username, usernameDest) { - return await User.updateOne({ idapp, username: username }, - { $pull: { 'profile.req_friends': { username: { $in: [usernameDest] } } } }); +UserSchema.statics.removeReqFriend = async function (idapp, username, usernameDest) { + return await User.updateOne( + { idapp, username: username }, + { $pull: { 'profile.req_friends': { username: { $in: [usernameDest] } } } } + ); }; - - // Aggiungo il Partecipa -UserSchema.statics.addAttend = async function ( - req, idapp, username, id, tab, num) { - const ris = await User.updateOne({ idapp, username }, - { $push: { 'profile.attend': { id, tab, num } } }); +UserSchema.statics.addAttend = async function (req, idapp, username, id, tab, num) { + const ris = await User.updateOne({ idapp, username }, { $push: { 'profile.attend': { id, tab, num } } }); const { SendNotif } = require('../models/sendnotif'); @@ -2407,43 +2358,38 @@ UserSchema.statics.addAttend = async function ( const recObjCreator = await globalTables.getUserCreatorByNumTabAndId(idapp, id, tab); if (recObjCreator) { - await SendNotif.createNewNotifToSingleUser(req, null, { usernameDest: recObjCreator.username, recObjCreator, username_action: req.user.username }, false, + await SendNotif.createNewNotifToSingleUser( + req, + null, + { usernameDest: recObjCreator.username, recObjCreator, username_action: req.user.username }, + false, shared_consts.TypeNotifs.TYPEDIR_EVENTS, - shared_consts.TypeNotifs.ID_EVENTS_ATTEND); - + shared_consts.TypeNotifs.ID_EVENTS_ATTEND + ); } return ris; }; // Rimuovo il Bookmark -UserSchema.statics.removeBookmark = async function ( - idapp, username, id, tab) { - return await User.updateOne({ idapp, username }, - { $pull: { 'profile.bookmark': { id: { $in: [id] }, tab } } }); +UserSchema.statics.removeBookmark = async function (idapp, username, id, tab) { + return await User.updateOne({ idapp, username }, { $pull: { 'profile.bookmark': { id: { $in: [id] }, tab } } }); }; // Aggiungo il Bookmark -UserSchema.statics.addBookmark = async function ( - idapp, username, id, tab) { - return await User.updateOne({ idapp, username }, - { $push: { 'profile.bookmark': { id, tab } } }); +UserSchema.statics.addBookmark = async function (idapp, username, id, tab) { + return await User.updateOne({ idapp, username }, { $push: { 'profile.bookmark': { id, tab } } }); }; // Rimuovo il Partecipa -UserSchema.statics.removeAttend = async function ( - idapp, username, id, tab) { - return await User.updateOne({ idapp, username }, - { $pull: { 'profile.attend': { id: { $in: [id] }, tab } } }); +UserSchema.statics.removeAttend = async function (idapp, username, id, tab) { + return await User.updateOne({ idapp, username }, { $pull: { 'profile.attend': { id: { $in: [id] }, tab } } }); }; // Aggiungo il Bookmark -UserSchema.statics.addSeen = async function ( - idapp, username, id, tab) { - return await User.updateOne({ idapp, username }, - { $push: { 'profile.seen': { id, tab } } }); +UserSchema.statics.addSeen = async function (idapp, username, id, tab) { + return await User.updateOne({ idapp, username }, { $push: { 'profile.seen': { id, tab } } }); }; UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, usernameDest, cmd, value, disablenotif) { - const { SendNotif } = require('../models/sendnotif'); const telegrambot = require('../telegram/telegrambot'); @@ -2453,8 +2399,7 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use } let userDest = null; - if (usernameDest) - userDest = await User.getUserShortDataByUsername(idapp, usernameDest); + if (usernameDest) userDest = await User.getUserShortDataByUsername(idapp, usernameDest); const username_action = req.user.username; let username_worked = usernameDest; @@ -2469,27 +2414,48 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use let update = {}; try { if (cmd === shared_consts.FRIENDSCMD.SETTRUST) { - let msgOrig = ''; let msgDest = ''; // Aggiorna true se lo accetti e false se non lo accetti - const ris = await User.updateOne({ idapp, username: usernameDest }, + const ris = await User.updateOne( + { idapp, username: usernameDest }, { $set: { verified_by_aportador: value, trust_modified: new Date() } }, - { new: false }); + { new: false } + ); if (value) { // Aggiungi alle amicizie // await this.setFriendsCmd(req, idapp, usernameOrig, usernameDest, // shared_consts.FRIENDSCMD.SETFRIEND, value); - msgOrig = i18n.__({ phrase: '✅ Hai Ammesso l\'accesso alla App a %s !', locale: userDest.lang }, userDest.username); + msgOrig = i18n.__( + { phrase: "✅ Hai Ammesso l'accesso alla App a %s !", locale: userDest.lang }, + userDest.username + ); msgDest = i18n.__({ phrase: '✅ Sei stato Ammesso correttamente da %s!', locale: lang }, usernameOrig); - msgAdmin = i18n.__({ phrase: '✅ %s è stato Ammesso correttamente (da %s)!', locale: userDest.lang }, userDest.username, usernameOrig); + msgAdmin = i18n.__( + { phrase: '✅ %s è stato Ammesso correttamente (da %s)!', locale: userDest.lang }, + userDest.username, + usernameOrig + ); } else { - msgOrig = i18n.__({ phrase: '🚫 Hai rifiutato l\'accesso alla App di RISO da parte di %s!', locale: userDest.lang }, userDest.username); - msgDest = i18n.__({ phrase: '🚫 Ti è stato rifiutato l\'accesso. Probabilmente l\'username con cui ti sei registrato non ti conosce. (%s) !
Contatta l\'Assistenza Tecnica.', locale: lang }, usernameOrig); - msgAdmin = i18n.__({ phrase: '🚫 %s ha rifiutato l\'accesso alla App a %s !', locale: userDest.lang }, usernameOrig, userDest.username); - + msgOrig = i18n.__( + { phrase: "🚫 Hai rifiutato l'accesso alla App di RISO da parte di %s!", locale: userDest.lang }, + userDest.username + ); + msgDest = i18n.__( + { + phrase: + "🚫 Ti è stato rifiutato l'accesso. Probabilmente l'username con cui ti sei registrato non ti conosce. (%s) !
Contatta l'Assistenza Tecnica.", + locale: lang, + }, + usernameOrig + ); + msgAdmin = i18n.__( + { phrase: "🚫 %s ha rifiutato l'accesso alla App a %s !", locale: userDest.lang }, + usernameOrig, + userDest.username + ); } await telegrambot.sendMsgTelegram(idapp, usernameOrig, msgOrig); @@ -2501,16 +2467,18 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use // telegrambot.askConfirmationUser(user.idapp, shared_consts.CallFunz.REGISTRATION, user, '', '', '', ''); return ris; - } else if (cmd === shared_consts.FRIENDSCMD.SETFRIEND) { // Aggiungo l'Amicizia a me - const foundIfAlreadyFriend = await User.findOne({ - idapp, - username: usernameOrig, - 'profile.friends': { - $elemMatch: { username: { $eq: usernameDest } }, + const foundIfAlreadyFriend = await User.findOne( + { + idapp, + username: usernameOrig, + 'profile.friends': { + $elemMatch: { username: { $eq: usernameDest } }, + }, }, - }, { _id: 1 }).lean(); + { _id: 1 } + ).lean(); if (!foundIfAlreadyFriend) { update = { @@ -2526,14 +2494,25 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use if (!disablenotif) { // Send a notification to the DESTINATION FRIENDSHIP ! let req = tools.getReqByPar(idapp, usernameOrig); - await SendNotif.createNewNotifToSingleUser(req, null, { usernameDest }, true, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, - shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED_MY_REQUEST); + await SendNotif.createNewNotifToSingleUser( + req, + null, + { usernameDest }, + true, + shared_consts.TypeNotifs.TYPEDIR_FRIENDS, + shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED_MY_REQUEST + ); // Send a notification to the SENDER FRIENDSHIP ! req = tools.getReqByPar(idapp, usernameDest); - await SendNotif.createNewNotifToSingleUser(req, null, { usernameDest: usernameOrig }, true, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, - shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED); - + await SendNotif.createNewNotifToSingleUser( + req, + null, + { usernameDest: usernameOrig }, + true, + shared_consts.TypeNotifs.TYPEDIR_FRIENDS, + shared_consts.TypeNotifs.ID_FRIENDS_ACCEPTED + ); } update = { $pull: { 'profile.req_friends': { username: { $in: [usernameDest] } } } }; @@ -2544,8 +2523,14 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use if (!disablenotif) { const userDest = await User.getRecLangAndIdByUsername(idapp, usernameDest); const user = await User.getRecLangAndIdByUsername(idapp, usernameOrig); - const msgDest = i18n.__({ phrase: '✅ %s accepted your Friendship request !', locale: userDest.lang }, usernameDest); - const msgOrig = i18n.__({ phrase: '✅ You have accepted %s\' Friendship request!', locale: user.lang }, usernameOrig); + const msgDest = i18n.__( + { phrase: '✅ %s accepted your Friendship request !', locale: userDest.lang }, + usernameDest + ); + const msgOrig = i18n.__( + { phrase: "✅ You have accepted %s' Friendship request!", locale: user.lang }, + usernameOrig + ); await telegrambot.sendMsgTelegram(idapp, usernameOrig, msgDest); await telegrambot.sendMsgTelegram(idapp, usernameDest, msgOrig); @@ -2554,17 +2539,19 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use console.error('Notification : ', e); } } - } // Controlla se lui aveva già la mia amicizia - const foundIfAlreadyFriend2 = await User.findOne({ - idapp, - username: usernameDest, - 'profile.friends': { - $elemMatch: { username: { $eq: usernameOrig } }, + const foundIfAlreadyFriend2 = await User.findOne( + { + idapp, + username: usernameDest, + 'profile.friends': { + $elemMatch: { username: { $eq: usernameOrig } }, + }, }, - }, { _id: 1 }).lean(); + { _id: 1 } + ).lean(); if (!foundIfAlreadyFriend2) { update = { @@ -2585,13 +2572,16 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use //} } else if (cmd === shared_consts.FRIENDSCMD.SETHANDSHAKE) { // Aggiungo la Stretta di mano a lui - const foundIfAlreadyHandshake = await User.findOne({ - idapp, - username: usernameDest, - 'profile.handshake': { - $elemMatch: { username: { $eq: usernameOrig } }, + const foundIfAlreadyHandshake = await User.findOne( + { + idapp, + username: usernameDest, + 'profile.handshake': { + $elemMatch: { username: { $eq: usernameOrig } }, + }, }, - }, { _id: 1 }).lean(); + { _id: 1 } + ).lean(); let rec = null; @@ -2650,13 +2640,16 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use ris = { rec, userprofile, myuser }; } else if (cmd === shared_consts.FRIENDSCMD.REQFRIEND) { // Aggiungo la richiesta di Amicizia a me - const foundIfAlreadyAskFriend = await User.findOne({ - idapp, - username: usernameDest, - 'profile.req_friends': { - $elemMatch: { username: { $eq: usernameOrig } }, + const foundIfAlreadyAskFriend = await User.findOne( + { + idapp, + username: usernameDest, + 'profile.req_friends': { + $elemMatch: { username: { $eq: usernameOrig } }, + }, }, - }, { _id: 1 }).lean(); + { _id: 1 } + ).lean(); if (value) { if (!foundIfAlreadyAskFriend) { @@ -2678,32 +2671,30 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use if (foundIfAlreadyAskFriend) { ris = await User.getInfoFriendByUsername(idapp, usernameDest); } - } } else if (cmd === shared_consts.FRIENDSCMD.REMOVE_FROM_MYFRIENDS) { - // Rimuovi anche le eventuali richieste di Amicizia ! await this.removeReqFriend(idapp, usernameDest, usernameOrig); // Rimuovo la Richiesta di Amicizia da lui await this.removeReqFriend(idapp, usernameOrig, usernameDest); // Rimuovo la Richiesta di Amicizia da me await this.removeFriend(idapp, usernameDest, usernameOrig); // Rimuovo l'Amicizia da lui ris = await this.removeFriend(idapp, usernameOrig, usernameDest); // Rimuovo l'Amicizia da me - } else if (cmd === shared_consts.FRIENDSCMD.REMOVE_FROM_MYHANDSHAKE) { - ris = await this.removeHandShake(idapp, usernameDest, usernameOrig); // Rimuovo l'Amicizia da lui - } else if (cmd === shared_consts.FRIENDSCMD.CANCEL_REQ_FRIEND) { - // CREATE NOTIFICATION IN TABLE SENDNOTIF const req = tools.getReqByPar(idapp, usernameOrig); - await SendNotif.createNewNotifToSingleUser(req, null, { usernameDest }, true, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, - shared_consts.TypeNotifs.ID_FRIENDS_REFUSED); + await SendNotif.createNewNotifToSingleUser( + req, + null, + { usernameDest }, + true, + shared_consts.TypeNotifs.TYPEDIR_FRIENDS, + shared_consts.TypeNotifs.ID_FRIENDS_REFUSED + ); ris = true; - } else if (cmd === shared_consts.FRIENDSCMD.BLOCK_USER) { - await this.removeReqFriend(idapp, usernameDest, usernameOrig); // Rimuovo la Richiesta di Amicizia da lui await this.removeReqFriend(idapp, usernameOrig, usernameDest); // Rimuovo la Richiesta di Amicizia da me @@ -2711,80 +2702,113 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use await this.removeFriend(idapp, usernameOrig, usernameDest); // Rimuovo l'Amicizia da me // Blocco la persona - ris = await User.updateOne({ idapp, username: usernameDest }, { - $set: { - blocked: true, - sospeso: true, - username_who_block: usernameOrig, - date_blocked: new Date(), - }, - }); + ris = await User.updateOne( + { idapp, username: usernameDest }, + { + $set: { + blocked: true, + sospeso: true, + username_who_block: usernameOrig, + date_blocked: new Date(), + }, + } + ); } else if (cmd === shared_consts.FRIENDSCMD.REPORT_USER) { - username_worked = usernameDest; // Segnalo la persona - ris = await User.updateOne({ idapp, username: username_worked }, { - $set: { - reported: true, - username_who_report: usernameOrig, - date_report: new Date(), - }, - }); + ris = await User.updateOne( + { idapp, username: username_worked }, + { + $set: { + reported: true, + username_who_report: usernameOrig, + date_report: new Date(), + }, + } + ); if (ris) { // Send a notification to the DESTINATION! // Sei stato segnalato da %s per comportamenti non idonei. Contatta %s per chiarimenti - await SendNotif.createNewNotifToSingleUser(req, null, { username_worked, usernameDest, username_action }, false, + await SendNotif.createNewNotifToSingleUser( + req, + null, + { username_worked, usernameDest, username_action }, + false, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, - shared_consts.TypeNotifs.ID_FRIENDS_REPORTED); + shared_consts.TypeNotifs.ID_FRIENDS_REPORTED + ); // Send a notification to the SENDER ! // Hai segnalato %s da %s per comportamenti non idonei. - await SendNotif.createNewNotifToSingleUser(req, null, { username_worked, usernameDest: username_action, username_action }, false, + await SendNotif.createNewNotifToSingleUser( + req, + null, + { username_worked, usernameDest: username_action, username_action }, + false, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, - shared_consts.TypeNotifs.ID_FRIENDS_REPORTED); + shared_consts.TypeNotifs.ID_FRIENDS_REPORTED + ); if (usernameOrig !== shared_consts.ADMIN_USER_SERVER) { // Send a notification to the Admin - await SendNotif.createNewNotifToSingleUser(req, null, - { username_worked, usernameDest: shared_consts.ADMIN_USER_SERVER, username_action, isAdmin: true }, false, + await SendNotif.createNewNotifToSingleUser( + req, + null, + { username_worked, usernameDest: shared_consts.ADMIN_USER_SERVER, username_action, isAdmin: true }, + false, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, - shared_consts.TypeNotifs.ID_FRIENDS_REPORTED); + shared_consts.TypeNotifs.ID_FRIENDS_REPORTED + ); } - } } else if (cmd === shared_consts.FRIENDSCMD.UNBLOCK_USER) { - username_worked = usernameDest; // Sblocco la persona - ris = await User.updateOne({ idapp, username: username_worked }, { - $set: { - reported: false, - }, - }); + ris = await User.updateOne( + { idapp, username: username_worked }, + { + $set: { + reported: false, + }, + } + ); if (ris) { // Send a notification to the DESTINATION! - await SendNotif.createNewNotifToSingleUser(req, null, { username_worked, usernameDest, username_action }, false, + await SendNotif.createNewNotifToSingleUser( + req, + null, + { username_worked, usernameDest, username_action }, + false, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, - shared_consts.TypeNotifs.ID_FRIENDS_UNBLOCKED); + shared_consts.TypeNotifs.ID_FRIENDS_UNBLOCKED + ); // Send a notification to the SENDER ! // Hai segnalato %s da %s per comportamenti non idonei. - await SendNotif.createNewNotifToSingleUser(req, null, { username_worked, usernameDest: username_action, username_action }, false, + await SendNotif.createNewNotifToSingleUser( + req, + null, + { username_worked, usernameDest: username_action, username_action }, + false, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, - shared_consts.TypeNotifs.ID_FRIENDS_UNBLOCKED); + shared_consts.TypeNotifs.ID_FRIENDS_UNBLOCKED + ); if (usernameOrig !== shared_consts.ADMIN_USER_SERVER) { // Send a notification to the Admin - await SendNotif.createNewNotifToSingleUser(req, null, - { username_worked, usernameDest: shared_consts.ADMIN_USER_SERVER, username_action, isAdmin: true }, false, + await SendNotif.createNewNotifToSingleUser( + req, + null, + { username_worked, usernameDest: shared_consts.ADMIN_USER_SERVER, username_action, isAdmin: true }, + false, shared_consts.TypeNotifs.TYPEDIR_FRIENDS, - shared_consts.TypeNotifs.ID_FRIENDS_UNBLOCKED); + shared_consts.TypeNotifs.ID_FRIENDS_UNBLOCKED + ); } - } } } catch (e) { @@ -2795,7 +2819,6 @@ UserSchema.statics.setFriendsCmd = async function (req, idapp, usernameOrig, use }; UserSchema.statics.sendCmd = async function (req, idapp, usernameOrig, usernameDest, cmd, value, disablenotif) { - const { SendNotif } = require('../models/sendnotif'); const telegrambot = require('../telegram/telegrambot'); @@ -2827,7 +2850,12 @@ UserSchema.statics.sendCmd = async function (req, idapp, usernameOrig, usernameD try { if (cmd === shared_consts.CallFunz.ENTRA_RIS_ITALIA) { mycircuitOrig = await Circuit.getCircuitMyProvince(idapp, usernameOrig); - descr = i18n.__({ phrase: 'SENDMSG_ENTRA_IN_RISO_ITALIA', locale: langdest }, usernameDest, usernameOrig, mycircuitOrig); + descr = i18n.__( + { phrase: 'SENDMSG_ENTRA_IN_RISO_ITALIA', locale: langdest }, + usernameDest, + usernameOrig, + mycircuitOrig + ); msgtelegram = descr; openUrl = '/circuit/ris_italia'; @@ -2847,7 +2875,6 @@ UserSchema.statics.sendCmd = async function (req, idapp, usernameOrig, usernameD ]); popupOnApp = 'Messaggio inviato al destinatario'; - } if (send_notif) { @@ -2857,14 +2884,21 @@ UserSchema.statics.sendCmd = async function (req, idapp, usernameOrig, usernameD // Invia Msg if (send_msgTelegramBot && msgtelegram) { - await telegrambot.local_sendMsgTelegramByIdTelegram(idapp, telegid, msgtelegram, undefined, undefined, true, keyb); + await telegrambot.local_sendMsgTelegramByIdTelegram( + idapp, + telegid, + msgtelegram, + undefined, + undefined, + true, + keyb + ); } const userprofile = await User.getInfoFriendByUsername(idapp, usernameDest); const myuser = await User.getInfoFriendByUsername(idapp, usernameOrig); ris = { userprofile, myuser, popupOnApp, result: true }; - } catch (e) { popupOnApp = e; ris = { popupOnApp }; @@ -2875,7 +2909,6 @@ UserSchema.statics.sendCmd = async function (req, idapp, usernameOrig, usernameD }; UserSchema.statics.ifAlreadyInGroup = async function (idapp, usernameOrig, groupnameDest) { - // Controllo se è stato già inserito return await User.findOne({ idapp, @@ -2884,11 +2917,9 @@ UserSchema.statics.ifAlreadyInGroup = async function (idapp, usernameOrig, group $elemMatch: { groupname: { $eq: groupnameDest } }, }, }).lean(); - }; UserSchema.statics.ifAlreadyInCircuit = async function (idapp, usernameOrig, circuitname) { - // Controllo se è stato già inserito return await User.findOne({ idapp, @@ -2901,7 +2932,6 @@ UserSchema.statics.ifAlreadyInCircuit = async function (idapp, usernameOrig, cir //** Get true if in 'profile.mycircuits' exist at least one circuit */ UserSchema.statics.ExistAtLeastOneCircuit = async function (idapp, username) { - // Controllo se è stato più inserito return await User.countDocuments({ idapp, @@ -2913,7 +2943,6 @@ UserSchema.statics.ExistAtLeastOneCircuit = async function (idapp, username) { }; UserSchema.statics.countUsersInGroup = async function (idapp, groupnameDest) { - // Controllo se è stato già inserito return await User.countDocuments({ idapp, @@ -2921,11 +2950,9 @@ UserSchema.statics.countUsersInGroup = async function (idapp, groupnameDest) { $elemMatch: { groupname: { $eq: groupnameDest } }, }, }); - }; UserSchema.statics.countUsersInCircuit = async function (idapp, circuitname) { - // Controllo se è stato già inserito return await User.countDocuments({ idapp, @@ -2933,11 +2960,9 @@ UserSchema.statics.countUsersInCircuit = async function (idapp, circuitname) { $elemMatch: { circuitname: { $eq: circuitname } }, }, }); - }; UserSchema.statics.setGroupsCmd = async function (idapp, usernameOrig, groupnameDest, cmd, value, username_action) { - let ris = null; let update = {}; try { @@ -2975,7 +3000,7 @@ UserSchema.statics.setGroupsCmd = async function (idapp, usernameOrig, groupname const foundIfAlreadyAskGroup = await MyGroup.findOne({ idapp, groupname: groupnameDest, - 'req_users': { + req_users: { $elemMatch: { username: { $eq: usernameOrig } }, }, }); @@ -2984,14 +3009,13 @@ UserSchema.statics.setGroupsCmd = async function (idapp, usernameOrig, groupname if (!foundIfAlreadyAskGroup) { update = { $push: { - 'req_users': { + req_users: { username: usernameOrig, date: new Date(), }, }, }; - ris = await MyGroup.updateOne({ idapp, groupname: groupnameDest }, - update); + ris = await MyGroup.updateOne({ idapp, groupname: groupnameDest }, update); } if (ris) { // Invia una notifica alla persona @@ -3002,16 +3026,22 @@ UserSchema.statics.setGroupsCmd = async function (idapp, usernameOrig, groupname ris = await this.removeFromMyGroups(idapp, usernameOrig, groupnameDest); // Rimuovo il Gruppo da me // Invia una notifica alla persona - await tools.sendNotificationByGroupname(idapp, usernameOrig, groupnameDest, cmd, false, true, username_action); + await tools.sendNotificationByGroupname( + idapp, + usernameOrig, + groupnameDest, + cmd, + false, + true, + username_action + ); } } if (ris) { ris = await MyGroup.getInfoGroupByGroupname(idapp, groupnameDest); } - } else if (cmd === shared_consts.GROUPSCMD.REMOVE_FROM_MYGROUP) { - // Remove if is also an Admin await MyGroup.removeAdminOfMyGroup(idapp, usernameOrig, groupnameDest); @@ -3020,56 +3050,47 @@ UserSchema.statics.setGroupsCmd = async function (idapp, usernameOrig, groupname // Invia una notifica alla persona await tools.sendNotificationByGroupname(idapp, usernameOrig, groupnameDest, cmd, false, true, username_action); - } else if (cmd === shared_consts.GROUPSCMD.DELETE_GROUP) { - ris = await User.removeFromMyGroups(idapp, usernameOrig, groupnameDest); // Rimuovo l'Amicizia da me if (ris) { // Invia una notifica alla persona e agli Admin await tools.sendNotificationByGroupname(idapp, usernameOrig, groupnameDest, cmd, false, true, username_action); - } ris = await MyGroup.deleteGroup(idapp, usernameOrig, groupnameDest); // Rimuovo l'Amicizia da me console.log('ris', ris); - } else if (cmd === shared_consts.GROUPSCMD.CANCEL_REQ_GROUP) { - ris = await MyGroup.removeReqGroup(idapp, usernameOrig, groupnameDest); // Rimuovo l'Amicizia da me - } else if (cmd === shared_consts.GROUPSCMD.REFUSE_REQ_GROUP) { - ris = await MyGroup.removeReqGroup(idapp, usernameOrig, groupnameDest); // Rimuovo l'Amicizia da me ris = await MyGroup.refuseReqGroup(idapp, usernameOrig, groupnameDest); // Rimuovo l'Amicizia da me - } else if (cmd === shared_consts.GROUPSCMD.BLOCK_GROUP) { - await User.removeFromMyGroups(idapp, usernameOrig, groupnameDest); // Rimuovo l'Amicizia da me // Blocco il Gruppo - ris = await MyGroup.updateOne({ idapp, groupname: groupnameDest }, { - $set: { - blocked: true, - username_who_block: usernameOrig, - date_blocked: new Date(), - }, - }); + ris = await MyGroup.updateOne( + { idapp, groupname: groupnameDest }, + { + $set: { + blocked: true, + username_who_block: usernameOrig, + date_blocked: new Date(), + }, + } + ); //++Todo: Send Notification to Admin and Group's manager tools.sendNotificationByGroupname(idapp, usernameOrig, groupnameDest, cmd, false, true, username_action); - } else if (cmd === shared_consts.GROUPSCMD.ADDADMIN_OFMYGROUP) { ris = await MyGroup.addToAdminOfMyGroup(idapp, usernameOrig, groupnameDest); // Rimuovo la richiesta di entrare nel gruppo // Invia una notifica alla persona await tools.sendNotificationByGroupname(idapp, usernameOrig, groupnameDest, cmd, false, true, username_action); - } else if (cmd === shared_consts.GROUPSCMD.REMOVEADMIN_OFMYGROUP) { ris = await MyGroup.removeAdminOfMyGroup(idapp, usernameOrig, groupnameDest); // Rimuovo la richiesta di entrare nel gruppo // Invia una notifica alla persona await tools.sendNotificationByGroupname(idapp, usernameOrig, groupnameDest, cmd, false, true, username_action); - } } catch (e) { console.error('Error: ', e); @@ -3079,7 +3100,6 @@ UserSchema.statics.setGroupsCmd = async function (idapp, usernameOrig, groupname }; UserSchema.statics.updateMyData = async function (outres, idapp, username) { - try { //++Todo: Ottimizzare ! Non occorre inviare tutti questi dati !!! Solo per il Circuito ?! const userprofile = await User.getExtraInfoByUsername(idapp, username); @@ -3088,18 +3108,22 @@ UserSchema.statics.updateMyData = async function (outres, idapp, username) { } outres.listcircuits = await Circuit.findAllIdApp(idapp); outres.mygroups = await MyGroup.findAllGroups(idapp); - } catch (e) { console.error('ERR', e); } return outres; - }; - -UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitname, cmd, value, username_action, extrarec) { - +UserSchema.statics.setCircuitCmd = async function ( + idapp, + usernameOrig, + circuitname, + cmd, + value, + username_action, + extrarec +) { // console.log('setCircuitCmd', cmd); const { SendNotif } = require('../models/sendnotif'); @@ -3120,42 +3144,53 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn // Il Conto Comunitario prende il nome del circuito ! await Account.createAccount(idapp, '', circuitname, true, '', mycirc.path); } - } else if (cmd === shared_consts.CIRCUITCMD.SET) { - if (groupname) { const foundIfCircuitInGroup = await MyGroup.ifCircuitAlreadyInGroup(idapp, groupname, circuitname); if (!foundIfCircuitInGroup) { ris = await this.addCircuitToUser(idapp, usernameOrig, circuitname, true, groupname); - } else { ris = false; } - await Circuit.updateData(idapp, circuitname) + await Circuit.updateData(idapp, circuitname); if (ris) { // Invia una notifica alla persona e agli Admin - tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, value, true, username_action, extrarec); + tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + value, + true, + username_action, + extrarec + ); outres.result = await Circuit.getInfoCircuitByName(idapp, circuitname); } } else { - ris = await this.addCircuitToUser(idapp, usernameOrig, circuitname, true, ''); - await Circuit.updateData(idapp, circuitname) + await Circuit.updateData(idapp, circuitname); if (ris) { // Invia una notifica alla persona e agli Admin - tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, value, true, username_action, extrarec); + tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + value, + true, + username_action, + extrarec + ); outres.result = await Circuit.getInfoCircuitByName(idapp, circuitname); } } - } else if (cmd === shared_consts.CIRCUITCMD.SETFIDO) { - ris = await Circuit.setFido(idapp, usernameOrig, circuitname, groupname); if (ris && ris.fidoConcesso && ris.changed) { - if (extrarec) { extrarec.fidoConcesso = ris.fidoConcesso; extrarec.qta_maxConcessa = ris.qta_maxConcessa; @@ -3165,63 +3200,85 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn update = { $pull: { req_users: { username: { $in: [usernameOrig] } } } }; await Circuit.updateOne({ idapp, name: circuitname }, update); - await Circuit.updateData(idapp, circuitname) + await Circuit.updateData(idapp, circuitname); if (ris) { // Invia una notifica alla persona e agli Admin - tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, value, true, username_action, extrarec); + tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + value, + true, + username_action, + extrarec + ); outres.result = await Circuit.getInfoCircuitByName(idapp, circuitname); } } else { // errore !? } - } else if (cmd === shared_consts.CIRCUITCMD.REQ) { - if (groupname) { // Aggiungo la richiesta di Gruppo a me const foundIfAlreadyAskCircuit = await Circuit.findOne({ idapp, name: circuitname, - 'req_groups': { + req_groups: { $elemMatch: { groupname: { $eq: groupname } }, }, }); if (value) { - ris = await this.addCircuitToUser(idapp, usernameOrig, circuitname, false, groupname, ''); if (!foundIfAlreadyAskCircuit) { update = { $push: { - 'req_groups': { + req_groups: { groupname, date: new Date(), }, }, }; ris = await Circuit.updateOne({ idapp, name: circuitname }, update); - } if (ris) { // Invia una notifica alla persona - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, true, true, username_action, extrarec); + await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + true, + true, + username_action, + extrarec + ); } } else { if (foundIfAlreadyAskCircuit) { outres.result = await MyGroup.removeCircuitFromGroup(idapp, groupname, circuitname); // Rimuovo il Circuito dal gruppo // Invia una notifica alla persona - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); + await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + false, + true, + username_action, + extrarec + ); } } - } else { // Aggiungo la richiesta di Circuito a me const foundIfAlreadyAskCircuit = await Circuit.findOne({ idapp, name: circuitname, - 'req_users': { + req_users: { $elemMatch: { username: { $eq: usernameOrig } }, }, }); @@ -3240,7 +3297,7 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn if (!foundIfAlreadyAskCircuit) { update = { $push: { - 'req_users': { + req_users: { username: usernameOrig, date: new Date(), }, @@ -3248,27 +3305,40 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn }; // Aggiungi la richiesta per ottenere il fido (o per entrare nel circuito) ris = await Circuit.updateOne({ idapp, name: circuitname }, update); - } if (ris) { // Invia una notifica alla persona - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, true, true, username_action, extrarec); + await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + true, + true, + username_action, + extrarec + ); } } else { if (foundIfAlreadyAskCircuit) { outres.result = await this.removeFromCircuits(idapp, usernameOrig, circuitname); // Rimuovo il Gruppo da me // Invia una notifica alla persona - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); + await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + false, + true, + username_action, + extrarec + ); } } - } - - } else if (cmd === shared_consts.CIRCUITCMD.REMOVE_FROM_MYLIST) { - if (groupname) { // Elimina la richiesta: update = { $pull: { req_groups: { groupname: { $in: [groupname] } } } }; @@ -3276,7 +3346,6 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn outres.result = await MyGroup.removeCircuitFromGroup(idapp, groupname, circuitname); // Rimuovo l'Amicizia da me } else { - // Remove if is also an Admin await Circuit.removeAdminOfMyCircuit(idapp, usernameOrig, circuitname); @@ -3287,30 +3356,40 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn } // Invia una notifica alla persona - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); - + await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + false, + true, + username_action, + extrarec + ); } else if (cmd === shared_consts.CIRCUITCMD.DELETE) { - ris = await this.removeFromCircuits(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me if (ris) { // Invia una notifica alla persona e agli Admin - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); - + await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + false, + true, + username_action, + extrarec + ); } outres.result = await Circuit.deleteCircuit(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me - } else if (cmd === shared_consts.CIRCUITCMD.CANCEL_REQ) { - if (groupname) outres.result = await Circuit.removeReqGroupCircuit(idapp, groupname, circuitname); // Rimuovo l'Amicizia da me - else - outres.result = await Circuit.removeReqCircuit(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me - - await Circuit.updateData(idapp, circuitname) + else outres.result = await Circuit.removeReqCircuit(idapp, usernameOrig, circuitname); // Rimuovo l'Amicizia da me + await Circuit.updateData(idapp, circuitname); } else if (cmd === shared_consts.CIRCUITCMD.REFUSE_REQ) { - if (groupname) { outres.result = await MyGroup.removeCircuitFromGroup(idapp, groupname, circuitname); // Rimuovo l'Amicizia da me outres.result = await Circuit.removeReqGroupCircuit(idapp, groupname, circuitname); // Rimuovo l'Amicizia da me @@ -3322,20 +3401,44 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn } // Invia una notifica alla persona - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); - + await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + false, + true, + username_action, + extrarec + ); } else if (cmd === shared_consts.CIRCUITCMD.ADDADMIN) { outres.result = await Circuit.addToAdminOfMyCircuit(idapp, usernameOrig, circuitname); // Rimuovo la richiesta di entrare nel gruppo // Invia una notifica alla persona - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); - + await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + false, + true, + username_action, + extrarec + ); } else if (cmd === shared_consts.CIRCUITCMD.REMOVEADMIN) { outres.result = await Circuit.removeAdminOfMyCircuit(idapp, usernameOrig, circuitname); // Rimuovo la richiesta di entrare nel gruppo // Invia una notifica alla persona - await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); - + await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + false, + true, + username_action, + extrarec + ); } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REQ) { const onlycheck = false; @@ -3385,7 +3488,16 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn if (outcheck.cansend) { // Invia una notifica di moneta (accettata o rifiutata) alla persona - const out = await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); + const out = await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + false, + true, + username_action, + extrarec + ); if (outres && extrarec.groupname) { // Setta agli altri admin, @@ -3393,13 +3505,24 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn } outres.recnotif = await SendNotif.getRecNotif(extrarec.notifId); - outres.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER, shared_consts.QualiNotifs.OTHERS); + outres.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp( + username_action, + extrarec.lastdr, + idapp, + shared_consts.LIMIT_NOTIF_FOR_USER, + shared_consts.QualiNotifs.OTHERS + ); if (await User.isAdminByUsername(idapp, username_action)) { outres.arrrecnotifcoins = await SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp); } else { - outres.arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIFCOINS_FOR_USER, shared_consts.QualiNotifs.CIRCUITS); + outres.arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp( + username_action, + extrarec.lastdr, + idapp, + shared_consts.LIMIT_NOTIFCOINS_FOR_USER, + shared_consts.QualiNotifs.CIRCUITS + ); } - } } @@ -3420,11 +3543,13 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn // await telegrambot.sendMsgTelegram(idapp, usernameOrig, msgOrig); // Invia questo msg anche all'Admin - await telegrambot.sendMsgTelegramToTheAdmin(idapp, outres.errormsg + '\n(Mittente: ' + usernameOrig + ')', true); - + await telegrambot.sendMsgTelegramToTheAdmin( + idapp, + outres.errormsg + '\n(Mittente: ' + usernameOrig + ')', + true + ); } - - } else if ((cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) || (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE)) { + } else if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT || cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE) { // Before to accept, I see if it's already set ! outres = { @@ -3442,7 +3567,7 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn risStatus = i18n.__('STATUS_REFUSED'); } // if (!await SendNotif.checkIfCoinsAlreadySent(extrarec.notifId)) { - if (!await Movement.checkIfCoinsAlreadySent(extrarec.notifId)) { + if (!(await Movement.checkIfCoinsAlreadySent(extrarec.notifId))) { if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) { outcheck = await Circuit.sendCoins(true, idapp, usernameOrig, extrarec); } else { @@ -3452,9 +3577,8 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn if (outcheck) { if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT && outcheck.cansend) { - if (!await Movement.checkIfCoinsAlreadySent(extrarec.notifId)) { + if (!(await Movement.checkIfCoinsAlreadySent(extrarec.notifId))) { outres = await Circuit.sendCoins(false, idapp, usernameOrig, extrarec); - } else { outcheck.cansend = false; //GIA INVIATO } @@ -3462,7 +3586,16 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn if (outcheck.cansend) { // Invia una notifica di moneta (accettata o rifiutata) alla persona - const out = await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec); + const out = await tools.sendNotificationByCircuit( + idapp, + usernameOrig, + circuitname, + cmd, + false, + true, + username_action, + extrarec + ); if (outres && extrarec.groupname) { // Setta agli altri admin, @@ -3470,16 +3603,26 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn } outres.recnotif = await SendNotif.getRecNotif(extrarec.notifId); - outres.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER); + outres.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp( + username_action, + extrarec.lastdr, + idapp, + shared_consts.LIMIT_NOTIF_FOR_USER + ); if (await User.isAdminByUsername(idapp, username_action)) { outres.arrrecnotifcoins = await SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp); } else { - outres.arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIFCOINS_FOR_USER, shared_consts.QualiNotifs.CIRCUITS); + outres.arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp( + username_action, + extrarec.lastdr, + idapp, + shared_consts.LIMIT_NOTIFCOINS_FOR_USER, + shared_consts.QualiNotifs.CIRCUITS + ); } } //---- - } else { outres.cansend = false; @@ -3492,11 +3635,9 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn outres = await this.updateMyData(outres, idapp, username_action); } - if (circuitname) - outres.circuit = await Circuit.getInfoCircuitByName(idapp, circuitname); + if (circuitname) outres.circuit = await Circuit.getInfoCircuitByName(idapp, circuitname); return outres; - } catch (e) { console.error('Error setCircuitCmd: ', e); } @@ -3550,7 +3691,6 @@ function getWhatToShow(idapp, username) { 'profile.da_contattare': 1, perm: 1, }; - } function getWhatToShow_Unknown(idapp, username) { @@ -3581,7 +3721,7 @@ function getWhatToShow_Unknown(idapp, username) { 'profile.attend': 1, 'profile.seen': 1, perm: 1, - } + }; } UserSchema.statics.getWhatToShow_IfFriends = async function (idapp, username) { @@ -3617,128 +3757,134 @@ UserSchema.statics.getWhatToShow_IfFriends = async function (idapp, username) { 'profile.seen': 1, perm: 1, }; - }; UserSchema.statics.getInfoFriendByUsername = async function (idapp, username) { - const whatToShow = getWhatToShow(idapp, username); - return await User.findOne({ - idapp, - username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, whatToShow).lean().then((rec) => !!rec ? rec : null); - + return await User.findOne( + { + idapp, + username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + whatToShow + ) + .lean() + .then((rec) => (!!rec ? rec : null)); }; -UserSchema.statics.getInfoAskFriendByUsername = async function ( - idapp, username) { - +UserSchema.statics.getInfoAskFriendByUsername = async function (idapp, username) { const whatToShow = getWhatToShow_Unknown(idapp, username); - return await User.findOne({ - idapp, - username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, whatToShow).lean().then((rec) => !!rec ? rec : null); - + return await User.findOne( + { + idapp, + username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + whatToShow + ) + .lean() + .then((rec) => (!!rec ? rec : null)); }; UserSchema.statics.getAskedFriendsByUsername = async function (idapp, username) { - const whatToShow_Unknown = getWhatToShow_Unknown(idapp, username); - return await User.find({ - idapp, - 'profile.req_friends': { - $elemMatch: { username: { $eq: username } }, + return await User.find( + { + idapp, + 'profile.req_friends': { + $elemMatch: { username: { $eq: username } }, + }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, whatToShow_Unknown).then((rec) => { - + whatToShow_Unknown + ).then((rec) => { //return rec.map(m => m.username); }); - }; - UserSchema.statics.getUsersToVerify = async function (idapp, username) { - const whatToShow_Unknown = getWhatToShow(idapp, username); - let usersToVerify = await User.find({ - idapp, aportador_solidario: username, - verified_by_aportador: { $exists: false }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }, whatToShow_Unknown).lean(); + let usersToVerify = await User.find( + { + idapp, + aportador_solidario: username, + verified_by_aportador: { $exists: false }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + whatToShow_Unknown + ).lean(); return usersToVerify; }; UserSchema.statics.getFriendsByUsername = async function (idapp, username) { - if (!username) { return { listFriends: [], listRequestFriends: [], listTrusted: [], listSentRequestFriends: [], - } + }; } try { const whatToShow = getWhatToShow(idapp, username); const whatToShow_Unknown = getWhatToShow_Unknown(idapp, username); - const arrUsernameFriends = await User.getUsernameFriendsByUsername(idapp, - username); - const arrUsernameReqFriends = await User.getUsernameReqFriendsByUsername( - idapp, username); - const arrUsernameHandShake = await User.getUsernameHandShakeByUsername(idapp, - username); + const arrUsernameFriends = await User.getUsernameFriendsByUsername(idapp, username); + const arrUsernameReqFriends = await User.getUsernameReqFriendsByUsername(idapp, username); + const arrUsernameHandShake = await User.getUsernameHandShakeByUsername(idapp, username); - let listFriends = await User.find({ - idapp, - username: { $in: arrUsernameFriends }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }, whatToShow); - - let listHandShake = await User.find({ - idapp, - username: { $in: arrUsernameHandShake }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }, whatToShow); - - let listRequestFriends = await User.find({ - idapp, - username: { $in: arrUsernameReqFriends }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }, whatToShow_Unknown); - - let listSentRequestFriends = await User.find({ - idapp, - 'profile.req_friends': { - $elemMatch: { username: { $eq: username } }, + let listFriends = await User.find( + { + idapp, + username: { $in: arrUsernameFriends }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }, whatToShow_Unknown); + whatToShow + ); - let listTrusted = await User.find({ - idapp, aportador_solidario: username, - 'profile.teleg_id': { $gt: 0 }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }, whatToShow); + let listHandShake = await User.find( + { + idapp, + username: { $in: arrUsernameHandShake }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + whatToShow + ); + + let listRequestFriends = await User.find( + { + idapp, + username: { $in: arrUsernameReqFriends }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + whatToShow_Unknown + ); + + let listSentRequestFriends = await User.find( + { + idapp, + 'profile.req_friends': { + $elemMatch: { username: { $eq: username } }, + }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + whatToShow_Unknown + ); + + let listTrusted = await User.find( + { + idapp, + aportador_solidario: username, + 'profile.teleg_id': { $gt: 0 }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + whatToShow + ); return { listFriends, @@ -3747,7 +3893,6 @@ UserSchema.statics.getFriendsByUsername = async function (idapp, username) { listTrusted, listSentRequestFriends, }; - } catch (e) { console.log('Error', e); } @@ -3758,22 +3903,23 @@ UserSchema.statics.getFriendsByUsername = async function (idapp, username) { listRequestFriends: [], listTrusted: [], listSentRequestFriends: [], - }; }; -UserSchema.statics.getAportadorSolidarioByUsername = async function ( - idapp, username) { +UserSchema.statics.getAportadorSolidarioByUsername = async function (idapp, username) { const User = this; return await User.findOne({ - idapp, username, + idapp, + username, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }).then((rec) => { - return ((rec) ? rec.aportador_solidario : ''); - }).catch((e) => { - console.error('getAportadorSolidarioByUsername', e); - }); + }) + .then((rec) => { + return rec ? rec.aportador_solidario : ''; + }) + .catch((e) => { + console.error('getAportadorSolidarioByUsername', e); + }); }; UserSchema.statics.UserByIdTelegram = async function (idapp, teleg_id) { @@ -3783,32 +3929,33 @@ UserSchema.statics.UserByIdTelegram = async function (idapp, teleg_id) { idapp, 'profile.teleg_id': teleg_id, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }).lean().then(async (rec) => { - if (!rec) { - // Cerca se esiste in quello salvato in precedenza: - const recold = await User.findOne({ - idapp, - 'profile.teleg_id_old': teleg_id - }).lean(); - if (recold && recold.profile.teleg_id_old === teleg_id) { - // Riaggiorna l'ID perché è ritornato sulla chat! - await User.SetTelegramIdSuccess(idapp, recold._id, recold.profile.teleg_id_old); - - rec = await User.findOne({ + }) + .lean() + .then(async (rec) => { + if (!rec) { + // Cerca se esiste in quello salvato in precedenza: + const recold = await User.findOne({ idapp, - 'profile.teleg_id': teleg_id, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + 'profile.teleg_id_old': teleg_id, }).lean(); + if (recold && recold.profile.teleg_id_old === teleg_id) { + // Riaggiorna l'ID perché è ritornato sulla chat! + await User.SetTelegramIdSuccess(idapp, recold._id, recold.profile.teleg_id_old); + + rec = await User.findOne({ + idapp, + 'profile.teleg_id': teleg_id, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }).lean(); + } } - - } - return (!!rec) ? rec : null; - }).catch((e) => { - console.error('UserExistByIdTelegram', e); - }); + return !!rec ? rec : null; + }) + .catch((e) => { + console.error('UserExistByIdTelegram', e); + }); }; - UserSchema.statics.setPicProfile = async function (idapp, username, imgpic) { const User = this; @@ -3816,67 +3963,96 @@ UserSchema.statics.setPicProfile = async function (idapp, username, imgpic) { 'profile.img': imgpic, }; - return await User.findOneAndUpdate({ - idapp, username, - }, { $set: fields_to_update }, { new: false }).lean().then((record) => { - return !!record; - }); - + return await User.findOneAndUpdate( + { + idapp, + username, + }, + { $set: fields_to_update }, + { new: false } + ) + .lean() + .then((record) => { + return !!record; + }); }; UserSchema.statics.TelegIdByUsername = async function (idapp, username) { const User = this; - return await User.findOne({ - idapp, username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { 'profile.teleg_id': 1 }).lean().then((rec) => { - return (!!rec) ? rec.profile.teleg_id : null; - }).catch((e) => { - console.error('TelegIdByUsername', e); - }); + return await User.findOne( + { + idapp, + username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { 'profile.teleg_id': 1 } + ) + .lean() + .then((rec) => { + return !!rec ? rec.profile.teleg_id : null; + }) + .catch((e) => { + console.error('TelegIdByUsername', e); + }); }; UserSchema.statics.TelegIdById = async function (idapp, id) { const User = this; - return await User.findOne({ - idapp, - _id: id, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { 'profile.teleg_id': 1 }).lean().then((rec) => { - return (!!rec) ? rec.profile.teleg_id : null; - }).catch((e) => { - console.error('TelegIdByUsername', e); - }); + return await User.findOne( + { + idapp, + _id: id, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { 'profile.teleg_id': 1 } + ) + .lean() + .then((rec) => { + return !!rec ? rec.profile.teleg_id : null; + }) + .catch((e) => { + console.error('TelegIdByUsername', e); + }); }; UserSchema.statics.notAsk_VerifByUsername = async function (idapp, username) { - - return await User.findOne({ - idapp, username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { 'notask_verif': 1 }).lean().then((rec) => { - return (!!rec && rec.notask_verif) ? true : false; - }).catch((e) => { - console.error('notAsk_VerifByUsername', e); - return false; - }); + return await User.findOne( + { + idapp, + username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { notask_verif: 1 } + ) + .lean() + .then((rec) => { + return !!rec && rec.notask_verif ? true : false; + }) + .catch((e) => { + console.error('notAsk_VerifByUsername', e); + return false; + }); }; -UserSchema.statics.SetTelegramCheckCode = async function ( - idapp, id, teleg_checkcode) { +UserSchema.statics.SetTelegramCheckCode = async function (idapp, id, teleg_checkcode) { const User = this; const fields_to_update = { 'profile.teleg_checkcode': teleg_checkcode, }; - return await User.findOneAndUpdate({ - _id: id, - }, { $set: fields_to_update }, { new: false }).lean().then((record) => { - return !!record; - }); - + return await User.findOneAndUpdate( + { + _id: id, + }, + { $set: fields_to_update }, + { new: false } + ) + .lean() + .then((record) => { + return !!record; + }); }; UserSchema.statics.NonVoglioImbarcarmi = async function (idapp, username) { @@ -3886,13 +4062,16 @@ UserSchema.statics.NonVoglioImbarcarmi = async function (idapp, username) { non_voglio_imbarcarmi: true, }; - return await User.findOneAndUpdate({ - idapp, - username, - }, { $set: fields_to_update }, { new: false }).then((record) => { + return await User.findOneAndUpdate( + { + idapp, + username, + }, + { $set: fields_to_update }, + { new: false } + ).then((record) => { return !!record; }); - }; UserSchema.statics.SetTelegramIdSuccess = async function (idapp, id, teleg_id) { @@ -3904,35 +4083,44 @@ UserSchema.statics.SetTelegramIdSuccess = async function (idapp, id, teleg_id) { 'profile.teleg_checkcode': 0, }; - return await User.findOneAndUpdate({ - idapp, - _id: id, - }, { $set: fields_to_update }, { new: false }).lean().then((record) => { - - if (record) { - return User.findOne({ - idapp, - _id: id, - }).lean(); - } - }); + return await User.findOneAndUpdate( + { + idapp, + _id: id, + }, + { $set: fields_to_update }, + { new: false } + ) + .lean() + .then((record) => { + if (record) { + return User.findOne({ + idapp, + _id: id, + }).lean(); + } + }); return null; - }; UserSchema.statics.getUsernameTelegram = async function (idapp, username) { const User = this; - return await User.findOne({ idapp, username }, { 'profile.username_telegram': 1 }).lean().then((ris) => { - if (ris) - return ris.profile.username_telegram; - else - return ''; - }); + return await User.findOne({ idapp, username }, { 'profile.username_telegram': 1 }) + .lean() + .then((ris) => { + if (ris) return ris.profile.username_telegram; + else return ''; + }); }; UserSchema.statics.setUsernameTelegram = async function ( - idapp, id, username_telegram, firstname_telegram, lastname_telegram) { + idapp, + id, + username_telegram, + firstname_telegram, + lastname_telegram +) { const User = this; const fields_to_update = { @@ -3941,13 +4129,16 @@ UserSchema.statics.setUsernameTelegram = async function ( 'profile.lastname_telegram': lastname_telegram, }; - return await User.findOneAndUpdate({ - idapp, - _id: id, - }, { $set: fields_to_update }, { new: false }).then((record) => { + return await User.findOneAndUpdate( + { + idapp, + _id: id, + }, + { $set: fields_to_update }, + { new: false } + ).then((record) => { return record; }); - }; UserSchema.statics.SetLang = async function (idapp, id, lang) { @@ -3957,12 +4148,15 @@ UserSchema.statics.SetLang = async function (idapp, id, lang) { lang, }; - return await User.findOneAndUpdate({ - _id: id, - }, { $set: fields_to_update }, { new: false }).then((record) => { + return await User.findOneAndUpdate( + { + _id: id, + }, + { $set: fields_to_update }, + { new: false } + ).then((record) => { return record; }); - }; UserSchema.statics.SetTelegramWasBlocked = async function (idapp, teleg_id) { @@ -3973,45 +4167,50 @@ UserSchema.statics.SetTelegramWasBlocked = async function (idapp, teleg_id) { 'profile.teleg_id': 0, }; - // if (tools.sulServer()) { if (true) { - - const ris = await User.findOneAndUpdate({ - idapp, - 'profile.teleg_id': teleg_id, - }, { $set: fields_to_update }, { new: false }).then((record) => { + const ris = await User.findOneAndUpdate( + { + idapp, + 'profile.teleg_id': teleg_id, + }, + { $set: fields_to_update }, + { new: false } + ).then((record) => { return record; }); } - }; -UserSchema.statics.getNameSurnameByUsername = async function ( - idapp, username, reale = false) { +UserSchema.statics.getNameSurnameByUsername = async function (idapp, username, reale = false) { const User = this; - return await User.findOne({ - idapp, username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { username: 1, name: 1, surname: 1 }).then((rec) => { - let ris = rec.username; - if (!!rec) { - if (reale) { - if (!rec.name) - return ''; + return await User.findOne( + { + idapp, + username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { username: 1, name: 1, surname: 1 } + ) + .then((rec) => { + let ris = rec.username; + if (!!rec) { + if (reale) { + if (!rec.name) return ''; - ris = `${rec.name} ${rec.surname}`; - } else { - if (rec.name) { ris = `${rec.name} ${rec.surname}`; + } else { + if (rec.name) { + ris = `${rec.name} ${rec.surname}`; + } } } - } - return (!!rec) ? ris : ''; - }).catch((e) => { - console.error('getNameSurnameByUsername', e); - }); + return !!rec ? ris : ''; + }) + .catch((e) => { + console.error('getNameSurnameByUsername', e); + }); }; UserSchema.statics.getIdByUsername = async function (idapp, username) { @@ -4019,15 +4218,20 @@ UserSchema.statics.getIdByUsername = async function (idapp, username) { let regexp = new RegExp(`^${username}$`, 'i'); - return await User.findOne({ - idapp, - username: { $regex: regexp }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { username: 1, _id: 1 }).then((rec) => { - return (!!rec) ? rec._id.toString() : ''; - }).catch((e) => { - console.error('getIdByUsername', e); - }); + return await User.findOne( + { + idapp, + username: { $regex: regexp }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { username: 1, _id: 1 } + ) + .then((rec) => { + return !!rec ? rec._id.toString() : ''; + }) + .catch((e) => { + console.error('getIdByUsername', e); + }); }; UserSchema.statics.getRealUsernameByUsername = async function (idapp, username) { @@ -4035,16 +4239,20 @@ UserSchema.statics.getRealUsernameByUsername = async function (idapp, username) let regexp = new RegExp(`^${username}$`, 'i'); - return await User.findOne({ - idapp, - username: - { $regex: regexp }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { username: 1, _id: 1 }).then((rec) => { - return (!!rec) ? rec.username : ''; - }).catch((e) => { - console.error('getRealUsernameByUsername', e); - }); + return await User.findOne( + { + idapp, + username: { $regex: regexp }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { username: 1, _id: 1 } + ) + .then((rec) => { + return !!rec ? rec.username : ''; + }) + .catch((e) => { + console.error('getRealUsernameByUsername', e); + }); }; UserSchema.statics.getRealUsernameByUsernameTelegram = async function (idapp, username) { @@ -4052,52 +4260,71 @@ UserSchema.statics.getRealUsernameByUsernameTelegram = async function (idapp, us let regexp = new RegExp(`^${username}$`, 'i'); - return await User.findOne({ - idapp, - 'profile.username_telegram': - { $regex: regexp }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { username: 1, _id: 1 }).then((rec) => { - return (!!rec) ? rec.username : ''; - }).catch((e) => { - console.error('getRealUsernameByUsername', e); - }); + return await User.findOne( + { + idapp, + 'profile.username_telegram': { $regex: regexp }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { username: 1, _id: 1 } + ) + .then((rec) => { + return !!rec ? rec.username : ''; + }) + .catch((e) => { + console.error('getRealUsernameByUsername', e); + }); }; UserSchema.statics.getRecLangAndIdByUsername = async function (idapp, username) { const User = this; - return await User.findOne({ - idapp, username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { lang: 1, _id: 1 }).then((rec) => { - return (!!rec) ? rec : null; - }).catch((e) => { - console.error('getRecLangAndIdByUsername', e); - }); + return await User.findOne( + { + idapp, + username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { lang: 1, _id: 1 } + ) + .then((rec) => { + return !!rec ? rec : null; + }) + .catch((e) => { + console.error('getRecLangAndIdByUsername', e); + }); }; UserSchema.statics.getNameSurnameById = async function (idapp, userId) { const User = this; - return await User.findOne({ - idapp, - _id: userId, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, { name: 1, surname: 1 }).then((rec) => { - return (!!rec) ? `${rec.name} ${rec.surname}` : ''; - }).catch((e) => { - console.error('getNameSurnameById', e); - }); + return await User.findOne( + { + idapp, + _id: userId, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { name: 1, surname: 1 } + ) + .then((rec) => { + return !!rec ? `${rec.name} ${rec.surname}` : ''; + }) + .catch((e) => { + console.error('getNameSurnameById', e); + }); }; UserSchema.statics.getusersManagers = async function (idapp) { const User = this; // Int32 mongodb 6.0 - return await User.find({ idapp, 'profile.manage_telegram': true, perm: { $bitsAnySet: 0b010 } }, - { username: 1, 'profile.teleg_id': 1, perm: 1 }).then((arrrec) => { - return (!!arrrec) ? arrrec : null; - }).catch((e) => { + return await User.find( + { idapp, 'profile.manage_telegram': true, perm: { $bitsAnySet: 0b010 } }, + { username: 1, 'profile.teleg_id': 1, perm: 1 } + ) + .then((arrrec) => { + return !!arrrec ? arrrec : null; + }) + .catch((e) => { console.error('getusersManagers', e); }); }; @@ -4107,10 +4334,14 @@ UserSchema.statics.getusersAdmin = async function (idapp) { // Int32 mongodb 6.0 - return await User.find({ idapp, 'profile.admin_telegram': true, perm: { $bitsAnySet: 0b001 } }, - { username: 1, 'profile.teleg_id': 1, perm: 1 }).then((arrrec) => { - return (!!arrrec) ? arrrec : null; - }).catch((e) => { + return await User.find( + { idapp, 'profile.admin_telegram': true, perm: { $bitsAnySet: 0b001 } }, + { username: 1, 'profile.teleg_id': 1, perm: 1 } + ) + .then((arrrec) => { + return !!arrrec ? arrrec : null; + }) + .catch((e) => { console.error('getusersAdmin', e); }); }; @@ -4118,10 +4349,11 @@ UserSchema.statics.getusersAdmin = async function (idapp) { UserSchema.statics.getusersRespList = async function (idapp) { const User = this; - return await User.find({ idapp, 'profile.resplist': true }, - { _id: 1, username: 1, name: 1, surname: 1 }).then((arrrec) => { - return (!!arrrec) ? arrrec : null; - }).catch((e) => { + return await User.find({ idapp, 'profile.resplist': true }, { _id: 1, username: 1, name: 1, surname: 1 }) + .then((arrrec) => { + return !!arrrec ? arrrec : null; + }) + .catch((e) => { console.error('getusersRespList', e); }); }; @@ -4129,10 +4361,11 @@ UserSchema.statics.getusersRespList = async function (idapp) { UserSchema.statics.getusersWorkersList = async function (idapp) { const User = this; - return await User.find({ idapp, 'profile.workerslist': true }, - { _id: 1, username: 1, name: 1, surname: 1 }).then((arrrec) => { - return (!!arrrec) ? arrrec : null; - }).catch((e) => { + return await User.find({ idapp, 'profile.workerslist': true }, { _id: 1, username: 1, name: 1, surname: 1 }) + .then((arrrec) => { + return !!arrrec ? arrrec : null; + }) + .catch((e) => { console.error('getusersWorkersList', e); }); }; @@ -4146,19 +4379,18 @@ UserSchema.statics.getusersManagersAndZoomeri = async function (idapp) { or: [ { 'profile.manage_telegram': true }, { - perm: - { - $bit: - - Number(shared_consts.Permissions.Zoomeri), - + perm: { + $bit: Number(shared_consts.Permissions.Zoomeri), }, }, ], }, - { 'profile.teleg_id': 1 }).then((arrrec) => { - return (!!arrrec) ? arrrec : null; - }).catch((e) => { + { 'profile.teleg_id': 1 } + ) + .then((arrrec) => { + return !!arrrec ? arrrec : null; + }) + .catch((e) => { console.error('getusersManagers', e); }); }; @@ -4169,60 +4401,69 @@ UserSchema.statics.getUsersTelegALL = async function (idapp, username) { if (!!username) { return await User.find({ idapp, username, 'profile.teleg_id': { $gt: 0 } }).lean(); then((arrrec) => { - return (!!arrrec) ? arrrec : null; - }). - catch((e) => { - console.error('getUsersTelegALL', e); - }); + return !!arrrec ? arrrec : null; + }).catch((e) => { + console.error('getUsersTelegALL', e); + }); } else { - return await User.find({ idapp, 'profile.teleg_id': { $gt: 0 } }). - lean(). - then((arrrec) => { - return (!!arrrec) ? arrrec : null; - }). - catch((e) => { + return await User.find({ idapp, 'profile.teleg_id': { $gt: 0 } }) + .lean() + .then((arrrec) => { + return !!arrrec ? arrrec : null; + }) + .catch((e) => { console.error('getUsersTelegALL', e); }); } - }; UserSchema.statics.isManagerByIdTeleg = async function (idapp, idtelegram) { const User = this; - return await User.findOne({ - idapp, - 'profile.manage_telegram': true, - 'profile.teleg_id': idtelegram, - }, { 'profile.teleg_id': 1 }).then((rec) => { - return (!!rec && rec.profile.teleg_id === idtelegram); - }).catch((e) => { - console.error('isManagerByIdTeleg', e); - return false; - }); + return await User.findOne( + { + idapp, + 'profile.manage_telegram': true, + 'profile.teleg_id': idtelegram, + }, + { 'profile.teleg_id': 1 } + ) + .then((rec) => { + return !!rec && rec.profile.teleg_id === idtelegram; + }) + .catch((e) => { + console.error('isManagerByIdTeleg', e); + return false; + }); }; UserSchema.statics.isAdminByUsername = async function (idapp, username) { const User = this; - return await User.findOne({ - idapp, - username, - }, { perm: 1 }).then((rec) => { - return User.isAdmin(rec.perm); - }).catch((e) => { - console.error('isAdminByUsername', e); - return false; - }); + return await User.findOne( + { + idapp, + username, + }, + { perm: 1 } + ) + .then((rec) => { + return User.isAdmin(rec.perm); + }) + .catch((e) => { + console.error('isAdminByUsername', e); + return false; + }); }; UserSchema.statics.getUsersList = function (idapp) { const User = this; - return User.find({ - 'idapp': idapp, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, + return User.find( + { + idapp: idapp, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, { username: 1, name: 1, @@ -4236,7 +4477,7 @@ UserSchema.statics.getUsersList = function (idapp) { email: 1, date_reg: 1, img: 1, - }, + } ); }; @@ -4282,18 +4523,15 @@ UserSchema.statics.getFieldsForSearchUserFriend_AllWords = function () { { field: 'profile.username_telegram', type: tools.FieldType.string }, { field: 'name', type: tools.FieldType.string }, { field: 'surname', type: tools.FieldType.string }, - ]; }; UserSchema.statics.executeQueryTable = function (idapp, params) { params.fieldsearch = this.getFieldsForSearch(); if (params.options) { - if (tools.isBitActive(params.options, - shared_consts.OPTIONS_SEARCH_USER_ONLY_FULL_WORDS)) { + if (tools.isBitActive(params.options, shared_consts.OPTIONS_SEARCH_USER_ONLY_FULL_WORDS)) { params.fieldsearch = this.getFieldsForSearchUserFriend(); - } else if (tools.isBitActive(params.options, - shared_consts.OPTIONS_SEARCH_USER_ALL_WORDS)) { + } else if (tools.isBitActive(params.options, shared_consts.OPTIONS_SEARCH_USER_ALL_WORDS)) { params.fieldsearch = this.getFieldsForSearchUserFriend_AllWords(); } } @@ -4312,15 +4550,16 @@ UserSchema.statics.findAllIdApp = async function (idapp) { }; UserSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) { - return await tools.DuplicateAllRecords(this, idapporig, idappdest); - }; UserSchema.statics.getDashboard = async function ( - idapp, aportador_solidario, username, aportador_solidario_nome_completo) { + idapp, + aportador_solidario, + username, + aportador_solidario_nome_completo +) { try { - // DATA: username, name, surname, email, intcode_cell, cell const dashboard = { aportador: {}, @@ -4331,16 +4570,13 @@ UserSchema.statics.getDashboard = async function ( dashboard.myself = await User.getUserShortDataByUsername(idapp, username); // Data of my Aportador - dashboard.aportador = await User.getUserShortDataByUsername(idapp, - aportador_solidario); + dashboard.aportador = await User.getUserShortDataByUsername(idapp, aportador_solidario); // if (dashboard.aportador === undefined) { // dashboard.aportador = await ExtraList.getUserNotRegisteredByNameSurname(idapp, aportador_solidario_nome_completo); // } - const arrap = await User.getDownlineByUsername(idapp, username, false, - true); - if (!!arrap) - dashboard.numpeople_aportador = arrap.length; + const arrap = await User.getDownlineByUsername(idapp, username, false, true); + if (!!arrap) dashboard.numpeople_aportador = arrap.length; // console.table(dashboard.arrnavi); @@ -4351,10 +4587,8 @@ UserSchema.statics.getDashboard = async function ( } }; -UserSchema.statics.getDownline = async function ( - idapp, aportador_solidario, username) { +UserSchema.statics.getDownline = async function (idapp, aportador_solidario, username) { try { - // DATA: username, name, surname, email, intcode_cell, cell let downline = {}; @@ -4362,20 +4596,17 @@ UserSchema.statics.getDownline = async function ( // Data of my Downline const arrap = await User.getDownlineByUsername(idapp, username); - if (!!arrap) - downline.numpeople_aportador = arrap.length; + if (!!arrap) downline.numpeople_aportador = arrap.length; downline.downline = await User.getDownlineByUsername(idapp, username, true); downline.downbyuser = {}; for (const down of downline.downline) { - downline.downbyuser[down.username] = await User.getDownlineByUsername( - idapp, down.username, false); + downline.downbyuser[down.username] = await User.getDownlineByUsername(idapp, down.username, false); for (const down2 of downline.downbyuser[down.username]) { - downline.downbyuser[down2.username] = await User.getDownlineByUsername( - idapp, down2.username, false); + downline.downbyuser[down2.username] = await User.getDownlineByUsername(idapp, down2.username, false); } } @@ -4386,15 +4617,14 @@ UserSchema.statics.getDownline = async function ( } }; -UserSchema.statics.findByCellAndNameSurname = function ( - idapp, cell, name, surname) { +UserSchema.statics.findByCellAndNameSurname = function (idapp, cell, name, surname) { const User = this; return User.findOne({ - 'idapp': idapp, + idapp: idapp, 'profile.cell': cell, - 'name': name, - 'surname': surname, + name: name, + surname: surname, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); }; @@ -4440,7 +4670,6 @@ UserSchema.statics.getUsersOnLineToday = async function (idapp) { return await User.countDocuments(myfind); }; - UserSchema.statics.getUsersOnLineActive = async function (idapp) { const User = this; @@ -4632,7 +4861,7 @@ UserSchema.statics.getUsersDreams = async function (idapp) { idapp, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], 'profile.my_dream': { $exists: true }, - '$expr': { '$gt': [{ '$strLenCP': '$profile.my_dream' }, 10] }, + $expr: { $gt: [{ $strLenCP: '$profile.my_dream' }, 10] }, }; return await User.countDocuments(myfind); @@ -4647,16 +4876,14 @@ UserSchema.statics.getLastUsers = async function (idapp) { { $match: { idapp, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, }, { $lookup: { - from: "users", + from: 'users', let: { - username: "$aportador_solidario", + username: '$aportador_solidario', idapp, }, pipeline: [ @@ -4665,35 +4892,26 @@ UserSchema.statics.getLastUsers = async function (idapp) { $expr: { $and: [ { - $eq: [ - "$$username", - "$username", - ], + $eq: ['$$username', '$username'], }, { - $eq: [ - "$$idapp", - "$idapp", - ], + $eq: ['$$idapp', '$idapp'], }, ], }, }, }, ], - as: "user_aportador", + as: 'user_aportador', }, }, { - $unwind: "$user_aportador", + $unwind: '$user_aportador', }, { $replaceRoot: { newRoot: { - $mergeObjects: [ - "$user_aportador", - "$$ROOT", - ], + $mergeObjects: ['$user_aportador', '$$ROOT'], }, }, }, @@ -4705,17 +4923,17 @@ UserSchema.statics.getLastUsers = async function (idapp) { lasttimeonline: 1, aportador_solidario: 1, idMyGroup: 1, - "profile.img": 1, - "profile.resid_province": 1, + 'profile.img': 1, + 'profile.resid_province': 1, date_reg: 1, index: 1, - "profile.nationality": 1, - "user_aportador.username": 1, - "user_aportador.name": 1, - "user_aportador.lasttimeonline": 1, - "user_aportador.surname": 1, - "user_aportador.profile.resid_province": 1, - "user_aportador.profile.img": 1, + 'profile.nationality': 1, + 'user_aportador.username': 1, + 'user_aportador.name': 1, + 'user_aportador.lasttimeonline': 1, + 'user_aportador.surname': 1, + 'user_aportador.profile.resid_province': 1, + 'user_aportador.profile.img': 1, }, }, { @@ -4724,14 +4942,12 @@ UserSchema.statics.getLastUsers = async function (idapp) { { $limit: lastn, }, - ]; return await User.aggregate(myquery).then((arr) => { //return JSON.stringify(arr) return arr; }); - }; UserSchema.statics.getLastOnlineUsers = async function (idapp) { @@ -4742,9 +4958,7 @@ UserSchema.statics.getLastOnlineUsers = async function (idapp) { return await User.find( { idapp, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, { username: 1, @@ -4757,11 +4971,15 @@ UserSchema.statics.getLastOnlineUsers = async function (idapp) { 'profile.img': 1, 'profile.resid_province': 1, index: 1, - }).sort({ lasttimeonline: -1 }).limit(lastn).lean().then((arr) => { + } + ) + .sort({ lasttimeonline: -1 }) + .limit(lastn) + .lean() + .then((arr) => { //return JSON.stringify(arr) return arr; }); - }; UserSchema.statics.getLastSharedLink = async function (idapp) { @@ -4773,16 +4991,14 @@ UserSchema.statics.getLastSharedLink = async function (idapp) { { $match: { idapp, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, }, { $lookup: { - from: "users", + from: 'users', let: { - username: "$aportador_solidario", + username: '$aportador_solidario', idapp, }, pipeline: [ @@ -4791,35 +5007,26 @@ UserSchema.statics.getLastSharedLink = async function (idapp) { $expr: { $and: [ { - $eq: [ - "$$username", - "$username", - ], + $eq: ['$$username', '$username'], }, { - $eq: [ - "$$idapp", - "$idapp", - ], + $eq: ['$$idapp', '$idapp'], }, ], }, }, }, ], - as: "user_aportador", + as: 'user_aportador', }, }, { - $unwind: "$user_aportador", + $unwind: '$user_aportador', }, { $replaceRoot: { newRoot: { - $mergeObjects: [ - "$user_aportador", - "$$ROOT", - ], + $mergeObjects: ['$user_aportador', '$$ROOT'], }, }, }, @@ -4831,17 +5038,17 @@ UserSchema.statics.getLastSharedLink = async function (idapp) { lasttimeonline: 1, aportador_solidario: 1, idMyGroup: 1, - "profile.img": 1, - "profile.resid_province": 1, + 'profile.img': 1, + 'profile.resid_province': 1, date_reg: 1, index: 1, - "profile.nationality": 1, - "user_aportador.username": 1, - "user_aportador.name": 1, - "user_aportador.lasttimeonline": 1, - "user_aportador.surname": 1, - "user_aportador.profile.resid_province": 1, - "user_aportador.profile.img": 1, + 'profile.nationality': 1, + 'user_aportador.username': 1, + 'user_aportador.name': 1, + 'user_aportador.lasttimeonline': 1, + 'user_aportador.surname': 1, + 'user_aportador.profile.resid_province': 1, + 'user_aportador.profile.img': 1, }, }, { @@ -4850,14 +5057,12 @@ UserSchema.statics.getLastSharedLink = async function (idapp) { { $limit: lastn, }, - ]; return await User.aggregate(myquery).then((arr) => { //return JSON.stringify(arr) return arr; }); - }; UserSchema.statics.getDiffusoriUsers = async function (idapp) { @@ -4865,11 +5070,10 @@ UserSchema.statics.getDiffusoriUsers = async function (idapp) { const lastn = 10; - return await User.aggregate(await User.getQueryUsersDiffusori(idapp)).then(ris => { + return await User.aggregate(await User.getQueryUsersDiffusori(idapp)).then((ris) => { // console.table(ris); return ris; }); - }; UserSchema.statics.getBestStretteDiManoUsers = async function (idapp) { @@ -4877,11 +5081,10 @@ UserSchema.statics.getBestStretteDiManoUsers = async function (idapp) { const lastn = 10; - return await User.aggregate(await User.getQueryUsersStretteDiMano(idapp)).then(ris => { + return await User.aggregate(await User.getQueryUsersStretteDiMano(idapp)).then((ris) => { // console.table(ris); return ris; }); - }; UserSchema.statics.getLastStretteDiManoUsers = async function (idapp) { @@ -4891,46 +5094,47 @@ UserSchema.statics.getLastStretteDiManoUsers = async function (idapp) { const myquery = await User.getQueryLastUsersStretteDiMano(idapp); - return await User.aggregate(myquery).then(ris => { + return await User.aggregate(myquery).then((ris) => { // console.table(ris); return ris; }); - }; UserSchema.statics.getReceiveRISUsers = async function (idapp) { const User = this; - return await User.aggregate(User.getQueryReceiveRISUsers(idapp, 8)).then(ris => { + return await User.aggregate(User.getQueryReceiveRISUsers(idapp, 8)).then((ris) => { // console.table(ris); return ris; }); - }; UserSchema.statics.getListLinkReg = async function (idapp) { const User = this; - return await User.aggregate(User.getQueryListLinkReg(idapp, 8)).then(ris => { + return await User.aggregate(User.getQueryListLinkReg(idapp, 8)).then((ris) => { // console.table(ris); return ris; }); - }; UserSchema.statics.checkUser = async function (idapp, username) { const User = this; - return await User.findOne({ idapp, username }, { - verified_email: 1, - verified_by_aportador: 1, - idMyGroup: 1, - notask_verif: 1, - 'profile.teleg_id': 1, - 'profile.teleg_checkcode': 1, - }).lean().then((rec) => { - return rec; - }); - + return await User.findOne( + { idapp, username }, + { + verified_email: 1, + verified_by_aportador: 1, + idMyGroup: 1, + notask_verif: 1, + 'profile.teleg_id': 1, + 'profile.teleg_checkcode': 1, + } + ) + .lean() + .then((rec) => { + return rec; + }); }; UserSchema.statics.calculateStat = async function (idapp, username) { @@ -4943,13 +5147,10 @@ UserSchema.statics.calculateStat = async function (idapp, username) { // const { MyGroup } = require('../models/mygroup'); const globalTables = require('../tools/globalTables'); - const numUsersReg = await User.countDocuments( - { - idapp, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], - }); + const numUsersReg = await User.countDocuments({ + idapp, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }); let numByTab = {}; @@ -4964,7 +5165,6 @@ UserSchema.statics.calculateStat = async function (idapp, username) { } catch (e) { console.error(e.message); } - }; UserSchema.statics.getDistinctNationalityQuery = function (idapp) { @@ -4972,9 +5172,7 @@ UserSchema.statics.getDistinctNationalityQuery = function (idapp) { { $match: { idapp, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, }, { @@ -4990,23 +5188,19 @@ UserSchema.statics.getDistinctNationalityQuery = function (idapp) { UserSchema.statics.findAllDistinctNationality = async function (idapp) { const User = this; - return await User.aggregate(User.getDistinctNationalityQuery(idapp)).then(ris => { + return await User.aggregate(User.getDistinctNationalityQuery(idapp)).then((ris) => { // console.table(ris); return ris; }); }; - UserSchema.statics.getUsersRegDaily = function (idapp, nrec) { - const query = [ { $match: { idapp, date_reg: { $gte: tools.IncDateNow(-(1000 * 60 * 60 * 24 * nrec)) }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, }, { @@ -5034,10 +5228,7 @@ UserSchema.statics.getUsersRegDailyAverage = function (idapp, nrec) { $match: { idapp, date_reg: { $gte: tools.IncDateNow(-(1000 * 60 * 60 * 24 * nrec)) }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } } - ], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, }, { @@ -5070,7 +5261,6 @@ UserSchema.statics.getUsersRegDailyAverage = function (idapp, nrec) { }; UserSchema.statics.getQueryUsersDiffusori = async function (idapp) { - const lastn = await Settings.getValDbSettings(idapp, 'SHOW_LAST_N_USERS', 20); const query = [ @@ -5094,14 +5284,14 @@ UserSchema.statics.getQueryUsersDiffusori = async function (idapp) { }, { $group: { - _id: "$aportador_solidario", + _id: '$aportador_solidario', count: { $sum: 1, }, }, }, { - $match: { "count": { $gte: 2 } } + $match: { count: { $gte: 2 } }, }, { $sort: { @@ -5111,9 +5301,9 @@ UserSchema.statics.getQueryUsersDiffusori = async function (idapp) { { $limit: lastn }, { $lookup: { - from: "users", + from: 'users', let: { - username: "$_id", + username: '$_id', idapp, }, pipeline: [ @@ -5122,30 +5312,24 @@ UserSchema.statics.getQueryUsersDiffusori = async function (idapp) { $expr: { $and: [ { - $eq: [ - "$$username", - "$username", - ], + $eq: ['$$username', '$username'], }, { - $eq: [ - "$$idapp", - "$idapp", - ], + $eq: ['$$idapp', '$idapp'], }, ], }, }, }, ], - as: "user", + as: 'user', }, }, - { $unwind: "$user" }, + { $unwind: '$user' }, { $replaceRoot: { newRoot: { - $mergeObjects: ["$user", "$$ROOT"], + $mergeObjects: ['$user', '$$ROOT'], }, }, }, @@ -5160,7 +5344,7 @@ UserSchema.statics.getQueryUsersDiffusori = async function (idapp) { lasttimeonline: 1, date_reg: 1, idapp: 1, - "profile.img": 1, + 'profile.img': 1, // 'profile.mycircuits': 1, // 'profile.handshake': 1, }, @@ -5170,13 +5354,12 @@ UserSchema.statics.getQueryUsersDiffusori = async function (idapp) { }; UserSchema.statics.getQueryUsersStretteDiMano = async function (idapp) { - const lastn = await Settings.getValDbSettings(idapp, 'SHOW_LAST_N_USERS', 20); const query = [ { $match: { - idapp: "13", + idapp: '13', 'profile.handshake': { $exists: true }, $or: [ { @@ -5195,20 +5378,18 @@ UserSchema.statics.getQueryUsersStretteDiMano = async function (idapp) { }, { - $group: - { - _id: "$username", - count: - { $sum: { $size: "$profile.handshake" } } - } + $group: { + _id: '$username', + count: { $sum: { $size: '$profile.handshake' } }, + }, }, { $sort: { count: -1 } }, { $limit: lastn }, { $lookup: { - from: "users", + from: 'users', let: { - username: "$_id", + username: '$_id', idapp, }, pipeline: [ @@ -5217,30 +5398,24 @@ UserSchema.statics.getQueryUsersStretteDiMano = async function (idapp) { $expr: { $and: [ { - $eq: [ - "$$username", - "$username", - ], + $eq: ['$$username', '$username'], }, { - $eq: [ - "$$idapp", - "$idapp", - ], + $eq: ['$$idapp', '$idapp'], }, ], }, }, }, ], - as: "user", + as: 'user', }, }, - { $unwind: "$user" }, + { $unwind: '$user' }, { $replaceRoot: { newRoot: { - $mergeObjects: ["$user", "$$ROOT"], + $mergeObjects: ['$user', '$$ROOT'], }, }, }, @@ -5255,7 +5430,7 @@ UserSchema.statics.getQueryUsersStretteDiMano = async function (idapp) { lasttimeonline: 1, date_reg: 1, idapp: 1, - "profile.img": 1, + 'profile.img': 1, // 'profile.handshake': 1, // 'profile.mycircuits': 1, }, @@ -5265,7 +5440,6 @@ UserSchema.statics.getQueryUsersStretteDiMano = async function (idapp) { }; UserSchema.statics.getQueryLastUsersStretteDiMano = async function (idapp) { - const lastn = await Settings.getValDbSettings(idapp, 'SHOW_LAST_N_USERS', 20); const query = [ @@ -5288,16 +5462,16 @@ UserSchema.statics.getQueryLastUsersStretteDiMano = async function (idapp) { ], }, }, - { $unwind: "$profile.handshake" }, + { $unwind: '$profile.handshake' }, // Ordiniamo in base alla data della handshake in modo decrescente - { $sort: { "profile.handshake.date": -1 } }, + { $sort: { 'profile.handshake.date': -1 } }, { $lookup: { - from: "users", + from: 'users', let: { - username: "$profile.handshake.username", + username: '$profile.handshake.username', idapp: idapp, }, pipeline: [ @@ -5306,62 +5480,56 @@ UserSchema.statics.getQueryLastUsersStretteDiMano = async function (idapp) { $expr: { $and: [ { - $eq: [ - "$$username", - "$username", - ], + $eq: ['$$username', '$username'], }, { - $eq: [ - "$$idapp", - "$idapp", - ], + $eq: ['$$idapp', '$idapp'], }, ], }, }, }, ], - as: "userfriend", + as: 'userfriend', }, }, - { $unwind: "$userfriend" }, + { $unwind: '$userfriend' }, // Raggruppiamo nuovamente gli utenti dopo l'ordinamento { $group: { - _id: "$_id", - userId: { $first: "$userId" }, - idapp: { $first: "$idapp" }, - username: { $first: "$username" }, - aportador_solidario: { $first: "$aportador_solidario" }, - name: { $first: "$name" }, - surname: { $first: "$surname" }, - lasttimeonline: { $first: "$lasttimeonline" }, - date_reg: { $first: "$date_reg" }, + _id: '$_id', + userId: { $first: '$userId' }, + idapp: { $first: '$idapp' }, + username: { $first: '$username' }, + aportador_solidario: { $first: '$aportador_solidario' }, + name: { $first: '$name' }, + surname: { $first: '$surname' }, + lasttimeonline: { $first: '$lasttimeonline' }, + date_reg: { $first: '$date_reg' }, userfriend: { $first: { profile: { - img: "$userfriend.profile.img", - resid_province: "$userfriend.profile.resid_province", - note: "$userfriend.profile.note", + img: '$userfriend.profile.img', + resid_province: '$userfriend.profile.resid_province', + note: '$userfriend.profile.note', }, - username: "$userfriend.username", - name: "$userfriend.name", - surname: "$userfriend.surname", - } + username: '$userfriend.username', + name: '$userfriend.name', + surname: '$userfriend.surname', + }, }, profile: { $first: { - img: "$profile.img", - handshake: "$profile.handshake", - resid_province: "$profile.resid_province", - note: "$profile.note", + img: '$profile.img', + handshake: '$profile.handshake', + resid_province: '$profile.resid_province', + note: '$profile.note', }, }, - handshakeDate: { $first: "$profile.handshake.date" }, - } + handshakeDate: { $first: '$profile.handshake.date' }, + }, }, { $sort: { @@ -5374,33 +5542,29 @@ UserSchema.statics.getQueryLastUsersStretteDiMano = async function (idapp) { }; UserSchema.statics.getQueryReceiveRISUsers = function (idapp, hours) { - const query = [ { $match: { idapp, 'profile.lastdate_reqRis': { $gte: tools.IncDateNow(-(1000 * 60 * 60 * hours)) }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, }, { - $group: - { - _id: "$username", + $group: { + _id: '$username', count: { $sum: 1, }, - } + }, }, { $sort: { 'profile.lastdate_reqRis': -1 } }, { $limit: 30 }, { $lookup: { - from: "users", + from: 'users', let: { - username: "$_id", + username: '$_id', idapp, }, pipeline: [ @@ -5409,30 +5573,24 @@ UserSchema.statics.getQueryReceiveRISUsers = function (idapp, hours) { $expr: { $and: [ { - $eq: [ - "$$username", - "$username", - ], + $eq: ['$$username', '$username'], }, { - $eq: [ - "$$idapp", - "$idapp", - ], + $eq: ['$$idapp', '$idapp'], }, ], }, }, }, ], - as: "user", + as: 'user', }, }, - { $unwind: "$user" }, + { $unwind: '$user' }, { $replaceRoot: { newRoot: { - $mergeObjects: ["$user", "$$ROOT"], + $mergeObjects: ['$user', '$$ROOT'], }, }, }, @@ -5449,7 +5607,7 @@ UserSchema.statics.getQueryReceiveRISUsers = function (idapp, hours) { 'profile.mycircuits': 1, date_reg: 1, idapp: 1, - "profile.img": 1, + 'profile.img': 1, 'profile.handshake': 1, 'profile.note': 1, 'profile.da_contattare': 1, @@ -5461,33 +5619,29 @@ UserSchema.statics.getQueryReceiveRISUsers = function (idapp, hours) { }; UserSchema.statics.getQueryListLinkReg = function (idapp, hours) { - const query = [ { $match: { idapp, 'profile.lastdate_LinkReg': { $gte: tools.IncDateNow(-(1000 * 60 * 60 * hours)) }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, }, { - $group: - { - _id: "$username", + $group: { + _id: '$username', count: { $sum: 1, }, - } + }, }, { $sort: { 'profile.lastdate_linkReg': -1 } }, { $limit: 30 }, { $lookup: { - from: "users", + from: 'users', let: { - username: "$_id", + username: '$_id', idapp, }, pipeline: [ @@ -5496,30 +5650,24 @@ UserSchema.statics.getQueryListLinkReg = function (idapp, hours) { $expr: { $and: [ { - $eq: [ - "$$username", - "$username", - ], + $eq: ['$$username', '$username'], }, { - $eq: [ - "$$idapp", - "$idapp", - ], + $eq: ['$$idapp', '$idapp'], }, ], }, }, }, ], - as: "user", + as: 'user', }, }, - { $unwind: "$user" }, + { $unwind: '$user' }, { $replaceRoot: { newRoot: { - $mergeObjects: ["$user", "$$ROOT"], + $mergeObjects: ['$user', '$$ROOT'], }, }, }, @@ -5536,7 +5684,7 @@ UserSchema.statics.getQueryListLinkReg = function (idapp, hours) { 'profile.mycircuits': 1, date_reg: 1, idapp: 1, - "profile.img": 1, + 'profile.img': 1, 'profile.handshake': 1, 'profile.note': 1, 'profile.da_contattare': 1, @@ -5548,15 +5696,12 @@ UserSchema.statics.getQueryListLinkReg = function (idapp, hours) { }; UserSchema.statics.getUsersRegWeekly = function (idapp, nrec) { - const query = [ { $match: { idapp, date_reg: { $gte: tools.IncDateNow(-(1000 * 60 * 60 * 24 * nrec)) }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, }, { @@ -5592,15 +5737,12 @@ UserSchema.statics.getUsersRegWeekly = function (idapp, nrec) { }; UserSchema.statics.getnumRegNDays = function (idapp, nrec) { - const query = [ { $match: { idapp, date_reg: { $lt: tools.IncDateNow(-(1000 * 60 * 60 * 24 * nrec)) }, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, }, { @@ -5628,7 +5770,6 @@ UserSchema.statics.calcnumRegUntilDay = async function (idapp) { return await User.aggregate(User.getnumRegNDays(idapp, 60)).then((arr) => { return arr.reduce((sum, rec) => sum + rec.count, 0); }); - }; function calculate30DayAverage(data) { @@ -5654,7 +5795,7 @@ function calculate30DayAverage(data) { averages.push({ _id: data[i]._id, - dailyAverage: sum / count + dailyAverage: sum / count, }); } @@ -5664,18 +5805,16 @@ function calculate30DayAverage(data) { UserSchema.statics.calcRegDaily = async function (idapp) { const User = this; - return await User.aggregate(User.getUsersRegDaily(idapp, 120)).then(ris => { + return await User.aggregate(User.getUsersRegDaily(idapp, 120)).then((ris) => { // console.table(ris); return ris; }); }; - - UserSchema.statics.calcRegWeekly = async function (idapp) { const User = this; - return await User.aggregate(User.getUsersRegDaily(idapp, 120)).then(ris => { + return await User.aggregate(User.getUsersRegDaily(idapp, 120)).then((ris) => { // console.table(ris); return calculate30DayAverage(ris); }); @@ -5687,7 +5826,6 @@ if (tools.INITDB_FIRSTIME) { UserSchema.index({ userId: 1 }); UserSchema.index({ idapp: 1 }); - // UserSchema.index({ username: 'text', name: 'text', surname: 'text', email: 'text' }); // UserSchema.index({ name: 'name' }); // UserSchema.index({ name: 1 }); @@ -5698,14 +5836,15 @@ if (tools.INITDB_FIRSTIME) { } UserSchema.statics.getUsernameByIndex = async function (idapp, index) { + const myrec = await User.findOne( + { + idapp, + index, + }, + { username: 1 } + ); - const myrec = await User.findOne({ - idapp, - index, - }, { username: 1 }); - - return (!!myrec) ? myrec.username : ''; - + return !!myrec ? myrec.username : ''; }; UserSchema.statics.ricalcolaIndex = async function (idapp) { @@ -5724,13 +5863,11 @@ UserSchema.statics.ricalcolaIndex = async function (idapp) { index++; - const ris = await User.findOneAndUpdate({ _id: user._id }, { $set: field }, - { new: false }); + const ris = await User.findOneAndUpdate({ _id: user._id }, { $set: field }, { new: false }); } } catch (e) { console.error(e.message); } - }; UserSchema.statics.getInfoUser = async function (idapp, username) { @@ -5739,17 +5876,14 @@ UserSchema.statics.getInfoUser = async function (idapp, username) { is7req: await User.isUserQualified7(idapp, username), // is9req: await User.isUserQualified9(idapp, username), }; - }; -UserSchema.statics.checkIfSbloccatiRequisiti = async function ( - idapp, allData, id) { +UserSchema.statics.checkIfSbloccatiRequisiti = async function (idapp, allData, id) { const User = this; const telegrambot = require('../telegram/telegrambot'); - if (!allData.myuser) - return false; + if (!allData.myuser) return false; //if (await Nave.checkIfNaveExist(idapp, allData.myuser.username)) { // // Se già sei dentro la Nave, allora sei OK @@ -5762,16 +5896,17 @@ UserSchema.statics.checkIfSbloccatiRequisiti = async function ( // const is9req = await User.isUserQualified9(idapp, allData.myuser.username); if (!!allData.precDataUser) { - if ((!allData.precDataUser.is9req && is9req) && - !await User.isUserAlreadyQualified_2Invitati(idapp, - allData.myuser.username)) { + if ( + !allData.precDataUser.is9req && + is9req && + !(await User.isUserAlreadyQualified_2Invitati(idapp, allData.myuser.username)) + ) { await User.setUserQualified_2Invitati(idapp, allData.myuser.username); // ORA HAI I 9 REQUISITI ! // const msgtext = telegrambot.getCiao(idapp, allData.myuser.username, allData.myuser.lang) + tools.gettranslate('HAI_I_9_REQUISITI', allData.myuser.lang); // telegrambot.sendMsgTelegram(idapp, allData.myuser.username, msgtext, false); // Anche a STAFF } - } // CHECK APORTADOR SOLIDARIO: @@ -5786,7 +5921,6 @@ UserSchema.statics.checkIfSbloccatiRequisiti = async function ( } */ } - }; UserSchema.statics.mettiSognoePaypal = async function (idapp, modifica) { @@ -5795,21 +5929,20 @@ UserSchema.statics.mettiSognoePaypal = async function (idapp, modifica) { let num = 0; arrusers = await User.find({ - 'idapp': idapp, + idapp: idapp, $or: [ { deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }, { subaccount: { $exists: false } }, - { subaccount: { $exists: true, $eq: false } }], + { subaccount: { $exists: true, $eq: false } }, + ], }); for (const rec of arrusers) { - if (rec.profile.saw_zoom_presentation) { aggiornato = false; my_dream_ok = !!rec.profile.my_dream; - if (my_dream_ok) - my_dream_ok = rec.profile.my_dream.length >= 8; + if (my_dream_ok) my_dream_ok = rec.profile.my_dream.length >= 8; if (!my_dream_ok) { if (modifica) { @@ -5821,10 +5954,9 @@ UserSchema.statics.mettiSognoePaypal = async function (idapp, modifica) { revolut_ok = !!rec.profile.revolut; paypal_ok = !!rec.profile.email_paypal; - if (paypal_ok) - paypal_ok = rec.profile.email_paypal.length > 8; + if (paypal_ok) paypal_ok = rec.profile.email_paypal.length > 8; - if ((!revolut_ok) && (!paypal_ok)) { + if (!revolut_ok && !paypal_ok) { if (modifica) { rec.profile.email_paypal = rec.email; aggiornato = true; @@ -5833,19 +5965,19 @@ UserSchema.statics.mettiSognoePaypal = async function (idapp, modifica) { } if (aggiornato && modifica) { - let allData = {}; allData.myuser = await User.getUserById(idapp, rec.id); - if (!!allData.myuser) - allData.precDataUser = await User.getInfoUser(idapp, - allData.myuser.username); - else - allData.precDataUser = null; + if (!!allData.myuser) allData.precDataUser = await User.getInfoUser(idapp, allData.myuser.username); + else allData.precDataUser = null; - const risupd = await User.findByIdAndUpdate(rec._id, { - 'profile.email_paypal': rec.profile.email_paypal, - 'profile.my_dream': rec.profile.my_dream, - }, { new: false }); + const risupd = await User.findByIdAndUpdate( + rec._id, + { + 'profile.email_paypal': rec.profile.email_paypal, + 'profile.my_dream': rec.profile.my_dream, + }, + { new: false } + ); if (risupd) { await User.checkIfSbloccatiRequisiti(idapp, allData, rec.id); @@ -5855,23 +5987,20 @@ UserSchema.statics.mettiSognoePaypal = async function (idapp, modifica) { } return { num }; - }; UserSchema.statics.convSubAccount = async function (idapp) { const User = this; // Solo i Cancellati ! - arrusers = await User.find({ 'idapp': idapp, deleted: true }); + arrusers = await User.find({ idapp: idapp, deleted: true }); let num = 0; for (const rec of arrusers) { // Cerca il suo Principale! const trovato = await User.findOne({ idapp, 'profile.teleg_id': rec.profile.teleg_id, - $or: [ - { deleted: { $exists: false } }, - { deleted: { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); if (trovato) { num++; @@ -5897,15 +6026,13 @@ UserSchema.statics.DbOp = async function (idapp, mydata) { const User = this; try { if (mydata.dbop === 'changeCellInt') { - arrusers = await User.find({ 'idapp': idapp }); + arrusers = await User.find({ idapp: idapp }); let num = 0; for (const rec of arrusers) { // DISATTIVATO: ORA NON MI SERVE PIU if (false) { - let mycell = tools.removespaces( - rec.profile.intcode_cell + rec.profile.cell); - await User.findOneAndUpdate({ _id: rec._id }, - { $set: { 'profile.cell': mycell } }); + let mycell = tools.removespaces(rec.profile.intcode_cell + rec.profile.cell); + await User.findOneAndUpdate({ _id: rec._id }, { $set: { 'profile.cell': mycell } }); num++; } } @@ -5914,13 +6041,12 @@ UserSchema.statics.DbOp = async function (idapp, mydata) { // return User.updateMany({ idapp }, { $set: { 'profile.cell': { $concat: ["$profile.intcode_cell", "$profile.cell"] } } }) } else if (mydata.dbop === 'changeEmailLowerCase') { - arrusers = await User.find({ 'idapp': idapp }); + arrusers = await User.find({ idapp: idapp }); let num = 0; for (const rec of arrusers) { let myemail = rec.email.toLowerCase(); if (myemail !== rec.email) { - await User.findOneAndUpdate({ _id: rec._id }, - { $set: { 'email': myemail } }); + await User.findOneAndUpdate({ _id: rec._id }, { $set: { email: myemail } }); num++; } } @@ -5950,9 +6076,7 @@ UserSchema.statics.DbOp = async function (idapp, mydata) { } } catch (e) { console.error(e.message); - } - }; UserSchema.statics.getExtraInfoByUsername = async function (idapp, username) { @@ -5965,7 +6089,6 @@ UserSchema.statics.getExtraInfoByUsername = async function (idapp, username) { } return null; - }; UserSchema.statics.getProfilePerActivitiesByUsername = async function (idapp, username) { const User = this; @@ -5975,7 +6098,7 @@ UserSchema.statics.getProfilePerActivitiesByUsername = async function (idapp, us if (myuser) { return { mygroups: myuser.profile.mygroups, - mycircuits: myuser.profile.mycircuits + mycircuits: myuser.profile.mycircuits, }; } } catch (e) { @@ -5983,7 +6106,6 @@ UserSchema.statics.getProfilePerActivitiesByUsername = async function (idapp, us } return null; - }; UserSchema.statics.addExtraInfo = async function (idapp, recUser, version) { @@ -6009,14 +6131,14 @@ UserSchema.statics.addExtraInfo = async function (idapp, recUser, version) { circuitobj, useraccounts, calcstat, - calcOther + calcOther, ] = await Promise.all([ // Richiesta per gli amici a cui è stata mandata una richiesta User.find( { idapp, 'profile.req_friends': { $elemMatch: { username: recUser.username } }, - $or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }] + $or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }], }, { username: 1 } ).lean(), @@ -6025,8 +6147,8 @@ UserSchema.statics.addExtraInfo = async function (idapp, recUser, version) { MyGroup.find( { idapp, - 'req_users': { $elemMatch: { username: recUser.username } }, - $or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }] + req_users: { $elemMatch: { username: recUser.username } }, + $or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }], }, MyGroup.getWhatToShow_Unknown() ).lean(), @@ -6035,20 +6157,18 @@ UserSchema.statics.addExtraInfo = async function (idapp, recUser, version) { MyGroup.find( { idapp, - 'refused_users': { $elemMatch: { username: recUser.username } }, - $or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }] + refused_users: { $elemMatch: { username: recUser.username } }, + $or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }], }, MyGroup.getWhatToShow_Unknown() ).lean(), // Richiesta per i gruppi gestiti (admin) - MyGroup.find( - { - idapp, - 'admins': { $elemMatch: { username: recUser.username } }, - $or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }] - } - ).lean(), + MyGroup.find({ + idapp, + admins: { $elemMatch: { username: recUser.username } }, + $or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }], + }).lean(), // Reazioni Reaction.find({ idapp, username: recUser.username }).lean(), @@ -6066,14 +6186,14 @@ UserSchema.statics.addExtraInfo = async function (idapp, recUser, version) { User.calculateStat(idapp, recUser.username), // Altri calcoli per l'utente - User.calcOtherByUser(idapp, recUser._id) + User.calcOtherByUser(idapp, recUser._id), ]); // Per ogni gruppo gestito, recupera gli account in parallelo const manageGroupsWithAccounts = await Promise.all( listManageGroups.map(async (group) => { const myaccounts = await Account.getGroupAccounts(idapp, group.groupname); - return { ...group, account: (myaccounts && myaccounts.length > 0) ? myaccounts[0] : null }; + return { ...group, account: myaccounts && myaccounts.length > 0 ? myaccounts[0] : null }; }) ); @@ -6099,12 +6219,11 @@ addRecordReaction = async function (arr, fields, fieldtoset) { let newrecord = {}; try { - if (tools.isArray(arr)) { for (let myrec of arr) { if (myrec.id) { let myfields = { ...{ idrec: myrec.id }, ...fields }; - newrecord = await Reaction.findOne(myfields) + newrecord = await Reaction.findOne(myfields); if (!newrecord) { newrecord = new Reaction(myfields); @@ -6115,20 +6234,17 @@ addRecordReaction = async function (arr, fields, fieldtoset) { await newrecord.save(); - let newrecfound = await Reaction.findOne(myfields) + let newrecfound = await Reaction.findOne(myfields); } // if (newrecfound) // console.log('trovato') } } - } catch (e) { console.error(e.message); } - }; - UserSchema.statics.moverecordsFavorite = async function (tab) { const { MySkill } = require('../models/myskill'); const { MyGood } = require('../models/mygood'); @@ -6139,12 +6255,9 @@ UserSchema.statics.moverecordsFavorite = async function (tab) { let index = 0; try { - - let index = 0; let totali = 0; for (let user of arrusers) { - if (user.profile) { let arrfav = user.profile.favorite; let arrseen = user.profile.seen; @@ -6161,7 +6274,7 @@ UserSchema.statics.moverecordsFavorite = async function (tab) { idapp: user.idapp, userId: user._id, username: user.username, - tab + tab, }; await addRecordReaction(arrfav, fields, 'fav'); @@ -6169,17 +6282,13 @@ UserSchema.statics.moverecordsFavorite = async function (tab) { await addRecordReaction(arrbookmark, fields, 'book:'); await addRecordReaction(arrattend, fields, 'attend'); } - } - } - } catch (e) { console.error(e.message); } console.log('fine moverecordsFavorite'); - }; UserSchema.statics.removerecordsFavorite = async function () { @@ -6189,20 +6298,17 @@ UserSchema.statics.removerecordsFavorite = async function () { if (attivacanc) { const queryfind = { idapp: '13' }; await User.findOneAndUpdate(queryfind, { - $set: - { + $set: { 'profile.favorite': [], 'profile.bookmark': [], 'profile.attend': [], - 'profile.seen': [] + 'profile.seen': [], }, }); - } }; UserSchema.statics.updateVersion = async function (userversion, recUser) { - const { MySkill } = require('../models/myskill'); const { MyGood } = require('../models/mygood'); const { City } = require('../models/city'); @@ -6212,9 +6318,14 @@ UserSchema.statics.updateVersion = async function (userversion, recUser) { recUser.profile.notifs = shared_consts.DEFAULT_NOTIFS_USER; } - const recfavoriteNotif = recUser.profile.notifs.find((rec) => rec.dir === shared_consts.TypeNotifs.TYPEDIR_FAVORITE); + const recfavoriteNotif = recUser.profile.notifs.find( + (rec) => rec.dir === shared_consts.TypeNotifs.TYPEDIR_FAVORITE + ); if (!recfavoriteNotif) { - recUser.profile.notifs.push({ dir: shared_consts.TypeNotifs.TYPEDIR_FAVORITE, value: shared_consts.TypeNotifs.ID_FAVORITE_ADDED }) + recUser.profile.notifs.push({ + dir: shared_consts.TypeNotifs.TYPEDIR_FAVORITE, + value: shared_consts.TypeNotifs.ID_FAVORITE_ADDED, + }); } const recAttendNotif = recUser.profile.notifs.find((rec) => rec.dir === shared_consts.TypeNotifs.TYPEDIR_EVENTS); @@ -6227,7 +6338,6 @@ UserSchema.statics.updateVersion = async function (userversion, recUser) { if (recUser.profile.notifs[i].dir === shared_consts.TypeNotifs.TYPEDIR_EVENTS) recUser.profile.notifs[i].value = recAttendNotif.value; } - } // Imposta la provincia, se non l'ho messa, in base al bene o servizio che hai messo. @@ -6243,7 +6353,6 @@ UserSchema.statics.updateVersion = async function (userversion, recUser) { } } - if (resid_province) { await User.findOneAndUpdate({ _id: recUser._id }, { $set: { 'profile.resid_province': resid_province } }); } @@ -6262,14 +6371,12 @@ UserSchema.statics.updateVersion = async function (userversion, recUser) { } if (userversion < 1016) { - } return recUser; }; UserSchema.statics.calcOtherByUser = async function (idapp, userId) { - const { MySkill } = require('../models/myskill'); const { MyGood } = require('../models/mygood'); const { MyHosp } = require('../models/myhosp'); @@ -6285,7 +6392,6 @@ UserSchema.statics.calcOtherByUser = async function (idapp, userId) { return calc; }; - UserSchema.statics.tooManyReqPassword = async function (idapp, email, set) { const User = this; @@ -6293,8 +6399,7 @@ UserSchema.statics.tooManyReqPassword = async function (idapp, email, set) { const user = await User.findByEmail(idapp, email); if (user) { - if (!user.retry_pwd) - user.retry_pwd = 0 + if (!user.retry_pwd) user.retry_pwd = 0; if (set && user.retry_pwd <= maxnum) { user.retry_pwd++; @@ -6302,7 +6407,6 @@ UserSchema.statics.tooManyReqPassword = async function (idapp, email, set) { } return user.retry_pwd > maxnum; } - }; UserSchema.statics.tooManyLoginWrong = async function (idapp, username, set) { const User = this; @@ -6311,8 +6415,7 @@ UserSchema.statics.tooManyLoginWrong = async function (idapp, username, set) { const user = await User.findByUsername(idapp, username, true, false); if (user) { - if (!user.retry_pwd) - user.retry_pwd = 0 + if (!user.retry_pwd) user.retry_pwd = 0; if (set && user.retry_pwd <= maxnum) { user.retry_pwd++; @@ -6325,36 +6428,44 @@ UserSchema.statics.tooManyLoginWrong = async function (idapp, username, set) { }; UserSchema.statics.setLastCircuitOpened = async function (idapp, username, circuitpath) { - try { return await User.findOneAndUpdate({ idapp, username }, { $set: { 'profile.last_circuitpath': circuitpath } }); } catch (e) { return false; } - }; UserSchema.statics.setReceiveRis = async function (idapp, username) { const User = this; - return await User.findOneAndUpdate({ - idapp, username, - }, - { $set: { 'profile.lastdate_reqRis': new Date() } }, { new: false }).lean().then((record) => { + return await User.findOneAndUpdate( + { + idapp, + username, + }, + { $set: { 'profile.lastdate_reqRis': new Date() } }, + { new: false } + ) + .lean() + .then((record) => { return !!record; }); - }; UserSchema.statics.setLinkReg = async function (idapp, username) { const User = this; - return await User.findOneAndUpdate({ - idapp, username, - }, - { $set: { 'profile.lastdate_LinkReg': new Date() } }, { new: false }).lean().then((record) => { + return await User.findOneAndUpdate( + { + idapp, + username, + }, + { $set: { 'profile.lastdate_LinkReg': new Date() } }, + { new: false } + ) + .lean() + .then((record) => { return !!record; }); - }; UserSchema.statics.addNewSite = async function (idappPass, body) { @@ -6374,13 +6485,12 @@ UserSchema.statics.addNewSite = async function (idappPass, body) { // cerca un IdApp Libero let idapp = await Site.generateNewSite_IdApp(idappPass, body, true); - if (idapp) { let arrSite = await Site.find({ idapp }).lean(); let numutenti = 0; if (idapp) { numutenti = await User.countDocuments({ idapp }); - }; + } if (arrSite && arrSite.length === 1 && numutenti < 2) { const MyTelegramBot = require('../telegram/telegrambot'); @@ -6423,17 +6533,18 @@ UserSchema.statics.addNewSite = async function (idappPass, body) { } catch (e) { console.error('Error in addNewSite:', e.message); } - }; UserSchema.statics.renameCircuitName = async function (idapp, oldcircuitname, newcircuitname) { const User = this; - return await User.updateMany({ idapp, 'profile.mycircuits.circuitname': oldcircuitname }, { $set: { 'profile.mycircuits.$.circuitname': newcircuitname } }); + return await User.updateMany( + { idapp, 'profile.mycircuits.circuitname': oldcircuitname }, + { $set: { 'profile.mycircuits.$.circuitname': newcircuitname } } + ); }; UserSchema.statics.getnumAnnunci = async function (idapp) { - const { MySkill } = require('../models/myskill'); const { MyGood } = require('../models/mygood'); const { MyBacheca } = require('../models/mybacheca'); @@ -6442,18 +6553,13 @@ UserSchema.statics.getnumAnnunci = async function (idapp) { let num = 0; try { - num += await MySkill.countDocuments({ idapp }); num += await MyGood.countDocuments({ idapp }); num += await MyBacheca.countDocuments({ idapp }); num += await MyHosp.countDocuments({ idapp }); - - } catch (e) { - - } + } catch (e) {} return num; - }; // crea una funzione per aggiornare il lasttimeonline e useragent @@ -6468,14 +6574,14 @@ UserSchema.statics.updateLastTimeAndUserAgent = async function (id, useragent) { $set: { lasttimeonline: new Date(), useragent, - retry_pwd: 0 + retry_pwd: 0, }, }, - { returnDocument: "after" } + { returnDocument: 'after' } ).lean(); return ris; -} +}; UserSchema.statics.getMyGroupsById = async function (id) { const User = this; @@ -6512,10 +6618,8 @@ UserSchema.statics.createNewSubRecord = async function (idapp, req) { return rec; }; - const User = mongoose.model('User', UserSchema); - class Hero { constructor(name, level) { this.name = name; @@ -6530,7 +6634,6 @@ class Hero { const FuncUsers = { createRegistration_withTelegram(userdata) { - const telegrambot = require('../telegram/telegrambot'); try { @@ -6541,33 +6644,40 @@ const FuncUsers = { user.lasttimeonline = new Date(); user.date_reg = new Date(); - return user.save().then(async () => { - return User.findByUsername(user.idapp, user.username, false). - then(async (usertrovato) => { - + return user + .save() + .then(async () => { + return User.findByUsername(user.idapp, user.username, false).then(async (usertrovato) => { const numutenti = await User.getNumUsers(user.idapp); let msg = '++ Nuovo Entrato: [' + numutenti + '] ' + user.username + ' ' + user.name + ' ' + user.surname; await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg); - return telegrambot.askConfirmationUser(user.idapp, shared_consts.CallFunz.REGISTRATION, user, '', '', '', ''); + return telegrambot.askConfirmationUser( + user.idapp, + shared_consts.CallFunz.REGISTRATION, + user, + '', + '', + '', + '' + ); }); - }).catch((e) => { - console.error(e.message); - }); - + }) + .catch((e) => { + console.error(e.message); + }); } catch (e) { console.error(e.message); } - - } + }, }; UserSchema.index({ 'tokens.token': 1, 'tokens.access': 1 }); module.exports = { - User, Hero, FuncUsers + User, + Hero, + FuncUsers, }; - - diff --git a/src/server/modules/GenPdf.js b/src/server/modules/GenPdf.js index 3838982..ca8b1c7 100644 --- a/src/server/modules/GenPdf.js +++ b/src/server/modules/GenPdf.js @@ -86,6 +86,7 @@ class GenPdf { try { console.log(`caricamento pagina: ${url}`); await page.goto(url, { waitUntil: 'networkidle0' }); + await page.waitForNavigation({ waitUntil: 'networkidle0' }).catch(() => {}); page.on('console', (msg) => { if (msg.type() === 'error') { @@ -93,7 +94,7 @@ class GenPdf { } }); - await tools.attendiNSecondi(8); + await tools.attendiNSecondi(6); let success = false; let numTentativi1 = 0; while (numTentativi1 < maxTentativi) { diff --git a/src/server/router/admin_router.js b/src/server/router/admin_router.js index a4abd4b..82386cf 100755 --- a/src/server/router/admin_router.js +++ b/src/server/router/admin_router.js @@ -239,13 +239,13 @@ async function compressPdfWithPs2Pdf(inputFile, outputFile, compression = 'ebook // DIAGNOSI COMPLETA DEL PROBLEMA async function diagnosePDFProblem() { console.log('=== DIAGNOSI COMPLETA SISTEMA ==='); - + // 1. Test ambiente Node.js console.log('Node.js version:', process.version); console.log('Platform:', process.platform); console.log('Architecture:', process.arch); console.log('Current working directory:', process.cwd()); - + // 2. Test moduli disponibili try { console.log('Testing gs module...'); @@ -253,12 +253,12 @@ async function diagnosePDFProblem() { } catch (error) { console.log('gs module error:', error.message); } - + // 3. Test comando di sistema const { exec } = require('child_process'); const util = require('util'); const execAsync = util.promisify(exec); - + try { console.log('Testing gs command from system...'); const { stdout, stderr } = await execAsync('gs -version'); @@ -267,12 +267,12 @@ async function diagnosePDFProblem() { } catch (error) { console.log('System gs command failed:', error.message); } - + // 4. Test scrittura file const fs = require('fs').promises; const path = require('path'); const testFile = path.join(process.cwd(), 'test_write.txt'); - + try { await fs.writeFile(testFile, 'test content'); console.log('File write test: SUCCESS'); @@ -282,19 +282,18 @@ async function diagnosePDFProblem() { } } - // ALTERNATIVA 1: Usando child_process direttamente async function convertPDF_ChildProcess(inputFile, outputFile, width, height, compressionLevel = 'screen') { const { spawn } = require('child_process'); const path = require('path'); - + console.log('=== CONVERSIONE CON CHILD_PROCESS E COMPRESSIONE ==='); - + // Verifica input if (!(await tools.isFileExistsAsync(inputFile))) { throw new Error(`File input non trovato: ${inputFile}`); } - + // Assicurati che la directory output esista const outputDir = path.dirname(outputFile); const fs = require('fs').promises; @@ -303,44 +302,40 @@ async function convertPDF_ChildProcess(inputFile, outputFile, width, height, com } catch (error) { // Directory già esistente, ok } - + // const widthPt = Math.round(width * 28.34646); // const heightPt = Math.round(height * 28.34646); - const widthPt = Math.round(width * 28.34646* 10); + const widthPt = Math.round(width * 28.34646 * 10); const heightPt = Math.round(height * 28.34646 * 10); - + // Parametri di compressione ottimizzati const compressionSettings = { - 'maximum': [ + maximum: [ '-dPDFSETTINGS=/screen', '-dDownsampleColorImages=true', '-dColorImageResolution=72', - '-dDownsampleGrayImages=true', + '-dDownsampleGrayImages=true', '-dGrayImageResolution=72', '-dDownsampleMonoImages=true', - '-dMonoImageResolution=72' + '-dMonoImageResolution=72', ], - 'high': [ + high: [ '-dPDFSETTINGS=/ebook', '-dDownsampleColorImages=true', '-dColorImageResolution=150', '-dDownsampleGrayImages=true', - '-dGrayImageResolution=150' + '-dGrayImageResolution=150', ], - 'printer': [ - '-dPDFSETTINGS=/printer', - '-dDownsampleColorImages=true', - '-dColorImageResolution=300' - ], - 'screen': [ + printer: ['-dPDFSETTINGS=/printer', '-dDownsampleColorImages=true', '-dColorImageResolution=300'], + screen: [ '-dPDFSETTINGS=/screen', '-dDownsampleColorImages=true', '-dColorImageResolution=96', '-dDownsampleGrayImages=true', - '-dGrayImageResolution=96' - ] + '-dGrayImageResolution=96', + ], }; - + return new Promise((resolve, reject) => { const args = [ '-sDEVICE=pdfwrite', @@ -349,52 +344,53 @@ async function convertPDF_ChildProcess(inputFile, outputFile, width, height, com '-dQUIET', '-dBATCH', '-dSAFER', - + // Parametri di compressione - ...compressionSettings[compressionLevel] || compressionSettings['screen'], + ...(compressionSettings[compressionLevel] || compressionSettings['screen']), '-dCompressFonts=true', '-dSubsetFonts=true', '-dColorImageFilter=/DCTEncode', '-dGrayImageFilter=/DCTEncode', '-dEmbedAllFonts=true', - + // Dimensioni pagina `-g${widthPt}x${heightPt}`, '-dFIXEDMEDIA', // '-dPDFFitPage', - + // Output `-sOutputFile=${outputFile}`, - inputFile + inputFile, ]; - + console.log('Spawning gs with compression args:', args.join(' ')); - + const gsProcess = spawn('gs', args, { stdio: ['ignore', 'pipe', 'pipe'], - shell: process.platform === 'win32' + shell: process.platform === 'win32', }); - + let stdout = ''; let stderr = ''; - + gsProcess.stdout.on('data', (data) => { stdout += data.toString(); - if (stdout.length < 1000) { // Evita log troppo lunghi + if (stdout.length < 1000) { + // Evita log troppo lunghi console.log('GS OUT:', data.toString().trim()); } }); - + gsProcess.stderr.on('data', (data) => { stderr += data.toString(); if (stderr.length < 1000) { console.log('GS ERR:', data.toString().trim()); } }); - + gsProcess.on('close', async (code) => { console.log(`GS process closed with code: ${code}`); - + if (code === 0) { // Attendi e verifica setTimeout(async () => { @@ -405,8 +401,8 @@ async function convertPDF_ChildProcess(inputFile, outputFile, width, height, com try { const originalStats = await tools.getFileStatsAsync(inputFile); const newStats = await tools.getFileStatsAsync(outputFile); - const compressionRatio = ((originalStats.size - newStats.size) / originalStats.size * 100).toFixed(1); - + const compressionRatio = (((originalStats.size - newStats.size) / originalStats.size) * 100).toFixed(1); + console.log(`📁 File originale: ${(originalStats.size / 1024 / 1024).toFixed(2)} MB`); console.log(`📁 File compresso: ${(newStats.size / 1024 / 1024).toFixed(2)} MB`); console.log(`🗜️ Compressione: ${compressionRatio}%`); @@ -414,7 +410,7 @@ async function convertPDF_ChildProcess(inputFile, outputFile, width, height, com } catch (statsError) { console.log('Warning: impossibile calcolare statistiche compressione'); } - + resolve(outputFile); } else { console.log('❌ FAIL: File non generato nonostante exit code 0'); @@ -428,7 +424,7 @@ async function convertPDF_ChildProcess(inputFile, outputFile, width, height, com reject(new Error(`Ghostscript failed with code ${code}: ${stderr}`)); } }); - + gsProcess.on('error', (error) => { console.log('GS process error:', error); reject(new Error(`Failed to start Ghostscript: ${error.message}`)); @@ -631,6 +627,7 @@ router.post('/online-pdf', authenticate, async (req, res) => { try { let myrec = null; + // Aggiorna il PDF OnLine, copiando il file da Generato a OnLine if (id_catalog) { myrec = await Catalog.findOne({ _id: id_catalog }); @@ -645,7 +642,7 @@ router.post('/online-pdf', authenticate, async (req, res) => { if (stampa) { myrec.pdf_online_stampa = myrec.pdf_generato_stampa.replace('_generato', ''); } else { - myrec.pdf_online = myrec.pdf_generato.replace('_generato', ''); + myrec.pdf_online = myrec.pdf_generato?.replace('_generato', ''); } // Aggiorna il PDF OnLine, copiando il file da Generato a OnLine @@ -699,17 +696,20 @@ async function JoinPDFCatalogs(cataloghi, options, outputFile, stampa) { for (let id_catalog of cataloghi) { let catalog = await Catalog.findOne({ _id: id_catalog }); if (catalog) { - let filename = stampa ? catalog.pdf_generato_stampa : catalog.pdf_generato; + let filename = stampa ? catalog.pdf_online_stampa : catalog.pdf_online; if (filename) { - const pdfBytes = await fs.promises.readFile(options.mydir + filename); - const pdf = await PDFDocument.load(pdfBytes); - const pages = pdf.getPages(); - const copiedPages = await pdfDoc.copyPages( - pdf, - pages.map((p, i) => i) - ); - for (let page of copiedPages) { - pdfDoc.addPage(page); + let myfile = tools.fixFilePath(options.mydir + '/' + filename); + if (await tools.isFileExistsAsync(myfile)) { + const pdfBytes = await fs.promises.readFile(myfile); + const pdf = await PDFDocument.load(pdfBytes); + const pages = pdf.getPages(); + const copiedPages = await pdfDoc.copyPages( + pdf, + pages.map((p, i) => i) + ); + for (let page of copiedPages) { + pdfDoc.addPage(page); + } } } else { console.log('ATTENZIONE! Catalogo non ancora Generato ! ', catalog.title); @@ -725,6 +725,12 @@ async function JoinPDFCatalogs(cataloghi, options, outputFile, stampa) { const outputFilename = path.basename(outputFile); const outputPath = path.join(options.dir_out, outputFilename); + if (await tools.isFileExistsAsync(outputFile)) { + console.log('✅ Catalogo Completo Generato correttamente ! ', outputFile); + } else { + console.log('❌ Catalogo non generato ! ', outputFile); + } + const ris = { outputPath, }; @@ -746,7 +752,8 @@ router.post('/join-pdf', authenticate, async (req, res) => { options.mydir = tools.getdirByIdApp(idapp); try { - const full_dir_out = tools.getdirByIdApp(options.idapp) + '/' + options.dir_out; + const mydirpath = tools.getdirByIdApp(options.idapp); + const full_dir_out = tools.fixFilePath(path.join(mydirpath, options.dir_out)); await fs.promises.mkdir(full_dir_out, { recursive: true }); // Aggiorna il PDF OnLine, copiando il file da Generato a OnLine @@ -767,13 +774,16 @@ router.post('/join-pdf', authenticate, async (req, res) => { const ris_stampa = await JoinPDFCatalogs(cataloghi, options, outputFileStampa, true); if (ris_stampa) { raccolta.pdf_generato_stampa = ris_stampa.outputPath; + let myfilecheckstampa = path.join(mydirpath, ris_stampa.outputPath); + raccolta.pdf_generato_stampa_size = await tools.getSizeFile(myfilecheckstampa); } } else { // Creazione file per WEB const ris = await JoinPDFCatalogs(cataloghi, options, outputFile, false); if (ris) { raccolta.pdf_generato = ris.outputPath; - raccolta.pdf_generato_size = await tools.getSizeFile(ris.outputPath); + let myfilecheck = path.join(mydirpath, ris.outputPath); + raccolta.pdf_generato_size = await tools.getSizeFile(myfilecheck); } } @@ -2663,5 +2673,4 @@ router.post('/generate-pdf', async (req, res) => { } }); - module.exports = router; diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 2bd9579..7cf0531 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -1173,7 +1173,7 @@ router.post('/dbop', authenticate, async (req, res) => { idapp = req.body.idapp; locale = req.body.locale; - if (!User.isAdmin(req.user.perm)) { + if (!User.isCollaboratore(req.user.perm)) { return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED }); } diff --git a/src/server/tools/general.js b/src/server/tools/general.js index fa01537..246f687 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -6186,5 +6186,9 @@ module.exports = { async attendiNSecondi(numsec) { await new Promise(resolve => setTimeout(resolve, numsec * 1000)); - } + }, + + fixFilePath(myfilepath) { + return myfilepath.replace(/\\/g, '/'); + }, };