Aggiornamenti

This commit is contained in:
Paolo Arena
2020-04-24 10:29:25 +02:00
parent 4a9fa9cf61
commit 2549d43447
21 changed files with 733 additions and 390 deletions

View File

@@ -7,14 +7,20 @@ const tools = require('../tools/general');
var { authenticate } = require('../middleware/authenticate');
router.post('/updateval', authenticate, (req, res) => {
router.post('/updateval', authenticate, async (req, res) => {
console.log('/updateval', req.body.pairval);
idapp = req.body.idapp;
pair = req.body.pairval;
cfgserver.findOneAndUpdate({chiave: pair.chiave, userID: pair.userId}, { $set: pair }, { new: false }).then((item) => {
// cfgserver.find({ chiave: pair.chiave }, (err, item) => {
res.status(200).send();
}).catch(err => {
return await cfgserver.findOneAndUpdate({ chiave: pair.chiave, idapp, userId: pair.userId }, { $set: pair }, { new: false })
.then((item) => {
// cfgserver.find({ chiave: pair.chiave }, (err, item) => {
if (!!item) {
res.status(200).send();
} else {
res.status(400).send();
}
}).catch(err => {
console.log('ERR:', err);
res.status(400).send();
})

View File

@@ -159,42 +159,25 @@ router.post('/getdoninavi', authenticate, async (req, res) => {
let index = 1;
for (nave of arrnavi) {
nave.rec = await Nave.getNaveByRigaCol(idapp, nave.riga1don, nave.col1don);
/*mypos = {
riga: nave.riga,
col: nave.col,
numup: 3,
};
tools.getRigaColByPosUp(mypos);*/
nave.index = index;
nave.DoniAttesaDiConferma = 0;
nave.DoniMancanti = 0;
nave.DoniConfermati = 0;
nave.tutor_namesurname = await User.getNameSurnameByUsername(idapp, nave.tutor);
if (!!nave.rec) {
if (!!nave.rec.donatore) {
nave.DoniAttesaDiConferma = nave.rec.donatore.arrdonatori.filter((rec) => (!!rec.date_made_gift && !rec.made_gift && !(rec.ind_order === nave.rec.donatore.recmediatore.ind_order && rec.num_tess === 2))).reduce((sum, item) => sum + 1, 0);
nave.DoniMancanti = nave.rec.donatore.arrdonatori.filter((rec) => (!rec.made_gift && !(rec.ind_order === nave.rec.donatore.recmediatore.ind_order && rec.num_tess === 2))).reduce((sum, item) => sum + 1, 0);
nave.DoniConfermati = nave.rec.donatore.arrdonatori.filter((rec) => rec.made_gift && !(rec.ind_order === nave.rec.donatore.recmediatore.ind_order && rec.num_tess === 2)).reduce((sum, item) => sum + 1, 0);
}
}
const fieldsvalue = {
DoniAttesaDiConferma: nave.DoniAttesaDiConferma,
DoniMancanti: nave.DoniMancanti,
DoniConfermati: nave.DoniConfermati,
tutor_namesurname: nave.tutor_namesurname,
};
const risu = await NavePersistente.findOneAndUpdate({ _id: nave._id }, { $set: fieldsvalue }, { new: false });
nave._doc.rec = nave.rec;
nave = await Nave.ricalcolaNave(idapp, nave, 0, 0, ricalcola, index);
index++;
}
} else {
arrnavi = await NavePersistente.findAllIdApp(idapp);
for (nave of arrnavi) {
nave._doc.rec = await Nave.getNaveByRigaCol(idapp, nave.riga1don, nave.col1don);
if (nave.provvisoria || nave.DoniTotali !== nave.DoniConfermati) {
nave._doc.rec = await Nave.getNaveByRigaCol(idapp, nave.riga1don, nave.col1don);
} else {
let rigapos = nave.riga1don;
let colpos = nave.col1don;
if (rigapos < 4) {
rigapos = 4;
colpos = 1;
}
nave._doc.rec = {};
nave._doc.rec.donatore = {};
nave._doc.rec.donatore.navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, rigapos, colpos, tools.Placca.SONOFUOCO);
}
}
}

View File

@@ -388,6 +388,8 @@ router.patch('/chval', authenticate, async (req, res) => {
}
}
let index = 0;
await mytable.findByIdAndUpdate(id, { $set: fieldsvalue }).then(async (rec) => {
// tools.mylogshow(' REC TO MODIFY: ', rec);
if (!rec) {
@@ -422,6 +424,12 @@ router.patch('/chval', authenticate, async (req, res) => {
}
}
} else if (mydata.table === 'navi') {
if ('made_gift' in fieldsvalue) {
if (!!fieldsvalue.riga) {
await Nave.ricalcolaNave(idapp, null, fieldsvalue.riga, fieldsvalue.col, true, index)
}
}
}
if (msg !== '')
@@ -433,11 +441,129 @@ router.patch('/chval', authenticate, async (req, res) => {
}
}).catch((e) => {
tools.mylogserr('Error patch USER: ', e);
tools.mylogserr('Error patch USER: ', e.message);
res.status(400).send();
})
});
router.patch('/callfunz', authenticate, async (req, res) => {
// const idapp = req.body.idapp;
const id = req.body.data.id;
const ind_order = req.body.data.ind_order;
const idapp = req.body.idapp;
const mydata = req.body.data;
try {
// If I change my record...
if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTutor(req.user.perm)) && !(req.user._id.toString() === id) && !tools.ModificheConsentite(mydata.table, fieldsvalue)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
const myuser = await User.findOne({ idapp, ind_order });
let rimosso = 0;
if (mydata.myfunc === 345) { // SOSTITUISCI
mianavedasost = await Nave.findOne({ idapp, riga: mydata.data.riga, col: mydata.data.col });
// Sostituisci l'Utente
myusernuovo = await User.getUserShortDataByUsername(idapp, mydata.data.username);
let navepersistente = await NavePersistente.findByRigaColByDonatore(idapp, mydata.data.riga, mydata.data.col, 0);
if (!!myusernuovo) {
// Controlla prima se è in una Nave Temporanea, allora lo elimina
miaarrnavi = await Nave.find({ idapp, ind_order: myusernuovo.ind_order });
if (miaarrnavi) {
for (const mianave of miaarrnavi) {
let persistente = await NavePersistente.findByRigaColByDonatore(idapp, mianave.riga, mianave.col, 0);
if (persistente.provvisoria) {
fieldsvalue = {
ind_order: -1
};
let ris = await Nave.findByIdAndUpdate(mianave.id, { $set: fieldsvalue });
if (!!ris) {
rimosso++;
}
}
}
}
if (!!myuser) {
// Metti campo 'delete': true su ListaIngresso
olduseringresso = await ListaIngresso.findOne({ idapp, ind_order: myuser.ind_order });
if (!!olduseringresso) {
let fieldsvalue = {
deleted: true
};
const risul = await ListaIngresso.findByIdAndUpdate(olduseringresso.id, { $set: fieldsvalue }, { new: false });
}
}
if (!!myuser) {
// Metti Deleted allo User
fieldsvalue = {
deleted: true
};
await User.findByIdAndUpdate(myuser.id, { $set: fieldsvalue });
}
// Aggiorna la Nave con il Nuovo
fieldsvalue = {
ind_order: myusernuovo.ind_order
};
const dachi = req.user.name + ' ' + req.user.surname;
return await Nave.findByIdAndUpdate(mianavedasost.id, { $set: fieldsvalue })
.then(async (rec) => {
// tools.mylogshow(' REC TO MODIFY: ', rec);
if (!rec) {
return res.status(404).send();
} else {
if (mydata.notifBot) {
// Send Notification to the BOT
let messaggio = 'Sei stato Spostato in una Nuova Nave !';
if (!!navepersistente.date_start) {
messaggio += tools.ACAPO + ' data di Partenza della Nave: ' + tools.getstrDateLong(navepersistente.date_start) + tools.ACAPO;
}
if (!!navepersistente.link_chat) {
messaggio += tools.ACAPO + 'Entra nella Gift Chat: ' + navepersistente.link_chat + tools.ACAPO;
}
const myplacca = await Nave.getNavePos(idapp, navepersistente.riga, navepersistente.col);
messaggio += tools.ACAPO + myplacca;
await telegrambot.sendMsgTelegram(idapp, myusernuovo.username, messaggio);
await telegrambot.sendMsgTelegramToTheManagers(idapp, mydata.notifBot.txt + ' ' + myusernuovo.name + ' ' + myusernuovo.surname + ' [da ' + dachi + ']' + tools.ACAPO + 'Inviato messaggio: ' + messaggio);
await telegrambot.sendMsgTelegram(idapp, req.user.username, mydata.notifBot.txt);
await telegrambot.sendMsgTelegram(idapp, req.user.username, myplacca);
}
// const nomecognomeprima = myuser.name + ' ' + myuser.surname + '(' + myuser.username + ')';
// const nomecognomenuovo = await User.getNameSurnameByUsername(idapp,);
res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
}
}).catch((e) => {
tools.mylogserr('Error patch USER: ', e);
res.status(400).send();
})
}
}
} catch (e) {
console.log(e);
res.status(400).send();
}
});
router.get('/copyfromapptoapp/:idapporig/:idappdest', async (req, res) => {
// const idapporig = req.params.idapporig;
// const idappdest = req.params.idappdest;
@@ -467,7 +593,7 @@ router.get('/copyfromapptoapp/:idapporig/:idappdest', async (req, res) => {
// }
});
router.delete('/delrec/:table/:id', authenticate, (req, res) => {
router.delete('/delrec/:table/:id', authenticate, async (req, res) => {
const id = req.params.id;
const idapp = req.user.idapp;
const tablename = req.params.table;
@@ -485,24 +611,54 @@ router.delete('/delrec/:table/:id', authenticate, (req, res) => {
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
let cancellato = false;
notifBot = tools.NotifyIfDelRecord(tablename);
let myrec = null;
return mytable.findByIdAndRemove(id).then((rec) => {
if (!rec) {
return res.status(404).send();
if (!User.isAdmin(req.user.perm) || !User.isManager(req.user.perm)) {
if (tablename === 'users') {
let fieldsvalue = {
deleted: true
};
const rec = await mytable.findByIdAndUpdate(id, { $set: fieldsvalue });
myrec = rec;
cancellato = true;
}
}
tools.mylog('DELETED ', rec._id);
let ris = null;
if (!cancellato) {
ris = await mytable.findByIdAndRemove(id).then((rec) => {
if (!rec) {
return res.status(404).send();
}
myrec = rec;
cancellato = true;
tools.mylog('DELETED ', rec._id);
}).catch((e) => {
console.log(e);
res.status(400).send();
});
}
if (cancellato) {
// Do extra things after deleted
return actions.doOtherThingsAfterDeleted(tablename, rec).then(async (ris) => {
return actions.doOtherThingsAfterDeleted(tablename, myrec).then(async (ris) => {
if (ris) {
if (notifBot) {
// Send Notification to the BOT
let nomerecord = '';
if ((tablename === 'users') || (tablename === 'extralist')) {
nomerecord = rec.name + ' ' + rec.surname + ' (' + rec.username + ')';
nomerecord = myrec.name + ' ' + myrec.surname + ' (' + myrec.username + ')';
}
addtext = 'Eliminato il Record "' + nomerecord + '" dalla tabella ' + tablename + '\n' +
@@ -514,12 +670,11 @@ router.delete('/delrec/:table/:id', authenticate, (req, res) => {
return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
}
});
}
res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
return ris;
}).catch((e) => {
console.log(e);
res.status(400).send();
});
});
@@ -651,8 +806,9 @@ router.get('/loadsite/:userId/:idapp/:sall', authenticate_noerror, (req, res) =>
});
router.get(process.env.LINK_CHECK_UPDATES, authenticate, (req, res) => {
router.get(process.env.LINK_CHECK_UPDATES, authenticate, async (req, res) => {
const userId = req.user._id;
const idapp = req.query.idapp;
// console.log("POST " + process.env.LINK_CHECK_UPDATES + " userId=" + userId);
@@ -660,7 +816,7 @@ router.get(process.env.LINK_CHECK_UPDATES, authenticate, (req, res) => {
return res.status(404).send();
}
cfgserver.find().then((arrcfgrec) => {
await cfgserver.find({ idapp }).then((arrcfgrec) => {
if (!arrcfgrec)
return res.status(404).send();

View File

@@ -47,7 +47,7 @@ router.post('/', authenticate, (req, res) => {
.then(record => {
// tools.mylog('REC SAVED :', record.descr);
tools.sendNotificationToUser(project.userId, 'Project: ' + record.descr, record.descr, '/project/' + project.category, 'project')
tools.sendNotificationToUser(project.userId, 'Project: ' + record.descr, record.descr, '/project/' + project.category, '', 'project', [])
.then(ris => {
if (ris) {
res.send({ record });

View File

@@ -5,78 +5,151 @@ const Subscription = mongoose.model('subscribers');
// const q = require('q');
const webpush = require('web-push');
const tools = require('../tools/general');
const { authenticate } = require('../middleware/authenticate');
const shared_consts = require('../tools/shared_nodejs');
const server_constants = require('../tools/server_constants');
const { User } = require('../models/user');
router.post('/', (req, res) => {
const payload = {
title: req.body.title,
message: req.body.message,
url: req.body.url,
ttl: req.body.ttl,
icon: req.body.icon,
image: req.body.image,
badge: req.body.badge,
tag: req.body.tag
};
const payload = {
title: req.body.title,
message: req.body.message,
url: req.body.url,
ttl: req.body.ttl,
icon: req.body.icon,
image: req.body.image,
badge: req.body.badge,
tag: req.body.tag
};
Subscription.find({}, (err, subscriptions) => {
if (err) {
console.error(`Error occurred while getting subscriptions`);
res.status(500).json({
error: 'Technical error occurred'
});
Subscription.find({}, (err, subscriptions) => {
if (err) {
console.error(`Error occurred while getting subscriptions`);
res.status(500).json({
error: 'Technical error occurred'
});
} else {
let parallelSubscriptionCalls = subscriptions.map((subscription) => {
return new Promise((resolve, reject) => {
const pushSubscription = {
endpoint: subscription.endpoint,
keys: {
p256dh: subscription.keys.p256dh,
auth: subscription.keys.auth
}
};
} else {
let parallelSubscriptionCalls = subscriptions.map((subscription) => {
return new Promise((resolve, reject) => {
const pushSubscription = {
endpoint: subscription.endpoint,
keys: {
p256dh: subscription.keys.p256dh,
auth: subscription.keys.auth
}
};
const pushPayload = JSON.stringify(payload);
const pushOptions = {
vapidDetails: {
subject: process.env.URLBASE_APP1,
privateKey: process.env.PRIVATE_VAPI_KEY,
publicKey: process.env.PUBLIC_VAPI_KEY,
},
TTL: payload.ttl,
headers: {}
};
webpush.sendNotification(
pushSubscription,
pushPayload,
pushOptions
).then((value) => {
resolve({
status: true,
endpoint: subscription.endpoint,
data: value
});
}).catch((err) => {
reject({
status: false,
endpoint: subscription.endpoint,
data: err
});
});
});
const pushPayload = JSON.stringify(payload);
const pushOptions = {
vapidDetails: {
subject: process.env.URLBASE_APP1,
privateKey: process.env.PRIVATE_VAPI_KEY,
publicKey: process.env.PUBLIC_VAPI_KEY,
},
TTL: payload.ttl,
headers: {}
};
webpush.sendNotification(
pushSubscription,
pushPayload,
pushOptions
).then((value) => {
resolve({
status: true,
endpoint: subscription.endpoint,
data: value
});
q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
console.info(pushResults);
}).catch((err) => {
reject({
status: false,
endpoint: subscription.endpoint,
data: err
});
res.json({
data: 'Push triggered'
});
}
});
});
});
});
q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
console.info(pushResults);
});
res.json({
data: 'Push triggered'
});
}
});
});
async function SendMsgTo(idapp, username, params) {
return await User.find({ idapp, username }).then((arrusers) => {
if (arrusers !== null) {
for (const user of arrusers) {
tools.sendNotificationToUser(user._id, params.title, params.content, params.openUrl, params.openUrl2, params.tag, params.actions)
.then(ris => {
if (ris) {
} else {
// already sent the error on calling sendNotificationToUser
}
})
.catch(e => {
console.error(e);
})
}
}
});
}
async function SendMsgToAll(idapp, params) {
const arrusers = await User.find({ idapp },
{
username: 1,
name: 1,
surname: 1,
}
);
let msgsent = 0;
for (const user of arrusers) {
await SendMsgTo(idapp, user.username, params);
msgsent++;
}
return msgsent;
}
router.post('/send', authenticate, async (req, res) => {
const idapp = req.body.idapp;
const params = req.body.params;
let nummsg = 0;
if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) && !User.isTutor(req.user.perm))) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
try {
if (params.typemsg === shared_consts.TypeMsg.SEND_TO_ALL) {
nummsg = await SendMsgToAll(idapp, params);
}
return res.send({ code: server_constants.RIS_CODE_OK, msg: nummsg + ' Msg Inviati !' });
}catch (e) {
return res.send({ code: server_constants.RIS_CODE_ERR, msg: nummsg + ' Msg Inviati !' });
}
});
router.get('/', (req, res) => {
res.json({
data: 'Invalid Request Bad'
});
res.json({
data: 'Invalid Request Bad'
});
});
module.exports = router;

View File

@@ -23,8 +23,6 @@ router.post('/load', async (req, res) => {
let datastat = {
num_tot_lista: await ExtraList.getTotInLista(idapp),
num_reg_lista: await ExtraList.getRegDellaLista(idapp),
num_reg: await User.getUsersRegistered(idapp),
email_non_verif: await User.getEmailNotVerified(idapp),
num_teleg_attivo: await User.getUsersTelegramAttivo(idapp),
@@ -34,7 +32,6 @@ router.post('/load', async (req, res) => {
num_modalita_pagamento: await User.getnumPaymentOk(idapp),
num_part_zoom: await User.getUsersZoom(idapp),
num_part_accepted: await User.getSaw_and_Accepted(idapp),
num_users_dream: await User.getUsersDreams(idapp),
arr_nations: await User.findAllDistinctNationality(idapp),
numreg_untilday: await User.calcnumRegUntilDay(idapp),
reg_daily: await User.calcRegDaily(idapp),

View File

@@ -74,7 +74,6 @@ router.post('/', authenticate, (req, res) => {
}
}
});
});
});

View File

@@ -52,7 +52,7 @@ router.post('/', authenticate, (req, res) => {
.then(record => {
// tools.mylog('REC SAVED :', record.descr);
tools.sendNotificationToUser(todo.userId, 'Todo: ' + record.descr, record.descr, '/todo/' + todo.category, 'todo')
tools.sendNotificationToUser(todo.userId, 'Todo: ' + record.descr, record.descr, '/todo/' + todo.category, '', 'todo', [])
.then(ris => {
if (ris) {
res.send({ record });

View File

@@ -64,7 +64,6 @@ router.post('/', async (req, res) => {
user.ipaddr = tools.getiPAddressUser(req);
user.lasttimeonline = new Date();
user.date_reg = new Date();
user.date_temp_reg = new Date();
user.aportador_iniziale = user.aportador_solidario;
if (user.idapp === tools.AYNI) {
user.profile.paymenttypes = ['paypal'];
@@ -175,7 +174,7 @@ router.post('/', async (req, res) => {
return 1;
}
let already_registered = recextra || user.aportador_solidario === tools.APORTADOR_NONE;
let already_registered = (recextra || user.aportador_solidario === tools.APORTADOR_NONE) && (user.idapp === tools.AYNI);
// Check if is an other people aportador_solidario