- aggiornata la grafica della Home di RISO

- Profilo Completition
- Email Verificata
- Invita un Amico (invio di email)
This commit is contained in:
Surya Paolo
2025-11-15 19:38:55 +01:00
parent 26a42b1f30
commit adf1aac10f
312 changed files with 12061 additions and 81773 deletions

View File

@@ -1 +0,0 @@

View File

@@ -1,55 +0,0 @@
const tools = require('../tools/general');
console.log('__');
console.log('__');
console.log('__');
console.log('__');
console.log('****************************************************');
console.log('*** AVVIO DEL SERVER NODE.JS ***');
console.log('****************************************************');
console.log('__');
if ((process.env.NODE_ENV === 'production')) {
console.log(' *** AMBIENTE DI PRODUZIONE !!!!')
} else if (process.env.NODE_ENV === 'test') {
console.log(' *** ### AMBIENTE DI TEST ')
} else if (process.env.NODE_ENV === 'development') {
console.log(' *** ### AMBIENTE DI SVILUPPO (LOCALE) ')
}
console.log('__');
// still in app.js
const node_env = process.env.NODE_ENV || 'production';
var file = `.env.${node_env}`;
// GLOBALI (Uguali per TUTTI)
process.env.LINKVERIF_REG = '/vreg';
process.env.LINK_REQUEST_NEWPASSWORD = '/requestnewpwd';
process.env.ADD_NEW_SITE = '/addNewSite';
process.env.LINK_UPDATE_PASSWORD = '/updatepassword';
process.env.LINK_UPDATE_PWD = '/updatepwd';
process.env.LINK_CHECK_UPDATES = '/checkupdates';
process.env.KEY_APP_ID = 'KKPPAA5KJK435J3KSS9F9D8S9F8SD98F9SDF';
console.log("Starting Node with: " + file);
require('dotenv').config({ path: file });
process.env.DATABASE = process.env.DATABASE || 'FreePlanet';
console.log('process.env.DOMAIN:', process.env.DOMAIN);
const domain = process.env.DOMAIN;
const username = encodeURIComponent(process.env.MONGODB_USER);
const password = encodeURIComponent(process.env.MONGODB_PWD);
const database = process.env.DATABASE || "test"; // Nome del database, default a 'test'
if (process.env.AUTH_DB_PASSING === "1") {
// replace username and password in the process.env.DOMAIN
process.env.MONGODB_URI = process.env.DOMAIN_AUTH.replace('{username}', username).replace('{password}', password) + database;
process.env.MONGODB_URI_NOPWD = process.env.DOMAIN_AUTH.replace('{username}', username) + database;
} else {
process.env.MONGODB_URI = domain + database;
process.env.MONGODB_URI_NOPWD = domain + database;
}
console.log('process.env.MONGODB_URI:', process.env.MONGODB_URI_NOPWD);

View File

@@ -1,27 +0,0 @@
require("dotenv").config();
const { Sequelize } = require("sequelize");
const sequelize = new Sequelize(process.env.DB_DATABASE_SQLSRVTEST, process.env.DB_USERNAME_SQLSRVTEST, process.env.DB_PASSWORD_SQLSRVTEST, {
host: process.env.DB_HOST_SQLSRVTEST || "localhost",
port: process.env.DB_PORT_SQLSRVTEST || 1433,
dialect: "mssql",
dialectOptions: {
options: {
encrypt: false, // Cambia a true se usi SSL
},
},
logging: false, // Disabilita il logging delle query
});
async function testConnection() {
try {
await sequelize.authenticate();
console.log("Connessione al database riuscita!");
} catch (error) {
console.error("Errore nella connessione al database:", error);
}
}
testConnection();
module.exports = sequelize;

File diff suppressed because it is too large Load Diff

View File

@@ -1,46 +0,0 @@
// @ts-check
const EventModel = require('../models/Event');
const { pick } = require('../utils/pick');
async function listEvents(req, res) {
const { limit = '6', page = '1', from, to, sort = 'start' } = /** @type {any} */ (req.query);
const q = {};
if (from) q.start = { ...(q.start || {}), $gte: new Date(from) };
if (to) q.start = { ...(q.start || {}), $lte: new Date(to) };
const lim = Math.min(Number(limit) || 6, 50);
const skip = (Math.max(Number(page) || 1, 1) - 1) * lim;
const [items, total] = await Promise.all([
EventModel.find(q)
.sort({ [sort]: 1 })
.skip(skip)
.limit(lim)
.lean(),
EventModel.countDocuments(q),
]);
res.set('Cache-Control', 'public, max-age=30, stale-while-revalidate=120');
return res.json({ items, total, page: Number(page), limit: lim });
}
async function createEvent(req, res) {
const data = pick(req.body, ['title', 'start', 'end', 'place', 'teaser', 'cover', 'to']);
const doc = await EventModel.create(data);
return res.status(201).json(doc);
}
async function updateEvent(req, res) {
const data = pick(req.body, ['title', 'start', 'end', 'place', 'teaser', 'cover', 'to']);
const doc = await EventModel.findByIdAndUpdate(req.params.id, data, { new: true });
if (!doc) return res.status(404).json({ message: 'Evento non trovato' });
return res.json(doc);
}
async function deleteEvent(req, res) {
const r = await EventModel.findByIdAndDelete(req.params.id);
if (!r) return res.status(404).json({ message: 'Evento non trovato' });
return res.status(204).send();
}
module.exports = { listEvents, createEvent, updateEvent, deleteEvent };

View File

@@ -1,18 +0,0 @@
// @ts-check
const { HomeModel } = require('../models/Home');
async function getHome(req, res) {
const doc = await HomeModel.findOne({});
if (!doc) return res.status(404).json({ message: 'Home non configurata' });
res.set('Cache-Control', 'public, max-age=60, stale-while-revalidate=300');
res.set('ETag', `"${doc.updatedAt?.getTime?.() || Date.now()}"`);
return res.json(doc);
}
async function upsertHome(req, res) {
const payload = req.body || {};
const doc = await HomeModel.findOneAndUpdate({}, payload, { upsert: true, new: true, setDefaultsOnInsert: true });
return res.json(doc);
}
module.exports = { getHome, upsertHome };

View File

@@ -1,20 +0,0 @@
// @ts-check
async function subscribe(req, res) {
const { email } = req.body || {};
if (!email || !/.+@.+\..+/.test(email)) {
return res.status(400).json({ message: 'Email non valida' });
}
// Integra qui Mailchimp/Sendinblue se necessario
return res.status(200).json({ ok: true });
}
async function unsubscribe(req, res) {
const { email } = req.body || {};
if (!email || !/.+@.+\..+/.test(email)) {
return res.status(400).json({ message: 'Email non valida' });
}
// Integra qui Mailchimp/Sendinblue se necessario
return res.status(200).json({ ok: true });
}
module.exports = { subscribe, unsubscribe };

View File

@@ -1,41 +0,0 @@
// @ts-check
const { PostModel } = require('../models/Post');
const { pick } = require('../utils/pick');
async function listPosts(req, res) {
const { limit = '3', page = '1', sort = '-date', category } = /** @type {any} */ (req.query);
const q = {};
if (category) q.category = category;
const lim = Math.min(Number(limit) || 3, 50);
const skip = (Math.max(Number(page) || 1, 1) - 1) * lim;
const [items, total] = await Promise.all([
PostModel.find(q).sort(sort).skip(skip).limit(lim).lean(),
PostModel.countDocuments(q)
]);
res.set('Cache-Control', 'public, max-age=30, stale-while-revalidate=120');
return res.json({ items, total, page: Number(page), limit: lim });
}
async function createPost(req, res) {
const data = pick(req.body, ['title','date','category','teaser','cover','to','bodyMd']);
const doc = await PostModel.create(data);
return res.status(201).json(doc);
}
async function updatePost(req, res) {
const data = pick(req.body, ['title','date','category','teaser','cover','to','bodyMd']);
const doc = await PostModel.findByIdAndUpdate(req.params.id, data, { new: true });
if (!doc) return res.status(404).json({ message: 'Post non trovato' });
return res.json(doc);
}
async function deletePost(req, res) {
const r = await PostModel.findByIdAndDelete(req.params.id);
if (!r) return res.status(404).json({ message: 'Post non trovato' });
return res.status(204).send();
}
module.exports = { listPosts, createPost, updatePost, deletePost };

63
src/server/cronJobs.js Normal file
View File

@@ -0,0 +1,63 @@
const cron = require('node-cron');
const tools = require('../tools/general');
async function mycron() {
try {
const sendemail = require('../sendemail');
const { Cron } = require('../models/cron');
const arr = await tools.getApps();
for (const app of arr) {
await sendemail.checkifPendingNewsletter(app.idapp);
await sendemail.checkifSentNewsletter(app.idapp);
await Cron.startJobCron(app.idapp);
}
} catch (e) {
console.error('Err mycron:', e);
}
}
async function mycron_30min() {
const { Settings } = require('../models/settings');
const arr = await tools.getApps();
for (const app of arr) {
const enabled = await Settings.getValDbSettings(app.idapp, tools.ENABLE_CRONTAB, false);
if (enabled) {
// aggiungi qui logiche aggiuntive
}
}
}
async function mycron_everyday() {
const { User } = require('../models/user');
const telegrambot = require('../telegram/telegrambot');
try {
const arrapps = await tools.getApps();
for (const app of arrapps) {
const usersblocked = await User.find({
idapp: app.idapp,
retry_pwd: { $exists: true, $gte: 29 },
}).lean();
for (const user of usersblocked) {
await User.findByIdAndUpdate(user._id, { $set: { retry_pwd: 20 } });
const text = `⚠️ L'utente ${user.username} (${user.name} ${user.surname}) è stato sbloccato!`;
await telegrambot.sendMsgTelegramToTheAdminAllSites(text, false);
}
}
} catch (e) {
console.error('mycron_everyday:', e);
}
}
// ⏱️ pianifica i cron
function setupCronJobs() {
cron.schedule('*/1 * * * *', mycron);
cron.schedule('*/60 * * * *', mycron_30min);
cron.schedule('0 21 * * *', mycron_everyday);
console.log('⏱️ Cron Jobs attivi');
}
module.exports = { mycron, mycron_30min, mycron_everyday, setupCronJobs };

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +0,0 @@
// @ts-check
const mongoose = require('mongoose');
const { env } = require('../config/env');
export async function connectDB() {
if (mongoose.connection.readyState === 1) return;
mongoose.set('strictQuery', true);
await mongoose.connect(env.MONGO_URI);
console.log('[mongo] connected');
}

View File

@@ -1,84 +0,0 @@
var mongoose = require('mongoose').set('debug', process.env.VITE_DEBUG);
// Configurazione globale di Mongoose
mongoose.Promise = global.Promise;
mongoose.level = "";
mongoose.set('debug', false);
mongoose.set('strictQuery', false);
// Opzioni di connessione
let options = {
maxPoolSize: 5,
// useNewUrlParser: true,
// useUnifiedTopology: true,
serverSelectionTimeoutMS: 20000, // Timeout di 30 secondi per la selezione del server
};
// Controllo dell'autenticazione
console.log('process.env.AUTH_MONGODB', process.env.AUTH_MONGODB);
const username = encodeURIComponent(process.env.MONGODB_USER);
const password = encodeURIComponent(process.env.MONGODB_PWD);
if (process.env.AUTH_MONGODB === '1') {
options.auth = {
authSource: "admin",
username,
password
};
}
if (options.auth && options.auth.username) {
console.log('MongoDb con Authenticazione:', options.auth.username, '******');
} else {
console.log('### MongoDb SENZA Authenticazione !!! ');
}
// Stampa delle informazioni di sistema
console.log('Node Version ' + process.version);
console.log('Mongoose Version ' + mongoose.version);
// URL di connessione
const connectionUrl = process.env.MONGODB_URI;
console.log('Connessione a ' + process.env.MONGODB_URI_NOPWD + ' in corso...');
// Funzione per connettersi al database con retry
async function connectToDatabase(uri, opts) {
let isConnected = false;
while (!isConnected) {
try {
console.log("Sto provando a connettermi al database...");
await mongoose.connect(uri);
console.log(' *** CONNESSIONE EFFETTUATA ! ' + ' db: ' + process.env.DATABASE);
console.log(' Database corrente:', mongoose.connection.name);
// Ottieni l'URL completo della connessione
// console.log(' URL di connessione:', mongoose.connection.client.s.url);
const db = mongoose.connection;
const serverInfo = await db.db.admin().serverStatus(); // Ottieni lo stato del server
console.log(` Versione di MongoDB: ${serverInfo.version}`); // Stampa la versione
isConnected = true; // Imposta la flag di connessione a true
} catch (error) {
console.error(" Errore durante la connessione al database:", error.message);
// if (error.name === 'MongooseServerSelectionError' || error.name === 'MongoServerError') {
console.log(" Ritento la connessione tra 1 minuto...");
await new Promise((resolve) => setTimeout(resolve, 60000)); // Attendi 1 minuto prima di ritentare
/*} else {
console.error(" Errore irreversibile. Arresto il processo.");
await new Promise((resolve) => setTimeout(resolve, 10000)); // Attendi 1 minuto prima di ritentare
process.exit(1); // Termina il processo in caso di errore irreversibile
}*/
}
}
}
// Esporta Mongoose
module.exports = { mongoose, connectToDatabase, connectionUrl, options };

View File

@@ -1,59 +0,0 @@
const fs = require('fs');
const path = require('path');
const url = require('url');
// const { connectDB } = require('./connect');
const { HomeModel } = require('../models/Home');
const { EventModel } = require('../models/Event');
const { PostModel } = require('../models/Post');
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
async function run() {
// await connectDB();
// Adatta il percorso se frontend e backend sono separati
const samplePath = path.resolve(__dirname, '../../../src/server/mocks/home.sample.json');
const raw = fs.readFileSync(samplePath, 'utf-8');
const json = JSON.parse(raw);
// Home snapshot
await HomeModel.deleteMany({});
await HomeModel.create({
hero: json.hero,
pillars: json.pillars,
testimonials: json.testimonials,
gallery: json.gallery,
faq: json.faq,
partners: json.partners,
posts: json.posts
});
// Events
await EventModel.deleteMany({});
await EventModel.insertMany(json.events.map((e) => ({
title: e.title,
start: new Date(e.start),
end: e.end ? new Date(e.end) : undefined,
place: e.place,
teaser: e.teaser,
cover: e.cover,
to: e.to
})));
// Posts
await PostModel.deleteMany({});
await PostModel.insertMany(json.posts.map((p) => ({
title: p.title,
date: new Date(p.date),
category: p.category,
teaser: p.teaser,
cover: p.cover,
to: p.to,
bodyMd: `# ${p.title}\n\n${p.teaser}\n`
})));
console.log('[seed] done');
process.exit(0);
}
run().catch((e) => { console.error(e); process.exit(1); });

95
src/server/extraJobs.js Normal file
View File

@@ -0,0 +1,95 @@
const tools = require('../tools/general');
const { Newstosent } = require('../models/newstosent');
async function resetProcessingJob() {
try {
const records = await Newstosent.find({});
for (const rec of records) {
rec.processing_job = false;
await Newstosent.findByIdAndUpdate(rec._id, { $set: rec }, { new: false });
}
console.log('✅ resetProcessingJob completato');
} catch (err) {
console.error('❌ Errore resetProcessingJob:', err.message);
}
}
async function testmsgwebpush() {
try {
const { User } = require('../models/user');
const users = await User.find({ username: 'surya1977', idapp: '1' }).lean();
for (const user of users) {
await tools.sendNotificationToUser(user._id, 'Server', 'Il Server è Ripartito', '/', '', 'server', []);
}
console.log('✅ testmsgwebpush completato');
} catch (err) {
console.error('❌ Errore testmsgwebpush:', err.message);
}
}
async function populateDBadmin() {
const { CfgServer } = require('../models/cfgserver');
const { ObjectId } = require('mongodb');
try {
const cfg = new CfgServer({
_id: new ObjectId(),
idapp: '9',
chiave: 'vers',
userId: 'ALL',
valore: '0.1.2',
});
await cfg.save();
console.log('✅ populateDBadmin completato');
} catch (err) {
console.error('❌ Errore populateDBadmin:', err.message);
}
}
async function inizia() {
try {
telegrambot = require('../telegram/telegrambot');
if (false) {
const url = 'https://raw.githubusercontent.com/matteocontrini/comuni-json/master/comuni.json';
const outputPath = './comuni_italia_geojson.json';
downloadGeoJSON(url, outputPath);
}
mycron_everyday();
if (process.env.NODE_ENV === 'development') {
await telegrambot.sendMsgTelegram(
tools.FREEPLANET,
shared_consts.ADMIN_USER_SERVER,
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}!`
);
await telegrambot.sendMsgTelegramByIdTelegram(
tools.FREEPLANET,
telegrambot.ADMIN_IDTELEGRAM_SERVER,
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}\n` + `🔅 Il Server ${process.env.DATABASE} è appena ripartito!`
);
} else {
await telegrambot.sendMsgTelegramToTheAdminAllSites(
`Ciao Admin\n` + `🔅🔅🔅 Il Server col BOT di {appname} è appena ripartito!`,
false
);
}
await Site.createFirstUserAdmin();
/*const {Circuit} = require('./models/circuit');
await Circuit.setDeperimentoOff();
*/
} catch (e) {}
}
module.exports = {
resetProcessingJob,
testmsgwebpush,
populateDBadmin,
inizia,
};

View File

@@ -1,52 +0,0 @@
'use strict';
const ftp = require('basic-ftp');
// const fs = require('fs');
class FTPClient {
constructor(host = 'localhost', port = 21, username = 'anonymous', password = 'guest', secure = false, secureOptions = '') {
this.client = new ftp.Client();
// this.client.ftp.verbose = true;
this.settings = {
host: host,
port: port,
user: username,
password: password,
secure: secure,
secureOptions: secureOptions
};
}
async upload(sourcePath, remotePath, permissions) {
let self = this;
try {
let access = await self.client.access(self.settings);
let upload = await self.client.uploadFrom(sourcePath, remotePath);
// let permissions = await self.changePermissions(permissions.toString(), remotePath);
self.client.close();
return true;
} catch (err) {
console.log('upload ERR: ', err);
self.client.close();
return false;
}
}
async createDir(miadir) {
let access = await this.client.access(this.settings);
await this.client.ensureDir(miadir);
}
close() {
this.client.close();
}
changePermissions(perms, filepath) {
let cmd = 'SITE CHMOD ' + perms + ' ' + filepath;
return this.client.send(cmd, false);
}
}
module.exports = FTPClient;

139
src/server/init.js Normal file
View File

@@ -0,0 +1,139 @@
const tools = require('../tools/general');
const Site = require('../models/site');
async function faitest() {
const telegrambot = require('../telegram/telegrambot');
// console.log('Fai Test:')
const testfind = false;
// const $vers = tools.getVersionint('1.92.45');
if (true) {
// tools.execScript("ls -la");
}
if (false) {
prova = tools.removeAtChar('@prova');
}
if (false) {
const prova = tools.getConfSiteOptionEnabledByIdApp('13', shared_consts.ConfSite.Notif_Reg_Push_Admin);
console.log('prova', prova);
}
if (testfind) {
const { City } = require('../models/city');
let miacity = 'roma';
const ris = await City.findByCity(miacity);
console.log('ris', ris);
}
const { User } = require('../models/user');
if (false) {
let myuser = await User.findOne({
idapp: '1',
username: 'paoloar77',
});
const langdest = 'it';
telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser);
}
const inviaemailtestsurya = false;
if (inviaemailtestsurya) {
const user = await User.findOne({
idapp: 13,
username: 'surya2',
});
const sendemail = require('../sendemail');
await sendemail.sendEmail_Registration('it', 'paolo@arcodiluce.it', user, '13', '');
}
if (false) {
const { User } = require('../models/user');
const idapp = tools.FREEPLANET;
const idreg = 0;
try {
const user = await User.findOne({
idapp,
username: 'paoloar773',
});
user.aportador_solidario = 'surya1977';
let mylocalsconf = {
idapp,
dataemail: null,
locale: user.lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
strlinksito: tools.getHostByIdApp(idapp),
strlinkreg: '',
username: user.username,
name: user.name,
surname: user.surname,
forgetpwd: tools.getHostByIdApp(idapp) + '/requestresetpwd',
emailto: '',
user,
};
await telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION, mylocalsconf);
} catch (e) {
console.log('error ' + e);
}
}
}
async function runStartupTasks() {
//mystart
try {
// 1) log versione + elenco app
const vers = await tools.getVersServer();
const apps = await tools.getApps();
console.log('----------------------------------------------');
console.log(`🌍 Versione Server: ${vers}`);
console.log('📱 App caricate:');
for (const app of apps) {
console.log(` • ID: ${app.idapp}${app.nomeapp || app.name || 'N/A'}`);
}
console.log('----------------------------------------------');
const telegrambot = require('../telegram/telegrambot');
const { resetProcessingJob, testmsgwebpush, inizia } = require('./extraJobs');
// 2) azioni post-boot
await Site.createFirstUserAdmin?.();
// 3) test notifiche webpush (facoltativo: metti dietro un flag)
if (process.env.ENABLE_TEST_WEBPUSH === 'true') {
await testmsgwebpush();
}
await inizia();
// 4) reset job pendenti
await resetProcessingJob();
// 5) popolamenti/attività extra (facoltativo)
const populate = require('../populate/populate');
populate.popolaTabelleNuove();
faitest();
// 6) ping agli admin
await telegrambot.sendMsgTelegramToTheAdminAllSites(`🔅 Server ${vers} avviato con successo`);
} catch (err) {
console.error('❌ errore in runStartupTasks:', err.message);
}
}
module.exports = { runStartupTasks };

View File

@@ -1,4 +0,0 @@
{
"Email Verificata!": "Email Verified! Close this window and return to the other.",
"partecipanti": "participants",
}

View File

@@ -1,8 +0,0 @@
{
"L'Email è già stata Verificata": "El email ya ha sido verificado",
"Email Verificata!": "Email Verificada! Cierre esta ventana y regrese a la otra.",
"a": "a",
"Nuova Registrazione": "Nuevo Registro",
"Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro",
"partecipanti": "participantes",
}

View File

@@ -1,8 +0,0 @@
{
"L'Email è già stata Verificata": "L'Email è già stata Verificata",
"Email Verificata!": "Email Verificata! Chiudere questa finestra e ritornare sull'altra.",
"a": "a",
"Nuova Registrazione": "Nuova Registrazione",
"Effettuata una Nuova Registrazione": "Effettuata una Nuova Registrazione",
"partecipanti": "partecipanti",
}

View File

@@ -1,61 +0,0 @@
{
"L'Email è già stata Verificata": "L'Email è già stata Verificata",
"Email Verificata!": "Email Verificada! Cierre esta ventana y regrese a la otra.",
"Nuova Registrazione": "Nuevo Registro",
"Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro",
"partecipanti": "participantes",
"Hello": "Hello",
"Hello %s": "Ciao %s",
"Good: %s": "Good: %s",
"Service: %s": "Service: %s",
"<strong>%s</strong> new Good: %s": "<strong>%s</strong> new Good: %s",
"<strong>%s</strong> new Service: %s": "<strong>%s</strong> new Service: %s",
"OPEN PAGE": "OPEN PAGE",
"<strong>%s</strong> asked you for Friendship": "<strong>%s</strong> asked you for Friendship",
"<strong>%s</strong> accepted your Friendship": "<strong>%s</strong> accepted your Friendship",
"<strong>%s</strong> refused your Friendship": "<strong>%s</strong> refused your Friendship",
"✅ %s accepted your Friendship request !": "✅ %s ha accettato la tua richiesta di Amicizia !",
"✅ You have accepted %s' Friendship request!": "✅ You have accepted %s' Friendship request!",
"GROUPS_ACCEPTED": "✅ You have been accepted by %s to join the Group %s (by %s)",
"GROUPS_REFUSED": "❌ You have been denied access by %s to join the %s Group. If you think this is an error, please contact the group administrator.",
"GROUPS_REMOVED": "❌ user %s was removed from the %s Group (by %s)",
"ACCETTATO_NOTIFICA_ADMINS": "✅ l'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)",
"GROUP_CREATED": "✅ A new Group created by %s called %s has been created",
"GROUP_REQUEST_TO_ENTER": "%s asked to join the group %s",
"GROUP_REQUEST": "Richiesta di entrare nel Gruppo %s da parte di %s",
"RICHIESTA_BLOCCO_GRUPPO": "Richiesta di bloccare il Gruppo %s da parte di %s",
"GRUPPO_ELIMINATO": "Il gruppo %s è stato eliminato da parte di %s",
"FRIEND_REPORTED_TO_ME": "Sei stato segnalato da %s per comportamenti non idonei. Contatta %s per chiarimenti",
"FRIEND_REPORTED": "E' stato segnalato %s da %s per comportamenti non idonei.",
"FRIEND_REPORTED_YOU": "Hai segnalato %s per comportamenti non idonei.",
"FRIEND_UNBLOCKED_TO_ME": "Sei stato riattivato da %s",
"FRIEND_UNBLOCKED": "E' stato riattivato %s da %s.",
"FRIEND_UNBLOCKED_YOU": "Hai riattivato %s.",
"CIRCUIT_ACCEPT_NEWENTRY": "❇️👥 🧍‍♂️ Accetta Ingresso nel Circuito %s:",
"CIRCUIT_REQUEST_TO_ENTER": "%s ha chiesto di entrare nel circuito %s",
"CIRCUIT_CREATED": "✅ %s ha creato un nuovo Circuito chiamato %s",
"CIRCUIT_REQUEST": "Richiesta di entrare nel Circuito %s da parte di %s",
"CIRCUIT_ADDED_ADMIN": "E' stato aggiunto %s come Amministratore/Amministratrice del circuito %s da parte di %s",
"CIRCUIT_ADDED_ADMIN_YOU": "Sei stato aggiunto come Amministratore/Amministratrice del circuito %s da parte di %s",
"CIRCUIT_REMOVED_ADMIN": "E' stato rimosso l'incarico di Amministratore a %s del circuito %s da parte di %s",
"CIRCUIT_REMOVED_ADMIN_YOU": "Ti è stato rimosso l'incarico di Amministratore del circuito %s da parte di %s",
"RICHIESTA_BLOCCO_CIRCUIT": "Richiesta di bloccare il Circuito %s da parte di %s",
"CIRCUIT_ELIMINATO": "Il circuito %s è stato eliminato da parte di %s",
"ACCETTATO_NOTIFICA_ADMINS_CIRCUIT": "✅ l'utente %s è stato accettato a far parte del Circuito %s (da parte di %s)",
"CIRCUIT_ACCEPTED": "✅ Sei stato accettato da %s a far parte del Circuito %s.\nApri la APP e clicca in alto a destra sull'icona delle monete, oppure clicca qui: %s",
"CIRCUIT_REFUSED": "❌ Ti è stato rifiutato l'accesso da %s a far parte del Circuito %s. Se pensi sia un'errore, contatta l'amministratore del Circuito.",
"CIRCUIT_REMOVED": "❌ l'utente %s è stato rimosso del Circuito %s (da parte di %s)",
"CIRCUIT_REFUSED_TO_ME": "All'utente %s gli è stato rifiutato l'accesso a far parte del Circuito %s (da parte di %s).",
"CIRCUIT_EXIT_USER": "❌ l'utente %s è uscito dal Circuito %s",
"CIRCUIT_EXIT_USER_TO_ME": "❌ Sei uscito dal Circuito %s",
"CIRCUIT_REMOVED_TO_ME": "❌ Sei stato rimosso dal Circuito %s (da parte di %s)",
"CIRCUIT_SENDCOINSREQ": "%s ti sta inviando %s %s.",
"ID_CIRCUIT_COINS_ACCEPTED": "%s %s accettati da %s.",
"SALDO_UPDATE": "[Saldo <strong>%s %s</strong>]",
"ID_CIRCUIT_COINS_ACCEPTED_TO_ME": "%s %s accettati da %s.",
"ID_CIRCUIT_COINS_REFUSED": "%s %s rifiutati da %s.",
"ID_CIRCUIT_COINS_REFUSED_TO_ME": "%s %s rifiutati da %s.",
"CIRCUIT_COINS_ALREADY_PROCESSED": "La richiesta è stata già processata. Stato %s",
"STATUS_SENT": "Inviato",
"STATUS_REFUSED": "Rifiutato"
}

View File

@@ -1 +0,0 @@
{}

View File

@@ -1,7 +0,0 @@
{
"L'Email è già stata Verificata": "El email ya ha sido verificado",
"Email Verificata!": "Email Verificada! Cierre esta ventana y regrese a la otra.",
"Nuova Registrazione": "Nuevo Registro",
"Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro",
"partecipanti": "participantes",
}

View File

@@ -1 +0,0 @@
{}

View File

