From 9c7cf28a4a2c45bcd9627a8103bfe8556595f890 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Sun, 10 May 2020 21:07:51 +0200 Subject: [PATCH 01/14] SubAccounts --- docs/email.md | 7 + docs/note.txt | 1 + docs/passi.txt | 54 +++ src/server/models/extralist.js | 77 ++-- src/server/models/listaingresso.js | 539 ++++++++++++++++++++++++--- src/server/models/nave.js | 378 ++++++++++++------- src/server/models/navepersistente.js | 26 +- src/server/models/project.js | 2 - src/server/models/user.js | 482 +++++++++++++----------- src/server/router/api/actions.js | 2 +- src/server/router/index_router.js | 105 ++++-- src/server/router/site_router.js | 4 +- src/server/router/users_router.js | 81 +++- src/server/sendemail.js | 2 +- src/server/telegram/telegrambot.js | 117 ++++-- src/server/tools/general.js | 155 +++++++- src/server/tools/shared_nodejs.js | 2 +- 17 files changed, 1535 insertions(+), 499 deletions(-) create mode 100644 docs/note.txt create mode 100644 docs/passi.txt diff --git a/docs/email.md b/docs/email.md index 33c3101..a21ca4f 100755 --- a/docs/email.md +++ b/docs/email.md @@ -11,3 +11,10 @@ EMOJI:
https://listemoji.com/symbols-emoji + + +Copy Database: + +db.copyDatabase('FreePlanet', 'test_FreePlanet') + + diff --git a/docs/note.txt b/docs/note.txt new file mode 100644 index 0000000..dbea10b --- /dev/null +++ b/docs/note.txt @@ -0,0 +1 @@ +TiziCaso 6 IDTELEG 989199479 diff --git a/docs/passi.txt b/docs/passi.txt new file mode 100644 index 0000000..db45952 --- /dev/null +++ b/docs/passi.txt @@ -0,0 +1,54 @@ +AGGIORNARE: +------------ + +// ++Todo: DA FARE: + +TESTARE -> inviare il msg anche al Sognatore della Gift Chat +- Aggiornare il titolo della Gift Chat (da 5/5 a 12/5) +- Aggiornare il testo sulla Placca (Data Inizio e Data Fine Doni) + + +// ++Todo: TOGLIERE! + +- AGGIONARE AMBIENTE DI TEST +- ESEGUIRE LA CONVERSIONE 1 E 2 ! + +- CHECK getProssimiInLista +X - CONTROLLARE arrIdTelegramUsers + +- TESTARE SOSTITUISCI UTENTE DA NAVE + +- TESTARE AGGIUNGI VIAGGIO + +- Accorpare tutti i sotto account, in 1 unico ! + - Nel campo note, metterci l'username vecchio. + + - Sistemare le navi con num_tess === 4 : indorder=0 e 46 : + Prendere quelli del num_tess === 3 e SOSTITUISCI ind_order del num_Tess = 4 con ind_order di num_tess = 3 + +------------- +- AGGIONARE AMBIENTE DI PRODUZIONE +- ESEGUIRE LA CONVERSIONE 1 E 2 ! + + - Sistemare le navi con num_tess === 4 : indorder=0 e 46 : + Prendere quelli del num_tess === 3 e SOSTITUISCI ind_order del num_Tess = 4 con ind_order di num_tess = 3 + +------------- + + +SOSTITUISCI: + - Mettere flag se si vuole spostare l'Utente oppure Aggiungerlo... + + +- Sistemare che in Edit Pagina, se è troppo grande, va oltre l'altezza della finestra. + +- Aggiornare le FAQ in lingua +- Attivare le Traduttrici alle Pagine + + +- CONTROLLARE CON ARGENTINA E PORTOGALLO e Brasile: + Il sito deve comparire in Spagnolo e in Portoghese + + +TRADURRE: +'Giorno in cui Inviare il DONO': 'Hai 4 giorni di tempo per inviare il tuo dono. Giorno di Chiusura:', diff --git a/src/server/models/extralist.js b/src/server/models/extralist.js index 6b6d924..6c20e72 100755 --- a/src/server/models/extralist.js +++ b/src/server/models/extralist.js @@ -170,46 +170,47 @@ ExtraListSchema.statics.getUsersList = function (idapp) { }; -ExtraListSchema.statics.getDownlineNotRegisteredByNameSurname = function (idapp, nameandsurname) { - const ExtraList = this; - - return ExtraList.find({ - 'aportador_solidario_name_surname': nameandsurname, - registered: false, - }, { - ind_order: 1, - name: 1, - surname: 1, - cell_complete: 1, - num_invitati: 1, - nationality: 1, - }, (err, arrrec) => { - return arrrec - }); -}; - -ExtraListSchema.statics.getUserNotRegisteredByNameSurname = function (idapp, nameandsurname) { - const ExtraList = this; - - return ExtraList.findOne({ - name_complete: nameandsurname, - registered: false, - }, { - lang: 1, - ind_order: 1, - name: 1, - surname: 1, - cell_complete: 1, - num_invitati: 1, - nationality: 1, - }, (err, arrrec) => { - return arrrec - }); -}; +// ExtraListSchema.statics.getDownlineNotRegisteredByNameSurname = function (idapp, nameandsurname) { +// const ExtraList = this; +// +// return ExtraList.find({ +// 'aportador_solidario_name_surname': nameandsurname, +// registered: false, +// }, { +// ind_order: 1, +// name: 1, +// surname: 1, +// cell_complete: 1, +// num_invitati: 1, +// nationality: 1, +// }, (err, arrrec) => { +// return arrrec +// }); +// }; +// ExtraListSchema.statics.getUserNotRegisteredByNameSurname = function (idapp, nameandsurname) { +// const ExtraList = this; +// +// return ExtraList.findOne({ +// name_complete: nameandsurname, +// registered: false, +// }, { +// lang: 1, +// ind_order: 1, +// name: 1, +// surname: 1, +// cell_complete: 1, +// num_invitati: 1, +// nationality: 1, +// }, (err, arrrec) => { +// return arrrec +// }); +// }; +// ExtraListSchema.statics.getFieldsForSearch = function () { - return [{ field: 'username', type: tools.FieldType.string }, + return [ + { field: 'username', type: tools.FieldType.string }, { field: 'name', type: tools.FieldType.string }, { field: 'surname', type: tools.FieldType.string }, { field: 'cell_complete', type: tools.FieldType.string }, @@ -239,6 +240,7 @@ ExtraListSchema.statics.DuplicateAllRecords = async function (idapporig, idappde }; +/* ExtraListSchema.statics.ImportData = async function (locale, idapp, strdata) { const ExtraList = this; @@ -325,6 +327,7 @@ ExtraListSchema.statics.ImportData = async function (locale, idapp, strdata) { console.err(e); } }; +*/ const ExtraList = mongoose.model('ExtraList', ExtraListSchema); diff --git a/src/server/models/listaingresso.js b/src/server/models/listaingresso.js index 8705bdb..e6d9d61 100755 --- a/src/server/models/listaingresso.js +++ b/src/server/models/listaingresso.js @@ -10,7 +10,6 @@ const { ObjectID } = require('mongodb'); const { Nave } = require('./nave'); - const shared_consts = require('../tools/shared_nodejs'); const queryclass = require('../classes/queryclass'); @@ -29,9 +28,18 @@ const ListaIngressoSchema = new mongoose.Schema({ type: String, required: true, }, + username: { + type: String, + }, ind_order: { type: Number, }, + index: { + type: Number, + }, + invitante_username: { + type: String, + }, date_added: { type: Date, }, @@ -42,6 +50,9 @@ const ListaIngressoSchema = new mongoose.Schema({ num_tess: { type: Number, }, + note: { + type: String, + }, deleted: { type: Boolean, default: false, @@ -49,6 +60,27 @@ const ListaIngressoSchema = new mongoose.Schema({ }); +ListaIngressoSchema.pre('save', async function (next) { + if (this.isNew) { + try { + if (!this.ind_order) { + const myrec = await ListaIngresso.findOne({ idapp: this.idapp }).limit(1).sort({ ind_order: -1 }); + + if (!!myrec) { + this.ind_order = myrec._doc.ind_order + 1; + } else { + this.ind_order = 1; + } + } + } catch (e) { + this.ind_order = 2; + } + } + + next(); +}); + + // ListaIngressoSchema.methods.toJSON = function () { // const ListaIngresso = this; // const userObject = ListaIngresso.toObject(); @@ -86,13 +118,27 @@ ListaIngressoSchema.statics.findByIndOrder = function (idapp, ind_order) { } }; -ListaIngressoSchema.statics.findByIndOrderETess = function (idapp, ind_order, num_tess) { +ListaIngressoSchema.statics.findByAllRecByUsername = function (idapp, username) { const ListaIngresso = this; try { - return ListaIngresso.findOne({ - 'idapp': idapp, - 'ind_order': ind_order, + return ListaIngresso.find({ + idapp, + username, + deleted: false + }); + } catch (e) { + + } +}; + +ListaIngressoSchema.statics.findByUsernameETess = async function (idapp, username, num_tess) { + const ListaIngresso = this; + + try { + return await ListaIngresso.findOne({ + idapp, + username, num_tess, }); } catch (e) { @@ -100,67 +146,87 @@ ListaIngressoSchema.statics.findByIndOrderETess = function (idapp, ind_order, nu } }; -ListaIngressoSchema.statics.findAllByIndOrder = function (idapp, ind_order) { +ListaIngressoSchema.statics.findAllByUsername = function (idapp, username) { const ListaIngresso = this; try { return ListaIngresso.find({ 'idapp': idapp, - 'ind_order': ind_order, - added: false, + username, + added: false, // NON QUELLI GIA INSERITI ! $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); } catch (e) { - + console.error(e.message); } }; -ListaIngressoSchema.statics.deleteUserInListaIngresso = async function (idapp, ind_order) { +ListaIngressoSchema.statics.deleteUserInListaIngresso = async function (idapp, username) { const ListaIngresso = this; - return ListaIngresso.findOneAndUpdate({ + return ListaIngresso.updateMany({ idapp, - ind_order, + username, }, { $set: { deleted: true } }, { new: false }) }; -ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, ind_order, lang, addednowreal, num_tess) { +ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, username, invitante_username, lang, addednowreal, nuovo, dateins, note, added) { const ListaIngresso = this; const { User } = require('./user'); const telegrambot = require('../telegram/telegrambot'); try { - let listaingresso = await ListaIngresso.findByIndOrderETess(idapp, ind_order, num_tess); + let listaingresso = null; + if (!nuovo) { + listaingresso = await ListaIngresso.findByUsernameETess(idapp, username, 1); + } if (!listaingresso) { listaingresso = new ListaIngresso({ - ind_order: ind_order, + _id: new ObjectID(), idapp, - num_tess, + username, + num_tess: 1, date_added: new Date(), - _id: new ObjectID() + invitante_username, }); + if (!!note) { + listaingresso.note = note; + } + if (!!added) { + listaingresso.added = added; + } + + if (!!dateins) { + try { + listaingresso.date_added = dateins; + } catch (e) { + listaingresso.date_added = new Date(); + } + } + if (listaingresso) { - return await listaingresso.save().then(async (ris) => { - if (addednowreal) { - if (!!ris) { - const username = await User.getUsernameByIndOrder(idapp, ind_order); - msgtext = '🔵 ' + username + ' ' + tools.gettranslate('ADDED_TOLISTAINGRESSO', lang); - await telegrambot.sendMsgTelegram(idapp, username, msgtext, true); // Anche a STAFF - } + const ris = await listaingresso.save(); + if (addednowreal) { + if (!!ris) { + const nome = await User.getNameSurnameByUsername(idapp, username); + msgtext = '🔵 ' + nome + ' (' + username + ') ' + tools.gettranslate('ADDED_TOLISTAINGRESSO', lang); + await telegrambot.sendMsgTelegram(idapp, username, msgtext, true); // Anche a STAFF } - return ris; - }); + } + return ris; } } - const giapresente = await Nave.findOne({ idapp, ind_order, num_tess }); + const giapresente = await + Nave.findOne({ idapp, ind_order, num_tess: 1 }); if (!!giapresente) { // Era stato già aggiunto! let fields_to_update = { added: true }; - await ListaIngresso.findOneAndUpdate({ _id: listaingresso._id }, { $set: fields_to_update }, { new: false }); + await + ListaIngresso.findOneAndUpdate({ _id: listaingresso._id }, { $set: fields_to_update }, { new: false }); return false; } @@ -171,44 +237,69 @@ ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, ind_ console.error(e.message); } return null; -}; +} +; -function getQueryProj(myfilter, myobjField, myfilter2) { +function getQueryProj(myfilter, myobjField, myfilter2, mygroup) { const query = [ { $match: myfilter }, { $lookup: { from: "users", - localField: "ind_order", - foreignField: "ind_order", // field in the user collection - as: "user" + as: "user", + let: { username: '$username' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$username', '$$username'] }, + { $eq: ['$idapp', myfilter.idapp] }, + ] + } + } + } + ] } }, { $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] }, "$$ROOT"] } } }, { $match: myfilter2 }, - { $project: myobjField } ]; + if (!!mygroup) { + query.push( + { $group: mygroup } + ); + } + + if (!!myobjField) { + query.push( + { $project: myobjField } + ); + } + return query; } -ListaIngressoSchema.statics.getPosizioneInLista = async function (idapp, ind_order, num_tess) { +ListaIngressoSchema.statics.getPosizioneInLista = async function (idapp, arrrec, ind_order, num_tess) { - arrrec = await ListaIngresso.getProssimiInLista(idapp, true); let posiz = 0; let totposiz = arrrec.length; + let numNaviEntrato = 0; for (let ind = 0; ind < arrrec.length; ind++) { if (arrrec[ind].ind_order === ind_order && arrrec[ind].num_tess === num_tess) { posiz = ind; + numNaviEntrato = arrrec[ind].numNaviEntrato; + break; } } - return { posiz: posiz + 1, totposiz, num_tess } + return { posiz: posiz + 1, totposiz, num_tess, numNaviEntrato } }; @@ -220,7 +311,8 @@ ListaIngressoSchema.statics.showListaOrd = async function (idapp, solonuovi) { let mystr = ''; let conta = 1; for (const rec of arrrec) { - mystr += '[' + conta + '] ' + rec.ind_order + ' [' + rec.numinvitatiattivi + '] - [' + rec.numinvitati + '] (' + rec.ind_order + ') ' + rec.name + ' ' + rec.surname; + mystr += conta + ' - ' + ' [' + rec.numinvitatiattivi + '] - [' + rec.numinvitati + '] (' + rec.ind_order + ') ' + rec.username + ' ' + rec.name + ' ' + rec.surname; + mystr += ' inv = ' + rec.invitante_username; mystr += ' num_tess = ' + rec.num_tess; if (rec.added) mystr += ' (ADDED ++)'; @@ -234,7 +326,11 @@ ListaIngressoSchema.statics.showListaOrd = async function (idapp, solonuovi) { ListaIngressoSchema.statics.getFieldsForSearch = function () { - return [{field: 'ind_order', type: tools.FieldType.number }] + return [ + { field: 'ind_order', type: tools.FieldType.number }, + { field: 'username', type: tools.FieldType.string }, + { field: 'invitante_username', type: tools.FieldType.string }, + ] }; ListaIngressoSchema.statics.executeQueryTable = function (idapp, params) { @@ -269,6 +365,7 @@ ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuov name: 1, surname: 1, username: 1, + invitante_username: 1, email: 1, lang: 1, num_tess: 1, @@ -278,7 +375,7 @@ ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuov }; let myfilter2 = { - username: { $exists: true }, + surname: { $exists: true }, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }; @@ -297,19 +394,36 @@ ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuov }, myobjField, myfilter2); } - arrrec = await ListaIngresso.aggregate(myquery).sort({ ind_order: 1 }) + // await ListaIngresso.aggiornaIndex(); + + arrrec = await ListaIngresso.aggregate(myquery).sort({ date_added: 1 }) .then(async (arrlista) => { const { User } = require('../models/user'); - for (const rec of arrlista) { - rec.numinvitati = await User.getnumInvitati(idapp, rec.username); - rec.numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, rec.username); + const arrindex = {}; - if (rec.num_tess > 2) { - rec.numinvitati = rec.numinvitati - (rec.num_tess - 1); - rec.numinvitatiattivi = rec.numinvitatiattivi - (rec.num_tess - 1); + for (const rec of arrlista) { + + // ++Todo: TOGLIERE! + if (false) { + rec.numNaviEntrato = await Nave.getnumNaviByUsername(idapp, rec.username); + + rec.numinvitati = await ListaIngresso.getnumInvitati(idapp, rec.username); + rec.numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, rec.username); } + + const arrListaIngrUser = arrindex[rec.username]; + if (!arrListaIngrUser) { + arrindex[rec.username] = 1 + rec.numNaviEntrato; + } else { + arrindex[rec.username] += 1; // incrementa + } + + // if (rec.num_tess > 2) { + rec.numinvitati = rec.numinvitati - (arrindex[rec.username] - 1) * 2; + rec.numinvitatiattivi = rec.numinvitatiattivi - (arrindex[rec.username] - 1) * 2; + // } if (rec.numinvitati < 0) { rec.numinvitati = 0; } @@ -335,6 +449,337 @@ ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuov return arrrec; }; +ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { + const ListaIngresso = this; + + const { User } = require('./user'); + + try { + if (true) { + // Elimina TUTTI i Cancellati (ma non Sospesi) + await User.remove({ + idapp, + $and: [ + { deleted: { $exists: true, $eq: true } }, // cancellati + { $or: [{ sospeso: { $exists: false } }, { sospeso: { $exists: true, $eq: false } }] }, // ma non sospeso + ] + }); + + + // Comprende anche i sospesi + const arrusers = await User.find({ + idapp, + }); + + // Ricalcola il Campo Index + await User.ricalcolaIndex(idapp); + + // Ricrea i record ListaIngresso (num_tess = 1), per ogni User + for (const user of arrusers) { + if (user.ind_order >= 0) { + let ingr = new ListaIngresso(); + ingr._id = new ObjectID(); + ingr.idapp = idapp; + ingr.ind_order = user.ind_order; + ingr.username = user.username; + ingr.invitante_username = user.aportador_solidario; + ingr.num_tess = 1; + // ingr.date_added = user.date_reg; + ingr.added = false; + const listaingr = await ListaIngresso.find({ idapp, ind_order: ingr.ind_order, num_tess: 1 }); + + const trovatanave = await Nave.findOne({ idapp, ind_order: ingr.ind_order, num_tess: 1 }) + .then((mynave) => { + if (!!mynave) { + ingr.date_added = mynave.created; + ingr.added = true; + } + return !!mynave; + }); + + if (listaingr.length === 0) { + if (trovatanave) + await ingr.save(); + else { + // non ha ancora i 7 requisiti + } + + } else { + + const listaingr2 = await ListaIngresso.find({ idapp, ind_order: ingr.ind_order }); + + for (const ingr2 of listaingr2) { + + const ris = await ListaIngresso.findByIdAndUpdate(ingr2._id, { + $set: { + username: ingr.username, + invitante_username: ingr.invitante_username + } + }, { new: false }); + } + + } + + // cancella in user i campi che non uso più + await User.findByIdAndUpdate(user.id, { + $set: { + old_order: user.ind_order, + ind_order: -1, + // aportador_solidario: '' + } + }) + } + } + } + + // Comprende anche i sospesi + const arrIdTelegramUsers = await User.find({ idapp, 'profile.teleg_id': { $gt: 1 } }, + { _id: 1, username: 1, aportador_solidario: 1, old_order: 1, lang: 1, date_reg: 1, 'profile.teleg_id': 1 }) + .sort({ + 'profile.teleg_id': 1, + old_order: 1 + }); + + + // Crea altri ListaIngresso per gli utenti con i sottoaccount: + /* + const arrIdTelegramUsers = []; + const arrusersAlreadyExist = []; + for (const user of arrusers) { + if (!!user.profile.teleg_id) { + const trovati = arrusersAlreadyExist.find((rec) => rec.teleg_id === user.profile.teleg_id); + if (trovati) { + // era già presente, quindi lo aggiungo ! + const trovatoidteleg = arrIdTelegramUsers.find((rec) => rec.teleg_id === user.profile.teleg_id); + if (!trovatoidteleg) + arrIdTelegramUsers.push({ teleg_id: user.profile.teleg_id, username: user.username }); + } else { + arrusersAlreadyExist.push({ teleg_id: user.profile.teleg_id, username: user.username }); + } + } + } + */ + + let index = 0; + + let teleg_id = 0; + let username = ''; + let invitante_username = ''; + let invitante_degli_invitati = ''; + + // Questi sono Utenti che hanno associato Telegram a più Account ! + for (const myuser of arrIdTelegramUsers) { + + // Crea 1 record listaingresso per ogni record aggiuntivo ! escludendo il primo! + if (teleg_id !== myuser.profile.teleg_id) { + index = 0; + teleg_id = myuser.profile.teleg_id; + username = myuser.username; + invitante_username = myuser.aportador_solidario; + invitante_degli_invitati = myuser.username; + } + + if (index > 0) { + // Ind_order to find ! + const ind_order = myuser.old_order; + //const findnave = await Nave.find({ idapp, ind_order: myuser.old_order, num_tess: 1 }); + + if (ind_order >= 0) { + const findlistaingresso = await ListaIngresso.findOne({ idapp, ind_order, num_tess: 1 }); + + if (!!findlistaingresso) { + await ListaIngresso.findByIdAndUpdate(findlistaingresso._id, { + $set: { + username, + invitante_username, + note: findlistaingresso.username, + } + }, { new: false }); + + await Nave.updateMany({idapp, ind_order}, { + $set: { + note: findlistaingresso.username, + } + }, { new: false }); + + + // Crea Record ListaIngresso + // const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, myuser.username, invitante_username, myuser.lang, false, true, myuser.date_reg, note, added); + + // Assegna l'Invitante agli Invitati ! trova tutti gli invitati che hanno questo username + const arrinvitati = await User.find({ idapp, aportador_solidario: myuser.username }, { username: 1 }); + for (const invitato of arrinvitati) { + await User.changeInvitante(idapp, invitato.username, invitante_degli_invitati, ind_order) + } + + // poi imposta come cancellato questo record + await User.findByIdAndUpdate(myuser._id, { $set: { deleted: true } }); + } + } + + } + index++; + } + + return index; + + } catch (e) { + console.error(e.message); + } + +}; + +ListaIngressoSchema.statics.getListaTessByUsername = function (idapp, username) { + const ListaIngresso = this; + + return ListaIngresso.find({ + idapp, + username, + // added: true, + deleted: false, + }); + + +}; + +ListaIngressoSchema.statics.getarray = async function (idapp, filtri, myobjField) { + const ListaIngresso = this; + + let myfilter2 = { + surname: { $exists: true }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }; + + let myquery = getQueryProj( + filtri, + myobjField, + myfilter2 + ); + + return await ListaIngresso.aggregate(myquery); + +}; + + +ListaIngressoSchema.statics.getInvitati = async function (idapp, username, myobjField) { + const ListaIngresso = this; + + return ListaIngresso.getarray(idapp, + { + idapp, + deleted: false, + invitante_username: username, + username: { $ne: username }, + }, + myobjField); + +}; + +/* +ListaIngressoSchema.statics.getUserByInvitante_Username = async function (idapp, invitante_username) { + const ListaIngresso = this; + + const arr = ListaIngresso.getarray(idapp, + { + idapp, + deleted: false, + invitante_username: invitante_username, + username: { $ne: {invitante_username} }, + }, + null); + + if (!!arr) + return arr[0]; + else + return null; +}; + +*/ + +ListaIngressoSchema.statics.getnumInvitati = async function (idapp, username) { + const ListaIngresso = this; + + const arrlistainv = await ListaIngresso.find({ + idapp, + invitante_username: username, + deleted: false, + username: { $ne: username }, + }, { username: 1 }); + + const { User } = require('./user'); + + // Ottieni gli invitati che ancora non hanno un'imbarco + const arrinv = await User.find({ + idapp, + aportador_solidario: username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + }); + + for (const inv of arrinv) { + if (!arrlistainv.find((rec) => rec.username === inv.username)) + arrlistainv.push(inv); + } + + if (!!arrlistainv) + return arrlistainv.length; + else + return 0; + +}; + +ListaIngressoSchema.statics.getnumInvitatiAttivi = async function (idapp, username) { + const ListaIngresso = this; + + const { User } = require('./user'); + + let myfilter2 = { + surname: { $exists: true }, + $and: User.getQueryQualified(), + }; + + let myquery = getQueryProj({ + idapp, + invitante_username: username, + username: { $ne: username }, + deleted: false, + }, + { username: 1, ind_order: 1 }, + myfilter2, + ); + + // { _id: null, count: { $sum: 1 } + + arrlistainv = await ListaIngresso.aggregate(myquery); + + // Ottieni gli invitati che ancora non hanno un'imbarco + const arrinv = await User.find({ + idapp, + aportador_solidario: username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + $and: User.getQueryQualified() + }); + + for (const inv of arrinv) { + if (!arrlistainv.find((rec) => rec.username === inv.username)) + arrlistainv.push(inv); + } + + if (!!arrlistainv) + return arrlistainv.length; + else + return 0; +}; + + +ListaIngressoSchema.statics.aggiornaIndex = function (idapp) { + const ListaIngresso = this; + + const arrlista = ListaIngresso.find({ idapp }).sort({ created: 1 }); + + +}; + + const ListaIngresso = mongoose.model('ListaIngresso', ListaIngressoSchema); diff --git a/src/server/models/nave.js b/src/server/models/nave.js index 15900c9..24f9c34 100755 --- a/src/server/models/nave.js +++ b/src/server/models/nave.js @@ -91,6 +91,31 @@ NaveSchema.statics.findByIndOrder = function (idapp, ind_order) { } }; +NaveSchema.statics.checkIfNaveExist = async function (idapp, username) { + const Nave = this; + + try { + + const arrlista = await ListaIngresso.find({ + idapp, + username, + // added: true, + deleted: false, + }); + + for (const rec of arrlista) { + const mynave = await Nave.find({ idapp, ind_order: rec.ind_order }); + if (!!mynave) + return true; + } + + return false; + + } catch (e) { + + } +}; + NaveSchema.statics.findByIndOrderAndNumTess = function (idapp, ind_order, num_tess) { const Nave = this; @@ -108,9 +133,34 @@ NaveSchema.statics.findByIndOrderAndNumTess = function (idapp, ind_order, num_te NaveSchema.statics.findById = function (idapp, id) { const Nave = this; - const myquery = getQueryProj({ idapp, '_id': ObjectID(id) }); + const { User } = require('./user'); - return Nave.aggregate(myquery); + const myquery = getQueryProj({ idapp, '_id': id }); + + return Nave.aggregate(myquery) + .then(async (rec) => { + try { + if (!!rec) { + if (rec.length > 0) { + const ris = await User.findByIndOrder(idapp, rec[0].ind_order); + if (!!ris) { + if (!!ris._doc) + rec[0] = { ...rec[0], ...ris._doc }; + else + rec[0] = { ...rec[0], ...ris }; + return rec[0]; + } + return rec[0]; + } else { + return null; + } + } else { + return null; + } + }catch (e) { + console.error(e.message); + } + }); }; @@ -176,7 +226,7 @@ NaveSchema.statics.findDonatoreByNave = function (idapp, nave) { return Nave.findOne(miaquery); } catch (e) { - + console.error(e.message); } }; @@ -243,16 +293,13 @@ NaveSchema.statics.findRecByRigaColParent = async function (idapp, riga, col, nu recfind = await Nave.findById(idapp, myrec.parent_id); if (!!recfind) { - if (recfind.length > 0) { - recfind = recfind[0]; - lastrec = recfind; - myrigacol.riga = lastrec.riga; - myrigacol.col = lastrec.col; - } else { - //lastrec = await User.findByIndOrder(idapp, 0); - lastrec = await Nave.findGeneric({ idapp, riga: 0, col: 0 }); - break; - } + lastrec = recfind; + myrigacol.riga = lastrec.riga; + myrigacol.col = lastrec.col; + } else { + //lastrec = await User.findByIndOrder(idapp, 0); + lastrec = await Nave.findGeneric({ idapp, riga: 0, col: 0 }); + break; } } parentup++; @@ -267,43 +314,6 @@ NaveSchema.statics.findRecByRigaColParent = async function (idapp, riga, col, nu }; -function getlimiti(mypos) { - - if (mypos.col < 0) { - mypos.col = 0; - } - - if (mypos.riga < 0) { - mypos.riga = 0; - mypos.col = 0; - } - - return mypos; -} - -function getRigaColGenerica(idapp, riga, col, numup) { - mypos = { - idapp, - riga, - col, - numup - }; - - if (idapp === tools.AYNI) { - tools.getRigaColByPosUp(mypos); - ris = getlimiti(mypos); - } - - return ris; -} - -function getRigaColSognatoreByFuoco(idapp, riga, col) { - return getRigaColGenerica(idapp, riga, col, 6); -} - -function getRigaColMediatoreByFuoco(idapp, riga, col) { - return getRigaColGenerica(idapp, riga, col, 3); -} NaveSchema.statics.findGeneric = function (myrigacol) { @@ -339,17 +349,17 @@ NaveSchema.statics.findGeneric = function (myrigacol) { if (!!newrec) { let myarr = {}; if (rec[0]._doc === undefined) - myarr = { ...newrec._doc, ...rec[0] }; + myarr = { ...newrec, ...rec[0] }; else - myarr = { ...newrec._doc, ...rec[0]._doc }; + myarr = { ...newrec, ...rec[0]._doc }; return myarr; } else { let myarr = rec[0]; if (!!newrec) { if (rec[0]._doc === undefined) - myarr = { ...newrec._doc, ...rec[0] }; + myarr = { ...newrec, ...rec[0] }; else - myarr = { ...newrec._doc, ...rec[0]._doc }; + myarr = { ...newrec, ...rec[0]._doc }; } return myarr; } @@ -403,9 +413,11 @@ function getQueryProj(myfilter) { name: 1, surname: 1, username: 1, + invitante_username: 1, deleted: 1, sospeso: 1, 'profile.paymenttypes': 1, + 'profile.teleg_id': 1, 'profile.email_paypal': 1, 'profile.cell': 1, made_gift: 1, @@ -433,10 +445,32 @@ function getQueryProj(myfilter) { { $match: myfilter }, { $lookup: { - from: "users", + from: "listaingressos", localField: "ind_order", foreignField: "ind_order", // field in the user collection - as: "user" + as: "mylista" + } + }, + { + $unwind: "$mylista" + }, + { + $lookup: { + from: "users", + as: "user", + let: {username: '$mylista.username' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$username', '$$username'] }, + { $eq: ['$idapp', myfilter.idapp] }, + ] + } + } + } + ] } }, { @@ -521,32 +555,34 @@ NaveSchema.statics.getPlaccaGenerica = async function (idapp, riga, col, offset, let recmediatore = await Nave.findMediatoreByFuoco(idapp, riga, col, offset); let navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, riga, col, offset); - mystr = tools.ACAPO; + if (!solorecord) { + mystr = tools.ACAPO; - mystr += 'GIFTING CHAT (' + riga + '.' + col + ') ' + tools.ACAPO + tools.ACAPO; + mystr += 'GIFTING CHAT (' + riga + '.' + col + ') ' + tools.ACAPO + tools.ACAPO; - if (offset === tools.Placca.SONOFUOCO) { - mystr += tools.Placca.SOGNATORE + tools.Placca.STR_SOGNATORE + ': ' + await getusertextbyrec(recsognatori[0], '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; - mystr += tools.Placca.MEDIATORE + tools.Placca.STR_MEDIATORE + ': ' + await getusertextbyrec(recmediatore, '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; - } + if (offset === tools.Placca.SONOFUOCO) { + mystr += tools.Placca.SOGNATORE + tools.Placca.STR_SOGNATORE + ': ' + await getusertextbyrec(recsognatori[0], '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; + mystr += tools.Placca.MEDIATORE + tools.Placca.STR_MEDIATORE + ': ' + await getusertextbyrec(recmediatore, '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; + } - if (offset === tools.Placca.SONOACQUA) { - mystr += tools.Placca.SOGNATORE + tools.Placca.STR_SOGNATORE + ': ' + await getusertextbyrec(recmediatore, '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; - } + if (offset === tools.Placca.SONOACQUA) { + mystr += tools.Placca.SOGNATORE + tools.Placca.STR_SOGNATORE + ': ' + await getusertextbyrec(recmediatore, '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; + } - let symb = { - car: 'D', - icona: '🔥' - }; - - if (offset === tools.Placca.SONOFUOCO) { - mystr += tools.Placca.STR_DONATORI + ':' + tools.ACAPO; - } else if (offset === tools.Placca.SONOACQUA) { - mystr += tools.Placca.STR_MEDIATORI + ':' + tools.ACAPO; - symb = { - car: 'A', - icona: '💦' + let symb = { + car: 'D', + icona: '🔥' }; + + if (offset === tools.Placca.SONOFUOCO) { + mystr += tools.Placca.STR_DONATORI + ':' + tools.ACAPO; + } else if (offset === tools.Placca.SONOACQUA) { + mystr += tools.Placca.STR_MEDIATORI + ':' + tools.ACAPO; + symb = { + car: 'A', + icona: '💦' + }; + } } // mystr += '🔥🌏💦💨🔥🌏💦💨' + tools.ACAPO; @@ -573,7 +609,9 @@ NaveSchema.statics.getPlaccaGenerica = async function (idapp, riga, col, offset, recfuoco = checkifNullThenEmpty(recfuoco, indr, indc); arrdonatori.push({ index: ind, ...recfuoco }); - mystr += await getusertextbyrec(recfuoco, symb.icona, symb.car, indr, indc, ind) + tools.ACAPO; + if (!solorecord) { + mystr += await getusertextbyrec(recfuoco, symb.icona, symb.car, indr, indc, ind) + tools.ACAPO; + } ind++; } @@ -777,45 +815,82 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in }; -async function Fuochi8Completati(idapp, params) { - // Inviare un msg al Mediatore che può aprire la Chat con gli 8 fuochi - const telegrambot = require('../telegram/telegrambot'); - - let text = '\nCompletata NAVE [riga=' + params.riga + ',col=' + params.col + ', ind_order=' + params.ind_order + ']'; - console.log(text); - tools.writeNaveLog(text); - - const { User } = require('./user'); - - const rec = await User.findByIndOrder(idapp, params.ind_order); - - text = await Nave.getNaveByUser(idapp, params.ind_order, rec.lang, true); - - // Inviare un msg a questi 8 Fuochi, che la loro placca è Pronta ! - - if (tools.isAbilitaNave(idapp)) { - // ............. - } - - if (false) { - await telegrambot.sendMsgTelegram(idapp, rec.username, text, true); - } else { - await telegrambot.sendMsgTelegramToTheAdmin(idapp, text); - } - - // Inviare la placca a Managers - // await telegrambot.sendMsgTelegramToTheManagers(idapp, txt); -} +// async function Fuochi8Completati(idapp, params) { +// // Inviare un msg al Mediatore che può aprire la Chat con gli 8 fuochi +// const telegrambot = require('../telegram/telegrambot'); +// +// let text = '\nCompletata NAVE [riga=' + params.riga + ',col=' + params.col + ', ind_order=' + params.ind_order + ']'; +// console.log(text); +// tools.writeNaveLog(text); +// +// const { User } = require('./user'); +// +// const rec = await User.findByIndOrder(idapp, params.ind_order); +// +// text = await Nave.getNaveByUser(idapp, params.ind_order, rec.lang, true); +// +// // Inviare un msg a questi 8 Fuochi, che la loro placca è Pronta ! +// +// if (tools.isAbilitaNave(idapp)) { +// // ............. +// } +// +// if (false) { +// await telegrambot.sendMsgTelegram(idapp, rec.username, text, true); +// } else { +// await telegrambot.sendMsgTelegramToTheAdmin(idapp, text); +// } +// +// // Inviare la placca a Managers +// // await telegrambot.sendMsgTelegramToTheManagers(idapp, txt); +// } NaveSchema.statics.getArrPosizioniByIndOrder = async function (idapp, ind_order) { const Nave = this; - arrposizioni = await Nave.find({ 'idapp': idapp, ind_order }).sort({ riga: 1, col: 1 }); + arrposizioni = await Nave.find({ idapp, ind_order }).sort({ riga: 1, col: 1 }); return arrposizioni; }; +NaveSchema.statics.getArrPosizioniByUsername = async function (idapp, username) { + const Nave = this; + + const { ListaIngresso } = require('./listaingresso'); + + try { + const arrrec_indorder = await ListaIngresso.findByAllRecByUsername(idapp, username).distinct("ind_order"); + + let arrposizioni = []; + + for (const ind_order of arrrec_indorder) { + const arr = await Nave.find({ 'idapp': idapp, ind_order }).sort({ riga: 1, col: 1 }); + if (!!arr) + arrposizioni = [...arrposizioni, ...arr]; + } + + return arrposizioni; + } catch (e) { + console.error(e.message); + } + +}; + +NaveSchema.statics.getArrProfiliByIndOrder = async function (idapp, ind_order) { + const Nave = this; + + arrposizioni = await Nave.find({ 'idapp': idapp, ind_order }).sort({ riga: 1, col: 1 }); + + arrprofili = []; + + // Ind_Order + // Ind_order_base + + + return arrprofili; +}; + NaveSchema.statics.getPrimaNaveByRiga = async function (idapp, riga) { const Nave = this; @@ -1174,32 +1249,36 @@ NaveSchema.statics.visuNaviUtentiEliminati = async function (idapp) { }; -NaveSchema.statics.getNaveByUser = async function (idapp, ind_order, lang, fuoco) { +NaveSchema.statics.getNaveByUser = async function (idapp, username, lang, fuoco) { const Nave = this; let mystr = ''; let rec = {}; - const arrposiz = await Nave.getArrPosizioniByIndOrder(idapp, ind_order); - if (!!arrposiz) { - for (const pos of arrposiz) { - let mypos = { - riga: pos.riga, - col: pos.col, - numup: 3, - }; - tools.getRigaColByPosUp(mypos); + try { + const arrposiz = await Nave.getArrPosizioniByUsername(idapp, username); + if (!!arrposiz) { + for (const pos of arrposiz) { + let mypos = { + riga: pos.riga, + col: pos.col, + numup: 3, + }; + tools.getRigaColByPosUp(mypos); - let persistente = await NavePersistente.findByRigaColByDonatore(idapp, pos.riga, pos.col, 0); - if (!!persistente) { - if (persistente.provvisoria) { - mystr += tools.ACAPO + tools.get__('NAVE', lang) + ' ' + '[' + mypos.riga + '.' + mypos.col + '] - ' + tools.get__('TEMPORANEA', lang) + tools.ACAPO+ tools.ACAPO; - } else { - mystr += await Nave.getNavePos(idapp, mypos.riga, mypos.col, false, ind_order); + let persistente = await NavePersistente.findByRigaColByDonatore(idapp, pos.riga, pos.col, 0); + if (!!persistente) { + if (persistente.provvisoria) { + mystr += tools.ACAPO + tools.get__('NAVE', lang) + ' ' + '[' + mypos.riga + '.' + mypos.col + '] - ' + tools.get__('TEMPORANEA', lang) + tools.ACAPO + tools.ACAPO; + } else { + mystr += await Nave.getNavePos(idapp, mypos.riga, mypos.col, false, ind_order); + } } + // mystr += await Nave.getPlaccaPerDonatore(idapp, pos.riga, pos.col, false, rec); + // mystr += await Nave.getPlaccaPerMediatore(idapp, pos.riga, pos.col, false, rec); } - // mystr += await Nave.getPlaccaPerDonatore(idapp, pos.riga, pos.col, false, rec); - // mystr += await Nave.getPlaccaPerMediatore(idapp, pos.riga, pos.col, false, rec); } + } catch (e) { + console.error(e.message); } return mystr; @@ -1333,6 +1412,53 @@ NaveSchema.statics.getNextNumTess = async function (idapp, ind_order) { }; +NaveSchema.statics.getnumNaviByUsername = async function (idapp, username) { + const Nave = this; + + try { + + const { ListaIngresso } = require('./listaingresso'); + + // Get array di ind_order + const arrind_order = await ListaIngresso.find({ idapp, username }).distinct('ind_order'); + + const arrrec = await Nave.find({ idapp, ind_order: arrind_order, num_tess: { $mod: [ 2 , 1] } }, { + riga: 1, + col: 1, + ind_order: 1 + }); + + if (!!arrrec) + return arrrec.length; + else + return 0; + + }catch (e) { + console.error(e.message); + } +}; + +NaveSchema.statics.getSognatoreByRigaColMediatore = async function (idapp, navemediatore) { + + const ris = this.getRigaColSognatoreByMediatore(idapp, navemediatore.riga, navemediatore.col, 3); + + const myquery = getQueryProj({ + idapp, + riga: ris.riga, + col: ris.col, + }); + + arrrec = await Nave.aggregate(myquery); + + if (!!arrrec) { + if (arrrec.length > 0) + return arrrec[0]; + } + + return null; +}; + + const Nave = mongoose.model('Nave', NaveSchema); diff --git a/src/server/models/navepersistente.js b/src/server/models/navepersistente.js index 56be2ef..9b33351 100755 --- a/src/server/models/navepersistente.js +++ b/src/server/models/navepersistente.js @@ -118,10 +118,32 @@ function getQueryProj(myfilter) { { $match: myfilter }, { $lookup: { - from: "users", + from: "listaingressos", localField: "ind_order", foreignField: "ind_order", // field in the user collection - as: "user" + as: "mylista" + } + }, + { + $unwind: "$mylista" + }, + { + $lookup: { + from: "users", + as: "user", + let: {username: '$mylista.username' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$username', '$$username'] }, + { $eq: ['$idapp', myfilter.idapp] }, + ] + } + } + } + ] } }, { diff --git a/src/server/models/project.js b/src/server/models/project.js index 74c34bd..10b2a9d 100755 --- a/src/server/models/project.js +++ b/src/server/models/project.js @@ -333,8 +333,6 @@ ProjectSchema.statics.updateCalc = async function (userId, idproj, objdatacalc, ProjectSchema.pre('save', function (next) { - // var Project = this; - // console.log('Project.expiring_at', Project.expiring_at); next(); diff --git a/src/server/models/user.js b/src/server/models/user.js index ae723e2..6ac73f4 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -10,7 +10,7 @@ const { Settings } = require('../models/settings'); const { ListaIngresso } = require('../models/listaingresso'); const { Nave } = require('../models/nave'); const { NavePersistente } = require('../models/navepersistente'); -const { ExtraList } = require('../models/extralist'); +// const { ExtraList } = require('../models/extralist'); const { ObjectID } = require('mongodb'); @@ -46,9 +46,15 @@ const UserSchema = new mongoose.Schema({ type: String, required: true, }, + index: { + type: Number + }, ind_order: { type: Number }, + old_order: { + type: Number + }, username: { type: String, required: true, @@ -121,7 +127,7 @@ const UserSchema = new mongoose.Schema({ news_on: { type: Boolean }, - aportador_solidario: { + aportador_solidario: { // da cancellare type: String, }, aportador_iniziale: { @@ -401,6 +407,7 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) lang: 1, ind_order: 1, username: 1, + aportador_solidario: 1, name: 1, surname: 1, deleted: 1, @@ -429,101 +436,96 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) if (myrec) { myrec.qualified = await User.isUserQualified7(idapp, myrec.username); - myrec.numinvitati = await User.getnumInvitati(idapp, myrec.username); - myrec.numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, myrec.username); + myrec.numNaviEntrato = await Nave.getnumNaviByUsername(idapp, myrec.username); + myrec.numinvitati = await ListaIngresso.getnumInvitati(idapp, myrec.username); + myrec.numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, myrec.username); } return myrec }; UserSchema.statics.getDownlineByUsername = async function (idapp, username) { + if (username === undefined) return null; - const User = this; - const arrrec = await User.find({ - 'idapp': idapp, - 'aportador_solidario': username, + const arrrec = await ListaIngresso.getInvitati(idapp, username, + { + index: 1, + lang: 1, + invitante_username: 1, + ind_order: 1, + username: 1, + name: 1, + surname: 1, + verified_email: 1, + 'profile.teleg_id': 1, + 'profile.saw_zoom_presentation': 1, + 'profile.saw_and_accepted': 1, + 'profile.email_paypal': 1, + 'profile.my_dream': 1, + 'profile.paymenttypes': 1, + 'profile.cell': 1, + made_gift: 1, + email: 1, + date_reg: 1, + img: 1 + } + ); + + // Ottieni gli invitati che ancora non hanno un'imbarco + const arrinv = await User.find({ + idapp, + aportador_solidario: username, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] - }, { - lang: 1, - aportador_solidario: 1, - ind_order: 1, - username: 1, - name: 1, - surname: 1, - verified_email: 1, - 'profile.teleg_id': 1, - 'profile.saw_zoom_presentation': 1, - 'profile.saw_and_accepted': 1, - 'profile.email_paypal': 1, - 'profile.my_dream': 1, - 'profile.paymenttypes': 1, - 'profile.cell': 1, - made_gift: 1, - email: 1, - date_reg: 1, - img: 1 - }, (err, arrrec) => { - return arrrec; }); + for (const inv of arrinv) { + if (!arrrec.find((rec) => rec.username === inv.username)) + arrrec.push(inv); + } + + if (!!arrrec) { for (const rec of arrrec) { - rec._doc.qualified = await User.isUserQualified7(idapp, rec.username); - rec._doc.numinvitati = await User.getnumInvitati(idapp, rec.username); - rec._doc.numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, rec.username); + rec.qualified = await User.isUserQualified7(idapp, rec.username); + rec.numNaviEntrato = await Nave.getnumNaviByUsername(idapp, rec.username); + rec.numinvitati = await ListaIngresso.getnumInvitati(idapp, rec.username); + rec.numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, rec.username); } } - - return arrrec + return arrrec; }; +UserSchema.statics.getQueryQualified = function () { + return [ + { + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }, + { + $or: [ + { + 'profile.special_req': true + }, + { + verified_email: true, + 'profile.teleg_id': { $gt: 1 }, + 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED, + 'profile.saw_zoom_presentation': true, + 'profile.my_dream': { $exists: true }, + 'profile.email_paypal': { $exists: true }, + 'profile.paymenttypes': { "$in": ['paypal'] }, + $and: [ + { "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } }, + { "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } } + ], + // $where: "this.profile.paymenttypes.length >= 1", + }] + } + ]; +} -UserSchema.statics.getnumInvitatiAttivi = function (idapp, username) { - const User = this; - - if (username === undefined) - return 0; - - // return User.count({ - return User.countDocuments({ - idapp, - aportador_solidario: username, - $and: [ - { - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, - { - $or: [ - { - 'profile.special_req': true - }, - { - - verified_email: true, - 'profile.teleg_id': { $gt: 1 }, - 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED, - 'profile.saw_zoom_presentation': true, - 'profile.my_dream': { $exists: true }, - 'profile.paymenttypes': { "$in": ['paypal'] }, - $and: [ - { 'profile.my_dream': { $exists: true } }, - { "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } }, - { - $and: [ - { 'profile.email_paypal': { $exists: true } }, - { "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } } - ], - } - ], - }] - } - ] - }) - ; -}; UserSchema.statics.isUserQualified7 = async function (idapp, username) { const User = this; @@ -534,30 +536,7 @@ UserSchema.statics.isUserQualified7 = async function (idapp, username) { const myquery = { 'idapp': idapp, 'username': username, - $and: [ - { - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }, - { - $or: [ - { - 'profile.special_req': true - }, - { - verified_email: true, - 'profile.teleg_id': { $gt: 1 }, - 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED, - 'profile.saw_zoom_presentation': true, - 'profile.my_dream': { $exists: true }, - 'profile.email_paypal': { $exists: true }, - 'profile.paymenttypes': { "$in": ['paypal'] }, - $and: [ - { "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } }, - { "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } } - ], - $where: "this.profile.paymenttypes.length >= 1", - }] - }] + $and: User.getQueryQualified(), }; const myrec = await User.findOne(myquery); @@ -572,7 +551,7 @@ UserSchema.statics.isUserQualified9 = async function (idapp, username) { return false; qualified = await User.isUserQualified7(idapp, username); - numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, username); + numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, username); return qualified && (numinvitatiattivi >= 2); @@ -616,16 +595,6 @@ UserSchema.statics.getindOrderDuplicate = function (idapp) { }); }; -UserSchema.statics.getnumInvitati = function (idapp, username) { - const User = this; - - return User.count({ - idapp, - aportador_solidario: username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }); -}; - UserSchema.statics.findByLinkreg = function (idapp, linkreg) { const User = this; @@ -696,24 +665,55 @@ UserSchema.statics.findByIndOrder = function (idapp, ind_order) { } }; +UserSchema.statics.findByOldOrder = function (idapp, old_order) { + const User = this; -UserSchema.pre('save', function (next) { - const user = this; - - - /* - if (user.isModified('password')) { - bcrypt.genSalt(10, (err, salt) => { - bcrypt.hash(user.password, salt, (err, hash) => { - user.password = hash; - next(); - }); + try { + return User.findOne({ + idapp, + old_order, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); - } else { - next(); + } catch (e) { + console.error(e.message); + } +}; + + +UserSchema.pre('save', async function (next) { + + try { + if (this.isNew) { + try { + const myrec = await User.findOne({ idapp: this.idapp }).limit(1).sort({ index: -1 }); + + if (!!myrec) { + this.index = myrec._doc.index + 1; + } else { + this.index = 1; + } + } catch (e) { + this.index = 2; + } + } + + /* + if (user.isModified('password')) { + bcrypt.genSalt(10, (err, salt) => { + bcrypt.hash(user.password, salt, (err, hash) => { + user.password = hash; + next(); + }); + }); + } else { + next(); + } + */ + + next(); + }catch (e) { + console.error(e.message); } - */ - next(); }); UserSchema.methods.removeToken = function (token) { @@ -763,15 +763,6 @@ UserSchema.statics.getUserById = function (idapp, id) { }) }; -UserSchema.statics.getUserByAportador = function (idapp, aportador_solidario) { - const User = this; - - return User.findOne({ - idapp, aportador_solidario, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }) -}; - UserSchema.statics.getAportadorSolidarioByUsername = async function (idapp, username) { const User = this; @@ -920,25 +911,31 @@ UserSchema.statics.getNameSurnameByUsername = async function (idapp, username) { }; UserSchema.statics.getSmallRecByIndOrder = async function (idapp, ind_order) { - const User = this; - return await User.findOne({ - idapp, ind_order, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] - }, - { - idapp: 1, - ind_order: 1, - username: 1, - name: 1, - surname: 1 - } - ) - .then((rec) => { - return rec; - }).catch((e) => { - console.error('getSmallRecByIndOrder', e); - }); + try { + const rec = await ListaIngresso.getarray(idapp, + { + idapp, + ind_order, + deleted: false, + }, + { + idapp: 1, + ind_order: 1, + username: 1, + name: 1, + surname: 1 + }); + + if (!!rec) + return rec[0]; + + return null; + + } catch (e) { + console.error('getSmallRecByIndOrder', e); + } + }; @@ -995,7 +992,7 @@ UserSchema.statics.isAdminByIdTeleg = async function (idapp, idtelegram) { return await User.findOne({ idapp, - 'username': 'paoloar77', + username: 'paoloar77', 'profile.manage_telegram': true, 'profile.teleg_id': idtelegram }, { 'profile.teleg_id': 1 }) @@ -1061,13 +1058,17 @@ UserSchema.statics.getUsersListByParams = function (params) { */ UserSchema.statics.getFieldsForSearch = function () { - return [{ field: 'username', type: tools.FieldType.string }, + return [ + { field: 'username', type: tools.FieldType.string }, { field: 'name', type: tools.FieldType.string }, + { field: 'index', type: tools.FieldType.number }, { field: 'ind_order', type: tools.FieldType.number }, + { field: 'old_order', type: tools.FieldType.number }, { field: 'surname', type: tools.FieldType.string }, { field: 'email', type: tools.FieldType.string }, { field: 'profile.cell', type: tools.FieldType.string }, { field: 'profile.email_paypal', type: tools.FieldType.string }, + { field: 'profile.teleg_id', type: tools.FieldType.number }, { field: 'profile.username_telegram', type: tools.FieldType.string }, { field: 'aportador_solidario', type: tools.FieldType.string }] }; @@ -1102,20 +1103,23 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us // DATA: username, name, surname, email, intcode_cell, cell const dashboard = { aportador: {}, - downline: [] + downline: [], + arrposizioni: [], + arrimbarchi: [], + arrusers: {}, }; dashboard.myself = await User.getUserShortDataByUsername(idapp, username); // Data of my Aportador dashboard.aportador = await User.getUserShortDataByUsername(idapp, aportador_solidario); - if (dashboard.aportador === undefined) { - dashboard.aportador = await ExtraList.getUserNotRegisteredByNameSurname(idapp, aportador_solidario_nome_completo); - } + // if (dashboard.aportador === undefined) { + // dashboard.aportador = await ExtraList.getUserNotRegisteredByNameSurname(idapp, aportador_solidario_nome_completo); + // } dashboard.downline = []; // Data of my Downline - const arrap = await User.getDownlineByUsername(idapp, aportador_solidario); + const arrap = await User.getDownlineByUsername(idapp, username); if (!!arrap) dashboard.numpeople_aportador = arrap.length; @@ -1132,32 +1136,33 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us } } - if (!!dashboard.myself.ind_order) - dashboard.arrposizioni = await Nave.getArrPosizioniByIndOrder(idapp, dashboard.myself.ind_order); - else - dashboard.arrposizioni = []; + dashboard.arrimbarchi = await ListaIngresso.findAllByUsername(idapp, username); - if (!!dashboard.myself.ind_order) - dashboard.arrimbarchi = await ListaIngresso.findAllByIndOrder(idapp, dashboard.myself.ind_order); - else - dashboard.arrimbarchi = []; + // dashboard.arrprofili = await Nave.getArrProfiliByIndOrder(idapp, dashboard.myself.ind_order); + + dashboard.arrposizioni = await Nave.getArrPosizioniByUsername(idapp, username); + + const arrrec = await ListaIngresso.getProssimiInLista(idapp, true); for (let myimbarco of dashboard.arrimbarchi) { - myimbarco._doc.posiz = await ListaIngresso.getPosizioneInLista(idapp, myimbarco.ind_order, myimbarco.num_tess); + if (!!myimbarco.invitante_username) + dashboard.arrusers[myimbarco.invitante_username] = await User.getUserShortDataByUsername(idapp, myimbarco.invitante_username); + myimbarco._doc.posiz = await ListaIngresso.getPosizioneInLista(idapp, arrrec, myimbarco.ind_order, myimbarco.num_tess); } dashboard.navi_partenza = await NavePersistente.getListaNavi(idapp); dashboard.lastnave = await NavePersistente.getLastNave(idapp); - //for (let indriga = 0; indriga < 10; indriga++) { - // dashboard.navi_partenza.push(await Nave.getPrimaNaveByRiga(idapp, indriga)); - //} - for (let mypos of dashboard.arrposizioni) { mypos._doc.rec = await Nave.getNaveByRigaCol(idapp, mypos.riga, mypos.col); mypos._doc.nave_partenza = await NavePersistente.findByRigaColByDonatore(idapp, mypos.riga, mypos.col, 0); } + //for (let indriga = 0; indriga < 10; indriga++) { + // dashboard.navi_partenza.push(await Nave.getPrimaNaveByRiga(idapp, indriga)); + //} + + const arrnew = []; for (let mypos of dashboard.arrposizioni) { @@ -1167,7 +1172,8 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us if (mypos.num_tess % 2 !== 0) { for (let myrec of dashboard.arrposizioni) { - if (myrec.num_tess === mypos.num_tess + 1) { + if (myrec.num_tess === mypos.num_tess + 1 && (myrec.ind_order === mypos.ind_order)) { + // La Nave di Ritorno (numtess = 2) esiste nella lista ! trovato = true } } @@ -1190,14 +1196,14 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us myrec.nave_partenza = await NavePersistente.findByRigaColByDonatore(idapp, myrec.riga, myrec.col, 0); - arrnew.push(myrec); + arrnew.push(myrec); } } } dashboard.arrposizioni = [...dashboard.arrposizioni, ...arrnew]; - // console.table(dashboard.arrnavi); + // console.table(dashboard.arrnavi); return dashboard; } catch (e) { @@ -1248,6 +1254,7 @@ UserSchema.statics.getUsersRegistered = async function (idapp) { return await User.count(myfind); }; +/* UserSchema.statics.getUsersQualified = async function (idapp, numinvitati) { const User = this; @@ -1285,7 +1292,7 @@ UserSchema.statics.getUsersQualified = async function (idapp, numinvitati) { let arrris = []; for (const rec of arrusers) { - rec.numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, rec.username); + rec.numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, rec.username); if (rec.numinvitatiattivi >= numinvitati) { arrris.push(rec); } @@ -1294,33 +1301,14 @@ UserSchema.statics.getUsersQualified = async function (idapp, numinvitati) { return arrris }; +*/ UserSchema.statics.visuUtentiNonInNavi = async function (idapp) { const User = this; const arrusers = await User.find({ idapp, - $and: [ - { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] }, - { - $or: [ - { - 'profile.special_req': true - }, - { - verified_email: true, - 'profile.teleg_id': { $gt: 0 }, - 'profile.paymenttypes': { "$in": ['paypal'] }, - 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED, - 'profile.saw_zoom_presentation': true, - 'profile.my_dream': { $exists: true }, - $and: [ - { "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } }, - { "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } } - ], - }] - }] - + $and: User.getQueryQualified() }, { name: 1, surname: 1, @@ -1373,7 +1361,7 @@ UserSchema.statics.visuUtentiNonInNavi = async function (idapp) { visualizza = true; } - user.numinvitati = await User.getnumInvitati(idapp, user.username); + user.numinvitati = await ListaIngresso.getnumInvitati(idapp, user.username); reg++; let mianave = await Nave.findOne({ idapp, ind_order: user.ind_order }); let mialistaingresso = await ListaIngresso.findOne({ idapp, ind_order: user.ind_order }); @@ -1439,13 +1427,13 @@ UserSchema.statics.visuUtentiNonInNavi = async function (idapp) { return { num, mystr }; }; -UserSchema.statics.getNumUsersQualified = async function (idapp, numinvitati) { - - arrrec = await this.getUsersQualified(idapp, numinvitati); - - return arrrec.length - -}; +// UserSchema.statics.getNumUsersQualified = async function (idapp, numinvitati) { +// +// arrrec = await this.getUsersQualified(idapp, numinvitati); +// +// return arrrec.length +// +// }; UserSchema.statics.getEmailNotVerified = async function (idapp) { @@ -1562,8 +1550,8 @@ UserSchema.statics.calculateStat = async function (idapp, username) { const User = this; return calcstat = { - numinvitati: await User.getnumInvitati(idapp, username), - numinvitati_attivi: await User.getnumInvitatiAttivi(idapp, username), + numinvitati: await ListaIngresso.getnumInvitati(idapp, username), + numinvitati_attivi: await ListaIngresso.getnumInvitatiAttivi(idapp, username), }; }; @@ -1693,12 +1681,13 @@ if (tools.INITDB_FIRSTIME) { } async function addUtentiInLista(idapp, mode, arrusers) { + let num = 0; for (const rec of arrusers) { let ok = false; let qualified = await User.isUserQualified7(idapp, rec.username); - let numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, rec.username); - let numinvitati = await User.getnumInvitati(idapp, rec.username); + let numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, rec.username); + let numinvitati = await ListaIngresso.getnumInvitati(idapp, rec.username); if (rec.profile.special_req) { numinvitatiattivi = 2; @@ -1719,12 +1708,13 @@ async function addUtentiInLista(idapp, mode, arrusers) { } if (ok) { - ris = await ListaIngresso.addUserInListaIngresso(idapp, rec.ind_order, rec.lang, false, 1); + ris = await ListaIngresso.addUserInListaIngresso(idapp, rec.username, rec.aportador_solidario, rec.lang, false, true); if (!!ris) num++; } } return num; + } UserSchema.statics.deveRitessersi = async function (idapp, ind_order) { @@ -1750,6 +1740,72 @@ UserSchema.statics.getUsernameByIndOrder = async function (idapp, ind_order) { }; +UserSchema.statics.getUsernameByIndex = async function (idapp, index) { + + const myrec = await User.findOne({ + idapp, + index, + }, { username: 1 }); + + return (!!myrec) ? myrec.username : '' + +}; + +UserSchema.statics.ricalcolaIndex = async function (idapp) { + const User = this; + + const arrusers = await User.find({ idapp }).sort({ ind_order: 1 }); + let index = 1; + try { + for (const user of arrusers) { + let field = { + index + }; + + index++; + + const ris = await User.findOneAndUpdate({ _id: user._id }, { $set: field }, { new: false }); + } + }catch (e) { + console.error(e.message); + } + + +}; + +UserSchema.statics.changeInvitante = async function (idapp, username, invitante_username, ind_order_ingr) { + const User = this; + + const rec_ind_order_prima = await ListaIngresso.findOne({ idapp, username }); + + let modif_aportador = false; + // cambia aportador_solidario solo se è la prima nave! + + // Oppure se ancora non sono in Lista! + if (!rec_ind_order_prima) { + modif_aportador = true; + } else { + if (rec_ind_order_prima.ind_order === ind_order_ingr) { + modif_aportador = true; + } + } + + if (modif_aportador) { + await User.findOneAndUpdate({ idapp, username }, { $set: { aportador_solidario: invitante_username } }); + } + + // ** + // ** Cambia invitante_username e ind_order di LISTAINGRESSO + // ** + const rec_ingr = await ListaIngresso.findOne({ idapp, username: username }); + if (!!rec_ingr) { + await ListaIngresso.findByIdAndUpdate(rec_ingr._id, { $set: { invitante_username, ind_order: ind_order_ingr } }); + } + + +}; + + UserSchema.statics.DbOp = async function (idapp, mydata) { const User = this; try { @@ -1788,7 +1844,7 @@ UserSchema.statics.DbOp = async function (idapp, mydata) { arrusers = await User.find({ 'idapp': idapp, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] - }).sort({ ind_order: 1 }); + }).sort({ date_added: 1 }); let num = 0; num += await addUtentiInLista(idapp, 1, arrusers); diff --git a/src/server/router/api/actions.js b/src/server/router/api/actions.js index 7e03e6d..53e45a6 100755 --- a/src/server/router/api/actions.js +++ b/src/server/router/api/actions.js @@ -11,7 +11,7 @@ module.exports = { try { if (tablename === 'users') { - await ListaIngresso.deleteUserInListaIngresso(rec.idapp, rec.ind_order); + await ListaIngresso.deleteUserInListaIngresso(rec.idapp, rec.username); // Controlla se aveva invitati, li regala a quello sopra const arrap = await User.getDownlineByUsername(rec.idapp, rec.username); diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 6d385fc..f555627 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -30,7 +30,7 @@ const _ = require('lodash'); const { User } = require('../models/user'); const { Nave } = require('../models/nave'); const { NavePersistente } = require('../models/navepersistente'); -const { ExtraList } = require('../models/extralist'); +// const { ExtraList } = require('../models/extralist'); const { Booking } = require('../models/booking'); const { Operator } = require('../models/operator'); const { Where } = require('../models/where'); @@ -179,8 +179,10 @@ function getTableByTableName(tablename) { mytable = ''; if (tablename === 'users') mytable = User; - else if (tablename === 'extralist') - mytable = ExtraList; + else if (tablename === 'tessitura') + mytable = Tessitura; + // else if (tablename === 'extralist') + // mytable = ExtraList; else if (tablename === 'bookings') mytable = Booking; else if (tablename === 'operators') @@ -280,7 +282,7 @@ router.post('/gettable', authenticate, (req, res) => { async function checkIfSbloccatiRequisiti(idapp, allData, id) { - if (await Nave.findByIndOrder(idapp, allData.myuser.ind_order)) { + if (await Nave.checkIfNaveExist(idapp, allData.myuser.username)) { // Se già sei dentro la Nave, allora sei OK return true; } @@ -289,18 +291,18 @@ async function checkIfSbloccatiRequisiti(idapp, allData, id) { const is7req = await User.isUserQualified7(idapp, allData.myuser.username); const is9req = await User.isUserQualified9(idapp, allData.myuser.username); - const userlista = await ListaIngresso.findByIndOrder(idapp, allData.myuser.ind_order); - if (!userlista) { + const userlista = await ListaIngresso.getListaTessByUsername(idapp, allData.myuser.username); + if (userlista.length === 0) { // Se non sono ancora dentro alla lista, allora controllo if (!allData.precDataUser.is7req && is7req) { // ORA HAI I 7 REQUISITI ! - const msgtext = telegrambot.getCiao(idapp, allData.myuser.username, allData.myuser.lang) + tools.gettranslate('HAI_I_7_REQUISITI', allData.myuser.lang); - telegrambot.sendMsgTelegram(idapp, allData.myuser.username, msgtext, true); // Anche a STAFF + // const msgtext = telegrambot.getCiao(idapp, allData.myuser.username, allData.myuser.lang) + tools.gettranslate('HAI_I_7_REQUISITI', allData.myuser.lang); + // telegrambot.sendMsgTelegram(idapp, allData.myuser.username, msgtext, true); // Anche a STAFF if (tools.isAbilitaNave(idapp)) { // Aggiungilo alla ListaIngresso - ris = await ListaIngresso.addUserInListaIngresso(idapp, allData.myuser.ind_order, allData.myuser.lang, true, 1); + risingr = await ListaIngresso.addUserInListaIngresso(idapp, allData.myuser.username, allData.myuser.aportador_iniziale, allData.myuser.lang, true, false); } } } @@ -308,11 +310,12 @@ async function checkIfSbloccatiRequisiti(idapp, allData, id) { if (!allData.precDataUser.is9req && is9req) { // 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, true); // Anche a STAFF + telegrambot.sendMsgTelegram(idapp, allData.myuser.username, msgtext, false); // Anche a STAFF } // CHECK APORTADOR SOLIDARIO: if (!!allData.useraportador) { +/* const is9reqAportador = await User.isUserQualified9(idapp, allData.myuser.aportador_solidario); if (!allData.precDataAportador.is9req && is9reqAportador) { @@ -320,6 +323,7 @@ async function checkIfSbloccatiRequisiti(idapp, allData, id) { const msgtext = telegrambot.getCiao(idapp, allData.myuser.aportador_solidario, allData.useraportador.lang) + tools.gettranslate('HAI_I_9_REQUISITI', allData.useraportador.lang); telegrambot.sendMsgTelegram(idapp, allData.myuser.aportador_solidario, msgtext, true); // Anche a STAFF } +*/ } } @@ -385,8 +389,8 @@ router.patch('/chval', authenticate, async (req, res) => { allData = {}; allData.myuser = await User.getUserById(idapp, id); allData.precDataUser = await getInfoUser(idapp, allData.myuser.username); - allData.useraportador = await User.getUserByAportador(idapp, allData.myuser.aportador_solidario); - allData.precDataAportador = await getInfoUser(idapp, allData.myuser.aportador_solidario); + // allData.useraportador = await ListaIngresso.getUserByInvitante_Username(idapp, allData.myuser.aportador_solidario); + // allData.precDataAportador = await getInfoUser(idapp, allData.myuser.aportador_solidario); } } @@ -401,7 +405,7 @@ router.patch('/chval', authenticate, async (req, res) => { // Send Notification to the BOT await telegrambot.sendMsgTelegram(idapp, mydata.notifBot.un, mydata.notifBot.txt); addtext = '[Msg Inviato a ' + mydata.notifBot.un + ']:' + '\n' + mydata.notifBot.txt; - await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext); + await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext, true); } if (mydata.table === 'users') { @@ -412,12 +416,26 @@ router.patch('/chval', authenticate, async (req, res) => { if (mydata.table === 'users') { if ('aportador_solidario' in fieldsvalue) { + ind_order_ingr = mydata.ind_order_ingr; + // SERVE SE CI METTO LE MINUSCOLE/MAIUSCOLE SBAGLIATE in invitante_username! const myuserfound = await User.findByUsername(idapp, fieldsvalue.aportador_solidario, false); if (!!myuserfound) { if (!!myuserfound._id && !myuserfound.deleted) { - fieldsvalue.aportador_solidario = await User.getUsernameById(idapp, myuserfound._id); + const aportador = await User.getUsernameById(idapp, myuserfound._id); + fieldsvalue.aportador_solidario = aportador; //Aggiorna record ! await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }); + + const myfirstrec = await ListaIngresso.findOne({ username: rec.username, ind_order: ind_order_ingr }); + if (!!myfirstrec) { + if (!!myfirstrec._id && !myfirstrec.deleted) { + let fieldsv2 = { + invitante_username: aportador + }; + //Aggiorna record ! + const ris = await ListaIngresso.findByIdAndUpdate(myfirstrec._id.toString(), { $set: fieldsv2 }); + } + } } } else { res.send({ code: server_constants.RIS_CODE_ERR, msg: 'Non aggiornato' }); @@ -427,6 +445,33 @@ router.patch('/chval', authenticate, async (req, res) => { } } + if (mydata.table === 'listaingressos') { + if ('invitante_username' in fieldsvalue) { + // SERVE SE CI METTO LE MINUSCOLE/MAIUSCOLE SBAGLIATE in invitante_username! + const myuserfound = await User.findByUsername(idapp, fieldsvalue.invitante_username, false); + if (!!myuserfound) { + if (!!myuserfound._id && !myuserfound.deleted) { + fieldsvalue.invitante_username = await User.getUsernameById(idapp, myuserfound._id); + //Aggiorna record ! + const ris = await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }); + if (!!ris) { + /*let fieldsv2 = { + aportador_solidario: fieldsvalue.invitante_username + }; + + //Aggiorna record ! + await User.findByIdAndUpdate(myuserfound._id, { $set: fieldsv2 }); + */ + } + } + } else { + // res.send({ code: server_constants.RIS_CODE_ERR, msg: 'Non aggiornato' }); + // res.status(400).send(); + // return false; + } + } + } + if (tools.ModificheConsentite(mydata.table, fieldsvalue)) { let msg = ''; if (mydata.table === 'users') { @@ -463,12 +508,15 @@ router.patch('/chval', authenticate, async (req, res) => { tools.mylogserr('Error patch USER: ', e.message); res.status(400).send(); }) + + }); router.patch('/callfunz', authenticate, async (req, res) => { // const idapp = req.body.idapp; const id = req.body.data.id; const ind_order = req.body.data.ind_order; + const username = req.body.data.username; const idapp = req.body.idapp; const mydata = req.body.data; @@ -486,7 +534,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { } } - const myuser = await User.findOne({ idapp, ind_order }); + const myuser = await User.findOne({ idapp, username }); let rimosso = 0; @@ -518,8 +566,12 @@ router.patch('/callfunz', authenticate, async (req, res) => { } if (!!myuser) { + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // CONTROLLARE !!! + // ++Todo: Controllare che sia corretto che lo nascondo !!! + // Metti campo 'delete': true su ListaIngresso - olduseringresso = await ListaIngresso.findOne({ idapp, ind_order: myuser.ind_order }); + olduseringresso = await ListaIngresso.findOne({ idapp, ind_order: old_ind_order }); if (!!olduseringresso) { let fieldsvalue = { deleted: true @@ -553,13 +605,13 @@ router.patch('/callfunz', authenticate, async (req, res) => { } else { if (mydata.notifBot && !!navepersistente.link_chat) { // Send Notification to the BOT - let messaggio = 'Sei stato Spostato in una Nuova Nave !'; + let messaggio = tools.get__('SPOSTATO', req.user.lang); if (!!navepersistente.date_start) { - messaggio += tools.ACAPO + ' data di Partenza della Nave: ' + tools.getstrDateLong(navepersistente.date_start) + tools.ACAPO; + messaggio += tools.ACAPO + tools.get__('DATA_PART_NAVE', req.user.lang) + tools.getstrDateLong(navepersistente.date_start) + tools.ACAPO; } if (!!navepersistente.link_chat) { - messaggio += tools.ACAPO + 'Entra nella Gift Chat: ' + navepersistente.link_chat + tools.ACAPO; + messaggio += tools.ACAPO + tools.get__('ENTRA_GIFT_CHAT', req.user.lang) + navepersistente.link_chat + tools.ACAPO; } const myplacca = await Nave.getNavePos(idapp, navepersistente.riga, navepersistente.col); @@ -586,21 +638,28 @@ router.patch('/callfunz', authenticate, async (req, res) => { } } else if (mydata.myfunc === shared_consts.CallFunz.AGGIUNGI_NUOVO_IMBARCO) { // Ottieni il prossimo Numero di Tessitura - let num_tess = await Nave.getNextNumTess(idapp, ind_order); + //let num_tess = await Nave.getNextNumTess(idapp, ind_order); + const num_tess = 1; + /* let listaingr = await ListaIngresso.find({ idapp, ind_order }).sort({ num_tess: 1 }); const trovato = listaingr.find((rec) => rec.num_tess === num_tess); if (trovato) { num_tess = listaingr.slice(-1)[0].num_tess + 2; } + */ - ris = await ListaIngresso.addUserInListaIngresso(idapp, ind_order, myuser.lang, true, num_tess); + // metti l'invitante inizialmente a Te stesso ! + const invitante_username = req.body.data.invitante_username; - arrimbarchi = await ListaIngresso.findAllByIndOrder(idapp, ind_order); + ris = await ListaIngresso.addUserInListaIngresso(idapp, username, invitante_username, myuser.lang, true, true); + + arrimbarchi = await ListaIngresso.findAllByUsername(idapp, username); return res.send({ code: server_constants.RIS_CODE_OK, arrimbarchi }); + } else if (mydata.myfunc === shared_consts.CallFunz.CANCELLA_IMBARCO) { - await ListaIngresso.remove({ idapp, ind_order, num_tess: mydata.data.num_tess }); + await ListaIngresso.remove({ idapp, username, ind_order }); return res.send({ code: server_constants.RIS_CODE_OK }); diff --git a/src/server/router/site_router.js b/src/server/router/site_router.js index 4acec06..865bc23 100755 --- a/src/server/router/site_router.js +++ b/src/server/router/site_router.js @@ -17,7 +17,7 @@ const _ = require('lodash'); const { ObjectID } = require('mongodb'); -const { ExtraList } = require('../models/extralist'); +// const { ExtraList } = require('../models/extralist'); router.post('/load', async (req, res) => { const idapp = req.body.idapp; @@ -32,7 +32,7 @@ router.post('/load', async (req, res) => { num_teleg_attivo: await User.getUsersTelegramAttivo(idapp), num_teleg_pending: await User.getUsersTelegramPending(idapp), // num_qualificati: await User.getNumUsersQualified(idapp, 2), - num_requisiti: await User.getNumUsersQualified(idapp, 0), + // num_requisiti: await User.getNumUsersQualified(idapp, 0), num_modalita_pagamento: await User.getnumPaymentOk(idapp), num_part_zoom: await User.getUsersZoom(idapp), num_part_accepted: await User.getSaw_and_Accepted(idapp), diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index ba9e997..a9663b3 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -5,7 +5,7 @@ const { User } = require('../models/user'); const { Nave } = require('../models/nave'); const { NavePersistente } = require('../models/navepersistente'); const { ListaIngresso } = require('../models/listaingresso'); -const { ExtraList } = require('../models/extralist'); +// const { ExtraList } = require('../models/extralist'); const { ObjectID } = require('mongodb'); const sendemail = require('../sendemail'); @@ -126,16 +126,16 @@ router.post('/', async (req, res) => { // } const lastuser = await User.getLastUser(user.idapp); - const lastextra = await ExtraList.getLastUser(user.idapp); + // const lastextra = await ExtraList.getLastUser(user.idapp); let lastindorder = 0; if (lastuser) { lastindorder = lastuser.ind_order; } - if (lastextra) { - if (lastextra.ind_order > lastindorder) - lastindorder = lastextra.ind_order; - } + //if (lastextra) { + // if (lastextra.ind_order > lastindorder) + // lastindorder = lastextra.ind_order; + //} if (lastindorder > 0) user.ind_order = lastindorder + 1; @@ -210,9 +210,9 @@ router.post('/', async (req, res) => { user.perm = shared_consts.Permissions.Manager + shared_consts.Permissions.Admin; } - const useraportador = await ExtraList.findByIndOrder(user.idapp, user.aportador_solidario_ind_order); - if (useraportador) - user.aportador_solidario = useraportador.username; + // const useraportador = await ExtraList.findByIndOrder(user.idapp, user.aportador_solidario_ind_order); + // if (useraportador) + // user.aportador_solidario = useraportador.username; } } @@ -263,6 +263,10 @@ router.get('/:idapp/:username', async (req, res) => { var username = req.params.username; const idapp = req.params.idapp; + // if (username === 'pippo') { + // return res.status(200).send(); + // } + await User.findByUsername(idapp, username, false).then((user) => { if (!user) { return res.status(404).send(); @@ -406,7 +410,7 @@ router.post('/import_extralist', async (req, res) => { idapp = req.body.idapp; locale = req.body.locale; - const ris = await ExtraList.ImportData(locale, idapp, strdata); + // const ris = await ExtraList.ImportData(locale, idapp, strdata); console.log('ris', ris); res.send(ris); @@ -482,6 +486,51 @@ router.post('/dbop', authenticate, async (req, res) => { ris = { mystr }; } else if (mydata.dbop === 'visuNaviUtentiEliminati') { ris = await Nave.visuNaviUtentiEliminati(idapp); + } else if (mydata.dbop === 'creaTessituraeConv') { + ris = await ListaIngresso.creaTessituraeConv(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'convNaviTessinListaIngressoRec') { + let num = 0; + + const arrnavitess = await Nave.find({idapp, num_tess: { $gte: 3 } }); + + for (const recnave of arrnavitess) { + if (recnave.num_tess === 3 || recnave.num_tess === 5 || recnave.num_tess === 7) { + const ind_order = recnave.ind_order; + + // Prima controlla se ho già 2 record dello stesso ind_order, allora non lo faccio: + const arringr = await ListaIngresso.find({idapp, ind_order}); + let dafare = true; + if (arringr.length > 0) { + const arringrtest = await ListaIngresso.find({idapp, ind_order}).distinct('num_tess'); + if (arringr.length !== arringrtest.length){ + dafare = false; // Ci sono 2 o piu record! pertanto probabilmente l'ho già fatto! + } + } + if (dafare) { + const user = await User.findByOldOrder(idapp, ind_order); + + if (!!user) { + let note = recnave.num_tess; + // Crea record ListaIngresso + const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, user.username, user.username, user.lang, false, true, recnave.created, note, true); + + const fieldsvalue = { + ind_order: newrecingr.ind_order, + num_tess: 1, + }; + + // Aggiorna la nave con l'Ind_order nuovo e il num_tess a 1 + await Nave.findOneAndUpdate({ _id: recnave._id }, { $set: fieldsvalue }, { new: false }); + + num++; + } + } + } + } + + ris = { num }; + } else if (mydata.dbop === 'initListaIngresso') { // const aaa = await User.updateMany({ idapp }, { $set: { 'profile.nationality': 'IT' } }); @@ -595,10 +644,18 @@ router.post('/dbop', authenticate, async (req, res) => { let num = 0; lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1); + let last = 1; + if (lastrec) { + last = lastrec[0].ind_order; + } + if (!last) { + last = 1; + } + for (let ind = 0; ind < 100; ind++) { let myuser = new User(); myuser._id = new ObjectID(); - myuser.ind_order = lastrec[0].ind_order + ind + 1; + myuser.ind_order = last + ind + 1; myuser.idapp = idapp; myuser.password = "$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG"; myuser.lang = 'it'; @@ -659,7 +716,7 @@ router.post('/dbop', authenticate, async (req, res) => { const user = await User.getUserShortDataByUsername(idapp, mydata.username); if (user) { - arrnavi = await Nave.getArrPosizioniByIndOrder(idapp, user.ind_order); + arrnavi = await Nave.getArrPosizioniByUsername(idapp, user.username); for (let mynave of arrnavi) { mynave._doc.rec = await Nave.getNaveByRigaCol(idapp, mynave.riga, mynave.col); diff --git a/src/server/sendemail.js b/src/server/sendemail.js index d945ba9..8c4d86c 100755 --- a/src/server/sendemail.js +++ b/src/server/sendemail.js @@ -565,7 +565,7 @@ module.exports = { // console.log('-> Invio Email (', mynewsrec.numemail_sent, '/', mynewsrec.numemail_tot, ')'); const esito = this.sendEmail_base('newsletter/' + lang, mylocalsconf.emailto, mylocalsconf, mylocalsconf.dataemail.email_reply, smtpTransport); - if ((mynewsrec.numemail_sent % 50) === 0) { + if ((mynewsrec.numemail_sent % 100) === 0) { const msgproc = 'In Corso ' + mynewsrec.numemail_sent + ' / ' + mynewsrec.numemail_tot + ' Email inviate...'; await telegrambot.sendMsgTelegramToTheManagers(idapp, msgproc); } diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 3d305d7..5a33fa4 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -492,29 +492,33 @@ module.exports = { }, - sendMsgTelegramToTheManagers: async function (idapp, text) { - const usersmanagers = await User.getusersManagers(idapp); - // console.log('usersmanagers', usersmanagers); + sendMsgTelegramToTheManagers: async function (idapp, text, onlyintofile) { tools.writeManagersLog(text); - if (usersmanagers) { - for (const rec of usersmanagers) { - await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': ' + text, undefined, undefined, true); - await tools.snooze(300) + if (!onlyintofile) { + const usersmanagers = await User.getusersManagers(idapp); + if (usersmanagers) { + for (const rec of usersmanagers) { + await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': ' + text, undefined, undefined, true); + await tools.snooze(300) + } } } return true }, - getMsgByTipoMsg: function (mydata, lang, user) { + getMsgByTipoMsg: function (mydata, lang, user, sonosognatore) { if (!!mydata.msgextra) { return mydata.msgextra; } if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { - return printf(tools.gettranslate('SEND_LINK_CHAT_DONATORI', lang), user.name, mydata.msgpar1); + if (sonosognatore) + return printf(tools.gettranslate('SEND_LINK_CHAT_SOGNATORE', lang), user.name, mydata.navemediatore.riga + '.' + mydata.navemediatore.col, mydata.msgpar1); + else + return printf(tools.gettranslate('SEND_LINK_CHAT_DONATORI', lang), user.name, mydata.navemediatore.riga + '.' + mydata.navemediatore.col, mydata.msgpar1); } else if (mydata.tipomsg === tools.TipoMsg.SEND_MSG || mydata.tipomsg === tools.TipoMsg.SEND_MSG_SINGOLO) { let mymsg = ''; if (!!mydata.username_mitt) { @@ -533,19 +537,17 @@ module.exports = { try { const arrnavi = await Nave.getusersByNave(idapp, mydata.navemediatore); - // console.log('usersmanagers', usersmanagers); - tools.writeManagersLog('sendMsgTelegramToNave'); - if (arrnavi) { + tools.writeManagersLog('sendMsgTelegramToNave', mydata.navemediatore.riga + '.' + mydata.navemediatore.col); for (const nave of arrnavi) { const user = await User.findByIndOrder(idapp, nave.ind_order); if (!!user) { const lang = user.lang; const idteleg = user.profile.teleg_id; - const mymsg = this.getMsgByTipoMsg(mydata, lang, user); + const mymsg = this.getMsgByTipoMsg(mydata, lang, user, false); if (!!idteleg) { strout += '\n' + user.name + ' ' + user.surname + ':'; @@ -568,6 +570,31 @@ module.exports = { } } + if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { + + const usersognatore = await Nave.getSognatoreByRigaColMediatore(idapp, mydata.navemediatore); + + console.log('Sognatore: ', usersognatore.username); + + if (!!usersognatore) { + const lang = usersognatore.lang; + const idteleg = usersognatore.profile.teleg_id; + const mymsg = this.getMsgByTipoMsg(mydata, lang, usersognatore, true); + + // Invia Msg al Sognatore ! + if (mydata.inviareale) { + await this.sendMsgTelegramByIdTelegram(idapp, idteleg, mymsg, undefined, undefined, true); + await tools.snooze(300); + nummsgsent++; + strout += '\n' + usersognatore.name + ' ' + usersognatore.surname + ':'; + strout += ' -> MSG INVIATO'; + } else { + strout += ' (Pronto da Inviare)'; + } + } + + } + if (nummsgsent > 0) { if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { const fields_to_update = { @@ -887,8 +914,12 @@ class Telegram { rec.msgcodeprec = MsgBot.COME_STAI } else if (MsgBot.CHI_SONO_IO.includes(testo.replace('?', ''))) { risp = 'Su Telegram ti chiami "' + msg.chat.first_name + ' ' + msg.chat.last_name + '"\n'; + if (!!rec.user) { - risp += '\nSul sito ti sei registrato come:\n\n[N. ' + rec.user.ind_order + ']: ' + rec.user.name + ' ' + rec.user.surname + '\nUsername: ' + rec.user.username + '\n' + 'Email: ' + rec.user.email + '\nLang: ' + rec.user.lang; + const myrec = await User.getUserShortDataByUsername(this.idapp, rec.user.username); + risp += '\nSul sito ti sei registrato come:\n\n[N. ' + rec.user.ind_order + ']: ' + rec.user.name + ' ' + rec.user.surname + '\nUsername: ' + rec.user.username + '\n' + 'Email: ' + rec.user.email + '\nLang: ' + rec.user.lang + tools.ACAPO; + risp += 'Num Invitati: ' + myrec.numinvitati + tools.ACAPO; + risp += 'Num Invitati Attivi: ' + myrec.numinvitatiattivi + tools.ACAPO; } else { risp = 'Ancora non ti sei Attivato su AYNI BOT'; } @@ -965,6 +996,7 @@ class Telegram { if (contastiera) { keyboard = { + "parse_mode": "HTML", "reply_markup": { "resize_keyboard": true, "keyboard": await this.getKeyboard(id, undefined, this.getlang(msg)) @@ -1209,7 +1241,7 @@ class Telegram { tuttie9 = dashboard.myself.qualified && (numpersone >= 2) && invitati_attivi >= 2; - mystrnave = await Nave.getNaveByUser(this.idapp, user.ind_order, user.lang, true); + mystrnave = await Nave.getNaveByUser(this.idapp, user.username, user.lang, true); if (mystrnave === '' && tuttie9) { mystr += tools.gettranslate('NO_PROG', user.lang); @@ -1305,7 +1337,7 @@ class Telegram { if (!rec.user) return ""; - let ind_order_to_check = rec.user.ind_order; + let username_to_check = rec.user.username; let arrstringa = msg.text.split(" "); if (!!arrstringa) { @@ -1317,7 +1349,7 @@ class Telegram { } } - mystr = await Nave.getNaveByUser(this.idapp, ind_order_to_check, rec.user.lang, true); + mystr = await Nave.getNaveByUser(this.idapp, username_to_check, rec.user.lang, true); if (!!mystr) await this.sendMsg(msg.chat.id, mystr); @@ -1484,9 +1516,46 @@ class Telegram { } } + getlink(qualelink) { + + if (qualelink === 'website') { + return 'https://ayni.gifteconomy.app' + } else if (qualelink === 'biblio') { + return 'https://t.me/joinchat/AAAAAFMDe8b5lB1X7vOYng'; + } else if (qualelink === 'help') { + return 'https://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw'; + } else if (qualelink === 'faq') { + return 'https://ayni.gifteconomy.app/faq'; + } else if (qualelink === 'empower') { + return "ITA 🇮🇹: https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g" + tools.ACAPO + + "SLO 🇸🇮: https://t.me/aynislovenija" + tools.ACAPO + + "ESP 🇪🇸 - PRT 🇵🇹: https://t.me/joinchat/AL2qKBqJRuIEuc2FivgAzg" + tools.ACAPO + + "ENG 🇬🇧: https://t.me/joinchat/AL2qKBYX0yVvOJ6Ssf9hKg" + tools.ACAPO + + "FRA 🇫🇷: https://t.me/joinchat/Kz0wtxieJjzoC3L_DsrdZw"; + } + } + async menuAssistenza(msg) { - const mytext = tools.get__('TESTO_ASSISTENZA', this.getlang(msg)); + const sito = this.getlink('website'); + const empower = this.getlink('empower'); + const biblio = this.getlink('biblio'); + const faq = this.getlink('faq'); + + let help = ""; + let helpaperta = true; + if (tools.isMonToSat() && tools.isBetweenTwoTime('8:00:00', '19:50:00')) { + help = '✅ ' + this.getlink('help'); + } else { + help = "🔴 [ORA CHIUSA - NOW CLOSED]"; + helpaperta = false; + } + + let mytext = ""; + if (this.getlang(msg) === 'it') + mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, empower, biblio, faq, help); + else + mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, empower, biblio, help); let menu = null; const rec = this.getRecInMem(msg); @@ -1544,8 +1613,8 @@ class Telegram { if (conmsg) { await this.sendMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_ERRORE_USERNAME_NOT_FOUND'), MenuNoLogin); const lang = this.getlang(msg); - const textman = msg.chat.first_name + ' ' + msg.chat.last_name + ' sta tentando di autenticarsi con il BOT (lang=' + lang + ') (username che scrive: ' + msg.text + ') '; - await local_sendMsgTelegramToTheManagers(this.idapp, textman, msg); + // const textman = msg.chat.first_name + ' ' + msg.chat.last_name + ' sta tentando di autenticarsi con il BOT (lang=' + lang + ') (username che scrive: ' + msg.text + ') '; + // await local_sendMsgTelegramToTheManagers(this.idapp, textman, msg); rec.username_bo = ''; } } else { @@ -1615,7 +1684,7 @@ class Telegram { if (recuser) { let name = recuser.name; this.sendMsg(msg.from.id, printf(getstr(recuser.lang, 'MSG_VERIFY_OK'), name)); - local_sendMsgTelegramToTheManagers(this.idapp, recuser.name + ' ' + recuser.surname + ' si è Verificato a Telegram BOT! (lang=' + recuser.lang + ')' + emo.STARS, msg); + // local_sendMsgTelegramToTheManagers(this.idapp, recuser.name + ' ' + recuser.surname + ' si è Verificato a Telegram BOT! (lang=' + recuser.lang + ')' + emo.STARS, msg); } else { this.sendMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_ERR_UNKNOWN_VERIFY_CODE')); } @@ -1724,8 +1793,8 @@ class Telegram { } else if (destin === Destin.MSG_TO_NAVE) { invia = !await Nave.findDonatoreByNave(this.idapp, rec.extraparam); } else if (destin === Destin.SI_INVITATI_NO_7REQ_INVITATI) { - const numinvitati = await User.getnumInvitati(this.idapp, utente.username); - const numinvitatiattivi = await User.getnumInvitatiAttivi(this.idapp, utente.username); + const numinvitati = await ListaIngresso.getnumInvitati(this.idapp, utente.username); + const numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(this.idapp, utente.username); invia = (numinvitati >= 2) && (numinvitatiattivi < 2); } if (invia) { @@ -2021,6 +2090,7 @@ class Telegram { try { if (!form) { form = { + "parse_mode": "HTML", "message_id": msg_id, "reply_markup": { "resize_keyboard": true, @@ -2116,6 +2186,7 @@ class Telegram { async msgScegliMenu(msg) { // const rec = this.getRecInMem(msg); this._inviaMsg(msg.from.id, getstr(this.getlang(msg), 'MSG_SCEGLI_MENU'), { + "parse_mode": "HTML", "reply_markup": { "resize_keyboard": true, "keyboard": await this.getKeyboard(msg.from.id, undefined, this.getlang(msg)) diff --git a/src/server/tools/general.js b/src/server/tools/general.js index e0b8757..91f9aa8 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -51,7 +51,13 @@ textlang = { "Nuova Registrazione": "Nuova Registrazione", "Effettuata una Nuova Registrazione": "Effettuata una Nuova Registrazione", "partecipanti": "partecipanti", - 'TESTO_ASSISTENZA': "Per entrare nel Sito AYNI:\nhttps://ayni.gifteconomy.app\n\nChat AYNI - EMPOWER: Entra ⛩ nella nostra Community chat:\n ITA 🇮🇹: https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g\n SLO 🇸🇮: https://t.me/aynislovenija\n ESP 🇪🇸 - PRT 🇵🇹: https://t.me/joinchat/AL2qKBqJRuIEuc2FivgAzg\n ENG 🇬🇧: https://t.me/joinchat/AL2qKBYX0yVvOJ6Ssf9hKg\n FRA 🇫🇷: https://t.me/joinchat/Kz0wtxieJjzoC3L_DsrdZw \n\nChat AYNI-BIBLIO: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nPER AIUTO: Leggi le Domande più Frequenti:\nhttps://ayni.gifteconomy.app/faq\n\nChat di Supporto 'AYNI - HELP'\nDa Lunedì al Sabato (8:00 - 20:00)\nhttps://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw\n1 - Fai la tua domanda e chiedi assistenza.\n2 - Dopo aver ricevuto aiuto esci dalla chat.\nPotrai rientrare ogni qualvolta ne avrai la necessità.", + 'TESTO_ASSISTENZA': "👉 Per entrare nel Sito AYNI\n\n" + + "👉 Hai dimenticato la password?\n\n" + + "👉 Chat AYNI - EMPOWER: Entra ⛩ nella nostra Community chat\n%s\n\n" + + "👉 Canale News e Informazioni AYNI-BIBLIO\n\n" + + "👉 PER AIUTO: Leggi le Domande più Frequenti:\n%s\n\n" + + "Chat di Supporto 'AYNI - HELP'\nDa Lunedì al Sabato (8:00 - 20:00)\n%s\n" + + "1 - Fai la tua domanda e chiedi assistenza.\n2 - Dopo aver ricevuto aiuto Esci dalla chat.\nPotrai rientrare ogni qualvolta ne avrai la necessità.", 'BENVENUTO': "Benvenuto", 'TUE_NAVI': "Ecco le tue Navi programmate", 'HAI_I_7_REQUISITI': 'PRIMI PASSI OK!\nHai i Primi 7 Requisiti per Entrare nella Lista d\'Imbarco!', @@ -85,9 +91,12 @@ textlang = { 'SCEGLI_VOCE': 'scegli una voce:', 'INVITATI_LISTA': 'I Tuoi Invitati (in verde con almeno i primi 7 Requisiti)', 'CIAO': 'Ciao', - 'ADDED_TOLISTAINGRESSO': 'Sei stato aggiunto alla Lista delle persone che entreranno nella Lista D\'Imbarco !\nNei prossimi giorni riceverai un messaggio quando la tua Nave partirà.', + 'ADDED_TOLISTAINGRESSO': 'Complimenti ! Hai completato i 7 Passi!🎊\nSei stato aggiunto alla Lista delle persone che entreranno nella Lista D\'Imbarco !\nNei prossimi giorni riceverai un messaggio quando la tua Nave partirà.', 'NO_PROG': 'Attualmente non sei ancora dentro alla Lista d\'Imbarco!', - 'SEND_LINK_CHAT_DONATORI': 'Ciao %s!\nLa tua NAVE sta finalmente Salpando!\nEntra nella Gift Chat cliccando qui: %s', + 'SEND_LINK_CHAT_DONATORI': 'Ciao %s!\nLa tua NAVE sta finalmente Salpando!\nEntra nella Gift Chat della nave {%s} cliccando qui: %s', + 'SEND_LINK_CHAT_SOGNATORE': 'Ciao %s!\nOggi Diventi Sognatore !!! 🎊🎊🎊 Entra nella Gift Chat della nave {%s} cliccando qui: %s', + 'ENTRA_GIFT_CHAT': 'Entra nella Gift Chat', + 'DATA_PART_NAVE': 'data di Partenza della Nave:', 'SOGNATORE': 'SOGNATORE', 'MEDIATORE': 'MEDIATORE', 'DONATORI': 'DONATORI', @@ -96,7 +105,8 @@ textlang = { 'Doni Effettuati': 'Doni Effettuati', 'Tutor che affianchèra il Mediatore': 'Tutor che affianchèra il Mediatore', 'Giorno di Apertura GIFT CHAT': 'Giorno di Apertura GIFT CHAT', - 'Giorno in cui Inviare il DONO': 'Giorno in cui Inviare il DONO', + 'Giorno in cui Inviare il DONO': 'Hai 4 giorni di tempo per inviare il tuo dono. Giorno di Chiusura:', + 'SPOSTATO': 'Sei stato Spostato in una Nuova Nave !', 'Note': 'Note', 'TEMPORANEA': 'TEMPORANEA', 'NAVE': 'NAVE', @@ -107,7 +117,14 @@ textlang = { "Nuova Registrazione": "Nova Registracija", "Effettuata una Nuova Registrazione": "Izpelji novo Registracijo", "partecipanti": "Udeleženci", - 'TESTO_ASSISTENZA': "Za vstop na spletno stran:\nhttps://ayni.gifteconomy.app\n\nSi pozabil geslo za vstop na stran?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\nKlepet AYNI BOT (questa):\nhttps://t.me/notevoleaynibot\n\nKlepet AYNI - EMPOWER: Vstopi ⛩ v našo Skupnost klepet:\n ITA 🇮🇹: https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g\n SLO 🇸🇮: https://t.me/aynislovenija\n ESP 🇪🇸 - PRT 🇵🇹: https://t.me/joinchat/AL2qKBqJRuIEuc2FivgAzg\n ENG 🇬🇧: https://t.me/joinchat/AL2qKBYX0yVvOJ6Ssf9hKg\n FRA 🇫🇷: https://t.me/joinchat/Kz0wtxieJjzoC3L_DsrdZw \n\nKlepet AYNI-BIBLIO: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nKlepet za Pomoč in Suport: 'AYNI - HELP'\nhttps://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw\n1 - Postavi svoje vprašanje in prosi za asistenco.\n2 - KO si sprejel pomoč, izstopi iz klepeta.\n Vstopil boš lahko vedno, ko boš potreboval pomoč.", + 'TESTO_ASSISTENZA': "Za vstop na spletno stran:\n%s\n\n" + + "Si pozabil geslo za vstop na stran?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n" + + "Klepet AYNI BOT (questa):\nhttps://t.me/notevoleaynibot\n\n" + + "Klepet AYNI - EMPOWER: Vstopi ⛩ v našo Skupnost klepet:\n%s\n\n" + + "Canal News AYNI-BIBLIO:\n%s\n\n" + + "Klepet za Pomoč in Suport: 'AYNI - HELP'\n%s\n" + + "1 - Postavi svoje vprašanje in prosi za asistenco.\n2 - KO si sprejel pomoč, izstopi iz klepeta.\n " + + "Vstopil boš lahko vedno, ko boš potreboval pomoč.", 'BENVENUTO': "Dobrodošel", 'TUE_NAVI': "Tvoje programirane Ladje", 'HAI_I_7_REQUISITI': 'PRVI KORAKI OK!\nIzpolnjuješ Prvih 7 Zahtev za vstop na Listo d\'Vkrcanje!', @@ -144,6 +161,9 @@ textlang = { 'ADDED_TOLISTAINGRESSO': 'Si bil dodan na Seznam oseb, ki bodo vstopile v Listo D\'Vkrcanje !', 'NO_PROG': 'Trenutno še nisi na Listi d\'Vkrcanja!', 'SEND_LINK_CHAT_DONATORI': 'Zdravo %s!\nTvoja LADJA bo končno Izplula!\nVstopi v Darilni (Gift) klepet s klikom tu: %s', + 'SEND_LINK_CHAT_SOGNATORE': 'Zdravo %s!\nDanes Postajaš Sanjač !!! 🎊🎊🎊 Vstopi v Darilni Klepet {%s} s klikom tu: %s', + 'ENTRA_GIFT_CHAT': 'Vstopi v Darilni Klepet', + 'DATA_PART_NAVE': 'Datum odhoda ladje:', 'SOGNATORE': 'Sanjača', 'MEDIATORE': 'MEDIATOR', 'DONATORI': 'DONATOR', @@ -153,6 +173,7 @@ textlang = { 'Tutor che affianchèra il Mediatore': 'Tutor, ki bo podpiral Mediatorja', 'Giorno di Apertura GIFT CHAT': 'Dan odpiranja GIFT CHAT', 'Giorno in cui Inviare il DONO': 'Dan za pošiljanje DARILA', + 'SPOSTATO': 'Prestavljen si v Novo Ladjico !', 'Note': 'Opombe', 'TEMPORANEA': 'ZAČASNA', 'NAVE': 'LADJE', @@ -163,7 +184,12 @@ textlang = { "Nuova Registrazione": "Nuevo Registro", "Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro", "partecipanti": "participantes", - 'TESTO_ASSISTENZA': "Para entrar en el sitio de AYNI:\nhttps://ayni.gifteconomy.app\n\n¿Olvidó su contraseña para acceder al sitio?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\nChat AYNI BOT (este):\nhttps://t.me/notevoleaynibot\n\nChat AYNI - EMPOWER: Entra en ⛩ en nuestra comunidad de chat:\n ITA 🇮🇹: https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g\n SLO 🇸🇮: https://t.me/aynislovenija\n ESP 🇪🇸 - PRT 🇵🇹: https://t.me/joinchat/AL2qKBqJRuIEuc2FivgAzg\n ENG 🇬🇧: https://t.me/joinchat/AL2qKBYX0yVvOJ6Ssf9hKg\n FRA 🇫🇷: https://t.me/joinchat/Kz0wtxieJjzoC3L_DsrdZw \n\nChat de la AYNI-BIBLIO: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nChat de ayuda y soporte: 'AYNI - HELP'\nDe lunes a sábado (8:00 - 21:00)\nhttps://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw\n1 - Haga su pregunta y pida ayuda.\n2 - Después de que consigas ayuda, sal de la sala de chat.\nPuedes volver cuando necesites ayuda..", + 'TESTO_ASSISTENZA': "Para entrar en el sitio de AYNI:\n%s\n\n" + + "¿Olvidó su contraseña para acceder al sitio?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n" + + "Chat AYNI BOT (este):\nhttps://t.me/notevoleaynibot\n\n" + + "Chat AYNI - EMPOWER: Entra en ⛩ en nuestra comunidad de chat:\n%s\n\n" + + "Chat de ayuda y soporte: 'AYNI - HELP'\nDe lunes a sábado (8:00 - 21:00)\n%s\n" + + "1 - Haga su pregunta y pida ayuda.\n2 - Después de que consigas ayuda, sal de la sala de chat.\nPuedes volver cuando necesites ayuda..", 'BENVENUTO': "Bienvenido", 'TUE_NAVI': "Aquí están sus naves programadas", 'HAI_I_7_REQUISITI': '¡LOS PRIMEROS PASOS ESTÁN BIEN!\nTiene los primeros 7 requisitos para entrar en la lista de embarque!', @@ -200,6 +226,9 @@ textlang = { 'ADDED_TOLISTAINGRESSO': 'Has sido añadido a la lista de personas que entrarán en Lista de embarque!', 'NO_PROG': 'Actualmente no está en la lista de embarque.!', 'SEND_LINK_CHAT_DONATORI': 'Hola %s!\n¡Tu barco por fin está navegando!\nEntra en el Gift Chat haciendo clic aquí: %s', + 'SEND_LINK_CHAT_SOGNATORE': '¡Hola!\n¡Hoy te conviertes en un soñador! 🎊🎊🎊 Entre en el Chat de Regalos de la nave {%s} haciendo clic aquí: %s', + 'ENTRA_GIFT_CHAT': 'Entre en el Chat de Regalos', + 'DATA_PART_NAVE': 'fecha de salida de la nave:', 'SOGNATORE': 'SOÑADOR', 'MEDIATORE': 'MEDIATOR', 'DONATORI': 'DONANTES', @@ -209,6 +238,7 @@ textlang = { 'Tutor che affianchèra il Mediatore': 'Tutor de apoyo al Donante', 'Giorno di Apertura GIFT CHAT': 'Día de apertura GIFT CHAT', 'Giorno in cui Inviare il DONO': 'Día en el que enviar el REGALO', + 'SPOSTATO': 'Has sido trasladado a una nueva nave !', 'Note': 'Notas', 'TEMPORANEA': 'TEMPORAL', 'NAVE': 'NAVE', @@ -216,7 +246,12 @@ textlang = { }, enUs: { "partecipanti": "participants", - 'TESTO_ASSISTENZA': "To enter the AYNI Site:\nhttps://ayni.gifteconomy.app\n\nForgot your password to access the site?\nhttps://ayni.gifteconomy.app/requestresetpwd\nChat AYNI BOT (this one):\nhttps://t.me/notevoleaynibot\n\nChat AYNI - EMPOWER: Enter ⛩ into our chat community:\nITA 🇮🇹: https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g\n SLO 🇸🇮: https://t.me/aynislovenija\n ESP 🇪🇸 - PRT 🇵🇹: https://t.me/joinchat/AL2qKBqJRuIEuc2FivgAzg\n ENG 🇬🇧: https://t.me/joinchat/AL2qKBYX0yVvOJ6Ssf9hKg\n FRA 🇫🇷: https://t.me/joinchat/Kz0wtxieJjzoC3L_DsrdZw \n\nChat AYNI-BIBLIO: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nHelp and Support Chat: 'AYNI - HELP'.\nMonday to Saturday (8:00 - 20:00)\nhttps://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw\n1 - Ask your question and ask for assistance.\n2 - After receiving help, exit the chat.\nYou can come back whenever you need help.", + 'TESTO_ASSISTENZA': "To enter the AYNI Site:\n%s\n\nForgot your password to access the site?\n" + + "https://ayni.gifteconomy.app/requestresetpwd\nChat AYNI BOT (this one):\nhttps://t.me/notevoleaynibot\n\n" + + "Chat AYNI - EMPOWER: Enter ⛩ into our chat community:\n%s\n\n" + + "Canale News AYNI-BIBLIO:\n%s\n\n" + + "Help and Support Chat: 'AYNI - HELP'.\nMonday to Saturday (8:00 - 20:00)\n%s\n" + + "1 - Ask your question and ask for assistance.\n2 - After receiving help, exit the chat.\nYou can come back whenever you need help.", 'BENVENUTO': "Welcome", 'TUE_NAVI': "Here are your programmed ships", 'HAI_I_7_REQUISITI': 'FIRST STEPS OK!\nYou have the First 7 Requirements to Enter the Boarding List!', @@ -253,6 +288,9 @@ textlang = { 'ADDED_TOLISTAINGRESSO': 'You have been added to the List of people who will enter the Boarding List!', 'NO_PROG': 'You are not currently on the boarding list.!', 'SEND_LINK_CHAT_DONATORI': 'Hi %s!\nYour ship is finally sailing!\nEnter the Gift Chat by clicking here: %s', + 'SEND_LINK_CHAT_SOGNATORE': 'Hello %s!\nToday you become a Dreamer! 🎊🎊🎊 Enter the ship\'s Gift Chat {%s} by clicking here: %s', + 'ENTRA_GIFT_CHAT': 'Enter the ship\'s Gift Chat', + 'DATA_PART_NAVE': 'date of departure of the ship:', 'SOGNATORE': 'DREAMER', 'MEDIATORE': 'MEDIATOR', 'DONATORI': 'DONOR', @@ -262,6 +300,7 @@ textlang = { 'Tutor che affianchèra il Mediatore': 'Tutor supporting the Mediator', 'Giorno di Apertura GIFT CHAT': 'Opening Day GIFT CHAT', 'Giorno in cui Inviare il DONO': 'Day on which to send the Gift', + 'SPOSTATO': 'You\'ve been moved to a New Ship !', 'Note': 'Note', 'TEMPORANEA': 'TEMPORARY', 'NAVE': 'SHIP', @@ -272,7 +311,13 @@ textlang = { "Nuova Registrazione": "Nouvelle inscription", "Effettuata una Nuova Registrazione": "Un nouvel enregistrement a été effectué", "partecipanti": "participants", - 'TESTO_ASSISTENZA': "Pour entrer sur le site AYNI:\nhttps://ayni.gifteconomy.app\n\nVous avez oublié votre mot de passe pour accéder au site ?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\nChat AYNI BOT (ce):\nhttps://t.me/notevoleaynibot\n\nChat AYNI - EMPOWER : Entrez ⛩ dans notre Community chat:\nITA 🇮🇹: https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g\n SLO 🇸🇮: https://t.me/aynislovenija\n ESP 🇪🇸 - PRT 🇵🇹: https://t.me/joinchat/AL2qKBqJRuIEuc2FivgAzg\n ENG 🇬🇧: https://t.me/joinchat/AL2qKBYX0yVvOJ6Ssf9hKg\n FRA 🇫🇷: https://t.me/joinchat/Kz0wtxieJjzoC3L_DsrdZw \n\nChat AYNI-BIBLIO: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nChat d’Aide et de Support: 'AYNI - HELP'\nDu lundi au samedi (8:00 - 20:00)\nhttps://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw\n1 - Posez votre question et demandez d’être assisté.\n2 - Après avoir reçu l’aide, quittez le groupe .\\n Vous pourrez y entrer chaque fois qu’il vous sera nécessaire.", + 'TESTO_ASSISTENZA': "Pour entrer sur le site AYNI:\n%s\n\n" + + "Vous avez oublié votre mot de passe pour accéder au site ?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n" + + "Chat AYNI BOT (ce):\nhttps://t.me/notevoleaynibot\n\n" + + "Chat AYNI - EMPOWER : Entrez ⛩ dans notre Community chat:\n%s\n\n" + + "Canale News AYNI-BIBLIO:\n%s\n\n" + + "Chat d’Aide et de Support: 'AYNI - HELP'\nDu lundi au samedi (8:00 - 20:00)\n%s\n" + + "1 - Posez votre question et demandez d’être assisté.\n2 - Après avoir reçu l’aide, quittez le groupe.\nVous pourrez y entrer chaque fois qu’il vous sera nécessaire.", 'BENVENUTO': "Bienvenue", 'TUE_NAVI': "Voici vos navires programmés", 'HAI_I_7_REQUISITI': 'PREMIÈRES ÉTAPES OK!\nvous avez les 7 premiers Requis pour Entrer dans la liste d\'embarquement!', @@ -309,6 +354,9 @@ textlang = { 'ADDED_TOLISTAINGRESSO': 'Vous avez été ajouté à la liste d\'embarquement !', 'NO_PROG': 'Vous n\'êtes pas encore sur la liste d\'embarquement.!', 'SEND_LINK_CHAT_DONATORI': 'Salut %s!\nVotre SHIP prend enfin la mer.!\nEntrez dans le Chat Cadeau en cliquant ici: %s', + 'SEND_LINK_CHAT_SOGNATORE': 'Bonjour %s !\nAujourd\'hui, vous devenez un Rêveur ! 🎊🎊🎊 Entrez dans le chat des cadeaux du navire {%s} en cliquant ici : %s', + 'ENTRA_GIFT_CHAT': 'Entrez dans le chat des cadeaux', + 'DATA_PART_NAVE': 'la date de départ du navire:', 'SOGNATORE': 'Rêveur', 'MEDIATORE': 'Médiateur', 'DONATORI': 'DONATEUR', @@ -318,6 +366,7 @@ textlang = { 'Tutor che affianchèra il Mediatore': 'Le tuteur qui soutient le Mediateur', 'Giorno di Apertura GIFT CHAT': 'Jour d\'ouverture GIFT CHAT', 'Giorno in cui Inviare il DONO': 'Envoyer le jour il DONO', + 'SPOSTATO': 'Vous avez été transféré sur un nouveau navire !', 'Note': 'Notes', 'TEMPORANEA': 'TEMPORAIRE', 'NAVE': 'NAVIRE', @@ -328,7 +377,13 @@ textlang = { "Nuova Registrazione": "Novo Registo", "Effettuata una Nuova Registrazione": "Foi efectuado um novo registo", "partecipanti": "participantes", - 'TESTO_ASSISTENZA': "Para entrar no site do AYNI:\nhttps://ayni.gifteconomy.app\n\nEsqueceu sua senha para acessar o site?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\nChat AYNI BOT (isto):\nhttps://t.me/notevoleaynibot\n\nChat AYNI - EMPOWER: Entrar em ⛩ na nossa comunidade de chat:ITA 🇮🇹: https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g\n SLO 🇸🇮: https://t.me/aynislovenija\n ESP 🇪🇸 - PRT 🇵🇹: https://t.me/joinchat/AL2qKBqJRuIEuc2FivgAzg\n ENG 🇬🇧: https://t.me/joinchat/AL2qKBYX0yVvOJ6Ssf9hKg\n FRA 🇫🇷: https://t.me/joinchat/Kz0wtxieJjzoC3L_DsrdZw \n\nChat AYNI-BIBLIO: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nChat de Ajuda e Suporte: 'AYNI - HELP'.\nDe segunda a sábado (8:00 - 20:00 ITALY)\nhttps://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw\n1 - Faça a sua pergunta e peça ajuda.\n2 - Depois de receber ajuda, saia do chat.\nPode voltar sempre que precisar de o fazer..", + 'TESTO_ASSISTENZA': "Para entrar no site do AYNI:\n%s\n\n" + + "Esqueceu sua senha para acessar o site?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n" + + "Chat AYNI BOT (isto):\nhttps://t.me/notevoleaynibot\n\n" + + "Chat AYNI - EMPOWER: Entrar em ⛩ na nossa comunidade de chat:%s\n\n" + + "Canale News AYNI-BIBLIO:\n%s\n\n" + + "Chat de Ajuda e Suporte: 'AYNI - HELP'.\nDe segunda a sábado (8:00 - 20:00 ITALY)\n%s\n" + + "1 - Faça a sua pergunta e peça ajuda.\n2 - Depois de receber ajuda, saia do chat.\nPode voltar sempre que precisar de o fazer..", 'BENVENUTO': "Bem-vindo", 'TUE_NAVI': "Aqui estão os seus navios programados", 'HAI_I_7_REQUISITI': 'PRIMEIROS PASSOS OK!\nVocê tem os 7 primeiros requisitos para entrar na lista de embarque!', @@ -365,6 +420,9 @@ textlang = { 'ADDED_TOLISTAINGRESSO': 'Foi acrescentado à Lista de Embarque !', 'NO_PROG': 'Actualmente, ainda não consta da lista de embarque.!', 'SEND_LINK_CHAT_DONATORI': 'Olà %s!\nO seu SHIP está finalmente a zarpar.!\nEntre no Gift Chat, clicando aqui: %s', + 'SEND_LINK_CHAT_SOGNATORE': 'Olá %s!\nHoje você se torna um sonhador! 🎊🎊🎊 Entre no Gift Chat do navio {%s} clicando aqui: %s', + 'ENTRA_GIFT_CHAT': 'Entre no Gift Chat do navio', + 'DATA_PART_NAVE': 'data de partida do navio:', 'SOGNATORE': 'SONHEIROS', 'MEDIATORE': 'MEDIATOR', 'DONATORI': 'DONATORES', @@ -374,6 +432,7 @@ textlang = { 'Tutor che affianchèra il Mediatore': 'Tutor que apoia o Mediator', 'Giorno di Apertura GIFT CHAT': 'Dia de Abertura GIFT CHAT', 'Giorno in cui Inviare il DONO': 'Dia em que enviar o REGALO', + 'SPOSTATO': 'Você foi transferido para um novo navio !', 'Note': 'Notas', 'TEMPORANEA': 'TEMPORÁRIO', 'NAVE': 'NAVE', @@ -1072,6 +1131,47 @@ module.exports = { return date; }, + isMonToSat() { + const dayOfWeek = new Date(new Date()).getDay(); + return dayOfWeek >= 1 && dayOfWeek <= 6 + }, + + // var startTime = '15:10:10'; + // var endTime = '22:30:00'; + isBetweenTwoTime(startTime, endTime) { + + currentDate = new Date(); + + startDate = new Date(currentDate.getTime()); + startDate.setHours(startTime.split(":")[0]); + startDate.setMinutes(startTime.split(":")[1]); + startDate.setSeconds(startTime.split(":")[2]); + + endDate = new Date(currentDate.getTime()); + endDate.setHours(endTime.split(":")[0]); + endDate.setMinutes(endTime.split(":")[1]); + endDate.setSeconds(endTime.split(":")[2]); + + + valid = startDate < currentDate && endDate > currentDate; + + return valid; + }, + + getlimiti(mypos) { + + if (mypos.col < 0) { + mypos.col = 0; + } + + if (mypos.riga < 0) { + mypos.riga = 0; + mypos.col = 0; + } + + return mypos; + }, + getRigaColByPosUp(mypos) { if (mypos.numup > 0) { mypos.riga = mypos.riga - mypos.numup; @@ -1089,6 +1189,34 @@ module.exports = { } }, + getRigaColGenerica(idapp, riga, col, numup) { + mypos = { + idapp, + riga, + col, + numup + }; + + if (idapp === tools.AYNI) { + this.getRigaColByPosUp(mypos); + ris = this.getlimiti(mypos); + } + + return ris; + }, + + getRigaColSognatoreByDonatore(idapp, riga, col) { + return this.getRigaColGenerica(idapp, riga, col, 6); + }, + + getRigaColMediatoreByFuoco(idapp, riga, col) { + return this.getRigaColGenerica(idapp, riga, col, 3); + }, + + getRigaColSognatoreByMediatore(idapp, riga, col) { + return this.getRigaColGenerica(idapp, riga, col, 3); + }, + appendLeadingZeroes(n) { if (n <= 9) { return "0" + n; @@ -1375,6 +1503,15 @@ module.exports = { } } + if (table === 'listaingressos') { + if ('invitante_username' in fieldsvalue) { + return true; + } + if ('username' in fieldsvalue) { + return true; + } + } + if (table === 'navi') { if ('date_made_gift' in fieldsvalue) { return true; diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index b65bc3d..48965d8 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -49,7 +49,7 @@ module.exports = { }, fieldsUserToChange() { - return ['_id', 'username', 'email', 'name', 'surname', 'perm', 'date_reg', 'verified_email', 'ipaddr', 'lasttimeonline', 'profile', 'calcstat', 'news_on', 'aportador_solidario', 'made_gift', 'ind_order', 'numinvitati', 'numinvitatiattivi', 'qualified'] + return ['_id', 'index', 'username', 'email', 'name', 'surname', 'perm', 'date_reg', 'verified_email', 'ipaddr', 'lasttimeonline', 'profile', 'calcstat', 'news_on', 'aportador_solidario', 'made_gift', 'ind_order', 'old_order', 'numinvitati', 'numinvitatiattivi', 'qualified'] } }; From c6acadb3e6e0f0bbd74e11812349c180d65e7cf9 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Mon, 11 May 2020 22:43:14 +0200 Subject: [PATCH 02/14] Grosse Modifiche Completate ! --- docs/passi.txt | 19 ++- src/server/models/listaingresso.js | 19 ++- src/server/models/nave.js | 60 +++----- src/server/models/navepersistente.js | 9 +- src/server/models/user.js | 91 +++++++----- src/server/router/dashboard_router.js | 12 +- src/server/router/index_router.js | 194 +++++++++++++++----------- src/server/router/users_router.js | 27 +--- src/server/telegram/telegrambot.js | 22 +-- src/server/tools/general.js | 45 +++--- 10 files changed, 269 insertions(+), 229 deletions(-) diff --git a/docs/passi.txt b/docs/passi.txt index db45952..9dc6c40 100644 --- a/docs/passi.txt +++ b/docs/passi.txt @@ -4,13 +4,17 @@ AGGIORNARE: // ++Todo: DA FARE: TESTARE -> inviare il msg anche al Sognatore della Gift Chat -- Aggiornare il titolo della Gift Chat (da 5/5 a 12/5) -- Aggiornare il testo sulla Placca (Data Inizio e Data Fine Doni) +X - Aggiornare il titolo della Gift Chat (da 5/5 a 12/5) +X - Aggiornare il testo sulla Placca (Data Inizio e Data Fine Doni) + + +// ++Todo: SISTEMARE: + // ++Todo: TOGLIERE! -- AGGIONARE AMBIENTE DI TEST +x- AGGIONARE AMBIENTE DI TEST - ESEGUIRE LA CONVERSIONE 1 E 2 ! - CHECK getProssimiInLista @@ -20,10 +24,10 @@ X - CONTROLLARE arrIdTelegramUsers - TESTARE AGGIUNGI VIAGGIO -- Accorpare tutti i sotto account, in 1 unico ! - - Nel campo note, metterci l'username vecchio. +x- Accorpare tutti i sotto account, in 1 unico ! +x - Nel campo note, metterci l'username vecchio. - - Sistemare le navi con num_tess === 4 : indorder=0 e 46 : +x - Sistemare le navi con num_tess === 4 : indorder=0 e 46 : Prendere quelli del num_tess === 3 e SOSTITUISCI ind_order del num_Tess = 4 con ind_order di num_tess = 3 ------------- @@ -52,3 +56,6 @@ SOSTITUISCI: TRADURRE: 'Giorno in cui Inviare il DONO': 'Hai 4 giorni di tempo per inviare il tuo dono. Giorno di Chiusura:', + + +- Mettere le bandierine nella lista Zoom (su AYNI BOT). diff --git a/src/server/models/listaingresso.js b/src/server/models/listaingresso.js index e6d9d61..dec3af6 100755 --- a/src/server/models/listaingresso.js +++ b/src/server/models/listaingresso.js @@ -171,7 +171,7 @@ ListaIngressoSchema.statics.deleteUserInListaIngresso = async function (idapp, u }; -ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, username, invitante_username, lang, addednowreal, nuovo, dateins, note, added) { +ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, username, invitante_username, lang, addednowreal, nuovo, dateins, note, added, opt) { const ListaIngresso = this; const { User } = require('./user'); @@ -214,6 +214,16 @@ ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, user const nome = await User.getNameSurnameByUsername(idapp, username); msgtext = '🔵 ' + nome + ' (' + username + ') ' + tools.gettranslate('ADDED_TOLISTAINGRESSO', lang); await telegrambot.sendMsgTelegram(idapp, username, msgtext, true); // Anche a STAFF + + if (!!opt) { + if (!!opt.sendmsgtoinvitante) { + if (opt.sendmsgtoinvitante) { + const nome = await User.getNameSurnameByUsername(idapp, invitante_username); + // msgtext = '🔵 ' + nome + ' (' + username + ') ' + tools.gettranslate('ADDED_TOLISTAINGRESSO', lang); + // await telegrambot.sendMsgTelegram(idapp, username, msgtext, true); // Anche a STAFF + } + } + } } } return ris; @@ -405,8 +415,7 @@ ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuov for (const rec of arrlista) { - // ++Todo: TOGLIERE! - if (false) { + if (true) { rec.numNaviEntrato = await Nave.getnumNaviByUsername(idapp, rec.username); rec.numinvitati = await ListaIngresso.getnumInvitati(idapp, rec.username); @@ -602,10 +611,6 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { } }, { new: false }); - - // Crea Record ListaIngresso - // const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, myuser.username, invitante_username, myuser.lang, false, true, myuser.date_reg, note, added); - // Assegna l'Invitante agli Invitati ! trova tutti gli invitati che hanno questo username const arrinvitati = await User.find({ idapp, aportador_solidario: myuser.username }, { username: 1 }); for (const invitato of arrinvitati) { diff --git a/src/server/models/nave.js b/src/server/models/nave.js index 24f9c34..22931f3 100755 --- a/src/server/models/nave.js +++ b/src/server/models/nave.js @@ -10,6 +10,8 @@ const { User } = require('./user'); const { ObjectID } = require('mongodb'); +const printf = require('util').format; + const shared_consts = require('../tools/shared_nodejs'); mongoose.Promise = global.Promise; @@ -81,6 +83,7 @@ NaveSchema.statics.getTotInLista = async function (idapp) { NaveSchema.statics.findByIndOrder = function (idapp, ind_order) { const Nave = this; + try { return Nave.findOne({ 'idapp': idapp, @@ -297,7 +300,6 @@ NaveSchema.statics.findRecByRigaColParent = async function (idapp, riga, col, nu myrigacol.riga = lastrec.riga; myrigacol.col = lastrec.col; } else { - //lastrec = await User.findByIndOrder(idapp, 0); lastrec = await Nave.findGeneric({ idapp, riga: 0, col: 0 }); break; } @@ -306,7 +308,6 @@ NaveSchema.statics.findRecByRigaColParent = async function (idapp, riga, col, nu } if (!lastrec) { - // return await User.findByIndOrder(idapp, 0); return await Nave.findGeneric({ idapp, riga: 0, col: 0 }); } @@ -452,13 +453,13 @@ function getQueryProj(myfilter) { } }, { - $unwind: "$mylista" + $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$mylista", 0 ] }, "$$ROOT" ] } } }, { $lookup: { from: "users", as: "user", - let: {username: '$mylista.username' }, + let: {username: '$username' }, pipeline: [ { $match: { @@ -793,19 +794,22 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in if (!!recnavepersistente.tutor_namesurname) data += '👤 ' + tools.get__('Tutor che affianchèra il Mediatore', lang) + ': "' + recnavepersistente.tutor_namesurname + '"' + tools.ACAPO; - data += '💬 ' + tools.get__('Giorno di Apertura GIFT CHAT', lang) + ': ' + tools.getstrDateLong(recnavepersistente.date_gift_chat_open, lang) + tools.ACAPO; + data += '💬 ' + printf(tools.get__('APERTURA_CHIUSURA_GIFT_CHAT', lang), tools.getstrDateLong(recnavepersistente.date_gift_chat_open, lang), tools.getstrDateLong(recnavepersistente.date_start, lang)) + tools.ACAPO; - data += '🎁 ' + tools.get__('Giorno in cui Inviare il DONO', lang) + ' : ' + tools.getstrDateLong(recnavepersistente.date_start, lang) + tools.ACAPO; + + // data += '💬 ' + tools.get__('Giorno di Apertura GIFT CHAT', lang) + ': ' + tools.getstrDateLong(recnavepersistente.date_gift_chat_open, lang) + tools.ACAPO; + + // data += '🎁 ' + tools.get__('Giorno in cui Inviare il DONO', lang) + ' : ' + tools.getstrDateLong(recnavepersistente.date_start, lang) + tools.ACAPO; if (!!recnavepersistente.note_bot) data += tools.get__('Note', lang) + ": " + recnavepersistente.note_bot + tools.ACAPO; if (recnavepersistente.provvisoria) - mystrtemp = tools.get__('TEMPORANEA', lang) + ' '; + mystrtemp = '' + tools.get__('TEMPORANEA', lang) + ' '; } else data = ""; - mystr = tools.ACAPO + tools.get__('NAVE', lang) + ' ' + '[' + riga + '.' + col + '] ' + mystrtemp + tools.ACAPO + data + tools.ACAPO + mystr; + mystr = tools.ACAPO + '⛵️ ' + tools.get__('NAVE', lang) + ' ' + '[' + riga + '.' + col + '] ' + mystrtemp + tools.ACAPO + data + tools.ACAPO + mystr; return mystr; } catch (e) { @@ -815,36 +819,6 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in }; -// async function Fuochi8Completati(idapp, params) { -// // Inviare un msg al Mediatore che può aprire la Chat con gli 8 fuochi -// const telegrambot = require('../telegram/telegrambot'); -// -// let text = '\nCompletata NAVE [riga=' + params.riga + ',col=' + params.col + ', ind_order=' + params.ind_order + ']'; -// console.log(text); -// tools.writeNaveLog(text); -// -// const { User } = require('./user'); -// -// const rec = await User.findByIndOrder(idapp, params.ind_order); -// -// text = await Nave.getNaveByUser(idapp, params.ind_order, rec.lang, true); -// -// // Inviare un msg a questi 8 Fuochi, che la loro placca è Pronta ! -// -// if (tools.isAbilitaNave(idapp)) { -// // ............. -// } -// -// if (false) { -// await telegrambot.sendMsgTelegram(idapp, rec.username, text, true); -// } else { -// await telegrambot.sendMsgTelegramToTheAdmin(idapp, text); -// } -// -// // Inviare la placca a Managers -// // await telegrambot.sendMsgTelegramToTheManagers(idapp, txt); -// } - NaveSchema.statics.getArrPosizioniByIndOrder = async function (idapp, ind_order) { const Nave = this; @@ -911,7 +885,7 @@ NaveSchema.statics.showListaOrd = async function (idapp) { for (const rec of arrrec) { let recnavepersistente = await NavePersistente.findByRigaColByDonatore(idapp, rec.riga, rec.col, 0); if (!!recnavepersistente) { - mystr += '[' + conta + '] [' + rec.riga + '.' + rec.col + '] ' + rec.ind_order + ' ' + rec.name + ' ' + rec.surname + ' (' + tools.getstrDateShort(recnavepersistente.date_start) + ')'; + mystr += '[' + conta + '] [' + rec.riga + '.' + rec.col + '] ' + rec.ind_order + ' ' + rec.name + ' ' + rec.surname + ' (' + tools.getstrDateShort(recnavepersistente.date_gift_chat_open) + ')'; mystr += ' num_tess = ' + rec.num_tess; mystr += '\n'; } @@ -1097,7 +1071,7 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida } if ((params.riga === 4 + 3) && (params.col === (8 * 2) + 3)) { // Si ritesse il Fondo AYNI nella Nave 3.3 - const userFondo = await User.findByIndOrder(idapp, 0); + const userFondo = await User.findByIndex(idapp, 0); params.ind_order = userFondo.ind_order; params.id = userFondo._id; params.num_tess = userFondo.num_tess; @@ -1129,6 +1103,8 @@ NaveSchema.statics.generaNave = async function (idapp, mydata) { numpersone: mydata.numpersone, }; + //++Todo: date_gift_chat_open e date_start : Ricalcolarle in Automatico... + params.primavolta = (params.riga === 1) && (params.col === 1); // params.primavolta = false; @@ -1141,7 +1117,7 @@ NaveSchema.statics.generaNave = async function (idapp, mydata) { await NavePersistente.addRecordNavePersistenteByParams({ idapp, riga: 0, col: 0, riga1don: 0, col1don: 0 }); - const userFondo = await User.findByIndOrder(idapp, 0); + const userFondo = await User.findByIndex(idapp, 0); if (!userFondo || userFondo === undefined) { await telegrambot.sendMsgTelegramToTheAdmin(idapp, 'Devi creare l\'utente FONDO , con ind_order = 0 ! '); } @@ -1270,7 +1246,7 @@ NaveSchema.statics.getNaveByUser = async function (idapp, username, lang, fuoco) if (persistente.provvisoria) { mystr += tools.ACAPO + tools.get__('NAVE', lang) + ' ' + '[' + mypos.riga + '.' + mypos.col + '] - ' + tools.get__('TEMPORANEA', lang) + tools.ACAPO + tools.ACAPO; } else { - mystr += await Nave.getNavePos(idapp, mypos.riga, mypos.col, false, ind_order); + mystr += await Nave.getNavePos(idapp, mypos.riga, mypos.col, false, pos.ind_order); } } // mystr += await Nave.getPlaccaPerDonatore(idapp, pos.riga, pos.col, false, rec); diff --git a/src/server/models/navepersistente.js b/src/server/models/navepersistente.js index 9b33351..3b4c334 100755 --- a/src/server/models/navepersistente.js +++ b/src/server/models/navepersistente.js @@ -125,13 +125,13 @@ function getQueryProj(myfilter) { } }, { - $unwind: "$mylista" + $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$mylista", 0 ] }, "$$ROOT" ] } } }, { $lookup: { from: "users", as: "user", - let: {username: '$mylista.username' }, + let: {username: '$username' }, pipeline: [ { $match: { @@ -196,6 +196,7 @@ NavePersistenteSchema.statics.getListaNavi = function (idapp) { col: 1, riga1don: 1, col1don: 1, + date_gift_chat_open: 1, date_start: 1, provvisoria: 1, DoniConfermati: 1, @@ -252,6 +253,10 @@ NavePersistenteSchema.statics.getLastRigaCol = async function (idapp) { return NavePersistente.findOne({ idapp }).sort({ _id: -1 }); }; +NavePersistenteSchema.statics.getLastRigaColDefinitiva = async function (idapp) { + return NavePersistente.findOne({ idapp, provvisoria: false }).sort({ riga: -1, col: -1 }); +}; + NavePersistenteSchema.pre('save', async function (next) { if (this.isNew) { const myrec = await NavePersistente.findOne().limit(1).sort({ _id: -1 }); diff --git a/src/server/models/user.js b/src/server/models/user.js index 6ac73f4..8ac6f40 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -405,6 +405,7 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, { lang: 1, + index: 1, ind_order: 1, username: 1, aportador_solidario: 1, @@ -647,17 +648,24 @@ UserSchema.statics.getLastUser = function (idapp) { return User.findOne({ idapp, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }).sort({ ind_order: -1 }) + }).sort({ index: -1 }) }; UserSchema.statics.findByIndOrder = function (idapp, ind_order) { const User = this; + return User.getRecByIndOrder(idapp, ind_order); + +}; + +UserSchema.statics.findByIndex = function (idapp, index) { + const User = this; + try { // ++Todo: non mettere tutti i campi !! return User.findOne({ idapp, - ind_order, + index, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }); } catch (e) { @@ -711,7 +719,7 @@ UserSchema.pre('save', async function (next) { */ next(); - }catch (e) { + } catch (e) { console.error(e.message); } }); @@ -855,12 +863,9 @@ UserSchema.statics.SetTelegramIdSuccess = async function (idapp, id, teleg_id) { UserSchema.statics.getLangByIndOrder = async function (idapp, ind_order) { const User = this; - return await User.findOne({ idapp, ind_order }, { lang: 1 }) - .then((rec) => { - return (!!rec) ? rec.lang : ''; - }).catch((e) => { - return 'it'; - }); + const rec = await User.getSmallRecByIndOrder(idapp, ind_order); + return (!!rec) ? rec.lang : ''; + }; @@ -921,10 +926,14 @@ UserSchema.statics.getSmallRecByIndOrder = async function (idapp, ind_order) { }, { idapp: 1, + index: 1, ind_order: 1, + old_order: 1, username: 1, name: 1, - surname: 1 + lang: 1, + surname: 1, + 'profile.teleg_id': 1, }); if (!!rec) @@ -938,6 +947,27 @@ UserSchema.statics.getSmallRecByIndOrder = async function (idapp, ind_order) { }; +UserSchema.statics.getRecByIndOrder = async function (idapp, ind_order) { + + try { + const rec = await ListaIngresso.getarray(idapp, + { + idapp, + ind_order, + deleted: false, + }); + + if (!!rec) + return rec[0]; + + return null; + + } catch (e) { + console.error('getRecByIndOrder', e); + } + +}; + UserSchema.statics.getusersManagers = async function (idapp) { const User = this; @@ -1142,7 +1172,10 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us dashboard.arrposizioni = await Nave.getArrPosizioniByUsername(idapp, username); - const arrrec = await ListaIngresso.getProssimiInLista(idapp, true); + let arrrec = []; + if (dashboard.arrimbarchi.length > 0) { + arrrec = await ListaIngresso.getProssimiInLista(idapp, true); + } for (let myimbarco of dashboard.arrimbarchi) { if (!!myimbarco.invitante_username) @@ -1158,6 +1191,7 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us mypos._doc.nave_partenza = await NavePersistente.findByRigaColByDonatore(idapp, mypos.riga, mypos.col, 0); } + //for (let indriga = 0; indriga < 10; indriga++) { // dashboard.navi_partenza.push(await Nave.getPrimaNaveByRiga(idapp, indriga)); //} @@ -1196,7 +1230,7 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us myrec.nave_partenza = await NavePersistente.findByRigaColByDonatore(idapp, myrec.riga, myrec.col, 0); - arrnew.push(myrec); + arrnew.push(myrec); } } } @@ -1212,6 +1246,7 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us } }; +/* UserSchema.statics.fixUsername = async function (idapp, aportador_solidario_ind_order, username) { const User = this; @@ -1229,6 +1264,7 @@ UserSchema.statics.fixUsername = async function (idapp, aportador_solidario_ind_ }; +*/ UserSchema.statics.findByCellAndNameSurname = function (idapp, cell, name, surname) { const User = this; @@ -1371,7 +1407,7 @@ UserSchema.statics.visuUtentiNonInNavi = async function (idapp) { visualizza = true; if (visualizza) { - mystr += user.username + ' ' + user.name + ' ' + user.surname + ' [' + user.ind_order + '] [inv=' + user.numinvitati + ']' + mystr += user.username + ' ' + user.name + ' ' + user.surname + ' [' + user.index + '] [inv=' + user.numinvitati + ']' trovato = true; } @@ -1524,7 +1560,7 @@ UserSchema.statics.getLastUsers = async function (idapp) { name: 1, surname: 1, date_reg: 1, - ind_order: 1, + index: 1, 'profile.nationality': 1, }).sort({ date_reg: -1 }).limit(lastn).then((arr) => { //return JSON.stringify(arr) @@ -1717,26 +1753,10 @@ async function addUtentiInLista(idapp, mode, arrusers) { } -UserSchema.statics.deveRitessersi = async function (idapp, ind_order) { - - const myrec = await User.findOne({ - 'idapp': idapp, - 'ind_order': ind_order, - "profile.vuole_ritessersi": true - }); - - return (!!myrec) - -}; - UserSchema.statics.getUsernameByIndOrder = async function (idapp, ind_order) { - const myrec = await User.findOne({ - 'idapp': idapp, - 'ind_order': ind_order, - }, { username: 1 }); - - return (!!myrec) ? myrec.username : '' + const myrec = await User.getSmallRecByIndOrder(idapp, ind_order); + return (!!myrec) ? myrec.username : ''; }; @@ -1755,7 +1775,7 @@ UserSchema.statics.ricalcolaIndex = async function (idapp) { const User = this; const arrusers = await User.find({ idapp }).sort({ ind_order: 1 }); - let index = 1; + let index = 0; try { for (const user of arrusers) { let field = { @@ -1766,7 +1786,7 @@ UserSchema.statics.ricalcolaIndex = async function (idapp) { const ris = await User.findOneAndUpdate({ _id: user._id }, { $set: field }, { new: false }); } - }catch (e) { + } catch (e) { console.error(e.message); } @@ -1799,7 +1819,8 @@ UserSchema.statics.changeInvitante = async function (idapp, username, invitante_ // ** const rec_ingr = await ListaIngresso.findOne({ idapp, username: username }); if (!!rec_ingr) { - await ListaIngresso.findByIdAndUpdate(rec_ingr._id, { $set: { invitante_username, ind_order: ind_order_ingr } }); + // await ListaIngresso.findByIdAndUpdate(rec_ingr._id, { $set: { invitante_username, ind_order: ind_order_ingr } }); + await ListaIngresso.findByIdAndUpdate(rec_ingr._id, { $set: { invitante_username } }); } diff --git a/src/server/router/dashboard_router.js b/src/server/router/dashboard_router.js index 8004aef..0319278 100755 --- a/src/server/router/dashboard_router.js +++ b/src/server/router/dashboard_router.js @@ -122,6 +122,8 @@ router.post('/getnavi', authenticate, async (req, res) => { let arrnavi = await NavePersistente.findAllIdApp(idapp); + // let arrnavi = await NavePersistente.find({idapp, date_gift_chat_open: { $gte: tools.IncDateNow(-1000 * 3600 * 24 * 7 ) } }).sort({ riga: 1, col: 1 }); + for (nave of arrnavi) { //nave.rec = await Nave.getNaveByRigaCol(idapp, nave.riga, nave.col); nave._doc.rec = { @@ -153,8 +155,14 @@ router.post('/getnavi', authenticate, async (req, res) => { router.post('/getdoninavi', authenticate, async (req, res) => { const idapp = req.body.idapp; const ricalcola = req.body.ricalcola; + const showall = req.body.showall; + + let arrnavi = null; + if (showall) + arrnavi = await NavePersistente.findAllIdApp(idapp); + else + arrnavi = await NavePersistente.find({idapp, date_gift_chat_open: { $gte: tools.IncDateNow(-1000 * 3600 * 24 * 7 ) } }).sort({ riga: 1, col: 1 }); - let arrnavi = await NavePersistente.findAllIdApp(idapp); let test = false; //arrnavi.push({ riga: indriga, col: indcol, rigadon: indriga + 3, coldon: (indcol * 8) - 7 }); @@ -168,7 +176,7 @@ router.post('/getdoninavi', authenticate, async (req, res) => { index++; } } else { - arrnavi = await NavePersistente.findAllIdApp(idapp); + // arrnavi = await NavePersistente.findAllIdApp(idapp); for (nave of arrnavi) { if (nave.provvisoria || nave.DoniTotali !== nave.DoniConfermati) { nave._doc.rec = await Nave.getNaveByRigaCol(idapp, nave.riga1don, nave.col1don); diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index f555627..bb7976d 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -315,15 +315,15 @@ async function checkIfSbloccatiRequisiti(idapp, allData, id) { // CHECK APORTADOR SOLIDARIO: if (!!allData.useraportador) { -/* - const is9reqAportador = await User.isUserQualified9(idapp, allData.myuser.aportador_solidario); + /* + const is9reqAportador = await User.isUserQualified9(idapp, allData.myuser.aportador_solidario); - if (!allData.precDataAportador.is9req && is9reqAportador) { - // ORA HAI I 9 REQUISITI ! - const msgtext = telegrambot.getCiao(idapp, allData.myuser.aportador_solidario, allData.useraportador.lang) + tools.gettranslate('HAI_I_9_REQUISITI', allData.useraportador.lang); - telegrambot.sendMsgTelegram(idapp, allData.myuser.aportador_solidario, msgtext, true); // Anche a STAFF - } -*/ + if (!allData.precDataAportador.is9req && is9reqAportador) { + // ORA HAI I 9 REQUISITI ! + const msgtext = telegrambot.getCiao(idapp, allData.myuser.aportador_solidario, allData.useraportador.lang) + tools.gettranslate('HAI_I_9_REQUISITI', allData.useraportador.lang); + telegrambot.sendMsgTelegram(idapp, allData.myuser.aportador_solidario, msgtext, true); // Anche a STAFF + } + */ } } @@ -405,7 +405,7 @@ router.patch('/chval', authenticate, async (req, res) => { // Send Notification to the BOT await telegrambot.sendMsgTelegram(idapp, mydata.notifBot.un, mydata.notifBot.txt); addtext = '[Msg Inviato a ' + mydata.notifBot.un + ']:' + '\n' + mydata.notifBot.txt; - await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext, true); + telegrambot.sendMsgTelegramToTheManagers(idapp, addtext, true); } if (mydata.table === 'users') { @@ -534,107 +534,137 @@ router.patch('/callfunz', authenticate, async (req, res) => { } } - const myuser = await User.findOne({ idapp, username }); + let myuser = await User.findOne({ idapp, username }); let rimosso = 0; if (mydata.myfunc === shared_consts.CallFunz.SOSTITUISCI) { // SOSTITUISCI + + username_da_sostituire = mydata.data.username_da_sostituire; + mianavedasost = await Nave.findOne({ idapp, riga: mydata.data.riga, col: mydata.data.col }); + if (!!mianavedasost) { - // Sostituisci l'Utente - myusernuovo = await User.getUserShortDataByUsername(idapp, mydata.data.username); - let navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, mydata.data.riga, mydata.data.col, 0); + // Sostituisci l'Utente + myusernuovo = await User.getUserShortDataByUsername(idapp, mydata.data.username); + let navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, mydata.data.riga, mydata.data.col, 0); - if (!!myusernuovo) { - // Controlla prima se è in una Nave Temporanea, allora lo elimina - miaarrnavi = await Nave.find({ idapp, ind_order: myusernuovo.ind_order }); - if (miaarrnavi) { - for (const mianave of miaarrnavi) { - let persistente = await NavePersistente.findByRigaColByDonatore(idapp, mianave.riga, mianave.col, 0); - if (persistente.provvisoria) { + if (!!myusernuovo) { + + if (!mydata.data.AddImbarco && !!mianavedasost && mianavedasost.ind_order > 0) { + // Controlla prima se è in una Nave Temporanea, allora lo elimina dalla Nave Temporanea + + miaarrnavi = await Nave.getArrPosizioniByUsername(idapp, username); + if (miaarrnavi) { + for (const mianave of miaarrnavi) { + let persistente = await NavePersistente.findByRigaColByDonatore(idapp, mianave.riga, mianave.col, 0); + if (persistente.provvisoria) { + fieldsvalue = { + ind_order: -1 + }; + + let ris = await Nave.findByIdAndUpdate(mianave.id, { $set: fieldsvalue }); + if (!!ris) { + rimosso++; + break; // Rimuovilo solo 1 ! + } + } + } + } + } + + if (!!myuser) { + if (!!mianavedasost && mianavedasost.ind_order >= 0) { + // Metti campo 'delete': true su ListaIngresso + olduseringresso = await ListaIngresso.findOne({ idapp, ind_order: mianavedasost.ind_order }); + if (!!olduseringresso) { + let fieldsvalue = { + deleted: true + }; + const risul = await ListaIngresso.findByIdAndUpdate(olduseringresso.id, { $set: fieldsvalue }, { new: false }); + } + } + } + + if (!!myuser) { + if (mydata.data.deleteUser && !!mianavedasost && mianavedasost.ind_order > 0) { + // Metti Deleted allo User fieldsvalue = { - ind_order: -1 + deleted: true }; - - let ris = await Nave.findByIdAndUpdate(mianave.id, { $set: fieldsvalue }); - if (!!ris) { - rimosso++; - } + await User.findByIdAndUpdate(myuser.id, { $set: fieldsvalue }); + await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuser.name} ${myuser.surname} (${myuser.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); } } - } - if (!!myuser) { - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - // CONTROLLARE !!! - // ++Todo: Controllare che sia corretto che lo nascondo !!! - // Metti campo 'delete': true su ListaIngresso - olduseringresso = await ListaIngresso.findOne({ idapp, ind_order: old_ind_order }); - if (!!olduseringresso) { - let fieldsvalue = { - deleted: true - }; - const risul = await ListaIngresso.findByIdAndUpdate(olduseringresso.id, { $set: fieldsvalue }, { new: false }); + let ind_order = -1; + let myingr = null; + // Estrai un ind_order dalla Lista, se era ancora in attesa + if (!mydata.data.AddImbarco) + myingr = await ListaIngresso.findOne({ idapp, added: false, username: myusernuovo.username }); + + if (!!myingr) { + ind_order = myingr.ind_order; + + myingr.added = true; + await myingr.save(); + } else { + // Crea un nuovo Ingresso + myingr = await ListaIngresso.addUserInListaIngresso(idapp, myuser.username, myuser.username, myuser.lang, false, true, null, null, true); + ind_order = myingr.ind_order; + + await myingr.save(); } - } - if (!!myuser) { - // Metti Deleted allo User + // Aggiorna la Nave con il Nuovo fieldsvalue = { - deleted: true + ind_order }; - await User.findByIdAndUpdate(myuser.id, { $set: fieldsvalue }); - } - - // Aggiorna la Nave con il Nuovo - fieldsvalue = { - ind_order: myusernuovo.ind_order - }; - - const dachi = req.user.name + ' ' + req.user.surname; + const dachi = req.user.name + ' ' + req.user.surname; - return await Nave.findByIdAndUpdate(mianavedasost.id, { $set: fieldsvalue }) - .then(async (rec) => { - // tools.mylogshow(' REC TO MODIFY: ', rec); - if (!rec) { - return res.status(404).send(); - } else { - if (mydata.notifBot && !!navepersistente.link_chat) { - // Send Notification to the BOT - let messaggio = tools.get__('SPOSTATO', req.user.lang); + return await Nave.findByIdAndUpdate(mianavedasost.id, { $set: fieldsvalue }) + .then(async (rec) => { + // tools.mylogshow(' REC TO MODIFY: ', rec); + if (!rec) { + return res.status(404).send(); + } else { + if (mydata.data.notifBot && !!navepersistente.link_chat) { + // Send Notification to the BOT + let messaggio = tools.get__('SPOSTATO', req.user.lang); - if (!!navepersistente.date_start) { - messaggio += tools.ACAPO + tools.get__('DATA_PART_NAVE', req.user.lang) + tools.getstrDateLong(navepersistente.date_start) + tools.ACAPO; - } - if (!!navepersistente.link_chat) { - messaggio += tools.ACAPO + tools.get__('ENTRA_GIFT_CHAT', req.user.lang) + navepersistente.link_chat + tools.ACAPO; + if (!!navepersistente.date_start) { + messaggio += tools.ACAPO + tools.get__('DATA_PART_NAVE', req.user.lang) + tools.getstrDateLong(navepersistente.date_gift_chat_open) + tools.ACAPO; + } + if (!!navepersistente.link_chat) { + messaggio += tools.ACAPO + '👉🏻👉🏻 ' + tools.get__('ENTRA_GIFT_CHAT', req.user.lang) + ' ' + tools.ACAPO; + } + + const myplacca = await Nave.getNavePos(idapp, navepersistente.riga, navepersistente.col); + messaggio += tools.ACAPO + myplacca; + + await telegrambot.sendMsgTelegram(idapp, myusernuovo.username, messaggio); + + await telegrambot.sendMsgTelegramToTheManagers(idapp, mydata.notifBot.txt + ' ' + myusernuovo.name + ' ' + myusernuovo.surname + ' [da ' + dachi + ']' + tools.ACAPO + 'Inviato messaggio: ' + messaggio); + await telegrambot.sendMsgTelegram(idapp, req.user.username, mydata.notifBot.txt); + await telegrambot.sendMsgTelegram(idapp, req.user.username, myplacca); } - const myplacca = await Nave.getNavePos(idapp, navepersistente.riga, navepersistente.col); - messaggio += tools.ACAPO + myplacca; - await telegrambot.sendMsgTelegram(idapp, myusernuovo.username, messaggio); + // const nomecognomeprima = myuser.name + ' ' + myuser.surname + '(' + myuser.username + ')'; + // const nomecognomenuovo = await User.getNameSurnameByUsername(idapp,); - await telegrambot.sendMsgTelegramToTheManagers(idapp, mydata.notifBot.txt + ' ' + myusernuovo.name + ' ' + myusernuovo.surname + ' [da ' + dachi + ']' + tools.ACAPO + 'Inviato messaggio: ' + messaggio); - await telegrambot.sendMsgTelegram(idapp, req.user.username, mydata.notifBot.txt); - await telegrambot.sendMsgTelegram(idapp, req.user.username, myplacca); + res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); } - - // const nomecognomeprima = myuser.name + ' ' + myuser.surname + '(' + myuser.username + ')'; - // const nomecognomenuovo = await User.getNameSurnameByUsername(idapp,); - - res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); - } - - }).catch((e) => { - tools.mylogserr('Error patch USER: ', e); - res.status(400).send(); - }) + }).catch((e) => { + tools.mylogserr('Error patch USER: ', e); + res.status(400).send(); + }) + } } } else if (mydata.myfunc === shared_consts.CallFunz.AGGIUNGI_NUOVO_IMBARCO) { // Ottieni il prossimo Numero di Tessitura diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index a9663b3..5df10b2 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -125,21 +125,6 @@ router.post('/', async (req, res) => { // nomeaportador_corretto = recextra.aportador_solidario_originale_name_surname; // } - const lastuser = await User.getLastUser(user.idapp); - // const lastextra = await ExtraList.getLastUser(user.idapp); - let lastindorder = 0; - - if (lastuser) { - lastindorder = lastuser.ind_order; - } - //if (lastextra) { - // if (lastextra.ind_order > lastindorder) - // lastindorder = lastextra.ind_order; - //} - - if (lastindorder > 0) - user.ind_order = lastindorder + 1; - const numero = user.name.slice(-1); if ((numero === '2') || (numero === '3') || (numero === '4') || (numero === '5') || (numero === '6')) { recorig = await User.findByCellAndNameSurname(user.idapp, user.profile.cell, user.name.slice(0, -1), user.surname); @@ -238,7 +223,7 @@ router.post('/', async (req, res) => { recextra.username = user.username; await recextra.save(); - await User.fixUsername(user.idapp, user.ind_order, user.username); + // await User.fixUsername(user.idapp, user.ind_order, user.username); } return token; }) @@ -646,7 +631,7 @@ router.post('/dbop', authenticate, async (req, res) => { lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1); let last = 1; if (lastrec) { - last = lastrec[0].ind_order; + last = lastrec[0].index; } if (!last) { last = 1; @@ -655,15 +640,15 @@ router.post('/dbop', authenticate, async (req, res) => { for (let ind = 0; ind < 100; ind++) { let myuser = new User(); myuser._id = new ObjectID(); - myuser.ind_order = last + ind + 1; + myuser.index = last + ind + 1; myuser.idapp = idapp; myuser.password = "$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG"; myuser.lang = 'it'; myuser.email = "miaemail@email.it"; - myuser.name = 'U' + myuser.ind_order; - myuser.surname = 'Ar' + myuser.ind_order; + myuser.name = 'U' + myuser.index; + myuser.surname = 'Ar' + myuser.index; myuser.verified_email = true; - if (myuser.ind_order < 2) + if (myuser.index < 2) myuser.perm = "3"; myuser.username = "Userna_" + myuser.name; myuser.profile.special_req = true; diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 5a33fa4..f0d7db1 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -462,7 +462,7 @@ module.exports = { let userdest = mylocalsconf.user.aportador_solidario; let langdest = mylocalsconf.user.lang; let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname}`; - const ind_order = mylocalsconf.user.ind_order; + const index = mylocalsconf.user.index; let aportador = ''; if (userdest) { @@ -478,7 +478,7 @@ module.exports = { NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp, userdest) + aportador; aportador = NameFrom; } - text = printf(getstr(langdest, 'MSG_APORTADOR_USER_REGISTERED'), `${mylocalsconf.user.name} ${mylocalsconf.user.surname} (${mylocalsconf.user.username})`, ind_order, aportador); + text = printf(getstr(langdest, 'MSG_APORTADOR_USER_REGISTERED'), `${mylocalsconf.user.name} ${mylocalsconf.user.surname} (${mylocalsconf.user.username})`, index, aportador); } let addtext = ""; @@ -501,7 +501,7 @@ module.exports = { if (usersmanagers) { for (const rec of usersmanagers) { await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': ' + text, undefined, undefined, true); - await tools.snooze(300) + await tools.snooze(200) } } } @@ -840,6 +840,10 @@ class Telegram { } + geturlfaq() { + return tools.getHostByIdApp(this.idapp) + '/faq' + } + async IsTesto(msg) { let risp = ''; @@ -855,7 +859,7 @@ class Telegram { const rec = this.getRecInMem(msg); let myname = ''; if (rec.user) { - myname = rec.user.name + ' ' + rec.user.surname + ' (n.' + rec.user.ind_order + ')'; + myname = rec.user.name + ' ' + rec.user.surname + ' (n.' + rec.user.index + ')'; } if (rec.statusmsg === Status.WAITFOR_RISPOSTA) { @@ -917,7 +921,7 @@ class Telegram { if (!!rec.user) { const myrec = await User.getUserShortDataByUsername(this.idapp, rec.user.username); - risp += '\nSul sito ti sei registrato come:\n\n[N. ' + rec.user.ind_order + ']: ' + rec.user.name + ' ' + rec.user.surname + '\nUsername: ' + rec.user.username + '\n' + 'Email: ' + rec.user.email + '\nLang: ' + rec.user.lang + tools.ACAPO; + risp += '\nSul sito ti sei registrato come:\n\n[N. ' + rec.user.index + ']: ' + rec.user.name + ' ' + rec.user.surname + '\nUsername: ' + rec.user.username + '\n' + 'Email: ' + rec.user.email + '\nLang: ' + rec.user.lang + tools.ACAPO; risp += 'Num Invitati: ' + myrec.numinvitati + tools.ACAPO; risp += 'Num Invitati Attivi: ' + myrec.numinvitatiattivi + tools.ACAPO; } else { @@ -986,13 +990,14 @@ class Telegram { risp = emo.JOY + emo.JOY + emo.JOY; } else if (testo.length >= 10) { noanswer = true; - risp = 'Questo messaggio è stato inviato alla Chat Help\nIo sono solo un Robot ' + emo.ROBOT_FACE + emo.JOY2 + '\n\nPer AIUTO, contatta la Chat AYNI - HELP'; + let myfaq = this.geturlfaq(); + risp = 'Io sono solo un Robot ' + emo.ROBOT_FACE + emo.JOY2 + '\n\nPer AIUTO, clicca qui:\n👉🏻👉🏻FAQ di AIUTO (risposte alle domande più frequenti)\n\nSe non trovi risposta allora contatta la Chat AYNI - HELP.\nGrazie\nStaff AYNI'; // risp += '\nClicca qui per entrare nella Chat AYNI - HELP di Supporto\n' + 'https://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw' + '\n\nI miei colleghi umani ti aiuteranno a risolvere !'; await local_sendMsgTelegramToTheManagers(this.idapp, testo, msg, rec.username_bo); } } - let keyboard = {}; + let keyboard = null; if (contastiera) { keyboard = { @@ -1250,6 +1255,7 @@ class Telegram { if (!!mystrnave) { mystr += '✨✨✨' + tools.get__('TUE_NAVI', this.getlang(msg)) + ':\n'; mystr += mystrnave; + } else { if (!tuttie9) { @@ -1291,7 +1297,7 @@ class Telegram { let index = 1; dashboard.downline.forEach((user) => { mystr += emoji.get('star-struck') + ` ${index}°: `; - mystr += (user._doc.qualified) ? emo.CHECK_VERDE : emo.CROSS_ROSSA; + mystr += (user.qualified) ? emo.CHECK_VERDE : emo.CROSS_ROSSA; mystr += `${user.name} ${user.surname} (${user.username})\n`; index++; }); diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 91f9aa8..3c7c032 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -65,8 +65,8 @@ textlang = { 'HAI_I_9_REQUISITI': 'COMPLIMENTI!\nHai Completato TUTTI i 9 Passi della Guida! Grazie per Aiutare AYNI ad Espandersi!', 'NON_HAI_I_9_REQUISITI': 'Ricqorda che puoi Aiutare a far Crescere ed Espandere il Movimento, Condividendo con chiunque questo nostro viaggio!', 'INFO_LA_MIA_LAVAGNA': '✨ Lista dei Passi: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'Per completare tutti i requisiti vai sul sito:\n%s\nPer vedere lo stato della tua Nave e dei tuoi invitati, clicca sulle 3 linee in alto a sinistra ed accedi alla voce "Lavagna".\n', - 'INFO_LAVAGNA_SITO': 'Per vedere in dettaglio lo stato della tua Nave, sul sito AYNI, clicca sulle 3 linee in alto a sinistra ed accedi alla voce "Lavagna".\n', + 'INFO_LAVAGNA_SITO_COMPLETARE': 'Per completare tutti i requisiti vai sul sito:\n%s\nPer vedere lo stato della tua Nave e dei tuoi invitati:\n 👉🏻 Entra nella tua Lavagna.\n', + 'INFO_LAVAGNA_SITO': 'Per vedere in dettaglio lo STATO della tua Nave, sul sito AYNI\n 👉🏻 Entra nella tua Lavagna.\n', 'INFO_LINK_DA_CONDIVIDERE': 'Link da condividere ai tuoi invitati per farli registrare al sito di Ayni:\n\n%s', 'INFO_LINK_ZOOM': 'Link da condividere per partecipare allo Zoom (Conferenza OnLine):\n%s', 'ZOOM_CONFERENCE': 'Ecco il programma delle Conferenze (Zoom) aperti a TUTTI:', @@ -91,7 +91,8 @@ textlang = { 'SCEGLI_VOCE': 'scegli una voce:', 'INVITATI_LISTA': 'I Tuoi Invitati (in verde con almeno i primi 7 Requisiti)', 'CIAO': 'Ciao', - 'ADDED_TOLISTAINGRESSO': 'Complimenti ! Hai completato i 7 Passi!🎊\nSei stato aggiunto alla Lista delle persone che entreranno nella Lista D\'Imbarco !\nNei prossimi giorni riceverai un messaggio quando la tua Nave partirà.', + 'ADDED_TOLISTAINGRESSO': 'Complimenti! 🎊\nSei stato aggiunto alla Lista D\'Imbarco !\nNei prossimi giorni riceverai un messaggio qui quando la tua Nave sarà pronta a partire.\nRicorda che per salire di graduatoria, puoi condividere il Movimento con i tuoi amici ❤️.', + 'REGALATO_INVITANTE': 'da fare.... 😍🎊 Hai ricevuto in Regalo un Invitato {invitato} da parte di {mittente} !', 'NO_PROG': 'Attualmente non sei ancora dentro alla Lista d\'Imbarco!', 'SEND_LINK_CHAT_DONATORI': 'Ciao %s!\nLa tua NAVE sta finalmente Salpando!\nEntra nella Gift Chat della nave {%s} cliccando qui: %s', 'SEND_LINK_CHAT_SOGNATORE': 'Ciao %s!\nOggi Diventi Sognatore !!! 🎊🎊🎊 Entra nella Gift Chat della nave {%s} cliccando qui: %s', @@ -104,8 +105,9 @@ textlang = { 'NAVE COMPLETATA': 'NAVE COMPLETATA', 'Doni Effettuati': 'Doni Effettuati', 'Tutor che affianchèra il Mediatore': 'Tutor che affianchèra il Mediatore', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura GIFT CHAT\n%s Chiusura GIFT CHAT\nNota Bene: Hai tempo 4 giorni dall\'apertura per entrare in Chat ed effettuare il tuo Dono, dopodichè effettueremo la sostituzione.', 'Giorno di Apertura GIFT CHAT': 'Giorno di Apertura GIFT CHAT', - 'Giorno in cui Inviare il DONO': 'Hai 4 giorni di tempo per inviare il tuo dono. Giorno di Chiusura:', + 'Giorno in cui Inviare il DONO': 'Hai 4 giorni di tempo per inviare il tuo dono.\nGiorno di Chiusura', 'SPOSTATO': 'Sei stato Spostato in una Nuova Nave !', 'Note': 'Note', 'TEMPORANEA': 'TEMPORANEA', @@ -132,7 +134,7 @@ textlang = { 'HAI_I_9_REQUISITI': 'ČESTITAMO!\nIzpolnil si VSEH 9 korakov v navodilih! Hvala ker pomagaš k širitvi AYNI !', 'NON_HAI_I_9_REQUISITI': 'Zapomni si, če želiš Pomagati Rasti in Širit Gibanje, lahko to storiš z delitvijo med ljudmi!', 'INFO_LA_MIA_LAVAGNA': '✨ Seznam Krajev: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'Da izpolneš vse zahteve, pojdi na spletno stran:\n%s\nDa pogledaš status svoje Ladje in status svojih povabljencev, klikni na levi strani zgoraj na tri črte in izberi "Tabla".\n', + 'INFO_LAVAGNA_SITO_COMPLETARE': 'Da izpolneš vse zahteve, pojdi na spletno stran:\n%s\nDa pogledaš status svoje Ladje in status svojih povabljencev, klikni na levi strani zgoraj na tri črte in izberi "Tabla".\n👉🏻 Table', 'INFO_LAVAGNA_SITO': 'Da lahko podrobno pogledaš status svoje Ladje,na spletni strani AYNI, klikni, na levi strani zgoraj, na tri črtice in izberi "Tabla".\n', 'INFO_LINK_DA_CONDIVIDERE': 'Link, ki ga deliš svojim povabljencem, da se lahko registrirajo na spletni strani Ayni:\n\n%s', 'INFO_LINK_ZOOM': 'Link, ki ga deliš za udeležbo na Zoom (Konferenca OnLine):\n%s', @@ -171,8 +173,7 @@ textlang = { 'NAVE COMPLETATA': 'LADJE DOSTAVLJEN', 'Doni Effettuati': 'Darila narejena', 'Tutor che affianchèra il Mediatore': 'Tutor, ki bo podpiral Mediatorja', - 'Giorno di Apertura GIFT CHAT': 'Dan odpiranja GIFT CHAT', - 'Giorno in cui Inviare il DONO': 'Dan za pošiljanje DARILA', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura GIFT CHAT\n%s Zapiranje DARILNEGA KLEPETA\nBodi pozoren: Časa imaš 4 dni od odprtja za vstop v Klepet- ladjico in izpeljati svoje Vplačilo, po tem času bomo izvedli zamenjavo', 'SPOSTATO': 'Prestavljen si v Novo Ladjico !', 'Note': 'Opombe', 'TEMPORANEA': 'ZAČASNA', @@ -197,7 +198,7 @@ textlang = { 'HAI_I_9_REQUISITI': '¡FELICITACIONES!\n¡Has completado los 9 pasos de la Guía! Gracias por ayudar a AYNI a expandirse!', 'NON_HAI_I_9_REQUISITI': 'Recuerda que puedes ayudar a que el Movimiento crezca y se expanda compartiendo nuestro viaje con todos.!', 'INFO_LA_MIA_LAVAGNA': '✨ Lista de pasos: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'Para completar todos los requisitos vaya al sitio:\n%s\nPara ver el estado de su nave y sus invitados, haga clic en las 3 líneas de arriba a la izquierda y vaya a "Pizarra".\n', + 'INFO_LAVAGNA_SITO_COMPLETARE': 'Para completar todos los requisitos vaya al sitio:\n%s\nPara ver el estado de su nave y sus invitados,👉🏻 Pizarra.\n', 'INFO_LAVAGNA_SITO': 'Para ver en detalle el estado de su nave, en el sitio web de AYNI, haga clic en las 3 líneas de la parte superior izquierda y vaya a "Pizarra"..\n', 'INFO_LINK_DA_CONDIVIDERE': 'Enlaces para compartir con sus invitados para que se registren en el sitio web de Ayni:\n\n%s', 'INFO_LINK_ZOOM': 'Enlaces para compartir para participar en el Zoom (Conferencia en línea):\n%s', @@ -236,8 +237,7 @@ textlang = { 'NAVE COMPLETATA': 'NAVE COMPLETADA', 'Doni Effettuati': 'Regalos Realizados', 'Tutor che affianchèra il Mediatore': 'Tutor de apoyo al Donante', - 'Giorno di Apertura GIFT CHAT': 'Día de apertura GIFT CHAT', - 'Giorno in cui Inviare il DONO': 'Día en el que enviar el REGALO', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura del CHAT DE REGALOS\n%s Cierre del CHAT DE REGALOS\nNota: Tienes 4 días desde la apertura para entrar en el Chat y hacer tu Regalo, después de lo cual haremos el reemplazo', 'SPOSTATO': 'Has sido trasladado a una nueva nave !', 'Note': 'Notas', 'TEMPORANEA': 'TEMPORAL', @@ -259,7 +259,7 @@ textlang = { 'HAI_I_9_REQUISITI': 'CONGRATULATIONS!\nYou have completed ALL 9 steps of the Guide! Thank you for Helping AYNI Expand!', 'NON_HAI_I_9_REQUISITI': 'Remember that you can help the Movement grow and expand by sharing our journey with everyone.!', 'INFO_LA_MIA_LAVAGNA': '✨ Step List: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'To complete all the requirements go to the site:%s\nTo see the status of your Ship and your guests, click on the 3 lines at the top left and go to "Dashboard"\n', + 'INFO_LAVAGNA_SITO_COMPLETARE': 'To complete all the requirements go to the site:%s\nTo see the status of your Ship and your guests\n👉🏻 Dashboard\n', 'INFO_LAVAGNA_SITO': 'To see in detail the status of your ship, on the AYNI website, click on the 3 lines at the top left and go to "Blackboard".\n', 'INFO_LINK_DA_CONDIVIDERE': 'Links to share with your guests to have them register on Ayni\'s website:\n\n%s', 'INFO_LINK_ZOOM': 'Links to share to participate in Zoom (Online Conference):\n%s', @@ -298,8 +298,7 @@ textlang = { 'NAVE COMPLETATA': 'SHIP COMPLETED', 'Doni Effettuati': 'Gifts Made', 'Tutor che affianchèra il Mediatore': 'Tutor supporting the Mediator', - 'Giorno di Apertura GIFT CHAT': 'Opening Day GIFT CHAT', - 'Giorno in cui Inviare il DONO': 'Day on which to send the Gift', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Opening GIFT CHAT\n%s Closing GIFT CHAT\nNote: You have 4 days from the opening to enter the Chat and make your Gift, after which we will make the replacement.', 'SPOSTATO': 'You\'ve been moved to a New Ship !', 'Note': 'Note', 'TEMPORANEA': 'TEMPORARY', @@ -325,8 +324,8 @@ textlang = { 'HAI_I_9_REQUISITI': 'FÉLICITATIONS!\n!Vous avez franchi les 9 étapes de la conduite ! Merci d\'avoir aidé AYNI à se développer!', 'NON_HAI_I_9_REQUISITI': 'N\'oubliez pas que vous pouvez aider le Mouvement à grandir et à se développer en partageant notre voyage avec tout le monde.!', 'INFO_LA_MIA_LAVAGNA': '✨ Liste des étapes: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'Pour remplir toutes les conditions, rendez-vous sur le site:\n%s\nPour voir le statut de votre navire et de vos invités, cliquez sur les 3 lignes en haut à gauche et allez sur "Tableau noir".\n', - 'INFO_LAVAGNA_SITO': 'Pour voir en détail le statut de votre navire, sur le site de l\'AYNI, cliquez sur les 3 lignes en haut à gauche et allez sur "Tableau noir".\n', + 'INFO_LAVAGNA_SITO_COMPLETARE': 'Pour remplir toutes les conditions, rendez-vous sur le site:\n%s\nPour voir le statut de votre navire et de vos invités\n 👉🏻 Tableau.\n', + 'INFO_LAVAGNA_SITO': 'Pour voir en détail le statut de votre navire, sur le site de l\'AYNI, cliquez sur les 3 lignes en haut à gauche et allez sur "Tableau".\n', 'INFO_LINK_DA_CONDIVIDERE': 'Liens à partager avec vos invités pour qu\'ils s\'inscrivent sur le site web d\'Ayni:\n\n%s', 'INFO_LINK_ZOOM': 'Liens à partager pour participer à Zoom (Conférence en ligne):\n%s', 'ZOOM_CONFERENCE': 'Vous trouverez ici les dates de programmation sur Zoom:', @@ -364,8 +363,7 @@ textlang = { 'NAVE COMPLETATA': 'NAVIRE COMPLÉTÉ', 'Doni Effettuati': 'Don effectués', 'Tutor che affianchèra il Mediatore': 'Le tuteur qui soutient le Mediateur', - 'Giorno di Apertura GIFT CHAT': 'Jour d\'ouverture GIFT CHAT', - 'Giorno in cui Inviare il DONO': 'Envoyer le jour il DONO', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s : Chat d\'ouverture\n%s Clôture du GIFT CHAT\nNote: Vous avez 4 jours à partir de l\'ouverture pour entrer dans le Chat et faire votre Cadeau, après quoi nous ferons le remplacement', 'SPOSTATO': 'Vous avez été transféré sur un nouveau navire !', 'Note': 'Notes', 'TEMPORANEA': 'TEMPORAIRE', @@ -391,7 +389,7 @@ textlang = { 'HAI_I_9_REQUISITI': 'FELICITAÇÕES!\nVocê completou TODAS as 9 etapas da condução! Obrigado por ajudar a AYNI a expandir!', 'NON_HAI_I_9_REQUISITI': 'Lembre-se que pode ajudar o Movimento a crescer e expandir-se, partilhando a nossa jornada com todos!', 'INFO_LA_MIA_LAVAGNA': '✨ Lista de etapas: ✨ \n', - 'INFO_LAVAGNA_SITO_COMPLETARE': 'Para completar todos os requisitos ir para o sitio:\n%s\nPer vedere lo stato della tua Nave e dei tuoi invitati, clicca sulle 3 linee in alto a sinistra ed accedi alla voce "Lavagna".\n', + 'INFO_LAVAGNA_SITO_COMPLETARE': 'Para completar todos os requisitos ir para o sitio:\n%s\nPara ver o estado do seu navio e dos seus convidados:\n 👉🏻 Entre no seu Tablero.\n', 'INFO_LAVAGNA_SITO': 'Para ver em detalhe o estado do seu navio, no site da AYNI, clique nas 3 linhas no canto superior esquerdo e vá para "DashBoard"..\n', 'INFO_LINK_DA_CONDIVIDERE': 'Links para partilhar com os seus convidados para que se registem no website da Ayni:\n\n%s', 'INFO_LINK_ZOOM': 'Links para partilhar para participar na Zoom (Conferência Online):\n%s', @@ -430,8 +428,7 @@ textlang = { 'NAVE COMPLETATA': 'NAVIO COMPLETADO', 'Doni Effettuati': 'Regalo Feitos', 'Tutor che affianchèra il Mediatore': 'Tutor que apoia o Mediator', - 'Giorno di Apertura GIFT CHAT': 'Dia de Abertura GIFT CHAT', - 'Giorno in cui Inviare il DONO': 'Dia em que enviar o REGALO', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Abertura do GIFT CHAT\n%s Fechamento GIFT CHAT\nNota: Você tem 4 dias desde a abertura para entrar no Chat e fazer o seu Presente, depois do qual faremos o substituição.', 'SPOSTATO': 'Você foi transferido para um novo navio !', 'Note': 'Notas', 'TEMPORANEA': 'TEMPORÁRIO', @@ -466,10 +463,10 @@ module.exports = { DONATORI: 1, TUTTI: 2, - STR_SOGNATORE: 'Sognatore', - STR_MEDIATORE: 'Mediatore', - STR_MEDIATORI: 'Mediatori', - STR_DONATORI: 'Donatori', + STR_SOGNATORE: 'Sognatore', + STR_MEDIATORE: 'Mediatore', + STR_MEDIATORI: 'Mediatori', + STR_DONATORI: 'Donatori', SOGNATORE: 'E1 🌈 ', MEDIATORE: 'A1 💦 ', SONOFUOCO: 0, From 2cb04f4f499de50086ee826e358183d8642c5efd Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Wed, 13 May 2020 01:32:27 +0200 Subject: [PATCH 03/14] Modifiche ultimate: Grafica Navi , Prenota un Altro Viaggio. --- docs/passi.txt | 21 +++------ src/server/models/listaingresso.js | 75 +++++++++++++++++++++++------- src/server/models/nave.js | 33 ++++++++----- src/server/models/user.js | 22 +++++---- src/server/router/index_router.js | 41 +++++++++------- src/server/router/users_router.js | 3 ++ src/server/telegram/telegrambot.js | 13 ++++-- src/server/tools/general.js | 6 +++ 8 files changed, 142 insertions(+), 72 deletions(-) diff --git a/docs/passi.txt b/docs/passi.txt index 9dc6c40..7708482 100644 --- a/docs/passi.txt +++ b/docs/passi.txt @@ -9,23 +9,19 @@ X - Aggiornare il testo sulla Placca (Data Inizio e Data Fine Doni) // ++Todo: SISTEMARE: + X - Devo comparire come mio invitato se aggiungo un nuovo Viaggio. + X - Fare la lista delle Navi (in alto alla Lavagna) con il loro tragitto. + X- Nel campo note, metterci il Sogno + X - Se nave Temporanea, mettere Info. + X- Mettere flag se si vuole spostare l'Utente oppure Aggiungerlo... + - Mettere Sfondo immagine su ogni nave + - Mettere il tragitto anche sul BOT. -// ++Todo: TOGLIERE! - x- AGGIONARE AMBIENTE DI TEST - ESEGUIRE LA CONVERSIONE 1 E 2 ! -- CHECK getProssimiInLista -X - CONTROLLARE arrIdTelegramUsers - -- TESTARE SOSTITUISCI UTENTE DA NAVE - -- TESTARE AGGIUNGI VIAGGIO - -x- Accorpare tutti i sotto account, in 1 unico ! -x - Nel campo note, metterci l'username vecchio. x - Sistemare le navi con num_tess === 4 : indorder=0 e 46 : Prendere quelli del num_tess === 3 e SOSTITUISCI ind_order del num_Tess = 4 con ind_order di num_tess = 3 @@ -41,7 +37,6 @@ x - Sistemare le navi con num_tess === 4 : indorder=0 e 46 : SOSTITUISCI: - - Mettere flag se si vuole spostare l'Utente oppure Aggiungerlo... - Sistemare che in Edit Pagina, se è troppo grande, va oltre l'altezza della finestra. @@ -55,7 +50,5 @@ SOSTITUISCI: TRADURRE: -'Giorno in cui Inviare il DONO': 'Hai 4 giorni di tempo per inviare il tuo dono. Giorno di Chiusura:', - - Mettere le bandierine nella lista Zoom (su AYNI BOT). diff --git a/src/server/models/listaingresso.js b/src/server/models/listaingresso.js index dec3af6..99078c0 100755 --- a/src/server/models/listaingresso.js +++ b/src/server/models/listaingresso.js @@ -171,6 +171,12 @@ ListaIngressoSchema.statics.deleteUserInListaIngresso = async function (idapp, u }; +ListaIngressoSchema.statics.getNumDaImbarcare = async function (idapp) { + const ListaIngresso = this; + + return await ListaIngresso.count({ idapp, added: false, deleted: false }) + +}; ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, username, invitante_username, lang, addednowreal, nuovo, dateins, note, added, opt) { const ListaIngresso = this; @@ -212,8 +218,19 @@ ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, user if (addednowreal) { if (!!ris) { const nome = await User.getNameSurnameByUsername(idapp, username); - msgtext = '🔵 ' + nome + ' (' + username + ') ' + tools.gettranslate('ADDED_TOLISTAINGRESSO', lang); - await telegrambot.sendMsgTelegram(idapp, username, msgtext, true); // Anche a STAFF + const numimbarcare = await ListaIngresso.getNumDaImbarcare(idapp); + let msgtext = '🛳 '; + msgtext += nome + ' (' + username + ') ' + tools.gettranslate('ADDED_TOLISTAINGRESSO', lang); + await telegrambot.sendMsgTelegram(idapp, username, msgtext, false); + + msgtext = '🛳 '; + if (nuovo) { + msgtext += '🌠 '; + } + + const msgadd = msgtext + ' [' + numimbarcare + '] Imbarcare ' + nome + ' (' + username + ') '; + + await telegrambot.sendMsgTelegramToTheManagers(idapp, msgadd, false); // Anche a STAFF if (!!opt) { if (!!opt.sendmsgtoinvitante) { @@ -458,6 +475,22 @@ ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuov return arrrec; }; +ListaIngressoSchema.statics.eliminaListeIngressoNascoste = async function (idapp) { + const ListaIngresso = this; + + const { User } = require('./user'); + + const arrIngr = await ListaIngresso.find({ idapp, deleted: true }); + + for (const ingr of arrIngr) { + const user = await User.findOne({ idapp, old_order: ingr.ind_order }); + if (!user) { + await ListaIngresso.deleteOne({ _id: ingr._id }) + } + } + +}; + ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { const ListaIngresso = this; @@ -501,6 +534,7 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { .then((mynave) => { if (!!mynave) { ingr.date_added = mynave.created; + ingr.deleted = false; ingr.added = true; } return !!mynave; @@ -580,7 +614,7 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { for (const myuser of arrIdTelegramUsers) { // Crea 1 record listaingresso per ogni record aggiuntivo ! escludendo il primo! - if (teleg_id !== myuser.profile.teleg_id) { + if (teleg_id !== myuser.profile.teleg_id && myuser.old_order > 0) { index = 0; teleg_id = myuser.profile.teleg_id; username = myuser.username; @@ -605,7 +639,7 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { } }, { new: false }); - await Nave.updateMany({idapp, ind_order}, { + await Nave.updateMany({ idapp, ind_order }, { $set: { note: findlistaingresso.username, } @@ -666,17 +700,21 @@ ListaIngressoSchema.statics.getarray = async function (idapp, filtri, myobjField }; -ListaIngressoSchema.statics.getInvitati = async function (idapp, username, myobjField) { +ListaIngressoSchema.statics.getInvitati = async function (idapp, username, includemyself, myobjField) { const ListaIngresso = this; - return ListaIngresso.getarray(idapp, - { - idapp, - deleted: false, - invitante_username: username, - username: { $ne: username }, - }, - myobjField); + let myq = { + idapp, + deleted: false, + invitante_username: username, + }; + + if (!includemyself) { + myq = { ...myq, username: { $ne: username } } + } + + return ListaIngresso.getarray(idapp, myq, myobjField); + }; @@ -708,7 +746,7 @@ ListaIngressoSchema.statics.getnumInvitati = async function (idapp, username) { idapp, invitante_username: username, deleted: false, - username: { $ne: username }, + // username: { $ne: username }, }, { username: 1 }); const { User } = require('./user'); @@ -720,10 +758,10 @@ ListaIngressoSchema.statics.getnumInvitati = async function (idapp, username) { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] }); - for (const inv of arrinv) { + /*for (const inv of arrinv) { if (!arrlistainv.find((rec) => rec.username === inv.username)) arrlistainv.push(inv); - } + }*/ if (!!arrlistainv) return arrlistainv.length; @@ -745,7 +783,7 @@ ListaIngressoSchema.statics.getnumInvitatiAttivi = async function (idapp, userna let myquery = getQueryProj({ idapp, invitante_username: username, - username: { $ne: username }, + // username: { $ne: username }, deleted: false, }, { username: 1, ind_order: 1 }, @@ -764,10 +802,11 @@ ListaIngressoSchema.statics.getnumInvitatiAttivi = async function (idapp, userna $and: User.getQueryQualified() }); + /* for (const inv of arrinv) { if (!arrlistainv.find((rec) => rec.username === inv.username)) arrlistainv.push(inv); - } + }*/ if (!!arrlistainv) return arrlistainv.length; diff --git a/src/server/models/nave.js b/src/server/models/nave.js index 22931f3..f2452f0 100755 --- a/src/server/models/nave.js +++ b/src/server/models/nave.js @@ -160,7 +160,7 @@ NaveSchema.statics.findById = function (idapp, id) { } else { return null; } - }catch (e) { + } catch (e) { console.error(e.message); } }); @@ -453,13 +453,13 @@ function getQueryProj(myfilter) { } }, { - $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$mylista", 0 ] }, "$$ROOT" ] } } + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$mylista", 0] }, "$$ROOT"] } } }, { $lookup: { from: "users", as: "user", - let: {username: '$username' }, + let: { username: '$username' }, pipeline: [ { $match: { @@ -723,13 +723,22 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in let recnavepersistente = await NavePersistente.findByRigaCol(idapp, riga, col, 0); - mystr = '🌈' + tools.get__('SOGNATORE', lang) + ': '; - for (let indsogn = 0; indsogn < recsognatori.length; indsogn++) { - mystr += 'A' + (3 - indsogn) + await getusertextbyrec(recsognatori[indsogn], '', '', riga, col, '') + tools.ACAPO; + mystr = '7️⃣° 🌈 ' + tools.get__('SOGNATORE', lang) + ': '; + mystr += '' + await getusertextbyrec(recsognatori[0], '', '', riga, col, '') + '' + tools.ACAPO; + for (let indsogn = 1; indsogn < recsognatori.length; indsogn++) { + if (indsogn === 1) + mystr += '6️⃣°'; + else + mystr += '5️⃣°'; + + mystr += ' ' + tools.get__('INTERMEDIO', lang) + ': '; + + mystr += await getusertextbyrec(recsognatori[indsogn], '', '', riga, col, '') + tools.ACAPO; } - mystr += tools.ACAPO + '🌀 ' + tools.get__('MEDIATORE', lang) + ':' + await getusertextbyrec(recmediatore, '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; + mystr += tools.ACAPO + '4️⃣° 🌀 ' + tools.get__('MEDIATORE', lang) + ':' + await getusertextbyrec(recmediatore, '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; + mystr += '3️⃣° ' + tools.get__('INTERMEDIO', lang) +':' + tools.ACAPO; for (let indterra = 1; indterra <= 2; indterra++) { miacol = calcval(riga, col, 2) + (indterra); miariga = riga + 1; @@ -739,6 +748,7 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in mystr += tools.ACAPO; + mystr += '2️⃣° ' + tools.get__('INTERMEDIO', lang) + ':' + tools.ACAPO; for (let indaria = 1; indaria <= 4; indaria++) { miacol = calcval(riga, col, 4) + (indaria); miariga = riga + 2; @@ -750,7 +760,7 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in let primofuoco = null; - mystr += '🎁 ' + tools.get__('DONATORI', lang) + ':' + tools.ACAPO; + mystr += '1️⃣° 🎁 ' + tools.get__('DONATORI', lang) + ':' + tools.ACAPO; let donitotali = 0; let donifatti = 0; @@ -794,7 +804,7 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in if (!!recnavepersistente.tutor_namesurname) data += '👤 ' + tools.get__('Tutor che affianchèra il Mediatore', lang) + ': "' + recnavepersistente.tutor_namesurname + '"' + tools.ACAPO; - data += '💬 ' + printf(tools.get__('APERTURA_CHIUSURA_GIFT_CHAT', lang), tools.getstrDateLong(recnavepersistente.date_gift_chat_open, lang), tools.getstrDateLong(recnavepersistente.date_start, lang)) + tools.ACAPO; + data += '💬 ' + printf(tools.get__('APERTURA_CHIUSURA_GIFT_CHAT', lang), tools.getstrDateLong(recnavepersistente.date_gift_chat_open, lang), tools.getstrDateLong(recnavepersistente.date_start, lang)) + tools.ACAPO; // data += '💬 ' + tools.get__('Giorno di Apertura GIFT CHAT', lang) + ': ' + tools.getstrDateLong(recnavepersistente.date_gift_chat_open, lang) + tools.ACAPO; @@ -1398,7 +1408,7 @@ NaveSchema.statics.getnumNaviByUsername = async function (idapp, username) { // Get array di ind_order const arrind_order = await ListaIngresso.find({ idapp, username }).distinct('ind_order'); - const arrrec = await Nave.find({ idapp, ind_order: arrind_order, num_tess: { $mod: [ 2 , 1] } }, { + const arrrec = await Nave.find({ idapp, ind_order: arrind_order, num_tess: { $mod: [2, 1] } }, { riga: 1, col: 1, ind_order: 1 @@ -1409,7 +1419,7 @@ NaveSchema.statics.getnumNaviByUsername = async function (idapp, username) { else return 0; - }catch (e) { + } catch (e) { console.error(e.message); } }; @@ -1435,7 +1445,6 @@ NaveSchema.statics.getSognatoreByRigaColMediatore = async function (idapp, navem }; - const Nave = mongoose.model('Nave', NaveSchema); module.exports = { Nave }; diff --git a/src/server/models/user.js b/src/server/models/user.js index 8ac6f40..4d998b5 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -445,12 +445,12 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) return myrec }; -UserSchema.statics.getDownlineByUsername = async function (idapp, username) { +UserSchema.statics.getDownlineByUsername = async function (idapp, username, includemyself) { if (username === undefined) return null; - const arrrec = await ListaIngresso.getInvitati(idapp, username, + const arrrec = await ListaIngresso.getInvitati(idapp, username, includemyself, { index: 1, lang: 1, @@ -474,12 +474,18 @@ UserSchema.statics.getDownlineByUsername = async function (idapp, username) { } ); - // Ottieni gli invitati che ancora non hanno un'imbarco - const arrinv = await User.find({ + let myq = { idapp, aportador_solidario: username, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] - }); + }; + + if (!includemyself) { + myq = { ...myq, username: {$ne: username} } + } + + // Ottieni gli invitati che ancora non hanno un'imbarco + const arrinv = await User.find(myq); for (const inv of arrinv) { if (!arrrec.find((rec) => rec.username === inv.username)) @@ -1153,16 +1159,16 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us if (!!arrap) dashboard.numpeople_aportador = arrap.length; - dashboard.downline = await User.getDownlineByUsername(idapp, username); + dashboard.downline = await User.getDownlineByUsername(idapp, username, true); // dashboard.downnotreg = await ExtraList.getDownlineNotRegisteredByNameSurname(idapp, dashboard.myself.name + ' ' + dashboard.myself.surname); dashboard.downbyuser = {}; for (const down of dashboard.downline) { - dashboard.downbyuser[down.username] = await User.getDownlineByUsername(idapp, down.username); + dashboard.downbyuser[down.username] = await User.getDownlineByUsername(idapp, down.username, false); for (const down2 of dashboard.downbyuser[down.username]) { - dashboard.downbyuser[down2.username] = await User.getDownlineByUsername(idapp, down2.username); + dashboard.downbyuser[down2.username] = await User.getDownlineByUsername(idapp, down2.username, false); } } diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index bb7976d..a9b1af2 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -543,6 +543,8 @@ router.patch('/callfunz', authenticate, async (req, res) => { username_da_sostituire = mydata.data.username_da_sostituire; + let myuservecchio = await User.findOne({ idapp, username: username_da_sostituire }); + mianavedasost = await Nave.findOne({ idapp, riga: mydata.data.riga, col: mydata.data.col }); if (!!mianavedasost) { @@ -574,8 +576,9 @@ router.patch('/callfunz', authenticate, async (req, res) => { } } - if (!!myuser) { + if (!!myusernuovo) { if (!!mianavedasost && mianavedasost.ind_order >= 0) { + // Metti campo 'delete': true su ListaIngresso olduseringresso = await ListaIngresso.findOne({ idapp, ind_order: mianavedasost.ind_order }); if (!!olduseringresso) { @@ -587,14 +590,14 @@ router.patch('/callfunz', authenticate, async (req, res) => { } } - if (!!myuser) { + if (!!myuservecchio) { if (mydata.data.deleteUser && !!mianavedasost && mianavedasost.ind_order > 0) { // Metti Deleted allo User fieldsvalue = { deleted: true }; - await User.findByIdAndUpdate(myuser.id, { $set: fieldsvalue }); - await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuser.name} ${myuser.surname} (${myuser.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); + await User.findByIdAndUpdate(myuservecchio.id, { $set: fieldsvalue }); + await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuservecchio.name} ${myuservecchio.surname} (${myuservecchio.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); } } @@ -632,27 +635,31 @@ router.patch('/callfunz', authenticate, async (req, res) => { if (!rec) { return res.status(404).send(); } else { + // Send Notification to the BOT + let messaggio = tools.get__('SPOSTATO', req.user.lang); + + if (!!navepersistente.date_start) { + messaggio += tools.ACAPO + tools.get__('DATA_PART_NAVE', req.user.lang) + tools.getstrDateLong(navepersistente.date_gift_chat_open) + tools.ACAPO; + } + if (!!navepersistente.link_chat) { + messaggio += tools.ACAPO + '👉🏻👉🏻 ' + tools.get__('ENTRA_GIFT_CHAT', req.user.lang) + ' ' + tools.ACAPO; + } + + const myplacca = await Nave.getNavePos(idapp, navepersistente.riga, navepersistente.col); + messaggio += tools.ACAPO + myplacca; + + const mymsg = mydata.notifBot.txt + ' ' + myusernuovo.name + ' ' + myusernuovo.surname + ' [da ' + dachi + ']' + tools.ACAPO + 'Inviato messaggio: ' + messaggio; + if (mydata.data.notifBot && !!navepersistente.link_chat) { - // Send Notification to the BOT - let messaggio = tools.get__('SPOSTATO', req.user.lang); - - if (!!navepersistente.date_start) { - messaggio += tools.ACAPO + tools.get__('DATA_PART_NAVE', req.user.lang) + tools.getstrDateLong(navepersistente.date_gift_chat_open) + tools.ACAPO; - } - if (!!navepersistente.link_chat) { - messaggio += tools.ACAPO + '👉🏻👉🏻 ' + tools.get__('ENTRA_GIFT_CHAT', req.user.lang) + ' ' + tools.ACAPO; - } - - const myplacca = await Nave.getNavePos(idapp, navepersistente.riga, navepersistente.col); - messaggio += tools.ACAPO + myplacca; await telegrambot.sendMsgTelegram(idapp, myusernuovo.username, messaggio); - await telegrambot.sendMsgTelegramToTheManagers(idapp, mydata.notifBot.txt + ' ' + myusernuovo.name + ' ' + myusernuovo.surname + ' [da ' + dachi + ']' + tools.ACAPO + 'Inviato messaggio: ' + messaggio); + await telegrambot.sendMsgTelegramToTheManagers(idapp, mymsg); await telegrambot.sendMsgTelegram(idapp, req.user.username, mydata.notifBot.txt); await telegrambot.sendMsgTelegram(idapp, req.user.username, myplacca); } + tools.writeManagersLog(mymsg); // const nomecognomeprima = myuser.name + ' ' + myuser.surname + '(' + myuser.username + ')'; // const nomecognomenuovo = await User.getNameSurnameByUsername(idapp,); diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 5df10b2..b9be6bb 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -474,6 +474,9 @@ router.post('/dbop', authenticate, async (req, res) => { } else if (mydata.dbop === 'creaTessituraeConv') { ris = await ListaIngresso.creaTessituraeConv(idapp); ris = { mystr }; + } else if (mydata.dbop === 'eliminaListeIngressoNascoste') { + ris = await ListaIngresso.eliminaListeIngressoNascoste(idapp); + ris = { mystr }; } else if (mydata.dbop === 'convNaviTessinListaIngressoRec') { let num = 0; diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index f0d7db1..69188ea 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -500,7 +500,7 @@ module.exports = { const usersmanagers = await User.getusersManagers(idapp); if (usersmanagers) { for (const rec of usersmanagers) { - await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': ' + text, undefined, undefined, true); + await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + ': ' + text, undefined, undefined, true); await tools.snooze(200) } } @@ -732,7 +732,7 @@ async function local_sendMsgTelegramToTheManagers(idapp, text, msg, username_bo) if (username_bo) username = username_bo; - text = emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': Da ' + msg.chat.first_name + ' ' + msg.chat.last_name + ' (' + username + '): \n' + text; + text = emo.ROBOT_FACE + ': Da ' + msg.chat.first_name + ' ' + msg.chat.last_name + ' (' + username + '): \n' + text; tools.writeEventsLog(text); if (usersmanagers) { @@ -2145,7 +2145,14 @@ class Telegram { async sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec) { - return await this._inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec); + if (text.length > 4096) { + let text1 = text.slice(0, 4096); + let text2 = text.slice(4096, text.length); + await this._inviaMsg(id, text1, form, menu, msg_id, chat_id, ripr_menuPrec); + return await this._inviaMsg(id, text2, form, menu, msg_id, chat_id, ripr_menuPrec); + }else { + return await this._inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec); + } } diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 3c7c032..0ddf3b7 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -99,6 +99,7 @@ textlang = { 'ENTRA_GIFT_CHAT': 'Entra nella Gift Chat', 'DATA_PART_NAVE': 'data di Partenza della Nave:', 'SOGNATORE': 'SOGNATORE', + 'INTERMEDIO': 'Intermedio', 'MEDIATORE': 'MEDIATORE', 'DONATORI': 'DONATORI', 'RITESSITURA': 'RITESSITURA', @@ -167,6 +168,7 @@ textlang = { 'ENTRA_GIFT_CHAT': 'Vstopi v Darilni Klepet', 'DATA_PART_NAVE': 'Datum odhoda ladje:', 'SOGNATORE': 'Sanjača', + 'INTERMEDIO': 'POTNIK', 'MEDIATORE': 'MEDIATOR', 'DONATORI': 'DONATOR', 'RITESSITURA': 'Avtomatičen Vpis', @@ -231,6 +233,7 @@ textlang = { 'ENTRA_GIFT_CHAT': 'Entre en el Chat de Regalos', 'DATA_PART_NAVE': 'fecha de salida de la nave:', 'SOGNATORE': 'SOÑADOR', + 'INTERMEDIO': 'Intermedio', 'MEDIATORE': 'MEDIATOR', 'DONATORI': 'DONANTES', 'RITESSITURA': 'RETEJIDO', @@ -292,6 +295,7 @@ textlang = { 'ENTRA_GIFT_CHAT': 'Enter the ship\'s Gift Chat', 'DATA_PART_NAVE': 'date of departure of the ship:', 'SOGNATORE': 'DREAMER', + 'INTERMEDIO': 'Intermediate', 'MEDIATORE': 'MEDIATOR', 'DONATORI': 'DONOR', 'RITESSITURA': 'RE-ENTER', @@ -357,6 +361,7 @@ textlang = { 'ENTRA_GIFT_CHAT': 'Entrez dans le chat des cadeaux', 'DATA_PART_NAVE': 'la date de départ du navire:', 'SOGNATORE': 'Rêveur', + 'INTERMEDIO': 'Intermediaire', 'MEDIATORE': 'Médiateur', 'DONATORI': 'DONATEUR', 'RITESSITURA': 'RETESSITURA', @@ -422,6 +427,7 @@ textlang = { 'ENTRA_GIFT_CHAT': 'Entre no Gift Chat do navio', 'DATA_PART_NAVE': 'data de partida do navio:', 'SOGNATORE': 'SONHEIROS', + 'INTERMEDIO': 'Intermediar', 'MEDIATORE': 'MEDIATOR', 'DONATORI': 'DONATORES', 'RITESSITURA': 'ENTRE EM', From 1215d28777d672b4d5d65a005add5f30e744c65c Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Thu, 14 May 2020 17:23:17 +0200 Subject: [PATCH 04/14] Ultimo aggiornamento Nuova versione del Sito ! --- docs/passi.txt | 51 ++++-- docs/query_mongodb.js | 28 ++++ src/server/models/listaingresso.js | 109 +++++++++++-- src/server/models/nave.js | 76 +++++++++ src/server/models/user.js | 213 ++++++++++++++++++-------- src/server/router/dashboard_router.js | 38 ++++- src/server/router/index_router.js | 12 +- src/server/router/users_router.js | 28 +++- src/server/telegram/telegrambot.js | 7 +- 9 files changed, 457 insertions(+), 105 deletions(-) create mode 100644 docs/query_mongodb.js diff --git a/docs/passi.txt b/docs/passi.txt index 7708482..4d42b9e 100644 --- a/docs/passi.txt +++ b/docs/passi.txt @@ -3,20 +3,14 @@ AGGIORNARE: // ++Todo: DA FARE: +- Se sei imbarcata i tuoi due invitati usati per quella posizione sono bloccati. Se ne hai in più li puoi regalare + - Mettere il tragitto anche sul BOT. + + TESTARE -> inviare il msg anche al Sognatore della Gift Chat -X - Aggiornare il titolo della Gift Chat (da 5/5 a 12/5) -X - Aggiornare il testo sulla Placca (Data Inizio e Data Fine Doni) // ++Todo: SISTEMARE: - X - Devo comparire come mio invitato se aggiungo un nuovo Viaggio. - X - Fare la lista delle Navi (in alto alla Lavagna) con il loro tragitto. - X- Nel campo note, metterci il Sogno - X - Se nave Temporanea, mettere Info. - X- Mettere flag se si vuole spostare l'Utente oppure Aggiungerlo... - - - Mettere Sfondo immagine su ogni nave - - Mettere il tragitto anche sul BOT. x- AGGIONARE AMBIENTE DI TEST @@ -28,7 +22,7 @@ x - Sistemare le navi con num_tess === 4 : indorder=0 e 46 : ------------- - AGGIONARE AMBIENTE DI PRODUZIONE -- ESEGUIRE LA CONVERSIONE 1 E 2 ! +- ESEGUIRE LA CONVERSIONE 1 E 2 e ! - Sistemare le navi con num_tess === 4 : indorder=0 e 46 : Prendere quelli del num_tess === 3 e SOSTITUISCI ind_order del num_Tess = 4 con ind_order di num_tess = 3 @@ -52,3 +46,38 @@ SOSTITUISCI: TRADURRE: - Mettere le bandierine nella lista Zoom (su AYNI BOT). + + +1- mi appaiono prima le navi del secondo account +2- forse metterei ogni nave seguita dal relativo viaggio di "ritorno" (a me piace chiamarlo così!) +X 3- sotto le navi, alla voce donatore, c'è ancora scritto "Effettuerai il tuo dono ESATTAMENTE il giorno indicato" +X 4- nei miei invitati non compaiono le mie ritessiture, fatte con il magico bottone, da chi sono invitata? + + +- Controllare Tragitto (Elisabetta) +- Monica Sozzi -> Davide Moirano (0) è giusto. + - Andrea Decouter (2) + - Enrica Pescio (OK) + - 852 (Gerico2) Elio2 Garelli -> (Gerico) + +Andrea 346 + +ind_order: 231 Gerico Elio Garelli +ind_order: 852 Gerico2 Elio2 Garelli + + +Morgana Roveta (Maelabo) + --- Gerico Elio Garelli + + +ANDREA + |-----GERICO2 852 + + + +.update({}, {$unset: {$ind_order: 1}, {multi: true}); + + + + + diff --git a/docs/query_mongodb.js b/docs/query_mongodb.js new file mode 100644 index 0000000..c948710 --- /dev/null +++ b/docs/query_mongodb.js @@ -0,0 +1,28 @@ +db.getCollection('users').aggregate([ + { $match: { idapp: '7', username:'Emycapp' } }, + { + $lookup: { + from: "naves", + as: "ingr", + let: { ind_order: '$ind_order' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$ind_order', '$$ind_order'] }, + ] + } + } + } + ] + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$ingr", 0] }, "$$ROOT"] } } + }, + { + $match: { made_gift: { $exists: true } } + } + +]) diff --git a/src/server/models/listaingresso.js b/src/server/models/listaingresso.js index 99078c0..678f594 100755 --- a/src/server/models/listaingresso.js +++ b/src/server/models/listaingresso.js @@ -43,6 +43,9 @@ const ListaIngressoSchema = new mongoose.Schema({ date_added: { type: Date, }, + date_deleted: { + type: Date, + }, added: { // Added into Programmation (Nave) type: Boolean, default: false, @@ -311,6 +314,50 @@ function getQueryProj(myfilter, myobjField, myfilter2, mygroup) { return query; } +function getQueryIndOrder(myfilter, myobjField, myfilter2, mygroup) { + const query = [ + { $match: myfilter }, + { + $lookup: { + from: "users", + as: "user", + let: { ind_order: '$ind_order' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$ind_order', '$$ind_order'] }, + { $eq: ['$idapp', myfilter.idapp] }, + ] + } + } + } + ] + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] }, "$$ROOT"] } } + }, + { $match: myfilter2 }, + ]; + + if (!!mygroup) { + query.push( + { $group: mygroup } + ); + } + + if (!!myobjField) { + query.push( + { $project: myobjField } + ); + } + + return query; +} + + ListaIngressoSchema.statics.getPosizioneInLista = async function (idapp, arrrec, ind_order, num_tess) { @@ -338,9 +385,11 @@ ListaIngressoSchema.statics.showListaOrd = async function (idapp, solonuovi) { let mystr = ''; let conta = 1; for (const rec of arrrec) { - mystr += conta + ' - ' + ' [' + rec.numinvitatiattivi + '] - [' + rec.numinvitati + '] (' + rec.ind_order + ') ' + rec.username + ' ' + rec.name + ' ' + rec.surname; + mystr += conta + '- ' + ' [' + rec.numinvitatiattivi + '-' + rec.numinvitati + '] (' + rec.index + ') '; + mystr += ' [' + tools.getstrDateShort(rec.date_added, 'it') + '] '; + mystr += rec.username + ' ' + rec.name + ' ' + rec.surname; mystr += ' inv = ' + rec.invitante_username; - mystr += ' num_tess = ' + rec.num_tess; + mystr += ' tess = ' + rec.num_tess; if (rec.added) mystr += ' (ADDED ++)'; @@ -388,6 +437,7 @@ ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuov let myobjField = { idapp: 1, + index: 1, ind_order: 1, name: 1, surname: 1, @@ -396,6 +446,7 @@ ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuov email: 1, lang: 1, num_tess: 1, + date_added: 1, added: 1, deleted: 1, sospeso: 1, @@ -491,6 +542,14 @@ ListaIngressoSchema.statics.eliminaListeIngressoNascoste = async function (idapp }; +ListaIngressoSchema.statics.RendiVisibileIrecordNascosti = async function (idapp) { + const ListaIngresso = this; + + const num = await ListaIngresso.updateMany({ idapp, deleted: true }, { $set: { deleted: false } }); + +}; + + ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { const ListaIngresso = this; @@ -513,8 +572,6 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { idapp, }); - // Ricalcola il Campo Index - await User.ricalcolaIndex(idapp); // Ricrea i record ListaIngresso (num_tess = 1), per ogni User for (const user of arrusers) { @@ -634,7 +691,7 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { await ListaIngresso.findByIdAndUpdate(findlistaingresso._id, { $set: { username, - invitante_username, + // invitante_username, note: findlistaingresso.username, } }, { new: false }); @@ -652,7 +709,7 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { } // poi imposta come cancellato questo record - await User.findByIdAndUpdate(myuser._id, { $set: { deleted: true } }); + await User.findByIdAndUpdate(myuser._id, { $set: { deleted: true, date_deleted: new Date() } }); } } @@ -660,6 +717,13 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { index++; } + // RIMUOVI IL CAMPO IND_ORDER SULLA USER! + await User.update({}, {$unset: {ind_order: 1}}, {multi: true}); + + // Ricalcola il Campo Index + await User.ricalcolaIndex(idapp); + + return index; } catch (e) { @@ -684,6 +748,13 @@ ListaIngressoSchema.statics.getListaTessByUsername = function (idapp, username) ListaIngressoSchema.statics.getarray = async function (idapp, filtri, myobjField) { const ListaIngresso = this; + const { User } = require('./user'); + + if (!await User.NuovoSistema(idapp)) { + return await ListaIngresso.getarrayIndOrder(idapp, filtri, myobjField); + } + + let myfilter2 = { surname: { $exists: true }, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], @@ -699,6 +770,24 @@ ListaIngressoSchema.statics.getarray = async function (idapp, filtri, myobjField }; +ListaIngressoSchema.statics.getarrayIndOrder = async function (idapp, filtri, myobjField) { + const ListaIngresso = this; + + let myfilter2 = { + surname: { $exists: true }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }; + + let myquery = getQueryIndOrder( + filtri, + myobjField, + myfilter2 + ); + + return await ListaIngresso.aggregate(myquery); + +}; + ListaIngressoSchema.statics.getInvitati = async function (idapp, username, includemyself, myobjField) { const ListaIngresso = this; @@ -758,10 +847,10 @@ ListaIngressoSchema.statics.getnumInvitati = async function (idapp, username) { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] }); - /*for (const inv of arrinv) { + for (const inv of arrinv) { if (!arrlistainv.find((rec) => rec.username === inv.username)) arrlistainv.push(inv); - }*/ + } if (!!arrlistainv) return arrlistainv.length; @@ -802,11 +891,11 @@ ListaIngressoSchema.statics.getnumInvitatiAttivi = async function (idapp, userna $and: User.getQueryQualified() }); - /* + for (const inv of arrinv) { if (!arrlistainv.find((rec) => rec.username === inv.username)) arrlistainv.push(inv); - }*/ + } if (!!arrlistainv) return arrlistainv.length; diff --git a/src/server/models/nave.js b/src/server/models/nave.js index f2452f0..2675830 100755 --- a/src/server/models/nave.js +++ b/src/server/models/nave.js @@ -485,6 +485,71 @@ function getQueryProj(myfilter) { return query; } +function getQueryInvitante(myfilter) { + + myobjField = { + ind_order: 1, + name: 1, + surname: 1, + username: 1, + invitante_username: 1, + made_gift: 1, + sent_msg_howto_make_gift: 1, + date_made_gift: 1, + note: 1, + received_gift: 1, + date_received_gift: 1, + num_tess: 1, + parent_id: 1, + riga: 1, + col: 1, + created: 1, + }; + + const query = [ + { $match: myfilter }, + { + $lookup: { + from: "listaingressos", + localField: "ind_order", + foreignField: "ind_order", // field in the user collection + as: "mylista" + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$mylista", 0] }, "$$ROOT"] } } + }, + { + $lookup: { + from: "users", + as: "user", + let: { username: '$username' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$username', '$$username'] }, + { $eq: ['$idapp', myfilter.idapp] }, + ] + } + } + } + ] + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] }, "$$ROOT"] } } + // $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] },] } } + }, + { $match: { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] } }, + { $project: myobjField } + ]; + + return query; +} + + NaveSchema.statics.setRiga = function (idapp, riga) { return Settings.setKeyNum(idapp, 'riga', riga); @@ -848,11 +913,22 @@ NaveSchema.statics.getArrPosizioniByUsername = async function (idapp, username) let arrposizioni = []; + for (const ind_order of arrrec_indorder) { + const myquery = getQueryInvitante({ idapp, ind_order }); + + const arr = await Nave.aggregate(myquery).sort({ riga: 1, col: 1 }); + if (!!arr) + arrposizioni = [...arrposizioni, ...arr]; + } + + + /* for (const ind_order of arrrec_indorder) { const arr = await Nave.find({ 'idapp': idapp, ind_order }).sort({ riga: 1, col: 1 }); if (!!arr) arrposizioni = [...arrposizioni, ...arr]; } + */ return arrposizioni; } catch (e) { diff --git a/src/server/models/user.js b/src/server/models/user.js index 4d998b5..3650d25 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -115,6 +115,9 @@ const UserSchema = new mongoose.Schema({ date_reg: { type: Date, }, + date_deleted: { + type: Date, + }, date_tokenforgot: { type: Date }, @@ -143,7 +146,8 @@ const UserSchema = new mongoose.Schema({ type: String, }, deleted: { - type: Boolean + type: Boolean, + default: false }, sospeso: { type: Boolean @@ -445,12 +449,12 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) return myrec }; -UserSchema.statics.getDownlineByUsername = async function (idapp, username, includemyself) { +UserSchema.statics.getDownlineByUsername = async function (idapp, username, includemyself, onlynumber) { if (username === undefined) return null; - const arrrec = await ListaIngresso.getInvitati(idapp, username, includemyself, + let arrrec = await ListaIngresso.getInvitati(idapp, username, includemyself, { index: 1, lang: 1, @@ -481,7 +485,7 @@ UserSchema.statics.getDownlineByUsername = async function (idapp, username, incl }; if (!includemyself) { - myq = { ...myq, username: {$ne: username} } + myq = { ...myq, username: { $ne: username } } } // Ottieni gli invitati che ancora non hanno un'imbarco @@ -489,16 +493,35 @@ UserSchema.statics.getDownlineByUsername = async function (idapp, username, incl for (const inv of arrinv) { if (!arrrec.find((rec) => rec.username === inv.username)) - arrrec.push(inv); + arrrec.push(inv._doc); } + const arrusername = []; - if (!!arrrec) { - for (const rec of arrrec) { - rec.qualified = await User.isUserQualified7(idapp, rec.username); - rec.numNaviEntrato = await Nave.getnumNaviByUsername(idapp, rec.username); - rec.numinvitati = await ListaIngresso.getnumInvitati(idapp, rec.username); - rec.numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, rec.username); + for (const inv of arrrec) { + + const rectrovato = arrusername.find((rec) => inv.username === rec.username); + if (!!rectrovato) { + rectrovato.quanti++; + } else { + const myrec = { ...inv }; + myrec.quanti = 1; + arrusername.push(myrec) + } + + } + + arrrec = arrusername; + + + if (!onlynumber) { + if (!!arrrec) { + for (const rec of arrrec) { + rec.qualified = await User.isUserQualified7(idapp, rec.username); + rec.numNaviEntrato = await Nave.getnumNaviByUsername(idapp, rec.username); + rec.numinvitati = await ListaIngresso.getnumInvitati(idapp, rec.username); + rec.numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, rec.username); + } } } return arrrec; @@ -928,7 +951,7 @@ UserSchema.statics.getSmallRecByIndOrder = async function (idapp, ind_order) { { idapp, ind_order, - deleted: false, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] }, { idapp: 1, @@ -953,15 +976,44 @@ UserSchema.statics.getSmallRecByIndOrder = async function (idapp, ind_order) { }; -UserSchema.statics.getRecByIndOrder = async function (idapp, ind_order) { +UserSchema.statics.NuovoSistema = function (idapp) { + const User = this; try { + return User.findOne({ idapp, old_order: { $exists: true } }) + .then((ris) => { + return !!ris; + }); + } catch (e) { + console.error('NuovoSistema', e.message); + } + +}; + + +UserSchema.statics.getRecByIndOrder = async function (idapp, ind_order) { + const User = this; + + try { + + let filters = { + idapp: 1, + index: 1, + ind_order: 1, + old_order: 1, + username: 1, + name: 1, + lang: 1, + surname: 1, + 'profile.teleg_id': 1, + }; + const rec = await ListaIngresso.getarray(idapp, { idapp, ind_order, - deleted: false, - }); + }, + filters); if (!!rec) return rec[0]; @@ -1139,7 +1191,6 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us // DATA: username, name, surname, email, intcode_cell, cell const dashboard = { aportador: {}, - downline: [], arrposizioni: [], arrimbarchi: [], arrusers: {}, @@ -1152,26 +1203,10 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us // dashboard.aportador = await ExtraList.getUserNotRegisteredByNameSurname(idapp, aportador_solidario_nome_completo); // } - dashboard.downline = []; - - // Data of my Downline - const arrap = await User.getDownlineByUsername(idapp, username); + const arrap = await User.getDownlineByUsername(idapp, username, false, true); if (!!arrap) dashboard.numpeople_aportador = arrap.length; - dashboard.downline = await User.getDownlineByUsername(idapp, username, true); - // dashboard.downnotreg = await ExtraList.getDownlineNotRegisteredByNameSurname(idapp, dashboard.myself.name + ' ' + dashboard.myself.surname); - - dashboard.downbyuser = {}; - - for (const down of dashboard.downline) { - dashboard.downbyuser[down.username] = await User.getDownlineByUsername(idapp, down.username, false); - - for (const down2 of dashboard.downbyuser[down.username]) { - dashboard.downbyuser[down2.username] = await User.getDownlineByUsername(idapp, down2.username, false); - } - } - dashboard.arrimbarchi = await ListaIngresso.findAllByUsername(idapp, username); // dashboard.arrprofili = await Nave.getArrProfiliByIndOrder(idapp, dashboard.myself.ind_order); @@ -1193,8 +1228,8 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us dashboard.lastnave = await NavePersistente.getLastNave(idapp); for (let mypos of dashboard.arrposizioni) { - mypos._doc.rec = await Nave.getNaveByRigaCol(idapp, mypos.riga, mypos.col); - mypos._doc.nave_partenza = await NavePersistente.findByRigaColByDonatore(idapp, mypos.riga, mypos.col, 0); + mypos.rec = await Nave.getNaveByRigaCol(idapp, mypos.riga, mypos.col); + mypos.nave_partenza = await NavePersistente.findByRigaColByDonatore(idapp, mypos.riga, mypos.col, 0); } @@ -1205,40 +1240,53 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us const arrnew = []; - for (let mypos of dashboard.arrposizioni) { - // Controlla se è presente la Nave con il num_tess pari + try { + for (let mypos of dashboard.arrposizioni) { + // Controlla se è presente la Nave con il num_tess pari - let trovato = false; + let trovato = false; - if (mypos.num_tess % 2 !== 0) { - for (let myrec of dashboard.arrposizioni) { - if (myrec.num_tess === mypos.num_tess + 1 && (myrec.ind_order === mypos.ind_order)) { - // La Nave di Ritorno (numtess = 2) esiste nella lista ! - trovato = true + if (mypos.num_tess % 2 !== 0) { + for (let myrec of dashboard.arrposizioni) { + if (myrec.num_tess === mypos.num_tess + 1 && (myrec.ind_order === mypos.ind_order)) { + // La Nave di Ritorno (numtess = 2) esiste nella lista ! + trovato = true; + break; + } + } + } else { + trovato = true; + } + if (!trovato) { + let myr = null; + if (!!mypos._doc) + myr = mypos._doc; + else + myr = mypos; + + if (!!myr && !!myr.rec.mediatore) { + const mymediatore = myr.rec.mediatore.arrdonatori[7]; + if (!!mymediatore) { + const myrec = { + riga: mymediatore.riga, + col: mymediatore.col, + name: myr.rec.mediatore.recmediatore.name, + surname: myr.rec.mediatore.recmediatore.surname, + username: myr.rec.mediatore.recmediatore.username, + num_tess: myr.rec.mediatore.recmediatore.num_tess + 1, + rec: await Nave.getNaveByRigaCol(idapp, mymediatore.riga, mymediatore.col), + nave_partenza: {}, + }; + + myrec.nave_partenza = await NavePersistente.findByRigaColByDonatore(idapp, myrec.riga, myrec.col, 0); + + arrnew.push(myrec); + } } } - } else { - trovato = true; - } - if (!trovato) { - const mymediatore = mypos._doc.rec.mediatore.arrdonatori[7]; - if (!!mymediatore) { - const myrec = { - riga: mymediatore.riga, - col: mymediatore.col, - name: mypos._doc.rec.mediatore.recmediatore.name, - surname: mypos._doc.rec.mediatore.recmediatore.surname, - username: mypos._doc.rec.mediatore.recmediatore.username, - num_tess: mypos._doc.rec.mediatore.recmediatore.num_tess + 1, - rec: await Nave.getNaveByRigaCol(idapp, mymediatore.riga, mymediatore.col), - nave_partenza: {}, - }; - - myrec.nave_partenza = await NavePersistente.findByRigaColByDonatore(idapp, myrec.riga, myrec.col, 0); - - arrnew.push(myrec); - } } + } catch (e) { + console.error(e.message); } dashboard.arrposizioni = [...dashboard.arrposizioni, ...arrnew]; @@ -1252,6 +1300,38 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us } }; +UserSchema.statics.getDownline = async function (idapp, aportador_solidario, username) { + try { + + // DATA: username, name, surname, email, intcode_cell, cell + let downline = {}; + + downline.downline = []; + + // Data of my Downline + const arrap = await User.getDownlineByUsername(idapp, username); + 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); + + for (const down2 of downline.downbyuser[down.username]) { + downline.downbyuser[down2.username] = await User.getDownlineByUsername(idapp, down2.username, false); + } + } + + return downline; + } catch (e) { + console.error(e.message); + return false; + } +}; + /* UserSchema.statics.fixUsername = async function (idapp, aportador_solidario_ind_order, username) { const User = this; @@ -1780,7 +1860,10 @@ UserSchema.statics.getUsernameByIndex = async function (idapp, index) { UserSchema.statics.ricalcolaIndex = async function (idapp) { const User = this; - const arrusers = await User.find({ idapp }).sort({ ind_order: 1 }); + const arrusers = await User.find({ + idapp, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + }).sort({ old_order: 1 }); let index = 0; try { for (const user of arrusers) { diff --git a/src/server/router/dashboard_router.js b/src/server/router/dashboard_router.js index 0319278..352561a 100755 --- a/src/server/router/dashboard_router.js +++ b/src/server/router/dashboard_router.js @@ -33,13 +33,6 @@ router.post('/', authenticate, async (req, res) => { let aportador_solidario = req.user.aportador_solidario; let aportador_solidario_nome_completo = req.user.aportador_solidario_nome_completo; - // if (User.isAdmin(req.user.perm) || User.isManager(req.user.perm)) { - // const recuser = await User.findByUsername(idapp, username); - // if (recuser) { - // aportador_solidario_nome_completo = recuser.name + ' ' + recuser.surname; - // } - // } - if (username) { aportador_solidario = await User.getAportadorSolidarioByUsername(idapp, username); aportador_solidario_nome_completo = await User.getNameSurnameByUsername(idapp, username); @@ -59,6 +52,37 @@ router.post('/', authenticate, async (req, res) => { }); +router.post('/downline', authenticate, async (req, res) => { + try { + const idapp = req.body.idapp; + let username = req.body.username; + + if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) && (username) !== req.user.username) { + // If without permissions, exit + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + } + let aportador_solidario = req.user.aportador_solidario; + let aportador_solidario_nome_completo = req.user.aportador_solidario_nome_completo; + + if (username) { + aportador_solidario = await User.getAportadorSolidarioByUsername(idapp, username); + aportador_solidario_nome_completo = await User.getNameSurnameByUsername(idapp, username); + } else { + username = req.user.username; + } + + const downline = await User.getDownline(idapp, aportador_solidario, username, aportador_solidario_nome_completo); + if (downline) + res.send({ downline }); + else + res.status(400).send(e); + + } catch (e) { + res.status(400).send(e); + } + +}); + router.post('/msgnave', authenticate, async (req, res) => { const idapp = req.body.idapp; diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index a9b1af2..bd9974e 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -583,6 +583,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { olduseringresso = await ListaIngresso.findOne({ idapp, ind_order: mianavedasost.ind_order }); if (!!olduseringresso) { let fieldsvalue = { + date_deleted: new Date(), deleted: true }; const risul = await ListaIngresso.findByIdAndUpdate(olduseringresso.id, { $set: fieldsvalue }, { new: false }); @@ -591,10 +592,16 @@ router.patch('/callfunz', authenticate, async (req, res) => { } if (!!myuservecchio) { + // Se ha gia delle altre navi, non cancellarlo! + Nave.checkIfMadeGift(idapp, ) + const noncanc = await Nave.findOne({idapp, ind_order: mianavedasost.ind_order, made_gift: true }); + + if (mydata.data.deleteUser && !!mianavedasost && mianavedasost.ind_order > 0) { // Metti Deleted allo User fieldsvalue = { - deleted: true + deleted: true, + date_deleted: new Date(), }; await User.findByIdAndUpdate(myuservecchio.id, { $set: fieldsvalue }); await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuservecchio.name} ${myuservecchio.surname} (${myuservecchio.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); @@ -763,7 +770,8 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { if (tablename === 'users') { let fieldsvalue = { - deleted: true + deleted: true, + date_deleted: new Date(), }; const rec = await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }); diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index b9be6bb..b22b3a6 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -477,31 +477,35 @@ router.post('/dbop', authenticate, async (req, res) => { } else if (mydata.dbop === 'eliminaListeIngressoNascoste') { ris = await ListaIngresso.eliminaListeIngressoNascoste(idapp); ris = { mystr }; + } else if (mydata.dbop === 'RendiVisibileIrecordNascosti') { + ris = await ListaIngresso.RendiVisibileIrecordNascosti(idapp); + ris = { mystr }; } else if (mydata.dbop === 'convNaviTessinListaIngressoRec') { let num = 0; - const arrnavitess = await Nave.find({idapp, num_tess: { $gte: 3 } }); + const arrnavitess = await Nave.find({ idapp, num_tess: { $gte: 3 } }); for (const recnave of arrnavitess) { if (recnave.num_tess === 3 || recnave.num_tess === 5 || recnave.num_tess === 7) { const ind_order = recnave.ind_order; // Prima controlla se ho già 2 record dello stesso ind_order, allora non lo faccio: - const arringr = await ListaIngresso.find({idapp, ind_order}); + const arringr = await ListaIngresso.find({ idapp, ind_order }); let dafare = true; if (arringr.length > 0) { - const arringrtest = await ListaIngresso.find({idapp, ind_order}).distinct('num_tess'); - if (arringr.length !== arringrtest.length){ + const arringrtest = await ListaIngresso.find({ idapp, ind_order }).distinct('num_tess'); + if (arringr.length !== arringrtest.length) { dafare = false; // Ci sono 2 o piu record! pertanto probabilmente l'ho già fatto! } } if (dafare) { - const user = await User.findByOldOrder(idapp, ind_order); + // const user = await User.findByOldOrder(idapp, ind_order); + const user = await User.findByIndOrder(idapp, ind_order); if (!!user) { - let note = recnave.num_tess; + //let note = recnave.num_tess; // Crea record ListaIngresso - const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, user.username, user.username, user.lang, false, true, recnave.created, note, true); + const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, user.username, user.username, user.lang, false, true, recnave.created, '', true); const fieldsvalue = { ind_order: newrecingr.ind_order, @@ -517,6 +521,14 @@ router.post('/dbop', authenticate, async (req, res) => { } } + + const arrnavitess2 = await Nave.find({ idapp, num_tess: 2 }); + + for (const recnave of arrnavitess2) { + + + } + ris = { num }; } else if (mydata.dbop === 'initListaIngresso') { @@ -664,7 +676,7 @@ router.post('/dbop', authenticate, async (req, res) => { } else if (mydata.dbop === 'visuPlacca') { mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' + - 'ECCO LE NUOVE NAVI DEFINITIVE CHE APRONO DOMANI LA GIFT CHAT !!! DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) +'\n' + + 'ECCO LE NUOVE NAVI DEFINITIVE CHE APRONO DOMANI LA GIFT CHAT !!! DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) + '\n' + 'AUGURI ALLA NUOVA SOGNATRICE !!!\n' + '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨'; diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 69188ea..614dc3a 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -1226,8 +1226,9 @@ class Telegram { let mystr = ''; const dashboard = await User.getDashboard(this.idapp, user.aportador_solidario, user.username, user.aportador_solidario_name_surname); + const downline = await User.getDownline(this.idapp, user.aportador_solidario, user.username); - let numpersone = (dashboard.downline) ? dashboard.downline.length : 0; + let numpersone = (downline.downline) ? downline.downline.length : 0; let invitati_attivi = dashboard.myself.numinvitatiattivi; mystr = ""; // if (dashboard.aportador) { @@ -1295,7 +1296,7 @@ class Telegram { mystr += tools.get__('INVITATI_LISTA', this.getlang(msg)) + ':\n'; let index = 1; - dashboard.downline.forEach((user) => { + downline.downline.forEach((user) => { mystr += emoji.get('star-struck') + ` ${index}°: `; mystr += (user.qualified) ? emo.CHECK_VERDE : emo.CROSS_ROSSA; mystr += `${user.name} ${user.surname} (${user.username})\n`; @@ -2115,6 +2116,8 @@ class Telegram { } if (blocked) { User.SetTelegramWasBlocked(this.idapp, id); + + // ++Todo: DA FARE ! local_sendMsgTelegramToTheManagers(this.idapp, addtext + text); } return 0; }); From 591dd4672351c80bb3ffc705e544953514313680 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Tue, 19 May 2020 00:18:13 +0200 Subject: [PATCH 05/14] =?UTF-8?q?=E2=9C=A8=E2=9C=A8=E2=9C=A8=20AGGIORNAMEN?= =?UTF-8?q?TO=20SITO=20=E2=9C=A8=E2=9C=A8=E2=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 👉🏻 E' possibile ora visualizzare la Posizione Reale d'imbarco di quando si verrà aggiunti alle prossime Navi Definitive. Le posizioni verranno aggiornate ogni ora in automatico! 👉🏻 Ora gli imbarchi comprendono anche le navi provvisorie, pertanto è possibile annullarli oppure cambiare l'Invitante, dalla lista imbarchi. 👉🏻 E' ora possibile spostare gli invitati solo se si hanno piu' di 2 invitati per ogni Nave già partita. 👨🏻‍💻 Per i Tutor: 👉🏻- Sostituzioni : Cliccando su "Cerca il Primo Disponibile" vi suggerirà in automatico il primo passeggero disponibile per la sostituzione. ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ --- .env.old | 22 + docs/passi.txt | 50 +- src/server/models/graduatoria.js | 395 ++++++++++++++++ src/server/models/listaingresso.js | 471 +++++++++++++------ src/server/models/nave.js | 107 +++-- src/server/models/navepersistente.js | 32 +- src/server/models/settings.js | 18 + src/server/models/user.js | 28 +- src/server/router/api/actions.js | 57 ++- src/server/router/index_router.js | 131 ++++-- src/server/router/site_router.js | 4 +- src/server/router/users_router.js | 655 ++++++++++++++------------- src/server/server.js | 21 +- src/server/telegram/telegrambot.js | 3 +- src/server/tools/general.js | 19 +- src/server/tools/shared_nodejs.js | 3 + 16 files changed, 1483 insertions(+), 533 deletions(-) create mode 100644 .env.old create mode 100755 src/server/models/graduatoria.js diff --git a/.env.old b/.env.old new file mode 100644 index 0000000..6be4079 --- /dev/null +++ b/.env.old @@ -0,0 +1,22 @@ +DATABASE=Old_FreePlanet +UDB=paofreeplanet +PDB=suerteFreePlanet@1A +SEND_EMAIL=1 +PORT=3002 +ENABLE_PUSHNOTIFICATION=0 +DIRECTORY_SERVER=old.freeplanet_serverside +SERVERDIR_WEBSITE=old.freeplanet_server +URLBASE_APP1=https://old.freeplanet.app +PORT_APP1="0" +DOMAIN=mongodb://localhost:27019/ +SIGNCODE=abc123 +DEBUG=0 +DELAY_SENDEMAIL=1000 +PATH_CERT_KEY=/etc/letsencrypt/live/freeplanet.app/privkey.pem +PATH_SERVER_CRT=/etc/letsencrypt/live/freeplanet.app/fullchain.pem +PUBLIC_VAPI_KEY="" +PRIVATE_VAPI_KEY="" +GCM_API_KEY="" +PROD=0 +PROJECT_DESCR_MAIN='__PROJECTS' +SECRK=iUUb38v23jjDFaosWj92axkBOXCQ diff --git a/docs/passi.txt b/docs/passi.txt index 4d42b9e..db768eb 100644 --- a/docs/passi.txt +++ b/docs/passi.txt @@ -1,10 +1,50 @@ -AGGIORNARE: ------------ -// ++Todo: DA FARE: +// ++Todo: FATTO: DA CONTROLLARE -- Se sei imbarcata i tuoi due invitati usati per quella posizione sono bloccati. Se ne hai in più li puoi regalare - - Mettere il tragitto anche sul BOT. +X - Se sei imbarcata i tuoi due invitati usati per quella posizione sono bloccati. Se ne hai in più li puoi regalare + +- L'ultimo Utente della Creazione della Nave, compare ancora il Sognatore !!! + Sistemato: TESTARE SE ORA È' OK... + + +// ************************************************ + +// ++Todo: PRIORITA' ALTA: + +CONTROLLARE: + + +- Sistemare la Creazione delle Navi... in semi-automatico. + +- Controllare gli Account di Andrea (sembrano mescolati....) socio856 è dentro invece non doveva esserci... + - socio856 non è stato raggruppato con socio85 (Andrea Lai) + + +- Mettere il tragitto anche sul BOT. + +- Inviare il Link che punta alla Pagina del Sito, per effettuare il Dono! + E per eventualmente Entrare nella GIFT CHAT! + + +// ++Todo: PRIORITA' NORMALE: + +- Se entro con la seconda utenza, gli mando messaggio che dice che deve collegarsi con la prima utenza.... + +- Fare funzione che passa un Utente secondario in un utente Primario! (c'è gia) + +- L'orario degli Zoom sul BOT è diverso che dal sito, deve dare quello locale... + +// ++Todo: DA FARE PIU AVANTI: + +- Sistemare poter modificare le Pagine. + +- Per il Fondo Ayni, prevedere anche altri Metodi di Pagamento... Revolut, N26, ecc... + ed inserirlo sul sito per il Sognatore (flag Pagato al Fondo: nave.offerta_al_fondo). + +- Le pagine dovranno andare memorizzate su statics/upload/pages/.... di modo da risparmiare banda. + +- Per Regalare una propria Nave? TESTARE -> inviare il msg anche al Sognatore della Gift Chat @@ -81,3 +121,5 @@ ANDREA +//++TODO: *** FATTI *** + diff --git a/src/server/models/graduatoria.js b/src/server/models/graduatoria.js new file mode 100755 index 0000000..3e1de6e --- /dev/null +++ b/src/server/models/graduatoria.js @@ -0,0 +1,395 @@ +const bcrypt = require('bcryptjs'); +const mongoose = require('mongoose'); +const validator = require('validator'); +const jwt = require('jsonwebtoken'); +const _ = require('lodash'); + +const tools = require('../tools/general'); + +const { ObjectID } = require('mongodb'); + +const { Nave } = require('./nave'); +const { Settings } = require('./settings'); + +const shared_consts = require('../tools/shared_nodejs'); +const queryclass = require('../classes/queryclass'); + +mongoose.Promise = global.Promise; + +mongoose.level = "F"; +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +mongoose.set('debug', process.env.DEBUG); + +const GraduatoriaSchema = new mongoose.Schema({ + idapp: { + type: String, + required: true, + }, + index: { + type: Number, + }, + idListaIngresso: { + type: String, + }, + ind_order: { + type: Number, + }, + num_tess: { + type: Number, + }, + ind: { + type: Number, + }, + // USER: + username: { + type: String, + }, + name: { + type: String, + }, + surname: { + type: String, + }, + indimbarco: { + type: Number, + }, + numNaviEntrato: { // Numero dell'Imbarco attuale + type: Number, + }, + numinvitati: { + type: Number, + }, + numinvitatiattivi: { + type: Number, + }, + numinvitatiTot: { + type: Number, + }, + numinvitatiattiviTot: { + type: Number, + }, + punteggio: { + type: Number, + }, + invitante_username: { + type: String, + }, + date_added: { // Data d'Ingresso (Completato i Requisiti o premuto Bottone Magico) + type: Date, + }, + +}); + +GraduatoriaSchema.pre('save', async function (next) { + if (this.isNew) { + try { + if (!this.index) { + const myrec = await Graduatoria.findOne({ idapp: this.idapp }).limit(1).sort({ index: -1 }); + + if (!!myrec) { + this.index = myrec._doc.index + 1; + } else { + this.index = 1; + } + } + } catch (e) { + this.index = 2; + } + } + + next(); +}); + + +GraduatoriaSchema.statics.findByIndOrder = function (idapp, ind_order) { + const Graduatoria = this; + + try { + return Graduatoria.findOne({ + 'idapp': idapp, + 'ind_order': ind_order, + }); + } catch (e) { + + } +}; + +GraduatoriaSchema.statics.findByAllRecByUsername = function (idapp, username) { + const Graduatoria = this; + + try { + return Graduatoria.find({ + idapp, + username, + }); + } catch (e) { + + } +}; + +GraduatoriaSchema.statics.getNumDaImbarcare = async function (idapp) { + const Graduatoria = this; + + return await Graduatoria.count({ idapp }) + +}; + +GraduatoriaSchema.statics.AggiornaIndiceGraduatoria = async function (idapp) { + const Graduatoria = this; + + let index = 1; + + await Graduatoria.find({ idapp }).sort({ punteggio: -1, date_added: 1 }).then(async (arrrec) => { + + for (const rec of arrrec) { + + await Graduatoria.findOneAndUpdate({ _id: rec._id }, { $set: { index } }, { new: false }); + index++; + } + }); + + return index - 1; + +}; + +GraduatoriaSchema.statics.getLastImbarco = async function (idapp, username) { + const Graduatoria = this; + + return await Graduatoria.findOne({ idapp, username }).sort({ _id: -1 }); + +}; + +GraduatoriaSchema.statics.getFirstUserGradFree = async function (idapp) { + const Graduatoria = this; + + const { User } = require('../models/user'); + + const arrrecgrad = await Graduatoria.find({ idapp, ind_order: { $gt: 0 } }).sort({ index: 1 }).limit(20); + if (!!arrrecgrad) { + for (const recgrad of arrrecgrad) { + const myuser = await User.findOne({ + idapp, + username: recgrad.username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + }); + + if (!!myuser) { + return recgrad; + } + } + } + + return null; + +}; + + +GraduatoriaSchema.statics.addSingoloInGraduatoria_InFondo = async function (idapp, recingr) { + const Graduatoria = this; + + const lastimbarco = await Graduatoria.getLastImbarco(idapp, recingr.username); + + const arrindex = []; + + const { ListaIngresso } = require('../models/listaingresso'); + + arrindex[recingr.username] = lastimbarco.indimbarco; + + const newingr = await ListaIngresso.aggiornaRecListaIngr(idapp, recingr, arrindex); + + const myrectoadd = addRecGraduatoria(idapp, newingr); + + return await myrectoadd.save(myrectoadd) + .then((ris) => { + return !!ris; + }) + .catch((e) => { + console.error(e.message); + }); + +}; + +function addRecGraduatoria(idapp, ingr, index) { + + try { + let rec = new Graduatoria({ + _id: new ObjectID(), + idapp, + idListaIngresso: ingr._id, + ind_order: ingr.ind_order, + num_tess: ingr.num_tess, + username: ingr.username, + name: ingr.name, + surname: ingr.surname, + indimbarco: ingr.indimbarco, + numNaviEntrato: ingr.numNaviEntrato, + numinvitati: ingr.numinvitati, + numinvitatiattivi: ingr.numinvitatiattivi, + numinvitatiTot: ingr.numinvitatiTot, + numinvitatiattiviTot: ingr.numinvitatiattiviTot, + punteggio: ingr.punteggio, + invitante_username: ingr.invitante_username, + date_added: ingr.date_added, + }); + + if (!!index) { + rec.index = index; + } + return rec; + } catch (e) { + console.error(e.message); + return null; + } + +} + +GraduatoriaSchema.statics.addArrayInGraduatoria = async function (idapp, arrayingr) { + const Graduatoria = this; + + try { + let myobjadd = []; + + let index = 0; + + for (const ingr of arrayingr) { + + index++; + + myobjadd.push(addRecGraduatoria(idapp, ingr, index)); + } + + // Cancella prima tutto + await Graduatoria.deleteMany({ idapp }); + + // Riscrivi Tutto + const ris = await Graduatoria.insertMany(myobjadd); + + + if (!!ris) + return ris.length; + else + return 0; + + } catch (e) { + console.error(e.message); + } + return null; +}; + +GraduatoriaSchema.statics.getFieldsForSearch = function () { + return [ + { field: 'index', type: tools.FieldType.number }, + { field: 'ind_order', type: tools.FieldType.number }, + { field: 'name', type: tools.FieldType.string }, + { field: 'surname', type: tools.FieldType.string }, + { field: 'username', type: tools.FieldType.string }, + { field: 'invitante_username', type: tools.FieldType.string }, + ] +}; + +GraduatoriaSchema.statics.executeQueryTable = function (idapp, params) { + params.fieldsearch = this.getFieldsForSearch(); + return tools.executeQueryTable(this, idapp, params); +}; + +GraduatoriaSchema.statics.findAllIdApp = function (idapp) { + const Graduatoria = this; + + const myfind = { idapp }; + + return Graduatoria.find(myfind, (err, arrrec) => { + return arrrec + }); +}; + +GraduatoriaSchema.statics.isWorking = function (idapp) { + + return Settings.getValDbSettings(idapp, 'GRAD_WORK', false); + +}; + +GraduatoriaSchema.statics.setWorking = function (idapp, stato) { + + return Settings.setBool(idapp, 'GRAD_WORK', stato); + +}; + +function getinvit(index, myrec) { + let inv = myrec.numinvitati; + let invattivi = myrec.numinvitatiattivi; + + const step = (myrec.numNaviEntrato + index) * 2; + + inv -= step; + // console.log('inv', inv, 'step = ', step) + invattivi -= step; + if (inv < 0) + inv = 0; + if (invattivi < 0) + invattivi = 0; + if (inv > 2) + inv = 2; + if (invattivi > 2) + invattivi = 2; + + return { invattivi, inv } +} + +/* +function getnuminv(index, myrec) { + const ris = getinvit(index, myrec); + + return ris.inv +} + +function getnuminvattivi(index, myrec) { + const ris = getinvit(index, myrec); + + return ris.invattivi +}*/ + + +GraduatoriaSchema.statics.getPosizioneInGraduatoria = async function (idapp, ind_order, username, num_tess) { + const Graduatoria = this; + + const totposiz = await Graduatoria.countDocuments({ idapp }); + + return Graduatoria.findOne({ idapp, username, ind_order, num_tess }).then((rec) => { + + if (!!rec) { + + } else { + return { + posiz: 0, + totposiz: 0, + num_tess: 0, + numinvitatiTot: 0, + numinvitatiattiviTot: 0, + numNaviEntrato: 0, + indimbarco: 1, + } + } + + const ris = { + totposiz, + posiz: rec.index, + numinvitatiTot: rec.numinvitatiTot, + numinvitatiattiviTot: rec.numinvitatiattiviTot, + num_tess: rec.num_tess, + numNaviEntrato: rec.numNaviEntrato, + indimbarco: rec.indimbarco, + }; + + return ris; + }); + +}; + + +const Graduatoria = mongoose.model('Graduatoria', GraduatoriaSchema); + +module.exports = { Graduatoria }; diff --git a/src/server/models/listaingresso.js b/src/server/models/listaingresso.js index 678f594..54122ad 100755 --- a/src/server/models/listaingresso.js +++ b/src/server/models/listaingresso.js @@ -1,4 +1,4 @@ -var bcrypt = require('bcryptjs'); +const bcrypt = require('bcryptjs'); const mongoose = require('mongoose'); const validator = require('validator'); const jwt = require('jsonwebtoken'); @@ -9,6 +9,7 @@ const tools = require('../tools/general'); const { ObjectID } = require('mongodb'); const { Nave } = require('./nave'); +const { Graduatoria } = require('./graduatoria'); const shared_consts = require('../tools/shared_nodejs'); const queryclass = require('../classes/queryclass'); @@ -108,6 +109,63 @@ ListaIngressoSchema.statics.getTotInLista = async function (idapp) { return await ListaIngresso.count(myfind); }; +ListaIngressoSchema.statics.getImbarcatiDaily = function (idapp, nrec) { + + const query = [ + { + $match: { + idapp, deleted: false, date_added: { $gte: tools.IncDateNow(-(1000 * 60 * 60 * 24 * nrec)) }, + } + }, + { + $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$date_added" } }, count: { $sum: 1 } } + }, + { + $sort: { _id: 1 } + } + ]; + return query +}; + + +ListaIngressoSchema.statics.getImbarcatiWeekly = function (idapp, nrec) { + + const query = [ + { + $match: { + idapp, deleted: false, date_added: { $gte: tools.IncDateNow(-(1000 * 60 * 60 * 24 * nrec)) }, + } + }, + { + $group: { _id: { $dateToString: { format: "%Y-%U", date: "$date_added" } }, count: { $sum: 1 } } + }, + { + $sort: { _id: 1 } + } + ]; + return query +}; + + +ListaIngressoSchema.statics.ImbarcatiWeekly = async function (idapp) { + const ListaIngresso = this; + + return ListaIngresso.aggregate(ListaIngresso.getImbarcatiWeekly(idapp, 20 * 7)) + .then(ris => { + return JSON.stringify(ris.slice(0, -1)); + }); +}; + +ListaIngressoSchema.statics.ImbarcatiDaily = async function (idapp) { + const ListaIngresso = this; + + return ListaIngresso.aggregate(ListaIngresso.getImbarcatiDaily(idapp, 30)) + .then(ris => { + return JSON.stringify(ris.slice(0, -1)); + }); +}; + + ListaIngressoSchema.statics.findByIndOrder = function (idapp, ind_order) { const ListaIngresso = this; @@ -220,6 +278,12 @@ ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, user const ris = await listaingresso.save(); if (addednowreal) { if (!!ris) { + + if (addednowreal) { + // Aggiungilo anche nella Graduatoria ! + await Graduatoria.addSingoloInGraduatoria_InFondo(idapp, listaingresso); + } + const nome = await User.getNameSurnameByUsername(idapp, username); const numimbarcare = await ListaIngresso.getNumDaImbarcare(idapp); let msgtext = '🛳 '; @@ -238,7 +302,7 @@ ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, user if (!!opt) { if (!!opt.sendmsgtoinvitante) { if (opt.sendmsgtoinvitante) { - const nome = await User.getNameSurnameByUsername(idapp, invitante_username); + // const nome = await User.getNameSurnameByUsername(idapp, invitante_username); // msgtext = '🔵 ' + nome + ' (' + username + ') ' + tools.gettranslate('ADDED_TOLISTAINGRESSO', lang); // await telegrambot.sendMsgTelegram(idapp, username, msgtext, true); // Anche a STAFF } @@ -271,6 +335,49 @@ ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, user ; +function getQueryNumInvitati(myfilter, myobjField, myfilter2, mygroup) { + const query = [ + { $match: myfilter }, + { + $lookup: { + from: "users", + as: "user", + let: { username: '$username' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$username', '$$username'] }, + { $eq: ['$idapp', myfilter.idapp] }, + ] + } + } + } + ] + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] }, "$$ROOT"] } } + }, + { $match: myfilter2 }, + ]; + + if (!!mygroup) { + query.push( + { $group: mygroup } + ); + } + + if (!!myobjField) { + query.push( + { $project: myobjField } + ); + } + + return query; +} + function getQueryProj(myfilter, myobjField, myfilter2, mygroup) { const query = [ { $match: myfilter }, @@ -358,6 +465,7 @@ function getQueryIndOrder(myfilter, myobjField, myfilter2, mygroup) { } +/* ListaIngressoSchema.statics.getPosizioneInLista = async function (idapp, arrrec, ind_order, num_tess) { @@ -376,6 +484,7 @@ ListaIngressoSchema.statics.getPosizioneInLista = async function (idapp, arrrec, return { posiz: posiz + 1, totposiz, num_tess, numNaviEntrato } }; +*/ ListaIngressoSchema.statics.showListaOrd = async function (idapp, solonuovi) { const ListaIngresso = this; @@ -386,6 +495,7 @@ ListaIngressoSchema.statics.showListaOrd = async function (idapp, solonuovi) { let conta = 1; for (const rec of arrrec) { mystr += conta + '- ' + ' [' + rec.numinvitatiattivi + '-' + rec.numinvitati + '] (' + rec.index + ') '; + mystr += ' {' + rec.numinvitatiattivireali + ',' + rec.numinvitatireali + '} '; mystr += ' [' + tools.getstrDateShort(rec.date_added, 'it') + '] '; mystr += rec.username + ' ' + rec.name + ' ' + rec.surname; mystr += ' inv = ' + rec.invitante_username; @@ -426,15 +536,89 @@ ListaIngressoSchema.statics.findAllIdApp = function (idapp) { function sortRec(rec) { return rec.sort(function (reca, recb) { - return Math.round((recb.numinvitatiattivi + recb.numinvitati) / recb.num_tess) - Math.round((reca.numinvitatiattivi + reca.numinvitati) / reca.num_tess); + // return Math.round((recb.numinvitatiattivi + recb.numinvitati) / recb.num_tess) - Math.round((reca.numinvitatiattivi + reca.numinvitati) / reca.num_tess); + // return Math.round((recb.numinvitatiattivi + recb.numinvitati) / recb.indimbarco * 2) - Math.round((reca.numinvitatiattivi + reca.numinvitati) / reca.indimbarco * 2); + // return Math.round((recb.numinvitatiattiviTot + recb.numinvitatiTot) / (recb.indimbarco + recb.numNaviEntrato * 2)) - Math.round((reca.numinvitatiattiviTot + reca.numinvitatiTot) / (reca.indimbarco + reca.numNaviEntrato * 2)); + + // return ((recb.numinvitatiattiviTot - recb.numNaviEntrato * 2) - (recb.indimbarco - 1) * 2) + ((recb.numinvitatiTot - recb.numNaviEntrato * 2) - (recb.indimbarco - 1) * 2) / + // (((reca.numinvitatiattiviTot - reca.numNaviEntrato * 2) - (reca.indimbarco - 1) * 2)) + ((reca.numinvitatiTot - reca.numNaviEntrato * 2) - (reca.indimbarco - 1) * 2); +// + //return Math.round(((recb.numinvitatiattiviTot * 2) + recb.numinvitatiTot) / (recb.indimbarco + recb.numNaviEntrato * 2)) - Math.round(((reca.numinvitatiattiviTot * 2) + reca.numinvitatiTot) / (reca.indimbarco + reca.numNaviEntrato * 2)); + }); } -ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuovi) { +ListaIngressoSchema.statics.getProssimiInLista = function (idapp, solonuovi) { + return Graduatoria.findAllIdApp(idapp).sort({ index: 1 }); +}; + + +ListaIngressoSchema.statics.aggiornaRecListaIngr = async function (idapp, rec, arrindex) { + + rec.numNaviEntrato = await Nave.getnumNaviByUsername(idapp, rec.username); + + rec.numinvitati = await ListaIngresso.getnumInvitati(idapp, rec.username); + rec.numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, rec.username); + + const arrListaIngrUser = arrindex[rec.username]; + if (!arrListaIngrUser) { + // arrindex[rec.username] = 1 + rec.numNaviEntrato; + arrindex[rec.username] = 1; + } else { + arrindex[rec.username] += 1; // incrementa + } + + rec.indimbarco = arrindex[rec.username]; + rec.numinvitatiTot = rec.numinvitati; + rec.numinvitatiattiviTot = rec.numinvitatiattivi; + + // rec.punteggio = (((rec.numinvitatiattiviTot * 1.5) - (rec.numNaviEntrato * 2)) - (rec.indimbarco - 1) * 2) + ((rec.numinvitatiTot - (rec.numNaviEntrato * 2)) - (rec.indimbarco - 1) * 2); + + let val1 = (((rec.numinvitatiattiviTot * 1.5) - (rec.numNaviEntrato * 2)) - (rec.indimbarco - 1) * 2); + let val2 = ((rec.numinvitatiTot - (rec.numNaviEntrato * 2)) - (rec.indimbarco - 1) * 2); + + if (val1 < 0) + val1 = 0; + if (val2 < 0) + val2 = 0; + if (val1 > 2) + val1 = 2; + if (val2 > 2) + val2 = 2; + + rec.punteggio = val1 + val2; + + // if (rec.num_tess > 2) { + rec.numinvitati = rec.numinvitati - (arrindex[rec.username] - 1) * 2; + rec.numinvitatiattivi = rec.numinvitatiattivi - (arrindex[rec.username] - 1) * 2; + // } + if (rec.numinvitati < 0) { + rec.numinvitati = 0; + } + if (rec.numinvitati > 2) { + rec.numinvitati = 2; + } + if (rec.numinvitatiattivi < 0) { + rec.numinvitatiattivi = 0; + } + + if (rec.numinvitatiattivi > 2) + rec.numinvitatiattivi = 2; + + return rec; +}; + +ListaIngressoSchema.statics.GeneraGraduatoria = async function (idapp, solonuovi) { const ListaIngresso = this; let myquery = ''; + //++Todo: DA TOGLIERE IL COMMENTO !!! + // if (await Graduatoria.isWorking(idapp)) + // return; + + await Graduatoria.setWorking(idapp, true); + let myobjField = { idapp: 1, index: 1, @@ -452,77 +636,68 @@ ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuov sospeso: 1, }; - let myfilter2 = { - surname: { $exists: true }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }; + try { + let myfilter2 = { + surname: { $exists: true }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }; - if (solonuovi) { - myquery = getQueryProj({ - 'idapp': idapp, - ind_order: { $gte: 0 }, - added: false, - deleted: false, - }, myobjField, myfilter2); - } else { - myquery = getQueryProj({ - 'idapp': idapp, - ind_order: { $gte: 0 }, - deleted: false, - }, myobjField, myfilter2); + if (solonuovi) { + myquery = getQueryProj({ + 'idapp': idapp, + ind_order: { $gte: 0 }, + added: false, + deleted: false, + }, myobjField, myfilter2); + } else { + myquery = getQueryProj({ + 'idapp': idapp, + ind_order: { $gte: 0 }, + deleted: false, + }, myobjField, myfilter2); + } + + // await ListaIngresso.aggiornaIndex(); + + arrrec = await ListaIngresso.aggregate(myquery) + .then(async (arrlista) => { + + const { User } = require('../models/user'); + + let arrindex = {}; + + for (const rec of arrlista) { + + await ListaIngresso.aggiornaRecListaIngr(idapp, rec, arrindex) + + } + + /*if (arrlista) { + arrlista = sortRec(arrlista); + // arrlista.reverse(); + }*/ + + const salvasudb = true; + if (salvasudb) { + numrec = await Graduatoria.addArrayInGraduatoria(idapp, arrlista); + } + + await Graduatoria.AggiornaIndiceGraduatoria(idapp); + + await Graduatoria.setWorking(idapp, false); + + return numrec; + }).catch((e) => { + Graduatoria.setWorking(idapp, false); + + console.error(e.message); + return null + }); + + } catch (e) { + await Graduatoria.setWorking(idapp, false); } - // await ListaIngresso.aggiornaIndex(); - - arrrec = await ListaIngresso.aggregate(myquery).sort({ date_added: 1 }) - .then(async (arrlista) => { - - const { User } = require('../models/user'); - - const arrindex = {}; - - for (const rec of arrlista) { - - if (true) { - rec.numNaviEntrato = await Nave.getnumNaviByUsername(idapp, rec.username); - - rec.numinvitati = await ListaIngresso.getnumInvitati(idapp, rec.username); - rec.numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, rec.username); - } - - const arrListaIngrUser = arrindex[rec.username]; - if (!arrListaIngrUser) { - arrindex[rec.username] = 1 + rec.numNaviEntrato; - } else { - arrindex[rec.username] += 1; // incrementa - } - - // if (rec.num_tess > 2) { - rec.numinvitati = rec.numinvitati - (arrindex[rec.username] - 1) * 2; - rec.numinvitatiattivi = rec.numinvitatiattivi - (arrindex[rec.username] - 1) * 2; - // } - if (rec.numinvitati < 0) { - rec.numinvitati = 0; - } - if (rec.numinvitatiattivi < 0) { - rec.numinvitatiattivi = 0; - } - - if (rec.numinvitatiattivi > 2) - rec.numinvitatiattivi = 2; - } - - if (arrlista) { - arrlista = sortRec(arrlista); - // arrlista.reverse(); - } - - return arrlista; - }).catch((e) => { - console.error(e.message); - return null - }); - return arrrec; }; @@ -558,7 +733,7 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { try { if (true) { // Elimina TUTTI i Cancellati (ma non Sospesi) - await User.remove({ + await User.deleteMany({ idapp, $and: [ { deleted: { $exists: true, $eq: true } }, // cancellati @@ -718,7 +893,7 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { } // RIMUOVI IL CAMPO IND_ORDER SULLA USER! - await User.update({}, {$unset: {ind_order: 1}}, {multi: true}); + await User.update({}, { $unset: { ind_order: 1 } }, { multi: true }); // Ricalcola il Campo Index await User.ricalcolaIndex(idapp); @@ -757,7 +932,7 @@ ListaIngressoSchema.statics.getarray = async function (idapp, filtri, myobjField let myfilter2 = { surname: { $exists: true }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], }; let myquery = getQueryProj( @@ -788,13 +963,33 @@ ListaIngressoSchema.statics.getarrayIndOrder = async function (idapp, filtri, my }; +ListaIngressoSchema.statics.getIngrEUserByFilter = async function (idapp, myfilter) { + const ListaIngresso = this; + + const arr = await ListaIngresso.getarray(idapp, myfilter, { + _id: 1, + idapp: 1, + username: 1, + ind_order: 1, + name: 1, + surname: 1, + index: 1 + }); + + if (!!arr) { + return arr.length > 0 ? arr[0] : null; + } + return null; + +}; + ListaIngressoSchema.statics.getInvitati = async function (idapp, username, includemyself, myobjField) { const ListaIngresso = this; let myq = { idapp, - deleted: false, + $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], invitante_username: username, }; @@ -828,9 +1023,71 @@ ListaIngressoSchema.statics.getUserByInvitante_Username = async function (idapp, */ +ListaIngressoSchema.statics.getnumInvitatiBase = async function (idapp, username, attivi) { + const ListaIngresso = this; + + const { User } = require('./user'); + + let myfilter2 = { + surname: { $exists: true }, + }; + + if (attivi) { + myfilter2 = { + ...myfilter2, + $and: User.getQueryQualified(), + } + } + + let myquery = getQueryProj({ + idapp, + invitante_username: username, + // username: { $ne: username }, + $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], + }, + { username: 1, ind_order: 1 }, + myfilter2, + ); + + // { _id: null, count: { $sum: 1 } + + arrlistainv = await ListaIngresso.aggregate(myquery); + + // Ottieni gli invitati che ancora non hanno un'imbarco + let myqueryuser = { + idapp, + aportador_solidario: username, + //$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], + }; + + if (attivi) { + myqueryuser = { + ...myqueryuser, + $and: User.getQueryQualified() + } + } + + const arrinv = await User.find(myqueryuser); + + for (const inv of arrinv) { + if (!arrlistainv.find((rec) => rec.username === inv.username)) + arrlistainv.push(inv); + } + + if (!!arrlistainv) + return arrlistainv.length; + else + return 0; +}; + + ListaIngressoSchema.statics.getnumInvitati = async function (idapp, username) { const ListaIngresso = this; + return ListaIngresso.getnumInvitatiBase(idapp, username, false); + + /* const arrlistainv = await ListaIngresso.find({ idapp, invitante_username: username, @@ -847,71 +1104,31 @@ ListaIngressoSchema.statics.getnumInvitati = async function (idapp, username) { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] }); - for (const inv of arrinv) { - if (!arrlistainv.find((rec) => rec.username === inv.username)) - arrlistainv.push(inv); - } - - if (!!arrlistainv) - return arrlistainv.length; - else - return 0; - -}; - -ListaIngressoSchema.statics.getnumInvitatiAttivi = async function (idapp, username) { - const ListaIngresso = this; - - const { User } = require('./user'); - - let myfilter2 = { - surname: { $exists: true }, - $and: User.getQueryQualified(), - }; - - let myquery = getQueryProj({ - idapp, - invitante_username: username, - // username: { $ne: username }, - deleted: false, - }, - { username: 1, ind_order: 1 }, - myfilter2, - ); - - // { _id: null, count: { $sum: 1 } - - arrlistainv = await ListaIngresso.aggregate(myquery); - - // Ottieni gli invitati che ancora non hanno un'imbarco - const arrinv = await User.find({ - idapp, - aportador_solidario: username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - $and: User.getQueryQualified() - }); for (const inv of arrinv) { if (!arrlistainv.find((rec) => rec.username === inv.username)) arrlistainv.push(inv); - } + } */ + - if (!!arrlistainv) - return arrlistainv.length; - else - return 0; }; - -ListaIngressoSchema.statics.aggiornaIndex = function (idapp) { +ListaIngressoSchema.statics.Esegui_CronTab = async function (idapp) { const ListaIngresso = this; - const arrlista = ListaIngresso.find({ idapp }).sort({ created: 1 }); + console.log('Lancia CronTab: [IDAPP=' + idapp + ']'); + await ListaIngresso.GeneraGraduatoria(idapp, true); }; +ListaIngressoSchema.statics.getnumInvitatiAttivi = function (idapp, username) { + const ListaIngresso = this; + + return ListaIngresso.getnumInvitatiBase(idapp, username, true); +}; + const ListaIngresso = mongoose.model('ListaIngresso', ListaIngressoSchema); diff --git a/src/server/models/nave.js b/src/server/models/nave.js index 2675830..4f4bc32 100755 --- a/src/server/models/nave.js +++ b/src/server/models/nave.js @@ -36,6 +36,9 @@ const NaveSchema = new mongoose.Schema({ col: { type: Number, }, + idListaIngresso: { + type: String, + }, ind_order: { type: Number, }, @@ -57,6 +60,9 @@ const NaveSchema = new mongoose.Schema({ type: Boolean, default: false, }, + offerta_al_fondo: { + type: Number, + }, date_received_gift: { type: Date, }, @@ -75,7 +81,7 @@ const NaveSchema = new mongoose.Schema({ NaveSchema.statics.getTotInLista = async function (idapp) { const Nave = this; - const myfind = { idapp }; + const myfind = { idapp, ind_order: { $gte: 0 } }; return await Nave.count(myfind); }; @@ -410,6 +416,7 @@ function getQueryProj(myfilter) { _id: 1, idapp: 1, lang: 1, + idListaIngresso: 1, ind_order: 1, name: 1, surname: 1, @@ -488,6 +495,7 @@ function getQueryProj(myfilter) { function getQueryInvitante(myfilter) { myobjField = { + idListaIngresso: 1, ind_order: 1, name: 1, surname: 1, @@ -550,7 +558,6 @@ function getQueryInvitante(myfilter) { } - NaveSchema.statics.setRiga = function (idapp, riga) { return Settings.setKeyNum(idapp, 'riga', riga); }; @@ -567,11 +574,6 @@ NaveSchema.statics.getCol = function (idapp) { return Settings.getKeyNum(idapp, 'col', 1); }; -function getmaxcol(riga) { - - return Math.pow(2, riga - 1); -} - function getPrimoFuocoByIndCol(col) { // let ris = Math.ceil(col - (col % 8)) + 1; let ris = ((Math.ceil(col / 8) - 1) * 8) + 1; @@ -602,6 +604,7 @@ async function getusertextbyrec(myrec, symbol, lettera, riga, col, ind) { function checkifNullThenEmpty(rec, riga, col) { if (rec === null) { return { + idListaIngresso: -1, name: '', surname: '', username: '', @@ -803,7 +806,7 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in mystr += tools.ACAPO + '4️⃣° 🌀 ' + tools.get__('MEDIATORE', lang) + ':' + await getusertextbyrec(recmediatore, '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; - mystr += '3️⃣° ' + tools.get__('INTERMEDIO', lang) +':' + tools.ACAPO; + mystr += '3️⃣° ' + tools.get__('INTERMEDIO', lang) + ':' + tools.ACAPO; for (let indterra = 1; indterra <= 2; indterra++) { miacol = calcval(riga, col, 2) + (indterra); miariga = riga + 1; @@ -813,7 +816,7 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in mystr += tools.ACAPO; - mystr += '2️⃣° ' + tools.get__('INTERMEDIO', lang) + ':' + tools.ACAPO; + mystr += '2️⃣° ' + tools.get__('INTERMEDIO', lang) + ':' + tools.ACAPO; for (let indaria = 1; indaria <= 4; indaria++) { miacol = calcval(riga, col, 4) + (indaria); miariga = riga + 2; @@ -983,7 +986,7 @@ NaveSchema.statics.showListaOrd = async function (idapp) { }; NaveSchema.statics.getLastRigaCol = async function (idapp) { - return Nave.findOne({ idapp }).sort({ _id: -1 }); + return Nave.findOne({ idapp }).sort({ riga: -1, col: -1 }); }; async function addRecordNaveByParams(params, siRitesse) { @@ -1014,8 +1017,10 @@ async function addRecordNaveByParams(params, siRitesse) { num_tess: params.num_tess }); if (!!giapresente) { - let fields_to_update = { added: true }; - await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); + if (params.persistenti) { + let fields_to_update = { added: true }; + await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); + } return false; } @@ -1024,6 +1029,7 @@ async function addRecordNaveByParams(params, siRitesse) { let myNave = new Nave({ idapp: params.idapp, + idListaIngresso: params.id, ind_order: params.ind_order, riga: params.riga, col: params.col, @@ -1044,15 +1050,17 @@ async function addRecordNaveByParams(params, siRitesse) { myNave.parent_id = "0"; } - console.log('addRecordNaveByParams (' + myNave.parent_id + ')'); + // console.log('addRecordNaveByParams (' + myNave.parent_id + ')'); return await myNave.save() .then(async (result) => { if (!!result) { - let fields_to_update = { added: true }; - await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); + if (params.persistenti) { + let fields_to_update = { added: true }; + await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); + } params.conta++; @@ -1071,7 +1079,7 @@ async function addRecordNaveByParams(params, siRitesse) { params.riga++; params.rigaparent = params.riga - 1; params.col = 1; - params.maxcol = getmaxcol(params.riga); + params.maxcol = tools.getmaxcol(params.riga); } else { params.col++; } @@ -1126,7 +1134,7 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida params.primavolta = (params.riga === 1) && (params.col === 1); params.riga = await Nave.getRiga(idapp); params.col = await Nave.getCol(idapp); - params.maxcol = getmaxcol(params.riga); + params.maxcol = tools.getmaxcol(params.riga); params.colparent = Math.ceil(params.col / 2); params.rigaparent = params.riga - 1; @@ -1139,7 +1147,7 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida const inserito = await addRecordNaveByParams(params, false); if (inserito) { if (idapp === tools.AYNI) { - if (((params.col) % 8) === 0) { + if ((((params.col) % 8) === 0) && (params.col % 64 !== 0)) { let recmediatore = await Nave.findMediatoreByFuoco(idapp, myriga, mycol, 0); if (!!recmediatore) { const ris = await Nave.checkifDeveRitessersi(recmediatore); @@ -1149,13 +1157,16 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida params.ind_order = recmediatore.ind_order; params.id = recmediatore._id; params.num_tess = recmediatore.num_tess + 1; + params.idListaIngresso = -1; await addRecordNaveByParams(params, true); } } } } - if ((params.riga === 4 + 3) && (params.col === (8 * 2) + 3)) { + + /** + if ((params.riga === 4 + 3) && (params.col === (8 * 2) + 3)) { // Si ritesse il Fondo AYNI nella Nave 3.3 const userFondo = await User.findByIndex(idapp, 0); params.ind_order = userFondo.ind_order; @@ -1163,7 +1174,8 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida params.num_tess = userFondo.num_tess; await addRecordNaveByParams(params, true); - } + } **/ + } } @@ -1174,7 +1186,7 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida }; -NaveSchema.statics.generaNave = async function (idapp, mydata) { +NaveSchema.statics.generaNave = async function (idapp, mydata, persistenti) { const Nave = this; const { User } = require('./user'); @@ -1189,6 +1201,10 @@ NaveSchema.statics.generaNave = async function (idapp, mydata) { numpersone: mydata.numpersone, }; + if (!persistenti) { + params.numpersone = 2000; // Mettili tutti + } + //++Todo: date_gift_chat_open e date_start : Ricalcolarle in Automatico... params.primavolta = (params.riga === 1) && (params.col === 1); @@ -1215,8 +1231,9 @@ NaveSchema.statics.generaNave = async function (idapp, mydata) { for (const reclista of arrlistaingresso) { params.ind_order = reclista.ind_order; - params.id = reclista._id; + params.id = reclista.idListaIngresso; params.num_tess = reclista.num_tess; + params.persistenti = persistenti; await Nave.addUserFromListaIngresso_IntoNave(index === 0, idapp, params, false); index++; @@ -1233,9 +1250,12 @@ async function addUserToNave(idapp, rec) { let params = {}; - params.id = rec._id; + params.ind_order = rec.ind_order; + params.id = rec.idListaIngresso; params.num_tess = rec.num_tess; + params.persistenti = false; + //CONTROLLARE SE SERVE ANCORA !!!!!!!!!!!!!!!!!!!!!! return await Nave.addUserFromListaIngresso_IntoNave(true, idapp, params, true); } @@ -1401,6 +1421,12 @@ NaveSchema.statics.getDonatoridelSognatore = async function (idapp, riganave, co }; +NaveSchema.statics.isDefinitiva = async function (idapp, mynave) { + const nave = await NavePersistente.findByRigaColByDonatore(idapp, mynave.riga, mynave.col, 0); + return (!!nave) ? !nave.provvisoria : false; + +}; + NaveSchema.statics.ricalcolaNave = async function (idapp, nave, riga1don, col1don, ricalcola, index) { const Nave = this; @@ -1490,16 +1516,43 @@ NaveSchema.statics.getnumNaviByUsername = async function (idapp, username) { ind_order: 1 }); - if (!!arrrec) - return arrrec.length; - else - return 0; + // SOLO QUELLE PERMANENTI ! + let ind = 0; + for (const mynave of arrrec) { + const trovato = await NavePersistente.findByRigaColByDonatore(idapp, mynave.riga, mynave.col, 0); + if (!!trovato) { + ind++; + } + } + + return ind; } catch (e) { console.error(e.message); } }; +NaveSchema.statics.checkIfMadeGift = async function (idapp, username) { + const Nave = this; + + const { ListaIngresso } = require('./listaingresso'); + + const arrlistaingr = await ListaIngresso.find({ idapp, username }); + for (const ingr of arrlistaingr) { + + let mynave = await Nave.findOne({ idapp, ind_order: ingr.ind_order }); + if (!!mynave) { + if (mynave.made_gift) { + return true; + } + } + } + + return false; + + +}; + NaveSchema.statics.getSognatoreByRigaColMediatore = async function (idapp, navemediatore) { const ris = this.getRigaColSognatoreByMediatore(idapp, navemediatore.riga, navemediatore.col, 3); diff --git a/src/server/models/navepersistente.js b/src/server/models/navepersistente.js index 3b4c334..6fcd055 100755 --- a/src/server/models/navepersistente.js +++ b/src/server/models/navepersistente.js @@ -250,7 +250,7 @@ NavePersistenteSchema.statics.findByRigaCol = function (idapp, riga, col) { NavePersistenteSchema.statics.getLastRigaCol = async function (idapp) { - return NavePersistente.findOne({ idapp }).sort({ _id: -1 }); + return NavePersistente.findOne({ idapp }).sort({ riga: -1, col: -1 }); }; NavePersistenteSchema.statics.getLastRigaColDefinitiva = async function (idapp) { @@ -270,6 +270,19 @@ NavePersistenteSchema.pre('save', async function (next) { next(); }); +function getNextDayNave(miadata) { + + const dayofweek = [1, 3, 5]; // LUNEDI, MERCOLEDI, VENERDI + + let mydate = tools.AddDate(miadata, 1); + + while (!dayofweek.includes(mydate.getDay())) { + mydate = tools.AddDate(mydate, 1); + } + + return mydate + +} NavePersistenteSchema.statics.addRecordNavePersistenteByParams = async function (params) { @@ -281,14 +294,27 @@ NavePersistenteSchema.statics.addRecordNavePersistenteByParams = async function }); if (!giapresente) { + // Prende la nave prima: + const lastnave = await NavePersistente.findOne({idapp}).sort({riga: -1, col: -1}); + + let nextgiftchat = null; + + if (((params.col - 1) % 8 === 0)) { + nextgiftchat = getNextDayNave(lastnave.date_gift_chat_open); + } else { + nextgiftchat = lastnave.date_gift_chat_open; + } + + const next_date_start = tools.AddDate(nextgiftchat, 7); + let myNavePersistente = new NavePersistente({ idapp: params.idapp, riga: params.riga, col: params.col, riga1don: params.riga1don, col1don: params.col1don, - date_start: params.date_start, - date_gift_chat_open: params.date_gift_chat_open, + date_gift_chat_open: nextgiftchat, + date_start: next_date_start, provvisoria: true, }); return await myNavePersistente.save(); diff --git a/src/server/models/settings.js b/src/server/models/settings.js index d2ea399..2c86378 100755 --- a/src/server/models/settings.js +++ b/src/server/models/settings.js @@ -114,6 +114,24 @@ SettingsSchema.statics.setKeyNum = async function (idapp, key, value) { }; +SettingsSchema.statics.setBool = async function (idapp, key, valbool) { + const Settings = this; + + let myrec = await Settings.findOne({ idapp, key }); + if (!myrec) { + myrec = new Settings({ key }); + myrec._id = new ObjectID(); + myrec.idapp = idapp; + myrec.type = tools.FieldType.boolean; + myrec.value_bool = valbool; + + return await myrec.save(); + } else { + myrec = await Settings.findOneAndUpdate({ idapp, key }, { $set: { value_bool: valbool } }, { new: false }); + } + +}; + SettingsSchema.statics.getKeyNum = async function (idapp, key, mydefault) { const Settings = this; diff --git a/src/server/models/user.js b/src/server/models/user.js index 3650d25..8c9450d 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -8,6 +8,7 @@ const tools = require('../tools/general'); const { Settings } = require('../models/settings'); const { ListaIngresso } = require('../models/listaingresso'); +const { Graduatoria } = require('../models/graduatoria'); const { Nave } = require('../models/nave'); const { NavePersistente } = require('../models/navepersistente'); // const { ExtraList } = require('../models/extralist'); @@ -557,6 +558,7 @@ UserSchema.statics.getQueryQualified = function () { } + UserSchema.statics.isUserQualified7 = async function (idapp, username) { const User = this; @@ -921,12 +923,15 @@ UserSchema.statics.SetTelegramWasBlocked = async function (idapp, teleg_id) { 'profile.teleg_id': 0, }; - const ris = await User.findOneAndUpdate({ - idapp, - 'profile.teleg_id': teleg_id - }, { $set: fields_to_update }, { new: false }).then((record) => { - return record; - }); + if (process.env.PROD === 1) { + + const ris = await User.findOneAndUpdate({ + idapp, + 'profile.teleg_id': teleg_id + }, { $set: fields_to_update }, { new: false }).then((record) => { + return record; + }); + } }; @@ -1213,15 +1218,15 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us dashboard.arrposizioni = await Nave.getArrPosizioniByUsername(idapp, username); - let arrrec = []; + /* let arrrec = []; if (dashboard.arrimbarchi.length > 0) { arrrec = await ListaIngresso.getProssimiInLista(idapp, true); - } + }*/ for (let myimbarco of dashboard.arrimbarchi) { if (!!myimbarco.invitante_username) dashboard.arrusers[myimbarco.invitante_username] = await User.getUserShortDataByUsername(idapp, myimbarco.invitante_username); - myimbarco._doc.posiz = await ListaIngresso.getPosizioneInLista(idapp, arrrec, myimbarco.ind_order, myimbarco.num_tess); + myimbarco._doc.posiz = await Graduatoria.getPosizioneInGraduatoria(idapp, myimbarco.ind_order, myimbarco.username, myimbarco.num_tess); } dashboard.navi_partenza = await NavePersistente.getListaNavi(idapp); @@ -1681,7 +1686,10 @@ UserSchema.statics.calculateStat = async function (idapp, username) { UserSchema.statics.getDistinctNationalityQuery = function (idapp) { const query = [ { - $match: { idapp } + $match: { + idapp, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + } }, { $group: { _id: "$profile.nationality", count: { $sum: 1 } } diff --git a/src/server/router/api/actions.js b/src/server/router/api/actions.js index 53e45a6..0a40792 100755 --- a/src/server/router/api/actions.js +++ b/src/server/router/api/actions.js @@ -1,14 +1,21 @@ -var mongoose = require('mongoose'); +const mongoose = require('mongoose'); const Subscription = mongoose.model('subscribers'); const { ListaIngresso } = require('../../models/listaingresso'); +const { Graduatoria } = require('../../models/graduatoria'); const { User } = require('../../models/user'); +const { Nave } = require('../../models/nave'); + +const { ObjectID } = require('mongodb'); + +const tools = require('../../tools/general'); const telegrambot = require('../../telegram/telegrambot'); module.exports = { - doOtherThingsAfterDeleted: async function (tablename, rec) { + doOtherThingsAfterDeleted: async function (tablename, rec, notifBot) { try { + let ris = null; if (tablename === 'users') { await ListaIngresso.deleteUserInListaIngresso(rec.idapp, rec.username); @@ -23,17 +30,57 @@ module.exports = { }, { $set: { aportador_solidario: rec.aportador_solidario } }, { new: false }); let msg = 'Spostato ' + user.name + ' ' + user.surname + ' sotto di ' + rec.aportador_solidario; - telegrambot.sendMsgTelegramToTheManagers(idapp, msg); + telegrambot.sendMsgTelegramToTheManagers(rec.idapp, msg); } // Delete also all the subscribers record of this User - return Subscription.deleteOne({ userId: rec._id }) + ris = Subscription.deleteOne({ userId: rec._id }) } + + if (tablename === 'listaingressos') { + // Rimuovi anche nella Tabella Graduatoria + ris = await Graduatoria.deleteOne({ idListaIngresso: ObjectID(rec._id) }); + if (!!ris) { + + let msg = 'Eliminato Imbarco di ' + rec.name + ' ' + rec.surname + ' [Index = ' + rec.index + ']'; + await telegrambot.sendMsgTelegramToTheManagers(rec.idapp, msg); + } + + // Elimina anche la Nave se è temporanea! + const arrnave = await Nave.find({ idapp: rec.idapp, ind_order: rec.ind_order }); + for (const mynave of arrnave) { + if (!!mynave) { + if (!await Nave.isDefinitiva(rec.idapp, mynave)) { + await Nave.findByIdAndUpdate(mynave.id, { $set: { ind_order: -1 } }); + break; + } + } + } + } + + if (!!ris) { + + if (notifBot) { + // Send Notification to the BOT + let nomerecord = ''; + if ((tablename === 'users') || (tablename === 'extralist')) { + nomerecord = rec.name + ' ' + rec.surname + ' (' + rec.username + ')'; + } + + addtext = 'Eliminato il Record "' + nomerecord + '" dalla tabella ' + tablename + '\n' + + 'Eseguito da ' + req.user.name + ' ' + req.user.surname + ' \n'; + await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext); + } + + } + + return ris + } catch (e) { console.error(e.message); return false } - return true; + }, doOtherThingsAfterDuplicated: async function (tablename, myrec, mynewrec) { try { diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index bd9974e..36fb6af 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -13,6 +13,7 @@ const { authenticate, authenticate_noerror } = require('../middleware/authentica const { ObjectID } = require('mongodb'); const { ListaIngresso } = require('../models/listaingresso'); +const { Graduatoria } = require('../models/graduatoria'); const mongoose = require('mongoose'); const cfgserver = mongoose.model('cfgserver'); @@ -223,6 +224,8 @@ function getTableByTableName(tablename) { mytable = NavePersistente; else if (tablename === 'listaingressos') mytable = ListaIngresso; + else if (tablename === 'graduatorias') + mytable = Graduatoria; return mytable } @@ -442,6 +445,8 @@ router.patch('/chval', authenticate, async (req, res) => { res.status(400).send(); return false; } + } else if ('deleted' in fieldsvalue) { + await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${rec.name} ${rec.surname} (${rec.username}) è stato cancellato (nascosto) da ${req.user.name} ${req.user.surname}`); } } @@ -512,6 +517,32 @@ router.patch('/chval', authenticate, async (req, res) => { }); +router.patch('/askfunz', authenticate, async (req, res) => { + // const idapp = req.body.idapp; + const id = req.body.data.id; + const ind_order = req.body.data.ind_order; + const username = req.body.data.username; + const idapp = req.body.idapp; + const mydata = req.body.data; + + let entra = false; + if (!entra) { + // If I change my record... + if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTutor(req.user.perm)) && !(req.user._id.toString() === id)) { + // If without permissions, exit + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + } + } + + if (mydata.myfunc === shared_consts.CallFunz.DAMMI_PRIMO_UTENTE_LIBERO) { + const userfree = await Graduatoria.getFirstUserGradFree(idapp); + + if (!!userfree) + return res.send({ code: server_constants.RIS_CODE_OK, out: userfree }); + } + +}); + router.patch('/callfunz', authenticate, async (req, res) => { // const idapp = req.body.idapp; const id = req.body.data.id; @@ -528,7 +559,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { } if (!entra) { // If I change my record... - if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTutor(req.user.perm)) && !(req.user._id.toString() === id) && !tools.ModificheConsentite(mydata.table, fieldsvalue)) { + if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTutor(req.user.perm)) && !(req.user._id.toString() === id)) { // If without permissions, exit return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } @@ -555,7 +586,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { if (!!myusernuovo) { if (!mydata.data.AddImbarco && !!mianavedasost && mianavedasost.ind_order > 0) { - // Controlla prima se è in una Nave Temporanea, allora lo elimina dalla Nave Temporanea + // Controlla prima se è in una Nave Temporanea, allora lo elimina dalla PRIMA Nave Temporanea miaarrnavi = await Nave.getArrPosizioniByUsername(idapp, username); if (miaarrnavi) { @@ -566,7 +597,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { ind_order: -1 }; - let ris = await Nave.findByIdAndUpdate(mianave.id, { $set: fieldsvalue }); + let ris = await Nave.findByIdAndUpdate(mianave._id, { $set: fieldsvalue }); if (!!ris) { rimosso++; break; // Rimuovilo solo 1 ! @@ -580,31 +611,45 @@ router.patch('/callfunz', authenticate, async (req, res) => { if (!!mianavedasost && mianavedasost.ind_order >= 0) { // Metti campo 'delete': true su ListaIngresso - olduseringresso = await ListaIngresso.findOne({ idapp, ind_order: mianavedasost.ind_order }); + olduseringresso = await ListaIngresso.findById(mianavedasost.idListaIngresso); if (!!olduseringresso) { let fieldsvalue = { date_deleted: new Date(), deleted: true }; - const risul = await ListaIngresso.findByIdAndUpdate(olduseringresso.id, { $set: fieldsvalue }, { new: false }); + const risul = await ListaIngresso.findByIdAndUpdate(mianavedasost.idListaIngresso, { $set: fieldsvalue }, { new: false }); + if (!!risul) { + const myrecuser = await ListaIngresso.getIngrEUserByFilter(idapp, { + idapp, + username: username_da_sostituire, + _id: ObjectID(mianavedasost.idListaIngresso) + }); + + if (!!myrecuser) { + const risdel = await ListaIngresso.deleteOne({ _id: olduseringresso.id }); + + if (!!risdel) { + await actions.doOtherThingsAfterDeleted('listaingressos', myrecuser, false) + } + } + } } } } if (!!myuservecchio) { // Se ha gia delle altre navi, non cancellarlo! - Nave.checkIfMadeGift(idapp, ) - const noncanc = await Nave.findOne({idapp, ind_order: mianavedasost.ind_order, made_gift: true }); + if (!await Nave.checkIfMadeGift(idapp, myuservecchio.username)) { - - if (mydata.data.deleteUser && !!mianavedasost && mianavedasost.ind_order > 0) { - // Metti Deleted allo User - fieldsvalue = { - deleted: true, - date_deleted: new Date(), - }; - await User.findByIdAndUpdate(myuservecchio.id, { $set: fieldsvalue }); - await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuservecchio.name} ${myuservecchio.surname} (${myuservecchio.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); + if (mydata.data.deleteUser && !!mianavedasost && mianavedasost.ind_order > 0) { + // Metti Deleted allo User + fieldsvalue = { + deleted: true, + date_deleted: new Date(), + }; + await User.findByIdAndUpdate(myuservecchio.id, { $set: fieldsvalue }); + await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuservecchio.name} ${myuservecchio.surname} (${myuservecchio.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); + } } } @@ -626,8 +671,17 @@ router.patch('/callfunz', authenticate, async (req, res) => { ind_order = myingr.ind_order; await myingr.save(); + } + // Togliolo dalla Graduatoria! + const mygrad = await Graduatoria.findOneAndUpdate({ + idapp, + idListaIngresso: myingr._id + }, { $set: { ind_order: -1 } }, { new: false }); + + + // Aggiorna la Nave con il Nuovo fieldsvalue = { ind_order @@ -635,7 +689,6 @@ router.patch('/callfunz', authenticate, async (req, res) => { const dachi = req.user.name + ' ' + req.user.surname; - return await Nave.findByIdAndUpdate(mianavedasost.id, { $set: fieldsvalue }) .then(async (rec) => { // tools.mylogshow(' REC TO MODIFY: ', rec); @@ -703,11 +756,26 @@ router.patch('/callfunz', authenticate, async (req, res) => { } else if (mydata.myfunc === shared_consts.CallFunz.CANCELLA_IMBARCO) { - await ListaIngresso.remove({ idapp, username, ind_order }); + const myrec = await ListaIngresso.getIngrEUserByFilter(idapp, { idapp, _id: ObjectID(mydata.data.id) }); - return res.send({ code: server_constants.RIS_CODE_OK }); + if (!!myrec) { + const risdel = await ListaIngresso.deleteOne({ _id: mydata.data.id }); + + if (!!risdel) { + return await actions.doOtherThingsAfterDeleted('listaingressos', myrec, false) + .then((ris) => { + + if (!!ris) + // tools.mylog('DELETED Others things ...'); + return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); + }); + } + } } + + return res.send({ code: server_constants.RIS_CODE_ERR }); + } catch (e) { console.log(e.message); res.status(400).send(); @@ -800,27 +868,10 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { }); } + if (cancellato) { // Do extra things after deleted - return actions.doOtherThingsAfterDeleted(tablename, myrec).then(async (ris) => { - if (ris) { - - if (notifBot) { - // Send Notification to the BOT - let nomerecord = ''; - if ((tablename === 'users') || (tablename === 'extralist')) { - nomerecord = myrec.name + ' ' + myrec.surname + ' (' + myrec.username + ')'; - } - - addtext = 'Eliminato il Record "' + nomerecord + '" dalla tabella ' + tablename + '\n' + - 'Eseguito da ' + req.user.name + ' ' + req.user.surname + ' \n'; - await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext); - } - - tools.mylog('DELETED Others things ...'); - return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); - } - }); + return actions.doOtherThingsAfterDeleted(tablename, myrec, notifBot); } res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); @@ -878,10 +929,6 @@ router.post('/duprec/:table/:id', authenticate, (req, res) => { }); -function doOtherThingsAfterDeleted() { - -} - router.get('/loadsite/:userId/:idapp/:sall', authenticate_noerror, (req, res) => { const userId = req.params.userId; const idapp = req.params.idapp; diff --git a/src/server/router/site_router.js b/src/server/router/site_router.js index 865bc23..a6251bc 100755 --- a/src/server/router/site_router.js +++ b/src/server/router/site_router.js @@ -26,7 +26,7 @@ router.post('/load', async (req, res) => { let datastat = { num_reg: await User.getUsersRegistered(idapp), - num_passeggeri: await Nave.getTotInLista(idapp) + await ListaIngresso.getTotInLista(idapp), + num_passeggeri: await Nave.getTotInLista(idapp), num_imbarcati: await ListaIngresso.getTotInLista(idapp), email_non_verif: await User.getEmailNotVerified(idapp), num_teleg_attivo: await User.getUsersTelegramAttivo(idapp), @@ -39,6 +39,8 @@ router.post('/load', async (req, res) => { arr_nations: await User.findAllDistinctNationality(idapp), numreg_untilday: await User.calcnumRegUntilDay(idapp), reg_daily: await User.calcRegDaily(idapp), + imbarcati_daily: await ListaIngresso.ImbarcatiDaily(idapp), + imbarcati_weekly: await ListaIngresso.ImbarcatiWeekly(idapp), reg_weekly: await User.calcRegWeekly(idapp), lastsreg: await User.getLastUsers(idapp), checkuser: await User.checkUser(idapp, username), diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index b22b3a6..7a38db5 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -5,6 +5,7 @@ const { User } = require('../models/user'); const { Nave } = require('../models/nave'); const { NavePersistente } = require('../models/navepersistente'); const { ListaIngresso } = require('../models/listaingresso'); +const { Graduatoria } = require('../models/graduatoria'); // const { ExtraList } = require('../models/extralist'); const { ObjectID } = require('mongodb'); @@ -401,341 +402,375 @@ router.post('/import_extralist', async (req, res) => { res.send(ris); }); -router.post('/dbop', authenticate, async (req, res) => { +async function eseguiDbOp(idapp, mydata, locale) { - const mydata = req.body.mydata; - idapp = req.body.idapp; - locale = req.body.locale; + let ris = await User.DbOp(idapp, mydata); - let ris = await User.DbOp(idapp, mydata); + let mystr = ''; - let mystr = ''; + try { - try { + if (mydata.dbop === 'rigeneraTutto') { - if (mydata.dbop === 'creaNavi') { - const num = await Nave.generaNave(idapp, mydata); - ris = { num }; - } else if (mydata.dbop === 'delNavi') { - await Nave.setRiga(idapp, 1); + mydata.dbop = 'delNaviProvvisorie'; + await eseguiDbOp(idapp, mydata, locale); + + mydata.dbop = 'GeneraGraduatoria'; + await eseguiDbOp(idapp, mydata, locale); + + mydata.dbop = 'creaNavi'; + ris = await eseguiDbOp(idapp, mydata, locale); + + } else if (mydata.dbop === 'creaNavi') { + const num = await Nave.generaNave(idapp, mydata, false); + ris = { num }; + } else if (mydata.dbop === 'CreaNaviPersistenti') { + const num = await Nave.generaNave(idapp, mydata, true); + ris = { num }; + } else if (mydata.dbop === 'delNavi') { + await Nave.setRiga(idapp, 1); + await Nave.setCol(idapp, 1); + const num = await Nave.deleteOne({ idapp }); + ris = { num }; + // } else if (mydata.dbop === 'delNaviNoStarted') { + // await Nave.setRiga(idapp, 1); + // await Nave.setCol(idapp, 1); + // const num = await Nave.remove({ idapp, date_start: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 24 * 3) } }); + // ris = { num }; + } else if (mydata.dbop === 'delNaviProvvisorie') { + + let num = 0; + + const arrnavi = await Nave.find({ idapp }); + + for (const nave of arrnavi) { + let persistente = await NavePersistente.findByRigaColByDonatore(idapp, nave.riga, nave.col, 0); + if (!!persistente) { + if (persistente.provvisoria) { + let ris = await Nave.deleteOne({ _id: nave._id }); + if (!!ris) { + num++; + } + } + } + } + + // Pulisci gli added se era stato cancellato dalla nave + await Nave.pulisciNonPresenzeInNave(idapp); + + const data = await Nave.getLastRigaCol(idapp); + await Nave.setRiga(idapp, data.riga); + await Nave.setCol(idapp, data.col + 1); + + const maxcol = tools.getmaxcol(data.riga); + if (data.col === maxcol) { + await Nave.setRiga(idapp, data.riga + 1); await Nave.setCol(idapp, 1); - const num = await Nave.remove({ idapp }); - ris = { num }; - // } else if (mydata.dbop === 'delNaviNoStarted') { - // await Nave.setRiga(idapp, 1); - // await Nave.setCol(idapp, 1); - // const num = await Nave.remove({ idapp, date_start: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 24 * 3) } }); - // ris = { num }; - } else if (mydata.dbop === 'delNaviProvvisorie') { + } - let num = 0; + ris = { num }; + } else if (mydata.dbop === 'visuListaNave') { + mystr = await Nave.showListaOrd(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'visuStat') { + ris = await User.visuUtentiNonInNavi(idapp); + } else if (mydata.dbop === 'pulisciNonPresenzeInNave') { + mystr = await Nave.pulisciNonPresenzeInNave(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'checkInserimentiUtentiInNave') { + mystr = await Nave.checkIfDevoAggiungereInNave(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'visuListaIngresso') { + mystr = await ListaIngresso.showListaOrd(idapp, false); + ris = { mystr }; + } else if (mydata.dbop === 'visuListaIngressoNuovi') { + mystr = await ListaIngresso.showListaOrd(idapp, true); + ris = { mystr }; + } else if (mydata.dbop === 'GeneraGraduatoria') { + mystr = await ListaIngresso.GeneraGraduatoria(idapp, true); + ris = { mystr }; + } else if (mydata.dbop === 'AggiornaIndiceGraduatoria') { + mystr = await Graduatoria.AggiornaIndiceGraduatoria(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'visuNaviUtentiEliminati') { + ris = await Nave.visuNaviUtentiEliminati(idapp); + } else if (mydata.dbop === 'creaTessituraeConv') { + ris = await ListaIngresso.creaTessituraeConv(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'eliminaListeIngressoNascoste') { + ris = await ListaIngresso.eliminaListeIngressoNascoste(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'RendiVisibileIrecordNascosti') { + ris = await ListaIngresso.RendiVisibileIrecordNascosti(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'convNaviTessinListaIngressoRec') { + let num = 0; - const arrnavi = await Nave.find({ idapp }); + const arrnavitess = await Nave.find({ idapp, num_tess: { $gte: 3 } }); - for (const nave of arrnavi) { - let persistente = await NavePersistente.findByRigaColByDonatore(idapp, nave.riga, nave.col, 0); - if (!!persistente) { - if (persistente.provvisoria) { - let ris = await Nave.remove({ _id: nave._id }); - if (!!ris) { - num++; - } + for (const recnave of arrnavitess) { + if (recnave.num_tess === 3 || recnave.num_tess === 5 || recnave.num_tess === 7) { + const ind_order = recnave.ind_order; + + // Prima controlla se ho già 2 record dello stesso ind_order, allora non lo faccio: + const arringr = await ListaIngresso.find({ idapp, ind_order }); + let dafare = true; + if (arringr.length > 0) { + const arringrtest = await ListaIngresso.find({ idapp, ind_order }).distinct('num_tess'); + if (arringr.length !== arringrtest.length) { + dafare = false; // Ci sono 2 o piu record! pertanto probabilmente l'ho già fatto! } } - } + if (dafare) { + // const user = await User.findByOldOrder(idapp, ind_order); + const user = await User.findByIndOrder(idapp, ind_order); - // Pulisci gli added se era stato cancellato dalla nave - await Nave.pulisciNonPresenzeInNave(idapp); + if (!!user) { + //let note = recnave.num_tess; + // Crea record ListaIngresso + const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, user.username, user.username, user.lang, false, true, recnave.created, '', true); - const data = await Nave.getLastRigaCol(idapp); - await Nave.setRiga(idapp, data.riga); - await Nave.setCol(idapp, data.col + 1); + const fieldsvalue = { + ind_order: newrecingr.ind_order, + num_tess: 1, + }; - ris = { num }; - } else if (mydata.dbop === 'visuListaNave') { - mystr = await Nave.showListaOrd(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'visuStat') { - ris = await User.visuUtentiNonInNavi(idapp); - } else if (mydata.dbop === 'pulisciNonPresenzeInNave') { - mystr = await Nave.pulisciNonPresenzeInNave(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'checkInserimentiUtentiInNave') { - mystr = await Nave.checkIfDevoAggiungereInNave(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'visuListaIngresso') { - mystr = await ListaIngresso.showListaOrd(idapp, false); - ris = { mystr }; - } else if (mydata.dbop === 'visuListaIngressoNuovi') { - mystr = await ListaIngresso.showListaOrd(idapp, true); - ris = { mystr }; - } else if (mydata.dbop === 'visuNaviUtentiEliminati') { - ris = await Nave.visuNaviUtentiEliminati(idapp); - } else if (mydata.dbop === 'creaTessituraeConv') { - ris = await ListaIngresso.creaTessituraeConv(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'eliminaListeIngressoNascoste') { - ris = await ListaIngresso.eliminaListeIngressoNascoste(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'RendiVisibileIrecordNascosti') { - ris = await ListaIngresso.RendiVisibileIrecordNascosti(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'convNaviTessinListaIngressoRec') { - let num = 0; + // Aggiorna la nave con l'Ind_order nuovo e il num_tess a 1 + await Nave.findOneAndUpdate({ _id: recnave._id }, { $set: fieldsvalue }, { new: false }); - const arrnavitess = await Nave.find({ idapp, num_tess: { $gte: 3 } }); - - for (const recnave of arrnavitess) { - if (recnave.num_tess === 3 || recnave.num_tess === 5 || recnave.num_tess === 7) { - const ind_order = recnave.ind_order; - - // Prima controlla se ho già 2 record dello stesso ind_order, allora non lo faccio: - const arringr = await ListaIngresso.find({ idapp, ind_order }); - let dafare = true; - if (arringr.length > 0) { - const arringrtest = await ListaIngresso.find({ idapp, ind_order }).distinct('num_tess'); - if (arringr.length !== arringrtest.length) { - dafare = false; // Ci sono 2 o piu record! pertanto probabilmente l'ho già fatto! - } - } - if (dafare) { - // const user = await User.findByOldOrder(idapp, ind_order); - const user = await User.findByIndOrder(idapp, ind_order); - - if (!!user) { - //let note = recnave.num_tess; - // Crea record ListaIngresso - const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, user.username, user.username, user.lang, false, true, recnave.created, '', true); - - const fieldsvalue = { - ind_order: newrecingr.ind_order, - num_tess: 1, - }; - - // Aggiorna la nave con l'Ind_order nuovo e il num_tess a 1 - await Nave.findOneAndUpdate({ _id: recnave._id }, { $set: fieldsvalue }, { new: false }); - - num++; - } - } - } - } - - - const arrnavitess2 = await Nave.find({ idapp, num_tess: 2 }); - - for (const recnave of arrnavitess2) { - - - } - - ris = { num }; - - } else if (mydata.dbop === 'initListaIngresso') { - // const aaa = await User.updateMany({ idapp }, { $set: { 'profile.nationality': 'IT' } }); - - const num = await ListaIngresso.updateMany({ idapp }, { $set: { added: false } }); - - ris = { num }; - } else if (mydata.dbop === 'ImpostaATuttiPaypal') { - const listautenti = await User.find({ idapp }); - let num = 0; - for (let rec of listautenti) { - if (!rec._doc.profile.paymenttypes.includes('paypal')) { - rec._doc.profile.paymenttypes = [...rec._doc.profile.paymenttypes, 'paypal']; - const user = await User.findOneAndUpdate({ _id: rec._id }, { $set: { 'profile.paymenttypes': rec._doc.profile.paymenttypes } }); - // await rec.save(); - num++; - } - // const num = await User.f({ idapp }, { $set: { 'profile: false } }); - } - - - ris = { num }; - } else if (mydata.dbop === 'numtessUno') { - const listanavi = await ListaIngresso.find({ idapp }); - let num = 0; - for (let rec of listanavi) { - if (!rec._doc.num_tess) { - rec._doc.num_tess = 1; - const risu = await ListaIngresso.findOneAndUpdate({ _id: rec._id }, { $set: { num_tess: rec._doc.num_tess } }, { new: false }); - // await rec.save(); - if (!!risu) - num++; - } - // const num = await User.f({ idapp }, { $set: { 'profile: false } }); - } - - - ris = { num }; - } else if (mydata.dbop === 'Corregginumtess') { - const listanavi = await Nave.find({ idapp }); - let num = 0; - for (let rec of listanavi) { - const myarrrec = await Nave.find({ idapp, ind_order: rec.ind_order }).sort({ riga: 1, col: 1 }); - let indextess = 1; - for (let ind = 0; ind < myarrrec.length; ind++) { - if (myarrrec[ind].num_tess !== indextess && myarrrec[ind].num_tess === 1) { - myarrrec[ind].num_tess = indextess; - const risu = await Nave.findOneAndUpdate({ _id: myarrrec[ind]._id }, { $set: { num_tess: myarrrec[ind].num_tess } }, { new: false }); num++; } - indextess++; } } - - ris = { num }; - /* - } - - else if (mydata.dbop === 'CreaNaviPersistenti') { - const listanavi = await Nave.find({ idapp }).sort({riga: 1, col: 1}); - - let params = { - idapp - }; - - let num = 0; - for (let rec of listanavi) { - let mypos = { - idapp, - riga: rec.riga, - col: rec.col, - numup: 3 - }; - tools.getRigaColByPosUp(mypos); - let persistente = await NavePersistente.findByRigaCol(idapp, mypos.riga, mypos.col, 0); - if (!persistente) { - - params.date_start = rec.date_start; - params.date_gift_chat_open = rec.date_gift_chat_open; - params.riga = mypos.riga; - params.col = mypos.col; - if (rec.riga > 3) { - params.riga1don = rec.riga; - params.col1don = rec.col; - } else { - params.riga1don = rec.riga; - params.col1don = rec.col; - } - if (params.riga > 0) { - await NavePersistente.addRecordNavePersistenteByParams(params); - num++; - } - } - } - - ris = { num }; */ - } else if (mydata.dbop === 'CorreggiDataGiftChat') { - const listanavi = await NavePersistente.find({ idapp }); - let num = 0; - for (let rec of listanavi) { - const fieldsvalue = { - date_gift_chat_open: tools.AddDate(rec.date_start, -7) - }; - const risu = await NavePersistente.findOneAndUpdate({ _id: rec._id }, { $set: fieldsvalue }, { new: false }); - if (!!risu) { - num++; - } - } - - ris = { num }; - } else if (mydata.dbop === 'creaUtentiTest') { - - let num = 0; - lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1); - let last = 1; - if (lastrec) { - last = lastrec[0].index; - } - if (!last) { - last = 1; - } - - for (let ind = 0; ind < 100; ind++) { - let myuser = new User(); - myuser._id = new ObjectID(); - myuser.index = last + ind + 1; - myuser.idapp = idapp; - myuser.password = "$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG"; - myuser.lang = 'it'; - myuser.email = "miaemail@email.it"; - myuser.name = 'U' + myuser.index; - myuser.surname = 'Ar' + myuser.index; - myuser.verified_email = true; - if (myuser.index < 2) - myuser.perm = "3"; - myuser.username = "Userna_" + myuser.name; - myuser.profile.special_req = true; - myuser.profile.nationality = 'IT'; - await myuser.save(); - num++; - } - - ris = { num }; - } else if (mydata.dbop === 'visuPlacca') { - - mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' + - 'ECCO LE NUOVE NAVI DEFINITIVE CHE APRONO DOMANI LA GIFT CHAT !!! DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) + '\n' + - 'AUGURI ALLA NUOVA SOGNATRICE !!!\n' + - '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨'; - - const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT'); - - for (let ind = 0; ind < 8; ind++) { - mystr += await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col) + ind, false); - mystr += tools.ACAPO; - if (visu_nave_Bot && ind === 3) { - await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); - mystr = ''; - } - } - - if (visu_nave_Bot) - await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); - - ris = { mystr }; - - /*const rec = {}; - const placca = await Nave.getPlaccaPerDonatore(idapp, parseInt(mydata.riga), parseInt(mydata.col), false, rec); - - telegrambot.sendMsgTelegramToTheAdmin(idapp, placca); - - ris = { placca };*/ - } else if (mydata.dbop === 'visuNave') { - mystr = await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col)); - - const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT'); - if (visu_nave_Bot) - telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); - - ris = { mystr }; - } else if (mydata.dbop === 'getnavibyuser') { - - let arrnavi = null; - - const user = await User.getUserShortDataByUsername(idapp, mydata.username); - if (user) { - arrnavi = await Nave.getArrPosizioniByUsername(idapp, user.username); - - for (let mynave of arrnavi) { - mynave._doc.rec = await Nave.getNaveByRigaCol(idapp, mynave.riga, mynave.col); - } - - } - - ris = { data: arrnavi }; } - // console.log('ris', ris); + const arrnavitess2 = await Nave.find({ idapp, num_tess: 2 }); - res.send(ris); - } catch (e) { - console.log(e.message); + for (const recnave of arrnavitess2) { + + + } + + ris = { num }; + + } else if (mydata.dbop === 'initListaIngresso') { + // const aaa = await User.updateMany({ idapp }, { $set: { 'profile.nationality': 'IT' } }); + + const num = await ListaIngresso.updateMany({ idapp }, { $set: { added: false } }); + + ris = { num }; + } else if (mydata.dbop === 'ImpostaATuttiPaypal') { + const listautenti = await User.find({ idapp }); + let num = 0; + for (let rec of listautenti) { + if (!rec._doc.profile.paymenttypes.includes('paypal')) { + rec._doc.profile.paymenttypes = [...rec._doc.profile.paymenttypes, 'paypal']; + const user = await User.findOneAndUpdate({ _id: rec._id }, { $set: { 'profile.paymenttypes': rec._doc.profile.paymenttypes } }); + // await rec.save(); + num++; + } + // const num = await User.f({ idapp }, { $set: { 'profile: false } }); + } + + + ris = { num }; + } else if (mydata.dbop === 'numtessUno') { + const listanavi = await ListaIngresso.find({ idapp }); + let num = 0; + for (let rec of listanavi) { + if (!rec._doc.num_tess) { + rec._doc.num_tess = 1; + const risu = await ListaIngresso.findOneAndUpdate({ _id: rec._id }, { $set: { num_tess: rec._doc.num_tess } }, { new: false }); + // await rec.save(); + if (!!risu) + num++; + } + // const num = await User.f({ idapp }, { $set: { 'profile: false } }); + } + + + ris = { num }; + } else if (mydata.dbop === 'Corregginumtess') { + const listanavi = await Nave.find({ idapp }); + let num = 0; + for (let rec of listanavi) { + const myarrrec = await Nave.find({ idapp, ind_order: rec.ind_order }).sort({ riga: 1, col: 1 }); + let indextess = 1; + for (let ind = 0; ind < myarrrec.length; ind++) { + if (myarrrec[ind].num_tess !== indextess && myarrrec[ind].num_tess === 1) { + myarrrec[ind].num_tess = indextess; + const risu = await Nave.findOneAndUpdate({ _id: myarrrec[ind]._id }, { $set: { num_tess: myarrrec[ind].num_tess } }, { new: false }); + num++; + } + indextess++; + } + } + + ris = { num }; + /* + } + + else if (mydata.dbop === 'CreaNaviPersistenti') { + const listanavi = await Nave.find({ idapp }).sort({riga: 1, col: 1}); + + let params = { + idapp + }; + + let num = 0; + for (let rec of listanavi) { + let mypos = { + idapp, + riga: rec.riga, + col: rec.col, + numup: 3 + }; + tools.getRigaColByPosUp(mypos); + let persistente = await NavePersistente.findByRigaCol(idapp, mypos.riga, mypos.col, 0); + if (!persistente) { + + params.date_start = rec.date_start; + params.date_gift_chat_open = rec.date_gift_chat_open; + params.riga = mypos.riga; + params.col = mypos.col; + if (rec.riga > 3) { + params.riga1don = rec.riga; + params.col1don = rec.col; + } else { + params.riga1don = rec.riga; + params.col1don = rec.col; + } + if (params.riga > 0) { + await NavePersistente.addRecordNavePersistenteByParams(params); + num++; + } + } + } + + ris = { num }; */ + } else if (mydata.dbop === 'CorreggiDataGiftChat') { + const listanavi = await NavePersistente.find({ idapp }); + let num = 0; + for (let rec of listanavi) { + const fieldsvalue = { + date_gift_chat_open: tools.AddDate(rec.date_start, -7) + }; + const risu = await NavePersistente.findOneAndUpdate({ _id: rec._id }, { $set: fieldsvalue }, { new: false }); + if (!!risu) { + num++; + } + } + + ris = { num }; + } else if (mydata.dbop === 'creaUtentiTest') { + + let num = 0; + lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1); + let last = 1; + if (lastrec) { + last = lastrec[0].index; + } + if (!last) { + last = 1; + } + + for (let ind = 0; ind < 100; ind++) { + let myuser = new User(); + myuser._id = new ObjectID(); + myuser.index = last + ind + 1; + myuser.idapp = idapp; + myuser.password = "$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG"; + myuser.lang = 'it'; + myuser.email = "miaemail@email.it"; + myuser.name = 'U' + myuser.index; + myuser.surname = 'Ar' + myuser.index; + myuser.verified_email = true; + if (myuser.index < 2) + myuser.perm = "3"; + myuser.username = "Userna_" + myuser.name; + myuser.profile.special_req = true; + myuser.profile.nationality = 'IT'; + await myuser.save(); + num++; + } + + ris = { num }; + } else if (mydata.dbop === 'visuPlacca') { + + mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' + + 'ECCO LE NUOVE NAVI DEFINITIVE CHE APRONO DOMANI LA GIFT CHAT !!! DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) + '\n' + + 'AUGURI ALLA NUOVA SOGNATRICE !!!\n' + + '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨'; + + const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT'); + + for (let ind = 0; ind < 8; ind++) { + mystr += await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col) + ind, false); + mystr += tools.ACAPO; + if (visu_nave_Bot && ind === 3) { + await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); + mystr = ''; + } + } + + if (visu_nave_Bot) + await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); + + ris = { mystr }; + + /*const rec = {}; + const placca = await Nave.getPlaccaPerDonatore(idapp, parseInt(mydata.riga), parseInt(mydata.col), false, rec); + + telegrambot.sendMsgTelegramToTheAdmin(idapp, placca); + + ris = { placca };*/ + } else if (mydata.dbop === 'visuNave') { + mystr = await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col)); + + const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT'); + if (visu_nave_Bot) + telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); + + ris = { mystr }; + } else if (mydata.dbop === 'getnavibyuser') { + + let arrnavi = null; + + const user = await User.getUserShortDataByUsername(idapp, mydata.username); + if (user) { + arrnavi = await Nave.getArrPosizioniByUsername(idapp, user.username); + + for (let mynave of arrnavi) { + mynave._doc.rec = await Nave.getNaveByRigaCol(idapp, mynave.riga, mynave.col); + } + + } + + ris = { data: arrnavi }; } + + + // console.log('ris', ris); + + return ris; + + } catch (e) { + console.log(e.message); } -); +} + +router.post('/dbop', authenticate, async (req, res) => { + + const mydata = req.body.mydata; + idapp = req.body.idapp; + locale = req.body.locale; + + const ris = await eseguiDbOp(idapp, mydata, locale); + + res.send(ris); + +}); module.exports = router; diff --git a/src/server/server.js b/src/server/server.js index 68130ca..32c235c 100755 --- a/src/server/server.js +++ b/src/server/server.js @@ -18,6 +18,8 @@ const sendemail = require('./sendemail'); const cron = require('node-cron'); +const { Settings } = require('./models/settings'); + i18n = require("i18n"); if ((process.env.NODE_ENV === 'production') || (process.env.NODE_ENV === 'test')) { @@ -248,11 +250,22 @@ function mycron() { for (const app of MYAPPS) { sendemail.checkifPendingNewsletter(app.idapp); sendemail.checkifSentNewsletter(app.idapp); + + } +} + +async function mycron_30min() { + for (const app of MYAPPS) { + const enablecrontab = await Settings.getValDbSettings(app.idapp, tools.ENABLE_CRONTAB, false); + + if (enablecrontab) { + ListaIngresso.Esegui_CronTab(app.idapp); + } } } function testmsgwebpush() { - var { User } = require('./models/user'); + const { User } = require('./models/user'); // console.log('nomeapp 1: ' , tools.getNomeAppByIdApp(1)); // console.log('nomeapp 2: ' , tools.getNomeAppByIdApp(2)); @@ -280,6 +293,12 @@ cron.schedule('*/2 * * * *', () => { mycron(); }); +// Cron every X minutes +cron.schedule('*/30 * * * *', async () => { + + mycron_30min(); +}); + async function resetProcessingJob() { arrrec = await Newstosent.find({}); diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 614dc3a..faedaba 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -2116,7 +2116,6 @@ class Telegram { } if (blocked) { User.SetTelegramWasBlocked(this.idapp, id); - // ++Todo: DA FARE ! local_sendMsgTelegramToTheManagers(this.idapp, addtext + text); } return 0; @@ -2153,7 +2152,7 @@ class Telegram { let text2 = text.slice(4096, text.length); await this._inviaMsg(id, text1, form, menu, msg_id, chat_id, ripr_menuPrec); return await this._inviaMsg(id, text2, form, menu, msg_id, chat_id, ripr_menuPrec); - }else { + } else { return await this._inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec); } diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 0ddf3b7..87a2fc4 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -448,6 +448,8 @@ module.exports = { INITDB_FIRSTIME: true, ACAPO: '\n', + ENABLE_CRONTAB: 'CRONTAB', + LANGADMIN: 'it', AYNI: '7', @@ -1000,6 +1002,14 @@ module.exports = { }); if (params.filterand.includes(shared_consts.FILTER_USER_TELEGRAM_BLOCKED)) filtriadded.push({ 'profile.teleg_id_old': { $gt: 1 } }); + if (params.filterand.includes(shared_consts.FILTER_ATTIVI)) + filtriadded.push({ + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + }); + if (params.filterand.includes(shared_consts.FILTER_NASCOSTI)) + filtriadded.push({ + deleted: { $exists: true, $eq: true } + }); } @@ -1522,6 +1532,9 @@ module.exports = { if ('made_gift' in fieldsvalue) { return true; } + if ('note' in fieldsvalue) { + return true; + } } if (table === 'navepersistente') { if ('link_chat' in fieldsvalue) { @@ -1533,7 +1546,7 @@ module.exports = { }, NotifyIfDelRecord(table) { - if ((table === 'users') || (table === 'extralist')) { + if ((table === 'users') || (table === 'extralist') || (table === 'listaingressos')) { return true; } @@ -1555,5 +1568,9 @@ module.exports = { return '' }, + getmaxcol(riga) { + return Math.pow(2, riga - 1); + }, + }; diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index 48965d8..16af737 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -18,6 +18,8 @@ module.exports = { FILTER_USER_NO_DREAM: 256, FILTER_EXTRALIST_DELETED: 512, FILTER_USER_TELEGRAM_BLOCKED: 1024, + FILTER_ATTIVI: 2048, + FILTER_NASCOSTI: 4096, Permissions: { Admin: 1, @@ -46,6 +48,7 @@ module.exports = { SOSTITUISCI: 345, AGGIUNGI_NUOVO_IMBARCO: 380, CANCELLA_IMBARCO: 385, + DAMMI_PRIMO_UTENTE_LIBERO: 390, }, fieldsUserToChange() { From 92d426c3a6d5d5b02cc95c66c528874fedf651c9 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Mon, 8 Jun 2020 13:31:05 +0200 Subject: [PATCH 06/14] =?UTF-8?q?-=20Nuovo=20Sistema=20di=20Flotte=20per?= =?UTF-8?q?=20Tutor.=20X=20-=20Mettere=20anche=20la=20email=20del=20sognat?= =?UTF-8?q?ore,=20per=20chi=20=C3=A8=20abituato=20ad=20inviarla=20in=20que?= =?UTF-8?q?l=20modo...=20X=20-=20Controllare=20che=20sul=20sito=20compaian?= =?UTF-8?q?o=20le=20informazioni=20del=20Sognatore...?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/passi.txt | 77 ++++- emails/standard/html.pug | 7 + emails/standard/subject.pug | 1 + src/server/models/flotta.js | 325 ++++++++++++++++++ src/server/models/graduatoria.js | 29 +- src/server/models/listaingresso.js | 67 +++- src/server/models/msg_template.js | 102 ++++++ src/server/models/nave.js | 255 +++++++++++--- src/server/models/navepersistente.js | 173 +++++++++- src/server/models/settings.js | 6 +- src/server/models/user.js | 244 ++++++++++++- src/server/router/api/actions.js | 7 +- src/server/router/dashboard_router.js | 83 ++++- src/server/router/index_router.js | 223 ++++++++++-- src/server/router/users_router.js | 65 ++-- src/server/sendemail.js | 27 ++ src/server/server.js | 17 +- src/server/telegram/telegrambot.js | 476 ++++++++++++++++++++++---- src/server/tools/general.js | 102 +++++- src/server/tools/server_constants.js | 1 + src/server/tools/shared_nodejs.js | 4 + 21 files changed, 2037 insertions(+), 254 deletions(-) create mode 100755 emails/standard/html.pug create mode 100755 emails/standard/subject.pug create mode 100755 src/server/models/flotta.js create mode 100755 src/server/models/msg_template.js diff --git a/docs/passi.txt b/docs/passi.txt index db768eb..07024e9 100644 --- a/docs/passi.txt +++ b/docs/passi.txt @@ -1,8 +1,5 @@ ------------ -// ++Todo: FATTO: DA CONTROLLARE - -X - Se sei imbarcata i tuoi due invitati usati per quella posizione sono bloccati. Se ne hai in più li puoi regalare - L'ultimo Utente della Creazione della Nave, compare ancora il Sognatore !!! Sistemato: TESTARE SE ORA È' OK... @@ -12,24 +9,61 @@ X - Se sei imbarcata i tuoi due invitati usati per quella posizione sono bloccat // ++Todo: PRIORITA' ALTA: -CONTROLLARE: +- Puoi imbarcarti non piu di 2 volte temporanee. + +- Togliere Sogno e Video. -- Sistemare la Creazione delle Navi... in semi-automatico. +- Profili Incompleti: + Poter inviare dei messaggi in automatico per ricordargli di completare ... -- Controllare gli Account di Andrea (sembrano mescolati....) socio856 è dentro invece non doveva esserci... - - socio856 non è stato raggruppato con socio85 (Andrea Lai) +- Se non hai fatto una registrazione con verifica email o BOT: + Mandare email dicendo che se non t'iscrivi, verrai cancellato. +- Se non si è qualificato entro 7 gg, manda un msg a lui e all'invitante che verrà cancellato entro 7 gg. -- Mettere il tragitto anche sul BOT. +- Se sei in conversazione e premi i menu, esci dalla conversazione ! + +- CHIEDERE ALLA PERSONA SE VUOLE ESSERE SOSPESO OPPURE CANCELLATO! + Se ha solo questo imbarco: + - Come da tua richiesta, sei stato sostituito. + - Vuoi cancellare questo profilo? -> "Nascosto" + - Vuoi Sospendere il profilo? -> "Sospeso" + +- Se l'utente entra ed è "Nascosto": + - Gli chiedo se vuole ripristinare l'account... + +- Rimettere "made_gift" a false se si ha sbagliato... + +- Mettere 3 giorni. + +- Fondo Ayni 9.152 : aggiungere registrazione Paolo2 Arena. e mettere paypal.me + +- Mandare msg ai Non Invitati, o inferiori di 2. + +- aggiungere le note di pagamento, a nome di chi è il pagamento? - Inviare il Link che punta alla Pagina del Sito, per effettuare il Dono! E per eventualmente Entrare nella GIFT CHAT! +- Mettere i messaggi del DONO in LINGUA (metterli sul server). + +- ULTIMA FLOTTA DA - A DEFINITIVA +- ULTIMA NAVE DEFINITIVA...N.NN + + +- Non poter sostituire i Ritessuti ! D8 + + + - Il LastNave non sembra essere corretto! + + +- Sistemare la Creazione delle Navi... in semi-automatico. + // ++Todo: PRIORITA' NORMALE: -- Se entro con la seconda utenza, gli mando messaggio che dice che deve collegarsi con la prima utenza.... +- AGGIUNGERCI L'USERNAME REALE ! ALTRIMENTI PRENDE IL PRINCIPALE !! - Fare funzione che passa un Utente secondario in un utente Primario! (c'è gia) @@ -37,7 +71,6 @@ CONTROLLARE: // ++Todo: DA FARE PIU AVANTI: -- Sistemare poter modificare le Pagine. - Per il Fondo Ayni, prevedere anche altri Metodi di Pagamento... Revolut, N26, ecc... ed inserirlo sul sito per il Sognatore (flag Pagato al Fondo: nave.offerta_al_fondo). @@ -74,9 +107,11 @@ SOSTITUISCI: - Sistemare che in Edit Pagina, se è troppo grande, va oltre l'altezza della finestra. +- Attivare le Traduttrici alle Pagine + +- Inviare messaggi solo per ITALIANI (o di lingua cmq). - Aggiornare le FAQ in lingua -- Attivare le Traduttrici alle Pagine - CONTROLLARE CON ARGENTINA E PORTOGALLO e Brasile: @@ -123,3 +158,23 @@ ANDREA //++TODO: *** FATTI *** + + +// ++Todo: FATTO: DA CONTROLLARE + +X - Se sei imbarcata i tuoi due invitati usati per quella posizione sono bloccati. Se ne hai in più li puoi regalare +X - Numero d'invitati sbagliato -> Nogalska +X - 50 persone non hanno un'imbarco -> Chiamare funzione che gliela rimette. + +X - Poter Inviare un msg preconfezionato a chi non la la nave ! +X Poter cliccare SI per aggiungersi ad un Nuovo Imbarco. +X - Se entro con la seconda utenza, gli mando messaggio che dice che deve collegarsi con la prima utenza.... + +X - Sistemare poter modificare le Pagine. + +X - SISTEMARE QUANDO L'ULTIMA NAVE DELLA FLOTTA C'E' UN SOGNATORE CHE HA LA NAVE DI RITORNO! +X - IL MEDIATORE DEVE AVERE LA SUA RITESSUTURA !!! ( TOGLIERE L'IF NEL CASO NON SIA SOGNATORE) + +X - Mettere anche la email del sognatore, per chi è abituato ad inviarla in quel modo... +X - Controllare che sul sito compaiano le informazioni del Sognatore... + diff --git a/emails/standard/html.pug b/emails/standard/html.pug new file mode 100755 index 0000000..a957076 --- /dev/null +++ b/emails/standard/html.pug @@ -0,0 +1,7 @@ +p #{dataemail.emailbody} + +style(type="text/css"). + html, body { + padding: 0; + margin: 0; + } diff --git a/emails/standard/subject.pug b/emails/standard/subject.pug new file mode 100755 index 0000000..28e7d70 --- /dev/null +++ b/emails/standard/subject.pug @@ -0,0 +1 @@ +=`${dataemail.emailtitle}` diff --git a/src/server/models/flotta.js b/src/server/models/flotta.js new file mode 100755 index 0000000..20cfbf3 --- /dev/null +++ b/src/server/models/flotta.js @@ -0,0 +1,325 @@ +const mongoose = require('mongoose'); +const _ = require('lodash'); + +const tools = require('../tools/general'); + +const { ListaIngresso } = require('./listaingresso'); +const { Settings } = require('./settings'); +const { User } = require('./user'); + +const { ObjectID } = require('mongodb'); + +const shared_consts = require('../tools/shared_nodejs'); + +mongoose.Promise = global.Promise; + +mongoose.level = "F"; +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +mongoose.set('debug', process.env.DEBUG); + + +const FlottaSchema = new mongoose.Schema({ + idapp: { + type: String, + required: true, + }, + index: { + type: Number + }, + riga: { + type: Number, + }, + col_prima: { + type: Number, + }, + col_ultima: { + type: Number, + }, + date_start: { + type: Date + }, + date_close: { + type: Date + }, + provvisoria: { + type: Boolean, + }, + DoniAttesaDiConferma: { + type: Number, + }, + DoniMancanti: { + type: Number, + }, + DoniConfermati: { + type: Number, + }, + DoniTotali: { + type: Number, + }, + note_interne: { + type: String + }, + sognatore: { + type: String + }, + sognatore_nomecognome: { + type: String + }, + link_superchat: { + type: String, + }, + link_payment: { + type: String, + }, + email_paypal: { + type: String, + }, + note_payment: { + type: String, + }, + tutor1: { + type: String, + }, + tutor2: { + type: String, + }, + tutor3: { + type: String, + }, + tutorslo: { + type: String, + }, + msg_inviato: { + type: Boolean, + }, + +}); + +function getQueryProj(myfilter) { + + myobjField = { + _id: 1, + idapp: 1, + lang: 1, + ind_order: 1, + name: 1, + surname: 1, + username: 1, + 'profile.paymenttypes': 1, + 'profile.email_paypal': 1, + 'profile.cell': 1, + made_gift: 1, + commento_al_sognatore: 1, + sent_msg_howto_make_gift: 1, + date_made_gift: 1, + note: 1, + received_gift: 1, + date_received_gift: 1, + num_tess: 1, + parent_id: 1, + riga: 1, + col: 1, + created: 1, + // date_start: 1, + // date_gift_chat_open: 1, + // link_chat: 1, + // provvisoria: 1, + // note_bot: 1, + // note_interne: 1, + // tutor: 1, + // tutor_namesurname: 1, + }; + + const query = [ + { $match: myfilter }, + { + $lookup: { + from: "listaingressos", + localField: "ind_order", + foreignField: "ind_order", // field in the user collection + as: "mylista" + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$mylista", 0 ] }, "$$ROOT" ] } } + }, + { + $lookup: { + from: "users", + as: "user", + let: {username: '$username' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$username', '$$username'] }, + { $eq: ['$idapp', myfilter.idapp] }, + ] + } + } + } + ] + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] }, "$$ROOT"] } } + // $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] },] } } + }, + { $project: myobjField } + ]; + + return query; +} + + +FlottaSchema.statics.findById = function (idapp, id) { + const Flotta = this; + + const myquery = getQueryProj({ idapp, '_id': ObjectID(id) }); + + return Flotta.aggregate(myquery); + +}; + +FlottaSchema.statics.getFieldsForSearch = function () { + return [{ field: 'ind_order', type: tools.FieldType.number }, + { field: 'col', type: tools.FieldType.number }] +}; + +FlottaSchema.statics.executeQueryTable = function (idapp, params) { + params.fieldsearch = this.getFieldsForSearch(); + return tools.executeQueryTable(this, idapp, params); +}; + +FlottaSchema.statics.findAllIdApp = function (idapp) { + const Flotta = this; + + const myfind = { idapp }; + + return Flotta.find(myfind).sort({ riga: 1, col: 1 }); +}; + +FlottaSchema.statics.getListaFlotta = function (idapp) { + const Flotta = this; + + const myfind = { idapp }; + + return Flotta.find(myfind).sort({ riga: 1, col_prima: 1 }); +}; + +FlottaSchema.statics.getLastFlotta = function (idapp) { + const Flotta = this; + + const myfind = { idapp, date_start: { $lte: tools.IncDateNow(0) }, provvisoria: false }; + + return Flotta.findOne(myfind).sort({ riga: -1, col_prima: -1 }).limit(1); +}; + +FlottaSchema.statics.findByRigaColByDonatore = function (idapp, riga, col, offset) { + const Flotta = this; + + mypos = { + riga, + col, + numup: 3 + offset, + }; + tools.getRigaColByPosUp(mypos); + + return Flotta.findOne({ idapp, riga: mypos.riga, col_prima: mypos.col }); + +}; + +FlottaSchema.statics.findByRigaCol = function (idapp, riga, col) { + const Flotta = this; + + return Flotta.findOne({ idapp, riga, col }); + +}; + + +FlottaSchema.statics.getLastRigaCol = async function (idapp) { + return Flotta.findOne({ idapp }).sort({ riga: -1, col_prima: -1 }); +}; + +FlottaSchema.statics.getLastRigaColDefinitiva = async function (idapp) { + return Flotta.findOne({ idapp, provvisoria: false }).sort({ riga: -1, col_prima: -1 }); +}; + +FlottaSchema.pre('save', async function (next) { + if (this.isNew) { + const myrec = await Flotta.findOne().limit(1).sort({ _id: -1 }); + if (!!myrec) { + this.index = myrec._doc.index + 1; + } else { + this.index = 1; + } + } + + next(); +}); + + +FlottaSchema.statics.addRecordFlottaByParams = async function (params) { + + // Check if Exist: + const giapresente = await Flotta.findOne({ + idapp: params.idapp, + riga: params.riga, + col: params.col + }); + + if (!giapresente) { + // Prende la nave prima: + const lastnave = await Flotta.findOne({idapp}).sort({riga: -1, col: -1}); + + let nextgiftchat = null; + + if (((params.col - 1) % 8 === 0)) { + nextgiftchat = getNextDayNave(lastnave.date_gift_chat_open); + } else { + nextgiftchat = lastnave.date_gift_chat_open; + } + + const next_date_start = tools.AddDate(nextgiftchat, 7); + + let myFlotta = new Flotta({ + idapp: params.idapp, + riga: params.riga, + col: params.col, + riga1don: params.riga1don, + col1don: params.col1don, + date_gift_chat_open: nextgiftchat, + date_start: next_date_start, + provvisoria: true, + }); + return await myFlotta.save(); + } + + return false; +}; + +FlottaSchema.statics.getFlottaByNavePersistente = async function (idapp, navepers) { + const Flotta = this; + + // const indcolflottaprima = tools.getPrimaColFlotta(navepers.col1don + 7); + + const myflotta = await Flotta.findOne({ idapp, riga: navepers.riga, + $and: [ + { col_prima: { $lte: navepers.col1don } }, + { col_ultima: { $gte: navepers.col1don } } ] + }); + + return myflotta; +}; + + +const Flotta = mongoose.model('Flotta', FlottaSchema); + +module.exports = { Flotta }; + + diff --git a/src/server/models/graduatoria.js b/src/server/models/graduatoria.js index 3e1de6e..6d1bee6 100755 --- a/src/server/models/graduatoria.js +++ b/src/server/models/graduatoria.js @@ -78,6 +78,12 @@ const GraduatoriaSchema = new mongoose.Schema({ invitante_username: { type: String, }, + navestr: { + type: String, + }, + note: { + type: String, + }, date_added: { // Data d'Ingresso (Completato i Requisiti o premuto Bottone Magico) type: Date, }, @@ -197,11 +203,15 @@ GraduatoriaSchema.statics.addSingoloInGraduatoria_InFondo = async function (idap const { ListaIngresso } = require('../models/listaingresso'); - arrindex[recingr.username] = lastimbarco.indimbarco; + if (!!lastimbarco) { + arrindex[recingr.username] = lastimbarco.indimbarco; + } else { + arrindex[recingr.username] = 1; + } const newingr = await ListaIngresso.aggiornaRecListaIngr(idapp, recingr, arrindex); - const myrectoadd = addRecGraduatoria(idapp, newingr); + const myrectoadd = addRecGraduatoria(idapp, newingr, 100000); return await myrectoadd.save(myrectoadd) .then((ris) => { @@ -211,6 +221,7 @@ GraduatoriaSchema.statics.addSingoloInGraduatoria_InFondo = async function (idap console.error(e.message); }); + }; function addRecGraduatoria(idapp, ingr, index) { @@ -233,6 +244,8 @@ function addRecGraduatoria(idapp, ingr, index) { numinvitatiattiviTot: ingr.numinvitatiattiviTot, punteggio: ingr.punteggio, invitante_username: ingr.invitante_username, + navestr: ingr.navestr, + note: ingr.note, date_added: ingr.date_added, }); @@ -312,12 +325,24 @@ GraduatoriaSchema.statics.isWorking = function (idapp) { }; +GraduatoriaSchema.statics.isUpdating = function (idapp) { + + return Settings.getValDbSettings(idapp, tools.UPDATE_GRADUATORIA, false); + +}; + GraduatoriaSchema.statics.setWorking = function (idapp, stato) { return Settings.setBool(idapp, 'GRAD_WORK', stato); }; +GraduatoriaSchema.statics.setGradUpdating = function (idapp, stato) { + + return Settings.setBool(idapp, tools.UPDATE_GRADUATORIA, stato); + +}; + function getinvit(index, myrec) { let inv = myrec.numinvitati; let invattivi = myrec.numinvitatiattivi; diff --git a/src/server/models/listaingresso.js b/src/server/models/listaingresso.js index 54122ad..17baa74 100755 --- a/src/server/models/listaingresso.js +++ b/src/server/models/listaingresso.js @@ -54,6 +54,9 @@ const ListaIngressoSchema = new mongoose.Schema({ num_tess: { type: Number, }, + navestr: { + type: String, + }, note: { type: String, }, @@ -614,8 +617,8 @@ ListaIngressoSchema.statics.GeneraGraduatoria = async function (idapp, solonuovi let myquery = ''; //++Todo: DA TOGLIERE IL COMMENTO !!! - // if (await Graduatoria.isWorking(idapp)) - // return; + if (await Graduatoria.isWorking(idapp)) + return; await Graduatoria.setWorking(idapp, true); @@ -627,6 +630,7 @@ ListaIngressoSchema.statics.GeneraGraduatoria = async function (idapp, solonuovi surname: 1, username: 1, invitante_username: 1, + navestr: 1, email: 1, lang: 1, num_tess: 1, @@ -638,8 +642,13 @@ ListaIngressoSchema.statics.GeneraGraduatoria = async function (idapp, solonuovi try { let myfilter2 = { - surname: { $exists: true }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + + $or: [{ surname: { $exists: true } }, { deleted: { $exists: false } }, { + deleted: { + $exists: true, + $eq: false + } + }], }; if (solonuovi) { @@ -931,8 +940,13 @@ ListaIngressoSchema.statics.getarray = async function (idapp, filtri, myobjField let myfilter2 = { - surname: { $exists: true }, - $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], + + $or: [{ surname: { $exists: true } }, { 'user.deleted': { $exists: false } }, { + 'user.deleted': { + $exists: true, + $eq: false + } + }], }; let myquery = getQueryProj( @@ -949,8 +963,8 @@ ListaIngressoSchema.statics.getarrayIndOrder = async function (idapp, filtri, my const ListaIngresso = this; let myfilter2 = { - surname: { $exists: true }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + + $or: [{ surname: { $exists: true } }, { deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }; let myquery = getQueryIndOrder( @@ -973,7 +987,8 @@ ListaIngressoSchema.statics.getIngrEUserByFilter = async function (idapp, myfilt ind_order: 1, name: 1, surname: 1, - index: 1 + index: 1, + num_tess: 1 }); if (!!arr) { @@ -989,7 +1004,7 @@ ListaIngressoSchema.statics.getInvitati = async function (idapp, username, inclu let myq = { idapp, - $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], invitante_username: username, }; @@ -1043,7 +1058,7 @@ ListaIngressoSchema.statics.getnumInvitatiBase = async function (idapp, username idapp, invitante_username: username, // username: { $ne: username }, - $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, { username: 1, ind_order: 1 }, myfilter2, @@ -1058,7 +1073,7 @@ ListaIngressoSchema.statics.getnumInvitatiBase = async function (idapp, username idapp, aportador_solidario: username, //$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }; if (attivi) { @@ -1114,13 +1129,37 @@ ListaIngressoSchema.statics.getnumInvitati = async function (idapp, username) { }; -ListaIngressoSchema.statics.Esegui_CronTab = async function (idapp) { +ListaIngressoSchema.statics.Esegui_CronTab = async function (idapp, mydata) { const ListaIngresso = this; console.log('Lancia CronTab: [IDAPP=' + idapp + ']'); - await ListaIngresso.GeneraGraduatoria(idapp, true); + let num = 0; + try { + if (!await Graduatoria.isUpdating()) { + await Graduatoria.setGradUpdating(idapp, true); + + ris = await Nave.delNaviProvvisorie(idapp); + + mystr = await ListaIngresso.GeneraGraduatoria(idapp, true); + await Graduatoria.setWorking(idapp, false); + + num = await Nave.generaNave(idapp, mydata, false); + } + + } catch (e) { + console.error('ERRORE CronTab: [IDAPP=' + idapp + ']', e.message); + + } finally { + await Graduatoria.setGradUpdating(idapp, false); + await Graduatoria.setWorking(idapp, false); + + console.log('FINE CronTab: [IDAPP=' + idapp + ']'); + } + + + return num; }; ListaIngressoSchema.statics.getnumInvitatiAttivi = function (idapp, username) { diff --git a/src/server/models/msg_template.js b/src/server/models/msg_template.js new file mode 100755 index 0000000..06a74d9 --- /dev/null +++ b/src/server/models/msg_template.js @@ -0,0 +1,102 @@ +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +const tools = require('../tools/general'); + +mongoose.Promise = global.Promise; +mongoose.level = "F"; + + +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +const MsgTemplateSchema = new Schema({ + idapp: { + type: String, + }, + typemsg: { + type: Number, + }, + title: { + type: String, + }, + title_it: { + type: String, + }, + msg_it: { + type: String, + }, + title_enUs: { + type: String, + }, + msg_enUs: { + type: String, + }, + title_si: { + type: String, + }, + msg_si: { + type: String, + }, + title_fr: { + type: String, + }, + msg_fr: { + type: String, + }, + title_es: { + type: String, + }, + msg_es: { + type: String, + }, + title_pt: { + type: String, + }, + msg_pt: { + type: String, + }, +}); + +MsgTemplateSchema.statics.getFieldsForSearch = function () { + return [{ field: 'title', type: tools.FieldType.string }, + ] +}; + +MsgTemplateSchema.statics.executeQueryTable = function (idapp, params) { + params.fieldsearch = this.getFieldsForSearch(); + return tools.executeQueryTable(this, idapp, params); +}; + +MsgTemplateSchema.statics.getMsgByLang = async function (idapp, typemsg, lang) { + const MsgTemplate = this; + + try { + const mymsg = await MsgTemplate.findOne({ idapp, typemsg }); + if (!!mymsg) { + if ((!!mymsg["msg_" + lang]) && (!!mymsg["title_" + lang])) { + return { body: mymsg["msg_" + lang], title: mymsg["title_" + lang] } + } + } + } catch (e) { + return { body: '', title: '' }; + } + + return { body: '', title: '' }; + +}; +MsgTemplateSchema.statics.findAllIdApp = async function (idapp) { + const MsgTemplate = this; + + const myfind = { idapp }; + + return await MsgTemplate.find(myfind, (err, arrrec) => { + return arrrec + }); +}; + +const MsgTemplate = mongoose.model('MsgTemplate', MsgTemplateSchema); + +module.exports = { MsgTemplate }; diff --git a/src/server/models/nave.js b/src/server/models/nave.js index 4f4bc32..388236e 100755 --- a/src/server/models/nave.js +++ b/src/server/models/nave.js @@ -7,6 +7,7 @@ const { ListaIngresso } = require('./listaingresso'); const { NavePersistente } = require('./navepersistente'); const { Settings } = require('./settings'); const { User } = require('./user'); +const { Flotta } = require('../models/flotta'); const { ObjectID } = require('mongodb'); @@ -73,6 +74,9 @@ const NaveSchema = new mongoose.Schema({ type: Number, default: 1 }, + commento_al_sognatore: { + type: String + }, note: { type: String }, @@ -272,6 +276,21 @@ NaveSchema.statics.getusersByNave = function (idapp, navemediatore) { }; +NaveSchema.statics.getusersByFlotta = function (idapp, riga, col_prima, col_ultima) { + + const miaquery = { + idapp, + riga: riga + 3, + $and: [ + { col: { $gte: col_prima } }, + { col: { $lte: col_ultima } } + ], + }; + + return Nave.find(miaquery); + +}; + NaveSchema.statics.findRecByRigaColParent = async function (idapp, riga, col, numparentUp) { const Nave = this; @@ -427,7 +446,10 @@ function getQueryProj(myfilter) { 'profile.paymenttypes': 1, 'profile.teleg_id': 1, 'profile.email_paypal': 1, + 'profile.link_payment': 1, + 'profile.note_payment': 1, 'profile.cell': 1, + commento_al_sognatore: 1, made_gift: 1, sent_msg_howto_make_gift: 1, date_made_gift: 1, @@ -502,6 +524,7 @@ function getQueryInvitante(myfilter) { username: 1, invitante_username: 1, made_gift: 1, + commento_al_sognatore: 1, sent_msg_howto_make_gift: 1, date_made_gift: 1, note: 1, @@ -574,13 +597,6 @@ NaveSchema.statics.getCol = function (idapp) { return Settings.getKeyNum(idapp, 'col', 1); }; -function getPrimoFuocoByIndCol(col) { - // let ris = Math.ceil(col - (col % 8)) + 1; - let ris = ((Math.ceil(col / 8) - 1) * 8) + 1; - if (ris <= 0) - ris = 1; - return ris -} async function getusertextbyrec(myrec, symbol, lettera, riga, col, ind) { let visu_test = false; @@ -619,10 +635,16 @@ function checkifNullThenEmpty(rec, riga, col) { NaveSchema.statics.getPlaccaGenerica = async function (idapp, riga, col, offset, solorecord) { const Nave = this; + const { Flotta } = require('../models/flotta'); + + try { let recsognatori = await Nave.findSognatoriByFuoco(idapp, riga, col, offset); let recmediatore = await Nave.findMediatoreByFuoco(idapp, riga, col, offset); let navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, riga, col, offset); + let flotta = null; + if (!!navepersistente) + flotta = await Flotta.getFlottaByNavePersistente(idapp, navepersistente); if (!solorecord) { mystr = tools.ACAPO; @@ -658,7 +680,7 @@ NaveSchema.statics.getPlaccaGenerica = async function (idapp, riga, col, offset, let arrdonatori = []; // let numcol = Math.pow(2, indriga - 1); - let primofuoco = getPrimoFuocoByIndCol(col * Math.pow(2, offset)); + let primofuoco = tools.getPrimoFuocoByIndCol(col * Math.pow(2, offset)); let ind = 1; for (let indcol = primofuoco; indcol < primofuoco + 8; indcol++) { @@ -689,6 +711,7 @@ NaveSchema.statics.getPlaccaGenerica = async function (idapp, riga, col, offset, recsognatori, recmediatore, navepersistente, + flotta, arrdonatori }; @@ -1014,7 +1037,7 @@ async function addRecordNaveByParams(params, siRitesse) { const giapresente = await Nave.findOne({ idapp: params.idapp, ind_order: params.ind_order, - num_tess: params.num_tess + num_tess: params.num_tess, }); if (!!giapresente) { if (params.persistenti) { @@ -1037,10 +1060,14 @@ async function addRecordNaveByParams(params, siRitesse) { }); myNave.created = new Date(); + if (!!params.note) { + myNave.note = params.note; + } + // console.log('[' + params.riga + ',' + params.col + ']'); // console.log('parent = [' + params.rigaparent + ',' + params.colparent + ']'); - const recfindparent = await Nave.findByRigaCol(idapp, params.rigaparent, params.colparent, false); + const recfindparent = await Nave.findByRigaCol(params.idapp, params.rigaparent, params.colparent, false); // console.log('recfindparent = [' + recfindparent + ']'); // console.table(recfindparent); @@ -1058,14 +1085,17 @@ async function addRecordNaveByParams(params, siRitesse) { if (!!result) { if (params.persistenti) { - let fields_to_update = { added: true }; + let fields_to_update = { added: true, navestr: mypos.riga + '.' + mypos.col }; + await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); + } else { + let fields_to_update = { navestr: mypos.riga + '.' + mypos.col }; await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); } params.conta++; // Check if the Ship has Completed - if (idapp === tools.AYNI) { + if (params.idapp === tools.AYNI) { if ((params.col % 8) === 0) { // Completed 8 people if (!params.primavolta) { @@ -1089,8 +1119,8 @@ async function addRecordNaveByParams(params, siRitesse) { else params.colparent = Math.ceil(params.col / 2); - await Nave.setRiga(idapp, params.riga); - await Nave.setCol(idapp, params.col); + await Nave.setRiga(params.idapp, params.riga); + await Nave.setCol(params.idapp, params.col); return true; } @@ -1126,33 +1156,35 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida const { User } = require('./user'); - if (init) { - params.idapp = idapp; - params.conta = 0; - } + try { - params.primavolta = (params.riga === 1) && (params.col === 1); - params.riga = await Nave.getRiga(idapp); - params.col = await Nave.getCol(idapp); - params.maxcol = tools.getmaxcol(params.riga); - params.colparent = Math.ceil(params.col / 2); - params.rigaparent = params.riga - 1; + if (init) { + params.idapp = idapp; + params.conta = 0; + } - if (params.rigaparent === 0) - params.colparent = 0; + params.primavolta = (params.riga === 1) && (params.col === 1); + params.riga = await Nave.getRiga(idapp); + params.col = await Nave.getCol(idapp); + params.maxcol = tools.getmaxcol(params.riga); + params.colparent = Math.ceil(params.col / 2); + params.rigaparent = params.riga - 1; - myriga = params.riga; - mycol = params.col; + if (params.rigaparent === 0) + params.colparent = 0; - const inserito = await addRecordNaveByParams(params, false); - if (inserito) { - if (idapp === tools.AYNI) { - if ((((params.col) % 8) === 0) && (params.col % 64 !== 0)) { + myriga = params.riga; + mycol = params.col; + + const inserito = await addRecordNaveByParams(params, false); + if (inserito) { + if (idapp === tools.AYNI) { let recmediatore = await Nave.findMediatoreByFuoco(idapp, myriga, mycol, 0); - if (!!recmediatore) { - const ris = await Nave.checkifDeveRitessersi(recmediatore); - if (ris.deveritessersi) { - console.log('Si deve ritessere: [riga=', params.riga, 'col', params.col, ']'); + let sognatore = await Nave.getSognatoreByRigaColMediatore(idapp, recmediatore); + if ((((params.col) % 8) === 0) && ((params.col % 64 !== 0) || (sognatore.username !== recmediatore.username))) { + if (!!recmediatore) { + const ris = await Nave.checkifDeveRitessersi(recmediatore); + // console.log('Si deve ritessere: [riga=', params.riga, 'col', params.col, ']'); if (ris.deveritessersi) { params.ind_order = recmediatore.ind_order; params.id = recmediatore._id; @@ -1163,10 +1195,9 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida } } } - } - /** - if ((params.riga === 4 + 3) && (params.col === (8 * 2) + 3)) { + /** + if ((params.riga === 4 + 3) && (params.col === (8 * 2) + 3)) { // Si ritesse il Fondo AYNI nella Nave 3.3 const userFondo = await User.findByIndex(idapp, 0); params.ind_order = userFondo.ind_order; @@ -1176,12 +1207,15 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida await addRecordNaveByParams(params, true); } **/ + } } - } - // Se ho completato 8 persone, allora - if (addednowreal) { + // Se ho completato 8 persone, allora + if (addednowreal) { + } + } catch (e) { + console.error(e.message); } }; @@ -1233,6 +1267,7 @@ NaveSchema.statics.generaNave = async function (idapp, mydata, persistenti) { params.ind_order = reclista.ind_order; params.id = reclista.idListaIngresso; params.num_tess = reclista.num_tess; + params.note = reclista.note; params.persistenti = persistenti; await Nave.addUserFromListaIngresso_IntoNave(index === 0, idapp, params, false); @@ -1307,26 +1342,49 @@ NaveSchema.statics.pulisciNonPresenzeInNave = async function (idapp) { NaveSchema.statics.visuNaviUtentiEliminati = async function (idapp) { const Nave = this; - let numrec = 0; + const { ListaIngresso } = require('./listaingresso'); + const { User } = require('./user'); - const myquery = getQueryProj({ idapp }); - - arrrec = await Nave.aggregate(myquery).sort({ riga: 1, col: 1 }); + arrnavi = await Nave.find({ idapp }).sort({ riga: 1, col: 1 }); let mystr = 'ELIMINATI: \n'; let conta = 0; - for (const rec of arrrec) { - if (!rec.username) { - let navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, rec.riga, rec.col, 0); + for (const nave of arrnavi) { + const recingr = await ListaIngresso.findOne({ + idapp, + ind_order: nave.ind_order, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + }); + + let rec = null; + + if (!!recingr) { + rec = await User.findOne({ idapp, username: recingr.username }); + } + + if (!rec || !rec.username || rec.deleted) { + let navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, nave.riga, nave.col, 0); if (!!navepersistente) { - mystr += '[' + conta + '] [NAVI ' + navepersistente.riga + '.' + navepersistente.col + '] [' + rec.riga + '.' + rec.col + '] ' + rec.ind_order; - mystr += ' num_tess = ' + rec.num_tess; + mystr += '[' + conta + '] [NAVI ' + navepersistente.riga + '.' + navepersistente.col + '] [' + nave.riga + '.' + nave.col + '] ' + ' ord= ' + nave.ind_order; + mystr += ' num_tess = ' + nave.num_tess + ' '; + if (!!rec) { + if (!!rec.username) { + mystr += ' [' + rec.username + '] '; + } + if (!!rec.name) { + mystr += ' (' + rec.name + ' ' + rec.surname + ') '; + } + if (rec.deleted) { + mystr += ' (CANCELLATO)'; + } + } mystr += '\n'; conta++; } } } + return { mystr, num: conta }; }; @@ -1421,6 +1479,58 @@ NaveSchema.statics.getDonatoridelSognatore = async function (idapp, riganave, co }; +NaveSchema.statics.getFlotta = async function (idapp, riga, col_prima, col_ultima) { + const Nave = this; + + const myquery = getQueryProj({ + idapp, + riga: riga + 3, + col: { $gte: col_prima, $lte: col_ultima } + }); + + const { Flotta } = require('../models/flotta'); + + const flotta = await Flotta.findOne({ idapp, riga, col_prima }); + + const { User } = require('./user'); + + const usersognatore = await User.findOne({idapp, username: flotta.sognatore }); + if (!!usersognatore) { + flotta.link_payment = usersognatore.profile.link_payment; + flotta.email_paypal = usersognatore.profile.email_paypal; + flotta.note_payment = usersognatore.profile.note_payment; + } + + const arrnaviout = []; + + const arrnavi = await Nave.aggregate(myquery); + + for (const nave of arrnavi) { + // Se è il mediatore, allora non includerlo nei Donatori! + mypos = { + riga: nave.riga, + col: nave.col, + numup: 3, + }; + + tools.getRigaColByPosUp(mypos); + + const navemediatore = await Nave.findByRigaCol(idapp, mypos.riga, mypos.col, true); + if (!!navemediatore) { + if (navemediatore.ind_order !== nave.ind_order) { + arrnaviout.push(nave); + } + } else { + arrnaviout.push(nave); + } + } + + flotta._doc.log_attivita = tools.readFlottaLog(idapp, flotta.riga, flotta.col_prima); + + return { arrdonatori: arrnaviout, flotta }; + +}; + NaveSchema.statics.isDefinitiva = async function (idapp, mynave) { const nave = await NavePersistente.findByRigaColByDonatore(idapp, mynave.riga, mynave.col, 0); return (!!nave) ? !nave.provvisoria : false; @@ -1553,9 +1663,47 @@ NaveSchema.statics.checkIfMadeGift = async function (idapp, username) { }; -NaveSchema.statics.getSognatoreByRigaColMediatore = async function (idapp, navemediatore) { +NaveSchema.statics.delNaviProvvisorie = async function (idapp) { + const Nave = this; - const ris = this.getRigaColSognatoreByMediatore(idapp, navemediatore.riga, navemediatore.col, 3); + let num = 0; + + const arrnavi = await Nave.find({ idapp }); + + for (const nave of arrnavi) { + let persistente = await NavePersistente.findByRigaColByDonatore(idapp, nave.riga, nave.col, 0); + if (!!persistente) { + if (persistente.provvisoria) { + let ris = await Nave.deleteOne({ _id: nave._id }); + if (!!ris) { + num++; + } + } + } + } + + // Pulisci gli added se era stato cancellato dalla nave + await Nave.pulisciNonPresenzeInNave(idapp); + + const data = await Nave.getLastRigaCol(idapp); + await Nave.setRiga(idapp, data.riga); + await Nave.setCol(idapp, data.col + 1); + + const maxcol = tools.getmaxcol(data.riga); + if (data.col === maxcol) { + await Nave.setRiga(idapp, data.riga + 1); + await Nave.setCol(idapp, 1); + } + + return { num }; + +}; + + +NaveSchema.statics.getSognatoreByRigaColMediatore = async function (idapp, navemediatore) { + const Nave = this; + + const ris = tools.getRigaColSognatoreByMediatore(idapp, navemediatore.riga, navemediatore.col); const myquery = getQueryProj({ idapp, @@ -1573,7 +1721,6 @@ NaveSchema.statics.getSognatoreByRigaColMediatore = async function (idapp, navem return null; }; - const Nave = mongoose.model('Nave', NaveSchema); module.exports = { Nave }; diff --git a/src/server/models/navepersistente.js b/src/server/models/navepersistente.js index 6fcd055..626fbff 100755 --- a/src/server/models/navepersistente.js +++ b/src/server/models/navepersistente.js @@ -7,6 +7,8 @@ const { ListaIngresso } = require('./listaingresso'); const { Settings } = require('./settings'); const { User } = require('./user'); +const { Flotta } = require('./flotta'); + const { ObjectID } = require('mongodb'); const shared_consts = require('../tools/shared_nodejs'); @@ -92,6 +94,8 @@ function getQueryProj(myfilter) { username: 1, 'profile.paymenttypes': 1, 'profile.email_paypal': 1, + 'profile.link_payment': 1, + 'profile.note_payment': 1, 'profile.cell': 1, made_gift: 1, sent_msg_howto_make_gift: 1, @@ -125,13 +129,13 @@ function getQueryProj(myfilter) { } }, { - $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$mylista", 0 ] }, "$$ROOT" ] } } + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$mylista", 0] }, "$$ROOT"] } } }, { $lookup: { from: "users", as: "user", - let: {username: '$username' }, + let: { username: '$username' }, pipeline: [ { $match: { @@ -209,7 +213,7 @@ NavePersistenteSchema.statics.getListaNavi = function (idapp) { NavePersistenteSchema.statics.getLastNave = function (idapp) { const NavePersistente = this; - const myfind = { idapp, date_start: { $lte: tools.IncDateNow(0) }, provvisoria: false }; + const myfind = { idapp, date_start: { $lte: tools.IncDateNow(0) }, provvisoria: false }; return NavePersistente.findOne(myfind, { @@ -250,10 +254,13 @@ NavePersistenteSchema.statics.findByRigaCol = function (idapp, riga, col) { NavePersistenteSchema.statics.getLastRigaCol = async function (idapp) { + const NavePersistente = this; return NavePersistente.findOne({ idapp }).sort({ riga: -1, col: -1 }); }; NavePersistenteSchema.statics.getLastRigaColDefinitiva = async function (idapp) { + const NavePersistente = this; + return NavePersistente.findOne({ idapp, provvisoria: false }).sort({ riga: -1, col: -1 }); }; @@ -272,7 +279,8 @@ NavePersistenteSchema.pre('save', async function (next) { function getNextDayNave(miadata) { - const dayofweek = [1, 3, 5]; // LUNEDI, MERCOLEDI, VENERDI + // const dayofweek = [1, 2, 4, 5]; // LUNEDI, MARTEDI', GIOVEDI, VENERDI + const dayofweek = [1, 4]; // LUNEDI, GIOVEDI let mydate = tools.AddDate(miadata, 1); @@ -285,6 +293,7 @@ function getNextDayNave(miadata) { } NavePersistenteSchema.statics.addRecordNavePersistenteByParams = async function (params) { + const NavePersistente = this; // Check if Exist: const giapresente = await NavePersistente.findOne({ @@ -295,7 +304,7 @@ NavePersistenteSchema.statics.addRecordNavePersistenteByParams = async function if (!giapresente) { // Prende la nave prima: - const lastnave = await NavePersistente.findOne({idapp}).sort({riga: -1, col: -1}); + const lastnave = await NavePersistente.findOne({ idapp: params.idapp }).sort({ riga: -1, col: -1 }); let nextgiftchat = null; @@ -323,6 +332,160 @@ NavePersistenteSchema.statics.addRecordNavePersistenteByParams = async function return false; }; +NavePersistenteSchema.statics.generaFlotte = async function (idapp) { + const NavePersistente = this; + + // await Flotta.deleteMany({ idapp }); + + const arrnavi = await NavePersistente.find({ idapp, col: { $mod: [8, 1] } }).sort({ riga: 1, col: 1 }); + + let num = 0; + + for (const navepers of arrnavi) { + + const ris = await NavePersistente.aggiornaFlottaByNavePersistente(idapp, navepers); + if (ris) + num++; + } + + return { num } + +}; + +NavePersistenteSchema.statics.changeField = async function (idapp, flotta, fieldvalue) { + + let myval = {}; + + if ('date_close' in fieldvalue) { + myval['date_gift_chat_open'] = fieldvalue['date_close']; + } else { + myval = fieldvalue; + } + + const ris = await NavePersistente.updateMany({ + idapp, + riga: flotta.riga, + $and: [ + { col1don: { $gte: flotta.col_prima } }, + { col1don: { $lte: flotta.col_ultima } }, + ] + }, { $set: myval }); + + return ris; +}; + +NavePersistenteSchema.statics.aggiornaFlottaByNavePersistente = async function (idapp, naveinput) { + + const { Nave } = require('../models/nave'); + const { User } = require('./user'); + + let num = 0; + + try { + let nuovo = false; + // let primacol = false; + + indcolflottaprima = tools.getPrimaColFlotta(naveinput.col1don + 7); + + console.log(num, ' -> [', naveinput.riga, '.', naveinput.col, '] indcolflottaprima=', indcolflottaprima); + + let ini = Math.ceil(indcolflottaprima / 8); + let fine = ini + 7; + + const arrnavi = await NavePersistente.find({ + idapp, + riga: naveinput.riga, + $and: [{ col: { $gte: ini } }, { col: { $lte: fine } }] + }).sort({ riga: 1, col: 1 }); + + let primogiro = true; + + let myflotta = await Flotta.findOne({ idapp, riga: naveinput.riga, col_prima: indcolflottaprima }); + + if (!myflotta) { + myflotta = new Flotta({ + _id: new ObjectID(), + idapp, + }); + nuovo = true; + } + + for (const navepers of arrnavi) { + + if (primogiro) { + myflotta.DoniAttesaDiConferma = 0; + myflotta.DoniMancanti = 0; + myflotta.DoniConfermati = 0; + myflotta.DoniTotali = 0; + primogiro = false; + } + + if (nuovo) { + myflotta.riga = navepers.riga; + myflotta.col_prima = indcolflottaprima; + myflotta.col_ultima = indcolflottaprima + 63; + + myflotta.sognatore = ''; + myflotta.sognatore_nomecognome = ''; + myflotta.link_superchat = ''; + myflotta.msg_inviato = false; + } + + myflotta.date_start = navepers.date_start; + myflotta.date_close = navepers.date_gift_chat_open; + + let sognatore = await Nave.getSognatoreByRigaColMediatore(idapp, { riga: navepers.riga, col: navepers.col }); + if (myflotta.sognatore_nomecognome === '') { + myflotta.sognatore = sognatore.username; + if (!!sognatore.username) + myflotta.sognatore_nomecognome = await User.getNameSurnameByUsername(idapp, sognatore.username); + } + + if (nuovo) { + myflotta.email_paypal = ''; + myflotta.link_payment = ''; + myflotta.note_payment = ''; + if (!!sognatore) { + myflotta.email_paypal = sognatore.profile.email_paypal; + myflotta.link_payment = sognatore.profile.link_payment; + myflotta.note_payment = sognatore.profile.note_payment; + } + } + + if (!!sognatore) { + if (!myflotta.email_paypal) + myflotta.email_paypal = sognatore.profile.email_paypal; + if (!myflotta.link_payment) + myflotta.link_payment = sognatore.profile.link_payment; + if (!myflotta.note_payment) + myflotta.note_payment = sognatore.profile.note_payment; + } + + myflotta.provvisoria = navepers.provvisoria; + + if (!!navepers.DoniAttesaDiConferma && !isNaN(navepers.DoniAttesaDiConferma)) + myflotta.DoniAttesaDiConferma += navepers.DoniAttesaDiConferma; + if (!!navepers.DoniMancanti && !isNaN(navepers.DoniMancanti)) + myflotta.DoniMancanti += navepers.DoniMancanti; + if (!!navepers.DoniConfermati && !isNaN(navepers.DoniConfermati)) + myflotta.DoniConfermati += navepers.DoniConfermati; + if (!!navepers.DoniTotali && !isNaN(navepers.DoniTotali)) + myflotta.DoniTotali += navepers.DoniTotali; + + + } + + await myflotta.save(); + + return true; + + } catch (e) { + console.log(e.message); + return false; + } + +}; + const NavePersistente = mongoose.model('NavePersistente', NavePersistenteSchema); diff --git a/src/server/models/settings.js b/src/server/models/settings.js index 2c86378..51929c8 100755 --- a/src/server/models/settings.js +++ b/src/server/models/settings.js @@ -56,7 +56,7 @@ SettingsSchema.statics.getValDbSettings = function (idapp, key, def) { return Settings.findOne({ idapp, key }) .then((myrec) => { // console.log('getValDbSettings', myrec, 'idapp', idapp); - if (myrec) { + if (!!myrec) { if (myrec.type === tools.FieldType.date) return myrec.value_date; else if (myrec.type === tools.FieldType.number) @@ -112,6 +112,8 @@ SettingsSchema.statics.setKeyNum = async function (idapp, key, value) { myrec = await Settings.findOneAndUpdate({ idapp, key }, { $set: { value_num: value } }, { new: false }); } + return myrec + }; SettingsSchema.statics.setBool = async function (idapp, key, valbool) { @@ -130,6 +132,8 @@ SettingsSchema.statics.setBool = async function (idapp, key, valbool) { myrec = await Settings.findOneAndUpdate({ idapp, key }, { $set: { value_bool: valbool } }, { new: false }); } + return myrec + }; diff --git a/src/server/models/user.js b/src/server/models/user.js index 8c9450d..7fcc583 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -6,6 +6,7 @@ const _ = require('lodash'); const tools = require('../tools/general'); +const { Flotta } = require('../models/flotta'); const { Settings } = require('../models/settings'); const { ListaIngresso } = require('../models/listaingresso'); const { Graduatoria } = require('../models/graduatoria'); @@ -153,6 +154,15 @@ const UserSchema = new mongoose.Schema({ sospeso: { type: Boolean }, + non_voglio_imbarcarmi: { + type: Boolean + }, + navinonpresenti: { + type: Boolean + }, + subaccount: { + type: Boolean + }, profile: { img: { type: String @@ -175,6 +185,12 @@ const UserSchema = new mongoose.Schema({ email_paypal: { type: String }, + link_payment: { + type: String + }, + note_payment: { + type: String + }, paymenttypes: [], username_telegram: { type: String @@ -203,10 +219,13 @@ const UserSchema = new mongoose.Schema({ saw_zoom_presentation: { type: Boolean }, - special_req: { + qualified: { type: Boolean }, - vuole_ritessersi: { + qualified_2invitati: { + type: Boolean + }, + special_req: { type: Boolean }, sex: { @@ -345,7 +364,17 @@ UserSchema.statics.findByCredentials = function (idapp, username, password) { return User.findOne({ idapp, username: username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + $or: [ + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } }, + { + $and: [ + { deleted: { $exists: true, $eq: true } }, + { subaccount: { $exists: true, $eq: true } } + ] + } + ], + }).then((user) => { if (!user) { // Check if with email: @@ -354,7 +383,7 @@ UserSchema.statics.findByCredentials = function (idapp, username, password) { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] }) } else { - return !user.deleted ? user : null + return !user.deleted || (user.deleted && user.subaccount) ? user : null } }).then(user => { if (!user) @@ -409,6 +438,7 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) 'username': username, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], }, { + idapp: 1, lang: 1, index: 1, ind_order: 1, @@ -421,8 +451,12 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) verified_email: 1, 'profile.teleg_id': 1, 'profile.saw_zoom_presentation': 1, + 'profile.qualified': 1, + 'profile.qualified_2invitati': 1, 'profile.saw_and_accepted': 1, 'profile.email_paypal': 1, + 'profile.link_payment': 1, + 'profile.note_payment': 1, 'profile.my_dream': 1, 'profile.paymenttypes': 1, 'profile.cell': 1, @@ -467,8 +501,12 @@ UserSchema.statics.getDownlineByUsername = async function (idapp, username, incl verified_email: 1, 'profile.teleg_id': 1, 'profile.saw_zoom_presentation': 1, + 'profile.qualified': 1, + 'profile.qualified_2invitati': 1, 'profile.saw_and_accepted': 1, 'profile.email_paypal': 1, + 'profile.link_payment': 1, + 'profile.note_payment': 1, 'profile.my_dream': 1, 'profile.paymenttypes': 1, 'profile.cell': 1, @@ -558,7 +596,6 @@ UserSchema.statics.getQueryQualified = function () { } - UserSchema.statics.isUserQualified7 = async function (idapp, username) { const User = this; @@ -576,6 +613,72 @@ UserSchema.statics.isUserQualified7 = async function (idapp, username) { return !!myrec; }; +UserSchema.statics.isUserAlreadyQualified = async function (idapp, username) { + const User = this; + + if (username === undefined) + return false; + + const myquery = { + 'idapp': idapp, + 'username': username, + 'profile.qualified': { $exists: true, $eq: true }, + }; + + const myrec = await User.findOne(myquery); + + return !!myrec; +}; + +UserSchema.statics.isUserAlreadyQualified_2Invitati = async function (idapp, username) { + const User = this; + + if (username === undefined) + return false; + + const myquery = { + 'idapp': idapp, + 'username': username, + 'profile.qualified_2invitati': { $exists: true, $eq: true }, + }; + + const myrec = await User.findOne(myquery); + + return !!myrec; +}; + +UserSchema.statics.setUserQualified = async function (idapp, username) { + const User = this; + + if (username === undefined) + return false; + + const myquery = { + 'idapp': idapp, + 'username': username, + }; + + const myrec = await User.findOneAndUpdate(myquery, { $set: { 'profile.qualified': true } }, { new: false } ); + + return !!myrec; +}; + +UserSchema.statics.setUserQualified_2Invitati = async function (idapp, username) { + const User = this; + + if (username === undefined) + return false; + + const myquery = { + 'idapp': idapp, + 'username': username, + }; + + const myrec = await User.findOneAndUpdate(myquery, { $set: { 'profile.qualified_2invitati': true } }, { new: false } ); + + return !!myrec; +}; + UserSchema.statics.isUserQualified9 = async function (idapp, username) { const User = this; @@ -873,6 +976,22 @@ UserSchema.statics.SetTelegramCheckCode = async function (idapp, id, teleg_check }; +UserSchema.statics.NonVoglioImbarcarmi = async function (idapp, username) { + const User = this; + + const fields_to_update = { + non_voglio_imbarcarmi: true + }; + + 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) { const User = this; @@ -923,7 +1042,7 @@ UserSchema.statics.SetTelegramWasBlocked = async function (idapp, teleg_id) { 'profile.teleg_id': 0, }; - if (process.env.PROD === 1) { + if (process.env.PROD === "1") { const ris = await User.findOneAndUpdate({ idapp, @@ -1007,10 +1126,15 @@ UserSchema.statics.getRecByIndOrder = async function (idapp, ind_order) { ind_order: 1, old_order: 1, username: 1, + email: 1, name: 1, lang: 1, surname: 1, 'profile.teleg_id': 1, + 'profile.email_paypal': 1, + 'profile.link_payment': 1, + 'profile.note_payment': 1, + 'profile.paymenttypes': 1, }; const rec = await ListaIngresso.getarray(idapp, @@ -1161,6 +1285,7 @@ UserSchema.statics.getFieldsForSearch = function () { { field: 'email', type: tools.FieldType.string }, { field: 'profile.cell', type: tools.FieldType.string }, { field: 'profile.email_paypal', type: tools.FieldType.string }, + { field: 'profile.link_payment', type: tools.FieldType.string }, { field: 'profile.teleg_id', type: tools.FieldType.number }, { field: 'profile.username_telegram', type: tools.FieldType.string }, { field: 'aportador_solidario', type: tools.FieldType.string }] @@ -1235,6 +1360,8 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us for (let mypos of dashboard.arrposizioni) { mypos.rec = await Nave.getNaveByRigaCol(idapp, mypos.riga, mypos.col); mypos.nave_partenza = await NavePersistente.findByRigaColByDonatore(idapp, mypos.riga, mypos.col, 0); + if (!!mypos.nave_partenza) + mypos.flotta = await Flotta.getFlottaByNavePersistente(idapp, mypos.nave_partenza); } @@ -1924,6 +2051,111 @@ UserSchema.statics.changeInvitante = async function (idapp, username, invitante_ }; +UserSchema.statics.NessunaNavePresenteByUsername = async function (idapp, username) { + const User = this; + + const rec = await User.findOne({ idapp, username }, { username: 1, ind_order: 1 }); + if (!!rec) { + // Controlla se è qualificato! + const qualified = await User.isUserQualified7(idapp, rec.username); + if (qualified) { + + // Ha un'imbarco almeno? + const arrimbarchi = await ListaIngresso.findOne({ + idapp, username: rec.username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + }); + + const arrnavi = await Nave.findOne({ + idapp, ind_order: rec.old_order, + }); + + + if (!arrimbarchi && !arrnavi) { + // NEANCHE 1 ! + const recout = await User.findOneAndUpdate({ + idapp, + username + }, { $set: { navinonpresenti: true } }, { new: false }); + + return (!!recout); + } + } + } + + return false; + +}; + +UserSchema.statics.flagUtentiNaviNonPresenti = async function (idapp) { + const User = this; + + let num = 0; + + await User.updateMany({ idapp }, { $set: { navinonpresenti: false } }); + + arrusers = await User.find({ + 'idapp': idapp, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }, + { subaccount: { $exists: false } }, { subaccount: { $exists: true, $eq: false } }] + }); + + for (const rec of arrusers) { + + const nessunanave = await User.NessunaNavePresenteByUsername(idapp, rec.username); + if (nessunanave) + num++; + } + + return { num }; +}; + +UserSchema.statics.addNavePerUtentiNaviNonPresenti = async function (idapp) { + const User = this; + + let num = 0; + + arrusers = await User.find({ + 'idapp': idapp, + navinonpresenti: true + }); + + for (const user of arrusers) { + // Controlla se è qualificato! + mydata = tools.AddDate(user.date_reg, 7); + + const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, user.username, user.aportador_solidario, user.lang, true, true, mydata); + await tools.snooze(1000); + + num++; + } + + return { num }; +}; + +UserSchema.statics.convSubAccount = async function (idapp) { + const User = this; + + + // Solo i Cancellati ! + 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 } }] + }); + if (trovato) { + num++; + await User.findByIdAndUpdate(rec._id, { subaccount: true }, { new: false }); + } + } + + return { num }; +}; + UserSchema.statics.DbOp = async function (idapp, mydata) { const User = this; try { diff --git a/src/server/router/api/actions.js b/src/server/router/api/actions.js index 0a40792..7f0a430 100755 --- a/src/server/router/api/actions.js +++ b/src/server/router/api/actions.js @@ -13,7 +13,7 @@ const tools = require('../../tools/general'); const telegrambot = require('../../telegram/telegrambot'); module.exports = { - doOtherThingsAfterDeleted: async function (tablename, rec, notifBot) { + doOtherThingsAfterDeleted: async function (tablename, rec, notifBot, req) { try { let ris = null; if (tablename === 'users') { @@ -42,12 +42,13 @@ module.exports = { ris = await Graduatoria.deleteOne({ idListaIngresso: ObjectID(rec._id) }); if (!!ris) { - let msg = 'Eliminato Imbarco di ' + rec.name + ' ' + rec.surname + ' [Index = ' + rec.index + ']'; + let msg = 'Eliminato Imbarco di ' + rec.name + ' ' + rec.surname + ' (ind_order=' + rec.ind_order + ', num_tess=' + rec.num_tess + ') [Num = ' + rec.index + `] (da ${req.user.name} ${req.user.surname} )` ; await telegrambot.sendMsgTelegramToTheManagers(rec.idapp, msg); + tools.writeSostituzioniLog(msg); } // Elimina anche la Nave se è temporanea! - const arrnave = await Nave.find({ idapp: rec.idapp, ind_order: rec.ind_order }); + const arrnave = await Nave.find({ idapp: rec.idapp, ind_order: rec.ind_order, num_tess: rec.num_tess }); for (const mynave of arrnave) { if (!!mynave) { if (!await Nave.isDefinitiva(rec.idapp, mynave)) { diff --git a/src/server/router/dashboard_router.js b/src/server/router/dashboard_router.js index 352561a..70f61ef 100755 --- a/src/server/router/dashboard_router.js +++ b/src/server/router/dashboard_router.js @@ -10,7 +10,9 @@ const { authenticate } = require('../middleware/authenticate'); const { User } = require('../models/user'); const { Nave } = require('../models/nave'); +const { Flotta } = require('../models/flotta'); const { NavePersistente } = require('../models/navepersistente'); +const { MsgTemplate } = require('../models/msg_template'); const mongoose = require('mongoose'); const Subscription = mongoose.model('subscribers'); @@ -94,10 +96,11 @@ router.post('/msgnave', authenticate, async (req, res) => { if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_SINGOLO) { let mymsg = ''; if (!!mydata.username_mitt) { - mymsg = '[' + tools.getres__('MSG_SEND_FROM', res) + ' ' + mydata.username_mitt + ']:' + tools.ACAPO; + mymsg = '[' + tools.getres__('MSG_SEND_FROM', res) + ' ' + mydata.username_mitt + ' a ' + mydata.username + ']:' + tools.ACAPO; } mymsg += mydata.msgpar1; - ris = await telegrambot.sendMsgTelegram(idapp, mydata.username, mymsg, true, mydata.username_mitt); // Anche a STAFF + // ris = await telegrambot.sendMsgTelegram(idapp, mydata.username, mymsg, true, mydata.username_mitt); // Anche a STAFF + ris = await telegrambot.sendMsgTelegram(idapp, mydata.username, mymsg, true); // Anche a STAFF } else ris = await telegrambot.sendMsgTelegramToNave(idapp, mydata); @@ -113,6 +116,27 @@ router.post('/msgnave', authenticate, async (req, res) => { }); +router.post('/msgflotta', authenticate, async (req, res) => { + const idapp = req.body.idapp; + let mydata = req.body; + + try { + + let ris = null; + ris = await telegrambot.sendMsgTelegramToNave(idapp, mydata); + + if (ris) + res.send({ code: server_constants.RIS_CODE_OK, ris }); + else + res.send({ code: server_constants.RIS_CODE_ERR, ris: null }); + + + } catch (e) { + res.status(400).send(e); + } + +}); + router.post('/getnave', authenticate, async (req, res) => { const idapp = req.body.idapp; const riga = req.body.riga; @@ -144,6 +168,9 @@ router.post('/getnave', authenticate, async (req, res) => { router.post('/getnavi', authenticate, async (req, res) => { const idapp = req.body.idapp; + const { Flotta } = require('../models/flotta'); + + let arrnavi = await NavePersistente.findAllIdApp(idapp); // let arrnavi = await NavePersistente.find({idapp, date_gift_chat_open: { $gte: tools.IncDateNow(-1000 * 3600 * 24 * 7 ) } }).sort({ riga: 1, col: 1 }); @@ -163,6 +190,8 @@ router.post('/getnavi', authenticate, async (req, res) => { // } // nave._doc.rec.donatore.navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, riganave, colnave, 0); nave._doc.rec.donatore.navepersistente = await NavePersistente.findOne({ idapp, riga: riganave, col: colnave }); + if (!!nave._doc.rec.donatore.navepersistente) + nave._doc.rec.donatore.flotta = await Flotta.getFlottaByNavePersistente(idapp, nave._doc.rec.donatore.navepersistente); } const navi_partenza = await NavePersistente.findAllIdApp(idapp); @@ -176,6 +205,48 @@ router.post('/getnavi', authenticate, async (req, res) => { }); +router.post('/getmsg_templates', authenticate, async (req, res) => { + const idapp = req.body.idapp; + + let ris = await MsgTemplate.findAllIdApp(idapp); + + if (!!ris) + res.send({ code: server_constants.RIS_CODE_OK, ris }); + else + res.status(400).send(e); + + +}); + +router.post('/getflotte', authenticate, async (req, res) => { + const idapp = req.body.idapp; + + let arrflotte = await Flotta.findAllIdApp(idapp); + + if (!!arrflotte) + res.send({ code: server_constants.RIS_CODE_OK, arrflotte }); + else + res.status(400).send(e); + +}); + +router.post('/getflotta', authenticate, async (req, res) => { + const idapp = req.body.idapp; + const riga = req.body.riga; + const col_prima = req.body.col_prima; + const col_ultima = req.body.col_ultima; + + let ris = await Nave.getFlotta(idapp, riga, col_prima, col_ultima); + + ris.flotta._doc.log_attivita = tools.readFlottaLog(idapp, ris.flotta.riga, ris.flotta.col_prima); + + if (!!ris) + res.send({ code: server_constants.RIS_CODE_OK, flotta: ris.flotta, arrdonatori: ris.arrdonatori }); + else + res.status(400).send(e); + +}); + router.post('/getdoninavi', authenticate, async (req, res) => { const idapp = req.body.idapp; const ricalcola = req.body.ricalcola; @@ -185,7 +256,7 @@ router.post('/getdoninavi', authenticate, async (req, res) => { if (showall) arrnavi = await NavePersistente.findAllIdApp(idapp); else - arrnavi = await NavePersistente.find({idapp, date_gift_chat_open: { $gte: tools.IncDateNow(-1000 * 3600 * 24 * 7 ) } }).sort({ riga: 1, col: 1 }); + arrnavi = await NavePersistente.find({idapp, date_gift_chat_open: { $gte: tools.IncDateNow(-1000 * 3600 * 24 * 10 ) } }).sort({ riga: 1, col: 1 }); let test = false; @@ -201,6 +272,7 @@ router.post('/getdoninavi', authenticate, async (req, res) => { } } else { // arrnavi = await NavePersistente.findAllIdApp(idapp); + let index = 1; for (nave of arrnavi) { if (nave.provvisoria || nave.DoniTotali !== nave.DoniConfermati) { nave._doc.rec = await Nave.getNaveByRigaCol(idapp, nave.riga1don, nave.col1don); @@ -214,8 +286,13 @@ router.post('/getdoninavi', authenticate, async (req, res) => { nave._doc.rec = {}; nave._doc.rec.donatore = {}; nave._doc.rec.donatore.navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, rigapos, colpos, tools.Placca.SONOFUOCO); + index++; + } + if (index > 8 * 6 ) { + break; } } + } ris = { arrnavi }; diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 36fb6af..8bc5a4f 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -30,6 +30,7 @@ const _ = require('lodash'); const { User } = require('../models/user'); const { Nave } = require('../models/nave'); +const { Flotta } = require('../models/flotta'); const { NavePersistente } = require('../models/navepersistente'); // const { ExtraList } = require('../models/extralist'); const { Booking } = require('../models/booking'); @@ -49,6 +50,7 @@ const { MailingList } = require('../models/mailinglist'); const { Settings } = require('../models/settings'); const { SendMsg } = require('../models/sendmsg'); const { Permission } = require('../models/permission'); +const { MsgTemplate } = require('../models/msg_template'); const tools = require('../tools/general'); @@ -220,6 +222,10 @@ function getTableByTableName(tablename) { mytable = MailingList; else if (tablename === 'navi') mytable = Nave; + else if (tablename === 'flotte') + mytable = Flotta; + else if (tablename === 'msg_templates') + mytable = MsgTemplate; else if (tablename === 'navepersistente') mytable = NavePersistente; else if (tablename === 'listaingressos') @@ -285,6 +291,9 @@ router.post('/gettable', authenticate, (req, res) => { async function checkIfSbloccatiRequisiti(idapp, allData, id) { + if (!allData.myuser) + return false; + if (await Nave.checkIfNaveExist(idapp, allData.myuser.username)) { // Se già sei dentro la Nave, allora sei OK return true; @@ -298,22 +307,27 @@ async function checkIfSbloccatiRequisiti(idapp, allData, id) { if (userlista.length === 0) { // Se non sono ancora dentro alla lista, allora controllo - if (!allData.precDataUser.is7req && is7req) { - // ORA HAI I 7 REQUISITI ! - // const msgtext = telegrambot.getCiao(idapp, allData.myuser.username, allData.myuser.lang) + tools.gettranslate('HAI_I_7_REQUISITI', allData.myuser.lang); - // telegrambot.sendMsgTelegram(idapp, allData.myuser.username, msgtext, true); // Anche a STAFF + if (!!allData.precDataUser) { + if ((!allData.precDataUser.is7req && is7req) && !await User.isUserAlreadyQualified(idapp, allData.myuser.username)) { + await User.setUserQualified(idapp, allData.myuser.username); + // ORA HAI I 7 REQUISITI ! + // const msgtext = telegrambot.getCiao(idapp, allData.myuser.username, allData.myuser.lang) + tools.gettranslate('HAI_I_7_REQUISITI', allData.myuser.lang); + // telegrambot.sendMsgTelegram(idapp, allData.myuser.username, msgtext, true); // Anche a STAFF - if (tools.isAbilitaNave(idapp)) { // Aggiungilo alla ListaIngresso risingr = await ListaIngresso.addUserInListaIngresso(idapp, allData.myuser.username, allData.myuser.aportador_iniziale, allData.myuser.lang, true, false); } } } - if (!allData.precDataUser.is9req && is9req) { - // 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 + if (!!allData.precDataUser) { + 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: @@ -391,7 +405,10 @@ router.patch('/chval', authenticate, async (req, res) => { if (camporequisiti) { allData = {}; allData.myuser = await User.getUserById(idapp, id); - allData.precDataUser = await getInfoUser(idapp, allData.myuser.username); + if (!!allData.myuser) + allData.precDataUser = await getInfoUser(idapp, allData.myuser.username); + else + allData.precDataUser = null; // allData.useraportador = await ListaIngresso.getUserByInvitante_Username(idapp, allData.myuser.aportador_solidario); // allData.precDataAportador = await getInfoUser(idapp, allData.myuser.aportador_solidario); } @@ -404,9 +421,42 @@ router.patch('/chval', authenticate, async (req, res) => { if (!rec) { return res.status(404).send(); } else { + let addmsg = ''; + + if (mydata.table === 'navi' && ('made_gift' in fieldsvalue)) { + if (fieldsvalue['made_gift'] && !rec.received_gift) { + if (mydata.tipomsg) { + + let mypos = { + idapp, + riga: rec.riga, + col: rec.col, + numup: 3 + }; + tools.getRigaColByPosUp(mypos); + + const myuser = await User.findByIndOrder(idapp, rec.ind_order); + if (!!myuser) { + const mydatamsg = { + tipomsg: tools.TipoMsg.SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE, + navemediatore: { riga: mypos.riga, col: mypos.col }, + }; + const rismsg = await telegrambot.getMsgByTipoMsg(mydatamsg, myuser.lang, myuser, false); + addmsg = rismsg.body; + } + } + + await mytable.findByIdAndUpdate(id, { $set: { received_gift: true } }); + } + } + + // SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE + if (mydata.notifBot) { // Send Notification to the BOT await telegrambot.sendMsgTelegram(idapp, mydata.notifBot.un, mydata.notifBot.txt); + if (!!addmsg) + await telegrambot.sendMsgTelegram(idapp, mydata.notifBot.un, addmsg); addtext = '[Msg Inviato a ' + mydata.notifBot.un + ']:' + '\n' + mydata.notifBot.txt; telegrambot.sendMsgTelegramToTheManagers(idapp, addtext, true); } @@ -417,6 +467,12 @@ router.patch('/chval', authenticate, async (req, res) => { } } + if (mydata.table === 'flotte') { + if (('date_start' in fieldsvalue) || ('date_close' in fieldsvalue)) { + await NavePersistente.changeField(idapp, rec, fieldsvalue); + } + } + if (mydata.table === 'users') { if ('aportador_solidario' in fieldsvalue) { ind_order_ingr = mydata.ind_order_ingr; @@ -446,7 +502,13 @@ router.patch('/chval', authenticate, async (req, res) => { return false; } } else if ('deleted' in fieldsvalue) { - await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${rec.name} ${rec.surname} (${rec.username}) è stato cancellato (nascosto) da ${req.user.name} ${req.user.surname}`); + let msg = ''; + if (fieldsvalue.deleted) + msg = 'cancellato (nascosto)'; + else + msg = 'Ripristinato'; + + await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${rec.name} ${rec.surname} (${rec.username}) è stato ${msg} da ${req.user.name} ${req.user.surname}`); } } @@ -475,6 +537,13 @@ router.patch('/chval', authenticate, async (req, res) => { // return false; } } + if ('note' in fieldsvalue) { + // Aggiornalo anche in Graduatorie + await Graduatoria.findOneAndUpdate({ + idapp, + idListaIngresso: id + }, { $set: { note: fieldsvalue.note } }, { new: false }) + } } if (tools.ModificheConsentite(mydata.table, fieldsvalue)) { @@ -496,7 +565,10 @@ router.patch('/chval', authenticate, async (req, res) => { } else if (mydata.table === 'navi') { if ('made_gift' in fieldsvalue) { if (!!fieldsvalue.riga) { - await Nave.ricalcolaNave(idapp, null, fieldsvalue.riga, fieldsvalue.col, true, index) + const navepers = await Nave.ricalcolaNave(idapp, null, fieldsvalue.riga, fieldsvalue.col, true, index); + + if (!!navepers) + await NavePersistente.aggiornaFlottaByNavePersistente(idapp, navepers); } } } @@ -539,8 +611,29 @@ router.patch('/askfunz', authenticate, async (req, res) => { if (!!userfree) return res.send({ code: server_constants.RIS_CODE_OK, out: userfree }); + /*} else if (mydata.myfunc === shared_consts.CallFunz.GET_VALBYTABLE) { + const mytable = getTableByTableName(mydata.table); + const coltoshow = { + [mydata.coltoshow]: 1 + }; + + const ris = await mytable.findOne({ _id: id }, coltoshow); + + return ris; + } else if (mydata.myfunc === shared_consts.CallFunz.SET_VALBYTABLE) { + const mytable = getTableByTableName(mydata.table); + const value = mydata.value; + const coltoset = { + [mydata.coltoshow]: value + }; + + const ris = await mytable.findOneAndUpdate({ _id: id }, { $set: coltoset }, { new: false }); + if (!!ris) + return res.send({ code: server_constants.RIS_CODE_OK });*/ } + return res.send({ code: server_constants.RIS_CODE_ERR }); + }); router.patch('/callfunz', authenticate, async (req, res) => { @@ -586,10 +679,11 @@ router.patch('/callfunz', authenticate, async (req, res) => { if (!!myusernuovo) { if (!mydata.data.AddImbarco && !!mianavedasost && mianavedasost.ind_order > 0) { - // Controlla prima se è in una Nave Temporanea, allora lo elimina dalla PRIMA Nave Temporanea + // Controlla prima se è in una Nave Temporanea, allora lo elimina dall'ultima Nave Temporanea miaarrnavi = await Nave.getArrPosizioniByUsername(idapp, username); if (miaarrnavi) { + miaarrnavi = miaarrnavi.reverse(); // parto dall'ultima for (const mianave of miaarrnavi) { let persistente = await NavePersistente.findByRigaColByDonatore(idapp, mianave.riga, mianave.col, 0); if (persistente.provvisoria) { @@ -629,7 +723,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { const risdel = await ListaIngresso.deleteOne({ _id: olduseringresso.id }); if (!!risdel) { - await actions.doOtherThingsAfterDeleted('listaingressos', myrecuser, false) + await actions.doOtherThingsAfterDeleted('listaingressos', myrecuser, false, req) } } } @@ -651,6 +745,28 @@ router.patch('/callfunz', authenticate, async (req, res) => { await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuservecchio.name} ${myuservecchio.surname} (${myuservecchio.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); } } + + if (mydata.data.notifBot) { + + const mydatamsg = { + tipomsg: tools.TipoMsg.SEND_MSG_A_UTENTE_SOSTITUITO, + navemediatore: { riga: navepersistente.riga, col: navepersistente.col }, + }; + + mydatamsg.flotta = await Flotta.getFlottaByNavePersistente(idapp, navepersistente); + + const rismsg = await telegrambot.getMsgByTipoMsg(mydatamsg, myuservecchio.lang, myuservecchio, false); + + if (!!rismsg) { + let messaggio = rismsg.body; + mytitle = rismsg.title; + if (!!messaggio) { + await telegrambot.sendMsgTelegram(idapp, myusernuovo.username, messaggio); + } + } + } + + } @@ -681,7 +797,6 @@ router.patch('/callfunz', authenticate, async (req, res) => { }, { $set: { ind_order: -1 } }, { new: false }); - // Aggiorna la Nave con il Nuovo fieldsvalue = { ind_order @@ -695,31 +810,50 @@ router.patch('/callfunz', authenticate, async (req, res) => { if (!rec) { return res.status(404).send(); } else { - // Send Notification to the BOT - let messaggio = tools.get__('SPOSTATO', req.user.lang); - if (!!navepersistente.date_start) { - messaggio += tools.ACAPO + tools.get__('DATA_PART_NAVE', req.user.lang) + tools.getstrDateLong(navepersistente.date_gift_chat_open) + tools.ACAPO; - } - if (!!navepersistente.link_chat) { - messaggio += tools.ACAPO + '👉🏻👉🏻 ' + tools.get__('ENTRA_GIFT_CHAT', req.user.lang) + ' ' + tools.ACAPO; - } + const mydatamsg = { + tipomsg: tools.TipoMsg.SEND_MSG_EFFETTUA_IL_DONO, + navemediatore: { riga: navepersistente.riga, col: navepersistente.col }, + }; - const myplacca = await Nave.getNavePos(idapp, navepersistente.riga, navepersistente.col); - messaggio += tools.ACAPO + myplacca; + mydatamsg.flotta = await Flotta.getFlottaByNavePersistente(idapp, navepersistente); - const mymsg = mydata.notifBot.txt + ' ' + myusernuovo.name + ' ' + myusernuovo.surname + ' [da ' + dachi + ']' + tools.ACAPO + 'Inviato messaggio: ' + messaggio; + const rismsg = await telegrambot.getMsgByTipoMsg(mydatamsg, myusernuovo.lang, myusernuovo, false); - if (mydata.data.notifBot && !!navepersistente.link_chat) { + let messaggio = rismsg.body; + mytitle = rismsg.title; + + // const myplacca = await Nave.getNavePos(idapp, navepersistente.riga, navepersistente.col); + // messaggio += tools.ACAPO + myplacca; + + let testostaff = ''; + if (mydata.notifBot) + testostaff = mydata.notifBot.txt; + + const mymsg = testostaff + ' ' + myusernuovo.name + ' ' + myusernuovo.surname + ' [da ' + dachi + ']' + tools.ACAPO + 'Inviato messaggio: ' + messaggio; + + if (mydata.data.notifBot) { await telegrambot.sendMsgTelegram(idapp, myusernuovo.username, messaggio); - await telegrambot.sendMsgTelegramToTheManagers(idapp, mymsg); - await telegrambot.sendMsgTelegram(idapp, req.user.username, mydata.notifBot.txt); - await telegrambot.sendMsgTelegram(idapp, req.user.username, myplacca); + if (mydata.data.inviaemail) { + await sendemail.sendEmail_ByText(myusernuovo.lang, myusernuovo.email, myusernuovo, idapp, { + emailbody: messaggio, + emailtitle: mytitle + }); + } + + await telegrambot.sendMsgTelegramToTheManagers(idapp, testostaff); + await telegrambot.sendMsgTelegram(idapp, req.user.username, testostaff); + // await telegrambot.sendMsgTelegram(idapp, req.user.username, myplacca); + } else { + tools.writeManagersLog(mymsg); } - tools.writeManagersLog(mymsg); + const msgsost = '[NAVE ' + navepersistente.riga + '.' + navepersistente.col + '] Sostituito ' + myuservecchio.username + ' (' + myuservecchio.name + ' ' + myuservecchio.surname + ') ' + ' con -> ' + myusernuovo.username + ' (' + myusernuovo.name + ' ' + myusernuovo.surname + ') ' + ' [da ' + dachi + ']'; + tools.writeSostituzioniLog(msgsost); + tools.writeFlottaLog(idapp, msgsost, mydatamsg.flotta.riga, mydatamsg.flotta.col_prima); + await telegrambot.sendMsgTelegramToTheManagers(idapp, msgsost); // const nomecognomeprima = myuser.name + ' ' + myuser.surname + '(' + myuser.username + ')'; // const nomecognomenuovo = await User.getNameSurnameByUsername(idapp,); @@ -728,7 +862,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { } }).catch((e) => { - tools.mylogserr('Error patch USER: ', e); + tools.mylogserr('Error patch USER: ', e.message); res.status(400).send(); }) } @@ -759,15 +893,28 @@ router.patch('/callfunz', authenticate, async (req, res) => { const myrec = await ListaIngresso.getIngrEUserByFilter(idapp, { idapp, _id: ObjectID(mydata.data.id) }); if (!!myrec) { - const risdel = await ListaIngresso.deleteOne({ _id: mydata.data.id }); + const myingr = await ListaIngresso.find({ _id: mydata.data.id }); + // Controlla se ci sono 2 navi + const arrnavi = await Nave.find({ idapp, ind_order: mydata.ind_order }); - if (!!risdel) { - return await actions.doOtherThingsAfterDeleted('listaingressos', myrec, false) + let risdel = false; + if (arrnavi.length === 1) { + // Solo 1 nave da cancellare, quindi cancello anche l'ingresso + risdel = await ListaIngresso.deleteOne({ _id: mydata.data.id }); + } else { + // non cancellare la listaingresso (perchè con lo stesso ind_order ho piu navi ! + risdel = true + } + + if (risdel) { + return await actions.doOtherThingsAfterDeleted('listaingressos', myrec, false, req) .then((ris) => { - if (!!ris) - // tools.mylog('DELETED Others things ...'); + if (!!ris) { + + // tools.mylog('DELETED Others things ...'); return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); + } }); } } @@ -871,7 +1018,7 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { if (cancellato) { // Do extra things after deleted - return actions.doOtherThingsAfterDeleted(tablename, myrec, notifBot); + return actions.doOtherThingsAfterDeleted(tablename, myrec, notifBot, req); } res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 7a38db5..a0dae7a 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -3,6 +3,7 @@ const router = express.Router(); const { User } = require('../models/user'); const { Nave } = require('../models/nave'); +const { Flotta } = require('../models/flotta'); const { NavePersistente } = require('../models/navepersistente'); const { ListaIngresso } = require('../models/listaingresso'); const { Graduatoria } = require('../models/graduatoria'); @@ -135,7 +136,10 @@ router.post('/', async (req, res) => { user.profile.saw_and_accepted = recorig.profile.saw_and_accepted; user.profile.my_dream = recorig.profile.my_dream; user.profile.email_paypal = recorig.profile.email_paypal; + user.profile.link_payment = recorig.profile.link_payment; + user.profile.note_payment = recorig.profile.note_payment; user.profile.paymenttypes = recorig.profile.paymenttypes; + user.profile.qualified = recorig.profile.qualified; let msgseconda = '!!! REGISTRATA '; if (numero === '2') msgseconda += 'SECONDA'; @@ -312,6 +316,13 @@ router.post('/login', (req, res) => { tools.mylogshow(msg); // telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg); res.status(404).send({ code: server_constants.RIS_CODE_LOGIN_ERR }); + } else if (!!user.subaccount && user.subaccount) { + await tools.snooze(1000); + // const msg = "Tentativo di Login ERRATO [" + body.username + ' , ' + body.password + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + ']'; + // tools.mylogshow(msg); + // telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg); + res.status(404).send({ code: server_constants.RIS_CODE_LOGIN_ERR_SUBACCOUNT }); + return null; } return user }) @@ -364,7 +375,7 @@ router.post('/login', (req, res) => { } }) .catch((e) => { - tools.mylog("ERRORE IN LOGIN: " + e); + tools.mylog("ERRORE IN LOGIN: " + e.message); if (!resalreadysent) res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC }); }); @@ -411,16 +422,7 @@ async function eseguiDbOp(idapp, mydata, locale) { try { if (mydata.dbop === 'rigeneraTutto') { - - mydata.dbop = 'delNaviProvvisorie'; - await eseguiDbOp(idapp, mydata, locale); - - mydata.dbop = 'GeneraGraduatoria'; - await eseguiDbOp(idapp, mydata, locale); - - mydata.dbop = 'creaNavi'; - ris = await eseguiDbOp(idapp, mydata, locale); - + await ListaIngresso.Esegui_CronTab(idapp, mydata); } else if (mydata.dbop === 'creaNavi') { const num = await Nave.generaNave(idapp, mydata, false); ris = { num }; @@ -439,36 +441,8 @@ async function eseguiDbOp(idapp, mydata, locale) { // ris = { num }; } else if (mydata.dbop === 'delNaviProvvisorie') { - let num = 0; + ris = await Nave.delNaviProvvisorie(idapp); - const arrnavi = await Nave.find({ idapp }); - - for (const nave of arrnavi) { - let persistente = await NavePersistente.findByRigaColByDonatore(idapp, nave.riga, nave.col, 0); - if (!!persistente) { - if (persistente.provvisoria) { - let ris = await Nave.deleteOne({ _id: nave._id }); - if (!!ris) { - num++; - } - } - } - } - - // Pulisci gli added se era stato cancellato dalla nave - await Nave.pulisciNonPresenzeInNave(idapp); - - const data = await Nave.getLastRigaCol(idapp); - await Nave.setRiga(idapp, data.riga); - await Nave.setCol(idapp, data.col + 1); - - const maxcol = tools.getmaxcol(data.riga); - if (data.col === maxcol) { - await Nave.setRiga(idapp, data.riga + 1); - await Nave.setCol(idapp, 1); - } - - ris = { num }; } else if (mydata.dbop === 'visuListaNave') { mystr = await Nave.showListaOrd(idapp); ris = { mystr }; @@ -494,6 +468,14 @@ async function eseguiDbOp(idapp, mydata, locale) { ris = { mystr }; } else if (mydata.dbop === 'visuNaviUtentiEliminati') { ris = await Nave.visuNaviUtentiEliminati(idapp); + } else if (mydata.dbop === 'convSubAccount') { + ris = await User.convSubAccount(idapp); + } else if (mydata.dbop === 'flagUtentiNaviNonPresenti') { + ris = await User.flagUtentiNaviNonPresenti(idapp); + } else if (mydata.dbop === 'generaFlotte') { + ris = await NavePersistente.generaFlotte(idapp); + } else if (mydata.dbop === 'addNavePerUtentiNaviNonPresenti') { + ris = await User.addNavePerUtentiNaviNonPresenti(idapp); } else if (mydata.dbop === 'creaTessituraeConv') { ris = await ListaIngresso.creaTessituraeConv(idapp); ris = { mystr }; @@ -506,6 +488,7 @@ async function eseguiDbOp(idapp, mydata, locale) { } else if (mydata.dbop === 'convNaviTessinListaIngressoRec') { let num = 0; + const arrnavitess = await Nave.find({ idapp, num_tess: { $gte: 3 } }); for (const recnave of arrnavitess) { @@ -699,7 +682,7 @@ async function eseguiDbOp(idapp, mydata, locale) { } else if (mydata.dbop === 'visuPlacca') { mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' + - 'ECCO LE NUOVE NAVI DEFINITIVE CHE APRONO DOMANI LA GIFT CHAT !!! DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) + '\n' + + 'NAVI CHE SALPANO DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) + '\n' + 'AUGURI ALLA NUOVA SOGNATRICE !!!\n' + '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨'; diff --git a/src/server/sendemail.js b/src/server/sendemail.js index 8c4d86c..209d64b 100755 --- a/src/server/sendemail.js +++ b/src/server/sendemail.js @@ -306,6 +306,33 @@ module.exports = { // Send Email also to the Admin // this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf); }, + + sendEmail_ByText: async function (lang, emailto, user, idapp, rec) { + + tools.mylog('sendEmail_ByText'); + + mylocalsconf = { + idapp, + dataemail: await this.getdataemail(idapp), + locale: lang, + nomeapp: tools.getNomeAppByIdApp(idapp), + name: user.name, + surname: user.surname, + usernameorig: user.name + ' ' + user.surname, + emailto: emailto, + }; + + mylocalsconf.dataemail.emailbody = rec.emailbody; + mylocalsconf.dataemail.emailtitle = rec.emailtitle; + + const replyto = tools.getreplyToEmailByIdApp(idapp); + + return this.sendEmail_base('standard', emailto, mylocalsconf, replyto); + + // Send Email also to the Admin + // this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf); + }, + Add_to_MailingList_AndSendEmailNotify: async function (lang, user, idapp, sendnews) { // console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp)); diff --git a/src/server/server.js b/src/server/server.js index 32c235c..10b81d0 100755 --- a/src/server/server.js +++ b/src/server/server.js @@ -62,6 +62,9 @@ const users_router = require('./router/users_router'); const site_router = require('./router/site_router'); const admin_router = require('./router/admin_router'); + +const { ListaIngresso } = require('./models/listaingresso'); + const { MyEvent } = require('./models/myevent'); const telegrambot = require('./telegram/telegrambot'); @@ -256,10 +259,12 @@ function mycron() { async function mycron_30min() { for (const app of MYAPPS) { - const enablecrontab = await Settings.getValDbSettings(app.idapp, tools.ENABLE_CRONTAB, false); + let enablecrontab = false; + + enablecrontab = await Settings.getValDbSettings(app.idapp, tools.ENABLE_CRONTAB, false); if (enablecrontab) { - ListaIngresso.Esegui_CronTab(app.idapp); + ListaIngresso.Esegui_CronTab(app.idapp, {}); } } } @@ -293,12 +298,18 @@ cron.schedule('*/2 * * * *', () => { mycron(); }); + // Cron every X minutes -cron.schedule('*/30 * * * *', async () => { +cron.schedule('*/60 * * * *', async () => { mycron_30min(); }); +// mycron_30min(); + +// tools.writelogfile('test', 'prova.txt'); + + async function resetProcessingJob() { arrrec = await Newstosent.find({}); diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index faedaba..c196e75 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -12,10 +12,16 @@ const { CalZoom } = require('../models/calzoom'); const { Nave } = require('../models/nave'); const shared_consts = require('../tools/shared_nodejs'); +const { ListaIngresso } = require('../models/listaingresso'); +const { MsgTemplate } = require('../models/msg_template'); + const emoji = require('node-emoji'); + const i18n = require("i18n"); +let url = process.env.URL || 'https://'; + const Benvenuto = emoji.get('heartbeat') + emoji.get('heartbeat') + emoji.get('heartbeat') + ' Benvenuto!'; const emo = { @@ -151,8 +157,10 @@ const Menu = { MSG_TO_NAVE: emoji.get('incoming_envelope') + 'Msg_to_Navi', MSG_NO_7_REQ: emoji.get('incoming_envelope') + 'No 7 Req.', MSG_NO_9_REQ: emoji.get('incoming_envelope') + 'No 9 Req', + NESSUN_IMBARCO_7REQ: emoji.get('incoming_envelope') + 'No Imbarco (7 Req)', MSG_SI_INVITATI_NO_7REQ_INVITATI: emoji.get('incoming_envelope') + 'Inv e NO 7 Req', MSGSTAFF: emoji.get('incoming_envelope') + ' Invia a STAFF', + MSGPAOLO: emoji.get('incoming_envelope') + ' Invia a PAOLO', MSGATUTTI: emoji.get('incoming_envelope') + ' Invia a TUTTI', it: { ACCEDI: emo.PERSON + ' Accedi', @@ -231,8 +239,15 @@ const Menu = { const CONTA_SOLO = 'contasolo'; const RICEVI_EMAIL = 'riceviemail'; +const NOME_COGNOME = 'nomecognome'; +const CHEDI_SE_IMBARCARTI = 'chiedi_se_imbarcarti'; -const SendMsgCmd = [CONTA_SOLO, RICEVI_EMAIL]; +const InlineCmd = { + VOGLIO_IMBARCARMI: 'voglio_imbarcarmi', + NON_VOGLIO_IMBARCARMI: 'non_voglio_imbarcarmi' +}; + +const SendMsgCmd = [CONTA_SOLO, RICEVI_EMAIL, NOME_COGNOME, CHEDI_SE_IMBARCARTI]; const MenuNoLogin = { @@ -276,11 +291,11 @@ const MenuYesNo = { }; const MenuAdmin = { - it: { menu: [[Menu.MSGSTAFF, Menu.MSGATUTTI, Menu.it.INDIETRO], [Menu.MSG_NO_7_REQ, Menu.MSG_NO_9_REQ], [Menu.MSG_TO_NAVE, Menu.MSG_SI_INVITATI_NO_7REQ_INVITATI]] }, + it: { menu: [[Menu.MSGSTAFF, Menu.MSGATUTTI, Menu.it.INDIETRO], [Menu.MSG_NO_7_REQ, Menu.MSG_NO_9_REQ, Menu.NESSUN_IMBARCO_7REQ], [Menu.MSGPAOLO, Menu.MSG_TO_NAVE, Menu.MSG_SI_INVITATI_NO_7REQ_INVITATI]] }, }; const MenuSend = { - it: { menu: [[CONTA_SOLO, RICEVI_EMAIL], [Menu.it.INDIETRO]] }, + it: { menu: [[CONTA_SOLO, RICEVI_EMAIL, NOME_COGNOME], [CHEDI_SE_IMBARCARTI, Menu.it.INDIETRO]] }, }; const MenuChat = { @@ -298,6 +313,7 @@ const Sex = { }; const Status = { + EXIT: -5, NONE: 0, VERIFIED: 1, WAITFOR_USERNAME_BO: 102, @@ -313,6 +329,8 @@ const Destin = { SI_INVITATI_NO_7REQ_INVITATI: 5, A_UTENTE: 6, MSG_TO_NAVE: 7, + NESSUN_IMBARCO_7REQ: 8, + PAOLO: 9, }; const StatusMSGALL = { @@ -446,7 +464,7 @@ const TelegramBot = require('node-telegram-bot-api'); module.exports = { - ADMIN_IDTELEGRAM_SERVER: '12429864', + ADMIN_IDTELEGRAM_SERVER: '12429864', //Paolo ADMIN_USER_SERVER: 'paoloar77', ADMIN_USER_NAME_SERVER: 'Paolo', @@ -509,105 +527,239 @@ module.exports = { }, - getMsgByTipoMsg: function (mydata, lang, user, sonosognatore) { + getMsgByTipoMsg: async function (mydata, lang, user, sonosognatore) { if (!!mydata.msgextra) { - return mydata.msgextra; + return { body: mydata.msgextra, title: ''} ; } + let title = ''; + let msg = ''; + if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { if (sonosognatore) - return printf(tools.gettranslate('SEND_LINK_CHAT_SOGNATORE', lang), user.name, mydata.navemediatore.riga + '.' + mydata.navemediatore.col, mydata.msgpar1); + msg = printf(tools.gettranslate('SEND_LINK_CHAT_SOGNATORE', lang), user.name, mydata.navemediatore.riga + '.' + mydata.navemediatore.col, mydata.msgpar1); else - return printf(tools.gettranslate('SEND_LINK_CHAT_DONATORI', lang), user.name, mydata.navemediatore.riga + '.' + mydata.navemediatore.col, mydata.msgpar1); + msg = printf(tools.gettranslate('SEND_LINK_CHAT_DONATORI', lang), user.name, mydata.navemediatore.riga + '.' + mydata.navemediatore.col, mydata.msgpar1); } else if (mydata.tipomsg === tools.TipoMsg.SEND_MSG || mydata.tipomsg === tools.TipoMsg.SEND_MSG_SINGOLO) { - let mymsg = ''; if (!!mydata.username_mitt) { - mymsg = '[' + tools.gettranslate('MSG_SEND_FROM', lang) + ' ' + mydata.username_mitt + ']:' + tools.ACAPO; + msg = '[' + tools.gettranslate('MSG_SEND_FROM', lang) + ' ' + mydata.username_mitt + ']:' + tools.ACAPO; } - mymsg += mydata.msgpar1; - return mymsg; + msg += mydata.msgpar1; + } else if (mydata.tipomsg >= 1000) { + const ris = await MsgTemplate.getMsgByLang(user.idapp, mydata.tipomsg, lang); + msg = ris.body; + title = ris.title; } + if (!!user) { + msg = msg.replace('{username}', user.username); + msg = msg.replace('{name}', user.name); + msg = msg.replace('{surname}', user.surname); + if (!!user.profile.link_payment) + msg = msg.replace('{link_paypalme}', user.profile.link_payment); + if (!!user.profile.email_paypal) + msg = msg.replace('{email_paypal}', user.profile.email_paypal); + if (!!user.profile.note_payment) + msg = msg.replace('{note_payment}', user.profile.note_payment); + } + + if (!!mydata.flotta) { + // SOSTITUISCI LE PAROLE CHIAVI + if (!!mydata.flotta.date_start) + msg = msg.replace('{date_start}', tools.getstrDateLong(new Date(mydata.flotta.date_start), user.lang)); + if (!!mydata.flotta.date_close) + msg = msg.replace('{date_close}', tools.getstrDateLong(new Date(mydata.flotta.date_close), user.lang)); + if (!!mydata.flotta.link_superchat) + msg = msg.replace('{link_superchat}', mydata.flotta.link_superchat); + if (!!mydata.flotta.tutor1) + msg = msg.replace('{tutor1}', mydata.flotta.tutor1); + if (!!mydata.flotta.tutor2) + msg = msg.replace('{tutor2}', mydata.flotta.tutor2); + if (!!mydata.flotta.tutor3) + msg = msg.replace('{tutor3}', mydata.flotta.tutor3); + if (!!mydata.flotta.tutorslo) + msg = msg.replace('{tutorslo}', mydata.flotta.tutorslo); + if (!!mydata.flotta.sognatore_nomecognome) + msg = msg.replace('{sognatore}', mydata.flotta.sognatore_nomecognome); + } + + return { body: msg, title }; }, sendMsgTelegramToNave: async function (idapp, mydata) { + let nummsgtosend = 0; let nummsgsent = 0; let strout = ''; + let flotta = mydata.flotta; + + const sendemail = require('../sendemail'); try { - const arrnavi = await Nave.getusersByNave(idapp, mydata.navemediatore); + let arrnavi = null; + if (flotta) { + arrnavi = await Nave.getusersByFlotta(idapp, flotta.riga, flotta.col_prima, flotta.col_ultima); + + if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_A_SOGNATORE) { + arrnavi = await User.find({ idapp, username: flotta.sognatore }); + } + } else { + arrnavi = await Nave.getusersByNave(idapp, mydata.navemediatore); + } + // console.log('usersmanagers', usersmanagers); + let mymsg = ""; + let mymsgprimo = ""; + + tipomsgorig = mydata.tipomsg; + if (arrnavi) { - tools.writeManagersLog('sendMsgTelegramToNave', mydata.navemediatore.riga + '.' + mydata.navemediatore.col); + if (!flotta) + tools.writeManagersLog('sendMsgTelegramToNave', mydata.navemediatore.riga + '.' + mydata.navemediatore.col); + let index = 1; + + if (mydata.inviareale) { + let mystrmsg = tools.getStrMsgByTipoMsg(tipomsgorig); + if (!!mystrmsg) { + tools.writeFlottaLog(idapp, mystrmsg, flotta.riga, flotta.col_prima); + } + } + for (const nave of arrnavi) { - const user = await User.findByIndOrder(idapp, nave.ind_order); + + mydata.tipomsg = tipomsgorig; + + let user = null; + + if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_A_SOGNATORE) { + user = nave; + } else { + user = await User.findByIndOrder(idapp, nave.ind_order); + + if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_SOLLECITO_DONATORI_NO_DONO) { + // Solo a quelli che non hanno fatto il dono + if (nave.made_gift) + user = null; + } + + if ((nave.num_tess % 2) === 0) { + // MEDIATORE ! + // Se l'ultimo Donatore è un Mediatore, allora NON GLI MANDO IL MESSAGGIO ! + if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_EFFETTUA_IL_DONO) { + user = null; + } + if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_SOLLECITO_DONATORI_NO_DONO) { + user = null; + } + } else { + // DONATORE + + if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_A_MEDIATORI) { + user = null; // Se sto mandando msg a Mediatore, allora questo no! + } + } + } + + //mydata.tipomsg = tools.TipoMsg.SEND_MSG_A_MEDIATORI; if (!!user) { const lang = user.lang; const idteleg = user.profile.teleg_id; - const mymsg = this.getMsgByTipoMsg(mydata, lang, user, false); + mydata.nave = nave; + const rismsg = await this.getMsgByTipoMsg(mydata, lang, user, false); + + mymsg = rismsg.body; + mytitle = rismsg.title; + + if (mymsgprimo === '') { + mymsgprimo = mymsg; + } if (!!idteleg) { - strout += '\n' + user.name + ' ' + user.surname + ':'; + strout += '\n (' + index + ') ' + user.name + ' ' + user.surname + ':'; if (mydata.inviareale) { await this.sendMsgTelegramByIdTelegram(idapp, idteleg, mymsg, undefined, undefined, true); await tools.snooze(300); - strout += ' -> MSG INVIATO'; + strout += ' -> (MSG OK)'; + + if (mydata.inviaemail && !!user.email) { + // user.email = 'paolo.arena77@gmail.com'; + await sendemail.sendEmail_ByText(user.lang, user.email, user, idapp, {emailbody: mymsg, emailtitle: mytitle}); + strout += ' -> (EMAIL OK)'; + } + + nummsgsent++; } else { - strout += ' (Pronto da Inviare)'; - } - nummsgsent++; - } - if ((nummsgsent === 1) && (mydata.inviareale)) { - try { - await this.sendMsgTelegramToTheManagers(idapp, 'Inviato messaggio a tutti i Donatori della Nave ' + mydata.navemediatore.riga + '.' + mydata.navemediatore.col + '\n' + mymsg) - } catch (e) { - + strout += ' (Ok)'; + nummsgtosend++; } } } + index++; } + } - if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { + if (!mydata.inviareale) { + await this.sendMsgTelegramToTheManagers(idapp, 'TEST INVIO MESSAGGIO:\n' + mymsgprimo + '\n\n(Messaggi da Inviare: ' + nummsgtosend + ')'); + } - const usersognatore = await Nave.getSognatoreByRigaColMediatore(idapp, mydata.navemediatore); - - console.log('Sognatore: ', usersognatore.username); - - if (!!usersognatore) { - const lang = usersognatore.lang; - const idteleg = usersognatore.profile.teleg_id; - const mymsg = this.getMsgByTipoMsg(mydata, lang, usersognatore, true); - - // Invia Msg al Sognatore ! - if (mydata.inviareale) { - await this.sendMsgTelegramByIdTelegram(idapp, idteleg, mymsg, undefined, undefined, true); - await tools.snooze(300); - nummsgsent++; - strout += '\n' + usersognatore.name + ' ' + usersognatore.surname + ':'; - strout += ' -> MSG INVIATO'; - } else { - strout += ' (Pronto da Inviare)'; - } + if ((nummsgsent > 1) && (mydata.inviareale)) { + try { + let msg = ''; + if (!!flotta) { + msg = 'Inviato messaggio a tutta la FLOTTA DA ' + flotta.riga + '.' + flotta.col_prima + ' A ' + flotta.riga + '.' + flotta.col_ultima + ' \n' + mymsg; + } else { + msg = 'Inviato messaggio a tutti i Donatori della Nave ' + mydata.navemediatore.riga + '.' + mydata.navemediatore.col + '\n' + mymsg; } + await this.sendMsgTelegramToTheManagers(idapp, msg) + } catch (e) { } + } - if (nummsgsent > 0) { - if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { - const fields_to_update = { - sent_msg_howto_make_gift: true - }; - await Nave.findOneAndUpdate({ _id: mydata.navemediatore.id }, { $set: fields_to_update }, { new: false }); + /* + if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { + + + const usersognatore = await Nave.getSognatoreByRigaColMediatore(idapp, mydata.navemediatore); + + console.log('Sognatore: ', usersognatore.username); + + if (!!usersognatore) { + const lang = usersognatore.lang; + const idteleg = usersognatore.profile.teleg_id; + const mymsg = this.getMsgByTipoMsg(mydata, lang, usersognatore, true); + + // Invia Msg al Sognatore ! + if (mydata.inviareale) { + await this.sendMsgTelegramByIdTelegram(idapp, idteleg, mymsg, undefined, undefined, true); + await tools.snooze(300); + nummsgsent++; + strout += '\n' + usersognatore.name + ' ' + usersognatore.surname + ':'; + strout += ' -> MSG INVIATO'; + } else { + strout += ' (Pronto da Inviare)'; } } } + */ + + if (nummsgsent > 0) { + if (mydata.tipomsg === tools.TipoMsg.SEND_LINK_CHAT_DONATORI) { + const fields_to_update = { + sent_msg_howto_make_gift: true + }; + await Nave.findOneAndUpdate({ _id: mydata.navemediatore.id }, { $set: fields_to_update }, { new: false }); + } + } + + return { nummsgsent, strout }; } catch (e) { console.error(e.message); + strout = 'Error: ' + e.message + '\n' + strout; return { nummsgsent, strout }; } }, @@ -1137,10 +1289,14 @@ class Telegram { await this.menumsgAll(msg) } else if (msg.text === Menu.MSGSTAFF) { await this.menumsgStaff(msg) + } else if (msg.text === Menu.MSGPAOLO) { + await this.menumsgPaolo(msg) } else if (msg.text === Menu.MSG_NO_7_REQ) { await this.menumsg_No_7_Req(msg) } else if (msg.text === Menu.MSG_NO_9_REQ) { await this.menumsg_No_9_Req(msg) + } else if (msg.text === Menu.NESSUN_IMBARCO_7REQ) { + await this.menumsgGenerico(msg, Destin.NESSUN_IMBARCO_7REQ); } else if (cmd1 === Menu.MSG_TO_NAVE) { await this.menumsg_to_Nave(msg, cmd2) } else if (msg.text === Menu.MSG_SI_INVITATI_NO_7REQ_INVITATI) { @@ -1460,6 +1616,8 @@ class Telegram { return 'TUTTI'; else if (destin === Destin.STAFF) return 'STAFF'; + else if (destin === Destin.PAOLO) + return 'PAOLO'; else if (destin === Destin.NO_7_REQ) return 'No 7 Requisiti'; else if (destin === Destin.NO_9_REQ) @@ -1468,6 +1626,8 @@ class Telegram { return '2 Invitati ma NO Requisiti'; else if (destin === Destin.MSG_TO_NAVE) return 'Nave ' + rec.extraparam; + else if (destin === Destin.NESSUN_IMBARCO_7REQ) + return 'No Imbarcati (7 Req) '; else if (destin === Destin.A_UTENTE) { const rec = this.getRecInMem(msg); return rec.msgall_username_specifico @@ -1483,6 +1643,10 @@ class Telegram { await this.menumsgGenerico(msg, Destin.STAFF); } + async menumsgPaolo(msg) { + await this.menumsgGenerico(msg, Destin.PAOLO); + } + async menumsg_No_7_Req(msg) { await this.menumsgGenerico(msg, Destin.NO_7_REQ); } @@ -1592,7 +1756,7 @@ class Telegram { } getRecInMem(msg) { - return this.arrUsers.find((rec) => rec.id === msg.from.id); + return this.arrUsers.find((rec) => rec.id === this.getchatid(msg)); } getRecInMemById(id) { @@ -1608,7 +1772,7 @@ class Telegram { } deleteRecInMem(msg) { - this.arrUsers = this.arrUsers.filter((rec) => rec.id !== msg.from.id); + this.arrUsers = this.arrUsers.filter((rec) => rec.id !== this.getchatid(msg)); } async getUser(msg, rec, conmsg) { @@ -1776,7 +1940,15 @@ class Telegram { tools.writeEventsLog(this.getDestinStr(msg, destin, rec) + ':\n' + texttosend); + // let chiedisino = false; + + // TEST usersall = await User.getUsersTelegALL(rec.user.idapp, 'paoloar77'); + for (const utente of usersall) { + + let FormDaMostrare = null; + const lang = utente.lang; + if (!utente.deleted && !utente.sospeso) { if (this.isSelMenu(msg, texttosend === 'LAVAGNA')) { textdainviare = await this.getLavagnaByUser(utente, msg); @@ -1791,12 +1963,16 @@ class Telegram { invia = User.isManager(utente.perm); } else if (destin === Destin.TUTTI) { invia = true; + } else if (destin === Destin.PAOLO) { + invia = utente.username === 'paoloar77'; } else if (destin === Destin.A_UTENTE) { invia = utente.username === rec.msgall_username_specifico; } else if (destin === Destin.NO_7_REQ) { invia = !await User.isUserQualified7(this.idapp, utente.username); } else if (destin === Destin.NO_9_REQ) { invia = !await User.isUserQualified9(this.idapp, utente.username); + } else if (destin === Destin.NESSUN_IMBARCO_7REQ) { + invia = await User.NessunaNavePresenteByUsername(this.idapp, utente.username); } else if (destin === Destin.MSG_TO_NAVE) { invia = !await Nave.findDonatoreByNave(this.idapp, rec.extraparam); } else if (destin === Destin.SI_INVITATI_NO_7REQ_INVITATI) { @@ -1804,21 +1980,56 @@ class Telegram { const numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(this.idapp, utente.username); invia = (numinvitati >= 2) && (numinvitatiattivi < 2); } + + // TEST invia = true; + if (invia) { + let inviaveramente = false; + if (cmd === RICEVI_EMAIL) { preparatesto += utente.email + ', '; + } else if (cmd === NOME_COGNOME) { + preparatesto += utente.name + ' ' + utente.surname + '(' + utente.username + ')' + '\n'; } else if (cmd === CONTA_SOLO) { // Niente + } else if (cmd === CHEDI_SE_IMBARCARTI) { + textdainviare = tools.gettranslate('VUOI_IMBARCARTI', lang); + // chiedisino = true; + // rec.msgall_status = StatusMSGALL.CONFIRM; + FormDaMostrare = this.getInlineKeyboard(lang, [ + { text: Menu[lang].SI, callback_data: InlineCmd.VOGLIO_IMBARCARMI }, + { text: Menu[lang].NO, callback_data: InlineCmd.NON_VOGLIO_IMBARCARMI }, + ]); + inviaveramente = true; } else { + inviaveramente = true; + } + + + if (inviaveramente) { if (destin === Destin.A_UTENTE) { await this.sistemaRecDest(rec, msg); await this.sendMsg(utente.profile.teleg_id, '[' + rec.username_bo + ' ti scrive]:\n' + textdainviare, MenuChat); } else { - await this.sendMsg(utente.profile.teleg_id, textdainviare); + + // if (chiedisino) { + // this.ChiediSINO(msg, textdainviare); + // } else { + // TEST + + let telegid = utente.profile.teleg_id; + // if (process.env.PROD === "0") { + // telegid = 12429864; + // } + await this.sendMsg(telegid, textdainviare, null, FormDaMostrare); + + // break; } - await tools.snooze(300) + await tools.snooze(300); + + nummsgsent++; } - nummsgsent++; + if (!SendMsgCmd.includes(cmd)) { if ((nummsgsent % 50) === 0) { @@ -1834,6 +2045,10 @@ class Telegram { let msgris = ""; if (cmd === CONTA_SOLO) { msgris = nummsgsent + ' ' + getstr(this.getlang(msg), 'MSG_MSG_TOSENT'); + } else if (cmd === NOME_COGNOME) { + msgris = nummsgsent + ' ' + 'Utenti'; + await this.sendMsg(msg.chat.id, msgris); + msgris = preparatesto; } else if (cmd === RICEVI_EMAIL) { msgris = nummsgsent + ' ' + 'Email'; await this.sendMsg(msg.chat.id, msgris); @@ -1870,17 +2085,28 @@ class Telegram { || (msg.text === Menu.LANG_FR) || (msg.text === Menu.LANG_SI) || (msg.text === Menu.LANG_PT)) } - async receiveMsg(msg) { + async setInit(msg) { let status = this.getstatusInMemory(msg); if (status === Status.NONE) { await this.start(msg); let status = this.getstatusInMemory(msg); if (status !== Status.VERIFIED) - return + return Status.EXIT; } else { await this.setUser(msg) } + return status; + } + + async receiveMsg(msg) { + + let status = await this.setInit(msg); + + if (status === Status.EXIT) { + return + } + const rec = this.getRecInMem(msg); status = this.getstatus(rec); @@ -1912,6 +2138,8 @@ class Telegram { domanda = 'Confermi di vedere a quante persone arriverebbe questo messaggio, a ' + achi + ' ?\n' + rec.msgtosent; else if (cmd === RICEVI_EMAIL) domanda = 'Confermi di vedere la lista delle email di ' + achi + '?'; + else if (cmd === NOME_COGNOME) + domanda = 'Confermi di vedere la lista di persone ' + achi + '?'; else { if (rec.msgall_achi === Destin.A_UTENTE) domanda = 'Confermi d\'Iniziare una Chat messaggi con ' + achi + ' ?\n' + rec.msgtosent; @@ -1940,7 +2168,8 @@ class Telegram { async askVerifiedCode(msg) { - const rec = this.arrUsers.find((rec) => rec.id === msg.from.id); + const rec = this.getRecInMem(msg); + if (!rec) { await this.addUser(msg); @@ -1954,9 +2183,10 @@ class Telegram { } async setUser(msg) { - const id = msg.from.id; + let id = this.getchatid(msg); + const user = await User.UserByIdTelegram(this.idapp, id); - let rec = this.arrUsers.find((rec) => rec.id === msg.from.id); + let rec = this.getRecInMem(msg); if (user && rec) { rec.user = user; } @@ -1971,12 +2201,19 @@ class Telegram { } + getchatid(msg) { + if (msg.from.is_bot) + return msg.chat.id; + else + return msg.from.id; + } + async alreadyExist(msg) { - const id = msg.from.id; + const id = this.getchatid(msg); let rec = null; try { const user = await User.UserByIdTelegram(this.idapp, id); - let rec = this.arrUsers.find((rec) => rec.id === msg.from.id); + let rec = this.getRecInMem(msg); if (user && !rec) { rec = this.addUser(msg); } @@ -1998,7 +2235,7 @@ class Telegram { const code = 100000 + Math.round(Math.random() * 899999); const rec = { - id: msg.from.id, + id: this.getchatid(msg), code, lang, status: Status.WAITFOR_USERNAME_BO, @@ -2060,7 +2297,7 @@ class Telegram { } - async _inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec) { + async _inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec, opt) { if (!text) return 0; @@ -2095,6 +2332,12 @@ class Telegram { } try { + + text = text.replace(/
/g, "\n"); + text = text.replace(/
/g, ""); + text = text.replace(/<\/div>/g, "\n"); + text = text.replace(/ /g, " "); + if (!form) { form = { "parse_mode": "HTML", @@ -2169,6 +2412,48 @@ class Telegram { return mymenuout; } + getInlineKeyboard(lang, arrrisp1, arrrisp2, arrrisp3) { + let mykeyb = { + parse_mode: 'HTML', + reply_markup: { + inline_keyboard: [] + } + }; + + // text + // callback_data + + // url + + const arrriga1 = []; + if (!!arrrisp1) { + for (const ris of arrrisp1) { + arrriga1.push(ris); + } + } + const arrriga2 = []; + if (!!arrrisp2) { + for (const ris of arrrisp2) { + arrriga2.push(ris); + } + } + const arrriga3 = []; + if (!!arrrisp3) { + for (const ris of arrrisp3) { + arrriga3.push(ris); + } + } + + if (arrriga1.length > 0) + mykeyb.reply_markup.inline_keyboard.push(arrriga1); + if (arrriga2.length > 0) + mykeyb.reply_markup.inline_keyboard.push(arrriga2); + if (arrriga3.length > 0) + mykeyb.reply_markup.inline_keyboard.push(arrriga3); + + return mykeyb; + } + async ChiediSINO(msg, domanda) { const lang = this.getlang(msg); @@ -2246,6 +2531,15 @@ if (!tools.testing()) { if (!!token) { const bot = new TelegramBot(token, { polling: true }); + if (url === '0') { + const ngrok = require('ngrok'); + ngrok.connect(port, function onConnect(error, u) { + if (error) throw error; + url = u; + console.log(`Game tunneled at ${url}`); + }); + } + arrTelegram.push({ idapp, cl: new Telegram(idapp, bot) }); bot.onText(/\/start/, (msg) => { @@ -2290,10 +2584,52 @@ if (!tools.testing()) { }); // Handle callback queries - bot.on('callback_query', function onCallbackQuery(callbackQuery) { - console.log('callback_query', callbackQuery); + bot.on('callback_query', async (callbackQuery) => { + // console.log('callback_query', callbackQuery); - bot.answerCallbackQuery(callbackQuery.id, { url }); + const myclTelegram = getclTelegBytoken(bot.token); + + const action = callbackQuery.data; + const msg = callbackQuery.message; + const opts = { + chat_id: msg.chat.id, + message_id: msg.message_id, + }; + + const status = await myclTelegram.setInit(msg); + + const rec = myclTelegram.getRecInMem(msg); + if (!!rec) { + if (!!rec.user) { + if (action === InlineCmd.VOGLIO_IMBARCARMI) { + // Controlla se è qualificato! + const mydata = tools.AddDate(rec.user.date_reg, 7); + + const newrecingr = await ListaIngresso.addUserInListaIngresso(rec.user.idapp, rec.user.username, rec.user.aportador_solidario, rec.user.lang, true, true, mydata); + + bot.editMessageText(tools.gettranslate('ADDED_TOLISTAINGRESSO', rec.user.lang), opts); + + } else if (action === InlineCmd.NON_VOGLIO_IMBARCARMI) { + await User.NonVoglioImbarcarmi(rec.user.idapp, rec.user.username); + + const msgadd = '[' + rec.user.username + '] ' + rec.user.name + ' ' + rec.user.surname + ' ha risposto che NON VUOLE IMBARCARSI !'; + + await local_sendMsgTelegramToTheManagers(rec.user.idapp, msgadd, msg, false); // Anche a STAFF + } + } + } + + /* + let text; + + if (action === 'edit') { + text = 'Edited Text'; + } + + bot.editMessageText(text, opts); + */ + + // bot.answerCallbackQuery(callbackQuery.id, { url }); }); } diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 87a2fc4..8652394 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -25,6 +25,7 @@ const webpush = require('web-push'); const FILELOG = 'filelog.txt'; const FILEEVENTS = 'logevents.txt'; const FILEMANAGERS = 'logmanagers.txt'; +const FILESOSTITUZIONI = 'log_sostituzioni.txt'; const FILENAVE = 'logNave.txt'; const subject = process.env.URLBASE_APP1; const publicVapidKey = process.env.PUBLIC_VAPI_KEY; @@ -114,6 +115,7 @@ textlang = { 'TEMPORANEA': 'TEMPORANEA', 'NAVE': 'NAVE', 'MSG_SEND_FROM': 'Msg Inviato da', + 'VUOI_IMBARCARTI': 'Attenzione! Ci risulta che attualmente non ti è stato assegnato Nessun Imbarco.\nQuesto può essere dovuto ad un errore durante la fase di aggiornamento del sito, oppure perchè tu stesso hai cancellato l\'imbarco.\n\nVuoi Aggiungerti ora al prossimo Imbarco per continuare nel tuo Viaggio in AYNI? ', }, si: { "Email je že bila preverjena": "Email je že bila preverjenaL'Email è già stata Verificata", @@ -181,6 +183,7 @@ textlang = { 'TEMPORANEA': 'ZAČASNA', 'NAVE': 'LADJE', 'MSG_SEND_FROM': 'sporočilo, ki ga je poslal', + 'VUOI_IMBARCARTI': 'Pozor! Opazili smo, da ti trenutno ni bila dodeljena Nobena ladjica.\nTo je lahko posledica napake med fazo posodabljanja spletnega mesta ali ker si sam zbrisal svoj vpis.\n\nAli želiš nadaljevati plovbo, če želiš nadaljevati potovanje z AYNI ?', }, es: { "L'Email è già stata Verificata": "El correo electrónico ya ha sido verificado", @@ -246,6 +249,7 @@ textlang = { 'TEMPORANEA': 'TEMPORAL', 'NAVE': 'NAVE', 'MSG_SEND_FROM': 'Mensaje enviado por', + 'VUOI_IMBARCARTI': '¡Atención! Entendemos que actualmente no está asignado a No Boarding.\nEsto puede deberse a un error durante la fase de actualización del sitio web, o porque usted mismo ha cancelado el embarque.\n\n¿Quieres añadirte ahora al próximo embarque para continuar tu viaje en AYNI?', }, enUs: { "partecipanti": "participants", @@ -308,6 +312,7 @@ textlang = { 'TEMPORANEA': 'TEMPORARY', 'NAVE': 'SHIP', 'MSG_SEND_FROM': 'Msg sent by', + 'VUOI_IMBARCARTI': 'Attention! We understand that you have No Boarding assigned.\nThis may be due to an error during the site update phase, or because you have cancelled boarding yourself.\n\nDo you want to add now to the Next Boarding to continue your AYNI Trip?', }, fr: { "L'Email è già stata Verificata": "Le courrier électronique a déjà été vérifié", @@ -374,6 +379,7 @@ textlang = { 'TEMPORANEA': 'TEMPORAIRE', 'NAVE': 'NAVIRE', 'MSG_SEND_FROM': 'Message envoyé par', + 'VUOI_IMBARCARTI': 'Attention ! Nous comprenons que vous n\'êtes actuellement pas affecté Pas d\'embarquement.\nCela peut être dû à une erreur lors de la phase de mise à jour du site, ou parce que vous avez vous-même annulé l\'embarquement.\n\nVoulez-vous vous ajouter maintenant au prochain embarquement pour continuer votre voyage AYNI ? ', }, pt: { "L'Email è già stata Verificata": "", @@ -440,6 +446,7 @@ textlang = { 'TEMPORANEA': 'TEMPORÁRIO', 'NAVE': 'NAVE', 'MSG_SEND_FROM': 'Mensagem enviada por', + 'VUOI_IMBARCARTI': 'Atenção! Compreendemos que actualmente não lhe é atribuído Sem Embarque.\nIsto pode ser devido a um erro durante a fase de actualização do site, ou porque você mesmo cancelou o embarque.\n\nDeseja juntar-se agora ao próximo embarque para continuar a sua viagem AYNI?', }, }; @@ -449,6 +456,7 @@ module.exports = { ACAPO: '\n', ENABLE_CRONTAB: 'CRONTAB', + UPDATE_GRADUATORIA: 'UPDATE_GRAD', LANGADMIN: 'it', @@ -465,6 +473,12 @@ module.exports = { SEND_MSG: 2, SEND_MSG_SINGOLO: 3, SEND_TO_ALL: 10, + SEND_MSG_EFFETTUA_IL_DONO: 1000, + SEND_MSG_SOLLECITO_DONATORI_NO_DONO: 1005, + SEND_MSG_A_MEDIATORI: 1010, + SEND_MSG_A_SOGNATORE: 1020, + SEND_MSG_A_UTENTE_SOSTITUITO: 1030, + SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE: 1040, }, Placca: { @@ -982,6 +996,8 @@ module.exports = { 'note': { $exists: true }, "$expr": { "$gt": [{ "$strLenCP": "$note" }, 1] } }); + if (params.filterand.includes(shared_consts.FILTER_QUALIFIED)) + filtriadded.push({ 'profile.qualified': true }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_ZOOM)) filtriadded.push({ 'profile.saw_zoom_presentation': false }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_INVITANTE)) @@ -1010,6 +1026,11 @@ module.exports = { filtriadded.push({ deleted: { $exists: true, $eq: true } }); + if (params.filterand.includes(shared_consts.FILTER_NAVI_NON_PRESENTI)) + filtriadded.push({ + navinonpresenti: { $exists: true, $eq: true }, + $or: [{ subaccount: { $exists: false } }, { subaccount: { $exists: true, $eq: false } }] + }); } @@ -1210,7 +1231,7 @@ module.exports = { numup }; - if (idapp === tools.AYNI) { + if (idapp === this.AYNI) { this.getRigaColByPosUp(mypos); ris = this.getlimiti(mypos); } @@ -1294,6 +1315,15 @@ module.exports = { } }, + getstrDateLongFile(mydate, lang) { + if (mydate) { + // console.log('getstrDate', mytimestamp) + return mydate.getFullYear() + '-' + this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + this.appendLeadingZeroes(mydate.getDate()) + ' (' + this.getWeekDayByLang(mydate, lang) + ')' + } else { + return ''; + } + }, + getlinkzoom(idconf) { if (idconf === '') idconf = '6668882000'; @@ -1378,12 +1408,22 @@ module.exports = { // console.log('Saved!'); // }); - // mystr = this.getstrDateTimeShort(Date.now()) + ' ' + mystr; + mystr = this.getstrDateTimeShort(new Date(), 'it') + ': ' + mystr; + const stream = fs.createWriteStream(filename, { flags: 'a' }); stream.write('\n' + mystr); stream.end(); }, + readlogfile(idapp, filename) { + + try{ + return fs.readFileSync(idapp + '/' + filename, 'utf8'); + }catch (e) { + return ''; + } + }, + writelog(mystr) { this.writelogfile(mystr, FILELOG); }, @@ -1396,6 +1436,20 @@ module.exports = { this.writelogfile(mystr, FILEMANAGERS); }, + writeSostituzioniLog(mystr) { + this.writelogfile(mystr, FILESOSTITUZIONI); + }, + + writeFlottaLog(idapp, mystr, riga, col) { + this.mkdirpath(idapp + '/'); + this.writelogfile(mystr, idapp + '/' + riga + '_' + col + '.txt'); + }, + + readFlottaLog(idapp, riga, col) { + const nomefile = riga + '_' + col + '.txt'; + return this.readlogfile(idapp, nomefile); + }, + writeNaveLog(mystr) { this.writelogfile(mystr, FILENAVE); }, @@ -1523,6 +1577,9 @@ module.exports = { if ('username' in fieldsvalue) { return true; } + if ('note' in fieldsvalue) { + return true; + } } if (table === 'navi') { @@ -1541,12 +1598,15 @@ module.exports = { return true; } } + if (table === 'flotte') { + return true; + } return false; }, NotifyIfDelRecord(table) { - if ((table === 'users') || (table === 'extralist') || (table === 'listaingressos')) { + if ((table === 'users') || (table === 'extralist') || (table === 'listaingressos') || (table === 'graduatorias')) { return true; } @@ -1572,5 +1632,41 @@ module.exports = { return Math.pow(2, riga - 1); }, + getPrimoFuocoByIndCol(col) { + // let ris = Math.ceil(col - (col % 8)) + 1; + let ris = ((Math.ceil(col / 8) - 1) * 8) + 1; + if (ris <= 0) + ris = 1; + return ris + }, + + getPrimaColFlotta(col) { + // let ris = Math.ceil(col - (col % 8)) + 1; + let ris = ((Math.ceil(col / 64) - 1) * 64) + 1; + if (ris <= 0) + ris = 1; + return ris + }, + + getStrMsgByTipoMsg(tipomsg) { + + let mystr = ''; + + if (tipomsg === this.TipoMsg.SEND_MSG_EFFETTUA_IL_DONO) + mystr = 'Inviato Messaggio per Effettuare il Dono a Tutta la Flotta'; + else if (tipomsg === this.TipoMsg.SEND_MSG_SOLLECITO_DONATORI_NO_DONO) + mystr = 'Inviato Messaggio per RICORDARE di Effettuare il Dono a chi ancora non l\'ha fatto'; + else if (tipomsg === this.TipoMsg.SEND_MSG_A_MEDIATORI) + mystr = 'Inviato Messaggio ai Mediatori'; + else if (tipomsg === this.TipoMsg.SEND_MSG_A_SOGNATORE) + mystr = 'Inviato Messaggio al Sognatore'; + else if (tipomsg === this.TipoMsg.SEND_MSG_A_UTENTE_SOSTITUITO) + mystr = 'Inviato Messaggio all\'utente Sostituito'; + else if (tipomsg === this.TipoMsg.SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE) + mystr = 'Inviato Messaggio Dono Ricevuto Correttamente'; + + return mystr; + } + }; diff --git a/src/server/tools/server_constants.js b/src/server/tools/server_constants.js index 9546f43..7ce747b 100755 --- a/src/server/tools/server_constants.js +++ b/src/server/tools/server_constants.js @@ -16,6 +16,7 @@ module.exports = Object.freeze({ RIS_CODE_ERR_UNAUTHORIZED: -30, RIS_CODE_LOGIN_ERR_GENERIC: -20, RIS_CODE_LOGIN_ERR: -10, + RIS_CODE_LOGIN_ERR_SUBACCOUNT: -8, RIS_CODE_OK: 1, RIS_CODE_LOGIN_OK: 1, diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index 16af737..da2895b 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -20,6 +20,8 @@ module.exports = { FILTER_USER_TELEGRAM_BLOCKED: 1024, FILTER_ATTIVI: 2048, FILTER_NASCOSTI: 4096, + FILTER_NAVI_NON_PRESENTI: 8192, + FILTER_QUALIFIED: 16384, Permissions: { Admin: 1, @@ -49,6 +51,8 @@ module.exports = { AGGIUNGI_NUOVO_IMBARCO: 380, CANCELLA_IMBARCO: 385, DAMMI_PRIMO_UTENTE_LIBERO: 390, + GET_VALBYTABLE: 400, + SET_VALBYTABLE: 410, }, fieldsUserToChange() { From 6e8122db866b70893b7dabd9db8cc5a7ea7d0133 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Thu, 2 Jul 2020 22:00:58 +0200 Subject: [PATCH 07/14] Sistemazioni... --- docs/passi.txt | 44 ++++++- src/server/models/flotta.js | 29 +++++ src/server/models/listaingresso.js | 75 ++++++++++++ src/server/models/nave.js | 15 ++- src/server/models/navepersistente.js | 17 ++- src/server/models/user.js | 68 +++++++---- src/server/router/api/actions.js | 5 +- src/server/router/dashboard_router.js | 14 ++- src/server/router/index_router.js | 166 ++++++++++++++------------ src/server/router/users_router.js | 1 + src/server/sendemail.js | 6 +- src/server/telegram/telegrambot.js | 81 +++++++++---- src/server/tools/general.js | 104 ++++++++++++---- 13 files changed, 454 insertions(+), 171 deletions(-) diff --git a/docs/passi.txt b/docs/passi.txt index 07024e9..9b4c8c8 100644 --- a/docs/passi.txt +++ b/docs/passi.txt @@ -1,18 +1,55 @@ ------------ - - L'ultimo Utente della Creazione della Nave, compare ancora il Sognatore !!! Sistemato: TESTARE SE ORA È' OK... - // ************************************************ // ++Todo: PRIORITA' ALTA: +- Togliere i Video e il Sogno. (5 requisiti) +- Cestino di ELIMINA non funziona !! + +- (Linuccia) - Natalina Malerbi + DA CONTROLLARE CHE LEI NON HA PAGATO 8.44. + QUINDI QUALCUNO HA PRESO IL SUO POSTO. + + + - 7.64 : NATALINA NON HA LA RITESSITURA !! + + +- 1403 : Kukovič + ha tutto disattivato, mentre non è vero. +- 1344: Piera La Porta + ha tutto attivo invece non ha niente... + +- SubAccount: + filtro. + +- Aggiornare le Traduzioni di Darja (ritessitura). + +- Sistemare la email che arriva ai Donatori (HTML) ! + +- Flotte: Poter scegliere quale messaggio inviare ! + +- SE CAMBIANO LE CREDENZIALI: EMAIL... o username: segnalarlo sul BOT ! + +- Alla sostituzione, mandare msg all'Invitante + +- CONTROLLARE CHE IN NAVI NON CI SIANO i num_tess e ind_order UGUALI ! + ad esempio Angela + - Record 1 -> ind_order = 51 num_tess = 1 + - Record 2 -> ind_order = 51 num_tess = 1 <--- DEV'ESSERE A 3 ! + - Puoi imbarcarti non piu di 2 volte temporanee. - Togliere Sogno e Video. +- Controllare che da errore in fase di cancellazione dell'utente, dal profilo: + Fare una pagina intermedia che dice che sei stato cancellato... + +- Controllare la data nel tragitto sembra essere sbagliata (vedi Cinzia Ortolan). + - Profili Incompleti: Poter inviare dei messaggi in automatico per ricordargli di completare ... @@ -144,18 +181,15 @@ ind_order: 852 Gerico2 Elio2 Garelli Morgana Roveta (Maelabo) --- Gerico Elio Garelli - ANDREA |-----GERICO2 852 - .update({}, {$unset: {$ind_order: 1}, {multi: true}); - //++TODO: *** FATTI *** diff --git a/src/server/models/flotta.js b/src/server/models/flotta.js index 20cfbf3..c24375f 100755 --- a/src/server/models/flotta.js +++ b/src/server/models/flotta.js @@ -78,6 +78,9 @@ const FlottaSchema = new mongoose.Schema({ email_paypal: { type: String, }, + revolut: { + type: String, + }, note_payment: { type: String, }, @@ -111,6 +114,7 @@ function getQueryProj(myfilter) { username: 1, 'profile.paymenttypes': 1, 'profile.email_paypal': 1, + 'profile.revolut': 1, 'profile.cell': 1, made_gift: 1, commento_al_sognatore: 1, @@ -317,6 +321,31 @@ FlottaSchema.statics.getFlottaByNavePersistente = async function (idapp, naveper return myflotta; }; +FlottaSchema.statics.getStrFlotta = function (flotta) { + return `Flotta ${flotta.riga}.${Math.ceil(flotta.col_prima / 8)} - ${flotta.riga}.${Math.ceil(flotta.col_ultima / 8)}: Sognatore: ${flotta.sognatore_nomecognome}`; +}; + + +FlottaSchema.statics.getFlottaByRigaColDonatore = async function (idapp, riga, col) { + const Flotta = this; + + let mypos = { + idapp, + riga, + col, + numup: 3 + }; + tools.getRigaColByPosUp(mypos); + + const myflotta = await Flotta.findOne({ idapp, riga: mypos.riga, + $and: [ + { col_prima: { $lte: col } }, + { col_ultima: { $gte: col } } ] + }); + + return myflotta; +}; + const Flotta = mongoose.model('Flotta', FlottaSchema); diff --git a/src/server/models/listaingresso.js b/src/server/models/listaingresso.js index 17baa74..489eff1 100755 --- a/src/server/models/listaingresso.js +++ b/src/server/models/listaingresso.js @@ -11,6 +11,8 @@ const { ObjectID } = require('mongodb'); const { Nave } = require('./nave'); const { Graduatoria } = require('./graduatoria'); +const actions = require('../router/api/actions'); + const shared_consts = require('../tools/shared_nodejs'); const queryclass = require('../classes/queryclass'); @@ -929,6 +931,79 @@ ListaIngressoSchema.statics.getListaTessByUsername = function (idapp, username) }; + +ListaIngressoSchema.statics.eliminaListaIngresso = async function (idapp, ind_order, req, num_tess) { + const ListaIngresso = this; + + const telegrambot = require('../telegram/telegrambot'); + + const myrec = await ListaIngresso.getIngrEUserByFilter(idapp, { + idapp, + ind_order + }); + + let filtro = { idapp, ind_order }; + + // if (!!num_tess) { + // filtro.num_tess = num_tess; + // } + + // Controlla se ci sono piu navi + const arrnavi = await Nave.find(filtro); + + const eliminaveramente = false; + + let nasc = ''; + let receliminato = false; + + let risdel = false; + if (arrnavi.length === 1) { + if (!arrnavi[0].made_gift) { + // SE NON E' STATO CONFERMATO CHE HA FATTO IL DONO! + // Solo 1 nave da cancellare, quindi cancello anche l'ingresso + let filtrocanc = { idapp, ind_order }; + if (!!num_tess) + filtrocanc.num_tess = num_tess; + + let recdel = null; + if (eliminaveramente) { + recdel = await ListaIngresso.deleteOne(filtrocanc); + } else { + nasc = '(nascosto)'; + let fieldsvalue = { + date_deleted: new Date(), + deleted: true + }; + recdel = await ListaIngresso.findOneAndUpdate(filtrocanc, { $set: fieldsvalue }, { new: false }); + } + + risdel = !!recdel; + receliminato = !!recdel; + } + } else { + // non cancellare la listaingresso (perchè con lo stesso ind_order ho piu navi ! + risdel = true; + receliminato = false; + } + + let msg = ''; + if (risdel) { + if (receliminato) { + msg = 'Eliminato RECORD in Lista Imbarco ' + nasc + ' di ' + myrec.name + ' ' + myrec.surname + ' (ind_order=' + myrec.ind_order + ', num_tess=' + myrec.num_tess + ') [Num = ' + myrec.index + `] (da ${req.user.name} ${req.user.surname} )`; + } + await actions.doOtherThingsAfterDeleted('listaingressos', myrec, false, req) + } else { + msg = 'ATTENZIONE: il RECORD non è stato Eliminato perchè gia c\'era in altra NAVE -> di ' + myrec.name + ' ' + myrec.surname + ' (ind_order=' + myrec.ind_order + ', num_tess=' + myrec.num_tess + ') [Num = ' + myrec.index + `] (da ${req.user.name} ${req.user.surname} )`; + } + + if (!!msg) { + await telegrambot.sendMsgTelegramToTheManagers(myrec.idapp, msg); + tools.writeSostituzioniLog(msg); + } + + return risdel; +}; + ListaIngressoSchema.statics.getarray = async function (idapp, filtri, myobjField) { const ListaIngresso = this; diff --git a/src/server/models/nave.js b/src/server/models/nave.js index 388236e..105c46c 100755 --- a/src/server/models/nave.js +++ b/src/server/models/nave.js @@ -445,7 +445,9 @@ function getQueryProj(myfilter) { sospeso: 1, 'profile.paymenttypes': 1, 'profile.teleg_id': 1, + 'profile.nationality': 1, 'profile.email_paypal': 1, + 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, 'profile.cell': 1, @@ -1498,6 +1500,7 @@ NaveSchema.statics.getFlotta = async function (idapp, riga, col_prima, col_ultim if (!!usersognatore) { flotta.link_payment = usersognatore.profile.link_payment; flotta.email_paypal = usersognatore.profile.email_paypal; + flotta.revolut = usersognatore.profile.revolut; flotta.note_payment = usersognatore.profile.note_payment; } @@ -1505,6 +1508,8 @@ NaveSchema.statics.getFlotta = async function (idapp, riga, col_prima, col_ultim const arrnavi = await Nave.aggregate(myquery); + const arrmediatori = []; + for (const nave of arrnavi) { // Se è il mediatore, allora non includerlo nei Donatori! mypos = { @@ -1519,6 +1524,8 @@ NaveSchema.statics.getFlotta = async function (idapp, riga, col_prima, col_ultim if (!!navemediatore) { if (navemediatore.ind_order !== nave.ind_order) { arrnaviout.push(nave); + } else { + arrmediatori.push(nave); } } else { arrnaviout.push(nave); @@ -1527,7 +1534,7 @@ NaveSchema.statics.getFlotta = async function (idapp, riga, col_prima, col_ultim flotta._doc.log_attivita = tools.readFlottaLog(idapp, flotta.riga, flotta.col_prima); - return { arrdonatori: arrnaviout, flotta }; + return { arrdonatori: arrnaviout, flotta, arrmediatori }; }; @@ -1650,11 +1657,9 @@ NaveSchema.statics.checkIfMadeGift = async function (idapp, username) { const arrlistaingr = await ListaIngresso.find({ idapp, username }); for (const ingr of arrlistaingr) { - let mynave = await Nave.findOne({ idapp, ind_order: ingr.ind_order }); + let mynave = await Nave.findOne({ idapp, ind_order: ingr.ind_order, made_gift: true }); if (!!mynave) { - if (mynave.made_gift) { - return true; - } + return true; } } diff --git a/src/server/models/navepersistente.js b/src/server/models/navepersistente.js index 626fbff..f44dc2a 100755 --- a/src/server/models/navepersistente.js +++ b/src/server/models/navepersistente.js @@ -94,6 +94,7 @@ function getQueryProj(myfilter) { username: 1, 'profile.paymenttypes': 1, 'profile.email_paypal': 1, + 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, 'profile.cell': 1, @@ -357,7 +358,9 @@ NavePersistenteSchema.statics.changeField = async function (idapp, flotta, field let myval = {}; if ('date_close' in fieldvalue) { - myval['date_gift_chat_open'] = fieldvalue['date_close']; + myval['date_start'] = fieldvalue['date_close']; + } else if ('date_start' in fieldvalue) { + myval['date_gift_chat_open'] = fieldvalue['date_start']; } else { myval = fieldvalue; } @@ -378,6 +381,8 @@ NavePersistenteSchema.statics.aggiornaFlottaByNavePersistente = async function ( const { Nave } = require('../models/nave'); const { User } = require('./user'); + const { Flotta } = require('./flotta'); + let num = 0; @@ -387,7 +392,7 @@ NavePersistenteSchema.statics.aggiornaFlottaByNavePersistente = async function ( indcolflottaprima = tools.getPrimaColFlotta(naveinput.col1don + 7); - console.log(num, ' -> [', naveinput.riga, '.', naveinput.col, '] indcolflottaprima=', indcolflottaprima); + console.log(num, ' -> [', naveinput.riga, '.', naveinput.col1don, '] indcolflottaprima=', indcolflottaprima); let ini = Math.ceil(indcolflottaprima / 8); let fine = ini + 7; @@ -431,8 +436,8 @@ NavePersistenteSchema.statics.aggiornaFlottaByNavePersistente = async function ( myflotta.msg_inviato = false; } - myflotta.date_start = navepers.date_start; - myflotta.date_close = navepers.date_gift_chat_open; + myflotta.date_start = navepers.date_gift_chat_open; + myflotta.date_close = navepers.date_start; let sognatore = await Nave.getSognatoreByRigaColMediatore(idapp, { riga: navepers.riga, col: navepers.col }); if (myflotta.sognatore_nomecognome === '') { @@ -443,10 +448,12 @@ NavePersistenteSchema.statics.aggiornaFlottaByNavePersistente = async function ( if (nuovo) { myflotta.email_paypal = ''; + myflotta.revolut = ''; myflotta.link_payment = ''; myflotta.note_payment = ''; if (!!sognatore) { myflotta.email_paypal = sognatore.profile.email_paypal; + myflotta.revolut = sognatore.profile.revolut; myflotta.link_payment = sognatore.profile.link_payment; myflotta.note_payment = sognatore.profile.note_payment; } @@ -455,6 +462,8 @@ NavePersistenteSchema.statics.aggiornaFlottaByNavePersistente = async function ( if (!!sognatore) { if (!myflotta.email_paypal) myflotta.email_paypal = sognatore.profile.email_paypal; + if (!myflotta.revolut) + myflotta.revolut = sognatore.profile.revolut; if (!myflotta.link_payment) myflotta.link_payment = sognatore.profile.link_payment; if (!myflotta.note_payment) diff --git a/src/server/models/user.js b/src/server/models/user.js index 7fcc583..f0fecb1 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -185,6 +185,9 @@ const UserSchema = new mongoose.Schema({ email_paypal: { type: String }, + revolut: { + type: String + }, link_payment: { type: String }, @@ -455,6 +458,7 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) 'profile.qualified_2invitati': 1, 'profile.saw_and_accepted': 1, 'profile.email_paypal': 1, + 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, 'profile.my_dream': 1, @@ -505,6 +509,7 @@ UserSchema.statics.getDownlineByUsername = async function (idapp, username, incl 'profile.qualified_2invitati': 1, 'profile.saw_and_accepted': 1, 'profile.email_paypal': 1, + 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, 'profile.my_dream': 1, @@ -583,11 +588,14 @@ UserSchema.statics.getQueryQualified = function () { 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED, 'profile.saw_zoom_presentation': true, 'profile.my_dream': { $exists: true }, - 'profile.email_paypal': { $exists: true }, - 'profile.paymenttypes': { "$in": ['paypal'] }, + $or: [ + { 'profile.email_paypal': { $exists: true } }, + { 'profile.revolut': { $exists: true } }, + ], + // 'profile.paymenttypes': { "$in": ['paypal'] }, $and: [ { "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } }, - { "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } } + // { "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } } ], // $where: "this.profile.paymenttypes.length >= 1", }] @@ -658,7 +666,7 @@ UserSchema.statics.setUserQualified = async function (idapp, username) { '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; }; @@ -674,7 +682,7 @@ UserSchema.statics.setUserQualified_2Invitati = async function (idapp, username) '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; }; @@ -697,10 +705,18 @@ UserSchema.statics.getnumPaymentOk = function (idapp) { return User.count({ idapp, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - 'profile.paymenttypes': { "$in": ['paypal'] }, - $where: "this.profile.paymenttypes.length >= 1", - 'profile.email_paypal': { $exists: true }, + $and: [ + { + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + 'profile.paymenttypes': { "$in": ['paypal'] }, + }, + { + $or: [ + { 'profile.email_paypal': { $exists: true } }, + { 'profile.revolut': { $exists: true } }, + ] + } + ] }); }; @@ -1132,6 +1148,7 @@ UserSchema.statics.getRecByIndOrder = async function (idapp, ind_order) { surname: 1, 'profile.teleg_id': 1, 'profile.email_paypal': 1, + 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, 'profile.paymenttypes': 1, @@ -1285,6 +1302,7 @@ UserSchema.statics.getFieldsForSearch = function () { { field: 'email', type: tools.FieldType.string }, { field: 'profile.cell', type: tools.FieldType.string }, { field: 'profile.email_paypal', type: tools.FieldType.string }, + { field: 'profile.revolut', type: tools.FieldType.string }, { field: 'profile.link_payment', type: tools.FieldType.string }, { field: 'profile.teleg_id', type: tools.FieldType.number }, { field: 'profile.username_telegram', type: tools.FieldType.string }, @@ -2187,26 +2205,26 @@ UserSchema.statics.DbOp = async function (idapp, mydata) { return { num }; - } else if (mydata.dbop === 'creaLista') { + /*} else if (mydata.dbop === 'creaLista') { - await ListaIngresso.deleteMany({ idapp, added: false }); + await ListaIngresso.deleteMany({ idapp, added: false }); - arrusers = await User.find({ - 'idapp': idapp, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] - }).sort({ date_added: 1 }); - let num = 0; + arrusers = await User.find({ + 'idapp': idapp, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + }).sort({ date_added: 1 }); + let num = 0; - num += await addUtentiInLista(idapp, 1, arrusers); - num += await addUtentiInLista(idapp, 2, arrusers); - num += await addUtentiInLista(idapp, 3, arrusers); - num += await addUtentiInLista(idapp, 4, arrusers); - num += await addUtentiInLista(idapp, 5, arrusers); - // num += await addUtentiInLista(idapp, 3); - // num += await addUtentiInLista(idapp, 4); - - return { num }; + num += await addUtentiInLista(idapp, 1, arrusers); + num += await addUtentiInLista(idapp, 2, arrusers); + num += await addUtentiInLista(idapp, 3, arrusers); + num += await addUtentiInLista(idapp, 4, arrusers); + num += await addUtentiInLista(idapp, 5, arrusers); + // num += await addUtentiInLista(idapp, 3); + // num += await addUtentiInLista(idapp, 4); + return { num }; + */ } } catch (e) { console.error(e.message); diff --git a/src/server/router/api/actions.js b/src/server/router/api/actions.js index 7f0a430..822a8b7 100755 --- a/src/server/router/api/actions.js +++ b/src/server/router/api/actions.js @@ -16,6 +16,9 @@ module.exports = { doOtherThingsAfterDeleted: async function (tablename, rec, notifBot, req) { try { let ris = null; + + const { ListaIngresso } = require('../../models/listaingresso'); + if (tablename === 'users') { await ListaIngresso.deleteUserInListaIngresso(rec.idapp, rec.username); @@ -42,7 +45,7 @@ module.exports = { ris = await Graduatoria.deleteOne({ idListaIngresso: ObjectID(rec._id) }); if (!!ris) { - let msg = 'Eliminato Imbarco di ' + rec.name + ' ' + rec.surname + ' (ind_order=' + rec.ind_order + ', num_tess=' + rec.num_tess + ') [Num = ' + rec.index + `] (da ${req.user.name} ${req.user.surname} )` ; + let msg = 'Eliminato dalla Graduatoria di ' + rec.name + ' ' + rec.surname + ' (ind_order=' + rec.ind_order + ', num_tess=' + rec.num_tess + ') [Num = ' + rec.index + `] (da ${req.user.name} ${req.user.surname} )` ; await telegrambot.sendMsgTelegramToTheManagers(rec.idapp, msg); tools.writeSostituzioniLog(msg); } diff --git a/src/server/router/dashboard_router.js b/src/server/router/dashboard_router.js index 70f61ef..4749990 100755 --- a/src/server/router/dashboard_router.js +++ b/src/server/router/dashboard_router.js @@ -102,7 +102,7 @@ router.post('/msgnave', authenticate, async (req, res) => { // ris = await telegrambot.sendMsgTelegram(idapp, mydata.username, mymsg, true, mydata.username_mitt); // Anche a STAFF ris = await telegrambot.sendMsgTelegram(idapp, mydata.username, mymsg, true); // Anche a STAFF } else - ris = await telegrambot.sendMsgTelegramToNave(idapp, mydata); + ris = await telegrambot.sendMsgTelegramToNave(idapp, mydata, res); if (ris) res.send({ code: server_constants.RIS_CODE_OK, ris }); @@ -123,7 +123,7 @@ router.post('/msgflotta', authenticate, async (req, res) => { try { let ris = null; - ris = await telegrambot.sendMsgTelegramToNave(idapp, mydata); + ris = await telegrambot.sendMsgTelegramToNave(idapp, mydata, res); if (ris) res.send({ code: server_constants.RIS_CODE_OK, ris }); @@ -190,8 +190,10 @@ router.post('/getnavi', authenticate, async (req, res) => { // } // nave._doc.rec.donatore.navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, riganave, colnave, 0); nave._doc.rec.donatore.navepersistente = await NavePersistente.findOne({ idapp, riga: riganave, col: colnave }); - if (!!nave._doc.rec.donatore.navepersistente) - nave._doc.rec.donatore.flotta = await Flotta.getFlottaByNavePersistente(idapp, nave._doc.rec.donatore.navepersistente); + if (!!nave._doc.rec) { + if (!!nave._doc.rec.donatore.navepersistente) + nave._doc.rec.donatore.flotta = await Flotta.getFlottaByNavePersistente(idapp, nave._doc.rec.donatore.navepersistente); + } } const navi_partenza = await NavePersistente.findAllIdApp(idapp); @@ -236,12 +238,14 @@ router.post('/getflotta', authenticate, async (req, res) => { const col_prima = req.body.col_prima; const col_ultima = req.body.col_ultima; + // const ris2 = await NavePersistente.aggiornaFlottaByNavePersistente(idapp, {riga, col1don: col_prima }); + let ris = await Nave.getFlotta(idapp, riga, col_prima, col_ultima); ris.flotta._doc.log_attivita = tools.readFlottaLog(idapp, ris.flotta.riga, ris.flotta.col_prima); if (!!ris) - res.send({ code: server_constants.RIS_CODE_OK, flotta: ris.flotta, arrdonatori: ris.arrdonatori }); + res.send({ code: server_constants.RIS_CODE_OK, flotta: ris.flotta, arrdonatori: ris.arrdonatori, arrmediatori: ris.arrmediatori }); else res.status(400).send(e); diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 8bc5a4f..2bd7edf 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -389,6 +389,7 @@ router.patch('/chval', authenticate, async (req, res) => { const mytable = getTableByTableName(mydata.table); const fieldsvalue = mydata.fieldsvalue; + const unset = mydata.unset; // tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue); @@ -416,6 +417,39 @@ router.patch('/chval', authenticate, async (req, res) => { let index = 0; + let recoldnave = null; + + let myuser = null; + let mydatamsg = {}; + + let flotta = null; + let strflotta = ''; + + if (mydata.table === 'navi') { + if (!!id) { + recoldnave = await mytable.findOne({ _id: ObjectID(id) }); + + let mypos = { + idapp, + riga: recoldnave.riga, + col: recoldnave.col, + numup: 3 + }; + tools.getRigaColByPosUp(mypos); + mydatamsg = { + navemediatore: { riga: mypos.riga, col: mypos.col }, + }; + + if (!!fieldsvalue.riga) { + flotta = await Flotta.getFlottaByRigaColDonatore(idapp, fieldsvalue.riga, fieldsvalue.col); + if (!!flotta) { + strflotta = Flotta.getStrFlotta(flotta); + } + myuser = await User.findByIndOrder(idapp, recoldnave.ind_order); + } + } + } + await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }).then(async (rec) => { // tools.mylogshow(' REC TO MODIFY: ', rec); if (!rec) { @@ -423,24 +457,14 @@ router.patch('/chval', authenticate, async (req, res) => { } else { let addmsg = ''; + if (mydata.table === 'navi' && ('made_gift' in fieldsvalue)) { + if (fieldsvalue['made_gift'] && !rec.received_gift) { if (mydata.tipomsg) { - let mypos = { - idapp, - riga: rec.riga, - col: rec.col, - numup: 3 - }; - tools.getRigaColByPosUp(mypos); - - const myuser = await User.findByIndOrder(idapp, rec.ind_order); if (!!myuser) { - const mydatamsg = { - tipomsg: tools.TipoMsg.SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE, - navemediatore: { riga: mypos.riga, col: mypos.col }, - }; + mydatamsg.tipomsg = tools.TipoMsg.SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE; const rismsg = await telegrambot.getMsgByTipoMsg(mydatamsg, myuser.lang, myuser, false); addmsg = rismsg.body; } @@ -448,6 +472,29 @@ router.patch('/chval', authenticate, async (req, res) => { await mytable.findByIdAndUpdate(id, { $set: { received_gift: true } }); } + + if (!!unset) { + const risunset = await mytable.findByIdAndUpdate(id, { $unset: unset }); + if (!!risunset) { + if ('date_made_gift' in unset) { + addtext = strflotta + ` E' stato annullato l'invio del dono di ${myuser.name} ${myuser.surname} (${myuser.username}) da parte di ${req.user.name} ${req.user.surname} - [Posiz: ${fieldsvalue.riga}.${fieldsvalue.col}]`; + telegrambot.sendMsgTelegramToTheManagers(idapp, addtext, false); + tools.writeFlottaLog(idapp, addtext, flotta.riga, flotta.col_prima); + + if (!!recoldnave) { + if (!!recoldnave.date_made_gift) { + // Se l'utente aveva confermato il Dono, allora gli mando un msg che non è stato ricevuto ... + mydatamsg.tipomsg = tools.TipoMsg.SEND_MSG_DONO_NON_RICEVUTO; + const rismsg = await telegrambot.getMsgByTipoMsg(mydatamsg, myuser.lang, myuser, false); + let mymsg = rismsg.body; + if (!!mymsg) { + await telegrambot.sendMsgTelegram(idapp, myuser.username, mymsg); + } + } + } + } + } + } } // SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE @@ -459,6 +506,9 @@ router.patch('/chval', authenticate, async (req, res) => { await telegrambot.sendMsgTelegram(idapp, mydata.notifBot.un, addmsg); addtext = '[Msg Inviato a ' + mydata.notifBot.un + ']:' + '\n' + mydata.notifBot.txt; telegrambot.sendMsgTelegramToTheManagers(idapp, addtext, true); + + if (!!flotta) + tools.writeFlottaLog(idapp, addtext, flotta.riga, flotta.col_prima); } if (mydata.table === 'users') { @@ -679,6 +729,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { if (!!myusernuovo) { if (!mydata.data.AddImbarco && !!mianavedasost && mianavedasost.ind_order > 0) { + // Controlla prima se è in una Nave Temporanea, allora lo elimina dall'ultima Nave Temporanea miaarrnavi = await Nave.getArrPosizioniByUsername(idapp, username); @@ -704,48 +755,16 @@ router.patch('/callfunz', authenticate, async (req, res) => { if (!!myusernuovo) { if (!!mianavedasost && mianavedasost.ind_order >= 0) { - // Metti campo 'delete': true su ListaIngresso - olduseringresso = await ListaIngresso.findById(mianavedasost.idListaIngresso); - if (!!olduseringresso) { - let fieldsvalue = { - date_deleted: new Date(), - deleted: true - }; - const risul = await ListaIngresso.findByIdAndUpdate(mianavedasost.idListaIngresso, { $set: fieldsvalue }, { new: false }); - if (!!risul) { - const myrecuser = await ListaIngresso.getIngrEUserByFilter(idapp, { - idapp, - username: username_da_sostituire, - _id: ObjectID(mianavedasost.idListaIngresso) - }); + // ELIMINO LA LISTAINGRESSO CHE STO SOSTITUENDO (SOLO SE NON VIENE USATA DA ALTRA NAVE!) + let eliminatoingr = await ListaIngresso.eliminaListaIngresso(idapp, mianavedasost.ind_order, req, mianavedasost.num_tess); - if (!!myrecuser) { - const risdel = await ListaIngresso.deleteOne({ _id: olduseringresso.id }); - - if (!!risdel) { - await actions.doOtherThingsAfterDeleted('listaingressos', myrecuser, false, req) - } - } - } + if (!eliminatoingr){ + return res.send({ code: server_constants.RIS_CODE_ERR, msg: 'La Sostituzione non può avvenire ! Contattare Paolo. (ind_order=' + mianavedasost.ind_order + ')' }); } } } if (!!myuservecchio) { - // Se ha gia delle altre navi, non cancellarlo! - if (!await Nave.checkIfMadeGift(idapp, myuservecchio.username)) { - - if (mydata.data.deleteUser && !!mianavedasost && mianavedasost.ind_order > 0) { - // Metti Deleted allo User - fieldsvalue = { - deleted: true, - date_deleted: new Date(), - }; - await User.findByIdAndUpdate(myuservecchio.id, { $set: fieldsvalue }); - await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuservecchio.name} ${myuservecchio.surname} (${myuservecchio.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); - } - } - if (mydata.data.notifBot) { const mydatamsg = { @@ -766,6 +785,20 @@ router.patch('/callfunz', authenticate, async (req, res) => { } } + // Se ha gia delle altre navi, non cancellarlo! + if (!await Nave.checkIfMadeGift(idapp, myuservecchio.username)) { + + if (mydata.data.deleteUser && !!mianavedasost && mianavedasost.ind_order > 0) { + // Metti Deleted allo User + fieldsvalue = { + deleted: true, + date_deleted: new Date(), + }; + + await User.findByIdAndUpdate(myuservecchio.id, { $set: fieldsvalue }); + await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuservecchio.name} ${myuservecchio.surname} (${myuservecchio.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); + } + } } @@ -791,12 +824,11 @@ router.patch('/callfunz', authenticate, async (req, res) => { } // Togliolo dalla Graduatoria! - const mygrad = await Graduatoria.findOneAndUpdate({ + await Graduatoria.findOneAndUpdate({ idapp, idListaIngresso: myingr._id }, { $set: { ind_order: -1 } }, { new: false }); - // Aggiorna la Nave con il Nuovo fieldsvalue = { ind_order @@ -805,9 +837,9 @@ router.patch('/callfunz', authenticate, async (req, res) => { const dachi = req.user.name + ' ' + req.user.surname; return await Nave.findByIdAndUpdate(mianavedasost.id, { $set: fieldsvalue }) - .then(async (rec) => { + .then(async (nave) => { // tools.mylogshow(' REC TO MODIFY: ', rec); - if (!rec) { + if (!nave) { return res.status(404).send(); } else { @@ -850,10 +882,11 @@ router.patch('/callfunz', authenticate, async (req, res) => { tools.writeManagersLog(mymsg); } - const msgsost = '[NAVE ' + navepersistente.riga + '.' + navepersistente.col + '] Sostituito ' + myuservecchio.username + ' (' + myuservecchio.name + ' ' + myuservecchio.surname + ') ' + ' con -> ' + myusernuovo.username + ' (' + myusernuovo.name + ' ' + myusernuovo.surname + ') ' + ' [da ' + dachi + ']'; + const msgsost = '[NAVE ' + navepersistente.riga + '.' + navepersistente.col + '] Sostituito ' + myuservecchio.username + ' (' + myuservecchio.name + ' ' + myuservecchio.surname + ') ' + ' con -> ' + myusernuovo.username + ' (' + myusernuovo.name + ' ' + myusernuovo.surname + '' + + ') [Posiz. ' + nave.riga + '.' + nave.col + ' ind_order=' + nave.ind_order + '] ' + ' [da ' + dachi + ']'; tools.writeSostituzioniLog(msgsost); tools.writeFlottaLog(idapp, msgsost, mydatamsg.flotta.riga, mydatamsg.flotta.col_prima); - await telegrambot.sendMsgTelegramToTheManagers(idapp, msgsost); + await telegrambot.sendMsgTelegramToTheManagers(idapp, msgsost, false); // const nomecognomeprima = myuser.name + ' ' + myuser.surname + '(' + myuser.username + ')'; // const nomecognomenuovo = await User.getNameSurnameByUsername(idapp,); @@ -894,28 +927,11 @@ router.patch('/callfunz', authenticate, async (req, res) => { if (!!myrec) { const myingr = await ListaIngresso.find({ _id: mydata.data.id }); - // Controlla se ci sono 2 navi - const arrnavi = await Nave.find({ idapp, ind_order: mydata.ind_order }); - let risdel = false; - if (arrnavi.length === 1) { - // Solo 1 nave da cancellare, quindi cancello anche l'ingresso - risdel = await ListaIngresso.deleteOne({ _id: mydata.data.id }); - } else { - // non cancellare la listaingresso (perchè con lo stesso ind_order ho piu navi ! - risdel = true - } + const risdel = await ListaIngresso.eliminaListaIngresso(idapp, mydata.ind_order, req, mydata.data.num_tess); if (risdel) { - return await actions.doOtherThingsAfterDeleted('listaingressos', myrec, false, req) - .then((ris) => { - - if (!!ris) { - - // tools.mylog('DELETED Others things ...'); - return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); - } - }); + return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); } } @@ -981,7 +997,7 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { notifBot = tools.NotifyIfDelRecord(tablename); let myrec = null; - if (!User.isAdmin(req.user.perm) || !User.isManager(req.user.perm)) { + if (!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) { if (tablename === 'users') { let fieldsvalue = { diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index a0dae7a..64708bd 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -136,6 +136,7 @@ router.post('/', async (req, res) => { user.profile.saw_and_accepted = recorig.profile.saw_and_accepted; user.profile.my_dream = recorig.profile.my_dream; user.profile.email_paypal = recorig.profile.email_paypal; + user.profile.revolut = recorig.profile.revolut; user.profile.link_payment = recorig.profile.link_payment; user.profile.note_payment = recorig.profile.note_payment; user.profile.paymenttypes = recorig.profile.paymenttypes; diff --git a/src/server/sendemail.js b/src/server/sendemail.js index 209d64b..230223f 100755 --- a/src/server/sendemail.js +++ b/src/server/sendemail.js @@ -325,9 +325,11 @@ module.exports = { mylocalsconf.dataemail.emailbody = rec.emailbody; mylocalsconf.dataemail.emailtitle = rec.emailtitle; - const replyto = tools.getreplyToEmailByIdApp(idapp); + if (!!mylocalsconf.dataemail.emailtitle && !!mylocalsconf.dataemail.emailbody) { + const replyto = tools.getreplyToEmailByIdApp(idapp); - return this.sendEmail_base('standard', emailto, mylocalsconf, replyto); + return this.sendEmail_base('standard', emailto, mylocalsconf, replyto); + } // Send Email also to the Admin // this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf); diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index c196e75..4d621c4 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -17,6 +17,7 @@ const { MsgTemplate } = require('../models/msg_template'); const emoji = require('node-emoji'); +const { Flotta } = require('../models/flotta'); const i18n = require("i18n"); @@ -557,18 +558,23 @@ module.exports = { msg = msg.replace('{surname}', user.surname); if (!!user.profile.link_payment) msg = msg.replace('{link_paypalme}', user.profile.link_payment); + if (!!user.profile.revolut) + msg = msg.replace('{revolut}', user.profile.revolut); if (!!user.profile.email_paypal) msg = msg.replace('{email_paypal}', user.profile.email_paypal); if (!!user.profile.note_payment) msg = msg.replace('{note_payment}', user.profile.note_payment); } + // const cl = getclTelegByidapp(user.idapp); + msg = msg.replace('{link_chathelp}', tools.HELP_CHAT); + if (!!mydata.flotta) { // SOSTITUISCI LE PAROLE CHIAVI if (!!mydata.flotta.date_start) - msg = msg.replace('{date_start}', tools.getstrDateLong(new Date(mydata.flotta.date_start), user.lang)); + msg = msg.replace('{date_start}', tools.getstrDateLongTot(new Date(mydata.flotta.date_start), user.lang)); if (!!mydata.flotta.date_close) - msg = msg.replace('{date_close}', tools.getstrDateLong(new Date(mydata.flotta.date_close), user.lang)); + msg = msg.replace('{date_close}', tools.getstrDateLongTot(new Date(mydata.flotta.date_close), user.lang)); if (!!mydata.flotta.link_superchat) msg = msg.replace('{link_superchat}', mydata.flotta.link_superchat); if (!!mydata.flotta.tutor1) @@ -581,12 +587,14 @@ module.exports = { msg = msg.replace('{tutorslo}', mydata.flotta.tutorslo); if (!!mydata.flotta.sognatore_nomecognome) msg = msg.replace('{sognatore}', mydata.flotta.sognatore_nomecognome); + if (!!mydata.flotta.sognatore_nomecognome) + msg = msg.replace('{flotta}', mydata.flotta.riga + '.' + Math.ceil(mydata.flotta.col_prima / 8) + ' - ' + mydata.flotta.riga + '.' + Math.ceil(mydata.flotta.col_ultima / 8)); } return { body: msg, title }; }, - sendMsgTelegramToNave: async function (idapp, mydata) { + sendMsgTelegramToNave: async function (idapp, mydata, res) { let nummsgtosend = 0; let nummsgsent = 0; let strout = ''; @@ -596,7 +604,9 @@ module.exports = { try { let arrnavi = null; + let strflotta = ''; if (flotta) { + strflotta = Flotta.getStrFlotta(flotta); arrnavi = await Nave.getusersByFlotta(idapp, flotta.riga, flotta.col_prima, flotta.col_ultima); if (mydata.tipomsg === tools.TipoMsg.SEND_MSG_A_SOGNATORE) { @@ -673,7 +683,8 @@ module.exports = { mytitle = rismsg.title; if (mymsgprimo === '') { - mymsgprimo = mymsg; + if (lang === 'it') + mymsgprimo = mymsg; } if (!!idteleg) { @@ -701,14 +712,18 @@ module.exports = { } if (!mydata.inviareale) { - await this.sendMsgTelegramToTheManagers(idapp, 'TEST INVIO MESSAGGIO:\n' + mymsgprimo + '\n\n(Messaggi da Inviare: ' + nummsgtosend + ')'); + await this.sendMsgTelegram(idapp, res.req.user.username, 'TEST INVIO MESSAGGIO:\n' + mymsgprimo + '\n\n(Messaggi da Inviare: ' + nummsgtosend + ')'); } if ((nummsgsent > 1) && (mydata.inviareale)) { try { let msg = ''; if (!!flotta) { - msg = 'Inviato messaggio a tutta la FLOTTA DA ' + flotta.riga + '.' + flotta.col_prima + ' A ' + flotta.riga + '.' + flotta.col_ultima + ' \n' + mymsg; + if (!!mydata.tipomsg) { + msg = 'Flotta ' + strflotta + '): ' + tools.getStrMsgByTipoMsg(mydata.tipomsg) + '\n' + mymsg ; + } else { + msg = 'Inviato messaggio a tutta la FLOTTA DA ' + flotta.riga + '.' + flotta.col_prima + ' A ' + flotta.riga + '.' + flotta.col_ultima + ' \n' + mymsg; + } } else { msg = 'Inviato messaggio a tutti i Donatori della Nave ' + mydata.navemediatore.riga + '.' + mydata.navemediatore.col + '\n' + mymsg; } @@ -1114,7 +1129,7 @@ class Telegram { } else if (MsgBot.PRINCIPE_AZZURRO.find((rec) => testo.indexOf(rec) > -1)) { risp = 'Chissà... Forse si!\nAnche se meglio averne un\'altro di scorta, nel caso il Principe non sia disponibile.'; } else if (MsgBot.AIUTO.find((rec) => testo.indexOf(rec) > -1)) { - risp = 'Clicca qui per entrare nella Chat AYNI - HELP di Supporto\n' + 'https://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw' + '\n\nI miei colleghi umani ti aiuteranno a risolvere !'; + risp = 'Clicca qui per entrare nella Chat AYNI - HELP di Supporto\n' + tools.HELP_CHAT + '\n\nI miei colleghi umani ti aiuteranno a risolvere !'; } else if (MsgBot.SPOSAMI.find((rec) => testo.indexOf(rec) > -1)) { risp = 'No Grazie! Sono per la Libertà a Vita! ' + emo.JOY + '\nMa se vuoi possiamo conoscerci meglio!' + emo.DANCER + emo.FIRE; } else if (MsgBot.CHE_TEMPO_FA.find((rec) => testo.indexOf(rec) > -1)) { @@ -1524,7 +1539,7 @@ class Telegram { let mystr = ''; if (rec.user) { mystr += printf(tools.get__('INFO_LINK_DA_CONDIVIDERE', this.getlang(msg)), tools.getHostByIdApp(this.idapp) + '/signup/' + rec.user.username); - mystr += tools.ACAPO + tools.ACAPO + printf(tools.get__('INFO_LINK_ZOOM', this.getlang(msg)), tools.getlinkzoom('')); + mystr += tools.ACAPO + tools.ACAPO + printf(tools.get__('INFO_LINK_ZOOM', this.getlang(msg)), tools.getlinkzoom(null)); await this.sendMsg(msg.chat.id, mystr); } } @@ -1566,16 +1581,19 @@ class Telegram { iniziata = (nextzoom._id.toString() === evento._id.toString()); + let lang = this.getlang(msg); + if (iniziata) { - mystr += emo.CHECK_VERDE + ' ' + tools.get__('ZOOM_INIZIATO', this.getlang(msg)) + ' ' + emo.CHECK_VERDE + '\n'; + mystr += emo.CHECK_VERDE + ' ' + tools.get__('ZOOM_INIZIATO', lang) + ' ' + emo.CHECK_VERDE + '\n'; } - mystr += `${emo.EYES} ${tools.getstrDateTimeShort(evento.date_start, this.getlang(msg))} ${emo.EYES}`; - mystr += `\n${evento.title}\n(${evento.note})\n\n`; + mystr += tools.getflagtelegrambyLang(evento.lang) + ` ${emo.EYES} ${tools.getstrDateTimeShort(evento.date_start, this.getlang(msg))} ${emo.EYES}`; + mystr += `\n${evento.title}\n(${evento.note})`; + mystr += `\n${tools.getlinkzoom(evento)}\n\n`; if (nextzoom) { if (iniziata) { mystr += emo.FIRE + tools.get__('CLICCA_ENTRA', this.getlang(msg)) + ' ' + emo.FIRE + '\n'; - mystr += tools.getlinkzoom(evento.id_conf_zoom) + '\n'; + mystr += tools.getlinkzoom(evento) + '\n'; mystr += '\n'; //mystr += pwd + '\n\n'; } @@ -1587,7 +1605,7 @@ class Telegram { if (!nextzoom && index > 1) { mystr += "✨✨✨✨✨✨✨✨✨✨✨✨\n" + - tools.get__('CLICCA_PER_ZOOM', this.getlang(msg)) + ':\n' + tools.getlinkzoom(listazoom[0].id_conf_zoom) + '\n' + "✨✨✨✨✨✨✨✨✨✨✨✨\n"; + tools.get__('CLICCA_PER_ZOOM', this.getlang(msg)) + '\n' + "✨✨✨✨✨✨✨✨✨✨✨✨\n"; } return mystr @@ -1694,7 +1712,7 @@ class Telegram { } else if (qualelink === 'biblio') { return 'https://t.me/joinchat/AAAAAFMDe8b5lB1X7vOYng'; } else if (qualelink === 'help') { - return 'https://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw'; + return tools.HELP_CHAT; } else if (qualelink === 'faq') { return 'https://ayni.gifteconomy.app/faq'; } else if (qualelink === 'empower') { @@ -1997,8 +2015,8 @@ class Telegram { // chiedisino = true; // rec.msgall_status = StatusMSGALL.CONFIRM; FormDaMostrare = this.getInlineKeyboard(lang, [ - { text: Menu[lang].SI, callback_data: InlineCmd.VOGLIO_IMBARCARMI }, - { text: Menu[lang].NO, callback_data: InlineCmd.NON_VOGLIO_IMBARCARMI }, + { text: Menu[lang].SI, callback_data: { action: InlineCmd.VOGLIO_IMBARCARMI, username: utente.username } }, + { text: Menu[lang].NO, callback_data: { action: InlineCmd.NON_VOGLIO_IMBARCARMI, username: utente.username } }, ]); inviaveramente = true; } else { @@ -2301,6 +2319,10 @@ class Telegram { if (!text) return 0; + if (process.env.LOCALE === "1") { + id = '12429864'; + } + if (!!msg_id) { return this.modificaMsg(chat_id, msg_id, text); } @@ -2335,6 +2357,12 @@ class Telegram { text = text.replace(/
/g, "\n"); text = text.replace(/
/g, ""); + text = text.replace(//g, ""); + text = text.replace(//g, ""); + text = text.replace(/

/g, ""); text = text.replace(/<\/div>/g, "\n"); text = text.replace(/ /g, " "); @@ -2589,7 +2617,7 @@ if (!tools.testing()) { const myclTelegram = getclTelegBytoken(bot.token); - const action = callbackQuery.data; + const data = callbackQuery.data; const msg = callbackQuery.message; const opts = { chat_id: msg.chat.id, @@ -2599,22 +2627,23 @@ if (!tools.testing()) { const status = await myclTelegram.setInit(msg); const rec = myclTelegram.getRecInMem(msg); + const user = await User.getUserShortDataByUsername(idapp, data.username); if (!!rec) { - if (!!rec.user) { - if (action === InlineCmd.VOGLIO_IMBARCARMI) { + if (!!user) { + if (data.action === InlineCmd.VOGLIO_IMBARCARMI) { // Controlla se è qualificato! - const mydata = tools.AddDate(rec.user.date_reg, 7); + const mydata = tools.AddDate(user.date_reg, 7); - const newrecingr = await ListaIngresso.addUserInListaIngresso(rec.user.idapp, rec.user.username, rec.user.aportador_solidario, rec.user.lang, true, true, mydata); + const newrecingr = await ListaIngresso.addUserInListaIngresso(user.idapp, user.username, user.aportador_solidario, user.lang, true, true, mydata); - bot.editMessageText(tools.gettranslate('ADDED_TOLISTAINGRESSO', rec.user.lang), opts); + bot.editMessageText(tools.gettranslate('ADDED_TOLISTAINGRESSO', user.lang), opts); - } else if (action === InlineCmd.NON_VOGLIO_IMBARCARMI) { - await User.NonVoglioImbarcarmi(rec.user.idapp, rec.user.username); + } else if (data.action === InlineCmd.NON_VOGLIO_IMBARCARMI) { + await User.NonVoglioImbarcarmi(user.idapp, user.username); - const msgadd = '[' + rec.user.username + '] ' + rec.user.name + ' ' + rec.user.surname + ' ha risposto che NON VUOLE IMBARCARSI !'; + const msgadd = '[' + user.username + '] ' + user.name + ' ' + user.surname + ' ha risposto che NON VUOLE IMBARCARSI !'; - await local_sendMsgTelegramToTheManagers(rec.user.idapp, msgadd, msg, false); // Anche a STAFF + await local_sendMsgTelegramToTheManagers(user.idapp, msgadd, msg, false); // Anche a STAFF } } } diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 8652394..0697fbd 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -82,11 +82,11 @@ textlang = { 'LINEE_GUIDA': 'Accettato le Linee Guida', 'VIDEO_INTRO': 'Visto il Video di AYNI', 'SCRITTO_SOGNO': 'Hai scritto il tuo Sogno', - 'PAYMENTS': 'Modalità di Pagamento (Obbligatorio Paypal)', + 'PAYMENTS': 'Modalità di Pagamento', 'INVITATI': 'persone registrate che hai invitato', 'INVITATI_ATTIVI': 'Invitati con i 7 Requisiti', 'NONREG': 'Invitati non Registrati', - 'CLICCA_PER_ZOOM': 'AL GIORNO E ORA INDICATA, PER ENTRARE NELLA VIDEO-CONFERENZA, CLICCA QUI', + 'CLICCA_PER_ZOOM': 'AL GIORNO E ORA INDICATA, PER ENTRARE NELLA VIDEO-CONFERENZA, CLICCA SUL LINK INDICATO', 'CLICCA_ENTRA': 'CLICCA QUI PER ENTRARE !', 'ZOOM_INIZIATO': 'QUESTA CONFERENZA E\' INIZIATA!', 'SCEGLI_VOCE': 'scegli una voce:', @@ -107,9 +107,9 @@ textlang = { 'NAVE COMPLETATA': 'NAVE COMPLETATA', 'Doni Effettuati': 'Doni Effettuati', 'Tutor che affianchèra il Mediatore': 'Tutor che affianchèra il Mediatore', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura GIFT CHAT\n%s Chiusura GIFT CHAT\nNota Bene: Hai tempo 4 giorni dall\'apertura per entrare in Chat ed effettuare il tuo Dono, dopodichè effettueremo la sostituzione.', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura GIFT CHAT\n%s Chiusura GIFT CHAT\nNota Bene: Hai tempo 3 giorni dall\'apertura per entrare in Chat ed effettuare il tuo Dono, dopodichè effettueremo la sostituzione.', 'Giorno di Apertura GIFT CHAT': 'Giorno di Apertura GIFT CHAT', - 'Giorno in cui Inviare il DONO': 'Hai 4 giorni di tempo per inviare il tuo dono.\nGiorno di Chiusura', + 'Giorno in cui Inviare il DONO': 'Hai 3 giorni di tempo per inviare il tuo dono.\nGiorno di Chiusura', 'SPOSTATO': 'Sei stato Spostato in una Nuova Nave !', 'Note': 'Note', 'TEMPORANEA': 'TEMPORANEA', @@ -153,7 +153,7 @@ textlang = { 'LINEE_GUIDA': 'Sprejemam pogoje poslovanja', 'VIDEO_INTRO': 'Pogledal sem video AYNI', 'SCRITTO_SOGNO': 'Sem zapisal Sanje', - 'PAYMENTS': 'Načini Plačila (Obvezen Paypal)', + 'PAYMENTS': 'Načini Plačila', 'INVITATI': 'registrirane osebe, ki si povabil', 'INVITATI_ATTIVI': 'Povabljenci s 7 Zahtevami', 'NONREG': 'Neregistrirani povabljenci', @@ -177,7 +177,7 @@ textlang = { 'NAVE COMPLETATA': 'LADJE DOSTAVLJEN', 'Doni Effettuati': 'Darila narejena', 'Tutor che affianchèra il Mediatore': 'Tutor, ki bo podpiral Mediatorja', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura GIFT CHAT\n%s Zapiranje DARILNEGA KLEPETA\nBodi pozoren: Časa imaš 4 dni od odprtja za vstop v Klepet- ladjico in izpeljati svoje Vplačilo, po tem času bomo izvedli zamenjavo', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura GIFT CHAT\n%s Zapiranje DARILNEGA KLEPETA\nBodi pozoren: Časa imaš 3 dni od odprtja za vstop v Klepet- ladjico in izpeljati svoje Vplačilo, po tem času bomo izvedli zamenjavo', 'SPOSTATO': 'Prestavljen si v Novo Ladjico !', 'Note': 'Opombe', 'TEMPORANEA': 'ZAČASNA', @@ -219,7 +219,7 @@ textlang = { 'LINEE_GUIDA': 'Directrices aceptadas', 'VIDEO_INTRO': 'Ver el video de AYNI', 'SCRITTO_SOGNO': 'Escribiste tu sueño', - 'PAYMENTS': 'Métodos de pago (Paypal obligatorio)', + 'PAYMENTS': 'Métodos de pago', 'INVITATI': 'las personas registradas que usted invitó', 'INVITATI_ATTIVI': 'Invitado con los 7 requisitos', 'NONREG': 'Invitados no registrados', @@ -243,7 +243,7 @@ textlang = { 'NAVE COMPLETATA': 'NAVE COMPLETADA', 'Doni Effettuati': 'Regalos Realizados', 'Tutor che affianchèra il Mediatore': 'Tutor de apoyo al Donante', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura del CHAT DE REGALOS\n%s Cierre del CHAT DE REGALOS\nNota: Tienes 4 días desde la apertura para entrar en el Chat y hacer tu Regalo, después de lo cual haremos el reemplazo', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Apertura del CHAT DE REGALOS\n%s Cierre del CHAT DE REGALOS\nNota: Tienes 3 días desde la apertura para entrar en el Chat y hacer tu Regalo, después de lo cual haremos el reemplazo', 'SPOSTATO': 'Has sido trasladado a una nueva nave !', 'Note': 'Notas', 'TEMPORANEA': 'TEMPORAL', @@ -282,7 +282,7 @@ textlang = { 'LINEE_GUIDA': 'Guidelines Accepted', 'VIDEO_INTRO': 'Seen the AYNI Video', 'SCRITTO_SOGNO': 'You wrote your Dream', - 'PAYMENTS': 'Methods of Payment (Mandatory Paypal)', + 'PAYMENTS': 'Methods of Payment', 'INVITATI': 'registered people you invited', 'INVITATI_ATTIVI': 'Guests with the 7 Requirements', 'NONREG': 'Non-registered Guests', @@ -306,7 +306,7 @@ textlang = { 'NAVE COMPLETATA': 'SHIP COMPLETED', 'Doni Effettuati': 'Gifts Made', 'Tutor che affianchèra il Mediatore': 'Tutor supporting the Mediator', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Opening GIFT CHAT\n%s Closing GIFT CHAT\nNote: You have 4 days from the opening to enter the Chat and make your Gift, after which we will make the replacement.', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Opening GIFT CHAT\n%s Closing GIFT CHAT\nNote: You have 3 days from the opening to enter the Chat and make your Gift, after which we will make the replacement.', 'SPOSTATO': 'You\'ve been moved to a New Ship !', 'Note': 'Note', 'TEMPORANEA': 'TEMPORARY', @@ -349,7 +349,7 @@ textlang = { 'LINEE_GUIDA': 'Lignes directrices acceptées', 'VIDEO_INTRO': 'Voir la vidéo AYNI', 'SCRITTO_SOGNO': 'Vous avez écrit votre rêve', - 'PAYMENTS': 'Modes de paiement (Paypal obligatoire)', + 'PAYMENTS': 'Modes de paiement', 'INVITATI': 'personnes inscrites que vous avez invitées', 'INVITATI_ATTIVI': 'Invité avec les 7 exigences', 'NONREG': 'Invités non enregistrés', @@ -373,7 +373,7 @@ textlang = { 'NAVE COMPLETATA': 'NAVIRE COMPLÉTÉ', 'Doni Effettuati': 'Don effectués', 'Tutor che affianchèra il Mediatore': 'Le tuteur qui soutient le Mediateur', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s : Chat d\'ouverture\n%s Clôture du GIFT CHAT\nNote: Vous avez 4 jours à partir de l\'ouverture pour entrer dans le Chat et faire votre Cadeau, après quoi nous ferons le remplacement', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s : Chat d\'ouverture\n%s Clôture du GIFT CHAT\nNote: Vous avez 3 jours à partir de l\'ouverture pour entrer dans le Chat et faire votre Cadeau, après quoi nous ferons le remplacement', 'SPOSTATO': 'Vous avez été transféré sur un nouveau navire !', 'Note': 'Notes', 'TEMPORANEA': 'TEMPORAIRE', @@ -416,7 +416,7 @@ textlang = { 'LINEE_GUIDA': 'Directrizes Aceites', 'VIDEO_INTRO': 'Ver o vídeo do AYNI', 'SCRITTO_SOGNO': 'Você escreveu o seu sonho', - 'PAYMENTS': 'Formas de pagamento (Obrigatório Paypal)', + 'PAYMENTS': 'Formas de pagamento', 'INVITATI': 'pessoas registadas que convidou', 'INVITATI_ATTIVI': 'Convidado com os 7 Requisitos', 'NONREG': 'Convidados não registados', @@ -440,7 +440,7 @@ textlang = { 'NAVE COMPLETATA': 'NAVIO COMPLETADO', 'Doni Effettuati': 'Regalo Feitos', 'Tutor che affianchèra il Mediatore': 'Tutor que apoia o Mediator', - 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Abertura do GIFT CHAT\n%s Fechamento GIFT CHAT\nNota: Você tem 4 dias desde a abertura para entrar no Chat e fazer o seu Presente, depois do qual faremos o substituição.', + 'APERTURA_CHIUSURA_GIFT_CHAT': '%s: Abertura do GIFT CHAT\n%s Fechamento GIFT CHAT\nNota: Você tem 3 dias desde a abertura para entrar no Chat e fazer o seu Presente, depois do qual faremos o substituição.', 'SPOSTATO': 'Você foi transferido para um novo navio !', 'Note': 'Notas', 'TEMPORANEA': 'TEMPORÁRIO', @@ -463,6 +463,10 @@ module.exports = { AYNI: '7', SIP: '9', + HELP_CHAT: 'https://t.me/joinchat/AL2qKE80rxDkgbeMGO-0bw', + TYPECONF_ZOOM: 'zoom', + TYPECONF_JITSI: 'jitsi', + APORTADOR_NONE: '------', TYPE_PROJECT: 1, @@ -479,6 +483,7 @@ module.exports = { SEND_MSG_A_SOGNATORE: 1020, SEND_MSG_A_UTENTE_SOSTITUITO: 1030, SEND_MSG_DONO_RICEVUTO_CORRETTAMENTE: 1040, + SEND_MSG_DONO_NON_RICEVUTO: 1050, }, Placca: { @@ -1258,7 +1263,7 @@ module.exports = { return n }, - getWeekDayByLang(date, lang) { + getWeekDayByLangByNumCar(date, lang, num) { if (!lang) lang = 'it'; @@ -1272,9 +1277,21 @@ module.exports = { pt: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'], de: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], si: ['Nedelja', 'Ponedeljek', 'Torek', 'Sreda', 'četrtek', 'Petek', 'Sobota'], - } + }; - return isNaN(dayOfWeek) ? '' : myday[lang][dayOfWeek].substring(0, 3) + if (num > 0) { + return isNaN(dayOfWeek) ? '' : myday[lang][dayOfWeek].substring(0, num) + } else { + return isNaN(dayOfWeek) ? '' : myday[lang][dayOfWeek] + } + }, + + getWeekDayByLang(date, lang) { + return this.getWeekDayByLangByNumCar(date, lang, 3) + }, + + getWeekDayByLangTot(date, lang) { + return this.getWeekDayByLangByNumCar(date, lang, 0) }, getWeekDay(date) { @@ -1315,6 +1332,15 @@ module.exports = { } }, + getstrDateLongTot(mydate, lang) { + if (mydate) { + // console.log('getstrDate', mytimestamp) + return this.getWeekDayByLangTot(mydate, lang) + ' ' + this.appendLeadingZeroes(mydate.getDate()) + '/' + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + mydate.getFullYear(); + } else { + return ''; + } + }, + getstrDateLongFile(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) @@ -1324,10 +1350,27 @@ module.exports = { } }, - getlinkzoom(idconf) { - if (idconf === '') - idconf = '6668882000'; - return 'https://zoom.us/j/' + idconf + getlinkzoom(rec) { + if (rec === null) { + rec = { + typeconf: this.TYPECONF_ZOOM, + id_conf_zoom: '', + } + } + let typeconf = rec.typeconf; + if (typeconf === '') + typeconf = this.TYPECONF_ZOOM; + + let mylink = 'https://zoom.us/j/'; + if (typeconf === this.TYPECONF_JITSI) + mylink = 'https://meet.jit.si/'; + + if (rec.id_conf_zoom === '') { + rec.id_conf_zoom = '6668882000'; + } + + return mylink + rec.id_conf_zoom + }, getmd5(mystr) { @@ -1417,9 +1460,9 @@ module.exports = { readlogfile(idapp, filename) { - try{ + try { return fs.readFileSync(idapp + '/' + filename, 'utf8'); - }catch (e) { + } catch (e) { return ''; } }, @@ -1666,6 +1709,21 @@ module.exports = { mystr = 'Inviato Messaggio Dono Ricevuto Correttamente'; return mystr; + }, + + getflagtelegrambyLang(lang) { + if (lang === 'it') + return '🇮🇹'; + else if (lang === 'si') + return '🇸🇮'; + else if (lang === 'es') + return '🇪🇸'; + else if (lang === 'enUs') + return '🇬🇧'; + else if (lang === 'uk') + return '🇬🇧'; + else if (lang === 'fr') + return '🇫🇷'; } From 7dc4e4454d68a914b2b2ae2d318ec4d505bbc20d Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Sat, 4 Jul 2020 11:03:16 +0200 Subject: [PATCH 08/14] Sistemazioni... --- {docs => documentation}/passi.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {docs => documentation}/passi.txt (100%) diff --git a/docs/passi.txt b/documentation/passi.txt similarity index 100% rename from docs/passi.txt rename to documentation/passi.txt From 2a11673113bc040d0e0aca706ef68d3def4b2682 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Sat, 11 Jul 2020 17:10:19 +0200 Subject: [PATCH 09/14] Sistemazioni... --- docs/note.txt | 1 - documentation/passi.txt | 14 +++++++++----- src/server/router/index_router.js | 2 ++ src/server/telegram/telegrambot.js | 6 +++--- 4 files changed, 14 insertions(+), 9 deletions(-) delete mode 100644 docs/note.txt diff --git a/docs/note.txt b/docs/note.txt deleted file mode 100644 index dbea10b..0000000 --- a/docs/note.txt +++ /dev/null @@ -1 +0,0 @@ -TiziCaso 6 IDTELEG 989199479 diff --git a/documentation/passi.txt b/documentation/passi.txt index 9b4c8c8..429b72a 100644 --- a/documentation/passi.txt +++ b/documentation/passi.txt @@ -7,6 +7,14 @@ // ++Todo: PRIORITA' ALTA: +- Errore durante la sostituzione... + +- far pagare direttamente al Sognatore. +- Il dono al Fondo, fallo fare a prescindere (non al 57¨ dono). + +- Se sostituisco mi da sempre la stessa persona. + + - Togliere i Video e il Sogno. (5 requisiti) - Cestino di ELIMINA non funziona !! @@ -17,11 +25,7 @@ - 7.64 : NATALINA NON HA LA RITESSITURA !! - -- 1403 : Kukovič - ha tutto disattivato, mentre non è vero. -- 1344: Piera La Porta - ha tutto attivo invece non ha niente... + - Controllare che ci sono registrazioni doppie !! (stesso username e stessa email!) - SubAccount: filtro. diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 2bd7edf..c760cb2 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -694,6 +694,8 @@ router.patch('/callfunz', authenticate, async (req, res) => { const idapp = req.body.idapp; const mydata = req.body.data; + const telegrambot = require('../telegram/telegrambot'); + try { let entra = false; if (mydata.myfunc === shared_consts.CallFunz.AGGIUNGI_NUOVO_IMBARCO || diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 4d621c4..86ef408 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -2418,9 +2418,9 @@ class Telegram { async sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec) { - if (text.length > 4096) { - let text1 = text.slice(0, 4096); - let text2 = text.slice(4096, text.length); + if (text.length > 4090) { + let text1 = text.slice(0, 4090); + let text2 = text.slice(4090, text.length); await this._inviaMsg(id, text1, form, menu, msg_id, chat_id, ripr_menuPrec); return await this._inviaMsg(id, text2, form, menu, msg_id, chat_id, ripr_menuPrec); } else { From 650fddc2770cb81ed8b02a9d089a843928d0a3ad Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Mon, 13 Jul 2020 23:35:05 +0200 Subject: [PATCH 10/14] Attacco SPAM --- src/server/models/user.js | 13 ++++++++++ src/server/router/users_router.js | 36 +++++++++++++++++++++++++-- src/server/telegram/telegrambot.js | 26 +++++++++++++------ src/server/tools/general.js | 37 ++++++++++++++++++++++++++-- src/server/tools/server_constants.js | 2 ++ 5 files changed, 102 insertions(+), 12 deletions(-) diff --git a/src/server/models/user.js b/src/server/models/user.js index f0fecb1..a7658cf 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -2174,6 +2174,19 @@ UserSchema.statics.convSubAccount = async function (idapp) { return { num }; }; + +UserSchema.statics.getLastRec = async function (idapp) { + const User = this; + + lastrec = await User.find({ idapp }).sort({ date_reg: -1 }).limit(1); + if (!!lastrec) { + return lastrec[0]; + } else { + return null; + } +}; + + UserSchema.statics.DbOp = async function (idapp, mydata) { const User = this; try { diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 64708bd..9e6795a 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -58,18 +58,50 @@ router.post('/', async (req, res) => { body.email = body.email.toLowerCase(); const user = new User(body); + user.ipaddr = tools.getiPAddressUser(req); // tools.mylog("LANG PASSATO = " + user.lang, "IDAPP", user.idapp); + if (!tools.isAlphaNumeric(body.username)) { + await tools.snooze(5000); + res.status(400).send({ code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: '' }); + return 1; + } + + if (tools.blockwords(body.username)) { + tools.writeIPToBan(user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.surname); + await tools.snooze(100000); + res.status(400).send({ code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: '' }); + return 1; + } + + user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username); user.verified_email = false; - user.ipaddr = tools.getiPAddressUser(req); user.lasttimeonline = new Date(); user.date_reg = new Date(); user.aportador_iniziale = user.aportador_solidario; - if (user.idapp === tools.AYNI) { + /* if (user.idapp === tools.AYNI) { user.profile.paymenttypes = ['paypal']; + } */ + + // Controlla se anche l'ultimo record era dallo stesso IP: + const lastrec = await User.getLastRec(body.idapp); + if (!!lastrec) { + if (lastrec.ipaddr === user.ipaddr) { + // Se l'ha fatto troppo ravvicinato + if (lastrec.date_reg) { + let ris = tools.isdiffSecDateLess(lastrec.date_reg, 120); + if (ris) { + tools.writeIPToBan(user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.surname); + await tools.snooze(10000); + res.status(400).send({ code: server_constants.RIS_CODE_BANIP, msg: '' }); + return 1; + } + } + } } + // user.perm = 3; if (tools.testing()) { user.verified_email = true; diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 86ef408..0e15d61 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -530,7 +530,7 @@ module.exports = { getMsgByTipoMsg: async function (mydata, lang, user, sonosognatore) { if (!!mydata.msgextra) { - return { body: mydata.msgextra, title: ''} ; + return { body: mydata.msgextra, title: '' }; } let title = ''; @@ -696,7 +696,10 @@ module.exports = { if (mydata.inviaemail && !!user.email) { // user.email = 'paolo.arena77@gmail.com'; - await sendemail.sendEmail_ByText(user.lang, user.email, user, idapp, {emailbody: mymsg, emailtitle: mytitle}); + await sendemail.sendEmail_ByText(user.lang, user.email, user, idapp, { + emailbody: mymsg, + emailtitle: mytitle + }); strout += ' -> (EMAIL OK)'; } @@ -720,7 +723,7 @@ module.exports = { let msg = ''; if (!!flotta) { if (!!mydata.tipomsg) { - msg = 'Flotta ' + strflotta + '): ' + tools.getStrMsgByTipoMsg(mydata.tipomsg) + '\n' + mymsg ; + msg = 'Flotta ' + strflotta + '): ' + tools.getStrMsgByTipoMsg(mydata.tipomsg) + '\n' + mymsg; } else { msg = 'Inviato messaggio a tutta la FLOTTA DA ' + flotta.riga + '.' + flotta.col_prima + ' A ' + flotta.riga + '.' + flotta.col_ultima + ' \n' + mymsg; } @@ -1356,14 +1359,15 @@ class Telegram { if (user) { let ispaypal = false; if (!!user.profile.paymenttypes) { - if (user.profile.paymenttypes.includes('paypal')) { + /*if (user.profile.paymenttypes.includes('paypal')) { if (user.profile.email_paypal) { ispaypal = true } - } + }*/ + if (!!user.profile) if (!!user.profile.paymenttypes) { - return (user.profile.paymenttypes.length >= 1) && ispaypal; + return (user.profile.paymenttypes.length >= 1); } } @@ -2015,8 +2019,14 @@ class Telegram { // chiedisino = true; // rec.msgall_status = StatusMSGALL.CONFIRM; FormDaMostrare = this.getInlineKeyboard(lang, [ - { text: Menu[lang].SI, callback_data: { action: InlineCmd.VOGLIO_IMBARCARMI, username: utente.username } }, - { text: Menu[lang].NO, callback_data: { action: InlineCmd.NON_VOGLIO_IMBARCARMI, username: utente.username } }, + { + text: Menu[lang].SI, + callback_data: { action: InlineCmd.VOGLIO_IMBARCARMI, username: utente.username } + }, + { + text: Menu[lang].NO, + callback_data: { action: InlineCmd.NON_VOGLIO_IMBARCARMI, username: utente.username } + }, ]); inviaveramente = true; } else { diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 0697fbd..0c7be4e 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -26,6 +26,7 @@ const FILELOG = 'filelog.txt'; const FILEEVENTS = 'logevents.txt'; const FILEMANAGERS = 'logmanagers.txt'; const FILESOSTITUZIONI = 'log_sostituzioni.txt'; +const FILEIP_TO_BAN = 'log_iptoban.txt'; const FILENAVE = 'logNave.txt'; const subject = process.env.URLBASE_APP1; const publicVapidKey = process.env.PUBLIC_VAPI_KEY; @@ -1164,6 +1165,14 @@ module.exports = { return mydate }, + isdiffSecDateLess(mydatediffstr, secs) { + let mydate = new Date(); + // console.log('mydate', mydate); + let mydata2 = new Date(mydatediffstr); + let ris = ((mydate.getTime() - mydata2.getTime()) / 1000); + return (ris < secs); + }, + AddDate(mydate, days) { let date = new Date(mydate); date.setTime(date.getTime() + days * 86400000); @@ -1483,6 +1492,10 @@ module.exports = { this.writelogfile(mystr, FILESOSTITUZIONI); }, + writeIPToBan(mystr) { + this.writelogfile(mystr, FILEIP_TO_BAN); + }, + writeFlottaLog(idapp, mystr, riga, col) { this.mkdirpath(idapp + '/'); this.writelogfile(mystr, idapp + '/' + riga + '_' + col + '.txt'); @@ -1724,7 +1737,27 @@ module.exports = { return '🇬🇧'; else if (lang === 'fr') return '🇫🇷'; + }, + + blockwords(mystr) { + if (mystr.includes('ttp')) { + return true; + } + + return false; + }, + + isAlphaNumeric(str) { + let code, i, len; + + for (i = 0, len = str.length; i < len; i++) { + code = str.charCodeAt(i); + if (!(code > 47 && code < 58) && // numeric (0-9) + !(code > 64 && code < 91) && // upper alpha (A-Z) + !(code > 96 && code < 123)) { // lower alpha (a-z) + return false; + } + } + return true; } - - }; diff --git a/src/server/tools/server_constants.js b/src/server/tools/server_constants.js index 7ce747b..4297710 100755 --- a/src/server/tools/server_constants.js +++ b/src/server/tools/server_constants.js @@ -9,6 +9,8 @@ module.exports = Object.freeze({ RIS_CODE_USER_NOT_THIS_APORTADOR: -75, RIS_CODE_USER_EXTRALIST_NOTFOUND: -70, RIS_CODE_USERNAME_ALREADY_EXIST: -60, + RIS_CODE_USERNAME_NOT_VALID: -65, + RIS_CODE_BANIP: -63, RIS_CODE_EMAIL_ALREADY_EXIST: -50, RIS_CODE_USER_ALREADY_EXIST: -48, RIS_CODE_EMAIL_NOT_EXIST: -45, From 6b7f2b36d1e701d0016b51b603b25f3f50c4e3e9 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Fri, 4 Sep 2020 00:06:49 +0200 Subject: [PATCH 11/14] Payeer e AdvCash --- .env.old | 0 docs/query_mongodb.js | 0 documentation/passi.txt | 6 +- emails/admin/registration/esEs/html.pug | 0 emails/admin/registration/esEs/subject.pug | 0 emails/registration/it/textold.pug | 0 src/server/locales/enUs.json | 0 src/server/locales/fr.json | 0 src/server/locales/pt.json | 0 src/server/locales/si.json | 0 src/server/models/flotta.js | 8 + src/server/models/listaingresso.js | 1 + src/server/models/nave.js | 4 + src/server/models/navepersistente.js | 8 + src/server/models/user.js | 233 ++++++++++++++++++++- src/server/router/api/actions.js | 6 +- src/server/router/index_router.js | 104 +++------ src/server/router/site_router.js | 2 +- src/server/router/users_router.js | 15 +- src/server/telegram/telegrambot.js | 112 ++++++++-- src/server/tools/general.js | 34 ++- src/server/tools/shared_nodejs.js | 3 + 22 files changed, 425 insertions(+), 111 deletions(-) mode change 100644 => 100755 .env.old mode change 100644 => 100755 docs/query_mongodb.js mode change 100644 => 100755 documentation/passi.txt mode change 100644 => 100755 emails/admin/registration/esEs/html.pug mode change 100644 => 100755 emails/admin/registration/esEs/subject.pug mode change 100644 => 100755 emails/registration/it/textold.pug mode change 100644 => 100755 src/server/locales/enUs.json mode change 100644 => 100755 src/server/locales/fr.json mode change 100644 => 100755 src/server/locales/pt.json mode change 100644 => 100755 src/server/locales/si.json diff --git a/.env.old b/.env.old old mode 100644 new mode 100755 diff --git a/docs/query_mongodb.js b/docs/query_mongodb.js old mode 100644 new mode 100755 diff --git a/documentation/passi.txt b/documentation/passi.txt old mode 100644 new mode 100755 index 429b72a..366976e --- a/documentation/passi.txt +++ b/documentation/passi.txt @@ -7,6 +7,8 @@ // ++Todo: PRIORITA' ALTA: +- Togliere gli imbarchi: far pagare subito la persona. + - Errore durante la sostituzione... - far pagare direttamente al Sognatore. @@ -23,9 +25,9 @@ QUINDI QUALCUNO HA PRESO IL SUO POSTO. - - 7.64 : NATALINA NON HA LA RITESSITURA !! +- 7.64 : NATALINA NON HA LA RITESSITURA !! - - Controllare che ci sono registrazioni doppie !! (stesso username e stessa email!) +- Controllare che ci sono registrazioni doppie !! (stesso username e stessa email!) - SubAccount: filtro. diff --git a/emails/admin/registration/esEs/html.pug b/emails/admin/registration/esEs/html.pug old mode 100644 new mode 100755 diff --git a/emails/admin/registration/esEs/subject.pug b/emails/admin/registration/esEs/subject.pug old mode 100644 new mode 100755 diff --git a/emails/registration/it/textold.pug b/emails/registration/it/textold.pug old mode 100644 new mode 100755 diff --git a/src/server/locales/enUs.json b/src/server/locales/enUs.json old mode 100644 new mode 100755 diff --git a/src/server/locales/fr.json b/src/server/locales/fr.json old mode 100644 new mode 100755 diff --git a/src/server/locales/pt.json b/src/server/locales/pt.json old mode 100644 new mode 100755 diff --git a/src/server/locales/si.json b/src/server/locales/si.json old mode 100644 new mode 100755 diff --git a/src/server/models/flotta.js b/src/server/models/flotta.js index c24375f..539784f 100755 --- a/src/server/models/flotta.js +++ b/src/server/models/flotta.js @@ -81,6 +81,12 @@ const FlottaSchema = new mongoose.Schema({ revolut: { type: String, }, + payeer_id: { + type: String, + }, + advcash_id: { + type: String, + }, note_payment: { type: String, }, @@ -114,6 +120,8 @@ function getQueryProj(myfilter) { username: 1, 'profile.paymenttypes': 1, 'profile.email_paypal': 1, + 'profile.payeer_id': 1, + 'profile.advcash_id': 1, 'profile.revolut': 1, 'profile.cell': 1, made_gift: 1, diff --git a/src/server/models/listaingresso.js b/src/server/models/listaingresso.js index 489eff1..ac81522 100755 --- a/src/server/models/listaingresso.js +++ b/src/server/models/listaingresso.js @@ -254,6 +254,7 @@ ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, user if (!nuovo) { listaingresso = await ListaIngresso.findByUsernameETess(idapp, username, 1); } + // listaingresso = null; // TOGLIEREE if (!listaingresso) { listaingresso = new ListaIngresso({ _id: new ObjectID(), diff --git a/src/server/models/nave.js b/src/server/models/nave.js index 105c46c..e04a9a0 100755 --- a/src/server/models/nave.js +++ b/src/server/models/nave.js @@ -447,6 +447,8 @@ function getQueryProj(myfilter) { 'profile.teleg_id': 1, 'profile.nationality': 1, 'profile.email_paypal': 1, + 'profile.payeer_id': 1, + 'profile.advcash_id': 1, 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, @@ -1500,6 +1502,8 @@ NaveSchema.statics.getFlotta = async function (idapp, riga, col_prima, col_ultim if (!!usersognatore) { flotta.link_payment = usersognatore.profile.link_payment; flotta.email_paypal = usersognatore.profile.email_paypal; + flotta.payeer_id = usersognatore.profile.payeer_id; + flotta.advcash_id = usersognatore.profile.advcash_id; flotta.revolut = usersognatore.profile.revolut; flotta.note_payment = usersognatore.profile.note_payment; } diff --git a/src/server/models/navepersistente.js b/src/server/models/navepersistente.js index f44dc2a..3442abe 100755 --- a/src/server/models/navepersistente.js +++ b/src/server/models/navepersistente.js @@ -448,11 +448,15 @@ NavePersistenteSchema.statics.aggiornaFlottaByNavePersistente = async function ( if (nuovo) { myflotta.email_paypal = ''; + myflotta.payeer_id = ''; + myflotta.advcash_id = ''; myflotta.revolut = ''; myflotta.link_payment = ''; myflotta.note_payment = ''; if (!!sognatore) { myflotta.email_paypal = sognatore.profile.email_paypal; + myflotta.payeer_id = sognatore.profile.payeer_id; + myflotta.advcash_id = sognatore.profile.advcash_id; myflotta.revolut = sognatore.profile.revolut; myflotta.link_payment = sognatore.profile.link_payment; myflotta.note_payment = sognatore.profile.note_payment; @@ -462,6 +466,10 @@ NavePersistenteSchema.statics.aggiornaFlottaByNavePersistente = async function ( if (!!sognatore) { if (!myflotta.email_paypal) myflotta.email_paypal = sognatore.profile.email_paypal; + if (!myflotta.payeer_id) + myflotta.payeer_id = sognatore.profile.payeer_id; + if (!myflotta.advcash_id) + myflotta.advcash_id = sognatore.profile.advcash_id; if (!myflotta.revolut) myflotta.revolut = sognatore.profile.revolut; if (!myflotta.link_payment) diff --git a/src/server/models/user.js b/src/server/models/user.js index a7658cf..3954c8f 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -19,6 +19,8 @@ const { ObjectID } = require('mongodb'); const shared_consts = require('../tools/shared_nodejs'); const queryclass = require('../classes/queryclass'); +const telegrambot = require('../telegram/telegrambot'); + mongoose.Promise = global.Promise; mongoose.level = "F"; @@ -185,6 +187,12 @@ const UserSchema = new mongoose.Schema({ email_paypal: { type: String }, + payeer_id: { + type: String + }, + advcash_id: { + type: String + }, revolut: { type: String }, @@ -222,6 +230,9 @@ const UserSchema = new mongoose.Schema({ saw_zoom_presentation: { type: Boolean }, + ask_zoom_partecipato: { + type: Boolean + }, qualified: { type: Boolean }, @@ -296,6 +307,36 @@ UserSchema.statics.setPermissionsById = function (id, perm) { }; +UserSchema.statics.setZoomPresenza = async function (idapp, id, presenza) { + const User = this; + + const telegrambot = require('../telegram/telegrambot'); + + let allData = {}; + allData.myuser = await User.getUserById(idapp, id); + 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 User.findByIdAndUpdate(id, { $set: { 'profile.ask_zoom_partecipato': false } }) + .then((user) => { + + + User.checkIfSbloccatiRequisiti(idapp, allData, id); + }); + }); + +}; + UserSchema.statics.isAdmin = function (perm) { try { return ((perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin); @@ -320,6 +361,14 @@ UserSchema.statics.isTraduttrici = function (perm) { } }; +UserSchema.statics.isZoomeri = function (perm) { + try { + return ((perm & shared_consts.Permissions.Zoomeri) === shared_consts.Permissions.Zoomeri); + } catch (e) { + return false + } +}; + UserSchema.statics.isTutor = function (perm) { try { return ((perm & shared_consts.Permissions.Tutor) === shared_consts.Permissions.Tutor); @@ -454,10 +503,13 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) verified_email: 1, 'profile.teleg_id': 1, 'profile.saw_zoom_presentation': 1, + 'profile.ask_zoom_partecipato': 1, 'profile.qualified': 1, 'profile.qualified_2invitati': 1, 'profile.saw_and_accepted': 1, 'profile.email_paypal': 1, + 'profile.payeer_id': 1, + 'profile.advcash_id': 1, 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, @@ -505,10 +557,13 @@ UserSchema.statics.getDownlineByUsername = async function (idapp, username, incl verified_email: 1, 'profile.teleg_id': 1, 'profile.saw_zoom_presentation': 1, + 'profile.ask_zoom_partecipato': 1, 'profile.qualified': 1, 'profile.qualified_2invitati': 1, 'profile.saw_and_accepted': 1, 'profile.email_paypal': 1, + 'profile.payeer_id': 1, + 'profile.advcash_id': 1, 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, @@ -587,16 +642,14 @@ UserSchema.statics.getQueryQualified = function () { 'profile.teleg_id': { $gt: 1 }, 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED, 'profile.saw_zoom_presentation': true, - 'profile.my_dream': { $exists: true }, $or: [ + { 'profile.link_payment': { $exists: true } }, { 'profile.email_paypal': { $exists: true } }, + { 'profile.payeer_id': { $exists: true } }, + { 'profile.advcash_id': { $exists: true } }, { 'profile.revolut': { $exists: true } }, ], // 'profile.paymenttypes': { "$in": ['paypal'] }, - $and: [ - { "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } }, - // { "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } } - ], // $where: "this.profile.paymenttypes.length >= 1", }] } @@ -700,6 +753,7 @@ UserSchema.statics.isUserQualified9 = async function (idapp, username) { }; +/* UserSchema.statics.getnumPaymentOk = function (idapp) { const User = this; @@ -719,6 +773,7 @@ UserSchema.statics.getnumPaymentOk = function (idapp) { ] }); }; +*/ UserSchema.statics.getUsersNationalityQuery = function (idapp) { const query = [ @@ -1148,6 +1203,8 @@ UserSchema.statics.getRecByIndOrder = async function (idapp, ind_order) { surname: 1, 'profile.teleg_id': 1, 'profile.email_paypal': 1, + 'profile.payeer_id': 1, + 'profile.advcash_id': 1, 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, @@ -1184,6 +1241,33 @@ UserSchema.statics.getusersManagers = async function (idapp) { }); }; +UserSchema.statics.getusersManagersAndZoomeri = async function (idapp) { + const User = this; + + return await User.find( + { + idapp, + or: [ + { 'profile.manage_telegram': true }, + { + perm: + { + $bit: + + Number(shared_consts.Permissions.Zoomeri) + + } + } + ], + }, + { 'profile.teleg_id': 1 }) + .then((arrrec) => { + return (!!arrrec) ? arrrec : null; + }).catch((e) => { + console.error('getusersManagers', e); + }); +}; + UserSchema.statics.getUsersTelegALL = async function (idapp, username) { const User = this; @@ -1302,6 +1386,8 @@ UserSchema.statics.getFieldsForSearch = function () { { field: 'email', type: tools.FieldType.string }, { field: 'profile.cell', type: tools.FieldType.string }, { field: 'profile.email_paypal', type: tools.FieldType.string }, + { field: 'profile.payeer_id', type: tools.FieldType.string }, + { field: 'profile.advcash_id', type: tools.FieldType.string }, { field: 'profile.revolut', type: tools.FieldType.string }, { field: 'profile.link_payment', type: tools.FieldType.string }, { field: 'profile.teleg_id', type: tools.FieldType.number }, @@ -2105,6 +2191,143 @@ UserSchema.statics.NessunaNavePresenteByUsername = async function (idapp, userna }; +UserSchema.statics.getInfoUser = async function (idapp, username) { + return { + username, + is7req: await User.isUserQualified7(idapp, username), + is9req: await User.isUserQualified9(idapp, username), + } + +} + +UserSchema.statics.checkIfSbloccatiRequisiti = async function (idapp, allData, id) { + const User = this; + + const telegrambot = require('../telegram/telegrambot'); + + if (!allData.myuser) + return false; + + if (await Nave.checkIfNaveExist(idapp, allData.myuser.username)) { + // Se già sei dentro la Nave, allora sei OK + return true; //TOGLEREE + } + + // Controlla se Sblocca i 7 requisiti + const is7req = await User.isUserQualified7(idapp, allData.myuser.username); + const is9req = await User.isUserQualified9(idapp, allData.myuser.username); + + const userlista = await ListaIngresso.getListaTessByUsername(idapp, allData.myuser.username); + //if (userlista.length > 0) { //TOGLIERE + if (userlista.length === 0) { + // Se non sono ancora dentro alla lista, allora controllo + + if (!!allData.precDataUser) { + if ((!allData.precDataUser.is7req && is7req) && !await User.isUserAlreadyQualified(idapp, allData.myuser.username)) { + + await User.setUserQualified(idapp, allData.myuser.username); + // ORA HAI I 7 REQUISITI ! + // const msgtext = telegrambot.getCiao(idapp, allData.myuser.username, allData.myuser.lang) + tools.gettranslate('HAI_I_7_REQUISITI', allData.myuser.lang); + // telegrambot.sendMsgTelegram(idapp, allData.myuser.username, msgtext, true); // Anche a STAFF + + // Aggiungilo alla ListaIngresso + risingr = await ListaIngresso.addUserInListaIngresso(idapp, allData.myuser.username, allData.myuser.aportador_iniziale, allData.myuser.lang, true, false); + } + } + } + + if (!!allData.precDataUser) { + 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: + if (!!allData.useraportador) { + /* + const is9reqAportador = await User.isUserQualified9(idapp, allData.myuser.aportador_solidario); + + if (!allData.precDataAportador.is9req && is9reqAportador) { + // ORA HAI I 9 REQUISITI ! + const msgtext = telegrambot.getCiao(idapp, allData.myuser.aportador_solidario, allData.useraportador.lang) + tools.gettranslate('HAI_I_9_REQUISITI', allData.useraportador.lang); + telegrambot.sendMsgTelegram(idapp, allData.myuser.aportador_solidario, msgtext, true); // Anche a STAFF + } + */ + } + +}; + + +UserSchema.statics.mettiSognoePaypal = async function (idapp, modifica) { + const User = this; + + let num = 0; + + arrusers = await User.find({ + 'idapp': idapp, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }, + { subaccount: { $exists: 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) { + if (modifica) { + rec.profile.my_dream = '............'; + aggiornato = true; + } + num++; + } + revolut_ok = !!rec.profile.revolut; + paypal_ok = !!rec.profile.email_paypal; + + if (paypal_ok) + paypal_ok = rec.profile.email_paypal.length > 8; + + if ((!revolut_ok) && (!paypal_ok)) { + if (modifica) { + rec.profile.email_paypal = rec.email; + aggiornato = true; + } + num++; + } + + 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; + + + 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); + } + } + } + } + + return { num }; + +}; + UserSchema.statics.flagUtentiNaviNonPresenti = async function (idapp) { const User = this; diff --git a/src/server/router/api/actions.js b/src/server/router/api/actions.js index 822a8b7..7b5dee6 100755 --- a/src/server/router/api/actions.js +++ b/src/server/router/api/actions.js @@ -15,6 +15,10 @@ const telegrambot = require('../../telegram/telegrambot'); module.exports = { doOtherThingsAfterDeleted: async function (tablename, rec, notifBot, req) { try { + + const { User } = require('../../models/user'); + const telegrambot = require('../../telegram/telegrambot'); + let ris = null; const { ListaIngresso } = require('../../models/listaingresso'); @@ -73,7 +77,7 @@ module.exports = { addtext = 'Eliminato il Record "' + nomerecord + '" dalla tabella ' + tablename + '\n' + 'Eseguito da ' + req.user.name + ' ' + req.user.surname + ' \n'; - await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext); + await telegrambot.sendMsgTelegramToTheManagers(rec.idapp, addtext); } } diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index c760cb2..9b5dfc2 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -65,8 +65,11 @@ UserCost = { 'profile.teleg_id', 'profile.saw_zoom_presentation', 'profile.saw_and_accepted', + 'profile.revolut', + 'profile.payeer_id', + 'profile.advcash_id', + 'profile.link_payment', 'profile.email_paypal', - 'profile.my_dream', 'profile.paymenttypes'] }; @@ -289,70 +292,6 @@ router.post('/gettable', authenticate, (req, res) => { }); -async function checkIfSbloccatiRequisiti(idapp, allData, id) { - - if (!allData.myuser) - return false; - - if (await Nave.checkIfNaveExist(idapp, allData.myuser.username)) { - // Se già sei dentro la Nave, allora sei OK - return true; - } - - // Controlla se Sblocca i 7 requisiti - const is7req = await User.isUserQualified7(idapp, allData.myuser.username); - const is9req = await User.isUserQualified9(idapp, allData.myuser.username); - - const userlista = await ListaIngresso.getListaTessByUsername(idapp, allData.myuser.username); - if (userlista.length === 0) { - // Se non sono ancora dentro alla lista, allora controllo - - if (!!allData.precDataUser) { - if ((!allData.precDataUser.is7req && is7req) && !await User.isUserAlreadyQualified(idapp, allData.myuser.username)) { - await User.setUserQualified(idapp, allData.myuser.username); - // ORA HAI I 7 REQUISITI ! - // const msgtext = telegrambot.getCiao(idapp, allData.myuser.username, allData.myuser.lang) + tools.gettranslate('HAI_I_7_REQUISITI', allData.myuser.lang); - // telegrambot.sendMsgTelegram(idapp, allData.myuser.username, msgtext, true); // Anche a STAFF - - // Aggiungilo alla ListaIngresso - risingr = await ListaIngresso.addUserInListaIngresso(idapp, allData.myuser.username, allData.myuser.aportador_iniziale, allData.myuser.lang, true, false); - } - } - } - - if (!!allData.precDataUser) { - 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: - if (!!allData.useraportador) { - /* - const is9reqAportador = await User.isUserQualified9(idapp, allData.myuser.aportador_solidario); - - if (!allData.precDataAportador.is9req && is9reqAportador) { - // ORA HAI I 9 REQUISITI ! - const msgtext = telegrambot.getCiao(idapp, allData.myuser.aportador_solidario, allData.useraportador.lang) + tools.gettranslate('HAI_I_9_REQUISITI', allData.useraportador.lang); - telegrambot.sendMsgTelegram(idapp, allData.myuser.aportador_solidario, msgtext, true); // Anche a STAFF - } - */ - } - -} - -async function getInfoUser(idapp, username) { - return { - username, - is7req: await User.isUserQualified7(idapp, username), - is9req: await User.isUserQualified9(idapp, username), - } - -} router.patch('/setlang', authenticate, async (req, res) => { const username = req.body.data.username; @@ -407,7 +346,7 @@ router.patch('/chval', authenticate, async (req, res) => { allData = {}; allData.myuser = await User.getUserById(idapp, id); if (!!allData.myuser) - allData.precDataUser = await getInfoUser(idapp, allData.myuser.username); + allData.precDataUser = await User.getInfoUser(idapp, allData.myuser.username); else allData.precDataUser = null; // allData.useraportador = await ListaIngresso.getUserByInvitante_Username(idapp, allData.myuser.aportador_solidario); @@ -513,7 +452,7 @@ router.patch('/chval', authenticate, async (req, res) => { if (mydata.table === 'users') { if (camporequisiti) { - await checkIfSbloccatiRequisiti(idapp, allData, id); + await User.checkIfSbloccatiRequisiti(idapp, allData, id); } } @@ -524,6 +463,14 @@ router.patch('/chval', authenticate, async (req, res) => { } if (mydata.table === 'users') { + if ('saw_zoom_presentation' in fieldsvalue) { + if (fieldsvalue['saw_zoom_presentation']) { + const messaggio = tools.get__('ZOOM_CONFERMATO'); + await telegrambot.sendMsgTelegram(idapp, myuser.username, messaggio); + await telegrambot.sendMsgTelegramToTheManagersAndZoomeri(idapp, `L\'utente ${rec.name} ${rec.surname} (${rec.username}) è stato confermato per aver visto lo Zoom di Benvenuto`); + } + } + if ('aportador_solidario' in fieldsvalue) { ind_order_ingr = mydata.ind_order_ingr; // SERVE SE CI METTO LE MINUSCOLE/MAIUSCOLE SBAGLIATE in invitante_username! @@ -760,8 +707,11 @@ router.patch('/callfunz', authenticate, async (req, res) => { // ELIMINO LA LISTAINGRESSO CHE STO SOSTITUENDO (SOLO SE NON VIENE USATA DA ALTRA NAVE!) let eliminatoingr = await ListaIngresso.eliminaListaIngresso(idapp, mianavedasost.ind_order, req, mianavedasost.num_tess); - if (!eliminatoingr){ - return res.send({ code: server_constants.RIS_CODE_ERR, msg: 'La Sostituzione non può avvenire ! Contattare Paolo. (ind_order=' + mianavedasost.ind_order + ')' }); + if (!eliminatoingr) { + return res.send({ + code: server_constants.RIS_CODE_ERR, + msg: 'La Sostituzione non può avvenire ! Contattare Paolo. (ind_order=' + mianavedasost.ind_order + ')' + }); } } } @@ -937,6 +887,17 @@ router.patch('/callfunz', authenticate, async (req, res) => { } } + } else if (mydata.myfunc === shared_consts.CallFunz.ZOOM_GIA_PARTECIPATO) { + + if (!!myuser.username) { + FormDaMostrare = telegrambot.getFormDaMostrare(idapp, mydata.myfunc, myuser); + + await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuser.name} ${myuser.surname} (${myuser.username}) ha detto di aver già visto lo Zoom di Benvenuto`, false, FormDaMostrare); + + const ris = await User.findByIdAndUpdate(myuser.id, { $set: { 'profile.ask_zoom_partecipato': true } }); + if (ris) + return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); + } } return res.send({ code: server_constants.RIS_CODE_ERR }); @@ -1036,7 +997,10 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { if (cancellato) { // Do extra things after deleted - return actions.doOtherThingsAfterDeleted(tablename, myrec, notifBot, req); + ris = await actions.doOtherThingsAfterDeleted(tablename, myrec, notifBot, req); + if (!!ris) { + return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); + } } res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); diff --git a/src/server/router/site_router.js b/src/server/router/site_router.js index a6251bc..ada3ed1 100755 --- a/src/server/router/site_router.js +++ b/src/server/router/site_router.js @@ -33,7 +33,7 @@ router.post('/load', async (req, res) => { num_teleg_pending: await User.getUsersTelegramPending(idapp), // num_qualificati: await User.getNumUsersQualified(idapp, 2), // num_requisiti: await User.getNumUsersQualified(idapp, 0), - num_modalita_pagamento: await User.getnumPaymentOk(idapp), + // num_modalita_pagamento: await User.getnumPaymentOk(idapp), num_part_zoom: await User.getUsersZoom(idapp), num_part_accepted: await User.getSaw_and_Accepted(idapp), arr_nations: await User.findAllDistinctNationality(idapp), diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 9e6795a..48c2072 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -68,11 +68,10 @@ router.post('/', async (req, res) => { return 1; } - if (tools.blockwords(body.username)) { - tools.writeIPToBan(user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.surname); - await tools.snooze(100000); - res.status(400).send({ code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: '' }); - return 1; + if (tools.blockwords(body.username) || tools.blockwords(body.name) || tools.blockwords(body.surname)) { + // tools.writeIPToBan(user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.surname); + await tools.snooze(5000); + return res.status(404).send(); } @@ -168,6 +167,8 @@ router.post('/', async (req, res) => { user.profile.saw_and_accepted = recorig.profile.saw_and_accepted; user.profile.my_dream = recorig.profile.my_dream; user.profile.email_paypal = recorig.profile.email_paypal; + user.profile.payeer_id = recorig.profile.payeer_id; + user.profile.advcash_id = recorig.profile.advcash_id; user.profile.revolut = recorig.profile.revolut; user.profile.link_payment = recorig.profile.link_payment; user.profile.note_payment = recorig.profile.note_payment; @@ -507,6 +508,10 @@ async function eseguiDbOp(idapp, mydata, locale) { ris = await User.flagUtentiNaviNonPresenti(idapp); } else if (mydata.dbop === 'generaFlotte') { ris = await NavePersistente.generaFlotte(idapp); + } else if (mydata.dbop === 'mettiSognoePaypal') { + ris = await User.mettiSognoePaypal(idapp, true); + } else if (mydata.dbop === 'mettiSognoePaypalView') { + ris = await User.mettiSognoePaypal(idapp, false); } else if (mydata.dbop === 'addNavePerUtentiNaviNonPresenti') { ris = await User.addNavePerUtentiNaviNonPresenti(idapp); } else if (mydata.dbop === 'creaTessituraeConv') { diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 0e15d61..c4f3ced 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -244,8 +244,13 @@ const NOME_COGNOME = 'nomecognome'; const CHEDI_SE_IMBARCARTI = 'chiedi_se_imbarcarti'; const InlineCmd = { - VOGLIO_IMBARCARMI: 'voglio_imbarcarmi', - NON_VOGLIO_IMBARCARMI: 'non_voglio_imbarcarmi' + VOGLIO_IMBARCARMI: 'w_imb', + NON_VOGLIO_IMBARCARMI: 'nw_imb' +}; + +const InlineZoomConferma = { + CONFERMA_ZOOM_PRESENZA: 'conf_pres', + NON_CONFERMA_ZOOM_PRESENZA: 'nonconf_pres' }; const SendMsgCmd = [CONTA_SOLO, RICEVI_EMAIL, NOME_COGNOME, CHEDI_SE_IMBARCARTI]; @@ -473,6 +478,30 @@ module.exports = { REGISTRATION: 1 }, + getFormDaMostrare: function (idapp, myfunc, myuser) { + + FormDaMostrare = null; + + const cl = getclTelegByidapp(idapp); + + if (myfunc === shared_consts.CallFunz.ZOOM_GIA_PARTECIPATO) { + FormDaMostrare = cl.getInlineKeyboard(myuser.lang, [ + { + text: 'Conferma Presenza Zoom', + // callback_data: { action: InlineZoomConferma.CONFERMA_ZOOM_PRESENZA, username: myuser.username } + callback_data: InlineZoomConferma.CONFERMA_ZOOM_PRESENZA + '|' + myuser.username + }, + { + text: 'Annulla Presenza Zoom', + // callback_data: { action: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA, username: myuser.username } + callback_data: InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA + '|' + myuser.username + }, + ]); + } + + return FormDaMostrare; + }, + getCiao: function (idapp, username, lang) { return tools.gettranslate('CIAO', lang) + ' ' + username + '!\n'; }, @@ -511,7 +540,7 @@ module.exports = { }, - sendMsgTelegramToTheManagers: async function (idapp, text, onlyintofile) { + sendMsgTelegramToTheManagers: async function (idapp, text, onlyintofile, MyForm = null) { tools.writeManagersLog(text); @@ -519,8 +548,26 @@ module.exports = { const usersmanagers = await User.getusersManagers(idapp); if (usersmanagers) { for (const rec of usersmanagers) { - await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + ': ' + text, undefined, undefined, true); - await tools.snooze(200) + await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + ': ' + text, undefined, undefined, true, MyForm); + await tools.snooze(100) + } + } + } + return true + + }, + + sendMsgTelegramToTheManagersAndZoomeri: async function (idapp, text, onlyintofile, MyForm = null) { + + tools.writeManagersLog(text); + + if (!onlyintofile) { + // const usersmanagers = await User.getusersManagersAndZoomeri(idapp); + const usersmanagers = await User.getusersManagers(idapp); + if (usersmanagers) { + for (const rec of usersmanagers) { + await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + ': ' + text, undefined, undefined, true, MyForm); + await tools.snooze(100) } } } @@ -560,6 +607,10 @@ module.exports = { msg = msg.replace('{link_paypalme}', user.profile.link_payment); if (!!user.profile.revolut) msg = msg.replace('{revolut}', user.profile.revolut); + if (!!user.profile.payeer_id) + msg = msg.replace('{payeer_id}', user.profile.payeer_id); + if (!!user.profile.advcash_id) + msg = msg.replace('{advcash_id}', user.profile.advcash_id); if (!!user.profile.email_paypal) msg = msg.replace('{email_paypal}', user.profile.email_paypal); if (!!user.profile.note_payment) @@ -691,7 +742,7 @@ module.exports = { strout += '\n (' + index + ') ' + user.name + ' ' + user.surname + ':'; if (mydata.inviareale) { await this.sendMsgTelegramByIdTelegram(idapp, idteleg, mymsg, undefined, undefined, true); - await tools.snooze(300); + await tools.snooze(100); strout += ' -> (MSG OK)'; if (mydata.inviaemail && !!user.email) { @@ -836,7 +887,7 @@ module.exports = { return ris; }, - sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text, message_id, chat_id, ripr_menuPrec) { + sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text, message_id, chat_id, ripr_menuPrec, MyForm = null) { if (!idtelegram) return; @@ -844,7 +895,7 @@ module.exports = { if (cl && idtelegram) { let myform = null; - return await cl.sendMsg(idtelegram, text, null, null, message_id, chat_id, ripr_menuPrec) + return await cl.sendMsg(idtelegram, text, null, MyForm, message_id, chat_id, ripr_menuPrec) } } @@ -912,7 +963,7 @@ async function local_sendMsgTelegramToTheManagers(idapp, text, msg, username_bo) if (cl && idtelegram) { await cl.sendMsg(idtelegram, text, undefined, undefined, undefined, undefined, true) } - await tools.snooze(300) + await tools.snooze(100) } } return true @@ -1357,7 +1408,6 @@ class Telegram { ispayment(user) { if (user) { - let ispaypal = false; if (!!user.profile.paymenttypes) { /*if (user.profile.paymenttypes.includes('paypal')) { if (user.profile.email_paypal) { @@ -1737,7 +1787,7 @@ class Telegram { let help = ""; let helpaperta = true; - if (tools.isMonToSat() && tools.isBetweenTwoTime('8:00:00', '19:50:00')) { + if (tools.isMonToFri() && tools.isBetweenTwoTime('9:00:00', '19:00:00')) { help = '✅ ' + this.getlink('help'); } else { help = "🔴 [ORA CHIUSA - NOW CLOSED]"; @@ -2021,11 +2071,13 @@ class Telegram { FormDaMostrare = this.getInlineKeyboard(lang, [ { text: Menu[lang].SI, - callback_data: { action: InlineCmd.VOGLIO_IMBARCARMI, username: utente.username } + // callback_data: { action: InlineCmd.VOGLIO_IMBARCARMI, username: utente.username } + callback_data: InlineCmd.VOGLIO_IMBARCARMI + '|' + utente.username }, { text: Menu[lang].NO, - callback_data: { action: InlineCmd.NON_VOGLIO_IMBARCARMI, username: utente.username } + // callback_data: { action: InlineCmd.NON_VOGLIO_IMBARCARMI, username: utente.username } + callback_data: InlineCmd.NON_VOGLIO_IMBARCARMI + '|' + utente.username }, ]); inviaveramente = true; @@ -2053,16 +2105,16 @@ class Telegram { // break; } - await tools.snooze(300); + await tools.snooze(100); nummsgsent++; } if (!SendMsgCmd.includes(cmd)) { - if ((nummsgsent % 50) === 0) { - myid = await this.sendMsg(msg.chat.id, nummsgsent + ' ' + getstr(this.getlang(msg), 'MSG_MSG_INCORSO'), null, { message_id: myid }); - await tools.snooze(300) + if ((nummsgsent % 100) === 0) { + myid = await this.sendMsg(msg.chat.id, nummsgsent + ' ' + getstr(this.getlang(msg), 'MSG_MSG_INCORSO'), null, null, myid); + await tools.snooze(100) } } } @@ -2404,6 +2456,7 @@ class Telegram { return res; } catch (e) { + console.error(e); return 0 } } @@ -2627,7 +2680,22 @@ if (!tools.testing()) { const myclTelegram = getclTelegBytoken(bot.token); - const data = callbackQuery.data; + let dataarr = []; + let data = { + action: 0, + username: '' + }; + + const datastr = callbackQuery.data; + if (!!datastr) { + dataarr = datastr.split("|"); + if (!!dataarr) { + data = { + action: dataarr[0], + username: dataarr[1], + } + } + } const msg = callbackQuery.message; const opts = { chat_id: msg.chat.id, @@ -2654,6 +2722,14 @@ if (!tools.testing()) { const msgadd = '[' + user.username + '] ' + user.name + ' ' + user.surname + ' ha risposto che NON VUOLE IMBARCARSI !'; await local_sendMsgTelegramToTheManagers(user.idapp, msgadd, msg, false); // Anche a STAFF + } else if (data.action === InlineZoomConferma.CONFERMA_ZOOM_PRESENZA) { + + await User.setZoomPresenza(user.idapp, user._id, true); + + } else if (data.action === InlineZoomConferma.NON_CONFERMA_ZOOM_PRESENZA) { + + await User.setZoomPresenza(user.idapp, user._id, false); + } } } diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 0c7be4e..39790aa 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -55,10 +55,10 @@ textlang = { "partecipanti": "partecipanti", 'TESTO_ASSISTENZA': "👉 Per entrare nel Sito AYNI\n\n" + "👉 Hai dimenticato la password?\n\n" + + "👉 Entra nel Canale d'Informazione per Importanti Avvisi!\nCanale AYNI-BIBLIO\n\n" + "👉 Chat AYNI - EMPOWER: Entra ⛩ nella nostra Community chat\n%s\n\n" + - "👉 Canale News e Informazioni AYNI-BIBLIO\n\n" + - "👉 PER AIUTO: Leggi le Domande più Frequenti:\n%s\n\n" + - "Chat di Supporto 'AYNI - HELP'\nDa Lunedì al Sabato (8:00 - 20:00)\n%s\n" + + "👉 PER AIUTO: Leggi le Domande più Frequenti:\n%s\nOppure chiedi prima al tuo Invitante!\n\n" + + "SOLO se non trovi la risposta che ti serve puoi accedere alla Chat di Supporto 'AYNI - HELP'\nDa Lunedì al Venerdí (9:00 - 19:00)\n%s\n" + "1 - Fai la tua domanda e chiedi assistenza.\n2 - Dopo aver ricevuto aiuto Esci dalla chat.\nPotrai rientrare ogni qualvolta ne avrai la necessità.", 'BENVENUTO': "Benvenuto", 'TUE_NAVI': "Ecco le tue Navi programmate", @@ -117,6 +117,7 @@ textlang = { 'NAVE': 'NAVE', 'MSG_SEND_FROM': 'Msg Inviato da', 'VUOI_IMBARCARTI': 'Attenzione! Ci risulta che attualmente non ti è stato assegnato Nessun Imbarco.\nQuesto può essere dovuto ad un errore durante la fase di aggiornamento del sito, oppure perchè tu stesso hai cancellato l\'imbarco.\n\nVuoi Aggiungerti ora al prossimo Imbarco per continuare nel tuo Viaggio in AYNI? ', + 'ZOOM_CONFERMATO': 'Sei stato confermato ad aver visto la Video Conferenza di Benvenuto!', }, si: { "Email je že bila preverjena": "Email je že bila preverjenaL'Email è già stata Verificata", @@ -185,6 +186,7 @@ textlang = { 'NAVE': 'LADJE', 'MSG_SEND_FROM': 'sporočilo, ki ga je poslal', 'VUOI_IMBARCARTI': 'Pozor! Opazili smo, da ti trenutno ni bila dodeljena Nobena ladjica.\nTo je lahko posledica napake med fazo posodabljanja spletnega mesta ali ker si sam zbrisal svoj vpis.\n\nAli želiš nadaljevati plovbo, če želiš nadaljevati potovanje z AYNI ?', + 'ZOOM_CONFERMATO': 'Potrjeno je bilo, da ste videli dobrodošlico video konference!', }, es: { "L'Email è già stata Verificata": "El correo electrónico ya ha sido verificado", @@ -195,7 +197,7 @@ textlang = { "¿Olvidó su contraseña para acceder al sitio?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n" + "Chat AYNI BOT (este):\nhttps://t.me/notevoleaynibot\n\n" + "Chat AYNI - EMPOWER: Entra en ⛩ en nuestra comunidad de chat:\n%s\n\n" + - "Chat de ayuda y soporte: 'AYNI - HELP'\nDe lunes a sábado (8:00 - 21:00)\n%s\n" + + "Chat de ayuda y soporte: 'AYNI - HELP'\nDe lunes a viernes (9:00 - 19:00)\n%s\n" + "1 - Haga su pregunta y pida ayuda.\n2 - Después de que consigas ayuda, sal de la sala de chat.\nPuedes volver cuando necesites ayuda..", 'BENVENUTO': "Bienvenido", 'TUE_NAVI': "Aquí están sus naves programadas", @@ -251,6 +253,7 @@ textlang = { 'NAVE': 'NAVE', 'MSG_SEND_FROM': 'Mensaje enviado por', 'VUOI_IMBARCARTI': '¡Atención! Entendemos que actualmente no está asignado a No Boarding.\nEsto puede deberse a un error durante la fase de actualización del sitio web, o porque usted mismo ha cancelado el embarque.\n\n¿Quieres añadirte ahora al próximo embarque para continuar tu viaje en AYNI?', + 'ZOOM_CONFERMATO': '¡Se ha confirmado que ha visto la Video Conferencia de Bienvenida!', }, enUs: { "partecipanti": "participants", @@ -258,7 +261,7 @@ textlang = { "https://ayni.gifteconomy.app/requestresetpwd\nChat AYNI BOT (this one):\nhttps://t.me/notevoleaynibot\n\n" + "Chat AYNI - EMPOWER: Enter ⛩ into our chat community:\n%s\n\n" + "Canale News AYNI-BIBLIO:\n%s\n\n" + - "Help and Support Chat: 'AYNI - HELP'.\nMonday to Saturday (8:00 - 20:00)\n%s\n" + + "Help and Support Chat: 'AYNI - HELP'.\nMonday to Friday (9:00 - 19:00)\n%s\n" + "1 - Ask your question and ask for assistance.\n2 - After receiving help, exit the chat.\nYou can come back whenever you need help.", 'BENVENUTO': "Welcome", 'TUE_NAVI': "Here are your programmed ships", @@ -314,6 +317,7 @@ textlang = { 'NAVE': 'SHIP', 'MSG_SEND_FROM': 'Msg sent by', 'VUOI_IMBARCARTI': 'Attention! We understand that you have No Boarding assigned.\nThis may be due to an error during the site update phase, or because you have cancelled boarding yourself.\n\nDo you want to add now to the Next Boarding to continue your AYNI Trip?', + 'ZOOM_CONFERMATO': 'You have been confirmed to have seen the Welcome Video Conference!', }, fr: { "L'Email è già stata Verificata": "Le courrier électronique a déjà été vérifié", @@ -325,7 +329,7 @@ textlang = { "Chat AYNI BOT (ce):\nhttps://t.me/notevoleaynibot\n\n" + "Chat AYNI - EMPOWER : Entrez ⛩ dans notre Community chat:\n%s\n\n" + "Canale News AYNI-BIBLIO:\n%s\n\n" + - "Chat d’Aide et de Support: 'AYNI - HELP'\nDu lundi au samedi (8:00 - 20:00)\n%s\n" + + "Chat d’Aide et de Support: 'AYNI - HELP'\nDu lundi au Vendredi (9:00 - 19:00)\n%s\n" + "1 - Posez votre question et demandez d’être assisté.\n2 - Après avoir reçu l’aide, quittez le groupe.\nVous pourrez y entrer chaque fois qu’il vous sera nécessaire.", 'BENVENUTO': "Bienvenue", 'TUE_NAVI': "Voici vos navires programmés", @@ -381,6 +385,7 @@ textlang = { 'NAVE': 'NAVIRE', 'MSG_SEND_FROM': 'Message envoyé par', 'VUOI_IMBARCARTI': 'Attention ! Nous comprenons que vous n\'êtes actuellement pas affecté Pas d\'embarquement.\nCela peut être dû à une erreur lors de la phase de mise à jour du site, ou parce que vous avez vous-même annulé l\'embarquement.\n\nVoulez-vous vous ajouter maintenant au prochain embarquement pour continuer votre voyage AYNI ? ', + 'ZOOM_CONFERMATO': 'Vous avez été confirmé comme ayant vu la vidéoconférence de bienvenue !', }, pt: { "L'Email è già stata Verificata": "", @@ -392,7 +397,7 @@ textlang = { "Chat AYNI BOT (isto):\nhttps://t.me/notevoleaynibot\n\n" + "Chat AYNI - EMPOWER: Entrar em ⛩ na nossa comunidade de chat:%s\n\n" + "Canale News AYNI-BIBLIO:\n%s\n\n" + - "Chat de Ajuda e Suporte: 'AYNI - HELP'.\nDe segunda a sábado (8:00 - 20:00 ITALY)\n%s\n" + + "Chat de Ajuda e Suporte: 'AYNI - HELP'.\nDe segunda a Sexta (9:00 - 19:00 ITALY)\n%s\n" + "1 - Faça a sua pergunta e peça ajuda.\n2 - Depois de receber ajuda, saia do chat.\nPode voltar sempre que precisar de o fazer..", 'BENVENUTO': "Bem-vindo", 'TUE_NAVI': "Aqui estão os seus navios programados", @@ -448,6 +453,7 @@ textlang = { 'NAVE': 'NAVE', 'MSG_SEND_FROM': 'Mensagem enviada por', 'VUOI_IMBARCARTI': 'Atenção! Compreendemos que actualmente não lhe é atribuído Sem Embarque.\nIsto pode ser devido a um erro durante a fase de actualização do site, ou porque você mesmo cancelou o embarque.\n\nDeseja juntar-se agora ao próximo embarque para continuar a sua viagem AYNI?', + 'ZOOM_CONFERMATO': 'Foi-lhe confirmado que assistiu à Conferência de Vídeo de Boas-vindas!', }, }; @@ -1006,6 +1012,8 @@ module.exports = { filtriadded.push({ 'profile.qualified': true }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_ZOOM)) filtriadded.push({ 'profile.saw_zoom_presentation': false }); + if (params.filterand.includes(shared_consts.FILTER_ASK_ZOOM_VISTO)) + filtriadded.push({ 'profile.ask_zoom_partecipato': false }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_INVITANTE)) filtriadded.push({ aportador_solidario: { $exists: false } @@ -1184,6 +1192,11 @@ module.exports = { return dayOfWeek >= 1 && dayOfWeek <= 6 }, + isMonToFri() { + const dayOfWeek = new Date(new Date()).getDay(); + return dayOfWeek >= 1 && dayOfWeek <= 5 + }, + // var startTime = '15:10:10'; // var endTime = '22:30:00'; isBetweenTwoTime(startTime, endTime) { @@ -1740,8 +1753,11 @@ module.exports = { }, blockwords(mystr) { - if (mystr.includes('ttp')) { - return true; + const arrwords = ['http', 'Http', 'Asasfasfas', '://', 'mrbit']; + for (const myword of arrwords) { + if (mystr.includes(myword)) { + return true; + } } return false; diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index da2895b..cea2644 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -22,6 +22,7 @@ module.exports = { FILTER_NASCOSTI: 4096, FILTER_NAVI_NON_PRESENTI: 8192, FILTER_QUALIFIED: 16384, + FILTER_ASK_ZOOM_VISTO: 32768, Permissions: { Admin: 1, @@ -29,6 +30,7 @@ module.exports = { Teacher: 4, Tutor: 8, Traduttrici: 16, + Zoomeri: 32, }, MessageOptions: { @@ -53,6 +55,7 @@ module.exports = { DAMMI_PRIMO_UTENTE_LIBERO: 390, GET_VALBYTABLE: 400, SET_VALBYTABLE: 410, + ZOOM_GIA_PARTECIPATO: 510 }, fieldsUserToChange() { From 700c64a5d0c4edd333132e6abc347581d28a7cb0 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Tue, 8 Sep 2020 14:59:49 +0200 Subject: [PATCH 12/14] Chat Fra cambiata --- src/server/telegram/telegrambot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index c4f3ced..6ecc612 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -1774,7 +1774,7 @@ class Telegram { "SLO 🇸🇮: https://t.me/aynislovenija" + tools.ACAPO + "ESP 🇪🇸 - PRT 🇵🇹: https://t.me/joinchat/AL2qKBqJRuIEuc2FivgAzg" + tools.ACAPO + "ENG 🇬🇧: https://t.me/joinchat/AL2qKBYX0yVvOJ6Ssf9hKg" + tools.ACAPO + - "FRA 🇫🇷: https://t.me/joinchat/Kz0wtxieJjzoC3L_DsrdZw"; + "FRA 🇫🇷: https://t.me/joinchat/POqmM1ddtRmnxtLdKkm5sQ"; } } From 9093f49fbd8aab30d57f4dcf7fcb7b76ac1fb6c2 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Tue, 15 Sep 2020 11:49:20 +0200 Subject: [PATCH 13/14] - Tolto Zoom e Sogni come requisiti - Corretto Email con HTML che si visualizzavano tutti i caratteri HTML... --- documentation/passi.txt | 97 ++------------------------ src/server/models/user.js | 10 +-- src/server/router/index_router.js | 5 +- src/server/router/newsletter_router.js | 11 ++- src/server/router/users_router.js | 4 +- src/server/sendemail.js | 48 ++++++++++--- src/server/telegram/telegrambot.js | 14 ++-- 7 files changed, 72 insertions(+), 117 deletions(-) diff --git a/documentation/passi.txt b/documentation/passi.txt index 366976e..fab290c 100755 --- a/documentation/passi.txt +++ b/documentation/passi.txt @@ -1,40 +1,32 @@ ------------ -- L'ultimo Utente della Creazione della Nave, compare ancora il Sognatore !!! - Sistemato: TESTARE SE ORA È' OK... - -// ************************************************ - // ++Todo: PRIORITA' ALTA: - Togliere gli imbarchi: far pagare subito la persona. - Errore durante la sostituzione... +- Se sostuisci una persona, al nuovo utente gli arriva il messaggio sbagliato! + (🌟Caro Tiziana - TiziCaso 🌟 Il tuo imbarco è stato cancellato, + questo succede quando non riceviamo risposta ad un nostro messaggio per giorni.) -- far pagare direttamente al Sognatore. - Il dono al Fondo, fallo fare a prescindere (non al 57¨ dono). -- Se sostituisco mi da sempre la stessa persona. +- Controllare che ci sono registrazioni doppie !! (stesso username e stessa email!) -- Togliere i Video e il Sogno. (5 requisiti) -- Cestino di ELIMINA non funziona !! - - (Linuccia) - Natalina Malerbi DA CONTROLLARE CHE LEI NON HA PAGATO 8.44. QUINDI QUALCUNO HA PRESO IL SUO POSTO. - - 7.64 : NATALINA NON HA LA RITESSITURA !! -- Controllare che ci sono registrazioni doppie !! (stesso username e stessa email!) - SubAccount: filtro. - Aggiornare le Traduzioni di Darja (ritessitura). -- Sistemare la email che arriva ai Donatori (HTML) ! +- Sistemare la email che arriva ai Donatori (HTML) non si legge !!! - Flotte: Poter scegliere quale messaggio inviare ! @@ -78,9 +70,7 @@ - Rimettere "made_gift" a false se si ha sbagliato... -- Mettere 3 giorni. - -- Fondo Ayni 9.152 : aggiungere registrazione Paolo2 Arena. e mettere paypal.me +- Fondo Ayni 9.152 : aggiungere registrazione Paolo2 Arena. e mettere paypal.me ?? - Mandare msg ai Non Invitati, o inferiori di 2. @@ -106,12 +96,8 @@ // ++Todo: PRIORITA' NORMALE: -- AGGIUNGERCI L'USERNAME REALE ! ALTRIMENTI PRENDE IL PRINCIPALE !! - - Fare funzione che passa un Utente secondario in un utente Primario! (c'è gia) -- L'orario degli Zoom sul BOT è diverso che dal sito, deve dare quello locale... - // ++Todo: DA FARE PIU AVANTI: @@ -129,92 +115,21 @@ TESTARE -> inviare il msg anche al Sognatore della Gift Chat // ++Todo: SISTEMARE: -x- AGGIONARE AMBIENTE DI TEST -- ESEGUIRE LA CONVERSIONE 1 E 2 ! - - -x - Sistemare le navi con num_tess === 4 : indorder=0 e 46 : - Prendere quelli del num_tess === 3 e SOSTITUISCI ind_order del num_Tess = 4 con ind_order di num_tess = 3 - -------------- -- AGGIONARE AMBIENTE DI PRODUZIONE -- ESEGUIRE LA CONVERSIONE 1 E 2 e ! - - - Sistemare le navi con num_tess === 4 : indorder=0 e 46 : - Prendere quelli del num_tess === 3 e SOSTITUISCI ind_order del num_Tess = 4 con ind_order di num_tess = 3 - -------------- - SOSTITUISCI: - -- Sistemare che in Edit Pagina, se è troppo grande, va oltre l'altezza della finestra. -- Attivare le Traduttrici alle Pagine - - Inviare messaggi solo per ITALIANI (o di lingua cmq). -- Aggiornare le FAQ in lingua - - - CONTROLLARE CON ARGENTINA E PORTOGALLO e Brasile: Il sito deve comparire in Spagnolo e in Portoghese TRADURRE: -- Mettere le bandierine nella lista Zoom (su AYNI BOT). - - -1- mi appaiono prima le navi del secondo account -2- forse metterei ogni nave seguita dal relativo viaggio di "ritorno" (a me piace chiamarlo così!) -X 3- sotto le navi, alla voce donatore, c'è ancora scritto "Effettuerai il tuo dono ESATTAMENTE il giorno indicato" -X 4- nei miei invitati non compaiono le mie ritessiture, fatte con il magico bottone, da chi sono invitata? - - -- Controllare Tragitto (Elisabetta) -- Monica Sozzi -> Davide Moirano (0) è giusto. - - Andrea Decouter (2) - - Enrica Pescio (OK) - - 852 (Gerico2) Elio2 Garelli -> (Gerico) - -Andrea 346 - -ind_order: 231 Gerico Elio Garelli -ind_order: 852 Gerico2 Elio2 Garelli - - -Morgana Roveta (Maelabo) - --- Gerico Elio Garelli - -ANDREA - |-----GERICO2 852 - - .update({}, {$unset: {$ind_order: 1}, {multi: true}); -//++TODO: *** FATTI *** - - - // ++Todo: FATTO: DA CONTROLLARE -X - Se sei imbarcata i tuoi due invitati usati per quella posizione sono bloccati. Se ne hai in più li puoi regalare -X - Numero d'invitati sbagliato -> Nogalska -X - 50 persone non hanno un'imbarco -> Chiamare funzione che gliela rimette. - -X - Poter Inviare un msg preconfezionato a chi non la la nave ! -X Poter cliccare SI per aggiungersi ad un Nuovo Imbarco. -X - Se entro con la seconda utenza, gli mando messaggio che dice che deve collegarsi con la prima utenza.... - -X - Sistemare poter modificare le Pagine. - -X - SISTEMARE QUANDO L'ULTIMA NAVE DELLA FLOTTA C'E' UN SOGNATORE CHE HA LA NAVE DI RITORNO! -X - IL MEDIATORE DEVE AVERE LA SUA RITESSUTURA !!! ( TOGLIERE L'IF NEL CASO NON SIA SOGNATORE) - -X - Mettere anche la email del sognatore, per chi è abituato ad inviarla in quel modo... -X - Controllare che sul sito compaiano le informazioni del Sognatore... - diff --git a/src/server/models/user.js b/src/server/models/user.js index 3954c8f..429efbc 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -502,7 +502,7 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) sospeso: 1, verified_email: 1, 'profile.teleg_id': 1, - 'profile.saw_zoom_presentation': 1, + // 'profile.saw_zoom_presentation': 1, 'profile.ask_zoom_partecipato': 1, 'profile.qualified': 1, 'profile.qualified_2invitati': 1, @@ -513,7 +513,7 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, - 'profile.my_dream': 1, + // 'profile.my_dream': 1, 'profile.paymenttypes': 1, 'profile.cell': 1, made_gift: 1, @@ -556,7 +556,7 @@ UserSchema.statics.getDownlineByUsername = async function (idapp, username, incl surname: 1, verified_email: 1, 'profile.teleg_id': 1, - 'profile.saw_zoom_presentation': 1, + // 'profile.saw_zoom_presentation': 1, 'profile.ask_zoom_partecipato': 1, 'profile.qualified': 1, 'profile.qualified_2invitati': 1, @@ -567,7 +567,7 @@ UserSchema.statics.getDownlineByUsername = async function (idapp, username, incl 'profile.revolut': 1, 'profile.link_payment': 1, 'profile.note_payment': 1, - 'profile.my_dream': 1, + // 'profile.my_dream': 1, 'profile.paymenttypes': 1, 'profile.cell': 1, made_gift: 1, @@ -641,7 +641,7 @@ UserSchema.statics.getQueryQualified = function () { verified_email: true, 'profile.teleg_id': { $gt: 1 }, 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED, - 'profile.saw_zoom_presentation': true, + // 'profile.saw_zoom_presentation': true, $or: [ { 'profile.link_payment': { $exists: true } }, { 'profile.email_paypal': { $exists: true } }, diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 9b5dfc2..f3f343a 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -63,7 +63,6 @@ const shared_consts = require('../tools/shared_nodejs'); UserCost = { FIELDS_REQUISITI: ['verified_email', 'profile.teleg_id', - 'profile.saw_zoom_presentation', 'profile.saw_and_accepted', 'profile.revolut', 'profile.payeer_id', @@ -463,13 +462,13 @@ router.patch('/chval', authenticate, async (req, res) => { } if (mydata.table === 'users') { - if ('saw_zoom_presentation' in fieldsvalue) { + /*if ('saw_zoom_presentation' in fieldsvalue) { if (fieldsvalue['saw_zoom_presentation']) { const messaggio = tools.get__('ZOOM_CONFERMATO'); await telegrambot.sendMsgTelegram(idapp, myuser.username, messaggio); await telegrambot.sendMsgTelegramToTheManagersAndZoomeri(idapp, `L\'utente ${rec.name} ${rec.surname} (${rec.username}) è stato confermato per aver visto lo Zoom di Benvenuto`); } - } + }*/ if ('aportador_solidario' in fieldsvalue) { ind_order_ingr = mydata.ind_order_ingr; diff --git a/src/server/router/newsletter_router.js b/src/server/router/newsletter_router.js index 3927f82..e4e0a31 100755 --- a/src/server/router/newsletter_router.js +++ b/src/server/router/newsletter_router.js @@ -347,7 +347,16 @@ router.post('/testemail', authenticate, async (req, res) => { lang = req.body.locale; previewonly = req.body.previewonly; - const ris = await sendemail.testemail(idapp, lang, previewonly); + const test = true; + + if (test) { + const email = 'pao.loarena77@gmail.com'; + const myuser = await User.findOne({ idapp, email }); + + const ris = await sendemail.testemailHtml(idapp, lang, email, myuser); + } else { + const ris = await sendemail.testemail(idapp, lang, previewonly); + } if (ris) return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 48c2072..c90d31d 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -163,9 +163,9 @@ router.post('/', async (req, res) => { recorig = await User.findByCellAndNameSurname(user.idapp, user.profile.cell, user.name.slice(0, -1), user.surname); if (!!recorig) { user.profile.teleg_id = recorig.profile.teleg_id; - user.profile.saw_zoom_presentation = recorig.profile.saw_zoom_presentation; + // user.profile.saw_zoom_presentation = recorig.profile.saw_zoom_presentation; user.profile.saw_and_accepted = recorig.profile.saw_and_accepted; - user.profile.my_dream = recorig.profile.my_dream; + // user.profile.my_dream = recorig.profile.my_dream; user.profile.email_paypal = recorig.profile.email_paypal; user.profile.payeer_id = recorig.profile.payeer_id; user.profile.advcash_id = recorig.profile.advcash_id; diff --git a/src/server/sendemail.js b/src/server/sendemail.js index 230223f..a38e0ef 100755 --- a/src/server/sendemail.js +++ b/src/server/sendemail.js @@ -105,23 +105,27 @@ module.exports = { }); }, - sendEmail_Normale: function (to, subject, html, replyTo) { + sendEmail_Normale: async function (to, subject, html, replyTo) { // setup e-mail data with unicode symbols var mailOptions = { from: tools.getEmailByIdApp(mylocalsconf.idapp), // sender address + dataemail: await this.getdataemail(idapp), to: to, generateTextFromHTML: true, subject: subject, html: html, }; + if (replyTo) mailOptions['reply-to'] = replyTo; - if (process.env.SEND_EMAIL === 1) { + const smtpTransport = this.getTransport(mylocalsconf); + + if (process.env.SEND_EMAIL === "1") { // console.log("SEND EMAIL..."); -// send mail with defined transport object + // send mail with defined transport object smtpTransport.sendMail(mailOptions, function (error, response) { if (error) { console.log("Email Inviata ERRORE RISPOSTA: " + error); @@ -328,7 +332,8 @@ module.exports = { if (!!mylocalsconf.dataemail.emailtitle && !!mylocalsconf.dataemail.emailbody) { const replyto = tools.getreplyToEmailByIdApp(idapp); - return this.sendEmail_base('standard', emailto, mylocalsconf, replyto); + //return this.sendEmail_base('standard', emailto, mylocalsconf, replyto); + return await this.sendEmail_Normale(emailto, mylocalsconf.dataemail.emailtitle, mylocalsconf.dataemail.emailbody, replyto); } // Send Email also to the Admin @@ -490,7 +495,7 @@ module.exports = { // Create Transport let smtpTransport = null; - if (mylocalsconf.dataemail.email_service !== 'gmail' && mylocalsconf.dataemail.email_service !== undefined) { + if (mylocalsconf.dataemail.email_service !== 'gmail' && mylocalsconf.dataemail.email_service !== undefined && mylocalsconf.dataemail.email_service !== "") { smtpTransport = nodemailer.createTransport({ host: mylocalsconf.dataemail.email_service, port: mylocalsconf.dataemail.email_port, @@ -500,21 +505,24 @@ module.exports = { } }); } else if (mylocalsconf.dataemail.email_service === 'gmail' && mylocalsconf.dataemail.email_service !== undefined) { - smtpTransport = { + + //smtpTransport = { + smtpTransport = nodemailer.createTransport({ service: 'gmail', //'Gmail', auth: { user: mylocalsconf.dataemail.from, pass: mylocalsconf.dataemail.pwd_from } - }; + }); } else { - smtpTransport = { + // smtpTransport = { + smtpTransport = nodemailer.createTransport({ service: 'gmail', auth: { user: tools.getEmailByIdApp(mylocalsconf.idapp), pass: tools.getPwdByIdApp(mylocalsconf.idapp) } - }; + }); } return smtpTransport; @@ -719,6 +727,28 @@ module.exports = { console.log('-> Invio Email TEST a', mylocalsconf.emailto, 'previewonly', previewonly); return this.sendEmail_base('newsletter/' + lang, mylocalsconf.emailto, mylocalsconf, '', smtpTransport, previewonly); + }, + + testemailHtml: async function (idapp, lang, email, myuser) { + + + mytitle = 'Prova msg' + messaggio = '
Ciao!

Come stai?

Tutto Bene?
Prova Link
Corsivo '; + + /*const htmlToText = require('html-to-text'); + + messaggio = htmlToText.fromString(messaggio, { + wordwrap: 80, + preserveNewlines: true, + singleNewLineParagraphs: true + }); + */ + + return await this.sendEmail_ByText(lang, email, myuser, idapp, { + emailbody: messaggio, + emailtitle: mytitle + }); + } diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index c4f3ced..3259cb0 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -1502,8 +1502,8 @@ class Telegram { mystr += '\n3. ' + this.getsymb(emo.PENCIL, tools.isBitActive(user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_READ_GUIDELINES)) + tools.get__('LINEE_GUIDA', this.getlang(msg)); mystr += '\n4. ' + this.getsymb(emo.TV, tools.isBitActive(user.profile.saw_and_accepted, shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI)) + tools.get__('VIDEO_INTRO', this.getlang(msg)); - mystr += '\n5. ' + this.getsymb(emo.EYES, user.profile.saw_zoom_presentation) + tools.get__('ZOOM_PARTECIPATO', this.getlang(msg)); - mystr += '\n6. ' + this.getsymb(emo.DREAM, this.isdreamset(user)) + tools.get__('SCRITTO_SOGNO', this.getlang(msg)); + // mystr += '\n5. ' + this.getsymb(emo.EYES, user.profile.saw_zoom_presentation) + tools.get__('ZOOM_PARTECIPATO', this.getlang(msg)); + // mystr += '\n6. ' + this.getsymb(emo.DREAM, this.isdreamset(user)) + tools.get__('SCRITTO_SOGNO', this.getlang(msg)); mystr += '\n7. ' + this.getsymb(emo.CREDIT_CARD, this.ispayment(user)) + tools.get__('PAYMENTS', this.getlang(msg)); } @@ -1772,9 +1772,11 @@ class Telegram { } else if (qualelink === 'empower') { return "ITA 🇮🇹: https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g" + tools.ACAPO + "SLO 🇸🇮: https://t.me/aynislovenija" + tools.ACAPO + + "HRV 🇭🇷 BIH 🇧🇦 SRB 🇷🇸 MNE 🇲🇪: https://t.me/joinchat/KFGPolcH0lLrqrdloOASYQ" + tools.ACAPO + "ESP 🇪🇸 - PRT 🇵🇹: https://t.me/joinchat/AL2qKBqJRuIEuc2FivgAzg" + tools.ACAPO + - "ENG 🇬🇧: https://t.me/joinchat/AL2qKBYX0yVvOJ6Ssf9hKg" + tools.ACAPO + - "FRA 🇫🇷: https://t.me/joinchat/Kz0wtxieJjzoC3L_DsrdZw"; + "FRA 🇫🇷: https://t.me/joinchat/POqmM1ddtRmnxtLdKkm5sQ" + tools.ACAPO + + "ENG 🇬🇧: https://t.me/joinchat/AL2qKBYX0yVvOJ6Ssf9hKg" + tools.ACAPO + ; } } @@ -1796,9 +1798,9 @@ class Telegram { let mytext = ""; if (this.getlang(msg) === 'it') - mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, empower, biblio, faq, help); + mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, biblio, empower, faq, help); else - mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, empower, biblio, help); + mytext = printf(tools.get__('TESTO_ASSISTENZA', this.getlang(msg)), sito, biblio, empower, help); let menu = null; const rec = this.getRecInMem(msg); From f67f448cd4a36e6e31f9ac9117524dd5e76a4843 Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Sat, 17 Oct 2020 22:11:29 +0200 Subject: [PATCH 14/14] - Tolto Zoom e Sogni come requisiti - Corretto Email con HTML che si visualizzavano tutti i caratteri HTML... --- documentation/passi.txt | 5 +++ src/server/config/config.js | 47 ++++++++++++++++++++++++++ src/server/router/index_router.js | 6 ++-- src/server/router/newsletter_router.js | 2 +- 4 files changed, 57 insertions(+), 3 deletions(-) diff --git a/documentation/passi.txt b/documentation/passi.txt index fab290c..c3a434c 100755 --- a/documentation/passi.txt +++ b/documentation/passi.txt @@ -2,6 +2,10 @@ // ++Todo: PRIORITA' ALTA: +- ETELEGRAM: 400 Bad Request: message identifier is not specified. +- ETELEGRAM: 400 Bad Request: message is too long + + - Togliere gli imbarchi: far pagare subito la persona. - Errore durante la sostituzione... @@ -13,6 +17,7 @@ - Controllare che ci sono registrazioni doppie !! (stesso username e stessa email!) +- Mostrare il numero della tua posizione... - (Linuccia) - Natalina Malerbi DA CONTROLLARE CHE LEI NON HA PAGATO 8.44. diff --git a/src/server/config/config.js b/src/server/config/config.js index 622ba56..9250c42 100755 --- a/src/server/config/config.js +++ b/src/server/config/config.js @@ -148,6 +148,22 @@ if (process.env.NODE_ENV === 'production') { pathreg_add:'_sip', abilitanave: false, }, + { + idapp: '10', + name: 'Comunità Nuovo Mondo', + adminemail: 'comunitanuovomondo@gmail.com', + manageremail: '', + replyTo: '', + host: 'https://comunitanuovomondo.app', + portapp: '0', + dir: '/var/www/comunitanuovomondo.app', + email_from: 'comunitanuovomondo@gmail.com', + email_pwd: 'c6f63e7aba9393c73f56e338a7fe5283a73949363662d26bd375dd05b6f6f37ebkw4vINQ0O/4d8JN71aNH3UsyndeFRgyyMvJMVl4iOk=', + telegram_key:'1202788747:AAErwzIsD7k-3Yj5AX6ci3p7ELMuyASq4vA', + telegram_bot_name: 'comunitanuovomondo_bot', + pathreg_add:'_cnm', + abilitanave: false, + }, ]; } else if (process.env.NODE_ENV === 'test') { // ---------------- AMBIENTE DI TEST -------------------- @@ -276,6 +292,22 @@ if (process.env.NODE_ENV === 'production') { pathreg_add:'_sip', abilitanave: false, }, + { + idapp: '10', + name: 'Comunità Nuovo Mondo (Server Test)', + adminemail: 'info.pianetalibero@gmail.com', + manageremail: '', + replyTo: '', + host: 'https://test.comunitanuovomondo.app', + portapp: '0', + dir: '/var/www/test.comunitanuovomondo.app', + email_from: 'info.pianetalibero@gmail.com', + email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==', + telegram_key:'', + telegram_bot_name: '', + pathreg_add:'_cnm', + abilitanave: false, + } ]; } else { // ---------------- AMBIENTE IN L O C A L E -------------------- @@ -404,6 +436,21 @@ if (process.env.NODE_ENV === 'production') { pathreg_add:'_sip', abilitanave: false, }, + { + idapp: '10', + name: 'Comunità Nuovo Mondo', + adminemail: 'paolo.arena77@gmail.com', + manageremail: '', + host: 'http://localhost', + portapp: '8090', + dir: '', + email_from: 'info.pianetalibero@gmail.com', + email_pwd: '66ffeb915e71fada64ad5c26947dd087c262be3b343734a0447c6dee534b888aZcfbjXEuMBWKxvbh60cniw==', + telegram_key: '', + telegram_bot_name: '', + pathreg_add:'_cnm', + abilitanave: false, + } ]; } diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index f3f343a..7cc8cf7 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -186,7 +186,7 @@ function getTableByTableName(tablename) { mytable = User; else if (tablename === 'tessitura') mytable = Tessitura; - // else if (tablename === 'extralist') + // else if (tablename === 'extralist') // mytable = ExtraList; else if (tablename === 'bookings') mytable = Booking; @@ -987,6 +987,8 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { tools.mylog('DELETED ', rec._id); + return true; + }).catch((e) => { console.log(e.message); res.status(400).send(); @@ -996,7 +998,7 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { if (cancellato) { // Do extra things after deleted - ris = await actions.doOtherThingsAfterDeleted(tablename, myrec, notifBot, req); + let ris2 = await actions.doOtherlasThingsAfterDeleted(tablename, myrec, notifBot, req); if (!!ris) { return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); } diff --git a/src/server/router/newsletter_router.js b/src/server/router/newsletter_router.js index e4e0a31..846ad72 100755 --- a/src/server/router/newsletter_router.js +++ b/src/server/router/newsletter_router.js @@ -347,7 +347,7 @@ router.post('/testemail', authenticate, async (req, res) => { lang = req.body.locale; previewonly = req.body.previewonly; - const test = true; + const test = false; if (test) { const email = 'pao.loarena77@gmail.com';