- 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

17
src/models/Event.js Normal file
View File

@@ -0,0 +1,17 @@
// @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);

63
src/models/Home.js Normal file
View File

@@ -0,0 +1,63 @@
// @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);

128
src/models/JobsInProgress.js Executable file
View File

@@ -0,0 +1,128 @@
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 };

27
src/models/PageView.js Executable file
View File

@@ -0,0 +1,27 @@
// /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);

16
src/models/Post.js Normal file
View File

@@ -0,0 +1,16 @@
// @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);

791
src/models/account.js Executable file
View File

@@ -0,0 +1,791 @@
/*
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 };

66
src/models/adtype.js Executable file
View File

@@ -0,0 +1,66 @@
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};

72
src/models/adtypegood.js Executable file
View File

@@ -0,0 +1,72 @@
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};

397
src/models/attivita.js Executable file
View File

@@ -0,0 +1,397 @@
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 };

57
src/models/author.js Executable file
View File

@@ -0,0 +1,57 @@
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;
});

127
src/models/booking.js Executable file
View File

@@ -0,0 +1,127 @@
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 };

213
src/models/bot.js Executable file
View File

@@ -0,0 +1,213 @@
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 };

84
src/models/calzoom.js Executable file
View File

@@ -0,0 +1,84 @@
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 };

273
src/models/cart.js Executable file
View File

@@ -0,0 +1,273 @@
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;
});

74
src/models/cashCategory.js Executable file
View File

@@ -0,0 +1,74 @@
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;
});
}

76
src/models/cashSubCategory.js Executable file
View File

@@ -0,0 +1,76 @@
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; });

62
src/models/catai.js Executable file
View File

@@ -0,0 +1,62 @@
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;

343
src/models/catalog.js Executable file
View File

@@ -0,0 +1,343 @@
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 };

59
src/models/category.js Executable file
View File

@@ -0,0 +1,59 @@
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 };

88
src/models/catgrp.js Executable file
View File

@@ -0,0 +1,88 @@
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 };

182
src/models/catprod.js Executable file
View File

@@ -0,0 +1,182 @@
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;

52
src/models/cfgserver.js Executable file
View File

@@ -0,0 +1,52 @@
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};

1838
src/models/circuit.js Executable file

File diff suppressed because it is too large Load Diff

282
src/models/city.js Executable file
View File

@@ -0,0 +1,282 @@
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 };

129
src/models/collana.js Executable file
View File

@@ -0,0 +1,129 @@
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; });

60
src/models/contribtype.js Executable file
View File

@@ -0,0 +1,60 @@
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 };

176
src/models/cron.js Executable file
View File

@@ -0,0 +1,176 @@
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 };

50
src/models/department.js Executable file
View File

@@ -0,0 +1,50 @@
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();
};

59
src/models/destnewsletter.js Executable file
View File

@@ -0,0 +1,59 @@
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 };

114
src/models/discipline.js Executable file
View File

@@ -0,0 +1,114 @@
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 };

341
src/models/extralist.js Executable file
View File

@@ -0,0 +1,341 @@
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 };

70
src/models/gallery.js Executable file
View File

@@ -0,0 +1,70 @@
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 };

84
src/models/gasordine.js Executable file
View File

@@ -0,0 +1,84 @@
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; });

88
src/models/good.js Executable file
View File

@@ -0,0 +1,88 @@
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 };

421
src/models/graduatoria.js Executable file
View File

@@ -0,0 +1,421 @@
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 };

53
src/models/group.js Executable file
View File

@@ -0,0 +1,53 @@
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; });

232
src/models/hours.js Executable file
View File

@@ -0,0 +1,232 @@
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; });

66
src/models/importadescr.js Executable file
View File

@@ -0,0 +1,66 @@
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;
}
};

66
src/models/importaisbn.js Executable file
View File

@@ -0,0 +1,66 @@
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;
}
};

68
src/models/importamacro.js Executable file
View File

@@ -0,0 +1,68 @@
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;
}
};

58
src/models/inventariogm.js Executable file
View File

@@ -0,0 +1,58 @@
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);
};

200
src/models/iscrittiConacreis.js Executable file
View File

@@ -0,0 +1,200 @@
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; });

79
src/models/level.js Executable file
View File

@@ -0,0 +1,79 @@
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};

127
src/models/mailinglist.js Executable file
View File

@@ -0,0 +1,127 @@
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 };

1087
src/models/movement.js Executable file

File diff suppressed because it is too large Load Diff

132
src/models/msg_template.js Executable file
View File

@@ -0,0 +1,132 @@
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 };

373
src/models/mybacheca.js Executable file
View File

@@ -0,0 +1,373 @@
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 };

586
src/models/myelem.js Executable file
View File

@@ -0,0 +1,586 @@
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');
try {
const pages = await MyPage.find({ idapp });
if (pages.length === 0) {
return 'Nessuna pagina trovata per questo idapp.';
}
const bulkOps = [];
pages.forEach((page) => {
if (page.path) {
// Aggiorna documenti con 'path'
bulkOps.push({
updateMany: {
filter: { idapp: idapp, path: page.path },
update: {
$set: { idPage: page._id, oldpath: page.path },
$unset: { path: '' },
},
},
});
// Aggiorna documenti con 'oldpath' ma senza 'idPage'
bulkOps.push({
updateMany: {
filter: {
idapp: idapp,
oldpath: page.path,
idPage: { $exists: false },
},
update: { $set: { idPage: page._id } },
},
});
}
});
if (bulkOps.length > 0) {
const result = await MyElem.bulkWrite(bulkOps);
console.log(`Aggiornati ${result.modifiedCount} documenti.`);
return `Aggiornamenti effettuati: ${result.modifiedCount} documenti.`;
}
return 'Nessun documento da aggiornare.';
} catch (error) {
console.error("Errore durante l'aggiornamento:", error);
throw 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 };

286
src/models/myevent.js Executable file
View File

@@ -0,0 +1,286 @@
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};

375
src/models/mygood.js Executable file
View File

@@ -0,0 +1,375 @@
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 };

666
src/models/mygroup.js Executable file
View File

@@ -0,0 +1,666 @@
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 };

390
src/models/myhosp.js Executable file
View File

@@ -0,0 +1,390 @@
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 };

261
src/models/mypage.js Executable file
View File

@@ -0,0 +1,261 @@
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 };

174
src/models/myscheda.js Executable file
View File

@@ -0,0 +1,174 @@
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 };

99
src/models/myscrapingbook.js Executable file
View File

@@ -0,0 +1,99 @@
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 };

376
src/models/myskill.js Executable file
View File

@@ -0,0 +1,376 @@
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 };

176
src/models/newstosent.js Executable file
View File

@@ -0,0 +1,176 @@
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 };

118
src/models/operator.js Executable file
View File

@@ -0,0 +1,118 @@
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 };

49
src/models/opzemail.js Executable file
View File

@@ -0,0 +1,49 @@
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 };

709
src/models/order.js Executable file
View File

@@ -0,0 +1,709 @@
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 !!!

1185
src/models/orderscart.js Executable file

File diff suppressed because it is too large Load Diff

52
src/models/paymenttype.js Executable file
View File

@@ -0,0 +1,52 @@
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 };

63
src/models/permission.js Executable file
View File

@@ -0,0 +1,63 @@
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 };

58
src/models/pickup.js Executable file
View File

@@ -0,0 +1,58 @@
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;
},
};

107
src/models/producer.js Executable file
View File

@@ -0,0 +1,107 @@
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; });

1439
src/models/product.js Executable file

File diff suppressed because it is too large Load Diff

305
src/models/productInfo.js Executable file
View File

@@ -0,0 +1,305 @@
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; });

434
src/models/project.js Executable file
View File

@@ -0,0 +1,434 @@
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 };

1
src/models/prova.htm Normal file
View File

@@ -0,0 +1 @@
<div class="landing" data-v-313f9fef=""><section data-v-313f9fef=""><div class="row justify-between items-start q-col-gutter-sm" data-v-313f9fef=""><div class="col-12" data-v-313f9fef=""><div class="feature-item" data-v-313f9fef="" style="margin-top: 0px !important;"><div class="text-big" data-v-313f9fef="" style="margin: 0px !important; padding: 2px !important;">Come posso sostenere il progetto <b>Riso.app</b>?</div><p class="feat-descr" data-v-313f9fef=""></p><ul class="mylist" style="padding-left: 20px;"><li>📱<b>Condividendo la APP</b> a tutti coloro che vogliono far parte insieme della crescita e sviluppo di una Nuova Era.</li><li>👥 Aiutando a creare Gruppi Territoriali nella vostra città, impegnandosi a realizzare progetti per il Bene Comune, in onore ai principi Amorevoli e di condivisione.</li><li>🌱 Sostenendo le persone attorno a voi, e rispettando la nostra vera Casa: Madre Natura e Tutti gli Esseri Viventi. ❤️</li><li>👨🏻‍💻 Con una <b>piccola donazione</b> per le spese dei Server, manutenzione e per i continui sviluppi e miglioramenti.</li></ul>1) Tramite <b><a href="https://paypal.me/paoloarena" target="_blank"><font size="4">Paypal</font></a></b><br>2) Tramite <b><a href="https://www.satispay.com/app/match/link/money-box/S6Y-SVN--62712D42-35B0-4BB9-8511-410C2AB8CD45" target="_blank"><font size="4">Satispay</font></a></b><br>In alternativa scegli tu una forma di scambio (auto-produzioni di cibo) da donare (per info: <a href="https://t.me/surya1977" target="_blank">Surya Paolo</a>)<br><span style="color: red; font-size: 2rem;"></span>&nbsp;<br>Grazie Mille per l'Aiuto ed il Supporto<br><p></p></div><div class="feature-item" data-v-313f9fef="" style="margin-top: 0px !important;"><br></div></div></div></section></div>

65
src/models/provider.js Executable file
View File

@@ -0,0 +1,65 @@
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 providerSchema = new Schema({
idapp: {
type: String,
},
name: {
type: String,
},
description: {
type: String,
},
referent: {
type: String,
},
address: {
type: String,
},
city: {
type: String,
},
region: {
type: String,
},
img: {
type: String,
},
website: {
type: String,
},
});
var Provider = module.exports = mongoose.model('Provider', providerSchema);
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 Provider.find(myfind);
};
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

162
src/models/province.js Executable file
View File

@@ -0,0 +1,162 @@
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 shared_consts = require('../tools/shared_nodejs');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin((schema) => {
schema.options.usePushEach = true;
});
const ProvinceSchema = new Schema(
{
_id: {
type: Number,
},
reg: {
type: String,
},
prov: {
type: String,
// unique: true,
maxlength: 3,
},
idCircuitToAssign: {
type: String,
},
descr: {
type: String,
},
link_grp: {
type: String,
},
card: {
type: String,
},
link_telegram: {
type: String,
},
lat: {
type: Number,
},
long: {
type: Number,
},
},
{ _id: false }
);
ProvinceSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await Province.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();
});
ProvinceSchema.statics.getRegionByStrProvince = async function (strprovince) {
const myrec = await Province.findOne({ prov: strprovince }).lean();
if (myrec) {
return myrec.reg;
}
return '';
};
ProvinceSchema.statics.getStrProvinceByProv = async function (prov) {
const myrec = await Province.findOne({ prov }).lean();
if (myrec) {
return myrec.descr;
}
return '';
};
ProvinceSchema.statics.getFieldsForSearch = function () {
return [
{ field: 'prov', type: tools.FieldType.string },
{ field: 'descr', type: tools.FieldType.string },
];
};
ProvinceSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
const strfind = params.search;
if (strfind === '') {
return [];
}
return tools.executeQueryTable(this, 0, params);
};
ProvinceSchema.statics.executeQueryPickup = async function (idapp, params) {
const strfind = params.search;
if (strfind === '') {
return [];
}
let filterfindexact = { descr: strfind };
const risexact = await Province.find(filterfindexact).lean();
let filterfind = {};
filterfind = { descr: { $regex: '^' + strfind, $options: 'i' } };
const ris = await Province.find(filterfind).lean().limit(10);
return [...risexact, ...ris];
};
ProvinceSchema.statics.findAllIdApp = async function (idapp) {
const myfind = {};
return Province.find(myfind).sort({ descr: 1 }).lean();
};
ProvinceSchema.statics.setCoordinatesOnDB = async function () {
const arrprov = await Province.find({}).lean();
// Funzione per ottenere le coordinate di tutte le città
for (const prov of arrprov) {
if (!prov.lat) {
let coord = await tools.getCityCoordinates(prov);
if (coord) {
let ris = await Province.findOneAndUpdate(
{ _id: prov._id },
{ $set: { lat: coord.lat, long: coord.long } },
{ new: true }
);
console.log(' *** Update ', prov.descr, 'lat', ris.lat, 'long', ris.long);
}
}
}
};
const Province = mongoose.model('Province', ProvinceSchema);
Province.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports = { Province };

119
src/models/publisher.js Executable file
View File

@@ -0,0 +1,119 @@
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 PublisherSchema = new Schema({
idapp: {
type: String,
},
name: {
type: String,
},
link: {
type: String,
},
img: {
type: String,
},
quanti: {
type: Number,
},
});
var Publisher = module.exports = mongoose.model('Publisher', PublisherSchema);
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 Publisher.find(myfind).sort({ name: 1 }).lean();
};
module.exports.getEditoriWithTitleCount = async function (idapp, updatedata) {
try {
const myquery = [
{ $match: { idapp } },
{
$lookup: {
from: 'products', // Nome della tua collezione productInfo
localField: '_id',
foreignField: 'productInfo.idPublisher',
as: 'products'
}
},
{
$addFields: {
myproducts: {
$filter: {
input: "$products",
as: "prod",
cond: {
$in: ["$$prod.productInfo.idStatoProdotto", [1, 4, 34, 45, 46]]
}
}
}
}
}, {
$project: {
_id: 1,
name: 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: { name: 1 } } // Ordina i risultati per nome
];
const result = await Publisher.aggregate(myquery);
if (updatedata) {
for (const record of result) {
await Publisher.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; });

89
src/models/queryai.js Executable file
View File

@@ -0,0 +1,89 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
// const CatAI = require('./catai');
const { ObjectId } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const OpenAI = require("openai");
const QueryAISchema = new Schema({
idapp: {
type: String,
},
descr: {
type: String,
},
catAI: { type: Schema.Types.ObjectId, ref: 'CatAI' },
query: {
type: String,
},
ask: [
{
descr: {
type: String,
},
value: {
type: Number,
},
}
],
buttons: [
{
type: String, //ButtonCodeAction
},
],
output_type: {
type: String,
},
icon: {
type: String,
},
img: {
type: String,
},
});
QueryAISchema.statics.findAllIdApp = async function (idapp) {
const QueryAI = this;
const query = [
{ $sort: { descr: 1 } }
];
return await QueryAI
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
QueryAISchema.statics.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }]
};
QueryAISchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
const QueryAI = mongoose.model('QueryAI', QueryAISchema);
QueryAI.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { QueryAI };

100
src/models/raccoltacataloghi.js Executable file
View File

@@ -0,0 +1,100 @@
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 RaccoltaCataloghiSchema = new Schema({
idapp: {
type: String,
},
active: {
type: Boolean,
default: false,
},
title: {
type: String,
index: true,
},
foto_raccolta: IImg,
idPageAssigned: {
type: String,
},
pdf_copertina: IImg,
nomefile_da_generare: String,
pdf_generato: String,
pdf_generato_size: String,
pdf_generato_stampa: String,
data_generato: {
type: Date,
},
data_generato_stampa: {
type: Date,
},
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,
},
lista_cataloghi: [
{
type: Schema.Types.ObjectId,
ref: 'Catalog',
},
],
});
RaccoltaCataloghiSchema.statics.getFieldsForSearch = function () {
return [{ field: 'title', type: tools.FieldType.string }];
};
RaccoltaCataloghiSchema.statics.executeQueryTable = function (idapp, params, user) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params, user);
};
RaccoltaCataloghiSchema.statics.findAllIdApp = async function (idapp) {
const RaccoltaCataloghi = this;
try {
let arrrec = await RaccoltaCataloghi.find({ idapp }).sort({ title: 1 })
.populate({
path: 'lista_cataloghi',
select: '-lista_prodotti',
}).lean();
return arrrec;
} catch (err) {
console.error('Errore: ', err);
}
};
const RaccoltaCataloghi = mongoose.model('RaccoltaCataloghi', RaccoltaCataloghiSchema);
RaccoltaCataloghi.createIndexes()
.then(() => {})
.catch((err) => {
throw err;
});
module.exports = { RaccoltaCataloghi };

441
src/models/reaction.js Executable file
View File

@@ -0,0 +1,441 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const i18n = require('i18n');
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 reactionSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String,
},
username: {
type: String,
},
idrec: {
type: String,
},
tab: {
type: Number,
},
fav: {
type: Boolean,
},
book: {
type: Boolean,
},
seen: {
type: Boolean,
},
attend: {
type: Boolean,
},
});
reactionSchema.statics.getFieldsForReactions = function () {
let reactionsField = {
numseen: {
type: Number,
},
numbook: {
type: Number,
},
numfav: {
type: Number,
},
numattend: {
type: Number,
},
};
return reactionsField;
};
reactionSchema.statics.getReactionsCounts = async function (mytable, idapp, idrec, numtab) {
let query = [];
try {
query =
[
{
$match: {
_id: idrec,
},
},
{
$lookup: {
from: "reactions",
let: {
tab: numtab,
id: '$_id',
},
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$idrec', idrec] },
{ $eq: ['$tab', numtab] },
{ $eq: ['$idapp', idapp] },
],
},
},
},
{
$group: {
_id: "$idrec",
numseen: {
$sum: {
$cond: {
if: { $ifNull: ["$seen", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
}
},
numfav: {
$sum: {
$cond: {
if: { $ifNull: ["$fav", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
}
},
numbook: {
$sum: {
$cond: {
if: { $ifNull: ["$book", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
}
},
numattend: {
$sum: {
$cond: {
if: { $ifNull: ["$attend", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
}
}
},
},
],
as: 'myreact',
},
},
{
$unwind: {
path: "$myreact",
preserveNullAndEmptyArrays: true,
},
},
];
const ris = await mytable.aggregate(query);
return ris ? ris[0]: null;
} catch (e) {
}
};
reactionSchema.statics.updateReactionsCounts = async function () {
const globalTables = require('../tools/globalTables');
console.log('INIZIO - updateReactionsCounts');
try {
for (const tablestr of shared_consts.TABLES_REACTIONS) {
const numtab = tools.getNumTabByTable(tablestr);
const mytable = globalTables.getTableByTableName(tablestr);
const arrrec = await mytable.find({});
console.log(' updateReactionsCounts tabella', tablestr);
for (const rec of arrrec) {
// Calcola
const ris = await Reaction.getReactionsCounts(mytable, idapp, rec._id, numtab);
if (ris && ris.myreact) {
risupdate = await mytable.updateOne({ _id: rec._id }, {
$set: {
numseen: ris.myreact.numseen ?? 0,
numfav: ris.myreact.numfav ?? 0,
numbook: ris.myreact.numbook ?? 0,
numattend: ris.myreact.numattend ?? 0,
}
})
}
}
}
console.log('FINE - updateReactionsCounts');
} catch (err) {
console.error(err);
}
};
;
reactionSchema.statics.getFieldsForSearch = function () {
return [
{ field: 'username', type: tools.FieldType.string }];
};
reactionSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
reactionSchema.statics.calcReactions = async function (idapp, id, tab) {
try {
let myquerycountreaction = [
{
$match: {
idapp,
idrec: id,
tab,
},
},
{
$group: {
_id: null,
numseen: {
$sum: {
$cond: {
if: { $ifNull: ["$seen", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
}
},
numfav: {
$sum: {
$cond: {
if: { $ifNull: ["$fav", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
}
},
numbook: {
$sum: {
$cond: {
if: { $ifNull: ["$book", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
}
},
numattend: {
$sum: {
$cond: {
if: { $ifNull: ["$attend", false] }, // Check if the field exists and is not null
then: 1, // Increment count by 1 if the field exists
else: 0, // Otherwise, keep the count unchanged
}
}
}
},
},
];
return await Reaction.aggregate(myquerycountreaction)
.then((ris) => {
return ris ? ris[0] : null;
});
} catch (err) {
console.error(err);
}
};
// Aggiungo il Favorite
reactionSchema.statics.addFavorite = async function (req, idapp, username, id, tab) {
let ris = null;
try {
let ok = false;
const myrec = await Reaction.findOne({ idrec: id, idapp, username });
if (!myrec) {
const myrec = new Reaction({ idrec: id, idapp, userId: req.user.id, username, tab, fav: true });
ris = await myrec.save();
ok = ris ? 1 : 0;
} else {
ris = await Reaction.updateOne({ idrec: id, idapp, username }, {
$set: {
fav: true,
}
})
ok = ris.acknowledged;
}
const { SendNotif } = require('../models/sendnotif');
const globalTables = require('../tools/globalTables');
// Invia una Notifica al Destinatario
const recObjCreator = await globalTables.getUserCreatorByNumTabAndId(idapp, id, tab);
if (recObjCreator) {
await SendNotif.createNewNotifToSingleUser(req, null, { usernameDest: recObjCreator.username, recObjCreator, username_action: req.user.username }, false, shared_consts.TypeNotifs.TYPEDIR_FAVORITE,
shared_consts.TypeNotifs.ID_FAVORITE_ADDED);
}
return ris;
} catch (e) {
console.error('Err addFavorite', e);
return null;
}
};
// Aggiungo il Seen
reactionSchema.statics.addSeen = async function (req, idapp, username, id, tab) {
const myrec = await Reaction.findOne({ idrec: id, idapp, username });
if (!myrec) {
const myrec = new Reaction({ idrec: id, idapp, userId: req.user.id, username, tab, seen: true });
return await myrec.save()
.then((ris) => {
// console.log('salvato proj!');
return ris;
})
.catch(err => {
console.log("Error addSeen", err.message);
});
} else {
return Reaction.updateOne({ _id: myrec._id }, {
$set: {
seen: true,
}
})
}
};
// Aggiungo il Bookmark
reactionSchema.statics.addBookmark = async function (req, idapp, username, id, tab) {
const myrec = await Reaction.findOne({ idrec: id, idapp, username });
if (!myrec) {
const myrec = new Reaction({ idrec: id, idapp, userId: req.user.id, username, tab, book: true });
return await myrec.save()
.then((ris) => {
return ris;
})
.catch(err => {
console.log("Error addBookmark", err.message);
});
} else {
return Reaction.updateOne({ _id: myrec._id }, {
$set: {
book: true,
}
})
}
};
// Aggiungo il Attend
reactionSchema.statics.addAttend = async function (req, idapp, username, id, tab) {
const myrec = await Reaction.findOne({ idrec: id, idapp, username });
if (!myrec) {
const myrec = new Reaction({ idrec: id, idapp, userId: req.user.id, username, tab, attend: true });
return await myrec.save()
.then((ris) => {
return ris;
})
.catch(err => {
console.log("Error addAttend", err.message);
});
} else {
return Reaction.updateOne({ _id: myrec._id }, {
$set: {
attend: true,
}
})
}
};
// Rimuovo il Favorite
reactionSchema.statics.removeFavorite = async function (
idapp, username, id, tab) {
const myrec = await Reaction.findOne({ idrec: id, idapp, username });
if (myrec) {
return Reaction.updateOne({ _id: myrec._id }, {
$set: {
fav: false,
}
})
}
return false;
};
// Rimuovo il Bookmark
reactionSchema.statics.removeBookmark = async function (
idapp, username, id, tab) {
const myrec = await Reaction.findOne({ idrec: id, idapp, username });
if (myrec) {
return Reaction.updateOne({ _id: myrec._id }, {
$set: {
book: false,
}
})
}
return false;
};
const Reaction = mongoose.model('Reaction', reactionSchema);
Reaction.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Reaction };

69
src/models/scontistica.js Executable file
View File

@@ -0,0 +1,69 @@
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 scontisticaSchema = new Schema({
idapp: {
type: String,
},
attivo: {
type: Boolean,
},
code: {
type: String,
},
description: {
type: String,
},
qta: {
type: Number,
},
perc_sconto: {
type: Number,
},
price: {
type: Number,
},
applica: {
type: Number,
},
comulativo: {
type: Boolean,
default: false,
},
});
var Scontistica = module.exports = mongoose.model('Scontistica', scontisticaSchema);
module.exports.getFieldsForSearch = function () {
return [
{ field: 'code', 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, attivo: true };
return await Scontistica.find(myfind);
};
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

52
src/models/search.js Executable file
View File

@@ -0,0 +1,52 @@
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 searchSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String,
},
date_created: {
type: Date,
default: Date.now,
},
text: {
type: String,
},
});
searchSchema.statics.findAllByUserIdAndIdApp = function (userId, idapp, sall) {
const Search = this;
let myfind = {};
if (sall === '1')
myfind = { idapp };
else
myfind = { userId, idapp };
return Search.find(myfind).lean();
};
const Search = mongoose.model('Search', searchSchema);
Search.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Search };

83
src/models/sector.js Executable file
View File

@@ -0,0 +1,83 @@
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 SectorSchema = new Schema({
_id: {
type: Number,
},
descr: {
type: String,
},
idSector: {
type: Number
},
icon: {
type: String,
},
img: {
type: String,
},
color: {
type: String,
},
theme: {
type: String,
},
});
SectorSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await Sector.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();
});
SectorSchema.statics.findAllIdApp = async function (idapp) {
const Sector = this;
const query = [
{ $sort: { descr: 1 } }
];
return Sector
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
SectorSchema.statics.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }]
};
SectorSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const Sector = mongoose.model('Sector', SectorSchema);
module.exports = { Sector };

88
src/models/sectoractivities.js Executable file
View File

@@ -0,0 +1,88 @@
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 SectorActivitiesSchema = new Schema({
_id: {
type: Number,
},
descr: {
type: String,
},
idSectorActivities: {
type: Number
},
icon: {
type: String,
},
img: {
type: String,
},
color: {
type: String,
},
theme: {
type: String,
},
});
SectorActivitiesSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await SectorActivities.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();
});
SectorActivitiesSchema.statics.findAllIdApp = async function (idapp) {
const SectorActivities = this;
const query = [
{ $sort: { descr: 1 } }
];
return await SectorActivities
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
SectorActivitiesSchema.statics.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }]
};
SectorActivitiesSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const SectorActivities = mongoose.model('SectorActivities', SectorActivitiesSchema);
SectorActivities.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { SectorActivities };

88
src/models/sectorgood.js Executable file
View File

@@ -0,0 +1,88 @@
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 SectorGoodSchema = new Schema({
_id: {
type: Number,
},
descr: {
type: String,
},
idSectorGood: {
type: Number
},
icon: {
type: String,
},
img: {
type: String,
},
color: {
type: String,
},
theme: {
type: String,
},
});
SectorGoodSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await SectorGood.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();
});
SectorGoodSchema.statics.findAllIdApp = async function (idapp) {
const SectorGood = this;
const query = [
{ $sort: { descr: 1 } }
];
return await SectorGood
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
SectorGoodSchema.statics.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }]
};
SectorGoodSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const SectorGood = mongoose.model('SectorGood', SectorGoodSchema);
SectorGood.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { SectorGood };

117
src/models/sendmsg.js Executable file
View File

@@ -0,0 +1,117 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { ObjectId } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const sendmsgSchema = new Schema({
idapp: {
type: String,
},
source: {
page: { type: String },
event_id: { type: String },
infoevent: { type: String }
},
origin: {
type: String,
},
dest: {
type: String,
},
message: {
type: String,
},
datemsg: {
type: Date,
},
status: {
type: Number,
},
typesend: {
type: Number,
},
read: {
type: Boolean,
default: false
},
deleted: {
type: Boolean,
default: false
},
});
sendmsgSchema.statics.findAllMsgByUsernameIdAndIdApp = function (username, lastdataread, idapp) {
const SendMsg = this;
return SendMsg.find({
$and: [
{ $or: [ { 'dest': username }, { 'origin': username },] },
{ 'datemsg': {$gt: new Date(lastdataread)} },
{ idapp }
]
}).then((arrmsg) => {
console.log('arrmsg', arrmsg.length);
return arrmsg
}).catch((err) => {
console.error('err', err);
});
};
sendmsgSchema.statics.findLastGroupByUserIdAndIdApp = function (userId, username, idapp) {
const SendMsg = this;
return SendMsg.aggregate([
{
$match: {
$or: [{ 'origin': username }, { 'dest': username }, { idapp }],
$and: [{ idapp }]
}
},
{
$group:
{
_id: "$dest",
message: { $last: "$message" },
datemsg: { $last: "$datemsg" },
dest: { $last: "$dest" },
origin: { $last: "$origin" },
read: { $last: "$read" }
}
},
{
$sort: { datemsg: -1 }
},
])
.then((arrmsg) => {
// Remove duplicate
// Exclude my chat
const myarr = arrmsg.filter((ris) => ris._id !== username);
// console.table(myarr);
return myarr
}).catch((err) => {
console.error(err);
});
};
const SendMsg = mongoose.model('SendMsg', sendmsgSchema);
SendMsg.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { SendMsg };

1697
src/models/sendnotif.js Executable file

File diff suppressed because it is too large Load Diff

188
src/models/settings.js Executable file
View File

@@ -0,0 +1,188 @@
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 SettingsSchema = new Schema({
idapp: {
type: String,
},
key: {
type: String,
},
type: {
type: Number,
},
value_str: {
type: String,
},
value_date: {
type: Date,
},
value_num: {
type: Number,
},
value_bool: {
type: Boolean,
},
serv: {
type: Boolean,
default: false
},
crypted: {
type: Boolean,
default: false
}
});
SettingsSchema.statics.getFieldsForSearch = function () {
return [{ field: 'key', type: tools.FieldType.string },
{ field: 'value_str', type: tools.FieldType.string }, { field: 'value_num', type: tools.FieldType.number }]
};
SettingsSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
SettingsSchema.statics.getValDbSettings = function (idapp, key, def) {
return Settings.findOne({ idapp, key })
.then((myrec) => {
// console.log('getValDbSettings', myrec, 'idapp', idapp);
if (!!myrec) {
if (myrec.type === tools.FieldType.date)
return myrec.value_date;
else if ((myrec.type === tools.FieldType.number) || (myrec.type === tools.FieldType.hours))
return myrec.value_num;
else if (myrec.type === tools.FieldType.boolean)
return myrec.value_bool;
else if (myrec.type === tools.FieldType.crypted)
return tools.decryptdata(myrec.value_str);
else
return myrec.value_str;
} else {
return def
}
}).catch((err) => {
console.error('getValDbSettings', err);
return def;
});
};
SettingsSchema.statics.DuplicateAllRecords = async function (idapporig, idappdest) {
return await tools.DuplicateAllRecords(this, idapporig, idappdest);
};
SettingsSchema.statics.findAllIdApp = async function (idapp, serv, crypted = false) {
const Settings = this;
try {
let myfind = '';
if (serv) {
myfind = { idapp, serv };
} else
myfind = { idapp };
// myfind = {...myfind, $or: [{ crypted: { $exists: false } }, { crypted: { $exists: true, $eq: crypted } }]};
const arrorig = await Settings.find(myfind).lean();
let myarr = []
if (!crypted) {
for (let rec of arrorig) {
if (rec.crypted) {
rec.value_str = ''
}
myarr.push({ ...rec });
}
} else {
myarr = [...arrorig];
}
return myarr;
} catch (e) {
console.error('Settings: findAllIdApp', e);
return null;
}
};
SettingsSchema.statics.setKeyNum = async function (idapp, key, value) {
const Settings = this;
let myrec = await Settings.findOne({ idapp, key });
if (!myrec) {
myrec = new Settings({ key });
myrec._id = new ObjectId();
myrec.idapp = idapp;
myrec.type = tools.FieldType.number;
myrec.value_num = value;
return await myrec.save();
} else {
myrec = await Settings.findOneAndUpdate({ idapp, key },
{ $set: { value_num: value } },
{ new: false });
}
return myrec
};
SettingsSchema.statics.setBool = async function (idapp, key, valbool) {
const Settings = this;
let myrec = await Settings.findOne({ idapp, key });
if (!myrec) {
myrec = new Settings({ key });
myrec._id = new ObjectId();
myrec.idapp = idapp;
myrec.type = tools.FieldType.boolean;
myrec.value_bool = valbool;
return await myrec.save();
} else {
myrec = await Settings.findOneAndUpdate({ idapp, key }, { $set: { value_bool: valbool } }, { new: false });
}
return myrec
};
SettingsSchema.statics.getKeyNum = async function (idapp, key, mydefault) {
const Settings = this;
const ret = await Settings.findOne({ idapp, key });
if (!!ret) {
return ret.value_num;
} else {
return mydefault;
}
};
const Settings = mongoose.model('Settings', SettingsSchema);
Settings.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Settings };

53
src/models/sharewithus.js Executable file
View File

@@ -0,0 +1,53 @@
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 ShareWithUsSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String,
},
description: {
type: String,
},
numshared: {
type: Number,
},
rating: {
type: Number,
},
});
var ShareWithUs = module.exports = mongoose.model('ShareWithUs', ShareWithUsSchema);
module.exports.getFieldsForSearch = function () {
return [{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 ShareWithUs.find(myfind);
};
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

438
src/models/site.js Executable file
View File

@@ -0,0 +1,438 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
mongoose.set('debug', false);
const { ObjectId } = require('mongodb');
const shared_consts = require('../tools/shared_nodejs');
const _ = require('lodash');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const SiteSchema = new Schema({
active: {
type: Boolean,
},
idapp: {
type: String,
},
name: {
type: String,
},
adminemail: {
type: String,
},
manageremail: {
type: String,
},
replyTo: {
type: String,
},
host: {
type: String,
},
host_ip: {
type: String,
},
host_test: {
type: String,
},
host_test_ip: {
type: String,
},
host_api: {
type: String,
},
host_api_ip: {
type: String,
},
host_testapi: {
type: String,
},
host_testapi_ip: {
type: String,
},
cf_token: {
type: String,
},
cf_zoneId: {
type: String,
},
servermail: {
type: String,
},
servermailip: {
type: String,
},
dkim: {
type: String,
},
enable_servermail: {
type: Boolean,
},
portapp: {
type: String,
},
dir: {
type: String,
},
dir_test: {
type: String,
},
email_from: {
type: String,
},
email_pwd: {
type: String,
},
telegram_key: {
type: String,
},
telegram_bot_name: {
type: String,
},
telegram_key_test: {
type: String,
},
load_process_telegram: {
type: Boolean,
},
load_process_telegram_test: {
type: String,
},
teleg_cfg: {
type: String,
},
teleg_cfg_test: {
type: String,
},
telegram_bot_name_test: {
type: String,
},
telegram_support_chat: {
type: String,
},
pathreg_add: {
type: String,
},
who: {
type: String
},
status: {
type: String
},
note: {
type: String
},
domain_provider: {
type: String,
},
domain_expiring: {
type: Date
},
next_payment: {
type: Date
},
description: {
type: String,
},
keywords: {
type: String,
},
confpages: {
font: { type: String, default: '' },
col_toolbar: { type: String, default: '' },
col_bgfooter: { type: String, default: '' },
show_darkopt: { type: Boolean, default: false },
showButtHome: { type: Boolean, default: false },
showProfile: { type: Boolean, default: false },
showUserMenu: { type: Boolean, default: true },
showiscrittiMenu: { type: Boolean, default: false },
showRegButton: { type: Boolean, default: false },
enableReg: { type: Boolean, default: false },
showNL: { type: Boolean, default: false },
sendNewsletter: { type: Boolean, default: false },
showMsgs: { type: Boolean, default: false },
showNotif: { type: Boolean, default: false },
showCoins: { type: Boolean, default: false },
showRIS: { type: Boolean, default: false },
showMenuCoins: { type: Boolean, default: false },
showNameSurname: { type: Boolean, default: false },
showCompetenze: { type: Boolean, default: false },
showConnected: { type: Boolean, default: false },
bookingEvents: { type: Boolean, default: false },
enableEcommerce: { type: Boolean, default: false },
enableAI: { type: Boolean, default: false },
enableGroups: { type: Boolean, default: false },
enableCircuits: { type: Boolean, default: false },
enableGoods: { type: Boolean, default: false },
enableServices: { type: Boolean, default: false },
enableActivities: { type: Boolean, default: false },
enableHosps: { type: Boolean, default: false },
enableEvents: { type: Boolean, default: false },
enableProj: { type: Boolean, default: false },
enableTodos: { type: Boolean, default: false },
enableRegByBot: { type: Boolean, default: false },
enableRegMultiChoice: { type: Boolean, default: false },
enableTokenExpired: { type: Boolean, default: false },
enableDebugOn: { type: Boolean, default: false },
enabledRegNeedTelegram: { type: Boolean, default: false },
showViewEventi: { type: Boolean, default: false },
showViewGroups: { type: Boolean, default: false },
showViewCircuits: { type: Boolean, default: false },
showViewUsers: { type: Boolean, default: false },
showViewBooking: { type: Boolean, default: false },
showViewProfile: { type: Boolean, default: false },
showViewCart: { type: Boolean, default: false },
showViewOrders: { type: Boolean, default: false },
enablePwa: { type: Boolean, default: false },
lang: {
type: Number,
default: 0,
},
videoPromo: { type: String, default: '' },
PDFPromo: { type: String, default: '' },
},
confsite: {
options: { // ConfSite
type: Number,
default: 0,
},
},
policy: {
show: { type: Boolean, default: false },
owneremail: { type: String },
siteName: { type: String },
ownerDataName: { type: String },
managerData: { type: String },
includeData: { type: String },
url: { type: String },
lastdataupdate: { type: String },
country: { type: String },
},
contacts: {
facebook: { type: String, default: '' },
instagram: { type: String, default: '' },
whatsapp: { type: String, default: '' },
whatsapp_home: { type: Boolean, default: false },
telegram: { type: String, default: '' },
youtube: { type: String, default: '' },
email: { type: String, default: '' },
address: { type: String, default: '' },
map: { type: String, default: '' },
info2: { type: String, default: '' },
cell: { type: String, default: '' },
},
ecomm: {
enablePreOrders: { type: Boolean, default: false },
NoteExtraOnCart: { type: String, default: '' },
},
idMyGroup: {
type: String,
},
});
var Site = module.exports = mongoose.model('Site', SiteSchema);
module.exports.getFieldsForSearch = function () {
return []
};
module.exports.executeQueryTable = async function (idapp, params, userreq) {
params.fieldsearch = this.getFieldsForSearch();
// return tools.executeQueryTable(this, null, params);
const { User } = require('../models/user');
// Solo l'Admin puó leggerlo
const extrapar = params.extrapar;
if (extrapar) {
if (User.isManager(userreq.perm)) {
return await Site.findOne({ idapp: extrapar }).lean();
} else {
return await Site.findOne({ idapp: extrapar }, {
name: 1, manageremail: 1,
confsite: 1,
description: 1,
keywords: 1,
}).lean();
}
}
if (User.isAdmin(userreq.perm)) {
const myarr = await Site.find({});
if (myarr.length === 0) {
/* {
"_id" : new ObjectId("620a71e194438ecd1acfdbca"),
"idapp" : "14",
"chiave" : "vers",
"userId" : "ALL",
"valore" : "0.3.21"
}*/
}
// return await Site.find({}).lean();
return ({ count: myarr.length, rows: myarr })
}
};
module.exports.findAll = async function () {
const myfind = { active: true };
return await Site.find(myfind).lean();
};
module.exports.findAllIdApp = async function (idapp) {
let myfind = { idapp, active: true };
let rec = await Site.findOne(myfind).lean();
if (rec) {
rec.email_pwd = '';
rec.telegram_key = '';
rec.telegram_key_test = '';
rec.cf_token = '';
rec.cf_zoneId = '';
// rec.confsite = {};
return rec;
} else {
myfind = { name: 'local' };
let rec = await Site.findOne(myfind).lean();
if (!rec) {
const mysite = new Site();
mysite.name = 'local';
await mysite.save();
mysite.idapp = idapp;
return mysite;
} else {
return rec;
}
}
return {};
};
module.exports.generateNewSite_IdApp = async function (idapp, params, createpage) {
const { MyPage } = require('../models/mypage');
let ris = null;
try {
if (idapp) {
ris = await Site.find({ idapp: idapp.toString(), host: params.host });
} else {
for (let idapp = 20; idapp <= 100; idapp++) {
ris = await Site.find({ idapp: idapp.toString(), host: params.host });
break;
}
}
if (ris && ris.length === 0) {
const paramSite = _.pick(params, ['name', 'host', 'email']);
let mysite = new Site(paramSite);
mysite.active = true;
mysite.idapp = idapp.toString();
mysite.adminemail = params.email;
const ris = await mysite.save();
if (createpage) {
// 1. Crea Pagina principale HOME - Loggato
let myp = new MyPage({
order: 10,
idapp: mysite.idapp,
path: 'home',
active: true,
title: 'Home',
});
let rispag = await myp.save();
// 2. Crea Pagina principale HOME - Non Loggato
myp = new MyPage({
order: 10,
idapp: mysite.idapp,
path: 'home_logout',
active: true,
title: 'Home NoLoggato',
});
rispag = await myp.save();
}
if (ris)
return mysite.idapp;
else
return '';
}
} catch (e) {
console.error(e);
}
return '';
};
module.exports.createFirstUserAdmin = async function () {
const { User } = require('../models/user');
const telegrambot = require('../telegram/telegrambot');
try {
let arrSite = await Site.find({ idapp: { $exists: true } }).lean();
for (const mysite of arrSite) {
if (mysite.idapp > 0) {
const numusers = await User.countDocuments({ idapp: mysite.idapp });
if (numusers === 0) {
// Non esistono utenti, quindi creo quello di Admin
console.error('❌❌❌❌ ***** Non esistono utenti, quindi creo quello di Admin ! app=', mysite.idapp);
const utenteadmin = { idapp: '13', username: shared_consts.ADMIN_USER_SERVER };
const newuser = new User(utenteadmin);
newuser._id = new ObjectId();
newuser.idapp = mysite.idapp;
newuser.profile.mygroups = [];
newuser.profile.mycircuits = [];
await newuser.save();
}
}
}
} catch (e) {
console.error('Error ', e);
}
};
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