@@ -1,135 +0,0 @@
{
"Hello": "Ciao",
"Hello %s": "Ciao %s",
"Good": "Bene",
"Service": "Servizio",
"Hosp": "Ospitalità",
"Hosp %s": "Ospitalità: %s",
"Event": "Evento",
"Good: %s": "Bene: %s",
"Service: %s": "Servizio: %s",
"NEW_GOOD": "❇️ <strong>%s</strong> ha aggiunto un nuovo Bene: \n<strong>%s</strong> a %s",
"NEW_SERVICE": "❇️ <strong>%s</strong> ha aggiunto un nuovo Servizio: \n<strong>%s</strong> a %s",
"NEW_HOSP": "❇️ <strong>%s</strong> ha aggiunto una nuova Ospitalità: \n<strong>%s</strong> a %s",
"NEW_EVENT": "❇️ <strong>%s</strong> ha aggiunto un nuovo Evento: \n%s\n<strong>%s</strong>\n%s",
"NEW_EVENT_TELEGRAM": "%s\n\n❇ <strong>%s</strong>\n\n%s\n\n%s",
"NEW_ANNUNCIO_TELEGRAM": "❇️ <strong>%s</strong>\n\n%s\n\n%s",
"EVENT_ADDED_FROM": "\n\n<i>(Evento aggiunto da <strong>%s</strong>)</i>",
"ADDED_FROM": "\n\n<i>(Aggiunto da <strong>%s</strong>)</i>",
"CONTRIB": "\n💠 Contributo richiesto: %s",
"ORGANIZED_BY": "\n<i>Organizzato da <strong>%s</strong></i>",
"SHOW_POST": "👉🏻 vedi post su RISO",
"OPEN PAGE": "<em>APRI la APP RISO oppure visita riso.app</em>",
"<strong>%s</strong> asked you for Friendship": "<strong>%s</strong> ti ha chiesto l'Amicizia",
"<strong>%s</strong> accepted your Friendship": "<strong>%s</strong> ha accettato l'Amicizia",
"<strong>%s</strong> refused your Friendship": "<strong>%s</strong> ha rifiutato l'Amicizia",
"✅ %s accepted your Friendship request !": "✅ %s ha accettato la tua richiesta di Amicizia !",
"✅ You have accepted %s' Friendship request!": "✅ Hai accettato la richiesta di Amicizia di %s !",
"HANDSHAKE_SET": "<strong>%s</strong> ha comunicato che ti conosce personalmente e ha Fiducia in te (Stretta di mano).",
"HANDSHAKE_SENT_FROM_YOU": "🤝 hai inviato una Stretta di Mano a <strong>%s</strong>, perché la conosci personalmente !",
"HANDSHAKE_CONFIRMED": "🤝 Hai contraccambiato la stretta di mano di <strong>%s</strong>!",
"HANDSHAKE_ACCEPTED": "🤝 <strong>%s</strong> ha contraccambiato la tua stretta di mano !",
"GROUPS_ACCEPTED": "✅ Sei stato accettato a far parte del Gruppo %s (da parte di %s)",
"GROUPS_REFUSED": "❌ Ti è stato rifiutato l'accesso da %s a far parte del Gruppo %s. Se pensi sia un'errore, contatta l'amministratore del Gruppo.",
"GROUPS_REMOVED": "❌ l'utente %s è stato rimosso del Gruppo %s (da parte di %s)",
"GROUPS_EXIT_USER": "❌ l'utente %s è uscito dal Gruppo %s",
"GROUPS_EXIT_USER_TO_ME": "❌ Sei uscito dal Gruppo %s",
"GROUPS_REMOVED_TO_ME": "❌ Sei stato rimosso dal Gruppo %s (da parte di %s)",
"ACCETTATO_NOTIFICA_ADMINS": "✅ l'utente %s è stato accettato a far parte del Gruppo %s (da parte di %s)",
"GROUP_REQUEST_TO_ENTER": "%s ha chiesto di entrare nel gruppo %s",
"GROUP_CREATED": "✅ %s ha creato un nuovo Gruppo chiamato %s",
"GROUP_REQUEST": "Richiesta di entrare nel Gruppo %s da parte di %s",
"GROUPS_ADDED_ADMIN_GROUP": "E' stato aggiunto %s come Amministratore/Amministratrice del gruppo %s da parte di %s",
"GROUPS_ADDED_ADMIN_GROUP_YOU": "Sei stato aggiunto come Amministratore/Amministratrice del gruppo %s da parte di %s",
"GROUPS_REMOVED_ADMIN_GROUP": "E' stato rimosso l'incarico di Amministratore a %s del gruppo %s da parte di %s",
"GROUPS_REMOVED_ADMIN_GROUP_YOU": "Ti è stato rimosso l'incarico di Amministratore del gruppo %s da parte di %s",
"RICHIESTA_BLOCCO_GRUPPO": "Richiesta di bloccare il Gruppo %s da parte di %s",
"GRUPPO_ELIMINATO": "Il gruppo %s è stato eliminato da parte di %s",
"FRIEND_REPORTED_TO_ME": "Sei stato segnalato da %s per comportamenti non idonei. Contatta %s per chiarimenti",
"FRIEND_REPORTED": "E' stato segnalato %s da %s per comportamenti non idonei.",
"FRIEND_REPORTED_YOU": "Hai segnalato %s per comportamenti non idonei.",
"FRIEND_UNBLOCKED_TO_ME": "Sei stato riattivato da %s",
"FRIEND_UNBLOCKED": "E' stato riattivato %s da %s.",
"FRIEND_UNBLOCKED_YOU": "Hai riattivato %s.",
"CIRCUIT_ACCEPT_NEWENTRY": "❇️👥 🧍‍♂️ Abilita Fiducia a %s nel '%s':",
"CIRCUIT_ACCEPT_NEWENTRY_BYGROUP": "❇️👥 🧍‍♂️ Abilita Fiducia nel Circuito al gruppo %s:",
"CIRCUIT_ACCEPT_NEWENTRY_CIRC": "❇️👥 🧍‍♂️ Fai entrare a %s nel '%s':",
"CIRCUIT_ACCEPT_NEWENTRY_BYGROUP_CIRC": "❇️👥 🧍‍♂️ Fai entrare nel Circuito al gruppo %s:",
"CIRCUIT_OPEN_RISITALIA": "Apri il Circuito RIS Italia e chiedi di entrare",
"CIRCUIT_REQUEST_TO_ENTER": "%s è entrato nel %s (con %s iscritti) ed è in attesa di essere abilitato alla Fiducia\n🙎🏻 Invitato da %s",
"CIRCUIT_REQUEST_TO_ENTER_ASKMANAGER": "%s ha fatto richiesta di entrare nel %s (con %s iscritti)\n🙎🏻 Invitato da %s",
"CIRCUIT_REQUEST_TO_ENTER_ASKMANAGER_SHORT": "%s ha fatto richiesta di entrare nel %s (con %s iscritti)\n🙎🏻 Invitato da %s",
"CIRCUIT_REQUEST_TO_ENTER_ASKMANAGER_TITLE": "++ Nuova Richiesta di %s",
"CIRCUIT_ADMINS": "Gli amministratori del circuito sono %s:\n%s",
"CIRCUIT_WHERE_IS_PRESENT": "\nAttualmente è presente in: %s",
"CIRCUIT_REQUEST_TO_ENTER_WITH_GROUP": "il gruppo %s ha chiesto di entrare nel %s (con %s iscritti)",
"CIRCUIT_CREATED": "✅ %s ha creato un nuovo Circuito chiamato %s",
"CIRCUIT_REQUEST": "Richiesta di entrare nel %s da parte di %s",
"CIRCUIT_ADDED_ADMIN": "E' stato aggiunto %s come Amministratore/Amministratrice del %s da parte di %s",
"CIRCUIT_ADDED_ADMIN_YOU": "%s sei stato aggiunto come Amministratore/Amministratrice del %s da parte di %s",
"CIRCUIT_REMOVED_ADMIN": "E' stato rimosso l'incarico di Amministratore/Amministratrice a %s del %s da parte di %s",
"CIRCUIT_REMOVED_ADMIN_YOU": "%s ti è stato rimosso l'incarico di Amministratore del %s da parte di %s",
"RICHIESTA_BLOCCO_CIRCUIT": "Richiesta di bloccare il %s da parte di %s",
"CIRCUIT_ELIMINATO": "Il %s è stato eliminato da parte di %s",
"FIDO_IMPOSTATO_ADMINS_CIRCUIT": "✅ l'utente %s è stato abilitato alla Fiducia (%s RIS) sul '%s' (da parte di %s)",
"FIDO_IMPOSTATO_ADMINS_CIRCUIT_MYGROUP": "✅ il Conto di Gruppo %s è stato abilitato alla Fiducia fino a -%s sul '%s' (da parte di %s)",
"ACCETTATO_NOTIFICA_ADMINS_CIRCUIT": "✅ l'utente %s è stato accettato a far parte del '%s' (da parte di %s)",
"ACCETTATO_NOTIFICA_ADMINS_CIRCUIT_MYGROUP": "✅ il Conto di Gruppo %s è stato accettato a far parte del '%s' (da parte di %s)",
"CIRCUIT_ACCEPTED": "✅ Sei stato accettato da %s a far parte del %s.\nApri la APP e clicca in alto a destra sull'icona delle monete, oppure clicca qui: %s",
"FIDO_IMPOSTATO": "✅ Ti è stata attivata la possibilità di utilizzare la Fiducia Concessa fino a %s RIS da %s sul '%s'.",
"CIRCUIT_ACCEPTED_YOU": "✅ Hai accettato %s a far parte del '%s'",
"CIRCUIT_REFUSED": "❌ Ti è stato rifiutato l'accesso da %s a far parte del '%s'. Se pensi sia un'errore, contatta l'amministratore del Circuito.",
"CIRCUIT_REMOVED": "❌ l'utente %s è stato rimosso del %s (da parte di %s)",
"CIRCUIT_REFUSED_TO_ME": "All'utente %s gli è stato rifiutato l'accesso a far parte del '%s' (da parte di %s).",
"CIRCUIT_REFUSED_TO_MYGROUP": "Al Conto Collettivo %s gli è stato rifiutato l'accesso a far parte del '%s' (da parte di %s).",
"CIRCUIT_EXIT_USER": "❌ l'utente %s è uscito dal '%s'",
"CIRCUIT_EXIT_USER_TO_ME": "❌ Sei uscito dal '%s'",
"CIRCUIT_REMOVED_TO_ME": "❌ Sei stato rimosso dal '%s' (da parte di %s)",
"CIRCUIT_SENDCOINSREQ": "%s ti sta inviando <strong>%s %s</strong> sul <strong>'%s'</strong>",
"COMUNITARIO": "Comunitario",
"COLLETTIVO": "Gruppo",
"CIRCUIT_SENDCOINSREQ_GROUP": "%s sta inviando <strong>%s %s</strong> al Conto %s '%s' sul '%s'.",
"CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_USER": "il conto %s '%s' (%s) sta inviando <strong>%s %s</strong> a %s sul '%s'.",
"CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_YOU": "il conto %s '%s' (%s) ti sta inviando <strong>%s %s</strong> sul '%s'",
"CIRCUIT_SENDCOINSREQ_FROM_GROUP_TO_GROUP": "il conto %s '%s' (%s) sta inviando <strong>%s %s</strong> al conto %s '%s' sul '%s'.",
"CIRCUIT_SENDCOINSREQ_TO_ME": "Stai inviando <strong>%s %s</strong> a %s sul '%s'.",
"CIRCUIT_SENDCOINSREQ_TO_GROUP": "Stai inviando <strong>%s %s</strong> al Conto %s '%s' sul '%s'.",
"ID_CIRCUIT_COINS_ACCEPTED_FROM_GROUP_TO_YOU": "🟢 Hai ricevuto <strong>%s %s</strong> dal Conto %s '%s' sul '%s' (%s) .",
"ID_CIRCUIT_COINS_ACCEPTED_FROM_GROUP_TO_GROUP": "🟢 il conto %s '%s' (%s) ha ricevuto <strong>%s %s</strong> dal conto %s '%s' sul '%s' (%s).",
"ID_CIRCUIT_COINS_ACCEPTED_FROM_ME_TO_GROUP": "🟢 il conto %s '%s' (%s) ha ricevuto <strong>%s %s</strong> da %s sul '%s'.",
"ID_CIRCUIT_COINS_ACCEPTED_FROM_ME_TO_YOU": "🟢 Hai ricevuto <strong>%s %s</strong> da %s sul '%s'.",
"ID_CIRCUIT_COINS_ACCEPTED": "🟢 <strong>%s %s</strong> ricevuti da %s sul '%s'.",
"SALDO_UPDATE": "[Saldo <strong>%s %s</strong> sul '%s']",
"SALDO_UPDATE_WHO": "[Saldo %s <strong>%s %s</strong> sul '%s']",
"ID_CIRCUIT_COINS_ACCEPTED_TO_ME": "🔄 Hai inviato <strong>%s %s</strong> a %s sul '%s'.",
"ID_CIRCUIT_COINS_REFUSED": "%s %s rifiutati da %s sul '%s'.",
"ID_CIRCUIT_COINS_REFUSED_TO_ME": "%s %s rifiutati da %s sul '%s'.",
"CIRCUIT_AMOUNT_EXCEED_FIDO": "⚠️ L'importo supera la quantità massima concessa per %s",
"CIRCUIT_AMOUNT_EXCEED_QTAMAX": "⚠️ L'importo supera la quantità massima che il destinatario (%s) può accumulare",
"CIRCUIT_COINS_ALREADY_PROCESSED": "La richiesta è stata già processata. Stato %s",
"STATUS_SENT": "Inviato",
"STATUS_REFUSED": "Rifiutato",
"SALDO_VARIATO": "[%s] l'utente %s ha variato il Saldo di %s da %s a %s %s",
"FIDOCONCESSO_VARIATO": "[%s] l'utente %s ha variato la Fiducia Concessa di %s da %s a %s %s",
"QTAMAX_VARIATO": "[%s] l'utente %s ha variato la quantità massima concessa di %s da %s a %s %s",
"SET_FAVORITE": "%s ha messo 'Mi Piace' al tuo post: %s",
"SET_FAVORITE_OTHERS": "%s e altre %s persone hanno messo 'Mi Piace' al tuo post: %s",
"EVENT_SEND_MSG": "%s ha mandato un messaggio sull'evento %s: \n%s",
"SET_ATTEND": "%s ha detto che Parteciperà all'evento: %s",
"SET_ATTEND_OTHERS": "%s e altre %s persone hanno detto che Parteciperanno all'evento: %s",
"DATEDAYONLY": "%s dalle %s alle %s",
"DATE_2DAYS": "%s dalle %s fino a %s alle %s",
"SENDMSG_ENTRA_IN_RISO_ITALIA": "Ciao %s!<br>%s che appartiene al <em>%s</em> vuole inviarti dei RIS. Per poterli ricevere dovete entrambi utilizzare il <strong>Circuito RIS Italia</strong>.",
"CLICCA_QUI": "CLICCA QUI",
"✅ %s è stato Ammesso correttamente (da %s)!": "✅ %s è stato Ammesso correttamente (da %s)!",
"✅ Sei stato Ammesso correttamente da %s!": "✅ Sei stato Ammesso correttamente da %s!",
"🚫 Hai rifiutato l'accesso alla App di RISO da parte di %s!": "🚫 Hai rifiutato l'accesso alla App di RISO da parte di %s!",
"🚫 Ti è stato rifiutato l'accesso. Probabilmente l'username con cui ti sei registrato non ti conosce. (%s) !<br>Contatta l'Assistenza Tecnica.": "🚫 Ti è stato rifiutato l'accesso. Probabilmente l'username con cui ti sei registrato non ti conosce. (%s) !<br>Contatta l'Assistenza Tecnica.",
"🚫 %s ha rifiutato l'accesso alla App a %s !": "🚫 %s ha rifiutato l'accesso alla App a %s !",
"✅ Hai Ammesso l'accesso alla App a %s !": "✅ Hai Ammesso l'accesso alla App a %s !",
"EXCEED_FIDO": "⚠️ L'importo supera la Fiducia concessa per %s",
"EXCEED_QTAMAX": "⚠️ Attenzione! %s sta tentando di inviarti %s RIS, ma il tuo conto ha raggiunto il limite massimo di accumulo sul %s. \nPer poter ricevere il pagamento, devi prima spendere alcuni RIS cercando quello che ti serve, in modo da liberare spazio nel tuo conto. 🙏🏻",
"EXCEED_QTAMAX_MITTENTE": "⚠️ Attenzione! %s ha raggiunto la quota massima accumulabile in RIS, pertanto non puoi inviarglieli. Dovrebbe prima cercare di spendere i RIS cercando quello che gli serve, in modo da liberare spazio nel suo conto. 🙏🏻",
"Good: %": "Good: %",
"Service: %": "Service: %"
}

View File

@@ -1 +0,0 @@
{}

View File

@@ -1 +0,0 @@
{}

View File

@@ -1,6 +0,0 @@
// @ts-check
const ah = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch((err) => next(err));
module.exports = { ah };

View File

@@ -1,77 +0,0 @@
const server_constants = require('../tools/server_constants');
var { User } = require('../models/user');
const tools = require('../tools/general');
const auth_default = (req, res, next) => {
if (req.body.keyappid === process.env.KEY_APP_ID)
next();
};
const authenticateMiddleware = async (req, res, next, withUser = false, lean = false, noError = false) => {
try {
const token = req.header('x-auth');
const refreshToken = req.header('x-refrtok');
const logPrefix = noError ? (withUser ? (lean ? 'WITHUSERLEAN' : 'WITHUSER') : 'NOERROR') : 'AUTH';
// console.log('authenticateMiddleware, token:', token, ' refreshToken:', refreshToken, 'withUser:', withUser, 'noError:', noError);
if (!token) {
req.user = null;
req.token = null;
req.code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN;
if (!noError)
console.log(` ## ${logPrefix}_TOKEN INVALIDO ❌ ...`);
return noError ? next() : res.status(req.code).send();
}
const user = await User.findByToken(token, 'auth', false, withUser, lean);
req.statuscode2 = null;
if (user.code !== server_constants.RIS_CODE_OK) {
req.user = null;
req.token = null;
req.code = user.code;
if (user.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED)
console.log('TOKEN SCADUTO!');
} else {
req.user = user.user;
req.token = token;
req.refreshToken = refreshToken;
req.code = user.code;
}
if (user.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) {
console.log(` TOKEN SCADUTO ! `);
if (noError) {
req.statuscode2 = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED;
return next()
// return res.status(server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED).send();
} else {
return res.status(server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED).send();
}
}
// console.log(` ## ${logPrefix} NEXT ! AVANTI...`);
next();
} catch (e) {
console.error('Errore nel middleware di autenticazione:', e);
req.user = null;
req.token = null;
req.code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN;
noError ? next() : res.status(req.code).send();
}
};
const authenticate = (req, res, next) => authenticateMiddleware(req, res, next);
const authenticate_withUser = (req, res, next) => authenticateMiddleware(req, res, next, true);
const authenticate_withUserLean = (req, res, next) => authenticateMiddleware(req, res, next, true, true);
const authenticate_noerror = (req, res, next) => authenticateMiddleware(req, res, next, false, false, true);
const authenticate_noerror_WithUser = (req, res, next) => authenticateMiddleware(req, res, next, true, false, true);
const authenticate_noerror_WithUserLean = (req, res, next) => authenticateMiddleware(req, res, next, true, true, true);
module.exports = { authenticate, authenticate_noerror, auth_default, authenticate_withUser, authenticate_noerror_WithUser, authenticate_noerror_WithUserLean };

View File

@@ -1,13 +0,0 @@
// @ts-check
function notFound(_req, res) {
res.status(404).json({ message: 'Not Found' });
}
function errorHandler(err, _req, res, _next) {
const status = err.status || 500;
const message = err.message || 'Server Error';
if (status >= 500) console.error(err);
res.status(status).json({ message });
}
module.exports = { notFound, errorHandler };

View File

@@ -1,21 +0,0 @@
// @ts-check
const buckets = new Map();
/** 10 secondi */
const WINDOW_MS = 10_000;
const LIMIT = 100;
function rateLimit(req, res, next) {
const key = req.ip || 'global';
const now = Date.now();
const bucket = buckets.get(key) || { count: 0, ts: now };
if (now - bucket.ts > WINDOW_MS) {
bucket.count = 0;
bucket.ts = now;
}
bucket.count++;
buckets.set(key, bucket);
if (bucket.count > LIMIT) return res.status(429).json({ message: 'Troppo traffico, riprova tra poco.' });
next();
}
module.exports = { rateLimit };

View File

@@ -1,17 +0,0 @@
// @ts-check
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const EventSchema = new Schema({
title: { type: String, required: true },
start: { type: Date, required: true, index: true },
end: { type: Date },
place: String,
teaser: String,
cover: String,
to: String,
createdAt: { type: Date, default: Date.now }
}, { collection: 'events', versionKey: false });
var EventModel = module.exports = mongoose.model('Event', EventSchema);

View File

@@ -1,63 +0,0 @@
// @ts-check
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const HeroSchema = new Schema({
title: { type: String, required: true },
subtitle: String,
badge: String,
mediaUrl: { type: String, required: true },
ctas: [{ label: String, to: String, href: String }]
}, { _id: false });
const PillarSchema = new Schema({
id: { type: String, required: true },
icon: { type: String, required: true },
title: { type: String, required: true },
excerpt: String,
to: String
}, { _id: false });
const TestimonialSchema = new Schema({
id: String, quote: String, author: String, role: String, avatar: String
}, { _id: false });
const GallerySchema = new Schema({
id: String, src: String, alt: String
}, { _id: false });
const FaqSchema = new Schema({
q: String, a: String
}, { _id: false });
const PostLiteSchema = new Schema({
id: String, title: String, date: String, category: String, teaser: String, cover: String, to: String
}, { _id: false });
const PartnerSchema = new Schema({
id: String, name: String, logo: String, href: String
}, { _id: false });
const HomeSchema = new Schema({
hero: { type: HeroSchema, required: true },
pillars: { type: [PillarSchema], default: [] },
testimonials: { type: [TestimonialSchema], default: [] },
gallery: { type: [GallerySchema], default: [] },
faq: { type: [FaqSchema], default: [] },
posts: { type: [PostLiteSchema], default: [] },
partners: { type: [PartnerSchema], default: [] },
meta: { title: String, description: String, ogImage: String },
updatedAt: { type: Date, default: Date.now }
}, { collection: 'home', versionKey: false });
HomeSchema.pre('save', function(next) {
this.set('updatedAt', new Date());
next();
});
var HomeModel = module.exports = mongoose.model('Home', HomeSchema);

View File

@@ -1,128 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
const shared_consts = require('../tools/shared_nodejs');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const JobsInProgressSchema = new Schema({
idapp: {
type: String,
},
descr: {
type: String,
},
nomeFunzioneDbOp: {
type: String,
},
status: {
type: Number,
},
terminatedWhy: {
type: Number,
},
comment: {
type: String,
},
date_created: {
type: Date,
default: Date.now
},
});
JobsInProgressSchema.statics.chechifExistJobWorking = async function (jobData, terminateiftoolong) {
// controlla se esiste un altro job, non ancora terminato !STATUS_JOB.FINISH
// se esiste già allora ritorna false
const existingJob = await this.findOne({ idapp: jobData.idapp, nomeFunzioneDbOp: jobData.nomeFunzioneDbOp, status: { $ne: shared_consts.STATUS_JOB.FINISH } });
if (existingJob) {
// se il Job trovato è passato troppo tempo (oltre 3 ore date_created), allora fai finta che abbia già terminato
// (in questo caso, non ritorna false, ma ritorna il job trovato, per permettere di gestire il caso in cui si vuole forzare il job a terminare)
if (Math.abs(Date.now() - existingJob.date_created.getTime()) > 180 * 60 * 1000) {
if (terminateiftoolong) {
existingJob.status = shared_consts.STATUS_JOB.FINISH;
existingJob.terminatedWhy = shared_consts.TERMINATED_WHY.TOOLONGTIME;
await existingJob.save();
return false;
}
} else {
return true; // E' in FUNZIONE il JOB
}
}
return false;
};
JobsInProgressSchema.statics.addNewJob = async function (jobData) {
if (!jobData || typeof jobData !== 'object') {
console.error('ERRORE: ❌ jobData deve essere un oggetto valido');
}
const esistegia = await this.chechifExistJobWorking(jobData, true);
if (esistegia) {
return null;
}
try {
const newJob = await this.create(jobData);
return newJob;
} catch (err) {
console.error('Errore nell\'aggiungere un nuovo record: ', err);
throw err;
}
};
JobsInProgressSchema.methods.terminateJob = async function (witherror) {
try {
this.status = shared_consts.STATUS_JOB.FINISH;
this.terminatedWhy = witherror ? shared_consts.TERMINATED_WHY.END_WITHERROR : shared_consts.TERMINATED_WHY.END_NORMALLY;
await this.save();
return true;
} catch (err) {
console.error('Errore durante la terminazione del job: ', err);
return false;
}
};
JobsInProgressSchema.statics.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }]
};
JobsInProgressSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params, user);
};
JobsInProgressSchema.statics.findAllIdApp = async function (idapp) {
const JobsInProgress = this;
try {
return await JobsInProgress.find({ idapp }).then((arrrec) => {
return arrrec;
});
} catch (err) {
console.error('Errore: ', err);
}
};
const JobsInProgress = mongoose.model('JobsInProgress', JobsInProgressSchema);
JobsInProgress.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { JobsInProgress };

View File

