diff --git a/emails/registration/enUs/html.pug b/emails/registration/enUs/html.pug index 7f17977..5dd333b 100644 --- a/emails/registration/enUs/html.pug +++ b/emails/registration/enUs/html.pug @@ -6,7 +6,7 @@ span Forgot your Password? :  strong Find it here
span Email:  strong #{emailto}
-p To confirm the registration click on the button: +p To confirm the registration click on the button, or click here #{strlinkreg}: div.divbtn button.btn.btn-lg Verify Registration diff --git a/emails/registration/it/html.pug b/emails/registration/it/html.pug index d7b1cbe..c170004 100644 --- a/emails/registration/it/html.pug +++ b/emails/registration/it/html.pug @@ -6,7 +6,7 @@ span hai dimenticato la Password? :  strong Trovala qui
span Email:  strong #{emailto}
-p Per confermare la registrazione clicca sul bottone: +p Per confermare la registrazione clicca sul bottone, oppure qui: #{strlinkreg}: div.divbtn button.btn.btn-lg Verifica Registrazione diff --git a/emails/registration_ayni/es/html.pug b/emails/registration_ayni/es/html.pug index 093e9ed..29594bc 100644 --- a/emails/registration_ayni/es/html.pug +++ b/emails/registration_ayni/es/html.pug @@ -6,7 +6,7 @@ span ¿Olvidaste tu contraseña? :  strong Encuéntrelo aquí
span Email:  strong #{emailto}
-p Para confirmar el registro haz clic en el botón: +p Para confirmar el registro haz clic en el botón, o aquì #{strlinkreg}: div.divbtn button.btn.btn-lg Verificar registro diff --git a/emails/registration_ayni/fr/html.pug b/emails/registration_ayni/fr/html.pug index f9d1dc2..85330a5 100644 --- a/emails/registration_ayni/fr/html.pug +++ b/emails/registration_ayni/fr/html.pug @@ -6,7 +6,7 @@ span avez-vous oublié votre mot de passe ? :  strong Essayez ici
span Email:  strong #{emailto}
-p Cliquez sur le bouton pour confirmer votre inscription : +p Cliquez sur le bouton pour confirmer votre inscription ou cliquez ici #{strlinkreg}: div.divbtn button.btn.btn-lg Vérifier l'enregistrement diff --git a/emails/registration_ayni/it/html.pug b/emails/registration_ayni/it/html.pug index 07eb332..b5923fa 100644 --- a/emails/registration_ayni/it/html.pug +++ b/emails/registration_ayni/it/html.pug @@ -6,7 +6,7 @@ span hai dimenticato la Password? :  strong Trovala qui
span Email:  strong #{emailto}
-p Per confermare la registrazione clicca sul bottone: +p Per confermare la registrazione clicca sul bottone oppure clicca qui #{strlinkreg}: div.divbtn button.btn.btn-lg Verifica Registrazione diff --git a/emails/registration_ayni/pt/html.pug b/emails/registration_ayni/pt/html.pug index 8f4fc74..f94a3b1 100644 --- a/emails/registration_ayni/pt/html.pug +++ b/emails/registration_ayni/pt/html.pug @@ -6,7 +6,7 @@ span você esqueceu sua senha? :  strong Encontre-o aqui>br> span Email:  strong #{{emailto}
-p Clique no botão para confirmar o seu registo: +p Clique no botão para confirmar o seu registo ou clique aqui #{strlinkreg}: div.divbtn button.btn.btn-lg Verificação de registro diff --git a/emails/registration_ayni/si/html.pug b/emails/registration_ayni/si/html.pug index a668540..83b2170 100644 --- a/emails/registration_ayni/si/html.pug +++ b/emails/registration_ayni/si/html.pug @@ -6,7 +6,7 @@ span ste pozabili geslo? :  strong Poiščite tukaj
span Email:  strong #{emailto}
-p Za potrditev registracije kliknite na gumb: +p Za potrditev registracije kliknite na gumb ali kliknite tukaj: #{strlinkreg} div.divbtn button.btn.btn-lg Preveri registracijo diff --git a/package.json b/package.json index 6f250e0..973e47e 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,7 @@ "jsonwebtoken": "^8.5.1", "lodash": "^4.17.15", "mongodb": "^3.4.1", - "mongoose": "^5.8.4", + "mongoose": "^5.9.3", "mysql": "^2.17.1", "node-cron": "^2.0.3", "node-emoji": "^1.10.0", diff --git a/src/server/config/config.js b/src/server/config/config.js index 0715678..0016589 100644 --- a/src/server/config/config.js +++ b/src/server/config/config.js @@ -34,6 +34,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '2', @@ -49,6 +50,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '3', @@ -64,6 +66,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '4', @@ -79,6 +82,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '6', @@ -94,6 +98,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '7', @@ -109,6 +114,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'1037577457:AAGQbdIuYoB838v61ewJ0Hearx9UPpTBhMI', telegram_bot_name: 'notevoleaynibot', pathreg_add:'_ayni', + abilitanave: false, }, { idapp: '8', @@ -124,6 +130,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, ]; } else if (process.env.NODE_ENV === 'test') { @@ -143,6 +150,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '2', @@ -158,6 +166,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '3', @@ -172,6 +181,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '4', @@ -186,6 +196,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '6', @@ -200,6 +211,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '7', @@ -214,6 +226,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'1011893908:AAEThZB3fVPw8P5gTCFgTEsDmY21DdbV1Cw', telegram_bot_name: 'testnotevoleaynibot', pathreg_add:'_ayni', + abilitanave: true, }, { idapp: '8', @@ -229,6 +242,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, ]; } else { @@ -248,6 +262,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '2', @@ -263,6 +278,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '3', @@ -275,6 +291,7 @@ if (process.env.NODE_ENV === 'production') { email_from: 'info.pianetalibero@gmail.com', email_pwd: '66ffeb915e71fada64ad5c26947dd087c262be3b343734a0447c6dee534b888aZcfbjXEuMBWKxvbh60cniw==', pathreg_add:'', + abilitanave: false, }, { idapp: '4', @@ -289,6 +306,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '6', @@ -303,6 +321,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, { idapp: '7', @@ -317,6 +336,7 @@ if (process.env.NODE_ENV === 'production') { telegram_bot_name: 'paotestlocalebot', telegram_key:'353996190:AAEcEbfrm_zTK6mBKf8ye9j-PXt958SDxew', pathreg_add:'_ayni', + abilitanave: true, }, { idapp: '8', @@ -332,6 +352,7 @@ if (process.env.NODE_ENV === 'production') { telegram_key:'', telegram_bot_name: '', pathreg_add:'', + abilitanave: false, }, ]; diff --git a/src/server/locales/back/en.json b/src/server/locales/back/en.json new file mode 100644 index 0000000..200c4ea --- /dev/null +++ b/src/server/locales/back/en.json @@ -0,0 +1,4 @@ +{ + "Email Verificata!": "Email Verified! Close this window and return to the other.", + "partecipanti": "participants", +} diff --git a/src/server/locales/back/es.json b/src/server/locales/back/es.json new file mode 100644 index 0000000..ecd6c4f --- /dev/null +++ b/src/server/locales/back/es.json @@ -0,0 +1,8 @@ +{ + "L'Email è già stata Verificata": "El email ya ha sido verificado", + "Email Verificata!": "Email Verificada! Cierre esta ventana y regrese a la otra.", + "a": "a", + "Nuova Registrazione": "Nuevo Registro", + "Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro", + "partecipanti": "participantes", +} diff --git a/src/server/locales/back/it.json b/src/server/locales/back/it.json new file mode 100644 index 0000000..48621d3 --- /dev/null +++ b/src/server/locales/back/it.json @@ -0,0 +1,8 @@ +{ + "L'Email è già stata Verificata": "L'Email è già stata Verificata", + "Email Verificata!": "Email Verificata! Chiudere questa finestra e ritornare sull'altra.", + "a": "a", + "Nuova Registrazione": "Nuova Registrazione", + "Effettuata una Nuova Registrazione": "Effettuata una Nuova Registrazione", + "partecipanti": "partecipanti", +} diff --git a/src/server/models/billettera.js b/src/server/models/billettera.js deleted file mode 100644 index e8b5d09..0000000 --- a/src/server/models/billettera.js +++ /dev/null @@ -1,412 +0,0 @@ -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 telegrambot = require('../telegram/telegrambot'); - -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 BilletteraSchema = new mongoose.Schema({ - idapp: { - type: String, - required: true, - }, - riga: { - type: Number, - }, - col: { - type: Number, - }, - indprimario: { - type: Number, - }, - parent_indprimario: { - type: Number, - }, - date_start: { - type: Date - }, - made_gift: { - type: Boolean, - default: false, - }, - received_gift: { - type: Boolean, - default: false, - }, - created: { - type: Date, - }, - num_tess: { // numero di tessitura - type: Boolean, - default: 1 - } - -}); - -BilletteraSchema.statics.getTotInLista = async function (idapp) { - const Billettera = this; - - const myfind = { idapp }; - - return await Billettera.count(myfind); -}; - -BilletteraSchema.statics.findByIndOrder = function (idapp, ind_order) { - const User = this; - - try { - return User.findOne({ - 'idapp': idapp, - 'ind_order': ind_order, - }); - } catch (e) { - - } -}; - - -BilletteraSchema.statics.getFieldsForSearch = function () { - return ['username', 'name', 'surname', 'ind_order'] -}; - -BilletteraSchema.statics.executeQueryTable = function (idapp, params) { - params.fieldsearch = this.getFieldsForSearch(); - return tools.executeQueryTable(this, idapp, params); -}; - -BilletteraSchema.statics.findAllIdApp = function (idapp) { - const Billettera = this; - - const myfind = { idapp }; - - return Billettera.find(myfind, (err, arrrec) => { - return arrrec - }); -}; - -BilletteraSchema.statics.findByRigaCol = function (idapp, riga, col) { - const Billettera = this; - - const myfind = { idapp, riga, col }; - - return Billettera.findOne(myfind, (err, arrrec) => { - return arrrec - }); -}; - -BilletteraSchema.statics.findRecByRigaColParent = async function (idapp, riga, col, numparentUp) { - const Billettera = this; - - const myfind = { idapp, riga, col }; - - let parentup = 0; - let myrec = null; - while (parentup < numparentUp) { - myrec = await Billettera.findOne(myfind); - - if (myrec.parent_indprimario === 0) - break; - } - - return myrec; - -}; - -function getlimiti(mypos) { - - if (mypos.col < 0) { - mypos.col = 0; - } - - if (mypos.riga < 0) { - mypos.riga = 0; - mypos.col = 0; - } - - return mypos; -} - -function getRigaColByPosUp(mypos) { - riga = riga - mypos.numup; - col = Math.ceil(col / (Math.pow(2, mypos.numup))); - if ((col % 2) !== 0) - col++; - -} - -function getRigaColGenerica(idapp, riga, col, numup) { - mypos = { - riga, - col, - numup - }; - - if (idapp === tools.AYNI) { - this.getRigaColByPosUp(mypos); - ris = this.getlimiti(mypos); - riga = ris.riga; - col = ris.col; - } - - return { riga, col }; -} - - -function getRigaColSognatoreByFuoco(idapp, riga, col) { - return this.getRigaColGenerica(idapp, riga, col, 6); -} - -function getRigaColMediatoreByFuoco(idapp, riga, col) { - return this.getRigaColGenerica(idapp, riga, col, 3); -} - - -BilletteraSchema.statics.findMediatoreByFuoco = function (idapp, riga, col) { - const Billettera = this; - - const myrigacol = getRigaColMediatoreByFuoco(idapp, riga, col); - - const myfind = { idapp, riga: myrigacol.riga, col: myrigacol.col }; - - return Billettera.findOne(myfind, (err, arrrec) => { - return arrrec - }); -}; - -function getQueryProj(myfilter) { - const query = [ - { $match: myfilter }, - { - $lookup: { - from: "users", - localField: "ind_order", - foreignField: "ind_order", // field in the user collection - as: "user" - } - }, - { - $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] }, "$$ROOT"] } } - }, - ]; - - return query; -} - -BilletteraSchema.statics.findSognatoreByFuoco = function (idapp, riga, col) { - const Billettera = this; - - const myrigacol = getRigaColSognatoreByFuoco(idapp, riga, col); - - const myquery = this.getQueryProj({ idapp, riga: myrigacol.riga, col: myrigacol.col }); - - return Billettera.find(myquery, (err, arrrec) => { - return arrrec - }); -}; - - -BilletteraSchema.statics.setRiga = async function (idapp, riga) { - const newrec = new Settings({ key: 'riga' }); - newrec._id = new ObjectID(); - newrec.idapp = idapp; - newrec.type = tools.FieldType.number; - newrec.value_num = riga; - - await newrec.save(); -}; - -BilletteraSchema.statics.getRiga = async function (idapp) { - const ret = await Settings.findOne({ key: 'riga', idapp }); - if (!!ret) { - return ret.value_num; - } else { - return 1; - } -}; - -BilletteraSchema.statics.setCol = async function (idapp, col) { - const newrec = new Settings({ key: 'col' }); - newrec._id = new ObjectID(); - newrec.idapp = idapp; - newrec.type = tools.FieldType.number; - newrec.value_num = col; - - await newrec.save(); -}; - -BilletteraSchema.statics.getCol = async function (idapp) { - const ret = await Settings.findOne({ key: 'col', idapp }); - if (!!ret) { - return ret.value_num; - } else { - return 1; - } -}; - -function getmaxcol(riga) { - - let maxcol = 1; - if (riga === 1) { - maxcol = 1; - } else if (riga === 2) { - maxcol = 2; - } else { - maxcol = Math.pow(riga - 1, 2); - } - - return maxcol; -} - -function getPrimoFuocoByIndCol(col) { - return Math.ceil(col / 8) + (col % 8); -} - -function getusertextbyrec(myrec, symbol) { - return symbol + ' ' + recfuoco.ind_order + ' (' + recfuoco.name + ' ' + recfuoco.surname + ')'; -} - -BilletteraSchema.statics.getPlaccaByFuoco = async function (idapp, riga, col) { - const Billettera = this; - - try { - let recsognatore = await Billettera.findSognatoreByFuoco(idapp, riga, col); - let recmediatore = await Billettera.findMediatoreByFuoco(idapp, riga, col); - - let primofuoco = this.getPrimoFuocoByIndCol(col); - - mystr = '🌈 Dreamer ' + this.getusertextbyrec(recsognatore, '🔥') + tools.ACAPO; - mystr = '🌈 Mediator ' + this.getusertextbyrec(recmediatore, '🔥') + tools.ACAPO; - - mystr = '🔥🌏💦💨🔥🌏💦💨' + tools.ACAPO; - - for (let indcol = primofuoco; indcol < primofuoco + 8; indcol++) { - let recfuoco = await Billettera.findByRigaCol(idapp, riga, indcol); - mystr += this.getusertextbyrec(recfuoco, '🔥') + tools.ACAPO; - } - } catch (e) { - console.error(e); - } - -} - -function Fuochi8Completati(idapp, riga, col) { - // Inviare un msg al Mediatore che può aprire la Chat con gli 8 fuochi - - // Inviare un msg a questi 8 Fuochi, che la loro placca è Pronta ! - - txt = ''; - // Inviare la placca a Managers - telegrambot.sendMsgTelegramToTheManagers(idapp, txt); -} - -BilletteraSchema.statics.generaBillettera = async function (idapp) { - const Billettera = this; - - let riga = await Billettera.getRiga(idapp); - let col = await Billettera.getCol(idapp); - - let primavolta = (riga === 1) && (col === 1); - primavolta = false; - - const recfindFondo = await Billettera.findByRigaCol(idapp, 0, 0); - if (!recfindFondo) { - billettera = new Billettera({ idapp, indprimario: 0, riga: 0, col: 0 }); - billettera.created = new Date(); - await billettera.save(); - - const UserFondo = await User.findByIndOrder(idapp, 0); - if (!UserFondo) { - telegrambot.sendMsgTelegramToTheAdmin(idapp, 'Devi creare l\'utente FONDO , con ind_order = 0 ! '); - } - } - - - let maxcol = getmaxcol(riga); - - // Identifica il prossimo d'aggiungere - - arrlistaingresso = await ListaIngresso.find({ 'idapp': idapp, added: false }).sort({ indprimario: 1 }); - - let conta = 0; - let colparent = Math.ceil(col / 2); - let rigaparent = riga - 1; - - for (const reclista of arrlistaingresso) { - - billettera = new Billettera({ idapp, indprimario: reclista.indprimario, riga, col }); - billettera.created = new Date(); - - const recfind = await Billettera.findByRigaCol(idapp, rigaparent, colparent); - if (!!recfind) { - billettera.parent_indprimario = recfind.indprimario; - } else { - billettera.parent_indprimario = 0; - } - - await billettera.save() - .then(async (result) => { - let fields_to_update = { added: true }; - const ris = await ListaIngresso.findOneAndUpdate({ _id: reclista._id.toString() }, { $set: fields_to_update }, { new: false }); - - await Billettera.setRiga(idapp, riga); - await Billettera.getCol(idapp, col); - conta++; - - // Check if Billetera has Completed - if (idapp === tools.AYNI) { - if ((col % 8) === 0) { - // Completed 8 people - let text = 'Completata Billettera [riga=' + riga + ',col=' + col + ']'; - tools.writeBilletteraLog(text); - if (!primavolta) { - telegrambot.sendMsgTelegramToTheManagers(idapp, text); - this.Fuochi8Completati(idapp, riga, col); - } - } - } - - // Next - if (col === maxcol) { - riga++; - rigaparent = riga - 1; - col = 1; - maxcol = getmaxcol(riga); - } else { - col++; - } - - if ((col % 2) !== 0) - colparent++; - - }); - - } - -}; - - -const Billettera = mongoose.model('Billettera', BilletteraSchema); - - -module.exports = { Billettera }; - - diff --git a/src/server/models/listaingresso.js b/src/server/models/listaingresso.js index f4d583f..9511780 100644 --- a/src/server/models/listaingresso.js +++ b/src/server/models/listaingresso.js @@ -6,6 +6,10 @@ const _ = require('lodash'); const tools = require('../tools/general'); +const { ObjectID } = require('mongodb'); + +const { Nave } = require('./nave'); + const shared_consts = require('../tools/shared_nodejs'); const queryclass = require('../classes/queryclass'); @@ -30,16 +34,17 @@ const ListaIngressoSchema = new mongoose.Schema({ ind_order: { type: Number, }, - username: { - type: String, + date_added: { + type: Date, }, - name: { - type: String, + added: { // Added into Programmation (Nave) + type: Boolean, + default: false, }, - surname: { - type: String, + num_tess: { + type: Number, }, - added: { // Added into Programmation (Billettera) + deleted: { type: Boolean, default: false, } @@ -48,7 +53,7 @@ const ListaIngressoSchema = new mongoose.Schema({ ListaIngressoSchema.pre('save', async function (next) { if (this.isNew) { - const myrec = await ListaIngresso.findOne().limit(1).sort({indprimario:-1}); + const myrec = await ListaIngresso.findOne().limit(1).sort({ indprimario: -1 }); if (!!myrec) { if (myrec._doc.indprimario === 0) this.indprimario = 1; @@ -108,9 +113,123 @@ ListaIngressoSchema.statics.findByIndOrder = function (idapp, ind_order) { } }; +ListaIngressoSchema.statics.findByIndOrderETess = function (idapp, ind_order, num_tess) { + const ListaIngresso = this; + + try { + return ListaIngresso.findOne({ + 'idapp': idapp, + 'ind_order': ind_order, + num_tess, + }); + } catch (e) { + + } +}; + +ListaIngressoSchema.statics.deleteUserInListaIngresso = async function (idapp, ind_order) { + const ListaIngresso = this; + + return ListaIngresso.findOneAndUpdate({ + idapp, + ind_order, + }, { $set: { deleted: true } }, { new: false }) + +}; + +ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, ind_order, lang, addednowreal, num_tess) { + const ListaIngresso = this; + + const { User } = require('./user'); + const telegrambot = require('../telegram/telegrambot'); + + try { + let listaingresso = null; + if (!await ListaIngresso.findByIndOrderETess(idapp, ind_order, num_tess)) { + listaingresso = new ListaIngresso({ + ind_order: ind_order, + idapp, + num_tess, + date_added: new Date(), + _id: new ObjectID() + }); + + if (listaingresso) { + return await listaingresso.save().then(async (ris) => { + if (addednowreal) { + if (!!ris) { + msgtext = tools.gettranslate('ADDED_TOLISTAINGRESSO', lang); + const username = await User.getUsernameByIndOrder(idapp, ind_order); + await telegrambot.sendMsgTelegram(idapp, username, msgtext, true); // Anche a STAFF + } + } + return ris; + }); + } + } + + const giapresente = await Nave.findOne({ idapp, ind_order: num_tess }); + if (!!giapresente) { + // Era stato già aggiunto! + let fields_to_update = { added: true }; + await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); + + return false; + } + + return null; + + } catch (e) { + console.error(e); + } + return null; +}; + + +function getQueryProj(myfilter) { + const query = [ + { $match: myfilter }, + { + $lookup: { + from: "users", + localField: "ind_order", + foreignField: "ind_order", // field in the user collection + as: "user" + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] }, "$$ROOT"] } } + }, + ]; + + return query; +} + + +ListaIngressoSchema.statics.showListaOrd = async function (idapp) { + const ListaIngresso = this; + + const myquery = getQueryProj({ idapp }); + + arrrec = await ListaIngresso.aggregate(myquery).sort({ indprimario: 1 }); + + let mystr = ''; + let conta = 1; + for (const rec of arrrec) { + mystr += '[' + conta + '] ' + rec.ind_order + ' (' + rec.ind_order + ') ' + rec.name + ' ' + rec.surname; + if (rec.added) + mystr += ' (ADDED ++)'; + + mystr += '\n'; + conta++; + } + + return mystr; +}; + ListaIngressoSchema.statics.getFieldsForSearch = function () { - return ['username', 'name', 'surname', 'ind_order'] + return ['ind_order'] }; ListaIngressoSchema.statics.executeQueryTable = function (idapp, params) { @@ -128,6 +247,45 @@ ListaIngressoSchema.statics.findAllIdApp = function (idapp) { }); }; +function sortRec(rec) { + return rec.sort(function (reca, recb) { + return recb.numinvitatiattivi - reca.numinvitatiattivi + }); +} + +ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, tutti) { + const ListaIngresso = this; + + const myquery = getQueryProj({ + 'idapp': idapp, + ind_order: { $gt: 0 }, + added: false, + deleted: false, + }); + + arrrec = await ListaIngresso.aggregate(myquery).sort({ indprimario: 1 }) + .then(async (arrlista) => { + + const { User } = require('../models/user'); + + for (const rec of arrlista) { + rec.numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, rec.username); + if (rec.numinvitatiattivi > 2) + rec.numinvitatiattivi = 2; + } + if (arrlista) { + arrlista = sortRec(arrlista); + // arrlista.reverse(); + } + + return arrlista; + }).catch((e) => { + console.error(e); + return null + }); + + return arrrec; +}; const ListaIngresso = mongoose.model('ListaIngresso', ListaIngressoSchema); diff --git a/src/server/models/nave.js b/src/server/models/nave.js new file mode 100644 index 0000000..32a6a74 --- /dev/null +++ b/src/server/models/nave.js @@ -0,0 +1,991 @@ +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 NaveSchema = new mongoose.Schema({ + idapp: { + type: String, + required: true, + }, + riga: { + type: Number, + }, + col: { + type: Number, + }, + indprimario: { + type: Number, + }, + ind_order: { + type: Number, + }, + parent_id: { + type: mongoose.Schema.Types.ObjectId, + }, + date_start: { + type: Date + }, + link_chat: { + type: String, + }, + sent_msg_howto_make_gift: { + type: Boolean, + default: false, + }, + made_gift: { + type: Boolean, + default: false, + }, + date_made_gift: { + type: Date, + }, + received_gift: { + type: Boolean, + default: false, + }, + date_received_gift: { + type: Date, + }, + created: { + type: Date, + }, + num_tess: { // numero di tessitura + type: Number, + default: 1 + } + +}); + +NaveSchema.statics.getTotInLista = async function (idapp) { + const Nave = this; + + const myfind = { idapp }; + + return await Nave.count(myfind); +}; + +NaveSchema.statics.findByIndOrder = function (idapp, ind_order) { + const Nave = this; + + try { + return Nave.findOne({ + 'idapp': idapp, + 'ind_order': ind_order, + }); + } catch (e) { + + } +}; + +NaveSchema.statics.findById = function (idapp, id) { + const Nave = this; + + const myquery = getQueryProj({ idapp, '_id': ObjectID(id) }); + + return Nave.aggregate(myquery); + +}; + +NaveSchema.statics.findByIndPrimario = function (idapp, indprimario) { + const Nave = this; + + try { + return Nave.findOne({ + idapp, + indprimario, + }); + } catch (e) { + + } +}; + + +NaveSchema.statics.getFieldsForSearch = function () { + return ['username', 'name', 'surname', 'ind_order'] +}; + +NaveSchema.statics.executeQueryTable = function (idapp, params) { + params.fieldsearch = this.getFieldsForSearch(); + return tools.executeQueryTable(this, idapp, params); +}; + +NaveSchema.statics.findAllIdApp = function (idapp) { + const Nave = this; + + const myfind = { idapp }; + + return Nave.find(myfind, (err, arrrec) => { + return arrrec + }); +}; + +NaveSchema.statics.findByRigaCol = function (idapp, riga, col, nullifnotexist) { + const Nave = this; + + myrigacol = { + idapp, + riga, + col, + nullifnotexist + }; + + return Nave.findGeneric(myrigacol); + +}; + +NaveSchema.statics.findDonatoreByNave = function (idapp, nave) { + try { + + const arrrigacol = nave.split("."); + if (arrrigacol.length <= 0) + return; + + let riganave = parseInt(arrrigacol[0]); + let colnave = parseInt(arrrigacol[1]); + + let rigadonatore = riganave + 3; + if (rigadonatore < 1) + rigadonatore = 1; + + coldonatoreIni = calcval(riganave, colnave, 8) + (1); + coldonatoreFine = calcval(riganave, colnave, 8) + (8); + + const miaquery = { + idapp, + riga: rigadonatore, + $and: [{ col: { $gte: { coldonatoreIni } } }, { col: { $lte: { coldonatoreFine } } }] + }; + + return Nave.findOne(miaquery); + } catch (e) { + + } +}; + +function getIndColonneByNave(navemediatore) { + let riga = navemediatore.riga; + let col = navemediatore.col; + + let col_ini = calcval(riga, col, 8) + 1; + let col_fine = col_ini + 8; + + return { riga: riga + 3, col_ini, col_fine } +} + +NaveSchema.statics.getusersByNave = function (idapp, navemediatore) { + + const obj = getIndColonneByNave(navemediatore); + + const miacol_ini = obj.col_ini; + const miacol_fine = obj.col_fine; + + const miaquery = { + idapp, + riga: obj.riga, + $and: [ + { col: { $gte: miacol_ini } }, + { col: { $lte: miacol_fine } } + ], + }; + + return Nave.find(miaquery); + +}; + + +NaveSchema.statics.findRecByRigaColParent = async function (idapp, riga, col, numparentUp) { + const Nave = this; + + const { User } = require('./user'); + + const myrigacol = { + idapp, + riga, + col + }; + + if (numparentUp === 0) { + return await Nave.findGeneric(myrigacol); + } + + let parentup = 0; + let myrec = null; + let lastrec = null; + + while (parentup < numparentUp) { + + myrec = await Nave.findGeneric(myrigacol); + if (!!myrec) { + if (myrec.parent_id === "0") { + break; + } + + 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); + break; + } + } + } + parentup++; + } + + if (!lastrec) { + return await User.findByIndOrder(idapp, 0); + } + + return lastrec; + +}; + +function getlimiti(mypos) { + + if (mypos.col < 0) { + mypos.col = 0; + } + + if (mypos.riga < 0) { + mypos.riga = 0; + mypos.col = 0; + } + + return mypos; +} + +function getRigaColByPosUp(mypos) { + mypos.riga = mypos.riga - mypos.numup; + mypos.col = Math.floor(mypos.col / (Math.pow(2, mypos.numup))); + // if ((mypos.col % 2) !== 0) + // mypos.col++; + +} + +function getRigaColGenerica(idapp, riga, col, numup) { + mypos = { + idapp, + riga, + col, + numup + }; + + if (idapp === tools.AYNI) { + 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) { + + const { ListaIngresso } = require('./listaingresso'); + + const myquery = getQueryProj({ idapp: myrigacol.idapp, riga: myrigacol.riga, col: myrigacol.col }); + + return Nave.aggregate(myquery) + .then(async (rec) => { + if (!rec || rec.length === 0) { + if (myrigacol.nullifnotexist) + return null; + + const ris = await ListaIngresso.findByIndOrder(myrigacol.idapp, 0); + const arr = []; + arr.push(ris); + return arr; + } + else { + return rec; + } + } + ).then(async (rec) => { + + const { User } = require('./user'); + + if (!!rec) { + if (rec.length > 0) { + // console.log('rec', rec); + // console.table('myrigacol', myrigacol); + if (!!rec[0]) { + const newrec = await User.getSmallRecByIndOrder(myrigacol.idapp, rec[0].ind_order); + if (!!newrec) { + let myarr = {}; + if (rec[0]._doc === undefined) + myarr = { ...newrec._doc, ...rec[0] }; + else + myarr = { ...newrec._doc, ...rec[0]._doc }; + return myarr; + } else { + let myarr = null; + if (rec[0]._doc === undefined) + myarr = { ...newrec._doc, ...rec[0] }; + else + myarr = { ...newrec._doc, ...rec[0]._doc }; + + return myarr; + } + } else { + const ris = await ListaIngresso.findByIndOrder(myrigacol.idapp, 0); + if (!!ris) + return ris[0] + } + } + } + return null; + }).catch((e) => { + console.error(e); + }); + +} +; + + +NaveSchema.statics.findSognatoriByFuoco = async function (idapp, riga, col, offset) { + const Nave = this; + + // const myrigacol = getRigaColSognatoreByFuoco(idapp, riga, col); + + // return Nave.findGeneric(myrigacol); + + return [await Nave.findRecByRigaColParent(idapp, riga, col, 6 - offset), + await Nave.findRecByRigaColParent(idapp, riga, col, 5 - offset), + await Nave.findRecByRigaColParent(idapp, riga, col, 4 - offset) + ] + +}; + + +NaveSchema.statics.findMediatoreByFuoco = async function (idapp, riga, col, offset) { + const Nave = this; + + // const myrigacol = getRigaColMediatoreByFuoco(idapp, riga, col); + // return Nave.findGeneric(myrigacol); + return await Nave.findRecByRigaColParent(idapp, riga, col, 3 - offset); + + +}; + +function getQueryProj(myfilter) { + + myobjField = { + _id: 1, + lang: 1, + ind_order: 1, + name: 1, + surname: 1, + username: 1, + date_start: 1, + made_gift: 1, + link_chat: 1, + date_made_gift: 1, + received_gift: 1, + date_received_gift: 1, + num_tess: 1, + indprimario: 1, + parent_id: 1, + riga: 1, + col: 1, + created: 1, + }; + + const query = [ + { $match: myfilter }, + { + $lookup: { + from: "users", + localField: "ind_order", + foreignField: "ind_order", // field in the user collection + as: "user" + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] }, "$$ROOT"] } } + // $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] },] } } + }, + { $project: myobjField } + ]; + + return query; +} + + +NaveSchema.statics.setRiga = function (idapp, riga) { + return Settings.setKeyNum(idapp, 'riga', riga); +}; + +NaveSchema.statics.getRiga = function (idapp) { + return Settings.getKeyNum(idapp, 'riga', 1); +}; + +NaveSchema.statics.setCol = function (idapp, col) { + return Settings.setKeyNum(idapp, 'col', col); +}; + +NaveSchema.statics.getCol = function (idapp) { + return Settings.getKeyNum(idapp, 'col', 1); +}; + +function getmaxcol(riga) { + + return Math.pow(2, riga - 1); +} + +function getPrimoFuocoByIndCol(col) { + return Math.floor(col - (col % 8)) + 1; +} + +async function getusertextbyrec(myrec, symbol, lettera, riga, col, ind) { + let visu_test = false; + if (!!myrec) + visu_test = await Settings.getValDbSettings(myrec.idapp, 'VISU_TEST'); + + if (!visu_test) { + if (myrec) + return lettera + ind + ' - ' + symbol + ' ' + myrec.name + ' ' + tools.getFirst2Car(myrec.surname) + ' (' + myrec.username + ')'; + else + return lettera + ind + ' - ' + symbol; + + } else { + if (myrec) + return lettera + ind + ' - ' + symbol + '[' + miariga + ',' + miacol + ']' + ' ' + myrec.name + ' ' + myrec.surname + ''; + else + return lettera + ind + ' - ' + symbol; + } +} + +NaveSchema.statics.getPlaccaGenerica = async function (idapp, riga, col, offset, solorecord) { + const Nave = this; + + try { + let recsognatori = await Nave.findSognatoriByFuoco(idapp, riga, col, offset); + let recmediatore = await Nave.findMediatoreByFuoco(idapp, riga, col, offset); + + let primofuoco = getPrimoFuocoByIndCol(col); + + mystr = 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.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: '💦' + }; + } + + // mystr += '🔥🌏💦💨🔥🌏💦💨' + tools.ACAPO; + + let arrdonatori = []; + let ind = 1; + for (let indcol = primofuoco; indcol < primofuoco + 8; indcol++) { + let indr = riga + offset; + let indc = indcol + (offset * indr); + + indr = riga + offset; + indc = calcval(riga, col, 8) + (indcol - primofuoco + 1); + // miacol = calcval(riga, col, 8) + (indfuoco); + + + let recfuoco = await Nave.findByRigaCol(idapp, indr, indc, true); + arrdonatori.push(recfuoco); + mystr += await getusertextbyrec(recfuoco, symb.icona, symb.car, indr, indc, ind) + tools.ACAPO; + ind++; + } + + if (solorecord) { + res = { + recsognatori, + recmediatore, + arrdonatori + }; + + return res; + } else { + return mystr; + } + + } catch (e) { + console.error(e); + } + +}; + +NaveSchema.statics.getPlaccaPerDonatore = async function (idapp, riga, col, solorecord) { + const Nave = this; + return Nave.getPlaccaGenerica(idapp, riga, col, tools.Placca.SONOFUOCO, solorecord); +}; + +NaveSchema.statics.getPlaccaPerMediatore = async function (idapp, riga, col, solorecord) { + const Nave = this; + return Nave.getPlaccaGenerica(idapp, riga, col, tools.Placca.SONOACQUA, solorecord); +}; + +function calcval(riga, col, quanti) { + return (quanti * (col - 1)); +} + +NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord) { + const Nave = this; + + try { + let recsognatori = [await Nave.findRecByRigaColParent(idapp, riga, col, 3), + await Nave.findRecByRigaColParent(idapp, riga, col, 2), + await Nave.findRecByRigaColParent(idapp, riga, col, 1)]; + + let recmediatore = await Nave.findByRigaCol(idapp, riga, col, true); + + + mystr = '🌈SOGNATORE: '; + for (let indsogn = 0; indsogn < recsognatori.length; indsogn++) { + mystr += 'A' + (3 - indsogn) + await getusertextbyrec(recsognatori[indsogn], '', '', riga, col, '') + tools.ACAPO; + } + + mystr += tools.ACAPO + '🌀 MEDIATORE:' + await getusertextbyrec(recmediatore, '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; + + for (let indterra = 1; indterra <= 2; indterra++) { + miacol = calcval(riga, col, 2) + (indterra); + miariga = riga + 1; + let recterra = await Nave.findByRigaCol(idapp, miariga, miacol, true); + mystr += await getusertextbyrec(recterra, '', 'B', miariga, miacol, indterra) + tools.ACAPO; + } + + mystr += tools.ACAPO; + + for (let indaria = 1; indaria <= 4; indaria++) { + miacol = calcval(riga, col, 4) + (indaria); + miariga = riga + 2; + let recaria = await Nave.findByRigaCol(idapp, miariga, miacol, true); + mystr += await getusertextbyrec(recaria, '', 'C', miariga, miacol, indaria) + tools.ACAPO; + } + + mystr += tools.ACAPO; + + let primofuoco = null; + + mystr += '🎁 DONATORI:' + tools.ACAPO; + for (let indfuoco = 1; indfuoco <= 8; indfuoco++) { + miacol = calcval(riga, col, 8) + (indfuoco); + miariga = riga + 3; + // miariga = riga + 2; + let recfuoco = await Nave.findByRigaCol(idapp, miariga, miacol, true); + if (indfuoco === 1) + primofuoco = recfuoco; + mystr += await getusertextbyrec(recfuoco, '', 'D', miariga, miacol, indfuoco) + tools.ACAPO; + } + + let data = ""; + if (primofuoco) + data = "Partenza il " + tools.getstrDateLong(primofuoco.date_start) + tools.ACAPO; + else + data = ""; + + mystr = tools.ACAPO + 'NAVE (' + riga + '.' + col + ') ' + tools.ACAPO + data + tools.ACAPO + mystr; + + return mystr; + } catch (e) { + console.error(e); + } + +}; + +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 }); + + return arrposizioni; +}; + +NaveSchema.statics.getPrimaNaveByRiga = async function (idapp, riga) { + const Nave = this; + + nave = await Nave.find({ 'idapp': idapp, riga: (riga + 3), col: 1 }); + + return nave; +}; + +NaveSchema.statics.showListaOrd = async function (idapp) { + const Nave = this; + + const myquery = getQueryProj({ idapp }); + + arrrec = await Nave.aggregate(myquery).sort({ riga: 1, col: 1 }); + + let mystr = ''; + let conta = 1; + for (const rec of arrrec) { + mystr += '[' + conta + '] [' + rec.riga + '.' + rec.col + '] ' + rec.ind_order + ' ' + rec.name + ' ' + rec.surname + ' (' + tools.getstrDateShort(rec.date_start) + ')\n'; + conta++; + } + + + return mystr; +}; + +async function addRecordNaveByParams(params, siRitesse) { + const { ListaIngresso } = require('./listaingresso'); + + if (!siRitesse) { + // Check if Exist: + const giapresente = await Nave.findOne({ idapp: params.idapp, ind_order: params.ind_order, 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 }); + + return false; + } + } + + + let myNave = new Nave({ + idapp: params.idapp, + indprimario: params.indprimario, + ind_order: params.ind_order, + riga: params.riga, + col: params.col, + date_start: params.date_start, + num_tess: params.num_tess, + }); + myNave.created = new Date(); + + console.log('[' + params.riga + ',' + params.col + ']'); + + const recfindparent = await Nave.findByRigaCol(idapp, params.rigaparent, params.colparent, false); + if (!!recfindparent) { + myNave.parent_id = recfindparent._id; + } else { + myNave.parent_id = "0"; + } + + 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 }); + + params.conta++; + + // Check if the Ship has Completed + if (idapp === tools.AYNI) { + if ((params.col % 8) === 0) { + // Completed 8 people + if (!params.primavolta) { + await Fuochi8Completati(idapp, params); + } + } + } + + // Next + if (params.col === params.maxcol) { + params.riga++; + params.rigaparent = params.riga - 1; + params.col = 1; + params.maxcol = getmaxcol(params.riga); + } else { + params.col++; + } + + if (params.riga === 2) + params.colparent = 1; + else + params.colparent = Math.ceil(params.col / 2); + + await Nave.setRiga(idapp, params.riga); + await Nave.setCol(idapp, params.col); + + return true; + } + + return false; + + }).catch((e) => { + console.error(e); + }); +} + +NaveSchema.statics.checkifDeveRitessersi = async function (recuser) { + const Nave = this; + + let deveritessersi = true; + + arrrec = await Nave.find({ idapp: recuser.idapp, ind_order: recuser.ind_order }); + + if (!!arrrec) { + if (arrrec.length > 2) { + // deveritessersi = await User.deveRitessersi(recuser.idapp, recuser.ind_order) + deveritessersi = false; + } + } + + return { deveritessersi, num_tess: arrrec.length }; + +}; + + +NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, idapp, params, addednowreal) { + const Nave = this; + + const { User } = require('./user'); + + if (init) { + params.idapp = idapp; + params.conta = 0; + } + + 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.colparent = Math.ceil(params.col / 2); + params.rigaparent = params.riga - 1; + + myriga = params.riga; + mycol = params.col; + + const inserito = await addRecordNaveByParams(params, false); + if (inserito) { + if (idapp === tools.AYNI) { + if (((params.col) % 8) === 0) { + // Trova se la persona di 3 livelli sopra, si deve ritessere + let recmediatore = await Nave.findMediatoreByFuoco(idapp, myriga, mycol, 0); + if (!!recmediatore) { + const ris = await Nave.checkifDeveRitessersi(recmediatore); + if (ris.num_tess > 2) { + console.log('E\' arrivato alla TERZA RITESSITURA, PERTANTO LO METTIAMO IN CODA... [riga=', params.riga, 'col', params.col, '] indorder=' + recmediatore.ind_order); + // E' arrivato alla TERZA RITESSITURA, PERTANTO LO METTIAMO IN CODA... + const risultato = await ListaIngresso.addUserInListaIngresso(idapp, recmediatore.ind_order, rec.lang, false, ris.num_tess); + + } else { + console.log('Si deve ritessere: [riga=', params.riga, 'col', params.col, ']'); + if (ris.deveritessersi) { + params.indprimario = recmediatore.indprimario; + params.ind_order = recmediatore.ind_order; + params.id = recmediatore._id; + params.num_tess = ris.num_tess; + + await addRecordNaveByParams(params, true); + } + } + } + } + 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); + params.indprimario = userFondo.indprimario; + params.ind_order = userFondo.ind_order; + params.id = userFondo._id; + params.num_tess = userFondo.num_tess; + + await addRecordNaveByParams(params, true); + } + } + } + + // Se ho completato 8 persone, allora + if (addednowreal) { + + } + +}; + +NaveSchema.statics.generaNave = async function (idapp, mydata) { + const Nave = this; + + const { User } = require('./user'); + const { ListaIngresso } = require('./listaingresso'); + + let params = { + idapp, + riga: await Nave.getRiga(idapp), + col: await Nave.getCol(idapp), + date_start: mydata.date_start, + numpersone: mydata.numpersone, + }; + + params.primavolta = (params.riga === 1) && (params.col === 1); + // params.primavolta = false; + + const recfindFondo = await Nave.findByRigaCol(params.idapp, 0, 0, true); + if (!recfindFondo) { + let myNave = new Nave({ idapp, indprimario: 0, ind_order: 0, riga: 0, col: 0 }); + myNave.created = new Date(); + myNave.parent_id = ObjectID("5e592aecbfd0b75f3021d9c9"); + myNave.date_start = params.date_start; + await myNave.save(); + + const userFondo = await User.findByIndOrder(idapp, 0); + if (!userFondo || userFondo === undefined) { + await telegrambot.sendMsgTelegramToTheAdmin(idapp, 'Devi creare l\'utente FONDO , con ind_order = 0 ! '); + } + } + + const arrlistaingresso = await ListaIngresso.getProssimiInLista(idapp, true); + + let index = 0; + for (const reclista of arrlistaingresso) { + + params.indprimario = reclista.indprimario; + params.ind_order = reclista.ind_order; + params.id = reclista._id; + params.num_tess = reclista.num_tess; + + await Nave.addUserFromListaIngresso_IntoNave(index === 0, idapp, params, false); + index++; + + if (index >= params.numpersone) + break; + } + + return params.conta; + +}; + +async function addUserToNave(idapp, rec) { + + let params = {}; + + params.indprimario = rec.indprimario; + params.ind_order = rec.ind_order; + params.id = rec._id; + params.num_tess = rec.num_tess; + + return await Nave.addUserFromListaIngresso_IntoNave(true, idapp, params, true); + +} + +NaveSchema.statics.checkIfDevoAggiungereInNave = async function (idapp) { + + const { ListaIngresso } = require('./listaingresso'); + + // Ottieni la lista Ordinata in base al numero d'invitati + arrlista = await ListaIngresso.getProssimiInLista(idapp, false); + + for (const rec of arrlista) { + if (rec.numinvitatiattivi >= 2) { + await addUserToNave(idapp, rec); + } + } + +}; + +NaveSchema.statics.getNaveByUser = async function (idapp, ind_order, lang, fuoco) { + const Nave = this; + + let mystr = ''; + const arrposiz = await Nave.getArrPosizioniByIndOrder(idapp, ind_order); + if (!!arrposiz) { + for (const pos of arrposiz) { + mystr += await Nave.getNavePos(idapp, pos.riga - 3, Math.floor(pos.col / (2 * 4)), false); + mystr += await Nave.getPlaccaPerDonatore(idapp, pos.riga, pos.col, false); + mystr += await Nave.getPlaccaPerMediatore(idapp, pos.riga, pos.col, false); + } + } + + if (mystr === '') { + mystr = tools.gettranslate('NO_PROG', lang); + } + + return mystr; +}; + +NaveSchema.statics.getNaveByRigaCol = async function (idapp, riga, col) { + const Nave = this; + + rec = {}; + rec.donatore = await Nave.getPlaccaPerDonatore(idapp, riga, col, true); + rec.mediatore = await Nave.getPlaccaPerMediatore(idapp, riga, col, true); + + return rec; +}; + + +const Nave = mongoose.model('Nave', NaveSchema); + + +module.exports = { Nave }; + + diff --git a/src/server/models/settings.js b/src/server/models/settings.js index 4fd0764..29457e6 100644 --- a/src/server/models/settings.js +++ b/src/server/models/settings.js @@ -95,7 +95,37 @@ SettingsSchema.statics.findAllIdApp = function (idapp, serv) { }); }; +SettingsSchema.statics.setKeyNum = async function (idapp, key, value) { + const Settings = this; -const Settings = mongoose.model('Settings', SettingsSchema); + let myrec = await Settings.findOne({ idapp, key }); + if (!myrec) { + myrec = new Settings({ key }); + myrec._id = new ObjectID(); + myrec.idapp = idapp; + myrec.type = tools.FieldType.number; + myrec.value_num = value; + + return await myrec.save(); + } else { + myrec = await Settings.findOneAndUpdate({ idapp, key }, { $set: { value_num: value } }, { new: false}); + } + +}; + + +SettingsSchema.statics.getKeyNum = async function (idapp, key, mydefault) { + const Settings = this; + + const ret = await Settings.findOne({ idapp, key}); + if (!!ret) { + return ret.value_num; + } else { + return mydefault; + } + +}; + + const Settings = mongoose.model('Settings', SettingsSchema); module.exports = { Settings }; diff --git a/src/server/models/user.js b/src/server/models/user.js index 5987b30..817507e 100644 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -8,7 +8,7 @@ const tools = require('../tools/general'); const { Settings } = require('../models/settings'); const { ListaIngresso } = require('../models/listaingresso'); -const { Billettera } = require('./billettera'); +const { Nave } = require('../models/nave'); const { ExtraList } = require('../models/extralist'); const { ObjectID } = require('mongodb'); @@ -126,6 +126,9 @@ const UserSchema = new mongoose.Schema({ aportador_solidario: { type: String, }, + aportador_iniziale: { + type: String, + }, aportador_solidario_nome_completo: { type: String, }, @@ -188,6 +191,9 @@ const UserSchema = new mongoose.Schema({ special_req: { type: Boolean }, + vuole_ritessersi: { + type: Boolean + }, sex: { type: Number, }, @@ -338,7 +344,7 @@ UserSchema.statics.findByUsername = async function (idapp, username, alsoemail) if ((!ris) && (alsoemail)) { regexemail = new RegExp(["^", username.toLowerCase(), "$"].join(""), "i"); - return await User.findOne({ + return User.findOne({ 'idapp': idapp, 'email': regexemail, }); @@ -365,6 +371,7 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) 'profile.email_paypal': 1, 'profile.my_dream': 1, 'profile.paymenttypes': 1, + 'profile.cell': 1, made_gift: 1, email: 1, date_reg: 1, @@ -389,6 +396,9 @@ UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) }; UserSchema.statics.getDownlineByUsername = async function (idapp, username) { + if (username === undefined) + return null; + const User = this; const arrrec = await User.find({ 'idapp': idapp, @@ -406,6 +416,7 @@ UserSchema.statics.getDownlineByUsername = async function (idapp, username) { 'profile.email_paypal': 1, 'profile.my_dream': 1, 'profile.paymenttypes': 1, + 'profile.cell': 1, made_gift: 1, email: 1, date_reg: 1, @@ -430,32 +441,45 @@ UserSchema.statics.getDownlineByUsername = async function (idapp, username) { UserSchema.statics.getnumInvitatiAttivi = function (idapp, username) { const User = this; - return User.count({ + if (username === undefined) + return 0; + + // return User.count({ + return User.countDocuments({ idapp, aportador_solidario: username, - 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 }, - $and: [ - { "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } }, - { "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } } - ], - $where: "this.profile.paymenttypes.length >= 1", - 'profile.email_paypal': { $exists: true }, + $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: [ + { "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } }, + { "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } } + ], + }] }); }; UserSchema.statics.isUserQualified7 = async function (idapp, username) { const User = this; - const myrec = await User.findOne({ + if (username === undefined) + return false; + + const myquery = { 'idapp': idapp, 'username': username, $or: [ { - special_req: true + 'profile.special_req': true }, { verified_email: true, @@ -464,22 +488,39 @@ UserSchema.statics.isUserQualified7 = async function (idapp, username) { '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", }] - }); + }; + + const myrec = await User.findOne(myquery); return !!myrec; }; +UserSchema.statics.isUserQualified9 = async function (idapp, username) { + const User = this; + + if (username === undefined) + return false; + + qualified = await User.isUserQualified7(idapp, username); + numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, username); + + return qualified && (numinvitatiattivi >= 2); + +}; + UserSchema.statics.getnumPaymentOk = function (idapp) { const User = this; return User.count({ idapp, + 'profile.paymenttypes': { "$in": ['paypal'] }, $where: "this.profile.paymenttypes.length >= 1", 'profile.email_paypal': { $exists: true }, }); @@ -529,6 +570,21 @@ UserSchema.statics.findByLinkreg = function (idapp, linkreg) { }); }; +UserSchema.statics.AportadorOrig = function (idapp, id) { + const User = this; + + return User.findOne({ + '_id': id, + 'idapp': idapp, + }).then((rec) => { + if (rec) + return rec.aportador_iniziale; + else + return ''; + }); +}; + + UserSchema.statics.findByLinkTokenforgot = function (idapp, email, tokenforgot) { const User = this; @@ -560,17 +616,17 @@ UserSchema.statics.findByIndOrder = function (idapp, ind_order) { const User = this; try { + // ++Todo: non mettere tutti i campi !! return User.findOne({ - 'idapp': idapp, - 'ind_order': ind_order, + idapp, + ind_order, }); } catch (e) { - + console.error(e); } }; - UserSchema.pre('save', function (next) { const user = this; @@ -611,6 +667,29 @@ UserSchema.statics.getEmailByUsername = async function (idapp, username) { }); }; +UserSchema.statics.getUsernameById = async function (idapp, id) { + const User = this; + + return await User.findOne({ idapp, _id: id }, { username: 1 }) + .then((myuser) => { + return ((myuser) ? myuser.username : ''); + }).catch((e) => { + + }); +}; + +UserSchema.statics.getUserById = function (idapp, id) { + const User = this; + + return User.findOne({ idapp, _id: id }) +}; + +UserSchema.statics.getUserByAportador = function (idapp, aportador_solidario) { + const User = this; + + return User.findOne({ idapp, aportador_solidario }) +}; + UserSchema.statics.getAportadorSolidarioByUsername = async function (idapp, username) { const User = this; @@ -633,6 +712,17 @@ UserSchema.statics.UserByIdTelegram = async function (idapp, teleg_id) { }); }; +UserSchema.statics.UsersByIdTelegram = async function (idapp, teleg_id) { + const User = this; + + return await User.find({ idapp, 'profile.teleg_id': teleg_id }) + .then((rec) => { + return (!!rec) ? rec._doc : null; + }).catch((e) => { + console.error('UserExistByIdTelegram', e); + }); +}; + UserSchema.statics.TelegIdByUsername = async function (idapp, username) { const User = this; @@ -705,6 +795,24 @@ 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 }, + { + ind_order: 1, + username: 1, + name: 1, + surname: 1 + } + ) + .then((rec) => { + return rec; + }).catch((e) => { + console.error('getSmallRecByIndOrder', e); + }); +}; + UserSchema.statics.getusersManagers = async function (idapp) { const User = this; @@ -717,15 +825,25 @@ UserSchema.statics.getusersManagers = async function (idapp) { }); }; -UserSchema.statics.getUsersTelegALL = async function (idapp) { +UserSchema.statics.getUsersTelegALL = async function (idapp, username) { const User = this; - return await User.find({ idapp, 'profile.teleg_id': { $gt: 0 } }) - .then((arrrec) => { - return (!!arrrec) ? arrrec : null; - }).catch((e) => { - console.error('getUsersTelegALL', e); - }); + if (!!username) { + return await User.find({ idapp, username, 'profile.teleg_id': { $gt: 0 } }) + .then((arrrec) => { + return (!!arrrec) ? arrrec : null; + }).catch((e) => { + console.error('getUsersTelegALL', e); + }); + } else { + return await User.find({ idapp, 'profile.teleg_id': { $gt: 0 } }) + .then((arrrec) => { + return (!!arrrec) ? arrrec : null; + }).catch((e) => { + console.error('getUsersTelegALL', e); + }); + } + }; UserSchema.statics.isManagerByIdTeleg = async function (idapp, idtelegram) { @@ -851,13 +969,15 @@ 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, aportador_solidario); - dashboard.numpeople_aportador = arrap.length; + if (!!arrap) + dashboard.numpeople_aportador = arrap.length; dashboard.downline = await User.getDownlineByUsername(idapp, username); - dashboard.downnotreg = await ExtraList.getDownlineNotRegisteredByNameSurname(idapp, dashboard.myself.name + ' ' + dashboard.myself.surname); + // dashboard.downnotreg = await ExtraList.getDownlineNotRegisteredByNameSurname(idapp, dashboard.myself.name + ' ' + dashboard.myself.surname); dashboard.downbyuser = {}; @@ -868,6 +988,18 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us dashboard.downbyuser[down2.username] = await User.getDownlineByUsername(idapp, down2.username); } } + + dashboard.arrnavi = await Nave.getArrPosizioniByIndOrder(idapp, dashboard.myself.ind_order); + + dashboard.navi_partenza = []; + for (let indriga = 0; indriga < 10; indriga++) { + dashboard.navi_partenza.push(await Nave.getPrimaNaveByRiga(idapp, indriga)); + } + + for (let mynave of dashboard.arrnavi) { + mynave._doc.rec = await Nave.getNaveByRigaCol(idapp, mynave.riga, mynave.col); + } + return dashboard; } catch (e) { console.error(e); @@ -920,12 +1052,12 @@ UserSchema.statics.getUsersQualified = async function (idapp, numinvitati) { idapp, $or: [ { - special_req: true + 'profile.special_req': true }, { verified_email: true, 'profile.teleg_id': { $gt: 0 }, - $where: "this.profile.paymenttypes.length >= 1", + 'profile.paymenttypes': { "$in": ['paypal'] }, 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED, 'profile.saw_zoom_presentation': true, 'profile.my_dream': { $exists: true }, @@ -1022,7 +1154,15 @@ UserSchema.statics.getLastUsers = async function (idapp) { const lastn = await Settings.getValDbSettings(idapp, 'SHOW_LAST_N_USERS', 5); - return await User.find({ idapp }).sort({ date_temp_reg: -1 }).limit(lastn).then((arr) => { + return await User.find({ idapp }, { + username: 1, + name: 1, + surname: 1, + date_temp_reg: 1, + date_reg: 1, + ind_order: 1, + 'profile.nationality': 1, + }).sort({ date_temp_reg: -1 }).limit(lastn).then((arr) => { //return JSON.stringify(arr) return arr }); @@ -1079,23 +1219,47 @@ UserSchema.statics.findAllDistinctNationality = async function (idapp) { }; UserSchema.statics.getUsersRegDaily = function (idapp, nrec) { + const query = [ { - $match: { idapp } + $match: { idapp, date_temp_reg: { $gte: tools.IncDateNow(-(1000 * 60 * 60 * 24 * nrec)) } } }, { $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$date_temp_reg" } }, count: { $sum: 1 } } }, { $sort: { _id: 1 } - }, - { - $limit: nrec } ]; return query }; +UserSchema.statics.getnumRegNDays = function (idapp, nrec) { + + + const query = [ + { + $match: { idapp, date_temp_reg: { $lt: tools.IncDateNow(-(1000 * 60 * 60 * 24 * nrec)) } } + }, + { + $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$date_temp_reg" } }, count: { $sum: 1 } } + }, + { + $sort: { _id: 1 } + } + ]; + return query +}; + +UserSchema.statics.calcnumRegUntilDay = async function (idapp) { + const User = this; + + return await User.aggregate(User.getnumRegNDays(idapp, 30)) + .then((arr) => { + return arr.reduce((sum, rec) => sum + rec.count, 0); + }); + +}; UserSchema.statics.calcRegDaily = async function (idapp) { const User = this; @@ -1116,22 +1280,31 @@ if (tools.INITDB_FIRSTIME) { // UserSchema.index({ surname: 1 }); } -async function addUtentiInLista(idapp, mode) { +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); + if (rec.profile.special_req) { + numinvitatiattivi = 2; + } if (mode === 1) { // 9 punti qualificati ok = qualified && (numinvitatiattivi >= 2); } else if (mode === 2) { + // 8 punti qualificati ( 1 Invitato) + ok = qualified && (numinvitati === 2); + } else if (mode === 3) { + ok = qualified && (numinvitatiattivi === 1); + } else if (mode === 4) { + ok = qualified && (numinvitati === 1); + } else if (mode === 5) { // 7 punti qualificati ok = qualified; - } else { - ok = true; // // almeno telegram ID // ok = user.profile.teleg_id > 0; // } else { @@ -1139,24 +1312,37 @@ async function addUtentiInLista(idapp, mode) { } if (ok) { - if (!await ListaIngresso.findByUsername(idapp, rec.username)) { - let listaingresso = new ListaIngresso({ - username: rec.username, - ind_order: rec.ind_order, - name: rec.name, - surname: rec.surname, - idapp, - _id: new ObjectID() - }); - - await listaingresso.save(); + ris = await ListaIngresso.addUserInListaIngresso(idapp, rec.ind_order, rec.lang, false, 1); + if (!!ris) num++; - } } } return num; } +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 : '' + +}; + UserSchema.statics.DbOp = async function (idapp, mydata) { const User = this; try { @@ -1190,26 +1376,21 @@ UserSchema.statics.DbOp = async function (idapp, mydata) { } else if (mydata.dbop === 'creaLista') { - await ListaIngresso.remove({ idapp }); + await ListaIngresso.deleteMany({ idapp, added: false }); arrusers = await User.find({ 'idapp': idapp }).sort({ ind_order: 1 }); let num = 0; - num += await addUtentiInLista(idapp, 1); - num += await addUtentiInLista(idapp, 2); + 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 }; - } else if (mydata.dbop === 'creaBillettera') { - const num = await Billettera.generaBillettera(idapp); - - return { num }; - } else if (mydata.dbop === 'visuPlacca') { - const placca = await Billettera.getPlaccaByFuoco(idapp, riga, col); - - return { placca }; } } catch (e) { console.error(e); diff --git a/src/server/router/api/actions.js b/src/server/router/api/actions.js index 19fe401..8a1a777 100644 --- a/src/server/router/api/actions.js +++ b/src/server/router/api/actions.js @@ -1,14 +1,36 @@ var mongoose = require('mongoose'); const Subscription = mongoose.model('subscribers'); +const { ListaIngresso } = require('../../models/listaingresso'); +const { User } = require('../../models/user'); + +const telegrambot = require('../../telegram/telegrambot'); + module.exports = { doOtherThingsAfterDeleted: async function (tablename, rec) { try { if (tablename === 'users') { + + await ListaIngresso.deleteUserInListaIngresso(rec.idapp, rec.ind_order); + + // Controlla se aveva invitati, li regala a quello sopra + const arrap = await User.getDownlineByUsername(rec.idapp, rec.username); + for (let user of arrap) { + + await User.findOneAndUpdate({ + idapp: rec.idapp, + username: user.username + }, { $set: { aportador_solidario: rec.aportador_solidario } }, { new: false }); + + let msg = 'Spostato ' + user.name + ' ' + user.surname + ' sotto di ' + rec.aportador_solidario; + telegrambot.sendMsgTelegramToTheManagers(idapp, msg); + } + // Delete also all the subscribers record of this User return Subscription.deleteOne({ userId: rec._id }) } } catch (e) { + console.error(e); return false } return true; diff --git a/src/server/router/dashboard_router.js b/src/server/router/dashboard_router.js index d1caf5a..2f27a7b 100644 --- a/src/server/router/dashboard_router.js +++ b/src/server/router/dashboard_router.js @@ -12,6 +12,8 @@ const { User } = require('../models/user'); const mongoose = require('mongoose'); const Subscription = mongoose.model('subscribers'); +const telegrambot = require('../telegram/telegrambot'); + const _ = require('lodash'); const { ObjectID } = require('mongodb'); @@ -49,4 +51,14 @@ router.post('/', authenticate, async (req, res) => { }); + +router.post('/msgnave', authenticate, async (req, res) => { + const idapp = req.body.idapp; + let mydata = req.body; + + const ris = await telegrambot.sendMsgTelegramToNave(idapp, mydata); + res.send({ code: server_constants.RIS_CODE_OK, ris }); + +}); + module.exports = router; diff --git a/src/server/router/files/Musica_Dell_Anima_Serata.jpg b/src/server/router/files/Musica_Dell_Anima_Serata.jpg new file mode 100644 index 0000000..6e529dc Binary files /dev/null and b/src/server/router/files/Musica_Dell_Anima_Serata.jpg differ diff --git a/src/server/router/files/batidora-de-brazo-600-w--5.jpg b/src/server/router/files/batidora-de-brazo-600-w--5.jpg new file mode 100644 index 0000000..7e621ec Binary files /dev/null and b/src/server/router/files/batidora-de-brazo-600-w--5.jpg differ diff --git a/src/server/router/files/estados_emocionales.jpg b/src/server/router/files/estados_emocionales.jpg new file mode 100644 index 0000000..7e25dd8 Binary files /dev/null and b/src/server/router/files/estados_emocionales.jpg differ diff --git a/src/server/router/files/flat_earth.png b/src/server/router/files/flat_earth.png new file mode 100644 index 0000000..2daae85 Binary files /dev/null and b/src/server/router/files/flat_earth.png differ diff --git a/src/server/router/files/malaga_beach.jpg b/src/server/router/files/malaga_beach.jpg new file mode 100644 index 0000000..dda1109 Binary files /dev/null and b/src/server/router/files/malaga_beach.jpg differ diff --git a/src/server/router/files/paolo_piano3.jpg b/src/server/router/files/paolo_piano3.jpg new file mode 100644 index 0000000..1f38e6d Binary files /dev/null and b/src/server/router/files/paolo_piano3.jpg differ diff --git a/src/server/router/files/terra_piatta.jpg b/src/server/router/files/terra_piatta.jpg new file mode 100644 index 0000000..f0766e2 Binary files /dev/null and b/src/server/router/files/terra_piatta.jpg differ diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index b8e834f..4d6f9a5 100644 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -12,6 +12,7 @@ const sendemail = require('../sendemail'); const { authenticate, authenticate_noerror } = require('../middleware/authenticate'); const { ObjectID } = require('mongodb'); +const { ListaIngresso } = require('../models/listaingresso'); const mongoose = require('mongoose'); const cfgserver = mongoose.model('cfgserver'); @@ -27,6 +28,7 @@ if (!fs.existsSync(folder)) { const _ = require('lodash'); const { User } = require('../models/user'); +const { Nave } = require('../models/nave'); const { ExtraList } = require('../models/extralist'); const { Booking } = require('../models/booking'); const { Operator } = require('../models/operator'); @@ -52,6 +54,15 @@ const tools = require('../tools/general'); const server_constants = require('../tools/server_constants'); const actions = require('./api/actions'); +UserCost = { + FIELDS_REQUISITI: ['verified_email', + 'profile.teleg_id', + 'profile.saw_zoom_presentation', + 'profile.saw_and_accepted', + 'profile.email_paypal', + 'profile.my_dream', + 'profile.paymenttypes'] +}; router.post(process.env.LINKVERIF_REG, (req, res) => { const body = _.pick(req.body, ['idapp', 'idlink']); @@ -77,7 +88,10 @@ router.post(process.env.LINKVERIF_REG, (req, res) => { user.lasttimeonline = new Date(); user.save().then(() => { //console.log("TROVATOOOOOO!"); - res.send({ code: server_constants.RIS_CODE_EMAIL_VERIFIED, msg: tools.getres__('EMAIL', res) + ' ' + tools.getres__('VERIF', res) }); + res.send({ + code: server_constants.RIS_CODE_EMAIL_VERIFIED, + msg: tools.getres__('EMAIL', res) + ' ' + tools.getres__('VERIF', res) + }); }); } } @@ -93,7 +107,7 @@ router.post(process.env.LINKVERIF_REG, (req, res) => { router.post(process.env.LINK_REQUEST_NEWPASSWORD, (req, res) => { const body = _.pick(req.body, ['idapp', 'email']); const idapp = body.idapp; - const email = body.email; + const email = body.email.toLowerCase().trim(); console.log("POST " + process.env.LINK_REQUEST_NEWPASSWORD + " idapp= " + idapp + " email = " + email); User.findByEmail(idapp, email).then(async (user) => { @@ -124,7 +138,7 @@ router.post(process.env.LINK_REQUEST_NEWPASSWORD, (req, res) => { router.post(process.env.LINK_UPDATE_PWD, (req, res) => { const body = _.pick(req.body, ['idapp', 'email', 'tokenforgot', 'password']); const idapp = body.idapp; - const email = body.email; + const email = body.email.toLowerCase().trim(); const tokenforgot = body.tokenforgot; const password = body.password; const msg = "Richiesta Nuova Password: idapp= " + idapp + " email = " + email; @@ -198,6 +212,10 @@ function getTableByTableName(tablename) { mytable = Permission; else if (tablename === 'mailinglist') mytable = MailingList; + else if (tablename === 'navi') + mytable = Nave; + else if (tablename === 'listaingressos') + mytable = ListaIngresso; return mytable } @@ -255,8 +273,63 @@ router.post('/gettable', authenticate, (req, res) => { }); +async function checkIfSbloccatiRequisiti(idapp, allData, id) { -router.patch('/chval', authenticate, (req, res) => { + if (await Nave.findByIndOrder(idapp, allData.myuser.ind_order)) { + // 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.findByIndOrder(idapp, allData.myuser.ind_order); + if (!userlista) { + // 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 (tools.isAbilitaNave(idapp)) { + // Aggiungilo alla ListaIngresso + ris = await ListaIngresso.addUserInListaIngresso(idapp, allData.myuser.ind_order, allData.myuser.lang, true, 1); + } + } + } + + 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 + } + + // 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.useraportador.username, 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('/chval', authenticate, async (req, res) => { // const idapp = req.body.idapp; const id = req.body.data.id; const idapp = req.body.idapp; @@ -265,7 +338,7 @@ router.patch('/chval', authenticate, (req, res) => { const mytable = getTableByTableName(mydata.table); const fieldsvalue = mydata.fieldsvalue; - tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue); + // tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue); // If I change my record... if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) && !(req.user._id.toString() === id) && !tools.ModificheConsentite(mydata.table, fieldsvalue)) { @@ -273,7 +346,20 @@ router.patch('/chval', authenticate, (req, res) => { return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } - mytable.findByIdAndUpdate(id, { $set: fieldsvalue }).then(async (rec) => { + const camporequisiti = UserCost.FIELDS_REQUISITI.includes(Object.keys(fieldsvalue)[0]); + + let allData = {}; + if (mydata.table === 'users') { + if (camporequisiti) { + 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); + } + } + + await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }).then(async (rec) => { // tools.mylogshow(' REC TO MODIFY: ', rec); if (!rec) { return res.status(404).send(); @@ -285,6 +371,12 @@ router.patch('/chval', authenticate, (req, res) => { telegrambot.sendMsgTelegramToTheManagers(idapp, addtext); } + if (mydata.table === 'users') { + if (camporequisiti) { + await checkIfSbloccatiRequisiti(idapp, allData, id); + } + } + if (tools.ModificheConsentite(mydata.table, fieldsvalue)) { let msg = ''; if (mydata.table === 'users') { @@ -294,7 +386,13 @@ router.patch('/chval', authenticate, (req, res) => { msg = `Variato l'invitante di ` + rec.name + ' ' + rec.surname + '\nmodificato da ' + req.user.name + ' ' + req.user.surname + ' \n' + 'Prima: ' + nomecognomeas + ' (' + rec.aportador_solidario + ')\n' + 'Dopo: ' + nomecognomenuovo + ' (' + fieldsvalue.aportador_solidario + ') ]'; + + // Metti l'iniziale + if (!await User.AportadorOrig(id)) { + await mytable.findByIdAndUpdate(id, { $set: { aportador_iniziale: fieldsvalue.aportador_solidario } }, { new: false }); + } } + } if (msg !== '') @@ -351,7 +449,9 @@ router.delete('/delrec/:table/:id', authenticate, (req, res) => { const mytable = getTableByTableName(tablename); - if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) && (tablename !== 'extralist')) { + const fields = { 'ALL': 1 }; + + if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) && (tablename !== 'extralist') && !tools.ModificheConsentite(tablename, fields, id, req.user)) { // If without permissions, exit return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } @@ -366,7 +466,7 @@ router.delete('/delrec/:table/:id', authenticate, (req, res) => { tools.mylog('DELETED ', rec._id); // Do extra things after deleted - return actions.doOtherThingsAfterDeleted(tablename, rec).then((ris) => { + return actions.doOtherThingsAfterDeleted(tablename, rec).then(async (ris) => { if (ris) { if (notifBot) { @@ -378,7 +478,7 @@ router.delete('/delrec/:table/:id', authenticate, (req, res) => { addtext = 'Eliminato il Record "' + nomerecord + '" dalla tabella ' + tablename + '\n' + 'Eseguito da ' + req.user.name + ' ' + req.user.surname + ' \n'; - telegrambot.sendMsgTelegramToTheManagers(idapp, addtext); + await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext); } tools.mylog('DELETED Others things ...'); @@ -549,7 +649,8 @@ router.get(process.env.LINK_CHECK_UPDATES, authenticate, (req, res) => { // If User is Admin, then send user Lists if (User.isAdmin(req.user.perm)) { // Send UsersList - usersList = User.getUsersList(req.user.idapp) + // usersList = User.getUsersList(req.user.idapp) + usersList = null; } } diff --git a/src/server/router/notevole_router.js b/src/server/router/notevole_router.js index 1cb2775..b852eb7 100644 --- a/src/server/router/notevole_router.js +++ b/src/server/router/notevole_router.js @@ -29,13 +29,14 @@ router.post('/load', async (req, res) => { email_non_verif: await User.getEmailNotVerified(idapp), num_teleg_attivo: await User.getUsersTelegramAttivo(idapp), num_teleg_pending: await User.getUsersTelegramPending(idapp), - num_qualificati: await User.getNumUsersQualified(idapp, 2), + // num_qualificati: await User.getNumUsersQualified(idapp, 2), 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), num_users_dream: await User.getUsersDreams(idapp), arr_nations: await User.findAllDistinctNationality(idapp), + numreg_untilday: await User.calcnumRegUntilDay(idapp), reg_daily: await User.calcRegDaily(idapp), lastsreg: await User.getLastUsers(idapp), checkuser: await User.checkUser(idapp, username), diff --git a/src/server/router/upload/78672181_2455539731334358_8338493870618705920_n.jpg b/src/server/router/upload/78672181_2455539731334358_8338493870618705920_n.jpg new file mode 100644 index 0000000..3a9a594 Binary files /dev/null and b/src/server/router/upload/78672181_2455539731334358_8338493870618705920_n.jpg differ diff --git a/src/server/router/upload/WhatsApp Image 2019-11-02 at 18.05.25.jpeg b/src/server/router/upload/WhatsApp Image 2019-11-02 at 18.05.25.jpeg new file mode 100644 index 0000000..c440e6d Binary files /dev/null and b/src/server/router/upload/WhatsApp Image 2019-11-02 at 18.05.25.jpeg differ diff --git a/src/server/router/upload/WhatsApp Image 2019-11-27 at 13.25.20.jpeg b/src/server/router/upload/WhatsApp Image 2019-11-27 at 13.25.20.jpeg new file mode 100644 index 0000000..7a811a7 Binary files /dev/null and b/src/server/router/upload/WhatsApp Image 2019-11-27 at 13.25.20.jpeg differ diff --git a/src/server/router/upload/olii_essenziali.jpg b/src/server/router/upload/olii_essenziali.jpg new file mode 100644 index 0000000..aaf9d96 Binary files /dev/null and b/src/server/router/upload/olii_essenziali.jpg differ diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 411d57e..a2893fc 100644 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -2,10 +2,15 @@ const express = require('express'); const router = express.Router(); const { User } = require('../models/user'); +const { Nave } = require('../models/nave'); +const { ListaIngresso } = require('../models/listaingresso'); const { ExtraList } = require('../models/extralist'); +const { ObjectID } = require('mongodb'); const sendemail = require('../sendemail'); +const { Settings } = require('../models/settings'); + const tools = require('../tools/general'); const shared_consts = require('../tools/shared_nodejs'); @@ -47,10 +52,10 @@ function getMobileComplete(user) { router.post('/', async (req, res) => { tools.mylog("POST /users"); const body = _.pick(req.body, ['email', 'password', 'username', 'name', 'surname', 'idapp', 'keyappid', 'lang', 'profile', 'aportador_solidario']); - const user = new User(body); - body.email = body.email.toLowerCase(); + const user = new User(body); + // tools.mylog("LANG PASSATO = " + user.lang, "IDAPP", user.idapp); user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username); @@ -59,6 +64,10 @@ router.post('/', async (req, res) => { user.lasttimeonline = new Date(); user.date_reg = new Date(); user.date_temp_reg = new Date(); + user.aportador_iniziale = user.aportador_solidario; + if (user.idapp === tools.AYNI) { + user.profile.paymenttypes = ['paypal']; + } // user.perm = 3; if (tools.testing()) { user.verified_email = true; @@ -147,7 +156,7 @@ router.post('/', async (req, res) => { msgseconda += 'QUARTA'; msgseconda += ' UTENZA di ' + recorig.name + ' ' + recorig.surname + ' (' + recorig.username + ') : ' + user.name + ' ' + user.surname + ' (' + user.username + ') '; - telegrambot.sendMsgTelegramToTheManagers(user.idapp, msgseconda); + await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msgseconda); } } @@ -158,7 +167,7 @@ router.post('/', async (req, res) => { let msg = 'L\'utente ' + user.name + ' ' + user.surname + ' si sta registrando con il link di ' + user.aportador_solidario + ' (' + namesurname_aportador_reg + ') ' + 'invece è assegnato a ' + nomeaportador_corretto; - telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg); + await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg); res.status(400).send({ code: server_constants.RIS_CODE_USER_NOT_THIS_APORTADOR, msg: '' }); return 1; } @@ -173,8 +182,11 @@ router.post('/', async (req, res) => { if (!recextra) { const msg = 'Utente non trovato: ' + user.name + ' ' + user.surname + ' ' + user.profile.nationality + ' ' + user.profile.cell + ' email: ' + user.email + ' username: ' + user.username; console.log('Utente non trovato; ', msg); - telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg); - res.status(400).send({ code: server_constants.RIS_CODE_USER_EXTRALIST_NOTFOUND, msg: 'Controlla se il numero ' + user.profile.cell + ' è corretto.' }); + await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg); + res.status(400).send({ + code: server_constants.RIS_CODE_USER_EXTRALIST_NOTFOUND, + msg: 'Controlla se il numero ' + user.profile.cell + ' è corretto.' + }); return 1; } else { user.ind_order = recextra.ind_order; @@ -244,11 +256,11 @@ router.post('/', async (req, res) => { }) }); -router.get('/:idapp/:username', (req, res) => { +router.get('/:idapp/:username', async (req, res) => { var username = req.params.username; const idapp = req.params.idapp; - User.findByUsername(idapp, username, false).then((user) => { + await User.findByUsername(idapp, username, false).then((user) => { if (!user) { return res.status(404).send(); } @@ -397,17 +409,130 @@ router.post('/import_extralist', async (req, res) => { res.send(ris); }); -router.post('/dbop', async (req, res) => { +router.post('/dbop', authenticate, async (req, res) => { - const mydata = req.body.mydata; - idapp = req.body.idapp; - locale = req.body.locale; + const mydata = req.body.mydata; + idapp = req.body.idapp; + locale = req.body.locale; - const ris = await User.DbOp(idapp, mydata); - console.log('ris', ris); + let ris = await User.DbOp(idapp, mydata); - res.send(ris); -}); + if (mydata.dbop === 'creaNave') { + const num = await Nave.generaNave(idapp, mydata); + ris = { num }; + } else if (mydata.dbop === 'delNavi') { + await Nave.setRiga(idapp, 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 === 'visuListaNave') { + const mystr = await Nave.showListaOrd(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'checkInserimentiUtentiInNave') { + const mystr = await Nave.checkIfDevoAggiungereInNave(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'visuListaIngresso') { + const mystr = await ListaIngresso.showListaOrd(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'initListaIngresso') { + 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 === 'creaUtentiTest') { + + let num = 0; + lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1); + for (let ind = 0; ind < 1; ind++) { + let myuser = new User(); + myuser._id = new ObjectID(); + myuser.ind_order = lastrec[0].ind_order + 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.verified_email = true; + if (myuser.ind_order < 2) + myuser.perm = "3"; + myuser.username = "Userna_" + myuser.name; + myuser.profile.special_req = true; + await myuser.save(); + num++; + } + + ris = { num }; + } else if (mydata.dbop === 'visuPlacca') { + const placca = await Nave.getPlaccaPerDonatore(idapp, parseInt(mydata.riga), parseInt(mydata.col)); + + telegrambot.sendMsgTelegramToTheAdmin(idapp, placca); + + ris = { placca }; + } else if (mydata.dbop === 'visuNave') { + const 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); + + ris = { mystr }; + } else if (mydata.dbop === 'getnavibyuser') { + + let arrnavi = null; + + const user = await User.getUserShortDataByUsername(idapp, mydata.username); + if (user) { + arrnavi = await Nave.getArrPosizioniByIndOrder(idapp, user.ind_order); + + for (let mynave of arrnavi) { + mynave._doc.rec = await Nave.getNaveByRigaCol(idapp, mynave.riga, mynave.col); + } + + } + + ris = { data: arrnavi }; + } + + // console.log('ris', ris); + + res.send(ris); + } +); module.exports = router; diff --git a/src/server/sendemail.js b/src/server/sendemail.js index a3fa35b..49b0287 100644 --- a/src/server/sendemail.js +++ b/src/server/sendemail.js @@ -496,7 +496,7 @@ module.exports = { const msginizio = 'INIZIO - sendEmail_Newsletter_Events: ' + tools.getNomeAppByIdApp(idapp); console.log(msginizio); - telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); + await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); //++Todo Extract List Email to send const userstosend = await MailingList.findAllIdAppSubscribed(idapp); @@ -539,7 +539,7 @@ module.exports = { if (!activate) { // Invio Newsletter Abortito! mynewsrec.error_job = 'Invio Newsletter abortito alle ore ' + new Date().toDateString() + new Date().toTimeString(); - telegrambot.sendMsgTelegramToTheManagers(idapp, mynewsrec.error_job); + await telegrambot.sendMsgTelegramToTheManagers(idapp, mynewsrec.error_job); await mynewsrec.save(); await Newstosent.processingJob(id_newstosent, false); console.log('*** L\'Invio della Newsletter è stato fermato ! '); @@ -567,7 +567,7 @@ module.exports = { if ((mynewsrec.numemail_sent % 50) === 0) { const msgproc = 'In Corso ' + mynewsrec.numemail_sent + ' / ' + mynewsrec.numemail_tot + ' Email inviate...'; - telegrambot.sendMsgTelegramToTheManagers(idapp, msgproc); + await telegrambot.sendMsgTelegramToTheManagers(idapp, msgproc); } //Put the result in the database, to check if is sent or not. @@ -591,7 +591,7 @@ module.exports = { } catch (e) { const msgerr = 'Error LOOP sendEmail_Newsletter_Events: ' + e; console.error(msgerr); - telegrambot.sendMsgTelegramToTheManagers(idapp, msgerr); + await telegrambot.sendMsgTelegramToTheManagers(idapp, msgerr); } } @@ -601,7 +601,7 @@ module.exports = { msgfine += mynewsrec.numemail_sent + ' Email inviate'; console.log(msgfine); - telegrambot.sendMsgTelegramToTheManagers(idapp, msgfine); + await telegrambot.sendMsgTelegramToTheManagers(idapp, msgfine); } catch (e) { @@ -610,7 +610,7 @@ module.exports = { if (!activate) { // Invio Newsletter Abortito! mynewsrec.error_job = 'Invio Newsletter abortito alle ore ' + new Date().toDateString() + new Date().toTimeString(); - telegrambot.sendMsgTelegramToTheManagers(idapp, mynewsrec.error_job); + await telegrambot.sendMsgTelegramToTheManagers(idapp, mynewsrec.error_job); await mynewsrec.save(); await Newstosent.processingJob(id_newstosent, false); console.log('*** L\'Invio della Newsletter è stato fermato ! '); diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 7bf0fe1..33a217e 100644 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -9,6 +9,7 @@ const printf = require('util').format; const { User } = require('../models/user'); const { CalZoom } = require('../models/calzoom'); +const { Nave } = require('../models/nave'); const shared_consts = require('../tools/shared_nodejs'); const emoji = require('node-emoji'); @@ -48,6 +49,7 @@ const emo = { YELLOW_HEART: emoji.get('yellow_heart'), PURPLE_HEART: emoji.get('purple_heart'), GIFT_HEART: emoji.get('gift_heart'), + GIFT: emoji.get('gift'), ROBOT_FACE: emoji.get('robot_face'), ADMIN: emoji.get('information_desk_person'), MALE: emoji.get('man-tipping-hand'), @@ -59,7 +61,9 @@ const emo = { MsgBot = { - CIAO: ['ciao', 'ciaoo', 'hola', 'holaa', 'hey', 'salve', 'buongiorno', 'buondi'], + MIANAVE: ['Nave'], + + CIAO: ['ciao', 'ciaoo', 'hola', 'holaa', 'hey', 'salve', 'buongiorno', 'buondi', 'ciao ❤️'], CI_SEI: ['ci sei', 'c\'è qualcuno', 'c\'è nessuno'], CHI_SONO_IO: ['chi sono io', 'chi sono'], COME_STAI: ['tutto bene', 'come stai', 'come stai', 'come va', 'come butta', 'come va oggi'], @@ -81,7 +85,7 @@ MsgBot = { NON_TROO_INVITATI: ['non trovo invitati', 'non riesco a trovare invitati'], PAROLACCE: ['stronz', 'fanculo'], COME_SI_CHIAMA: ['come si chiama'], - PROSSIMO_ZOOM: ['prossimo zoom', 'fare lo zoom', 'gli zoom', 'conferenz'], + PROSSIMO_ZOOM: ['prossimo zoom', 'fare lo zoom', 'gli zoom', 'conferenz', 'zoom'], LAVAGNA: ['lavagna', 'Lavagna', 'LAVAGNA'], SEI_LIBERO: ['sei liber', 'sei sposat', 'sei fidanzat', 'sei single'], AIUTO: ['ayni help', 'help', 'aiuto', 'ho bisogno di', 'ho problemi', 'non riesco', 'mi puoi aiutare', 'mi aiuti', 'aiutami', 'posso chiederti', 'puoi aiutarmi'], @@ -123,9 +127,13 @@ function getemojibynumber(number) { return emoji.get('height') } else if (number === 9) { return emoji.get('nine') + } else { + return number; } } +strNave = "Nave"; + const Menu = { ACCEDI: emo.PERSON + ' Accedi', @@ -138,22 +146,36 @@ const Menu = { ADMIN: emoji.get('information_desk_person') + ' Admin', ALTRO: emoji.get('newspaper') + ' Altro', MSGATUTTI: emoji.get('incoming_envelope') + ' Invia a TUTTI', + 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', + MSG_TO_USER: 'sendmsgto', + MSG_SI_INVITATI_NO_7REQ_INVITATI: emoji.get('incoming_envelope') + 'Inv e NO 7 Req', MSGSTAFF: emoji.get('incoming_envelope') + ' Invia a STAFF', INDIETRO: emoji.get('back') + ' Indietro', SI: emoji.get('thumbsup') + ' SI', NO: emoji.get('thumbsdown') + ' NO', - + CHAT_PERSONALE: emoji.get('female-office-worker') + emoji.get('computer'), + ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Esci dalla Conversazione', EXIT_TELEGRAM: 'exittotelegram', + MIANAVE: emo.GIFT + ' ' + strNave, }; +const CONTA_SOLO = 'contasolo'; +const RICEVI_EMAIL = 'riceviemail'; + +const SendMsgCmd = [CONTA_SOLO, RICEVI_EMAIL]; + const MenuNoLogin = [[Menu.ACCEDI], [Menu.ASSISTENZA]]; const MenuStandard = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.ZOOM, Menu.ASSISTENZA]]; -const MenuPerAdmin = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.ZOOM, Menu.ASSISTENZA], [Menu.ADMIN, Menu.ALTRO]]; +const MenuPerAdmin = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.ZOOM, Menu.ASSISTENZA], [Menu.MIANAVE, Menu.ADMIN, Menu.ALTRO]]; const MenuYesNo = [[Menu.SI, Menu.NO]]; -const MenuAdmin = [[Menu.LAVAGNA, Menu.ZOOM], [Menu.MSGSTAFF, Menu.MSGATUTTI, Menu.INDIETRO], ['', '']]; +const MenuAdmin = [[Menu.MSGSTAFF, Menu.MSGATUTTI, Menu.INDIETRO], [Menu.MSG_NO_7_REQ, Menu.MSG_NO_9_REQ], [Menu.MSG_TO_NAVE, Menu.MSG_SI_INVITATI_NO_7REQ_INVITATI]]; +const MenuSend = [[CONTA_SOLO, RICEVI_EMAIL], [Menu.INDIETRO]]; const MenuYes = [[Menu.MSGSTAFF, Menu.INDIETRO], ['', '']]; +const MenuChat = [[Menu.ESCI_DA_CHAT, Menu.INDIETRO]]; const Sex = { MALE: 1, @@ -168,6 +190,16 @@ const Status = { WAITFOR_RISPOSTA: 110, }; +const Destin = { + STAFF: 1, + TUTTI: 2, + NO_7_REQ: 3, + NO_9_REQ: 4, + SI_INVITATI_NO_7REQ_INVITATI: 5, + A_UTENTE: 6, + MSG_TO_NAVE: 7, +}; + const StatusMSGALL = { NONE: 0, ASK: 1, @@ -178,7 +210,7 @@ const txt = { MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Scegli una voce di menu:' + emoji.get('dizzy'), MSG_ASK_USERNAME_BO: 'Scrivi nel messaggio lo username o la email con cui ti sei registrato sul sito di %s:', MSG_ERRORE_USERNAME: 'Attenzione! Devi inserire solo lo username (40 caratteri massimo)', - MSG_ERRORE_USERNAME_NOT_FOUND: 'Per Completare la Verifica Telegram BOT, devi ora scrivere qui sotto nel messaggio l\'Username o la email con cui ti sei registrato sul sito di AYNI:', + MSG_ERRORE_USERNAME_NOT_FOUND: 'Per Completare la Verifica Telegram BOT, devi ora scrivere qui sotto nel messaggio l\'Username OPPURE la email con cui ti sei registrato sul sito di AYNI:', MSG_ERRORE_USERNAME_ANNULLA: 'Inserimento Annullato. Riprovare', MSG_OPERAZ_ANNULLATA: 'Operazione Annullata', MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attenzione! Devi inserire solo il codice a 6 cifre', @@ -191,6 +223,7 @@ const txt = { MSG_EXIT_TELEGRAM: 'L\'account è stato ora scollegato da questo Telegram BOT.', MSG_APORTADOR_USER_REGISTERED: emo.FIRE + ' Si è appena Registrato "%s (n. %s)"\n(Invitato da %s)', MSG_MSG_SENT: emoji.get('envelope') + ' Messaggi Inviati !', + MSG_MSG_TOSENT: emoji.get('envelope') + ' Messaggi da Inviare', MSG_MSG_INCORSO: emoji.get('envelope') + ' messaggi in corso... Inviati attualmente', }; @@ -206,6 +239,10 @@ module.exports = { REGISTRATION: 1 }, + getCiao: function (idapp, username, lang) { + return tools.gettranslate('CIAO', lang) + ' ' + username + '!\n'; + }, + notifyToTelegram: async function (phase, mylocalsconf) { let userdest = mylocalsconf.user.aportador_solidario; let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname}`; @@ -243,9 +280,11 @@ module.exports = { const usersmanagers = await User.getusersManagers(idapp); // console.log('usersmanagers', usersmanagers); + tools.writeManagersLog(text); + if (usersmanagers) { for (const rec of usersmanagers) { - this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': ' + text) + await this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': ' + text, undefined, undefined, true); await tools.snooze(300) } } @@ -253,13 +292,74 @@ module.exports = { }, + getMsgByTipoMsg: function (mydata, lang, user) { + 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); + } + }, + + sendMsgTelegramToNave: async function (idapp, mydata) { + let nummsgsent = 0; + let strout = ''; + + try { + const arrnavi = await Nave.getusersByNave(idapp, mydata.navemediatore); + + + // console.log('usersmanagers', usersmanagers); + + tools.writeManagersLog('sendMsgTelegramToNave'); + + if (arrnavi) { + 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); + + if (!!idteleg) { + strout += '\n' + user.name + ' ' + user.surname + ':'; + if (mydata.inviareale) { + await this.sendMsgTelegramByIdTelegram(idapp, idteleg, mymsg, undefined, undefined, true); + await tools.snooze(300); + strout += ' -> MSG INVIATO'; + } else { + strout += ' (Pronto da Inviare)'; + } + nummsgsent++; + } + } + } + + 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); + return { nummsgsent , strout }; + } + }, + sendMsgTelegramToTheAdmin: async function (idapp, text) { const usersmanagers = await User.getusersManagers(idapp); if (usersmanagers) { for (const rec of usersmanagers) { if (User.isAdmin(rec.perm)) { - this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + '[BOT-STAFF]' + emo.ADMIN + ': ' + text) + this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': ' + text, undefined, undefined, true); await tools.snooze(300) } } @@ -280,16 +380,19 @@ module.exports = { }, - sendMsgTelegram: async function (idapp, username, text) { + sendMsgTelegram: async function (idapp, username, text, alsotomanagers) { const teleg_id = await User.TelegIdByUsername(idapp, username); const cl = getclTelegByidapp(idapp); if (cl && teleg_id) { await cl.sendMsg(teleg_id, text) } + if (alsotomanagers) { + await this.sendMsgTelegramToTheManagers(idapp, text) + } }, - sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text, message_id, chat_id) { + sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text, message_id, chat_id, ripr_menuPrec) { if (!idtelegram) return; @@ -297,7 +400,7 @@ module.exports = { if (cl && idtelegram) { let myform = null; - return await cl.sendMsg(idtelegram, text, null, null, message_id, chat_id) + return await cl.sendMsg(idtelegram, text, null, null, message_id, chat_id, ripr_menuPrec) } } @@ -307,9 +410,16 @@ module.exports = { async function sendMsgTelegramToTheAdmin(idapp, text, msg) { const usersmanagers = await User.getusersManagers(idapp); - const username = msg.chat.username; + const clorig = getclTelegByidapp(idapp); + const rec = clorig.getRecInMem(msg); + let username = ''; + if (!!rec) { + username = rec.username_bo; + } else { + username = msg.chat.username; + } - text = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': Da ' + msg.chat.first_name + ' ' + msg.chat.last_name + ' (' + username + '): \n' + text; + text = emo.ROBOT_FACE + '[BOT-ADMIN]' + emo.ADMIN + ': Da ' + msg.chat.first_name + ' ' + msg.chat.last_name + ' [' + username + ']: \n' + text; tools.writeEventsLog(text); if (usersmanagers) { @@ -328,10 +438,25 @@ async function sendMsgTelegramToTheAdmin(idapp, text, msg) { } -async function local_sendMsgTelegramToTheManagers(idapp, text, msg) { +function getusernameByUser(idapp, msg) { + let username = ''; + let rec = this.getRecInMem(msg); + if (!!rec) + username = rec.username_bo; + + if (username === '') { + username = msg.chat.username; + } + + return username; +} + +async function local_sendMsgTelegramToTheManagers(idapp, text, msg, username_bo) { const usersmanagers = await User.getusersManagers(idapp); - const username = msg.chat.username; + let username = msg.chat.username; + 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; tools.writeEventsLog(text); @@ -341,7 +466,7 @@ async function local_sendMsgTelegramToTheManagers(idapp, text, msg) { const idtelegram = rec.profile.teleg_id; const cl = getclTelegByidapp(idapp); if (cl && idtelegram) { - await cl.sendMsg(idtelegram, text) + await cl.sendMsg(idtelegram, text, undefined, undefined, undefined, undefined, true) } await tools.snooze(300) } @@ -489,10 +614,10 @@ class Telegram { contastiera = true; } else if (MsgBot.UGUALE.includes(testo)) { risp = testo; - } else if (MsgBot.CHI_E_VISTAR.includes(testo)) { - risp = 'Vistar è un nomade che vive in Perù tra i selvaggi, filosofeggiando e cazzeggiando qua e la... Per questo è un Fico ed è adulato dalle ragazze di tutto il Globo ' + emo.JOY + emo.JOY + emo.JOY; - } else if (MsgBot.CHI_E_PAOLO.includes(testo)) { - risp = 'Paolo è il Programmatore Sborone di AYNI. Anche lui Fico quanto Vistar (ma chi è Vistar) ' + emo.JOY + ' che anzichè creare la Billettera cazzeggia su AYNI BOT, trovando risposte alle domande più assurde.' + emo.JOY2 + emo.JOY2; + // } else if (MsgBot.CHI_E_VISTAR.includes(testo)) { + // risp = 'Vistar è un nomade che vive in Perù tra i selvaggi, filosofeggiando e cazzeggiando qua e la... Per questo è un Fico ed è adulato dalle ragazze di tutto il Globo ' + emo.JOY + emo.JOY + emo.JOY; + // } else if (MsgBot.CHI_E_PAOLO.includes(testo)) { + // risp = 'Paolo è il Programmatore Sborone di AYNI. Anche lui Fico quanto Vistar (ma chi è Vistar) ' + emo.JOY + ' che anzichè creare la Nave cazzeggia su AYNI BOT, trovando risposte alle domande più assurde.' + emo.JOY2 + emo.JOY2; } else if (MsgBot.COME_SI_CHIAMA.includes(testo)) { risp = 'Eh non te lo posso dire! ' + emo.JOY; } else if (MsgBot.GRAZIE.includes(testo.replace('!', ''))) { @@ -530,11 +655,11 @@ class Telegram { risp = 'Da te non me l\'aspettavo proprio !! ' + emo.INNOCENT + emo.CROSS_ROSSA; } else if (MsgBot.HAHA.find((rec) => testo.indexOf(rec) > -1) && testo.length < 8) { risp = emo.JOY + emo.JOY + emo.JOY; - } else { + } else if (testo.length > 1) { noanswer = true; risp = 'Non ti capisco... d\'altronde sono solo un Robot ' + emo.ROBOT_FACE + emo.JOY2 + '\n\n(Per AIUTO, contatta la Chat AYNI - HELP)'; // risp += '\nClicca qui per entrare nella Chat AYNI - HELP di Supporto\n' + 'https://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w' + '\n\nI miei colleghi umani ti aiuteranno a risolvere !'; - await sendMsgTelegramToTheAdmin(this.idapp, testo, msg); + await local_sendMsgTelegramToTheManagers(this.idapp, testo, msg, rec.username_bo); } } @@ -551,22 +676,22 @@ class Telegram { } if (rec.numdomande > 3 && rec.msgcodeprec === '') { - if (rec.user) { - const dashboard = await User.getDashboard(this.idapp, rec.user.aportador_solidario, rec.user.username, rec.user.aportador_solidario_name_surname); - - risp += '\n\nNel frattempo ti ricordo che '; - if (dashboard.myself.numinvitati === 1) - risp += 'hai solo ' + dashboard.myself.numinvitati + ' invitato!'; - else if (dashboard.myself.numinvitati === 0) - risp += 'ancora non hai portato nessun Invitato! ' + emo.LEFT_FACING_FIST; - else if (dashboard.myself.numinvitati > 2) - risp += 'hai ' + dashboard.myself.numinvitati + ' invitati !' + emo.STARS; - - risp += '\n\nSei già entrato nella Chat di EMPOWER?'; - rec.msgcodeprec = MsgBot.CHAT_EMPOWER; - rec.statusmsg = Status.WAITFOR_RISPOSTA; - rec.numdomande = 0; - } + // if (rec.user) { + // const dashboard = await User.getDashboard(this.idapp, rec.user.aportador_solidario, rec.user.username, rec.user.aportador_solidario_name_surname); + // + // risp += '\n\nNel frattempo ti ricordo che '; + // if (dashboard.myself.numinvitati === 1) + // risp += 'hai solo ' + dashboard.myself.numinvitati + ' invitato!'; + // else if (dashboard.myself.numinvitati === 0) + // risp += 'ancora non hai portato nessun Invitato! ' + emo.LEFT_FACING_FIST; + // else if (dashboard.myself.numinvitati > 2) + // risp += 'hai ' + dashboard.myself.numinvitati + ' invitati !' + emo.STARS; + // + // risp += '\n\nSei già entrato nella Chat di EMPOWER?'; + // rec.msgcodeprec = MsgBot.CHAT_EMPOWER; + // rec.statusmsg = Status.WAITFOR_RISPOSTA; + // rec.numdomande = 0; + // } } if (risp !== '') { @@ -607,8 +732,27 @@ class Telegram { if (msg.text === undefined) return; + const arrtext = msg.text.split(" "); + let cmd2 = ""; + let cmd1 = arrtext[0]; + if (arrtext.length > 1) + cmd2 = arrtext[1]; + + let oldusername = rec.msgall_username_specifico; + + if ((msg.text === Menu.ESCI_DA_CHAT) || (msg.text === Menu.INDIETRO)) { + rec.msgall_username_specifico = ''; + } else { + if (rec.msgall_username_specifico !== '') { + await this.SendMsgToUser(msg, rec, rec.msgall_username_specifico, msg.text); + return true; + } + } + if (msg.text === Menu.LAVAGNA || MsgBot.LAVAGNA.find((rec) => msg.text.indexOf(rec) > -1)) { - await this.menuLavagna(msg) + await this.menuLavagna(msg); + } else if (msg.text === Menu.MIANAVE || (cmd2 === strNave) || MsgBot.MIANAVE.find((rec) => msg.text.indexOf(rec) > -1)) { + await this.menuNave(msg) } else if (msg.text === Menu.ACCEDI) { await this.menuAccedi(msg) } else if (msg.text === Menu.LINK_CONDIVIDERE) { @@ -621,8 +765,21 @@ class Telegram { await this.menumsgAll(msg) } else if (msg.text === Menu.MSGSTAFF) { await this.menumsgStaff(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 (cmd1 === Menu.MSG_TO_NAVE) { + await this.menumsg_to_Nave(msg, cmd2) + } else if (msg.text === Menu.MSG_SI_INVITATI_NO_7REQ_INVITATI) { + await this.menumsg_Si_Invitati_No_7Req(msg) + } else if (cmd1.toLowerCase() === Menu.MSG_TO_USER) { + await this.menumsg_A_Utente(msg) } else if (msg.text === Menu.INDIETRO) { await this.msgScegliMenu(msg); + } else if (msg.text === Menu.ESCI_DA_CHAT) { + await this.sendMsg(msg.chat.id, 'Uscito dalla Chat con ' + oldusername); + rec.msgall_username_specifico = ''; } else { await this.isMenuNotVerified(rec, msg); } @@ -747,16 +904,16 @@ class Telegram { } - if (dashboard.downnotreg) { - if (dashboard.downnotreg.length > 0) { - mystr += '\n' + emo.QUESTION_MARK + ' ' + tools.get__('NONREG', msg) + ':' + emo.QUESTION_MARK + '\n'; - let index = 1; - dashboard.downnotreg.forEach((user) => { - mystr += ` - ${index}°: ${user.name} ${user.surname} (tel: ${user.cell_complete})\n`; - index++; - }); - } - } + // if (dashboard.downnotreg) { + // if (dashboard.downnotreg.length > 0) { + // mystr += '\n' + emo.QUESTION_MARK + ' ' + tools.get__('NONREG', msg) + ':' + emo.QUESTION_MARK + '\n'; + // let index = 1; + // dashboard.downnotreg.forEach((user) => { + // mystr += ` - ${index}°: ${user.name} ${user.surname} (tel: ${user.cell_complete})\n`; + // index++; + // }); + // } + // } if (tuttie9) mystr += '\n' + printf(tools.get__('INFO_LAVAGNA_SITO', msg)); @@ -768,7 +925,6 @@ class Telegram { async menuLavagna(msg) { const rec = this.getRecInMem(msg); - // console.log('rec', rec); let mystr = ''; if (rec.user) { mystr = await this.getLavagnaByUser(rec.user, msg) @@ -778,6 +934,30 @@ class Telegram { await this.sendMsg(msg.chat.id, mystr); } + async menuNave(msg) { + const rec = this.getRecInMem(msg); + let mystr = ''; + if (!rec.user) + return ""; + + let ind_order_to_check = rec.user.ind_order; + let arrstringa = msg.text.split(" "); + + if (!!arrstringa) { + if (arrstringa.length > 1) { + let last = arrstringa.slice(-1)[0]; + if (!isNaN(last)) { + ind_order_to_check = last; + } + } + } + + mystr = await Nave.getNaveByUser(this.idapp, ind_order_to_check, rec.user.lang, true); + + if (!!mystr) + await this.sendMsg(msg.chat.id, mystr); + } + async menuLinkCondividere(msg) { const rec = this.getRecInMem(msg); @@ -823,7 +1003,7 @@ class Telegram { if (iniziata) { - mystr += emo.CHECK_VERDE + ' ' + tools.get__('ZOOM_INIZIATO') + ' ' + emo.CHECK_VERDE + '\n'; + mystr += emo.CHECK_VERDE + ' ' + tools.get__('ZOOM_INIZIATO') + ' ' + emo.CHECK_VERDE + '\n'; } mystr += `${emo.EYES} ${tools.getstrDateTimeShort(evento.date_start)} ${emo.EYES}`; @@ -859,23 +1039,71 @@ class Telegram { this.sendMsg(msg.chat.id, mystr, MenuAdmin); } - async menumsgAll(msg) { - const rec = this.getRecInMem(msg); - if (rec.user) { - const mystr = 'Scrivi qui un Messaggio da inviare a TUTTI:'; - rec.msgall_status = StatusMSGALL.ASK; - rec.msgall_staff = false; - await this.sendMsg(msg.chat.id, mystr, MenuAdmin); + getDestinStr(msg, destin, rec) { + if (destin === Destin.TUTTI) + return 'TUTTI'; + else if (destin === Destin.STAFF) + return 'STAFF'; + else if (destin === Destin.NO_7_REQ) + return 'No 7 Requisiti'; + else if (destin === Destin.NO_9_REQ) + return 'No 9 Requisiti'; + else if (destin === Destin.SI_INVITATI_NO_7REQ_INVITATI) + return '2 Invitati ma NO Requisiti'; + else if (destin === Destin.MSG_TO_NAVE) + return 'Nave ' + rec.extraparam; + else if (destin === Destin.A_UTENTE) { + const rec = this.getRecInMem(msg); + return rec.msgall_username_specifico } + + } + + async menumsgAll(msg) { + await this.menumsgGenerico(msg, Destin.TUTTI); } async menumsgStaff(msg) { + await this.menumsgGenerico(msg, Destin.STAFF); + } + + async menumsg_No_7_Req(msg) { + await this.menumsgGenerico(msg, Destin.NO_7_REQ); + } + + async menumsg_No_9_Req(msg) { + await this.menumsgGenerico(msg, Destin.NO_9_REQ); + } + + async menumsg_to_Nave(msg, nave) { + await this.menumsgGenerico(msg, Destin.MSG_TO_NAVE, undefined, nave); + } + + async menumsg_Si_Invitati_No_7Req(msg) { + await this.menumsgGenerico(msg, Destin.SI_INVITATI_NO_7REQ_INVITATI); + } + + async menumsg_A_Utente(msg) { + const arr = msg.text.split(' '); + if (!!arr && arr.length > 1) { + const username = arr[1]; + const rec = this.getRecInMem(msg); + rec.msg_wait = true; + await this.SendMsgToUser(msg, rec, username, msg.text); + } + } + + async menumsgGenerico(msg, dest, username, extraparam) { const rec = this.getRecInMem(msg); if (rec.user) { - const mystr = 'Scrivi qui un Messaggio da inviare allo STAFF:'; rec.msgall_status = StatusMSGALL.ASK; - rec.msgall_staff = true; - await this.sendMsg(msg.chat.id, mystr, MenuAdmin); + rec.msgall_achi = dest; + rec.extraparam = extraparam; + if (!!username) { + rec.msgall_username_specifico = username; + } + const mystr = 'Scrivi qui un Messaggio da inviare a' + ' [' + this.getDestinStr(msg, dest, rec) + ']:'; + await this.sendMsg(msg.chat.id, mystr, MenuSend); } } @@ -918,6 +1146,14 @@ class Telegram { return this.arrUsers.find((rec) => rec.id === id); } + getRecByUsername(username) { + return this.arrUsers.find((rec) => rec.username_bo === username); + } + + getRecInMemById(id) { + return this.arrUsers.find((rec) => rec.id === id); + } + deleteRecInMem(msg) { this.arrUsers = this.arrUsers.filter((rec) => rec.id !== msg.from.id); } @@ -925,7 +1161,8 @@ class Telegram { async getUser(msg, rec, conmsg) { let myid = 0; let ok = false; - const user = await User.findByUsername(this.idapp, msg.text.trim(), true); + let mystruser = tools.getFirstWord(msg.text.trim()); + const user = await User.findByUsername(this.idapp, mystruser, true); if (!user) { if (conmsg) { await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND, MenuNoLogin); @@ -1029,54 +1266,143 @@ class Telegram { } } - async sendMsgToAll(rec, msg, texttosend, solostaff) { - if (texttosend.length < 3) { - } else { - const usersall = await User.getUsersTelegALL(rec.user.idapp); - - let nummsgsent = 0; - - let textdainviare = ""; - - if (texttosend === Menu.ZOOM) { - texttosend = await this.getNextZoom() + async sistemaRecDest(rec, msg) { + let recdest = this.getRecByUsername(rec.msgall_username_specifico); + if (!recdest) { + const userdest = await User.findByUsername(this.idapp, rec.msgall_username_specifico); + if (!!userdest) { + let msgdest = msg; + msgdest.from.id = userdest.profile.teleg_id; + await this.createIfNotExist(msgdest); + recdest = this.getRecByUsername(rec.msgall_username_specifico); } - - if (usersall) { - if (solostaff) - tools.writeEventsLog('[MSG_A_STAFF]: ' + texttosend); - else - tools.writeEventsLog('[MSG_A_TUTTI]: ' + texttosend); - - for (const utente of usersall) { - - if (texttosend === Menu.LAVAGNA) { - textdainviare = await this.getLavagnaByUser(utente, msg); - } else { - textdainviare = texttosend; - } - let invia = true; - if (solostaff) { - invia = User.isManager(utente.perm) - } - if (invia) { - await this.sendMsg(utente.profile.teleg_id, textdainviare); - nummsgsent++; - await tools.snooze(300) - } - - if ((nummsgsent % 100) === 0) - myid = await this.sendMsg(msg.chat.id, nummsgsent + ' ' + getstr(msg.from.language_code, txt.MSG_MSG_INCORSO), null, { message_id: myid }); - - // ++Todo: SLEEP ??? sleep(0.03) - } - } - - await this.sendMsg(msg.chat.id, nummsgsent + ' ' + getstr(msg.from.language_code, txt.MSG_MSG_SENT)); } - rec.start_write_msgall = false; + if (!!recdest) { + recdest.msgall_username_specifico = rec.username_bo; + } else { + rec.msgall_username_specifico = ''; + } + + return recdest } + + async sendMsgToAll(rec, msg, texttosend, destin) { + try { + if ((texttosend.length < 3) && (destin !== Destin.A_UTENTE)) { + } else { + + let usersall = null; + if (destin === Destin.A_UTENTE) + usersall = await User.getUsersTelegALL(rec.user.idapp, rec.msgall_username_specifico); + else + usersall = await User.getUsersTelegALL(rec.user.idapp); + + let nummsgsent = 0; + + let textdainviare = ""; + let preparatesto = ''; + let myid = ''; + + if (texttosend === Menu.ZOOM) { + texttosend = await this.getNextZoom() + } + + const cmd = texttosend.toLowerCase(); + + if (usersall) { + if (cmd === Menu.INDIETRO) { + rec.msgall_status = StatusMSGALL.NONE; + return + } + + tools.writeEventsLog(this.getDestinStr(msg, destin, rec) + ':\n' + texttosend); + + for (const utente of usersall) { + + if (texttosend === Menu.LAVAGNA) { + textdainviare = await this.getLavagnaByUser(utente, msg); + } else if (destin === Destin.A_UTENTE) { + textdainviare = texttosend; + } else { + textdainviare = texttosend; + } + + let invia = false; + if (destin === Destin.STAFF) { + invia = User.isManager(utente.perm); + } else if (destin === Destin.TUTTI) { + invia = true; + } 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.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); + invia = (numinvitati >= 2) && (numinvitatiattivi < 2); + } + if (invia) { + if (cmd === RICEVI_EMAIL) { + preparatesto += utente.email + ', '; + } else if (cmd === CONTA_SOLO) { + // Niente + } else { + 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); + } + await tools.snooze(300) + } + nummsgsent++; + + if (!SendMsgCmd.includes(cmd)) { + if ((nummsgsent % 50) === 0) { + myid = await this.sendMsg(msg.chat.id, nummsgsent + ' ' + getstr(msg.from.language_code, txt.MSG_MSG_INCORSO), null, { message_id: myid }); + await tools.snooze(300) + } + } + } + } + } + + let msgris = ""; + if (cmd === CONTA_SOLO) { + msgris = nummsgsent + ' ' + getstr(msg.from.language_code, txt.MSG_MSG_TOSENT); + } else if (cmd === RICEVI_EMAIL) { + msgris = nummsgsent + ' ' + 'Email'; + await this.sendMsg(msg.chat.id, msgris); + msgris = preparatesto; + } else { + msgris = nummsgsent + ' ' + getstr(msg.from.language_code, txt.MSG_MSG_SENT); + } + + if (destin === Destin.A_UTENTE) { + const recdest = await this.sistemaRecDest(rec); + if (!!recdest) { + await this.sendMsg(msg.chat.id, 'Conversazione Iniziata con ' + rec.msgall_username_specifico + ' !', MenuChat); + } else { + await this.sendMsg(msg.chat.id, 'Utente ' + rec.msgall_username_specifico + ' non presente sul BOT !'); + } + } else { + tools.writeEventsLog(msgris); + await this.sendMsg(msg.chat.id, msgris); + } + + } + rec.start_write_msgall = false; + } catch (e) { + console.error(e); + } + } + + selectMenuHelp(msg) { return ((msg.text === Menu.INFO) || (msg.text === Menu.ASSISTENZA)) } @@ -1106,8 +1432,7 @@ class Telegram { if (rec.msgall_status === StatusMSGALL.CONFIRM) { if (msg.text === Menu.SI) { // Take msg to send to ALL - await - this.sendMsgToAll(rec, msg, rec.msgtosent, rec.msgall_staff) + await this.sendMsgToAll(rec, msg, rec.msgtosent, rec.msgall_achi) } else { this.sendMsg(msg.chat.id, txt.MSG_OPERAZ_ANNULLATA); } @@ -1117,10 +1442,20 @@ class Telegram { if (msg.text !== Menu.INDIETRO) { rec.msgtosent = msg.text; rec.msgall_status = StatusMSGALL.CONFIRM; - let achi = "TUTTI"; - if (rec.msgall_staff) - achi = "STAFF"; - const domanda = 'Confermi d\'Inviare questo messaggio a ' + achi + ' ?\n' + rec.msgtosent; + const cmd = rec.msgtosent.toLowerCase(); + let achi = this.getDestinStr(msg, rec.msgall_achi, rec); + let domanda = ''; + if (cmd === CONTA_SOLO) + 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 (rec.msgall_achi === Destin.A_UTENTE) + domanda = 'Confermi d\'Iniziare una Chat messaggi con ' + achi + ' ?\n' + rec.msgtosent; + else + domanda = 'Confermi d\'Inviare questo messaggio a ' + achi + ' ?\n' + rec.msgtosent; + } + this.ChiediSINO(msg, domanda); } else { rec.msgall_status = StatusMSGALL.NONE; @@ -1157,8 +1492,7 @@ class Telegram { async setUser(msg) { const id = msg.from.id; - const user = await - User.UserByIdTelegram(this.idapp, id); + const user = await User.UserByIdTelegram(this.idapp, id); let rec = this.arrUsers.find((rec) => rec.id === msg.from.id); if (user && rec) { rec.user = user; @@ -1166,6 +1500,15 @@ class Telegram { } + async setUserbyUsername(username) { + const user = await User.findByUsername(this.idapp, username); + let rec = this.arrUsers.find((rec) => rec.username_bo === username); + if (user && rec) { + rec.user = user; + } + + } + async alreadyExist(msg) { const id = msg.from.id; let rec = null; @@ -1204,7 +1547,12 @@ class Telegram { retry: 0, username_bo: '', msgall_status: StatusMSGALL.NONE, + msgall_achi: 0, + msgall_username_specifico: '', + extraparam: '', msgtosent: '', + msg_wait: false, + lastmenu: null, }; this.arrUsers.push(rec); @@ -1222,9 +1570,8 @@ class Telegram { async getKeyboard(id, menu) { let keyb = MenuStandard; // Check if you are Admin - const ismanager = await - User.isAdminByIdTeleg(this.idapp, id); - if (ismanager) + const ismanager = await User.isAdminByIdTeleg(this.idapp, id); + if (ismanager && menu !== MenuChat) keyb = MenuPerAdmin; if (menu) { keyb = menu @@ -1247,7 +1594,7 @@ class Telegram { } - async _inviaMsg(id, text, form, menu, msg_id, chat_id) { + async _inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec) { if (!text) return 0; @@ -1255,6 +1602,26 @@ class Telegram { return this.modificaMsg(chat_id, msg_id, text); } + const recmem = this.getRecInMemById(id); + + if (!menu) { + if (recmem) { + if (recmem.msgall_username_specifico !== '') { + menu = MenuChat + } + } + } + + if (recmem) { + recmem.lastmenu = menu + } + + if (ripr_menuPrec) { + if (recmem && !!recmem.lastmenu) { + menu = recmem.lastmenu + } + } + try { if (!form) { form = { @@ -1286,9 +1653,27 @@ class Telegram { } } - async sendMsg(id, text, menu, form, msg_id, chat_id) { + async SendMsgToUser(msg, rec, username, text) { + if (rec.msg_wait) { + await this.menumsgGenerico(msg, Destin.A_UTENTE, username); + rec.msg_wait = false; + } else { + const telegid = await User.TelegIdByUsername(this.idapp, username); + if (telegid > 0) { + await this.sistemaRecDest(rec, msg); + // await this.sendMsg(msg.chat.id, '[Msg inviato a ' + username + ']: '); + await this.sendMsg(telegid, Menu.CHAT_PERSONALE + '[' + rec.username_bo + ' ti scrive]:\n' + text, MenuChat); + } else { + await this.sendMsg(msg.chat.id, 'Username non valido'); + rec.msgall_username_specifico = '' + } + } + } - return this._inviaMsg(id, text, form, menu, msg_id, chat_id); + + async sendMsg(id, text, menu, form, msg_id, chat_id, ripr_menuPrec) { + + return 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 b009db4..6ec2457 100644 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -24,11 +24,13 @@ const webpush = require('web-push'); const FILELOG = 'filelog.txt'; const FILEEVENTS = 'logevents.txt'; -const FILEBILLETTERA = 'logBillettera.txt'; +const FILEMANAGERS = 'logmanagers.txt'; +const FILENAVE = 'logNave.txt'; const subject = process.env.URLBASE_APP1; const publicVapidKey = process.env.PUBLIC_VAPI_KEY; const privateVapidKey = process.env.PRIVATE_VAPI_KEY; + // Code goes here const keySize = 256; const ivSize = 128; @@ -50,11 +52,11 @@ textlang = { "partecipanti": "partecipanti", 'TESTO_ASSISTENZA': "Per entrare nel Sito AYNI:\nhttps://ayni.gifteconomy.app\n\nHai dimenticato la Password per accedere al sito?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\nChat AYNI BOT (questa):\nhttps://t.me/notevoleaynibot\n\nChat AYNI - EMPOWER: Entra ⛩ nella nostra Community chat:\n https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g\n\nChat AYNI-BIBLIO: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nChat di Aiuto e Supporto: 'AYNI - HELP'\nhttps://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w\n1 - 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", - 'HAI_I_7_REQUISITI': 'PRIMI PASSI OK!\nHai i Primi 7 Requisiti per Entrare in programmazione!', - 'NON_HAI_I_7_REQUISITI': 'Attenzione!\nAncora non hai i 7 Requisiti per Entrare in programmazione!', - 'HAI_I_9_REQUISITI': 'COMPLIMENTI!\nHai TUTTI i 9 Requisiti per poter effettuare e poi ricevere il tuo Dono!', - 'NON_HAI_I_9_REQUISITI': 'Attenzione!\nAncora non hai Tutti i 9 Requisiti per poter effettuare e poi ricevere il tuo Dono!', - 'INFO_LA_MIA_LAVAGNA': '✨ Lista dei Requisiti: ✨ \n', + 'HAI_I_7_REQUISITI': 'PRIMI PASSI OK!\nHai i Primi 7 Requisiti per Entrare nella Lista d\'Imbarco!', + 'NON_HAI_I_7_REQUISITI': 'Attenzione!\nAncora non hai i 7 Requisiti per Entrare nella Lista d\'Imbarco!', + 'HAI_I_9_REQUISITI': 'COMPLIMENTI!\nHai Completato TUTTI i 9 Passi della Guida! Grazie per Aiutare AYNI ad Espandersi!', + 'NON_HAI_I_9_REQUISITI': 'Ricorda 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 dei tuoi invitati, clicca sulle 3 linee in alto a sinistra ed accedi alla voce "Lavagna".\n', 'INFO_LAVAGNA_SITO': 'Per vedere lo stato dei tuoi invitati, sul sito AYNI, clicca sulle 3 linee in alto a sinistra ed accedi alla voce "Lavagna".\n', 'INFO_LINK_DA_CONDIVIDERE': 'Link da condividere ai tuoi invitati per farli registrare al sito di Ayni:\n%s\n\nLink da condividere per partecipare allo Zoom (Conferenza OnLine):\n%s', @@ -70,7 +72,7 @@ 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', + 'PAYMENTS': 'Modalità di Pagamento (Obbligatorio Paypal)', 'INVITATI': 'persone registrate che hai invitato', 'INVITATI_ATTIVI': 'Invitati con i 7 Requisiti', 'NONREG': 'Invitati non Registrati', @@ -79,6 +81,10 @@ textlang = { 'ZOOM_INIZIATO': 'QUESTA CONFERENZA E\' INIZIATA!', '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 !', + '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' }, es: { "L'Email è già stata Verificata": "L'Email è già stata Verificata", @@ -87,11 +93,11 @@ textlang = { "partecipanti": "participantes", 'TESTO_ASSISTENZA': "Per entrare nel Sito AYNI:\nhttps://ayni.gifteconomy.app\n\nHai dimenticato la Password per accedere al sito?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\nChat AYNI BOT (questa):\nhttps://t.me/notevoleaynibot\n\nChat AYNI - EMPOWER: Entra ⛩ nella nostra Community chat:\n https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g\n\nChat AYNI-BIBLIO: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nChat di Aiuto e Supporto: 'AYNI - HELP'\nhttps://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w\n1 - 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", - 'HAI_I_7_REQUISITI': 'PRIMI PASSI OK!\nHai i Primi 7 Requisiti per Entrare in programmazione!', - 'NON_HAI_I_7_REQUISITI': 'Attenzione!\nAncora non hai i 7 Requisiti per Entrare in programmazione!', - 'HAI_I_9_REQUISITI': 'COMPLIMENTI!\nHai TUTTI i 9 Requisiti per poter effettuare e poi ricevere il tuo Dono!', - 'NON_HAI_I_9_REQUISITI': 'Attenzione!\nAncora non hai Tutti i 9 Requisiti per poter effettuare e poi ricevere il tuo Dono!', - 'INFO_LA_MIA_LAVAGNA': '✨ Lista dei Requisiti: ✨ \n', + 'HAI_I_7_REQUISITI': 'PRIMI PASSI OK!\nHai i Primi 7 Requisiti per Entrare nella Lista d\'Imbarco!', + 'NON_HAI_I_7_REQUISITI': 'Attenzione!\nAncora non hai i 7 Requisiti per Entrare nella Lista d\'Imbarco!', + 'HAI_I_9_REQUISITI': 'COMPLIMENTI!\nHai Completato TUTTI i 9 Passi della Guida! Grazie per Aiutare AYNI ad Espandersi!', + 'NON_HAI_I_9_REQUISITI': 'Ricorda 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 dei tuoi invitati, clicca sulle 3 linee in alto a sinistra ed accedi alla voce "Lavagna".\n', 'INFO_LAVAGNA_SITO': 'Per vedere lo stato dei tuoi invitati, sul sito AYNI, clicca sulle 3 linee in alto a sinistra ed accedi alla voce "Lavagna".\n', 'INFO_LINK_DA_CONDIVIDERE': 'Link da condividere ai tuoi invitati per farli registrare al sito di Ayni:\n%s\n\nLink da condividere per partecipare allo Zoom (Conferenza OnLine):\n%s', @@ -107,7 +113,7 @@ 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', + 'PAYMENTS': 'Modalità di Pagamento (Obbligatorio Paypal)', 'INVITATI': 'persone registrate che hai invitato', 'INVITATI_ATTIVI': 'Invitati con i 7 Requisiti', 'NONREG': 'Invitati non Registrati', @@ -116,16 +122,20 @@ textlang = { 'ZOOM_INIZIATO': 'QUESTA CONFERENZA E\' INIZIATA!', 'SCEGLI_VOCE': 'scegli una voce:', 'INVITATI_LISTA': 'I Tuoi Invitati (in verde con almeno i primi 7 Requisiti)', + 'CIAO': 'Hola', + 'ADDED_TOLISTAINGRESSO': 'Has sido añadido a la lista de personas que entrarán en Lista de embarque!', + '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' }, us: { "partecipanti": "participants", 'TESTO_ASSISTENZA': "Per entrare nel Sito AYNI:\nhttps://ayni.gifteconomy.app\n\nHai dimenticato la Password per accedere al sito?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\nChat AYNI BOT (questa):\nhttps://t.me/notevoleaynibot\n\nChat AYNI - EMPOWER: Entra ⛩ nella nostra Community chat:\n https://t.me/joinchat/C741mkx5QYXu-kyYCYvA8g\n\nChat AYNI-BIBLIO: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nChat di Aiuto e Supporto: 'AYNI - HELP'\nhttps://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w\n1 - 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", - 'HAI_I_7_REQUISITI': 'PRIMI PASSI OK!\nHai i Primi 7 Requisiti per Entrare in programmazione!', - 'NON_HAI_I_7_REQUISITI': 'Attenzione!\nAncora non hai i 7 Requisiti per Entrare in programmazione!', - 'HAI_I_9_REQUISITI': 'COMPLIMENTI!\nHai TUTTI i 9 Requisiti per poter effettuare e poi ricevere il tuo Dono!', - 'NON_HAI_I_9_REQUISITI': 'Attenzione!\nAncora non hai Tutti i 9 Requisiti per poter effettuare e poi ricevere il tuo Dono!', - 'INFO_LA_MIA_LAVAGNA': '✨ Lista dei Requisiti: ✨ \n', + 'HAI_I_7_REQUISITI': 'PRIMI PASSI OK!\nHai i Primi 7 Requisiti per Entrare nella Lista d\'Imbarco!', + 'NON_HAI_I_7_REQUISITI': 'Attenzione!\nAncora non hai i 7 Requisiti per Entrare nella Lista d\'Imbarco!', + 'HAI_I_9_REQUISITI': 'COMPLIMENTI!\nHai Completato TUTTI i 9 Passi della Guida! Grazie per Aiutare AYNI ad Espandersi!', + 'NON_HAI_I_9_REQUISITI': 'Ricorda 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 dei tuoi invitati, clicca sulle 3 linee in alto a sinistra ed accedi alla voce "Lavagna".\n', 'INFO_LAVAGNA_SITO': 'Per vedere lo stato dei tuoi invitati, sul sito AYNI, clicca sulle 3 linee in alto a sinistra ed accedi alla voce "Lavagna".\n', 'INFO_LINK_DA_CONDIVIDERE': 'Link da condividere ai tuoi invitati per farli registrare al sito di Ayni:\n%s\n\nLink da condividere per partecipare allo Zoom (Conferenza OnLine):\n%s', @@ -141,7 +151,7 @@ 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', + 'PAYMENTS': 'Modalità di Pagamento (Obbligatorio Paypal)', 'INVITATI': 'persone registrate che hai invitato', 'INVITATI_ATTIVI': 'Invitati con i 7 Requisiti', 'NONREG': 'Invitati non Registrati', @@ -150,6 +160,10 @@ textlang = { 'ZOOM_INIZIATO': 'QUESTA CONFERENZA E\' INIZIATA!', 'SCEGLI_VOCE': 'scegli una voce:', 'INVITATI_LISTA': 'I Tuoi Invitati (in verde con almeno i primi 7 Requisiti)', + 'CIAO': 'Hi', + 'ADDED_TOLISTAINGRESSO': 'You have been added to the List of people who will enter the Boarding List!', + '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' } }; @@ -167,6 +181,24 @@ module.exports = { TYPE_PROJECT: 1, TYPE_TODO: 2, + TipoMsg: { + SEND_LINK_CHAT_DONATORI: 1, + }, + + Placca: { + DONATORI: 1, + TUTTI: 2, + + STR_SOGNATORE: 'Sognatore', + STR_MEDIATORE: 'Mediatore', + STR_MEDIATORI: 'Mediatori', + STR_DONATORI: 'Donatori', + SOGNATORE: 'E1 🌈 ', + MEDIATORE: 'A1 💦 ', + SONOFUOCO: 0, + SONOACQUA: 3, + }, + FieldType: { boolean: 1, date: 2, @@ -518,6 +550,11 @@ module.exports = { return ''; }, + isAbilitaNave: function (idapp) { + const myapp = MYAPPS.find(item => item.idapp === idapp); + return myapp.abilitanave; + }, + getdirByIdApp: function (idapp) { const myapp = @@ -801,13 +838,35 @@ module.exports = { }, getstrDateTimeShort(mydate) { - // console.log('getstrDate', mytimestamp) - return this.getWeekDay(mydate) + ' ' + this.appendLeadingZeroes(mydate.getDate()) + '/' + this.appendLeadingZeroes(mydate.getMonth() + 1) + ' ORE ' + this.appendLeadingZeroes(mydate.getHours()) + ':' + this.appendLeadingZeroes(mydate.getMinutes()); + if (mydate) { + // console.log('getstrDate', mytimestamp) + return this.getWeekDay(mydate) + ' ' + this.appendLeadingZeroes(mydate.getDate()) + '/' + this.appendLeadingZeroes(mydate.getMonth() + 1) + ' ORE ' + this.appendLeadingZeroes(mydate.getHours()) + ':' + this.appendLeadingZeroes(mydate.getMinutes()); + } else { + return ''; + } + }, + + getstrDateShort(mydate) { + if (mydate) { + // console.log('getstrDate', mytimestamp) + return this.getWeekDay(mydate).substring(0, 3) + ' ' + this.appendLeadingZeroes(mydate.getDate()) + '/' + this.appendLeadingZeroes(mydate.getMonth() + 1); + } else { + return ''; + } + }, + + getstrDateLong(mydate) { + if (mydate) { + // console.log('getstrDate', mytimestamp) + return this.getWeekDay(mydate) + ' ' + this.appendLeadingZeroes(mydate.getDate()) + '/' + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + mydate.getFullYear(); + } else { + return ''; + } }, getlinkzoom(idconf) { if (idconf === '') - idconf = '8886662000'; + idconf = '6668882000'; return 'https://zoom.us/j/' + idconf }, @@ -889,8 +948,9 @@ module.exports = { // console.log('Saved!'); // }); - const stream = fs.createWriteStream(filename, {flags:'a'}); - stream.write(mystr); + // mystr = this.getstrDateTimeShort(Date.now()) + ' ' + mystr; + const stream = fs.createWriteStream(filename, { flags: 'a' }); + stream.write('\n' + mystr); stream.end(); }, @@ -902,8 +962,12 @@ module.exports = { this.writelogfile(mystr, FILEEVENTS); }, - writeBilletteraLog(mystr) { - this.writelogfile(mystr, FILEBILLETTERA); + writeManagersLog(mystr) { + this.writelogfile(mystr, FILEMANAGERS); + }, + + writeNaveLog(mystr) { + this.writelogfile(mystr, FILENAVE); }, move(oldPath, newPath, callback) { @@ -1011,11 +1075,15 @@ module.exports = { return mystr.replace(/\s+/g, '') }, - ModificheConsentite(table, fieldsvalue) { + ModificheConsentite(table, fieldsvalue, idrec, user) { if (table === 'users') { if ('aportador_solidario' in fieldsvalue) { return true; } + if ('ALL' in fieldsvalue) { + //++Todo: Cancellalo solo se sono io il creatore dell'utente ... o se posso! + return true + } } return false; @@ -1029,5 +1097,20 @@ module.exports = { return false; }, + getFirstWord(mystr) { + const myarr = mystr.split(" "); + if (myarr.length > 0) + return myarr[0]; + else + return mystr + }, + + getFirst2Car(mystr) { + if (!!mystr) + return mystr.substring(0, 2) + '.'; + else + return '' + }, + }; diff --git a/src/server/tools/shared_vuejs.ts b/src/server/tools/shared_vuejs.ts new file mode 120000 index 0000000..d0febe4 --- /dev/null +++ b/src/server/tools/shared_vuejs.ts @@ -0,0 +1 @@ +../../../../freeplanet/src/common/shared_vuejs.ts \ No newline at end of file