diff --git a/.vscode/launch.json b/.vscode/launch.json index 1c69253..f0a94ca 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -2,6 +2,27 @@ "version": "0.2.0", "configurations": [ { + "type": "node", + "request": "launch", + "name": "Launch via Nodemon", + "program": "${workspaceFolder}/node_modules/nodemon/bin/nodemon.js", + "restart": true, + "runtimeExecutable": "node", + "runtimeArgs": [ + "--inspect=9229" // Use "--inspect=0.0.0.0:9229" for remote debugging + ], + "args": ["${workspaceFolder}/src/server/server.js"], // Replace with your entry file + "cwd": "${workspaceFolder}", + "autoAttachChildProcesses": true, + "console": "integratedTerminal", + "internalConsoleOptions": "neverOpen", + "sourceMaps": true, + "env": { + "NODE_ENV":"development", + "TESTING_ON":"1" + }, + }, + { "name": "Server Debug", "request": "launch", "runtimeArgs": [ @@ -12,6 +33,10 @@ "skipFiles": [ "/**" ], + "env": { + "NODE_ENV":"development", + "TESTING_ON":"1" + }, "type": "node" }, { diff --git a/deploy_solo1.sh b/deploy_solo1.sh new file mode 100755 index 0000000..31f2852 --- /dev/null +++ b/deploy_solo1.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +source ./.env.production + +msg="*** SERVER DI PRODUZIONE **** SEI SICURO DI INVIARE IL SINGOLO FILE GENERAL.JS - SUL SERVER DI PRODUZIONE ?? $SERVERDIR_WEBSITE (Y/N) ? " + +if [ "$1" = "" ]; then + read -p "$msg" risposta +else + echo $msg + risposta=$1 +fi + +if [[ $risposta == "Y" || $risposta == "y" ]]; then + echo "Sincronizzazione di 1 FILE in corso..." + rsync -avz -e 'ssh -p 8855' src/server/tools/general.js suryapaolo@servereng:/var/www/$SERVERDIR_WEBSITE/src/server/tools/general.js + echo "Sincronizzazione TERMINATA - SERVER PRODUZIONE!" +fi diff --git a/src/server/db/mongoose.js b/src/server/db/mongoose.js index 650be13..c07b665 100755 --- a/src/server/db/mongoose.js +++ b/src/server/db/mongoose.js @@ -44,6 +44,9 @@ const db = mongoose.connection; // mongoose.connect(process.env.MONGODB_URI + '?authSource=admin', { options }) // console.log(' -> PASSAGGIO PARAMETRI MONGOOSE') +console.log('Node Version ' + process.version); +console.log('Mongoose Version ' + mongoose.version); +console.log('Connessione a ' + process.env.MONGODB_URI + ' in corso...'); mongoose.connect(process.env.MONGODB_URI, options); db.on('error', console.error.bind(console, 'connection error:')); diff --git a/src/server/models/myskill.js b/src/server/models/myskill.js index 340a611..c6feebe 100755 --- a/src/server/models/myskill.js +++ b/src/server/models/myskill.js @@ -94,6 +94,9 @@ const MySkillSchema = new Schema({ }, }); +MySkillSchema.index({ 'idapp': 1 }); + + MySkillSchema.pre('save', async function(next) { if (this.isNew) { if (!this.date_created) diff --git a/src/server/models/permission.js b/src/server/models/permission.js index 202b01e..f975ea8 100755 --- a/src/server/models/permission.js +++ b/src/server/models/permission.js @@ -20,12 +20,12 @@ const PermissionSchema = new Schema({ type: String, default: '' } -},{ _id : false }); +}, { _id: false }); PermissionSchema.pre('save', async function (next) { if (this.isNew) { - const myrec = await Permission.findOne().limit(1).sort({_id:-1}); + const myrec = await Permission.findOne().limit(1).sort({ _id: -1 }); if (!!myrec) { if (myrec._doc._id === 0) this._id = 1; @@ -48,7 +48,7 @@ PermissionSchema.statics.executeQueryTable = function (idapp, params) { PermissionSchema.statics.findAllIdApp = async function () { const Permission = this; - const myfind = { }; + const myfind = {}; return await Permission.find(myfind, (err, arrrec) => { return arrrec diff --git a/src/server/models/reaction.js b/src/server/models/reaction.js new file mode 100755 index 0000000..beb4b54 --- /dev/null +++ b/src/server/models/reaction.js @@ -0,0 +1,210 @@ +const mongoose = require('mongoose').set('debug', false) +const Schema = mongoose.Schema; + +const i18n = require('i18n'); +const tools = require('../tools/general'); + + +const shared_consts = require('../tools/shared_nodejs'); + + +mongoose.Promise = global.Promise; +mongoose.level = "F"; + +const { ObjectID } = require('mongodb'); + +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +const reactionSchema = new Schema({ + idapp: { + type: String, + }, + userId: { + type: String, + }, + username: { + type: String, + }, + idrec: { + type: String, + }, + tab: { + type: Number, + }, + fav: { + type: Boolean, + }, + book: { + type: Boolean, + }, + seen: { + type: Boolean, + }, + attend: { + type: Boolean, + }, +}); + +reactionSchema.statics.getFieldsForSearch = function() { + return [ + {field: 'username', type: tools.FieldType.string}]; +}; + +reactionSchema.statics.executeQueryTable = function(idapp, params) { + params.fieldsearch = this.getFieldsForSearch(); + return tools.executeQueryTable(this, 0, params); +}; + + +// Aggiungo il Favorite +reactionSchema.statics.addFavorite = async function (req, idapp, username, id, tab) { + + let ris = null; + + try { + let ok = false; + + const myrec = await Reaction.findOne({ idrec: id, idapp, username }); + if (!myrec) { + const myrec = new Reaction({ idrec: id, idapp, userId: req.user.id, username, tab, fav: true }); + ris = await myrec.save(); + ok = ris ? 1 : 0; + } else { + ris = await Reaction.updateOne({ idrec: id, idapp, username }, { + $set: { + fav: true, + } + }) + ok = ris.ok; + } + + const { SendNotif } = require('../models/sendnotif'); + + const globalTables = require('../tools/globalTables'); + + // Invia una Notifica al Destinatario + const recObjCreator = await globalTables.getUserCreatorByNumTabAndId(idapp, id, tab); + + if (recObjCreator) { + await SendNotif.createNewNotifToSingleUser(req, null, { usernameDest: recObjCreator.username, recObjCreator, username_action: req.user.username }, false, shared_consts.TypeNotifs.TYPEDIR_FAVORITE, + shared_consts.TypeNotifs.ID_FAVORITE_ADDED); + + } + + return {ris, ok}; + + } catch (e) { + console.error('Err addFavorite', e); + return {ris: null, ok: 0}; + } +}; + +// Aggiungo il Seen +reactionSchema.statics.addSeen = async function (req, idapp, username, id, tab) { + + const myrec = await Reaction.findOne({ idrec: id, idapp, username }); + if (!myrec) { + const myrec = new Reaction({ idrec: id, idapp, userId: req.user.id, username, tab, seen: true }); + return await myrec.save() + .then((ris) => { + // console.log('salvato proj!'); + return {ris, ok: ris ? 1 : 0}; + }) + .catch(err => { + console.log("Error addSeen", err.message); + }); + } else { + return Reaction.updateOne({ _id: myrec._id }, { + $set: { + seen: true, + } + }) + } +}; + +// Aggiungo il Bookmark +reactionSchema.statics.addBookmark = async function (req, idapp, username, id, tab) { + + const myrec = await Reaction.findOne({ idrec: id, idapp, username }); + if (!myrec) { + const myrec = new Reaction({ idrec: id, idapp, userId: req.user.id, username, tab, book: true }); + return await myrec.save() + .then((ris) => { + return {ris, ok: ris ? 1 : 0}; + }) + .catch(err => { + console.log("Error addBookmark", err.message); + }); + } else { + return Reaction.updateOne({ _id: myrec._id }, { + $set: { + book: true, + } + }) + } +}; + +// Aggiungo il Attend +reactionSchema.statics.addAttend = async function (req, idapp, username, id, tab) { + + const myrec = await Reaction.findOne({ idrec: id, idapp, username }); + if (!myrec) { + const myrec = new Reaction({ idrec: id, idapp, userId: req.user.id, username, tab, attend: true }); + return await myrec.save() + .then((ris) => { + return {ris, ok: ris ? 1 : 0}; + }) + .catch(err => { + console.log("Error addAttend", err.message); + }); + } else { + return Reaction.updateOne({ _id: myrec._id }, { + $set: { + attend: true, + } + }) + } +}; + +// Rimuovo il Favorite +reactionSchema.statics.removeFavorite = async function ( + idapp, username, id, tab) { + + const myrec = await Reaction.findOne({ idrec: id, idapp, username }); + if (myrec) { + return Reaction.updateOne({ _id: myrec._id}, { + $set: { + fav: false, + } + }) + } + + return false; + + +}; + +// Rimuovo il Bookmark +reactionSchema.statics.removeBookmark = async function ( + idapp, username, id, tab) { + + const myrec = await Reaction.findOne({ idrec: id, idapp, username }); + if (myrec) { + return Reaction.updateOne({ _id: myrec._id}, { + $set: { + book: false, + } + }) + } + + return false; + + +}; + +const Reaction = mongoose.model('Reaction', reactionSchema); + +module.exports = { Reaction }; diff --git a/src/server/models/user.js b/src/server/models/user.js index 2cebfa3..5485f48 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -14,6 +14,7 @@ const { Graduatoria } = require('../models/graduatoria'); // const { ExtraList } = require('../models/extralist'); +const { Reaction } = require('../models/reaction'); const { MyGroup } = require('../models/mygroup'); const { Circuit } = require('../models/circuit'); @@ -485,6 +486,8 @@ const UserSchema = new mongoose.Schema({ }, }); + + UserSchema.methods.toJSON = function () { const user = this; const userObject = user.toObject(); @@ -1620,10 +1623,6 @@ UserSchema.statics.getUserProfileByUsername = async function ( 'profile.calc': 1, 'profile.handshake': 1, 'profile.friends': 1, - 'profile.favorite': 1, - 'profile.bookmark': 1, - 'profile.attend': 1, - 'profile.seen': 1, email: 1, date_reg: 1, 'useraport.username': 1, @@ -1668,10 +1667,6 @@ UserSchema.statics.getUserProfileByUsername = async function ( 'profile.calc': 1, 'profile.handshake': 1, 'profile.friends': 1, - 'profile.favorite': 1, - 'profile.bookmark': 1, - 'profile.attend': 1, - 'profile.seen': 1, email: 1, date_reg: 1, 'useraport.username': 1, @@ -1717,10 +1712,6 @@ UserSchema.statics.getUserProfileByUsername = async function ( 'profile.calc': 1, 'profile.handshake': 1, 'profile.friends': 1, - 'profile.favorite': 1, - 'profile.bookmark': 1, - 'profile.attend': 1, - 'profile.seen': 1, 'mycities': 1, 'comune': 1, email: 1, @@ -1978,34 +1969,7 @@ UserSchema.statics.removeReqFriend = async function ( { $pull: { 'profile.req_friends': { username: { $in: [usernameDest] } } } }); }; -// Rimuovo il Favorite -UserSchema.statics.removeFavorite = async function ( - idapp, username, id, tab) { - return await User.updateOne({ idapp, username }, - { $pull: { 'profile.favorite': { id: { $in: [id] }, tab } } }); -}; -// Aggiungo il Favorite -UserSchema.statics.addFavorite = async function ( - req, idapp, username, id, tab) { - const ris = await User.updateOne({ idapp, username }, - { $push: { 'profile.favorite': { id, tab } } }); - - const { SendNotif } = require('../models/sendnotif'); - - const globalTables = require('../tools/globalTables'); - - // Invia una Notifica al Destinatario - const recObjCreator = await globalTables.getUserCreatorByNumTabAndId(idapp, id, tab); - - if (recObjCreator) { - await SendNotif.createNewNotifToSingleUser(req, null, { usernameDest: recObjCreator.username, recObjCreator, username_action: req.user.username }, false, shared_consts.TypeNotifs.TYPEDIR_FAVORITE, - shared_consts.TypeNotifs.ID_FAVORITE_ADDED); - - } - - return ris; -}; // Aggiungo il Partecipa UserSchema.statics.addAttend = async function ( @@ -2934,10 +2898,6 @@ function getWhatToShow(idapp, username) { date_reg: 1, 'profile.friends': 1, 'profile.handshake': 1, - 'profile.favorite': 1, - 'profile.bookmark': 1, - 'profile.attend': 1, - 'profile.seen': 1, }; } @@ -4571,11 +4531,18 @@ UserSchema.statics.calcRegWeekly = async function (idapp) { if (tools.INITDB_FIRSTIME) { console.log(' createIndex User Index...'); + + UserSchema.index({ userId: 1 }); + UserSchema.index({ 'idapp': 1 }); + + // UserSchema.index({ username: 'text', name: 'text', surname: 'text', email: 'text' }); // UserSchema.index({ name: 'name' }); // UserSchema.index({ name: 1 }); // UserSchema.index({ surname: 1 }); // ter + + tools.INITDB_FIRSTIME = false; } UserSchema.statics.getUsernameByIndex = async function (idapp, index) { @@ -4860,7 +4827,7 @@ UserSchema.statics.addExtraInfo = async function (idapp, recUser, recUserSave, v versattualeuser = recUser.profile.version; } - versattualeuser = 0; + // versattualeuser = 0; // TOGLIERE! if (versattualeuser < version) { // Aggiornamento versione @@ -4922,6 +4889,8 @@ 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.manage_mygroups = listManageGroups ? listManageGroups : []; @@ -4955,6 +4924,109 @@ UserSchema.statics.addExtraInfo = async function (idapp, recUser, recUserSave, v return recUser; }; +addRecordReaction = async function (arr, fields, fieldtoset) { + let newrecord = {}; + + try { + + if (tools.isArray(arr)) { + for (let myrec of arr) { + if (myrec.id) { + let myfields = { ...{ idrec: myrec.id }, ...fields }; + newrecord = await Reaction.findOne(myfields) + + if (!newrecord) { + newrecord = new Reaction(myfields); + // console.log('Nuovo Record: ', newrecord._doc); + } + + newrecord[fieldtoset] = true; + + await newrecord.save(); + + let newrecfound = await Reaction.findOne(myfields) + } + // if (newrecfound) + // console.log('trovato') + } + } + + } catch (e) { + console.error(e.message); + } + +}; + + +UserSchema.statics.moverecordsFavorite = async function (tab) { + const { MySkill } = require('../models/myskill'); + const { MyGood } = require('../models/mygood'); + + console.log('INIZIO - moverecordsFavorite tab', tab); + + const arrusers = await User.find({ idapp: '13' }).lean(); + + let index = 0; + try { + + + let index = 0; + let totali = 0; + for (let user of arrusers) { + + if (user.profile) { + let arrfav = user.profile.favorite; + let arrseen = user.profile.seen; + let arrbookmark = user.profile.bookmark; + let arrattend = user.profile.attend; + + totali++; + + if (arrfav || arrseen) { + console.log('utente n.', index, 'su', totali, user.username); + index++; + + let fields = { + idapp: user.idapp, + userId: user._id, + username: user.username, + tab + }; + + await addRecordReaction(arrfav, fields, 'fav'); + await addRecordReaction(arrseen, fields, 'seen'); + await addRecordReaction(arrbookmark, fields, 'book:'); + await addRecordReaction(arrattend, fields, 'attend'); + } + + } + + } + + // Rimuovi i record del vecchio schema + const attivacanc = false; + + if (attivacanc) { + const queryfind = { idapp: '13' }; + await User.findOneAndUpdate(queryfind, { + $set: + { + 'profile.favorite': [], + 'profile.bookmark': [], + 'profile.attend': [], + 'profile.seen': [] + }, + }); + + } + } catch (e) { + console.error(e.message); + } + + console.log('fine moverecordsFavorite'); + +}; + UserSchema.statics.updateVersion = async function (userversion, recUser) { const { MySkill } = require('../models/myskill'); @@ -5015,6 +5087,10 @@ UserSchema.statics.updateVersion = async function (userversion, recUser) { await User.findOneAndUpdate({ _id: recUser._id }, { $set: { 'profile.notifs': recUser.profile.notifs } }); } + if (userversion < 1016) { + + } + return recUser; }; diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 5bb1836..29a62d7 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -619,6 +619,7 @@ router.post('/gettable', authenticate, (req, res) => { User.setOnLine(req.user.idapp, req.user.username); } + return mytable.executeQueryTable(idapp, params, req.user).then(ris => { return res.send(ris); @@ -1874,8 +1875,8 @@ function deleteFile(req, res, version) { const relativefile = req.query.filename; const idapp = req.user.idapp; - if (!relativefile) { - return; + if (!relativefile || relativefile.endsWith('/')) { + res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); } try { diff --git a/src/server/router/mygen_router.js b/src/server/router/mygen_router.js index 9b17824..2a1c051 100755 --- a/src/server/router/mygen_router.js +++ b/src/server/router/mygen_router.js @@ -5,6 +5,7 @@ const router = express.Router(); const tools = require('../tools/general'); + var server_constants = require('../tools/server_constants'); var {authenticate, auth_default} = require('../middleware/authenticate'); @@ -15,6 +16,7 @@ const Subscription = mongoose.model('subscribers'); const _ = require('lodash'); const {MyBacheca} = require('../models/mybacheca'); var {User} = require('../models/user'); +const { Reaction } = require('../models/reaction'); const globalTables = require('../tools/globalTables'); @@ -41,10 +43,19 @@ router.post('/page', authenticate, function(req, res, next) { mytable = globalTables.getTableByTableName(table); } + if (mytable) { return mytable.getMyRecById(idapp, id). - then((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; + };*/ if (ris) { res.send(ris); diff --git a/src/server/router/reactions_router.js b/src/server/router/reactions_router.js new file mode 100755 index 0000000..4ca4b21 --- /dev/null +++ b/src/server/router/reactions_router.js @@ -0,0 +1,99 @@ +const express = require('express'); +const router = express.Router(); + +const { Reaction } = require('../models/reaction'); + +const { User } = require('../models/user'); + +const Hours = require('../models/hours'); +const { ObjectID } = require('mongodb'); + +const sendemail = require('../sendemail'); + +const { Settings } = require('../models/settings'); + +const { SendNotif } = require('../models/sendnotif'); + +const tools = require('../tools/general'); +const shared_consts = require('../tools/shared_nodejs'); + +const server_constants = require('../tools/server_constants'); + +const telegrambot = require('../telegram/telegrambot'); + +const _ = require('lodash'); + +const reg = require('../reg/registration'); + +const { authenticate } = require('../middleware/authenticate'); + +const TypedError = require('../modules/ErrorHandler'); + +const mongoose = require('mongoose').set('debug', false); + +router.post('/cmd', authenticate, async (req, res) => { + + const mydata = req.body.mydata; + const idapp = req.body.idapp; + const cmd = req.body.cmd; + const id = req.body.id; + const tab = req.body.tab; + const num = req.body.num; + const value = req.body.value; + + + try { + const username = req.user.username; + + let ris = null; + let record = null; + + if (cmd === shared_consts.CMD_REACTION.SET_FAVORITE) { + if (tab) { + if (value) + ris = await Reaction.addFavorite(req, idapp, username, id, tab); + else + ris = await Reaction.removeFavorite(idapp, username, id, tab); + } + + } else if (cmd === shared_consts.CMD_REACTION.SET_BOOKMARK) { + if (tab) { + if (value) + ris = await Reaction.addBookmark(req, idapp, username, id, tab); + else + ris = await Reaction.removeBookmark(idapp, username, id, tab); + } + } else if (cmd === shared_consts.CMD_REACTION.SET_ATTEND) { + if (tab) { + if (value) + ris = await Reaction.addAttend(req, idapp, username, id, tab, num); + else + ris = await Reaction.removeAttend(idapp, username, id, tab); + } + } else if (cmd === shared_consts.CMD_REACTION.SET_SEEN) { + if (tab) { + if (value) { + ris = await Reaction.addSeen(req, idapp, username, id, tab); + } + const tabtofind = tools.getNumTabByTable('mybachecas'); + if (tab === tabtofind) { + const { MyBacheca } = require('../models/mybacheca'); + record = await MyBacheca.getCompleteRecord(idapp, id); + } + } + } + + let state = (value && ris && ris.ok === 1) ? 1 : ((!value && ris && ris.ok === 1) ? -1 : 0); + + return res.send({ state, record }); + + } catch (e) { + res.status(400).send(); + res.send({ code: server_constants.RIS_CODE_ERR, msg: e, state: null, record: null }); + + console.log(e.message); + } + +}); + +module.exports = router; diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 4173c4d..29bb163 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -1166,6 +1166,14 @@ async function eseguiDbOp(idapp, mydata, locale, req, res) { console.log('e', e); } + } else if (mydata.dbop === 'newRecordsFav') { + // Passa le tabelle da users sulle nuove tabelle: + await User.moverecordsFavorite(1); + await User.moverecordsFavorite(2); + await User.moverecordsFavorite(3); + await User.moverecordsFavorite(4); + await User.moverecordsFavorite(5); + } else if (mydata.dbop === 'emptyTabCatServiziBeni') { const { Sector } = require('../models/sector'); @@ -1384,7 +1392,7 @@ async function ConvertiDaIntAStr(mytable) { myrec._doc.date_created = x._doc.date_created; myrec._doc.date_updated = x._doc.date_updated; - + if (!myrec._doc.date_updated) { if (myrec.hasOwnProperty('date_created')) myrec._doc.date_updated = myrec._doc.date_created; @@ -1424,7 +1432,7 @@ async function RimuoviInteri(mytable) { const arr = await mytable.find({ '_id': { $lte: 10000 } }) console.log(' search interi...', arr.length); - + const ris = await mytable.deleteMany({ '_id': { $lte: 10000 } }) console.log('FINE - RimuoviInteri ', mytable.modelName, ris); @@ -1552,67 +1560,4 @@ router.post('/mgt', authenticate, async (req, res) => { }); -router.post('/cmd', authenticate, async (req, res) => { - - const mydata = req.body.mydata; - const idapp = req.body.idapp; - const cmd = req.body.cmd; - const id = req.body.id; - const tab = req.body.tab; - const num = req.body.num; - const value = req.body.value; - - try { - const username = req.user.username; - - let ris = null; - let record = null; - - if (cmd === shared_consts.CMD_USER.SET_FAVORITE) { - if (tab) { - if (value) - ris = await User.addFavorite(req, idapp, username, id, tab); - else - ris = await User.removeFavorite(idapp, username, id, tab); - } - } else if (cmd === shared_consts.CMD_USER.SET_BOOKMARK) { - if (tab) { - if (value) - ris = await User.addBookmark(idapp, username, id, tab); - else - ris = await User.removeBookmark(idapp, username, id, tab); - } - } else if (cmd === shared_consts.CMD_USER.SET_ATTEND) { - if (tab) { - if (value) - ris = await User.addAttend(req, idapp, username, id, tab, num); - else - ris = await User.removeAttend(idapp, username, id, tab); - } - } else if (cmd === shared_consts.CMD_USER.SET_SEEN) { - if (tab) { - if (value) { - ris = await User.addSeen(idapp, username, id, tab); - } - const tabtofind = tools.getNumTabByTable('mybachecas'); - if (tab === tabtofind) { - const { MyBacheca } = require('../models/mybacheca'); - record = await MyBacheca.getCompleteRecord(idapp, id); - } - } - } - - let state = (value && ris && ris.ok === 1) ? 1 : ((!value && ris && ris.ok === 1) ? -1 : 0); - - return res.send({ state, record }); - - } catch (e) { - res.status(400).send(); - res.send({ code: server_constants.RIS_CODE_ERR, msg: e }); - - console.log(e.message); - } - -}); - module.exports = router; diff --git a/src/server/server.js b/src/server/server.js index 8d25919..8cfa738 100755 --- a/src/server/server.js +++ b/src/server/server.js @@ -112,6 +112,7 @@ myLoad().then(ris => { const projects_router = require('./router/projects_router'); const report_router = require('./router/report_router'); const users_router = require('./router/users_router'); + const reactions_router = require('./router/reactions_router'); const mygroups_router = require('./router/mygroups_router'); const circuits_router = require('./router/circuits_router'); const accounts_router = require('./router/accounts_router'); @@ -177,6 +178,7 @@ myLoad().then(ris => { app.use('/test', test_router); app.use('/projects', projects_router); app.use('/users', users_router); + app.use('/reactions', reactions_router); app.use('/mygroup', mygroups_router); app.use('/circuit', circuits_router); app.use('/account', accounts_router); diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 72eddf9..2176284 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -1818,6 +1818,49 @@ module.exports = { return myquery; }, + getLookupStandardPipeline: function (params, num) { + const query = []; + + if (!params) + return; + + query.push( + { + $lookup: { + from: params.lk_tab, + let: { searchId: { $toObjectId: "$" + params.lk_LF } }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ["$" + params.lk_FF, "$$searchId"] }, + ], + }, + }, + }, + { + $project: params.lk_proj + }, + ], + as: params.lk_as + num, + }, + }, + { + $replaceRoot: { + newRoot: { + $mergeObjects: [ + { + $arrayElemAt: [ + '$' + params.lk_as + num, 0], + }, '$$ROOT'], + }, + }, + } + ) + return query; + }, + getLookup: function (params, num, pass_proj, proj_add) { const query = []; @@ -1963,144 +2006,179 @@ module.exports = { addNumFavoriteAndBookmarkToQuery(idapp, numtab) { let query = {}; + try { query = - [{ - $lookup: { - from: 'users', - let: { - tab: numtab, - id: '$_id', - }, - pipeline: [ - { - $unwind: '$profile.favorite', + [ + { + $lookup: { + from: "reactions", + let: { + tab: numtab, + id: '$_id', }, - { - $match: { - $expr: { - $and: [ - { $eq: ['$profile.favorite.id', '$$id'] }, - { $eq: ['$profile.favorite.tab', '$$tab'] }, - { $eq: ['$idapp', idapp] }, - ], + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$idrec', '$$id'] }, + { $eq: ['$tab', numtab] }, + { $eq: ['$idapp', idapp] }, + ], + }, }, }, - }, - { $project: { username: 1, name: 1, surname: 1, 'profile.resid_province': 1, 'profile.img': 1, 'profile.qualifica': 1 } }, - ], - as: 'myfav', - }, - }, - { - $lookup: { - from: "users", - let: { - tab: numtab, - id: '$_id', - }, - pipeline: [ - { - $unwind: '$profile.bookmark', - }, - { - $match: { - $expr: { - $and: [ - { $eq: ['$profile.bookmark.id', '$$id'] }, - { $eq: ['$profile.bookmark.tab', '$$tab'] }, - { $eq: ['$idapp', idapp] }, - ], + { + $group: { + _id: "$idrec", + numseen: { + $sum: { + $cond: { + if: { $ifNull: ["$seen", false] }, // Check if the field exists and is not null + then: 1, // Increment count by 1 if the field exists + else: 0, // Otherwise, keep the count unchanged + } + } + }, + numfav: { + $sum: { + $cond: { + if: { $ifNull: ["$fav", false] }, // Check if the field exists and is not null + then: 1, // Increment count by 1 if the field exists + else: 0, // Otherwise, keep the count unchanged + } + } + }, + numbook: { + $sum: { + $cond: { + if: { $ifNull: ["$book", false] }, // Check if the field exists and is not null + then: 1, // Increment count by 1 if the field exists + else: 0, // Otherwise, keep the count unchanged + } + } + } }, }, - }, - { - $project: { - username: 1, name: 1, surname: 1, 'profile.resid_province': 1, 'profile.img': 1, - 'profile.qualifica': 1, - } - }, - ], - as: 'mybook', - }, - }, - { - $lookup: { - from: "users", - let: { - tab: numtab, - id: '$_id', + ], + as: 'myreact', }, - pipeline: [ - { - $unwind: '$profile.seen', - }, - { - $match: { - $expr: { - $and: [ - { $eq: ['$profile.seen.id', '$$id'] }, - { $eq: ['$profile.seen.tab', '$$tab'] }, - { $eq: ['$idapp', idapp] }, - ], - }, - }, - }, - { - $project: { - username: 1, name: 1, surname: 1, 'profile.resid_province': 1, 'profile.img': 1, - 'profile.qualifica': 1, - } - }, - ], - as: 'myseen', }, - }, - { - $lookup: { - from: "users", - let: { - tab: numtab, - id: '$_id', - }, - pipeline: [ - { - $unwind: '$profile.attend', - }, - { - $match: { - $expr: { - $and: [ - { $eq: ['$profile.attend.id', '$$id'] }, - { $eq: ['$profile.attend.tab', '$$tab'] }, - { $eq: ['$idapp', idapp] }, - ], - }, - }, - }, - { - $project: { - username: 1, name: 1, surname: 1, 'profile.resid_province': 1, 'profile.img': 1, - 'profile.qualifica': 1, - } - }, - ], - as: 'myattend', - }, - }]; - const numtabbacheca = this.getNumTabByTable(shared_consts.TABLES_MYBACHECAS); - if (numtab === numtabbacheca) { - const queryadd = this.getQueryMyBacheca(idapp); - query = [...query, ...queryadd]; + { + $unwind: '$myreact', + }, + + /*{ + $lookup: { + from: "reactions", + let: { + tab: 2, + id: '$_id', + }, + pipeline: [ + { + $match: { + $expr: { + $and: [ + { $eq: ['$idrec', '$$id'] }, + { $eq: ['$tab', 2] }, + { $eq: ['$idapp', '13'] }, + ], + }, + }, + }, + { + $project: { + myid: '$_id', + _id: 0, + idapp: 1, + userId: 1, + username: 1, + fav: 1, + seen: 1, + }, + }, + ], + as: 'items', + }, + }, + { + $unwind: "$items" + }, + { + $lookup: { + from: "users", + let: { + itemId: { $toObjectId: "$items.userId" }, + items: "$items" + }, + pipeline: [ + { + $match: { + $expr: { + $eq: [ + "$_id", + "$$itemId" + ] + } + } + }, + { + $project: { + username: 1, + name: 1, + surname: 1, + 'profile.img': 1, + } + }, + { + $replaceRoot: { + newRoot: { + $mergeObjects: [ + "$$items", + "$$ROOT" + ] + } + } + } + ], + as: "myreact" + } + }, + { + $group: { + _id: "$_id", + userId: { + $first: "$userId" + }, + descr: { + $first: "$descr" + }, + myreact: { + $push: { + $first: "$myreact" + }, + + }, + firstDoc: { + $first: "$$ROOT" + }, + } + } */ + + ]; + + if (Object.keys(query).length > 0) { + const numtabbacheca = this.getNumTabByTable(shared_consts.TABLES_MYBACHECAS); + if (numtab === numtabbacheca) { + const queryadd = this.getQueryMyBacheca(idapp); + query = [...query, ...queryadd]; + } } proj = { - myfav: 1, - mybook: 1, - myseen: 1, - myattend: 1, - mybookings: 1, }; } catch (e) { console.error(e); @@ -2639,12 +2717,6 @@ module.exports = { let numtab = this.getNumTabByTable(params.table); - if (params.options && this.isBitActive(params.options, - shared_consts.OPTIONS_ADD_COUNT_FAVORITE)) { - objadd = this.addNumFavoriteAndBookmarkToQuery(idapp, numtab); - query = [...query, ...objadd.query]; - } - const q1 = this.getLookup(params.lookup1, 1, proj, objadd.proj); if (q1) query = [...query, ...q1]; @@ -2653,9 +2725,19 @@ module.exports = { query.push({ $unwind: params.unwind1 }); } + if (params.lookupPipeline1) { + const q1p = this.getLookupStandardPipeline(params.lookupPipeline1, 1); + if (q1p) query = [...query, ...q1p]; + } + const q2 = this.getLookup(params.lookup2, 2, proj, objadd.proj); if (q2) query = [...query, ...q2]; + if (params.lookupPipeline2) { + const q2p = this.getLookupStandardPipeline(params.lookupPipeline2, 2); + if (q2p) query = [...query, ...q2p]; + } + const q3 = this.getLookup(params.lookup3, 3, proj, objadd.proj); if (q3) query = [...query, ...q3]; @@ -2816,6 +2898,13 @@ module.exports = { // } } + if (params.options && this.isBitActive(params.options, + shared_consts.OPTIONS_ADD_COUNT_FAVORITE)) { + objadd = this.addNumFavoriteAndBookmarkToQuery(idapp, numtab); + if (Object.keys(objadd.query).length > 0) + query = [...query, ...objadd.query]; + } + } else { // VECCHIA VERSIONE const q1 = this.getLookup(params, 1); @@ -2849,17 +2938,35 @@ module.exports = { }, ); - // console.log('query', query); + if (this.testing()) { + console.log('query', query); + } return query; }, + startTimeLog(name) { + if (this.testing()) { + console.log('inizio', name); + console.time(name); + } + }, + + endTimeLog(name) { + if (this.testing()) { + console.log(' ... fine', name); + console.timeEnd(name); + } + }, + async executeQueryTable(mythistable, idapp, params, user) { let query = await this.getQueryTable(idapp, params, user); try { // console.log('query', query); + this.startTimeLog('Query 1'); + const [ris] = await mythistable.aggregate(query); if (ris) { @@ -2874,6 +2981,8 @@ module.exports = { } } + this.endTimeLog('Query 1'); + // console.table(ris.rows); // console.log('ROW ', ris.count); return ({ count: ris.count, rows: ris.rows }); diff --git a/src/server/tools/globalTables.js b/src/server/tools/globalTables.js index d19925b..0d72a37 100755 --- a/src/server/tools/globalTables.js +++ b/src/server/tools/globalTables.js @@ -16,6 +16,7 @@ const { Booking } = require('../models/booking'); const { Operator } = require('../models/operator'); const { Where } = require('../models/where'); const { MyEvent } = require('../models/myevent'); +const { Reaction } = require('../models/reaction'); const { Contribtype } = require('../models/contribtype'); const { PaymentType } = require('../models/paymenttype'); const { Discipline } = require('../models/discipline'); @@ -79,6 +80,10 @@ const shared_consts = require('./shared_nodejs'); module.exports = { + isTableReaction(tablename) { + return shared_consts.TABLES_REACTIONS.includes(tablename); + }, + getTableByTableName(tablename) { let mytable = ''; @@ -210,6 +215,8 @@ module.exports = { mytable = Account; else if (tablename === 'movements') mytable = Movement; + else if (tablename === 'reactions') + mytable = Reaction; else if (shared_consts.TablePickup.includes(tablename)) mytable = Pickup; //else if (shared_consts.TableCities.includes(tablename)) @@ -562,30 +569,76 @@ module.exports = { getNumFavoriteByIdObj: async function (idapp, numtab, id) { - const { User } = require('../models/user'); + const { Reaction } = require('../models/reaction'); let query = [ { $match: { idapp, - "profile.favorite": { - $elemMatch: - { id, tab: numtab } - } + idrec: id, }, }, { $group: { _id: null, - count: { $sum: 1 }, + count: { + $sum: { + $cond: { + if: { $ifNull: ["$fav", false] }, // Check if the field exists and is not null + then: 1, // Increment count by 1 if the field exists + else: 0, // Otherwise, keep the count unchanged + } + } + }, } }, { $project: { _id: 0 } } ]; try { - const [result] = await User.aggregate(query); + const [result] = await Reaction.aggregate(query); + + return result ? result.count : 0; + } catch (err) { + return 0; + } + + return 0; + + }, + + getNumBookByIdObj: async function (idapp, numtab, id) { + + const { Reaction } = require('../models/reaction'); + + let query = [ + { + $match: { + idapp, + idrec: id, + }, + }, + { + $group: + { + _id: null, + count: { + $sum: { + $cond: { + if: { $ifNull: ["$book", false] }, // Check if the field exists and is not null + then: 1, // Increment count by 1 if the field exists + else: 0, // Otherwise, keep the count unchanged + } + } + }, + } + }, + { $project: { _id: 0 } } + ]; + + try { + const [result] = await Reaction.aggregate(query); return result ? result.count : 0; } catch (err) { @@ -598,16 +651,13 @@ module.exports = { getNumAttendByIdObj: async function (idapp, numtab, id) { - const { User } = require('../models/user'); + const { Reaction } = require('../models/reaction'); let query = [ { $match: { idapp, - "profile.attend": { - $elemMatch: - { id, tab: numtab } - } + idrec: id, }, }, { @@ -615,7 +665,15 @@ module.exports = { { _id: null, count: { - $sum: + $sum: { + $cond: { + if: { $ifNull: ["$attent", false] }, // Check if the field exists and is not null + then: 1, // Increment count by 1 if the field exists + else: 0, // Otherwise, keep the count unchanged + } + }, + + /*$sum: { $reduce: { input: "$profile.attend", @@ -624,7 +682,7 @@ module.exports = { $add: ["$$value", "$$this.num"] } } - } + }*/ }, } }, @@ -632,7 +690,7 @@ module.exports = { ]; try { - const [result] = await User.aggregate(query); + const [result] = await Reaction.aggregate(query); return result ? result.count : 0; } catch (err) { @@ -654,13 +712,14 @@ module.exports = { let numattend = await this.getNumAttendByIdObj(idapp, numtab, id); let numfav = await this.getNumFavoriteByIdObj(idapp, numtab, id); + let numbook = await this.getNumBookByIdObj(idapp, numtab, id); let exist = false; if (table === shared_consts.TABLES_MYBACHECAS) exist = numattend > 1; else exist = numfav > 1; if (recuser) - return { userId: rec.userId, username: recuser.username, descr: rec.descr, id: rec._id, table, exist, numfav, numattend }; + return { userId: rec.userId, username: recuser.username, descr: rec.descr, id: rec._id, table, exist, numfav, numattend, numbook }; } } } catch (e) { diff --git a/src/server/tools/shared_nodejs.js b/src/server/tools/shared_nodejs.js index 77460ea..7eff035 100755 --- a/src/server/tools/shared_nodejs.js +++ b/src/server/tools/shared_nodejs.js @@ -149,7 +149,7 @@ module.exports = { { id: 4, table: 'mygoods' }, { id: 5, table: 'myevents' }], - CMD_USER: { + CMD_REACTION: { SET_FAVORITE: 1, SET_BOOKMARK: 2, SET_SEEN: 3, @@ -157,6 +157,7 @@ module.exports = { }, TABLES_ENABLE_GETREC_BYID: ['mybachecas', 'myhosps', 'myskills', 'mygoods'], + TABLES_REACTIONS: ['mybachecas', 'myhosps', 'myskills', 'mygoods'], TABLES_USER_INCLUDE_MY: ['mygroups', 'circuits'], TABLES_GETCOMPLETEREC: ['myskills', 'mybachecas', 'myhosps', 'mygoods'],