- aggiornata la grafica della Home di RISO
- Profilo Completition - Email Verificata - Invita un Amico (invio di email)
54
src/router/accounts_router.js
Executable file
@@ -0,0 +1,54 @@
|
||||
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 mongoose = require('mongoose').set('debug', false);
|
||||
|
||||
const { User } = require('../models/user');
|
||||
const { Circuit } = require('../models/circuit');
|
||||
const { Account } = require('../models/account');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
async function getCircuitRecAdminsInfo(idapp, data) {
|
||||
|
||||
if (data && data.admins) {
|
||||
for (const admin of data.admins) {
|
||||
const myuser = await User.findOne({ idapp, username: admin.username }, { 'profile.img': 1 }).lean();
|
||||
admin.profile = { img: myuser.profile.img };
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
router.post('/loadall', authenticate, async (req, res) => {
|
||||
const idapp = req.body.idapp;
|
||||
|
||||
try {
|
||||
let listaccounts = []
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
|
||||
listaccounts = await Account.find({ idapp }).lean();
|
||||
|
||||
}
|
||||
|
||||
res.send({ listaccounts });
|
||||
|
||||
} catch (e) {
|
||||
console.error('Error in Accounts', e);
|
||||
return res.status(400).send(e);
|
||||
}
|
||||
|
||||
const ris = null;
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
2448
src/router/admin_router.js
Executable file
246
src/router/aitools_router.js
Executable file
@@ -0,0 +1,246 @@
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var { authenticate, authenticate_noerror, auth_default } = require('../middleware/authenticate');
|
||||
|
||||
var mongoose = require('mongoose').set('debug', false);
|
||||
const Subscription = require('../models/subscribers');
|
||||
|
||||
const _ = require('lodash');
|
||||
const { QueryAI } = require('../models/queryai');
|
||||
var { User } = require('../models/user');
|
||||
const { Reaction } = require('../models/reaction');
|
||||
|
||||
const globalTables = require('../tools/globalTables');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const OpenAI = require('openai');
|
||||
|
||||
const { PassThrough } = require('stream');
|
||||
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
router.post('/getlist', authenticate_noerror, async function (req, res, next) {
|
||||
try {
|
||||
let idapp = req.body.idapp;
|
||||
|
||||
let queryAIList = await QueryAI.findAllIdApp(idapp);
|
||||
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
queryAIList,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('/getlist', e);
|
||||
return res.status(500).send({ code: server_constants.RIS_CODE_ERR, msg: e.message });
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
async function getDeepSeekResponse(prompt, options) {
|
||||
try {
|
||||
const deepseek = new OpenAI({
|
||||
baseURL: 'https://api.deepseek.com/v1',
|
||||
apiKey: process.env.DS_API_KEY,
|
||||
defaultHeaders: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!options.withexplain) {
|
||||
prompt = prompt + '\n' + 'Ritornami solo il risultato, senza spiegazione.';
|
||||
}
|
||||
if (options.outputType) {
|
||||
prompt = prompt + '\n' + options.outputType;
|
||||
}
|
||||
|
||||
const completionStream = await deepseek.chat.completions.create({
|
||||
model: options.model || 'deepseek-chat',
|
||||
messages: [
|
||||
{ role: 'system', content: options?.contestsystem || '' },
|
||||
{ role: 'user', content: prompt },
|
||||
],
|
||||
temperature: options?.temp || 0.3,
|
||||
max_tokens: options?.max_tokens || 1000,
|
||||
stream: options?.stream || false,
|
||||
});
|
||||
|
||||
if (options?.stream) {
|
||||
// Creiamo un PassThrough stream per inviare i chunk al frontend
|
||||
/*const stream = new PassThrough();
|
||||
completionStream.on('data', (chunk) => {
|
||||
stream.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
||||
});
|
||||
completionStream.on('end', () => {
|
||||
stream.end();
|
||||
});
|
||||
return stream;*/
|
||||
|
||||
return completionStream;
|
||||
} else {
|
||||
if (!completionStream || !completionStream.choices || completionStream.choices.length === 0) {
|
||||
throw new Error('Invalid response from DeepSeek API');
|
||||
}
|
||||
return completionStream.choices[0];
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('DeepSeek Error:', error.response?.data || error.message);
|
||||
throw new Error('Failed to get AI response');
|
||||
}
|
||||
}
|
||||
|
||||
router.post('/ds', authenticate, async (req, res) => {
|
||||
const { prompt, options } = req.body;
|
||||
|
||||
const isollama = options.model.startsWith('gemma3');
|
||||
|
||||
if (isollama) {
|
||||
// Endpoint per generare una risposta dal modello Ollama
|
||||
const { prompt } = req.body;
|
||||
// const model = "phi:3.8b-mini-4k"; // Modello predefinito
|
||||
const model = options.model;
|
||||
|
||||
if (!prompt) {
|
||||
return res.status(400).json({ error: 'Il prompt è richiesto.' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Chiamata all'API di Ollama
|
||||
const ollama = spawn('curl', [
|
||||
'-X',
|
||||
'POST',
|
||||
'http://localhost:11434/api/generate',
|
||||
'-H',
|
||||
'Content-Type: application/json',
|
||||
'-d',
|
||||
JSON.stringify({
|
||||
model: model,
|
||||
prompt: prompt,
|
||||
stream: false, // Imposta a true se vuoi una risposta in streaming
|
||||
}),
|
||||
]);
|
||||
|
||||
let data = '';
|
||||
let error = '';
|
||||
|
||||
ollama.stdout.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
|
||||
ollama.stderr.on('data', (chunk) => {
|
||||
error += chunk;
|
||||
});
|
||||
|
||||
ollama.on('close', (code) => {
|
||||
if (code !== 0) {
|
||||
console.error(`Errore Ollama: ${error}`);
|
||||
return res.status(500).json({ error: 'Errore nella generazione del modello.' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Ollama restituisce una risposta JSON
|
||||
const response = JSON.parse(data);
|
||||
const risp = response?.error ? response?.error : response?.response;
|
||||
//res.json({ response: response.response }); // Invia solo la risposta al frontend
|
||||
|
||||
if (response?.error) {
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: risp,
|
||||
});
|
||||
} else {
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
choice: risp,
|
||||
});
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.error('Errore nel parsing della risposta di Ollama:', parseError);
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: 'Errore nella risposta del modello.',
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: 'Errore interno del server.',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const isstream = options && options?.stream;
|
||||
|
||||
if (isstream) {
|
||||
// Se lo streaming è abilitato, restituiamo un flusso di dati
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
|
||||
try {
|
||||
// Ottieni il flusso di dati da DeepSeek
|
||||
const completionStream = await getDeepSeekResponse(prompt, options);
|
||||
|
||||
for await (const chunk of completionStream) {
|
||||
if (chunk.choices && chunk.choices[0]) {
|
||||
const data = JSON.stringify({ choice: chunk.choices[0] });
|
||||
res.write(`data: ${data}\n\n`);
|
||||
try {
|
||||
const msg = chunk.choices[0].delta.content;
|
||||
if (msg) {
|
||||
console.log(msg);
|
||||
// await tools.sleep(10000)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error: ' + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
} catch (error) {
|
||||
const errorstr = 'API Error:' + (error.response?.data || error.message);
|
||||
console.error(errorstr);
|
||||
|
||||
// In caso di errore durante lo streaming, invia un messaggio di errore
|
||||
const errorData = JSON.stringify({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: errorstr,
|
||||
});
|
||||
res.write(`data: ${errorData}\n\n`);
|
||||
res.end();
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
// Se lo streaming non è abilitato, restituisci la risposta completa
|
||||
const choice = await getDeepSeekResponse(prompt, options);
|
||||
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
choice,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorstr = 'API Error:' + (error.response?.data || error.message);
|
||||
console.error(errorstr);
|
||||
|
||||
// In caso di errore senza streaming, restituisci un errore standard
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: errorstr,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
82
src/router/api/actions.js
Executable file
@@ -0,0 +1,82 @@
|
||||
const mongoose = require('mongoose').set('debug', false)
|
||||
const Subscription = require('../../models/subscribers');
|
||||
|
||||
//const { ListaIngresso } = require('../../models/listaingresso');
|
||||
const { Graduatoria } = require('../../models/graduatoria');
|
||||
const { User } = require('../../models/user');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const tools = require('../../tools/general');
|
||||
|
||||
|
||||
module.exports = {
|
||||
doOtherThingsAfterDeleted: async function (tablename, rec, notifBot, req) {
|
||||
try {
|
||||
|
||||
const { User } = require('../../models/user');
|
||||
const telegrambot = require('../../telegram/telegrambot');
|
||||
|
||||
let ris = null;
|
||||
|
||||
// const { ListaIngresso } = require('../../models/listaingresso');
|
||||
|
||||
if (tablename === 'users') {
|
||||
|
||||
// await ListaIngresso.deleteUserInListaIngresso(rec.idapp, rec.username);
|
||||
|
||||
// Controlla se aveva invitati, li regala a quello sopra
|
||||
const arrap = await User.getDownlineByUsername(rec.idapp, rec.username);
|
||||
for (let user of arrap) {
|
||||
|
||||
await User.findOneAndUpdate({
|
||||
idapp: rec.idapp,
|
||||
username: user.username
|
||||
}, { $set: { aportador_solidario: rec.aportador_solidario } }, { new: false });
|
||||
|
||||
let msg = 'Spostato ' + user.name + ' ' + user.surname + ' sotto di ' + rec.aportador_solidario;
|
||||
telegrambot.sendMsgTelegramToTheManagers(rec.idapp, msg);
|
||||
}
|
||||
|
||||
// Delete also all the subscribers record of this User
|
||||
ris = Subscription.deleteOne({ userId: rec._id })
|
||||
}
|
||||
|
||||
if (!!ris) {
|
||||
|
||||
if (notifBot) {
|
||||
// Send Notification to the BOT
|
||||
let nomerecord = '';
|
||||
if ((tablename === 'users') || (tablename === 'extralist')) {
|
||||
nomerecord = rec.name + ' ' + rec.surname + ' (' + rec.username + ')';
|
||||
}
|
||||
|
||||
addtext = 'Eliminato il Record "' + nomerecord + '" dalla tabella ' + tablename + '\n' +
|
||||
'Eseguito da ' + req.user.username + ' \n';
|
||||
await telegrambot.sendMsgTelegramToTheManagers(rec.idapp, addtext);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return ris
|
||||
|
||||
} catch (e) {
|
||||
console.error(e.message);
|
||||
return false
|
||||
}
|
||||
|
||||
},
|
||||
doOtherThingsAfterDuplicated: async function (tablename, myrec, mynewrec) {
|
||||
try {
|
||||
if (tablename === 'users') {
|
||||
// Delete also all the subscribers record of this User
|
||||
|
||||
}
|
||||
return { myrec }
|
||||
|
||||
} catch (e) {
|
||||
return false
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
497
src/router/api_router.js
Normal file
@@ -0,0 +1,497 @@
|
||||
const express = require('express');
|
||||
const { authenticate, authenticate_noerror } = require('../middleware/authenticate');
|
||||
|
||||
const router = express.Router();
|
||||
const PageView = require('../models/PageView');
|
||||
|
||||
const multer = require('multer');
|
||||
const XLSX = require('xlsx');
|
||||
|
||||
const upload = multer({ dest: 'uploads/' });
|
||||
|
||||
const Product = require('../models/product');
|
||||
const Author = require('../models/author');
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
const { MyPage } = require('../models/mypage');
|
||||
const { MyElem } = require('../models/myelem');
|
||||
|
||||
const axios = require('axios');
|
||||
|
||||
router.post('/test-lungo', authenticate, (req, res) => {
|
||||
const timeout = req.body.timeout;
|
||||
|
||||
console.log(`🕙 Richiesta iniziata con timeout=${timeout}`);
|
||||
|
||||
// Simuliamo un'elaborazione lunga
|
||||
const durataMs = timeout - 2000;
|
||||
setTimeout(() => {
|
||||
console.log(`✅ Elaborazione completata di ${durataMs} ms`);
|
||||
res.json({ ok: true, message: `✅ Richiesta completata con successo! (${durataMs})` });
|
||||
}, durataMs);
|
||||
|
||||
// Verifico se la richiesta va a buon fine
|
||||
setTimeout(() => {
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({ ok: false, message: "❌ Errore durante l'elaborazione della richiesta!" });
|
||||
}
|
||||
}, durataMs + 1000);
|
||||
});
|
||||
|
||||
router.post('/track-pageview', authenticate_noerror, async (req, res) => {
|
||||
const { url, userAgent, idapp, referrer } = req.body;
|
||||
const ip = req.ip || req.headers['x-forwarded-for'] || 'unknown';
|
||||
|
||||
try {
|
||||
const pageView = new PageView({
|
||||
url,
|
||||
ip,
|
||||
idapp,
|
||||
referrer,
|
||||
userId: req.user ? req.user._id : '',
|
||||
username: req.user ? req.user.username : '',
|
||||
userAgent,
|
||||
});
|
||||
|
||||
await pageView.save();
|
||||
|
||||
return res.status(200).json({ message: '' });
|
||||
} catch (error) {
|
||||
console.error('Errore nel salvataggio della visita:', error);
|
||||
return res.status(500).json({ error: 'Impossibile registrare la visita' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/pageviews/stats', authenticate_noerror, async (req, res) => {
|
||||
const { userId, idapp, unique } = req.query;
|
||||
|
||||
try {
|
||||
const matchStage = { idapp };
|
||||
if (userId) {
|
||||
matchStage.$or = [{ userId }, { username: userId }];
|
||||
}
|
||||
|
||||
// Definiamo la base della pipeline
|
||||
const basePipeline = [{ $match: matchStage }];
|
||||
|
||||
const today = startOfDay(new Date());
|
||||
const weekAgo = startOfDay(subDays(new Date(), 7));
|
||||
const monthAgo = startOfDay(subDays(new Date(), 30));
|
||||
|
||||
// Funzione dinamica per creare pipeline di conteggio
|
||||
const countStage = (date) => {
|
||||
const match = { timestamp: { $gte: date } };
|
||||
if (!unique) {
|
||||
return [{ $match: match }, { $count: 'count' }];
|
||||
}
|
||||
return [
|
||||
{ $match: match },
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
url: '$url',
|
||||
user: { $ifNull: ['$userId', '$ip'] },
|
||||
date: { $dateToString: { format: '%Y-%m-%d', date: '$timestamp' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $count: 'count' },
|
||||
];
|
||||
};
|
||||
|
||||
// Pipeline completa
|
||||
const timeStatsPipeline = [
|
||||
...basePipeline,
|
||||
{
|
||||
$facet: {
|
||||
total: !unique
|
||||
? [{ $count: 'count' }]
|
||||
: [
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
url: '$url',
|
||||
user: { $ifNull: ['$userId', '$ip'] },
|
||||
date: { $dateToString: { format: '%Y-%m-%d', date: '$timestamp' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $count: 'count' },
|
||||
],
|
||||
today: countStage(today),
|
||||
week: countStage(weekAgo),
|
||||
month: countStage(monthAgo),
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// Eseguiamo solo la parte delle statistiche temporali
|
||||
const timeStatsResult = await PageView.aggregate(timeStatsPipeline);
|
||||
|
||||
// Ora costruiamo la pipeline completa per topPages (con o senza unique)
|
||||
let topPagesPipeline = [...basePipeline];
|
||||
|
||||
if (unique) {
|
||||
topPagesPipeline = [
|
||||
...topPagesPipeline,
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
url: '$url',
|
||||
userId: { $ifNull: ['$userId', '$ip'] },
|
||||
date: {
|
||||
$dateToString: {
|
||||
format: '%Y-%m-%d',
|
||||
date: '$timestamp',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $replaceRoot: { newRoot: '$_id' } },
|
||||
];
|
||||
}
|
||||
|
||||
// Aggiungi il group finale per contare le pagine
|
||||
const topPagesResult = await PageView.aggregate([
|
||||
...topPagesPipeline,
|
||||
{
|
||||
$group: {
|
||||
_id: '$url',
|
||||
count: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{ $sort: { count: -1 } },
|
||||
{ $limit: 10 },
|
||||
]);
|
||||
|
||||
// Formattazione dei risultati
|
||||
const formatCount = (arr) => (arr && arr.length > 0 ? arr[0].count || 0 : 0);
|
||||
|
||||
const stats = {
|
||||
total: formatCount(timeStatsResult[0]?.total),
|
||||
today: formatCount(timeStatsResult[0]?.today),
|
||||
week: formatCount(timeStatsResult[0]?.week),
|
||||
month: formatCount(timeStatsResult[0]?.month),
|
||||
topPages: topPagesResult,
|
||||
};
|
||||
|
||||
res.json(stats);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Errore nel calcolo delle statistiche' });
|
||||
}
|
||||
});
|
||||
|
||||
function startOfDay(date) {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
}
|
||||
|
||||
function subDays(date, days) {
|
||||
const newDate = new Date(date);
|
||||
newDate.setDate(newDate.getDate() - days);
|
||||
return newDate;
|
||||
}
|
||||
|
||||
router.delete('/mypage/:id', authenticate, async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
// Trova il record di MyPage da cancellare
|
||||
const pageToDelete = await MyPage.findByIdAndDelete(id);
|
||||
|
||||
if (!pageToDelete) return res.status(404).json({ error: 'Pagina non trovata' });
|
||||
if (!pageToDelete) {
|
||||
return res.status(404).json({ error: 'Pagina non trovata' });
|
||||
} else {
|
||||
await MyElem.deleteAllFromThisPage(id);
|
||||
}
|
||||
|
||||
res.json({ message: `Pagina eliminata con successo: ${pageToDelete.path}` });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: "Errore durante l'eliminazione della pagina" });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/pageviews/users', authenticate_noerror, async (req, res) => {
|
||||
try {
|
||||
const { idapp } = req.query;
|
||||
|
||||
// Trova tutte le entry con idapp e prendi userId e username
|
||||
const usersData = await PageView.find({ idapp }, { userId: 1, username: 1, _id: 0 }).lean();
|
||||
|
||||
// Usa un Map per garantire unicità basata su userId
|
||||
const uniqueUsersMap = new Map();
|
||||
|
||||
usersData.forEach(({ userId, username }) => {
|
||||
if (userId && !uniqueUsersMap.has(userId)) {
|
||||
uniqueUsersMap.set(userId, { userId, username });
|
||||
}
|
||||
});
|
||||
|
||||
// Converte la Map in array
|
||||
const uniqueUsers = Array.from(uniqueUsersMap.values());
|
||||
|
||||
res.json(uniqueUsers);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Errore nel recupero degli utenti' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/pageviews/weekly-top-pages', authenticate_noerror, async (req, res) => {
|
||||
const { idapp, userId, unique, year, week } = req.query;
|
||||
|
||||
try {
|
||||
const matchStage = { idapp };
|
||||
if (userId) {
|
||||
matchStage.$or = [{ userId }, { username: userId }];
|
||||
}
|
||||
|
||||
const pipeline = [];
|
||||
|
||||
// Filtro base
|
||||
pipeline.push({ $match: matchStage });
|
||||
|
||||
// Estrai settimana e anno
|
||||
pipeline.push({
|
||||
$addFields: {
|
||||
week: { $isoWeek: '$timestamp' },
|
||||
year: { $isoWeekYear: '$timestamp' },
|
||||
},
|
||||
});
|
||||
|
||||
// Filtra per settimana e anno se specificati
|
||||
if (year && week) {
|
||||
pipeline.push({
|
||||
$match: {
|
||||
year: parseInt(year),
|
||||
week: parseInt(week),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (unique === 'true') {
|
||||
// Visite uniche: 1 per utente/giorno/pagina
|
||||
pipeline.push({
|
||||
$group: {
|
||||
_id: {
|
||||
url: '$url',
|
||||
user: { $ifNull: ['$userId', '$ip'] },
|
||||
day: { $dateToString: { format: '%Y-%m-%d', date: '$timestamp' } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Riformatta per conteggio
|
||||
pipeline.push({
|
||||
$group: {
|
||||
_id: '$_id.url',
|
||||
count: { $sum: 1 },
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Visite totali: tutte le occorrenze
|
||||
pipeline.push({
|
||||
$group: {
|
||||
_id: '$url',
|
||||
count: { $sum: 1 },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Ordina per numero visite
|
||||
pipeline.push({ $sort: { count: -1 } });
|
||||
|
||||
// Aggiungi metadati settimana/anno se presenti
|
||||
if (year && week) {
|
||||
pipeline.push({
|
||||
$addFields: {
|
||||
year: parseInt(year),
|
||||
week: parseInt(week),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const result = await PageView.aggregate(pipeline);
|
||||
|
||||
res.json(
|
||||
result.map((r) => ({
|
||||
url: r._id,
|
||||
count: r.count,
|
||||
year: r.year,
|
||||
week: r.week,
|
||||
}))
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Errore nel calcolo delle statistiche settimanali' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/api/convert-csv-to-xls', upload.single('csv'), (req, res) => {
|
||||
try {
|
||||
const csvFilePath = req.file.path;
|
||||
|
||||
// Leggi il CSV con SheetJS
|
||||
const csvData = fs.readFileSync(csvFilePath, 'utf-8');
|
||||
const worksheet = XLSX.utils.csv_to_sheet(csvData);
|
||||
|
||||
// Crea un file Excel
|
||||
const workbook = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
|
||||
|
||||
// Imposta la risposta come file XLS
|
||||
const xlsFilePath = path.join(__dirname, 'converted', 'output.xls');
|
||||
XLSX.writeFile(workbook, xlsFilePath);
|
||||
|
||||
// Restituisci il file XLS al frontend come risposta
|
||||
res.download(xlsFilePath, 'converted-file.xls', (err) => {
|
||||
if (err) {
|
||||
console.error('Errore nel download del file:', err);
|
||||
res.status(500).send('Errore nel download del file');
|
||||
}
|
||||
|
||||
// Pulisci il file temporaneo
|
||||
fs.unlinkSync(csvFilePath);
|
||||
fs.unlinkSync(xlsFilePath);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Errore nella conversione del file:', error);
|
||||
res.status(500).send('Errore nella conversione del file');
|
||||
}
|
||||
});
|
||||
|
||||
// Funzione per "escapare" i caratteri speciali
|
||||
const escapeRegExp = (string) => {
|
||||
return string.replace(/[.*+?^=!:${}()|\[\]\/\\]/g, '\\$&'); // Escape dei caratteri speciali
|
||||
};
|
||||
|
||||
// API per la ricerca dei libri
|
||||
router.post('/search-books', authenticate, async (req, res) => {
|
||||
const { books } = req.body;
|
||||
|
||||
if (!books || books.length === 0) {
|
||||
return res.status(400).json({ error: 'Nessun dato fornito per la ricerca' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Crea un array per raccogliere i risultati
|
||||
let results = [];
|
||||
|
||||
let product = null;
|
||||
|
||||
for (const book of books) {
|
||||
let trovatoISBN = false;
|
||||
let trovato = false;
|
||||
let productfind = null;
|
||||
|
||||
for (let field of book) {
|
||||
|
||||
field = field.trim();
|
||||
let valido = typeof field === 'string' && field.length > 4 && field.length < 50;
|
||||
if (valido) {
|
||||
// Cerca il primo record che corrisponde per ISBN o titolo
|
||||
if (true) {
|
||||
if (!trovatoISBN) {
|
||||
let productInfoarrISBN = await Product.find({
|
||||
'productInfo.code': field.toUpperCase(),
|
||||
$or: [{ deleted: false }, { deleted: { $exists: false } }],
|
||||
}).exec();
|
||||
|
||||
// Priorità se lo trovo per ISBN:
|
||||
if (productInfoarrISBN.length === 1) {
|
||||
productfind = productInfoarrISBN[0];
|
||||
trovatoISBN = true;
|
||||
trovato = true;
|
||||
}
|
||||
}
|
||||
if (!trovatoISBN && !trovato) {
|
||||
// Prima cerca se è esattamente cosi
|
||||
let productarrTitle = await Product.find({
|
||||
$or: [{ deleted: false }, { deleted: { $exists: false } }],
|
||||
'productInfo.name': field,
|
||||
}).exec();
|
||||
if (productarrTitle.length === 1) {
|
||||
productfind = productarrTitle[0];
|
||||
trovato = true;
|
||||
} else {
|
||||
if (productarrTitle.length > 1) {
|
||||
// Prendi l'Ultimo !
|
||||
productfind = productarrTitle[productarrTitle.length - 1];
|
||||
trovato = true;
|
||||
}
|
||||
}
|
||||
if (!trovato) {
|
||||
// Altrimenti per Titolo
|
||||
productarrTitle = await Product.find({
|
||||
$or: [{ deleted: false }, { deleted: { $exists: false } }],
|
||||
'productInfo.name': new RegExp(`.*${escapeRegExp(tools.removeAccents(field.toUpperCase()))}.*`, 'i'),
|
||||
}).exec();
|
||||
if (productarrTitle.length === 1) {
|
||||
productfind = productarrTitle[0];
|
||||
trovato = true;
|
||||
} else {
|
||||
if (productarrTitle.length > 1) {
|
||||
// Prendi l'Ultimo !
|
||||
productfind = productarrTitle[productarrTitle.length - 1];
|
||||
trovato = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (trovato) {
|
||||
if (productfind) {
|
||||
product = await Product.findOne({ _id: productfind._id }).exec();
|
||||
if (product) {
|
||||
const existingResult = results.find((r) => r._id.toString() === product._id.toString());
|
||||
if (!existingResult) {
|
||||
let titolo = product.productInfo.name;
|
||||
results.push({
|
||||
...product,
|
||||
_id: product._id,
|
||||
title: titolo,
|
||||
isbn: product.isbn,
|
||||
authors: await Promise.all(
|
||||
product.productInfo.idAuthors.map(async (authorId) => {
|
||||
const author = await Author.findById(authorId).exec();
|
||||
return author ? `${author.name} ${author.surname}`.trim() : '';
|
||||
})
|
||||
),
|
||||
select: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//
|
||||
}
|
||||
|
||||
res.status(200).json(results); // Restituisci i risultati trovati
|
||||
} catch (err) {
|
||||
console.error('Errore durante la ricerca dei libri:', err);
|
||||
res.status(500).json({ error: 'Errore interno del server' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/chatbot', authenticate, async (req, res) => {
|
||||
try {
|
||||
const response = await axios.post('http://localhost:5005/webhooks/rest/webhook', {
|
||||
sender: 'user',
|
||||
message: req.body.payload.message,
|
||||
});
|
||||
|
||||
res.json(response.data);
|
||||
} catch (error) {
|
||||
console.error(error?.message);
|
||||
res.status(500).send('Errore nella comunicazione con Rasa');
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
19
src/router/articleRoutes.js
Normal file
@@ -0,0 +1,19 @@
|
||||
const express = require("express");
|
||||
const { getArticlesSalesHandler, exportArticlesSalesByJSON, viewTable, saveTable, queryTable, updateAllBookRoute, mssqlmigrateTables } = require("../controllers/articleController");
|
||||
const { authenticate } = require("../middleware/authenticate");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.post("/articles-sales", authenticate, getArticlesSalesHandler);
|
||||
|
||||
router.post("/export-articles-sales-json", authenticate, exportArticlesSalesByJSON);
|
||||
|
||||
router.post("/view-table", authenticate, viewTable);
|
||||
router.post("/save-table", authenticate, saveTable);
|
||||
router.post("/query", authenticate, queryTable);
|
||||
router.post("/updateAllBook", authenticate, updateAllBookRoute);
|
||||
|
||||
router.post("/mssqlmigrateTables", authenticate, mssqlmigrateTables);
|
||||
|
||||
|
||||
module.exports = router;
|
||||
139
src/router/booking_router.js
Executable file
@@ -0,0 +1,139 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
const server_constants = require('../tools/server_constants');
|
||||
|
||||
const { authenticate, authenticate_withUser } = require('../middleware/authenticate');
|
||||
|
||||
const { Booking } = require('../models/booking');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const sendemail = require('../sendemail');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const sendNotifBooking = async (res, idapp, user, recbooking) => {
|
||||
//++Todo: tools.sendNotificationToUser
|
||||
|
||||
// Send Email
|
||||
if (recbooking.booked)
|
||||
return await sendemail.sendEmail_Booking(res, user.lang, user.email, user, idapp, recbooking);
|
||||
else
|
||||
return await sendemail.sendEmail_CancelBooking(res, user.lang, user.email, user, idapp, recbooking);
|
||||
};
|
||||
|
||||
router.post('/', authenticate_withUser, (req, res) => {
|
||||
// tools.mylog('INIZIO - booking');
|
||||
// tools.mylog('req.body', req.body);
|
||||
const myrec = _.pick(req.body, tools.allfieldBooking());
|
||||
const id = myrec.id_bookedevent;
|
||||
const fieldtochange = _.pick(myrec, tools.allfieldBookingChange());
|
||||
|
||||
tools.mylog('crea Booking');
|
||||
const booking = new Booking(myrec);
|
||||
|
||||
const check = tools.checkUserOk(booking.userId, req.user._id, res);
|
||||
if (check.exit) return check.ret;
|
||||
|
||||
// console.log('fieldtochange', fieldtochange);
|
||||
|
||||
// Modify:
|
||||
return Booking.findOne({ id_bookedevent: id, userId: req.user._id })
|
||||
.then(trovato => {
|
||||
// console.log('trovato', trovato);
|
||||
if (trovato) {
|
||||
return Booking.findOneAndUpdate({ id_bookedevent: id }, { $set: fieldtochange }, {
|
||||
new: true,
|
||||
upsert: true
|
||||
}).then((recbooking) => {
|
||||
// tools.mylog('booking:', booking);
|
||||
// tools.mylog('already exist');
|
||||
sendNotifBooking(res, myrec.idapp, req.user, myrec);
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id });
|
||||
});
|
||||
} else {
|
||||
// save to database a new record
|
||||
tools.mylog('save to database a new record');
|
||||
booking._id = new ObjectId();
|
||||
return booking.save().then((writeresult) => {
|
||||
let idobj = writeresult._id;
|
||||
|
||||
Booking.findById(idobj)
|
||||
.then((recbooking) => {
|
||||
sendNotifBooking(res, myrec.idapp, req.user, writeresult);
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: writeresult._id });
|
||||
});
|
||||
});
|
||||
}
|
||||
}).catch((e) => {
|
||||
console.error('Error', e);
|
||||
return res.status(400).send();
|
||||
});
|
||||
});
|
||||
|
||||
router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
|
||||
console.log('DELETE Booking');
|
||||
const id = req.params.id;
|
||||
const notify = req.params.notify;
|
||||
const idapp = req.params.idapp;
|
||||
|
||||
Booking.findOneAndDelete({_id: id}).then((recbooking) => {
|
||||
if (!recbooking) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
if (notify === '1') {
|
||||
recbooking.booked = false;
|
||||
sendNotifBooking(res, idapp, req.user, recbooking);
|
||||
}
|
||||
|
||||
tools.mylog('DELETED ', recbooking._id);
|
||||
|
||||
res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recbooking._id });
|
||||
|
||||
}).catch((e) => {
|
||||
return 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 BOOKINGS : ', 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
|
||||
// const bookedevent = Booking.findAllByUserIdAndIdApp(userId, idapp, sall);
|
||||
// const eventlist = MyEvent.findAllIdApp(idapp);
|
||||
// const operators = Operator.findAllIdApp(idapp);
|
||||
// const wheres = Where.findAllIdApp(idapp);
|
||||
// const contribtype = Contribtype.findAllIdApp(idapp);
|
||||
//
|
||||
// return Promise.all([bookedevent, eventlist, operators, wheres, contribtype])
|
||||
// .then((arrdata) => {
|
||||
// console.table(arrdata);
|
||||
// res.send({ bookedevent: arrdata[0], eventlist: arrdata[1], operators: arrdata[2], wheres: arrdata[3], contribtype: arrdata[4] });
|
||||
// })
|
||||
// .catch((e) => {
|
||||
// console.log(e.message);
|
||||
// res.status(400).send(e);
|
||||
// });
|
||||
//
|
||||
// });
|
||||
//
|
||||
|
||||
module.exports = router;
|
||||
646
src/router/cart_router.js
Executable file
@@ -0,0 +1,646 @@
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const sendemail = require('../sendemail');
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var { Project } = require('../models/project');
|
||||
|
||||
const Scontistica = require('../models/scontistica');
|
||||
|
||||
var { authenticate, auth_default } = require('../middleware/authenticate');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const Product = require('../models/product');
|
||||
const Order = require('../models/order');
|
||||
const Variant = require('../models/variant');
|
||||
const { User } = require('../models/user');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
/*const Department = require('../models/Department')
|
||||
const Category = require('../models/Category')
|
||||
const TypedError = require('../modules/ErrorHandler')
|
||||
const paypal_config = require('../configs/paypal-config')
|
||||
const paypal = require('paypal-rest-sdk')
|
||||
*/
|
||||
|
||||
const CartClass = require('../modules/Cart');
|
||||
const Cart = require('../models/cart');
|
||||
const OrdersCart = require('../models/orderscart');
|
||||
|
||||
//GET cart
|
||||
router.get('/:userId', authenticate, async function (req, res, next) {
|
||||
try {
|
||||
let userId = req.params.userId;
|
||||
let idapp = req.user.idapp;
|
||||
|
||||
const cart = await Cart.getCartByUserId(userId, idapp);
|
||||
if (cart) return res.send({ code: server_constants.RIS_CODE_OK, cart });
|
||||
else return res.send({ code: server_constants.RIS_CODE_OK, cart: null });
|
||||
} catch (err) {
|
||||
console.error('Err', err);
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null });
|
||||
}
|
||||
});
|
||||
|
||||
async function aggiornaCarrello(mycartpar, userId, idapp) {
|
||||
try {
|
||||
let mycart = mycartpar;
|
||||
|
||||
if (!mycart) mycart = await Cart.getCartByUserId(userId, idapp);
|
||||
|
||||
if (!mycart) return null;
|
||||
|
||||
mycart = await Cart.getCartCompletoByCartId(mycart._id, idapp);
|
||||
|
||||
let newCart = await CartClass.constructByCart(mycart);
|
||||
if (newCart) return newCart.aggiornaCarrello();
|
||||
|
||||
return newCart;
|
||||
} catch (e) {
|
||||
console.error('Err AggiornaCarrello', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
//POST cart
|
||||
router.post('/:userId', authenticate, async function (req, res, next) {
|
||||
try {
|
||||
let idapp = req.body.idapp;
|
||||
let userId = req.params.userId;
|
||||
let addqty = req.body.addqty;
|
||||
let subqty = req.body.subqty;
|
||||
let order = req.body.order;
|
||||
|
||||
let mycart = await Cart.getCartByUserId(userId, idapp);
|
||||
|
||||
if (!order) {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, cart: null });
|
||||
}
|
||||
|
||||
let codice_sconto = mycart?.codice_sconto;
|
||||
|
||||
// const myorder = Order.getOrderByID(order._id);
|
||||
if (!addqty && !subqty && order) {
|
||||
order._id = await Order.createOrder(order, codice_sconto);
|
||||
if (!order._id) {
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, cart: 0 });
|
||||
}
|
||||
}
|
||||
|
||||
let cart = null;
|
||||
let product = null;
|
||||
// no cart save empty cart to database then return response
|
||||
let nuovo = false;
|
||||
if (!mycart) {
|
||||
let oldCart = new CartClass(order);
|
||||
cart = await Cart.createCart(oldCart.generateModel());
|
||||
|
||||
mycart = await Cart.getCartByUserId(userId, idapp);
|
||||
nuovo = true;
|
||||
}
|
||||
|
||||
let newCart = await CartClass.constructByCart(mycart);
|
||||
// order = await Product.updateProductInOrder(order);
|
||||
if (!nuovo) {
|
||||
// Controlla se sto inserendo un prodotto con 2 Negozi, non permetterlo !
|
||||
if (newCart.isSameStorehouse(order)) {
|
||||
if (addqty) {
|
||||
myord = await newCart.addqty(order);
|
||||
} else if (subqty) {
|
||||
myord = await newCart.subqty(order);
|
||||
} else {
|
||||
const ind = await newCart.addItem(order);
|
||||
const arrord = await Order.getTotalOrderById(order._id);
|
||||
myord = arrord ? arrord[0] : null;
|
||||
}
|
||||
} else {
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
cart: null,
|
||||
myord: null,
|
||||
msgerr: 'Non è possibile acquistare nello stesso ordine, su negozi differenti!',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
await newCart.updatecarttotals(true);
|
||||
await newCart.updateExtraOrder();
|
||||
const arrord = await Order.getTotalOrderById(order._id);
|
||||
myord = arrord ? arrord[0] : null;
|
||||
}
|
||||
cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel());
|
||||
|
||||
if (cart) {
|
||||
const carttot = await Cart.getCartByUserId(userId, idapp);
|
||||
if (order.idProduct) product = await Product.getProductById(order.idProduct);
|
||||
else if (order.product) product = await Product.getProductById(order.product._id);
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, myord, product });
|
||||
} else {
|
||||
console.error('Err:', err);
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null, myord: null });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Err:', e);
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, cart: 0 });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:userId', authenticate, async function (req, res) {
|
||||
console.log('DELETE Item');
|
||||
let idapp = req.query.idapp;
|
||||
let userId = req.params.userId;
|
||||
let orderId = req.query.orderId;
|
||||
|
||||
const mycart = await Cart.getCartByUserId(userId, idapp);
|
||||
|
||||
const ord = await Order.findOne({ _id: orderId });
|
||||
let idProduct = '';
|
||||
let product = null;
|
||||
if (ord) idProduct = ord.idProduct;
|
||||
|
||||
// Rimuovere l'Ordine
|
||||
const recremoved = await Order.deleteOne({ _id: orderId });
|
||||
if (recremoved) {
|
||||
// Rimuovere l'id sul Carrello
|
||||
|
||||
let newCart = await CartClass.constructByCart(mycart);
|
||||
await newCart.removeItem(orderId);
|
||||
let carttot = null;
|
||||
const cart = await Cart.updateCartByCartId(mycart._id, newCart.generateModel());
|
||||
|
||||
carttot = await Cart.getCartByUserId(userId, idapp);
|
||||
|
||||
if (idProduct) {
|
||||
product = await Product.getProductById(idProduct);
|
||||
}
|
||||
|
||||
console.log('carttot', carttot);
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, cart: carttot, product });
|
||||
}
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, cart: null });
|
||||
});
|
||||
|
||||
//PUT cart
|
||||
router.put('/:userId', authenticate, async function (req, res, next) {
|
||||
let userId = req.params.userId;
|
||||
let requestProduct = req.body;
|
||||
let { productId, color, size } = requestProduct.product;
|
||||
|
||||
try {
|
||||
try {
|
||||
const cart = await Cart.getCartByUserId(userId);
|
||||
|
||||
try {
|
||||
const myprod = await Product.getProductByID(productId);
|
||||
|
||||
let newCart = oldCart.add(myprod, productId, { color, size });
|
||||
|
||||
//exist cart in databse
|
||||
if (cart.length > 0) {
|
||||
try {
|
||||
const result = await Cart.updateCartByUserId(userId, {
|
||||
items: newCart.items,
|
||||
totalQty: newCart.totalQty,
|
||||
totalPrice: newCart.totalPrice,
|
||||
totalPriceCalc: newCart.totalPriceCalc,
|
||||
totalPriceIntero: newCart.totalPriceIntero,
|
||||
userId: userId,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
}
|
||||
} else {
|
||||
//no cart in database
|
||||
let newCartobj = {
|
||||
items: newCart.items,
|
||||
totalQty: newCart.totalQty,
|
||||
totalPrice: newCart.totalPrice,
|
||||
totalPriceCalc: newCart.totalPriceCalc,
|
||||
totalPriceIntero: newCart.totalPriceIntero,
|
||||
userId: userId,
|
||||
};
|
||||
try {
|
||||
const resultCart = await Cart.createCart(newCartobj);
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
}
|
||||
res.status(201).json(resultCart);
|
||||
}
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
}
|
||||
|
||||
const product = await Product.getProductById(productId);
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, product });
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
}
|
||||
|
||||
let oldCart = new CartClass(c || {});
|
||||
} catch (e) {
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:userId/app_sc', authenticate, async function (req, res, next) {
|
||||
let idapp = req.body.idapp;
|
||||
let cart_id = req.body.cart_id;
|
||||
let userId = req.params.userId;
|
||||
|
||||
let codice_sconto = req.body.code;
|
||||
let options = req.body.options;
|
||||
|
||||
let mycart = null;
|
||||
let valido = false;
|
||||
let errmsg = '';
|
||||
let recscontisticaTrovata = null;
|
||||
|
||||
try {
|
||||
let mycart = await Cart.getCartCompletoByCartId(cart_id, idapp);
|
||||
// let mycart = await Cart.findOne({ _id: cart_id }).lean();
|
||||
|
||||
if (codice_sconto === 'RIMUOVI') {
|
||||
mycart = await Cart.findOneAndUpdate({ _id: cart_id }, { $set: { codice_sconto: '' } }, { new: true }).lean();
|
||||
mycart = await aggiornaCarrello(mycart, userId, idapp);
|
||||
return res.send({ mycart, valido, msg: 'Codice Sconto rimosso', rimuovi: true });
|
||||
}
|
||||
|
||||
// attendi 3 secondi prima di poter inviare una nuova richiesta
|
||||
await tools.attendiNSecondi(1);
|
||||
|
||||
if (codice_sconto) {
|
||||
const recscontisticheTrovate = await CartClass.getRecSconto(idapp, codice_sconto, true);
|
||||
if (recscontisticheTrovate && recscontisticheTrovate.length > 0) {
|
||||
recscontisticaTrovata = recscontisticheTrovate[0];
|
||||
}
|
||||
|
||||
if (recscontisticaTrovata) {
|
||||
if (mycart.codice_sconto !== codice_sconto) {
|
||||
mycart.codice_sconto = codice_sconto;
|
||||
mycart.descr_sconto = recscontisticaTrovata.description;
|
||||
await Cart.updateOne({ _id: cart_id }, { $set: { codice_sconto, descr_sconto: mycart.descr_sconto } });
|
||||
}
|
||||
valido = true;
|
||||
|
||||
mycart = await aggiornaCarrello(mycart, userId, idapp);
|
||||
} else {
|
||||
errmsg = `Codice sconto "${codice_sconto}" non valido oppure scaduto`;
|
||||
}
|
||||
}
|
||||
|
||||
return res.send({ mycart, valido, errmsg, recsconto: recscontisticaTrovata });
|
||||
} catch (e) {
|
||||
console.error('Err Applica Sconto', e);
|
||||
return res.send({ valido: false, mycart: null, errmsg: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Recupera il carrello
|
||||
async function getCartById(cart_id) {
|
||||
const cart = await Cart.findOne({ _id: cart_id }).lean();
|
||||
return cart;
|
||||
}
|
||||
|
||||
// Crea o aggiorna un ordine partendo dal cart
|
||||
async function createOrUpdateOrderFromCart({ idapp, cart, userId, status, note }) {
|
||||
let numorder = await OrdersCart.getLastNumOrder(idapp);
|
||||
let numord_pers = await OrdersCart.getLastNumOrdPers(userId, idapp);
|
||||
|
||||
let myorderCart = await OrdersCart.getRecCartByUserId(userId, idapp, numorder);
|
||||
if (!myorderCart) {
|
||||
numorder++;
|
||||
numord_pers++;
|
||||
myorderCart = new OrdersCart({
|
||||
idapp,
|
||||
items: cart.items,
|
||||
totalQty: cart.totalQty,
|
||||
totalPrice: cart.totalPrice,
|
||||
totalPriceCalc: cart.totalPriceCalc,
|
||||
totalPriceIntero: cart.totalPriceIntero,
|
||||
note_ordine_gas: cart.note_ordine_gas,
|
||||
userId,
|
||||
status,
|
||||
note,
|
||||
codice_sconto: cart.codice_sconto,
|
||||
descr_sconto: cart.descr_sconto,
|
||||
numorder,
|
||||
numord_pers,
|
||||
created_at: new Date(),
|
||||
modify_at: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
return myorderCart;
|
||||
}
|
||||
|
||||
// Gestisce l'invio ordine (checkout)
|
||||
async function handleCheckout({ myorderCart, mycart, userId, idapp, req, options, userDest }) {
|
||||
try {
|
||||
const ris = await OrdersCart.updateOrdersCartById(-1, myorderCart);
|
||||
await Order.updateStatusOrders(mycart.items, shared_consts.OrderStatus.CHECKOUT_SENT);
|
||||
|
||||
await Cart.deleteCartByCartId(mycart._id);
|
||||
|
||||
const orders = await OrdersCart.getOrdersCartByUserId(userId, idapp, myorderCart.numorder);
|
||||
if (orders?.[0]) {
|
||||
await OrdersCart.updateCmd(orders[0], shared_consts.OrderStatus.CHECKOUT_SENT, true, req, options);
|
||||
await sendemail.sendEmail_OrderProduct(userDest.lang, idapp, orders[0], userDest);
|
||||
|
||||
const updatedOrder = await OrdersCart.findById(myorderCart._id).lean();
|
||||
return { status: ris.status, orders, recOrderCart: updatedOrder };
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Errore durante il checkout:', err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
//POST cart
|
||||
router.post('/:userId/createorderscart', authenticate, async function (req, res) {
|
||||
try {
|
||||
const { idapp, cart_id, status, note, options } = req.body;
|
||||
const userId = req.params.userId;
|
||||
|
||||
// console.log('createorderscart', cart_id);
|
||||
|
||||
const mycart = await getCartById(cart_id);
|
||||
if (!mycart) {
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
status: 0,
|
||||
recOrderCart: null,
|
||||
});
|
||||
}
|
||||
|
||||
let myorderCart = await createOrUpdateOrderFromCart({ idapp, cart: mycart, userId, status, note });
|
||||
let statusOrderCart = myorderCart.status;
|
||||
|
||||
const userDest = await User.findById(userId).lean();
|
||||
|
||||
if (status === shared_consts.OrderStatus.CHECKOUT_SENT) {
|
||||
try {
|
||||
const checkoutResult = await handleCheckout({
|
||||
myorderCart,
|
||||
mycart,
|
||||
userId,
|
||||
idapp,
|
||||
req,
|
||||
options,
|
||||
userDest,
|
||||
});
|
||||
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
status: checkoutResult.status,
|
||||
orders: checkoutResult.orders,
|
||||
recOrderCart: checkoutResult.recOrderCart,
|
||||
});
|
||||
} catch (err) {
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
|
||||
}
|
||||
}
|
||||
|
||||
// console.log('SEND OK', statusOrderCart);
|
||||
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
status: statusOrderCart,
|
||||
recOrderCart: myorderCart,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Errore generale:', e);
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0, recOrderCart: null });
|
||||
}
|
||||
});
|
||||
|
||||
//POST cart
|
||||
router.post('/:userId/ordercartstatus', authenticate, async function (req, res, next) {
|
||||
let idapp = req.body.idapp;
|
||||
let userId = req.params.userId;
|
||||
let order_id = req.body.order_id;
|
||||
let status = req.body.status;
|
||||
let options = req.body.options;
|
||||
|
||||
const { User } = require('../models/user');
|
||||
|
||||
let myOrdersCart = await OrdersCart.findOne({ idapp, _id: order_id }).lean();
|
||||
|
||||
if (userId !== String(req.user._id) && !User.isManager(req.user.perm)) {
|
||||
// I'm trying to write something not mine!
|
||||
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
|
||||
}
|
||||
|
||||
try {
|
||||
if (!!myOrdersCart) {
|
||||
let fields_to_update = { status };
|
||||
|
||||
await OrdersCart.findOneAndUpdate({ _id: order_id }, { $set: fields_to_update }, { new: false }).then(
|
||||
async (ris) => {
|
||||
const userDest = await User.findById(myOrdersCart.userId).lean();
|
||||
|
||||
if (ris) {
|
||||
let ordertype = '';
|
||||
|
||||
// Aggiorna gli Stati Interni !
|
||||
myOrdersCart = await OrdersCart.updateCmd(myOrdersCart, status, true, options);
|
||||
|
||||
if ((options.hasOwnProperty('sendmail') && options.sendmail) || !options.hasOwnProperty('sendmail')) {
|
||||
if (status === shared_consts.OrderStatus.ORDER_CONFIRMED) {
|
||||
ordertype = 'order_confirmed';
|
||||
} else if (status === shared_consts.OrderStatus.DELIVERED) {
|
||||
ordertype = 'order_consegnato';
|
||||
} else if (status === shared_consts.OrderStatus.CANCELED) {
|
||||
ordertype = 'order_canceled';
|
||||
}
|
||||
|
||||
if (ordertype !== '') {
|
||||
sendemail
|
||||
.sendEmail_Order(userDest.lang, idapp, myOrdersCart, userDest, ordertype, status)
|
||||
.then((ris) => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
let orderscart = null;
|
||||
|
||||
if (User.isManager(req.user.perm)) {
|
||||
// Prende Tutti gli Ordini !
|
||||
orderscart = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false);
|
||||
} else {
|
||||
orderscart = await OrdersCart.getOrdersCartByUserId(req.user.id, idapp, 0, false);
|
||||
}
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, status, orders: orderscart });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('err', e);
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, status: 0 });
|
||||
}
|
||||
});
|
||||
|
||||
//POST cart
|
||||
router.post('/:userId/gestord', authenticate, async function (req, res, next) {
|
||||
let idapp = req.body.idapp;
|
||||
let idGasordine = req.body.idGasordine;
|
||||
|
||||
const { User } = require('../models/user');
|
||||
|
||||
try {
|
||||
let queryord = [];
|
||||
|
||||
let filtroOrdini = [];
|
||||
|
||||
if (idGasordine) {
|
||||
const gasordine = {
|
||||
$match: {
|
||||
idGasordine: {
|
||||
$type: 'objectId', // Checks if the field is of type ObjectId
|
||||
$eq: new mongoose.Types.ObjectId(idGasordine), // Compares the value to a specific ObjectId
|
||||
},
|
||||
},
|
||||
};
|
||||
queryord.push(gasordine);
|
||||
}
|
||||
|
||||
const query = [
|
||||
{
|
||||
$lookup: {
|
||||
from: 'products',
|
||||
localField: 'idProduct',
|
||||
foreignField: '_id',
|
||||
as: 'product',
|
||||
},
|
||||
},
|
||||
{
|
||||
$unwind: {
|
||||
path: '$product',
|
||||
preserveNullAndEmptyArrays: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'gasordines',
|
||||
localField: 'idGasordine',
|
||||
foreignField: '_id',
|
||||
as: 'gasordine',
|
||||
},
|
||||
},
|
||||
{
|
||||
$unwind: {
|
||||
path: '$gasordine',
|
||||
preserveNullAndEmptyArrays: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
$match: {
|
||||
$or: [
|
||||
{
|
||||
quantity: {
|
||||
$gt: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
quantitypreordered: {
|
||||
$gt: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'orderscarts',
|
||||
localField: '_id',
|
||||
foreignField: 'items.order',
|
||||
as: 'matchingOrders',
|
||||
},
|
||||
},
|
||||
{
|
||||
$match: {
|
||||
matchingOrders: {
|
||||
$ne: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: '$product._id',
|
||||
name: {
|
||||
$first: '$product.productInfo.name',
|
||||
},
|
||||
weight: {
|
||||
$first: '$product.productInfo.weight',
|
||||
},
|
||||
unit: {
|
||||
$first: '$product.productInfo.unit',
|
||||
},
|
||||
price_acquistato: {
|
||||
$first: '$product.price_acquistato',
|
||||
},
|
||||
price: {
|
||||
$first: '$product.price',
|
||||
},
|
||||
totalQuantity: {
|
||||
$sum: {
|
||||
$add: ['$quantity', '$quantitypreordered'],
|
||||
},
|
||||
},
|
||||
totalPrice_acquistato: {
|
||||
$sum: {
|
||||
$multiply: [
|
||||
'$product.price_acquistato',
|
||||
{
|
||||
$add: ['$quantity', '$quantitypreordered'],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
totalPrice: {
|
||||
$sum: {
|
||||
$multiply: [
|
||||
'$product.price',
|
||||
{
|
||||
$add: ['$quantity', '$quantitypreordered'],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
count: {
|
||||
$sum: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$sort: {
|
||||
name: 1,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
queryord = [...queryord, ...query];
|
||||
|
||||
filtroOrdini = queryord;
|
||||
|
||||
const arrout = await Order.aggregate(filtroOrdini);
|
||||
|
||||
for (const rec of arrout) {
|
||||
}
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, arrout });
|
||||
} catch (e) {
|
||||
console.error('Err', e);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
69
src/router/catalogs_router.js
Executable file
@@ -0,0 +1,69 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var { Project } = require('../models/project');
|
||||
|
||||
const { User } = require('../models/user');
|
||||
|
||||
var { authenticate, auth_default } = require('../middleware/authenticate');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { Catalog } = require('../models/catalog');
|
||||
|
||||
const globalTables = require('../tools/globalTables');
|
||||
|
||||
router.post('/', auth_default, async function (req, res, next) {
|
||||
const idapp = req.body.idapp;
|
||||
const userId = req.body.userId;
|
||||
|
||||
let ismanager = await tools.isManagerByReq(req);
|
||||
|
||||
let catalogs = await Catalog.findAllIdApp(idapp);
|
||||
let orders = null;
|
||||
|
||||
if (catalogs) return res.send({ code: server_constants.RIS_CODE_OK, catalogs, orders });
|
||||
else return res.status(400).send({ code: server_constants.RIS_CODE_OK, catalogs, orders });
|
||||
});
|
||||
|
||||
router.get('/id/:id', async function (req, res) {
|
||||
const id = req.params.id;
|
||||
|
||||
try {
|
||||
var catalog = await Catalog.getCatalogById(id);
|
||||
|
||||
if (catalog) {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, catalog: catalog });
|
||||
} else {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, catalog: null });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error fetching catalog by ID:', e);
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
router.post('/addnew', authenticate, async function (req, res, next) {
|
||||
const idapp = req.body.idapp;
|
||||
const data = req.body.newCatalog;
|
||||
const username = req.user.username;
|
||||
|
||||
try {
|
||||
const newrecs = await globalTables.addNewCatalog(idapp, data, username);
|
||||
if (newrecs) {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, data: newrecs });
|
||||
} else {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, data: null });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error fetching catalog by ID:', e);
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
127
src/router/circuits_router.js
Executable file
@@ -0,0 +1,127 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
const server_constants = require('../tools/server_constants');
|
||||
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const { authenticate } = require('../middleware/authenticate');
|
||||
|
||||
const mongoose = require('mongoose').set('debug', false);
|
||||
|
||||
const { User } = require('../models/user');
|
||||
const { Circuit } = require('../models/circuit');
|
||||
const { Account } = require('../models/account');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
async function getCircuitRecAdminsInfo(idapp, data) {
|
||||
try {
|
||||
if (data && data.admins) {
|
||||
for (const admin of data.admins) {
|
||||
const myuser = await User.findOne({ idapp, username: admin.username }, { 'profile.img': 1 }).lean();
|
||||
if (myuser && myuser.profile) admin.profile = { img: myuser.profile.img };
|
||||
}
|
||||
|
||||
if (data.admins.length === 0) {
|
||||
for (const admin of shared_consts.USER_ADMIN_CIRCUITS) {
|
||||
data.admins.push({ username: admin });
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return data;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
router.post('/load', authenticate, async (req, res) => {
|
||||
const idapp = req.body.idapp;
|
||||
const path = req.body.path;
|
||||
const usernameOrig = req.user.username;
|
||||
|
||||
try {
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
const { Movement } = require('../models/movement');
|
||||
|
||||
// Check if ìs a Notif to read
|
||||
const idnotif = req.body['idnotif'] ? req.body['idnotif'] : '';
|
||||
const lastdr = req.body['lastdr'] ? req.body['lastdr'] : '';
|
||||
SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif);
|
||||
|
||||
const whatshow = Circuit.getWhatToShow(idapp, req.user.username);
|
||||
let data = await Circuit.findOne({ idapp, path }, whatshow).lean();
|
||||
|
||||
const whatshowUsers = await User.getWhatToShow_IfFriends(idapp, req.user.username);
|
||||
|
||||
/*let users_in_circuit = [];
|
||||
|
||||
if (data) {
|
||||
users_in_circuit = await User.find(
|
||||
{
|
||||
idapp,
|
||||
'profile.mycircuits': {
|
||||
$elemMatch: {circuitname: {$eq: data.name}},
|
||||
},
|
||||
},
|
||||
whatshowUsers,
|
||||
).lean();
|
||||
}
|
||||
*/
|
||||
|
||||
if (data === null) {
|
||||
data = null;
|
||||
}
|
||||
|
||||
const users_in_circuit = await Circuit.getUsersSingleCircuit(idapp, req.user.username, data.name, data._id);
|
||||
|
||||
data = await getCircuitRecAdminsInfo(idapp, data);
|
||||
|
||||
if (data) {
|
||||
data.movements = await Movement.getMovsByCircuitId(idapp, usernameOrig, data._id);
|
||||
}
|
||||
|
||||
if (data) {
|
||||
data.account = await Account.getAccountByUsernameAndCircuitId(idapp, '', data._id, false, false, '', data.path);
|
||||
}
|
||||
|
||||
let arrrecnotifcoins = null;
|
||||
const arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(
|
||||
req.user.username,
|
||||
lastdr,
|
||||
idapp,
|
||||
shared_consts.LIMIT_NOTIF_FOR_USER,
|
||||
shared_consts.QualiNotifs.OTHERS
|
||||
);
|
||||
if (User.isAdminById(req.user.id)) {
|
||||
arrrecnotifcoins = await SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp);
|
||||
} else {
|
||||
arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(
|
||||
req.user.username,
|
||||
lastdr,
|
||||
idapp,
|
||||
shared_consts.LIMIT_NOTIFCOINS_FOR_USER,
|
||||
shared_consts.QualiNotifs.CIRCUITS
|
||||
);
|
||||
}
|
||||
/// E' QUIIII !!!!
|
||||
const useraccounts = await Account.getUserAccounts(idapp, req.user.username);
|
||||
|
||||
await User.setLastCircuitOpened(idapp, req.user.username, path);
|
||||
|
||||
res.send({ circuit: data, users_in_circuit, arrrecnotif, arrrecnotifcoins, useraccounts });
|
||||
} catch (e) {
|
||||
console.error('Error in Circuits', e);
|
||||
return res.status(400).send(e);
|
||||
}
|
||||
|
||||
const ris = null;
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
127
src/router/city_router.js
Executable file
@@ -0,0 +1,127 @@
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var { Project } = require('../models/project');
|
||||
|
||||
var { authenticate, auth_default } = require('../middleware/authenticate');
|
||||
|
||||
var mongoose = require('mongoose').set('debug', false)
|
||||
const Subscription = require('../models/subscribers');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const { City } = require('../models/city');
|
||||
|
||||
|
||||
//POST
|
||||
router.post('/geojson', authenticate, function (req, res, next) {
|
||||
let prov = req.body.prov;
|
||||
// let idapp = req.body.idapp;
|
||||
return City.getGeoJsonByProvince(prov)
|
||||
.then((ris) => {
|
||||
|
||||
if (ris)
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, ris });
|
||||
|
||||
}).catch(err => {
|
||||
console.log('ERR:', err);
|
||||
return res.status(400).send();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
router.post('/updateord', authenticate, async (req, res) => {
|
||||
const idOrdersCart = req.body.idOrdersCart;
|
||||
const idOrder = req.body.idOrder;
|
||||
const paramstoupdate = req.body.paramstoupdate;
|
||||
|
||||
try {
|
||||
// Aggiorno l'Ordine Singolo
|
||||
await Order.updateOrderByParams(idOrder, paramstoupdate);
|
||||
|
||||
// Aggiorno il Totale degli Ordini (OrdersCart)
|
||||
await OrdersCart.updateOrdersCartTotals(idOrdersCart, true)
|
||||
.then((orderscart) => {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, orderscart });
|
||||
}).catch(err => {
|
||||
console.log('ERR:', err);
|
||||
return res.status(400).send();
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Err', e);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
router.post('/update', authenticate, async (req, res) => {
|
||||
let orderscart = null;
|
||||
const idOrdersCart = req.body.idOrdersCart;
|
||||
const paramstoupdate = req.body.paramstoupdate;
|
||||
|
||||
try {
|
||||
// Aggiorno Orderscart con i parametri passati
|
||||
orderscart = await OrdersCart.updateOrdersCartByParams(idOrdersCart, paramstoupdate);
|
||||
|
||||
let updatetotals = true;
|
||||
if (paramstoupdate && paramstoupdate.hasOwnProperty('totalPrice')) {
|
||||
updatetotals = false;
|
||||
}
|
||||
if (updatetotals) {
|
||||
|
||||
// Aggiorno il Totale degli Ordini (OrdersCart)
|
||||
await OrdersCart.updateOrdersCartTotals(idOrdersCart, true)
|
||||
.then((orderscart) => {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, orderscart });
|
||||
}).catch(err => {
|
||||
console.log('ERR:', err);
|
||||
return res.status(400).send();
|
||||
});
|
||||
} else {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, orderscart });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Err', e);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
|
||||
router.post('/sendmail', authenticate, async function (req, res, next) {
|
||||
const idOrdersCart = req.body.idOrdersCart;
|
||||
const idapp = req.body.idapp;
|
||||
const test = req.body.test;
|
||||
const previewonly = req.body.previewonly;
|
||||
const templemail_id = req.body.templemail_id;
|
||||
|
||||
try {
|
||||
// Invia Email
|
||||
let myOrderCart = await OrdersCart.getOrdersCartById(idOrdersCart);
|
||||
if (myOrderCart) {
|
||||
const userto = myOrderCart.user;
|
||||
let emailto = userto.email;
|
||||
|
||||
if (userto && emailto) {
|
||||
const emailsend = await sendemail.sendEmail_byTemplate(idapp, userto, previewonly, emailto, templemail_id, test);
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, emailsend });
|
||||
}
|
||||
}
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, emailsend: false });
|
||||
|
||||
} catch (e) {
|
||||
console.error('err:', e);
|
||||
return res.status(400).send(e);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
127
src/router/dashboard_router.js
Executable file
@@ -0,0 +1,127 @@
|
||||
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 { MsgTemplate } = require('../models/msg_template');
|
||||
|
||||
const telegrambot = require('../telegram/telegrambot');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
router.post('/', authenticate, async (req, res) => {
|
||||
try {
|
||||
const idapp = req.body.idapp;
|
||||
let username = req.body.username;
|
||||
|
||||
if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) && (username) !== req.user.username) {
|
||||
// If without permissions, exit
|
||||
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
|
||||
}
|
||||
let aportador_solidario = req.user.aportador_solidario;
|
||||
let aportador_solidario_nome_completo = req.user.aportador_solidario_nome_completo;
|
||||
|
||||
if (username) {
|
||||
aportador_solidario = await User.getAportadorSolidarioByUsername(idapp, username);
|
||||
aportador_solidario_nome_completo = await User.getNameSurnameByUsername(idapp, username);
|
||||
} else {
|
||||
username = req.user.username;
|
||||
}
|
||||
|
||||
const dashboard = await User.getDashboard(idapp, aportador_solidario, username, aportador_solidario_nome_completo);
|
||||
if (dashboard)
|
||||
res.send({ dashboard });
|
||||
else
|
||||
res.status(400).send(e);
|
||||
|
||||
} catch (e) {
|
||||
res.status(400).send(e);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
router.post('/downline', authenticate, async (req, res) => {
|
||||
try {
|
||||
const idapp = req.body.idapp;
|
||||
let username = req.body.username;
|
||||
|
||||
if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm)) && (username) !== req.user.username) {
|
||||
// If without permissions, exit
|
||||
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
|
||||
}
|
||||
let aportador_solidario = req.user.aportador_solidario;
|
||||
let aportador_solidario_nome_completo = req.user.aportador_solidario_nome_completo;
|
||||
|
||||
if (username) {
|
||||
aportador_solidario = await User.getAportadorSolidarioByUsername(idapp, username);
|
||||
aportador_solidario_nome_completo = await User.getNameSurnameByUsername(idapp, username);
|
||||
} else {
|
||||
username = req.user.username;
|
||||
}
|
||||
|
||||
const downline = await User.getDownline(idapp, aportador_solidario, username, aportador_solidario_nome_completo);
|
||||
if (downline)
|
||||
res.send({ downline });
|
||||
else
|
||||
res.status(400).send(e);
|
||||
|
||||
} catch (e) {
|
||||
res.status(400).send(e);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
router.post('/getmsg_templates', authenticate, async (req, res) => {
|
||||
const idapp = req.body.idapp;
|
||||
|
||||
let ris = await MsgTemplate.findAllIdApp(idapp);
|
||||
|
||||
if (!!ris)
|
||||
res.send({ code: server_constants.RIS_CODE_OK, ris });
|
||||
else
|
||||
res.status(400).send(e);
|
||||
|
||||
|
||||
});
|
||||
|
||||
router.post('/getflotte', authenticate, async (req, res) => {
|
||||
const idapp = req.body.idapp;
|
||||
|
||||
let arrflotte = await Flotta.findAllIdApp(idapp);
|
||||
|
||||
if (!!arrflotte)
|
||||
res.send({ code: server_constants.RIS_CODE_OK, arrflotte });
|
||||
else
|
||||
res.status(400).send(e);
|
||||
|
||||
});
|
||||
|
||||
|
||||
router.post('/getdata', authenticate, async (req, res) => {
|
||||
const idapp = req.body.idapp;
|
||||
const data = req.body.data;
|
||||
|
||||
try {
|
||||
|
||||
const mystr = await Nave.getNavePos(idapp, parseInt(data.riga), parseInt(data.col));
|
||||
|
||||
if (mystr)
|
||||
res.send({ code: server_constants.RIS_CODE_OK, ris: mystr });
|
||||
else
|
||||
res.status(400).send(e);
|
||||
} catch (e) {
|
||||
console.log(e.message)
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
34
src/router/email_router.js
Executable file
@@ -0,0 +1,34 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
var {User} = require('../models/user');
|
||||
|
||||
router.get('/:idapp/:email', (req, res) => {
|
||||
var email = req.params.email;
|
||||
const idapp = req.params.idapp;
|
||||
|
||||
User.findByEmail(idapp, email).then((user) => {
|
||||
if (!user) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
res.status(200).send();
|
||||
}).catch((e) => {
|
||||
res.status(400).send();
|
||||
});
|
||||
});
|
||||
|
||||
router.post('/ck', (req, res) => {
|
||||
const idapp = req.body.idapp;
|
||||
var email = req.body.email;
|
||||
|
||||
User.findByEmail(idapp, email, true).then((user) => {
|
||||
if (!user) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
res.status(200).send();
|
||||
}).catch((e) => {
|
||||
res.status(400).send();
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
BIN
src/router/files/Musica_Dell_Anima_Serata.jpg
Executable file
|
After Width: | Height: | Size: 94 KiB |
BIN
src/router/files/batidora-de-brazo-600-w--5.jpg
Executable file
|
After Width: | Height: | Size: 65 KiB |
BIN
src/router/files/estados_emocionales.jpg
Executable file
|
After Width: | Height: | Size: 68 KiB |
BIN
src/router/files/flat_earth.png
Executable file
|
After Width: | Height: | Size: 152 KiB |
BIN
src/router/files/malaga_beach.jpg
Executable file
|
After Width: | Height: | Size: 46 KiB |
BIN
src/router/files/paolo_piano3.jpg
Executable file
|
After Width: | Height: | Size: 119 KiB |
BIN
src/router/files/terra_piatta.jpg
Executable file
|
After Width: | Height: | Size: 18 KiB |
2586
src/router/index_router.js
Executable file
89
src/router/invitaAmicoRoutes.js
Normal file
@@ -0,0 +1,89 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const nodemailer = require('nodemailer');
|
||||
|
||||
const { authenticate, authenticate_noerror, auth_default } = require('../middleware/authenticate');
|
||||
|
||||
const sendemail = require('../sendemail');
|
||||
|
||||
// ==========================================
|
||||
// ENDPOINT API
|
||||
// ==========================================
|
||||
|
||||
/**
|
||||
* POST /inviti/invia-email
|
||||
* Invia un invito via email
|
||||
*/
|
||||
router.post('/invia-email', authenticate, async (req, res) => {
|
||||
try {
|
||||
const { emailAmico, messaggioPersonalizzato, usernameInvitante, idapp } = req.body;
|
||||
|
||||
// Validazione
|
||||
if (!emailAmico) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Email del destinatario è obbligatoria',
|
||||
});
|
||||
}
|
||||
|
||||
// Validazione formato email
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(emailAmico)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Formato email non valido',
|
||||
});
|
||||
}
|
||||
|
||||
const dati = { messaggioPersonalizzato, emailAmico, usernameInvitante };
|
||||
|
||||
const ris = await sendemail.sendEmail_InvitaAmico('it', emailAmico, null, idapp, dati);
|
||||
|
||||
if (ris) {
|
||||
// Risposta successo
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
message: 'Invito inviato con successo',
|
||||
emailInviata: true,
|
||||
});
|
||||
} else {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: "Errore durante l'invio dell'invito",
|
||||
emailInviata: false,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Errore invio email invito:', error);
|
||||
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: "Errore durante l'invio dell'invito",
|
||||
emailInviata: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /inviti/test-email
|
||||
* Endpoint di test per verificare la configurazione email
|
||||
*/
|
||||
router.get('/test-email', authenticate, async (req, res) => {
|
||||
try {
|
||||
await transporter.verify();
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Configurazione email corretta!',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Errore configurazione email:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Errore nella configurazione email',
|
||||
error: error instanceof Error ? error.message : 'Errore sconosciuto',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
82
src/router/iscrittiConacreis_router.js
Executable file
@@ -0,0 +1,82 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const IscrittiConacreis = require('../models/iscrittiConacreis');
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const sendemail = require('../sendemail');
|
||||
|
||||
const { Settings } = require('../models/settings');
|
||||
|
||||
const tools = require('../tools/general');
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const server_constants = require('../tools/server_constants');
|
||||
|
||||
const telegrambot = require('../telegram/telegrambot');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { authenticate } = require('../middleware/authenticate');
|
||||
|
||||
const mongoose = require('mongoose').set('debug', false)
|
||||
|
||||
|
||||
// POST /iscritti_conacreis
|
||||
router.post('/', async (req, res) => {
|
||||
tools.mylog("POST /iscritti_conacreis");
|
||||
const body = req.body;
|
||||
body.email = body.email.toLowerCase();
|
||||
|
||||
const iscritti = new IscrittiConacreis(body);
|
||||
iscritti.ipaddr = tools.getiPAddressUser(req);
|
||||
iscritti.lang = req.locale;
|
||||
|
||||
// tools.mylog("LANG PASSATO = " + iscritti.lang, "IDAPP", iscritti.idapp);
|
||||
|
||||
if (!tools.isAlphaNumeric(body.name)) {
|
||||
await tools.snooze(5000);
|
||||
res.status(400).send({ code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: '' });
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (tools.blockwords(body.username) || tools.blockwords(body.email) || tools.blockwords(body.name) || tools.blockwords(body.surname)) {
|
||||
// tools.writeIPToBan(iscritti.ipaddr + ': [' + iscritti.username + '] ' + iscritti.name + ' ' + iscritti.surname);
|
||||
await tools.snooze(5000);
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
iscritti.dateofreg = new Date();
|
||||
|
||||
// Controlla se anche l'ultimo record era dallo stesso IP:
|
||||
const lastrec = await IscrittiConacreis.getLastRec(body.idapp);
|
||||
if (!!lastrec) {
|
||||
if (process.env.LOCALE !== "1") {
|
||||
if (lastrec.ipaddr === iscritti.ipaddr) {
|
||||
// Se l'ha fatto troppo ravvicinato
|
||||
if (lastrec.date_reg) {
|
||||
let ris = tools.isdiffSecDateLess(lastrec.date_reg, 120);
|
||||
if (ris) {
|
||||
tools.writeIPToBan(iscritti.ipaddr + ': ' + tools.getNomeCognomeEUserNameByUser(iscritti));
|
||||
await tools.snooze(10000);
|
||||
res.status(400).send({ code: server_constants.RIS_CODE_BANIP, msg: '' });
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return iscritti.save()
|
||||
.then(async () => {
|
||||
await sendemail.sendEmail_IscrizioneConacreis(iscritti.lang, iscritti.email, iscritti, iscritti.idapp);
|
||||
// }
|
||||
return res.status(200).send();
|
||||
}).catch((e) => {
|
||||
console.error(e.message);
|
||||
res.status(400).send(e);
|
||||
})
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
121
src/router/myevent_router.js
Executable file
@@ -0,0 +1,121 @@
|
||||
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 globalTables = require('../tools/globalTables');
|
||||
|
||||
const {SendNotif} = require('../models/sendnotif');
|
||||
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
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, res);
|
||||
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: false,
|
||||
upsert: true,
|
||||
}).then(async (recmyevent) => {
|
||||
// tools.mylog('myevent:', myevent);
|
||||
// tools.mylog('already exist');
|
||||
SendNotif.createNewNotification(req, res, {}, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_NEW_REC);
|
||||
return res;
|
||||
}).then((res) => {
|
||||
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) => {
|
||||
recmyevent.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS
|
||||
recmyevent.typeid = shared_consts.TypeNotifs.ID_EVENTS_NEW_REC
|
||||
SendNotif.createNewNotification(req, res, {}, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_NEW_REC);
|
||||
return 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.deleteOne({_id: id}).then((recmyevent) => {
|
||||
if (!recmyevent) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
if (notify === '1') {
|
||||
SendNotif.createNewNotification(req, res, {}, shared_consts.TABLES_MYEVENTS, recmyevent, shared_consts.TypeNotifs.TYPEDIR_EVENTS, shared_consts.TypeNotifs.ID_EVENTS_REMOVE_REC);
|
||||
}
|
||||
|
||||
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
|
||||
return MyEvent.findAllByUserIdAndIdApp(userId, idapp, sall).then((recevent) => {
|
||||
res.send({recevent});
|
||||
}).catch((e) => {
|
||||
console.log(e.message);
|
||||
res.status(400).send(e);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
85
src/router/mygen_router.js
Executable file
@@ -0,0 +1,85 @@
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var { authenticate, authenticate_noerror, auth_default } = require('../middleware/authenticate');
|
||||
|
||||
var mongoose = require('mongoose').set('debug', false);
|
||||
const Subscription = require('../models/subscribers');
|
||||
|
||||
const _ = require('lodash');
|
||||
const { MyBacheca } = require('../models/mybacheca');
|
||||
var { User } = require('../models/user');
|
||||
const { Reaction } = require('../models/reaction');
|
||||
|
||||
const globalTables = require('../tools/globalTables');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
//GET orders
|
||||
router.post('/page', authenticate_noerror, function (req, res, next) {
|
||||
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
|
||||
try {
|
||||
let table = req.body.table;
|
||||
let id = req.body.id;
|
||||
let idapp = req.body.idapp;
|
||||
|
||||
let username = ''
|
||||
if (req.user)
|
||||
username = req.user.username ? req.user.username : '';
|
||||
|
||||
if (username) {
|
||||
// Check if ìs a Notif to read
|
||||
const idnotif = req.body.idnotif ? req.body.idnotif : '';
|
||||
SendNotif.setNotifAsRead(idapp, username, idnotif);
|
||||
}
|
||||
|
||||
let mytable = null;
|
||||
if (shared_consts.TABLES_ENABLE_GETREC_BYID.includes(table)) {
|
||||
mytable = globalTables.getTableByTableName(table);
|
||||
}
|
||||
|
||||
|
||||
if (mytable) {
|
||||
|
||||
return mytable.getMyRecById(idapp, id).
|
||||
then(async (ris) => {
|
||||
|
||||
// Se è un record singolo di tipo Reaction,
|
||||
// allora gli devo passare anche le liste degli utenti :
|
||||
if (globalTables.isTableReaction(table)) {
|
||||
// ...
|
||||
// const myreaction = await Reaction.find({idapp, idrec: id}).lean();
|
||||
// ris.myreaction = myreaction;
|
||||
|
||||
};
|
||||
|
||||
if (ris) {
|
||||
res.send(ris);
|
||||
|
||||
} else {
|
||||
res.status(400).send();
|
||||
}
|
||||
}).catch((e) => {
|
||||
console.error('Err', e);
|
||||
res.status(400).send(e);
|
||||
})
|
||||
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('/page', e);
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
50
src/router/mygoods_router.js
Executable file
@@ -0,0 +1,50 @@
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var {authenticate, auth_default} = require('../middleware/authenticate');
|
||||
|
||||
var mongoose = require('mongoose').set('debug', false);
|
||||
const Subscription = require('../models/subscribers');
|
||||
|
||||
const _ = require('lodash');
|
||||
const {MyGood} = require('../models/mygood');
|
||||
var {User} = require('../models/user');
|
||||
|
||||
const {ObjectId} = require('mongodb');
|
||||
|
||||
//GET orders
|
||||
router.post('/page', authenticate, function(req, res, next) {
|
||||
let idGood = req.body.idGood;
|
||||
let idapp = req.body.idapp;
|
||||
|
||||
return MyGood.getMyRecById(idapp, idGood).
|
||||
then((ris) => {
|
||||
|
||||
if (ris) {
|
||||
res.send(ris);
|
||||
/*
|
||||
const userId = ris.userId;
|
||||
return User.getUsernameById(idapp, userId).then((username) =>
|
||||
{
|
||||
res.send({...ris, username});
|
||||
});
|
||||
*/
|
||||
|
||||
} else {
|
||||
res.status(400).send();
|
||||
}
|
||||
}).catch((e) => {
|
||||
console.error('Err', e);
|
||||
res.status(400).send(e);
|
||||
})
|
||||
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
107
src/router/mygroups_router.js
Executable file
@@ -0,0 +1,107 @@
|
||||
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 mongoose = require('mongoose').set('debug', false);
|
||||
|
||||
const { User } = require('../models/user');
|
||||
const { MyGroup } = require('../models/mygroup');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
async function getGroupRecAdminsInfo(idapp, data) {
|
||||
try {
|
||||
if (data && data.admins) {
|
||||
for (const admin of data.admins) {
|
||||
const myuser = await User.findOne({ idapp, username: admin.username }, { 'profile.img': 1 }).lean();
|
||||
if (myuser)
|
||||
admin.profile = { img: myuser.profile.img };
|
||||
}
|
||||
}
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
router.post('/load', authenticate, async (req, res) => {
|
||||
const idapp = req.body.idapp;
|
||||
const groupname = req.body.groupname;
|
||||
const usernameOrig = req.user.username;
|
||||
|
||||
try {
|
||||
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
const { Circuit } = require('../models/circuit');
|
||||
const { Account } = require('../models/account');
|
||||
|
||||
// Check if ìs a Notif to read
|
||||
const idnotif = req.body['idnotif'] ? req.body['idnotif'] : '';
|
||||
SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif);
|
||||
|
||||
const whatshow = MyGroup.getWhatToShow(idapp, req.user.username);
|
||||
// let data = await MyGroup.findOne({ idapp, groupname }, whatshow).lean();
|
||||
let data = await MyGroup.getInfoGroupByGroupname(idapp, groupname);
|
||||
|
||||
/*
|
||||
if (data.mycircuits) {
|
||||
for (let i = 0; i < data.mycircuits.length; i++) {
|
||||
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean();
|
||||
data.mycircuits[i] = mycirc;
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
if (data.mycircuits) {
|
||||
for (let i = 0; i < data.mycircuits.length; i++) {
|
||||
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].name }).lean();
|
||||
if (mycirc) {
|
||||
data.mycircuits[i].account = await Account.getAccountByUsernameAndCircuitId(idapp, '', mycirc._id, true, true, groupname);
|
||||
data.mycircuits[i].account = tools.jsonCopy(data.mycircuits[i].account);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let cities = [];
|
||||
if (data) {
|
||||
cities = await MyGroup.extractCitiesName(idapp, data._id);
|
||||
if (cities && cities.length > 0) {
|
||||
cities = cities[0].mycities;
|
||||
}
|
||||
}
|
||||
|
||||
data = await getGroupRecAdminsInfo(idapp, data);
|
||||
|
||||
const whatshowUsers = await User.getWhatToShow_IfFriends(idapp, req.user.username);
|
||||
|
||||
const users_in_group = await User.find(
|
||||
{
|
||||
idapp,
|
||||
'profile.mygroups': {
|
||||
$elemMatch: { groupname: { $eq: groupname } },
|
||||
},
|
||||
},
|
||||
whatshowUsers,
|
||||
).lean();
|
||||
|
||||
res.send({ mygroup: data, users_in_group, cities });
|
||||
|
||||
} catch (e) {
|
||||
console.error('Error in MyGroups', e);
|
||||
return res.status(400).send(e);
|
||||
}
|
||||
|
||||
const ris = null;
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
57
src/router/myscraping_router.js
Executable file
@@ -0,0 +1,57 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
const { User } = require('../models/user');
|
||||
|
||||
var { authenticate, auth_default } = require('../middleware/authenticate');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { MyScrapingBook } = require('../models/myscrapingbook');
|
||||
const Product = require('../models/product');
|
||||
|
||||
const AmazonBookScraper = require('../modules/Scraping');
|
||||
|
||||
//GET /products
|
||||
router.post('/', auth_default, async function (req, res, next) {
|
||||
const idapp = req.body.idapp;
|
||||
const isbn = req.body.isbn;
|
||||
const forzacaricamento = req.body.forzacaricamento;
|
||||
|
||||
try {
|
||||
let myscraping = null;
|
||||
if (isbn) {
|
||||
myscraping = await MyScrapingBook.findOne({ isbn }).lean();
|
||||
|
||||
if (!myscraping && forzacaricamento) {
|
||||
const scraper = new AmazonBookScraper();
|
||||
|
||||
const options = {
|
||||
update: false,
|
||||
forzaricarica: false,
|
||||
};
|
||||
|
||||
const myproduct = await Product.getProductByIsbn(idapp, isbn);
|
||||
if (myproduct && myproduct.length > 0) {
|
||||
myscraping = await scraper.scrapeISBN(myproduct[0], isbn, options);
|
||||
// console.log(myscraping);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (myscraping) {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, myscraping });
|
||||
} else {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, myscraping: null });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
50
src/router/myskills_router.js
Executable file
@@ -0,0 +1,50 @@
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var {authenticate, auth_default} = require('../middleware/authenticate');
|
||||
|
||||
var mongoose = require('mongoose').set('debug', false);
|
||||
const Subscription = require('../models/subscribers');
|
||||
|
||||
const _ = require('lodash');
|
||||
const {MySkill} = require('../models/myskill');
|
||||
var {User} = require('../models/user');
|
||||
|
||||
const {ObjectId} = require('mongodb');
|
||||
|
||||
//GET orders
|
||||
router.post('/page', authenticate, function(req, res, next) {
|
||||
let idSkill = req.body.idSkill;
|
||||
let idapp = req.body.idapp;
|
||||
|
||||
return MySkill.getMyRecById(idapp, idSkill).
|
||||
then((ris) => {
|
||||
|
||||
if (ris) {
|
||||
res.send(ris);
|
||||
/*
|
||||
const userId = ris.userId;
|
||||
return User.getUsernameById(idapp, userId).then((username) =>
|
||||
{
|
||||
res.send({...ris, username});
|
||||
});
|
||||
*/
|
||||
|
||||
} else {
|
||||
res.status(400).send();
|
||||
}
|
||||
}).catch((e) => {
|
||||
console.error('Err', e);
|
||||
res.status(400).send(e);
|
||||
})
|
||||
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
421
src/router/newsletter_router.js
Executable file
@@ -0,0 +1,421 @@
|
||||
const server_constants = require('../tools/server_constants');
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const request = require('superagent');
|
||||
|
||||
const sendemail = require('../sendemail');
|
||||
|
||||
const { User } = require('../models/user');
|
||||
const { MailingList } = require('../models/mailinglist');
|
||||
const { Newstosent } = require('../models/newstosent');
|
||||
const { TemplEmail } = require('../models/templemail');
|
||||
const { DestNewsletter } = require('../models/destnewsletter');
|
||||
const { OpzEmail } = require('../models/opzemail');
|
||||
const { Settings } = require('../models/settings');
|
||||
|
||||
const tools = require('../tools/general');
|
||||
const { authenticate } = require('../middleware/authenticate');
|
||||
|
||||
const newsletter = [
|
||||
{
|
||||
name: 'Paolo',
|
||||
mailchimpInstance: 'us16',
|
||||
listUniqueId: 'e70fd8ba4c',
|
||||
mailchimpApiKey: '24d1eb0e4f21dd7c52d47214b0d62cfd-us16'
|
||||
// CLIENT ID 682712991042
|
||||
// Client Secret 69c627f5dad15f6072ac4f86f5312a6078c94f72a0902d2f4c
|
||||
},
|
||||
{
|
||||
name: 'Paolo',
|
||||
mailchimpInstance: 'us16',
|
||||
listUniqueId: 'e70fd8ba4c',
|
||||
mailchimpApiKey: '24d1eb0e4f21dd7c52d47214b0d62cfd-us16'
|
||||
// CLIENT ID 682712991042
|
||||
// Client Secret 69c627f5dad15f6072ac4f86f5312a6078c94f72a0902d2f4c
|
||||
},
|
||||
{
|
||||
name: 'AssShen',
|
||||
mailchimpInstance: 'us4',
|
||||
listUniqueId: '991c0b8321',
|
||||
mailchimpApiKey: '07dd8b0bd078ae3a79e398656c276bbd-us4'
|
||||
// CLIENT ID 682712991042
|
||||
// Client Secret 69c627f5dad15f6072ac4f86f5312a6078c94f72a0902d2f4c
|
||||
},
|
||||
{
|
||||
name: 'AssociazioneShen',
|
||||
mailchimpInstance: '',
|
||||
listUniqueId: '',
|
||||
mailchimpApiKey: ''
|
||||
},
|
||||
];
|
||||
|
||||
async function AddMailingList(locale, idapp, user, settomailchimp, sendnews) {
|
||||
|
||||
return await sendemail.Add_to_MailingList_AndSendEmailNotify(locale, user, idapp, sendnews).then((ris) => {
|
||||
|
||||
if (settomailchimp) {
|
||||
request
|
||||
.post('https://' + newsletter[idapp].mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + newsletter[idapp].listUniqueId + '/members/')
|
||||
.set('Content-Type', 'application/json;charset=utf-8')
|
||||
.set('Authorization', 'Basic ' + new Buffer('any:' + newsletter[idapp].mailchimpApiKey).toString('base64'))
|
||||
.send({
|
||||
'email_address': req.body.email,
|
||||
'status': server_constants.RIS_SUBSCRIBED_STR,
|
||||
'merge_fields': {
|
||||
'FNAME': user.name,
|
||||
'LNAME': user.surname
|
||||
}
|
||||
})
|
||||
.end(function (err, response) {
|
||||
console.log("STAT", response.status);
|
||||
|
||||
if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
|
||||
if (response.status === 400 && response.body.title === "Member Exists")
|
||||
return {
|
||||
code: server_constants.RIS_SUBSCRIBED_ALREADYEXIST,
|
||||
msg: server_constants.RIS_SUBSCRIBED_MSG_ALREADYEXIST[locale]
|
||||
};
|
||||
else
|
||||
return {
|
||||
code: server_constants.RIS_SUBSCRIBED_OK,
|
||||
msg: server_constants.RIS_SUBSCRIBED_MSG[locale]
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
code: server_constants.RIS_SUBSCRIBED_ERR,
|
||||
msg: server_constants.RIS_SUBSCRIBED_MSG_FAILED[locale]
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
} else {
|
||||
return ris;
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
router.post('/signup', (req, res) => {
|
||||
|
||||
settomailchimp = req.body.settomailchimp;
|
||||
idapp = req.body.idapp;
|
||||
locale = req.body.locale;
|
||||
|
||||
const user = {
|
||||
email: req.body.email,
|
||||
name: req.body.firstName,
|
||||
surname: req.body.lastName,
|
||||
};
|
||||
|
||||
return AddMailingList(locale, idapp, user, settomailchimp, true).then((ris) => {
|
||||
return res.send(ris);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
async function ImportData(locale, idapp, strdata, settomailchimp) {
|
||||
|
||||
try {
|
||||
let numadded = 0;
|
||||
let numtot = 0;
|
||||
let numalreadyexisted = 0;
|
||||
|
||||
// Convert to array
|
||||
let arrusers = strdata.split('\n');
|
||||
if (arrusers.length <= 0)
|
||||
arrusers = strdata.split(',');
|
||||
if (arrusers.length <= 0)
|
||||
arrusers = strdata.split(';');
|
||||
if (arrusers.length <= 0)
|
||||
arrusers = strdata.split('\t');
|
||||
|
||||
let sep = '';
|
||||
|
||||
// Controlla se ci sono spazi
|
||||
const arrtab = arrusers[0].split('\t');
|
||||
const arrspace = arrusers[0].split(' ');
|
||||
const arrcomma = arrusers[0].split(',');
|
||||
if (arrtab.length > 1) {
|
||||
sep = '\t';
|
||||
}
|
||||
if (arrspace.length > 1) {
|
||||
sep = ' '
|
||||
}
|
||||
if (arrcomma.length > 1) {
|
||||
sep = ','
|
||||
}
|
||||
|
||||
console.log('arrtab', arrtab);
|
||||
console.log('arrspace', arrspace);
|
||||
console.log('arrcomma', arrcomma);
|
||||
|
||||
console.log('sep', sep);
|
||||
|
||||
|
||||
try {
|
||||
for (const row of arrusers) {
|
||||
if (sep !== '') {
|
||||
let arrrow = row.split(sep);
|
||||
if (arrrow.length === 1) {
|
||||
user = {
|
||||
name: '',
|
||||
surname: '',
|
||||
email: arrrow[0]
|
||||
}
|
||||
} else {
|
||||
user = {
|
||||
name: arrrow[0],
|
||||
surname: arrrow[1],
|
||||
email: arrrow[2],
|
||||
}
|
||||
}
|
||||
} else {
|
||||
user = {
|
||||
name: '',
|
||||
surname: '',
|
||||
email: row
|
||||
}
|
||||
}
|
||||
console.log('user', user);
|
||||
if (user.email.indexOf('@') > -1) {
|
||||
numtot++;
|
||||
|
||||
await AddMailingList(locale, idapp, user, settomailchimp, false).then((ris) => {
|
||||
console.log('Addmail user', user, 'ris', ris);
|
||||
if (ris.code === server_constants.RIS_SUBSCRIBED_OK)
|
||||
numadded++;
|
||||
else if (ris.code === server_constants.RIS_SUBSCRIBED_ALREADYEXIST)
|
||||
numalreadyexisted++;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
|
||||
ris = { numadded, numtot, numalreadyexisted };
|
||||
|
||||
console.log(ris);
|
||||
return ris
|
||||
|
||||
} catch (e) {
|
||||
console.err(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
router.post('/import', async (req, res) => {
|
||||
|
||||
settomailchimp = req.body.settomailchimp;
|
||||
const strdata = req.body.strdataemail;
|
||||
idapp = req.body.idapp;
|
||||
locale = req.body.locale;
|
||||
|
||||
const ris = await ImportData(locale, idapp, strdata, settomailchimp);
|
||||
console.log('ris', ris);
|
||||
|
||||
res.send(ris);
|
||||
});
|
||||
|
||||
async function getDataNewsletter(lang, idapp) {
|
||||
const arrml = await MailingList.findAllIdApp(idapp);
|
||||
|
||||
const lastnewstosent = await Newstosent.getlast(idapp);
|
||||
const nextnewstosent = await Newstosent.findNewsletter_To_Send(idapp);
|
||||
const lastid = (lastnewstosent) ? lastnewstosent._id : 0;
|
||||
|
||||
const data = {
|
||||
lastnewstosent,
|
||||
nextnewstosent,
|
||||
totemail: 0,
|
||||
totsubscribed: 0,
|
||||
totunsubscribed: 0,
|
||||
totsentlastid: 0,
|
||||
};
|
||||
|
||||
for (const user of arrml) {
|
||||
data.totemail++;
|
||||
if (user.news_on)
|
||||
data.totsubscribed++;
|
||||
else
|
||||
data.totunsubscribed++;
|
||||
if (user.lastid_newstosent === lastid) {
|
||||
data.totsentlastid++;
|
||||
}
|
||||
}
|
||||
|
||||
// await tools.snooze(2000);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
router.post('/load', authenticate, async (req, res) => {
|
||||
|
||||
idapp = req.body.idapp;
|
||||
locale = req.body.locale;
|
||||
|
||||
let ris;
|
||||
|
||||
try {
|
||||
ris = {
|
||||
newsstate: await getDataNewsletter(locale, idapp),
|
||||
serv_settings: await Settings.findAllIdApp(idapp, true, false),
|
||||
templemail: await TemplEmail.findAllIdApp(idapp, true),
|
||||
destnewsletter: await DestNewsletter.findAllIdApp(idapp, true),
|
||||
opzemail: await OpzEmail.findAllIdApp(idapp)
|
||||
};
|
||||
|
||||
} catch (e) {
|
||||
console.error('Errore load newsletter: ', e);
|
||||
ris = { code: server_constants.RIS_CODE_ERR, msg: e.message };
|
||||
}
|
||||
|
||||
return res.send(ris);
|
||||
});
|
||||
|
||||
router.post('/setactivate', authenticate, async (req, res) => {
|
||||
|
||||
idapp = req.body.idapp;
|
||||
activate = req.body.activate;
|
||||
id = req.body._id;
|
||||
locale = req.body.locale;
|
||||
|
||||
const rec = {
|
||||
activate,
|
||||
};
|
||||
|
||||
try {
|
||||
const item = await Newstosent.findOneAndUpdate({ _id: id }, { $set: rec }, { new: false });
|
||||
|
||||
if (item) {
|
||||
const ris = await getDataNewsletter(locale, idapp);
|
||||
return res.send(ris);
|
||||
} else {
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: 'Record not found' });
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message });
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
router.post('/unsubscribe_user', async (req, res) => {
|
||||
hashemail = req.body.em;
|
||||
email = req.body.email;
|
||||
idapp = req.body.idapp;
|
||||
locale = req.body.locale ?? 'it';
|
||||
|
||||
try {
|
||||
const myuser = await User.findOne({ idapp, email }).lean();
|
||||
|
||||
if (myuser) {
|
||||
const hashcalc = tools.getHash(myuser.email + myuser.username);
|
||||
|
||||
if (hashcalc === hashemail) {
|
||||
await User.setNewsletter(idapp, myuser.username, false);
|
||||
|
||||
return res.send({
|
||||
code: server_constants.RIS_UNSUBSCRIBED_OK,
|
||||
msg: server_constants.RIS_SUBSCRIBED_MSG[locale]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error('err', e);
|
||||
}
|
||||
res.send({
|
||||
code: server_constants.RIS_SUBSCRIBED_ERR
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
|
||||
router.post('/unsubscribe', (req, res) => {
|
||||
|
||||
console.log('unsubscribe -> ', req.body);
|
||||
|
||||
hashemail = req.body.em;
|
||||
mailchimpactive = tools.StrToBool(req.body.mc);
|
||||
idapp = req.body.idapp;
|
||||
locale = req.body.locale;
|
||||
|
||||
sendemail.Remove_from_MailingList(locale, hashemail, idapp).then((ris) => {
|
||||
console.log('Remove_from_MailingList -> ', ris);
|
||||
|
||||
if (!!ris.myperson && mailchimpactive) {
|
||||
try {
|
||||
const subscriber_md5_email = tools.getmd5(ris.myperson.email);
|
||||
request
|
||||
.put('https://' + newsletter[idapp].mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + newsletter[idapp].listUniqueId + '/members/' + subscriber_md5_email)
|
||||
.set('Content-Type', 'application/json;charset=utf-8')
|
||||
.set('Authorization', 'Basic ' + new Buffer('any:' + newsletter[idapp].mailchimpApiKey).toString('base64'))
|
||||
.send({
|
||||
'email_address': ris.myperson.email,
|
||||
'status': server_constants.RIS_UNSUBSCRIBED_STR
|
||||
})
|
||||
.end(function (err, response) {
|
||||
console.log("STAT", response.status);
|
||||
|
||||
if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
|
||||
res.send({
|
||||
code: server_constants.RIS_UNSUBSCRIBED_OK
|
||||
});
|
||||
} else {
|
||||
res.send({
|
||||
code: server_constants.RIS_SUBSCRIBED_ERR
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
console.error('Errore unsubscribe -> ', e);
|
||||
res.send({
|
||||
code: server_constants.RIS_SUBSCRIBED_ERR,
|
||||
msg: e.message
|
||||
});
|
||||
}
|
||||
|
||||
} else {
|
||||
res.send({ code: ris.code, msg: ris.msg });
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
router.post('/testemail', authenticate, async (req, res) => {
|
||||
|
||||
if (!User.isAdmin(req.user.perm)) {
|
||||
// If without permissions, exit
|
||||
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
|
||||
}
|
||||
|
||||
idapp = req.body.idapp;
|
||||
lang = req.body.locale;
|
||||
previewonly = req.body.previewonly;
|
||||
|
||||
const test = false;
|
||||
|
||||
let ris = null;
|
||||
|
||||
if (test) {
|
||||
const email = 'pao.loarena77@gmail.com';
|
||||
const myuser = await User.findOne({ idapp, email });
|
||||
|
||||
ris = await sendemail.testemailHtml(idapp, lang, email, myuser);
|
||||
} else {
|
||||
ris = await sendemail.testemail(idapp, lang, previewonly);
|
||||
}
|
||||
|
||||
if (ris)
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
|
||||
else
|
||||
return res.send({ code: server_constants.RIS_CODE_EMAIL_NOT_SENT, msg: '' });
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
131
src/router/orders_router.js
Executable file
@@ -0,0 +1,131 @@
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var { Project } = require('../models/project');
|
||||
|
||||
var { authenticate, auth_default } = require('../middleware/authenticate');
|
||||
|
||||
var mongoose = require('mongoose').set('debug', false)
|
||||
const Subscription = require('../models/subscribers');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const Product = require('../models/product');
|
||||
const Order = require('../models/order');
|
||||
const Variant = require('../models/variant');
|
||||
|
||||
const sendemail = require('../sendemail');
|
||||
const CartClass = require('../modules/Cart')
|
||||
const Cart = require('../models/cart');
|
||||
const OrdersCart = require('../models/orderscart');
|
||||
|
||||
//GET orders
|
||||
router.get('/:userId', authenticate, function (req, res, next) {
|
||||
let userId = req.body.userId;
|
||||
let idapp = req.body.idapp;
|
||||
OrdersCart.getOrdersCartByUserId(userId, idapp, 0, false)
|
||||
.then((cart) => {
|
||||
|
||||
if (cart)
|
||||
res.send({ code: server_constants.RIS_CODE_OK, cart });
|
||||
else
|
||||
res.status(400).send(e);
|
||||
})
|
||||
|
||||
});
|
||||
|
||||
router.post('/updateord', authenticate, async (req, res) => {
|
||||
const idOrdersCart = req.body.idOrdersCart;
|
||||
const idOrder = req.body.idOrder;
|
||||
const paramstoupdate = req.body.paramstoupdate;
|
||||
|
||||
try {
|
||||
// Aggiorno l'Ordine Singolo
|
||||
await Order.updateOrderByParams(idOrder, paramstoupdate);
|
||||
|
||||
// Aggiorno il Totale degli Ordini (OrdersCart)
|
||||
await OrdersCart.updateOrdersCartTotals(idOrdersCart, true)
|
||||
.then((orderscart) => {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, orderscart });
|
||||
}).catch(err => {
|
||||
console.log('ERR:', err);
|
||||
res.status(400).send();
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Err', e);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
router.post('/update', authenticate, async (req, res) => {
|
||||
let orderscart = null;
|
||||
const idOrdersCart = req.body.idOrdersCart;
|
||||
const paramstoupdate = req.body.paramstoupdate;
|
||||
|
||||
try {
|
||||
// Aggiorno Orderscart con i parametri passati
|
||||
orderscart = await OrdersCart.updateOrdersCartByParams(idOrdersCart, paramstoupdate);
|
||||
|
||||
let updatetotals = true;
|
||||
if (paramstoupdate && paramstoupdate.hasOwnProperty('totalPrice')) {
|
||||
updatetotals = false;
|
||||
}
|
||||
if (updatetotals) {
|
||||
|
||||
// Aggiorno il Totale degli Ordini (OrdersCart)
|
||||
await OrdersCart.updateOrdersCartTotals(idOrdersCart, true)
|
||||
.then((orderscart) => {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, orderscart });
|
||||
}).catch(err => {
|
||||
console.log('ERR:', err);
|
||||
res.status(400).send();
|
||||
});
|
||||
} else {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, orderscart });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Err', e);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
|
||||
router.post('/sendmail', authenticate, async function (req, res, next) {
|
||||
const idOrdersCart = req.body.idOrdersCart;
|
||||
const idapp = req.body.idapp;
|
||||
const test = req.body.test;
|
||||
const previewonly = req.body.previewonly;
|
||||
const templemail_id = req.body.templemail_id;
|
||||
|
||||
try {
|
||||
// Invia Email
|
||||
let myOrderCart = await OrdersCart.getOrdersCartById(idOrdersCart);
|
||||
if (myOrderCart) {
|
||||
const userto = myOrderCart.user;
|
||||
let emailto = userto.email;
|
||||
|
||||
if (userto && emailto) {
|
||||
const emailsend = await sendemail.sendEmail_byTemplate(idapp, userto, previewonly, emailto, templemail_id, test);
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, emailsend });
|
||||
}
|
||||
}
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, emailsend: false });
|
||||
|
||||
} catch (e) {
|
||||
console.error('err:', e);
|
||||
res.status(400).send(e);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
102
src/router/products_router.js
Executable file
@@ -0,0 +1,102 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var { Project } = require('../models/project');
|
||||
|
||||
const { User } = require('../models/user');
|
||||
|
||||
var { authenticate, auth_default } = require('../middleware/authenticate');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const Product = require('../models/product');
|
||||
const OrdersCart = require('../models/orderscart');
|
||||
const Variant = require('../models/variant');
|
||||
|
||||
/*const Department = require('../models/Department')
|
||||
const Category = require('../models/Category')
|
||||
const TypedError = require('../modules/ErrorHandler')
|
||||
const paypal_config = require('../configs/paypal-config')
|
||||
const paypal = require('paypal-rest-sdk')
|
||||
*/
|
||||
|
||||
const CartClass = require('../modules/Cart')
|
||||
const Cart = require('../models/cart');
|
||||
|
||||
//GET /products
|
||||
router.post('/', auth_default, async function (req, res, next) {
|
||||
const idapp = req.body.idapp;
|
||||
const userId = req.body.userId;
|
||||
|
||||
let ismanager = await tools.isManagerByReq(req);
|
||||
|
||||
let products = await Product.findAllIdApp(idapp, "", undefined, ismanager);
|
||||
let orders = null;
|
||||
if (ismanager) {
|
||||
// Prende Tutti gli Ordini !
|
||||
orders = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false);
|
||||
} else {
|
||||
orders = await OrdersCart.getOrdersCartByUserId(userId, idapp, 0, false);
|
||||
}
|
||||
|
||||
/*
|
||||
let ind = 0;
|
||||
for (const ord of orders) {
|
||||
let newitems = []
|
||||
for (myord of ord.items) {
|
||||
if (!myord.order) {
|
||||
console.log('NO ORDINE ', myord, 'Ind=', ind);
|
||||
} else {
|
||||
if (myord.order && !myord.order.hasOwnProperty('idGasordine')) {
|
||||
console.log('NO idGasordine', myord);
|
||||
} else {
|
||||
newitems.push(myord)
|
||||
}
|
||||
}
|
||||
}
|
||||
ind++;
|
||||
|
||||
ord.items = newitems
|
||||
}
|
||||
*/
|
||||
|
||||
if (products)
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, products, orders });
|
||||
else
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_OK, products, orders });
|
||||
|
||||
});
|
||||
|
||||
router.post('/:code', auth_default, async function (req, res, next) {
|
||||
const idapp = req.body.idapp;
|
||||
const code = req.body.code;
|
||||
|
||||
var product = await Product.findAllIdApp(idapp, code);
|
||||
|
||||
if (product.length > 0) {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, product: product[0] });
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
router.get('/id/:id', async function (req, res) {
|
||||
|
||||
const id = req.params.id;
|
||||
|
||||
var product = await Product.getProductById(id);
|
||||
|
||||
// console.log('Product ID', id, product);
|
||||
|
||||
if (product) {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, product: product });
|
||||
} else {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, product: null });
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
269
src/router/projects_router.js
Executable file
@@ -0,0 +1,269 @@
|
||||
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');
|
||||
|
||||
// var mongoose = require('mongoose').set('debug', false)
|
||||
|
||||
const { Project } = require('../models/project');
|
||||
const { Todo } = require('../models/todo');
|
||||
const { User } = require('../models/user');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
|
||||
router.post('/', authenticate, (req, res) => {
|
||||
|
||||
var body = _.pick(req.body, tools.allfieldProjectWithId());
|
||||
// tools.mylogshow('PROJ INPUT', body);
|
||||
var project = new Project(body);
|
||||
|
||||
// project.expiring_at = new Date(project.expiring_at);
|
||||
|
||||
tools.mylog('ID :', project._id, project.descr, project.userId, req.user._id);
|
||||
|
||||
if (!('descr' in req.body)) {
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
|
||||
}
|
||||
|
||||
const check = tools.checkUserOk(project.userId, req.user._id, res);
|
||||
if (check.exit) return check.ret;
|
||||
|
||||
tools.mylog('PROJECT POST :', project.descr, project._id);
|
||||
|
||||
project.modified = false;
|
||||
if (!project.descr) {
|
||||
console.log('RECORD NON VALIDO !?', req.body)
|
||||
}
|
||||
|
||||
project.save().then((writeresult) => {
|
||||
let idobj = writeresult._id;
|
||||
Project.findById(idobj)
|
||||
.then(async (record) => {
|
||||
|
||||
await tools.sendNotificationToUser(record.userId, '[Progetto]: ' + record.descr, record.descr, '/todo/' + record._id, '', 'todo', [])
|
||||
|
||||
res.send({ record: record._doc });
|
||||
|
||||
/*
|
||||
tools.sendNotificationToUser(project.userId, 'Project: ' + record.descr, record.descr, '/project/' + project.category, '', 'project', [])
|
||||
.then(ris => {
|
||||
if (ris) {
|
||||
res.send({ record });
|
||||
} else {
|
||||
// already sent the error on calling sendNotificationToUser
|
||||
}
|
||||
})
|
||||
|
||||
*/
|
||||
})
|
||||
}).catch((e) => {
|
||||
console.log('ERRORE in PROJECT POST', e.message);
|
||||
res.status(400).send(e);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
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);
|
||||
|
||||
if (!ObjectId.isValid(id)) {
|
||||
tools.mylog('ERROR: id not VALID', id);
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
// check if you are able to modify this project
|
||||
if (!Project.enabletoModify(String(req.user._id), id))
|
||||
return res.status(404).send();
|
||||
|
||||
Project.findByIdAndUpdate(id, { $set: body }, { new: true }).then((project) => {
|
||||
tools.mylogshow(' PROJECT TO MODIFY: ', project.descr);
|
||||
if (!project) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
if (project.userId !== String(req.user._id) && project.privacywrite === server_constants.Privacy.onlyme) {
|
||||
// I'm trying to write something not mine!
|
||||
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
|
||||
}
|
||||
|
||||
project.modified = false;
|
||||
|
||||
// Recalculate
|
||||
return calcSingleProject('', project)
|
||||
.then(objout => {
|
||||
tools.mylog('PATCH ', project.descr, project._id, project.progressCalc);
|
||||
|
||||
return Project.findById(id).then((projectris) => {
|
||||
// console.log('projectris progressCalc', projectris.progressCalc);
|
||||
res.send({ projectris });
|
||||
});
|
||||
});
|
||||
|
||||
}).catch((e) => {
|
||||
tools.mylogserr('Error patch PROJECT: ', e);
|
||||
res.status(400).send();
|
||||
})
|
||||
});
|
||||
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
tools.mylog('GET ALL PROJECTS: ');
|
||||
const idapp = req.query.idapp;
|
||||
|
||||
return Project.getAllProjects('', idapp).then((objprojects) => {
|
||||
if (!!objprojects.arrproj)
|
||||
tools.mylog('projects', objprojects.arrproj.length);
|
||||
|
||||
return objprojects
|
||||
}).then((objprojects) => {
|
||||
res.send({ projects: objprojects.arrproj });
|
||||
}).catch((e) => {
|
||||
console.log(e.message);
|
||||
res.status(400).send(e);
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/calc/:id/:actualphase', authenticate, (req, res) => {
|
||||
var id = req.params.id;
|
||||
var actualphase = parseInt(req.params.actualphase);
|
||||
|
||||
return Todo.calculateTreeTodo(actualphase, '', id, false, id, false)
|
||||
.then((rec) => {
|
||||
return res.send({ rec });
|
||||
})
|
||||
.catch((err) => {
|
||||
res.status(400).send();
|
||||
});
|
||||
|
||||
})
|
||||
;
|
||||
|
||||
|
||||
router.get('/:userId', authenticate, (req, res) => {
|
||||
const userId = req.params.userId;
|
||||
const idapp = req.query.idapp;
|
||||
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
// Receive the Projects only for specific Users:
|
||||
return User.isUserVisuProjects(idapp, req.user.username).then((isresidente) => {
|
||||
// Extract all the projects of the userId only
|
||||
if (!isresidente)
|
||||
return res.send({ projects: [] });
|
||||
|
||||
return Project.getAllProjects(userId, idapp).then((objprojects) => {
|
||||
if (!!objprojects.arrproj)
|
||||
tools.mylog('projects', objprojects.arrproj.length);
|
||||
|
||||
return objprojects
|
||||
|
||||
}).then((objprojects) => {
|
||||
|
||||
res.send({ projects: objprojects.arrproj });
|
||||
|
||||
}).catch((e) => {
|
||||
console.log(e.message);
|
||||
res.status(400).send(e);
|
||||
});
|
||||
|
||||
})
|
||||
|
||||
});
|
||||
|
||||
|
||||
/*
|
||||
// USATO SOLO LE PRIME VOLTE! O A RICHIESTA!
|
||||
async function calcProjects(userId, obj) {
|
||||
|
||||
// let myarr = tools.jsonCopy(obj.arrproj);
|
||||
let myarr = [...obj.arrproj];
|
||||
|
||||
if (myarr.length > 0) {
|
||||
let promiseChain = Promise.resolve();
|
||||
|
||||
for (const rec of myarr) {
|
||||
promiseChain = promiseChain.then(() => {
|
||||
// Find the todos for this project
|
||||
// Calculate the Progression of the Project // sum the progression
|
||||
return Todo.calculateTreeTodo(userId, rec._id)
|
||||
})
|
||||
}
|
||||
return promiseChain
|
||||
} else {
|
||||
return new Promise((resolve, reject) => {
|
||||
resolve()
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
// USATO SOLO LE PRIME VOLTE! O A RICHIESTA!
|
||||
async function calcSingleProject(userId, myproj) {
|
||||
|
||||
return await Todo.calculateTreeTodo(myproj.actualphase, userId, myproj._id, false, myproj._id, false)
|
||||
|
||||
}
|
||||
|
||||
router.delete('/:id', authenticate, (req, res) => {
|
||||
var id = req.params.id;
|
||||
|
||||
const hide = true;
|
||||
|
||||
if (!ObjectId.isValid(id)) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
if (hide) {
|
||||
Project.findByIdAndUpdate(id, { $set: { deleted: true } }).then((project) => {
|
||||
if (!project) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
res.send({ project });
|
||||
}).catch((e) => {
|
||||
res.status(400).send();
|
||||
});
|
||||
|
||||
} else {
|
||||
|
||||
Project.deleteOne({_id: id}).then((project) => {
|
||||
if (!project) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
tools.mylog('DELETED ', project.descr, project._id);
|
||||
|
||||
res.send({ project });
|
||||
}).catch((e) => {
|
||||
res.status(400).send();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
156
src/router/push_router.js
Executable file
@@ -0,0 +1,156 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const mongoose = require('mongoose').set('debug', false);
|
||||
const Subscription = require('../models/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');
|
||||
|
||||
const globalTables = require('../tools/globalTables');
|
||||
|
||||
router.post('/', async (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,
|
||||
};
|
||||
|
||||
try {
|
||||
const subscriptions = await Subscription.find({});
|
||||
} catch (err) {
|
||||
console.error(`Error occurred while getting subscriptions`);
|
||||
res.status(500).json({
|
||||
error: 'Technical error occurred',
|
||||
});
|
||||
}
|
||||
|
||||
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.VAPI_KEY_SUBJECT,
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
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(async (arrusers) => {
|
||||
if (arrusers !== null) {
|
||||
for (const user of arrusers) {
|
||||
await tools.sendNotificationToUser(user._id, params.title, params.content,
|
||||
params.openUrl, params.openUrl2, params.tag, params.actions, params.id).
|
||||
then(ris => {
|
||||
if (ris) {
|
||||
|
||||
} else {
|
||||
// already sent the error on calling sendNotificationToUser
|
||||
}
|
||||
}).
|
||||
catch(e => {
|
||||
console.error(e.message);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
router.post('/send', authenticate, async (req, res) => {
|
||||
const idapp = req.body.idapp;
|
||||
const params = req.body.params;
|
||||
|
||||
// console.log('params', params);
|
||||
|
||||
let nummsg = 0;
|
||||
|
||||
if ((!User.isAdmin(req.user.perm) && !User.isManager(req.user.perm) &&
|
||||
!User.isFacilitatore(req.user.perm))) {
|
||||
// If without permissions, exit
|
||||
return res.status(404).
|
||||
send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
|
||||
}
|
||||
|
||||
let msgcosa = 'da Inviare';
|
||||
if (params.sendreally) {
|
||||
msgcosa = 'Inviati';
|
||||
}
|
||||
|
||||
try {
|
||||
if (params.typemsg === shared_consts.TypeMsg.SEND_TO_MYSELF) {
|
||||
params.usernameDest = req.user.username;
|
||||
}
|
||||
|
||||
const ris = await globalTables.SendMsgToParam(idapp, params);
|
||||
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
msg: ris.nummsgsent + ` Msg ${msgcosa} su ` + ris.numrec + ' !',
|
||||
nummsg: ris.nummsgsent,
|
||||
});
|
||||
} catch (e) {
|
||||
return res.send(
|
||||
{ code: server_constants.RIS_CODE_ERR, msg: nummsg + ` Msg ${msgcosa} !` });
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
res.json({
|
||||
data: 'Invalid Request Bad',
|
||||
});
|
||||
});
|
||||
module.exports = router;
|
||||
126
src/router/reactions_router.js
Executable file
@@ -0,0 +1,126 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const { Reaction } = require('../models/reaction');
|
||||
|
||||
const { User } = require('../models/user');
|
||||
|
||||
const Hours = require('../models/hours');
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const sendemail = require('../sendemail');
|
||||
|
||||
const { Settings } = require('../models/settings');
|
||||
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
|
||||
const tools = require('../tools/general');
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const server_constants = require('../tools/server_constants');
|
||||
|
||||
const telegrambot = require('../telegram/telegrambot');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const reg = require('../reg/registration');
|
||||
|
||||
const { authenticate, authenticate_noerror } = require('../middleware/authenticate');
|
||||
|
||||
const TypedError = require('../modules/ErrorHandler');
|
||||
const globalTables = require('../tools/globalTables');
|
||||
|
||||
const mongoose = require('mongoose').set('debug', false);
|
||||
|
||||
router.post('/cmd', authenticate, async (req, res) => {
|
||||
|
||||
const mydata = req.body.mydata;
|
||||
const idapp = req.body.idapp;
|
||||
const cmd = req.body.cmd;
|
||||
const id = req.body.id;
|
||||
const tab = req.body.tab;
|
||||
const num = req.body.num;
|
||||
const value = req.body.value;
|
||||
|
||||
try {
|
||||
const table = tools.getTableByNumTab(tab);
|
||||
const mytable = globalTables.getTableByTableName(table);
|
||||
let username = '';
|
||||
if (req.user) {
|
||||
username = req.user.username;
|
||||
} else {
|
||||
return res.send({ state: 0, record: null });
|
||||
}
|
||||
|
||||
let ris = null;
|
||||
let record = null;
|
||||
|
||||
const { User } = require('../models/user');
|
||||
|
||||
let objtoupdate = {};
|
||||
|
||||
if (cmd === shared_consts.CMD_REACTION.SET_FAVORITE) {
|
||||
if (tab) {
|
||||
if (value) {
|
||||
ris = await Reaction.addFavorite(req, idapp, username, id, tab);
|
||||
} else {
|
||||
ris = await Reaction.removeFavorite(idapp, username, id, tab);
|
||||
}
|
||||
}
|
||||
|
||||
} else if (cmd === shared_consts.CMD_REACTION.SET_BOOKMARK) {
|
||||
if (tab) {
|
||||
if (value)
|
||||
ris = await Reaction.addBookmark(req, idapp, username, id, tab);
|
||||
else
|
||||
ris = await Reaction.removeBookmark(idapp, username, id, tab);
|
||||
|
||||
}
|
||||
} else if (cmd === shared_consts.CMD_REACTION.SET_ATTEND) {
|
||||
if (tab) {
|
||||
if (value)
|
||||
ris = await Reaction.addAttend(req, idapp, username, id, tab, num);
|
||||
else
|
||||
ris = await Reaction.removeAttend(idapp, username, id, tab);
|
||||
|
||||
}
|
||||
} else if (cmd === shared_consts.CMD_REACTION.SET_SEEN) {
|
||||
if (tab) {
|
||||
if (value) {
|
||||
ris = await Reaction.addSeen(req, idapp, username, id, tab);
|
||||
}
|
||||
const tabtofind = tools.getNumTabByTable('mybachecas');
|
||||
if (tab === tabtofind) {
|
||||
const { MyBacheca } = require('../models/mybacheca');
|
||||
record = await MyBacheca.getCompleteRecord(idapp, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let state = (value && ris && ris.acknowledged) ? 1 : ((!value && ris && ris.acknowledged) ? -1 : 0);
|
||||
|
||||
const risreac = await Reaction.calcReactions(idapp, id, tab);
|
||||
if (risreac) {
|
||||
delete risreac._id;
|
||||
objtoupdate = risreac;
|
||||
}
|
||||
|
||||
if (mytable) {
|
||||
ris = await mytable.updateOne({ _id: id }, {
|
||||
$set: objtoupdate,
|
||||
})
|
||||
}
|
||||
|
||||
return res.send({ state, record });
|
||||
|
||||
} catch (e) {
|
||||
res.status(400).send();
|
||||
res.send({ code: server_constants.RIS_CODE_ERR, msg: e, state: null, record: null });
|
||||
|
||||
console.log(e.message);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
164
src/router/report_router.js
Executable file
@@ -0,0 +1,164 @@
|
||||
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');
|
||||
|
||||
// var mongoose = require('mongoose').set('debug', false)
|
||||
|
||||
const { Project } = require('../models/project');
|
||||
const { Todo } = require('../models/todo');
|
||||
const { User } = require('../models/user');
|
||||
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const Hours = require('../models/hours');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
router.post('/load', authenticate, async (req, res) => {
|
||||
let date_start = req.body.date_start;
|
||||
const date_end = req.body.date_end;
|
||||
const filter = req.body.filter;
|
||||
const idapp = req.body.idapp;
|
||||
|
||||
// tools.mylog('GET REPORT : ');
|
||||
|
||||
// Ottieni la reportistica
|
||||
// dei progetti
|
||||
// degli utenti Residenti
|
||||
// di tutta la settimana
|
||||
|
||||
try {
|
||||
// Ottieni la lista dei Residenti
|
||||
const listaResidenti = await User.getUsersResidenti(idapp);
|
||||
|
||||
// Extract all the projects of the userId only
|
||||
const objprojects = await Project.getAllProjects('', idapp);
|
||||
|
||||
const arrhour = {};
|
||||
|
||||
// date_start = '2021-03-04T01:37:47.969Z';
|
||||
|
||||
// let mydatets = tools.dateToEpoch(date_start)
|
||||
// let mydate = new Date(tools.getstrDateYYYY_MM_DD(new Date(date_start)));
|
||||
let mydate = new Date(date_start);
|
||||
let mydatestr = mydate.toDateString();
|
||||
let mydatets = tools.dateToEpoch(mydatestr) + (new Date().getTimezoneOffset() * 60 * 1000);
|
||||
mydate = new Date(mydatets);
|
||||
let mydateyyymmdd = tools.getstrUTCDateYYYY_MM_DD(tools.AddDate(new Date(mydatestr), 1));
|
||||
|
||||
let mydatets_end = tools.dateToEpoch(date_end);
|
||||
|
||||
for (const myuser of listaResidenti) {
|
||||
arrhour[myuser.username] = [];
|
||||
}
|
||||
|
||||
let totalacchours = [];
|
||||
for (const myuser of listaResidenti) {
|
||||
totalacchours[myuser.username] = 0;
|
||||
}
|
||||
|
||||
let rectotal = {};
|
||||
|
||||
|
||||
while (mydatets <= mydatets_end) {
|
||||
// console.log('mydatets', mydatets, 'mydate', mydate);
|
||||
for (const myuser of listaResidenti) {
|
||||
// for (const myproj of objprojects.arrproj) {
|
||||
//let myhours = await Hours.getHoursByIdCat(idapp, myuser._id, myproj._id, date_start, date_end);
|
||||
let rechours = await Hours.getHoursByDate(idapp, myuser._id, mydate);
|
||||
let ressum = await Hours.getTotalHoursByDate(idapp, myuser.id, mydate);
|
||||
|
||||
if (tools.isMondayDate(mydate)) {
|
||||
totalacchours[myuser.username] = 0;
|
||||
}
|
||||
|
||||
if ((ressum > 0) || ((tools.isSundayDate(mydate)) && totalacchours[myuser.username] > 0)) {
|
||||
totalacchours[myuser.username] = totalacchours[myuser.username] + ressum;
|
||||
rectotal = {
|
||||
totalhours: ressum,
|
||||
totalacchours: 0,
|
||||
date: mydateyyymmdd,
|
||||
}
|
||||
|
||||
if (tools.isSunday(mydatets)) {
|
||||
rectotal.totalacchours = totalacchours[myuser.username];
|
||||
}
|
||||
|
||||
if (tools.isBitActive(filter, shared_consts.REPORT_FILT_RESP)) {
|
||||
rectotal.resp = '';
|
||||
rectotal.viceResp = '';
|
||||
}
|
||||
|
||||
arrhour[myuser.username].push(rectotal);
|
||||
if (tools.isBitActive(filter, shared_consts.REPORT_FILT_ATTIVITA)) {
|
||||
for (const rec of rechours) {
|
||||
let myproj = await Project.findProjectByUserId('', rec.todoId);
|
||||
let colors = {
|
||||
themebgcolor: '',
|
||||
themecolor: ''
|
||||
}
|
||||
if (!myproj) {
|
||||
const mytodo = await Todo.findOne({ _id: rec.todoId });
|
||||
if (!!mytodo) {
|
||||
colors.themebgcolor = mytodo.themebgcolor;
|
||||
colors.themecolor = mytodo.themecolor;
|
||||
myproj = await Project.findProjectByUserId('', mytodo.category);
|
||||
if (!colors.themebgcolor && myproj) {
|
||||
colors.themebgcolor = myproj.themebgcolor;
|
||||
colors.themecolor = myproj.themecolor;
|
||||
}
|
||||
}
|
||||
// E' un Todo, trova il proj
|
||||
} else {
|
||||
colors.themebgcolor = myproj.themebgcolor;
|
||||
colors.themecolor = myproj.themecolor;
|
||||
}
|
||||
if (!colors.themebgcolor || colors.themebgcolor === 'white') {
|
||||
if (myproj) {
|
||||
colors = await Project.findColorsByProject(myproj._id);
|
||||
}
|
||||
}
|
||||
if (myproj) {
|
||||
const myrec = {
|
||||
title: rec.hours + 'h - ' + myproj.descr,
|
||||
details: myproj.longdescr,
|
||||
date: tools.getstrDateYYYY_MM_DD(mydate),
|
||||
bgcolor: colors.themebgcolor,
|
||||
color: colors.themecolor
|
||||
}
|
||||
arrhour[myuser.username].push(myrec);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// }
|
||||
}
|
||||
|
||||
// console.log('mydatestr', mydatestr, 'mydateyyymmdd', mydateyyymmdd)
|
||||
// if (!!rectotal)
|
||||
// console.log('TOT', rectotal.totalacchours);
|
||||
|
||||
mydatets += 86400000;
|
||||
mydate = tools.AddDate(mydate, 1);
|
||||
mydatestr = mydate.toDateString();
|
||||
mydateyyymmdd = tools.getstrUTCDateYYYY_MM_DD(tools.AddDate(new Date(mydatestr), 1));
|
||||
}
|
||||
|
||||
return res.send({ listaResidenti, arrhour });
|
||||
|
||||
|
||||
} catch (e) {
|
||||
console.log(e.message);
|
||||
res.status(400).send(e);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
118
src/router/sendmsg_router.js
Executable file
@@ -0,0 +1,118 @@
|
||||
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 { SendMsg } = require('../models/sendmsg');
|
||||
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const sendemail = require('../sendemail');
|
||||
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const globalTables = require('../tools/globalTables');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
|
||||
router.post('/', authenticate, (req, res) => {
|
||||
tools.mylog('INIZIO - SendMsg');
|
||||
// tools.mylog('req.body', req.body);
|
||||
const body = _.pick(req.body, tools.allfieldSendMsg());
|
||||
|
||||
tools.mylog('crea SendMsg');
|
||||
const myrecmsg = new SendMsg(body);
|
||||
|
||||
if (req.user && req.user.username) {
|
||||
User.setOnLine(req.user.idapp, req.user.username);
|
||||
}
|
||||
|
||||
const check = tools.checkUserOk(myrecmsg.origin, req.user.username, res);
|
||||
if (check.exit) return check.ret;
|
||||
|
||||
// console.log('fieldtochange', fieldtochange);
|
||||
|
||||
myrecmsg._id = new ObjectId();
|
||||
return myrecmsg.save()
|
||||
.then((writeresult) => {
|
||||
let idobj = writeresult._id;
|
||||
|
||||
myrecmsg._id = idobj;
|
||||
|
||||
return SendMsg.findById(idobj)
|
||||
.then(async (recmsg) => {
|
||||
const myrecsend = new SendNotif(
|
||||
{
|
||||
title: recmsg.source.infoevent,
|
||||
sender: recmsg.origin,
|
||||
dest: recmsg.dest,
|
||||
openUrl: '',
|
||||
});
|
||||
// Add this field because I don't want to add into the database
|
||||
// myrecsend.source.infoevent = body.source.infoevent;
|
||||
|
||||
myrecsend.typedir = shared_consts.TypeNotifs.TYPEDIR_EVENTS;
|
||||
myrecsend.typeid = shared_consts.TypeNotifs.ID_EVENTS_SEND_MSG;
|
||||
myrecsend.msg = recmsg.message;
|
||||
let myid = recmsg._id;
|
||||
// ##Todo !! DA SISTEMARE !!!
|
||||
return await SendNotif.saveAndSendNotif(myrecsend, req, res).then((out) => {
|
||||
if (out)
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: myid });
|
||||
else
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
|
||||
})
|
||||
|
||||
});
|
||||
}).catch((e) => {
|
||||
console.error(e.message);
|
||||
// res.status(400).send(e);
|
||||
// return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
|
||||
})
|
||||
|
||||
let fine = '';
|
||||
|
||||
});
|
||||
|
||||
router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
|
||||
tools.mylog('GET SendMsgS : ', 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 && req.user.username) {
|
||||
User.setOnLine(req.user.idapp, req.user.username);
|
||||
}
|
||||
|
||||
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 SendMsg.findAllMsgByUsernameIdAndIdApp(username, lastdataread, idapp).then((arrmsg) => {
|
||||
// const wait = new Promise((resolve, reject) => {
|
||||
// setTimeout(() => {
|
||||
res.send({ arrmsg });
|
||||
// }, 2000);
|
||||
// });
|
||||
|
||||
}).catch((e) => {
|
||||
console.log(e.message);
|
||||
res.status(400).send(e);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
188
src/router/sendnotif_router.js
Executable file
@@ -0,0 +1,188 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
const server_constants = require('../tools/server_constants');
|
||||
|
||||
const { authenticate, authenticate_noerror } = require('../middleware/authenticate');
|
||||
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
const { User } = require('../models/user');
|
||||
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
router.post('/', authenticate, async (req, res) => {
|
||||
tools.mylog('INIZIO - SendNotif');
|
||||
// tools.mylog('req.body', req.body);
|
||||
const body = _.pick(req.body, tools.allfieldSendNotif());
|
||||
|
||||
tools.mylog('crea SendNotif');
|
||||
let myrecnotif = new SendNotif(body);
|
||||
|
||||
const recout = await SendNotif.saveAndSendNotif(myrecnotif, req, res);
|
||||
if (recout) {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, notif: '', record: recout });
|
||||
} else {
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, notif: '' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/setall/:username/:qualinotif/:idapp', authenticate, async (req, res) => {
|
||||
const idapp = req.params.idapp;
|
||||
const username = req.params.username;
|
||||
const qualinotif = parseInt(req.params.qualinotif);
|
||||
const username_call = req.user.username;
|
||||
|
||||
try {
|
||||
if (username === username_call) {
|
||||
let query = { idapp, dest: username, read: false };
|
||||
|
||||
if (qualinotif === shared_consts.QualiNotifs.CIRCUITS) {
|
||||
query.typedir = { $eq: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS };
|
||||
} else if (qualinotif === shared_consts.QualiNotifs.OTHERS) {
|
||||
query.typedir = { $ne: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS };
|
||||
}
|
||||
const arrNotifs = await SendNotif.find(query).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('/set/:_id/:idapp', authenticate, async (req, res) => {
|
||||
const _id = req.params._id;
|
||||
const username_call = req.user.username;
|
||||
|
||||
try {
|
||||
let query = { _id, dest: username_call, read: false };
|
||||
|
||||
const rec = await SendNotif.findOne(query);
|
||||
if (rec) {
|
||||
rec.read = true;
|
||||
await rec.save();
|
||||
return res.send(true);
|
||||
}
|
||||
res.send(false);
|
||||
} catch (e) {
|
||||
res.status(400).send(e);
|
||||
}
|
||||
});
|
||||
|
||||
async function delNotif(res, idapp, username, id, username_call) {
|
||||
try {
|
||||
if (username === username_call) {
|
||||
await SendNotif.findOneAndDelete({ idapp, _id: id });
|
||||
return res.send(true);
|
||||
}
|
||||
} catch (e) {
|
||||
return res.status(400).send(e);
|
||||
}
|
||||
|
||||
return res.send(false);
|
||||
}
|
||||
|
||||
router.get('/del/:username/:id/:idapp', authenticate, async (req, res) => {
|
||||
try {
|
||||
return delNotif(res, req.params.idapp, req.params.username, req.params.id, req.user.username);
|
||||
} catch (e) {
|
||||
return res.status(400).send(e);
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/delall/:username/:qualinotif/:idapp', authenticate, async (req, res) => {
|
||||
const idapp = req.params.idapp;
|
||||
const username = req.params.username;
|
||||
const qualinotif = parseInt(req.params.qualinotif);
|
||||
const username_call = req.user.username;
|
||||
|
||||
try {
|
||||
if (username === username_call) {
|
||||
let query = { idapp, dest: username };
|
||||
|
||||
if (qualinotif === shared_consts.QualiNotifs.CIRCUITS) {
|
||||
query.typedir = { $eq: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS };
|
||||
} else if (qualinotif === shared_consts.QualiNotifs.OTHERS) {
|
||||
query.typedir = { $ne: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS };
|
||||
}
|
||||
const ris = await SendNotif.deleteMany(query);
|
||||
if (ris) return res.send(true);
|
||||
}
|
||||
} catch (e) {
|
||||
return res.status(400).send(e);
|
||||
}
|
||||
|
||||
return res.send(false);
|
||||
});
|
||||
|
||||
router.get('/:username/:lastdataread/:idapp', authenticate_noerror, (req, res) => {
|
||||
return getNotif(req, res);
|
||||
});
|
||||
|
||||
async function getNotif(req, res) {
|
||||
try {
|
||||
// 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) {
|
||||
return res.status(200).send();
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
const arrnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(
|
||||
username,
|
||||
lastdataread,
|
||||
idapp,
|
||||
shared_consts.LIMIT_NOTIF_FOR_USER,
|
||||
shared_consts.QualiNotifs.OTHERS
|
||||
);
|
||||
let arrnotifcoins_inattesa = null;
|
||||
|
||||
if (await User.isAdminByUsername(idapp, req.user.username)) {
|
||||
arrnotifcoins_inattesa = await SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp);
|
||||
} else {
|
||||
arrnotifcoins_inattesa = await SendNotif.findAllNotifByUsernameIdAndIdApp(
|
||||
username,
|
||||
lastdataread,
|
||||
idapp,
|
||||
shared_consts.LIMIT_NOTIFCOINS_IN_ATTESA_FOR_USER,
|
||||
shared_consts.QualiNotifs.CIRCUITS,
|
||||
[{ status: 0 }]
|
||||
);
|
||||
}
|
||||
|
||||
const arrnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(
|
||||
username,
|
||||
lastdataread,
|
||||
idapp,
|
||||
shared_consts.LIMIT_NOTIFCOINS_FOR_USER,
|
||||
shared_consts.QualiNotifs.CIRCUITS,
|
||||
[{ status: { $ne: 0 } }]
|
||||
);
|
||||
|
||||
//++Todo: Ottimizzare ! Non occorre inviare tutti questi dati !!! Solo per il Circuito ?!
|
||||
const userprofile = await User.getExtraInfoByUsername(idapp, req.user.username);
|
||||
|
||||
return res.send({ arrnotif, arrnotifcoins: [...arrnotifcoins, ...arrnotifcoins_inattesa], userprofile });
|
||||
} catch (e) {
|
||||
console.log(e.message);
|
||||
res.status(400).send(e);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
57
src/router/site_router.js
Executable file
@@ -0,0 +1,57 @@
|
||||
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 { MyGroup } = require('../models/mygroup');
|
||||
const { User } = require('../models/user');
|
||||
const { Stat } = require('../models/stat');
|
||||
|
||||
const mongoose = require('mongoose').set('debug', false)
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
// const { ExtraList } = require('../models/extralist');
|
||||
|
||||
router.post('/load', async (req, res) => {
|
||||
const idapp = req.body.idapp;
|
||||
const username = req.body.username;
|
||||
|
||||
try {
|
||||
let datastat = await Stat.getStats(idapp);
|
||||
|
||||
if (datastat) {
|
||||
datastat.checkuser = await User.checkUser(idapp, username);
|
||||
}
|
||||
|
||||
res.send({ datastat });
|
||||
|
||||
} catch (e) {
|
||||
console.error('Error', e);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
let datastat = {
|
||||
num_tot_lista: 80,
|
||||
num_reg: 40,
|
||||
lastsreg: [
|
||||
{ username: 'prova3', name: 'Datti', surname: 'Una Mossa', nationality: 'gb', date_reg: new Date()},
|
||||
{ username: 'prova2', name: 'Pinco', surname: 'Pallino', nationality: 'de', date_reg: new Date()},
|
||||
{ username: 'paoloar77', name: 'Paolo', surname: 'Arena', nationality: 'it', date_reg: new Date()},
|
||||
{ username: 'mariorossi', name: 'Mario', surname: 'Rossi', nationality: 'es', date_reg: new Date()},
|
||||
{ username: 'prova4', name: 'Quanto', surname: 'Siamo Fighi', nationality: 'uk', date_reg: new Date()},
|
||||
{ username: 'prova5', name: 'Secondo', surname: 'PPP', nationality: 'sl', date_reg: new Date()},
|
||||
]
|
||||
};
|
||||
*/
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
118
src/router/subscribe_router.js
Executable file
@@ -0,0 +1,118 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const mongoose = require('mongoose').set('debug', false);
|
||||
const Subscription = require('../models/subscribers');
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var { authenticate } = require('../middleware/authenticate');
|
||||
|
||||
const isValidSaveRequest = (req, res) => {
|
||||
try {
|
||||
if (!req.body || !req.body.subs.endpoint) {
|
||||
res.status(400);
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.send(JSON.stringify({
|
||||
error: {
|
||||
id: 'no-endpoint',
|
||||
message: 'Subscription must have an endpoint',
|
||||
},
|
||||
}));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
router.post('/', authenticate, async (req, res) => {
|
||||
// console.log('req.body.others', req.body.others);
|
||||
|
||||
if (!isValidSaveRequest(req, res)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let subscriptionModel = new Subscription(req.body.subs);
|
||||
subscriptionModel.userId = req.body.others.userId;
|
||||
subscriptionModel.access = req.body.others.access;
|
||||
subscriptionModel.browser = req.get('User-Agent');
|
||||
|
||||
// console.log('subscriptionModel.browser', subscriptionModel.browser);
|
||||
|
||||
// Find if already exist
|
||||
await Subscription.findOne({
|
||||
userId: subscriptionModel.userId,
|
||||
access: subscriptionModel.access,
|
||||
browser: subscriptionModel.browser,
|
||||
}).then(itemsub => {
|
||||
return itemsub;
|
||||
}).catch(err => {
|
||||
// Not found
|
||||
return null;
|
||||
}).then(async (myitem) => {
|
||||
|
||||
if (myitem === null) {
|
||||
myitem = subscriptionModel;
|
||||
// tools.mylogshow('Subscription NOT EXISTED IN DB, so I use this created!')
|
||||
} else {
|
||||
myitem.endpoint = subscriptionModel.endpoint;
|
||||
myitem.keys = subscriptionModel.keys;
|
||||
myitem.createDate = new Date();
|
||||
}
|
||||
|
||||
try {
|
||||
const subscription = await myitem.save();
|
||||
|
||||
// Send 201 - resource created
|
||||
// res.status(201).json({ data: 'Subscription saved.' });
|
||||
|
||||
// console.log('New Subscription id=', subscriptionModel.userId);
|
||||
|
||||
// console.log('req.body', req.body)
|
||||
|
||||
if (req.body.options !== null) {
|
||||
// Invia una notifica PUSH (asincrona)
|
||||
tools.sendBackNotif(subscription, req.body.options);
|
||||
}
|
||||
// console.log('Subscription saved... ')
|
||||
return res.send({ data: 'Subscription saved.' });
|
||||
|
||||
return subscription;
|
||||
|
||||
} catch (err) {
|
||||
console.error(`Error occurred while saving subscription. Err: ${err}`);
|
||||
return res.status(500).json({
|
||||
error: 'Technical error occurred',
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
router.delete('/del', authenticate, async (req, res) => {
|
||||
// tools.mylog("TOKENREM = " + req.token);
|
||||
try {
|
||||
|
||||
if (req.user) {
|
||||
const browser = req.get('User-Agent');
|
||||
return await Subscription.findOneAndDelete(
|
||||
{ userId: req.user._id, access: req.access, browser }).then(() => {
|
||||
res.status(200).send();
|
||||
}, () => {
|
||||
res.status(400).send();
|
||||
});
|
||||
}
|
||||
res.status(400).send();
|
||||
} catch (e) {
|
||||
console.error('Err:', e.message);
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
res.json({
|
||||
data: 'Invalid Request Bad',
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
26
src/router/telegram_router.js
Normal file
@@ -0,0 +1,26 @@
|
||||
// ============================================
|
||||
// telegram.routes.js
|
||||
// ============================================
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const telegramController = require('../controllers/telegram.controller');
|
||||
var { authenticate } = require('../middleware/authenticate');
|
||||
|
||||
// Genera token di verifica (richiede autenticazione)
|
||||
router.post('/generate-token', authenticate, telegramController.generateVerificationToken);
|
||||
|
||||
// Controlla stato verifica (richiede autenticazione)
|
||||
router.get('/check-verification', authenticate, telegramController.checkVerification);
|
||||
|
||||
// Webhook pubblico per il bot Telegram
|
||||
router.post('/webhook', telegramController.telegramWebhook);
|
||||
|
||||
// Setup webhook (admin only, da chiamare una sola volta)
|
||||
router.post('/setup-webhook', telegramController.setupWebhook);
|
||||
|
||||
// Scollega Telegram
|
||||
router.delete('/unlink', authenticate, telegramController.unlinkTelegram);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
67
src/router/test_router.js
Executable file
@@ -0,0 +1,67 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var { Project } = require('../models/project');
|
||||
|
||||
var { authenticate } = require('../middleware/authenticate');
|
||||
|
||||
var mongoose = require('mongoose').set('debug', false)
|
||||
const Subscription = require('../models/subscribers');
|
||||
|
||||
var { Todo } = require('../models/todo');
|
||||
const { Settings } = require('../models/settings');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
|
||||
const todo = {
|
||||
// category: "personal",
|
||||
statustodo: 0,
|
||||
completed_at: new Date(),
|
||||
created_at: new Date(),
|
||||
descr: "Primo Task Esempio",
|
||||
enableExpiring: false,
|
||||
expiring_at: new Date(),
|
||||
modified: false,
|
||||
modify_at: new Date(),
|
||||
pos: 1,
|
||||
priority: 1,
|
||||
progress: 0,
|
||||
userId: '5e135ede41a7ee26519464f7'
|
||||
};
|
||||
|
||||
const myrec = new Todo(todo);
|
||||
myrec._id = new ObjectId();
|
||||
|
||||
const TodoOne = myrec.save().then((ris, err) => {
|
||||
console.log('Err:', err);
|
||||
console.log('Ris:', ris);
|
||||
|
||||
});
|
||||
|
||||
|
||||
const newrec = new Settings({ key: 'chiave1' });
|
||||
newrec._id = new ObjectId();
|
||||
newrec.idapp = '8';
|
||||
|
||||
const rec = await newrec.save();
|
||||
if (err)
|
||||
console.log('ERROR: ', err);
|
||||
if (rec) {
|
||||
console.log('SAVED? ', rec);
|
||||
}
|
||||
|
||||
res.send({});
|
||||
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
273
src/router/todos_router.js
Executable file
@@ -0,0 +1,273 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
var server_constants = require('../tools/server_constants');
|
||||
|
||||
var { Project } = require('../models/project');
|
||||
|
||||
var { authenticate } = require('../middleware/authenticate');
|
||||
|
||||
|
||||
var { Todo } = require('../models/todo');
|
||||
|
||||
const Hours = require('../models/hours');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
|
||||
router.post('/', authenticate, async (req, res) => {
|
||||
|
||||
var body = _.pick(req.body, tools.allfieldTodoWithId());
|
||||
// tools.mylogshow('INPUT', body);
|
||||
var todo = new Todo(body);
|
||||
|
||||
// todo.expiring_at = new Date(todo.expiring_at);
|
||||
|
||||
// tools.mylog('ID :', todo._id, todo.descr, todo.userId, req.user._id);
|
||||
|
||||
if (!('descr' in req.body)) {
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
|
||||
}
|
||||
|
||||
if (String(todo.userId) !== String(req.user._id)) {
|
||||
// I'm trying to write something not mine!
|
||||
tools.mylog('todo.userId = ', todo.userId, 'req.user._id', req.user._id)
|
||||
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
|
||||
}
|
||||
|
||||
// tools.mylog('TODO POST :', todo.descr, todo._id);
|
||||
|
||||
todo.modified = false;
|
||||
if (!todo.descr) {
|
||||
console.log('RECORD NON VALIDO !?', req.body)
|
||||
}
|
||||
|
||||
let prevrec = null;
|
||||
if (!!todo && todo._id)
|
||||
prevrec = await Todo.findById(todo._id);
|
||||
|
||||
return todo.save()
|
||||
.then((writeresult) => {
|
||||
let idobj = writeresult._id;
|
||||
return Todo.findById(idobj)
|
||||
.then(async (record) => {
|
||||
// tools.mylog('REC SAVED :', record.descr);
|
||||
|
||||
let aggiorna = false;
|
||||
let titolo = '';
|
||||
|
||||
if (prevrec) {
|
||||
if (todo.completed_at !== prevrec.completed_at) {
|
||||
aggiorna = true;
|
||||
titolo = 'Attività Completata!'
|
||||
}
|
||||
} else {
|
||||
aggiorna = true;
|
||||
}
|
||||
|
||||
if (aggiorna) {
|
||||
await tools.sendNotificationToUser(todo.userId, titolo + ' ' + record.descr, record.descr, '/todo/' + todo.category, '', 'todo', [])
|
||||
.then(ris => {
|
||||
if (ris) {
|
||||
return res.send({ record });
|
||||
} else {
|
||||
// already sent the error on calling sendNotificationToUser
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}).catch((e) => {
|
||||
console.log('ERRORE in TODO POST', e.message);
|
||||
return res.status(400).send(e);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
router.patch('/:id', authenticate, (req, res) => {
|
||||
var id = req.params.id;
|
||||
var body = _.pick(req.body, tools.allfieldTodo());
|
||||
|
||||
// tools.mylogshow('PATCH TODO: ', id);
|
||||
|
||||
if (!ObjectId.isValid(id)) {
|
||||
tools.mylog('ERROR: id not VALID', id);
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
Todo.findById(id)
|
||||
.then((todorec) => {
|
||||
|
||||
if (todorec) {
|
||||
// Esiste, pertanto gli tolgo l'UserId generato in precedenza
|
||||
delete body["userId"];
|
||||
}
|
||||
|
||||
Todo.findByIdAndUpdate(id, { $set: body }, { new: true })
|
||||
.then((todo) => {
|
||||
if (!todo) {
|
||||
tools.mylogshow(' TODO NOT FOUND !: id:', id, 'body: ', body);
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
let level = 0;
|
||||
return Todo.calculateTreeTodo(todo.phase, todo.userId, todo.category, true, todo.category, false)
|
||||
.then(objdatacalc => {
|
||||
// tools.mylogshow(' TODO TO MODIFY: ', todo.descr, todo.expiring_at);
|
||||
|
||||
if (todo.userId !== String(req.user._id) && todo.privacywrite === server_constants.Privacy.onlyme) {
|
||||
// I'm trying to write something not mine!
|
||||
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
|
||||
}
|
||||
|
||||
todo.modified = false;
|
||||
|
||||
// tools.mylog('PATCH ', todo.descr, todo._id);
|
||||
|
||||
res.send({ todo, objdatacalc });
|
||||
});
|
||||
|
||||
}).catch((e) => {
|
||||
tools.mylogserr('Error patch TODO: ', e);
|
||||
res.status(400).send();
|
||||
})
|
||||
})
|
||||
});
|
||||
|
||||
|
||||
router.get('/calc/:id', authenticate, (req, res) => {
|
||||
var id = req.params.id;
|
||||
|
||||
let rec = {};
|
||||
|
||||
Hours.calculateHoursTodo(id).then((hoursworked) => {
|
||||
rec.hoursworked = hoursworked;
|
||||
return res.send({ rec });
|
||||
}).catch((err) => {
|
||||
res.status(400).send();
|
||||
});
|
||||
|
||||
return rec;
|
||||
|
||||
});
|
||||
|
||||
router.get('/:userId', authenticate, (req, res) => {
|
||||
var userId = req.params.userId;
|
||||
// var category = req.params.category;
|
||||
|
||||
// tools.mylog('GET TODOS : ', 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
|
||||
Todo.getAllTodo(userId).then((objtodos) => {
|
||||
if (!!objtodos.arrtodos) {
|
||||
// tools.mylog('todos', objtodos.arrtodos.length);
|
||||
// tools.mylog('categories', objtodos.arrcategories.length);
|
||||
}
|
||||
|
||||
res.send({ todos: objtodos.arrtodos, categories: objtodos.arrcategories });
|
||||
}).catch((e) => {
|
||||
console.log(e.message);
|
||||
res.status(400).send(e);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
router.get('/test', (req, res) => {
|
||||
|
||||
const todo = {
|
||||
_id: new ObjectId(),
|
||||
// category: "personal",
|
||||
statustodo: 0,
|
||||
completed_at: new Date(),
|
||||
created_at: new Date(),
|
||||
descr: "Primo Task Esempio",
|
||||
enableExpiring: false,
|
||||
expiring_at: new Date(),
|
||||
modified: false,
|
||||
modify_at: new Date(),
|
||||
pos: 1,
|
||||
priority: 1,
|
||||
progress: 0,
|
||||
userId: users[0]._id
|
||||
};
|
||||
|
||||
const TodoOne = new Todo(todo).save().then((err, ris) => {
|
||||
console.log('Err:', err);
|
||||
console.log('Ris:', ris);
|
||||
|
||||
});
|
||||
|
||||
res.send({});
|
||||
|
||||
});
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
// var category = req.params.category;
|
||||
|
||||
// tools.mylog('GET ALL TODOS ');
|
||||
|
||||
// Extract all the todos of the userId only
|
||||
Todo.getAllTodo('').then((objtodos) => {
|
||||
if (!!objtodos.arrtodos) {
|
||||
// tools.mylog('todos', objtodos.arrtodos.length);
|
||||
// tools.mylog('categories', objtodos.arrcategories.length);
|
||||
}
|
||||
|
||||
res.send({ todos: objtodos.arrtodos, categories: objtodos.arrcategories });
|
||||
}).catch((e) => {
|
||||
console.log(e.message);
|
||||
res.status(400).send(e);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
router.delete('/:id', authenticate, (req, res) => {
|
||||
var id = req.params.id;
|
||||
// var hide = req.params.hide;
|
||||
|
||||
let hide = true;
|
||||
|
||||
if (!ObjectId.isValid(id)) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
if (hide) {
|
||||
Todo.findByIdAndUpdate(id, { $set: { deleted: true } }).then((todo) => {
|
||||
if (!todo) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
res.send({ todo });
|
||||
}).catch((e) => {
|
||||
res.status(400).send();
|
||||
});
|
||||
|
||||
} else {
|
||||
Todo.deleteOne({_id: id}).then((todo) => {
|
||||
if (!todo) {
|
||||
return res.status(404).send();
|
||||
}
|
||||
|
||||
// tools.mylog('DELETED ', todo.descr, todo._id);
|
||||
|
||||
res.send({ todo });
|
||||
}).catch((e) => {
|
||||
res.status(400).send();
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
99
src/router/userrequest_router.js
Executable file
@@ -0,0 +1,99 @@
|
||||
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 mongoose = require('mongoose').set('debug', false);
|
||||
|
||||
const { User } = require('../models/user');
|
||||
const { MyGroup } = require('../models/mygroup');
|
||||
|
||||
const _ = require('lodash');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
async function getGroupRecAdminsInfo(idapp, data) {
|
||||
|
||||
if (data && data.admins) {
|
||||
for (const admin of data.admins) {
|
||||
const myuser = await User.findOne({ idapp, username: admin.username }, { 'profile.img': 1 }).lean();
|
||||
admin.profile = { img: myuser.profile.img };
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
router.post('/load', authenticate, async (req, res) => {
|
||||
const idapp = req.body.idapp;
|
||||
const groupname = req.body.groupname;
|
||||
const usernameOrig = req.user.username;
|
||||
|
||||
try {
|
||||
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
const { Circuit } = require('../models/circuit');
|
||||
const { Account } = require('../models/account');
|
||||
|
||||
// Check if ìs a Notif to read
|
||||
const idnotif = req.body['idnotif'] ? req.body['idnotif'] : '';
|
||||
SendNotif.setNotifAsRead(idapp, usernameOrig, idnotif);
|
||||
|
||||
const whatshow = MyGroup.getWhatToShow(idapp, req.user.username);
|
||||
let data = await MyGroup.findOne({ idapp, groupname }, whatshow).lean();
|
||||
|
||||
/*
|
||||
if (data.mycircuits) {
|
||||
for (let i = 0; i < data.mycircuits.length; i++) {
|
||||
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean();
|
||||
data.mycircuits[i] = mycirc;
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
if (data.mycircuits) {
|
||||
for (let i = 0; i < data.mycircuits.length; i++) {
|
||||
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean();
|
||||
if (mycirc)
|
||||
data.mycircuits[i].account = await Account.getAccountByUsernameAndCircuitId(idapp, '', mycirc._id, true, true, groupname);
|
||||
}
|
||||
}
|
||||
|
||||
let cities = [];
|
||||
if (data) {
|
||||
cities = await MyGroup.extractCitiesName(idapp, data._id);
|
||||
if (cities && cities.length > 0) {
|
||||
cities = cities[0].mycities;
|
||||
}
|
||||
}
|
||||
|
||||
data = await getGroupRecAdminsInfo(idapp, data);
|
||||
|
||||
const whatshowUsers = await User.getWhatToShow_IfFriends(idapp, req.user.username);
|
||||
|
||||
const users_in_group = await User.find(
|
||||
{
|
||||
idapp,
|
||||
'profile.mygroups': {
|
||||
$elemMatch: { groupname: { $eq: groupname } },
|
||||
},
|
||||
},
|
||||
whatshowUsers,
|
||||
).lean();
|
||||
|
||||
res.send({ mygroup: data, users_in_group, cities });
|
||||
|
||||
} catch (e) {
|
||||
console.error('Error in MyGroups', e);
|
||||
return res.status(400).send(e);
|
||||
}
|
||||
|
||||
const ris = null;
|
||||
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||