- Create Newsletter Page: MailingList (without the class style, using Gulp tasks)#94

This commit is contained in:
Paolo Arena
2019-11-21 00:18:40 +01:00
parent 20a3120054
commit f7fa0c4909
54 changed files with 675 additions and 51 deletions

View File

@@ -0,0 +1,110 @@
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 bookingSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String,
},
id_bookedevent: {
type: String,
},
numpeople: {
type: Number,
},
infoevent: {
type: String,
},
msgbooking: {
type: String,
},
datebooked: {
type: Date,
},
modified: {
type: Boolean,
default: false
},
booked: {
type: Boolean,
},
});
bookingSchema.statics.findAllByUserIdAndIdApp = function (userId, idapp, sall) {
const Booking = this;
let myfind = {};
if (sall === '1')
myfind = { idapp, booked: true };
else
myfind = { userId, idapp, booked: true };
return Booking.find(myfind, (err, arrbooked) => {
// console.log('ris Booking:', arrbooked);
return arrbooked
});
};
function getUsersByBooking(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
}
bookingSchema.statics.findAllDistinctByBooking = function (idapp) {
const Booking = this;
const query = getUsersByBooking(idapp);
return Booking.aggregate(query)
.then(ris => {
return ris
});
};
const Booking = mongoose.model('Booking', bookingSchema);
module.exports = { Booking };

View File

@@ -0,0 +1,30 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const cfgserverSchema = new Schema({
chiave: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
},
userId: {
type: String,
},
valore: {
type: String,
},
});
mongoose.model('cfgserver', cfgserverSchema);

View File

