From 04c8e929eecdf34db97253a5a40ee599e93fb0d9 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Sun, 1 Oct 2023 01:24:47 +0200 Subject: [PATCH] =?UTF-8?q?-=20Migliorata=20la=20Notifica=20degli=20Eventi?= =?UTF-8?q?=20su=20Telegram=20-=20Gli=20annunci=20(beni/servizi/ospitalit?= =?UTF-8?q?=C3=A0)=20ora=20possono=20essere=20visti=20anche=20tramite=20un?= =?UTF-8?q?=20link,=20anche=20per=20chi=20non=20=C3=A8=20dentro=20alla=20A?= =?UTF-8?q?pp.=20-=20Aggiunto=20bottone=20"Aggiorna"=20per=20aggiornare=20?= =?UTF-8?q?il=20Saldo=20attuale.=20-=20I=20"Conti=20Collettivi"=20ora=20ve?= =?UTF-8?q?ngono=20chiamati=20Gruppi=20(o=20Conto=20di=20Gruppo).?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- filelog.txt | 4 + logevents.txt | 2 + logtrans.txt | 6 +- src/server/locales/it.json | 13 ++- src/server/models/account.js | 44 +++++--- src/server/models/circuit.js | 14 +-- src/server/models/movement.js | 1 + src/server/models/sendnotif.js | 56 ++++++---- src/server/models/user.js | 62 ++++++----- src/server/router/circuits_router.js | 5 +- src/server/router/index_router.js | 1 + src/server/router/mygen_router.js | 61 ++++++----- src/server/router/reactions_router.js | 11 +- src/server/router/sendnotif_router.js | 2 +- src/server/router/users_router.js | 24 +++++ src/server/telegram/telegrambot.js | 4 +- src/server/tools/general.js | 142 +++++++++++++++++++++++++- src/server/tools/globalTables.js | 5 +- src/server/tools/shared_nodejs.js | 3 + 19 files changed, 348 insertions(+), 112 deletions(-) diff --git a/filelog.txt b/filelog.txt index 6c65eb4..551bfdc 100644 --- a/filelog.txt +++ b/filelog.txt @@ -43,3 +43,7 @@ Dom 18/06 ORE 19:59: USER [paoloar77]: /start inv Dom 18/06 ORE 19:59: USER [paoloar77]: /start inv Ven 23/06 ORE 14:08: USER [paoloar77]: link da condividere + +Sab 30/09 ORE 00:21: USER [SuryaArena]: vai al sito + +Sab 30/09 ORE 00:32: USER [SuryaArena]: vai al sito diff --git a/logevents.txt b/logevents.txt index c0066a4..20faefd 100644 --- a/logevents.txt +++ b/logevents.txt @@ -18,4 +18,6 @@ Dom 18/06 ORE 19:22: 🤖: Da Sùrya (Paolo) undefined (paoloar77): Ven 23/06 ORE 14:13: 🤖: Da Sùrya (Paolo) undefined (paoloar77): ✅ SuryaArena è stato Abilitato correttamente (da paoloar77)! Dom 25/06 ORE 16:11: 🤖: Da Sùrya (Paolo) undefined (paoloar77): +✅ SuryaArena è stato Abilitato correttamente (da paoloar77)! +Ven 29/09 ORE 23:18: 🤖: Da Sùrya (Paolo) undefined (paoloar77): ✅ SuryaArena è stato Abilitato correttamente (da paoloar77)! \ No newline at end of file diff --git a/logtrans.txt b/logtrans.txt index 430e02f..5f201bf 100644 --- a/logtrans.txt +++ b/logtrans.txt @@ -20,4 +20,8 @@ paogruppo2: 300 RIS] Lun 26/06 ORE 23:27: [Circuito RIS Ragusa]: Inviate Monete da paoloar77 a paogruppo2 20 RIS [causale: ] Saldi: paoloar77: -20 RIS] -paogruppo2: 320 RIS] \ No newline at end of file +paogruppo2: 320 RIS] +Sab 30/09 ORE 13:32: [Circuito RIS Bologna]: Inviate Monete da SuryaArena a paoloar77 1 RIS [causale: aaa] +Saldi: +SuryaArena: -1 RIS] +paoloar77: 11 RIS] \ No newline at end of file diff --git a/src/server/locales/it.json b/src/server/locales/it.json index a7d7cdb..ed7fc41 100644 --- a/src/server/locales/it.json +++ b/src/server/locales/it.json @@ -6,7 +6,12 @@ "NEW_GOOD": "❇️ %s ha aggiunto un nuovo Bene: \n%s", "NEW_SERVICE": "❇️ %s ha aggiunto un nuovo Servizio: \n%s", "NEW_HOSP": "❇️ %s ha aggiunto una nuova Ospitalità: \n%s", - "NEW_EVENT": "❇️ %s ha aggiunto un nuovo Evento: \n%s", + "NEW_EVENT": "❇️ %s ha aggiunto un nuovo Evento: \n%s\n%s\n%s", + "NEW_EVENT_TELEGRAM": "%s\n\n❇️ %s\n\n%s\n\n%s", + "ADDED_FROM": "\n\n(Evento aggiunto da %s)", + "CONTRIB": "\n💠 Contributo richiesto: %s", + "ORGANIZED_BY": "\nOrganizzato da %s", + "SHOW_POST": "👉🏻 vedi post su RISO", "OPEN PAGE": "APRI la APP RISO oppure visita riso.app", "%s asked you for Friendship": "%s ti ha chiesto l'Amicizia", "%s accepted your Friendship": "%s ha accettato l'Amicizia", @@ -68,7 +73,7 @@ "CIRCUIT_REMOVED_TO_ME": "❌ Sei stato rimosso dal '%s' (da parte di %s)", "CIRCUIT_SENDCOINSREQ": "%s ti sta inviando %s %s sul '%s'.", "COMUNITARIO": "Comunitario", - "COLLETTIVO": "Collettivo", + "COLLETTIVO": "Gruppo", "CIRCUIT_SENDCOINSREQ_GROUP": "%s sta inviando %s %s al Conto %s '%s' sul '%s'.", "CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_USER": "il conto %s '%s' (%s) sta inviando %s %s a %s sul '%s'.", "CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_YOU": "il conto %s '%s' (%s) ti sta inviando %s %s sul '%s'", @@ -98,5 +103,7 @@ "EVENT_SEND_MSG": "%s ha mandato un messaggio sull'evento %s: \n%s", "SET_ATTEND": "%s ha detto che Parteciperà all'evento: %s", "SET_ATTEND_OTHERS": "%s e altre %s persone hanno detto che Parteciperanno all'evento: %s", - "CLICCA_QUI": "CLICCA QUI" + "DATEDAYONLY": "%s dalle %s alle %s", + "DATE_2DAYS": "%s dalle %s fino a %s alle %s", + "CLICCA_QUI": "CLICCA QUI" } \ No newline at end of file diff --git a/src/server/models/account.js b/src/server/models/account.js index e785976..56d548b 100755 --- a/src/server/models/account.js +++ b/src/server/models/account.js @@ -141,7 +141,7 @@ AccountSchema.statics.calcTotCircolante = async function (idapp, circuitId) { { $group: { _id: null, count: { $sum: '$saldo' } } } ]; - ris = await Account.aggregate(aggr1); + const ris = await Account.aggregate(aggr1); return ris ? ris[0].count : 0; @@ -340,6 +340,7 @@ AccountSchema.statics.createAccount = async function (idapp, username, circuitNa }; AccountSchema.statics.getUserAccounts = async function (idapp, username) { + const { SendNotif } = require('../models/sendnotif'); try { let aggr1 = [ @@ -391,17 +392,25 @@ AccountSchema.statics.getUserAccounts = async function (idapp, username) { }, ]; - ris = await this.aggregate(aggr1); + const ris = await this.aggregate(aggr1); - const { SendNotif } = require('../models/sendnotif'); + // console.log('1 - INIZIA getUserAccounts ') + // console.log(aggr1); if (ris) { for (const account of ris) { try { - const pendingtransactions = await SendNotif.getSumPendingTransactions(idapp, username, account.circuit.name); - const saldopending = pendingtransactions.reduce((sum, rec) => sum + rec.extrarec.qty, 0); - account.saldo -= saldopending; - account.totTransato = account.totTransato || 0; + //++OTTIMIZZARE QUESTA PARTE ! (CON UNA QUERY...) + // console.log(' 1B - PENDIND... ') + + let pendingtransactions = await SendNotif.getSumPendingTransactions(idapp, username, account.circuit.name); + let saldopending = pendingtransactions.reduce((sum, rec) => sum + rec.extrarec.qty, 0); + if (saldopending !== 0) { + account.saldo -= saldopending; + account.totTransato = account.totTransato || 0; + } + + } catch (e) { console.error('getUserAccounts 1) ', e); } @@ -409,6 +418,7 @@ AccountSchema.statics.getUserAccounts = async function (idapp, username) { } } + // console.log(' 2 - FINE getUserAccounts LEN=', ris.length) return ris; } catch (e) { console.error('getUserAccounts', e); @@ -470,16 +480,20 @@ AccountSchema.statics.getGroupAccounts = async function (idapp, groupname) { }, ]; - ris = await this.aggregate(aggr1); + const ris = await this.aggregate(aggr1); const { SendNotif } = require('../models/sendnotif'); if (ris) { + // tools.startTimeLog('Query Pending') for (const account of ris) { const pendingtransactions = await SendNotif.getSumPendingTransactions(idapp, '', account.circuit.name, groupname); const saldopending = pendingtransactions.reduce((sum, rec) => sum + rec.result.extrarec.qty, 0); - account.saldo -= saldopending; + if (saldopending) { + account.saldo -= saldopending; + } } + // tools.endTimeLog('Query Pending') } return ris; @@ -493,7 +507,7 @@ AccountSchema.statics.getGroupAccounts = async function (idapp, groupname) { AccountSchema.statics.SetMinMaxCollettivi = async function (idapp, valmin, valmax) { const Account = this; - ris = await Account.updateMany({ idapp, groupname: { "$nin": [null, ""] } }, + const ris = await Account.updateMany({ idapp, groupname: { "$nin": [null, ""] } }, { $set: { @@ -508,7 +522,7 @@ AccountSchema.statics.SetMinMaxCollettivi = async function (idapp, valmin, valma AccountSchema.statics.SetMinMaxComunitari = async function (idapp, valmin, valmax) { const Account = this; - ris = await Account.updateMany({ idapp, contocom: { "$nin": [null, ""] } }, + const ris = await Account.updateMany({ idapp, contocom: { "$nin": [null, ""] } }, { $set: { @@ -524,7 +538,7 @@ AccountSchema.statics.SetMinMaxPersonali = async function (idapp, valmin, valmax const Account = this; if (circuitId) { - ris = await Account.updateMany({ idapp, circuitId, fidoConcesso: { $gt: 0 }, username: { "$nin": [null, ""] } }, + const ris = await Account.updateMany({ idapp, circuitId, fidoConcesso: { $gt: 0 }, username: { "$nin": [null, ""] } }, { $set: { @@ -533,7 +547,7 @@ AccountSchema.statics.SetMinMaxPersonali = async function (idapp, valmin, valmax } }); } else { - ris = await Account.updateMany({ idapp, fidoConcesso: { $gt: 0 }, username: { "$nin": [null, ""] } }, + const ris = await Account.updateMany({ idapp, fidoConcesso: { $gt: 0 }, username: { "$nin": [null, ""] } }, { $set: { @@ -556,12 +570,12 @@ AccountSchema.statics.updateFido = async function (idapp, username, circuitId, f }; AccountSchema.statics.canEditAccountAdmins = async function (username, id) { - const account = await Account.findOne({_id: id}).lean(); + const account = await Account.findOne({ _id: id }).lean(); const { Circuit } = require('../models/circuit'); if (account) { - const circuit = await Circuit.findOne({_id: account.circuitId}).lean(); + const circuit = await Circuit.findOne({ _id: account.circuitId }).lean(); if (circuit) { return circuit.admins.findIndex((admin) => admin.username === username) >= 0; } diff --git a/src/server/models/circuit.js b/src/server/models/circuit.js index 0ea5dbc..db6d59d 100755 --- a/src/server/models/circuit.js +++ b/src/server/models/circuit.js @@ -642,7 +642,7 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig }, }, }; - ris = await User.updateOne({ idapp, username: extrarec.dest }, update); + const ris = await User.updateOne({ idapp, username: extrarec.dest }, update); } } @@ -865,7 +865,7 @@ CircuitSchema.statics.setstrProvByIdCityCircuits = async function (idapp) { CircuitSchema.statics.AbilitaTuttiCircuiti = async function (idapp) { - ris = await Circuit.updateMany({ idapp }, + const ris = await Circuit.updateMany({ idapp }, { $set: { @@ -878,7 +878,7 @@ CircuitSchema.statics.AbilitaTuttiCircuiti = async function (idapp) { CircuitSchema.statics.AzzeraRegolamentiTuttiCircuiti = async function (idapp) { - ris = await Circuit.updateMany({ idapp }, + const ris = await Circuit.updateMany({ idapp }, { $set: { @@ -893,7 +893,7 @@ CircuitSchema.statics.AzzeraRegolamentiTuttiCircuiti = async function (idapp) { CircuitSchema.statics.SetDefMinMaxPersonali = async function (idapp, valmin, valmax, circuitId) { if (circuitId) { - ris = await Circuit.updateOne({ _id: circuitId }, + const ris = await Circuit.updateOne({ _id: circuitId }, { $set: { @@ -903,7 +903,7 @@ CircuitSchema.statics.SetDefMinMaxPersonali = async function (idapp, valmin, val }); } else { - ris = await Circuit.updateMany({ idapp }, + const ris = await Circuit.updateMany({ idapp }, { $set: { @@ -1065,7 +1065,7 @@ CircuitSchema.statics.getListCircuitsByUsername = async function (idapp, usernam CircuitSchema.statics.SetDefMinMaxCollettivi = async function (idapp, valmin, valmax, circuitId) { if (circuitId) { - ris = await Circuit.updateOne({ _id: circuitId }, + const ris = await Circuit.updateOne({ _id: circuitId }, { $set: { @@ -1074,7 +1074,7 @@ CircuitSchema.statics.SetDefMinMaxCollettivi = async function (idapp, valmin, va } }); } else { - ris = await Circuit.updateMany({ idapp }, + const ris = await Circuit.updateMany({ idapp }, { $set: { diff --git a/src/server/models/movement.js b/src/server/models/movement.js index 7d752be..35140d8 100755 --- a/src/server/models/movement.js +++ b/src/server/models/movement.js @@ -208,6 +208,7 @@ MovementSchema.statics.getQueryMovsByCircuitId = async function (idapp, username preserveNullAndEmptyArrays: true, }, }, + { $lookup: { from: 'circuits', diff --git a/src/server/models/sendnotif.js b/src/server/models/sendnotif.js index d52a096..0b14852 100755 --- a/src/server/models/sendnotif.js +++ b/src/server/models/sendnotif.js @@ -99,6 +99,9 @@ const sendNotifSchema = new Schema({ textaddTelegram: { type: String, }, + textcontent_Telegram: { + type: String, + }, linkaddTelegram: { type: String, } @@ -145,7 +148,7 @@ sendNotifSchema.statics.getRecNotif = function (id) { }; -sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function (username, lastdataread, idapp) { +sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function (username, lastdataread, idapp, limitrecord) { const SendNotif = this; if (!lastdataread) @@ -157,7 +160,7 @@ sendNotifSchema.statics.findAllNotifByUsernameIdAndIdApp = function (username, l { 'dest': username }, { 'datenotif': { $gt: new Date(lastdataread) } }, ], - }).lean().sort({ datenotif: -1 }).then(async (arrnotif) => { + }).lean().limit(limitrecord).sort({ datenotif: -1 }).then(async (arrnotif) => { // console.log('arrnotif', arrnotif.length); return this.compileOtherFields(arrnotif); @@ -172,6 +175,7 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us const numchars = 80; let newdescr = ''; + let newdescrtelegram = ''; let mydescr = ''; let myidrec = ''; let sender = recnotif.sender ? recnotif.sender : ''; @@ -205,7 +209,9 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us recnotif.openUrl = shared_consts.getDirectoryByTable(shared_consts.TABLES_MYBACHECAS, true) + myidrec; tag = 'newevent'; if (recnotif.typeid === shared_consts.TypeNotifs.ID_EVENTS_NEW_REC) { - newdescr = i18n.__('NEW_EVENT', userorig, mydescr); + let eventobj = await tools.getEventForTelegram(recnotif.myrectableorig, mydescr, userorig); + newdescr = eventobj.newdescr; + newdescrtelegram = eventobj.newdescrtelegram; } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_EVENTS_SEND_MSG) { newdescr = i18n.__('EVENT_SEND_MSG', userorig, recnotif.title, recnotif.msg); } else if (recnotif.typeid === shared_consts.TypeNotifs.ID_EVENTS_ATTEND) { @@ -217,11 +223,12 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us else newdescr = i18n.__('SET_ATTEND', recnotif.paramsObj.username_action, recnotif.paramsObj.recObjCreator.descr); + recnotif.openUrl = shared_consts.getDirectoryByTable(recnotif.paramsObj.recObjCreator.table, true) + recnotif.paramsObj.recObjCreator.id; tag = 'attend'; - recnotif.openUrl = shared_consts.getDirectoryByTable(recnotif.paramsObj.recObjCreator.table, true) + recnotif.paramsObj.recObjCreator.id; - recnotif.linkaddTelegram = 'Vedi post'; } + recnotif.textcontent_Telegram = newdescrtelegram; + recnotif.linkaddTelegram = i18n.__('SHOW_POST'); } else if (recnotif.typedir === shared_consts.TypeNotifs.TYPEDIR_FRIENDS) { recnotif.openUrl = '/my/' + sender; @@ -539,7 +546,7 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us tag = 'favorite'; recnotif.openUrl = shared_consts.getDirectoryByTable(recnotif.paramsObj.recObjCreator.table, true) + recnotif.paramsObj.recObjCreator.id; - recnotif.linkaddTelegram = 'Vedi post'; + recnotif.linkaddTelegram = i18n.__('SHOW_POST'); } recnotif.tag = recnotif.tag ? recnotif.tag : tag; @@ -898,9 +905,11 @@ sendNotifSchema.statics.createNewNotification = async function (req, res, params myrecnotif.idrec = rec._id; } + myrecnotif.typedir = typedir; myrecnotif.typeid = typeid; + await SendNotif.sendToTheDestinations(myrecnotif, req, res); return true; @@ -972,24 +981,27 @@ sendNotifSchema.statics.sendToTheDestinations = async function (myrecnotifpass, if (shared_consts.TABLES_ADV_NOTIFICATION.includes(myrecnotifpass.tablerec) || shared_consts.TABLES_EVENTS_NOTIFICATION.includes(myrecnotifpass.tablerec)) { - const myrectableorig = await mytable.findOne({ _id: myrecnotifpass.idrec }).lean(); - if (myrectableorig) { - for (const city of myrectableorig.idCity) { - const prov = await City.getProvinceByIdCity(city); - arrprovinces.push(await City.getProvinceByIdCity(city)); - arrregions.push(await City.getRegionByIdCity(city)); - arrcircuits.push(await City.getCircuitNameBystrProv(prov)); + if (myrecnotifpass.idrec && myrecnotifpass.idrec !== '0') { + // const myrectableorig = await mytable.findOne({ _id: myrecnotifpass.idrec }).lean(); + const myrectableorig = await mytable.getCompleteRecord(myrecnotifpass.idapp, myrecnotifpass.idrec); + if (myrectableorig) { + for (const city of myrectableorig.idCity) { + const prov = await City.getProvinceByIdCity(city); + arrprovinces.push(await City.getProvinceByIdCity(city)); + arrregions.push(await City.getRegionByIdCity(city)); + arrcircuits.push(await City.getCircuitNameBystrProv(prov)); + } + + + if (myrecnotifpass.tablerec === shared_consts.TABLES_MYGOODS) { + idSector = myrectableorig.idSectorGood; + } else { + idSector = myrectableorig.idSector; + } + } - - - if (myrecnotifpass.tablerec === shared_consts.TABLES_MYGOODS) { - idSector = myrectableorig.idSectorGood; - } else { - idSector = myrectableorig.idSector; - } - + myrecnotifpass.myrectableorig = myrectableorig; } - myrecnotifpass.myrectableorig = myrectableorig; } } diff --git a/src/server/models/user.js b/src/server/models/user.js index 5485f48..1868183 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -2834,7 +2834,7 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn } outres.recnotif = await SendNotif.getRecNotif(extrarec.notifId); - outres.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp); + outres.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER); } else { outres.cansend = false; @@ -3105,27 +3105,34 @@ UserSchema.statics.UserByIdTelegram = async function (idapp, teleg_id) { const User = this; return await User.findOne({ - idapp, 'profile.teleg_id': teleg_id, + idapp, + 'profile.teleg_id': teleg_id, $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }).lean().then((rec) => { + }).lean().then(async (rec) => { + if (!rec) { + // Cerca se esiste in quello salvato in precedenza: + const recold = await User.findOne({ + idapp, + 'profile.teleg_id_old': teleg_id + }).lean(); + if (recold && recold.profile.teleg_id_old === teleg_id) { + // Riaggiorna l'ID perché è ritornato sulla chat! + await User.SetTelegramIdSuccess(idapp, recold._id, recold.profile.teleg_id_old); + + rec = await User.findOne({ + idapp, + 'profile.teleg_id': teleg_id, + $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], + }).lean(); + } + + } return (!!rec) ? rec : null; }).catch((e) => { console.error('UserExistByIdTelegram', e); }); }; -UserSchema.statics.UsersByIdTelegram = async function (idapp, teleg_id) { - const User = this; - - return await User.find({ - idapp, 'profile.teleg_id': teleg_id, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], - }).lean().then((rec) => { - return (!!rec) ? rec : null; - }).catch((e) => { - console.error('UserExistByIdTelegram', e); - }); -}; UserSchema.statics.setPicProfile = async function (idapp, username, imgpic) { const User = this; @@ -3291,7 +3298,9 @@ UserSchema.statics.SetTelegramWasBlocked = async function (idapp, teleg_id) { 'profile.teleg_id': 0, }; - if (tools.sulServer()) { + + // if (tools.sulServer()) { + if (true) { const ris = await User.findOneAndUpdate({ idapp, @@ -4889,7 +4898,7 @@ UserSchema.statics.addExtraInfo = async function (idapp, recUser, recUserSave, v { deleted: { $exists: true, $eq: false } }], }).lean(); - recUser.profile.reaction = await Reaction.find({idapp, username: recUser.username}).lean(); + recUser.profile.reaction = await Reaction.find({ idapp, username: recUser.username }).lean(); recUser.profile.manage_mygroups = listManageGroups ? listManageGroups @@ -5003,9 +5012,18 @@ UserSchema.statics.moverecordsFavorite = async function (tab) { } + } catch (e) { + console.error(e.message); + } + + console.log('fine moverecordsFavorite'); + +}; + +UserSchema.statics.removerecordsFavorite = async function () { // Rimuovi i record del vecchio schema - const attivacanc = false; - + const attivacanc = true; + if (attivacanc) { const queryfind = { idapp: '13' }; await User.findOneAndUpdate(queryfind, { @@ -5019,12 +5037,6 @@ UserSchema.statics.moverecordsFavorite = async function (tab) { }); } - } catch (e) { - console.error(e.message); - } - - console.log('fine moverecordsFavorite'); - }; UserSchema.statics.updateVersion = async function (userversion, recUser) { diff --git a/src/server/router/circuits_router.js b/src/server/router/circuits_router.js index 8966b9e..109c4bd 100755 --- a/src/server/router/circuits_router.js +++ b/src/server/router/circuits_router.js @@ -5,6 +5,8 @@ const tools = require('../tools/general'); const server_constants = require('../tools/server_constants'); +const shared_consts = require('../tools/shared_nodejs'); + const { authenticate } = require('../middleware/authenticate'); const mongoose = require('mongoose').set('debug', false); @@ -82,7 +84,8 @@ router.post('/load', authenticate, async (req, res) => { data.account = await Account.getAccountByUsernameAndCircuitId(idapp, '', data._id, false, false, '', data.path); } - const arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(req.user.username, lastdr, idapp); + const arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(req.user.username, lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER); + /// E' QUIIII !!!! const useraccounts = await Account.getUserAccounts(idapp, req.user.username); await User.setLastCircuitOpened(idapp, req.user.username, path); diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 29a62d7..3f98910 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -428,6 +428,7 @@ router.post('/settable', authenticate, async (req, res) => { return await myPromise .then(async (doupdate) => { + if (doupdate) return mytable.updateOne({ _id: mytablerec._id }, mydata, { new: true }) else diff --git a/src/server/router/mygen_router.js b/src/server/router/mygen_router.js index 2a1c051..596a0bd 100755 --- a/src/server/router/mygen_router.js +++ b/src/server/router/mygen_router.js @@ -8,35 +8,39 @@ const tools = require('../tools/general'); var server_constants = require('../tools/server_constants'); -var {authenticate, auth_default} = require('../middleware/authenticate'); +var { authenticate, authenticate_noerror, auth_default } = require('../middleware/authenticate'); var mongoose = require('mongoose').set('debug', false); const Subscription = mongoose.model('subscribers'); const _ = require('lodash'); -const {MyBacheca} = require('../models/mybacheca'); -var {User} = require('../models/user'); +const { MyBacheca } = require('../models/mybacheca'); +var { User } = require('../models/user'); const { Reaction } = require('../models/reaction'); const globalTables = require('../tools/globalTables'); -const {ObjectID} = require('mongodb'); +const { ObjectID } = require('mongodb'); //GET orders -router.post('/page', authenticate, function(req, res, next) { +router.post('/page', authenticate_noerror, function (req, res, next) { - const {SendNotif} = require('../models/sendnotif'); + const { SendNotif } = require('../models/sendnotif'); try { let table = req.body.table; let id = req.body.id; let idapp = req.body.idapp; - const username = req.user.username ? req.user.username : ''; + let username = '' + if (req.user) + username = req.user.username ? req.user.username : ''; - // Check if ìs a Notif to read - const idnotif = req.body.idnotif ? req.body.idnotif : ''; - SendNotif.setNotifAsRead(idapp, username, idnotif); + if (username) { + // Check if ìs a Notif to read + const idnotif = req.body.idnotif ? req.body.idnotif : ''; + SendNotif.setNotifAsRead(idapp, username, idnotif); + } let mytable = null; if (shared_consts.TABLES_ENABLE_GETREC_BYID.includes(table)) { @@ -47,29 +51,30 @@ router.post('/page', authenticate, function(req, res, next) { if (mytable) { return mytable.getMyRecById(idapp, id). - then(async (ris) => { + then(async (ris) => { - // Se è un record singolo di tipo Reaction, - // allora gli devo passare anche le liste degli utenti : - /*if (globalTables.isTableReaction(table)) { - // ... - const myreaction = await Reaction.find({idapp, idrec: id}).lean(); - ris.myreaction = myreaction; - };*/ + // Se è un record singolo di tipo Reaction, + // allora gli devo passare anche le liste degli utenti : + if (globalTables.isTableReaction(table)) { + // ... + // const myreaction = await Reaction.find({idapp, idrec: id}).lean(); + // ris.myreaction = myreaction; - if (ris) { - res.send(ris); + }; - } else { - res.status(400).send(); - } - }).catch((e) => { - console.error('Err', e); - res.status(400).send(e); - }) + if (ris) { + res.send(ris); + + } else { + res.status(400).send(); + } + }).catch((e) => { + console.error('Err', e); + res.status(400).send(e); + }) } - }catch (e) { + } catch (e) { console.error('/page', e); } diff --git a/src/server/router/reactions_router.js b/src/server/router/reactions_router.js index 4ca4b21..2ee2cd7 100755 --- a/src/server/router/reactions_router.js +++ b/src/server/router/reactions_router.js @@ -25,13 +25,13 @@ const _ = require('lodash'); const reg = require('../reg/registration'); -const { authenticate } = require('../middleware/authenticate'); +const { authenticate, authenticate_noerror } = require('../middleware/authenticate'); const TypedError = require('../modules/ErrorHandler'); const mongoose = require('mongoose').set('debug', false); -router.post('/cmd', authenticate, async (req, res) => { +router.post('/cmd', authenticate_noerror, async (req, res) => { const mydata = req.body.mydata; const idapp = req.body.idapp; @@ -43,7 +43,12 @@ router.post('/cmd', authenticate, async (req, res) => { try { - const username = req.user.username; + let username = ''; + if (req.user) { + username = req.user.username; + } else { + return res.send({ state: 0, record: null }); + } let ris = null; let record = null; diff --git a/src/server/router/sendnotif_router.js b/src/server/router/sendnotif_router.js index bc08fe7..42fd05d 100755 --- a/src/server/router/sendnotif_router.js +++ b/src/server/router/sendnotif_router.js @@ -144,7 +144,7 @@ router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => { return res.status(404).send({code: server_constants.RIS_CODE_NOT_MY_USERNAME}); } - return SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdataread, idapp).then(async (arrnotif) => { + return SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdataread, idapp, shared_consts.LIMIT_NOTIF_FOR_USER).then(async (arrnotif) => { // const wait = new Promise((resolve, reject) => { // setTimeout(() => { diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 29bb163..b92c1ee 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -705,6 +705,26 @@ router.post('/circuits', authenticate, (req, res) => { }); +router.post('/updatesaldo', authenticate, async (req, res) => { + const username = req.user.username; + idapp = req.body.idapp; + locale = req.body.locale; + + try { + const userprofile = await User.getExtraInfoByUsername(idapp, username); + let ris = { + userprofile + } + + return res.send({ris}); + + } catch (e) { + tools.mylog('ERRORE IN updatesaldo: ' + e); + res.status(400).send(); + }; + +}); + router.post('/friends/cmd', authenticate, async (req, res) => { const usernameLogged = req.user.username; const idapp = req.body.idapp; @@ -1166,6 +1186,10 @@ async function eseguiDbOp(idapp, mydata, locale, req, res) { console.log('e', e); } + } else if (mydata.dbop === 'removeRecordsFav') { + // Passa le tabelle da users sulle nuove tabelle: + await User.removerecordsFavorite(); + } else if (mydata.dbop === 'newRecordsFav') { // Passa le tabelle da users sulle nuove tabelle: await User.moverecordsFavorite(1); diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index c63e13b..2c5c25f 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -3090,6 +3090,7 @@ class Telegram { const rec = this.getRecInMem(msg); let testo = msg.text.toLowerCase().trim(); + status = this.getstatus(rec); if (testo === Menu.EXIT_TELEGRAM) { await this.menuExitToTelegram(msg); @@ -3263,7 +3264,7 @@ class Telegram { const id = this.getchatid(msg); let rec = null; try { - const user = await User.UserByIdTelegram(this.idapp, id); + let user = await User.UserByIdTelegram(this.idapp, id); let rec = this.getRecInMem(msg); if (user && !rec) { rec = this.addUser(msg); @@ -3584,6 +3585,7 @@ class Telegram { // text = text.replace(/<\/div>/g, ''); text = text.replace(/ /g, ' '); + if (!form) { form = { 'parse_mode': 'HTML', diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 2176284..d5ab950 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -1520,6 +1520,40 @@ module.exports = { return msg; }, + htmlToTelegramText(html) { + + try { + const withMarkdown = html + .replace(/(.*?)<\/strong>/g, '*$1*') + .replace(/(.*?)<\/b>/g, '*$1*') + .replace(/(.*?)<\/em>/g, '_$1_') + .replace(/(.*?)<\/u>/g, '__$1__'); + + // Remove other HTML tags + const plainText = withMarkdown.replace(/<[^>]*>/g, ''); + + // Replace HTML entities with their equivalent Markdown or plain text representations + const replacements = [ + { pattern: /&/g, replacement: '&' }, + { pattern: /</g, replacement: '<' }, + { pattern: />/g, replacement: '>' }, + { pattern: /"/g, replacement: '"' }, + { pattern: /'/g, replacement: "'" }, + ]; + + let telegramText = plainText; + replacements.forEach((replacement) => { + telegramText = telegramText.replace(replacement.pattern, replacement.replacement); + }); + + return telegramText; + + } catch (e) { + console.error(e); + }; + + }, + convertTexttoHtml(myhtml) { // let msg = myhtml; // msg = msg.replace('\n', '
'); @@ -2067,9 +2101,11 @@ module.exports = { }, { - $unwind: '$myreact', + $unwind: { + path: "$myreact", + preserveNullAndEmptyArrays: true, + }, }, - /*{ $lookup: { from: "reactions", @@ -2170,6 +2206,11 @@ module.exports = { ]; + if (true) { + // RIMUOVI + // query = {}; + } + if (Object.keys(query).length > 0) { const numtabbacheca = this.getNumTabByTable(shared_consts.TABLES_MYBACHECAS); if (numtab === numtabbacheca) { @@ -2939,7 +2980,7 @@ module.exports = { ); if (this.testing()) { - console.log('query', query); + // console.log('query', query); } return query; @@ -3300,6 +3341,19 @@ module.exports = { } }, + getstrTime(mytimestamp) { + // Create a Date object with your desired date + const date = new Date(mytimestamp); // You can replace this with your specific date + + // Get the hour and minute components from the date + const hours = date.getHours(); + const minutes = date.getMinutes(); + + // Format the hour and minute components as HH:MM + const formattedTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`; + return formattedTime + }, + getstrDateShort(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) @@ -4204,6 +4258,88 @@ module.exports = { getAhref(username, link) { return `${username}`; }, + + firstchars(value, numchars) { + if (!value) { + return '' + } + try { + let mycar = value.substring(0, numchars) + if (value.length > numchars) + mycar += '...' + return mycar + } catch (e) { + return value + } + }, + + replaceStringAtEnd(inputString, searchString, replacement) { + // Create a regular expression that matches the searchString at the end of the inputString + const regex = new RegExp(searchString + '$'); + + // Use the replace method with the regular expression to replace the string + const result = inputString.replace(regex, replacement); + + return result; + }, + + getstrDateTimeEvent(myevent) { + let mystr = ''; + + // is same day? + if (this.getstrDateShort(myevent.dateTimeStart) === this.getstrDateShort(myevent.dateTimeEnd)) { + mystr = i18n.__('DATEDAYONLY', this.getstrDateLong(myevent.dateTimeStart), this.getstrTime(myevent.dateTimeStart), + this.getstrTime(myevent.dateTimeEnd)) + } else { + mystr = i18n.__('DATE_2DAYS', this.getstrDateLong(myevent.dateTimeStart), this.getstrTime(myevent.dateTimeStart), + this.getstrDateLong(myevent.dateTimeEnd), this.getstrTime(myevent.dateTimeEnd)) + } + + return '🗓 ' + mystr; + }, + + getDoveStrByEvent(myrec) { + let dove = '🏠 '; + if (myrec.mycities && myrec.mycities.length > 0) { + dove += myrec.mycities[0].comune + ' (' + myrec.mycities[0].prov + ')' + } + return dove; + }, + + async getDescrEstesaStrByEvent(myrec) { + let mystr = ''; + + mystr = await this.firstchars(this.replaceStringAtEnd(myrec.note, '', ''), 400); + if (mystr) + mystr = 'ℹ️ ' + mystr + return mystr; + }, + + + async getEventForTelegram(myrec, mydescr, userorig) { + try { + let datastr = this.getstrDateTimeEvent(myrec); + let dovestr = this.getDoveStrByEvent(myrec); + let descrestesa = await this.getDescrEstesaStrByEvent(myrec); + let organizedby = myrec.organisedBy; + let contributo = myrec.contribstr; + + let newdescr = i18n.__('NEW_EVENT', userorig, datastr, mydescr, dovestr); + let newdescrtelegram = i18n.__('NEW_EVENT_TELEGRAM', datastr, mydescr, dovestr, descrestesa, userorig); + if (organizedby) { + newdescrtelegram += i18n.__('ORGANIZED_BY', organizedby); + } + if (contributo) { + newdescrtelegram += i18n.__('CONTRIB', contributo); + } + newdescrtelegram += i18n.__('ADDED_FROM', userorig); + + return { newdescr, newdescrtelegram } + } catch (e) { + console.error('Error', e); + } + + }, }; diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index 0d72a37..043b332 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -259,9 +259,10 @@ module.exports = { actions: recnotif.actions ? recnotif.actions : [], id: recnotif._id, textaddTelegram: recnotif.textaddTelegram ? recnotif.textaddTelegram : '', + textcontent_Telegram: recnotif.textcontent_Telegram ? recnotif.textcontent_Telegram : '', linkaddTelegram: recnotif.linkaddTelegram ? recnotif.linkaddTelegram : '', }; - + if (tools.isBitActive(recnotif.typesend, shared_consts.MessageOptions.Notify_ByPushNotification) && this.checkifSendPushNotification) { params.typesend = params.typesend + shared_consts.TypeSend.PUSH_NOTIFICATION; invia = true; @@ -386,7 +387,7 @@ module.exports = { for (const user of arrusers) { const mytitle = await tools.convertSpecialTags(user, params.title); - const mycontent = await tools.convertSpecialTags(user, params.content); + const mycontent = await tools.convertSpecialTags(user, params.textcontent_Telegram ? params.textcontent_Telegram : params.content); let usernotifprofile = null; if (user.profile.notifs) diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index 7eff035..9f0a98b 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -3,6 +3,7 @@ module.exports = { CHECK_READ_GUIDELINES: 1, CHECK_SEE_VIDEO_PRINCIPI: 2, }, + LIMIT_NOTIF_FOR_USER: 200, QUERYTYPE_MYGROUP: 1, QUERYTYPE_REFUSED_USER_GRP: 2, @@ -732,7 +733,9 @@ module.exports = { groupname: 1, lasttimeonline: 1, comune: 1, + myreact: 1, mycities: 1, + lang: 1, 'profile.img': 1, 'profile.mygroups': 1, 'profile.mycircuits': 1,