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 {User} = require('../models/user'); const {Operator} = require('../models/operator'); const {SendNotif} = require('../models/sendnotif'); const {ObjectID} = require('mongodb'); const sendemail = require('../sendemail'); const shared_consts = require('../tools/shared_nodejs'); const _ = require('lodash'); router.post('/', authenticate, (req, res) => { tools.mylog('INIZIO - SendNotif'); // tools.mylog('req.body', req.body); const body = _.pick(req.body, tools.allfieldSendNotif()); tools.mylog('crea SendNotif'); const myrecnotif = new SendNotif(body); const check = tools.checkUserOk(myrecnotif.sender, req.user.username, res); if (check.exit) return check.ret; // console.log('fieldtochange', fieldtochange); myrecnotif._id = new ObjectID(); return myrecnotif.save().then((writeresult) => { let idobj = writeresult._id; myrecnotif._id = idobj; return SendNotif.findById(idobj).then(async (recnotif) => { // Add this field because I don't want to add into the database return await globalTables.sendNotif(res, body.idapp, req.user, recnotif).then((ris) => { return res.send({code: server_constants.RIS_CODE_OK, notif: '', id: recnotif._id}); }); }); }).catch((e) => { console.log(e.message); // res.status(400).send(e); return res.send({code: server_constants.RIS_CODE_ERR, notif: ''}); }); }); router.get('/setall/:username/:idapp', authenticate, async (req, res) => { const idapp = req.params.idapp; const username = req.params.username; const username_call = req.user.username; try { if (username === username_call) { const arrNotifs = await SendNotif.find({idapp, dest: username, read: false}).lean(); if (arrNotifs) { for (const rec of arrNotifs) { await SendNotif.setNotifAsRead(idapp, username_call, rec._id); } } res.send(true); } } catch (e) { res.status(400).send(e); } }); router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => { tools.mylog('GET NotifS : ', req.params); const username = req.params.username; const lastdataread = req.params.lastdataread; const idapp = req.params.idapp; // var category = req.params.category; if (req.user.idapp !== idapp) { // I'm trying to get something not mine! return res.status(404).send({code: server_constants.RIS_CODE_NOT_MY_USERNAME}); } // Extract all the todos of the userId only return SendNotif.findAllNotifByUsernameIdAndIdApp(username, lastdataread, idapp).then((arrnotif) => { // const wait = new Promise((resolve, reject) => { // setTimeout(() => { res.send({arrnotif}); // }, 2000); // }); }).catch((e) => { console.log(e.message); res.status(400).send(e); }); }); module.exports = router;