86
src/models/skill.js Executable file
View File

@@ -0,0 +1,86 @@
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 SkillSchema = new Schema({
_id: {
type: Number,
},
descr: {
type: String,
},
idSector: [{
type: Number
}],
icon: {
type: String,
},
img: {
type: String,
},
});
SkillSchema.statics.findAllIdApp = async function (idapp) {
const Skill = this;
const query = [
{ $sort: { descr: 1 } }
];
return await Skill
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
SkillSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await Skill.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();
});
SkillSchema.statics.getFieldsForSearch = function () {
return [{ field: 'label', type: tools.FieldType.string },
{ field: 'descr', type: tools.FieldType.string }]
};
SkillSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const Skill = mongoose.model('Skill', SkillSchema);
Skill.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Skill };

185
src/models/stat.js Executable file
View File

@@ -0,0 +1,185 @@
const mongoose = require('mongoose').set('debug', false);
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = 'F';
const tools = require('../tools/general');
const { User } = require('../models/user');
const { Movement } = require('../models/movement');
const { Circuit } = require('../models/circuit');
const { MyGroup } = require('../models/mygroup');
const { Settings } = require('../models/settings');
const shared_consts = require('../tools/shared_nodejs');
const { ObjectId } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true;
});
const StatSchema = new Schema({
...{
_id: {
type: String,
},
idapp: {
type: String,
required: true,
},
num_reg: {
type: Number,
},
date_created: {
type: Date,
default: Date.now,
},
num_reg: Number,
num_reg_today: Number,
online_today: Number,
activeusers: Number,
num_teleg_attivo: Number,
num_autorizzati: Number,
num_autorizzare: Number,
num_teleg_pending: Number,
arr_nations: [],
numreg_untilday: Number,
reg_daily: [],
reg_weekly: [],
lastsreg: [],
lastsonline: [],
lastssharedlink: [],
diffusorilist: [],
receiveRislist: [],
receiveRislistgroup: [],
listlinksreg: [],
strettelist: [],
num_transaz_tot: Number,
tot_RIS_transati: Number,
num_circuiti: Number,
num_circuiti_attivi: Number,
num_annunci: Number,
last_transactions: [],
},
});
StatSchema.statics.updateStats = async function (idapp, datastat) {
datastat.last_transactions = await Movement.getLastN_Transactions(idapp, 5, 5);
return datastat;
};
StatSchema.statics.calculateStats = async function (idapp) {
const Stat = this;
try {
let datastat = {
idapp,
num_reg: await User.getUsersRegistered(idapp),
num_reg_today: await User.getUsersRegisteredToday(idapp),
online_today: await User.getUsersOnLineToday(idapp),
activeusers: await User.getUsersOnLineActive(idapp),
num_teleg_attivo: await User.getUsersTelegramAttivo(idapp),
num_autorizzati: await User.getUsersAutorizzati(idapp),
num_autorizzare: await User.getUsersAutorizzare(idapp),
num_teleg_pending: await User.getUsersTelegramPending(idapp),
arr_nations: await User.findAllDistinctNationality(idapp),
numreg_untilday: await User.calcnumRegUntilDay(idapp),
reg_daily: await User.calcRegDaily(idapp),
reg_weekly: await User.calcRegWeekly(idapp),
lastsreg: await User.getLastUsers(idapp),
lastsonline: await User.getLastOnlineUsers(idapp),
lastssharedlink: await User.getLastSharedLink(idapp),
diffusorilist: await User.getDiffusoriUsers(idapp),
listlinksreg: await User.getListLinkReg(idapp),
receiveRislist: await User.getReceiveRISUsers(idapp),
receiveRislistgroup: await MyGroup.getReceiveRISGroups(idapp),
strettelist: await User.getLastStretteDiManoUsers(idapp),
num_transaz_tot: await Movement.getTotal_Transactions(idapp),
tot_RIS_transati: await Movement.getTot_RIS_Transati(idapp),
num_circuiti: await Circuit.getnumCircuits(idapp),
num_circuiti_attivi: await Circuit.getnumActiveCircuits(idapp),
num_annunci: await User.getnumAnnunci(idapp),
};
// Trova il record di oggi:
const trova_se_oggi = await Stat.findOne({ idapp, date_created: { $gte: new Date(new Date().setHours(0, 0, 0, 0)) } }).lean();
if (trova_se_oggi) {
// Aggiorna il record di oggi:
const ris = await Stat.findOneAndUpdate(
{ _id: trova_se_oggi._id },
{ $set: datastat },
{ returnDocument: "after" });
// console.log('ris', ris);
} else {
// Aggiungi un nuovo record:
await Stat.insertMany([datastat]);
}
return datastat;
} catch (e) {
console.error('Error', e);
return null;
}
};
StatSchema.statics.getStats = async function (idapp) {
const Stat = this;
const minuti = await Settings.getValDbSettings(idapp, 'NUMMINUTI_STAT', 30);
// Ottieni l'ultimo record salvato:
const rec = await Stat.findOne({ idapp })
.sort({ date_created: -1 })
.lean();
let isOld = true;
if (rec) {
// se rec.date_created è più vecchio di minuti fa, allora ricalcola.
const dateCreated = new Date(rec.date_created);
const now = new Date();
// Calcola la differenza in millisecondi
const difference = now - dateCreated; // Differenza in millisecondi
// Controlla se la differenza è maggiore di 10 minuti (10 * 60 * 1000 ms)
isOld = (difference > minuti * 60 * 1000);
}
let datastat = null;
if (tools.testing()) {
isOld = true;
}
if (isOld) {
datastat = await Stat.calculateStats(idapp);
} else {
datastat = rec;
}
datastat = await Stat.updateStats(idapp, datastat);
return datastat;
};
const Stat = mongoose.model('Stat', StatSchema);
Stat.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { Stat };

