diff --git a/docs/email.md b/docs/email.md new file mode 100644 index 0000000..59f9ae4 --- /dev/null +++ b/docs/email.md @@ -0,0 +1,9 @@ +
+ +# TO UNLOCK GMAIL ACCOUNT: + +- [Less Secure Apps](https://myaccount.google.com/lesssecureapps) ✔ +- [Display Unlock Captcha](https://accounts.google.com/b/0/displayunlockcaptcha) ✔ + + +
diff --git a/emails/admin/registration/it/text.pug b/emails/admin/registration/it/text.pug new file mode 100644 index 0000000..5e30a7b --- /dev/null +++ b/emails/admin/registration/it/text.pug @@ -0,0 +1,7 @@ +p #{name} #{surname} si è appena Registrato su #{nomeapp} +p Con i seguenti dati di accesso: +span Username:  + strong #{username}
+span Email:  + strong #{emailto}
+p
Saluti diff --git a/emails/registration/it/textold.pug b/emails/registration/it/textold.pug new file mode 100644 index 0000000..7c751a2 --- /dev/null +++ b/emails/registration/it/textold.pug @@ -0,0 +1,13 @@ +Benvenuto #{name} nel portale di #{nomeapp}! +I tuoi dati di accesso da ricordare sono: + Username: #{username} + + hai dimenticato la Password? + Trovala qui: #{forgetpwd} + + Email #{emailto} + +Per confermare la registrazione clicca su questo link: +#{strlinkreg} + +Potrai cosi' accedere al sito digitando i tuoi dati di accesso. diff --git a/server/config/config.js b/server/config/config.js index 1d709e6..1103205 100644 --- a/server/config/config.js +++ b/server/config/config.js @@ -61,6 +61,7 @@ if (process.env.NODE_ENV === 'production') { idapp: '1', name: 'FreePlanet', adminemail: 'paolo.arena77@gmail.com', + manageremail: '', replyTo: 'paolo.arena77@gmail.com', host: 'https://test.freeplanet.app', portapp: '0', @@ -69,6 +70,7 @@ if (process.env.NODE_ENV === 'production') { idapp: '2', name: 'Associazione Shen', adminemail: 'pao.loarena77@gmail.com', + manageremail: '', replyTo: 'info@associazioneshen.it', host: 'http://test.associazioneshen.it', portapp: '0', @@ -77,6 +79,7 @@ if (process.env.NODE_ENV === 'production') { idapp: '3', name: 'Brigitte MG Dumont', adminemail: '', + manageremail: '', host: 'http://test.brigittemgdumont.com', portapp: '0', }, @@ -84,6 +87,7 @@ if (process.env.NODE_ENV === 'production') { idapp: '4', name: 'Mandala per l\'Anima', adminemail: '', + manageremail: '', host: 'http://test.mandalaperlanima.eu', portapp: '0', } @@ -94,6 +98,7 @@ if (process.env.NODE_ENV === 'production') { idapp: '1', name: 'FreePlanet', adminemail: 'paolo.arena77@gmail.com', + manageremail: '', replyTo: 'paolo.arena77@gmail.com', host: 'http://localhost', portapp: '8080', @@ -102,6 +107,7 @@ if (process.env.NODE_ENV === 'production') { idapp: '2', name: 'Associazione Shen', adminemail: 'paolo.arena77@gmail.com', + manageremail: '', replyTo: 'info@associazioneshen.it', host: 'http://localhost', portapp: '8081', @@ -110,6 +116,7 @@ if (process.env.NODE_ENV === 'production') { idapp: '3', name: 'Brigitte', adminemail: 'paolo.arena77@gmail.com', + manageremail: '', host: 'http://localhost', portapp: '8082', }, @@ -117,6 +124,7 @@ if (process.env.NODE_ENV === 'production') { idapp: '4', name: 'Mandala per l\'Anima', adminemail: 'paolo.arena77@gmail.com', + manageremail: '', host: 'http://localhost', portapp: '8083', } diff --git a/server/models/booking.js b/server/models/booking.js index 6c07428..7f62f83 100644 --- a/server/models/booking.js +++ b/server/models/booking.js @@ -4,6 +4,8 @@ const Schema = mongoose.Schema; mongoose.Promise = global.Promise; mongoose.level = "F"; +const tools = require('../tools/general'); + const { ObjectID } = require('mongodb'); // Resolving error Unknown modifier: $pushAll @@ -13,7 +15,7 @@ mongoose.plugin(schema => { const bookingSchema = new Schema({ idapp: { - type: Number, + type: String, }, userId: { type: String, @@ -104,34 +106,6 @@ bookingSchema.statics.findAllDistinctByBooking = function (idapp) { }; -function getQueryBookingUser(filterMatchBefore = {}, userId) { - - let filterMatchAfter = { - $or: getQueryFilterTodo(userId) - }; - - let myobjField = getobjFieldTodo(true); - - const query = [ - { $match: filterMatchBefore }, - { - $lookup: { - from: "users", - localField: "userId", // field in my collection - foreignField: "_id", // field in the 'from' collection - as: "fromItems" - } - }, - { - $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$fromItems", 0] }, "$$ROOT"] } } - }, - { $match: filterMatchAfter }, - { $project: myobjField }]; - - return query; -} - - -var Booking = mongoose.model('Booking', bookingSchema); +const Booking = mongoose.model('Booking', bookingSchema); module.exports = { Booking }; diff --git a/server/models/myevent.js b/server/models/myevent.js new file mode 100644 index 0000000..90c768d --- /dev/null +++ b/server/models/myevent.js @@ -0,0 +1,173 @@ +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +mongoose.Promise = global.Promise; +mongoose.level = "F"; + +const tools = require('../tools/general'); + +const { ObjectID } = require('mongodb'); + +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +const MyEventSchema = new Schema({ + idapp: { + type: String, + }, + typol: { + type: String, + }, + short_tit: { + type: String, + }, + title: { + type: String, + }, + details: { + type: String, + }, + time: { + type: String, + }, + dur: { + type: Number, + }, + dur2: { + type: Number, + }, + days: { + type: Number, + }, + date: { + type: Date, + }, + bgcolor: { + type: String, + }, + icon: { + type: String, + }, + img_small: { + type: String, + }, + img: { + type: String, + }, + where: { + type: String, + }, + contribtype: { // TABLE + type: Number, + }, + price: { + type: Number, + }, + infoafterprice: { + type: String, + }, + teacher: { // TABLE ?! + type: String, + }, + teacher2: { + type: String, + }, + infoextra: { + type: String, + }, + linkpage: { + type: String, + }, + linkpdf: { + type: String, + }, + nobookable: { + type: Boolean, + }, + news: { + type: Boolean, + }, + canceled: { + type: Boolean, + }, + deleted: { + type: Boolean, + }, + dupId: { + type: mongoose.Schema.Types.ObjectId, + }, + modified: { + type: Boolean, + }, +}); + +MyEventSchema.statics.findAllByUserIdAndIdApp = function (userId, idapp, sall) { + const Event = this; + + let myfind = {}; + if (sall === '1') + myfind = { idapp, booked: true }; + else + myfind = { userId, idapp, booked: true }; + + return Event.find(myfind, (err, arrbooked) => { + // console.log('ris MyEvent:', arrbooked); + return arrbooked + }); +}; + + +function getUsersByEvent(idapp) { + const query = [ + { + $match: { idapp } + }, + { + $group: { _id: "$userId" } + }, + { + $project: { + _id: { + $toString: "$userId" + } + } + }, + { + $Lookup: { + from: "users", + localField: "userId", // field in my collection + foreignField: "ObjectId(_id)", // field in the 'from' collection + as: "fromItems" + } + }, + { + $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$fromItems", 0] },] } } + }, + { $project: { username: 1, name: 1, surname: 1 } } + + ]; + return query +} + + +MyEventSchema.statics.findAllDistinctByEvent = function (idapp) { + const Event = this; + + const query = getUsersByEvent(idapp); + + return Event.aggregate(query) + .then(ris => { + return ris + }); +}; + +MyEventSchema.statics.executeQueryTable = function (idapp, params) { + return tools.executeQueryTable(this, idapp, params); +}; + + +const MyEvent = mongoose.model('MyEvent', MyEventSchema); + +module.exports = { MyEvent }; diff --git a/server/models/operator.js b/server/models/operator.js new file mode 100644 index 0000000..c736d46 --- /dev/null +++ b/server/models/operator.js @@ -0,0 +1,63 @@ +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +const tools = require('../tools/general'); + +mongoose.Promise = global.Promise; +mongoose.level = "F"; + + +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +const OperatorSchema = new Schema({ + idapp: { + type: String, + }, + username: { + type: String, + }, + name: { + type: String, + }, + surname: { + type: String, + }, + email: { + type: String, + }, + cell: { + type: String, + }, + webpage: { + type: String, + }, + img: { + type: String, + }, + skype: { + type: String, + }, + days_working: { + type: String, + }, + facebook: { + type: String, + }, + disciplines: { + type: String, + }, + offers: { + type: String, + }, +}); + +OperatorSchema.statics.executeQueryTable = function (idapp, params) { + return tools.executeQueryTable(this, idapp, params); +}; + +const Operator = mongoose.model('Operator', OperatorSchema); + +module.exports = { Operator }; diff --git a/server/models/sendmsg.js b/server/models/sendmsg.js index c15afb0..f302e00 100644 --- a/server/models/sendmsg.js +++ b/server/models/sendmsg.js @@ -13,7 +13,7 @@ mongoose.plugin(schema => { const sendmsgSchema = new Schema({ idapp: { - type: Number, + type: String, }, userId: { type: String, diff --git a/server/models/user.js b/server/models/user.js index 6af69d2..d3270ab 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -330,45 +330,8 @@ UserSchema.statics.getUsersListByParams = function (params) { * @returns {Object} Object -> `{ rows, count }` */ -UserSchema.statics.queryTable = function (idapp, params) { - const User = this; - - if (typeof params.startRow !== 'number') { - throw new Error('startRow must be number') - } else if (typeof params.endRow !== 'number') { - throw new Error('endRow must be number') - } - - const query = [ - { $match: Object.assign({ idapp }, params.filter) } - ]; - - if (params.sortBy) { - // maybe we want to sort by blog title or something - const mysort = { $sort: params.sortBy }; - // console.log('sortBy', params.sortBy); - // console.table(mysort); - query.push(mysort) - } - - query.push( - { $group: { - _id: null, - // get a count of every result that matches until now - count: { $sum: 1 }, - // keep our results for the next operation - results: { $push: '$$ROOT' } - } }, - // and finally trim the results to within the range given by start/endRow - { $project: { - count: 1, - rows: { $slice: ['$results', params.startRow, params.endRow] } - } } - ); - - return User - .aggregate(query) - .then(([{ count, rows }]) => ({ count, rows })) +UserSchema.statics.executeQueryTable = function (idapp, params) { + return tools.executeQueryTable(this, idapp, params); }; diff --git a/server/router/api/actions.js b/server/router/api/actions.js new file mode 100644 index 0000000..e4e9cd2 --- /dev/null +++ b/server/router/api/actions.js @@ -0,0 +1,16 @@ +var mongoose = require('mongoose'); +const Subscription = mongoose.model('subscribers'); + +module.exports = { + doOtherThingsAfterDeleted: function (tablename, rec) { + try { + if (tablename === 'users') { + // Delete also all the subscribers record of this User + return Subscription.remove({ userId: rec._id }) + } + } catch (e) { + return false + } + return true; + } +}; diff --git a/server/router/index_router.js b/server/router/index_router.js index 0beb845..7f255a6 100644 --- a/server/router/index_router.js +++ b/server/router/index_router.js @@ -1,27 +1,31 @@ const express = require('express'); const router = express.Router(); -var { authenticate } = require('../middleware/authenticate'); +const { authenticate } = require('../middleware/authenticate'); const { ObjectID } = require('mongodb'); -var mongoose = require('mongoose'); +const mongoose = require('mongoose'); const cfgserver = mongoose.model('cfgserver'); const _ = require('lodash'); -var { User } = require('../models/user'); +const { User } = require('../models/user'); +const { Booking } = require('../models/booking'); +const { Operator } = require('../models/operator'); +const { MyEvent } = require('../models/myevent'); const tools = require('../tools/general'); -var server_constants = require('../tools/server_constants'); +const server_constants = require('../tools/server_constants'); +const actions = require('./api/actions'); router.post(process.env.LINKVERIF_REG, (req, res) => { - var body = _.pick(req.body, ['idapp', 'idlink']); - var idapp = body.idapp; - var idlink = body.idlink; + const body = _.pick(req.body, ['idapp', 'idlink']); + const idapp = body.idapp; + const idlink = body.idlink; console.log("LINKVERIF_REG POST " + process.env.LINKVERIF_REG + " idapp= " + idapp + " idlink = " + idlink); // Cerco l'idlink se è ancora da Verificare @@ -138,7 +142,7 @@ router.post(process.env.LINK_UPDATE_PASSWORD, (req, res) => { // Salva lo User user.save().then(() => { - res.header('x-auth', token).send({user}); // Ritorna il token di ritorno + res.header('x-auth', token).send({ user }); // Ritorna il token di ritorno }); }) } @@ -151,21 +155,51 @@ router.post(process.env.LINK_UPDATE_PASSWORD, (req, res) => { function getTableByTableName(tablename) { + mytable = ''; if (tablename === 'users') mytable = User; - else if (tablename === 'booking') + else if (tablename === 'bookings') mytable = Booking; + else if (tablename === 'operators') + mytable = Operator; + else if (tablename === 'events') + mytable = MyEvent; return mytable } +router.post('/settable', authenticate, (req, res) => { + const params = req.body; + const mytable = getTableByTableName(params.table); + const mydata = req.body.data; + + mydata.idapp = req.user.idapp; + + mytablerec = new mytable(mydata); + + return mytablerec.save() + .then(rec => { + // tools.mylog('rec', rec); + return res.send(rec); + + }).catch((e) => { + console.log(e); + res.status(400).send(e); + }); + +}); + router.post('/gettable', authenticate, (req, res) => { const params = req.body; const mytable = getTableByTableName(params.table); + // console.log('mytable', mytable); + if (!mytable) { + return res.status(400).send(e); + } - return mytable.queryTable(req.user.idapp, params).then(ris => { - // tools.mylog('list', ris); + return mytable.executeQueryTable(req.user.idapp, params).then(ris => { return res.send(ris); + }).catch((e) => { console.log(e); res.status(400).send(e); @@ -207,7 +241,7 @@ router.delete('/delrec/:table/:id', authenticate, (req, res) => { const tablename = req.params.table; // const idapp = req.body.idapp; - console.log('id', id , 'table', tablename); + console.log('id', id, 'table', tablename); const mytable = getTableByTableName(tablename); @@ -223,6 +257,12 @@ router.delete('/delrec/:table/:id', authenticate, (req, res) => { tools.mylog('DELETED ', rec._id); + // Do extra things after deleted + actions.doOtherThingsAfterDeleted(tablename, rec).then((ris) => { + if (ris) + tools.mylog('DELETED Others things ...'); + }); + res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); }).catch((e) => { res.status(400).send(); @@ -230,5 +270,9 @@ router.delete('/delrec/:table/:id', authenticate, (req, res) => { }); +function doOtherThingsAfterDeleted() { + +} + module.exports = router; diff --git a/server/router/myevent_router.js b/server/router/myevent_router.js new file mode 100644 index 0000000..919b222 --- /dev/null +++ b/server/router/myevent_router.js @@ -0,0 +1,114 @@ +const express = require('express'); +const router = express.Router(); + +const tools = require('../tools/general'); +const server_constants = require('../tools/server_constants'); + +const { authenticate } = require('../middleware/authenticate'); + +const { MyEvent } = require('../models/myevent'); + +const { ObjectID } = require('mongodb'); + +const sendemail = require('../sendemail'); + +const _ = require('lodash'); + +router.post('/', authenticate, (req, res) => { + tools.mylog('INIZIO - MyEvent'); + + // tools.mylog('req.body', req.body); + const myrec = _.pick(req.body, tools.allfieldMyEvent()); + const id = myrec._id; + const fieldtochange = _.pick(myrec, tools.allfieldMyEventChange()); + + tools.mylog('crea MyEvent'); + const myevent = new MyEvent(myrec); + + const check = tools.checkUserOk(myevent.userId, req.user._id); + if (check.exit) return check.ret; + + // Modify: + return MyEvent.findOne({ id }) + .then(trovato => { + // console.log('trovato', trovato); + if (trovato) { + return myevent.findOneAndUpdate({ id }, { $set: fieldtochange }, { + new: true, + upsert: true + }).then((recmyevent) => { + // tools.mylog('myevent:', myevent); + // tools.mylog('already exist'); + sendNotif(res, myrec.idapp, req.user, recmyevent); + res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id }); + }); + } else { + // save to database a new record + tools.mylog('save to database a new record'); + myevent._id = new ObjectID(); + return myevent.save().then((writeresult) => { + let idobj = writeresult._id; + + myevent.findById(idobj) + .then((recmyevent) => { + sendNotif(res, myrec.idapp, req.user, recmyevent); + res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id }); + }); + }); + } + }) +}); + +router.delete('/:id/:notify/:idapp', authenticate, (req, res) => { + console.log('DELETE myevent'); + const id = req.params.id; + const notify = req.params.notify; + const idapp = req.params.idapp; + + myevent.findByIdAndRemove(id).then((recmyevent) => { + if (!recmyevent) { + return res.status(404).send(); + } + + if (notify === '1') + sendNotif(res, idapp, req.user, recmyevent); + + tools.mylog('DELETED ', recmyevent.descr, recmyevent._id); + + res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id }); + + }).catch((e) => { + res.status(400).send(); + }); +}); + + +router.get('/:userId/:idapp/:sall', authenticate, (req, res) => { + const userId = req.params.userId; + const idapp = req.params.idapp; + const sall = req.params.sall; + // var category = req.params.category; + + // tools.mylog('GET myeventS : ', req.params); + + if (!ObjectID.isValid(userId)) { + return res.status(404).send(); + } + + if (userId !== String(req.user._id)) { + // I'm trying to write something not mine! + return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }); + } + + // Extract all the todos of the userId only + MyEvent.findAllByUserIdAndIdApp(userId, idapp, sall).then((recevent) => { + res.send({ recevent }); + }).catch((e) => { + console.log(e); + res.status(400).send(e); + }); + +}); + + +module.exports = router; diff --git a/server/router/projects_router.js b/server/router/projects_router.js index 0852115..a80a95e 100644 --- a/server/router/projects_router.js +++ b/server/router/projects_router.js @@ -65,6 +65,13 @@ router.post('/', authenticate, (req, res) => { router.patch('/:id', authenticate, (req, res) => { var id = req.params.id; + + // ------------- EXAMPLES: ----------------------- + // var mionome = req.query.name; // Esempio miosito.com?name=pippo + // const plainText = req. body.plainText; // + // ---------------------------------------------------- + + var body = _.pick(req.body, tools.allfieldProject()); tools.mylogshow('PATCH PROJECT: ', id); diff --git a/server/sendemail.js b/server/sendemail.js index c1e8df0..70ddcc9 100644 --- a/server/sendemail.js +++ b/server/sendemail.js @@ -28,8 +28,11 @@ function checkifSendEmail() { //return false; } + module.exports = { - sendEmail_base: function (template, username, to, mylocalsconf, replyTo) { + sendEmail_base: function (template, user, to, mylocalsconf, replyTo) { + + console.log('mylocalsconf', mylocalsconf); // console.log("check EMAIL :" + checkifSendEmail()); @@ -49,6 +52,7 @@ module.exports = { pass: process.env.EMAIL_PW } }, + // htmlToText: false }); @@ -132,7 +136,7 @@ module.exports = { // Send to the Admin an Email this.sendEmail_base('admin/registration/' + lang, user, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); - if (tools.getManagerEmailByIdApp(idapp) !== '' && tools.isManagAndAdminDifferent(idapp)) { + if (tools.isManagAndAdminDifferent(idapp)) { this.sendEmail_base('admin/registration/' + lang, user, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); } }, @@ -181,7 +185,7 @@ module.exports = { // Send Email also to the Admin this.sendEmail_base('admin/'+texthtml+'/' + lang, user, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); - if (tools.getManagerEmailByIdApp(idapp) !== '' && tools.isManagAndAdminDifferent(idapp)) { + if (tools.isManagAndAdminDifferent(idapp)) { this.sendEmail_base('admin/'+texthtml+'/' + lang, user, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); } @@ -210,7 +214,7 @@ module.exports = { // Send Email also to the Admin this.sendEmail_base('admin/cancelbooking/' + lang, user, tools.getAdminEmailByIdApp(idapp), mylocalsconf, ''); - if (tools.getManagerEmailByIdApp(idapp) !== '' && tools.isManagAndAdminDifferent(idapp)) { + if (tools.isManagAndAdminDifferent(idapp)) { this.sendEmail_base('admin/cancelbooking/' + lang, user, tools.getManagerEmailByIdApp(idapp), mylocalsconf, ''); } }, diff --git a/server/server.js b/server/server.js index 3e7f6ca..ce424a8 100644 --- a/server/server.js +++ b/server/server.js @@ -12,6 +12,8 @@ const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); +const sendemail = require('./sendemail'); + i18n = require("i18n"); @@ -37,6 +39,7 @@ const index_router = require('./router/index_router'); const push_router = require('./router/push_router'); const newsletter_router = require('./router/newsletter_router'); const booking_router = require('./router/booking_router'); +const myevent_router = require('./router/myevent_router'); const subscribe_router = require('./router/subscribe_router'); const email_router = require('./router/email_router'); const todos_router = require('./router/todos_router'); @@ -91,6 +94,7 @@ app.use('/subscribe', subscribe_router); app.use('/push', push_router); app.use('/signup_news', newsletter_router); app.use('/booking', booking_router); +app.use('/event', myevent_router); app.use('/email', email_router); app.use('/todos', todos_router); app.use('/projects', projects_router); @@ -142,6 +146,7 @@ if ((process.env.NODE_ENV === 'production') || (process.env.NODE_ENV === 'test') if (process.env.PROD !== 1) { testmsgwebpush(); + testemail(); } // ----------------- MAILCHIMP ----- @@ -186,6 +191,24 @@ function startserv() { } +function testemail() { + /*const user = { + username: 'paoloar77', + name: 'Paolo', + surname: 'Arena', + email: "paolo.arena77@gmail.com", + };*/ + + const user = { + username: 'cricri_test', + name: 'Cristina', + surname: 'Barattoni', + email: "Info@cristinabarattoni.it", + }; + + // sendemail.sendEmail_Registration("it", user.email, user, '2', "http://link_solo_di_prova.com"); +} + function testmsgwebpush() { var { User } = require('./models/user'); diff --git a/server/tools/general.js b/server/tools/general.js index ae9e79e..0b49d64 100644 --- a/server/tools/general.js +++ b/server/tools/general.js @@ -66,6 +66,10 @@ module.exports = { 'completed_at', 'expiring_at', 'enableExpiring', 'id_prev', 'progress', 'modified', 'phase', 'assigned_to_userId', 'hoursplanned', 'hoursworked', 'start_date', 'themecolor', 'themebgcolor'] }, + allfieldMyEvent: function () { + return ['userId',] + }, + allfieldTodoWithId: function () { return ['_id', ...this.allfieldTodo()] }, @@ -333,7 +337,8 @@ module.exports = { }, isManagAndAdminDifferent(idapp) { - return this.getManagerEmailByIdApp(idapp) !== this.getAdminEmailByIdApp(idapp) + const manag = this.getManagerEmailByIdApp(idapp); + return (manag !== this.getAdminEmailByIdApp(idapp)) && (manag !== ''); }, getManagerEmailByIdApp: function (idapp) { @@ -344,6 +349,63 @@ module.exports = { return ''; }, + getQueryTable(idapp, params) { + // console.log('idapp', idapp); + // console.table(params); + if (typeof params.startRow !== 'number') { + throw new Error('startRow must be number') + } else if (typeof params.endRow !== 'number') { + throw new Error('endRow must be number') + } + + const query = [ + { $match: Object.assign({ idapp }, params.filter) } + ]; + + if (params.sortBy) { + // maybe we want to sort by blog title or something + const mysort = { $sort: params.sortBy }; + // console.log('sortBy', params.sortBy); + // console.table(mysort); + query.push(mysort) + } + + query.push( + { + $group: { + _id: null, + // get a count of every result that matches until now + count: { $sum: 1 }, + // keep our results for the next operation + results: { $push: '$$ROOT' } + } + }, + // and finally trim the results to within the range given by start/endRow + { + $project: { + count: 1, + rows: { $slice: ['$results', params.startRow, params.endRow] } + } + } + ); + return query + + }, + + executeQueryTable(mythistable, idapp, params) { + let query = this.getQueryTable(idapp, params); + + return mythistable + .aggregate(query) + .then(([{ count, rows }]) => { + return ({ count, rows }) + }) + .catch(err => { + return { + count: 0, rows: [] + } + }); + + } }; -