@@ -1,27 +0,0 @@
// /backend/models/PageView.js
const mongoose = require('mongoose');
const PageViewSchema = new mongoose.Schema({
url: {
type: String,
required: true
},
idapp: String,
ip: {
type: String,
default: 'unknown'
},
userId: String,
username: String,
userAgent: {
type: String
},
referrer: String,
timestamp: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('PageView', PageViewSchema);

View File

@@ -1,16 +0,0 @@
// @ts-check
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostSchema = new Schema({
title: { type: String, required: true },
date: { type: Date, required: true, index: true },
category: String,
teaser: String,
cover: String,
to: String,
bodyMd: String,
createdAt: { type: Date, default: Date.now }
}, { collection: 'posts', versionKey: false });
var PostModel = module.exports = mongoose.model('Post', PostSchema);

View File

@@ -1,791 +0,0 @@
/*
Account is a User's single Circuit
*/
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
const shared_consts = require('../tools/shared_nodejs');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const AccountSchema = new Schema({
_id: {
type: String,
default: function () {
return new ObjectId().toString();
},
},
idapp: {
type: String,
},
numtransactions: {
type: Number,
},
username: {
type: String,
},
groupname: {
// For the Groups
type: String,
},
contocom: {
// For the Conto Comunitario dei Circuiti
type: String,
},
circuitId: {
// ----- REF TO Circuit
type: String,
},
name: {
type: String,
},
deperibile: {
type: Boolean,
},
fidoConcesso: {
type: Number,
},
qta_maxConcessa: {
type: Number,
},
importo_iniziale: {
type: Number,
default: 0,
},
saldo: {
type: Number,
default: 0,
},
totTransato: {
type: Number,
default: 0,
},
saldo_pend: {
type: Number,
default: 0,
},
totTransato_pend: {
type: Number,
default: 0,
},
regulation_ok: {
type: Boolean,
},
deleted: {
type: Boolean,
default: false,
},
date_created: {
type: Date,
default: Date.now,
},
date_updated: {
type: Date,
},
});
AccountSchema.statics.findAllIdApp = async function (idapp) {
const Account = this;
const myfind = { idapp, deleted: false };
return await Account.find(myfind).lean();
};
AccountSchema.pre('save', async function (next) {
if (this.isNew) {
this._id = new ObjectId().toString();
}
next();
});
AccountSchema.statics.getFieldsForSearch = function () {
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'username', type: tools.FieldType.string },
{ field: 'groupname', type: tools.FieldType.string },
{ field: 'contocom', type: tools.FieldType.string },
];
};
AccountSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
AccountSchema.statics.getAccountsByUsername = async function (idapp, username) {
const Account = this;
if (username === undefined) return false;
const myquery = {
idapp: idapp,
username: username,
};
return await Account.find(myquery).lean();
};
AccountSchema.statics.calcTotCircolante = async function (idapp, circuitId) {
const Account = this;
try {
let aggr1 = [
{
$match: { idapp, circuitId, saldo: { $gt: 0 } },
},
{ $group: { _id: null, count: { $sum: '$saldo' } } },
];
const ris = await Account.aggregate(aggr1);
return ris ? ris[0].count : 0;
} catch (e) {
console.error('err', e);
}
};
AccountSchema.methods.calcPending = async function (mittente) {
try {
const account = this;
const { SendNotif } = require('../models/sendnotif');
const { Circuit } = require('../models/circuit');
// *** Calc Pending Transactions ***
const circuit = await Circuit.getCircuitById(account.circuitId);
if (circuit) {
let prec_saldo_pend = account.saldo_pend;
let prec_totTransato_pend = account.totTransato_pend;
let transatopending = 0;
if (mittente) {
let pendingtransactionsMittente = await SendNotif.getSumPendingTransactionsMittente(
account.idapp,
account.username,
circuit.name,
account.groupname
);
let saldopendingMitt = pendingtransactionsMittente.reduce((sum, rec) => sum + rec.extrarec.qty, 0);
transatopending = pendingtransactionsMittente.reduce((sum, rec) => sum + Math.abs(rec.extrarec.qty), 0);
account.saldo_pend = account.saldo - saldopendingMitt;
} else {
// let pendingtransactionsDest = await SendNotif.getSumPendingTransactionsMittente(account.idapp, account.username, circuit.name, account.groupname);
// let saldopendingDest = pendingtransactionsDest.reduce((sum, rec) => sum + rec.extrarec.qty, 0);
// transatopending = pendingtransactionsDest.reduce((sum, rec) => sum + Math.abs(rec.extrarec.qty), 0);
// account.saldo_pend = account.saldo + saldopendingDest;
account.saldo_pend = account.saldo;
}
account.totTransato_pend = account.totTransato + transatopending;
if (prec_saldo_pend !== account.saldo_pend || prec_totTransato_pend !== account.totTransato_pend) {
const myaccountupdate = {
saldo_pend: account.saldo_pend,
totTransato_pend: account.totTransato_pend,
};
// Update Record
return await Account.findByIdAndUpdate(account.id, {
$set: myaccountupdate,
})
.then((ris) => {
console.log('calcPending', ris);
})
.catch((err) => {
console.error('calcPending', err);
});
}
}
// -----
} catch (e) {
console.error(e);
}
};
AccountSchema.statics.addtoSaldo = async function (myaccount, amount, mitt) {
const Account = this;
try {
let myaccountupdate = {};
if (myaccount) {
myaccount.saldo = myaccount.saldo + amount;
if (!myaccount.totTransato) {
myaccount.totTransato = 0;
}
myaccount.totTransato += Math.abs(amount);
if (!myaccount.numtransactions) myaccount.numtransactions = 0;
myaccount.numtransactions++;
myaccount.date_updated = new Date();
myaccountupdate.saldo = myaccount.saldo;
myaccountupdate.totTransato = myaccount.totTransato;
myaccountupdate.numtransactions = myaccount.numtransactions;
myaccountupdate.date_updated = myaccount.date_updated;
const ris = await Account.updateOne(
{ _id: myaccount.id },
{
$set: myaccountupdate,
}
);
// Calcola Saldo Pendente !
await myaccount.calcPending(true);
const recupdated = await Account.findOne({ _id: myaccount.id });
return recupdated;
}
} catch (e) {
console.error('error', e);
}
return null;
};
AccountSchema.pre('save', async function (next) {
if (this.isNew) {
if (!this.date_created) this.date_created = new Date();
}
next();
});
AccountSchema.statics.getAccountByUsernameAndCircuitId = async function (
idapp,
username,
circuitId,
createifnotexist,
confido,
groupname = '',
contocom = ''
) {
const Account = this;
try {
const { Circuit } = require('../models/circuit');
// if (username === undefined)
// return false;
let myquery = {
idapp,
circuitId,
};
if (groupname) {
myquery.groupname = groupname;
} else if (contocom) {
myquery.contocom = contocom;
} else {
myquery.username = username;
}
let mycircuit = await Circuit.getCircuitById(circuitId);
if (mycircuit) {
let myaccount = await Account.findOne(myquery);
if (!myaccount && createifnotexist) {
myaccount = new Account({
_id: new ObjectId().toString(),
idapp,
username: !groupname && !contocom ? username : '',
groupname,
contocom,
circuitId: mycircuit._id,
deperibile: false,
importo_iniziale: 0,
saldo: 0,
saldo_pend: 0,
fidoConcesso: 0,
qta_maxConcessa: 0,
totTransato: 0,
numtransactions: 0,
totTransato_pend: 0,
});
if (contocom) {
myaccount.fidoConcesso =
mycircuit.fido_scoperto_default_contocom || shared_consts.CIRCUIT_PARAMS.SCOPERTO_MIN_CONTO_COMUNITARIO;
myaccount.qta_maxConcessa =
mycircuit.qta_max_default_contocom || shared_consts.CIRCUIT_PARAMS.SCOPERTO_MAX_CONTO_COMUNITARIO;
} else {
if (!mycircuit.fido_scoperto_default_grp)
mycircuit.fido_scoperto_default_grp = shared_consts.CIRCUIT_PARAMS.SCOPERTO_MIN_GRP;
if (!mycircuit.qta_max_default_grp)
mycircuit.qta_max_default_grp = shared_consts.CIRCUIT_PARAMS.SCOPERTO_MAX_GRP;
if (groupname) {
myaccount.fidoConcesso = mycircuit.fido_scoperto_default_grp;
myaccount.qta_maxConcessa = mycircuit.qta_max_default_grp;
} else {
myaccount.fidoConcesso = mycircuit.fido_scoperto_default;
myaccount.qta_maxConcessa = mycircuit.qta_max_default;
}
}
if (!confido) {
myaccount.fidoConcesso = 0;
}
let acc = await myaccount.save();
if (mycircuit.creditodiPartenza && mycircuit.creditodiPartenza > 0) {
acc = await Account.addtoSaldo(acc, mycircuit.creditodiPartenza, false);
}
return acc;
}
return myaccount;
}
return null;
} catch (e) {
console.error('error', e);
}
};
AccountSchema.statics.isExistAccountByUsernameAndCircuitId = async function (
idapp,
username,
circuitId,
groupname = '',
contocom = ''
) {
const Account = this;
try {
const { Circuit } = require('../models/circuit');
if (username === undefined) return false;
let myquery = {
idapp,
circuitId,
};
if (groupname) {
myquery.groupname = groupname;
} else if (contocom) {
myquery.contocom = contocom;
} else {
myquery.username = username;
}
let mycircuit = await Circuit.getCircuitById(circuitId);
if (mycircuit) {
let myaccount = await Account.findOne(myquery);
return !!myaccount;
}
return false;
} catch (e) {
console.error('error', e);
}
};
AccountSchema.statics.createAccount = async function (
idapp,
username,
circuitName,
confido,
groupname = '',
contocom = ''
) {
const { Circuit } = require('../models/circuit');
try {
mycircuit = await Circuit.findOne({ name: circuitName }, { _id: 1 });
if (mycircuit) {
return await Account.getAccountByUsernameAndCircuitId(
idapp,
username,
mycircuit._id,
true,
confido,
groupname,
contocom
);
} else {
return null;
}
} catch (e) {
console.error('error', e);
return null;
}
};
AccountSchema.statics.getUserAccounts = async function (idapp, username) {
const { SendNotif } = require('../models/sendnotif');
try {
let aggr1 = [
{
$match: { idapp, username },
},
{
$lookup: {
from: 'circuits',
localField: 'circuitId',
foreignField: '_id',
as: 'circuit',
},
},
{ $unwind: '$circuit' },
{
$lookup: {
from: 'sendnotifs',
as: 'notifspending',
let: {
circuitname: '$circuit.name',
username: '$username',
idapp: '$idapp',
typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS,
typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ,
},
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idapp', '$$idapp'] },
{ $eq: ['$typedir', '$$typedir'] },
{ $eq: ['$typeid', '$$typeid'] },
{ $eq: ['$status', 0] },
{ $eq: ['$sender', '$$username'] },
{ $eq: ['$extrarec.circuitname', '$$circuitname'] },
],
},
},
},
{
$group: { _id: '$extrarec.notifIdToUpdate', result: { $first: '$$ROOT' } },
},
],
},
},
];
const ris = await this.aggregate(aggr1);
// console.log('1 - INIZIA getUserAccounts ')
// console.log(aggr1);
/* if (ris) {
for (const account of ris) {
try {
//++OTTIMIZZARE QUESTA PARTE ! (CON UNA QUERY...)
// console.log(' 1B - PENDIND... ')
let pendingtransactions = await SendNotif.getSumPendingTransactions(idapp, username, account.circuit.name);
let saldopending = pendingtransactions.reduce((sum, rec) => sum + rec.extrarec.qty, 0);
if (saldopending !== 0) {
account.saldo -= saldopending;
account.totTransato = account.totTransato || 0;
}
} catch (e) {
console.error('getUserAccounts 1) ', e);
}
}
} */
return ris;
} catch (e) {
console.error('getUserAccounts', e);
}
};
AccountSchema.statics.getGroupAccounts = async function (idapp, groupname) {
if (!groupname) {
return [];
}
try {
let aggr1 = [
{
$match: { idapp, groupname },
},
{
$lookup: {
from: 'circuits',
localField: 'circuitId',
foreignField: '_id',
as: 'circuit',
},
},
{ $unwind: '$circuit' },
{
$lookup: {
from: 'sendnotifs',
as: 'notifspending',
let: {
circuitname: '$circuit.name',
groupname: '$groupname',
idapp: '$idapp',
typedir: shared_consts.TypeNotifs.TYPEDIR_CIRCUITS,
typeid: shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ,
},
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$typedir', '$$typedir'] },
{ $eq: ['$typeid', '$$typeid'] },
{ $eq: ['$status', 0] },
{ $eq: ['$sendergroup', '$$groupname'] },
{ $eq: ['$idapp', '$$idapp'] },
{ $eq: ['$extrarec.circuitname', '$$circuitname'] },
],
},
},
},
{
$group: { _id: '$extrarec.notifIdToUpdate', result: { $first: '$$ROOT' } },
},
],
},
},
];
const ris = await this.aggregate(aggr1);
return ris;
} catch (e) {
console.error('e', e);
}
};
// Imposta a tutti i Conti Collettivi, i seguenti minimi e massimi
AccountSchema.statics.SetMinMaxCollettivi = async function (idapp, valmin, valmax) {
const Account = this;
const ris = await Account.updateMany(
{ idapp, groupname: { $nin: [null, ''] } },
{
$set: {
fidoConcesso: valmin,
qta_maxConcessa: valmax,
},
}
);
};
// Imposta a tutti i Conti Comunitari, i seguenti minimi e massimi
AccountSchema.statics.SetMinMaxComunitari = async function (idapp, valmin, valmax) {
const Account = this;
const ris = await Account.updateMany(
{ idapp, contocom: { $nin: [null, ''] } },
{
$set: {
fidoConcesso: valmin,
qta_maxConcessa: valmax,
},
}
);
};
// Imposta a tutti i Conti Personali, i seguenti minimi e massimi
AccountSchema.statics.SetMinMaxPersonali = async function (idapp, fidoConcesso, qta_maxConcessa, circuitId) {
const Account = this;
if (circuitId) {
const ris = await Account.updateMany(
{ idapp, circuitId, fidoConcesso: { $gt: 0 }, username: { $nin: [null, ''] } },
{
$set: {
fidoConcesso,
qta_maxConcessa,
},
}
);
const circuit = await Circuit.findOne({ _id: circuitId });
if (!circuit.circuitoIndipendente) {
// Se aggiorno questi dati, e non è un Circuito Indipendente, allora devo aggiornare anche gli account del RIS Nazionale
await Account.updateAccountCircuitoItaliaByLimiti(idapp, circuitId, fidoConcesso, qta_maxConcessa);
}
} else {
const ris = await Account.updateMany(
{ idapp, fidoConcesso: { $gt: 0 }, username: { $nin: [null, ''] } },
{
$set: {
fidoConcesso,
qta_maxConcessa,
},
}
);
}
};
AccountSchema.statics.updateFido = async function (idapp, username, groupname, circuitId, fido) {
let paramstoupdate = {
fidoConcesso: fido,
};
let risult = null;
if (groupname) risult = await Account.updateOne({ idapp, circuitId, groupname }, { $set: paramstoupdate });
else risult = await Account.updateOne({ idapp, username, circuitId }, { $set: paramstoupdate });
return risult;
};
AccountSchema.statics.updateQtaMax = async function (idapp, username, groupname, circuitId, qtamax) {
let paramstoupdate = {
qta_maxConcessa: qtamax,
};
let risult = null;
if (groupname) risult = await Account.updateOne({ idapp, circuitId, groupname }, { $set: paramstoupdate });
else risult = await Account.updateOne({ idapp, username, circuitId }, { $set: paramstoupdate });
return risult && risult.modifiedCount > 0;
};
AccountSchema.statics.getAccountsCircuitiExtraProvinciali = async function (idapp) {
const { Circuit } = require('../models/circuit');
const circuits = await Circuit.getCircuitiExtraProvinciali(idapp);
if (circuits.length > 0) {
const circuitIds = circuits.map((circuit) => circuit._id);
return Account.find({ idapp, circuitId: { $in: circuitIds } });
}
};
AccountSchema.statics.getAccountsCircuitoItalia = async function (idapp) {
const { Circuit } = require('../models/circuit');
const circuit = await Circuit.getCircuitoItalia(idapp);
if (circuit) {
return Account.find({ idapp, circuitId: circuit._id });
}
};
AccountSchema.statics.updateAccountCircuitoItaliaByLimiti = async function (
idapp,
circuitId,
fidoConcesso,
qta_maxConcessa
) {
const { Circuit } = require('../models/circuit');
try {
const accounts = await this.getAccountsCircuitoItalia(idapp);
for (const account of accounts) {
const circuitId = account.circuitId;
const circuit = await Circuit.findOne({ _id: circuitId });
if (circuit) {
let fido = 0;
let qtamax = 0;
if (account.groupname) {
fido = circuit.fido_scoperto_default_grp * shared_consts.CIRCUIT_CFG.MULT_FIDO_GROUP;
qtamax = circuit.qta_max_default_grp * shared_consts.CIRCUIT_CFG.MULT_FIDO_GROUP;
} else {
fido = circuit.fido_scoperto_default * shared_consts.CIRCUIT_CFG.MULT_FIDO_USER;
qtamax = circuit.qta_max_default * shared_consts.CIRCUIT_CFG.MULT_FIDO_USER;
}
let paramstoupdate = {
fidoConcesso: fido,
qta_maxConcessa: qtamax,
};
risult = await Account.updateOne({ _id: account.id }, { $set: paramstoupdate });
}
}
return risult;
} catch (e) {
console.error('updateAccountCircuitoItaliaByLimiti', e);
}
return false;
};
AccountSchema.statics.canEditAccountAdmins = async function (username, id) {
const account = await Account.findOne({ _id: id }).lean();
const { Circuit } = require('../models/circuit');
if (account) {
const circuit = await Circuit.findOne({ _id: account.circuitId }).lean();
if (circuit) {
return circuit.admins.findIndex((admin) => admin.username === username) >= 0;
}
}
return false;
};
AccountSchema.statics.addToPeopleOfMyAccount = async function (idapp, username, circuitId, person_username, perm) {
return await Account.updateOne(
{ idapp, username, circuitId },
{
$push: {
people: {
username: person_username,
perm,
date: new Date(),
},
},
}
);
};
// Rimuovi dagli Admin del Account
AccountSchema.statics.removeAdminOfAccount = async function (idapp, username, circuitId, person_username, perm) {
const { Circuit } = require('../models/circuit');
return await Circuit.updateOne(
{ idapp, username, circuitId },
{ $pull: { people: { username: { $in: [person_username] } } } }
);
};
// Rimuovi l'account
AccountSchema.statics.removeAccount = async function (accountId) {
return await Account.deleteOne({ _id: accountId });
};
AccountSchema.statics.updateSaldoAndTransato_AllAccounts = async function (idapp) {
const recaccounts = await Account.find({ idapp });
for (const account of recaccounts) {
await account.calcPending();
}
};
const Account = mongoose.model('Account', AccountSchema);
Account.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports = { Account };

View File

@@ -1,66 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "";
const tools = require('../tools/general');
const {ObjectId} = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const AdTypeSchema = new Schema({
_id: {
type: Number,
},
descr: {
type: String,
},
});
AdTypeSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await AdType.findOne().limit(1).sort({_id:-1});
if (!!myrec) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
}
next();
});
AdTypeSchema.statics.findAllIdApp = async function(idapp) {
const AdType = this;
return AdType.find({}).sort({_id: 1}).lean();
};
AdTypeSchema.statics.getFieldsForSearch = function() {
return [
{field: 'descr', type: tools.FieldType.string}];
};
AdTypeSchema.statics.executeQueryTable = function(idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const AdType = mongoose.model('AdType', AdTypeSchema);
AdType.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = {AdType};

View File

@@ -1,72 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "";
const tools = require('../tools/general');
const {ObjectId} = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const AdTypeGoodSchema = new Schema({
_id: {
type: Number,
},
descr: {
type: String,
},
});
AdTypeGoodSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await AdTypeGood.findOne().limit(1).sort({_id:-1});
if (!!myrec) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
}
next();
});
AdTypeGoodSchema.statics.findAllIdApp = async function(idapp) {
const AdTypeGood = this;
const query = [
{$sort: {_id: 1}},
];
return await AdTypeGood.aggregate(query).then((arrrec) => {
return arrrec;
});
};
AdTypeGoodSchema.statics.getFieldsForSearch = function() {
return [
{field: 'descr', type: tools.FieldType.string}];
};
AdTypeGoodSchema.statics.executeQueryTable = function(idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const AdTypeGood = mongoose.model('AdTypeGood', AdTypeGoodSchema);
AdTypeGood.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = {AdTypeGood};

View File

@@ -1,397 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const tools = require('../tools/general');
const { Reaction } = require('./reaction');
const { MyGroup } = require('./mygroup');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
const tableModel = shared_consts.TABLES_ATTIVITAS;
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const AttivitaSchema = new Schema(
{
...{
_id: {
type: String,
default: function () {
return new ObjectId().toString();
},
},
idapp: {
type: String,
required: true,
},
// userId: { type: Schema.Types.ObjectId, ref: 'User' },
idSector: {
type: Number,
},
idSkill: {
type: Number,
default: 0,
},
idCity: [
{
type: Number,
}],
logo:
{
imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
},
photos: [
{
imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
}],
note: {
type: String,
default: '',
},
website: {
type: String,
},
date_created: {
type: Date,
},
date_updated: {
type: Date,
},
tipodiAttivita: {
type: Number,
},
descr: {
type: String,
},
note: {
type: String,
},
coordinate_gps: {
address: {
type: String,
default: '',
},
type: {
type: String,
enum: ['Point'], // Specifica il tipo, in questo caso solo 'Point'
required: false,
},
coordinates: {
type: [Number], // L'array dovrebbe contenere lon e lat
required: false,
index: '2dsphere' // Indice geospaziale [lng, lat]
},
},
email: {
type: String,
},
telegram_username: {
type: String,
},
cell_phone: {
type: String,
},
whatsapp: {
type: String,
},
createdBy: { // Username del creatore (proponente)
type: String,
},
//**ADDFIELD_ATTIVITA
},
...Reaction.getFieldsForReactions(),
...tools.getFieldsForAnnunci()
}, { strict: false });
AttivitaSchema.pre('save', async function (next) {
if (this.isNew) {
if (!this.date_created)
this.date_created = new Date();
}
next();
});
AttivitaSchema.statics.findAllIdApp = async function (idapp) {
const Attivita = this;
const query = [
{ $match: { idapp } },
{ $sort: { descr: 1 } },
];
return await Attivita.aggregate(query).then((arrrec) => {
return arrrec;
});
};
AttivitaSchema.statics.getFieldsForSearch = function () {
return [];
};
AttivitaSchema.statics.getFieldsLastForSearch = function () {
return [
{ field: 'note', type: tools.FieldType.string },
{ field: 'descr', type: tools.FieldType.string },
{ field: 'recSkill.descr', type: tools.FieldType.string },
{ field: 'attivita.descr', type: tools.FieldType.string },
];
};
AttivitaSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
params.fieldsearch_last = this.getFieldsLastForSearch();
const otherparams = {
lookup1: {
lk_tab: 'users',
lk_LF: 'userId',
lk_FF: '_id',
lk_as: 'user',
af_objId_tab: 'myId',
lk_proj: shared_consts.getProjectForAll({}, tableModel),
},
};
params = { ...params, ...otherparams };
return tools.executeQueryTable(this, idapp, params, user);
};
AttivitaSchema.statics.getMyRecById = function (idapp, idSkill) {
const Attivita = this;
let query = [
{
'$match': {
'_id': idSkill, idapp
},
},
{
'$sort': {
'desc': 1,
},
},
{
'$addFields': {
'myId1': {
'$toObjectId': '$userId',
},
},
},
{
'$lookup': {
'from': 'users',
'localField': 'myId1',
'foreignField': '_id',
'as': 'user',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$user',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'skills',
'localField': 'idSkill',
'foreignField': '_id',
'as': 'recSkill',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$recSkill',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'sectors',
'localField': 'idSector',
'foreignField': '_id',
'as': 'sector',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$sector',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$attivita',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'cities',
'localField': 'idCity',
'foreignField': '_id',
'as': 'mycities',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$mycities',
0,
],
},
'$$ROOT',
],
},
},
},
];
let numtab = tools.getNumTabByTable(shared_consts.TABLES_ATTIVITAS);
const objadd = tools.addNumFavoriteAndBookmarkToQuery(idapp, numtab);
query = [...query, ...objadd.query];
const toadd = {
$project: shared_consts.getProjectForAll(objadd.proj, tableModel),
};
query = [...query, { ...toadd }];
return Attivita.aggregate(query).then((rec) => {
return rec ? rec[0] : null;
});
};
AttivitaSchema.statics.getProject = function (proj_add2) {
let proj = {
recSkill: 1,
sector: 1,
idSector: 1,
idSkill: 1,
idCity: 1,
logo: 1,
photos: 1,
note: 1,
descr: 1,
website: 1,
date_created: 1,
date_updated: 1,
tipodiAttivita: 1,
coordinate_gps: 1,
email: 1,
telegram_username: 1,
cell_phone: 1,
whatsapp: 1,
createdBy: 1,
//**ADDFIELD_ATTIVITA
};
const proj_add = shared_consts.getProjectForAll(proj_add2)
return Object.assign({}, proj, proj_add);
}
AttivitaSchema.statics.getCompleteRecord = function (idapp, id) {
const Attivita = this;
return Attivita.getMyRecById(idapp, id);
};
const Attivita = mongoose.model('Attivita', AttivitaSchema);
Attivita.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Attivita };

View File

@@ -1,57 +0,0 @@
mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = 'F';
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const AuthorSchema = new Schema({
idapp: {
type: String,
},
name: {
type: String,
},
surname: {
type: String,
},
bio: {
type: String,
},
img: {
type: String,
},
});
var Author = (module.exports = mongoose.model('Author', AuthorSchema));
module.exports.getFieldsForSearch = function () {
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'surname', type: tools.FieldType.string },
];
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Author.find(myfind).sort({ name: 1, surname: 1 }).select({ idapp: 0 }).lean();
};
module.exports
.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});

View File

@@ -1,127 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const bookingSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String,
},
username: {
type: String,
},
tableType: {
type: Number,
},
id_bookedevent: {
type: String,
},
numpeople: {
type: Number,
},
numpeopleLunch: {
type: Number,
},
numpeopleDinner: {
type: Number,
},
numpeopleDinnerShared: {
type: Number,
},
infoevent: {
type: String,
},
msgbooking: {
type: String,
},
datebooked: {
type: Date,
},
modified: {
type: Boolean,
default: false
},
booked: {
type: Boolean,
},
});
bookingSchema.statics.findAllByUserIdAndIdApp = function (userId, idapp, sall) {
const Booking = this;
let myfind = {};
if (sall === '1')
myfind = { idapp, booked: true };
else
myfind = { userId, idapp, booked: true };
return Booking.find(myfind).lean();
};
function getUsersByBooking(idapp) {
const query = [
{
$match: { idapp }
},
{
$group: { _id: "$userId" }
},
{
$project: {
_id: {
$toString: "$userId"
}
}
},
{
$Lookup: {
from: "users",
localField: "userId", // field in my collection
foreignField: "new ObjectId(_id)", // field in the 'from' collection
as: "fromItems"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$fromItems", 0] },] } }
},
{ $project: { username: 1, name: 1, surname: 1 } }
];
return query
}
bookingSchema.statics.findAllDistinctByBooking = function (idapp) {
const Booking = this;
const query = getUsersByBooking(idapp);
return Booking.aggregate(query)
.then(ris => {
return ris
});
};
const Booking = mongoose.model('Booking', bookingSchema);
Booking.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Booking };

View File

@@ -1,213 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = 'F';
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const BotSchema = new Schema({
idapp: {
type: String,
},
page: {
type: Number,
},
index: {
type: Number,
},
riga: {
type: Number,
},
active: {
type: Boolean,
},
lang: {
type: String,
},
main: {
type: Boolean,
},
label: {
type: String,
},
type: {
type: Number,
},
value: {
type: String,
},
visibility: {
type: Number, // VISIB_ALL, VISIB_ONLYIF_LOGGED, VISIB_ONLY_ADMIN
},
date_updated: {
type: Date,
},
});
BotSchema.statics.getFieldsForSearch = function () {
return [{ field: 'label', type: tools.FieldType.string }]
};
BotSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
BotSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {
return await tools.DuplicateAllRecords(this, idapporig, idappdest);
};
BotSchema.statics.generateBotMenuRecords = async function (idapp) {
try {
let arrrec = [
{
"page": 1,
"index": 1,
"riga": 1,
"active": true,
"label": "Vai al Sito",
"type": 3,
"value": "{host}",
"visibility": 0,
idapp,
"lang": "it",
"main": true
},
{
"page": 1,
"index": 1,
"riga": 2,
"active": true,
"label": "Il mio Profilo",
"type": 3,
"value": "{host}/my/{username}",
"visibility": 1,
idapp,
"lang": "it",
"main": true
},
{
"page": 1,
"index": 1,
"riga": 3,
"active": true,
"label": "Link da Condividere",
"type": 2,
"value": "{host}/registrati/{username}",
"visibility": 1,
idapp,
"lang": "it",
"main": true,
},
{
"page": 1,
"index": 2,
"riga": 1,
"active": true,
"label": "🔮 Help",
"type": 4,
"value": "",
"visibility": 0,
idapp,
"lang": "it",
"main": true,
},
{
"page": 1,
"index": 1,
"riga": 3,
"active": true,
"label": "💁‍♀️ Admin",
"type": 4,
"value": "",
"visibility": 5,
idapp,
"lang": "it",
"main": true
},
{
"page": 1,
"index": 2,
"riga": 2,
"active": true,
"label": "Imposta Foto Profilo",
"type": 4,
"value": "🖼 SetPicProfile",
"visibility": 1,
idapp,
"lang": "it",
"main": true
},
{
"page": 1,
"index": 2,
"riga": 3,
"active": true,
"label": "🛠 Strumenti",
"type": 1,
"value": "2",
"visibility": 1,
idapp,
"lang": "it",
"main": true,
},
{
"page": 2,
"index": 1,
"riga": 1,
"active": true,
"label": "🔑 Cambio Password",
"type": 4,
"value": "🔑 SetResetPwd",
"visibility": 1,
idapp,
"lang": "it",
},
{
"page": 2,
"index": 1,
"riga": 2,
"active": true,
"label": "👉🏻 Indietro",
"type": 1,
"value": "1",
"visibility": 1,
idapp,
"lang": "it",
}];
const ris = await MyBot.insertMany(arrrec);
return ris;
} catch (e) {
console.error('Err:', e);
}
}
BotSchema.statics.findAllIdApp = async function (idapp) {
const Bot = this;
const myfind = { idapp };
return await Bot.find(myfind).sort({ page: 1, lang: 1, riga: 1, index: 1 }).lean();
};
const MyBot = mongoose.model('Bot', BotSchema);
MyBot.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { MyBot };

View File

@@ -1,84 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CalZoomSchema = new Schema({
idapp: {
type: String,
},
lang: {
type: String,
},
title: {
type: String,
},
typeconf: {
type: String,
},
icon: {
type: String,
},
color: {
type: String,
},
date_start: {
type: Date
},
benvenuto: {
type: Boolean
},
date_end: {
type: Date
},
id_conf_zoom: {
type: String
},
note: {
type: String
}
});
CalZoomSchema.statics.getFieldsForSearch = function () {
return [{field: 'title', type: tools.FieldType.string}]
};
CalZoomSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
CalZoomSchema.statics.findAllIdApp = async function (idapp) {
const CalZoom = this;
const myfind = { idapp, date_start: { $gt: tools.IncDateNow(-1000 * 60 * 60 * 3) } };
return await CalZoom.find(myfind).sort({ date_start: 1 }).limit(10);
};
CalZoomSchema.statics.getNextZoom = async function (idapp) {
const CalZoom = this;
// const myfind = { idapp, $and: [{ date_start: { $gt: tools.IncDateNow(-1000 * 60 * 5) } }, { date_start: { $lt: tools.IncDateNow(1000 * 60 * 60 * 6) } }] } ;
const myfind = { idapp, $and: [{ date_start: { $lt: tools.IncDateNow(1000 * 60 * 5) } }, { date_start: { $gt: tools.IncDateNow(-1000 * 60 * 60 * 2) } }] } ;
return await CalZoom.findOne(myfind).sort({ date_start: 1 });
};
const CalZoom = mongoose.model('CalZoom', CalZoomSchema);
CalZoom.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { CalZoom };

View File

@@ -1,273 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = 'F';
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const CartSchema = new Schema({
idapp: {
type: String,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
totalQty: { type: Number, default: 0 },
totalPrice: { type: Number, default: 0 },
totalPriceCalc: { type: Number, default: 0 },
totalPriceIntero: { type: Number, default: 0 },
department: {
type: String,
ref: 'Department',
},
items: [
{
order: { type: Schema.Types.ObjectId, ref: 'Order' },
},
],
note: {
type: String,
},
codice_sconto: {
type: String,
},
descr_sconto: {
type: String,
},
note_ordine_gas: {
type: String,
},
modify_at: {
type: Date,
},
});
var Cart = (module.exports = mongoose.model('Cart', CartSchema));
module.exports.findAllIdApp = async function (idapp, userId) {
const myfind = { idapp, userId };
return await Cart.findOne(myfind).lean();
};
module.exports.getCartByUserId = async function (uid, idapp) {
try {
let mycart = await getCart(uid, idapp);
if (!mycart) return null;
await updateOrderDetails(mycart.items);
let haschanged = await filterValidItems(mycart);
// haschanged = true;
if (haschanged) {
const CartClass = require('../modules/Cart')
await saveCartItemsOrder(mycart);
mycart = await CartClass.aggiornaCarrelloByCart(mycart, uid, idapp);
}
return mycart;
} catch (e) {
console.log('getCartByUserId err', e);
}
};
module.exports.getCartCompletoByCartId = async function (id_cart, idapp) {
try {
const mycart = await getCartById(id_cart, idapp);
if (!mycart) return null;
await updateOrderDetails(mycart.items);
await filterValidItems(mycart);
return mycart;
} catch (e) {
console.log('getCartByUserId err', e);
}
};
// Recupera il carrello per l'utente e l'app
async function getCart(uid, idapp) {
const query = { userId: uid, idapp };
return await Cart.findOne(query).lean();
}
async function saveCartItemsOrder(cart) {
// aggiorna solo gli'id dell'order in items
for (const item of cart.items) {
item.order = item.order._id;
}
return await Cart.updateOne({ _id: cart._id }, { $set: { items: cart.items } });
}
async function getCartById(id_cart, idapp) {
return await Cart.findOne({ _id: id_cart }).lean();
}
// Aggiorna i dettagli dell'ordine per ogni articolo nel carrello
async function updateOrderDetails(items) {
const Order = require('../models/order');
for (const item of items) {
try {
const idorder = item.order ? item.order._id.toString() : item._id.toString();
const myord = await Order.getTotalOrderById(idorder);
if (myord.length > 0) {
item.order = myord[0];
}
} catch (e) {
console.log('err', e);
}
}
}
async function checkIfExistProduct(code) {
const Product = require('../models/product');
try {
const prod = await Product.findOne({ 'productInfo.code': code }).exec();
if (prod && prod.active) {
return prod;
} else {
return null;
}
} catch (e) {
console.log('err', e);
return null;
}
}
// Filtra solo gli articoli validi (con quantità > 0 o pre-ordinati)
async function filterValidItems(mycart) {
try {
mycart.newitems = [];
let haschanged = false;
for (let item of mycart.items) {
try {
if (
item.order &&
item.order.hasOwnProperty('idapp') &&
item.order.product.productInfo &&
(item.order.quantity > 0 || item.order.quantitypreordered > 0) &&
(await checkIfExistProduct(item.order.product.productInfo.code))
) {
mycart.newitems.push(item);
} else {
const Order = require('./order');
const OrdersCart = require('./orderscart');
// Cancella l'ordine su Order e OrderCart e cancella il record su Cart
await OrdersCart.deleteOrderById(item.order._id.toString());
await Order.deleteOrderById(item.order._id.toString());
haschanged = true;
}
} catch (e) {
console.log('err', e);
}
}
mycart.items = [...mycart.newitems];
mycart.newitems = [];
return haschanged;
} catch (e) {
console.log('err', e);
return false;
}
}
module.exports.updateCartByUserId = async function (userId, newCart) {
const query = { userId: userId };
try {
// Cerca il carrello esistente nel database
const existingCart = await Cart.findOne(query);
if (existingCart) {
// Se il carrello esiste, aggiorna i dati
const updatedCart = await Cart.findOneAndUpdate(
query,
{
$set: {
items: newCart.items,
totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice,
totalPriceIntero: newCart.totalPriceIntero,
totalPriceCalc: newCart.totalPriceCalc,
userId: userId,
},
},
{ new: true } // Restituisce il documento aggiornato
);
return updatedCart; // Restituisce il carrello aggiornato
} else {
// Se il carrello non esiste, crea un nuovo documento
const createdCart = new Cart(newCart);
await createdCart.init();
const savedCart = await createdCart.save();
return savedCart; // Restituisce il carrello creato
}
} catch (err) {
// Gestione degli errori
console.error("Errore durante l'aggiornamento del carrello:", err);
throw err; // Propaga l'errore al chiamante
}
};
module.exports.updateCartByCartId = async function (cartId, newCart) {
// delete newCart._doc._id;
const items = newCart.items;
const totalQty = newCart.totalQty;
const totalPrice = newCart.totalPrice;
const totalPriceCalc = newCart.totalPriceCalc;
const totalPriceIntero = newCart.totalPriceIntero;
const note = newCart.note;
const codice_sconto = newCart.codice_sconto;
const descr_sconto = newCart.descr_sconto;
const note_ordine_gas = newCart.note_ordine_gas;
const modify_at = new Date();
return await Cart.findOneAndUpdate(
{ _id: cartId },
{
$set: {
items,
totalPrice,
totalPriceCalc,
totalPriceIntero,
totalQty,
note,
codice_sconto,
descr_sconto,
note_ordine_gas,
modify_at: new Date(),
},
},
{ new: false }
)
.lean()
.then((ris) => {
return ris;
})
.catch((err) => {
console.log('err', err);
return null;
});
};
module.exports.deleteCartByCartId = async function (cartId) {
return await Cart.deleteOne({ _id: cartId });
};
module.exports.createCart = async function (newCart) {
return await newCart.save();
};
Cart.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});