83
src/models/statusSkill.js Executable file
View File

@@ -0,0 +1,83 @@
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 StatusSkillSchema = new Schema({
_id: {
type: Number,
},
descr: {
type: String,
},
color: {
type: String,
},
icon: {
type: String,
},
theme: {
type: String,
},
});
StatusSkillSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await StatusSkill.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();
});
StatusSkillSchema.statics.findAllIdApp = async function (idapp) {
const StatusSkill = this;
const query = [
{ $sort: { descr: 1 } }
];
return await StatusSkill
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
StatusSkillSchema.statics.getFieldsForSearch = function () {
return [{ field: 'descr', type: tools.FieldType.string }]
};
StatusSkillSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const StatusSkill = mongoose.model('StatusSkill', StatusSkillSchema);
StatusSkill.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { StatusSkill };

104
src/models/storehouse.js Executable file
View File

@@ -0,0 +1,104 @@
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 storehouseSchema = new Schema({
idapp: {
type: String,
},
name: {
type: String,
required: true,
},
username: {
type: String,
},
groupname: {
type: String,
},
description: {
type: String,
},
referent: {
type: String,
},
address: {
type: String,
},
city: {
type: String,
},
region: {
type: String,
},
img: {
type: String,
},
website: {
type: String,
},
email_html_header: {
type: String,
default: '',
},
email_html_footer: {
type: String,
default: '',
},
email_html_makeorder: {
type: String,
default: '',
},
email_html_order_confirmed: {
type: String,
default: '',
},
email_html_order_consegnato: {
type: String,
default: '',
},
email_html_GAS_makeorder: {
type: String,
default: '',
},
email_html_GAS_order_confirmed: {
type: String,
default: '',
},
email_html_GAS_order_consegnato: {
type: String,
default: '',
},
});
var Storehouse = module.exports = mongoose.model('Storehouse', storehouseSchema);
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 Storehouse.find(myfind);
};
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

