diff --git a/.env.development b/.env.development index 61bd7e9..3136acd 100644 --- a/.env.development +++ b/.env.development @@ -1,11 +1,11 @@ -DATABASE=test_PiuCheBuono +DATABASE=test_FreePlanet UDB=paofreeplanet PDB=mypassword@1A SEND_EMAIL=0 SEND_EMAIL_ORDERS=1 PORT=3000 -appTelegram_TEST=["1","17"] -appTelegram=["1","17"] +appTelegram_TEST=["1","13"] +appTelegram=["1","13"] DOMAIN=mongodb://localhost:27017/ AUTH_MONGODB=true MONGODB_USER=admin diff --git a/src/server/models/city.js b/src/server/models/city.js index fb7ee3b..67e1380 100755 --- a/src/server/models/city.js +++ b/src/server/models/city.js @@ -8,7 +8,7 @@ mongoose.level = 'F'; const tools = require('../tools/general'); -const {ObjectID} = require('mongodb'); +const { ObjectID } = require('mongodb'); const shared_consts = require('../tools/shared_nodejs'); @@ -51,9 +51,9 @@ const CitySchema = new Schema({ }, }); -CitySchema.pre('save', async function(next) { +CitySchema.pre('save', async function (next) { if (this.isNew) { - const myrec = await City.findOne().limit(1).sort({_id: -1}); + const myrec = await City.findOne().limit(1).sort({ _id: -1 }); if (!!myrec) { if (myrec._doc._id === 0) this._id = 1; @@ -68,8 +68,8 @@ CitySchema.pre('save', async function(next) { next(); }); -CitySchema.statics.getProvinceByIdCity = async function(idcity) { - const myrec = await City.findOne({_id: idcity}).lean(); +CitySchema.statics.getProvinceByIdCity = async function (idcity) { + const myrec = await City.findOne({ _id: idcity }).lean(); if (myrec) { return myrec.prov; } @@ -77,10 +77,10 @@ CitySchema.statics.getProvinceByIdCity = async function(idcity) { return ''; } -CitySchema.statics.getCircuitNameBystrProv = async function(strProv) { +CitySchema.statics.getCircuitNameBystrProv = async function (strProv) { const { Circuit } = require('../models/circuit'); - const myrec = await Circuit.findOne({strProv}).lean(); + const myrec = await Circuit.findOne({ strProv }).lean(); if (myrec) { return myrec.name; } @@ -88,8 +88,8 @@ CitySchema.statics.getCircuitNameBystrProv = async function(strProv) { return ''; } -CitySchema.statics.getRegionByIdCity = async function(idcity) { - const myrec = await City.findOne({_id: idcity}).lean(); +CitySchema.statics.getRegionByIdCity = async function (idcity) { + const myrec = await City.findOne({ _id: idcity }).lean(); if (myrec) { return myrec.reg; } @@ -97,13 +97,13 @@ CitySchema.statics.getRegionByIdCity = async function(idcity) { return ''; } -CitySchema.statics.findByCity = function(mycity) { +CitySchema.statics.findByCity = function (mycity) { let myregexp = new RegExp(mycity.trim().replace(' ', '|'), 'ig'); const query = [ - {$match: {comune: {$regex: myregexp}}}, - {$sort: {descr: 1}}, + { $match: { comune: { $regex: myregexp } } }, + { $sort: { descr: 1 } }, ]; return City.aggregate(query).then((arrrec) => { @@ -112,17 +112,17 @@ CitySchema.statics.findByCity = function(mycity) { }; -CitySchema.statics.getFieldsForSearch = function() { +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}, + { 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) { +CitySchema.statics.executeQueryTable = function (idapp, params) { params.fieldsearch = this.getFieldsForSearch(); const strfind = params.search; @@ -134,7 +134,7 @@ CitySchema.statics.executeQueryTable = function(idapp, params) { return tools.executeQueryTable(this, 0, params); }; -CitySchema.statics.executeQueryPickup = async function(idapp, params) { +CitySchema.statics.executeQueryPickup = async function (idapp, params) { const strfind = params.search; @@ -144,19 +144,19 @@ CitySchema.statics.executeQueryPickup = async function(idapp, params) { let filterfindexact = {}; if (strfind) { - filterfindexact = {comune: strfind}; + filterfindexact = { comune: strfind }; } let limit = 10; let risexact = []; - let filterfind = {comune: {$regex: '^' + strfind, $options: 'i'}}; + let filterfind = { comune: { $regex: '^' + strfind, $options: 'i' } }; let aggr1 = [ { - $match: {comune: strfind}, + $match: { comune: strfind }, }, - { $limit : 1 }, + { $limit: 1 }, { $project: { comune: { $concat: ["$comune", " (", "$prov", ")"] }, @@ -165,7 +165,7 @@ CitySchema.statics.executeQueryPickup = async function(idapp, params) { ]; if (params.filter) { - filterfind = {...params.filter, ...filterfind}; + filterfind = { ...params.filter, ...filterfind }; limit = 200; } else { // risexact = await City.find(filterfindexact, {comune: 1, prov: 1, reg: 1}).lean(); @@ -176,7 +176,7 @@ CitySchema.statics.executeQueryPickup = async function(idapp, params) { { $match: filterfind, }, - { $limit : limit }, + { $limit: limit }, { $project: { comune: { $concat: ["$comune", " (", "$prov", ")"] }, @@ -192,17 +192,18 @@ CitySchema.statics.executeQueryPickup = async function(idapp, params) { }; - -CitySchema.statics.findAllIdApp = async function(idapp) { +CitySchema.statics.findAllIdApp = async function (idapp) { const myfind = {}; return await City.find(myfind); }; + + const City = mongoose.model('City', CitySchema); City.createIndexes((err) => { if (err) throw err; }); -module.exports = {City}; +module.exports = { City }; diff --git a/src/server/models/order.js b/src/server/models/order.js index 27d6fe4..c4548b0 100755 --- a/src/server/models/order.js +++ b/src/server/models/order.js @@ -605,7 +605,8 @@ module.exports.getTotalOrderById = async function (id) { ]; - return await Order.aggregate(query); + const ris = await Order.aggregate(query); + return ris; } module.exports.RemoveDeletedOrdersInOrderscart = async function () { diff --git a/src/server/models/province.js b/src/server/models/province.js index 75296c6..feee72b 100755 --- a/src/server/models/province.js +++ b/src/server/models/province.js @@ -8,7 +8,7 @@ mongoose.level = 'F'; const tools = require('../tools/general'); -const {ObjectID} = require('mongodb'); +const { ObjectID } = require('mongodb'); const shared_consts = require('../tools/shared_nodejs'); @@ -35,18 +35,25 @@ const ProvinceSchema = new Schema({ link_grp: { type: String, }, - card : { + card: { type: String, }, - + link_telegram: { type: String, }, -}, { _id : false }); + 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}); + const myrec = await Province.findOne().limit(1).sort({ _id: -1 }); if (!!myrec) { if (myrec._doc._id === 0) this._id = 1; @@ -61,8 +68,8 @@ ProvinceSchema.pre('save', async function (next) { next(); }); -ProvinceSchema.statics.getRegionByStrProvince = async function(strprovince) { - const myrec = await Province.findOne({prov: strprovince}).lean(); +ProvinceSchema.statics.getRegionByStrProvince = async function (strprovince) { + const myrec = await Province.findOne({ prov: strprovince }).lean(); if (myrec) { return myrec.reg; } @@ -70,8 +77,8 @@ ProvinceSchema.statics.getRegionByStrProvince = async function(strprovince) { return ''; } -ProvinceSchema.statics.getStrProvinceByProv = async function(prov) { - const myrec = await Province.findOne({prov}).lean(); +ProvinceSchema.statics.getStrProvinceByProv = async function (prov) { + const myrec = await Province.findOne({ prov }).lean(); if (myrec) { return myrec.descr; } @@ -79,14 +86,14 @@ ProvinceSchema.statics.getStrProvinceByProv = async function(prov) { return ''; } -ProvinceSchema.statics.getFieldsForSearch = function() { +ProvinceSchema.statics.getFieldsForSearch = function () { return [ - {field: 'prov', type: tools.FieldType.string}, - {field: 'descr', type: tools.FieldType.string}, + { field: 'prov', type: tools.FieldType.string }, + { field: 'descr', type: tools.FieldType.string }, ]; }; -ProvinceSchema.statics.executeQueryTable = function(idapp, params) { +ProvinceSchema.statics.executeQueryTable = function (idapp, params) { params.fieldsearch = this.getFieldsForSearch(); const strfind = params.search; @@ -98,7 +105,7 @@ ProvinceSchema.statics.executeQueryTable = function(idapp, params) { return tools.executeQueryTable(this, 0, params); }; -ProvinceSchema.statics.executeQueryPickup = async function(idapp, params) { +ProvinceSchema.statics.executeQueryPickup = async function (idapp, params) { const strfind = params.search; @@ -106,12 +113,12 @@ ProvinceSchema.statics.executeQueryPickup = async function(idapp, params) { return []; } - let filterfindexact = {descr: strfind}; + let filterfindexact = { descr: strfind }; const risexact = await Province.find(filterfindexact).lean(); let filterfind = {}; - filterfind = {descr: {$regex: '^' + strfind, $options: 'i'}}; + filterfind = { descr: { $regex: '^' + strfind, $options: 'i' } }; const ris = await Province.find(filterfind).lean().limit(10); @@ -119,16 +126,34 @@ ProvinceSchema.statics.executeQueryPickup = async function(idapp, params) { }; -ProvinceSchema.statics.findAllIdApp = async function(idapp) { +ProvinceSchema.statics.findAllIdApp = async function (idapp) { const myfind = {}; - return Province.find(myfind).sort({descr: 1}); + return Province.find(myfind).sort({ descr: 1 }); }; +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((err) => { if (err) throw err; }); -module.exports = {Province}; +module.exports = { Province }; diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index 59faabc..87605b4 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -46,6 +46,7 @@ const TypedError = require('../modules/ErrorHandler'); const { MyGroup } = require('../models/mygroup'); const { Circuit } = require('../models/circuit'); +const { Province } = require('../models/province'); const { Account } = require('../models/account'); const mongoose = require('mongoose').set('debug', false); @@ -1253,6 +1254,8 @@ async function eseguiDbOp(idapp, mydata, locale, req, res) { await Circuit.CheckTransazioniCircuiti(false); } else if (mydata.dbop === 'CorreggiTransazioniCircuiti') { await Circuit.CheckTransazioniCircuiti(true); + } else if (mydata.dbop === 'UpdateCoordProv') { + await Province.setCoordinatesOnDB(); } else if (mydata.dbop === 'AbilitaNewsletterALL') { await User.updateMany({ $or: [ @@ -1708,6 +1711,113 @@ router.post('/dbopuser', authenticate, async (req, res) => { }); +router.post('/infomap', authenticate, async (req, res) => { + + const idapp = req.body.idapp; + const raggruppa = true; + + try { + let myquery = [ + { + $match: { + idapp, + $or: [ + { deleted: { $exists: false } }, + { deleted: { $exists: true, $eq: false } } + ] + } + }, + { + $lookup: { + from: "provinces", // Collezione delle province + localField: "profile.resid_province", // Campo nella collezione User che contiene l'ID della provincia + foreignField: "prov", // Campo nella collezione Province che identifica l'ID della provincia + as: "provinceInfo" // Nome del campo in cui verranno memorizzate le informazioni della provincia + } + }, + { + $addFields: { + "provinceInfo": { $arrayElemAt: ["$provinceInfo", 0] } // Estrae il primo elemento dell'array provinceInfo + } + }, + { + $project: { + username: 1, + name: 1, + surname: 1, + email: 1, + verified_by_aportador: 1, + aportador_solidario: 1, + lasttimeonline: 1, + 'profile.img': 1, + 'profile.resid_province': 1, + lat: "$provinceInfo.lat", // Aggiunge il campo lat preso dalla provincia + long: "$provinceInfo.long" // Aggiunge il campo long preso dalla provincia + } + } + ]; + + let ris = null; + + if (raggruppa) { + const myquery = [ + { + $lookup: { + from: "users", // Collezione degli utenti + localField: "prov", // Campo nella collezione Province che identifica l'ID della provincia + foreignField: "profile.resid_province", // Campo nella collezione User che contiene l'ID della provincia + as: "users" // Nome del campo in cui verranno memorizzati gli utenti della provincia + } + }, + { + $addFields: { + userCount: { $size: "$users" } // Aggiunge il numero di utenti nella provincia + } + }, + { + $lookup: { + from: "provinces", // Collezione delle province + localField: "prov", // Campo nella collezione Province che identifica l'ID della provincia + foreignField: "prov", // Campo nella collezione Province che identifica l'ID della provincia + as: "provinceInfo" // Nome del campo in cui verranno memorizzate le informazioni della provincia + } + }, + { + $addFields: { + provinceDescr: { $arrayElemAt: ["$provinceInfo.descr", 0] } // Aggiunge il campo descr preso dalla provincia + } + }, + { + $project: { + _id: 0, // Esclude il campo _id + province: "$prov", // Rinomina il campo prov come province + descr: "$provinceDescr", + userCount: 1, + lat: 1, // Include il campo lat + long: 1 // Include il campo long + } + } + ]; + + ris = await Province.aggregate(myquery); + } else { + ris = await User.aggregate(myquery); + } + + if (!ris) { + ris = {}; + } + + res.send({ code: server_constants.RIS_CODE_OK, ris }); + + } catch (e) { + res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e }); + + console.log(e.message); + } + +}); + router.post('/mgt', authenticate, async (req, res) => { const mydata = req.body.mydata; diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 1289a47..97c5bf3 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -7,6 +7,8 @@ require('../models/subscribers'); const printf = require('util').format; +const axios = require('axios'); + const CryptoJS = require('crypto-js'); const Url = require('url-parse'); @@ -4879,4 +4881,22 @@ module.exports = { } }, + // Funzione per ottenere le coordinate di una singola città + async getCityCoordinates(city) { + try { + const response = await axios.get(`https://nominatim.openstreetmap.org/search?format=json&q=${city.descr},${city.prov},Italia`); + if (response.data.length > 0) { + city.lat = parseFloat(response.data[0].lat); + city.long = parseFloat(response.data[0].lon); + // console.log(`${city.descr}: Lat ${city.lat}, Long ${city.long}`); + return city; + } else { + console.error(`Coordinate non trovate per ${city.descr}, ${city.prov}`); + } + return null; + } catch (error) { + console.error(`Errore durante il recupero delle coordinate per ${city.descr}, ${city.prov}:`, error.message); + } + }, + };