@@ -0,0 +1,48 @@
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 ContribtypeSchema = new Schema({
idapp: {
type: String,
},
label: {
type: String,
},
showprice: {
type: Boolean,
}
});
ContribtypeSchema.statics.getFieldsForSearch = function () {
return ['label']
};
ContribtypeSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
ContribtypeSchema.statics.findAllIdApp = function (idapp) {
const Contribtype = this;
const myfind = { idapp };
return Contribtype.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Contribtype = mongoose.model('Contribtype', ContribtypeSchema);
module.exports = { Contribtype };

View File

@@ -0,0 +1,86 @@
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 DisciplineSchema = new Schema({
idapp: {
type: String,
},
order: {
type: Number,
},
typol_code: {
type: String,
},
label: {
type: String,
},
description: {
type: String,
},
linkpage: {
type: String,
},
color: {
type: String,
},
icon: {
type: String,
},
img_small: {
type: String,
},
img: {
type: String,
},
showinnewsletter: {
type: Boolean,
},
showinhome: {
type: Boolean,
},
teachers: [{
type: String,
}],
});
DisciplineSchema.statics.findAllIdApp = function (idapp) {
const Discipline = this;
const query = [
{ $match: { idapp } },
{ $sort: { order: 1 } }
];
return Discipline
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
DisciplineSchema.statics.getFieldsForSearch = function () {
return ['label', 'description']
};
DisciplineSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
const Discipline = mongoose.model('Discipline', DisciplineSchema);
module.exports = { Discipline };

View File

@@ -0,0 +1,59 @@
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 MailingListSchema = new Schema({
idapp: {
type: String,
},
email: {
type: String,
trim: true,
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
lastid_newstosent: {
type: String
}
});
MailingListSchema.statics.getFieldsForSearch = function () {
return ['name', 'surname', 'email']
};
MailingListSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
MailingListSchema.statics.findAllIdApp = function (idapp) {
const MailingList = this;
const myfind = { idapp };
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return MailingList.find(myfind, (err, arrrec) => {
return arrrec
});
};
const MailingList = mongoose.model('MailingList', MailingListSchema);
module.exports = { MailingList };

View File

@@ -0,0 +1,152 @@
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,
},
bodytext: {
type: String,
},
dateTimeStart: {
type: Date,
},
dateTimeEnd: {
type: Date,
},
bgcolor: {
type: String,
},
icon: {
type: String,
},
img_small: {
type: String,
},
img: {
type: String,
},
wherecode: {
type: String,
},
contribtype: {
type: String,
},
price: {
type: Number,
},
infoafterprice: {
type: String,
},
teacher: {
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.findAllIdApp = function (idapp) {
const Event = this;
const query = [
{ $match: { idapp } },
{ $sort: { dateTimeStart: 1 } }
];
return Event
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
MyEventSchema.statics.getLastEvents = function (idapp) {
const Event = this;
const lastn = 3;
const query = [
{ $match: { idapp } },
{ $sort: { dateTimeStart: 1 } }
];
return Event
.aggregate(query)
.then((arrrec) => {
return arrrec.slice(-lastn)
})
};
MyEventSchema.statics.getFieldsForSearch = function () {
return ['short_tit', 'title', 'teacher', 'details']
};
MyEventSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
if (tools.INITDB_FIRSTIME) {
// console.log(' createIndex MyEvent Index...');
// MyEventSchema.index({ short_tit: 'text', title: 'text', teacher: 'text', details: 'text' });
}
const MyEvent = mongoose.model('MyEvent', MyEventSchema);
module.exports = { MyEvent };

View File

@@ -0,0 +1,114 @@
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 NewstosentSchema = new Schema({
idapp: {
type: String,
},
label: {
type: String,
},
activate: {
type: Boolean,
default: false
},
numemail_tot: {
type: Number,
default: 0
},
numemail_sent: {
type: Number,
default: 0
},
datetoSent: {
type: Date
},
datestartJob: {
type: Date
},
datefinishJob: {
type: Date
},
lastemailsent_Job: {
type: Date
},
starting_job: {
type: Boolean,
default: false
},
finish_job: {
type: Boolean,
default: false
},
error_job: {
type: String,
}
});
NewstosentSchema.statics.getFieldsForSearch = function () {
return ['name', 'surname', 'email']
};
NewstosentSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
NewstosentSchema.statics.findNewsletter_To_Send = function (idapp) {
const Newstosent = this;
return Newstosent.findOne({
datetoSent: { $gte: tools.IncDateNow(-1000 * 60 * 60) },
activate: true,
starting_job: false,
finish_job: false,
idapp
}).then((rec) => {
return (rec) ? rec._doc : null;
});
};
NewstosentSchema.statics.findNewsletterPending_To_Send = function (idapp) {
const Newstosent = this;
// Resend the Email after N hours no other email sent.
const numhours = 8;
return Newstosent.findOne({
datestartJob: { $lt: tools.IncDateNow(0) },
activate: true,
starting_job: true,
finish_job: false,
lastemailsent_Job: { $gte: tools.IncDateNow(-1000 * 60 * 60 * numhours) },
idapp
}).then((rec) => {
return (rec) ? rec._doc : null;
});
};
NewstosentSchema.statics.findAllIdApp = function (idapp) {
const Newstosent = this;
const myfind = { idapp };
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return Newstosent.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Newstosent = mongoose.model('Newstosent', NewstosentSchema);
module.exports = { Newstosent };

View File

@@ -0,0 +1,112 @@
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,
trim: true,
},
surname: {
type: String,
trim: true,
},
email: {
type: String,
trim: true,
},
usertelegram: {
type: String,
},
cell: {
type: String,
trim: true,
},
img: {
type: String,
},
qualification: { // President, Vice-President, ecc...
type: String,
},
disciplines: {
type: String,
},
certifications: {
type: String,
},
webpage: {
type: String,
},
days_working: {
type: String,
},
facebook: {
type: String,
},
info: {
type: String,
},
intro: {
type: String,
},
offers: {
type: String,
},
skype: {
type: String,
},
});
OperatorSchema.statics.getEmailByUsername = async function (idapp, username) {
const Operator = this;
return await Operator.findOne({ idapp, username })
.then((arrrec) => {
return ((arrrec) ? arrrec.email : '');
}).catch((e) => {
console.error('getEmailByUsername', e);
});
};
OperatorSchema.statics.getFieldsForSearch = function () {
return ['name', 'surname', 'email', 'cell']
};
OperatorSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
OperatorSchema.statics.findAllIdApp = function (idapp) {
const Operator = this;
const myfind = { idapp };
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return Operator.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Operator = mongoose.model('Operator', OperatorSchema);
module.exports = { Operator };

View File

@@ -0,0 +1,60 @@
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 PermissionSchema = new Schema({
_id: {
type: Number,
},
label: {
type: String,
default: ''
}
},{ _id : false });
PermissionSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await Permission.findOne().limit(1).sort({_id:-1});
if (!!myrec) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id * 2;
} else {
this._id = 1;
}
}
next();
});
PermissionSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
PermissionSchema.statics.findAllIdApp = function () {
const Permission = this;
const myfind = { };
return Permission.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Permission = mongoose.model('Permission', PermissionSchema);
module.exports = { Permission };

View File

@@ -0,0 +1,347 @@
var mongoose = require('mongoose');
const _ = require('lodash');
const tools = require('../tools/general');
var server_constants = require('../tools/server_constants');
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
mongoose.set('debug', process.env.DEBUG);
var ProjectSchema = new mongoose.Schema({
userId: {
type: String,
},
pos: {
type: Number,
},
descr: {
type: String,
},
longdescr: {
type: String,
},
typeproj: {
type: Number,
},
id_main_project: mongoose.Schema.Types.ObjectId,
id_parent: mongoose.Schema.Types.ObjectId,
priority: {
type: Number,
},
statusproj: {
type: Number,
default: 0
},
created_at: {
type: Date
},
modify_at: {
type: Date
},
completed_at: {
type: Date
},
expiring_at: {
type: Date,
},
enableExpiring: {
type: Boolean,
default: false
},
id_prev: mongoose.Schema.Types.ObjectId,
modified: {
type: Boolean,
},
live_url: {
type: String,
},
test_url: {
type: String,
},
totalphases: {
type: Number,
default: 1
},
actualphase: {
type: Number,
default: 1
},
hoursplanned: {
type: Number,
default: 0
},
hoursleft: {
type: Number,
default: 0
},
hoursworked: {
type: Number,
default: 0
},
themecolor: {
type: String,
default: ''
},
themebgcolor: {
type: String,
default: ''
},
progressCalc: {
type: Number,
default: 0
},
begin_development: {
type: Date,
},
begin_test: {
type: Date,
},
hoursweeky_plannedtowork: {
type: Number,
default: 0
},
endwork_estimate: {
type: Date
},
privacyread: {
type: String
},
privacywrite: {
type: String
}
});
ProjectSchema.methods.toJSON = function () {
var Project = this;
var projObject = Project.toObject();
// console.log(projObject);
return _.pick(projObject, tools.allfieldProjectWithId());
};
ProjectSchema.statics.findByUserIdAndIdParent = function (userId, id_parent) {
var Project = this;
if (userId === '') {
return Project.find({
'id_parent': id_parent,
});
} else {
return Project.find({
'userId': userId,
'id_parent': id_parent,
});
}
};
ProjectSchema.statics.findProjectByUserId = function (userId, idproj) {
var Project = this;
if (userId === '') {
return Project.findOne({
'_id': idproj,
});
} else {
return Project.findOne({
'userId': userId,
'_id': idproj,
});
}
};
ProjectSchema.statics.findAllProjByUserId = async function (userId) {
var Project = this;
return Project.aggregate([
{ $match: { $or: [{ privacyread: server_constants.Privacy.all }, { userId: userId }] } },
{
$graphLookup: {
from: "projects",
startWith: "$id_main_project",
connectFromField: "id_main_project",
connectToField: "_id",
as: "ris",
restrictSearchWithMatch: { $or: [{ privacyread: server_constants.Privacy.all }, { userId: userId }] }
}
},
{ $match: { "ris.privacyread": { $exists: true } } },
// {
// $project: {
// "descr": 1,
// "typeproj": 1,
// "id_main_project": 1,
// }
// }
]).then(ris1 => {
// console.log('findAllProjByUserId', ris1);
return ris1;
})
// return Project.find({
// $or: [
// { 'userId': userId },
// {'privacyread' : server_constants.Privacy.all}
// ],
// $or: [
// { 'typeproj': server_constants.TypeProj.TYPE_PROJECT },
// { 'typeproj': server_constants.TypeProj.TYPE_SUBDIR }
// ],
};
ProjectSchema.statics.getArrIdParentInTable = function (userId) {
var Project = this;
return Project.find({ 'userId': userId }).distinct("id_parent")
};
ProjectSchema.statics.getIdParentByIdProj = function (idProj) {
var Project = this;
console.log('INIT getIdParentByIdProj', idProj);
return Project.findOne({ '_id': ObjectId(idProj) }).then(rec => {
if (!!rec) {
console.log('getIdParentByIdProj', rec.id_parent);
return rec.id_parent;
} else {
return '';
}
}).catch(e => {
return '';
})
};
ProjectSchema.statics.creaProjMain = async function () {
const projmain = {
descr: process.env.PROJECT_DESCR_MAIN,
longdescr: process.env.PROJECT_DESCR_MAIN,
typeproj: 1,
id_main_project: null,
id_parent: null,
privacyread: server_constants.Privacy.all
};
return await new Project(projmain).save()
.then(ris => {
console.log('ris', ris);
if (!!ris)
return ris._doc;
else
return null;
});
};
ProjectSchema.statics.getAllProjects = async function (userId) {
var Project = this;
// console.log('getAllProjects');
let obj = [];
const projbase = await Project.findOne( { descr: process.env.PROJECT_DESCR_MAIN })
.then(ris => {
if (!!ris) {
// console.log('ris', ris);
if (!!ris._doc)
return ris._doc;
else
return null;
}else {
return Project.creaProjMain();
}
});
obj.arrproj = await Project.findAllProjByUserId(userId);
obj.arrproj.push(projbase);
return obj;
};
ProjectSchema.statics.enabletoModify = async function (userId, idProj) {
var Project = this;
let obj = [];
return Project.findOne({
'_id': idProj,
$or: [{
'privacywrite': server_constants.Privacy.all,
'userId': userId
}]
}).then(ris => {
return (!!ris);
});
};
ProjectSchema.statics.updateCalc = async function (userId, idproj, objdatacalc, recIn) {
return new Promise((resolve, reject) => {
if (!!recIn) {
return resolve(recIn);
} else {
return resolve(Project.findProjectByUserId(userId, idproj))
}
}).then((myproj) => {
if (!!myproj) {
console.log('objdatacalc progressCalc', objdatacalc.mydata.progressCalc);
objdatacalc.setValuesToRecord(myproj);
// console.log('updateCalc', myproj._id, myproj.progressCalc);
return myproj.save()
.then(() => {
// console.log('salvato proj!');
return true;
})
.catch(err => {
console.log("Error updateCalc", err.message);
});
}
return false;
}).catch(e => {
console.log('Error: ', e);
return false;
});
};
ProjectSchema.pre('save', function (next) {
// var Project = this;
// console.log('Project.expiring_at', Project.expiring_at);
next();
});
var Project = mongoose.model('Projects', ProjectSchema);
module.exports = { Project };

View File

@@ -0,0 +1,112 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const sendmsgSchema = new Schema({
idapp: {
type: String,
},
source: {
page: { type: String },
event_id: { type: String }
},
origin: {
username: { type: String },
},
dest: {
idapp: { type: String, },
username: { type: String },
},
message: {
type: String,
},
datemsg: {
type: Date,
},
status: {
type: Number,
},
options: {
type: Number,
},
read: {
type: Boolean,
default: false
},
deleted: {
type: Boolean,
default: false
},
});
sendmsgSchema.statics.findAllMsgByUsernameIdAndIdApp = function (username, lastdataread, idapp) {
const SendMsg = this;
return SendMsg.find({
$and: [
{ $or: [ { 'dest.username': username }, { 'origin.username': username },] },
{ 'datemsg': {$gt: new Date(lastdataread)} },
{ idapp }
]
}).then((arrmsg) => {
console.log('arrmsg', arrmsg.length);
return arrmsg
}).catch((err) => {
console.error('err', err);
});
};
sendmsgSchema.statics.findLastGroupByUserIdAndIdApp = function (userId, username, idapp) {
const SendMsg = this;
return SendMsg.aggregate([
{
$match: {
$or: [{ 'origin.username': username }, { 'dest.username': username }, { idapp }],
$and: [{ idapp }]
}
},
{
$group:
{
_id: "$dest.username",
message: { $last: "$message" },
datemsg: { $last: "$datemsg" },
dest: { $last: "$dest" },
origin: { $last: "$origin" },
read: { $last: "$read" }
}
},
{
$sort: { datemsg: -1 }
},
])
.then((arrmsg) => {
// Remove duplicate
// Exclude my chat
const myarr = arrmsg.filter((ris) => ris._id !== username);
// console.table(myarr);
return myarr
}).catch((err) => {
console.error(err);
});
};
const SendMsg = mongoose.model('SendMsg', sendmsgSchema);
module.exports = { SendMsg };

View File

@@ -0,0 +1,79 @@
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 SettingsSchema = new Schema({
idapp: {
type: String,
},
key: {
type: String,
},
type: {
type: Number,
},
value_str: {
type: String,
},
value_date: {
type: Date,
},
value_num: {
type: Number,
}
});
SettingsSchema.statics.getFieldsForSearch = function () {
return ['key', 'value_str']
};
SettingsSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
SettingsSchema.statics.getValDbSettings = function (idapp, key) {
return Settings.findOne({ idapp, key })
.then((myrec) => {
console.log('getValDbSettings', myrec, 'idapp', idapp);
if (myrec) {
if (myrec.type === tools.FieldType.date)
return myrec.value_date;
if (myrec.type === tools.FieldType.number)
return myrec.value_num;
else
return myrec.value_str;
} else {
return ''
}
}).catch((err) => {
console.error('getValDbSettings', err);
return null;
});
};
SettingsSchema.statics.findAllIdApp = function (idapp) {
const Settings = this;
const myfind = { idapp };
return Settings.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Settings = mongoose.model('Settings', SettingsSchema);
module.exports = { Settings };

View File

@@ -0,0 +1,27 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const SubscriberSchema = new Schema({
endpoint: String,
keys: Schema.Types.Mixed,
userId: String,
access: String,
browser: String,
createDate: {
type: Date,
default: Date.now
}
});
mongoose.model('subscribers', SubscriberSchema);

473
src/server/models/todo.js Normal file
View File

@@ -0,0 +1,473 @@
var mongoose = require('mongoose');
const _ = require('lodash');
const tools = require('../tools/general');
var { Project } = require('./project');
var server_constants = require('../tools/server_constants');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
mongoose.set('debug', process.env.DEBUG);
var TodoSchema = new mongoose.Schema({
userId: {
type: String,
},
pos: {
type: Number,
},
category: mongoose.Schema.Types.ObjectId,
descr: {
type: String,
},
priority: {
type: Number,
},
statustodo: {
type: Number,
default: 0
},
created_at: {
type: Date
},
modify_at: {
type: Date
},
start_date: {
type: Date,
},
completed_at: {
type: Date
},
expiring_at: {
type: Date,
},
enableExpiring: {
type: Boolean,
default: false
},
id_prev: mongoose.Schema.Types.ObjectId,
progress: {
type: Number,
},
phase: {
type: Number,
},
assigned_to_userId: {
type: String,
},
hoursplanned: {
type: Number,
},
hoursworked: {
type: Number,
},
themecolor: {
type: String,
},
themebgcolor: {
type: String,
default: '',
},
modified: {
type: Boolean,
},
});
TodoSchema.methods.toJSON = function () {
var todo = this;
var todoObject = todo.toObject();
// console.log(todoObject);
return _.pick(todoObject, tools.allfieldTodoWithId());
};
TodoSchema.statics.findByUserIdAndIdParent = function (userId, category, phase = '') {
var Todo = this;
let tofind = {
'category': category,
};
if (userId !== '') {
tofind['userId'] = userId;
}
if (!!phase) {
tofind['phase'] = phase;
}
return Todo.find(tofind);
};
// User.find({ admin: true }).where('created_at').gt(monthAgo).exec(function(err, users) {
// if (err) throw err;
function getQueryFilterTodo(userId) {
myobj = [{ privacyread: server_constants.Privacy.all }, { userId: userId }];
return myobj;
}
function getQueryTodo(filterMatchBefore = {}, userId) {
let filterMatchAfter = {
$or: getQueryFilterTodo(userId)
};
let myobjField = getobjFieldTodo(true);
const query = [
{ $match: filterMatchBefore },
{
$lookup: {
from: "projects",
localField: "category", // field in the Todo collection
foreignField: "_id", // field in the projects collection
as: "fromItems"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$fromItems", 0] }, "$$ROOT"] } }
},
{ $match: filterMatchAfter },
{ $project: myobjField }];
return query;
}
TodoSchema.statics.findAllByUserIdAndCat = function (userId) {
var Todo = this;
const query = getQueryTodo({}, userId);
return Todo.aggregate(query)
.then(ris => {
// console.log('ris TODO:', ris);
//return tools.mapSort(ris)
return ris
});
};
TodoSchema.statics.getArrIdParentInTable = function (userId) {
var Todo = this;
return Todo.find(getQueryFilterTodo(userId)).distinct("category")
.then(arrcategory => {
return arrcategory
})
};
function getobjFieldTodo(withprojectfield) {
let objfield = {};
for (const field of tools.allfieldTodo()) {
objfield[field] = 1;
}
if (withprojectfield) {
objfield["privacyread"] = 1;
objfield["privacywrite"] = 1;
}
// console.log("getobjFieldTodo", objfield);
return objfield
}
TodoSchema.statics.enabletoModify = async function (userId, idTodo) {
var Todo = this;
let params = {};
params['_id'] = ObjectId(idTodo);
const query = getQueryTodo(params, userId);
return Todo.aggregate(query)
.then(ris => {
return (!!ris);
})
.catch(err => {
console.log("ERR: ".err);
return false;
});
};
TodoSchema.statics.getAllTodo = async function (userId) {
var Todo = this;
const arralltodo = await Todo.findAllByUserIdAndCat(userId);
// console.log('arralltodo', arralltodo);
let obj = [];
obj.arrcategories = await Todo.getArrIdParentInTable(userId);
// console.log('obj.arrcategories', obj.arrcategories);
let arrtodos = [];
if (obj.arrcategories.length > 0) {
for (const mycat of obj.arrcategories) {
if (!!arralltodo) {
const arrfiltrato = arralltodo.filter(item => item.category.toString() === mycat.toString());
if (arrfiltrato.length > 0) {
const arrmap = tools.mapSort(arrfiltrato);
arrtodos.push(arrmap);
// console.log('AGGIUNGI RECORDS TODO! cat: ', mycat, 'da aggiungere:', arrfiltrato.length, 'attuali', arrtodos.length);
// console.log(arrtodos)
} else {
arrtodos.push([]);
}
}
}
}
obj.arrtodos = arrtodos;
// console.log('obj.arrtodos:');
// logtodo(obj.arrtodos);
return obj;
};
function getelem(item) {
return item.descr + ' ' + item.category;
}
function logtodo(myarr) {
console.log(getarrlog(myarr));
}
function getarrlog(myarr) {
let mystr = "";
for (const indcat in myarr) {
mystr += indcat + ': \n';
for (const indelem in myarr[indcat]) {
mystr += ' [' + indelem + '] ' + getelem(myarr[indcat][indelem]) + '\n';
}
}
return mystr
}
class CalcTodo {
constructor(phase) {
this.mydata = {
phase: phase,
numitem: 0
};
this.clean()
}
clean() {
this.mydata.hoursleft = 0;
this.mydata.hoursplanned = 0;
this.mydata.hoursworked = 0;
this.mydata.progressCalc = 0;
}
addDataProj(datain) {
if (!!datain) {
if (datain.actualphase === this.mydata.phase) {
CalcTodo.addFields(this.mydata, datain, true);
}
}
}
addDataTodo(datain) {
if (!!datain) {
if (datain.phase === this.mydata.phase) {
CalcTodo.addFields(this.mydata, datain, false);
}
}
}
static addFields(recout, recin, isproj) {
// console.log('addFields', recin);
recout.hoursworked += recin.hoursworked;
recout.hoursplanned += recin.hoursplanned;
let hoursleft = (recin.hoursplanned - recin.hoursworked);
if (hoursleft < 0)
hoursleft = 0;
recout.hoursleft += hoursleft;
if (recin.progress === undefined) {
recout.progressCalc += recin.progressCalc;
} else {
recout.progressCalc += recin.progress;
}
recout.numitem++;
}
static copyFields(recout, recin) {
recout.hoursworked = recin.hoursworked;
recout.hoursplanned = recin.hoursplanned;
recout.hoursleft = recin.hoursleft;
if (recin.progress === undefined)
recout.progressCalc = recin.progressCalc;
else {
if (!!recin.progressCalc)
recout.progressCalc = recin.progressCalc;
else
recout.progressCalc = 0;
}
}
setValuesToRecord(objout) {
CalcTodo.copyFields(objout, this.mydata)
}
endDataCalc() {
if (this.mydata.numitem > 0) {
this.mydata.progressCalc = Math.round(this.mydata.progressCalc / this.mydata.numitem);
}
console.log('this.mydata.progressCalc', this.mydata.progressCalc)
}
getData() {
// return tools.jsonCopy(this.mydata);
return { ...this.mydata }
}
}
TodoSchema.statics.calculateTreeTodo = async function (actualphase, userId, idproj, calcalsoUpper, masterproj, nocalcDown) {
// console.log('calculateTreeTodo', 'actualphase', actualphase, idproj);
const myrecproj = await Project.findProjectByUserId(userId, idproj);
// const id_parent = await Project.getIdParentByIdProj(idproj);
let objdata = new CalcTodo(actualphase);
let promiseChain = Promise.resolve();
return await Project.findByUserIdAndIdParent(userId, idproj)
.then(arrsubproj => {
// console.log(' ', arrsubproj.length, 'SubProjects trovati');
// console.log('arrsubproj', 'userId', userId, 'idproj', idproj, arrsubproj.length);
if (!nocalcDown) {
// 1) Calculate the SubProjects of this project Main
for (const subproj of arrsubproj) {
if (!calcalsoUpper) { // not include the first Project because it was already calculated before
promiseChain = promiseChain.then(() => {
return Todo.calculateTreeTodo(actualphase, userId, subproj._id, calcalsoUpper, masterproj, true)
.then((subobjdata) => {
objdata.addDataProj(subobjdata);
});
});
} else {
promiseChain = promiseChain.then(() => {
objdata.addDataProj(subproj);
});
}
}
}
return promiseChain;
})
.then(() => {
// console.log('objdata', objdata);
// 2) Calculate the Todos of this project
if (!!myrecproj)
return Todo.calculateTodoHoursAndProgress(userId, idproj, myrecproj.actualphase);
else
return null
})
.then((objdatatodos) => {
if (!!objdatatodos) {
if (!!myrecproj) {
if (myrecproj.actualphase === actualphase) {
// console.log('objdatatodos', objdatatodos);
objdata.addDataTodo(objdatatodos);
// End Calculate
objdata.endDataCalc();
// Update into the DB:
return Project.updateCalc(userId, idproj, objdata, null)
.then((ris) => {
if (ris)
return objdata.getData();
else
return null;
});
}
}
}
return null;
})
.then((ris) => {
if (calcalsoUpper) {
if (!!myrecproj) {
if (!!myrecproj.id_parent) {
// Calculate also the upper Projects !
return new Promise((resolve, reject) => {
Todo.calculateTreeTodo(actualphase, userId, myrecproj.id_parent, true, masterproj, false);
resolve(ris)
});
} else {
return new Promise((resolve, reject) => {
resolve()
});
}
}
}
return new Promise((resolve, reject) => {
resolve()
});
})
};
TodoSchema.statics.calculateTodoHoursAndProgress = async function (userId, idproj, actualphase) {
var Todo = this;
let objdata = new CalcTodo(actualphase);
return await Todo.findByUserIdAndIdParent(userId, idproj, actualphase)
.then(arrtodo => {
// console.log(' calculateTodo *', arrtodo.length, '* FOUND');
for (let itemtodo of arrtodo) {
objdata.addDataTodo(itemtodo);
}
objdata.endDataCalc();
return objdata.getData();
})
.catch(e => {
console.log('Error: ', e);
return null;
});
};
TodoSchema.pre('save', function (next) {
// var todo = this;
// console.log('todo.expiring_at', todo.expiring_at);
next();
});
var Todo = mongoose.model('Todos', TodoSchema);
module.exports = { Todo };

414
src/server/models/user.js Normal file
View File

@@ -0,0 +1,414 @@
var bcrypt = require('bcryptjs');
const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
const queryclass = require('../classes/queryclass');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
mongoose.set('debug', process.env.DEBUG);
var UserSchema = new mongoose.Schema({
userId: {
type: String,
},
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: false,
/*validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}*/
},
cell: {
type: String,
},
idapp: {
type: String,
required: true,
},
username: {
type: String,
required: true,
trim: true,
minlength: 6,
unique: false,
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
password: {
type: String,
require: true,
minlength: 6,
},
lang: {
type: String,
require: true,
},
linkreg: {
type: String,
required: false
},
verified_email: {
type: Boolean,
},
tokens: [{
access: {
type: String,
required: true
},
browser: {
type: String,
required: true
},
token: {
type: String,
required: true
},
date_login: {
type: Date
},
}],
perm: {
type: Number
},
ipaddr: {
type: String,
},
date_reg: {
type: Date,
default: Date.now()
},
date_tokenforgot: {
type: Date
},
tokenforgot: {
type: String,
},
lasttimeonline: {
type: Date
},
news_on: {
type: Boolean
},
profile: {
img: {
type: String
},
cell: {
type: String
},
dateofbirth: {
type: Date,
},
sex: {
type: Number,
},
},
});
UserSchema.methods.toJSON = function () {
var user = this;
var userObject = user.toObject();
return _.pick(userObject, ['_id', ...shared_consts.fieldsUserToChange()]);
};
UserSchema.methods.generateAuthToken = function (req) {
// console.log("GENERA TOKEN : ");
var user = this;
const useragent = req.get('User-Agent');
tools.mylog("GENERATE USER-AGENT = ", useragent);
const access = 'auth';
const browser = useragent;
const token = jwt.sign({ _id: user._id.toHexString(), access }, process.env.SIGNCODE).toString();
const date_login = new Date();
// CANCELLA IL PRECEDENTE !
user.tokens = user.tokens.filter(function (tok) {
return (tok.access !== access) || ((tok.access === access) && (tok.browser !== browser));
});
user.tokens.push({ access, browser, token, date_login });
user.lasttimeonline = new Date();
return user.save()
.then(() => {
console.log("TOKEN CREATO IN LOGIN : " + token);
return token;
})
.catch(err => {
console.log("Error", err.message);
});
};
UserSchema.statics.setPermissionsById = function (id, perm) {
const user = this;
return user.findByIdAndUpdate(id, { $set: { perm } }).then((user) => {
if (user)
return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
else
return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
});
};
UserSchema.statics.isAdmin = function (user) {
try {
return ((user.perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin);
} catch (e) {
return false
}
};
UserSchema.statics.isManager = function (user) {
try {
return ((user.perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager);
} catch (e) {
return false
}
};
UserSchema.statics.findByToken = function (token, typeaccess) {
const User = this;
let decoded;
try {
decoded = jwt.verify(token, process.env.SIGNCODE);
} catch (e) {
return Promise.resolve(null);
}
return User.findOne({
'_id': decoded._id,
'tokens.token': token,
'tokens.access': typeaccess,
});
};
UserSchema.statics.findByTokenAnyAccess = function (token) {
var User = this;
var decoded;
try {
decoded = jwt.verify(token, process.env.SIGNCODE);
} catch (e) {
return Promise.resolve(null);
}
return User.findOne({
'_id': decoded._id,
'tokens.token': token,
});
};
UserSchema.statics.findByCredentials = function (idapp, username, password) {
var User = this;
var pwd = "";
return User.findOne({ idapp, username: username }).then((user) => {
if (!user) {
// Check if with email:
return User.findOne({ idapp, email: username })
} else {
return user
}
}).then(user => {
if (!user)
return null;
pwd = user.password;
return new Promise((resolve, reject) => {
// Use bcrypt.compare to compare password and user.password
// console.log("pwd1 " + password);
// console.log("pwd2 " + pwd);
bcrypt.compare(password, pwd, (err, res) => {
if (res) {
resolve(user);
} else {
return resolve(null);
}
});
});
});
};
UserSchema.statics.findByUsername = function (idapp, username) {
const User = this;
return User.findOne({
'idapp': idapp,
'username': username,
});
};
UserSchema.statics.findByLinkreg = function (idapp, linkreg) {
var User = this;
return User.findOne({
'linkreg': linkreg,
'idapp': idapp,
});
};
UserSchema.statics.findByLinkTokenforgot = function (idapp, email, tokenforgot) {
var User = this;
return User.findOne({
'email': email,
'tokenforgot': tokenforgot,
'date_tokenforgot': { $gte: tools.IncDateNow(-1000 * 60 * 60 * 4) }, // 4 ore fa!
'idapp': idapp,
});
};
UserSchema.statics.findByEmail = function (idapp, email) {
var User = this;
return User.findOne({
'idapp': idapp,
'email': email,
});
};
UserSchema.pre('save', function (next) {
var user = this;
/*
if (user.isModified('password')) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = hash;
next();
});
});
} else {
next();
}
*/
next();
});
UserSchema.methods.removeToken = function (token) {
const user = this;
return user.update({
$pull: {
tokens: { token }
}
});
};
UserSchema.statics.getEmailByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username })
.then((arrrec) => {
return ((arrrec) ? arrrec.email : '');
}).catch((e) => {
console.error('getEmailByUsername', e);
});
};
UserSchema.statics.getUsersList = function (idapp) {
const User = this;
return User.find({ 'idapp': idapp }, {
username: 1,
name: 1,
surname: 1,
verified_email: 1,
perm: 1,
email: 1,
date_reg: 1,
img: 1
})
};
UserSchema.statics.getUsersListByParams = function (params) {
const User = this;
myclParamQuery = new queryclass.CParamsQuery(params);
const filterMatchBefore = `${ myclParamQuery.filter }`;
return User.find(
{ $match: filterMatchBefore },
{ 'idapp': idapp },
{ username: 1, name: 1, surname: 1, verified_email: 1, perm: 1, email: 1, date_reg: 1, img: 1, lasttimeonline: 1, news_on: 1 })
};
/**
* Query blog posts by user -> paginated results and a total count.
* @returns {Object} Object -> `{ rows, count }`
*/
UserSchema.statics.getFieldsForSearch = function () {
return ['name', 'surname', 'email', 'cell']
};
UserSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
if (tools.INITDB_FIRSTIME) {
console.log(' createIndex User Index...');
// UserSchema.index({ username: 'text', name: 'text', surname: 'text', email: 'text' });
// UserSchema.index({ name: 'name' });
// UserSchema.index({ name: 1 });
// UserSchema.index({ surname: 1 });
}
const User = mongoose.model('User', UserSchema);
class Hero {
constructor(name, level) {
this.name = name;
this.level = level;
}
// Adding a method to the constructor
greet() {
return `${this.name} says hello.`;
}
}
module.exports = { User, Hero };

View File

@@ -0,0 +1,54 @@
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 WhereSchema = new Schema({
_id: {
type: mongoose.Schema.Types.ObjectId
},
idapp: {
type: String,
},
code: {
type: String,
},
placename: {
type: String,
},
whereicon: {
type: String,
},
});
WhereSchema.statics.getFieldsForSearch = function () {
return ['placename']
};
WhereSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
WhereSchema.statics.findAllIdApp = function (idapp) {
const Where = this;
const myfind = { idapp };
return Where.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Where = mongoose.model('Where', WhereSchema);
module.exports = { Where };