69
src/models/subcatprod.js Executable file
View File

@@ -0,0 +1,69 @@
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 SubCatProdSchema = new Schema({
idapp: {
type: String,
},
idCatProd: {
type: String,
},
name: {
type: String,
},
descr_estesa: {
type: String,
},
img: {
type: String,
},
icon: {
type: String,
},
color: {
type: String,
},
});
SubCatProdSchema.statics.getAllCategories = function (callback) {
SubCatProd.find(callback)
}
SubCatProdSchema.statics.getSubCatProdById = function (id, callback) {
SubCatProd.findById(id, callback);
}
SubCatProdSchema.statics.getFieldsForSearch = function () {
return [{ field: 'name', type: tools.FieldType.string }]
};
SubCatProdSchema.statics.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params);
};
SubCatProdSchema.statics.findAllIdApp = async function (idapp) {
const myfind = { idapp };
return SubCatProd.find(myfind).sort({ name: 1 }).lean();
};
const SubCatProd = mongoose.model('SubCatProd', SubCatProdSchema);
SubCatProd.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = SubCatProd;

32
src/models/subscribers.js Executable file
View File

@@ -0,0 +1,32 @@
const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { ObjectId } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const SubscriberSchema = new Schema({
endpoint: String,
keys: Schema.Types.Mixed,
userId: String,
access: String,
browser: String,
createDate: {
type: Date,
default: Date.now
}
});
var Subscription = module.exports = mongoose.model('subscribers', SubscriberSchema);
Subscription.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