View File

@@ -1,74 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CashCategorySchema = new Schema({
idapp: {
type: String,
},
descr: {
type: String,
},
notes: {
type: String
},
});
var CashCategory = module.exports = mongoose.model('CashCategory', CashCategorySchema);
CashCategory.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports.getFieldsForSearch = function () {
return []
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await CashCategory.find(myfind).lean();
};
module.exports.getAllCashCategory = function (query, sort, callback) {
CashCategory.find(query, null, sort, callback)
}
module.exports.getCashCategoryByUserId = function (userId, sort, callback) {
CashCategory.find({ userId }, null, sort, callback)
}
module.exports.getCashCategoryByID = function (id, callback) {
CashCategory.findById(id, callback);
}
module.exports.createCashCategory = async function (CashCategory) {
const CashCategoryModel = new CashCategory(CashCategory);
return await CashCategoryModel.save(CashCategory)
.then((ris) => {
if (!!ris)
return ris._id;
return null;
});
}

View File

@@ -1,76 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CashSubCategorySchema = new Schema({
idapp: {
type: String,
},
idCashCategory: {
type: String,
},
descr: {
type: String,
},
notes: {
type: String
},
});
var CashSubCategory = module.exports = mongoose.model('CashSubCategory', CashSubCategorySchema);
module.exports.getFieldsForSearch = function () {
return []
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await CashSubCategory.find(myfind).lean();
};
module.exports.getAllCashSubCategory = function (query, sort, callback) {
CashSubCategory.find(query, null, sort, callback)
}
module.exports.getCashSubCategoryByUserId = function (userId, sort, callback) {
CashSubCategory.find({ userId }, null, sort, callback)
}
module.exports.getCashSubCategoryByID = function (id, callback) {
CashSubCategory.findById(id, callback);
}
module.exports.createCashSubCategory = async function (CashSubCategory) {
const CashSubCategoryModel = new CashSubCategory(CashSubCategory);
return await CashSubCategoryModel.save(CashSubCategory)
.then((ris) => {
if (!!ris)
return ris._id;
return null;
});
}
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

View File

@@ -1,62 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CatAISchema = new Schema({
name: {
type: String,
},
idapp: {
type: String,
},
img: {
type: String,
},
icon: {
type: String,
},
color: {
type: String,
},
});
CatAISchema.statics.getAllCategories = function (callback) {
CatAI.find(callback)
}
CatAISchema.statics.getCatAIById = function (id, callback) {
CatAI.findById(id, callback);
}
CatAISchema.statics.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
CatAISchema.statics.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params);
};
CatAISchema.statics.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await CatAI.find(myfind).sort({ name: 1 }).lean();
};
const CatAI = mongoose.model('CatAI', CatAISchema);
CatAI.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = CatAI;

View File

@@ -1,343 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
const { IImg } = require('../models/myscheda');
mongoose.Promise = global.Promise;
mongoose.level = 'F';
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const CatalogSchema = new Schema({
idapp: {
type: String,
},
active: {
type: Boolean,
default: false,
},
title: {
type: String,
index: true,
},
foto_collana: IImg,
idCollane: [
{
type: String,
},
],
idTipoFormato: [
{
type: Number,
},
],
argomenti: [
{
type: String,
},
],
condition_andor: {
type: Number,
default: 0,
},
editore: [{ type: String }],
editore_escludi: [{ type: String }],
descr_introduttiva: {
type: String,
},
idPageAssigned: {
type: String,
},
referenti: [
{
type: String,
},
],
disattiva_link_immagini: Boolean,
img_bordata: IImg,
img_intro: IImg,
img_bordata_stampa: IImg,
img_intro_stampa: IImg,
pagina_introduttiva_sfondo_nero: {
type: Boolean,
},
backcolor: String,
pdf_generato: String,
pdf_generato_compressed: String,
pdf_generato_size: String,
pdf_generato_compr_size: String,
pdf_generato_stampa: String,
pdf_generato_stampa_compressed: String,
pdf_generato_stampa_compr_size: String,
pdf_generato_stampa_size: String,
data_generato: {
type: Date,
},
data_generato_stampa: {
type: Date,
},
username_lista_generata: {
type: String,
},
data_lista_generata: {
type: Date,
},
data_lista_updated: {
type: Date,
},
username_lista_updated: {
type: String,
},
pdf_online: String,
pdf_online_size: String,
data_online: {
type: Date,
},
pdf_online_stampa: String,
pdf_online_stampa_size: String,
data_online_stampa: {
type: Date,
},
date_created: {
type: Date,
default: Date.now,
},
date_updated: {
type: Date,
},
lista_prodotti: [
{
type: Schema.Types.ObjectId,
ref: 'Product',
},
],
isCatalogoGenerale: Boolean,
});
/*
TOLTO ALTRIMENTI su /settable non mi crea l'ID
CatalogSchema.pre('save', async function (next) {
if (this.isNew) {
this._id = new ObjectId();
}
next();
});
*/
CatalogSchema.statics.getFieldsForSearch = function () {
return [{ field: 'title', type: tools.FieldType.string }];
};
CatalogSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params, user);
};
/*CatalogSchema.statics.OLD_findAllIdApp = async function (idapp) {
const Catalog = this;
const arrrec = await Catalog.aggregate([
// Filtra i documenti per idapp
{ $match: { idapp } },
// Ordina i risultati per titolo
{ $sort: { title: 1 } },
// Esegui il join con la collezione Collana
{
$lookup: {
from: "collanas", // Nome della collezione Collana
localField: "idCollane", // Campo in Catalog
foreignField: "idCollana", // Campo in Collana
as: "collana_info" // Nome del campo che conterrà i risultati del join
}
},
]);
return arrrec;
};*/
CatalogSchema.statics.findAllIdApp = async function (idapp) {
try {
const arrrec = await this.aggregate([
{ $match: { idapp } },
{ $addFields: { num_lista_prodotti: { $size: { $ifNull: ['$lista_prodotti', []] } } } },
{ $project: { lista_prodotti: 0 } },
{ $sort: { title: 1 } },
]);
return arrrec;
} catch (err) {
console.error('Errore:', err);
throw err;
}
};
CatalogSchema.statics.getCatalogById = async function (id) {
const Catalog = this;
try {
let arrrec = await Catalog.find({ _id: id })
.populate({
path: 'lista_prodotti',
populate: [
{
path: 'productInfo.idCatProds',
model: 'CatProd',
},
{
path: 'productInfo.idSubCatProds',
model: 'SubCatProd',
},
{
path: 'productInfo.idAuthors',
model: 'Author',
},
{
path: 'productInfo.idCollana',
model: 'Collana',
},
{
path: 'productInfo.idPublisher',
model: 'Publisher',
},
],
})
.populate({
path: 'lista_prodotti',
populate: {
path: 'idProducer',
model: 'Producer',
},
})
.populate({
path: 'lista_prodotti',
populate: {
path: 'idProvider',
model: 'Provider',
},
})
.populate({
path: 'lista_prodotti',
populate: {
path: 'idStorehouses',
model: 'Storehouse',
},
})
.populate({
path: 'lista_prodotti',
populate: {
path: 'idScontisticas',
model: 'Scontistica',
},
})
.populate({
path: 'lista_prodotti',
populate: {
path: 'idGasordine',
model: 'Gasordine',
},
});
// controlla prima se nella lista ci sono dei product che non esistono piu allora li devi rimuovere !
for (const catalog of arrrec) {
let old_lista = [...catalog.lista_prodotti];
let nuova_lista = [...catalog.lista_prodotti];
const originalLength = catalog.lista_prodotti.length;
nuova_lista = nuova_lista.filter(
(product) =>
product.productInfo &&
product.productInfo.code &&
product.productInfo.code !== '' &&
product.productInfo.imagefile &&
product.productInfo.imagefile !== 'noimg.jpg' &&
!product.delete
);
// Se la nuova lista è diversa da quella precedente di più del 10%, allora non aggiorna, perché potrebbe esserci un problema
let differencePercentage = (100 * Math.abs(originalLength - nuova_lista.length)) / originalLength;
if (differencePercentage < 10) {
// Aggiorno la lista solo se è cambiata poco
// confronta l'array nuova_lista con l'array catalog.lista_prodotti
let differents = tools.areDifferentProduct(catalog.lista_prodotti, nuova_lista);
if (differents) {
// aggiorna la lista
catalog.lista_prodotti = nuova_lista;
await catalog.save();
}
}
}
const transformedArrRec = arrrec.map((catalog) => ({
...catalog.toObject(), // Converte il documento Mongoose in un oggetto JavaScript puro
lista_prodotti: catalog.lista_prodotti.map((product) => ({
...product.toObject(),
productInfo: {
...product.productInfo,
catprods: product.productInfo.idCatProds,
subcatprods: product.productInfo.idSubCatProds,
collana: product.productInfo.idCollana,
authors: product.productInfo.idAuthors,
},
producer: product.idProducer,
storehouse: product.idStorehouses,
scontisticas: product.idScontisticas,
gasordine: product.idGasordine,
})),
}));
return transformedArrRec && transformedArrRec.length > 0 ? transformedArrRec[0] : null;
} catch (err) {
console.error('Errore: ', err);
return null;
}
};
CatalogSchema.statics.executeQueryPickup = async function (idapp, params) {
const strfind = params.search;
if (strfind === '') {
return [];
}
// Cerca title
const reg = new RegExp(strfind, 'i');
const arrrec = await this.find({
idapp,
title: reg,
})
.sort({ title: 1 })
.limit(10)
.select('title _id')
.lean();
return arrrec;
};
const Catalog = mongoose.model('Catalog', CatalogSchema);
Catalog.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports = { Catalog };

View File

@@ -1,59 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CategorySchema = new Schema({
idapp: {
type: String,
},
name: {
type: String,
unique: true,
index: true,
},
img: {
type: String,
},
});
CategorySchema.statics.getAllCategories = function (callback) {
Category.find(callback)
}
CategorySchema.statics.getCategoryById = function (id, callback) {
Category.findById(id, callback);
}
CategorySchema.statics.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
CategorySchema.statics.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params);
};
CategorySchema.statics.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Category.find(myfind).lean();
};
const Category = mongoose.model('Category', CategorySchema);
Category.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Category };

View File

@@ -1,88 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CatGrpSchema = new Schema({
_id: {
type: Number,
},
descr: {
type: String,
},
idCatGrp: {
type: Number
},
icon: {
type: String,
},
img: {
type: String,
},
color: {
type: String,
},
theme: {
type: String,
},
});
CatGrpSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await CatGrp.findOne().limit(1).sort({_id:-1});
if (!!myrec) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
}
next();
});
CatGrpSchema.statics.findAllIdApp = async function (idapp) {
const CatGrp = this;
const query = [
{ $sort: { descr: 1 } }
];
return await CatGrp
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
CatGrpSchema.statics.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }]
};
CatGrpSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const CatGrp = mongoose.model('CatGrp', CatGrpSchema);
CatGrp.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { CatGrp };

View File

@@ -1,182 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CatProdSchema = new Schema({
idapp: {
type: String,
},
idArgomento: {
type: Number,
},
name: {
type: String,
index: 1,
},
descr_estesa: {
type: String,
},
img: {
type: String,
},
icon: {
type: String,
},
color: {
type: String,
},
quanti: {
type: Number,
}
});
CatProdSchema.statics.getAllCategories = function (callback) {
CatProd.find(callback)
}
CatProdSchema.statics.getCatProdById = function (id, callback) {
CatProd.findById(id, callback);
}
CatProdSchema.statics.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
CatProdSchema.statics.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params);
};
CatProdSchema.statics.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await CatProd.find(myfind).sort({ name: 1 }).lean();
};
/*CatProdSchema.statics.updateCatDeleteEmpty = async function (idapp) {
try {
const toDelete = await CatProd.aggregate([
{ $match: { idapp } },
{
$lookup: {
from: 'products',
localField: '_id',
foreignField: 'idCatProds',
as: 'products'
}
},
{
$project: {
_id: 1,
name: 1,
quanti: { $size: '$products' } // Conta il numero di prodotti per ciascun CatProd
}
},
{ $match: { quanti: 0 } },
]);
if (toDelete.length > 0) {
const ids = toDelete.map(x => x._id);
const ris = await CatProd.deleteMany({ _id: { $in: ids } });
const deletedRecs = toDelete.map(x => ({ _id: x._id, name: x.name }));
if (deletedRecs.length > 0) {
return `Lista Argomenti cancellati: ${deletedRecs.map(x => x.name).join(', ')}`;
}
}
return "Nessun argomento cancellato";
} catch (error) {
console.error('Error UpdateCatDeleteEmpty:', error);
return error;
}
};*/
CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp, updatedata) {
try {
const myquery = [
{ $match: { idapp } },
{
$lookup: {
from: 'products', // Nome della tua collezione productInfo
localField: '_id',
foreignField: 'productInfo.idCatProds',
as: 'products'
}
},
{
$addFields: {
myproducts: {
$filter: {
input: "$products",
as: "prod",
cond: {
$in: ["$$prod.productInfo.idStatoProdotto", [1, 4, 34, 45, 46]]
}
}
}
}
}, {
$project: {
_id: 1,
name: 1,
idArgomento: 1,
descr_estesa: 1,
img: 1,
icon: 1,
color: 1,
quanti: { $size: '$myproducts' }, // Conta il numero di prodotti per ciascun CatProd
/*products: {
$map: {
input: "$myproducts",
as: "prod",
in: {
name: "$$prod.name"
}
}
}*/
}
},
{ $sort: { name: 1 } } // Ordina i risultati per nome
];
const result = await CatProd.aggregate(myquery);
// console.log(JSON.stringify(myquery, null, 2))
if (updatedata) {
for (const record of result) {
await CatProd.updateOne(
{ _id: record._id },
{ $set: { quanti: record.quanti } }
);
}
}
return result;
} catch (error) {
console.error('Error retrieving CatProd with title count:', error);
throw error;
}
}
const CatProd = mongoose.model('CatProd', CatProdSchema);
CatProd.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = CatProd;

View File

@@ -1,52 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CfgServerSchema = new Schema({
chiave: {
type: String,
trim: true,
minlength: 1,
},
idapp: {
type: String,
},
userId: {
type: String,
},
valore: {
type: String,
},
});
CfgServerSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {
return await tools.DuplicateAllRecords(this, idapporig, idappdest);
};
CfgServerSchema.statics.findAllIdApp = async function(idapp) {
const myfind = { idapp };
return await CfgServer.find(myfind).lean();
};
const CfgServer = mongoose.model('CfgServer', CfgServerSchema);
CfgServer.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = {CfgServer};

File diff suppressed because it is too large Load Diff

View File

@@ -1,282 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
const escapeStringRegexp = require('escape-string-regexp');
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
const fs = require('fs-extra');
const shared_consts = require('../tools/shared_nodejs');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const CitySchema = new Schema({
_id: {
type: Number,
},
istat: {
type: String,
},
comune: {
type: String,
},
prov: {
type: String,
maxlength: 3,
},
reg: {
type: String,
maxlength: 3,
},
pref: {
type: String,
},
cap: {
type: String,
maxlength: 6,
},
abitanti: {
type: String,
},
country: {
type: String,
maxlength: 3,
},
geojson: {
type: Object, // Tipo che può contenere le features GeoJSON
},
});
CitySchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await City.findOne().limit(1).sort({ _id: -1 });
if (!!myrec) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
}
next();
});
CitySchema.statics.getProvinceByIdCity = async function (idcity) {
const myrec = await City.findOne({ _id: idcity }).lean();
if (myrec) {
return myrec.prov;
}
return '';
}
CitySchema.statics.getCircuitNameBystrProv = async function (strProv) {
const { Circuit } = require('../models/circuit');
const myrec = await Circuit.findOne({ strProv }).lean();
if (myrec) {
return myrec.name;
}
return '';
}
CitySchema.statics.getRegionByIdCity = async function (idcity) {
const myrec = await City.findOne({ _id: idcity }).lean();
if (myrec) {
return myrec.reg;
}
return '';
}
CitySchema.statics.findByCity = function (mycity) {
let myregexp = new RegExp(mycity.trim().replace(' ', '|'), 'ig');
const query = [
{ $match: { comune: { $regex: myregexp } } },
{ $sort: { descr: 1 } },
];
return City.aggregate(query).then((arrrec) => {
return arrrec;
});
};
CitySchema.statics.getFieldsForSearch = function () {
return [
{ field: 'comune', type: tools.FieldType.string },
{ field: 'prov', type: tools.FieldType.string },
{ field: 'reg', type: tools.FieldType.string },
{ field: 'pref', type: tools.FieldType.number },
{ field: 'cap', type: tools.FieldType.number },
];
};
CitySchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
const strfind = params.search;
if (strfind === '') {
return [];
}
return tools.executeQueryTable(this, 0, params);
};
CitySchema.statics.executeQueryPickup = async function (idapp, params) {
const strfind = params.search;
if (strfind === '' && !params.filter) {
return [];
}
let filterfindexact = {};
if (strfind) {
filterfindexact = { comune: strfind };
}
let limit = 10;
let risexact = [];
let filterfind = { comune: { $regex: '^' + strfind, $options: 'i' } };
let aggr1 = [
{
$match: { comune: strfind },
},
{ $limit: 1 },
{
$project: {
comune: { $concat: ["$comune", " (", "$prov", ")"] },
},
},
];
if (params.filter) {
filterfind = { ...params.filter, ...filterfind };
limit = 200;
} else {
// risexact = await City.find(filterfindexact, {comune: 1, prov: 1, reg: 1}).lean();
risexact = await City.aggregate(aggr1);
}
let aggr2 = [
{
$match: filterfind,
},
{ $limit: limit },
{
$project: {
comune: { $concat: ["$comune", " (", "$prov", ")"] },
},
},
];
// let ris = await City.find(filterfind, {comune: 1, prov: 1, reg: 1}).lean().limit(limit);
let ris = await City.aggregate(aggr2).limit(limit);
return [...risexact, ...ris];
};
CitySchema.statics.findAllIdApp = async function (idapp) {
const myfind = {};
return await City.find(myfind).lean();
};
CitySchema.statics.getGeoJsonByProvince = async function (prov) {
let ris = null;
if (prov)
ris = await City.find({ prov }).lean();
else
ris = await City.find({}).lean();
try {
if (ris) {
const arrjson = ris
.filter(record => record.geojson && typeof record.geojson === 'object' && record.geojson.geometry) // Prima filtra per mantenere solo gli oggetti con "geometry"
.map((record, index) => {
// Crea un nuovo oggetto con gli attributi desiderati da ogni record
const newRecord = {
...record.geojson, // Spread dell'oggetto geojson per prendere tutte le sue proprietà
id: (index + 1).toString(), // Aggiunge un valore "id" incrementale in base all'indice
};
// Aggiungi o aggiorna la proprietà "prov" in "properties" dentro l'oggetto geojson
if (newRecord.properties) {
newRecord.properties.prov = record.prov; // Se "properties" esiste già
} else {
newRecord.properties = { prov: record.prov }; // Crea "properties" se non esiste
}
return newRecord;
});
return arrjson;
}
return [];
} catch (e) {
console.error('Err', e);
}
return null
};
CitySchema.statics.insertGeojsonToMongoDB = async function (nomefilejson) {
try {
// Lettura del file GeoJSON
const geojson = await fs.readJson(nomefilejson); // Sostituisci con il percorso del tuo file GeoJSON
let inseriti = 0;
const numcomuni = geojson.features.length;
for (const citta of geojson.features) {
// Identifica il documento esistente in cui vuoi aggiungere le features
const reccity = await City.findOne({ istat: String(citta.properties.ISTAT).padStart(6, '0') });
if (reccity) {
const ris = await City.updateOne({ _id: reccity._id }, { $set: { geojson: citta } });
if (ris.acknowledged) {
inseriti++;
}
}
}
console.log(`${inseriti} su ${numcomuni} comuni inseriti.`);
} catch (e) {
console.error('Err', e);
}
};
const City = mongoose.model('City', CitySchema);
City.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { City };

View File

@@ -1,129 +0,0 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const CollanaSchema = new Schema({
idapp: {
type: String,
},
idCollana: {
type: Number,
},
title: {
type: String,
index: true,
},
dataOra: {
type: Date,
},
enabled: {
type: Boolean,
},
enabledAlFresco: {
type: Boolean,
},
quanti: {
type: Number,
},
});
var Collana = module.exports = mongoose.model('Collana', CollanaSchema);
module.exports.getFieldsForSearch = function () {
return [
{ field: 'title', type: tools.FieldType.string },
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Collana.find(myfind).sort({title: 1}).lean();
};
module.exports.getCollaneWithTitleCount = async function (idapp, updatedata) {
try {
const myquery = [
{ $match: { idapp } },
{
$lookup: {
from: 'products', // Nome della tua collezione productInfo
localField: '_id',
foreignField: 'productInfo.idCollana',
as: 'products'
}
},
{
$addFields: {
myproducts: {
$filter: {
input: "$products",
as: "prod",
cond: {
$in: ["$$prod.productInfo.idStatoProdotto", [1, 4, 34, 45, 46]]
}
}
}
}
}, {
$project: {
_id: 1,
title: 1,
idCollana: 1,
dataOra: 1,
quanti: { $size: '$myproducts' },
products: {
$map: {
input: "$myproducts",
as: "prod",
in: {
name: "$$prod.name"
}
}
}
}
},
{ $match: { quanti: { $gt: 0 } } }, // esclude i record con quanti = 0
{ $sort: { title: 1 } } // Ordina i risultati per nome
];
const result = await Collana.aggregate(myquery);
if (updatedata) {
for (const record of result) {
await Collana.updateOne(
{ _id: record._id },
{ $set: { quanti: record.quanti } }
);
}
}
return result;
} catch (error) {
console.error('Error retrieving idCollana with title count:', error);
throw error;
}
}
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

View File

@@ -1,60 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const ContribtypeSchema = new Schema({
idapp: {
type: String,
},
label: {
type: String,
},
showprice: {
type: Boolean,
}
});
ContribtypeSchema.statics.getFieldsForSearch = function () {
return [{field: 'label', type: tools.FieldType.string}]
};
ContribtypeSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
ContribtypeSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {
return await tools.DuplicateAllRecords(this, idapporig, idappdest);
};
ContribtypeSchema.statics.findAllIdApp = async function (idapp) {
const Contribtype = this;
const myfind = { idapp };
return await Contribtype.find(myfind).lean();
};
const Contribtype = mongoose.model('Contribtype', ContribtypeSchema);
Contribtype.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Contribtype };

View File

@@ -1,176 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
mongoose.Promise = global.Promise;
mongoose.level = 'F';
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const CronMod = require('../modules/CronMod');
const CronSchema = new Schema({
idapp: {
type: String,
},
active: {
type: Boolean,
default: false,
},
descr: {
type: String,
},
nomeFunzioneDbOp: {
type: String,
},
startTime: {
// Orario iniziale (es. "08:30")
type: String,
},
everyXMinutes: {
// Esegui ogni X ore
type: Number,
},
quanteVolteEseguito: {
type: Number,
default: 0,
},
quanteVolteEseguiAlGG: {
type: Number,
default: 1,
},
lastJobStarted: {
type: Date,
},
lastJobEnd: {
type: Date,
},
log: {
type: String,
},
status: {
type: Number,
},
date_created: {
type: Date,
default: Date.now,
},
date_updated: {
type: Date,
},
});
CronSchema.statics.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }];
};
CronSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params, user);
};
CronSchema.statics.startJobCron = async function (idapp) {
// Esegui un loop su tutti i cron job che trovi per l'idapp specificato
const Cron = this;
try {
const cronJobs = await Cron.find({ idapp, active: true });
// console.log('Check startJobCron...', idapp);
const mycronMod = new CronMod();
const currentDate = new Date();
for (const mycron of cronJobs) {
const jobTime = new Date();
const [hours, minutes] = mycron.startTime.split(':');
jobTime.setHours(hours, minutes, 0, 0);
// Check if jobTime has passed and if 'everyXMinutes' have elapsed since last execution
if (!mycron.quanteVolteEseguito) mycron.quanteVolteEseguito = 0;
const timesPerDay = mycron.quanteVolteEseguiAlGG || 1;
const startDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
let lastJobDate = null;
if (mycron.lastJobStarted) {
lastJobDate = new Date(
mycron.lastJobStarted.getFullYear(),
mycron.lastJobStarted.getMonth(),
mycron.lastJobStarted.getDate()
);
}
let tempooltre = currentDate - mycron.lastJobStarted >= mycron.everyXMinutes * 60 * 1000;
const canExecute =
(!mycron.lastJobStarted || // se non c'è un ultimo eseguito, esegui
tempooltre) && // se è passato il tempo di attesa, esegui
(mycron.lastJobStarted && (mycron.quanteVolteEseguito < timesPerDay) || // se non ho ancora raggiunto il numero di esecuzioni al giorno
(!lastJobDate || (startDate.getTime() !== lastJobDate.getTime()))); // se non è lo stesso giorno, esegui
if (canExecute) {
if (currentDate >= jobTime) {
// Execute the function at the scheduled time
console.log(`Sto eseguendo il Cron Job: ${mycron.nomeFunzioneDbOp} alle ${currentDate.toLocaleTimeString()}`);
const status = shared_consts.STATUS_JOB.START;
if (!lastJobDate || startDate.getTime() !== lastJobDate.getTime()) {
mycron.quanteVolteEseguito = 0;
}
const quanteVolteEseguito = mycron.quanteVolteEseguito + 1;
await Cron.findOneAndUpdate(
{ _id: mycron._id },
{ $set: { lastJobStarted: currentDate, status, quanteVolteEseguito } },
{ new: true }
);
mycronMod
.eseguiDbOp(idapp, { dbop: mycron.nomeFunzioneDbOp }, null, null)
.then(async (ris) => {
console.log(`${currentDate.toLocaleTimeString()} LOG JOB: ${ris.mystr}`);
const myid = mycron._id;
const status = shared_consts.STATUS_JOB.FINISH;
const risupdate = await Cron.findOneAndUpdate(
{ _id: myid },
{ $set: { lastJobEnd: new Date(), status } },
{ new: true }
);
})
.catch(async (err) => {
const log = "Errore durante l'esecuzione del job: " + err.message || err;
const status = shared_consts.STATUS_JOB.ERR;
await Cron.findOneAndUpdate({ _id: mycron._id }, { $set: { log, status } }, { new: true });
console.error(log);
});
}
}
}
} catch (e) {
console.error('Error startJobCron:', e);
return false;
}
};
CronSchema.statics.findAllIdApp = async function (idapp) {
const Cron = this;
try {
return await Cron.find({ idapp }).then((arrrec) => {
return arrrec;
});
} catch (err) {
console.error('Errore: ', err);
}
};
const Cron = mongoose.model('Cron', CronSchema);
Cron.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports = { Cron };

View File

@@ -1,50 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const departmentSchema = new Schema({
idapp: {
type: String,
},
name: {
type: String,
},
username: {
type: String,
},
});
var Department = module.exports = mongoose.model('Department', departmentSchema);
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string },
{ field: 'username', type: tools.FieldType.string }
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Department.find(myfind).lean();
};

View File

@@ -1,59 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const DestNewsletterSchema = new Schema({
idapp: {
type: String,
},
descr: {
type: String,
},
tipodest_id: {
type: Number,
},
});
DestNewsletterSchema.statics.getFieldsForSearch = function () {
return []
};
DestNewsletterSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
DestNewsletterSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {
return await tools.DuplicateAllRecords(this, idapporig, idappdest);
};
DestNewsletterSchema.statics.findAllIdApp = async function (idapp) {
const DestNewsletter = this;
const myfind = { idapp };
return await DestNewsletter.find(myfind).lean();
};
const DestNewsletter = mongoose.model('DestNewsletter', DestNewsletterSchema);
DestNewsletter.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { DestNewsletter };

View File

