Files
freeplanet_serverside/src/server/models/user.js

1241 lines
28 KiB
JavaScript
Raw Normal View History

const bcrypt = require('bcryptjs');
2018-12-24 20:31:02 +01:00
const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const tools = require('../tools/general');
const { Settings } = require('../models/settings');
const { ListaIngresso } = require('../models/listaingresso');
const { Billettera } = require('./billettera');
const { ExtraList } = require('../models/extralist');
const { ObjectID } = require('mongodb');
const shared_consts = require('../tools/shared_nodejs');
const queryclass = require('../classes/queryclass');
2019-02-05 03:40:22 +01:00
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
2019-03-04 19:18:54 +01:00
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
2018-12-24 20:31:02 +01:00
2018-12-27 20:09:40 +01:00
mongoose.set('debug', process.env.DEBUG);
const UserSchema = new mongoose.Schema({
2019-02-05 03:40:22 +01:00
userId: {
type: String,
},
2018-12-24 20:31:02 +01:00
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: false,
/*validate: {
2018-12-24 20:31:02 +01:00
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}*/
2018-12-24 20:31:02 +01:00
},
idapp: {
type: String,
2018-12-24 20:31:02 +01:00
required: true,
},
ind_order: {
type: Number
},
2018-12-24 20:31:02 +01:00
username: {
type: String,
required: true,
trim: true,
minlength: 6,
unique: false,
2018-12-24 20:31:02 +01:00
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
2018-12-24 20:31:02 +01:00
password: {
type: String,
require: true,
minlength: 6,
},
lang: {
type: String,
require: true,
},
linkreg: {
type: String,
2019-02-06 18:48:32 +01:00
required: false
2018-12-24 20:31:02 +01:00
},
verified_email: {
type: Boolean,
},
2019-12-31 00:44:53 +01:00
made_gift: {
type: Boolean,
},
2018-12-24 20:31:02 +01:00
tokens: [{
access: {
type: String,
required: true
},
browser: {
type: String,
required: true
},
2018-12-24 20:31:02 +01:00
token: {
type: String,
required: true
},
date_login: {
type: Date
},
2018-12-24 20:31:02 +01:00
}],
perm: {
type: Number
},
ipaddr: {
type: String,
},
date_reg: {
type: Date,
},
date_temp_reg: {
type: Date,
},
2018-12-24 20:31:02 +01:00
date_tokenforgot: {
type: Date
},
tokenforgot: {
type: String,
},
lasttimeonline: {
type: Date
},
news_on: {
type: Boolean
},
aportador_solidario: {
type: String,
},
aportador_solidario_nome_completo: {
type: String,
},
aportador_solidario_ind_order: {
type: Number,
},
note: {
type: String,
},
profile: {
img: {
type: String
},
2019-12-29 23:30:49 +01:00
nationality: {
type: String
},
intcode_cell: {
type: String
},
iso2_cell: {
type: String
},
cell: {
type: String
},
2019-12-31 00:44:53 +01:00
country_pay: {
type: String
},
email_paypal: {
type: String
},
paymenttypes: [],
username_telegram: {
type: String
},
teleg_id: {
type: Number
},
teleg_id_old: {
type: Number
},
teleg_checkcode: {
type: Number
},
2020-01-03 22:02:18 +01:00
manage_telegram: {
type: Boolean
},
dateofbirth: {
type: Date,
},
my_dream: {
type: String,
},
saw_and_accepted: {
type: Number,
},
saw_zoom_presentation: {
type: Boolean
},
special_req: {
type: Boolean
},
sex: {
type: Number,
},
},
2018-12-24 20:31:02 +01:00
});
UserSchema.methods.toJSON = function () {
const user = this;
const userObject = user.toObject();
2018-12-24 20:31:02 +01:00
return _.pick(userObject, ['_id', ...shared_consts.fieldsUserToChange()]);
2018-12-24 20:31:02 +01:00
};
UserSchema.methods.generateAuthToken = function (req) {
// console.log("GENERA TOKEN : ");
const user = this;
const useragent = req.get('User-Agent');
2019-12-31 00:44:53 +01:00
// 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();
2018-12-24 20:31:02 +01:00
// CANCELLA IL PRECEDENTE !
2019-03-04 19:18:54 +01:00
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(() => {
2019-12-31 00:44:53 +01:00
// console.log("TOKEN CREATO IN LOGIN : " + token);
return token;
})
.catch(err => {
console.log("Error", err.message);
});
2018-12-24 20:31:02 +01:00
};
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 (perm) {
try {
2020-01-03 22:02:18 +01:00
return ((perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin);
} catch (e) {
return false
}
};
2020-01-03 22:02:18 +01:00
UserSchema.statics.isManager = function (perm) {
try {
2020-01-03 22:02:18 +01:00
return ((perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager);
} catch (e) {
return false
}
};
UserSchema.statics.findByToken = function (token, typeaccess) {
const User = this;
let decoded;
2018-12-24 20:31:02 +01:00
try {
decoded = jwt.verify(token, process.env.SIGNCODE);
} catch (e) {
return Promise.resolve(null);
2018-12-24 20:31:02 +01:00
}
return User.findOne({
'_id': decoded._id,
'tokens.token': token,
'tokens.access': typeaccess,
2018-12-24 20:31:02 +01:00
});
};
2019-02-13 18:47:58 +01:00
UserSchema.statics.findByTokenAnyAccess = function (token) {
const User = this;
let decoded;
2019-02-13 18:47:58 +01:00
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) {
const User = this;
let pwd = "";
2018-12-24 20:31:02 +01:00
return User.findOne({ idapp, username: username }).then((user) => {
2018-12-24 20:31:02 +01:00
if (!user) {
2019-03-04 19:18:54 +01:00
// Check if with email:
return User.findOne({ idapp, email: username.toLowerCase() })
2019-03-04 19:18:54 +01:00
} else {
return user
2018-12-24 20:31:02 +01:00
}
2019-03-04 19:18:54 +01:00
}).then(user => {
if (!user)
return null;
2018-12-24 20:31:02 +01:00
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);
2018-12-24 20:31:02 +01:00
bcrypt.compare(password, pwd, (err, res) => {
if (res) {
resolve(user);
} else {
return resolve(null);
}
});
});
});
};
UserSchema.statics.findByUsername = async function (idapp, username, alsoemail) {
const User = this;
2018-12-24 20:31:02 +01:00
const regexusername = new RegExp(["^", username, "$"].join(""), "i");
return await User.findOne({
'idapp': idapp,
'username': regexusername,
}).then(async (ris) => {
if ((!ris) && (alsoemail)) {
regexemail = new RegExp(["^", username.toLowerCase(), "$"].join(""), "i");
return await User.findOne({
'idapp': idapp,
'email': regexemail,
});
}
return ris;
2018-12-24 20:31:02 +01:00
});
};
UserSchema.statics.getUserShortDataByUsername = async function (idapp, username) {
2019-12-31 00:44:53 +01:00
const User = this;
const myrec = await User.findOne({
2019-12-31 00:44:53 +01:00
'idapp': idapp,
'username': username,
}, {
ind_order: 1,
2019-12-31 00:44:53 +01:00
username: 1,
name: 1,
surname: 1,
verified_email: 1,
'profile.teleg_id': 1,
'profile.saw_zoom_presentation': 1,
'profile.saw_and_accepted': 1,
'profile.email_paypal': 1,
'profile.my_dream': 1,
'profile.paymenttypes': 1,
2019-12-31 00:44:53 +01:00
made_gift: 1,
email: 1,
date_reg: 1,
img: 1
}).then((ris) => {
if (!!ris) {
// console.log('ris', ris);
if (!!ris._doc)
return ris._doc;
else
return null;
}
});
if (myrec) {
myrec.qualified = await User.isUserQualified7(idapp, myrec.username);
myrec.numinvitati = await User.getnumInvitati(idapp, myrec.username);
myrec.numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, myrec.username);
}
return myrec
2019-12-31 00:44:53 +01:00
};
UserSchema.statics.getDownlineByUsername = async function (idapp, username) {
2019-12-31 00:44:53 +01:00
const User = this;
const arrrec = await User.find({
2019-12-31 00:44:53 +01:00
'idapp': idapp,
'aportador_solidario': username,
}, {
aportador_solidario: 1,
ind_order: 1,
2019-12-31 00:44:53 +01:00
username: 1,
name: 1,
surname: 1,
verified_email: 1,
'profile.teleg_id': 1,
'profile.saw_zoom_presentation': 1,
'profile.saw_and_accepted': 1,
'profile.email_paypal': 1,
'profile.my_dream': 1,
'profile.paymenttypes': 1,
made_gift: 1,
2019-12-31 00:44:53 +01:00
email: 1,
date_reg: 1,
img: 1
}, (err, arrrec) => {
return arrrec;
});
if (!!arrrec) {
for (const rec of arrrec) {
rec._doc.qualified = await User.isUserQualified7(idapp, rec.username);
rec._doc.numinvitati = await User.getnumInvitati(idapp, rec.username);
rec._doc.numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, rec.username);
}
}
return arrrec
2019-12-31 00:44:53 +01:00
};
UserSchema.statics.getnumInvitatiAttivi = function (idapp, username) {
const User = this;
return User.count({
idapp,
aportador_solidario: username,
verified_email: true,
'profile.teleg_id': { $gt: 1 },
'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED,
'profile.saw_zoom_presentation': true,
'profile.my_dream': { $exists: true },
$and: [
{ "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } },
{ "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } }
],
$where: "this.profile.paymenttypes.length >= 1",
'profile.email_paypal': { $exists: true },
});
};
UserSchema.statics.isUserQualified7 = async function (idapp, username) {
const User = this;
const myrec = await User.findOne({
'idapp': idapp,
'username': username,
$or: [
{
special_req: true
},
{
verified_email: true,
'profile.teleg_id': { $gt: 1 },
'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED,
'profile.saw_zoom_presentation': true,
'profile.my_dream': { $exists: true },
'profile.email_paypal': { $exists: true },
$and: [
{ "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } },
{ "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } }
],
$where: "this.profile.paymenttypes.length >= 1",
}]
});
return !!myrec;
};
UserSchema.statics.getnumPaymentOk = function (idapp) {
const User = this;
return User.count({
idapp,
$where: "this.profile.paymenttypes.length >= 1",
'profile.email_paypal': { $exists: true },
});
};
UserSchema.statics.getUsersNationalityQuery = function (idapp) {
const query = [
{
$match: { idapp }
},
{
$group: { _id: "$profile.nationality", count: { $sum: 1 } }
},
{
$sort: { count: -1 }
}
];
return query
};
UserSchema.statics.getindOrderDuplicate = function (idapp) {
const User = this;
return User.aggregate(User.getUsersNationalityQuery(idapp))
.then(ris => {
// console.table(ris);
return JSON.stringify(ris);
});
};
UserSchema.statics.getnumInvitati = function (idapp, username) {
const User = this;
return User.count({
idapp,
aportador_solidario: username,
});
};
2018-12-24 20:31:02 +01:00
UserSchema.statics.findByLinkreg = function (idapp, linkreg) {
const User = this;
2018-12-24 20:31:02 +01:00
return User.findOne({
'linkreg': linkreg,
'idapp': idapp,
});
};
UserSchema.statics.findByLinkTokenforgot = function (idapp, email, tokenforgot) {
const User = this;
2018-12-24 20:31:02 +01:00
return User.findOne({
'email': email,
'tokenforgot': tokenforgot,
'date_tokenforgot': { $gte: tools.IncDateNow(-1000 * 60 * 60 * 4) }, // 4 ore fa!
2018-12-24 20:31:02 +01:00
'idapp': idapp,
});
};
UserSchema.statics.findByEmail = function (idapp, email) {
const User = this;
2018-12-24 20:31:02 +01:00
return User.findOne({
'idapp': idapp,
2018-12-24 20:31:02 +01:00
'email': email,
});
};
UserSchema.statics.getLastUser = function (idapp) {
const User = this;
return User.findOne({ idapp }).sort({ ind_order: -1 })
};
UserSchema.statics.findByIndOrder = function (idapp, ind_order) {
const User = this;
try {
return User.findOne({
'idapp': idapp,
'ind_order': ind_order,
});
} catch (e) {
}
};
2018-12-24 20:31:02 +01:00
UserSchema.pre('save', function (next) {
const user = this;
2018-12-24 20:31:02 +01:00
2018-12-24 20:31:02 +01:00
/*
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;
2018-12-24 20:31:02 +01:00
return user.updateOne({
2018-12-24 20:31:02 +01:00
$pull: {
tokens: { token }
2018-12-24 20:31:02 +01:00
}
});
};
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.getAportadorSolidarioByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username })
.then((rec) => {
return ((rec) ? rec.aportador_solidario : '');
}).catch((e) => {
console.error('getAportadorSolidarioByUsername', e);
});
};
UserSchema.statics.UserByIdTelegram = async function (idapp, teleg_id) {
const User = this;
return await User.findOne({ idapp, 'profile.teleg_id': teleg_id })
.then((rec) => {
return (!!rec) ? rec._doc : null;
}).catch((e) => {
console.error('UserExistByIdTelegram', e);
});
};
2020-01-03 22:02:18 +01:00
UserSchema.statics.TelegIdByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, { 'profile.teleg_id': 1 })
2020-01-03 22:02:18 +01:00
.then((rec) => {
return (!!rec) ? rec.profile.teleg_id : null;
}).catch((e) => {
console.error('TelegIdByUsername', e);
});
};
UserSchema.statics.SetTelegramCheckCode = async function (idapp, id, teleg_checkcode) {
const User = this;
const fields_to_update = {
'profile.teleg_checkcode': teleg_checkcode
};
return await User.findOneAndUpdate({
_id: id
}, { $set: fields_to_update }, { new: false }).then((record) => {
return !!record;
});
};
UserSchema.statics.SetTelegramIdSuccess = async function (idapp, id, teleg_id) {
const User = this;
const fields_to_update = {
'profile.teleg_id': teleg_id,
'profile.teleg_id_old': 0,
'profile.teleg_checkcode': 0
};
return await User.findOneAndUpdate({
idapp,
_id: id
}, { $set: fields_to_update }, { new: false }).then((record) => {
return record;
});
};
UserSchema.statics.SetTelegramWasBlocked = async function (idapp, teleg_id) {
const User = this;
const fields_to_update = {
'profile.teleg_id_old': teleg_id,
'profile.teleg_id': 0,
};
const ris = await User.findOneAndUpdate({
idapp,
'profile.teleg_id': teleg_id
}, { $set: fields_to_update }, { new: false }).then((record) => {
return record;
});
};
2020-01-03 22:02:18 +01:00
UserSchema.statics.getNameSurnameByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, { name: 1, surname: 1 })
2020-01-03 22:02:18 +01:00
.then((rec) => {
return (!!rec) ? `${rec.name} ${rec.surname}` : '';
}).catch((e) => {
console.error('getNameSurnameByUsername', e);
});
};
UserSchema.statics.getusersManagers = async function (idapp) {
const User = this;
return await User.find({ idapp, 'profile.manage_telegram': true }, { 'profile.teleg_id': 1, perm: 1 })
2020-01-03 22:02:18 +01:00
.then((arrrec) => {
return (!!arrrec) ? arrrec : null;
}).catch((e) => {
console.error('getusersManagers', e);
});
};
UserSchema.statics.getUsersTelegALL = async function (idapp) {
const User = this;
return await User.find({ idapp, 'profile.teleg_id': { $gt: 0 } })
.then((arrrec) => {
return (!!arrrec) ? arrrec : null;
}).catch((e) => {
console.error('getUsersTelegALL', e);
});
};
UserSchema.statics.isManagerByIdTeleg = async function (idapp, idtelegram) {
const User = this;
return await User.findOne({
idapp,
'profile.manage_telegram': true,
'profile.teleg_id': idtelegram
}, { 'profile.teleg_id': 1 })
.then((rec) => {
return (!!rec && rec.profile.teleg_id === idtelegram);
}).catch((e) => {
console.error('getusersManagers', e);
return false
});
};
UserSchema.statics.isAdminByIdTeleg = async function (idapp, idtelegram) {
const User = this;
return await User.findOne({
idapp,
'username': 'paoloar77',
'profile.manage_telegram': true,
'profile.teleg_id': idtelegram
}, { 'profile.teleg_id': 1 })
.then((rec) => {
return (!!rec && rec.profile.teleg_id === idtelegram);
}).catch((e) => {
console.error('getusersManagers', e);
return false
});
};
UserSchema.statics.getUsersList = function (idapp) {
const User = this;
return User.find({ 'idapp': idapp }, {
username: 1,
name: 1,
surname: 1,
verified_email: 1,
2019-12-31 00:44:53 +01:00
made_gift: 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 },
2019-12-31 00:44:53 +01:00
{
username: 1,
name: 1,
surname: 1,
verified_email: 1,
made_gift: 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 ['username', 'name', 'surname', 'email', 'profile.cell', 'profile.email_paypal', 'profile.username_telegram', 'aportador_solidario']
};
UserSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
UserSchema.statics.findAllIdApp = function (idapp) {
const User = this;
const myfind = { idapp };
return User.find(myfind, (err, arrrec) => {
return arrrec
});
};
UserSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {
return tools.DuplicateAllRecords(this, idapporig, idappdest);
};
UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, username, aportador_solidario_nome_completo) {
try {
// DATA: username, name, surname, email, intcode_cell, cell
const dashboard = {
aportador: {},
downline: []
};
dashboard.myself = await User.getUserShortDataByUsername(idapp, username);
// Data of my Aportador
dashboard.aportador = await User.getUserShortDataByUsername(idapp, aportador_solidario);
if (dashboard.aportador === undefined) {
dashboard.aportador = await ExtraList.getUserNotRegisteredByNameSurname(idapp, aportador_solidario_nome_completo);
}
// Data of my Downline
const arrap = await User.getDownlineByUsername(idapp, aportador_solidario);
dashboard.numpeople_aportador = arrap.length;
dashboard.downline = await User.getDownlineByUsername(idapp, username);
dashboard.downnotreg = await ExtraList.getDownlineNotRegisteredByNameSurname(idapp, dashboard.myself.name + ' ' + dashboard.myself.surname);
dashboard.downbyuser = {};
for (const down of dashboard.downline) {
dashboard.downbyuser[down.username] = await User.getDownlineByUsername(idapp, down.username);
for (const down2 of dashboard.downbyuser[down.username]) {
dashboard.downbyuser[down2.username] = await User.getDownlineByUsername(idapp, down2.username);
}
}
return dashboard;
} catch (e) {
console.error(e);
return false;
}
};
UserSchema.statics.fixUsername = async function (idapp, aportador_solidario_ind_order, username) {
const User = this;
// Check if somewhere there is my username
return User.find({ idapp, aportador_solidario_ind_order }, async (err, arrrec) => {
if (arrrec) {
for (const myuser of arrrec) {
if (!myuser.aportador_solidario || myuser.aportador_solidario === tools.APORTADOR_NONE) {
myuser.aportador_solidario = username;
await myuser.save()
}
}
}
});
};
UserSchema.statics.findByCellAndNameSurname = function (idapp, cell, name, surname) {
const User = this;
return User.findOne({
'idapp': idapp,
'profile.cell': cell,
'name': name,
'surname': surname,
});
};
UserSchema.statics.getUsersRegistered = async function (idapp) {
const User = this;
const myfind = { idapp };
return await User.count(myfind);
};
UserSchema.statics.getUsersQualified = async function (idapp, numinvitati) {
const User = this;
const arrusers = await User.find({
idapp,
$or: [
{
special_req: true
},
{
verified_email: true,
'profile.teleg_id': { $gt: 0 },
$where: "this.profile.paymenttypes.length >= 1",
'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED,
'profile.saw_zoom_presentation': true,
'profile.my_dream': { $exists: true },
$and: [
{ "$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] } },
{ "$expr": { "$gt": [{ "$strLenCP": "$profile.email_paypal" }, 6] } }
],
}]
}, {
'username': 1,
});
if (numinvitati === 0)
return arrusers; // PRENDI TUTTI
let arrris = [];
for (const rec of arrusers) {
rec.numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, rec.username);
if (rec.numinvitatiattivi >= numinvitati) {
arrris.push(rec);
}
}
return arrris
};
UserSchema.statics.getNumUsersQualified = async function (idapp, numinvitati) {
arrrec = await this.getUsersQualified(idapp, numinvitati);
return arrrec.length
};
UserSchema.statics.getEmailNotVerified = async function (idapp) {
const User = this;
const myfind = { idapp, verified_email: false };
return await User.count(myfind);
};
UserSchema.statics.getUsersTelegramAttivo = async function (idapp) {
const User = this;
const myfind = { idapp, 'profile.teleg_id': { $gt: 0 } };
return await User.count(myfind);
};
UserSchema.statics.getUsersTelegramPending = async function (idapp) {
const User = this;
const myfind = { idapp, 'profile.teleg_checkcode': { $gt: 0 } };
return await User.count(myfind);
};
UserSchema.statics.getUsersZoom = async function (idapp) {
const User = this;
const myfind = { idapp, 'profile.saw_zoom_presentation': true };
return await User.count(myfind);
};
UserSchema.statics.getSaw_and_Accepted = async function (idapp) {
const User = this;
const myfind = { idapp, 'profile.saw_and_accepted': shared_consts.ALL_SAW_AND_ACCEPTED };
return await User.count(myfind);
};
UserSchema.statics.getUsersDreams = async function (idapp) {
const User = this;
const myfind = {
idapp,
'profile.my_dream': { $exists: true },
"$expr": { "$gt": [{ "$strLenCP": "$profile.my_dream" }, 10] }
};
return await User.count(myfind);
};
UserSchema.statics.getLastUsers = async function (idapp) {
const User = this;
const lastn = await Settings.getValDbSettings(idapp, 'SHOW_LAST_N_USERS', 5);
return await User.find({ idapp }).sort({ date_temp_reg: -1 }).limit(lastn).then((arr) => {
//return JSON.stringify(arr)
return arr
});
};
UserSchema.statics.checkUser = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, {
verified_email: 1,
'profile.teleg_id': 1,
'profile.teleg_checkcode': 1,
}).then((rec) => {
return JSON.stringify(rec)
});
};
UserSchema.statics.calculateStat = async function (idapp, username) {
const User = this;
return calcstat = {
numinvitati: await User.getnumInvitati(idapp, username),
numinvitati_attivi: await User.getnumInvitatiAttivi(idapp, username),
};
};
UserSchema.statics.getDistinctNationalityQuery = function (idapp) {
const query = [
{
$match: { idapp }
},
{
$group: { _id: "$profile.nationality", count: { $sum: 1 } }
},
{
$sort: { count: -1 }
}
];
return query
};
UserSchema.statics.findAllDistinctNationality = async function (idapp) {
const User = this;
return User.aggregate(User.getDistinctNationalityQuery(idapp))
.then(ris => {
// console.table(ris);
return JSON.stringify(ris);
});
};
UserSchema.statics.getUsersRegDaily = function (idapp, nrec) {
const query = [
{
$match: { idapp }
},
{
$group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$date_temp_reg" } }, count: { $sum: 1 } }
},
{
$sort: { _id: 1 }
},
{
$limit: nrec
}
];
return query
};
UserSchema.statics.calcRegDaily = async function (idapp) {
const User = this;
return User.aggregate(User.getUsersRegDaily(idapp, 30))
.then(ris => {
// console.table(ris);
return JSON.stringify(ris);
});
};
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 });
}
2018-12-24 20:31:02 +01:00
async function addUtentiInLista(idapp, mode) {
let num = 0;
for (const rec of arrusers) {
let ok = false;
let qualified = await User.isUserQualified7(idapp, rec.username);
let numinvitatiattivi = await User.getnumInvitatiAttivi(idapp, rec.username);
if (mode === 1) {
// 9 punti qualificati
ok = qualified && (numinvitatiattivi >= 2);
} else if (mode === 2) {
// 7 punti qualificati
ok = qualified;
} else {
ok = true;
// // almeno telegram ID
// ok = user.profile.teleg_id > 0;
// } else {
// ok = true;
}
if (ok) {
if (!await ListaIngresso.findByUsername(idapp, rec.username)) {
let listaingresso = new ListaIngresso({
username: rec.username,
ind_order: rec.ind_order,
name: rec.name,
surname: rec.surname,
idapp,
_id: new ObjectID()
});
await listaingresso.save();
num++;
}
}
}
return num;
}
UserSchema.statics.DbOp = async function (idapp, mydata) {
const User = this;
try {
if (mydata.dbop === 'changeCellInt') {
arrusers = await User.find({ 'idapp': idapp });
let num = 0;
for (const rec of arrusers) {
// DISATTIVATO: ORA NON MI SERVE PIU
if (false) {
let mycell = tools.removespaces(rec.profile.intcode_cell + rec.profile.cell);
await User.findOneAndUpdate({ _id: rec._id }, { $set: { 'profile.cell': mycell } });
num++;
}
}
return { num };
// return await User.updateMany({ idapp }, { $set: { 'profile.cell': { $concat: ["$profile.intcode_cell", "$profile.cell"] } } })
} else if (mydata.dbop === 'changeEmailLowerCase') {
arrusers = await User.find({ 'idapp': idapp });
let num = 0;
for (const rec of arrusers) {
let myemail = rec.email.toLowerCase();
if (myemail !== rec.email) {
await User.findOneAndUpdate({ _id: rec._id }, { $set: { 'email': myemail } });
num++;
}
}
return { num };
} else if (mydata.dbop === 'creaLista') {
await ListaIngresso.remove({ idapp });
arrusers = await User.find({ 'idapp': idapp }).sort({ ind_order: 1 });
let num = 0;
num += await addUtentiInLista(idapp, 1);
num += await addUtentiInLista(idapp, 2);
// num += await addUtentiInLista(idapp, 3);
// num += await addUtentiInLista(idapp, 4);
return { num };
} else if (mydata.dbop === 'creaBillettera') {
const num = await Billettera.generaBillettera(idapp);
return { num };
} else if (mydata.dbop === 'visuPlacca') {
const placca = await Billettera.getPlaccaByFuoco(idapp, riga, col);
return { placca };
}
} catch (e) {
console.error(e);
}
};
const User = mongoose.model('User', UserSchema);
2018-12-24 20:31:02 +01:00
2018-12-24 20:31:02 +01:00
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 };
2018-12-24 20:31:02 +01:00