86
src/models/subskill.js Executable file
View File

@@ -0,0 +1,86 @@
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 SubSkillSchema = new Schema({
_id: {
type: Number,
},
idSkill: {
type: Number,
},
descr: {
type: String,
},
icon: {
type: String,
},
img: {
type: String,
},
});
SubSkillSchema.statics.findAllIdApp = async function (idapp) {
const SubSkill = this;
const query = [
{ $sort: { descr: 1 } }
];
return await SubSkill
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
SubSkillSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await SubSkill.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();
});
SubSkillSchema.statics.getFieldsForSearch = function () {
return [{ field: 'label', type: tools.FieldType.string },
{ field: 'descr', type: tools.FieldType.string }]
};
SubSkillSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
const SubSkill = mongoose.model('SubSkill', SubSkillSchema);
SubSkill.createIndexes()
.then(() => { })
.catch((err) => { throw err; });
module.exports = { SubSkill };

62
src/models/t_web_argomenti.js Executable file
View File

@@ -0,0 +1,62 @@
const mongoose = require('mongoose');
const { Schema } = mongoose;
mongoose.Promise = global.Promise;
mongoose.level = "F";
/**
* @typedef {Object} T_Web_Argomenti
* @property {bigint} Id
* @property {number} IdArgomento
* @property {string} Descrizione
* @property {Date} DataOra
* @property {boolean} Enabled
* @property {boolean} EnabledAlFresco
*/
const T_Web_ArgomentiSchema = new Schema({
IdArgomento: Number,
Descrizione: { type: String },
DataOra: Date,
Enabled: Boolean,
EnabledAlFresco: Boolean
}, { collection: 't_web_argomentis' });
const T_Web_Argomenti = module.exports = mongoose.model('T_Web_Argomenti', T_Web_ArgomentiSchema);
module.exports.findAllIdApp = async function () {
const myfind = {};
const myquery = [
{
$sort: { IdTipologia: 1, DataOra: -1 } // ordina per ID e DataOra decrescente
},
{
$group: {
_id: "$IdTipologia",
IdTipologia: { $first: "$IdTipologia" },
Descrizione: { $first: "$Descrizione" },
DataOra: { $first: "$DataOra" },
// aggiungi altri campi se servono
}
},
{
$sort: { IdTipologia: 1 } // opzionale, per ordinare il risultato
},
{
$project: {
_id: 0,
IdTipologia: 1,
Descrizione: 1
}
},
];
const rec = await T_Web_Argomenti.aggregate(myquery);
return rec;
};