@@ -1,114 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const DisciplineSchema = new Schema({
idapp: {
type: String,
},
order: {
type: Number,
},
typol_code: {
type: String,
},
label: {
type: String,
},
description: {
type: String,
},
linkpage: {
type: String,
},
color: {
type: String,
},
icon: {
type: String,
},
img_small: {
type: String,
},
img: {
type: String,
},
showinnewsletter: {
type: Boolean,
},
showinhome: {
type: Boolean,
},
teachers: [{
type: String,
}],
});
DisciplineSchema.statics.findAllIdApp = async function (idapp) {
const Discipline = this;
const query = [
{ $match: { idapp } },
{ $sort: { order: 1 } }
];
return await Discipline
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
DisciplineSchema.statics.getDisciplineforNewsletter = function (idapp) {
const Discipline = this;
const query = [
{ $match: { $and: [{ idapp }, { showinnewsletter: true }] } },
{ $sort: { order: 1 } }
];
return Discipline
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
DisciplineSchema.statics.getFieldsForSearch = function () {
return [{ field: 'label', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string }]
};
DisciplineSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
DisciplineSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {
return await tools.DuplicateAllRecords(this, idapporig, idappdest);
};
const Discipline = mongoose.model('Discipline', DisciplineSchema);
Discipline.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Discipline };

View File

@@ -1,341 +0,0 @@
var bcrypt = require('bcryptjs');
const mongoose = require('mongoose').set('debug', false)
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
mongoose.set('debug', false);
var ExtraListSchema = new mongoose.Schema({
idapp: {
type: String,
required: true,
},
ind_order: {
type: Number,
},
date_reg: {
type: Date,
},
name_complete: {
type: String,
trim: true,
},
username: {
type: String,
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
num_invitati: {
type: Number,
},
is_in_whatsapp: {
type: Boolean,
},
is_in_telegram: {
type: Boolean,
},
is_staff: {
type: Boolean,
},
cell_complete: {
type: String
},
nationality: {
type: String
},
saw_zoom_presentation: {
type: Boolean
},
aportador_solidario_name_surname: {
type: String,
},
aportador_solidario_ind_order: {
type: Number,
},
aportador_solidario_originale_name_surname: {
type: String,
},
note: {
type: String,
},
contacted: {
type: Boolean,
},
col_b: {
type: Number,
},
col_h: {
type: Number,
},
registered: {
type: Boolean,
default: false
},
});
// ExtraListSchema.methods.toJSON = function () {
// const extralist = this;
// const userObject = extralist.toObject();
//
// return _.pick(userObject, ['_id', ...shared_consts.fieldsUserToChange()]);
// };
//
ExtraListSchema.statics.findByUsername = function (idapp, username) {
const ExtraList = this;
return ExtraList.findOne({
'idapp': idapp,
'username': username,
});
};
ExtraListSchema.statics.getTotInLista = async function (idapp) {
const ExtraList = this;
const myfind = { idapp };
return await ExtraList.countDocuments(myfind);
};
ExtraListSchema.statics.getRegDellaLista = async function (idapp) {
const ExtraList = this;
const myfind = { idapp, registered: true };
return await ExtraList.countDocuments(myfind);
};
ExtraListSchema.statics.getLastUser = function (idapp) {
const ExtraList = this;
return ExtraList.findOne({ idapp }).sort({ ind_order: -1 })
};
ExtraListSchema.statics.findByCellAndNameSurname = function (idapp, cell_complete, name, surname) {
const ExtraList = this;
return ExtraList.findOne({
'idapp': idapp,
'cell_complete': cell_complete,
'name': name,
'surname': surname,
});
};
ExtraListSchema.statics.findByIndOrder = function (idapp, ind_order) {
const ExtraList = this;
try {
return ExtraList.findOne({
'idapp': idapp,
'ind_order': ind_order,
});
} catch (e) {
}
};
ExtraListSchema.statics.getUsersList = function (idapp) {
const User = this;
return User.find({ 'idapp': idapp }, {
username: 1,
name: 1,
surname: 1,
lasttimeonline: 1,
date_reg: 1,
})
};
// ExtraListSchema.statics.getDownlineNotRegisteredByNameSurname = function (idapp, nameandsurname) {
// const ExtraList = this;
//
// return ExtraList.find({
// 'aportador_solidario_name_surname': nameandsurname,
// registered: false,
// }, {
// ind_order: 1,
// name: 1,
// surname: 1,
// cell_complete: 1,
// num_invitati: 1,
// nationality: 1,
// }, (err, arrrec) => {
// return arrrec
// });
// };
// ExtraListSchema.statics.getUserNotRegisteredByNameSurname = function (idapp, nameandsurname) {
// const ExtraList = this;
//
// return ExtraList.findOne({
// name_complete: nameandsurname,
// registered: false,
// }, {
// lang: 1,
// ind_order: 1,
// name: 1,
// surname: 1,
// cell_complete: 1,
// num_invitati: 1,
// nationality: 1,
// }, (err, arrrec) => {
// return arrrec
// });
// };
//
ExtraListSchema.statics.getFieldsForSearch = function () {
return [
{ field: 'username', type: tools.FieldType.string },
{ field: 'name', type: tools.FieldType.string },
{ field: 'surname', type: tools.FieldType.string },
{ field: 'cell_complete', type: tools.FieldType.string },
{ field: 'aportador_solidario_name_surname', type: tools.FieldType.string },
{ field: 'aportador_solidario_originale_name_surname', type: tools.FieldType.string }]
};
ExtraListSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
ExtraListSchema.statics.findAllIdApp = async function (idapp) {
const ExtraList = this;
const myfind = { idapp };
return await tools.findAllQueryIdApp(this, myfind);
};
ExtraListSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {
return await tools.DuplicateAllRecords(this, idapporig, idappdest);
};
/*
ExtraListSchema.statics.ImportData = async function (locale, idapp, strdata) {
const ExtraList = this;
try {
let numadded = 0;
let numtot = 0;
let numalreadyexisted = 0;
// Convert to array
let arrusers = strdata.split('\n');
let sep = ',';
// console.log('arrusers', arrusers);
try {
for (const row of arrusers) {
console.log('row', row);
if (sep !== '' && row !== '') {
let col = row.split(sep);
if (col) {
if (col.length > 11) {
let user = null;
try {
user = new ExtraList({
idapp: idapp,
ind_order: col[0],
name_complete: col[2].trim(),
num_invitati: col[3].trim(),
is_in_whatsapp: col[4].trim() !== '',
is_in_telegram: col[5].trim() !== '',
is_staff: col[5].trim() === 'VV',
saw_zoom_presentation: col[6].trim() !== '',
cell_complete: col[7].trim(),
nationality: col[8].trim(),
aportador_solidario_name_surname: col[9].trim(),
aportador_solidario_ind_order: col[10].trim(),
aportador_solidario_originale_name_surname: col[11].trim(),
note: col[12].trim(),
col_b: col[13].trim(),
col_h: col[14].trim()
});
try {
user.date_reg = col[1];
} catch (e) {
console.log('error ', e);
}
if (user.cell_complete[0] !== '+')
user.cell_complete = '+' + user.cell_complete;
namesurname = tools.extractNameAndSurnameByComplete(user.name_complete);
user.name = namesurname.name;
user.surname = namesurname.surname;
if (user.name && user.surname && user.cell_complete) {
// Save into db
await user.save();
numadded++;
}
} catch (e) {
console.log('error ', e, col);
}
numtot++;
}
// numalreadyexisted++;
}
}
}
} catch (e) {
console.log('error ', e);
}
ris = { numadded, numtot, numalreadyexisted };
console.log(ris);
return ris
} catch (e) {
console.err(e);
}
};
*/
const ExtraList = mongoose.model('ExtraList', ExtraListSchema);
ExtraList.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { ExtraList };

View File

@@ -1,70 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const GallerySchema = new Schema({
idapp: {
type: String,
},
author_username: {
type: String,
},
title: {
type: String,
},
directory: {
type: String,
},
list: [
{
imagefile: {
type: String
},
order: {
type: Number
},
alt: {
type: String
},
description: {
type: String
}
}
]
});
GallerySchema.statics.getFieldsForSearch = function () {
return [{ field: 'title', type: tools.FieldType.string }]
};
GallerySchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
GallerySchema.statics.findAllIdApp = async function (idapp) {
const Gallery = this;
const myfind = { idapp };
return await Gallery.find(myfind).lean();
};
const Gallery = mongoose.model('Gallery', GallerySchema);
Gallery.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Gallery };

View File

@@ -1,84 +0,0 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const gasordineSchema = new Schema({
active: {
type: Boolean,
},
idapp: {
type: String,
},
name: {
type: String,
},
description: {
type: String,
},
referente: {
type: String,
},
city: {
type: String,
},
img: {
type: String,
},
note_ordine_gas: {
type: String,
},
dataora_chiusura_ordini: {
type: Date,
},
data_arrivo_merce: {
type: Date,
},
dataora_ritiro: {
type: Date,
},
dataora_termine_pagamento: {
type: Date,
},
});
var Gasordine = module.exports = mongoose.model('Gasordine', gasordineSchema);
module.exports.getFieldsForSearch = function () {
return [
{field: 'name', type: tools.FieldType.string},
{field: 'description', type: tools.FieldType.string},
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Gasordine.find(myfind).sort({dataora_chiusura_ordini: -1}).lean();
};
module.exports.getGasordineByID = function (id, callback) {
Gasordine.findById(id, callback);
}
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

View File

@@ -1,88 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const GoodSchema = new Schema({
_id: {
type: Number,
},
descr: {
type: String,
},
idSectorGood: [{
type: Number
}],
icon: {
type: String,
},
img: {
type: String,
},
});
GoodSchema.statics.findAllIdApp = async function (idapp) {
const Good = this;
const query = [
{ $sort: { descr: 1 } }
];
const res = await Good
.aggregate(query)
.then((arrrec) => {
return arrrec
})
return res;
};
GoodSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await Good.findOne().limit(1).sort({_id:-1});
if (!!myrec) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
}
next();
});
GoodSchema.statics.getFieldsForSearch = function () {
return [{ field: 'label', type: tools.FieldType.string },
{ field: 'descr', type: tools.FieldType.string }]
};
GoodSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const Good = mongoose.model('Good', GoodSchema);
Good.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Good };

View File

@@ -1,421 +0,0 @@
const bcrypt = require('bcryptjs');
const mongoose = require('mongoose').set('debug', false)
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
const { Settings } = require('./settings');
const shared_consts = require('../tools/shared_nodejs');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
mongoose.set('debug', false);
const GraduatoriaSchema = new mongoose.Schema({
idapp: {
type: String,
required: true,
},
index: {
type: Number,
},
idListaIngresso: {
type: String,
},
ind_order: {
type: Number,
},
num_tess: {
type: Number,
},
ind: {
type: Number,
},
// USER:
username: {
type: String,
},
name: {
type: String,
},
surname: {
type: String,
},
indimbarco: {
type: Number,
},
numNaviEntrato: { // Numero dell'Imbarco attuale
type: Number,
},
numinvitati: {
type: Number,
},
numinvitatiattivi: {
type: Number,
},
numinvitatiTot: {
type: Number,
},
numinvitatiattiviTot: {
type: Number,
},
punteggio: {
type: Number,
},
invitante_username: {
type: String,
},
navestr: {
type: String,
},
note: {
type: String,
},
date_added: { // Data d'Ingresso (Completato i Requisiti o premuto Bottone Magico)
type: Date,
},
});
GraduatoriaSchema.pre('save', async function (next) {
if (this.isNew) {
try {
if (!this.index) {
const myrec = await Graduatoria.findOne({ idapp: this.idapp }).limit(1).sort({ index: -1 });
if (!!myrec) {
this.index = myrec._doc.index + 1;
} else {
this.index = 1;
}
}
} catch (e) {
this.index = 2;
}
}
next();
});
GraduatoriaSchema.statics.findByIndOrder = function (idapp, ind_order) {
const Graduatoria = this;
try {
return Graduatoria.findOne({
'idapp': idapp,
'ind_order': ind_order,
});
} catch (e) {
}
};
GraduatoriaSchema.statics.findByAllRecByUsername = function (idapp, username) {
const Graduatoria = this;
try {
return Graduatoria.find({
idapp,
username,
});
} catch (e) {
}
};
GraduatoriaSchema.statics.getNumDaImbarcare = async function (idapp) {
const Graduatoria = this;
return await Graduatoria. countDocuments({ idapp })
};
GraduatoriaSchema.statics.AggiornaIndiceGraduatoria = async function (idapp) {
const Graduatoria = this;
let index = 1;
await Graduatoria.find({ idapp }).sort({ punteggio: -1, date_added: 1 }).then(async (arrrec) => {
for (const rec of arrrec) {
await Graduatoria.findOneAndUpdate({ _id: rec._id }, { $set: { index } }, { new: false });
index++;
}
});
return index - 1;
};
GraduatoriaSchema.statics.getLastImbarco = async function (idapp, username) {
const Graduatoria = this;
return await Graduatoria.findOne({ idapp, username }).sort({ _id: -1 });
};
GraduatoriaSchema.statics.getFirstUserGradFree = async function (idapp) {
const Graduatoria = this;
const { User } = require('../models/user');
const arrrecgrad = await Graduatoria.find({ idapp, ind_order: { $gt: 0 } }).sort({ index: 1 }).limit(20);
if (!!arrrecgrad) {
for (const recgrad of arrrecgrad) {
const myuser = await User.findOne({
idapp,
username: recgrad.username,
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }]
});
if (!!myuser) {
return recgrad;
}
}
}
return null;
};
/*
GraduatoriaSchema.statics.addSingoloInGraduatoria_InFondo = async function (idapp, recingr) {
const Graduatoria = this;
const lastimbarco = await Graduatoria.getLastImbarco(idapp, recingr.username);
const arrindex = [];
if (!!lastimbarco) {
arrindex[recingr.username] = lastimbarco.indimbarco;
} else {
arrindex[recingr.username] = 1;
}
const newingr = await ListaIngresso.aggiornaRecListaIngr(idapp, recingr, arrindex);
const myrectoadd = addRecGraduatoria(idapp, newingr, 100000);
return await myrectoadd.save(myrectoadd)
.then((ris) => {
return !!ris;
})
.catch((e) => {
console.error(e.message);
});
};
*/
function addRecGraduatoria(idapp, ingr, index) {
try {
let rec = new Graduatoria({
_id: new ObjectId(),
idapp,
idListaIngresso: ingr._id,
ind_order: ingr.ind_order,
num_tess: ingr.num_tess,
username: ingr.username,
name: ingr.name,
surname: ingr.surname,
indimbarco: ingr.indimbarco,
numNaviEntrato: ingr.numNaviEntrato,
numinvitati: ingr.numinvitati,
numinvitatiattivi: ingr.numinvitatiattivi,
numinvitatiTot: ingr.numinvitatiTot,
numinvitatiattiviTot: ingr.numinvitatiattiviTot,
punteggio: ingr.punteggio,
invitante_username: ingr.invitante_username,
navestr: ingr.navestr,
note: ingr.note,
date_added: ingr.date_added,
});
if (!!index) {
rec.index = index;
}
return rec;
} catch (e) {
console.error(e.message);
return null;
}
}
GraduatoriaSchema.statics.addArrayInGraduatoria = async function (idapp, arrayingr) {
const Graduatoria = this;
try {
let myobjadd = [];
let index = 0;
for (const ingr of arrayingr) {
index++;
myobjadd.push(addRecGraduatoria(idapp, ingr, index));
}
// Cancella prima tutto
await Graduatoria.deleteMany({ idapp });
// Riscrivi Tutto
const ris = await Graduatoria.insertMany(myobjadd);
if (!!ris)
return ris.length;
else
return 0;
} catch (e) {
console.error(e.message);
}
return null;
};
GraduatoriaSchema.statics.getFieldsForSearch = function () {
return [
{ field: 'index', type: tools.FieldType.number },
{ field: 'ind_order', type: tools.FieldType.number },
{ field: 'name', type: tools.FieldType.string },
{ field: 'surname', type: tools.FieldType.string },
{ field: 'username', type: tools.FieldType.string },
{ field: 'invitante_username', type: tools.FieldType.string },
]
};
GraduatoriaSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
GraduatoriaSchema.statics.findAllIdApp = async function (idapp) {
const Graduatoria = this;
const myfind = { idapp };
return await Graduatoria.find(myfind).lean();
};
GraduatoriaSchema.statics.isWorking = function (idapp) {
return Settings.getValDbSettings(idapp, 'GRAD_WORK', false);
};
GraduatoriaSchema.statics.isUpdating = function (idapp) {
return Settings.getValDbSettings(idapp, tools.UPDATE_GRADUATORIA, false);
};
GraduatoriaSchema.statics.setWorking = function (idapp, stato) {
return Settings.setBool(idapp, 'GRAD_WORK', stato);
};
GraduatoriaSchema.statics.setGradUpdating = function (idapp, stato) {
return Settings.setBool(idapp, tools.UPDATE_GRADUATORIA, stato);
};
function getinvit(index, myrec) {
let inv = myrec.numinvitati;
let invattivi = myrec.numinvitatiattivi;
const step = (myrec.numNaviEntrato + index) * 2;
inv -= step;
// console.log('inv', inv, 'step = ', step)
invattivi -= step;
if (inv < 0)
inv = 0;
if (invattivi < 0)
invattivi = 0;
if (inv > 2)
inv = 2;
if (invattivi > 2)
invattivi = 2;
return { invattivi, inv }
}
/*
function getnuminv(index, myrec) {
const ris = getinvit(index, myrec);
return ris.inv
}
function getnuminvattivi(index, myrec) {
const ris = getinvit(index, myrec);
return ris.invattivi
}*/
GraduatoriaSchema.statics.getPosizioneInGraduatoria = async function (idapp, ind_order, username, num_tess) {
const Graduatoria = this;
const totposiz = await Graduatoria.countDocuments({ idapp });
return await Graduatoria.findOne({ idapp, username, ind_order, num_tess }).then((rec) => {
if (!!rec) {
} else {
return {
posiz: 0,
totposiz: 0,
num_tess: 0,
numinvitatiTot: 0,
numinvitatiattiviTot: 0,
numNaviEntrato: 0,
indimbarco: 1,
}
}
const ris = {
totposiz,
posiz: rec.index,
numinvitatiTot: rec.numinvitatiTot,
numinvitatiattiviTot: rec.numinvitatiattiviTot,
num_tess: rec.num_tess,
numNaviEntrato: rec.numNaviEntrato,
indimbarco: rec.indimbarco,
};
return ris;
});
};
const Graduatoria = mongoose.model('Graduatoria', GraduatoriaSchema);
Graduatoria.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Graduatoria };

View File

@@ -1,53 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const GroupSchema = new Schema({
idapp: {
type: String,
},
descr: {
type: String,
},
resp: {
type: String,
},
viceResp: {
type: String,
},
assignedToUsers: [
{ type: String }
],
});
var Group = module.exports = mongoose.model('Group', GroupSchema);
module.exports.getFieldsForSearch = function () {
return [{field: 'descr', type: tools.FieldType.string}]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Group.find(myfind).lean();
};
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

View File

@@ -1,232 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const { ObjectId } = require('mongodb');
const HoursSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String
},
descr: {
type: String,
},
todoId: {
type: String,
},
date: {
type: Date,
default: Date.now
},
time_start: {
type: Number,
},
time_end: {
type: Number,
},
hours: {
type: Number,
},
});
var Hours = module.exports = mongoose.model('Hours', HoursSchema);
module.exports.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Hours.find(myfind);
};
module.exports.correggiHours = async function (idapp) {
const myfind = { idapp };
const myarr = await Hours.find(myfind);
for (const rec of myarr) {
rec.userId = rec.userId.toString();
let ris = await Hours.findOneAndUpdate({ _id: rec._id }, { $set: { userId: rec.userId } }, { new: false } );
if (!!ris) {
console.log('ris', ris);
}
}
};
module.exports.getHoursByIdCat = async function (idapp, userId, idCat, date_start, date_end) {
const myfind = [
{
$match: {
idapp,
userId,
date: { $gte: new Date(date_start), $lte: new Date(date_end) },
todoId: idCat
}
},
{
$group:
{
_id: "$todoId",
totalAmount: {
$sum: "$hours"
},
count: {
$sum: 1
}
}
}
];
try {
const ris = await Hours.aggregate(myfind);
if (ris.length > 0) {
return ris[0].totalAmount;
} else {
return 0;
}
} catch (e) {
console.log('e', e);
return 0;
}
};
module.exports.getTotalHoursByDate = async function (idapp, userId, date) {
const dateini = date;
const datefin = tools.AddDate(date, 1);
const myfind = [
{
$match: {
idapp,
userId,
hours: { $gt: 0 },
date:
{
$gte: dateini,
$lt: datefin,
}
},
},
{
$group:
{
_id: { $dateToString: { format: "%Y-%m-%d", date: "$date", timezone: 'Europe/Rome' } },
totalAmount: {
$sum: "$hours"
},
count: {
$sum: 1
}
}
}
]
;
try {
const ris = await Hours.aggregate(myfind);
if (ris.length > 0) {
// console.log('[',dateini, '-', datefin, '] TOT', ris[0].totalAmount)
return ris[0].totalAmount;
} else {
return 0;
}
} catch (e) {
console.log('e', e);
return 0;
}
}
;
module.exports.getHoursByDate = async function (idapp, userId, date) {
// console.log(mystr);
const myfind =
{
idapp,
userId,
hours: { $gt: 0 },
date: {
$gte: date,
$lt: tools.AddDate(date, 1)
}
};
try {
return await Hours.find(myfind);
} catch (e) {
console.log('e', e);
return 0;
}
};
module.exports.calculateHoursTodo = async function (idtodo) {
const Hours = this;
if (idtodo) {
const myfind = [
{
$match: { todoId: idtodo }
},
{
$group:
{
_id: "$todoId",
totalAmount: {
$sum: "$hours"
},
count: {
$sum: 1
}
}
}
];
try {
const ris = await Hours.aggregate(myfind);
if (ris.length > 0) {
return ris[0].totalAmount;
} else {
return 0;
}
} catch (e) {
console.log('e', e);
return 0;
}
} else {
return 0;
}
};
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

View File

@@ -1,66 +0,0 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// A1P
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const ImportaDescrSchema = new Schema({
idapp: {
type: String,
},
_id: {
type: String,
},
});
var ImportaDescr = module.exports = mongoose.model('ImportaDescr', ImportaDescrSchema);
ImportaDescrSchema.index({ idapp: 1 });
module.exports.getFieldsForSearch = function () {
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string },
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.getImportaDescrByCode = function (idapp, code) {
return ImportaDescr.findAllIdApp(idapp, code);
}
module.exports.getImportaDescrById = async function (id) {
const arrris = await ImportaDescr.findAllIdApp('', '', id);
return arrris && arrris.length > 0 ? arrris[0] : null
}
module.exports.findAllIdApp = async function (idapp) {
const ImportaDescr = this;
const myfind = { idapp, deleted: false };
try {
return await ImportaDescr.find(myfind).lean();
} catch (err) {
console.error("Errore in ImportaDescr:", err);
return null;
}
};

View File

@@ -1,66 +0,0 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// A1P
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const ImportaIsbnSchema = new Schema({
idapp: {
type: String,
},
_id: {
type: String,
},
});
var ImportaIsbn = module.exports = mongoose.model('ImportaIsbn', ImportaIsbnSchema);
ImportaIsbnSchema.index({ idapp: 1 });
module.exports.getFieldsForSearch = function () {
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string },
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.getImportaIsbnByCode = function (idapp, code) {
return ImportaIsbn.findAllIdApp(idapp, code);
}
module.exports.getImportaIsbnById = async function (id) {
const arrris = await ImportaIsbn.findAllIdApp('', '', id);
return arrris && arrris.length > 0 ? arrris[0] : null
}
module.exports.findAllIdApp = async function (idapp) {
const ImportaIsbn = this;
const myfind = { idapp, deleted: false };
try {
return await ImportaIsbn.find(myfind).lean();
} catch (err) {
console.error("Errore in ImportaIsbn:", err);
return null;
}
};

View File

@@ -1,68 +0,0 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// A1P
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const ImportaMacroSchema = new Schema({
idapp: {
type: String,
},
_id: {
type: String,
},
});
var ImportaMacro = module.exports = mongoose.model('ImportaMacro', ImportaMacroSchema);
ImportaMacroSchema.index({ idapp: 1 });
module.exports.getFieldsForSearch = function () {
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string },
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.getImportaMacroByCode = function (idapp, code) {
return ImportaMacro.findAllIdApp(idapp, code);
}
module.exports.getImportaMacroById = async function (id) {
const arrris = await ImportaMacro.findAllIdApp('', '', id);
return arrris && arrris.length > 0 ? arrris[0] : null
}
module.exports.findAllIdApp = async function (idapp) {
const ImportaMacro = this;
const myfind = { idapp, deleted: false };
try {
return await ImportaMacro.find(myfind).lean();
} catch (err) {
console.error("Errore in ImportaMacro:", err);
return null;
}
};

View File

@@ -1,58 +0,0 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// A1P
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const inventariogmSchema = new Schema({
idapp: {
type: String,
},
});
var Inventariogm = module.exports = mongoose.model('Inventariogm', inventariogmSchema);
inventariogmSchema.index({ idapp: 1 });
module.exports.getFieldsForSearch = function () {
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string },
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.getInventariogmByCode = function (idapp, code) {
return Inventariogm.findAllIdApp(idapp, code);
}
module.exports.getInventariogmById = async function (id) {
const arrris = await Inventariogm.findAllIdApp('', '', id);
return arrris && arrris.length > 0 ? arrris[0] : null
}
module.exports.findAllIdApp = async function (idapp) {
const Inventariogm = this;
const myfind = { idapp, deleted: false };
return await tools.findAllQueryIdApp(Inventariogm, myfind);
};

View File

@@ -1,201 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = 'F';
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const IscrittiArcadeiSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String,
},
numTesseraInterna: {
type: Number,
default: 0,
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
email: {
type: String,
trim: true,
},
email2: {
type: String,
trim: true,
},
residency_address: {
type: String,
},
residency_city: {
type: String,
trim: true,
},
residency_province: {
type: String,
trim: true,
},
residency_country: {
type: String,
trim: true,
},
residency_zipcode: {
type: String,
trim: true,
},
dateofbirth: {
type: Date,
},
born_city: {
type: String,
trim: true,
},
born_province: {
type: String,
trim: true,
},
born_country: {
type: String,
trim: true,
},
cell_phone: {
type: String,
},
cell_phone2: {
type: String,
},
newsletter_on: {
type: Boolean,
},
terms: {
type: Boolean,
},
metodo_pagamento: {
type: Number,
},
doctype: {
type: String,
},
documentnumber: {
type: String,
},
ha_pagato: {
type: Boolean,
},
iscrizione_compilata: {
type: Boolean,
},
dateofreg: {
type: Date,
},
dateofapproved: {
type: Date,
},
codiceArcadei: {
type: String,
},
annoTesseramento: {
type: Number,
},
motivazioni: {
type: String,
},
categorie_interesse: [
{
type: Number,
}],
altre_comunicazioni: {
type: String,
},
come_ci_hai_conosciuto: {
type: String,
},
note: {
type: String,
},
quota_versata: {
type: Number,
},
});
IscrittiArcadeiSchema.pre('save', async function(next) {
if (this.isNew) {
const myrec = await IscrittiArcadei.findOne().limit(1).sort({numTesseraInterna: -1});
if (!!myrec) {
this.numTesseraInterna = myrec._doc.numTesseraInterna + 1;
} else {
this.numTesseraInterna = 0;
}
}
next();
});
var IscrittiArcadei = module.exports = mongoose.model('IscrittiArcadei', IscrittiArcadeiSchema);
module.exports.getFieldsForSearch = function() {
return [
{field: 'name', type: tools.FieldType.string},
{field: 'surname', type: tools.FieldType.string},
{field: 'email', type: tools.FieldType.string}];
};
module.exports.executeQueryTable = function(idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.getLastRec = async function(idapp) {
const lastrec = await IscrittiArcadei.find({idapp}).sort({dateofreg: -1}).limit(1);
if (!!lastrec) {
return lastrec[0];
} else {
return null;
}
};
module.exports.getNameSurnameByEmail = async function(idapp, email) {
return await IscrittiArcadei.findOne({
idapp, email,
}, {name: 1, surname: 1}).then((rec) => {
return (!!rec) ? `${rec.name} ${rec.surname}` : '';
}).catch((e) => {
console.error('getNameSurnameByUsername', e);
});
};
module.exports.findByEmail = function(idapp, email) {
return IscrittiArcadei.findOne({
'idapp': idapp,
'email': email,
$or: [{deleted: {$exists: false}}, {deleted: {$exists: true, $eq: false}}],
});
};
module.exports.findAllIdApp = async function(idapp) {
const myfind = {idapp};
return await tools.findAllQueryIdApp(this, myfind);
};
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

View File

@@ -1,200 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const IscrittiConacreisSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String,
},
numTesseraInterna: {
type: Number,
default: 0,
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
email: {
type: String,
trim: true,
},
fiscalcode: {
type: String,
trim: true,
},
residency_address: {
type: String,
},
residency_city: {
type: String,
trim: true,
},
residency_province: {
type: String,
trim: true,
},
residency_country: {
type: String,
trim: true,
},
residency_zipcode: {
type: String,
trim: true,
},
dateofbirth: {
type: Date,
},
born_city: {
type: String,
trim: true,
},
born_province: {
type: String,
trim: true,
},
born_country: {
type: String,
trim: true,
},
cell_phone: {
type: String,
},
newsletter_on: {
type: Boolean,
},
terms: {
type: Boolean,
},
metodo_pagamento: {
type: Number,
},
ha_pagato: {
type: Boolean,
},
iscrizione_compilata: {
type: Boolean,
},
dateofreg: {
type: Date,
},
dateofapproved: {
type: Date,
},
codiceConacreis: {
type: String,
},
annoTesseramento: {
type: Number
},
motivazioni: {
type: String,
},
competenze_professionalita: {
type: String,
},
cosa_potrei_offrire: {
type: String,
},
cosa_vorrei_ricevere: {
type: String,
},
altre_comunicazioni: {
type: String,
},
come_ci_hai_conosciuto: {
type: String,
},
note: {
type: String,
},
});
IscrittiConacreisSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await IscrittiConacreis.findOne().limit(1).sort({ numTesseraInterna: -1 });
if (!!myrec) {
this.numTesseraInterna = myrec._doc.numTesseraInterna + 1;
} else {
this.numTesseraInterna = 0;
}
}
next();
});
var IscrittiConacreis = module.exports = mongoose.model('IscrittiConacreis', IscrittiConacreisSchema);
module.exports.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string },
{ field: 'surname', type: tools.FieldType.string },
{ field: 'email', type: tools.FieldType.string }]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.getLastRec = async function (idapp) {
const lastrec = await IscrittiConacreis.find({ idapp }).sort({ dateofreg: -1 }).limit(1);
if (!!lastrec) {
return lastrec[0];
} else {
return null;
}
};
module.exports.getNameSurnameByEmail = async function (idapp, email) {
return await IscrittiConacreis.findOne({
idapp, email,
}, { name: 1, surname: 1 })
.then((rec) => {
return (!!rec) ? `${rec.name} ${rec.surname}` : '';
}).catch((e) => {
console.error('getNameSurnameByUsername', e);
});
};
module.exports.findByEmail = function (idapp, email) {
return IscrittiConacreis.findOne({
'idapp': idapp,
'email': email,
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
});
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await tools.findAllQueryIdApp(this, myfind);
};
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

View File

