diff --git a/.env.old b/.env.old new file mode 100644 index 0000000..6be4079 --- /dev/null +++ b/.env.old @@ -0,0 +1,22 @@ +DATABASE=Old_FreePlanet +UDB=paofreeplanet +PDB=suerteFreePlanet@1A +SEND_EMAIL=1 +PORT=3002 +ENABLE_PUSHNOTIFICATION=0 +DIRECTORY_SERVER=old.freeplanet_serverside +SERVERDIR_WEBSITE=old.freeplanet_server +URLBASE_APP1=https://old.freeplanet.app +PORT_APP1="0" +DOMAIN=mongodb://localhost:27019/ +SIGNCODE=abc123 +DEBUG=0 +DELAY_SENDEMAIL=1000 +PATH_CERT_KEY=/etc/letsencrypt/live/freeplanet.app/privkey.pem +PATH_SERVER_CRT=/etc/letsencrypt/live/freeplanet.app/fullchain.pem +PUBLIC_VAPI_KEY="" +PRIVATE_VAPI_KEY="" +GCM_API_KEY="" +PROD=0 +PROJECT_DESCR_MAIN='__PROJECTS' +SECRK=iUUb38v23jjDFaosWj92axkBOXCQ diff --git a/docs/passi.txt b/docs/passi.txt index 4d42b9e..db768eb 100644 --- a/docs/passi.txt +++ b/docs/passi.txt @@ -1,10 +1,50 @@ -AGGIORNARE: ------------ -// ++Todo: DA FARE: +// ++Todo: FATTO: DA CONTROLLARE -- Se sei imbarcata i tuoi due invitati usati per quella posizione sono bloccati. Se ne hai in più li puoi regalare - - Mettere il tragitto anche sul BOT. +X - Se sei imbarcata i tuoi due invitati usati per quella posizione sono bloccati. Se ne hai in più li puoi regalare + +- L'ultimo Utente della Creazione della Nave, compare ancora il Sognatore !!! + Sistemato: TESTARE SE ORA È' OK... + + +// ************************************************ + +// ++Todo: PRIORITA' ALTA: + +CONTROLLARE: + + +- Sistemare la Creazione delle Navi... in semi-automatico. + +- Controllare gli Account di Andrea (sembrano mescolati....) socio856 è dentro invece non doveva esserci... + - socio856 non è stato raggruppato con socio85 (Andrea Lai) + + +- Mettere il tragitto anche sul BOT. + +- Inviare il Link che punta alla Pagina del Sito, per effettuare il Dono! + E per eventualmente Entrare nella GIFT CHAT! + + +// ++Todo: PRIORITA' NORMALE: + +- Se entro con la seconda utenza, gli mando messaggio che dice che deve collegarsi con la prima utenza.... + +- Fare funzione che passa un Utente secondario in un utente Primario! (c'è gia) + +- L'orario degli Zoom sul BOT è diverso che dal sito, deve dare quello locale... + +// ++Todo: DA FARE PIU AVANTI: + +- Sistemare poter modificare le Pagine. + +- Per il Fondo Ayni, prevedere anche altri Metodi di Pagamento... Revolut, N26, ecc... + ed inserirlo sul sito per il Sognatore (flag Pagato al Fondo: nave.offerta_al_fondo). + +- Le pagine dovranno andare memorizzate su statics/upload/pages/.... di modo da risparmiare banda. + +- Per Regalare una propria Nave? TESTARE -> inviare il msg anche al Sognatore della Gift Chat @@ -81,3 +121,5 @@ ANDREA +//++TODO: *** FATTI *** + diff --git a/src/server/models/graduatoria.js b/src/server/models/graduatoria.js new file mode 100755 index 0000000..3e1de6e --- /dev/null +++ b/src/server/models/graduatoria.js @@ -0,0 +1,395 @@ +const bcrypt = require('bcryptjs'); +const mongoose = require('mongoose'); +const validator = require('validator'); +const jwt = require('jsonwebtoken'); +const _ = require('lodash'); + +const tools = require('../tools/general'); + +const { ObjectID } = require('mongodb'); + +const { Nave } = require('./nave'); +const { Settings } = require('./settings'); + +const shared_consts = require('../tools/shared_nodejs'); +const queryclass = require('../classes/queryclass'); + +mongoose.Promise = global.Promise; + +mongoose.level = "F"; +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +mongoose.set('debug', process.env.DEBUG); + +const GraduatoriaSchema = new mongoose.Schema({ + idapp: { + type: String, + required: true, + }, + index: { + type: Number, + }, + idListaIngresso: { + type: String, + }, + ind_order: { + type: Number, + }, + num_tess: { + type: Number, + }, + ind: { + type: Number, + }, + // USER: + username: { + type: String, + }, + name: { + type: String, + }, + surname: { + type: String, + }, + indimbarco: { + type: Number, + }, + numNaviEntrato: { // Numero dell'Imbarco attuale + type: Number, + }, + numinvitati: { + type: Number, + }, + numinvitatiattivi: { + type: Number, + }, + numinvitatiTot: { + type: Number, + }, + numinvitatiattiviTot: { + type: Number, + }, + punteggio: { + type: Number, + }, + invitante_username: { + type: String, + }, + date_added: { // Data d'Ingresso (Completato i Requisiti o premuto Bottone Magico) + type: Date, + }, + +}); + +GraduatoriaSchema.pre('save', async function (next) { + if (this.isNew) { + try { + if (!this.index) { + const myrec = await Graduatoria.findOne({ idapp: this.idapp }).limit(1).sort({ index: -1 }); + + if (!!myrec) { + this.index = myrec._doc.index + 1; + } else { + this.index = 1; + } + } + } catch (e) { + this.index = 2; + } + } + + next(); +}); + + +GraduatoriaSchema.statics.findByIndOrder = function (idapp, ind_order) { + const Graduatoria = this; + + try { + return Graduatoria.findOne({ + 'idapp': idapp, + 'ind_order': ind_order, + }); + } catch (e) { + + } +}; + +GraduatoriaSchema.statics.findByAllRecByUsername = function (idapp, username) { + const Graduatoria = this; + + try { + return Graduatoria.find({ + idapp, + username, + }); + } catch (e) { + + } +}; + +GraduatoriaSchema.statics.getNumDaImbarcare = async function (idapp) { + const Graduatoria = this; + + return await Graduatoria.count({ idapp }) + +}; + +GraduatoriaSchema.statics.AggiornaIndiceGraduatoria = async function (idapp) { + const Graduatoria = this; + + let index = 1; + + await Graduatoria.find({ idapp }).sort({ punteggio: -1, date_added: 1 }).then(async (arrrec) => { + + for (const rec of arrrec) { + + await Graduatoria.findOneAndUpdate({ _id: rec._id }, { $set: { index } }, { new: false }); + index++; + } + }); + + return index - 1; + +}; + +GraduatoriaSchema.statics.getLastImbarco = async function (idapp, username) { + const Graduatoria = this; + + return await Graduatoria.findOne({ idapp, username }).sort({ _id: -1 }); + +}; + +GraduatoriaSchema.statics.getFirstUserGradFree = async function (idapp) { + const Graduatoria = this; + + const { User } = require('../models/user'); + + const arrrecgrad = await Graduatoria.find({ idapp, ind_order: { $gt: 0 } }).sort({ index: 1 }).limit(20); + if (!!arrrecgrad) { + for (const recgrad of arrrecgrad) { + const myuser = await User.findOne({ + idapp, + username: recgrad.username, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + }); + + if (!!myuser) { + return recgrad; + } + } + } + + return null; + +}; + + +GraduatoriaSchema.statics.addSingoloInGraduatoria_InFondo = async function (idapp, recingr) { + const Graduatoria = this; + + const lastimbarco = await Graduatoria.getLastImbarco(idapp, recingr.username); + + const arrindex = []; + + const { ListaIngresso } = require('../models/listaingresso'); + + arrindex[recingr.username] = lastimbarco.indimbarco; + + const newingr = await ListaIngresso.aggiornaRecListaIngr(idapp, recingr, arrindex); + + const myrectoadd = addRecGraduatoria(idapp, newingr); + + return await myrectoadd.save(myrectoadd) + .then((ris) => { + return !!ris; + }) + .catch((e) => { + console.error(e.message); + }); + +}; + +function addRecGraduatoria(idapp, ingr, index) { + + try { + let rec = new Graduatoria({ + _id: new ObjectID(), + idapp, + idListaIngresso: ingr._id, + ind_order: ingr.ind_order, + num_tess: ingr.num_tess, + username: ingr.username, + name: ingr.name, + surname: ingr.surname, + indimbarco: ingr.indimbarco, + numNaviEntrato: ingr.numNaviEntrato, + numinvitati: ingr.numinvitati, + numinvitatiattivi: ingr.numinvitatiattivi, + numinvitatiTot: ingr.numinvitatiTot, + numinvitatiattiviTot: ingr.numinvitatiattiviTot, + punteggio: ingr.punteggio, + invitante_username: ingr.invitante_username, + date_added: ingr.date_added, + }); + + if (!!index) { + rec.index = index; + } + return rec; + } catch (e) { + console.error(e.message); + return null; + } + +} + +GraduatoriaSchema.statics.addArrayInGraduatoria = async function (idapp, arrayingr) { + const Graduatoria = this; + + try { + let myobjadd = []; + + let index = 0; + + for (const ingr of arrayingr) { + + index++; + + myobjadd.push(addRecGraduatoria(idapp, ingr, index)); + } + + // Cancella prima tutto + await Graduatoria.deleteMany({ idapp }); + + // Riscrivi Tutto + const ris = await Graduatoria.insertMany(myobjadd); + + + if (!!ris) + return ris.length; + else + return 0; + + } catch (e) { + console.error(e.message); + } + return null; +}; + +GraduatoriaSchema.statics.getFieldsForSearch = function () { + return [ + { field: 'index', type: tools.FieldType.number }, + { field: 'ind_order', type: tools.FieldType.number }, + { field: 'name', type: tools.FieldType.string }, + { field: 'surname', type: tools.FieldType.string }, + { field: 'username', type: tools.FieldType.string }, + { field: 'invitante_username', type: tools.FieldType.string }, + ] +}; + +GraduatoriaSchema.statics.executeQueryTable = function (idapp, params) { + params.fieldsearch = this.getFieldsForSearch(); + return tools.executeQueryTable(this, idapp, params); +}; + +GraduatoriaSchema.statics.findAllIdApp = function (idapp) { + const Graduatoria = this; + + const myfind = { idapp }; + + return Graduatoria.find(myfind, (err, arrrec) => { + return arrrec + }); +}; + +GraduatoriaSchema.statics.isWorking = function (idapp) { + + return Settings.getValDbSettings(idapp, 'GRAD_WORK', false); + +}; + +GraduatoriaSchema.statics.setWorking = function (idapp, stato) { + + return Settings.setBool(idapp, 'GRAD_WORK', stato); + +}; + +function getinvit(index, myrec) { + let inv = myrec.numinvitati; + let invattivi = myrec.numinvitatiattivi; + + const step = (myrec.numNaviEntrato + index) * 2; + + inv -= step; + // console.log('inv', inv, 'step = ', step) + invattivi -= step; + if (inv < 0) + inv = 0; + if (invattivi < 0) + invattivi = 0; + if (inv > 2) + inv = 2; + if (invattivi > 2) + invattivi = 2; + + return { invattivi, inv } +} + +/* +function getnuminv(index, myrec) { + const ris = getinvit(index, myrec); + + return ris.inv +} + +function getnuminvattivi(index, myrec) { + const ris = getinvit(index, myrec); + + return ris.invattivi +}*/ + + +GraduatoriaSchema.statics.getPosizioneInGraduatoria = async function (idapp, ind_order, username, num_tess) { + const Graduatoria = this; + + const totposiz = await Graduatoria.countDocuments({ idapp }); + + return Graduatoria.findOne({ idapp, username, ind_order, num_tess }).then((rec) => { + + if (!!rec) { + + } else { + return { + posiz: 0, + totposiz: 0, + num_tess: 0, + numinvitatiTot: 0, + numinvitatiattiviTot: 0, + numNaviEntrato: 0, + indimbarco: 1, + } + } + + const ris = { + totposiz, + posiz: rec.index, + numinvitatiTot: rec.numinvitatiTot, + numinvitatiattiviTot: rec.numinvitatiattiviTot, + num_tess: rec.num_tess, + numNaviEntrato: rec.numNaviEntrato, + indimbarco: rec.indimbarco, + }; + + return ris; + }); + +}; + + +const Graduatoria = mongoose.model('Graduatoria', GraduatoriaSchema); + +module.exports = { Graduatoria }; diff --git a/src/server/models/listaingresso.js b/src/server/models/listaingresso.js index 678f594..54122ad 100755 --- a/src/server/models/listaingresso.js +++ b/src/server/models/listaingresso.js @@ -1,4 +1,4 @@ -var bcrypt = require('bcryptjs'); +const bcrypt = require('bcryptjs'); const mongoose = require('mongoose'); const validator = require('validator'); const jwt = require('jsonwebtoken'); @@ -9,6 +9,7 @@ const tools = require('../tools/general'); const { ObjectID } = require('mongodb'); const { Nave } = require('./nave'); +const { Graduatoria } = require('./graduatoria'); const shared_consts = require('../tools/shared_nodejs'); const queryclass = require('../classes/queryclass'); @@ -108,6 +109,63 @@ ListaIngressoSchema.statics.getTotInLista = async function (idapp) { return await ListaIngresso.count(myfind); }; +ListaIngressoSchema.statics.getImbarcatiDaily = function (idapp, nrec) { + + const query = [ + { + $match: { + idapp, deleted: false, date_added: { $gte: tools.IncDateNow(-(1000 * 60 * 60 * 24 * nrec)) }, + } + }, + { + $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$date_added" } }, count: { $sum: 1 } } + }, + { + $sort: { _id: 1 } + } + ]; + return query +}; + + +ListaIngressoSchema.statics.getImbarcatiWeekly = function (idapp, nrec) { + + const query = [ + { + $match: { + idapp, deleted: false, date_added: { $gte: tools.IncDateNow(-(1000 * 60 * 60 * 24 * nrec)) }, + } + }, + { + $group: { _id: { $dateToString: { format: "%Y-%U", date: "$date_added" } }, count: { $sum: 1 } } + }, + { + $sort: { _id: 1 } + } + ]; + return query +}; + + +ListaIngressoSchema.statics.ImbarcatiWeekly = async function (idapp) { + const ListaIngresso = this; + + return ListaIngresso.aggregate(ListaIngresso.getImbarcatiWeekly(idapp, 20 * 7)) + .then(ris => { + return JSON.stringify(ris.slice(0, -1)); + }); +}; + +ListaIngressoSchema.statics.ImbarcatiDaily = async function (idapp) { + const ListaIngresso = this; + + return ListaIngresso.aggregate(ListaIngresso.getImbarcatiDaily(idapp, 30)) + .then(ris => { + return JSON.stringify(ris.slice(0, -1)); + }); +}; + + ListaIngressoSchema.statics.findByIndOrder = function (idapp, ind_order) { const ListaIngresso = this; @@ -220,6 +278,12 @@ ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, user const ris = await listaingresso.save(); if (addednowreal) { if (!!ris) { + + if (addednowreal) { + // Aggiungilo anche nella Graduatoria ! + await Graduatoria.addSingoloInGraduatoria_InFondo(idapp, listaingresso); + } + const nome = await User.getNameSurnameByUsername(idapp, username); const numimbarcare = await ListaIngresso.getNumDaImbarcare(idapp); let msgtext = '🛳 '; @@ -238,7 +302,7 @@ ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, user if (!!opt) { if (!!opt.sendmsgtoinvitante) { if (opt.sendmsgtoinvitante) { - const nome = await User.getNameSurnameByUsername(idapp, invitante_username); + // const nome = await User.getNameSurnameByUsername(idapp, invitante_username); // msgtext = '🔵 ' + nome + ' (' + username + ') ' + tools.gettranslate('ADDED_TOLISTAINGRESSO', lang); // await telegrambot.sendMsgTelegram(idapp, username, msgtext, true); // Anche a STAFF } @@ -271,6 +335,49 @@ ListaIngressoSchema.statics.addUserInListaIngresso = async function (idapp, user ; +function getQueryNumInvitati(myfilter, myobjField, myfilter2, mygroup) { + const query = [ + { $match: myfilter }, + { + $lookup: { + from: "users", + as: "user", + let: { username: '$username' }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$username', '$$username'] }, + { $eq: ['$idapp', myfilter.idapp] }, + ] + } + } + } + ] + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$user", 0] }, "$$ROOT"] } } + }, + { $match: myfilter2 }, + ]; + + if (!!mygroup) { + query.push( + { $group: mygroup } + ); + } + + if (!!myobjField) { + query.push( + { $project: myobjField } + ); + } + + return query; +} + function getQueryProj(myfilter, myobjField, myfilter2, mygroup) { const query = [ { $match: myfilter }, @@ -358,6 +465,7 @@ function getQueryIndOrder(myfilter, myobjField, myfilter2, mygroup) { } +/* ListaIngressoSchema.statics.getPosizioneInLista = async function (idapp, arrrec, ind_order, num_tess) { @@ -376,6 +484,7 @@ ListaIngressoSchema.statics.getPosizioneInLista = async function (idapp, arrrec, return { posiz: posiz + 1, totposiz, num_tess, numNaviEntrato } }; +*/ ListaIngressoSchema.statics.showListaOrd = async function (idapp, solonuovi) { const ListaIngresso = this; @@ -386,6 +495,7 @@ ListaIngressoSchema.statics.showListaOrd = async function (idapp, solonuovi) { let conta = 1; for (const rec of arrrec) { mystr += conta + '- ' + ' [' + rec.numinvitatiattivi + '-' + rec.numinvitati + '] (' + rec.index + ') '; + mystr += ' {' + rec.numinvitatiattivireali + ',' + rec.numinvitatireali + '} '; mystr += ' [' + tools.getstrDateShort(rec.date_added, 'it') + '] '; mystr += rec.username + ' ' + rec.name + ' ' + rec.surname; mystr += ' inv = ' + rec.invitante_username; @@ -426,15 +536,89 @@ ListaIngressoSchema.statics.findAllIdApp = function (idapp) { function sortRec(rec) { return rec.sort(function (reca, recb) { - return Math.round((recb.numinvitatiattivi + recb.numinvitati) / recb.num_tess) - Math.round((reca.numinvitatiattivi + reca.numinvitati) / reca.num_tess); + // return Math.round((recb.numinvitatiattivi + recb.numinvitati) / recb.num_tess) - Math.round((reca.numinvitatiattivi + reca.numinvitati) / reca.num_tess); + // return Math.round((recb.numinvitatiattivi + recb.numinvitati) / recb.indimbarco * 2) - Math.round((reca.numinvitatiattivi + reca.numinvitati) / reca.indimbarco * 2); + // return Math.round((recb.numinvitatiattiviTot + recb.numinvitatiTot) / (recb.indimbarco + recb.numNaviEntrato * 2)) - Math.round((reca.numinvitatiattiviTot + reca.numinvitatiTot) / (reca.indimbarco + reca.numNaviEntrato * 2)); + + // return ((recb.numinvitatiattiviTot - recb.numNaviEntrato * 2) - (recb.indimbarco - 1) * 2) + ((recb.numinvitatiTot - recb.numNaviEntrato * 2) - (recb.indimbarco - 1) * 2) / + // (((reca.numinvitatiattiviTot - reca.numNaviEntrato * 2) - (reca.indimbarco - 1) * 2)) + ((reca.numinvitatiTot - reca.numNaviEntrato * 2) - (reca.indimbarco - 1) * 2); +// + //return Math.round(((recb.numinvitatiattiviTot * 2) + recb.numinvitatiTot) / (recb.indimbarco + recb.numNaviEntrato * 2)) - Math.round(((reca.numinvitatiattiviTot * 2) + reca.numinvitatiTot) / (reca.indimbarco + reca.numNaviEntrato * 2)); + }); } -ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuovi) { +ListaIngressoSchema.statics.getProssimiInLista = function (idapp, solonuovi) { + return Graduatoria.findAllIdApp(idapp).sort({ index: 1 }); +}; + + +ListaIngressoSchema.statics.aggiornaRecListaIngr = async function (idapp, rec, arrindex) { + + rec.numNaviEntrato = await Nave.getnumNaviByUsername(idapp, rec.username); + + rec.numinvitati = await ListaIngresso.getnumInvitati(idapp, rec.username); + rec.numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, rec.username); + + const arrListaIngrUser = arrindex[rec.username]; + if (!arrListaIngrUser) { + // arrindex[rec.username] = 1 + rec.numNaviEntrato; + arrindex[rec.username] = 1; + } else { + arrindex[rec.username] += 1; // incrementa + } + + rec.indimbarco = arrindex[rec.username]; + rec.numinvitatiTot = rec.numinvitati; + rec.numinvitatiattiviTot = rec.numinvitatiattivi; + + // rec.punteggio = (((rec.numinvitatiattiviTot * 1.5) - (rec.numNaviEntrato * 2)) - (rec.indimbarco - 1) * 2) + ((rec.numinvitatiTot - (rec.numNaviEntrato * 2)) - (rec.indimbarco - 1) * 2); + + let val1 = (((rec.numinvitatiattiviTot * 1.5) - (rec.numNaviEntrato * 2)) - (rec.indimbarco - 1) * 2); + let val2 = ((rec.numinvitatiTot - (rec.numNaviEntrato * 2)) - (rec.indimbarco - 1) * 2); + + if (val1 < 0) + val1 = 0; + if (val2 < 0) + val2 = 0; + if (val1 > 2) + val1 = 2; + if (val2 > 2) + val2 = 2; + + rec.punteggio = val1 + val2; + + // if (rec.num_tess > 2) { + rec.numinvitati = rec.numinvitati - (arrindex[rec.username] - 1) * 2; + rec.numinvitatiattivi = rec.numinvitatiattivi - (arrindex[rec.username] - 1) * 2; + // } + if (rec.numinvitati < 0) { + rec.numinvitati = 0; + } + if (rec.numinvitati > 2) { + rec.numinvitati = 2; + } + if (rec.numinvitatiattivi < 0) { + rec.numinvitatiattivi = 0; + } + + if (rec.numinvitatiattivi > 2) + rec.numinvitatiattivi = 2; + + return rec; +}; + +ListaIngressoSchema.statics.GeneraGraduatoria = async function (idapp, solonuovi) { const ListaIngresso = this; let myquery = ''; + //++Todo: DA TOGLIERE IL COMMENTO !!! + // if (await Graduatoria.isWorking(idapp)) + // return; + + await Graduatoria.setWorking(idapp, true); + let myobjField = { idapp: 1, index: 1, @@ -452,77 +636,68 @@ ListaIngressoSchema.statics.getProssimiInLista = async function (idapp, solonuov sospeso: 1, }; - let myfilter2 = { - surname: { $exists: true }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }; + try { + let myfilter2 = { + surname: { $exists: true }, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }; - if (solonuovi) { - myquery = getQueryProj({ - 'idapp': idapp, - ind_order: { $gte: 0 }, - added: false, - deleted: false, - }, myobjField, myfilter2); - } else { - myquery = getQueryProj({ - 'idapp': idapp, - ind_order: { $gte: 0 }, - deleted: false, - }, myobjField, myfilter2); + if (solonuovi) { + myquery = getQueryProj({ + 'idapp': idapp, + ind_order: { $gte: 0 }, + added: false, + deleted: false, + }, myobjField, myfilter2); + } else { + myquery = getQueryProj({ + 'idapp': idapp, + ind_order: { $gte: 0 }, + deleted: false, + }, myobjField, myfilter2); + } + + // await ListaIngresso.aggiornaIndex(); + + arrrec = await ListaIngresso.aggregate(myquery) + .then(async (arrlista) => { + + const { User } = require('../models/user'); + + let arrindex = {}; + + for (const rec of arrlista) { + + await ListaIngresso.aggiornaRecListaIngr(idapp, rec, arrindex) + + } + + /*if (arrlista) { + arrlista = sortRec(arrlista); + // arrlista.reverse(); + }*/ + + const salvasudb = true; + if (salvasudb) { + numrec = await Graduatoria.addArrayInGraduatoria(idapp, arrlista); + } + + await Graduatoria.AggiornaIndiceGraduatoria(idapp); + + await Graduatoria.setWorking(idapp, false); + + return numrec; + }).catch((e) => { + Graduatoria.setWorking(idapp, false); + + console.error(e.message); + return null + }); + + } catch (e) { + await Graduatoria.setWorking(idapp, false); } - // await ListaIngresso.aggiornaIndex(); - - arrrec = await ListaIngresso.aggregate(myquery).sort({ date_added: 1 }) - .then(async (arrlista) => { - - const { User } = require('../models/user'); - - const arrindex = {}; - - for (const rec of arrlista) { - - if (true) { - rec.numNaviEntrato = await Nave.getnumNaviByUsername(idapp, rec.username); - - rec.numinvitati = await ListaIngresso.getnumInvitati(idapp, rec.username); - rec.numinvitatiattivi = await ListaIngresso.getnumInvitatiAttivi(idapp, rec.username); - } - - const arrListaIngrUser = arrindex[rec.username]; - if (!arrListaIngrUser) { - arrindex[rec.username] = 1 + rec.numNaviEntrato; - } else { - arrindex[rec.username] += 1; // incrementa - } - - // if (rec.num_tess > 2) { - rec.numinvitati = rec.numinvitati - (arrindex[rec.username] - 1) * 2; - rec.numinvitatiattivi = rec.numinvitatiattivi - (arrindex[rec.username] - 1) * 2; - // } - if (rec.numinvitati < 0) { - rec.numinvitati = 0; - } - if (rec.numinvitatiattivi < 0) { - rec.numinvitatiattivi = 0; - } - - if (rec.numinvitatiattivi > 2) - rec.numinvitatiattivi = 2; - } - - if (arrlista) { - arrlista = sortRec(arrlista); - // arrlista.reverse(); - } - - return arrlista; - }).catch((e) => { - console.error(e.message); - return null - }); - return arrrec; }; @@ -558,7 +733,7 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { try { if (true) { // Elimina TUTTI i Cancellati (ma non Sospesi) - await User.remove({ + await User.deleteMany({ idapp, $and: [ { deleted: { $exists: true, $eq: true } }, // cancellati @@ -718,7 +893,7 @@ ListaIngressoSchema.statics.creaTessituraeConv = async function (idapp) { } // RIMUOVI IL CAMPO IND_ORDER SULLA USER! - await User.update({}, {$unset: {ind_order: 1}}, {multi: true}); + await User.update({}, { $unset: { ind_order: 1 } }, { multi: true }); // Ricalcola il Campo Index await User.ricalcolaIndex(idapp); @@ -757,7 +932,7 @@ ListaIngressoSchema.statics.getarray = async function (idapp, filtri, myobjField let myfilter2 = { surname: { $exists: true }, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], }; let myquery = getQueryProj( @@ -788,13 +963,33 @@ ListaIngressoSchema.statics.getarrayIndOrder = async function (idapp, filtri, my }; +ListaIngressoSchema.statics.getIngrEUserByFilter = async function (idapp, myfilter) { + const ListaIngresso = this; + + const arr = await ListaIngresso.getarray(idapp, myfilter, { + _id: 1, + idapp: 1, + username: 1, + ind_order: 1, + name: 1, + surname: 1, + index: 1 + }); + + if (!!arr) { + return arr.length > 0 ? arr[0] : null; + } + return null; + +}; + ListaIngressoSchema.statics.getInvitati = async function (idapp, username, includemyself, myobjField) { const ListaIngresso = this; let myq = { idapp, - deleted: false, + $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], invitante_username: username, }; @@ -828,9 +1023,71 @@ ListaIngressoSchema.statics.getUserByInvitante_Username = async function (idapp, */ +ListaIngressoSchema.statics.getnumInvitatiBase = async function (idapp, username, attivi) { + const ListaIngresso = this; + + const { User } = require('./user'); + + let myfilter2 = { + surname: { $exists: true }, + }; + + if (attivi) { + myfilter2 = { + ...myfilter2, + $and: User.getQueryQualified(), + } + } + + let myquery = getQueryProj({ + idapp, + invitante_username: username, + // username: { $ne: username }, + $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], + }, + { username: 1, ind_order: 1 }, + myfilter2, + ); + + // { _id: null, count: { $sum: 1 } + + arrlistainv = await ListaIngresso.aggregate(myquery); + + // Ottieni gli invitati che ancora non hanno un'imbarco + let myqueryuser = { + idapp, + aportador_solidario: username, + //$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + $or: [{ 'user.deleted': { $exists: false } }, { 'user.deleted': { $exists: true, $eq: false } }], + }; + + if (attivi) { + myqueryuser = { + ...myqueryuser, + $and: User.getQueryQualified() + } + } + + const arrinv = await User.find(myqueryuser); + + for (const inv of arrinv) { + if (!arrlistainv.find((rec) => rec.username === inv.username)) + arrlistainv.push(inv); + } + + if (!!arrlistainv) + return arrlistainv.length; + else + return 0; +}; + + ListaIngressoSchema.statics.getnumInvitati = async function (idapp, username) { const ListaIngresso = this; + return ListaIngresso.getnumInvitatiBase(idapp, username, false); + + /* const arrlistainv = await ListaIngresso.find({ idapp, invitante_username: username, @@ -847,71 +1104,31 @@ ListaIngressoSchema.statics.getnumInvitati = async function (idapp, username) { $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] }); - for (const inv of arrinv) { - if (!arrlistainv.find((rec) => rec.username === inv.username)) - arrlistainv.push(inv); - } - - if (!!arrlistainv) - return arrlistainv.length; - else - return 0; - -}; - -ListaIngressoSchema.statics.getnumInvitatiAttivi = async function (idapp, username) { - const ListaIngresso = this; - - const { User } = require('./user'); - - let myfilter2 = { - surname: { $exists: true }, - $and: User.getQueryQualified(), - }; - - let myquery = getQueryProj({ - idapp, - invitante_username: username, - // username: { $ne: username }, - deleted: false, - }, - { username: 1, ind_order: 1 }, - myfilter2, - ); - - // { _id: null, count: { $sum: 1 } - - arrlistainv = await ListaIngresso.aggregate(myquery); - - // Ottieni gli invitati che ancora non hanno un'imbarco - const arrinv = await User.find({ - idapp, - aportador_solidario: username, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - $and: User.getQueryQualified() - }); for (const inv of arrinv) { if (!arrlistainv.find((rec) => rec.username === inv.username)) arrlistainv.push(inv); - } + } */ + - if (!!arrlistainv) - return arrlistainv.length; - else - return 0; }; - -ListaIngressoSchema.statics.aggiornaIndex = function (idapp) { +ListaIngressoSchema.statics.Esegui_CronTab = async function (idapp) { const ListaIngresso = this; - const arrlista = ListaIngresso.find({ idapp }).sort({ created: 1 }); + console.log('Lancia CronTab: [IDAPP=' + idapp + ']'); + await ListaIngresso.GeneraGraduatoria(idapp, true); }; +ListaIngressoSchema.statics.getnumInvitatiAttivi = function (idapp, username) { + const ListaIngresso = this; + + return ListaIngresso.getnumInvitatiBase(idapp, username, true); +}; + const ListaIngresso = mongoose.model('ListaIngresso', ListaIngressoSchema); diff --git a/src/server/models/nave.js b/src/server/models/nave.js index 2675830..4f4bc32 100755 --- a/src/server/models/nave.js +++ b/src/server/models/nave.js @@ -36,6 +36,9 @@ const NaveSchema = new mongoose.Schema({ col: { type: Number, }, + idListaIngresso: { + type: String, + }, ind_order: { type: Number, }, @@ -57,6 +60,9 @@ const NaveSchema = new mongoose.Schema({ type: Boolean, default: false, }, + offerta_al_fondo: { + type: Number, + }, date_received_gift: { type: Date, }, @@ -75,7 +81,7 @@ const NaveSchema = new mongoose.Schema({ NaveSchema.statics.getTotInLista = async function (idapp) { const Nave = this; - const myfind = { idapp }; + const myfind = { idapp, ind_order: { $gte: 0 } }; return await Nave.count(myfind); }; @@ -410,6 +416,7 @@ function getQueryProj(myfilter) { _id: 1, idapp: 1, lang: 1, + idListaIngresso: 1, ind_order: 1, name: 1, surname: 1, @@ -488,6 +495,7 @@ function getQueryProj(myfilter) { function getQueryInvitante(myfilter) { myobjField = { + idListaIngresso: 1, ind_order: 1, name: 1, surname: 1, @@ -550,7 +558,6 @@ function getQueryInvitante(myfilter) { } - NaveSchema.statics.setRiga = function (idapp, riga) { return Settings.setKeyNum(idapp, 'riga', riga); }; @@ -567,11 +574,6 @@ NaveSchema.statics.getCol = function (idapp) { return Settings.getKeyNum(idapp, 'col', 1); }; -function getmaxcol(riga) { - - return Math.pow(2, riga - 1); -} - function getPrimoFuocoByIndCol(col) { // let ris = Math.ceil(col - (col % 8)) + 1; let ris = ((Math.ceil(col / 8) - 1) * 8) + 1; @@ -602,6 +604,7 @@ async function getusertextbyrec(myrec, symbol, lettera, riga, col, ind) { function checkifNullThenEmpty(rec, riga, col) { if (rec === null) { return { + idListaIngresso: -1, name: '', surname: '', username: '', @@ -803,7 +806,7 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in mystr += tools.ACAPO + '4️⃣° 🌀 ' + tools.get__('MEDIATORE', lang) + ':' + await getusertextbyrec(recmediatore, '', '', riga, col, '') + tools.ACAPO + tools.ACAPO; - mystr += '3️⃣° ' + tools.get__('INTERMEDIO', lang) +':' + tools.ACAPO; + mystr += '3️⃣° ' + tools.get__('INTERMEDIO', lang) + ':' + tools.ACAPO; for (let indterra = 1; indterra <= 2; indterra++) { miacol = calcval(riga, col, 2) + (indterra); miariga = riga + 1; @@ -813,7 +816,7 @@ NaveSchema.statics.getNavePos = async function (idapp, riga, col, solorecord, in mystr += tools.ACAPO; - mystr += '2️⃣° ' + tools.get__('INTERMEDIO', lang) + ':' + tools.ACAPO; + mystr += '2️⃣° ' + tools.get__('INTERMEDIO', lang) + ':' + tools.ACAPO; for (let indaria = 1; indaria <= 4; indaria++) { miacol = calcval(riga, col, 4) + (indaria); miariga = riga + 2; @@ -983,7 +986,7 @@ NaveSchema.statics.showListaOrd = async function (idapp) { }; NaveSchema.statics.getLastRigaCol = async function (idapp) { - return Nave.findOne({ idapp }).sort({ _id: -1 }); + return Nave.findOne({ idapp }).sort({ riga: -1, col: -1 }); }; async function addRecordNaveByParams(params, siRitesse) { @@ -1014,8 +1017,10 @@ async function addRecordNaveByParams(params, siRitesse) { num_tess: params.num_tess }); if (!!giapresente) { - let fields_to_update = { added: true }; - await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); + if (params.persistenti) { + let fields_to_update = { added: true }; + await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); + } return false; } @@ -1024,6 +1029,7 @@ async function addRecordNaveByParams(params, siRitesse) { let myNave = new Nave({ idapp: params.idapp, + idListaIngresso: params.id, ind_order: params.ind_order, riga: params.riga, col: params.col, @@ -1044,15 +1050,17 @@ async function addRecordNaveByParams(params, siRitesse) { myNave.parent_id = "0"; } - console.log('addRecordNaveByParams (' + myNave.parent_id + ')'); + // console.log('addRecordNaveByParams (' + myNave.parent_id + ')'); return await myNave.save() .then(async (result) => { if (!!result) { - let fields_to_update = { added: true }; - await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); + if (params.persistenti) { + let fields_to_update = { added: true }; + await ListaIngresso.findOneAndUpdate({ _id: params.id.toString() }, { $set: fields_to_update }, { new: false }); + } params.conta++; @@ -1071,7 +1079,7 @@ async function addRecordNaveByParams(params, siRitesse) { params.riga++; params.rigaparent = params.riga - 1; params.col = 1; - params.maxcol = getmaxcol(params.riga); + params.maxcol = tools.getmaxcol(params.riga); } else { params.col++; } @@ -1126,7 +1134,7 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida params.primavolta = (params.riga === 1) && (params.col === 1); params.riga = await Nave.getRiga(idapp); params.col = await Nave.getCol(idapp); - params.maxcol = getmaxcol(params.riga); + params.maxcol = tools.getmaxcol(params.riga); params.colparent = Math.ceil(params.col / 2); params.rigaparent = params.riga - 1; @@ -1139,7 +1147,7 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida const inserito = await addRecordNaveByParams(params, false); if (inserito) { if (idapp === tools.AYNI) { - if (((params.col) % 8) === 0) { + if ((((params.col) % 8) === 0) && (params.col % 64 !== 0)) { let recmediatore = await Nave.findMediatoreByFuoco(idapp, myriga, mycol, 0); if (!!recmediatore) { const ris = await Nave.checkifDeveRitessersi(recmediatore); @@ -1149,13 +1157,16 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida params.ind_order = recmediatore.ind_order; params.id = recmediatore._id; params.num_tess = recmediatore.num_tess + 1; + params.idListaIngresso = -1; await addRecordNaveByParams(params, true); } } } } - if ((params.riga === 4 + 3) && (params.col === (8 * 2) + 3)) { + + /** + if ((params.riga === 4 + 3) && (params.col === (8 * 2) + 3)) { // Si ritesse il Fondo AYNI nella Nave 3.3 const userFondo = await User.findByIndex(idapp, 0); params.ind_order = userFondo.ind_order; @@ -1163,7 +1174,8 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida params.num_tess = userFondo.num_tess; await addRecordNaveByParams(params, true); - } + } **/ + } } @@ -1174,7 +1186,7 @@ NaveSchema.statics.addUserFromListaIngresso_IntoNave = async function (init, ida }; -NaveSchema.statics.generaNave = async function (idapp, mydata) { +NaveSchema.statics.generaNave = async function (idapp, mydata, persistenti) { const Nave = this; const { User } = require('./user'); @@ -1189,6 +1201,10 @@ NaveSchema.statics.generaNave = async function (idapp, mydata) { numpersone: mydata.numpersone, }; + if (!persistenti) { + params.numpersone = 2000; // Mettili tutti + } + //++Todo: date_gift_chat_open e date_start : Ricalcolarle in Automatico... params.primavolta = (params.riga === 1) && (params.col === 1); @@ -1215,8 +1231,9 @@ NaveSchema.statics.generaNave = async function (idapp, mydata) { for (const reclista of arrlistaingresso) { params.ind_order = reclista.ind_order; - params.id = reclista._id; + params.id = reclista.idListaIngresso; params.num_tess = reclista.num_tess; + params.persistenti = persistenti; await Nave.addUserFromListaIngresso_IntoNave(index === 0, idapp, params, false); index++; @@ -1233,9 +1250,12 @@ async function addUserToNave(idapp, rec) { let params = {}; - params.id = rec._id; + params.ind_order = rec.ind_order; + params.id = rec.idListaIngresso; params.num_tess = rec.num_tess; + params.persistenti = false; + //CONTROLLARE SE SERVE ANCORA !!!!!!!!!!!!!!!!!!!!!! return await Nave.addUserFromListaIngresso_IntoNave(true, idapp, params, true); } @@ -1401,6 +1421,12 @@ NaveSchema.statics.getDonatoridelSognatore = async function (idapp, riganave, co }; +NaveSchema.statics.isDefinitiva = async function (idapp, mynave) { + const nave = await NavePersistente.findByRigaColByDonatore(idapp, mynave.riga, mynave.col, 0); + return (!!nave) ? !nave.provvisoria : false; + +}; + NaveSchema.statics.ricalcolaNave = async function (idapp, nave, riga1don, col1don, ricalcola, index) { const Nave = this; @@ -1490,16 +1516,43 @@ NaveSchema.statics.getnumNaviByUsername = async function (idapp, username) { ind_order: 1 }); - if (!!arrrec) - return arrrec.length; - else - return 0; + // SOLO QUELLE PERMANENTI ! + let ind = 0; + for (const mynave of arrrec) { + const trovato = await NavePersistente.findByRigaColByDonatore(idapp, mynave.riga, mynave.col, 0); + if (!!trovato) { + ind++; + } + } + + return ind; } catch (e) { console.error(e.message); } }; +NaveSchema.statics.checkIfMadeGift = async function (idapp, username) { + const Nave = this; + + const { ListaIngresso } = require('./listaingresso'); + + const arrlistaingr = await ListaIngresso.find({ idapp, username }); + for (const ingr of arrlistaingr) { + + let mynave = await Nave.findOne({ idapp, ind_order: ingr.ind_order }); + if (!!mynave) { + if (mynave.made_gift) { + return true; + } + } + } + + return false; + + +}; + NaveSchema.statics.getSognatoreByRigaColMediatore = async function (idapp, navemediatore) { const ris = this.getRigaColSognatoreByMediatore(idapp, navemediatore.riga, navemediatore.col, 3); diff --git a/src/server/models/navepersistente.js b/src/server/models/navepersistente.js index 3b4c334..6fcd055 100755 --- a/src/server/models/navepersistente.js +++ b/src/server/models/navepersistente.js @@ -250,7 +250,7 @@ NavePersistenteSchema.statics.findByRigaCol = function (idapp, riga, col) { NavePersistenteSchema.statics.getLastRigaCol = async function (idapp) { - return NavePersistente.findOne({ idapp }).sort({ _id: -1 }); + return NavePersistente.findOne({ idapp }).sort({ riga: -1, col: -1 }); }; NavePersistenteSchema.statics.getLastRigaColDefinitiva = async function (idapp) { @@ -270,6 +270,19 @@ NavePersistenteSchema.pre('save', async function (next) { next(); }); +function getNextDayNave(miadata) { + + const dayofweek = [1, 3, 5]; // LUNEDI, MERCOLEDI, VENERDI + + let mydate = tools.AddDate(miadata, 1); + + while (!dayofweek.includes(mydate.getDay())) { + mydate = tools.AddDate(mydate, 1); + } + + return mydate + +} NavePersistenteSchema.statics.addRecordNavePersistenteByParams = async function (params) { @@ -281,14 +294,27 @@ NavePersistenteSchema.statics.addRecordNavePersistenteByParams = async function }); if (!giapresente) { + // Prende la nave prima: + const lastnave = await NavePersistente.findOne({idapp}).sort({riga: -1, col: -1}); + + let nextgiftchat = null; + + if (((params.col - 1) % 8 === 0)) { + nextgiftchat = getNextDayNave(lastnave.date_gift_chat_open); + } else { + nextgiftchat = lastnave.date_gift_chat_open; + } + + const next_date_start = tools.AddDate(nextgiftchat, 7); + let myNavePersistente = new NavePersistente({ idapp: params.idapp, riga: params.riga, col: params.col, riga1don: params.riga1don, col1don: params.col1don, - date_start: params.date_start, - date_gift_chat_open: params.date_gift_chat_open, + date_gift_chat_open: nextgiftchat, + date_start: next_date_start, provvisoria: true, }); return await myNavePersistente.save(); diff --git a/src/server/models/settings.js b/src/server/models/settings.js index d2ea399..2c86378 100755 --- a/src/server/models/settings.js +++ b/src/server/models/settings.js @@ -114,6 +114,24 @@ SettingsSchema.statics.setKeyNum = async function (idapp, key, value) { }; +SettingsSchema.statics.setBool = async function (idapp, key, valbool) { + const Settings = this; + + let myrec = await Settings.findOne({ idapp, key }); + if (!myrec) { + myrec = new Settings({ key }); + myrec._id = new ObjectID(); + myrec.idapp = idapp; + myrec.type = tools.FieldType.boolean; + myrec.value_bool = valbool; + + return await myrec.save(); + } else { + myrec = await Settings.findOneAndUpdate({ idapp, key }, { $set: { value_bool: valbool } }, { new: false }); + } + +}; + SettingsSchema.statics.getKeyNum = async function (idapp, key, mydefault) { const Settings = this; diff --git a/src/server/models/user.js b/src/server/models/user.js index 3650d25..8c9450d 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -8,6 +8,7 @@ const tools = require('../tools/general'); const { Settings } = require('../models/settings'); const { ListaIngresso } = require('../models/listaingresso'); +const { Graduatoria } = require('../models/graduatoria'); const { Nave } = require('../models/nave'); const { NavePersistente } = require('../models/navepersistente'); // const { ExtraList } = require('../models/extralist'); @@ -557,6 +558,7 @@ UserSchema.statics.getQueryQualified = function () { } + UserSchema.statics.isUserQualified7 = async function (idapp, username) { const User = this; @@ -921,12 +923,15 @@ UserSchema.statics.SetTelegramWasBlocked = async function (idapp, teleg_id) { 'profile.teleg_id': 0, }; - const ris = await User.findOneAndUpdate({ - idapp, - 'profile.teleg_id': teleg_id - }, { $set: fields_to_update }, { new: false }).then((record) => { - return record; - }); + if (process.env.PROD === 1) { + + const ris = await User.findOneAndUpdate({ + idapp, + 'profile.teleg_id': teleg_id + }, { $set: fields_to_update }, { new: false }).then((record) => { + return record; + }); + } }; @@ -1213,15 +1218,15 @@ UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, us dashboard.arrposizioni = await Nave.getArrPosizioniByUsername(idapp, username); - let arrrec = []; + /* let arrrec = []; if (dashboard.arrimbarchi.length > 0) { arrrec = await ListaIngresso.getProssimiInLista(idapp, true); - } + }*/ for (let myimbarco of dashboard.arrimbarchi) { if (!!myimbarco.invitante_username) dashboard.arrusers[myimbarco.invitante_username] = await User.getUserShortDataByUsername(idapp, myimbarco.invitante_username); - myimbarco._doc.posiz = await ListaIngresso.getPosizioneInLista(idapp, arrrec, myimbarco.ind_order, myimbarco.num_tess); + myimbarco._doc.posiz = await Graduatoria.getPosizioneInGraduatoria(idapp, myimbarco.ind_order, myimbarco.username, myimbarco.num_tess); } dashboard.navi_partenza = await NavePersistente.getListaNavi(idapp); @@ -1681,7 +1686,10 @@ UserSchema.statics.calculateStat = async function (idapp, username) { UserSchema.statics.getDistinctNationalityQuery = function (idapp) { const query = [ { - $match: { idapp } + $match: { + idapp, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + } }, { $group: { _id: "$profile.nationality", count: { $sum: 1 } } diff --git a/src/server/router/api/actions.js b/src/server/router/api/actions.js index 53e45a6..0a40792 100755 --- a/src/server/router/api/actions.js +++ b/src/server/router/api/actions.js @@ -1,14 +1,21 @@ -var mongoose = require('mongoose'); +const mongoose = require('mongoose'); const Subscription = mongoose.model('subscribers'); const { ListaIngresso } = require('../../models/listaingresso'); +const { Graduatoria } = require('../../models/graduatoria'); const { User } = require('../../models/user'); +const { Nave } = require('../../models/nave'); + +const { ObjectID } = require('mongodb'); + +const tools = require('../../tools/general'); const telegrambot = require('../../telegram/telegrambot'); module.exports = { - doOtherThingsAfterDeleted: async function (tablename, rec) { + doOtherThingsAfterDeleted: async function (tablename, rec, notifBot) { try { + let ris = null; if (tablename === 'users') { await ListaIngresso.deleteUserInListaIngresso(rec.idapp, rec.username); @@ -23,17 +30,57 @@ module.exports = { }, { $set: { aportador_solidario: rec.aportador_solidario } }, { new: false }); let msg = 'Spostato ' + user.name + ' ' + user.surname + ' sotto di ' + rec.aportador_solidario; - telegrambot.sendMsgTelegramToTheManagers(idapp, msg); + telegrambot.sendMsgTelegramToTheManagers(rec.idapp, msg); } // Delete also all the subscribers record of this User - return Subscription.deleteOne({ userId: rec._id }) + ris = Subscription.deleteOne({ userId: rec._id }) } + + if (tablename === 'listaingressos') { + // Rimuovi anche nella Tabella Graduatoria + ris = await Graduatoria.deleteOne({ idListaIngresso: ObjectID(rec._id) }); + if (!!ris) { + + let msg = 'Eliminato Imbarco di ' + rec.name + ' ' + rec.surname + ' [Index = ' + rec.index + ']'; + await telegrambot.sendMsgTelegramToTheManagers(rec.idapp, msg); + } + + // Elimina anche la Nave se è temporanea! + const arrnave = await Nave.find({ idapp: rec.idapp, ind_order: rec.ind_order }); + for (const mynave of arrnave) { + if (!!mynave) { + if (!await Nave.isDefinitiva(rec.idapp, mynave)) { + await Nave.findByIdAndUpdate(mynave.id, { $set: { ind_order: -1 } }); + break; + } + } + } + } + + if (!!ris) { + + if (notifBot) { + // Send Notification to the BOT + let nomerecord = ''; + if ((tablename === 'users') || (tablename === 'extralist')) { + nomerecord = rec.name + ' ' + rec.surname + ' (' + rec.username + ')'; + } + + addtext = 'Eliminato il Record "' + nomerecord + '" dalla tabella ' + tablename + '\n' + + 'Eseguito da ' + req.user.name + ' ' + req.user.surname + ' \n'; + await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext); + } + + } + + return ris + } catch (e) { console.error(e.message); return false } - return true; + }, doOtherThingsAfterDuplicated: async function (tablename, myrec, mynewrec) { try { diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index bd9974e..36fb6af 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -13,6 +13,7 @@ const { authenticate, authenticate_noerror } = require('../middleware/authentica const { ObjectID } = require('mongodb'); const { ListaIngresso } = require('../models/listaingresso'); +const { Graduatoria } = require('../models/graduatoria'); const mongoose = require('mongoose'); const cfgserver = mongoose.model('cfgserver'); @@ -223,6 +224,8 @@ function getTableByTableName(tablename) { mytable = NavePersistente; else if (tablename === 'listaingressos') mytable = ListaIngresso; + else if (tablename === 'graduatorias') + mytable = Graduatoria; return mytable } @@ -442,6 +445,8 @@ router.patch('/chval', authenticate, async (req, res) => { res.status(400).send(); return false; } + } else if ('deleted' in fieldsvalue) { + await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${rec.name} ${rec.surname} (${rec.username}) è stato cancellato (nascosto) da ${req.user.name} ${req.user.surname}`); } } @@ -512,6 +517,32 @@ router.patch('/chval', authenticate, async (req, res) => { }); +router.patch('/askfunz', authenticate, async (req, res) => { + // const idapp = req.body.idapp; + const id = req.body.data.id; + const ind_order = req.body.data.ind_order; + const username = req.body.data.username; + const idapp = req.body.idapp; + const mydata = req.body.data; + + let entra = false; + if (!entra) { + // If I change my record... + if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTutor(req.user.perm)) && !(req.user._id.toString() === id)) { + // If without permissions, exit + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + } + } + + if (mydata.myfunc === shared_consts.CallFunz.DAMMI_PRIMO_UTENTE_LIBERO) { + const userfree = await Graduatoria.getFirstUserGradFree(idapp); + + if (!!userfree) + return res.send({ code: server_constants.RIS_CODE_OK, out: userfree }); + } + +}); + router.patch('/callfunz', authenticate, async (req, res) => { // const idapp = req.body.idapp; const id = req.body.data.id; @@ -528,7 +559,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { } if (!entra) { // If I change my record... - if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTutor(req.user.perm)) && !(req.user._id.toString() === id) && !tools.ModificheConsentite(mydata.table, fieldsvalue)) { + if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTutor(req.user.perm)) && !(req.user._id.toString() === id)) { // If without permissions, exit return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); } @@ -555,7 +586,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { if (!!myusernuovo) { if (!mydata.data.AddImbarco && !!mianavedasost && mianavedasost.ind_order > 0) { - // Controlla prima se è in una Nave Temporanea, allora lo elimina dalla Nave Temporanea + // Controlla prima se è in una Nave Temporanea, allora lo elimina dalla PRIMA Nave Temporanea miaarrnavi = await Nave.getArrPosizioniByUsername(idapp, username); if (miaarrnavi) { @@ -566,7 +597,7 @@ router.patch('/callfunz', authenticate, async (req, res) => { ind_order: -1 }; - let ris = await Nave.findByIdAndUpdate(mianave.id, { $set: fieldsvalue }); + let ris = await Nave.findByIdAndUpdate(mianave._id, { $set: fieldsvalue }); if (!!ris) { rimosso++; break; // Rimuovilo solo 1 ! @@ -580,31 +611,45 @@ router.patch('/callfunz', authenticate, async (req, res) => { if (!!mianavedasost && mianavedasost.ind_order >= 0) { // Metti campo 'delete': true su ListaIngresso - olduseringresso = await ListaIngresso.findOne({ idapp, ind_order: mianavedasost.ind_order }); + olduseringresso = await ListaIngresso.findById(mianavedasost.idListaIngresso); if (!!olduseringresso) { let fieldsvalue = { date_deleted: new Date(), deleted: true }; - const risul = await ListaIngresso.findByIdAndUpdate(olduseringresso.id, { $set: fieldsvalue }, { new: false }); + const risul = await ListaIngresso.findByIdAndUpdate(mianavedasost.idListaIngresso, { $set: fieldsvalue }, { new: false }); + if (!!risul) { + const myrecuser = await ListaIngresso.getIngrEUserByFilter(idapp, { + idapp, + username: username_da_sostituire, + _id: ObjectID(mianavedasost.idListaIngresso) + }); + + if (!!myrecuser) { + const risdel = await ListaIngresso.deleteOne({ _id: olduseringresso.id }); + + if (!!risdel) { + await actions.doOtherThingsAfterDeleted('listaingressos', myrecuser, false) + } + } + } } } } if (!!myuservecchio) { // Se ha gia delle altre navi, non cancellarlo! - Nave.checkIfMadeGift(idapp, ) - const noncanc = await Nave.findOne({idapp, ind_order: mianavedasost.ind_order, made_gift: true }); + if (!await Nave.checkIfMadeGift(idapp, myuservecchio.username)) { - - if (mydata.data.deleteUser && !!mianavedasost && mianavedasost.ind_order > 0) { - // Metti Deleted allo User - fieldsvalue = { - deleted: true, - date_deleted: new Date(), - }; - await User.findByIdAndUpdate(myuservecchio.id, { $set: fieldsvalue }); - await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuservecchio.name} ${myuservecchio.surname} (${myuservecchio.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); + if (mydata.data.deleteUser && !!mianavedasost && mianavedasost.ind_order > 0) { + // Metti Deleted allo User + fieldsvalue = { + deleted: true, + date_deleted: new Date(), + }; + await User.findByIdAndUpdate(myuservecchio.id, { $set: fieldsvalue }); + await telegrambot.sendMsgTelegramToTheManagers(idapp, `L\'utente ${myuservecchio.name} ${myuservecchio.surname} (${myuservecchio.username}) è stato cancellato (nascosto) perchè sostituito (da ${req.user.name} ${req.user.surname} )`); + } } } @@ -626,8 +671,17 @@ router.patch('/callfunz', authenticate, async (req, res) => { ind_order = myingr.ind_order; await myingr.save(); + } + // Togliolo dalla Graduatoria! + const mygrad = await Graduatoria.findOneAndUpdate({ + idapp, + idListaIngresso: myingr._id + }, { $set: { ind_order: -1 } }, { new: false }); + + + // Aggiorna la Nave con il Nuovo fieldsvalue = { ind_order @@ -635,7 +689,6 @@ router.patch('/callfunz', authenticate, async (req, res) => { const dachi = req.user.name + ' ' + req.user.surname; - return await Nave.findByIdAndUpdate(mianavedasost.id, { $set: fieldsvalue }) .then(async (rec) => { // tools.mylogshow(' REC TO MODIFY: ', rec); @@ -703,11 +756,26 @@ router.patch('/callfunz', authenticate, async (req, res) => { } else if (mydata.myfunc === shared_consts.CallFunz.CANCELLA_IMBARCO) { - await ListaIngresso.remove({ idapp, username, ind_order }); + const myrec = await ListaIngresso.getIngrEUserByFilter(idapp, { idapp, _id: ObjectID(mydata.data.id) }); - return res.send({ code: server_constants.RIS_CODE_OK }); + if (!!myrec) { + const risdel = await ListaIngresso.deleteOne({ _id: mydata.data.id }); + + if (!!risdel) { + return await actions.doOtherThingsAfterDeleted('listaingressos', myrec, false) + .then((ris) => { + + if (!!ris) + // tools.mylog('DELETED Others things ...'); + return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); + }); + } + } } + + return res.send({ code: server_constants.RIS_CODE_ERR }); + } catch (e) { console.log(e.message); res.status(400).send(); @@ -800,27 +868,10 @@ router.delete('/delrec/:table/:id', authenticate, async (req, res) => { }); } + if (cancellato) { // Do extra things after deleted - return actions.doOtherThingsAfterDeleted(tablename, myrec).then(async (ris) => { - if (ris) { - - if (notifBot) { - // Send Notification to the BOT - let nomerecord = ''; - if ((tablename === 'users') || (tablename === 'extralist')) { - nomerecord = myrec.name + ' ' + myrec.surname + ' (' + myrec.username + ')'; - } - - addtext = 'Eliminato il Record "' + nomerecord + '" dalla tabella ' + tablename + '\n' + - 'Eseguito da ' + req.user.name + ' ' + req.user.surname + ' \n'; - await telegrambot.sendMsgTelegramToTheManagers(idapp, addtext); - } - - tools.mylog('DELETED Others things ...'); - return res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); - } - }); + return actions.doOtherThingsAfterDeleted(tablename, myrec, notifBot); } res.send({ code: server_constants.RIS_CODE_ERR, msg: '' }); @@ -878,10 +929,6 @@ router.post('/duprec/:table/:id', authenticate, (req, res) => { }); -function doOtherThingsAfterDeleted() { - -} - router.get('/loadsite/:userId/:idapp/:sall', authenticate_noerror, (req, res) => { const userId = req.params.userId; const idapp = req.params.idapp; diff --git a/src/server/router/site_router.js b/src/server/router/site_router.js index 865bc23..a6251bc 100755 --- a/src/server/router/site_router.js +++ b/src/server/router/site_router.js @@ -26,7 +26,7 @@ router.post('/load', async (req, res) => { let datastat = { num_reg: await User.getUsersRegistered(idapp), - num_passeggeri: await Nave.getTotInLista(idapp) + await ListaIngresso.getTotInLista(idapp), + num_passeggeri: await Nave.getTotInLista(idapp), num_imbarcati: await ListaIngresso.getTotInLista(idapp), email_non_verif: await User.getEmailNotVerified(idapp), num_teleg_attivo: await User.getUsersTelegramAttivo(idapp), @@ -39,6 +39,8 @@ router.post('/load', async (req, res) => { arr_nations: await User.findAllDistinctNationality(idapp), numreg_untilday: await User.calcnumRegUntilDay(idapp), reg_daily: await User.calcRegDaily(idapp), + imbarcati_daily: await ListaIngresso.ImbarcatiDaily(idapp), + imbarcati_weekly: await ListaIngresso.ImbarcatiWeekly(idapp), reg_weekly: await User.calcRegWeekly(idapp), lastsreg: await User.getLastUsers(idapp), checkuser: await User.checkUser(idapp, username), diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index b22b3a6..7a38db5 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -5,6 +5,7 @@ const { User } = require('../models/user'); const { Nave } = require('../models/nave'); const { NavePersistente } = require('../models/navepersistente'); const { ListaIngresso } = require('../models/listaingresso'); +const { Graduatoria } = require('../models/graduatoria'); // const { ExtraList } = require('../models/extralist'); const { ObjectID } = require('mongodb'); @@ -401,341 +402,375 @@ router.post('/import_extralist', async (req, res) => { res.send(ris); }); -router.post('/dbop', authenticate, async (req, res) => { +async function eseguiDbOp(idapp, mydata, locale) { - const mydata = req.body.mydata; - idapp = req.body.idapp; - locale = req.body.locale; + let ris = await User.DbOp(idapp, mydata); - let ris = await User.DbOp(idapp, mydata); + let mystr = ''; - let mystr = ''; + try { - try { + if (mydata.dbop === 'rigeneraTutto') { - if (mydata.dbop === 'creaNavi') { - const num = await Nave.generaNave(idapp, mydata); - ris = { num }; - } else if (mydata.dbop === 'delNavi') { - await Nave.setRiga(idapp, 1); + mydata.dbop = 'delNaviProvvisorie'; + await eseguiDbOp(idapp, mydata, locale); + + mydata.dbop = 'GeneraGraduatoria'; + await eseguiDbOp(idapp, mydata, locale); + + mydata.dbop = 'creaNavi'; + ris = await eseguiDbOp(idapp, mydata, locale); + + } else if (mydata.dbop === 'creaNavi') { + const num = await Nave.generaNave(idapp, mydata, false); + ris = { num }; + } else if (mydata.dbop === 'CreaNaviPersistenti') { + const num = await Nave.generaNave(idapp, mydata, true); + ris = { num }; + } else if (mydata.dbop === 'delNavi') { + await Nave.setRiga(idapp, 1); + await Nave.setCol(idapp, 1); + const num = await Nave.deleteOne({ idapp }); + ris = { num }; + // } else if (mydata.dbop === 'delNaviNoStarted') { + // await Nave.setRiga(idapp, 1); + // await Nave.setCol(idapp, 1); + // const num = await Nave.remove({ idapp, date_start: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 24 * 3) } }); + // ris = { num }; + } else if (mydata.dbop === 'delNaviProvvisorie') { + + let num = 0; + + const arrnavi = await Nave.find({ idapp }); + + for (const nave of arrnavi) { + let persistente = await NavePersistente.findByRigaColByDonatore(idapp, nave.riga, nave.col, 0); + if (!!persistente) { + if (persistente.provvisoria) { + let ris = await Nave.deleteOne({ _id: nave._id }); + if (!!ris) { + num++; + } + } + } + } + + // Pulisci gli added se era stato cancellato dalla nave + await Nave.pulisciNonPresenzeInNave(idapp); + + const data = await Nave.getLastRigaCol(idapp); + await Nave.setRiga(idapp, data.riga); + await Nave.setCol(idapp, data.col + 1); + + const maxcol = tools.getmaxcol(data.riga); + if (data.col === maxcol) { + await Nave.setRiga(idapp, data.riga + 1); await Nave.setCol(idapp, 1); - const num = await Nave.remove({ idapp }); - ris = { num }; - // } else if (mydata.dbop === 'delNaviNoStarted') { - // await Nave.setRiga(idapp, 1); - // await Nave.setCol(idapp, 1); - // const num = await Nave.remove({ idapp, date_start: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 24 * 3) } }); - // ris = { num }; - } else if (mydata.dbop === 'delNaviProvvisorie') { + } - let num = 0; + ris = { num }; + } else if (mydata.dbop === 'visuListaNave') { + mystr = await Nave.showListaOrd(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'visuStat') { + ris = await User.visuUtentiNonInNavi(idapp); + } else if (mydata.dbop === 'pulisciNonPresenzeInNave') { + mystr = await Nave.pulisciNonPresenzeInNave(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'checkInserimentiUtentiInNave') { + mystr = await Nave.checkIfDevoAggiungereInNave(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'visuListaIngresso') { + mystr = await ListaIngresso.showListaOrd(idapp, false); + ris = { mystr }; + } else if (mydata.dbop === 'visuListaIngressoNuovi') { + mystr = await ListaIngresso.showListaOrd(idapp, true); + ris = { mystr }; + } else if (mydata.dbop === 'GeneraGraduatoria') { + mystr = await ListaIngresso.GeneraGraduatoria(idapp, true); + ris = { mystr }; + } else if (mydata.dbop === 'AggiornaIndiceGraduatoria') { + mystr = await Graduatoria.AggiornaIndiceGraduatoria(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'visuNaviUtentiEliminati') { + ris = await Nave.visuNaviUtentiEliminati(idapp); + } else if (mydata.dbop === 'creaTessituraeConv') { + ris = await ListaIngresso.creaTessituraeConv(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'eliminaListeIngressoNascoste') { + ris = await ListaIngresso.eliminaListeIngressoNascoste(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'RendiVisibileIrecordNascosti') { + ris = await ListaIngresso.RendiVisibileIrecordNascosti(idapp); + ris = { mystr }; + } else if (mydata.dbop === 'convNaviTessinListaIngressoRec') { + let num = 0; - const arrnavi = await Nave.find({ idapp }); + const arrnavitess = await Nave.find({ idapp, num_tess: { $gte: 3 } }); - for (const nave of arrnavi) { - let persistente = await NavePersistente.findByRigaColByDonatore(idapp, nave.riga, nave.col, 0); - if (!!persistente) { - if (persistente.provvisoria) { - let ris = await Nave.remove({ _id: nave._id }); - if (!!ris) { - num++; - } + for (const recnave of arrnavitess) { + if (recnave.num_tess === 3 || recnave.num_tess === 5 || recnave.num_tess === 7) { + const ind_order = recnave.ind_order; + + // Prima controlla se ho già 2 record dello stesso ind_order, allora non lo faccio: + const arringr = await ListaIngresso.find({ idapp, ind_order }); + let dafare = true; + if (arringr.length > 0) { + const arringrtest = await ListaIngresso.find({ idapp, ind_order }).distinct('num_tess'); + if (arringr.length !== arringrtest.length) { + dafare = false; // Ci sono 2 o piu record! pertanto probabilmente l'ho già fatto! } } - } + if (dafare) { + // const user = await User.findByOldOrder(idapp, ind_order); + const user = await User.findByIndOrder(idapp, ind_order); - // Pulisci gli added se era stato cancellato dalla nave - await Nave.pulisciNonPresenzeInNave(idapp); + if (!!user) { + //let note = recnave.num_tess; + // Crea record ListaIngresso + const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, user.username, user.username, user.lang, false, true, recnave.created, '', true); - const data = await Nave.getLastRigaCol(idapp); - await Nave.setRiga(idapp, data.riga); - await Nave.setCol(idapp, data.col + 1); + const fieldsvalue = { + ind_order: newrecingr.ind_order, + num_tess: 1, + }; - ris = { num }; - } else if (mydata.dbop === 'visuListaNave') { - mystr = await Nave.showListaOrd(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'visuStat') { - ris = await User.visuUtentiNonInNavi(idapp); - } else if (mydata.dbop === 'pulisciNonPresenzeInNave') { - mystr = await Nave.pulisciNonPresenzeInNave(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'checkInserimentiUtentiInNave') { - mystr = await Nave.checkIfDevoAggiungereInNave(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'visuListaIngresso') { - mystr = await ListaIngresso.showListaOrd(idapp, false); - ris = { mystr }; - } else if (mydata.dbop === 'visuListaIngressoNuovi') { - mystr = await ListaIngresso.showListaOrd(idapp, true); - ris = { mystr }; - } else if (mydata.dbop === 'visuNaviUtentiEliminati') { - ris = await Nave.visuNaviUtentiEliminati(idapp); - } else if (mydata.dbop === 'creaTessituraeConv') { - ris = await ListaIngresso.creaTessituraeConv(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'eliminaListeIngressoNascoste') { - ris = await ListaIngresso.eliminaListeIngressoNascoste(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'RendiVisibileIrecordNascosti') { - ris = await ListaIngresso.RendiVisibileIrecordNascosti(idapp); - ris = { mystr }; - } else if (mydata.dbop === 'convNaviTessinListaIngressoRec') { - let num = 0; + // Aggiorna la nave con l'Ind_order nuovo e il num_tess a 1 + await Nave.findOneAndUpdate({ _id: recnave._id }, { $set: fieldsvalue }, { new: false }); - const arrnavitess = await Nave.find({ idapp, num_tess: { $gte: 3 } }); - - for (const recnave of arrnavitess) { - if (recnave.num_tess === 3 || recnave.num_tess === 5 || recnave.num_tess === 7) { - const ind_order = recnave.ind_order; - - // Prima controlla se ho già 2 record dello stesso ind_order, allora non lo faccio: - const arringr = await ListaIngresso.find({ idapp, ind_order }); - let dafare = true; - if (arringr.length > 0) { - const arringrtest = await ListaIngresso.find({ idapp, ind_order }).distinct('num_tess'); - if (arringr.length !== arringrtest.length) { - dafare = false; // Ci sono 2 o piu record! pertanto probabilmente l'ho già fatto! - } - } - if (dafare) { - // const user = await User.findByOldOrder(idapp, ind_order); - const user = await User.findByIndOrder(idapp, ind_order); - - if (!!user) { - //let note = recnave.num_tess; - // Crea record ListaIngresso - const newrecingr = await ListaIngresso.addUserInListaIngresso(idapp, user.username, user.username, user.lang, false, true, recnave.created, '', true); - - const fieldsvalue = { - ind_order: newrecingr.ind_order, - num_tess: 1, - }; - - // Aggiorna la nave con l'Ind_order nuovo e il num_tess a 1 - await Nave.findOneAndUpdate({ _id: recnave._id }, { $set: fieldsvalue }, { new: false }); - - num++; - } - } - } - } - - - const arrnavitess2 = await Nave.find({ idapp, num_tess: 2 }); - - for (const recnave of arrnavitess2) { - - - } - - ris = { num }; - - } else if (mydata.dbop === 'initListaIngresso') { - // const aaa = await User.updateMany({ idapp }, { $set: { 'profile.nationality': 'IT' } }); - - const num = await ListaIngresso.updateMany({ idapp }, { $set: { added: false } }); - - ris = { num }; - } else if (mydata.dbop === 'ImpostaATuttiPaypal') { - const listautenti = await User.find({ idapp }); - let num = 0; - for (let rec of listautenti) { - if (!rec._doc.profile.paymenttypes.includes('paypal')) { - rec._doc.profile.paymenttypes = [...rec._doc.profile.paymenttypes, 'paypal']; - const user = await User.findOneAndUpdate({ _id: rec._id }, { $set: { 'profile.paymenttypes': rec._doc.profile.paymenttypes } }); - // await rec.save(); - num++; - } - // const num = await User.f({ idapp }, { $set: { 'profile: false } }); - } - - - ris = { num }; - } else if (mydata.dbop === 'numtessUno') { - const listanavi = await ListaIngresso.find({ idapp }); - let num = 0; - for (let rec of listanavi) { - if (!rec._doc.num_tess) { - rec._doc.num_tess = 1; - const risu = await ListaIngresso.findOneAndUpdate({ _id: rec._id }, { $set: { num_tess: rec._doc.num_tess } }, { new: false }); - // await rec.save(); - if (!!risu) - num++; - } - // const num = await User.f({ idapp }, { $set: { 'profile: false } }); - } - - - ris = { num }; - } else if (mydata.dbop === 'Corregginumtess') { - const listanavi = await Nave.find({ idapp }); - let num = 0; - for (let rec of listanavi) { - const myarrrec = await Nave.find({ idapp, ind_order: rec.ind_order }).sort({ riga: 1, col: 1 }); - let indextess = 1; - for (let ind = 0; ind < myarrrec.length; ind++) { - if (myarrrec[ind].num_tess !== indextess && myarrrec[ind].num_tess === 1) { - myarrrec[ind].num_tess = indextess; - const risu = await Nave.findOneAndUpdate({ _id: myarrrec[ind]._id }, { $set: { num_tess: myarrrec[ind].num_tess } }, { new: false }); num++; } - indextess++; } } - - ris = { num }; - /* - } - - else if (mydata.dbop === 'CreaNaviPersistenti') { - const listanavi = await Nave.find({ idapp }).sort({riga: 1, col: 1}); - - let params = { - idapp - }; - - let num = 0; - for (let rec of listanavi) { - let mypos = { - idapp, - riga: rec.riga, - col: rec.col, - numup: 3 - }; - tools.getRigaColByPosUp(mypos); - let persistente = await NavePersistente.findByRigaCol(idapp, mypos.riga, mypos.col, 0); - if (!persistente) { - - params.date_start = rec.date_start; - params.date_gift_chat_open = rec.date_gift_chat_open; - params.riga = mypos.riga; - params.col = mypos.col; - if (rec.riga > 3) { - params.riga1don = rec.riga; - params.col1don = rec.col; - } else { - params.riga1don = rec.riga; - params.col1don = rec.col; - } - if (params.riga > 0) { - await NavePersistente.addRecordNavePersistenteByParams(params); - num++; - } - } - } - - ris = { num }; */ - } else if (mydata.dbop === 'CorreggiDataGiftChat') { - const listanavi = await NavePersistente.find({ idapp }); - let num = 0; - for (let rec of listanavi) { - const fieldsvalue = { - date_gift_chat_open: tools.AddDate(rec.date_start, -7) - }; - const risu = await NavePersistente.findOneAndUpdate({ _id: rec._id }, { $set: fieldsvalue }, { new: false }); - if (!!risu) { - num++; - } - } - - ris = { num }; - } else if (mydata.dbop === 'creaUtentiTest') { - - let num = 0; - lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1); - let last = 1; - if (lastrec) { - last = lastrec[0].index; - } - if (!last) { - last = 1; - } - - for (let ind = 0; ind < 100; ind++) { - let myuser = new User(); - myuser._id = new ObjectID(); - myuser.index = last + ind + 1; - myuser.idapp = idapp; - myuser.password = "$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG"; - myuser.lang = 'it'; - myuser.email = "miaemail@email.it"; - myuser.name = 'U' + myuser.index; - myuser.surname = 'Ar' + myuser.index; - myuser.verified_email = true; - if (myuser.index < 2) - myuser.perm = "3"; - myuser.username = "Userna_" + myuser.name; - myuser.profile.special_req = true; - myuser.profile.nationality = 'IT'; - await myuser.save(); - num++; - } - - ris = { num }; - } else if (mydata.dbop === 'visuPlacca') { - - mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' + - 'ECCO LE NUOVE NAVI DEFINITIVE CHE APRONO DOMANI LA GIFT CHAT !!! DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) + '\n' + - 'AUGURI ALLA NUOVA SOGNATRICE !!!\n' + - '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨'; - - const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT'); - - for (let ind = 0; ind < 8; ind++) { - mystr += await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col) + ind, false); - mystr += tools.ACAPO; - if (visu_nave_Bot && ind === 3) { - await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); - mystr = ''; - } - } - - if (visu_nave_Bot) - await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); - - ris = { mystr }; - - /*const rec = {}; - const placca = await Nave.getPlaccaPerDonatore(idapp, parseInt(mydata.riga), parseInt(mydata.col), false, rec); - - telegrambot.sendMsgTelegramToTheAdmin(idapp, placca); - - ris = { placca };*/ - } else if (mydata.dbop === 'visuNave') { - mystr = await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col)); - - const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT'); - if (visu_nave_Bot) - telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); - - ris = { mystr }; - } else if (mydata.dbop === 'getnavibyuser') { - - let arrnavi = null; - - const user = await User.getUserShortDataByUsername(idapp, mydata.username); - if (user) { - arrnavi = await Nave.getArrPosizioniByUsername(idapp, user.username); - - for (let mynave of arrnavi) { - mynave._doc.rec = await Nave.getNaveByRigaCol(idapp, mynave.riga, mynave.col); - } - - } - - ris = { data: arrnavi }; } - // console.log('ris', ris); + const arrnavitess2 = await Nave.find({ idapp, num_tess: 2 }); - res.send(ris); - } catch (e) { - console.log(e.message); + for (const recnave of arrnavitess2) { + + + } + + ris = { num }; + + } else if (mydata.dbop === 'initListaIngresso') { + // const aaa = await User.updateMany({ idapp }, { $set: { 'profile.nationality': 'IT' } }); + + const num = await ListaIngresso.updateMany({ idapp }, { $set: { added: false } }); + + ris = { num }; + } else if (mydata.dbop === 'ImpostaATuttiPaypal') { + const listautenti = await User.find({ idapp }); + let num = 0; + for (let rec of listautenti) { + if (!rec._doc.profile.paymenttypes.includes('paypal')) { + rec._doc.profile.paymenttypes = [...rec._doc.profile.paymenttypes, 'paypal']; + const user = await User.findOneAndUpdate({ _id: rec._id }, { $set: { 'profile.paymenttypes': rec._doc.profile.paymenttypes } }); + // await rec.save(); + num++; + } + // const num = await User.f({ idapp }, { $set: { 'profile: false } }); + } + + + ris = { num }; + } else if (mydata.dbop === 'numtessUno') { + const listanavi = await ListaIngresso.find({ idapp }); + let num = 0; + for (let rec of listanavi) { + if (!rec._doc.num_tess) { + rec._doc.num_tess = 1; + const risu = await ListaIngresso.findOneAndUpdate({ _id: rec._id }, { $set: { num_tess: rec._doc.num_tess } }, { new: false }); + // await rec.save(); + if (!!risu) + num++; + } + // const num = await User.f({ idapp }, { $set: { 'profile: false } }); + } + + + ris = { num }; + } else if (mydata.dbop === 'Corregginumtess') { + const listanavi = await Nave.find({ idapp }); + let num = 0; + for (let rec of listanavi) { + const myarrrec = await Nave.find({ idapp, ind_order: rec.ind_order }).sort({ riga: 1, col: 1 }); + let indextess = 1; + for (let ind = 0; ind < myarrrec.length; ind++) { + if (myarrrec[ind].num_tess !== indextess && myarrrec[ind].num_tess === 1) { + myarrrec[ind].num_tess = indextess; + const risu = await Nave.findOneAndUpdate({ _id: myarrrec[ind]._id }, { $set: { num_tess: myarrrec[ind].num_tess } }, { new: false }); + num++; + } + indextess++; + } + } + + ris = { num }; + /* + } + + else if (mydata.dbop === 'CreaNaviPersistenti') { + const listanavi = await Nave.find({ idapp }).sort({riga: 1, col: 1}); + + let params = { + idapp + }; + + let num = 0; + for (let rec of listanavi) { + let mypos = { + idapp, + riga: rec.riga, + col: rec.col, + numup: 3 + }; + tools.getRigaColByPosUp(mypos); + let persistente = await NavePersistente.findByRigaCol(idapp, mypos.riga, mypos.col, 0); + if (!persistente) { + + params.date_start = rec.date_start; + params.date_gift_chat_open = rec.date_gift_chat_open; + params.riga = mypos.riga; + params.col = mypos.col; + if (rec.riga > 3) { + params.riga1don = rec.riga; + params.col1don = rec.col; + } else { + params.riga1don = rec.riga; + params.col1don = rec.col; + } + if (params.riga > 0) { + await NavePersistente.addRecordNavePersistenteByParams(params); + num++; + } + } + } + + ris = { num }; */ + } else if (mydata.dbop === 'CorreggiDataGiftChat') { + const listanavi = await NavePersistente.find({ idapp }); + let num = 0; + for (let rec of listanavi) { + const fieldsvalue = { + date_gift_chat_open: tools.AddDate(rec.date_start, -7) + }; + const risu = await NavePersistente.findOneAndUpdate({ _id: rec._id }, { $set: fieldsvalue }, { new: false }); + if (!!risu) { + num++; + } + } + + ris = { num }; + } else if (mydata.dbop === 'creaUtentiTest') { + + let num = 0; + lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1); + let last = 1; + if (lastrec) { + last = lastrec[0].index; + } + if (!last) { + last = 1; + } + + for (let ind = 0; ind < 100; ind++) { + let myuser = new User(); + myuser._id = new ObjectID(); + myuser.index = last + ind + 1; + myuser.idapp = idapp; + myuser.password = "$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG"; + myuser.lang = 'it'; + myuser.email = "miaemail@email.it"; + myuser.name = 'U' + myuser.index; + myuser.surname = 'Ar' + myuser.index; + myuser.verified_email = true; + if (myuser.index < 2) + myuser.perm = "3"; + myuser.username = "Userna_" + myuser.name; + myuser.profile.special_req = true; + myuser.profile.nationality = 'IT'; + await myuser.save(); + num++; + } + + ris = { num }; + } else if (mydata.dbop === 'visuPlacca') { + + mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' + + 'ECCO LE NUOVE NAVI DEFINITIVE CHE APRONO DOMANI LA GIFT CHAT !!! DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) + '\n' + + 'AUGURI ALLA NUOVA SOGNATRICE !!!\n' + + '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨'; + + const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT'); + + for (let ind = 0; ind < 8; ind++) { + mystr += await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col) + ind, false); + mystr += tools.ACAPO; + if (visu_nave_Bot && ind === 3) { + await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); + mystr = ''; + } + } + + if (visu_nave_Bot) + await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); + + ris = { mystr }; + + /*const rec = {}; + const placca = await Nave.getPlaccaPerDonatore(idapp, parseInt(mydata.riga), parseInt(mydata.col), false, rec); + + telegrambot.sendMsgTelegramToTheAdmin(idapp, placca); + + ris = { placca };*/ + } else if (mydata.dbop === 'visuNave') { + mystr = await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col)); + + const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT'); + if (visu_nave_Bot) + telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true); + + ris = { mystr }; + } else if (mydata.dbop === 'getnavibyuser') { + + let arrnavi = null; + + const user = await User.getUserShortDataByUsername(idapp, mydata.username); + if (user) { + arrnavi = await Nave.getArrPosizioniByUsername(idapp, user.username); + + for (let mynave of arrnavi) { + mynave._doc.rec = await Nave.getNaveByRigaCol(idapp, mynave.riga, mynave.col); + } + + } + + ris = { data: arrnavi }; } + + + // console.log('ris', ris); + + return ris; + + } catch (e) { + console.log(e.message); } -); +} + +router.post('/dbop', authenticate, async (req, res) => { + + const mydata = req.body.mydata; + idapp = req.body.idapp; + locale = req.body.locale; + + const ris = await eseguiDbOp(idapp, mydata, locale); + + res.send(ris); + +}); module.exports = router; diff --git a/src/server/server.js b/src/server/server.js index 68130ca..32c235c 100755 --- a/src/server/server.js +++ b/src/server/server.js @@ -18,6 +18,8 @@ const sendemail = require('./sendemail'); const cron = require('node-cron'); +const { Settings } = require('./models/settings'); + i18n = require("i18n"); if ((process.env.NODE_ENV === 'production') || (process.env.NODE_ENV === 'test')) { @@ -248,11 +250,22 @@ function mycron() { for (const app of MYAPPS) { sendemail.checkifPendingNewsletter(app.idapp); sendemail.checkifSentNewsletter(app.idapp); + + } +} + +async function mycron_30min() { + for (const app of MYAPPS) { + const enablecrontab = await Settings.getValDbSettings(app.idapp, tools.ENABLE_CRONTAB, false); + + if (enablecrontab) { + ListaIngresso.Esegui_CronTab(app.idapp); + } } } function testmsgwebpush() { - var { User } = require('./models/user'); + const { User } = require('./models/user'); // console.log('nomeapp 1: ' , tools.getNomeAppByIdApp(1)); // console.log('nomeapp 2: ' , tools.getNomeAppByIdApp(2)); @@ -280,6 +293,12 @@ cron.schedule('*/2 * * * *', () => { mycron(); }); +// Cron every X minutes +cron.schedule('*/30 * * * *', async () => { + + mycron_30min(); +}); + async function resetProcessingJob() { arrrec = await Newstosent.find({}); diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index 614dc3a..faedaba 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -2116,7 +2116,6 @@ class Telegram { } if (blocked) { User.SetTelegramWasBlocked(this.idapp, id); - // ++Todo: DA FARE ! local_sendMsgTelegramToTheManagers(this.idapp, addtext + text); } return 0; @@ -2153,7 +2152,7 @@ class Telegram { let text2 = text.slice(4096, text.length); await this._inviaMsg(id, text1, form, menu, msg_id, chat_id, ripr_menuPrec); return await this._inviaMsg(id, text2, form, menu, msg_id, chat_id, ripr_menuPrec); - }else { + } else { return await this._inviaMsg(id, text, form, menu, msg_id, chat_id, ripr_menuPrec); } diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 0ddf3b7..87a2fc4 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -448,6 +448,8 @@ module.exports = { INITDB_FIRSTIME: true, ACAPO: '\n', + ENABLE_CRONTAB: 'CRONTAB', + LANGADMIN: 'it', AYNI: '7', @@ -1000,6 +1002,14 @@ module.exports = { }); if (params.filterand.includes(shared_consts.FILTER_USER_TELEGRAM_BLOCKED)) filtriadded.push({ 'profile.teleg_id_old': { $gt: 1 } }); + if (params.filterand.includes(shared_consts.FILTER_ATTIVI)) + filtriadded.push({ + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + }); + if (params.filterand.includes(shared_consts.FILTER_NASCOSTI)) + filtriadded.push({ + deleted: { $exists: true, $eq: true } + }); } @@ -1522,6 +1532,9 @@ module.exports = { if ('made_gift' in fieldsvalue) { return true; } + if ('note' in fieldsvalue) { + return true; + } } if (table === 'navepersistente') { if ('link_chat' in fieldsvalue) { @@ -1533,7 +1546,7 @@ module.exports = { }, NotifyIfDelRecord(table) { - if ((table === 'users') || (table === 'extralist')) { + if ((table === 'users') || (table === 'extralist') || (table === 'listaingressos')) { return true; } @@ -1555,5 +1568,9 @@ module.exports = { return '' }, + getmaxcol(riga) { + return Math.pow(2, riga - 1); + }, + }; diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index 48965d8..16af737 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -18,6 +18,8 @@ module.exports = { FILTER_USER_NO_DREAM: 256, FILTER_EXTRALIST_DELETED: 512, FILTER_USER_TELEGRAM_BLOCKED: 1024, + FILTER_ATTIVI: 2048, + FILTER_NASCOSTI: 4096, Permissions: { Admin: 1, @@ -46,6 +48,7 @@ module.exports = { SOSTITUISCI: 345, AGGIUNGI_NUOVO_IMBARCO: 380, CANCELLA_IMBARCO: 385, + DAMMI_PRIMO_UTENTE_LIBERO: 390, }, fieldsUserToChange() {