107
src/models/t_web_articoli.js Executable file
View File

@@ -0,0 +1,107 @@
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
});
/**
* @typedef {Object} Article
* @property {bigint} Id
* @property {number} IdArticolo
* @property {string} Ean13
* @property {string} Titolo
* @property {string} ListaAutori
* @property {string} ListaArgomenti
* @property {number} IdStatoProdotto
* @property {number} PrezzoIvato
* @property {number} IdMarchioEditoriale
* @property {number} IdCollana
* @property {Date} DataPubblicazione
* @property {number} IdTipologia
* @property {number} IdTipoFormato
* @property {string} Misure
* @property {string} Pagine
* @property {string} Sottotitolo
* @property {string} Durata
* @property {string} Numero
* @property {string} Edizione
* @property {string} Ristampa
* @property {Date} DataInizioCampagna
* @property {Date} DataFineCampagna
* @property {number} ScontoCampagna
* @property {number} PrezzoIvatoScontatoCampagna
* @property {Date} DataOra
* @property {boolean} Enabled
* @property {number} IDTagGruppo
* @property {string} Utente
* @property {number} PercIva
* @property {number} IdTitoloOriginale
* @property {boolean} EnabledAlFresco
* @property {number} CodEdizione
* @property {string} FasciaEta
* @property {string} DescrizioneStatoProdotto
* @property {string} DescrizioneTipologia
* @property {string} DescrizioneFormato
* @property {string} DescrizioneCollana
* @property {string} DescrArgomento
* @property {string} AutoriCompleti
* @property {string} CasaEditrice
*/
const T_WEB_ArticoliSchema = new Schema({
IdArticolo: { type: Number },
Ean13: { type: String },
Titolo: { type: String },
ListaAutori: String,
ListaArgomenti: String,
IdStatoProdotto: Number,
PrezzoIvato: Number,
IdMarchioEditoriale: Number,
IdCollana: Number,
DataPubblicazione: Date,
IdTipologia: Number,
IdTipoFormato: Number,
Misure: String,
Pagine: String,
Sottotitolo: String,
Durata: String,
Numero: String,
Edizione: String,
Ristampa: String,
DataInizioCampagna: Date,
DataFineCampagna: Date,
ScontoCampagna: Number,
PrezzoIvatoScontatoCampagna: Number,
DataOra: Date,
Enabled: Boolean,
IDTagGruppo: Number,
Utente: String,
PercIva: Number,
IdTitoloOriginale: Number,
EnabledAlFresco: Boolean,
CodEdizione: Number,
FasciaEta: String,
DescrizioneStatoProdotto: String,
DescrizioneTipologia: String,
DescrizioneFormato: String,
DescrizioneCollana: String,
DescrArgomento: String,
AutoriCompleti: String,
CasaEditrice: String,
}, { collection: 't_web_articolis' });
module.exports = mongoose.model('T_WEB_Articoli', T_WEB_ArticoliSchema);
module.exports.createIndexes({ IdArticolo: 1, DataOra: -1 })
.then(() => { })
.catch((err) => { throw err; });