@@ -1,79 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const tools = require('../tools/general');
const {ObjectId} = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const LevelSchema = new Schema({
_id: {
type: Number,
},
descr: {
type: String,
},
years_of_exp: {
type: Number,
},
color: {
type: String,
},
theme: {
type: String,
},
});
LevelSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await Level.findOne().limit(1).sort({_id:-1});
if (!!myrec) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id + 1;
} else {
this._id = 1;
}
}
next();
});
LevelSchema.statics.findAllIdApp = async function(idapp) {
const Level = this;
const query = [
{$sort: {_id: 1}},
];
return Level.aggregate(query);
};
LevelSchema.statics.getFieldsForSearch = function() {
return [
{field: 'descr', type: tools.FieldType.string}];
};
LevelSchema.statics.executeQueryTable = function(idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const Level = mongoose.model('Level', LevelSchema);
Level.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = {Level};

View File

@@ -1,127 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { User } = require('./user');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const MailingListSchema = new Schema({
});
MailingListSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = User.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
MailingListSchema.statics.findAllIdAppSubscribed = function (idapp) {
const myfind = {
idapp,
news_on: true,
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
$or: [
{ email_errata: { $exists: false } },
{ email_errata: { $exists: true, $ne: true } }],
};
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return tools.findAllQueryIdApp(User, myfind);
};
MailingListSchema.statics.findAllIdAppDiarioSubscr = function (idapp) {
const myfind = {
idapp,
diario_on: true,
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
$or: [
{ email_errata: { $exists: false } },
{ email_errata: { $exists: true, $ne: true } }],
};
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return tools.findAllQueryIdApp(User, myfind);
};
MailingListSchema.statics.findAllIdAppDiarioSubscr = function (idapp) {
const myfind = {
idapp,
test: true,
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
$or: [
{ email_errata: { $exists: false } },
{ email_errata: { $exists: true, $ne: true } }],
};
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return tools.findAllQueryIdApp(User, myfind);
};
MailingListSchema.statics.getnumSent = async function (idapp, idUser) {
const myfind = { idapp, news_on: true, lastid_newstosent: idUser };
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return await User.countDocuments(myfind);
};
MailingListSchema.statics.isOk = async function (idapp, iduser, idUser) {
const myfind = { idapp, _id: iduser, news_on: true, lastid_newstosent: { $ne: idUser } };
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return await User.countDocuments(myfind) > 0;
};
MailingListSchema.statics.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await tools.findAllQueryIdApp(User, myfind);
};
MailingListSchema.statics.isUnsubscribed = async function (idapp, hash) {
let myperson = await User.findOne({ idapp, hash });
if (!!myperson) {
return (!myperson.news_on)
}
};
MailingListSchema.statics.findByHash = function (idapp, hash) {
const myfind = { idapp, hash };
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return User.findOne(myfind).lean();
};
const MailingList = mongoose.model('MailingList', MailingListSchema);
User.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { MailingList };

File diff suppressed because it is too large Load Diff

View File

@@ -1,132 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const MsgTemplateSchema = new Schema({
idapp: {
type: String,
},
typemsg: {
type: Number,
},
title: {
type: String,
},
title_it: {
type: String,
},
msg_it: {
type: String,
},
title_enUs: {
type: String,
},
msg_enUs: {
type: String,
},
title_si: {
type: String,
},
msg_si: {
type: String,
},
title_fr: {
type: String,
},
msg_fr: {
type: String,
},
title_es: {
type: String,
},
msg_es: {
type: String,
},
title_pt: {
type: String,
},
msg_pt: {
type: String,
},
});
MsgTemplateSchema.statics.getFieldsForSearch = function () {
return [{ field: 'title', type: tools.FieldType.string },
]
};
MsgTemplateSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
MsgTemplateSchema.statics.getMsgByLang = async function (idapp, myuser, typemsg, lang) {
const MsgTemplate = this;
try {
const mymsg = await MsgTemplate.findOne({ idapp, typemsg });
if (!!mymsg) {
if ((!!mymsg["msg_" + lang]) && (!!mymsg["title_" + lang])) {
let body = mymsg["msg_" + lang]
let title = mymsg["title_" + lang]
if (!body) {
body = mymsg["msg_it"]
title = mymsg["title_it"]
}
body = await tools.convertSpecialTags(myuser, body);
title = await tools.convertSpecialTags(myuser, title);
return { body, title }
}
}
} catch (e) {
return { body: '', title: '' };
}
return { body: '', title: '' };
};
MsgTemplateSchema.statics.getMsgByTitleAndLang = async function (idapp, title, lang) {
const MsgTemplate = this;
try {
const mymsg = await MsgTemplate.findOne({ idapp, title });
if (!!mymsg) {
if ((!!mymsg["msg_" + lang]) && (!!mymsg["title_" + lang])) {
return { body: mymsg["msg_" + lang], title: mymsg["title_" + lang] }
}
}
} catch (e) {
return { body: '', title: '' };
}
return { body: '', title: '' };
};
MsgTemplateSchema.statics.findAllIdApp = async function (idapp) {
const MsgTemplate = this;
const myfind = { idapp };
return await tools.findAllQueryIdApp(this, myfind);
};
const MsgTemplate = mongoose.model('MsgTemplate', MsgTemplateSchema);
MsgTemplate.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { MsgTemplate };

View File

@@ -1,373 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
const shared_consts = require('../tools/shared_nodejs');
const { Reaction } = require('./reaction');
const { MyGroup } = require('./mygroup');
const tableModel = shared_consts.TABLES_MYBACHECAS;
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const MyBachecaSchema = new Schema({
...{
_id: {
type: String,
default: function () {
return new ObjectId().toString();
},
},
idapp: {
type: String,
required: true,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
groupname: { type: String },
idSector: {
type: Number,
},
idSkill: {
type: Number,
default: 0,
},
idStatusSkill: [
{
type: Number,
},
],
idContribType: [
{
type: String,
},
],
idCity: [
{
type: Number,
},
],
dateTimeStart: {
type: Date,
},
dateTimeEnd: {
type: Date,
required: false, // non obbligatorio
default: null, // valore predefinito esplicito (opzionale)
},
organisedBy: {
type: String,
},
contact_phone: {
type: String,
},
contact_email: {
type: String,
},
contact_telegram: {
type: String,
},
address: {
type: String,
},
min_partecip: {
type: Number,
},
max_partecip: {
type: Number,
},
link_maplocation: {
type: String,
},
contribstr: {
type: String,
},
numLevel: {
type: Number,
default: 0,
},
adType: {
type: Number,
},
photos: [
{
imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
},
],
note: {
type: String,
default: '',
},
descr: {
type: String,
},
//**ADDFIELD_MYBACHECAS
website: {
type: String,
},
date_created: {
type: Date,
},
date_updated: {
type: Date,
},
link_conference: {
type: String,
},
},
...Reaction.getFieldsForReactions(),
...tools.getFieldsForAnnunci(),
});
MyBachecaSchema.pre('save', async function (next) {
if (this.isNew) {
if (!this.date_created) this.date_created = new Date();
}
next();
});
MyBachecaSchema.statics.findAllIdApp = async function (idapp) {
const MyBacheca = this;
const query = [{ $match: { idapp } }, { $sort: { descr: 1 } }];
return await MyBacheca.aggregate(query);
};
MyBachecaSchema.statics.getFieldsForSearch = function () {
return [];
};
MyBachecaSchema.statics.getFieldsLastForSearch = function () {
return [
{ field: 'note', type: tools.FieldType.string },
{ field: 'descr', type: tools.FieldType.string },
{ field: 'recSkill.descr', type: tools.FieldType.string },
{ field: 'MyBacheca.descr', type: tools.FieldType.string },
];
};
MyBachecaSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
params.fieldsearch_last = this.getFieldsLastForSearch();
const otherparams = {
lookup1: {
lk_tab: 'users',
lk_LF: 'userId',
lk_FF: '_id',
lk_as: 'user',
af_objId_tab: 'myId',
lk_proj: shared_consts.getProjectForAll({}, tableModel),
},
};
params = { ...params, ...otherparams };
return tools.executeQueryTable(this, idapp, params, user);
};
MyBachecaSchema.statics.getMyRecById = function (idapp, id) {
const MyBacheca = this;
let myparsid = {
_id: id,
idapp,
};
let query = [
{
$match: myparsid,
},
{
$sort: {
desc: 1,
},
},
{
$addFields: {
myId1: {
$toObjectId: '$userId',
},
},
},
{
$lookup: {
from: 'users',
localField: 'myId1',
foreignField: '_id',
as: 'user',
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: ['$user', 0],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
$lookup: {
from: 'skills',
localField: 'idSkill',
foreignField: '_id',
as: 'recSkill',
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: ['$recSkill', 0],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
$lookup: {
from: 'sectors',
localField: 'idSector',
foreignField: '_id',
as: 'sector',
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: ['$sector', 0],
},
'$$ROOT',
],
},
},
},
{
$lookup: {
from: 'mygroups',
localField: 'groupname',
foreignField: 'groupname',
as: 'mygrp',
},
},
{
$unwind: {
path: '$mygrp',
preserveNullAndEmptyArrays: true,
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
/*{
'$lookup': {
'from': 'subskills',
'localField': 'idSubSkill',
'foreignField': '_id',
'as': 'MyBacheca',
},
},*/
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: ['$MyBacheca', 0],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
$lookup: {
from: 'cities',
localField: 'idCity',
foreignField: '_id',
as: 'mycities',
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: ['$mycities', 0],
},
'$$ROOT',
],
},
},
},
];
try {
let numtab = tools.getNumTabByTable(shared_consts.TABLES_MYBACHECAS);
let objadd = tools.addNumFavoriteAndBookmarkToQuery(idapp, numtab);
query = [...query, ...objadd.query];
const toadd = {
$project: shared_consts.getProjectForAll(objadd.proj, tableModel),
};
query = [...query, { ...toadd }];
} catch (e) {
console.error('e', e);
}
return MyBacheca.aggregate(query).then((rec) => {
return rec ? rec[0] : null;
});
};
MyBachecaSchema.statics.getCompleteRecord = function (idapp, id) {
const MyBacheca = this;
return MyBacheca.getMyRecById(idapp, id);
};
const MyBacheca = mongoose.model('MyBacheca', MyBachecaSchema);
MyBacheca.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports = { MyBacheca };

View File

@@ -1,616 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
const shared_consts = require('../tools/shared_nodejs');
const { MySchedaSchema, IDimensioni, IImg, IText, IAreaDiStampa } = require('../models/myscheda');
mongoose.Promise = global.Promise;
mongoose.level = 'F';
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const IElementiPagina = new Schema({
isTemplate: Boolean,
linkIdTemplate: String,
name: String,
pagina: IDimensioni,
});
const myCard = new Schema({
imagefile: String,
vers_img: Number,
alt: String,
description: String,
style: String,
size: String,
color: String,
content: String,
colorsub: String,
link: String,
});
const animation = new Schema({
name: String,
clduration: String,
cldelay: String,
timingtype: String,
});
const elemText = new Schema({
text: String,
color: String,
class: String,
size: String,
anim: animation,
});
const catalogo = new Schema({
//++AddCATALOGO_FIELDS
idCatalogSel: { type: String },
productTypes: [{ type: Number }],
excludeproductTypes: [{ type: Number }],
editore: [{ type: String }],
argomenti: [{ type: String }],
idCollane: [{ type: String }],
idTipologia: [{ type: Number }],
idTipoFormato: [{ type: Number }],
sort_field: { type: String },
sort_dir: { type: Number },
pdf: { type: Boolean },
pdf_filename: { type: String },
printable: { type: Boolean },
indebug: { type: Boolean },
maxnumlibri: { type: Number },
showListaArgomenti: { type: Boolean },
showOnlyCatalogoPDF: { type: Boolean },
showListaCollane: { type: Boolean },
first_page: IDimensioni,
last_page: IDimensioni,
areadistampa: IAreaDiStampa,
print_isTemplate: Boolean,
print_linkIdTemplate: String,
dimensioni_def: IElementiPagina,
// -------------------
arrSchede: [
{
scheda: MySchedaSchema,
order: { type: Number },
numPagineMax: { type: Number },
/*arrProdToShow: {
type: [[mongoose.Schema.Types.Mixed]], // Definizione tipo
select: false // Imposta il campo come non selezionabile
},*/
},
],
});
const MySingleElemSchema = {
idapp: {
type: String,
},
path: {
type: String,
},
/*oldpath: {
type: String,
},*/
idElemParent: {
type: String,
},
idPage: { type: String },
type: {
type: Number,
},
img: {
type: String,
},
container: {
type: String,
},
container2: {
type: String,
},
container3: {
type: String,
},
container4: {
type: String,
},
align: {
type: Number,
},
vertalign: {
type: Number,
},
speed: {
type: Number,
},
parambool: {
type: Boolean,
},
span: {
type: Boolean,
},
parambool2: {
type: Boolean,
},
parambool3: {
type: Boolean,
},
parambool4: {
type: Boolean,
},
number: {
type: Number,
},
num2: {
type: Number,
},
imgback: {
type: String,
},
ratio: {
type: String,
},
containerHtml: {
type: String,
},
size: {
type: String,
},
order: {
type: Number,
default: 0,
},
height: {
type: Number,
},
heightimg: {
type: String,
},
heightcarousel: {
type: String,
},
widthimg: {
type: String,
},
width: {
type: Number,
},
heightcard: {
type: String,
},
widthcard: {
type: String,
},
link: {
type: String,
},
fit: {
type: String,
},
onlyif_logged: {
type: Boolean,
},
color: {
type: String,
},
elemsText: [elemText],
anim: animation,
features: [
{
name: {
type: String,
},
icon: {
type: String,
},
description: {
type: String,
},
},
],
active: {
type: Boolean,
default: false,
},
class: {
type: String,
},
class2: {
type: String,
},
class3: {
type: String,
},
class4: {
type: String,
},
styleadd: {
type: String,
},
image: {
type: String,
},
vers_img: {
type: Number,
},
titleBanner: String,
classBanner: String,
listcards: [myCard],
catalogo: catalogo,
list: [
{
imagefile: {
type: String,
},
vers_img: {
type: Number,
},
order: {
type: Number,
},
alt: {
type: String,
},
description: {
type: String,
},
},
],
date_created: {
type: Date,
default: Date.now,
},
date_updated: {
type: Date,
},
};
const MyElemSchema = new Schema({
...MySingleElemSchema,
// Aggiungi rows e columns
rows: {
type: [
{
...MySingleElemSchema,
columns: {
type: [
{
...MySingleElemSchema,
elems: [MySingleElemSchema],
},
],
},
},
],
},
});
MyElemSchema.pre('save', async function (next) {
if (this.isNew) {
this._id = new ObjectId();
}
next();
});
MyElemSchema.statics.getFieldsForSearch = function () {
return [
{ field: 'title', type: tools.FieldType.string },
{ field: 'content', type: tools.FieldType.string },
];
};
MyElemSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params, user);
};
MyElemSchema.statics.SetIdPageInsteadThePah = async function (idapp) {
const MyElem = this;
const { MyPage } = require('../models/mypage');
// Sostituisci path con IdPage
try {
// Recupera tutti i documenti di MyPage
const pages = await MyPage.find({ idapp }); // Puoi anche specificare condizioni, se necessario
// Utilizza una mappa per accoppiare i path con i loro Id
const pathToIdMap = {};
pages.forEach((page) => {
pathToIdMap[page.path] = page._id; // Mappa il path all'ID del documento MyPage
});
// Aggiorna MyElem utilizzando la mappa
for (const [path, id] of Object.entries(pathToIdMap)) {
if (path) {
await MyElem.updateMany(
{ idapp },
{ path: path }, // Condizione per aggiornare dove il path corrisponde
{
$set: {
idPage: id,
oldpath: path,
},
$unset: { path: '' }, // Rimuove il campo path
} // Imposta IdPage all'ID del documento corrispondente
);
}
}
if (false) {
// Utilizza una mappa per accoppiare i path con i loro Id
const pathToIdMap2 = {};
pages.forEach((page) => {
pathToIdMap2[page.path] = page._id.toString(); // Mappa il path all'ID del documento MyPage
});
// Aggiorna MyElem utilizzando la mappa
for (const [path, id] of Object.entries(pathToIdMap2)) {
await MyElem.updateMany(
{ oldpath: path }, // Condizione per aggiornare dove il path corrisponde
{
$unset: { idPage: '' }, // Rimuove il campo path
} // Imposta IdPage all'ID del documento corrispondente
);
}
for (const [oldpath, id] of Object.entries(pathToIdMap2)) {
await MyElem.updateMany(
{ oldpath: oldpath }, // Condizione per aggiornare dove il path corrisponde
{
$set: { idPage: id },
} // Imposta IdPage all'ID del documento corrispondente
);
}
}
const pathToIdMap2 = {};
pages.forEach((page) => {
pathToIdMap2[page.path] = page._id.toString(); // Mappa il path all'ID del documento MyPage
});
for (const [oldpath, id] of Object.entries(pathToIdMap2)) {
await MyElem.updateMany(
{ idapp },
{ oldpath: oldpath }, // Condizione per aggiornare dove il path corrisponde
{
$set: { idPage: id },
} // Imposta IdPage all'ID del documento corrispondente
);
}
console.log('Aggiornamenti effettuati con successo.');
return 'Aggiornamenti effettuati con successo.';
} catch (error) {
console.error("Errore durante l'aggiornamento:", error);
return "Errore durante l'aggiornamento:", error;
}
};
MyElemSchema.statics.deleteAllFromThisPage = async function (id) {
const MyElem = this;
return MyElem.deleteMany({ idPage: id });
};
MyElemSchema.statics.findAllIdApp = async function (idapp) {
const MyElem = this;
const myfind = { idapp };
const aggiorna = false;
let arrrec = null;
if (aggiorna) {
arrrec = await MyElem.find(myfind).sort({ order: 1 });
for (const elem of arrrec) {
if (elem.heightimg === 'NaNpx') {
elem.heightimg = '';
await elem.save();
}
}
} else {
arrrec = await MyElem.find(myfind).lean().sort({ order: 1 });
}
return arrrec;
};
async function deleteOldMyElems(idapp) {
try {
const { MyPage } = require('../models/mypage');
// 1. Recupera tutti gli _id dalle pagine
const existingPages = await MyPage.find({ idapp }).select('_id').lean();
const existingPageIds = existingPages.map((page) => page._id.toString());
// 2. Trova gli MyElem che hanno idPage non esistenti in MyPage
const elemsToDelete = await MyElem.find({
idapp,
idPage: { $nin: existingPageIds },
});
if (elemsToDelete.length > 0) {
// 3. Esegui la cancellazione
const result = await MyElem.deleteMany({ idPage: { $nin: existingPageIds } });
console.log(`Cancellati ${result.deletedCount} documenti di MyElem.`);
} else {
console.log('Nessun documento da cancellare.');
}
} catch (error) {
console.error('Errore durante la cancellazione dei documenti:', error);
}
}
/**
* Trova tutte le schede template associate a pagine di idapp.
* Restituisce un array di ogge tti con le seguenti proprietà:
* - scheda: l'oggetto scheda, con proprietà come _id, name, isTemplate
* - idPageOrig: l'idPage originale associata alla scheda
*
* Se idapp === '18', stampa i duplicati e i titoli delle pagine
* e cancella i documenti di MyElem con idPage non esistenti in MyPage
*
* @param {string} idapp ID dell'applicazione
* @returns {Promise<IMyElemTemplate[]>} Array di oggetti scheda con idPageOrig
*/
MyElemSchema.statics.findallSchedeTemplate = async function (idapp) {
const MyElem = this;
try {
const { MyPage } = require('../models/mypage');
const ris = await MyElem.find({ idapp }).lean();
const schedeTemplate = ris.flatMap((elem) =>
elem.catalogo && elem.catalogo.arrSchede
? elem.catalogo.arrSchede
.filter((scheda) => scheda.scheda?.isTemplate)
.map((scheda) => ({
...scheda, // mantieni i dati originali della scheda
idPageOrig: elem.idPage, // aggiungi l'idPage
}))
: []
);
if (idapp === '18') {
const duplicateIds = schedeTemplate.reduce((acc, scheda) => {
const id = scheda.scheda._id; // Ottieni l'ID della scheda
if (!acc[id]) {
acc[id] = []; // Inizializza un array per tenere traccia delle pagine
}
acc[id].push(scheda.idPageOrig); // Aggiungi l'idPage all'array
return acc;
}, {});
// Filtra i duplicati
const duplicates = Object.entries(duplicateIds)
.filter(([_, pages]) => pages.length > 1) // Mantieni solo gli ID con più di un'istanza
.map(([id, pages]) => ({ id, pages })); // Ottieni ID e pagine corrispondenti
// Recupera i dettagli delle pagine
const pageIds = duplicates.flatMap((dup) => dup.pages); // Estrai tutti gli idPage
const pages = await MyPage.find({ idapp, _id: { $in: pageIds } }).lean();
// Crea una mappatura tra idPage e title
const pageMap = pages.reduce((acc, page) => {
acc[page._id] = page.title; // Mappa idPage a title
return acc;
}, {});
// Associa i titoli delle pagine agli ID duplicati
const resultWithTitles = duplicates.map((dup) => ({
id: dup.id,
pages: dup.pages.map((_id) => ({
_id,
title: pageMap[_id] || 'Titolo non trovato', // Usa la mappatura per trovare il titolo
})),
}));
if (resultWithTitles.length > 0) {
console.log('Duplicati e titoli delle pagine:', JSON.stringify(resultWithTitles, null, 2));
// await deleteOldMyElems(idapp);
}
}
return schedeTemplate;
} catch (e) {
console.error('Err', e);
}
};
/**
* Ricerca tra tutte le schede, contenute in catalogo, se esiste un nome di template uguale,
* se non lo trova allora è quello giusto per crearne uno nuovo
*
* @param {string} idapp - ID dell'app
* @param {string} idPageOrig - ID della pagina originale
* @param {string} nomeTemplate - Nome del template
*
* @returns {string} Il nome del template libero
*/
MyElemSchema.statics.getNewFreeNameTemplate = async function (idapp, idPageOrig, nomeTemplate) {
const MyElem = this;
try {
// Trova tutti gli elementi che hanno un template con lo stesso nome
const ris = await MyElem.find(
{
idapp,
'catalogo.arrSchede.scheda.isTemplate': true,
'catalogo.arrSchede.scheda.idPage': { $ne: idPageOrig },
},
{
'catalogo.arrSchede.scheda.name': 1,
'catalogo.arrSchede.scheda.isTemplate': 1,
'catalogo.arrSchede.scheda.isPagIntro': 1,
'catalogo.arrSchede.scheda.idPage': 1,
}
);
// Recupera i nomi dei template già esistenti
const existingNames = new Set(
ris.flatMap(
(elem) =>
elem.catalogo?.arrSchede
?.filter((scheda) => scheda.scheda?.isTemplate && scheda.scheda?.idPage !== idPageOrig)
.map((scheda) => scheda.scheda?.name) || []
)
);
// Crea un nuovo nome di template univoco
let ind = 2;
let newNameTemplate;
do {
newNameTemplate = `${nomeTemplate}_copia_${ind}`;
ind++;
} while (existingNames.has(newNameTemplate) && ind <= 1000);
return newNameTemplate;
} catch (e) {
console.error('Err', e);
throw e; // Propagate the error
}
};
MyElemSchema.statics.findParentElem = async function (idapp, idElemParent) {
try {
let myelemParent = null;
myelemParent = await this.findOne({
idapp,
rows: {
$elemMatch: { columns: { $elemMatch: { _id: idElemParent } } },
},
}).lean();
return myelemParent;
} catch (e) {
console.error('Err', e);
throw e; // Propagate the error
}
};
const MyElem = mongoose.model('MyElem', MyElemSchema);
MyElem.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports = { MyElem };

View File

@@ -1,286 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const tools = require('../tools/general');
const {ObjectId} = require('mongodb');
const {Settings} = require('./settings');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const MyEventSchema = new Schema({
idapp: {
type: String,
},
typol: {
type: String,
},
short_tit: {
type: String,
},
title: {
type: String,
},
details: {
type: String,
},
bodytext: {
type: String,
},
dateTimeStart: {
type: Date,
},
dateTimeEnd: {
type: Date,
required: false, // non obbligatorio
default: null, // valore predefinito esplicito (opzionale)
},
bgcolor: {
type: String,
},
icon: {
type: String,
},
img_small: {
type: String,
},
img: {
type: String,
},
wherecode: {
type: String,
},
contribtype: {
type: String,
},
price: {
type: Number,
},
infoafterprice: {
type: String,
},
teacher: {
type: String,
},
teacher2: {
type: String,
},
teacher3: {
type: String,
},
teacher4: {
type: String,
},
infoextra: {
type: String,
},
linkpage: {
type: String,
},
linkpdf: {
type: String,
},
nobookable: {
type: Boolean,
},
news: {
type: Boolean,
},
canceled: {
type: Boolean,
},
lunchAvailable: {
type: Boolean,
},
dinnerAvailable: {
type: Boolean,
},
dinnerSharedAvailable: {
type: Boolean,
},
lunchType: {
type: Number,
},
dinnerType: {
type: Number,
},
lunchPrice: {
type: Number,
},
dinnerPrice: {
type: Number,
},
internal: {
type: Boolean,
},
note: {
type: String,
},
pagefooter: [
{
type: String,
}],
deleted: {
type: Boolean,
},
dupId: {
type: mongoose.Schema.Types.ObjectId,
},
facebook: {
type: String,
},
modified: {
type: Boolean,
},
});
MyEventSchema.statics.findAllIdApp = async function(socioresidente, idapp) {
const Event = this;
let query = [];
if (socioresidente) {
query = [
{
$match: {
idapp,
$or: [
{deleted: {$exists: false}},
{deleted: {$exists: true, $eq: false}}],
},
},
];
} else {
query = [
{
$match: {
idapp,
$and: [
{
$or: [
{deleted: {$exists: false}},
{deleted: {$exists: true, $eq: false}},
],
},
{
$or: [
{internal: {$exists: false}},
{internal: {$exists: true, $eq: false}}],
},
],
},
},
];
}
query.push({$sort: {dateTimeStart: 1}});
return Event.aggregate(query).then((arrrec) => {
return arrrec;
});
};
MyEventSchema.statics.getLastEvents = async function(idapp) {
const Event = this;
const lastn = await Settings.getValDbSettings(idapp, 'SHOW_LAST_N_EV', 1);
const query = [
{
$match: {
idapp,
dateTimeStart: {$gte: tools.IncDateNow(-1000 * 60 * 60 * 24)},
$or: [
{deleted: {$exists: false}},
{deleted: {$exists: true, $eq: false}}],
},
},
{
$lookup: {
from: 'operators',
localField: 'teacher',
foreignField: 'username',
as: 'op1',
},
},
{
$lookup: {
from: 'operators',
localField: 'teacher2',
foreignField: 'username',
as: 'op2',
},
},
{
$lookup: {
from: 'operators',
localField: 'teacher3',
foreignField: 'username',
as: 'op3',
},
},
{
$lookup: {
from: 'operators',
localField: 'teacher4',
foreignField: 'username',
as: 'op4',
},
},
{'$addFields': {'contribtype': {'$toObjectId': '$contribtype'}}},
{
$lookup: {
from: 'contribtypes',
localField: 'contribtype',
foreignField: '_id',
as: 'contrib',
},
},
{$sort: {dateTimeStart: 1}},
];
return Event.aggregate(query).then((arrrec) => {
// console.table(arrrec);
if (lastn > 0) {
return arrrec.slice(0, lastn);
} else {
return arrrec;
}
});
};
MyEventSchema.statics.getFieldsForSearch = function() {
return [
{field: 'short_tit', type: tools.FieldType.string},
{field: 'title', type: tools.FieldType.string},
{field: 'teacher', type: tools.FieldType.string},
{field: 'details', type: tools.FieldType.string}];
};
MyEventSchema.statics.executeQueryTable = function(idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params, user);
};
if (tools.INITDB_FIRSTIME) {
// console.log(' createIndex MyEvent Index...');
// MyEventSchema.index({ short_tit: 'text', title: 'text', teacher: 'text', details: 'text' });
}
const MyEvent = mongoose.model('MyEvent', MyEventSchema);
MyEvent.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = {MyEvent};

View File

@@ -1,375 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const tools = require('../tools/general');
const { Reaction } = require('./reaction');
const { MyGroup } = require('./mygroup');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
const tableModel = shared_consts.TABLES_MYGOODS;
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const MyGoodSchema = new Schema({
...{
_id: {
type: String,
},
idapp: {
type: String,
required: true,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
groupname: { type: String },
idSectorGood: {
type: Number,
},
idGood: {
type: Number,
default: 0,
},
idShipping: [
{
type: Number,
}],
idContribType: [
{
type: String,
}],
idCity: [
{
type: Number,
}],
pub_to_share: {
type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW
},
numLevel: {
type: Number,
default: 0,
},
adType: {
type: Number,
},
otherfilters: [{
type: Number,
}],
photos: [
{
imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
}],
note: {
type: String,
default: '',
},
descr: {
type: String,
},
//**ADDFIELD_MyGood
website: {
type: String,
},
date_created: {
type: Date,
},
date_updated: {
type: Date,
},
},
...Reaction.getFieldsForReactions(),
...tools.getFieldsForAnnunci()
});
MyGoodSchema.pre('save', async function (next) {
if (this.isNew) {
if (!this.date_created)
this.date_created = new Date();
}
next();
});
MyGoodSchema.statics.findAllIdApp = async function (idapp) {
const MyGood = this;
const query = [
{ $match: { idapp } },
{ $sort: { descr: 1 } },
];
return await MyGood.aggregate(query).then((arrrec) => {
return arrrec;
});
};
MyGoodSchema.statics.getFieldsForSearch = function () {
return [];
};
MyGoodSchema.statics.getFieldsLastForSearch = function () {
return [
{ field: 'note', type: tools.FieldType.string },
{ field: 'descr', type: tools.FieldType.string },
{ field: 'recGood.descr', type: tools.FieldType.string },
{ field: 'MyGood.descr', type: tools.FieldType.string },
];
};
MyGoodSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
params.fieldsearch_last = this.getFieldsLastForSearch();
const otherparams = {
lookup1: {
lk_tab: 'users',
lk_LF: 'userId',
lk_FF: '_id',
lk_as: 'user',
af_objId_tab: 'myId',
lk_proj: shared_consts.getProjectForAll({}, tableModel),
},
};
params = { ...params, ...otherparams };
return tools.executeQueryTable(this, idapp, params, user);
};
MyGoodSchema.statics.getMyRecById = function (idapp, idGood) {
const MyGood = this;
let myparsid = {
'_id': idGood,
idapp,
};
let query = [
{
'$match':
myparsid,
},
{
'$sort': {
'desc': 1,
},
},
{
'$addFields': {
'myId1': {
'$toObjectId': '$userId',
},
},
},
{
'$lookup': {
'from': 'users',
'localField': 'myId1',
'foreignField': '_id',
'as': 'user',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$user',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'goods',
'localField': 'idGood',
'foreignField': '_id',
'as': 'recGood',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$recGood',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'sectorgoods',
'localField': 'idSectorGood',
// 'localField': 'recGood.idSectorGood',
'foreignField': '_id',
'as': 'sectorGood',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$sectorgood',
0,
],
},
'$$ROOT',
],
},
},
},
{
$lookup: {
'from': 'mygroups',
'localField': 'groupname',
'foreignField': 'groupname',
'as': 'mygrp',
},
},
{
$unwind: {
path: '$mygrp',
preserveNullAndEmptyArrays: true,
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'subgoods',
'localField': 'idShipping',
'foreignField': '_id',
'as': 'MyGood',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$MyGood',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'cities',
'localField': 'idCity',
'foreignField': '_id',
'as': 'mycities',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$mycities',
0,
],
},
'$$ROOT',
],
},
},
},
];
let numtab = tools.getNumTabByTable(shared_consts.TABLES_MYGOODS);
const objadd = tools.addNumFavoriteAndBookmarkToQuery(idapp, numtab);
query = [...query, ...objadd.query];
const toadd = {
$project: shared_consts.getProjectForAll(objadd.proj, tableModel),
};
query = [...query, { ...toadd }];
return MyGood.aggregate(query).then((rec) => {
return rec ? rec[0] : null;
});
};
MyGoodSchema.statics.getCompleteRecord = function (idapp, id) {
const MyGood = this;
return MyGood.getMyRecById(idapp, id);
};
MyGoodSchema.statics.getProject = function () {
let proj = {
'recGood': 1,
'sectorGood': 1,
'idSectorGood': 1,
'idGood': 1,
'idShipping': 1,
'idStatusGood': 1,
//**ADDFIELD_MYGOOD
};
const proj_add = shared_consts.getProjectForAll()
return Object.assign({}, proj, proj_add);
}
const MyGood = mongoose.model('MyGood', MyGoodSchema);
MyGood.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { MyGood };

View File

@@ -1,666 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const { ObjectId } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const MyGroupSchema = new Schema({
_id: {
type: String,
default: function () {
return new ObjectId().toString();
},
},
idapp: {
type: String,
},
groupname: {
type: String,
},
title: {
type: String,
},
descr: {
type: String,
},
idCatGrp: [
{
type: Number,
},
],
userId: {
type: String,
},
photos: [
{
imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
},
],
idCity: [
{
type: Number,
},
],
website: {
type: String,
},
link_telegram: {
type: String,
},
note: {
type: String,
default: '',
},
visibility: [
{
type: Number,
},
],
pwd_cryp: {
type: String,
},
createdBy: {
type: String,
},
admins: [
{
username: { type: String },
perm: { type: Number },
date: { type: Date },
},
],
blocked: {
type: Boolean,
},
username_who_block: {
type: String,
},
date_created: {
type: Date,
},
date_updated: {
type: Date,
},
date_blocked: {
type: Date,
},
req_users: [
{
_id: false,
username: { type: String },
date: { type: Date },
},
], // username
refused_users: [
{
_id: false,
username: { type: String },
date: { type: Date },
},
], // username
deleted: {
type: Boolean,
default: false,
},
mycircuits: [
{
_id: false,
circuitname: { type: String },
date: { type: Date },
},
],
lastdate_reqRisGroup: {
type: Date,
},
//**ADDFIELD_MYGROUPS
...tools.getFieldsForAnnunci(),
});
MyGroupSchema.statics.getFieldsForSearch = function () {
return [
{ field: 'descr', type: tools.FieldType.string },
{ field: 'groupname', type: tools.FieldType.string },
{ field: 'title', type: tools.FieldType.string },
];
};
MyGroupSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
const { User } = require('./user');
/*if (params.options) {
if (tools.isBitActive(params.options, shared_consts.OPTIONS_SEARCH_USER_ONLY_FULL_WORDS)) {
params.fieldsearch = User.getFieldsForSearchUserFriend();
} else if (tools.isBitActive(params.options, shared_consts.OPTIONS_SEARCH_USER_ALL_WORDS)) {
params.fieldsearch = User.getFieldsForSearchUserFriend_AllWords();
}
}*/
return tools.executeQueryTable(this, idapp, params, user);
};
MyGroupSchema.pre('save', async function (next) {
if (this.isNew) {
if (!this.date_created) this.date_created = new Date();
}
next();
});
MyGroupSchema.statics.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await MyGroup.find(myfind).lean();
};
MyGroupSchema.statics.findAllGroups = async function (idapp) {
const whatToShow = this.getWhatToShow(idapp, '');
return await MyGroup.find(
{
idapp,
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
},
whatToShow
).lean();
};
// Rimuovo la Richiesta del Gruppo
MyGroupSchema.statics.removeReqGroup = async function (idapp, username, groupnameDest) {
return await MyGroup.updateOne(
{ idapp, groupname: groupnameDest },
{ $pull: { req_users: { username: { $in: [username] } } } }
);
};
// Aggiungi agli utenti Rifiutati del Gruppo
MyGroupSchema.statics.refuseReqGroup = async function (idapp, username, groupnameDest) {
return await MyGroup.updateOne(
{ idapp, groupname: groupnameDest },
{
$push: {
refused_users: {
username,
date: new Date(),
},
},
}
);
};
// Aggiungi agli Admin del Gruppo
MyGroupSchema.statics.addToAdminOfMyGroup = async function (idapp, username, groupnameDest) {
return await MyGroup.updateOne(
{ idapp, groupname: groupnameDest },
{
$push: {
admins: {
username,
date: new Date(),
},
},
}
);
};
// Rimuovi dagli Admin del Gruppo
MyGroupSchema.statics.removeAdminOfMyGroup = async function (idapp, username, groupnameDest) {
return await MyGroup.updateOne(
{ idapp, groupname: groupnameDest },
{ $pull: { admins: { username: { $in: [username] } } } }
);
};
MyGroupSchema.statics.getListAdminsByGroupName = async function (idapp, groupname) {
let arr = await MyGroup.findOne(
{
idapp,
groupname,
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
},
{ admins: 1 }
).lean();
return arr && arr.admins ? arr.admins : [];
};
MyGroupSchema.statics.getWhatToShow = function (idapp, username) {
// FOR ME, PERMIT ALL
let whatToShow = {
groupname: 1,
title: 1,
descr: 1,
visibility: 1,
idCatGrp: 1,
userId: 1,
photos: 1,
idCity: 1,
website: 1,
link_telegram: 1,
note: 1,
da_contattare: 1,
admins: 1,
blocked: 1,
req_users: 1,
refused_users: 1,
createdBy: 1,
date_created: 1,
date_updated: 1,
mycircuits: 1,
lastdate_reqRisGroup: 1,
//**ADDFIELD_MYGROUPS
};
whatToShow = { ...whatToShow, ...shared_consts.ANNUNCI_FIELDS };
return whatToShow;
};
MyGroupSchema.statics.getWhatToShow_Unknown = function (idapp, username) {
let whatToShow = {
groupname: 1,
title: 1,
descr: 1,
photos: 1,
visibility: 1,
idCatGrp: 1,
idCity: 1,
note: 1,
date_created: 1,
date_updated: 1,
mycircuits: 1,
lastdate_reqRisGroup: 1,
};
whatToShow = { ...whatToShow, ...shared_consts.ANNUNCI_FIELDS };
return whatToShow;
};
MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function (idapp, groupname, field) {
const { User } = require('../models/user');
const myobj = {};
myobj[field] = 1;
const ris = await User.findOne(
{
idapp,
groupname,
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
},
myobj
);
if (ris) {
return ris[field].map((m) => m.username);
}
return [];
};
MyGroupSchema.statics.getInfoGroupByGroupname = async function (idapp, groupname) {
const whatToShow = this.getWhatToShow(idapp, groupname);
const myfind = {
idapp,
groupname,
};
const query = [
{ $match: myfind },
{
$lookup: {
from: 'circuits',
localField: 'mycircuits.circuitname',
foreignField: 'name',
as: 'mycircuits',
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: ['$mycircuits', 0],
},
'$$ROOT',
],
},
},
},
{ $project: whatToShow },
{
$lookup: {
from: 'catgrps',
localField: 'idCatGrp',
foreignField: '_id',
as: 'recCatGrp',
},
},
{
$project: shared_consts.getProjectByTable(shared_consts.TABLES_MYGROUPS, {}),
},
];
try {
const ris = await MyGroup.aggregate(query);
if (ris && ris.length > 0) return ris[0];
} catch (e) {
return null;
}
return null;
};
MyGroupSchema.statics.deleteGroup = async function (idapp, usernameOrig, groupname) {
console.log('Gruppo ' + groupname + ' rimosso da ' + usernameOrig);
return await MyGroup.findOneAndDelete({ idapp, groupname });
};
MyGroupSchema.statics.getGroupsByUsername = async function (idapp, username, req) {
try {
const { User } = require('../models/user');
const whatToShow = this.getWhatToShow(idapp, username);
const whatToShow_Unknown = this.getWhatToShow_Unknown(idapp, username);
const arrUsernameGroups = await User.getUsernameGroupsByUsername(idapp, username);
// const arrUsernameReqGroups = await MyGroup.getUsernameReqGroupsByGroupname(idapp, username);
let listUsersGroup = await User.find(
{
idapp,
username: { $in: arrUsernameGroups },
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
},
whatToShow
);
let listgroups = await MyGroup.find(
{
idapp,
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
},
whatToShow_Unknown
);
/*let listRequestUsersGroup = await User.find({
idapp,
username: {$in: arrUsernameReqGroups},
$or: [
{deleted: {$exists: false}},
{deleted: {$exists: true, $eq: false}}],
}, whatToShow_Unknown);
*/
let listSentRequestGroups = await MyGroup.find(
{
idapp,
req_users: {
$elemMatch: { username: { $eq: username } },
},
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
},
whatToShow_Unknown
);
let listRefusedGroups = await MyGroup.find(
{
idapp,
refused_users: {
$elemMatch: { username: { $eq: username } },
},
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
},
whatToShow_Unknown
);
return {
listUsersGroup,
listgroups,
listSentRequestGroups,
listRefusedGroups,
mygroups: await User.getMyGroupsById(req.user._id),
};
} catch (e) {
console.log('Error', e);
}
return {
listUsersGroup: [],
listRequestUsersGroup: [],
listTrusted: [],
listSentRequestGroups: [],
listRefusedGroups: [],
};
};
MyGroupSchema.statics.extractCitiesName = async function (idapp, id) {
try {
let aggr1 = [
{
$match: { idapp, _id: id },
},
{
$lookup: {
from: 'cities',
localField: 'idCity',
foreignField: '_id',
as: 'mycities',
},
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
$arrayElemAt: ['$mycities', 0],
},
'$$ROOT',
],
},
},
},
{
$project: {
'mycities.comune': 1,
'mycities.prov': 1,
},
},
];
ris = await this.aggregate(aggr1);
return ris;
} catch (e) {
console.error('e', e);
}
};
MyGroupSchema.statics.ifCircuitAlreadyInGroup = async function (idapp, groupname, circuitname) {
// Controllo se è stato già inserito il circuito sul gruppo
return await this.findOne({
idapp,
groupname,
mycircuits: {
$elemMatch: { circuitname: { $eq: circuitname } },
},
}).lean();
};
// aggiungo il Circuito all'interno del Gruppo
MyGroupSchema.statics.addCircuitFromGroup = async function (idapp, groupname, circuitname) {
return await this.updateOne(
{ idapp, groupname },
{
$push: {
mycircuits: {
circuitname,
date: new Date(),
},
},
}
);
};
// Rimuovo il Circuito all'interno del Gruppo
MyGroupSchema.statics.removeCircuitFromGroup = async function (idapp, groupname, circuitname) {
const { Circuit } = require('../models/circuit');
const { Account } = require('../models/account');
const ris = await this.updateOne(
{ idapp, groupname },
{ $pull: { mycircuits: { circuitname: { $in: [circuitname] } } } }
);
const circuitId = await Circuit.getCircuitIdByName(idapp, circuitname);
let remove = false;
// Se il mio account non è stato utilizzato, allora lo cancello anche questo
const myaccount = await Account.getAccountByUsernameAndCircuitId(idapp, '', circuitId, false, false, groupname, '');
if (myaccount && myaccount.totTransato === 0) {
remove = true;
} else {
remove = true;
}
if (remove && myaccount) {
await Account.removeAccount(myaccount._id);
}
};
MyGroupSchema.statics.getQueryReceiveRISGroups = function (idapp, hours) {
const query = [
{
$match: {
idapp,
lastdate_reqRisGroup: { $gte: tools.IncDateNow(-(1000 * 60 * 60 * hours)) },
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
},
},
{
$group: {
_id: '$groupname',
count: {
$sum: 1,
},
},
},
{ $sort: { lastdate_reqRisGroup: -1 } },
{ $limit: 30 },
{
$lookup: {
from: 'mygroups',
let: {
groupname: '$_id',
idapp,
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: ['$$groupname', '$groupname'],
},
{
$eq: ['$$idapp', '$idapp'],
},
],
},
},
},
],
as: 'mygroup',
},
},
{ $unwind: '$mygroup' },
{
$replaceRoot: {
newRoot: {
$mergeObjects: ['$mygroup', '$$ROOT'],
},
},
},
{
$project: {
_id: 0,
groupname: 1,
title: 1,
descr: 1,
visibility: 1,
idCatGrp: 1,
userId: 1,
photos: 1,
idCity: 1,
website: 1,
link_telegram: 1,
note: 1,
admins: 1,
blocked: 1,
req_users: 1,
createdBy: 1,
date_created: 1,
date_updated: 1,
lastdate_reqRisGroup: 1,
},
},
];
return query;
};
MyGroupSchema.statics.getReceiveRISGroups = async function (idapp) {
return await this.aggregate(this.getQueryReceiveRISGroups(idapp, 8)).then((ris) => {
return ris;
});
};
MyGroupSchema.statics.renameCircuitName = async function (idapp, oldcircuitname, newcircuitname) {
return await this.updateMany(
{ idapp, 'mycircuits.circuitname': oldcircuitname },
{ $set: { 'profile.mycircuits.$.circuitname': newcircuitname } }
);
};
MyGroupSchema.statics.setReceiveRisGroup = async function (idapp, groupname) {
const record = await this.findOneAndUpdate(
{ idapp, groupname },
{ $set: { lastdate_reqRisGroup: new Date() } },
{ new: false }
).lean();
return !!record; // Restituisce true se il record esiste, false altrimenti
};
const MyGroup = mongoose.model('MyGroup', MyGroupSchema);
MyGroup.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports = { MyGroup };

View File

@@ -1,390 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const tools = require('../tools/general');
const { Reaction } = require('./reaction');
const { MyGroup } = require('./mygroup');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
const tableModel = shared_consts.TABLES_MYHOSPS;
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const MyHospSchema = new Schema({
...{
_id: {
type: String,
},
idapp: {
type: String,
required: true,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
groupname: { type: String },
visibile: {
type: Boolean
},
adType: {
type: Number,
},
typeHosp: { // scambio casa / ospitalità
type: Number,
},
numMaxPeopleHosp: {
type: Number,
},
accomodation: [
{
type: { // Letto matrimoniale / letto singolo / divano-letto / almaca / a terra sul tappeto (per sacco a pelo) / culla
type: Number,
},
location: { // in camera privata / in camera condivisa / in soggiorno / in camper / in tenda / in giardino / all'aperto
type: Number,
},
num: {
type: Number,
},
}],
preferences: [ // Accetto bambini, Accetto cani, Accetto gatti, E' consentito fumare in casa, Accessibile con sedia a rotelle
{
type: Number,
}],
photos: [
{
imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
}],
idContribType: [
{
type: String,
}],
idCity: [
{
type: Number,
}],
pub_to_share: {
type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW
},
descr: {
type: String,
},
note: {
type: String,
default: '',
},
website: {
type: String,
},
link_maplocation: {
type: String,
},
date_created: {
type: Date,
},
date_updated: {
type: Date,
},
},
...Reaction.getFieldsForReactions(),
...tools.getFieldsForAnnunci()
});
MyHospSchema.pre('save', async function (next) {
if (this.isNew) {
if (!this.date_created)
this.date_created = new Date();
}
next();
});
MyHospSchema.statics.findAllIdApp = async function (idapp) {
const MyHosp = this;
const query = [
{ $match: { idapp } },
{ $sort: { descr: 1 } },
];
return await MyHosp.aggregate(query).then((arrrec) => {
return arrrec;
});
};
MyHospSchema.statics.getFieldsForSearch = function () {
return [];
};
MyHospSchema.statics.getFieldsLastForSearch = function () {
return [
{ field: 'descr', type: tools.FieldType.string },
{ field: 'note', type: tools.FieldType.string },
];
};
MyHospSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
params.fieldsearch_last = this.getFieldsLastForSearch();
const otherparams = {
lookup1: {
lk_tab: 'users',
lk_LF: 'userId',
lk_FF: '_id',
lk_as: 'user',
af_objId_tab: 'myId',
lk_proj: shared_consts.getProjectForAll({}, tableModel),
},
};
params = { ...params, ...otherparams };
return tools.executeQueryTable(this, idapp, params, user);
};
MyHospSchema.statics.getMyRecById = function (idapp, id) {
const MyHosp = this;
const myparsid = { '_id': id, idapp };
let query = [
{
'$match':
myparsid,
},
{
'$sort': {
'desc': 1,
},
},
{
'$addFields': {
'myId1': {
'$toObjectId': '$userId',
},
},
},
{
'$lookup': {
'from': 'users',
'localField': 'myId1',
'foreignField': '_id',
'as': 'user',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$user',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'skills',
'localField': 'idSkill',
'foreignField': '_id',
'as': 'recSkill',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$recSkill',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'sectors',
'localField': 'idSector',
'foreignField': '_id',
'as': 'sector',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$sector',
0,
],
},
'$$ROOT',
],
},
},
},
{
$lookup: {
'from': 'mygroups',
'localField': 'groupname',
'foreignField': 'groupname',
'as': 'mygrp',
},
},
{
$unwind: {
path: '$mygrp',
preserveNullAndEmptyArrays: true,
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
/*{
'$lookup': {
'from': 'subskills',
'localField': 'idSubSkill',
'foreignField': '_id',
'as': 'MyHosp',
},
},*/
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$MyHosp',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'cities',
'localField': 'idCity',
'foreignField': '_id',
'as': 'mycities',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$mycities',
0,
],
},
'$$ROOT',
],
},
},
},
];
let numtab = tools.getNumTabByTable(shared_consts.TABLES_MYHOSPS);
const objadd = tools.addNumFavoriteAndBookmarkToQuery(idapp, numtab);
query = [...query, ...objadd.query];
const toadd = {
$project: shared_consts.getProjectForAll(objadd.proj, tableModel),
};
query = [...query, { ...toadd }];
return MyHosp.aggregate(query).then((rec) => {
return rec ? rec[0] : null;
});
};
MyHospSchema.statics.getCompleteRecord = function (idapp, id) {
const MyHosp = this;
return MyHosp.getMyRecById(idapp, id);
};
MyHospSchema.statics.SettaAdTypeOffro_In_Hosps = async function () {
const MyHosp = this;
try {
// Set all records 'adType' to shared_consts.AdType.OFFRO
const result = await MyHosp.updateMany({}, { $set: { adType: shared_consts.AdType.OFFRO } });
console.log('Successfully updated adType for', result.modifiedCount, 'records');
} catch (err) {
console.error('Error updating adType:', err);
}
};
MyHospSchema.statics.getProject = function () {
let proj = {
visibile: 1,
typeHosp: 1,
numMaxPeopleHosp: 1,
accomodation: 1,
preferences: 1,
photos: 1,
website: 1,
link_maplocation: 1,
//**ADDFIELD_MYHOSP
};
const proj_add = shared_consts.getProjectForAll()
return Object.assign({}, proj, proj_add);
}
const MyHosp = mongoose.model('MyHosp', MyHospSchema);
MyHosp.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { MyHosp };

View File

@@ -1,261 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const MyPageSchema = new Schema({
idapp: {
type: String,
},
author_username: {
type: String,
},
lang: {
type: String,
},
title: {
type: String,
},
subtitle: {
type: String,
},
isTemplate: {
type: Boolean,
},
icon: {
type: String,
},
iconsize: {
type: String,
},
order: {
type: Number,
default: 1000,
},
path: {
type: String,
},
keywords: {
type: String,
},
description: {
type: String,
},
heightimg: {
type: Number,
},
onlyif_logged: {
type: Boolean,
},
only_residenti: {
type: Boolean,
},
only_admin: {
type: Boolean,
},
only_collab: {
type: Boolean,
},
color: {
type: String,
},
imgback: {
type: String,
},
img1: {
type: String,
},
content: {
type: String,
},
video1: {
type: String,
},
ratio1: {
type: String,
},
img2: {
type: String,
},
content2: {
type: String,
},
video2: {
type: String,
},
ratio2: {
type: String,
},
img3: {
type: String,
},
content3: {
type: String,
},
video3: {
type: String,
},
ratio3: {
type: String,
},
content4: {
type: String,
},
active: {
type: Boolean,
},
inmenu: {
type: Boolean,
},
submenu: {
type: Boolean,
},
l_par: {
type: Number,
},
l_child: {
type: Number,
},
internalpage: {
type: Boolean,
},
infooter: {
type: Boolean,
},
extraclass: {
type: String,
},
loadFirst: {
type: Boolean,
},
showFooter: {
type: Boolean,
},
sottoMenu: [{
type: String
}],
hideHeader: {
type: Boolean,
},
date_created: {
type: Date,
default: Date.now
},
date_updated: {
type: Date,
},
sections: { type: Array },
});
MyPageSchema.statics.getFieldsForSearch = function () {
return [{ field: 'title', type: tools.FieldType.string },
{ field: 'path', type: tools.FieldType.string },
{ field: 'keywords', type: tools.FieldType.string },
{ field: 'description', type: tools.FieldType.string },
{ field: 'content', type: tools.FieldType.string }]
};
MyPageSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params, user);
};
MyPageSchema.statics.findAllIdApp = async function (idapp) {
const MyPage = this;
const myfind = { idapp };
try {
return await MyPage.find(myfind).sort({ title: 1 }).lean();
} catch (err) {
console.error("Errore in MyPage:", err, model);
return null;
}
};
MyPageSchema.statics.findOnlyStruttRec = async function (idapp) {
const MyPage = this;
const arrFirst = await MyPage.find(
{
idapp,
loadFirst: true,
}).lean();
const arrfixed = await MyPage.find(
{
idapp,
$or: [
{ loadFirst: { $exists: false } },
{ loadFirst: { $exists: true, $eq: false } }],
}
, {
title: 1,
subtitle: 1,
icon: 1,
order: 1,
keywords: 1,
description: 1,
path: 1,
active: 1,
onlyif_logged: 1,
isTemplate: 1,
only_residenti: 1,
only_admin: 1,
only_collab: 1,
inmenu: 1,
submenu: 1,
iconsize: 1,
extraclass: 1,
loadFirst: 1,
sottoMenu: 1,
}).lean();
return [...arrFirst, ...arrfixed];
};
MyPageSchema.statics.findInternalPages = async function (idapp) {
const MyPage = this;
try {
const myfind = {
idapp,
internalpage: { $exists: true, $eq: true }
};
const result = await MyPage.find(myfind, {
title: 1,
path: 1,
onlyif_logged: 1,
only_residenti: 1,
only_admin: 1,
only_collab: 1,
}).lean();
return result;
} catch (err) {
console.log('findInternalPages', err);
throw err;
}
};
const MyPage = mongoose.model('MyPage', MyPageSchema);
MyPage.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { MyPage };

View File

@@ -1,174 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
const { ObjectId } = require('mongodb');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const ISize = new Schema({
width: { type: String },
height: { type: String },
fit: { type: String },
gap: { type: String },
});
const IFont = new Schema({
name: { type: String },
size: { type: String },
line_height: { type: Number },
posiz_text: { type: Number },
perc_text: { type: String },
});
const IBorders = new Schema({
top: { type: String },
bottom: { type: String },
left: { type: String },
right: { type: String },
})
const IImg = new Schema({
imagefile: { type: String },
fit: { type: String },
})
const IText = new Schema(
{
contenuto: String,
maxlength: Number,
font: IFont,
size: ISize,
}
);
const IDimensioni = new Schema({
size: ISize,
margini: IBorders,
padding: IBorders,
imgsfondo: IImg,
text_html: IText,
});
const IPagina = new Schema({
dimensioni: IDimensioni,
testo_title: IText,
testo_up: IText,
testo_down: IText,
});
const IAreaDiStampa = new Schema({
margini: IBorders,
unit: String,
format: [{ type: Number }],
format_printable: [{ type: Number }],
orientation: String,
compress: Boolean,
scalex: Number,
scaley: Number,
scale_printablex: Number,
scale_printabley: Number,
scalecanvas: Number,
});
const INovita = new Schema(
{
show: Boolean,
months: Number,
}
);
const IBestseller = new Schema(
{
show: Boolean,
quantiFattRaggiunti: Number,
}
);
const IEtichette = new Schema(
{
novita: INovita,
bestseller: IBestseller,
}
);
const IBarCode = new Schema(
{
show: Boolean,
format: Number,
size: ISize,
font: IFont,
widthlines: Number,
show_at_right: Boolean,
}
);
const IElementiScheda = new Schema({
pagina: IPagina,
riga: IDimensioni,
scheda_prodotto: IDimensioni,
immagine_prodotto: IDimensioni,
});
const scheletroScheda = {
idapp: { type: String },
isTemplate: { type: Boolean },
isPagIntro: { type: Boolean },
linkIdTemplate: { type: String },
scalexscheda: Number,
scaleyscheda: Number,
name: { type: String },
numschede_perRiga: { type: Number },
numschede_perCol: { type: Number },
show_separatore: { type: Boolean },
testo_right_attaccato: IText,
testo_right: IText,
testo_bottom: IText,
barcode: IBarCode,
etichette: IEtichette,
dimensioni: IElementiScheda,
productTypes: [{ type: Number }],
excludeproductTypes: [{ type: Number }],
idTipologie: [{ type: Number }],
idTipoFormato: [{ type: Number }],
editore: [{ type: String }],
argomenti: [{ type: String }],
idCollane: [{ type: String }],
author: { type: String },
sort_field: { type: String },
sort_dir: { type: Number },
arrProdottiSpeciali: [{ type: String }],
};
const MySchedaSchema = new Schema(
scheletroScheda
);
MySchedaSchema.statics.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
MySchedaSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params, user);
};
MySchedaSchema.statics.findAllIdApp = async function (idapp) {
};
const MyScheda = mongoose.model('MyScheda', MySchedaSchema);
MyScheda.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { MyScheda, MySchedaSchema, IDimensioni, IImg, IText, IAreaDiStampa, IImg };

View File

@@ -1,99 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = 'F';
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const MyScrapingBookSchema = new Schema({
isbn: {
type: String,
index: true,
},
isbn10: {
type: String,
},
fonte: {
type: String,
},
titolo: {
type: String,
},
titoloOriginale: {
type: String,
},
sottotitolo: {
type: String,
},
autore: {
type: String,
},
pagine: {
type: String,
},
misure: {
type: String,
},
edizione: {
type: String,
},
editore: {
type: String,
},
date_pub: {
type: Date,
},
url: {
type: String,
},
stelline: {
type: Number,
},
prezzo: {
type: String,
},
date_extraction: {
type: Date,
},
descrizione_lunga: {
type: String,
},
});
MyScrapingBookSchema.statics.getFieldsForSearch = function () {
return [{ field: 'titolo', type: tools.FieldType.string }];
};
MyScrapingBookSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params, user);
};
MyScrapingBookSchema.statics.findAllIdApp = async function (idapp) {
const MyScrapingBook = this;
const myfind = { idapp };
try {
return await MyScrapingBook.find(myfind).sort({ titolo: 1 }).lean();
} catch (err) {
console.error('Errore in MyScrapingBook:', err, model);
return null;
}
};
const MyScrapingBook = mongoose.model('MyScrapingBook', MyScrapingBookSchema);
MyScrapingBook.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports = { MyScrapingBook };

View File