View File

@@ -0,0 +1,199 @@
const mongoose = require('mongoose');
const Product = require('./product');
// Definizione dello schema
const articoliFatturatiSchema = new mongoose.Schema({
Codice: {
type: Number, // Decimal in MongoDB è rappresentato come Number
required: true
},
AnnoDoc: {
type: String,
maxlength: 4,
required: true
},
NumeroDoc: {
type: Number, // Decimal in MongoDB è rappresentato come Number
required: true
},
TipoDoc: {
type: String,
maxlength: 20,
required: true
},
CodArticolo: {
type: String,
maxlength: 50,
required: true
},
Qta: {
type: String, // Mantenuto come stringa per flessibilità (può essere convertito in Number se necessario)
maxlength: 50,
required: true
},
DataOra: {
type: Date, // Datetime in MongoDB è rappresentato come Date
required: true
},
CodTrackingCorriere: {
type: String,
maxlength: 50
},
Stato: {
type: Number, // Int in MongoDB è rappresentato come Number
required: true
},
Note: {
type: String,
maxlength: 250
},
IdInternet: {
type: String,
maxlength: 50
}
}, {
timestamps: true, // Aggiunge automaticamente i campi createdAt e updatedAt
collection: 't_web_articolifatturatis',
});
// Creazione del modello
var articoliFatturati = module.exports = mongoose.model('T_WEB_ArticoliFatturati', articoliFatturatiSchema);
// Funzione per calcolare le statistiche
module.exports.updateStatisticsFatt = async function (CodArticolo, idapp, update) {
const currentDate = new Date();
// Calcola le date limite per i periodi di 3 mesi, 6 mesi e 1 anno
const threeMonthsAgo = new Date(currentDate);
threeMonthsAgo.setMonth(currentDate.getMonth() - 3);
const sixMonthsAgo = new Date(currentDate);
sixMonthsAgo.setMonth(currentDate.getMonth() - 6);
const oneYearAgo = new Date(currentDate);
oneYearAgo.setFullYear(currentDate.getFullYear() - 1);
const twoYearAgo = new Date(currentDate);
twoYearAgo.setFullYear(currentDate.getFullYear() - 2);
const fiveYearAgo = new Date(currentDate);
fiveYearAgo.setFullYear(currentDate.getFullYear() - 5);
try {
let myquery = [];
// Query di aggregazione per calcolare le statistiche
myquery.push(
{
$match: {
DataOra: { $gte: fiveYearAgo } // Filtra solo i record degli ultimi 12 mesi
}
});
if (CodArticolo) {
myquery.push({
$match: { $expr: { $eq: ["$CodArticolo", CodArticolo] } }
})
}
myquery.push(
{
$group: {
_id: "$CodArticolo", // Raggruppa per CodArticolo
fatLast3M: {
$sum: {
$cond: [
{ $gte: ["$DataOra", threeMonthsAgo] }, // Condizione: DataOra >= 3 mesi fa
{ $toInt: "$Qta" }, // Se vero, somma la quantità
0 // Altrimenti, somma 0
]
}
},
fatLast6M: {
$sum: {
$cond: [
{ $gte: ["$DataOra", sixMonthsAgo] }, // Condizione: DataOra >= 6 mesi fa
{ $toInt: "$Qta" }, // Se vero, somma la quantità
0 // Altrimenti, somma 0
]
}
},
fatLast1Y: {
$sum: {
$cond: [
{ $gte: ["$DataOra", oneYearAgo] }, // Condizione: DataOra >= 1 anno fa
{ $toInt: "$Qta" }, // Se vero, somma la quantità
0 // Altrimenti, somma 0
]
}
},
fatLast2Y: {
$sum: {
$cond: [
{ $gte: ["$DataOra", twoYearAgo] }, // Condizione: DataOra >= 1 anno fa
{ $toInt: "$Qta" }, // Se vero, somma la quantità
0 // Altrimenti, somma 0
]
}
},
totFat: {
$sum: {
$cond: [
{ $gte: ["$DataOra", fiveYearAgo] }, //
{ $toInt: "$Qta" }, // Se vero, somma la quantità
0 // Altrimenti, somma 0
]
}
},
}
},
{
$project: {
_id: 0, // Rimuove il campo _id dal risultato
sku: "$_id", // Rinomina _id in sku (equivalente a IdArticolo)
fatLast3M: 1,
fatLast6M: 1,
fatLast1Y: 1,
fatLast2Y: 1,
totFat: 1,
}
}
);
const statistics = await articoliFatturati.aggregate(myquery);
let countUpdate = 0;
if (update) {
for (const stat of statistics) {
const result = await Product.updateOne(
{
idapp,
'productInfo.sku': stat.sku,
}, // Cerca il documento con lo stesso sku
{
$set: {
'productInfo.fatLast3M': stat.fatLast3M,
'productInfo.fatLast6M': stat.fatLast6M,
'productInfo.fatLast1Y': stat.fatLast1Y,
'productInfo.fatLast2Y': stat.fatLast2Y,
'productInfo.totFat': stat.totFat,
}
},
{ upsert: false } // Non crea il documento se non esiste
);
if (result.modifiedCount > 0) {
countUpdate++;
}
}
}
return countUpdate;
} catch (error) {
console.error("Errore durante il calcolo delle statistiche:", error);
// throw error;
return 0;
}
}

52
src/models/t_web_disponibles.js Executable file
View File

@@ -0,0 +1,52 @@
const mongoose = require('mongoose');
const TWebDisponibileSchema = new mongoose.Schema({
Progressivo: {
type: mongoose.Schema.Types.Long || Number, // Usa 'mongoose-long' se vuoi long int
required: true,
unique: true,
},
Codice: {
type: String,
maxlength: 50,
required: true,
index: true, // usato nei lookup e nei match
},
QtaDisponibile: {
type: mongoose.Decimal128,
default: 0,
},
Giac: {
type: mongoose.Decimal128,
default: 0,
},
DataOra: {
type: Date,
default: Date.now,
index: true, // per ordinamento
},
Enabled: {
type: Boolean,
default: true,
},
DataOraSito: {
type: Date,
},
Ean13: {
type: String,
maxlength: 20,
},
QtaDisponibileOld: {
type: Number,
default: 0,
},
}, {
collection: 't_web_disponibiles',
timestamps: false,
});
module.exports = mongoose.model('TWebDisponibile', TWebDisponibileSchema);
module.exports.createIndexes()
.then(() => { })
.catch((err) => { throw err; });

200
src/models/t_web_ordini.js Executable file
View File

@@ -0,0 +1,200 @@
// allo stesso modo di t_web_articolifatturati.js
// creami il modello t_web_ordini:
// Tabella: T_WEB_Ordini
/*Codice - decimal ()
IdInternet - varchar (50)
CodArticoloGM - varchar (50)
Qta - decimal ()
PrezzoLordo - decimal ()
PercSconto - decimal ()
Enabled - int ()
DataOra - datetime ()
SovraSconto - decimal ()
Descrizione - varchar (250)
PrimaCopiaDaSpedire - int ()
*/
const mongoose = require('mongoose');
const Product = require('./product');
// Definizione dello schema
const ordiniSchema = new mongoose.Schema({
Codice: {
type: Number, // Decimal in MongoDB è rappresentato come Number
},
IdInternet: {
type: String,
maxlength: 50,
},
CodArticoloGM: {
type: String,
maxlength: 50,
},
Qta: {
type: Number, // Decimal in MongoDB è rappresentato come Number
},
PrezzoLordo: {
type: Number, // Decimal in MongoDB è rappresentato come Number
},
PercSconto: {
type: Number, // Decimal in MongoDB è rappresentato come Number
},
Enabled: {
type: Number, // Int in MongoDB è rappresentato come Number
},
DataOra: {
type: Date, // Datetime in MongoDB è rappresentato come Date
},
SovraSconto: {
type: Number, // Decimal in MongoDB è rappresentato come Number
},
Descrizione: {
type: String,
maxlength: 250
},
PrimaCopiaDaSpedire: {
type: Number, // Int in MongoDB è rappresentato come Number
}
}, {
timestamps: true, // Aggiunge automaticamente i campi createdAt e updatedAt
collection: 't_web_ordinis',
});
var T_WEB_Ordini = module.exports = mongoose.model('T_WEB_Ordini', ordiniSchema);
module.exports.updateStatisticsOrders = async function (CodArticoloGM, idapp, update) {
const currentDate = new Date();
// Calcola le date limite per i periodi di 3 mesi, 6 mesi e 1 anno
const threeMonthsAgo = new Date(currentDate);
threeMonthsAgo.setMonth(currentDate.getMonth() - 3);
const sixMonthsAgo = new Date(currentDate);
sixMonthsAgo.setMonth(currentDate.getMonth() - 6);
const oneYearAgo = new Date(currentDate);
oneYearAgo.setFullYear(currentDate.getFullYear() - 1);
const twoYearAgo = new Date(currentDate);
twoYearAgo.setFullYear(currentDate.getFullYear() - 2);
const fiveYear = new Date(currentDate);
fiveYear.setFullYear(currentDate.getFullYear() - 5);
try {
let myquery = [];
if (CodArticoloGM) {
// Query di aggregazione per calcolare le statistiche
myquery.push(
{
$match: {
CodArticoloGM: CodArticoloGM,
},
});
}
myquery.push(
{
$group: {
_id: "$CodArticoloGM", // Raggruppa per CodArticolo
totVen: {
$sum: {
$cond: [
{ $gte: ["$DataOra", fiveYear] }, // Condizione: DataOra totale
{ $toInt: "$Qta" }, // Se vero, somma la quantità
0 // Altrimenti, somma 0
]
}
},
vLast3M: {
$sum: {
$cond: [
{ $gte: ["$DataOra", threeMonthsAgo] }, // Condizione: DataOra >= 3 mesi fa
{ $toInt: "$Qta" }, // Se vero, somma la quantità
0 // Altrimenti, somma 0
]
}
},
vLast6M: {
$sum: {
$cond: [
{ $gte: ["$DataOra", sixMonthsAgo] }, // Condizione: DataOra >= 6 mesi fa
{ $toInt: "$Qta" }, // Se vero, somma la quantità
0 // Altrimenti, somma 0
]
}
},
vLast1Y: {
$sum: {
$cond: [
{ $gte: ["$DataOra", oneYearAgo] }, // Condizione: DataOra >= 1 anno fa
{ $toInt: "$Qta" }, // Se vero, somma la quantità
0 // Altrimenti, somma 0
]
}
},
vLast2Y: {
$sum: {
$cond: [
{ $gte: ["$DataOra", twoYearAgo] }, // Condizione: DataOra >= 1 anno fa
{ $toInt: "$Qta" }, // Se vero, somma la quantità
0 // Altrimenti, somma 0
]
}
},
}
},
{
$project: {
_id: 0, // Rimuove il campo _id dal risultato
sku: "$_id", // Rinomina _id in sku (equivalente a IdArticolo)
totVen: 1,
vLast3M: 1,
vLast6M: 1,
vLast1Y: 1,
vLast2Y: 1,
}
}
);
const statistics = await T_WEB_Ordini.aggregate(myquery);
let countUpdate = 0;
if (update) {
for (const stat of statistics) {
const result = await Product.updateOne(
{
'productInfo.sku': stat.sku,
idapp,
}, // Cerca il documento con lo stesso sku
{
$set: {
'productInfo.totVen': stat.totVen,
'productInfo.vLast3M': stat.vLast3M,
'productInfo.vLast6M': stat.vLast6M,
'productInfo.vLast1Y': stat.vLast1Y,
'productInfo.vLast2Y': stat.vLast2Y,
}
},
{ upsert: false } // Non crea il documento se non esiste
);
if (result.modifiedCount > 0) {
countUpdate++;
}
}
}
return countUpdate;
} catch (error) {
console.error("Errore durante il calcolo delle statistiche:", error);
return 0;
}
}

View File

@@ -0,0 +1,63 @@
const mongoose = require('mongoose');
const { Schema } = mongoose;
mongoose.Promise = global.Promise;
mongoose.level = "F";
/**
* @typedef {Object} StatoProdotto
* @property {bigint} Id
* @property {number} IdStatoProdotto
* @property {string} Descrizione
* @property {Date} DataOra
* @property {boolean} Enabled
* @property {boolean} EnabledAlFresco
*/
const StatoProdottoSchema = new Schema({
IdStatoProdotto: Number,
Descrizione: { type: String, maxlength: 100 },
DataOra: Date,
Enabled: Boolean,
EnabledAlFresco: Boolean
}, { collection: 't_web_statiprodottos' });
const T_WEB_StatiProdotto = module.exports = mongoose.model('T_WEB_StatiProdotto', StatoProdottoSchema);
module.exports.findAllIdApp = async function () {
const myfind = {};
const myquery = [
{
$sort: { IdStatoProdotto: 1, DataOra: -1 } // ordina per ID e DataOra decrescente
},
{
$group: {
_id: "$IdStatoProdotto",
IdStatoProdotto: { $first: "$IdStatoProdotto" },
Descrizione: { $first: "$Descrizione" },
DataOra: { $first: "$DataOra" },
// aggiungi altri campi se servono
}
},
{
$sort: { IdStatoProdotto: 1 } // opzionale, per ordinare il risultato
},
{
$project: {
_id: 1,
IdStatoProdotto: 1,
Descrizione: 1
// rimuovi DataOra e aggiungi altri campi se servono
}
}
];
const rec = await T_WEB_StatiProdotto.aggregate(myquery);
return rec;
};

61
src/models/t_web_tipiformato.js Executable file
View File

@@ -0,0 +1,61 @@
const mongoose = require('mongoose');
const { Schema } = mongoose;
mongoose.Promise = global.Promise;
mongoose.level = "F";
/**
* @typedef {Object} TipoFormato
* @property {bigint} Id
* @property {number} IdTipoFormato
* @property {string} Descrizione
* @property {Date} DataOra
* @property {boolean} Enabled
* @property {boolean} EnabledAlFresco
*/
const TipoFormatoSchema = new Schema({
IdTipoFormato: Number,
Descrizione: { type: String, maxlength: 100 },
DataOra: Date,
Enabled: Boolean,
EnabledAlFresco: Boolean
}, { collection: 't_web_tipiformatos' });
const T_WEB_TipiFormato = module.exports = mongoose.model('T_WEB_TipiFormato', TipoFormatoSchema);
module.exports.findAllIdApp = async function () {
const myfind = {};
const myquery = [
{
$sort: { IdTipoFormato: 1, DataOra: -1 } // ordina per ID e DataOra decrescente
},
{
$group: {
_id: "$IdTipoFormato",
IdTipoFormato: { $first: "$IdTipoFormato" },
Descrizione: { $first: "$Descrizione" },
DataOra: { $first: "$DataOra" },
// aggiungi altri campi se servono
}
},
{
$sort: { IdTipoFormato: 1 } // opzionale, per ordinare il risultato
},
{
$project: {
_id: 0,
IdTipoFormato: 1,
Descrizione: 1,
}
},
];
const rec = await T_WEB_TipiFormato.aggregate(myquery);
return rec;
};

62
src/models/t_web_tipologie.js Executable file
View File

@@ -0,0 +1,62 @@
const mongoose = require('mongoose');
const { Schema } = mongoose;
mongoose.Promise = global.Promise;
mongoose.level = "F";
/**
* @typedef {Object} Tipologie
* @property {bigint} Id
* @property {number} IdTipologia
* @property {string} Descrizione
* @property {Date} DataOra
* @property {boolean} Enabled
* @property {boolean} EnabledAlFresco
*/
const TipologieSchema = new Schema({
IdTipologia: Number,
Descrizione: { type: String, maxlength: 100 },
DataOra: Date,
Enabled: Boolean,
EnabledAlFresco: Boolean
}, { collection: 't_web_tipologies' });
const T_WEB_Tipologie = module.exports = mongoose.model('T_WEB_Tipologie', TipologieSchema);
module.exports.findAllIdApp = async function () {
const myfind = {};
const myquery = [
{
$sort: { IdTipologia: 1, DataOra: -1 } // ordina per ID e DataOra decrescente
},
{
$group: {
_id: "$IdTipologia",
IdTipologia: { $first: "$IdTipologia" },
Descrizione: { $first: "$Descrizione" },
DataOra: { $first: "$DataOra" },
// aggiungi altri campi se servono
}
},
{
$sort: { IdTipologia: 1 } // opzionale, per ordinare il risultato
},
{
$project: {
_id: 0,
IdTipologia: 1,
Descrizione: 1
}
},
];
const rec = await T_WEB_Tipologie.aggregate(myquery);
return rec;
};

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