@@ -1,376 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const tools = require('../tools/general');
const { Reaction } = require('./reaction');
const { MyGroup } = require('./mygroup');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
const tableModel = shared_consts.TABLES_MYSKILLS;
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const MySkillSchema = new Schema(
{
...{
_id: {
type: String,
default: function () {
return new ObjectId().toString();
},
},
idapp: {
type: String,
required: true,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
groupname: { type: String },
idSector: {
type: Number,
},
idSkill: {
type: Number,
default: 0,
},
/*idSubSkill: [
{
type: Number,
default: 0,
}],
*/
idStatusSkill: [
{
type: Number,
}],
idContribType: [
{
type: String,
}],
idCity: [
{
type: Number,
}],
pub_to_share: {
type: Number, // PUB_TO_SHARE_ALL, PUB_TO_SHARE_ONLY_TABLE_FOLLOW
},
numLevel: {
type: Number,
default: 0,
},
adType: {
type: Number,
},
photos: [
{
imagefile: {
type: String,
},
alt: {
type: String,
},
description: {
type: String,
},
}],
note: {
type: String,
default: '',
},
descr: {
type: String,
},
//**ADDFIELD_MYSKILL
website: {
type: String,
},
date_created: {
type: Date,
},
date_updated: {
type: Date,
},
},
...Reaction.getFieldsForReactions(),
...tools.getFieldsForAnnunci()
}, { strict: false });
MySkillSchema.index({ 'idapp': 1 });
MySkillSchema.pre('save', async function (next) {
if (this.isNew) {
if (!this.date_created)
this.date_created = new Date();
}
next();
});
MySkillSchema.statics.findAllIdApp = async function (idapp) {
const MySkill = this;
const query = [
{ $match: { idapp } },
{ $sort: { descr: 1 } },
];
return await MySkill.aggregate(query).then((arrrec) => {
return arrrec;
});
};
MySkillSchema.statics.getFieldsForSearch = function () {
return [];
};
MySkillSchema.statics.getFieldsLastForSearch = function () {
return [
{ field: 'note', type: tools.FieldType.string },
{ field: 'descr', type: tools.FieldType.string },
{ field: 'recSkill.descr', type: tools.FieldType.string },
{ field: 'myskill.descr', type: tools.FieldType.string },
];
};
MySkillSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
params.fieldsearch_last = this.getFieldsLastForSearch();
const otherparams = {
lookup1: {
lk_tab: 'users',
lk_LF: 'userId',
lk_FF: '_id',
lk_as: 'user',
af_objId_tab: 'myId',
lk_proj: shared_consts.getProjectForAll({}, tableModel),
},
};
params = { ...params, ...otherparams };
return tools.executeQueryTable(this, idapp, params, user);
};
MySkillSchema.statics.getMyRecById = function (idapp, idSkill) {
const MySkill = this;
let query = [
{
'$match': {
'_id': idSkill, idapp
},
},
{
'$sort': {
'desc': 1,
},
},
{
'$addFields': {
'myId1': {
'$toObjectId': '$userId',
},
},
},
{
'$lookup': {
'from': 'users',
'localField': 'myId1',
'foreignField': '_id',
'as': 'user',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$user',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'skills',
'localField': 'idSkill',
'foreignField': '_id',
'as': 'recSkill',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$recSkill',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'sectors',
'localField': 'idSector',
'foreignField': '_id',
'as': 'sector',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$sector',
0,
],
},
'$$ROOT',
],
},
},
},
{
$lookup: {
'from': 'mygroups',
'localField': 'groupname',
'foreignField': 'groupname',
'as': 'mygrp',
},
},
{
$unwind: {
path: '$mygrp',
preserveNullAndEmptyArrays: true,
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
/*{
'$lookup': {
'from': 'subskills',
'localField': 'idSubSkill',
'foreignField': '_id',
'as': 'myskill',
},
},
*/
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$myskill',
0,
],
},
'$$ROOT',
],
},
},
},
{
$project: shared_consts.getProjectForAll({}, tableModel),
},
{
'$lookup': {
'from': 'cities',
'localField': 'idCity',
'foreignField': '_id',
'as': 'mycities',
},
},
{
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [
{
'$arrayElemAt': [
'$mycities',
0,
],
},
'$$ROOT',
],
},
},
},
];
let numtab = tools.getNumTabByTable(shared_consts.TABLES_MYSKILLS);
const objadd = tools.addNumFavoriteAndBookmarkToQuery(idapp, numtab);
query = [...query, ...objadd.query];
const toadd = {
$project: shared_consts.getProjectForAll(objadd.proj, tableModel),
};
query = [...query, { ...toadd }];
return MySkill.aggregate(query).then((rec) => {
return rec ? rec[0] : null;
});
};
MySkillSchema.statics.getProject = function (proj_add2) {
let proj = {
recSkill: 1,
sector: 1,
idSector: 1,
idSkill: 1,
idStatusSkill: 1,
website: 1,
'numLevel': 1,
//**ADDFIELD_MYSKILL
};
const proj_add = shared_consts.getProjectForAll(proj_add2)
return Object.assign({}, proj, proj_add);
}
MySkillSchema.statics.getCompleteRecord = function (idapp, id) {
const MySkill = this;
return MySkill.getMyRecById(idapp, id);
};
const MySkill = mongoose.model('MySkill', MySkillSchema);
module.exports = { MySkill };

View File

@@ -1,176 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const NewstosentSchema = new Schema({
idapp: {
type: String,
},
label: {
type: String,
},
templemail_str: {
type: String,
},
destnewsletter_str: {
type: String,
},
activate: {
type: Boolean,
default: false
},
numemail_tot: {
type: Number,
default: 0
},
numemail_sent: {
type: Number,
default: 0
},
datetoSent: {
type: Date
},
datestartJob: {
type: Date
},
datefinishJob: {
type: Date
},
lastemailsent_Job: {
type: Date
},
starting_job: {
type: Boolean,
default: false
},
finish_job: {
type: Boolean,
default: false
},
processing_job: {
type: Boolean,
default: false
},
error_job: {
type: String,
}
});
NewstosentSchema.statics.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string },
{ field: 'surname', type: tools.FieldType.string },
{ field: 'email', type: tools.FieldType.string }]
};
NewstosentSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
NewstosentSchema.statics.findNewsletter_To_Send = function (idapp) {
const Newstosent = this;
return Newstosent.findOne({
// datetoSent: { $gte: tools.IncDateNow(-1000 * 60 * 60) },
datetoSent: { $gte: tools.IncDateNow(-1000 * 60 * 60) },
activate: true,
starting_job: false,
processing_job: false,
finish_job: false,
idapp
}).sort({ datetoSent: 1 }).lean();
};
NewstosentSchema.statics.endJob = async function (id) {
const Newstosent = this;
myjobnews = await Newstosent.findOne({ _id: id });
if (!!myjobnews) {
myjobnews.datefinishJob = new Date();
myjobnews.finish_job = true;
await myjobnews.save()
}
};
NewstosentSchema.statics.processingJob = async function (id, state) {
const Newstosent = this;
myjobnews = await Newstosent.findOne({ _id: id });
if (!!myjobnews) {
myjobnews.processing_job = state;
await myjobnews.save()
}
};
NewstosentSchema.statics.findNewsletterPending_To_Send = function (idapp) {
const Newstosent = this;
return Newstosent.findOne({
datestartJob: { $lt: tools.IncDateNow(0) },
activate: true,
starting_job: true,
finish_job: false,
processing_job: false,
$or: [
{ lastemailsent_Job: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 15) } },
{ lastemailsent_Job: null }
],
idapp
}).lean();
};
NewstosentSchema.statics.findAllIdApp = async function (idapp) {
const Newstosent = this;
const myfind = { idapp };
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return await tools.findAllQueryIdApp(this, myfind);
};
NewstosentSchema.statics.getlast = async function (idapp) {
const Newstosent = this;
try {
const mydoc = await Newstosent.findOne({ idapp }).sort({ datestartJob: -1 }).lean();
return mydoc || null;
} catch (e) {
return null;
}
};
NewstosentSchema.statics.isActivated = async function (_id) {
const Newstosent = this;
try {
const mydoc = await Newstosent.findOne({ _id }).lean();
return (mydoc.activate);
} catch (e) {
return false
}
};
const Newstosent = mongoose.model('Newstosent', NewstosentSchema);
Newstosent.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Newstosent };

View File

@@ -1,118 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const OperatorSchema = new Schema({
idapp: {
type: String,
},
username: {
type: String,
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
email: {
type: String,
trim: true,
},
usertelegram: {
type: String,
},
cell: {
type: String,
trim: true,
},
img: {
type: String,
},
qualification: { // President, Vice-President, ecc...
type: String,
},
disciplines: {
type: String,
},
certifications: {
type: String,
},
webpage: {
type: String,
},
days_working: {
type: String,
},
facebook: {
type: String,
},
info: { // Biografia HTML
type: String,
},
intro: {
type: String,
},
offers: {
type: String,
},
skype: {
type: String,
},
showInTeam: {
type: Boolean,
},
arrDisciplines: [{
type: String,
}],
});
OperatorSchema.statics.getEmailByUsername = async function (idapp, username) {
const Operator = this;
return await Operator.findOne({ idapp, username })
.then((arrrec) => {
return ((arrrec) ? arrrec.email : '');
}).catch((e) => {
console.error('getEmailByUsername', e);
});
};
OperatorSchema.statics.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string },
{ field: 'surname', type: tools.FieldType.string },
{ field: 'email', type: tools.FieldType.string },
{ field: 'cell', type: tools.FieldType.string }]
};
OperatorSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
OperatorSchema.statics.findAllIdApp = function (idapp) {
const query = this.find({ idapp }); // Crea la query
return query.exec(); // Esegui la query come promessa
};
const Operator = mongoose.model('Operator', OperatorSchema);
Operator.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Operator };

View File

@@ -1,49 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const OpzEmailSchema = new Schema({
key: {
type: String,
default: ''
},
label_it: {
type: String,
}
});
OpzEmailSchema.statics.getFieldsForSearch = function () {
return [{field: 'label_it', type: tools.FieldType.string}]
};
OpzEmailSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
OpzEmailSchema.statics.findAllIdApp = async function (idapp) {
const OpzEmail = this;
return await tools.findAllQueryIdApp(this, {});
};
const OpzEmail = mongoose.model('OpzEmail', OpzEmailSchema);
OpzEmail.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { OpzEmail };

View File

@@ -1,709 +0,0 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
const Scontistica = require('../models/scontistica');
const OrderClass = require('../modules/OrderClass');
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const fs = require('fs'); // 👈 Usa il modulo promises
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const orderSchema = new Schema({
idapp: {
type: String,
},
userId: { type: Schema.Types.ObjectId, ref: 'User' },
status: {
type: Number,
index: true,
},
idProduct: { type: Schema.Types.ObjectId, ref: 'Product', index: true },
idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' },
idStorehouse: { type: Schema.Types.ObjectId, ref: 'StoreHouse' },
idScontisticas: [{ type: Schema.Types.ObjectId, ref: 'Scontistica' }],
idProvider: { type: Schema.Types.ObjectId, ref: 'Provider' },
idGasordine: { type: Schema.Types.ObjectId, ref: 'Gasordine' },
price: {
type: Number,
default: 0,
},
after_price: {
type: String,
},
color: {
type: String,
},
size: {
type: String,
},
quantity: {
type: Number,
default: 0,
},
quantitypreordered: {
type: Number,
default: 0,
},
TotalPriceProduct: {
type: Number,
default: 0,
},
TotalPriceProductstr: {
type: String,
},
TotalPriceProductCalc: {
type: Number,
default: 0,
},
confermato: {
// e quindi è stato tolto dal magazzino (aggiornando il campo stockQty)
type: Boolean,
default: false,
},
date_confermato: {
type: Date,
},
pagato: {
type: Boolean,
default: false,
},
date_pagato: {
type: Date,
},
consegnato: {
type: Boolean,
default: false,
},
date_consegnato: {
type: Date,
},
spedito: {
type: Boolean,
default: false,
},
date_spedito: {
type: Date,
},
ricevuto: {
type: Boolean,
default: false,
},
date_ricevuto: {
type: Date,
},
weight: {
type: Number,
},
unit: {
type: Number,
},
stars: {
type: Number,
},
date_created: {
type: Date,
},
date_checkout: {
type: Date,
},
date_payment: {
type: Date,
},
date_shipping: {
type: Date,
},
date_delivered: {
type: Date,
},
note: {
type: String,
},
codice_sconto: {
type: String,
},
modify_at: {
type: Date,
index: true,
},
});
var Order = (module.exports = mongoose.model('Order', orderSchema));
module.exports
.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports.getFieldsForSearch = function () {
return [];
};
module.exports.executeQueryTable = function (idapp, params) {
const tools = require('../tools/general');
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const query = [
{ $match: { idapp } },
{
$lookup: {
from: 'products',
localField: 'idProduct',
foreignField: '_id',
as: 'product',
},
},
{
$lookup: {
from: 'producers',
localField: 'product.idProducer',
foreignField: '_id',
as: 'producer',
},
},
{
$lookup: {
from: 'providers',
localField: 'product.idProvider',
foreignField: '_id',
as: 'provider',
},
},
{
$lookup: {
from: 'gasordines',
localField: 'idGasordine',
foreignField: '_id',
as: 'gasordine',
},
},
{
$unwind: {
path: '$gasordine',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
$or: [{ gasordine: { $exists: false } }, { 'gasordine.active': true }],
},
},
{
$lookup: {
from: 'scontisticas',
localField: 'product.idScontisticas',
foreignField: '_id',
as: 'scontistica',
},
},
{
$unwind: {
path: '$product',
preserveNullAndEmptyArrays: true,
},
},
{
$unwind: {
path: '$producer',
preserveNullAndEmptyArrays: true,
},
},
{
$unwind: {
path: '$provider',
preserveNullAndEmptyArrays: true,
},
},
];
return await Order.aggregate(query);
};
module.exports.getAllOrders = function (query, sort, callback) {
Order.find(query, null, sort, callback);
};
module.exports.getOrderByUserId = function (userId, sort, callback) {
Order.find({ userId }, null, sort, callback);
};
module.exports.getOrderByID = function (id, callback) {
Order.findById(id, callback);
};
module.exports.createOrder = async function (order, codice_sconto) {
try {
if (order.idGasordine === '') {
order.idGasordine = undefined;
}
await Order.updateTotals(order, codice_sconto);
return await Order.create(order).then((ris) => {
if (!!ris) return ris._id;
return null;
});
} catch (e) {
console.error('err', e);
}
};
module.exports.updateStatusOrders = async function (arrOrders, status) {
for (const order of arrOrders) {
let ret = await Order.updateOne({ _id: order.order._id }, { $set: { status } });
}
};
module.exports.updateStatusOrdersElements = async function (arrOrders, myelements) {
for (const order of arrOrders) {
const ret = await Order.findOneAndUpdate({ _id: order.order._id }, { $set: myelements });
}
};
module.exports.updateOrderByParams = async function (idOrder, paramstoupdate) {
const ris = await Order.findOneAndUpdate({ _id: idOrder }, { $set: paramstoupdate });
let myorder = await Order.findOne({ _id: idOrder }).lean();
if (paramstoupdate && !paramstoupdate.hasOwnProperty('TotalPriceProduct')) {
await this.updateTotals(myorder);
await Order.findOneAndUpdate({ _id: idOrder }, { $set: myorder });
}
return myorder;
};
module.exports.updateTotals = async function (order, codice_sconto) {
try {
const CartClass = require('../modules/Cart');
if (!order) return;
OrderClass.initOrderTotals(order);
let total = 0;
let scontoapplicato = false;
let recscontisticheTrovate = [];
if (codice_sconto) {
recscontisticheTrovate = await CartClass.getRecSconto(order.idapp, codice_sconto, true);
}
// Se ha inserito una scontistica che esiste...
if (recscontisticheTrovate && recscontisticheTrovate.length > 0) {
const { sconti_da_applicare, qtanonscontata } = OrderClass.applyNonCumulativeDiscounts(order, recscontisticheTrovate);
total = OrderClass.calculateDiscountedPrice(order, sconti_da_applicare, qtanonscontata);
} else if (order.scontisticas && order.scontisticas.length > 0) {
const { sconti_da_applicare, qtanonscontata } = OrderClass.applyNonCumulativeDiscounts(order, order.scontisticas);
total = OrderClass.calculateDiscountedPrice(order, sconti_da_applicare, qtanonscontata);
} else {
total = OrderClass.calculateFullPrice(order);
}
order.TotalPriceProductCalc += total;
order.TotalPriceProduct += total;
order.TotalPriceProductstr = parseFloat(order.TotalPriceProduct.toFixed(2));
order.codice_sconto = codice_sconto;
return order;
} catch (e) {
console.error('Err:', e);
}
};
module.exports.getTotalOrderById = async function (id) {
const query = [
{ $match: { _id: new ObjectId(id) } },
{
$lookup: {
from: 'products',
localField: 'idProduct',
foreignField: '_id',
as: 'product',
},
},
{
$unwind: {
path: '$product',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'producers',
localField: 'product.idProducer',
foreignField: '_id',
as: 'producer',
},
},
{
$unwind: {
path: '$producer',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'storehouses',
localField: 'idStorehouse',
foreignField: '_id',
as: 'storehouse',
},
},
{
$unwind: {
path: '$storehouse',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'providers',
localField: 'product.idProvider',
foreignField: '_id',
as: 'provider',
},
},
{
$unwind: {
path: '$provider',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'gasordines',
localField: 'idGasordine',
foreignField: '_id',
as: 'gasordine',
},
},
{
$unwind: {
path: '$gasordine',
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
$or: [{ gasordine: { $exists: false } }, { 'gasordine.active': true }],
},
},
{
$lookup: {
from: 'scontisticas',
localField: 'product.idScontisticas',
foreignField: '_id',
as: 'scontisticas',
},
},
{
$lookup: {
from: 'orders',
let: { productId: '$product._id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{
$or: [
{
$eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT],
},
{
$and: [
{ $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] },
{
$gt: [
'$modify_at',
{ $subtract: [new Date(), 60 * 60 * 1000] }, // 1 hour in milliseconds 60 * 60
],
},
],
},
],
},
],
},
},
},
{
$group: {
_id: null,
totalQty: { $sum: '$quantity' },
},
},
],
as: 'productOrders',
},
},
{
$lookup: {
from: 'orders',
let: { productId: '$product._id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idProduct', '$$productId'] },
{
$or: [
{
$eq: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT],
},
{
$and: [
{ $lt: ['$status', shared_consts.OrderStatus.CHECKOUT_SENT] },
{
$gt: [
'$modify_at',
{ $subtract: [new Date(), 60 * 60 * 1000] }, // 1 hour in milliseconds 60 * 60
],
},
],
},
],
},
],
},
},
},
{
$group: {
_id: null,
totalQtyPreordered: { $sum: '$quantitypreordered' },
},
},
],
as: 'productPreOrders',
},
},
{
$addFields: {
'product.QuantitaOrdinateInAttesa': {
$ifNull: [
{
$cond: {
if: { $isArray: '$productOrders' },
then: { $arrayElemAt: ['$productOrders.totalQty', 0] },
else: 0,
},
},
0,
],
},
'product.QuantitaPrenotateInAttesa': {
$ifNull: [
{
$cond: {
if: { $isArray: '$productPreOrders' },
then: { $arrayElemAt: ['$productPreOrders.totalQtyPreordered', 0] },
else: 0,
},
},
0,
],
},
},
},
{
$addFields: {
'product.quantityAvailable': {
$subtract: ['$product.stockQty', '$product.QuantitaOrdinateInAttesa'],
},
'product.bookableAvailableQty': {
$subtract: ['$product.maxbookableGASQty', '$product.QuantitaPrenotateInAttesa'],
},
},
},
{
$unset: 'productOrders',
},
{
$unset: 'productPreOrders',
},
];
const ris = await Order.aggregate(query);
return ris;
};
module.exports.deleteOrderById = async function(id) {
try {
const ris = await Order.findOneAndDelete({ _id: id });
return ris;
} catch (e) {
console.error('Err', e);
return null;
}
}
module.exports.RemoveDeletedOrdersInOrderscart = async function () {
try {
const OrdersCart = require('./orderscart');
// Cancella gli Ordini che non esistono in OrdersCart
const arrorders = await OrdersCart.find({}).lean();
for (const rec of arrorders) {
let recordercart = await OrdersCart.getOrdersCartById(rec._id);
let arrord = [];
let cambiare = false;
for (const recOrd of recordercart.items) {
if (recOrd.order) {
arrord.push(recOrd);
} else {
cambiare = true;
}
}
if (cambiare) {
await OrdersCart.findOneAndUpdate({ _id: recordercart._id }, { $set: { items: arrord } }, { new: false });
}
}
// Controllo se Order non esiste in OrdersCart
const arrord = await Order.find({}).lean();
for (const ord of arrord) {
const idtofind = ord._id;
await OrdersCart.findOne({ 'items.order': { $in: [idtofind] } })
.then(async (orderCart) => {
if (!orderCart) {
// NON TROVATO ! Allora lo cancello
await Order.findOneAndDelete({ _id: ord._id });
}
})
.catch((err) => console.error(err));
}
} catch (e) {
console.error('Err', e);
}
};
module.exports.GeneraCSVOrdineProdotti = async function () {
const myidGasordine = '65c2a8cc379ee4f57e865ee7';
const myquery = [
{ $match: { idGasordine: new ObjectId(myidGasordine) } },
{
$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: [
{ 'gasordine.active': true }, // Include documents where gasordines.active is true
{ gasordine: { $exists: false } }, // Include documents where gasordines array doesn't exist
],
},
},
{
$match: {
$or: [{ quantity: { $gt: 0 } }, { quantitypreordered: { $gt: 0 } }],
},
},
{
$group: {
_id: '$product._id',
name: { $first: '$product.productInfo.name' },
weight: { $first: '$product.productInfo.weight' },
price_acquistato: { $first: '$product.price_acquistato' },
totalQuantity: { $sum: { $add: ['$quantity', '$quantitypreordered'] } },
totalPrice_acquistato: {
$sum: { $multiply: ['$product.price_acquistato', { $add: ['$quantity', '$quantitypreordered'] }] },
},
count: { $sum: 1 },
},
},
{
$sort: {
name: 1, // Sort in ascending order based on the "date_created" field
},
},
];
let myorderscart = await Order.aggregate(myquery);
console.log(myorderscart);
return generateCSV(myorderscart, 'outout.csv');
};
function generateCSV(data, outputPath) {
const headers = ['Num', 'Nome', 'Peso', 'Prezzo', 'Quantita', 'Totale', 'Ordini'];
const rows = data.map((item) => {
const formattedPrice = item.price_acquistato.toString().replace(/\./g, ','); // Converti "." in ","
const total = item.totalPrice_acquistato.toString().replace(/\./g, ','); // Converti "." in ","
return [0, `"${item.name}"`, item.weight, formattedPrice, item.totalQuantity, total, item.count];
});
rows.unshift(headers);
const csvData = rows.map((row) => row.join('|'));
fs.writeFile(outputPath, csvData.join('\n'), (err) => {
if (err) {
console.error('Error writing CSV file:', err);
} else {
console.log('CSV file has been successfully generated:', outputPath);
}
});
}
// const Order = mongoose.model('Order', OrderSchema);
// module.exports = { Order };
// **** TOTALPRICE !!!

File diff suppressed because it is too large Load Diff

View File

@@ -1,52 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const PaymentTypeSchema = new Schema({
idapp: {
type: String,
},
key: {
type: String,
},
label: {
type: String,
},
});
PaymentTypeSchema.statics.getFieldsForSearch = function () {
return [{field: 'label', type: tools.FieldType.string}]
};
PaymentTypeSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
PaymentTypeSchema.statics.findAllIdApp = async function (idapp) {
const PaymentType = this;
const myfind = { idapp };
return await tools.findAllQueryIdApp(this, myfind);
};
const PaymentType = mongoose.model('Paymenttype', PaymentTypeSchema);
PaymentType.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { PaymentType };

View File

@@ -1,63 +0,0 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const PermissionSchema = new Schema({
_id: {
type: Number,
},
label: {
type: String,
default: ''
}
}, { _id: false });
PermissionSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await Permission.findOne().limit(1).sort({ _id: -1 });
if (!!myrec) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id * 2;
} else {
this._id = 1;
}
}
next();
});
PermissionSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
PermissionSchema.statics.findAllIdApp = async function () {
const Permission = this;
const myfind = {};
return await tools.findAllQueryIdApp(this, {});
};
const Permission = mongoose.model('Permission', PermissionSchema);
Permission.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Permission };

View File

@@ -1,58 +0,0 @@
const shared_consts = require('../tools/shared_nodejs');
const tools = require('../tools/general');
const countryCodes = require('country-codes-list');
module.exports = {
async executeQueryPickup(idapp, params) {
const table = params.table;
const strfind = params.search;
if (strfind === '') {
return [];
}
let myCountryArr = [];
let out = {};
if (table === shared_consts.TAB_COUNTRY) {
// '[{countryCode}] {countryNameLocal}: +{countryCallingCode}'
out = {
id: '{countryCode}',
value: '{countryNameLocal}',
flag: '{flag}',
};
} else if (table === shared_consts.TAB_PHONES) {
out = {
id: '{countryCode}',
value: '{countryNameLocal} +{countryCallingCode}',
code: '+{countryCallingCode}',
flag: '{flag}',
};
}
try {
// const myCountryArr = countryCodes.filter('countryNameLocal', strfind);
// const myCountryArr = countryCodes.customList.filter()
// myCountryArr = countryCodes.customList('countryCode', lavueout, { filter: ((countryData) => { return countryData['countryNameLocal'].toLocaleLowerCase().indexOf(strfind) >= 0 })} );
myCountryArr = countryCodes.customArray(out, {
filter: ((countryData) => {
return countryData['countryNameLocal'].toLocaleLowerCase().
startsWith(strfind) || countryData['countryNameEn'].toLocaleLowerCase().
startsWith(strfind);
}),
});
} catch (e) {
console.log('err', e);
}
return myCountryArr;
},
};

View File

@@ -1,107 +0,0 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const producerSchema = new Schema({
idapp: {
type: String,
},
name: {
type: String,
},
description: {
type: String,
},
referent: {
type: String,
},
username: {
type: String,
},
region: {
type: String,
},
city: {
type: String,
},
img: {
type: String,
},
website: {
type: String,
}
});
var Producer = module.exports = mongoose.model('Producer', producerSchema);
module.exports.getFieldsForSearch = function () {
return [{field: 'name', type: tools.FieldType.string}]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
module.exports.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return await Producer.find(myfind).lean();
};
module.exports.getAllProducers = function (query, sort, callback) {
Producer.find(query, null, sort, callback)
}
module.exports.getProducerByDepartment = function (query,sort, callback) {
Producer.find(query, null, sort, callback)
}
module.exports.getProducerByCategory = function (query,sort, callback) {
Producer.find(query, null, sort, callback)
}
module.exports.getProducerByTitle = function (query,sort, callback) {
Producer.find(query, null, sort, callback)
}
module.exports.filterProducerByDepartment = function (department, callback) {
let regexp = new RegExp(`^${department}$`, 'i')
var query = { department: { $regex: regexp } };
Producer.find(query, callback)
}
module.exports.filterProducerByCategory = function (category, callback) {
let regexp = new RegExp(`^${category}$`, 'i')
var query = { category: { $regex: regexp } };
Producer.find(query, callback);
}
module.exports.filterProducerByTitle = function (title, callback) {
let regexp = new RegExp(`^${title}$`, 'i')
var query = { title: { $regex: regexp } };
Producer.find(query, callback);
}
module.exports.getProducerByID = function (id, callback) {
Producer.findById(id, callback);
}
// const Producer = mongoose.model('Producer', producerSchema);
// module.exports = { Producer };
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

File diff suppressed because it is too large Load Diff

View File

@@ -1,305 +0,0 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { IImg } = require('../models/myscheda');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const productInfoSchema = new Schema({
idapp: {
type: String,
},
deleted: {
type: Boolean,
},
department: {
type: String, ref: 'Department'
},
sku: {
type: String,
},
code: {
type: String,
unique: true,
required: true,
},
codice: { // codice interno prodotto
type: String,
},
id_wp: { // id in wordpress
type: String,
},
codice_EAN: {
type: String,
},
barcode: {
type: String,
},
name: {
type: String,
index: true,
},
description: {
type: String,
},
short_descr: {
type: String,
},
idCatProds: [{ type: Schema.Types.ObjectId, ref: 'CatProd', index: true }],
idSubCatProds: [{ type: Schema.Types.ObjectId, ref: 'SubCatProd' }],
idStatoProdotto: {
type: Number, index: true
},
color: {
type: String
},
size: {
type: String // 11x4x3
},
weight: {
type: Number
},
weight_lordo: {
type: Number
},
unit: {
type: Number,
},
unit_lordo: {
type: Number,
},
sfuso: { // serve se moltiplicare le qta (es: 12 kg) oppure fare (2 x 20 ml)
type: Boolean
},
vegan: {
type: Boolean
},
icon: {
type: String,
},
img: {
type: String,
},
imagefile: {
type: String,
},
image_not_found: {
type: Boolean,
},
vers_img: {
type: Number,
},
image_link: {
type: String,
},
link_scheda: {
type: String,
},
link: {
type: String,
},
checkout_link: {
type: String,
},
versioneGM: {
type: String,
},
img2: {
type: String,
},
img3: {
type: String,
},
img4: {
type: String,
},
ingredienti: {
type: String,
},
valori_nutrizionali: {
type: String,
},
note: {
type: String,
},
idAuthors: [{ type: Schema.Types.ObjectId, ref: 'Author', index: true }],
idCollana: { type: Schema.Types.ObjectId, ref: 'Collana', index: true },
idPublisher: { type: Schema.Types.ObjectId, ref: 'Publisher', index: true },
collezione: {
type: String,
},
ListaArgomenti: {
type: String,
},
date_pub: {
type: Date,
index: 1,
},
date_pub_ts: {
type: Number,
},
productTypes: [{
type: Number,
}],
date_updated: {
type: Date,
},
date_updated_fromGM: {
type: Date,
},
totVen: Number,
totFat: Number,
vLast3M: Number,
fatLast3M: Number,
fatLast6M: Number,
fatLast1Y: Number,
fatLast2Y: Number,
vLast6M: {
type: Number,
index: true,
},
vLast1Y: {
type: Number, index: true
},
vLast2Y: Number,
dataUltimoOrdine: Date,
rank3M: Number,
rank6M: Number,
rank1Y: Number,
descrizione_breve_macro: String,
descrizione_completa_macro: String,
descr_trafiletto_catalogo: String,
sottotitolo: String,
link_macro: String,
});
var productInfo = module.exports = mongoose.model('ProductInfo', productInfoSchema);
module.exports.getFieldsForSearch = function () {
return [
{ field: 'name', type: tools.FieldType.string },
{ field: 'code', type: tools.FieldType.string },
{ field: 'sku', type: tools.FieldType.string },
{ field: 'codice_EAN', type: tools.FieldType.string },
]
};
module.exports.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
/*module.exports.findAllIdApp = async function (idapp, code, id) {
let myfind = {};
let myqueryadd = {};
let query = [];
try {
if (idapp)
myfind = {
idapp,
$or: [
{ deleted: { $exists: false } },
{ deleted: false }
]
};
if (code) {
myfind = { ...myfind, code }
}
if (id) {
myqueryadd = {
$addFields: {
myId1: {
$toObjectId: id,
},
},
}
myfind = {
$expr: {
$eq: ["$_id", "$myId1"],
},
}
query.push(myqueryadd);
}
query.push(
{ $match: myfind },
{
$lookup: {
from: 'catprods',
localField: 'idCatProds',
foreignField: '_id',
as: 'catprods'
}
},
{
$lookup: {
from: 'authors',
localField: 'idAuthors',
foreignField: '_id',
as: 'authors'
}
},
{
$lookup: {
from: 'collanas',
localField: 'idCollana',
foreignField: '_id',
as: 'collana'
}
},
{
$lookup: {
from: 'publishers',
localField: 'idPublisher',
foreignField: '_id',
as: 'publisher'
}
},
{
$lookup: {
from: 'subcatprods',
localField: 'idSubCatProds',
foreignField: '_id',
as: 'subcatprods'
}
},
{
$sort: {
name: 1 // 1 for ascending order, -1 for descending order
}
},
);
let ris = await productInfo.aggregate(query)
return ris;
} catch (e) {
console.error('E', e);
}
};*/
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

View File

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

Some files were not shown because too many files have changed in this diff Show More