Compare commits
36 Commits
server_1.1
...
ver-1.2.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ab24b2abd | ||
|
|
09a05a11d5 | ||
|
|
6c254a6a8e | ||
|
|
240a7be7f1 | ||
|
|
58839c32e1 | ||
|
|
b77a0579f1 | ||
|
|
6e8d1fcff1 | ||
|
|
192fd4706c | ||
|
|
fcc3755c19 | ||
|
|
97abe8b46d | ||
|
|
e40fbd550b | ||
|
|
3d4f8b0d04 | ||
|
|
95793fd73f | ||
|
|
4b4e3963ac | ||
|
|
85e2df56e1 | ||
|
|
58431c144c | ||
|
|
ad45ce60ee | ||
|
|
fba2ebd710 | ||
|
|
8e8a3204a7 | ||
|
|
e1ca4ef17f | ||
|
|
5431fe118e | ||
|
|
789dc1dcae | ||
|
|
76bacf3f5a | ||
|
|
d94cbde948 | ||
|
|
dfe492df45 | ||
|
|
6c50f35b2b | ||
|
|
a03c4cf613 | ||
|
|
7d845355a9 | ||
|
|
aeb83a512b | ||
|
|
e04247b1b6 | ||
|
|
f713f66369 | ||
|
|
f32bd189dc | ||
|
|
0017f04e45 | ||
|
|
65b29a6eee | ||
|
|
7827e49760 | ||
|
|
d106a59bb5 |
@@ -21,8 +21,8 @@ DELAY_SENDEMAIL=2000
|
||||
VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app
|
||||
PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8
|
||||
PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo
|
||||
PATH_CERT_KEY=localhost.key
|
||||
PATH_SERVER_CRT=localhost.crt
|
||||
PATH_CERT_KEY=localhost-key.pem
|
||||
PATH_SERVER_CRT=localhost.pem
|
||||
PATH_SSL_ROOT_PEM=root.pem
|
||||
PATH_SSL_CHAIN_PEM=chain.pem
|
||||
GCM_API_KEY=""
|
||||
@@ -42,5 +42,5 @@ MIAB_HOST=box.lamiaposta.org
|
||||
MIAB_ADMIN_EMAIL=admin@lamiaposta.org
|
||||
MIAB_ADMIN_PASSWORD=passpao1pabox@1A
|
||||
DS_API_KEY="sk-222e3addb3d8455d8b0516d93906eec7"
|
||||
API_KEY_MSSQL="m68yADSr123MIVIDA@154$DSAGVOK"
|
||||
SERVER_A_URL="http://51.77.156.69:3000"
|
||||
SERVER_A_URL="http://51.77.156.69:3000"
|
||||
API_KEY_MSSQL="m68yADSr123MIVIDA@154$DSAGVOK"
|
||||
@@ -21,15 +21,15 @@ DELAY_SENDEMAIL=2000
|
||||
VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app
|
||||
PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8
|
||||
PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo
|
||||
PATH_CERT_KEY=localhost.key
|
||||
PATH_SERVER_CRT=localhost.crt
|
||||
PATH_CERT_KEY=localhost-key.pem
|
||||
PATH_SERVER_CRT=localhost.pem
|
||||
PATH_SSL_ROOT_PEM=root.pem
|
||||
PATH_SSL_CHAIN_PEM=chain.pem
|
||||
GCM_API_KEY=""
|
||||
PROD=0
|
||||
PROJECT_DESCR_MAIN='__PROJECTS'
|
||||
SECRK=Askb38v23jjDFaoskBOWj92axXCQ
|
||||
TOKEN_LIFE=2h
|
||||
TOKEN_LIFE=1m
|
||||
REFRESH_TOKEN_LIFE=14d
|
||||
FTPSERVER_HOST=139.162.166.31
|
||||
FTPSERVER_PORT=21
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
DATABASE=test_FreePlanet
|
||||
DATABASE=test_PiuCheBuono
|
||||
UDB=paofreeplanet
|
||||
PDB=mypassword@1A
|
||||
SEND_EMAIL=0
|
||||
SEND_EMAIL_ORDERS=1
|
||||
PORT=3000
|
||||
appTelegram_TEST=["1","13"]
|
||||
appTelegram=["1","13"]
|
||||
appTelegram_DEVELOP=["13"]
|
||||
appTelegram_TEST=["1","17"]
|
||||
appTelegram=["1","17"]
|
||||
appTelegram_DEVELOP=["17"]
|
||||
DOMAIN=mongodb://localhost:27017/
|
||||
AUTH_MONGODB=0
|
||||
ENABLE_PUSHNOTIFICATION=1
|
||||
@@ -21,15 +21,15 @@ DELAY_SENDEMAIL=2000
|
||||
VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app
|
||||
PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8
|
||||
PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo
|
||||
PATH_CERT_KEY=localhost.key
|
||||
PATH_SERVER_CRT=localhost.crt
|
||||
PATH_CERT_KEY=localhost-key.pem
|
||||
PATH_SERVER_CRT=localhost.pem
|
||||
PATH_SSL_ROOT_PEM=root.pem
|
||||
PATH_SSL_CHAIN_PEM=chain.pem
|
||||
GCM_API_KEY=""
|
||||
PROD=0
|
||||
PROJECT_DESCR_MAIN='__PROJECTS'
|
||||
SECRK=Askb38v23jjDFaoskBOWj92axXCQ
|
||||
TOKEN_LIFE=1m
|
||||
TOKEN_LIFE=2h
|
||||
REFRESH_TOKEN_LIFE=14d
|
||||
FTPSERVER_HOST=139.162.166.31
|
||||
FTPSERVER_PORT=21
|
||||
@@ -38,4 +38,9 @@ FTPSERVER_PWD=ftpmypwd@1A_
|
||||
AUTH_NEW_SITES=123123123
|
||||
SCRIPTS_DIR=admin_scripts
|
||||
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}]
|
||||
MIAB_HOST=box.lamiaposta.org
|
||||
MIAB_ADMIN_EMAIL=admin@lamiaposta.org
|
||||
MIAB_ADMIN_PASSWORD=passpao1pabox@1A
|
||||
DS_API_KEY="sk-222e3addb3d8455d8b0516d93906eec7"
|
||||
SERVER_A_URL="http://51.77.156.69:3000"
|
||||
API_KEY_MSSQL="m68yADSr123MIVIDA@154$DSAGVOK"
|
||||
@@ -10,8 +10,9 @@ ENABLE_PUSHNOTIFICATION=1
|
||||
DIRECTORY_SERVER=/var/www/nodejs_piuchebuono_server
|
||||
SERVERDIR_WEBSITE=/var/www/piuchebuono.app
|
||||
PORT_APP1="0"
|
||||
DOMAIN=mongodb://localhost:32001/
|
||||
DOMAIN_AUTH=mongodb://{username}:{password}@127.0.0.1:32001/
|
||||
DOMAIN_OFF=mongodb://localhost:32001/
|
||||
DOMAIN_AUTH_OLD=mongodb://{username}:{password}@127.0.0.1:32001/
|
||||
DOMAIN_AUTH=mongodb://{username}:{password}@127.0.0.1:27030/
|
||||
AUTH_MONGODB=1
|
||||
AUTH_DB_PASSING=1
|
||||
MONGODB_USER=admin
|
||||
@@ -33,15 +34,11 @@ TOKEN_LIFE=2h
|
||||
REFRESH_TOKEN_LIFE=14d
|
||||
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNVZZ
|
||||
DOMAINS=[{"hostname":"piuchebuono.app","port":"3030"},{"hostname":"gruppomacro.app","port":"3010"}]
|
||||
DOMAINS_ALLOWED=[]
|
||||
SCRIPTS_DIR=admin_scripts
|
||||
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}]
|
||||
MIAB_HOST=box.lamiaposta.org
|
||||
MIAB_ADMIN_EMAIL=admin@lamiaposta.org
|
||||
MIAB_ADMIN_PASSWORD=passpao1pabox@1A
|
||||
|
||||
#DB_CONNECTION=sqlsrv
|
||||
DB_HOST_SQLSRVTEST=31.3.180.50
|
||||
DB_PORT_SQLSRVTEST=14338
|
||||
DB_DATABASE_SQLSRVTEST=ANAG_MACRO
|
||||
DB_USERNAME_SQLSRVTEST=woo
|
||||
DB_PASSWORD_SQLSRVTEST=4n4traPe@
|
||||
SERVER_A_URL="http://51.77.156.69:3000"
|
||||
API_KEY_MSSQL="m68yADSr123MIVIDA@154$DSAGVOK"
|
||||
@@ -7,8 +7,9 @@ ENABLE_PUSHNOTIFICATION=1
|
||||
DIRECTORY_SERVER=/var/www/nodejs_riso_server
|
||||
SERVERDIR_WEBSITE=/var/www/riso.app
|
||||
PORT_APP1="0"
|
||||
DOMAIN=mongodb://localhost:32015/
|
||||
DOMAIN_AUTH=mongodb://{username}:{password}@127.0.0.1:32015/
|
||||
DOMAIN_OFF=mongodb://localhost:32015/
|
||||
DOMAIN_AUTH_OLD=mongodb://{username}:{password}@127.0.0.1:32015/
|
||||
DOMAIN_AUTH=mongodb://{username}:{password}@127.0.0.1:27030/
|
||||
AUTH_MONGODB=1
|
||||
AUTH_DB_PASSING=1
|
||||
MONGODB_USER=admin
|
||||
@@ -30,6 +31,7 @@ TOKEN_LIFE=2h
|
||||
REFRESH_TOKEN_LIFE=14d
|
||||
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV
|
||||
DOMAINS=[{"hostname":"riso.app","port":"3006"},{"hostname":"freeplanet.app","port":"3000"}]
|
||||
DOMAINS_ALLOWED=["comunitanuovomondo.app","kolibrilab.it","artenergetica.org","freeplanet.app","www.freeplanet.app","freeplanet.app:3000","freeplanet.app:3001","www.freeplanet.app:3000","www.freeplanet.app:3001"]
|
||||
#DOMAINS=[{"hostname":"abitaregliiblei.it","port":"3021"},{"hostname":"riso.app","port":"3005"}]
|
||||
SCRIPTS_DIR=admin_scripts
|
||||
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}]
|
||||
|
||||
@@ -15,7 +15,7 @@ DOMAIN_AUTH=mongodb://{username}:{password}@127.0.0.1:32002/
|
||||
AUTH_MONGODB=1
|
||||
AUTH_DB_PASSING=1
|
||||
MONGODB_USER=admin
|
||||
MONGODB_PWD=mypwadmin@1A
|
||||
MONGODB_PWD=mypwadminS1A
|
||||
SIGNCODE=SU2134hncaskjdbo231oihJSDNHEI$1@AB
|
||||
VITE_DEBUG=0
|
||||
LOCALE=0
|
||||
@@ -35,8 +35,11 @@ TOKEN_LIFE=2h
|
||||
REFRESH_TOKEN_LIFE=14d
|
||||
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV
|
||||
DOMAINS=[{"hostname":"piuchebuono.app","port":"3031"},{"hostname":"gruppomacro.app","port":"3011"}]
|
||||
DOMAINS_ALLOWED=[]
|
||||
SCRIPTS_DIR=admin_scripts
|
||||
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}]
|
||||
MIAB_HOST=box.lamiaposta.org
|
||||
MIAB_ADMIN_EMAIL=admin@lamiaposta.org
|
||||
MIAB_ADMIN_PASSWORD=passpao1pabox@1A
|
||||
MIAB_ADMIN_PASSWORD=passpao1pabox@1A
|
||||
SERVER_A_URL="http://51.77.156.69:3000"
|
||||
API_KEY_MSSQL="m68yADSr123MIVIDA@154$DSAGVOK"
|
||||
@@ -28,10 +28,11 @@ PATH_SSL_CHAIN_PEM=chain.pem
|
||||
PROD=0
|
||||
PROJECT_DESCR_MAIN='__PROJECTS'
|
||||
SECRK=iUUb38v23jjDFaosWj92axkBOXCQ
|
||||
TOKEN_LIFE=1m
|
||||
TOKEN_LIFE=2h
|
||||
REFRESH_TOKEN_LIFE=14d
|
||||
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV
|
||||
DOMAINS=[{"hostname":"riso.app","port":"3005"}]
|
||||
DOMAINS_ALLOWED=["comunitanuovomondo.app","kolibrilab.it","artenergetica.org","freeplanet.app","www.freeplanet.app","freeplanet.app:3000","freeplanet.app:3001","www.freeplanet.app:3000","www.freeplanet.app:3001"]
|
||||
SCRIPTS_DIR=admin_scripts
|
||||
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}]
|
||||
MIAB_HOST=box.lamiaposta.org
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
source ./.env.prod.pcb
|
||||
|
||||
echo "Sincronizzazione in corso PCB PRODUZIONE ... $DIRECTORY_SERVER/"
|
||||
echo ""
|
||||
|
||||
msg="*** SERVER DI ### PRODUZIONE ### PCB **** INVIARE GLI AGGIORNAMENTI ? (Y/N)"
|
||||
msg="*** SERVER DI PRODUZIONE PCB **** INVIARE GLI AGGIORNAMENTI ? (Y/N)"
|
||||
|
||||
if [ "$1" = "" ]; then
|
||||
read -p "$msg" risposta
|
||||
@@ -17,7 +19,6 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
|
||||
echo "Sincronizzazione in corso PCB PRODUZIONE ... $DIRECTORY_SERVER/"
|
||||
echo ""
|
||||
|
||||
|
||||
# Configurazione
|
||||
REMOTE_USER="pcbuser"
|
||||
REMOTE_HOST="pcb"
|
||||
@@ -25,6 +26,10 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
|
||||
REMOTE_DIR="$DIRECTORY_SERVER"
|
||||
SSH_OPTIONS="-p $REMOTE_PORT"
|
||||
|
||||
CONFIG_JS="ecosystem.config.pcb_prod.js"
|
||||
ENV_FILE=".env.prod.pcb"
|
||||
ENV_OUT=".env.production"
|
||||
|
||||
# Array di cartelle e file da sincronizzare
|
||||
SYNC_ITEMS=(
|
||||
"css"
|
||||
@@ -54,7 +59,8 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
|
||||
|
||||
# Sincronizza i file specifici
|
||||
rsync -avz -e "ssh $SSH_OPTIONS" \
|
||||
.env.prod.pcb "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/.env.production"
|
||||
$ENV_FILE "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/$ENV_OUT"
|
||||
|
||||
|
||||
echo ""
|
||||
echo "*** Copia del file package.json ... "
|
||||
@@ -62,15 +68,15 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
|
||||
package.json "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/package.json"
|
||||
|
||||
echo ""
|
||||
echo "*** Copia del file ecosystem.config.js ... "
|
||||
echo "*** Copia del file $CONFIG_JS in ecosystem.config.js ... "
|
||||
rsync -avz -e "ssh $SSH_OPTIONS" \
|
||||
ecosystem.config.pcb.js "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/ecosystem.config.js"
|
||||
$CONFIG_JS "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/ecosystem.config.js"
|
||||
|
||||
# Verifica il risultato
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "Sincronizzazione completata con successo. SERVER PCB! "
|
||||
echo "Sincronizzazione completata con successo. SERVER PCB PRODUZIONE! "
|
||||
else
|
||||
echo "Errore durante la sincronizzazione. Controlla l'output per i dettagli."
|
||||
fi
|
||||
|
||||
fi
|
||||
fi
|
||||
@@ -26,8 +26,8 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
|
||||
REMOTE_DIR="$DIRECTORY_SERVER"
|
||||
SSH_OPTIONS="-p $REMOTE_PORT"
|
||||
|
||||
CONFIG_JS="ecosystem.config.testriso.js"
|
||||
ENV_FILE=".env.test.risosrv"
|
||||
CONFIG_JS="ecosystem.config.pcb_test.js"
|
||||
ENV_FILE=".env.test.pcb"
|
||||
ENV_OUT=".env.test"
|
||||
|
||||
# Array di cartelle e file da sincronizzare
|
||||
@@ -67,11 +67,6 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
|
||||
rsync -avz -e "ssh $SSH_OPTIONS" \
|
||||
package.json "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/package.json"
|
||||
|
||||
echo ""
|
||||
echo "*** Copia del file ecosystem.config.testpcb.js in ecosystem.config.js ... "
|
||||
rsync -avz -e "ssh $SSH_OPTIONS" \
|
||||
ecosystem.config.testpcb.js "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/ecosystem.config.js"
|
||||
|
||||
echo ""
|
||||
echo "*** Copia del file $CONFIG_JS in ecosystem.config.js ... "
|
||||
rsync -avz -e "ssh $SSH_OPTIONS" \
|
||||
|
||||
@@ -22,13 +22,10 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
|
||||
REMOTE_PORT="8822"
|
||||
REMOTE_DIR="$DIRECTORY_SERVER"
|
||||
SSH_OPTIONS="-p $REMOTE_PORT"
|
||||
CONFIG_JS="ecosystem.config.prod_riso.js"
|
||||
CONFIG_JS="ecosystem.config.riso_prod.js"
|
||||
ENV_FILE=".env.prod.riso"
|
||||
ENV_OUT=".env.production"
|
||||
|
||||
#ENV_FILE=".env.prod.pcb"
|
||||
#ENV_OUT=".env.production"
|
||||
|
||||
# Array di cartelle e file da sincronizzare
|
||||
SYNC_ITEMS=(
|
||||
"css"
|
||||
|
||||
@@ -22,7 +22,7 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
|
||||
REMOTE_PORT="8822"
|
||||
REMOTE_DIR="$DIRECTORY_SERVER"
|
||||
SSH_OPTIONS="-p $REMOTE_PORT"
|
||||
CONFIG_JS="ecosystem.config.testriso.js"
|
||||
CONFIG_JS="ecosystem.config.riso_test.js"
|
||||
ENV_FILE=".env.test.risosrv"
|
||||
ENV_OUT=".env.test"
|
||||
|
||||
|
||||
38
docs/aaa.json
Normal file
38
docs/aaa.json
Normal file
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"id": "70606",
|
||||
"title": "Grande Libro dell'Autosufficienza - 50 anni - Nuovo",
|
||||
"description": "<em><strong>\"Il Grande Libro dell\u2019Autosufficienza\"<\/strong><\/em> di John Seymour \u00e8 un manuale completo che celebra 50 anni di pratiche di <strong>autosufficienza<\/strong> e <strong>sostenibilit\u00e0<\/strong>. Il libro offre insegnamenti pratici su come creare e gestire un <strong>orto biologico<\/strong>, raccogliere e conservare i raccolti, produrre <strong>energia rinnovabile<\/strong>, allevare animali e ridurre i rifiuti. Seymour ci guida passo passo in un viaggio verso una vita in armonia con la natura, promuovendo l\u2019indipendenza e la sostenibilit\u00e0. Un testo imprescindibile per chi desidera riscoprire le tradizioni agricole e applicarle per vivere in modo pi\u00f9 <strong>sostenibile<\/strong> e <strong>autonomo<\/strong>.\r\n<h2><strong>Con questo libro scoprirai<\/strong>:<\/h2>\r\n<ul>\r\n \t<li>Come <strong>coltivare un orto biologico<\/strong> e ottenere cibo sano.<\/li>\r\n \t<li>Le tecniche per <strong>conservare il raccolto<\/strong> e ottimizzare le risorse naturali.<\/li>\r\n \t<li>Come allevare animali per ottenere cibo e altri prodotti.<\/li>\r\n \t<li>Come produrre <strong>energia rinnovabile<\/strong> e ridurre l\u2019impatto ambientale.<\/li>\r\n \t<li>L\u2019arte di <strong>ridurre e riciclare<\/strong> rifiuti, promuovendo uno stile di vita pi\u00f9 sostenibile.<\/li>\r\n<\/ul>\r\n<h2><strong>Domande cruciali a cui <em>\"Il Grande Libro dell\u2019Autosufficienza\"<\/em> risponde<\/strong>:<\/h2>\r\n<ul>\r\n \t<li>Come posso vivere in modo <strong>autosufficiente<\/strong> e ridurre la mia dipendenza dalle risorse esterne?<\/li>\r\n \t<li>Quali sono le migliori tecniche per <strong>coltivare un orto biologico<\/strong> e garantire un raccolto abbondante?<\/li>\r\n \t<li>Come posso <strong>conservare il raccolto<\/strong> in modo naturale e duraturo?<\/li>\r\n \t<li>In che modo posso <strong>produrre energia rinnovabile<\/strong> a casa mia?<\/li>\r\n \t<li>Come posso vivere in <strong>armonia con la natura<\/strong> e promuovere la <strong>sostenibilit\u00e0<\/strong>?<\/li>\r\n<\/ul>\r\n<h2><strong>Questo libro \u00e8 dedicato a<\/strong>:<\/h2>\r\n<ul>\r\n \t<li>Lettori appassionati di <strong>giardinaggio<\/strong>, <strong>agricoltura biologica<\/strong> e vita rurale.<\/li>\r\n \t<li>Chiunque desideri adottare uno <strong>stile di vita sostenibile<\/strong> e autosufficiente.<\/li>\r\n \t<li><strong>Famiglie eco-consapevoli<\/strong> che vogliono ridurre il proprio impatto ambientale.<\/li>\r\n \t<li><strong>Amanti della natura<\/strong> e sostenitori delle <strong>energie rinnovabili<\/strong>.<\/li>\r\n<\/ul>\r\n<h2><strong>Contenuti chiave <em>\"Il Grande Libro dell\u2019Autosufficienza\"<\/em><\/strong>:<\/h2>\r\n<em>Il Grande Libro dell\u2019Autosufficienza<\/em> offre una panoramica completa di tutte le tecniche per vivere in modo <strong>autonomo<\/strong> e <strong>sostenibile<\/strong>. Attraverso 10 capitoli, il libro esplora vari aspetti dell\u2019autosufficienza, dalla coltivazione di ortaggi e frutti alla produzione di cibo dagli animali, fino alla gestione dell'energia e dei rifiuti. La guida si focalizza sul valore delle <strong>tradizioni agricole<\/strong>, sulla cura dell\u2019ambiente e sul benessere che deriva dal vivere in sintonia con la natura.\r\n\r\n ",
|
||||
"link": "https:\/\/www.fioredellavita.it\/grande-libro-dellautosufficienza-50-anni\/?attribute_pa_versione=nuovo",
|
||||
"image_link": "https:\/\/www.fioredellavita.it\/wp-content\/uploads\/2024\/09\/il-grande-libro-dell-autosufficienza-speciale-50-anni-copertina-web.jpg",
|
||||
"price": "39,00",
|
||||
"sale_price": "37,05",
|
||||
"categories": "Informazione Libera",
|
||||
"isbn": "",
|
||||
"Autore": "John,Seymour",
|
||||
"Editore": "Macro Edizioni",
|
||||
"Tipologia": "Libri",
|
||||
"Collezione": "Libri Informazione Libera,Informazione Libera",
|
||||
"Quantita": "1821",
|
||||
"Lunghezza": "",
|
||||
"Stato": "publish",
|
||||
"Pagine": "",
|
||||
"Edizione": "",
|
||||
"Traduzione": "",
|
||||
"Versione": "Nuovo",
|
||||
"StockStatus": "instock",
|
||||
"downloadable": "no",
|
||||
"img1": "https:\/\/www.fioredellavita.it\/wp-content\/uploads\/2024\/09\/quarta_nuovo_grande_libro_dell_autosufficienza_2024_17038.jpg",
|
||||
"img2": "",
|
||||
"img3": "",
|
||||
"formato": "Cartonato",
|
||||
"preOrderDate": "2025-02-25",
|
||||
"short_descr": null,
|
||||
"availability": "in stock",
|
||||
"checkout_link": "https:\/\/www.fioredellavita.it\/carrello\/?productId=70606",
|
||||
"seo_descr": "Versione: Nuovo",
|
||||
"preord": "no",
|
||||
"addtocart_link": "https:\/\/www.fioredellavita.it\/grande-libro-dellautosufficienza-50-anni\/?attribute_pa_versione=nuovo&variation_id=70606&add-to-cart=70606",
|
||||
"eta": "",
|
||||
"misure": "cm 22x28",
|
||||
"sku": "22464"
|
||||
},
|
||||
@@ -1,839 +0,0 @@
|
||||
require('./config/config');
|
||||
require('./config/config');
|
||||
|
||||
// console.log(" lodash");
|
||||
|
||||
console.log(process.versions);
|
||||
|
||||
const _ = require('lodash');
|
||||
// console.log(" cors");
|
||||
const cors = require('cors');
|
||||
|
||||
// console.log(" 2) fs");
|
||||
const fs = require('fs');
|
||||
|
||||
var https = require('https');
|
||||
|
||||
const NUOVO_METODO_TEST = true;
|
||||
|
||||
const server_constants = require('./tools/server_constants');
|
||||
|
||||
//const throttle = require('express-throttle-bandwidth');
|
||||
// app.use(throttle(1024 * 128)) // throttling bandwidth
|
||||
|
||||
const port = process.env.PORT;
|
||||
|
||||
// var cookieParser = require('cookie-parser')
|
||||
// var csrf = require('csurf')
|
||||
const express = require('express');
|
||||
const bodyParser = require('body-parser');
|
||||
const path = require('path');
|
||||
|
||||
const cron = require('node-cron');
|
||||
console.log('Starting mongoose...');
|
||||
|
||||
const tls = require('tls');
|
||||
|
||||
require('./db/mongoose');
|
||||
|
||||
// console.log('Starting pem...');
|
||||
|
||||
// const pem = require('pem')
|
||||
|
||||
const { Settings } = require('./models/settings');
|
||||
|
||||
const Site = require('./models/site');
|
||||
|
||||
// test
|
||||
|
||||
const i18n = require('i18n');
|
||||
|
||||
let credentials = null;
|
||||
|
||||
// OBTAIN
|
||||
// https://www.psclistens.com/insight/blog/enabling-a-nodejs-ssl-webserver-using-let-s-encrypt-pem-certificates/
|
||||
|
||||
|
||||
if ((process.env.NODE_ENV === 'production')) {
|
||||
console.log('*** AMBIENTE DI PRODUZIONE (Aprile 2024) !!!!')
|
||||
} else if (process.env.NODE_ENV === 'test') {
|
||||
console.log('*** ### AMBIENTE DI TEST ')
|
||||
}
|
||||
|
||||
|
||||
console.log('DB: ' + process.env.DATABASE);
|
||||
// console.log("PORT: " + port);
|
||||
// console.log("MONGODB_URI: " + process.env.MONGODB_URI);
|
||||
|
||||
var app = express();
|
||||
|
||||
|
||||
let telegrambot = null;
|
||||
|
||||
const tools = require('./tools/general');
|
||||
|
||||
const shared_consts = require('./tools/shared_nodejs');
|
||||
|
||||
var mongoose = require('mongoose').set('debug', false);
|
||||
|
||||
mongoose.set('debug', false);
|
||||
|
||||
const { CfgServer } = require('./models/cfgserver');
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const populate = require('./populate/populate');
|
||||
const { Circuit } = require('./models/circuit');
|
||||
|
||||
const printf = require('util').format;
|
||||
|
||||
myLoad().then(ris => {
|
||||
|
||||
const { User } = require('./models/user');
|
||||
|
||||
require('./models/todo');
|
||||
require('./models/project');
|
||||
require('./models/subscribers');
|
||||
require('./models/booking');
|
||||
require('./models/sendmsg');
|
||||
require('./models/sendnotif');
|
||||
require('./models/mailinglist');
|
||||
require('./models/newstosent');
|
||||
require('./models/mypage');
|
||||
require('./models/myelem');
|
||||
require('./models/bot');
|
||||
require('./models/calzoom');
|
||||
const mysql_func = require('./mysql/mysql_func');
|
||||
|
||||
const index_router = require('./router/index_router');
|
||||
const push_router = require('./router/push_router');
|
||||
const newsletter_router = require('./router/newsletter_router');
|
||||
const booking_router = require('./router/booking_router');
|
||||
const dashboard_router = require('./router/dashboard_router');
|
||||
const myevent_router = require('./router/myevent_router');
|
||||
const subscribe_router = require('./router/subscribe_router');
|
||||
const sendmsg_router = require('./router/sendmsg_router');
|
||||
const sendnotif_router = require('./router/sendnotif_router');
|
||||
const email_router = require('./router/email_router');
|
||||
const todos_router = require('./router/todos_router');
|
||||
const test_router = require('./router/test_router');
|
||||
const projects_router = require('./router/projects_router');
|
||||
const report_router = require('./router/report_router');
|
||||
const users_router = require('./router/users_router');
|
||||
const reactions_router = require('./router/reactions_router');
|
||||
const mygroups_router = require('./router/mygroups_router');
|
||||
const circuits_router = require('./router/circuits_router');
|
||||
const accounts_router = require('./router/accounts_router');
|
||||
const iscrittiConacreis_router = require('./router/iscrittiConacreis_router');
|
||||
const iscrittiArcadei_router = require('./router/iscrittiArcadei_router');
|
||||
const site_router = require('./router/site_router');
|
||||
const admin_router = require('./router/admin_router');
|
||||
const products_router = require('./router/products_router');
|
||||
const cart_router = require('./router/cart_router');
|
||||
const orders_router = require('./router/orders_router');
|
||||
const city_router = require('./router/city_router');
|
||||
const myskills_router = require('./router/myskills_router');
|
||||
const mygoods_router = require('./router/mygoods_router');
|
||||
const mygen_router = require('./router/mygen_router');
|
||||
const aitools_router = require('./router/aitools_router');
|
||||
|
||||
const { MyEvent } = require('./models/myevent');
|
||||
|
||||
app.use(bodyParser.json({ limit: '50mb' }));
|
||||
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
||||
|
||||
app.use(express.static('views'));
|
||||
|
||||
// app.use(express.static(path.join(__dirname, 'client')));
|
||||
|
||||
app.use(bodyParser.json());
|
||||
|
||||
// app.set('view engine', 'pug');
|
||||
|
||||
// Set static folder
|
||||
// app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
i18n.configure({
|
||||
locales: ['it', 'enUs', 'es', 'fr', 'pt', 'si'],
|
||||
defaultLocale: 'it',
|
||||
// cookie: 'cook',
|
||||
directory: __dirname + '/locales',
|
||||
api: {
|
||||
'__': 'translate',
|
||||
'__n': 'translateN'
|
||||
},
|
||||
});
|
||||
|
||||
app.use(cors({
|
||||
exposedHeaders: ['x-auth', 'x-refrtok'],
|
||||
}));
|
||||
|
||||
app.use(bodyParser.json());
|
||||
|
||||
// app.use(express.cookieParser());
|
||||
app.use(i18n.init);
|
||||
|
||||
console.log('Use Routes \...');
|
||||
|
||||
|
||||
// Use Routes
|
||||
app.use('/', index_router);
|
||||
app.use('/subscribe', subscribe_router);
|
||||
app.use('/sendmsg', sendmsg_router);
|
||||
app.use('/sendnotif', sendnotif_router);
|
||||
app.use('/push', push_router);
|
||||
app.use('/news', newsletter_router);
|
||||
app.use('/booking', booking_router);
|
||||
app.use('/dashboard', dashboard_router);
|
||||
app.use('/event', myevent_router);
|
||||
app.use('/email', email_router);
|
||||
app.use('/todos', todos_router);
|
||||
app.use('/test', test_router);
|
||||
app.use('/projects', projects_router);
|
||||
app.use('/users', users_router);
|
||||
app.use('/reactions', reactions_router);
|
||||
app.use('/mygroup', mygroups_router);
|
||||
app.use('/circuit', circuits_router);
|
||||
app.use('/account', accounts_router);
|
||||
app.use('/iscritti_conacreis', iscrittiConacreis_router);
|
||||
app.use('/iscritti_arcadei', iscrittiArcadei_router);
|
||||
app.use('/report', report_router);
|
||||
app.use('/site', site_router);
|
||||
app.use('/admin', admin_router);
|
||||
app.use('/products', products_router);
|
||||
app.use('/cart', cart_router);
|
||||
app.use('/orders', orders_router);
|
||||
app.use('/city', city_router);
|
||||
app.use('/myskills', myskills_router);
|
||||
app.use('/mygoods', mygoods_router);
|
||||
app.use('/mygen', mygen_router);
|
||||
app.use('/aitools', aitools_router);
|
||||
|
||||
// catch 404 and forward to error handler
|
||||
// app.use(function (req, res, next) {
|
||||
// var err = new Error('Not Found');
|
||||
// err.status = 404;
|
||||
// next(err);
|
||||
// });
|
||||
|
||||
// app.set('views', path.join(__dirname, 'views'));
|
||||
// app.set('view engine', 'pug');
|
||||
|
||||
// development error handler
|
||||
// will print stacktrace
|
||||
if (app.get('env') === 'development') {
|
||||
|
||||
app.use(function (err, req, res, next) {
|
||||
console.log('Server Error: ', err.message);
|
||||
// console.trace();
|
||||
res.status(err.status || 500).send({ error: err.message });
|
||||
// res.render('error', {
|
||||
// message: err.message,
|
||||
// error: err
|
||||
// });
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// require('./telegram/telegrambot');
|
||||
|
||||
// *** DB CONNECTIONS ***
|
||||
// mysql_func.mySqlConn_Shen.connect((err) => {
|
||||
// if (!err)
|
||||
// console.log('DB connection to Shen Database succeded.');
|
||||
// else
|
||||
// console.log('DB connection to Shen Database FAILED \n Error: ' + JSON.stringify(err, undefined, 2));
|
||||
// });
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
console.log('*** PRODUCTION! ');
|
||||
}
|
||||
|
||||
if ((process.env.NODE_ENV === 'production') ||
|
||||
(process.env.NODE_ENV === 'test')) {
|
||||
|
||||
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
|
||||
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
|
||||
|
||||
let privateKey = fs.readFileSync(keyStream, "utf8");
|
||||
let certificate = fs.readFileSync(certificateStream, "utf8");
|
||||
|
||||
let credentials = null;
|
||||
|
||||
|
||||
// arrSecureContext = ['piuchebuono.app', 'gruppomacro.app'];
|
||||
arrSecureContext = ['freeplanet.app', 'riso.app', 'comunitanuovomondo.app'];
|
||||
|
||||
let secureContext = {};
|
||||
|
||||
for (let i = 0; i < arrSecureContext.length; i++) {
|
||||
try {
|
||||
secureContext = {
|
||||
...secureContext,
|
||||
[arrSecureContext[i]]: tls.createSecureContext({
|
||||
key: fs.readFileSync('/etc/letsencrypt/live/' + arrSecureContext[i] + '/privkey.pem'),
|
||||
cert: fs.readFileSync('/etc/letsencrypt/live/' + arrSecureContext[i] + '/fullchain.pem')
|
||||
// ca: fs.readFileSync('../path_to_certificate_authority_bundle.ca-bundle1', 'utf8'), // this ca property is optional
|
||||
})
|
||||
}
|
||||
|
||||
credentials = {
|
||||
SNICallback: function (domain, cb) {
|
||||
if (secureContext) {
|
||||
if (cb) {
|
||||
cb(null, secureContext);
|
||||
} else {
|
||||
// compatibility for older versions of node
|
||||
return secureContext;
|
||||
}
|
||||
} else {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('Error: ' + err);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
let secureContext = {
|
||||
'piuchebuono.app': tls.createSecureContext({
|
||||
key: fs.readFileSync('/etc/letsencrypt/live/piuchebuono.app/privkey.pem'),
|
||||
cert: fs.readFileSync('/etc/letsencrypt/live/piuchebuono.app/fullchain.pem')
|
||||
// ca: fs.readFileSync('../path_to_certificate_authority_bundle.ca-bundle1', 'utf8'), // this ca property is optional
|
||||
}),
|
||||
'gruppomacro.app': tls.createSecureContext({
|
||||
key: fs.readFileSync('/etc/letsencrypt/live/gruppomacro.app/privkey.pem'),
|
||||
cert: fs.readFileSync('/etc/letsencrypt/live/gruppomacro.app/fullchain.pem')
|
||||
// ca: fs.readFileSync('../path_to_certificate_authority_bundle.ca-bundle1', 'utf8'), // this ca property is optional
|
||||
}),
|
||||
}*/
|
||||
|
||||
console.log('secureContext', secureContext);
|
||||
|
||||
if (NUOVO_METODO_TEST) {
|
||||
credentials = {
|
||||
SNICallback: function (domain, cb) {
|
||||
if (secureContext[domain]) {
|
||||
if (cb) {
|
||||
cb(null, secureContext[domain]);
|
||||
} else {
|
||||
// compatibility for older versions of node
|
||||
return secureContext[domain];
|
||||
}
|
||||
} else {
|
||||
throw new Error('No keys/certificates for domain requested');
|
||||
}
|
||||
},
|
||||
// must list a default key and cert because required by tls.createServer()
|
||||
key: privateKey,
|
||||
cert: certificate,
|
||||
}
|
||||
|
||||
/*} else {
|
||||
// NON USATO !
|
||||
credentials = {
|
||||
key: privateKey,
|
||||
cert: certificate,
|
||||
ca: [
|
||||
fs.readFileSync(process.env.PATH_SSL_ROOT_PEM, 'utf8'),
|
||||
fs.readFileSync(process.env.PATH_SSL_CHAIN_PEM, 'utf8'),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/*} else {
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
if (process.env.HTTPS_LOCALHOST === "true") {
|
||||
privateKey = fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8');
|
||||
certificate = fs.readFileSync(process.env.PATH_SERVER_CRT, 'utf8');
|
||||
credentials = {
|
||||
key: privateKey,
|
||||
cert: certificate,
|
||||
ciphers: 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
|
||||
honorCipherOrder: true,
|
||||
secureProtocol: 'TLSv1_2_method',
|
||||
};
|
||||
|
||||
} else {
|
||||
var http = require('http');
|
||||
}
|
||||
|
||||
if ((process.env.NODE_ENV === 'production') ||
|
||||
(process.env.NODE_ENV === 'test') || process.env.HTTPS_LOCALHOST === "true") {
|
||||
|
||||
const httpsServer = https.createServer(credentials, app);
|
||||
|
||||
console.log('httpsServer: port ', port);
|
||||
httpsServer.listen(port);
|
||||
} else {
|
||||
console.log('httpServer: port ', port);
|
||||
const httpServer = http.createServer(app);
|
||||
httpServer.listen(port);
|
||||
}
|
||||
|
||||
mystart();
|
||||
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
// app.use(throttle(1024 * 128)); // throttling bandwidth
|
||||
|
||||
// app.use((req, res, next) => {
|
||||
// res.header('Access-Control-Allow-Origin', '*')
|
||||
// res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
|
||||
// next()
|
||||
// });
|
||||
|
||||
async function myLoad() {
|
||||
|
||||
return tools.loadApps();
|
||||
}
|
||||
|
||||
async function mystart() {
|
||||
|
||||
// await estraiTutteLeImmagini();
|
||||
|
||||
await tools.getApps();
|
||||
|
||||
if (process.env.PROD !== 1) {
|
||||
|
||||
testmsgwebpush();
|
||||
|
||||
// tools.sendNotifToAdmin('Riparti', 'Riparti');
|
||||
|
||||
let miapass = '';
|
||||
|
||||
if (miapass !== '') {
|
||||
let crypt = tools.cryptdata(miapass);
|
||||
let decrypt = tools.decryptdata(crypt);
|
||||
|
||||
console.log('crypted:', crypt);
|
||||
console.log('decrypted:', decrypt);
|
||||
}
|
||||
|
||||
mycron();
|
||||
if (!process.env.VITE_DEBUG) {
|
||||
mycron();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
telegrambot = require('./telegram/telegrambot');
|
||||
|
||||
await inizia();
|
||||
|
||||
await resetProcessingJob();
|
||||
|
||||
populate.popolaTabelleNuove();
|
||||
|
||||
faitest();
|
||||
|
||||
// ----------------- MAILCHIMP -----
|
||||
const querystring = require('querystring');
|
||||
const mailchimpClientId = 'xxxxxxxxxxxxxxxx';
|
||||
|
||||
app.get('/mailchimp/auth/authorize', function (req, res) {
|
||||
res.redirect('https://login.mailchimp.com/oauth2/authorize?' +
|
||||
querystring.stringify({
|
||||
'response_type': 'code',
|
||||
'client_id': mailchimpClientId,
|
||||
'redirect_uri': 'http://127.0.0.1:3000/mailchimp/auth/callback',
|
||||
}));
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// -----------------
|
||||
|
||||
function populateDBadmin() {
|
||||
const cfgserv = [
|
||||
{
|
||||
_id: new ObjectId(),
|
||||
idapp: '9',
|
||||
chiave: 'vers',
|
||||
userId: 'ALL',
|
||||
valore: '0.1.2',
|
||||
}];
|
||||
|
||||
let cfg = new CfgServer(cfgserv[0]).save();
|
||||
}
|
||||
|
||||
async function mycron() {
|
||||
|
||||
try {
|
||||
const sendemail = require('./sendemail');
|
||||
|
||||
const arr = await tools.getApps();
|
||||
|
||||
for (const app of arr) {
|
||||
sendemail.checkifPendingNewsletter(app.idapp);
|
||||
sendemail.checkifSentNewsletter(app.idapp);
|
||||
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Err mycron', e);
|
||||
}
|
||||
}
|
||||
|
||||
async function mycron_30min() {
|
||||
for (const app of await tools.getApps()) {
|
||||
let enablecrontab = false;
|
||||
|
||||
enablecrontab = await Settings.getValDbSettings(app.idapp,
|
||||
tools.ENABLE_CRONTAB, false);
|
||||
|
||||
if (enablecrontab) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function mycron_everyday() {
|
||||
try {
|
||||
|
||||
const { User } = require('./models/user');
|
||||
|
||||
const arrapps = await tools.getApps();
|
||||
for (const app of arrapps) {
|
||||
|
||||
// Azzera le richieste di password:
|
||||
const usersblocked = await User.find({ idapp: app.idapp, retry_pwd: { $exists: true, $gte: 29 } }).lean();
|
||||
for (const user of usersblocked) {
|
||||
await User.findOneAndUpdate({ _id: user._id }, { $set: { retry_pwd: 20 } });
|
||||
let text = `⚠️⚠️⚠️ L\'utente ${user.username} (${user.name} ${user.surname}) viene sbloccato dal numero massimo di tentativi di richiesta password!\nTelerlo d\'occhio !\n@${user.profile.username_telegram}`;
|
||||
await telegrambot.sendMsgTelegramToTheAdminAllSites(text, false);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Crea un file con all'interno il nome del dominio per ogni app:
|
||||
await tools.createFileWithDomainName();
|
||||
|
||||
} catch (e) {
|
||||
console.error('mycron_everyday: ', e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function testmsgwebpush() {
|
||||
const { User } = require('./models/user');
|
||||
|
||||
// console.log('nomeapp 1: ' , tools.getNomeAppByIdApp(1));
|
||||
// console.log('nomeapp 2: ' , tools.getNomeAppByIdApp(2));
|
||||
|
||||
User.find({ username: 'paoloar77', idapp: '1' }).then(async (arrusers) => {
|
||||
if (arrusers !== null) {
|
||||
for (const user of arrusers) {
|
||||
await tools.sendNotificationToUser(user._id, 'Server',
|
||||
'Il Server è Ripartito', '/', '', 'server', []).then(ris => {
|
||||
if (ris) {
|
||||
|
||||
} else {
|
||||
// already sent the error on calling sendNotificationToUser
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// Cron every X minutes
|
||||
cron.schedule('*/1 * * * *', () => {
|
||||
// console.log('Running Cron Job');
|
||||
// if (!process.env.VITE_DEBUG) {
|
||||
mycron();
|
||||
// }
|
||||
});
|
||||
|
||||
// Cron every X minutes
|
||||
cron.schedule('*/60 * * * *', async () => {
|
||||
if (!process.env.VITE_DEBUG) {
|
||||
mycron_30min();
|
||||
}
|
||||
});
|
||||
|
||||
// Cron every 21:00 (1 volta al giorno)
|
||||
cron.schedule('0 21 * * *', async () => {
|
||||
mycron_everyday();
|
||||
});
|
||||
|
||||
// mycron_30min();
|
||||
|
||||
// tools.writelogfile('test', 'prova.txt');
|
||||
|
||||
async function resetProcessingJob() {
|
||||
|
||||
const { Newstosent } = require('./models/newstosent');
|
||||
|
||||
arrrec = await Newstosent.find({});
|
||||
|
||||
for (const rec of arrrec) {
|
||||
rec.processing_job = false;
|
||||
await Newstosent.findOneAndUpdate({ _id: rec.id }, { $set: rec }, { new: false }).
|
||||
then((item) => {
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//app.listen(port, () => {
|
||||
// console.log(`Server started at port ${port}`);
|
||||
//});
|
||||
|
||||
async function inizia() {
|
||||
|
||||
try {
|
||||
if (true) {
|
||||
const url = 'https://raw.githubusercontent.com/matteocontrini/comuni-json/master/comuni.json';
|
||||
const outputPath = './comuni_italia_geojson.json';
|
||||
downloadGeoJSON(url, outputPath);
|
||||
}
|
||||
|
||||
mycron_everyday();
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
await telegrambot.sendMsgTelegram(tools.FREEPLANET,
|
||||
shared_consts.ADMIN_USER_SERVER,
|
||||
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}!`);
|
||||
|
||||
await telegrambot.sendMsgTelegramByIdTelegram(tools.FREEPLANET,
|
||||
telegrambot.ADMIN_IDTELEGRAM_SERVER,
|
||||
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}\n` +
|
||||
`🔅 Il Server ${process.env.DATABASE} è appena ripartito!`);
|
||||
|
||||
} else {
|
||||
|
||||
await telegrambot.sendMsgTelegramToTheAdminAllSites(`Ciao Admin\n` + `🔅🔅🔅 Il Server col BOT di {appname} è appena ripartito!`, false);
|
||||
|
||||
}
|
||||
|
||||
await Site.createFirstUserAdmin();
|
||||
|
||||
/*const {Circuit} = require('./models/circuit');
|
||||
|
||||
await Circuit.setDeperimentoOff();
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
// telegrambot.sendMsgTelegramToTheManagers('7', 'PROVAAA!');
|
||||
|
||||
// if (process.env.PROD !== 1) {
|
||||
// const reg = require('./reg/registration');
|
||||
// const link = reg.getlinkregByEmail('7', 'tomasihelen@dasdasgmail.comAAAA' , 'HelenTomasidasdasd');
|
||||
// const link2 = reg.getlinkregByEmail('7', 'tomasihelen@gmail.com' , 'HelenTomasi');
|
||||
// //const link2 = reg.getlinkregByEmail('7', 'elenaliubicich@gmail.com' , 'Elenaliu');
|
||||
//
|
||||
// console.log(link);
|
||||
// console.log(link2);
|
||||
// }
|
||||
|
||||
async function estraiImmagini(table) {
|
||||
const { User } = require('./models/user');
|
||||
|
||||
let idapp = '13';
|
||||
|
||||
let arrlist;
|
||||
|
||||
const globalTables = require('./tools/globalTables');
|
||||
|
||||
|
||||
const mytable = globalTables.getTableByTableName(table);
|
||||
if (!mytable)
|
||||
return;
|
||||
|
||||
console.log('INIZIO - estraiImmagini', table);
|
||||
|
||||
arrlist = await mytable.find({ idapp }).lean();
|
||||
|
||||
let file = '';
|
||||
let filetocheck = '';
|
||||
let dirmain = '';
|
||||
let filefrom = '';
|
||||
let filefrom2 = '';
|
||||
let dir = tools.getdirByIdApp(idapp) + dirmain + '/upload/';
|
||||
|
||||
try {
|
||||
if (!tools.sulServer()) {
|
||||
dirmain = '/public';
|
||||
}
|
||||
|
||||
for (const rec of arrlist) {
|
||||
const myuser = await User.findOne({ idapp, _id: rec.userId }).lean();
|
||||
if (myuser) {
|
||||
const myphotos = rec.photos;
|
||||
|
||||
if (myphotos.length > 0) {
|
||||
let folderprof = dir + 'profile/' + myuser.username;
|
||||
|
||||
try {
|
||||
// console.log('checkdir', folderprof);
|
||||
if (!fs.existsSync(folderprof)) {
|
||||
console.log('*** Creadir', folderprof);
|
||||
fs.mkdirSync(folderprof);
|
||||
}
|
||||
|
||||
folderprof = dir + 'profile/' + myuser.username + '/' + table;
|
||||
// console.log('checkdir', folderprof);
|
||||
if (!fs.existsSync(folderprof)) {
|
||||
console.log('creadir', folderprof);
|
||||
fs.mkdirSync(folderprof);
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
for (const photo of myphotos) {
|
||||
|
||||
if (photo.imagefile) {
|
||||
file = dir + 'profile/' + myuser.username + '/' + table + '/' +
|
||||
photo.imagefile;
|
||||
filefrom = dir + 'profile/undefined/' + table + '/' + photo.imagefile;
|
||||
filefrom2 = dir + 'profile/' + myuser.username + '/' + photo.imagefile;
|
||||
|
||||
// console.log('file', file);
|
||||
// console.log('filefrom', filefrom);
|
||||
|
||||
if (!tools.isFileExists(file)) {
|
||||
// non esiste
|
||||
console.log('non esiste', file);
|
||||
console.log(' filefrom', filefrom);
|
||||
console.log(' filefrom2', filefrom2);
|
||||
}
|
||||
|
||||
if (!tools.isFileExists(file) && tools.isFileExists(filefrom)) {
|
||||
console.log('@@@@@@ copia file:', filefrom, 'a', file);
|
||||
tools.copy(filefrom, file);
|
||||
}
|
||||
if (!tools.isFileExists(file) && tools.isFileExists(filefrom2)) {
|
||||
console.log('@@@@@@ copia file 2:', filefrom2, 'a', file);
|
||||
tools.copy(filefrom2, file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log('FINE - estraiImmagini', table);
|
||||
} catch (e) {
|
||||
console.error('e', e);
|
||||
}
|
||||
}
|
||||
|
||||
async function estraiTutteLeImmagini() {
|
||||
|
||||
await estraiImmagini('myskills');
|
||||
await estraiImmagini('mygoods');
|
||||
await estraiImmagini('mybachecas');
|
||||
}
|
||||
|
||||
async function faitest() {
|
||||
// console.log('Fai Test:')
|
||||
|
||||
const testfind = false;
|
||||
|
||||
// const $vers = tools.getVersionint('1.92.45');
|
||||
|
||||
if (true) {
|
||||
// tools.execScript("ls -la");
|
||||
}
|
||||
|
||||
if (false) {
|
||||
prova = tools.removeAtChar('@prova');
|
||||
}
|
||||
|
||||
if (false) {
|
||||
const prova = tools.getConfSiteOptionEnabledByIdApp('13', shared_consts.ConfSite.Notif_Reg_Push_Admin);
|
||||
console.log('prova', prova);
|
||||
}
|
||||
|
||||
if (testfind) {
|
||||
const { City } = require('./models/city');
|
||||
|
||||
let miacity = 'roma';
|
||||
const ris = await City.findByCity(miacity);
|
||||
|
||||
console.log('ris', ris);
|
||||
}
|
||||
|
||||
const { User } = require('./models/user');
|
||||
|
||||
if (false) {
|
||||
let myuser = await User.findOne({
|
||||
idapp: '1',
|
||||
username: 'paoloar77',
|
||||
});
|
||||
const langdest = 'it';
|
||||
|
||||
telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser);
|
||||
|
||||
}
|
||||
|
||||
if (false) {
|
||||
|
||||
const user = await User.findOne({
|
||||
idapp: 12,
|
||||
username: 'paolotest1',
|
||||
});
|
||||
|
||||
await sendemail.sendEmail_Registration('it', 'paolo@arcodiluce.it', user,
|
||||
'12', '');
|
||||
|
||||
}
|
||||
|
||||
if (false) {
|
||||
|
||||
const { User } = require('./models/user');
|
||||
|
||||
const idapp = tools.FREEPLANET;
|
||||
const idreg = 0;
|
||||
|
||||
try {
|
||||
|
||||
const user = await User.findOne({
|
||||
idapp,
|
||||
username: 'paoloar773',
|
||||
});
|
||||
|
||||
user.aportador_solidario = 'paoloar77';
|
||||
|
||||
let mylocalsconf = {
|
||||
idapp,
|
||||
dataemail: null,
|
||||
locale: user.lang,
|
||||
nomeapp: tools.getNomeAppByIdApp(idapp),
|
||||
strlinksito: tools.getHostByIdApp(idapp),
|
||||
strlinkreg: '',
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
surname: user.surname,
|
||||
forgetpwd: tools.getHostByIdApp(idapp) + '/requestresetpwd',
|
||||
emailto: '',
|
||||
user,
|
||||
};
|
||||
|
||||
await telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION,
|
||||
mylocalsconf);
|
||||
} catch (e) {
|
||||
console.log('error ' + e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { app };
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: "PiuCheBuono",
|
||||
name: "PiuCheBuono (Prod)",
|
||||
script: "/var/www/nodejs_piuchebuono_server/src/server/server.js",
|
||||
ignore_watch: ["node_modules", "logs"],
|
||||
//autorestart: true,
|
||||
interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node",
|
||||
//autorestart: true,
|
||||
instances: 1,
|
||||
watch: false,
|
||||
env: {
|
||||
@@ -5,7 +5,6 @@ module.exports = {
|
||||
script: "/var/www/nodejs_test.piuchebuono_server/src/server/server.js",
|
||||
ignore_watch: ["node_modules", "logs"],
|
||||
interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node",
|
||||
//autorestart: true,
|
||||
instances: 1,
|
||||
watch: false,
|
||||
env: {
|
||||
@@ -1,7 +1,7 @@
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: "RISO",
|
||||
name: "RISO (Prod)",
|
||||
script: "/var/www/nodejs_riso_server/src/server/server.js",
|
||||
ignore_watch: ["node_modules", "logs"],
|
||||
interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node",
|
||||
@@ -6,7 +6,6 @@ module.exports = {
|
||||
ignore_watch: ["node_modules", "logs"],
|
||||
interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node",
|
||||
watch: false,
|
||||
//autorestart: true,
|
||||
instances: 1,
|
||||
env_test: {
|
||||
"PORT": 3001,
|
||||
@@ -18,232 +18,270 @@
|
||||
- var baseimg = baseurl + '/'
|
||||
doctype html
|
||||
html
|
||||
- if (dataemail.title)
|
||||
head
|
||||
title dataemail.subject
|
||||
head
|
||||
meta(charset="utf-8")
|
||||
meta(name="viewport", content="width=device-width, initial-scale=1")
|
||||
title= dataemail.title || "Email"
|
||||
style.
|
||||
/* embedded CSS */
|
||||
body { margin:0; padding:0; background:#E9F2F9; font-family:Tahoma, Geneva, sans-serif; color:#5b656e; }
|
||||
a { color:#09c; text-decoration:none; }
|
||||
table, td { border-collapse:collapse; }
|
||||
h1,h2,h3,p { margin:0; padding:0; }
|
||||
|
||||
//- import css/scss stylesheets
|
||||
//- these file names will be replace by gulp with proper css file paths
|
||||
link(rel="stylesheet", href="../sass/basic.scss")
|
||||
link(rel="stylesheet", href="../sass/one/styles.scss")
|
||||
.logoContainer { text-align:center; padding:20px 0; }
|
||||
.logoContainer img { max-width:200px; }
|
||||
|
||||
//- embdedded css allowed, but not sass
|
||||
style.
|
||||
.red {
|
||||
background-color: #E84C50;
|
||||
}
|
||||
.testomail { padding:10px; font-size:0.75rem; line-height:1.4; }
|
||||
|
||||
.full-width {
|
||||
width: 100%;
|
||||
}
|
||||
.clpromo {
|
||||
background-color:orange;
|
||||
text-align:center;
|
||||
font-size:1rem;
|
||||
padding:10px;
|
||||
color:#fff;
|
||||
font-weight:bold;
|
||||
}
|
||||
|
||||
.emailContainer {
|
||||
background:#fff;
|
||||
border-radius:10px;
|
||||
padding:20px;
|
||||
margin:20px auto;
|
||||
}
|
||||
|
||||
.sectionArticleImage img {
|
||||
max-width:150px;
|
||||
border:1px solid #ccc;
|
||||
display:block;
|
||||
margin-bottom:10px;
|
||||
}
|
||||
|
||||
.teacher {
|
||||
font-style:italic;
|
||||
font-size:0.75rem;
|
||||
color:#555;
|
||||
}
|
||||
|
||||
.contrib {
|
||||
font-size:0.75rem;
|
||||
font-weight:bold;
|
||||
color:#333;
|
||||
}
|
||||
|
||||
.button a {
|
||||
display:inline-block;
|
||||
padding:10px 20px;
|
||||
background:#f75666;
|
||||
color:#fff !important;
|
||||
text-decoration:none;
|
||||
border-radius:10px;
|
||||
font-size:13px;
|
||||
}
|
||||
|
||||
.button2 a {
|
||||
display:block;
|
||||
padding:12px 20px;
|
||||
background:#0000ff;
|
||||
color:#fff !important;
|
||||
text-decoration:none;
|
||||
border-radius:10px;
|
||||
font-size:1.15rem;
|
||||
}
|
||||
|
||||
.center_img img {
|
||||
display:block;
|
||||
margin:0 auto;
|
||||
}
|
||||
|
||||
.discContainer {
|
||||
background:#fff;
|
||||
border-radius:10px;
|
||||
padding:20px;
|
||||
margin:20px auto;
|
||||
}
|
||||
|
||||
.LinkDisc a {
|
||||
text-decoration:none;
|
||||
}
|
||||
|
||||
.pDisc:hover {
|
||||
background:#5c8ef4 !important;
|
||||
color:#fff !important;
|
||||
}
|
||||
|
||||
.pDisc {
|
||||
padding:5px 10px;
|
||||
border-radius:10px;
|
||||
display:inline-block;
|
||||
}
|
||||
|
||||
.socialMedia {
|
||||
background:#8bafcb;
|
||||
text-align:center;
|
||||
padding:10px 0;
|
||||
}
|
||||
|
||||
.socialMedia img {
|
||||
width:29px;
|
||||
height:auto;
|
||||
border:0;
|
||||
}
|
||||
|
||||
.firma-container {
|
||||
background:#ffffff;
|
||||
padding:15px;
|
||||
text-align:center;
|
||||
border-top:1px solid #e0e0e0;
|
||||
font-size:0.85rem;
|
||||
color:#313a42;
|
||||
}
|
||||
|
||||
.disclaimer-container {
|
||||
background:#f9f9f9;
|
||||
padding:15px;
|
||||
text-align:center;
|
||||
font-size:0.75rem;
|
||||
color:#666;
|
||||
border-top:1px solid #eee;
|
||||
border-bottom:1px solid #eee;
|
||||
}
|
||||
|
||||
.bottom-container {
|
||||
background:#e9f2f9;
|
||||
padding:15px;
|
||||
text-align:center;
|
||||
font-size:0.7rem;
|
||||
color:#999;
|
||||
}
|
||||
|
||||
.whitespace {
|
||||
line-height:0;
|
||||
font-size:0;
|
||||
height:20px;
|
||||
}
|
||||
|
||||
@media only screen and (max-width:480px) {
|
||||
.button a, .button2 a {
|
||||
font-size:1rem !important;
|
||||
width:100%;
|
||||
}
|
||||
.sectionArticleImage,
|
||||
.column {
|
||||
width:100% !important;
|
||||
display:block !important;
|
||||
}
|
||||
}
|
||||
body(yahoofix)
|
||||
span(id='body_style', style='display:block')
|
||||
table(class="topHeader", cellpadding="0", cellspacing="0", width="100%")
|
||||
- if (dataemail.height_logo)
|
||||
tr
|
||||
td
|
||||
table(cellpadding="0", cellspacing="0", align="center", summary="")
|
||||
tr
|
||||
td.logoContainer
|
||||
a(href=baseurl, title='logo')
|
||||
img.logo(src=baseurl+"/images/logo.png", height=dataemail.height_logo)
|
||||
|
||||
span#body_style(style='display:block')
|
||||
// Header
|
||||
table(width="100%", cellpadding="0", cellspacing="0", align="center")
|
||||
tr
|
||||
td.testomail
|
||||
p!= dataemail.templ.testoheadermail_out
|
||||
td.logoContainer
|
||||
a(href=baseurl)
|
||||
img.logo(src=baseurl+"/public/images/logo.png", alt="Logo")
|
||||
|
||||
- if (dataemail.templ.options.includes('SHOW_PROMO'))
|
||||
if dataemail.templ.testoheadermail_out
|
||||
tr
|
||||
td.testomail
|
||||
p!= dataemail.templ.testoheadermail_out
|
||||
|
||||
if dataemail.templ.options.includes('SHOW_PROMO')
|
||||
tr
|
||||
td.clpromo
|
||||
p!= dataemail.textpromo
|
||||
|
||||
- if (dataemail.templ.content)
|
||||
table(cellpadding="0", cellspacing="0", width="95%", align="center")
|
||||
// Main Content
|
||||
if dataemail.templ.content
|
||||
tr
|
||||
td.emailContainer
|
||||
p!=dataemail.templ.content
|
||||
if dataemail.templ.img
|
||||
img(src=baseimg + dataemail.templ.img, class="center_img")
|
||||
if dataemail.templ.content2
|
||||
p!=dataemail.templ.content2
|
||||
if dataemail.templ.img2
|
||||
img(src=baseimg + dataemail.templ.img2, class="center_img")
|
||||
|
||||
// Events
|
||||
if dataemail.templ.options.includes('SHOW_EVENTS')
|
||||
each event in arrevents
|
||||
tr
|
||||
td(class="textIniContainer", valign="top")
|
||||
p!=dataemail.templ.content
|
||||
- if (dataemail.templ.img)
|
||||
img(src=baseimg + dataemail.templ.img, alt="", class="myimg")
|
||||
- if (dataemail.templ.content2)
|
||||
p!=dataemail.templ.content2
|
||||
- if (dataemail.templ.img2)
|
||||
img(src=baseimg + dataemail.templ.img2, alt="", class="myimg")
|
||||
|
||||
table(cellpadding="0", cellspacing="0", width="640", align="center")
|
||||
- if (dataemail.templ.options.includes('SHOW_EVENTS'))
|
||||
tr
|
||||
td(class="whitespace", height="10")
|
||||
p
|
||||
tr
|
||||
td(class="emailContainer", valign="top")
|
||||
|
||||
each event in arrevents
|
||||
- var urlevent = baseurl + '/event/' + event.typol + '?eventid=' + event._id
|
||||
- var imgev = event.img_small
|
||||
- var mydate = prettyDate(event.dateTimeStart)
|
||||
unless (imgev)
|
||||
- imgev = event.img
|
||||
- var teacher1 = ''
|
||||
- var teacher2 = ''
|
||||
- var teacher3 = ''
|
||||
- var teacher4 = ''
|
||||
- var contrib = ''
|
||||
- var myclteach = 'q-chip'
|
||||
- if (event.op1[0] && event.op1[0].username !== 'nessuno')
|
||||
- teacher1 = event.op1[0].name + ' ' + event.op1[0].surname
|
||||
- if ((event.op2[0] && event.op2[0].username !== 'nessuno'))
|
||||
- teacher2 = event.op2[0].name + ' ' + event.op2[0].surname
|
||||
- myclteach = 'q-chip2'
|
||||
- if (event.op3[0] && event.op3[0].username !== 'nessuno')
|
||||
- teacher3 = "<br>" . event.op3[0].name + ' ' + event.op3[0].surname
|
||||
- if (event.op4[0] && event.op4[0].username !== 'nessuno')
|
||||
- teacher4 = "<br>" . event.op4[0].name + ' ' + event.op4[0].surname
|
||||
|
||||
- if (event.contrib[0])
|
||||
- contrib = event.contrib[0].label
|
||||
- if (event.contrib[0].showprice)
|
||||
- contrib += ' ' + event.price + ' €'
|
||||
|
||||
|
||||
table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
|
||||
td.emailContainer
|
||||
table(width="100%", cellpadding="0", cellspacing="0")
|
||||
tr
|
||||
td(class="column sectionArticleImage", valign="top")
|
||||
table(cellpadding="0", cellspacing="0", summary="", border="0")
|
||||
- if (event.news)
|
||||
tr
|
||||
td
|
||||
p(class="q-chip row inline no-wrap items-center cltexth5 chipnews shadow-5 glossy text-right bg-red text-white") Novità
|
||||
td.column.sectionArticleImage(width="150")
|
||||
if event.news
|
||||
p.q-chip.bg-red.text-white Novità
|
||||
img(src=baseimg + (event.img_small || event.img), alt=event.title)
|
||||
p.teacher= event.op1[0].name + ' ' + event.op1[0].surname
|
||||
td.column
|
||||
h2.sectionContentTitle= event.title
|
||||
p.sectionContentSubTitle= prettyDate(event.dateTimeStart)
|
||||
p.sectionContent!= event.details
|
||||
if event.contrib.length
|
||||
p.contrib= event.contrib[0].label + (event.contrib[0].showprice ? ' ' + event.price + ' €' : '')
|
||||
table.buttonContainer
|
||||
tr
|
||||
td
|
||||
img(src=baseimg + imgev, alt="", width="150")
|
||||
p(class="teacher") #{teacher1} <br> #{teacher2} #{teacher3} #{teacher4}
|
||||
td(class="column", valign="top")
|
||||
td.button
|
||||
a(href=baseurl + '/event/' + event.typol + '?eventid=' + event._id, target="_blank") Apri l'Evento
|
||||
|
||||
table(cellpadding="0", cellspacing="0", summary="", border="0")
|
||||
tr
|
||||
td(class="sectionContentTitle boldhigh", valign="top")
|
||||
p #{event.title}
|
||||
tr
|
||||
td(class="sectionContentSubTitle", valign="top")
|
||||
p(class="q-chip row inline no-wrap items-center cltexth5 chipnews shadow-5 glossy text-right bg-blue text-white") #{mydate}
|
||||
tr
|
||||
td(class="sectionContent", valign="top")
|
||||
p!= event.details
|
||||
p.contrib= contrib
|
||||
tr
|
||||
td(class="buttonContainer")
|
||||
table(width="50%", cellpadding="0", cellspacing="0", summary="", border="0")
|
||||
tr
|
||||
td(class="button hoverLink")
|
||||
a(href=urlevent, title='Evento', target='_blank') Apri l'Evento
|
||||
tr
|
||||
td.center_img
|
||||
a.button2(href=urlcal, target="_blank") Calendario Eventi
|
||||
|
||||
// Disciplines
|
||||
if dataemail.templ.options.includes('SHOW_DISC')
|
||||
tr
|
||||
td.center
|
||||
h2.cltitle_disc= dataemail.disc_title
|
||||
each disc in dataemail.arrdiscipline
|
||||
tr
|
||||
table(cellpadding="0", cellspacing="0", summary="", border="0", align="center", class="")
|
||||
tr
|
||||
td(class="whitespace", height="10")
|
||||
p
|
||||
tr
|
||||
td.center_img(class="button2 hoverLink")
|
||||
a(href=urlcal, title='Calendario Eventi', target='_blank') Calendario Eventi
|
||||
tr
|
||||
td(class="whitespace", height="10")
|
||||
p
|
||||
|
||||
- if (dataemail.templ.options.includes('SHOW_DISC'))
|
||||
tr
|
||||
td(class="whitespace bg-white", height="20")
|
||||
p(class="bg-white")
|
||||
tr
|
||||
td(class="center")
|
||||
p(class="cltitle_disc") #{dataemail.disc_title}
|
||||
tr
|
||||
td(class="discContainer", valign="top")
|
||||
|
||||
each disc in dataemail.arrdiscipline
|
||||
- var urldisc = baseurl + disc.linkpage
|
||||
- var imgdisc = disc.img_small
|
||||
unless (imgdisc)
|
||||
- imgdisc = disc.img
|
||||
|
||||
table(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
|
||||
td.discContainer
|
||||
table(width="100%", cellpadding="0", cellspacing="0")
|
||||
tr
|
||||
td(class="column sectionArticleImage", valign="top")
|
||||
table(cellpadding="0", cellspacing="0", summary="", border="0")
|
||||
tr
|
||||
td
|
||||
img(src=baseimg + imgdisc, alt="", width="150")
|
||||
td(class="column", valign="top")
|
||||
td.column.sectionArticleImage(width="150")
|
||||
img(src=baseimg + (disc.img_small || disc.img), alt=disc.label)
|
||||
td.column
|
||||
p.LinkDisc
|
||||
a(href=baseurl + disc.linkpage, target="_blank")
|
||||
span.pDisc(style=`background-color:`+disc.color)= disc.label
|
||||
p.sectionContent!= disc.description
|
||||
|
||||
table(cellpadding="0", cellspacing="0", summary="", border="0")
|
||||
tr
|
||||
td(class="sectionContentTitle boldhigh center LinkDisc", valign="top")
|
||||
a(href=urldisc, title='Disciplina', target='_blank')
|
||||
p(class="q-chip row inline no-wrap items-center cltexth4 chipnews shadow-5 glossy text-right text-white pDisc", style=`background-color: `+disc.color) #{disc.label}
|
||||
tr
|
||||
td(class="sectionContent", valign="top")
|
||||
p!= disc.description
|
||||
|
||||
tr
|
||||
td(class="whitespace", height="20")
|
||||
p
|
||||
|
||||
- if (dataemail.content_after_events)
|
||||
// Additional Content
|
||||
if dataemail.content_after_events
|
||||
tr
|
||||
table(cellpadding="0", cellspacing="0", summary="", border="0")
|
||||
tr
|
||||
td.testomail
|
||||
p!=dataemail.content_after_events
|
||||
tr
|
||||
td(class="whitespace", height="20")
|
||||
p
|
||||
td.testomail
|
||||
p!=dataemail.content_after_events
|
||||
|
||||
// Social Media
|
||||
table.socialMedia(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
|
||||
tr
|
||||
td(class="whitespace", height="5")
|
||||
p
|
||||
tr
|
||||
td
|
||||
table(width="120", cellpadding="0", cellspacing="0", summary="", border="0", align="center")
|
||||
tr
|
||||
- if (dataemail.urlinstagram)
|
||||
td(width="32", align="center")
|
||||
a(href=dataemail.urlinstagram, title='Instagram')
|
||||
img(src=imginstagram, alt="Instagram", width="29")
|
||||
- if (dataemail.urltwitter)
|
||||
td(width="32", align="center")
|
||||
a(href=dataemail.urltwitter, title='Twitter')
|
||||
img(src=imgtwitter, alt="Twitter", width="29")
|
||||
- if (dataemail.urlfb)
|
||||
td(width="32", align="center")
|
||||
a(href=dataemail.urlfb, title='Facebook')
|
||||
img(src=imgfb, alt="Facebook", width="29")
|
||||
- if (dataemail.urlyoutube)
|
||||
td(width="32", align="center")
|
||||
a(href=dataemail.urlyoutube, title='YouTube')
|
||||
img(src=imgyoutube, alt="YouTube", width="29")
|
||||
|
||||
tr
|
||||
td(class="whitespace", height="5")
|
||||
p
|
||||
tr
|
||||
td.socialMedia
|
||||
table(width="120", align="center", cellpadding="0", cellspacing="0")
|
||||
if dataemail.urlinstagram
|
||||
td
|
||||
a(href=dataemail.urlinstagram)
|
||||
img(src=imginstagram, alt="Instagram")
|
||||
if dataemail.urltwitter
|
||||
td
|
||||
a(href=dataemail.urltwitter)
|
||||
img(src=imgtwitter, alt="Twitter")
|
||||
if dataemail.urlfb
|
||||
td
|
||||
a(href=dataemail.urlfb)
|
||||
img(src=imgfb, alt="Facebook")
|
||||
if dataemail.urlyoutube
|
||||
td
|
||||
a(href=dataemail.urlyoutube)
|
||||
img(src=imgyoutube, alt="YouTube")
|
||||
|
||||
// Footer
|
||||
table.footer(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center")
|
||||
tr
|
||||
td(class="whitespace", height="10")
|
||||
p
|
||||
tr
|
||||
td.firma
|
||||
p!= dataemail.firma
|
||||
|
||||
tr
|
||||
td.disclaimer
|
||||
p!= dataemail.disclaimer_out
|
||||
|
||||
tr
|
||||
td.bottom
|
||||
p!= dataemail.disc_bottom_out
|
||||
|
||||
tr
|
||||
td(class="whitespace", height="10")
|
||||
p
|
||||
tr
|
||||
td.firma-container
|
||||
p!= dataemail.firma
|
||||
tr
|
||||
td.disclaimer-container
|
||||
p!= dataemail.disclaimer_out
|
||||
tr
|
||||
td.bottom-container
|
||||
p!= dataemail.disc_bottom_out
|
||||
1
localhost-key.pem
Symbolic link
1
localhost-key.pem
Symbolic link
@@ -0,0 +1 @@
|
||||
/Users/suryapaolo/certs/localhost-key.pem
|
||||
1
localhost.pem
Symbolic link
1
localhost.pem
Symbolic link
@@ -0,0 +1 @@
|
||||
/Users/suryapaolo/certs/localhost.pem
|
||||
47
logtrans.txt
47
logtrans.txt
@@ -438,4 +438,49 @@ Lun 03/03 ORE 01:06: [<b>Circuito RIS Arezzo</b>]: Inviate Monete da surya1977 a
|
||||
|
||||
Saldi:
|
||||
surya1977: -1.10 RIS]
|
||||
Andro: 1.00 RIS]
|
||||
Andro: 1.00 RIS]
|
||||
Mer 12/03 ORE 21:30: [<b>Circuito RIS Italia</b>]: Inviate Monete da surya1977 a Giovannifruttadisicilia 60 RIS [causale: prova]
|
||||
|
||||
Saldi:
|
||||
surya1977: 34.20 RIS]
|
||||
Giovannifruttadisicilia: 458.50 RIS]
|
||||
Gio 13/03 ORE 17:44: [<b>Circuito RIS Italia</b>]: Inviate Monete da surya1977 a PiuCheBuono(GaseBottega) 1 RIS [causale: AAA]
|
||||
|
||||
Saldi:
|
||||
surya1977: 33.20 RIS]
|
||||
PiuCheBuono(GaseBottega): -65.50 RIS]
|
||||
Gio 13/03 ORE 17:45: [<b>Circuito RIS Italia</b>]: Inviate Monete da surya1977 a PiuCheBuono(GaseBottega) 3.2 RIS [causale: GGG]
|
||||
|
||||
Saldi:
|
||||
surya1977: 30.00 RIS]
|
||||
PiuCheBuono(GaseBottega): -62.30 RIS]
|
||||
Gio 13/03 ORE 18:17: [<b>Circuito RIS Italia</b>]: Inviate Monete da surya1977 a pontiUmani 2 RIS [causale: bbb]
|
||||
|
||||
Saldi:
|
||||
surya1977: 28.00 RIS]
|
||||
pontiUmani: 2.00 RIS]
|
||||
Gio 13/03 ORE 18:18: [<b>Circuito RIS Italia</b>]: Inviate Monete da surya1977 a GruppoYurta 2 RIS [causale: ggg]
|
||||
|
||||
Saldi:
|
||||
surya1977: 26.00 RIS]
|
||||
GruppoYurta: 2.00 RIS]
|
||||
Gio 13/03 ORE 18:48: [<b>Circuito RIS Italia</b>]: Inviate Monete da surya1977 a GruppoYurta 11 RIS [causale: ]
|
||||
|
||||
Saldi:
|
||||
surya1977: 15.00 RIS]
|
||||
GruppoYurta: 13.00 RIS]
|
||||
Gio 13/03 ORE 18:53: [<b>Circuito RIS Italia</b>]: Inviate Monete da surya1977 a GruppoYurta 3 RIS [causale: ]
|
||||
|
||||
Saldi:
|
||||
surya1977: 12.00 RIS]
|
||||
GruppoYurta: 16.00 RIS]
|
||||
Gio 13/03 ORE 18:57: [<b>Circuito RIS Italia</b>]: Inviate Monete da surya1977 a GruppoYurta 1 RIS [causale: ]
|
||||
|
||||
Saldi:
|
||||
surya1977: 11.00 RIS]
|
||||
GruppoYurta: 17.00 RIS]
|
||||
Dom 23/03 ORE 22:24: [<b>Circuito RIS Italia</b>]: Inviate Monete da surya1977 a GruppoYurta 1 RIS [causale: ]
|
||||
|
||||
Saldi:
|
||||
surya1977: 88.20 RIS]
|
||||
GruppoYurta: 6.00 RIS]
|
||||
@@ -40,7 +40,7 @@
|
||||
"lodash": "^4.17.21",
|
||||
"mongodb": "^6.14.2",
|
||||
"mongoose": "^8.12.1",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"multer": "^1.4.5-lts.2",
|
||||
"mysql": "^2.18.1",
|
||||
"node-cron": "^3.0.3",
|
||||
"node-emoji": "^2.2.0",
|
||||
|
||||
@@ -46,8 +46,10 @@ const database = process.env.DATABASE || "test"; // Nome del database, default a
|
||||
if (process.env.AUTH_DB_PASSING === "1") {
|
||||
// replace username and password in the process.env.DOMAIN
|
||||
process.env.MONGODB_URI = process.env.DOMAIN_AUTH.replace('{username}', username).replace('{password}', password) + database;
|
||||
process.env.MONGODB_URI_NOPWD = process.env.DOMAIN_AUTH.replace('{username}', username) + database;
|
||||
} else {
|
||||
process.env.MONGODB_URI = domain + database;
|
||||
process.env.MONGODB_URI_NOPWD = domain + database;
|
||||
}
|
||||
|
||||
console.log('process.env.MONGODB_URI:', process.env.MONGODB_URI);
|
||||
console.log('process.env.MONGODB_URI:', process.env.MONGODB_URI_NOPWD);
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
const axios = require('axios');
|
||||
|
||||
const server_constants = require('../tools/server_constants');
|
||||
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const SERVER_A_URL = process.env.SERVER_A_URL || "http://IP_DI_SERVER_A:3000";
|
||||
const tools = require('../tools/general');
|
||||
|
||||
const axios = require('axios');
|
||||
|
||||
const T_Web_Articoli = require('../models/t_web_articoli');
|
||||
const T_Web_StatiProdotto = require('../models/t_web_statiprodotto');
|
||||
const T_Web_TipiFormato = require('../models/t_web_tipiformato');
|
||||
|
||||
const SERVER_A_URL = process.env.SERVER_A_URL || "";
|
||||
const API_KEY = process.env.API_KEY_MSSQL;
|
||||
|
||||
const mongoose = require('mongoose').set('debug', false);
|
||||
|
||||
// Funzione per ottenere i dati
|
||||
const getArticlesSales = async () => {
|
||||
try {
|
||||
@@ -18,8 +26,10 @@ const getArticlesSales = async () => {
|
||||
COALESCE(o.totVen, 0) as totVen, COALESCE(u.totFat, 0) as totFat,
|
||||
COALESCE(p.rank3M, 0) as rank3M, COALESCE(t.fatrank3M, 0) as fatrank3M,
|
||||
COALESCE(q.rank6M, 0) as rank6M, COALESCE(r.rank1Y, 0) as rank1Y,
|
||||
COALESCE(t.fat3mesi, 0) as fatLast3M, COALESCE(p.venduti3mesi, 0) as vLast3M,
|
||||
COALESCE(q.venduti6mesi, 0) as vLast6M, COALESCE(r.venduti1anno, 0) as vLastY,
|
||||
COALESCE(t.fat3mesi, 0) as fatLast3M,
|
||||
COALESCE(t2.fat6mesi, 0) as fatLast6M,
|
||||
COALESCE(p.venduti3mesi, 0) as vLast3M,
|
||||
COALESCE(q.venduti6mesi, 0) as vLast6M, COALESCE(r.venduti1anno, 0) as vLast1Y,
|
||||
s.ultimoOrdine as dataUltimoOrdine
|
||||
FROM T_WEB_Articoli a
|
||||
LEFT JOIN (SELECT CodArticoloGM, SUM(Qta) as totVen FROM T_WEB_Ordini GROUP BY CodArticoloGM) o
|
||||
@@ -67,7 +77,24 @@ exports.exportArticlesSalesByJSON = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateValue) => {
|
||||
exports.getTableContent = async (options) => {
|
||||
try {
|
||||
// Chiama getTableContent, se ritorna errore hangup, allora attendi 2 secondi e poi richiamala.
|
||||
const tableContent = await this.getTableContentBase(options);
|
||||
console.log(' uscito dalla funzione getTableContentBase ... ')
|
||||
return tableContent;
|
||||
} catch (error) {
|
||||
console.error('Error: ', error?.message);
|
||||
if (error.message === 'socket hang up') {
|
||||
console.log('Error: hangup, waiting 2 seconds and retrying...');
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
return await this.getTableContent(options);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
exports.formatDate = (dateValue) => {
|
||||
const date = new Date(dateValue);
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
@@ -75,14 +102,30 @@ const formatDate = (dateValue) => {
|
||||
return `${day}/${month}/${year}`;
|
||||
};
|
||||
|
||||
const getTableContent = async (options) => {
|
||||
exports.getModelByNameTable = (nameTable) => {
|
||||
switch (nameTable) {
|
||||
case 'T_Web_Articoli':
|
||||
return T_Web_Articoli;
|
||||
case 'T_Web_StatiProdotto':
|
||||
return T_Web_StatiProdotto;
|
||||
case 'T_Web_TipiFormato':
|
||||
return T_Web_TipiFormato;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
exports.getTableContentBase = async (options) => {
|
||||
try {
|
||||
const myurl = SERVER_A_URL + '/query';
|
||||
console.log('getTableContentBase...', myurl)
|
||||
// Verifica se la tabella esiste
|
||||
const checkTableQuery = `SELECT COUNT(*) as tableExists FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '${options.nameTable}'`;
|
||||
const checkResponse = await axios.post(SERVER_A_URL + '/query', { query: checkTableQuery }, {
|
||||
const checkResponse = await axios.post(myurl, { query: checkTableQuery }, {
|
||||
headers: { 'x-api-key': API_KEY }
|
||||
});
|
||||
if (!checkResponse.data || checkResponse.data.length === 0 || checkResponse.data[0].tableExists === 0) {
|
||||
console.log(' risposta 1...')
|
||||
if (!checkResponse?.data || checkResponse?.data.length === 0 || checkResponse?.data[0].tableExists === 0) {
|
||||
return `La tabella '${options.nameTable}' non esiste.`;
|
||||
}
|
||||
|
||||
@@ -91,6 +134,7 @@ const getTableContent = async (options) => {
|
||||
const columnsResponse = await axios.post(SERVER_A_URL + '/query', { query: columnsQuery }, {
|
||||
headers: { 'x-api-key': API_KEY }
|
||||
});
|
||||
console.log(' risposta 2 (schema)...')
|
||||
const tableColumns = columnsResponse.data.map(col => col.COLUMN_NAME);
|
||||
|
||||
// Mappatura per unire i campi (ID e Descrizione)
|
||||
@@ -107,15 +151,62 @@ const getTableContent = async (options) => {
|
||||
// Costruisce la query per recuperare i record
|
||||
let dataQuery = "";
|
||||
|
||||
let columnsToShow = 'T.*';
|
||||
if (options.fieldGM) {
|
||||
columnsToShow = 'T.' + options.fieldGM;
|
||||
}
|
||||
let records = [];
|
||||
|
||||
if (options.nameTable.toLowerCase() === 't_web_articoli') {
|
||||
if (true) {
|
||||
dataQuery = `
|
||||
SELECT TOP ${options.numrec}
|
||||
if (options?.usaDBGMLocale) {
|
||||
|
||||
// Cerca il modello corrispondente alla tabella se esiste
|
||||
let mymodel = this.getModelByNameTable(options.nameTable);
|
||||
if (!mymodel) {
|
||||
// fai una query sul db locale mongodb dela tabella chiamata "options.nameTable"
|
||||
mymodel = mongoose.model(options.nameTable, new mongoose.Schema({}, { strict: false }));
|
||||
if (!mymodel)
|
||||
return `Il modello per la tabella '${options.nameTable}' non esiste.`;
|
||||
}
|
||||
|
||||
if (options.aggregation) {
|
||||
console.log('options.aggregation', options.aggregation);
|
||||
records = await mymodel.aggregate(options.aggregation);
|
||||
|
||||
} else {
|
||||
const pipeline = [];
|
||||
|
||||
// Filtro base se specificato
|
||||
if (options.where) {
|
||||
const whereConditions = options.where;
|
||||
pipeline.push({ $match: whereConditions });
|
||||
}
|
||||
|
||||
if (options.sort) {
|
||||
pipeline.push({ $sort: options.sort });
|
||||
}
|
||||
|
||||
if (options.limit) {
|
||||
pipeline.push({ $limit: options.limit });
|
||||
}
|
||||
|
||||
// Selezione dei campi
|
||||
if (options.fieldGM) {
|
||||
pipeline.push({ $project: { [options.fieldGM]: 1 } });
|
||||
}
|
||||
|
||||
console.log(' aggregate pipeline...', pipeline);
|
||||
records = await mymodel.aggregate(pipeline);
|
||||
}
|
||||
|
||||
console.log('results', records ? records[0] : ' non ricevuto');
|
||||
|
||||
} else {
|
||||
|
||||
let columnsToShow = 'T.*';
|
||||
if (options.fieldGM) {
|
||||
columnsToShow = 'T.' + options.fieldGM;
|
||||
}
|
||||
|
||||
if (options.nameTable.toLowerCase() === 't_web_articoli') {
|
||||
if (true) {
|
||||
dataQuery = `
|
||||
SELECT TOP ${options.numrec || 10000}
|
||||
${columnsToShow}
|
||||
` + (options.campispeciali ? `
|
||||
,f.DescrizioneStatoProdotto
|
||||
@@ -125,14 +216,14 @@ const getTableContent = async (options) => {
|
||||
,z.AutoriCompleti
|
||||
,i2.DescrArgomento
|
||||
,z3.CasaEditrice` : ``) + (options.showQtaDisponibile ? ` ,q.QtaDisponibile ` : ``) +
|
||||
` FROM T_WEB_Articoli T
|
||||
` FROM T_WEB_Articoli T
|
||||
JOIN(
|
||||
SELECT IdArticolo, MAX(DataOra) AS data
|
||||
FROM T_WEB_Articoli
|
||||
GROUP BY IdArticolo
|
||||
) b ON T.IdArticolo = b.IdArticolo AND T.DataOra = b.data `
|
||||
+ (options.campispeciali ?
|
||||
` LEFT JOIN(
|
||||
+ (options.campispeciali ?
|
||||
` LEFT JOIN(
|
||||
SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto
|
||||
FROM T_WEB_StatiProdotto e
|
||||
JOIN(
|
||||
@@ -212,9 +303,9 @@ const getTableContent = async (options) => {
|
||||
GROUP BY IdMarchioEditoriale
|
||||
) aa3 ON a3.IdMarchioEditoriale = aa3.IdMarchioEditoriale AND a3.DataOra = aa3.maxData
|
||||
) z3 ON T.IdMarchioEditoriale = z3.IdMarchioEditoriale `
|
||||
: ``)
|
||||
+ (options.showQtaDisponibile ?
|
||||
` LEFT JOIN(
|
||||
: ``)
|
||||
+ (options.showQtaDisponibile ?
|
||||
` LEFT JOIN(
|
||||
SELECT o.Codice, o.QtaDisponibile
|
||||
FROM T_WEB_Disponibile o
|
||||
JOIN(
|
||||
@@ -223,8 +314,8 @@ const getTableContent = async (options) => {
|
||||
GROUP BY Codice
|
||||
) p ON o.Codice = p.Codice AND o.DataOra = p.data1
|
||||
) q ON T.IdArticolo = q.Codice` : ``)
|
||||
} else {
|
||||
dataQuery += `
|
||||
} else {
|
||||
dataQuery += `
|
||||
SELECT TOP ${options.numrec}
|
||||
T.*
|
||||
FROM T_WEB_Articoli T
|
||||
@@ -234,22 +325,28 @@ const getTableContent = async (options) => {
|
||||
GROUP BY IdArticolo
|
||||
) b ON T.IdArticolo = b.IdArticolo AND T.DataOra = b.data
|
||||
`;
|
||||
}
|
||||
} else {
|
||||
dataQuery = `SELECT TOP ${options.numrec || 10000} * FROM ${options.nameTable} `;
|
||||
}
|
||||
} else {
|
||||
dataQuery = `SELECT TOP ${options.numrec} * FROM ${options.nameTable} `;
|
||||
}
|
||||
if (options.where && options.where.trim() !== "") {
|
||||
dataQuery += ` WHERE ${options.where} `;
|
||||
if (options.where && options.where.trim() !== "") {
|
||||
dataQuery += ` WHERE ${options.where} `;
|
||||
}
|
||||
|
||||
console.log('dataQuery', dataQuery);
|
||||
|
||||
// Esegue la query per recuperare i dati
|
||||
// console.log('dataQuery', dataQuery);
|
||||
const dataResponse = await axios.post(SERVER_A_URL + '/query', { query: dataQuery }, {
|
||||
headers: { 'x-api-key': API_KEY }
|
||||
});
|
||||
|
||||
records = dataResponse?.data;
|
||||
}
|
||||
|
||||
// Esegue la query per recuperare i dati
|
||||
console.log('dataQuery', dataQuery);
|
||||
const dataResponse = await axios.post(SERVER_A_URL + '/query', { query: dataQuery }, {
|
||||
headers: { 'x-api-key': API_KEY }
|
||||
});
|
||||
const records = dataResponse.data;
|
||||
if (!records || records.length === 0) {
|
||||
return `Nessun record trovato nella tabella '${options.nameTable}'.`;
|
||||
console.log(`Nessun record trovato per la tabella ${options.nameTable}.`);
|
||||
return [];
|
||||
}
|
||||
|
||||
// Determina quali colonne visualizzare.
|
||||
@@ -272,13 +369,13 @@ const getTableContent = async (options) => {
|
||||
.map(item => {
|
||||
const trimmed = item.trim();
|
||||
const parsed = Date.parse(trimmed);
|
||||
return !isNaN(parsed) ? formatDate(trimmed) : trimmed;
|
||||
return !isNaN(parsed) ? this.formatDate(trimmed) : trimmed;
|
||||
})
|
||||
.join(', ');
|
||||
} else {
|
||||
const parsed = Date.parse(value);
|
||||
if (!isNaN(parsed)) {
|
||||
value = formatDate(value);
|
||||
value = this.formatDate(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -295,7 +392,7 @@ const getTableContent = async (options) => {
|
||||
// Se c'è un solo record, visualizza una lista di chiavi e valori
|
||||
const record = records[0];
|
||||
output += `
|
||||
< table border = '1' style = "border-collapse: collapse; width: 50%;" >
|
||||
<table border='1' style="border-collapse: collapse;" >
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="padding: 8px; background-color: #f2f2f2;">Campo</th>
|
||||
@@ -314,7 +411,7 @@ const getTableContent = async (options) => {
|
||||
});
|
||||
output += `
|
||||
</tbody>
|
||||
</table >
|
||||
</table>
|
||||
`;
|
||||
} else {
|
||||
// Se ci sono più record, visualizza una tabella con intestazioni
|
||||
@@ -345,9 +442,26 @@ const getTableContent = async (options) => {
|
||||
records.forEach(record => {
|
||||
let myrec = {}
|
||||
|
||||
displayColumns.forEach(column => {
|
||||
myrec[column] = `${getDisplayValue(record, column)} `;
|
||||
});
|
||||
if (options.recordraw) {
|
||||
myrec = record;
|
||||
} else {
|
||||
|
||||
displayColumns.forEach(column => {
|
||||
const value = record[column];
|
||||
if (value !== undefined && value !== null) {
|
||||
const type = typeof value;
|
||||
if (type === 'number' && !mergedMapping[column]) {
|
||||
myrec[column] = value;
|
||||
} else if (type === 'boolean') {
|
||||
myrec[column] = value;
|
||||
} else if (value instanceof Date) {
|
||||
myrec[column] = this.formatDate(value);
|
||||
} else {
|
||||
myrec[column] = `${getDisplayValue(record, column)}`.trim();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
output.push(myrec)
|
||||
});
|
||||
}
|
||||
@@ -355,7 +469,8 @@ const getTableContent = async (options) => {
|
||||
return output;
|
||||
|
||||
} catch (error) {
|
||||
console.error("Errore nel recupero della tabella: ", error.message);
|
||||
output = `${error?.response?.data?.error || error?.stack || error.message}`;
|
||||
console.error("Errore nel recupero della tabella: ", `${error.response.data.error || error.stack || error.message}`);
|
||||
if (options.outhtml) {
|
||||
output = `
|
||||
|
||||
@@ -409,23 +524,226 @@ const getTableContent = async (options) => {
|
||||
}
|
||||
};
|
||||
|
||||
const setTableContent = async (options) => {
|
||||
try {
|
||||
// checkPermissions()
|
||||
|
||||
const esegui = true
|
||||
|
||||
if (esegui) {
|
||||
|
||||
// Verifica se la tabella esiste
|
||||
const checkTableQuery = `SELECT COUNT(*) as tableExists FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '${options.nameTable}'`;
|
||||
const checkResponse = await axios.post(SERVER_A_URL + '/query', { query: checkTableQuery }, {
|
||||
headers: { 'x-api-key': API_KEY }
|
||||
});
|
||||
|
||||
if (!checkResponse.data || checkResponse.data.length === 0 || checkResponse.data[0].tableExists === 0) {
|
||||
return `La tabella '${options.nameTable}' non esiste.`;
|
||||
}
|
||||
|
||||
// Costruisce la query per inserire o aggiornare i record
|
||||
let dataQuery = "";
|
||||
if (options.insertMode) {
|
||||
// Modalità INSERT
|
||||
const columns = Object.keys(options.data);
|
||||
const values = columns.map(col => `'${options.data[col]}'`).join(", ");
|
||||
dataQuery = `
|
||||
INSERT INTO ${options.nameTable} (${columns.join(", ")})
|
||||
VALUES (${values});
|
||||
`;
|
||||
} else {
|
||||
// Modalità UPDATE
|
||||
const updateFields = Object.keys(options.data)
|
||||
.map(col => `${col} = '${options.data[col]}'`)
|
||||
.join(", ");
|
||||
const whereClause = options.where ? `WHERE ${options.where}` : "";
|
||||
dataQuery = `
|
||||
UPDATE ${options.nameTable}
|
||||
SET ${updateFields}
|
||||
${whereClause};
|
||||
`;
|
||||
}
|
||||
|
||||
console.log('dataQuery', dataQuery);
|
||||
|
||||
// Esegue la query per inserire o aggiornare i dati
|
||||
const dataResponse = await axios.post(SERVER_A_URL + '/query', { query: dataQuery }, {
|
||||
headers: { 'x-api-key': API_KEY }
|
||||
});
|
||||
|
||||
if (dataResponse.data && dataResponse.data.affectedRows > 0) {
|
||||
return `Operazione completata con successo su '${options.nameTable}'.`;
|
||||
} else {
|
||||
return `Nessun record modificato nella tabella '${options.nameTable}'.`;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Errore nell'inserimento o aggiornamento della tabella: ", error.message);
|
||||
if (options.outhtml) {
|
||||
output = `
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Errore nell'inserimento o aggiornamento della Tabella ${options.nameTable}</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
background-color: #f7f7f7;
|
||||
color: #333;
|
||||
padding: 20px;
|
||||
}
|
||||
.error-container {
|
||||
background-color: #ffe6e6;
|
||||
border: 1px solid #ff4d4d;
|
||||
padding: 20px;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
max-width: 800px;
|
||||
margin: auto;
|
||||
}
|
||||
.error-title {
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
color: #d8000c;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.error-message {
|
||||
font-size: 16px;
|
||||
white-space: pre-wrap;
|
||||
background: #fff;
|
||||
padding: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 3px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="error-container">
|
||||
<div class="error-title">Errore nell'inserimento o aggiornamento della Tabella ${options.nameTable}</div>
|
||||
<div class="error-message">
|
||||
${error.response.data.error || error.stack || error.message}
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
return output;
|
||||
}
|
||||
return "Errore nell'inserimento o aggiornamento della tabella.";
|
||||
}
|
||||
};
|
||||
const checkPermissions = async (options) => {
|
||||
try {
|
||||
const dataQuery = `
|
||||
SELECT
|
||||
dp.name AS UserName,
|
||||
dp.type_desc AS UserType,
|
||||
o.name AS ObjectName,
|
||||
p.permission_name,
|
||||
p.state_desc AS PermissionState
|
||||
FROM
|
||||
sys.database_permissions p
|
||||
JOIN
|
||||
sys.objects o ON p.major_id = o.object_id
|
||||
JOIN
|
||||
sys.database_principals dp ON p.grantee_principal_id = dp.principal_id
|
||||
WHERE
|
||||
o.name = 'T_WEB_Articoli';
|
||||
`;
|
||||
|
||||
console.log('checkPermissions query:', dataQuery);
|
||||
|
||||
// Esegue la query per inserire o aggiornare i dati
|
||||
const dataResponse = await axios.post(SERVER_A_URL + '/query', { query: dataQuery }, {
|
||||
headers: { 'x-api-key': API_KEY }
|
||||
});
|
||||
|
||||
console.log('checkPermissions result:', dataResponse.data);
|
||||
|
||||
if (dataResponse.data && dataResponse.data.affectedRows > 0) {
|
||||
return `Operazione completata con successo.`;
|
||||
} else {
|
||||
return `Nessun permesso.`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Errore nel check dei Permessi: ", error.message);
|
||||
if (options.outhtml) {
|
||||
output = `
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Errore nell'inserimento o aggiornamento della Tabella ${options.nameTable}</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
background-color: #f7f7f7;
|
||||
color: #333;
|
||||
padding: 20px;
|
||||
}
|
||||
.error-container {
|
||||
background-color: #ffe6e6;
|
||||
border: 1px solid #ff4d4d;
|
||||
padding: 20px;
|
||||
border-radius: 5px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
max-width: 800px;
|
||||
margin: auto;
|
||||
}
|
||||
.error-title {
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
color: #d8000c;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.error-message {
|
||||
font-size: 16px;
|
||||
white-space: pre-wrap;
|
||||
background: #fff;
|
||||
padding: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 3px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="error-container">
|
||||
<div class="error-title">Errore nell'inserimento o aggiornamento della Tabella ${options.nameTable}</div>
|
||||
<div class="error-message">
|
||||
${error.response.data.error || error.stack || error.message}
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
return output;
|
||||
}
|
||||
return "Errore nell'inserimento o aggiornamento della tabella.";
|
||||
}
|
||||
};
|
||||
|
||||
// Endpoint per mostrare i dati della tabella
|
||||
exports.viewTable = async (req, res) => {
|
||||
try {
|
||||
const options = req.body.options;
|
||||
const tableContent = await getTableContent(options);
|
||||
const tableContent = await this.getTableContent(options);
|
||||
|
||||
let out = {};
|
||||
|
||||
if (options.outhtml) {
|
||||
out = `
|
||||
<h2>Tabella: ${options.nameTable}</h2>
|
||||
${tableContent}
|
||||
<h2 class="text-center">Tabella: ${options.nameTable}</h2>
|
||||
<div class="text-h7 row justify-center text-blue">Query: ${options.where}<br></div>
|
||||
<div class="row justify-center">
|
||||
${tableContent}
|
||||
</div>
|
||||
`
|
||||
} else {
|
||||
out = tableContent;
|
||||
}
|
||||
|
||||
if (tableContent && tableContent.length > 0) {
|
||||
if (options.updatelocaldb) {
|
||||
this.updateLocalDb(tableContent[0], options)
|
||||
}
|
||||
}
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, data: out });
|
||||
|
||||
} catch (error) {
|
||||
@@ -434,17 +752,94 @@ exports.viewTable = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
exports.updateLocalDb = async (tableContent, options) => {
|
||||
try {
|
||||
|
||||
const ProductInfo = require('../models/productInfo');
|
||||
const CatProd = require('../models/catprod');
|
||||
|
||||
let recproductInfo = {
|
||||
code: tableContent.Ean13.trim(),
|
||||
};
|
||||
|
||||
let risrecUpdated = null;
|
||||
|
||||
const recfound = await ProductInfo.findOne({ code: recproductInfo.code }).lean();
|
||||
if (recfound) {
|
||||
|
||||
ListaArgomenti = tableContent.ListaArgomenti;
|
||||
|
||||
let arrayPulito = ListaArgomenti
|
||||
.trim() // Rimuove gli spazi all'inizio e alla fine
|
||||
.replace(/[\(\)]/g, '') // Rimuove le parentesi tonde
|
||||
.split(','); // Divide la stringa in un array usando la virgola come separatore
|
||||
|
||||
if (arrayPulito && arrayPulito.length > 0) {
|
||||
let aggiornacat = false;
|
||||
const precCatProds = recfound.idCatProds;
|
||||
let reccatprods = [];
|
||||
for (let i = 0; i < arrayPulito.length; i++) {
|
||||
const idArgomento = parseInt(arrayPulito[i]);
|
||||
reccateg = await CatProd.findOne({ idArgomento }).lean();
|
||||
|
||||
if (reccateg) {
|
||||
// aggiungi solo se non esiste già
|
||||
if (!reccatprods.includes(reccateg._id)) {
|
||||
reccatprods.push(reccateg._id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ora controlla se l'array reccatprods e' diverso da precCatProds
|
||||
if (reccatprods.length !== precCatProds.length) {
|
||||
aggiornacat = true;
|
||||
} else {
|
||||
for (let i = 0; i < reccatprods.length; i++) {
|
||||
if (reccatprods[i].toString() !== precCatProds[i].toString()) {
|
||||
aggiornacat = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (aggiornacat) {
|
||||
recproductInfo.idCatProds = reccatprods;
|
||||
aggiorna = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (tableContent.DataPubblicazione.trim()) {
|
||||
recproductInfo.date_pub = new Date(tools.convertiDataItaliana(tableContent.DataPubblicazione.trim()).date);
|
||||
// convert data to timestamp
|
||||
recproductInfo.date_pub_ts = recproductInfo.date_pub.getTime();
|
||||
aggiorna = true;
|
||||
}
|
||||
|
||||
if (aggiorna) {
|
||||
risrecUpdated = await ProductInfo.findOneAndUpdate({ code: recproductInfo.code }, { $set: recproductInfo }, { new: true, upsert: true });
|
||||
}
|
||||
|
||||
return risrecUpdated;
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error('Error: ', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Endpoint per mostrare i dati della tabella
|
||||
exports.queryTable = async (req, res) => {
|
||||
try {
|
||||
const options = req.body.options;
|
||||
const tableContent = await getTableContent(options);
|
||||
const tableContent = await this.getTableContent(options);
|
||||
|
||||
let out = {};
|
||||
|
||||
if (options.outhtml) {
|
||||
out = `
|
||||
<h2>Tabella: ${options.nameTable}</h2>
|
||||
<div class="text-h7 row justify-center text-blue">Query: ${options.where}<br></div>
|
||||
${tableContent}
|
||||
`
|
||||
} else {
|
||||
@@ -458,3 +853,107 @@ exports.queryTable = async (req, res) => {
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, error });
|
||||
}
|
||||
};
|
||||
// Endpoint per salvare i dati di una tabella
|
||||
exports.saveTable = async (req, res) => {
|
||||
try {
|
||||
const options = req.body.options;
|
||||
const tableContent = await setTableContent(options);
|
||||
|
||||
let out = {};
|
||||
|
||||
if (options.outhtml) {
|
||||
out = `
|
||||
<h2 class="text-center">Tabella: ${options.nameTable}</h2>
|
||||
<div class="text-h7 row justify-center text-blue">Query: ${options.where}<br></div>
|
||||
<div class="row justify-center">
|
||||
${tableContent}
|
||||
</div>
|
||||
`
|
||||
} else {
|
||||
out = tableContent;
|
||||
}
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, data: out });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error: ', error);
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR, error });
|
||||
}
|
||||
};
|
||||
|
||||
exports.mssqlmigrateTables = async (req) => {
|
||||
const MssqlMigrator = require('../modules/MssqlMigrator'); // Importa la classe Macro
|
||||
|
||||
try {
|
||||
const options = req.body.mydata.options;
|
||||
let listaTabelle = [];
|
||||
if (options?.parte1 || options?.tutte) {
|
||||
listaTabelle.push({ table: 'T_WEB_TitoliOriginali', usaDataOra: true, fieldId: 'IdTitoloOriginale' });
|
||||
listaTabelle.push({ table: 'T_WEB_TestateOrdini', usaDataOra: false });
|
||||
listaTabelle.push({ table: 'T_WEB_Ordini', usaDataOra: false });
|
||||
listaTabelle.push({ table: 'T_WOO_TestateOrdini', usaDataOra: false });
|
||||
listaTabelle.push({ table: 'T_WOO_Ordini', usaDataOra: false });
|
||||
listaTabelle.push({ table: 'T_WEB_Articoli', usaDataOra: true, fieldId: 'IdArticolo' });
|
||||
}
|
||||
if (options?.parte2 || options?.tutte) {
|
||||
listaTabelle.push({ table: 'T_WEB_Disponibile', usaDataOra: true, fieldId: 'Codice' });
|
||||
listaTabelle.push({ table: 'T_WEB_Argomenti', usaDataOra: true, fieldId: 'IdArgomento' });
|
||||
listaTabelle.push({ table: 'T_WEB_ClientiInternet', usaDataOra: false });
|
||||
listaTabelle.push({ table: 'T_WOO_Clienti', usaDataOra: false });
|
||||
listaTabelle.push({ table: 'T_WEB_Autori', usaDataOra: true, fieldId: 'IdAutore' });
|
||||
}
|
||||
if (options?.parte3 || options?.tutte) {
|
||||
listaTabelle.push({ table: 'T_WEB_Collane', usaDataOra: true, fieldId: 'IdCollana' });
|
||||
listaTabelle.push({ table: 'T_WEB_MarchiEditoriali', usaDataOra: true, fieldId: 'IdMarchioEditoriale' });
|
||||
listaTabelle.push({ table: 'T_WEB_StatiProdotto', usaDataOra: true, fieldId: 'IdStatoProdotto' });
|
||||
listaTabelle.push({ table: 'T_WEB_TipiFormato', usaDataOra: true, fieldId: 'IdTipoFormato' });
|
||||
listaTabelle.push({ table: 'T_WEB_Tipologie', usaDataOra: true, fieldId: 'IdTipologia' });
|
||||
listaTabelle.push({ table: 'T_WEB_ArticoliFatturati', usaDataOra: false });
|
||||
listaTabelle.push({ table: 'T_WEB_IdInternetFatturati', usaDataOra: false });
|
||||
listaTabelle.push({ table: 'T_WEB_Edizioni', usaDataOra: true, fieldId: 'IdEdizione' });
|
||||
listaTabelle.push({ table: 'T_WEB_Contratti', usaDataOra: true, fieldId: 'IdArticolo' });
|
||||
}
|
||||
if (options?.test) {
|
||||
listaTabelle.push({ table: 'T_WEB_Articoli', usaDataOra: true, fieldId: 'IdArticolo' });
|
||||
}
|
||||
|
||||
const migrator = new MssqlMigrator();
|
||||
return await migrator.migrateTables(listaTabelle);
|
||||
|
||||
} catch (e) {
|
||||
console.error(e.message);
|
||||
return 'Errore: ' + e.message
|
||||
}
|
||||
|
||||
};
|
||||
exports.updateAllBook = async (idapp, options) => {
|
||||
|
||||
const Macro = require('../modules/Macro'); // Importa la classe Macro
|
||||
|
||||
try {
|
||||
const macro = new Macro(idapp); // Crea un'istanza della classe Macro
|
||||
options.idapp = idapp;
|
||||
return await macro.updateLocalDbFromGM_T_Web_Articoli(options);
|
||||
|
||||
} catch (e) {
|
||||
console.error(e.message);
|
||||
return e.message;
|
||||
}
|
||||
};
|
||||
|
||||
exports.updateAllBookRoute = async (req, res) => {
|
||||
|
||||
try {
|
||||
const idapp = req.body.idapp;
|
||||
const options = req.body.options;
|
||||
const result = await this.updateAllBook(idapp, options);
|
||||
|
||||
return res.status(200).send({ data: result });
|
||||
|
||||
} catch (e) {
|
||||
console.error(e.message);
|
||||
if (res) {
|
||||
return res.status(400).send(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ console.log('Mongoose Version ' + mongoose.version);
|
||||
|
||||
// URL di connessione
|
||||
const connectionUrl = process.env.MONGODB_URI;
|
||||
console.log('Connessione a ' + connectionUrl + ' in corso...');
|
||||
console.log('Connessione a ' + process.env.MONGODB_URI_NOPWD + ' in corso...');
|
||||
|
||||
// Funzione per connettersi al database con retry
|
||||
async function connectToDatabase(uri, opts) {
|
||||
@@ -52,12 +52,12 @@ async function connectToDatabase(uri, opts) {
|
||||
console.log("Sto provando a connettermi al database...");
|
||||
await mongoose.connect(uri);
|
||||
|
||||
console.log(' *** CONNESSIONE EFFETTUATA ! ' + uri + ' db: ' + process.env.DATABASE);
|
||||
console.log(' *** CONNESSIONE EFFETTUATA ! ' + ' db: ' + process.env.DATABASE);
|
||||
|
||||
console.log(' Database corrente:', mongoose.connection.name);
|
||||
|
||||
// Ottieni l'URL completo della connessione
|
||||
console.log(' URL di connessione:', mongoose.connection.client.s.url);
|
||||
// console.log(' URL di connessione:', mongoose.connection.client.s.url);
|
||||
|
||||
const db = mongoose.connection;
|
||||
const serverInfo = await db.db.admin().serverStatus(); // Ottieni lo stato del server
|
||||
|
||||
@@ -104,8 +104,8 @@
|
||||
"ID_CIRCUIT_COINS_ACCEPTED_TO_ME": "🔄 Hai inviato <strong>%s %s</strong> a %s sul '%s'.",
|
||||
"ID_CIRCUIT_COINS_REFUSED": "%s %s rifiutati da %s sul '%s'.",
|
||||
"ID_CIRCUIT_COINS_REFUSED_TO_ME": "%s %s rifiutati da %s sul '%s'.",
|
||||
"CIRCUIT_AMOUNT_EXCEED_FIDO": "L'importo supera la quantità massima concessa per %s",
|
||||
"CIRCUIT_AMOUNT_EXCEED_QTAMAX": "L'importo supera la quantità massima che il destinatario (%s) può accumulare",
|
||||
"CIRCUIT_AMOUNT_EXCEED_FIDO": "⚠️ L'importo supera la quantità massima concessa per %s",
|
||||
"CIRCUIT_AMOUNT_EXCEED_QTAMAX": "⚠️ L'importo supera la quantità massima che il destinatario (%s) può accumulare",
|
||||
"CIRCUIT_COINS_ALREADY_PROCESSED": "La richiesta è stata già processata. Stato %s",
|
||||
"STATUS_SENT": "Inviato",
|
||||
"STATUS_REFUSED": "Rifiutato",
|
||||
@@ -127,6 +127,9 @@
|
||||
"🚫 Ti è stato rifiutato l'accesso. Probabilmente l'username con cui ti sei registrato non ti conosce. (%s) !<br>Contatta l'Assistenza Tecnica.": "🚫 Ti è stato rifiutato l'accesso. Probabilmente l'username con cui ti sei registrato non ti conosce. (%s) !<br>Contatta l'Assistenza Tecnica.",
|
||||
"🚫 %s ha rifiutato l'accesso alla App a %s !": "🚫 %s ha rifiutato l'accesso alla App a %s !",
|
||||
"✅ Hai Ammesso l'accesso alla App a %s !": "✅ Hai Ammesso l'accesso alla App a %s !",
|
||||
"EXCEED_FIDO": "⚠️ L'importo supera la Fiducia concessa per %s",
|
||||
"EXCEED_QTAMAX": "⚠️ Attenzione! %s sta tentando di inviarti %s RIS, ma il tuo conto ha raggiunto il limite massimo di accumulo sul %s. \nPer poter ricevere il pagamento, devi prima spendere alcuni RIS cercando quello che ti serve, in modo da liberare spazio nel tuo conto. 🙏🏻",
|
||||
"EXCEED_QTAMAX_MITTENTE": "⚠️ Attenzione! %s ha raggiunto la quota massima accumulabile in RIS, pertanto non puoi inviarglieli. Dovrebbe prima cercare di spendere i RIS cercando quello che gli serve, in modo da liberare spazio nel suo conto. 🙏🏻",
|
||||
"Good: %": "Good: %",
|
||||
"Service: %": "Service: %"
|
||||
}
|
||||
@@ -11,123 +11,58 @@ const auth_default = (req, res, next) => {
|
||||
|
||||
};
|
||||
|
||||
const authenticate = (req, res, next) => {
|
||||
const token = req.header('x-auth');
|
||||
//const refreshToken = req.header('x-refrtok');
|
||||
|
||||
// console.log('authenticate... ');
|
||||
|
||||
let noaut = false;
|
||||
|
||||
if (req.body.hasOwnProperty('noaut')) {
|
||||
noaut = req.body.noaut;
|
||||
}
|
||||
|
||||
if (noaut) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
const access = 'auth';
|
||||
|
||||
const idapp = getIdApp(req);
|
||||
|
||||
return User.findByToken(token, access, true, idapp).then((ris) => {
|
||||
|
||||
if (ris && ris.user && !!ris.user.deleted) {
|
||||
if (ris.user.deleted)
|
||||
ris.user = null;
|
||||
}
|
||||
|
||||
if (ris.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) {
|
||||
return Promise.reject(server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED);
|
||||
}
|
||||
|
||||
if (!ris.user) {
|
||||
return Promise.reject(server_constants.RIS_CODE_HTTP_INVALID_TOKEN);
|
||||
}
|
||||
|
||||
if (!!ris.user) {
|
||||
// Save last time online
|
||||
ris.user.lasttimeonline = new Date();
|
||||
ris.user.retry_pwd = 0
|
||||
ris.user.useragent = req.get('User-Agent');
|
||||
|
||||
return ris.user.save().then(() => {
|
||||
req.user = ris.user;
|
||||
req.token = token;
|
||||
// req.refreshToken = refreshToken;
|
||||
req.access = access;
|
||||
next(); // Esegui il codice successivo
|
||||
});
|
||||
}
|
||||
// tools.mylog('userid', user._id);
|
||||
|
||||
}).catch((e) => {
|
||||
if (e === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) {
|
||||
return res.status(server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED).send();
|
||||
}
|
||||
tools.mylog("ERR authenticate invalid Token =", e);
|
||||
res.status(server_constants.RIS_CODE_HTTP_INVALID_TOKEN).send();
|
||||
});
|
||||
};
|
||||
|
||||
const getIdApp = (req) => {
|
||||
let idapp = null;
|
||||
try {
|
||||
idapp = req.query.idapp;
|
||||
} catch (e) {
|
||||
console.log('IDAPP NON TROVATO !');
|
||||
}
|
||||
return idapp;
|
||||
|
||||
}
|
||||
|
||||
const authenticate_noerror = (req, res, next) => {
|
||||
const authenticateMiddleware = async (req, res, next, withUser = false, lean = false, noError = false) => {
|
||||
try {
|
||||
const token = req.header('x-auth');
|
||||
const refreshToken = req.header('x-refrtok');
|
||||
const logPrefix = noError ? (withUser ? (lean ? 'WITHUSERLEAN' : 'WITHUSER') : 'NOERROR') : 'AUTH';
|
||||
|
||||
if (!token) {
|
||||
req.user = null;
|
||||
req.token = null;
|
||||
req.code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN;
|
||||
return next();
|
||||
console.log(` ## ${logPrefix}_TOKEN INVALIDO ❌ ...`);
|
||||
return noError ? next() : res.status(req.code).send();
|
||||
}
|
||||
|
||||
User.findByToken(token, 'auth', false, getIdApp(req))
|
||||
.then((ris) => {
|
||||
if (ris.code !== server_constants.RIS_CODE_OK) {
|
||||
req.user = null;
|
||||
req.token = null;
|
||||
req.code = ris.code;
|
||||
} else {
|
||||
req.user = ris.user;
|
||||
req.token = token;
|
||||
req.refreshToken = refreshToken;
|
||||
req.code = ris.code;
|
||||
}
|
||||
const user = await User.findByToken(token, 'auth', false, withUser, lean);
|
||||
|
||||
if (ris.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) {
|
||||
return res.status(server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED).send();
|
||||
}
|
||||
if (user.code !== server_constants.RIS_CODE_OK) {
|
||||
req.user = null;
|
||||
req.token = null;
|
||||
req.code = user.code;
|
||||
} else {
|
||||
req.user = user.user;
|
||||
req.token = token;
|
||||
req.refreshToken = refreshToken;
|
||||
req.code = user.code;
|
||||
}
|
||||
|
||||
next();
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error('Errore durante l\'autenticazione:', e);
|
||||
req.user = null;
|
||||
req.token = null;
|
||||
req.code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN;
|
||||
next();
|
||||
});
|
||||
if (user.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) {
|
||||
console.log(` TOKEN SCADUTO ! `);
|
||||
if (noError) {
|
||||
return next()
|
||||
} else {
|
||||
return res.status(server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED).send();
|
||||
}
|
||||
}
|
||||
|
||||
// console.log(` ## ${logPrefix} NEXT ! AVANTI...`);
|
||||
next();
|
||||
} catch (e) {
|
||||
console.error('Errore nel middleware di autenticazione:', e);
|
||||
req.user = null;
|
||||
req.token = null;
|
||||
req.code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN;
|
||||
next();
|
||||
noError ? next() : res.status(req.code).send();
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { authenticate, authenticate_noerror, auth_default };
|
||||
const authenticate = (req, res, next) => authenticateMiddleware(req, res, next);
|
||||
const authenticate_withUser = (req, res, next) => authenticateMiddleware(req, res, next, true);
|
||||
const authenticate_withUserLean = (req, res, next) => authenticateMiddleware(req, res, next, true, true);
|
||||
const authenticate_noerror = (req, res, next) => authenticateMiddleware(req, res, next, false, false, true);
|
||||
const authenticate_noerror_WithUser = (req, res, next) => authenticateMiddleware(req, res, next, true, false, true);
|
||||
const authenticate_noerror_WithUserLean = (req, res, next) => authenticateMiddleware(req, res, next, true, true, true);
|
||||
|
||||
module.exports = { authenticate, authenticate_noerror, auth_default, authenticate_withUser, authenticate_noerror_WithUser, authenticate_noerror_WithUserLean };
|
||||
|
||||
128
src/server/models/JobsInProgress.js
Executable file
128
src/server/models/JobsInProgress.js
Executable 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 };
|
||||
@@ -657,7 +657,7 @@ AccountSchema.statics.updateQtaMax = async function (idapp, username, groupname,
|
||||
else
|
||||
risult = await Account.updateOne({ idapp, username, circuitId }, { $set: paramstoupdate });
|
||||
|
||||
return risult && risult.nModified > 0;
|
||||
return risult && risult.modifiedCount > 0;
|
||||
};
|
||||
|
||||
AccountSchema.statics.getAccountsCircuitiNazionali = async function (idapp) {
|
||||
|
||||
@@ -26,15 +26,27 @@ const CatalogSchema = new Schema({
|
||||
},
|
||||
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 }],
|
||||
|
||||
descr_introduttiva: {
|
||||
type: String,
|
||||
},
|
||||
@@ -57,9 +69,19 @@ const CatalogSchema = new Schema({
|
||||
},
|
||||
|
||||
pdf_generato: String,
|
||||
pdf_generato_stampa: String,
|
||||
data_generato: {
|
||||
type: Date,
|
||||
},
|
||||
data_generato_stampa: {
|
||||
type: Date,
|
||||
},
|
||||
username_lista_generata: {
|
||||
type: String,
|
||||
},
|
||||
data_lista_generata: {
|
||||
type: Date,
|
||||
},
|
||||
pdf_online: String,
|
||||
data_online: {
|
||||
type: Date,
|
||||
@@ -72,6 +94,11 @@ const CatalogSchema = new Schema({
|
||||
date_updated: {
|
||||
type: Date,
|
||||
},
|
||||
lista_prodotti: [{
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'Product',
|
||||
}],
|
||||
isCatalogoGenerale: Boolean,
|
||||
});
|
||||
|
||||
/*
|
||||
@@ -94,7 +121,7 @@ CatalogSchema.statics.executeQueryTable = function (idapp, params, user) {
|
||||
return tools.executeQueryTable(this, idapp, params, user);
|
||||
};
|
||||
|
||||
CatalogSchema.statics.findAllIdApp = async function (idapp) {
|
||||
/*CatalogSchema.statics.OLD_findAllIdApp = async function (idapp) {
|
||||
const Catalog = this;
|
||||
|
||||
const arrrec = await Catalog.aggregate([
|
||||
@@ -117,6 +144,107 @@ CatalogSchema.statics.findAllIdApp = async function (idapp) {
|
||||
]);
|
||||
|
||||
return arrrec;
|
||||
};*/
|
||||
|
||||
CatalogSchema.statics.findAllIdApp = async function (idapp) {
|
||||
const Catalog = this;
|
||||
|
||||
try {
|
||||
let arrrec = await Catalog.find({ idapp })
|
||||
.sort({ title: 1 }) // Ordina i risultati per titolo
|
||||
/*.populate({
|
||||
path: "idCollane", // Popola il campo idCollane
|
||||
model: "Collana" // Specifica il modello della collezione Collana
|
||||
})*/
|
||||
.populate({
|
||||
path: "lista_prodotti", // Popola il campo lista_prodotti
|
||||
populate: {
|
||||
path: "idProductInfo",
|
||||
model: "ProductInfo",
|
||||
populate: [
|
||||
{
|
||||
path: "idCatProds",
|
||||
model: "CatProd"
|
||||
},
|
||||
{
|
||||
path: "idSubCatProds",
|
||||
model: "SubCatProd"
|
||||
},
|
||||
{
|
||||
path: "idAuthors",
|
||||
model: "Author"
|
||||
}
|
||||
],
|
||||
},
|
||||
})
|
||||
.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) {
|
||||
const originalLength = catalog.lista_prodotti.length;
|
||||
catalog.lista_prodotti = catalog.lista_prodotti.filter(product => product.idProductInfo);
|
||||
if (catalog.lista_prodotti.length !== originalLength) {
|
||||
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.idProductInfo.toObject(), // Copia tutti i campi di idProductInfo
|
||||
catprods: product.idProductInfo.idCatProds, // Rinomina idCatProds in catprods
|
||||
subcatprods: product.idProductInfo.idSubCatProds,
|
||||
collana: product.idProductInfo.idCollana,
|
||||
authors: product.idProductInfo.idAuthors,
|
||||
},
|
||||
producer: product.idProducer,
|
||||
storehouse: product.idStorehouses,
|
||||
scontisticas: product.idScontisticas,
|
||||
gasordine: product.idGasordine,
|
||||
})),
|
||||
}));
|
||||
|
||||
return transformedArrRec;
|
||||
} catch (err) {
|
||||
console.error('Errore: ', err);
|
||||
}
|
||||
};
|
||||
|
||||
const Catalog = mongoose.model('Catalog', CatalogSchema);
|
||||
|
||||
@@ -21,6 +21,7 @@ const CatProdSchema = new Schema({
|
||||
},
|
||||
name: {
|
||||
type: String,
|
||||
index: 1,
|
||||
},
|
||||
descr_estesa: {
|
||||
type: String,
|
||||
@@ -34,6 +35,9 @@ const CatProdSchema = new Schema({
|
||||
color: {
|
||||
type: String,
|
||||
},
|
||||
quanti: {
|
||||
type: Number,
|
||||
}
|
||||
});
|
||||
|
||||
CatProdSchema.statics.getAllCategories = function (callback) {
|
||||
@@ -58,13 +62,13 @@ CatProdSchema.statics.findAllIdApp = async function (idapp) {
|
||||
return await CatProd.find(myfind).sort({ name: 1 }).lean();
|
||||
};
|
||||
|
||||
CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp) {
|
||||
CatProdSchema.statics.updateCatDeleteEmpty = async function (idapp) {
|
||||
try {
|
||||
const result = await CatProd.aggregate([
|
||||
const toDelete = await CatProd.aggregate([
|
||||
{ $match: { idapp } },
|
||||
{
|
||||
$lookup: {
|
||||
from: 'productinfos', // Nome della tua collezione productInfo
|
||||
from: 'productinfos',
|
||||
localField: '_id',
|
||||
foreignField: 'idCatProds',
|
||||
as: 'products'
|
||||
@@ -77,9 +81,86 @@ CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp) {
|
||||
quanti: { $size: '$products' } // Conta il numero di prodotti per ciascun CatProd
|
||||
}
|
||||
},
|
||||
{ $sort: { name: 1 } } // Ordina i risultati per nome
|
||||
{ $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: 'productinfos', // Nome della tua collezione productInfo
|
||||
localField: '_id',
|
||||
foreignField: 'idCatProds',
|
||||
as: 'products'
|
||||
}
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
myproducts: {
|
||||
$filter: {
|
||||
input: "$products",
|
||||
as: "prod",
|
||||
cond: {
|
||||
$in: ["$$prod.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);
|
||||
|
||||
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);
|
||||
|
||||
@@ -720,6 +720,7 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig
|
||||
let ris = {
|
||||
result: false,
|
||||
cansend: true,
|
||||
errorcode: 0,
|
||||
errormsg: '',
|
||||
rec: null,
|
||||
useraccounts: [],
|
||||
@@ -768,11 +769,13 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig
|
||||
if (accountorigTable.saldo - myqty < -accountorigTable.fidoConcesso) {
|
||||
ris.cansend = false;
|
||||
ris.errormsg = i18n.__('CIRCUIT_AMOUNT_EXCEED_FIDO', usernameOrig);
|
||||
ris.errorcode = shared_consts.SENDRIS_CODES.EXCEED_FIDO;
|
||||
}
|
||||
|
||||
if (accountdestTable.saldo + myqty > accountdestTable.qta_maxConcessa) {
|
||||
ris.cansend = false;
|
||||
ris.errormsg = i18n.__('CIRCUIT_AMOUNT_EXCEED_QTAMAX', extrarec.dest);
|
||||
ris.errorcode = shared_consts.SENDRIS_CODES.EXCEED_QTAMAX;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1338,7 +1341,7 @@ CircuitSchema.statics.setFido = async function (idapp, username, circuitName, gr
|
||||
|
||||
const ris = await Account.updateFido(idapp, username, groupname, circuitId, fido);
|
||||
if (ris) {
|
||||
return { qta_maxConcessa: qtamax, fidoConcesso: fido, changed: variato || (ris && ris.nModified > 0) };
|
||||
return { qta_maxConcessa: qtamax, fidoConcesso: fido, changed: variato || (ris && ris.modifiedCount > 0) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,7 +256,7 @@ CitySchema.statics.insertGeojsonToMongoDB = async function (nomefilejson) {
|
||||
|
||||
if (reccity) {
|
||||
const ris = await City.updateOne({ _id: reccity._id }, { $set: { geojson: citta } });
|
||||
if (ris.ok === 1) {
|
||||
if (ris.acknowledged) {
|
||||
inseriti++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ const CollanaSchema = new Schema({
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
index: true,
|
||||
},
|
||||
dataOra: {
|
||||
type: Date,
|
||||
@@ -30,6 +31,9 @@ const CollanaSchema = new Schema({
|
||||
enabledAlFresco: {
|
||||
type: Boolean,
|
||||
},
|
||||
quanti: {
|
||||
type: Number,
|
||||
},
|
||||
|
||||
});
|
||||
|
||||
@@ -52,6 +56,73 @@ module.exports.findAllIdApp = async function (idapp) {
|
||||
return await Collana.find(myfind).sort({title: 1}).lean();
|
||||
};
|
||||
|
||||
module.exports.getCollaneWithTitleCount = async function (idapp, updatedata) {
|
||||
try {
|
||||
|
||||
const myquery = [
|
||||
{ $match: { idapp } },
|
||||
{
|
||||
$lookup: {
|
||||
from: 'productinfos', // Nome della tua collezione productInfo
|
||||
localField: '_id',
|
||||
foreignField: 'idCollana',
|
||||
as: 'products'
|
||||
}
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
myproducts: {
|
||||
$filter: {
|
||||
input: "$products",
|
||||
as: "prod",
|
||||
cond: {
|
||||
$in: ["$$prod.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; });
|
||||
|
||||
176
src/server/models/cron.js
Executable file
176
src/server/models/cron.js
Executable 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 };
|
||||
59
src/server/models/destnewsletter.js
Executable file
59
src/server/models/destnewsletter.js
Executable 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 };
|
||||
@@ -39,6 +39,41 @@ MailingListSchema.statics.findAllIdAppSubscribed = function (idapp) {
|
||||
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 };
|
||||
|
||||
@@ -61,7 +61,9 @@ const catalogo = new Schema(
|
||||
excludeproductTypes: [{ type: Number }],
|
||||
editore: [{ type: String }],
|
||||
argomenti: [{ type: String }],
|
||||
idCollane: [{ type: Number }],
|
||||
idCollane: [{ type: String }],
|
||||
idTipologia: [{ type: Number }],
|
||||
idTipoFormato: [{ type: Number }],
|
||||
sort_field: { type: String },
|
||||
sort_dir: { type: Number },
|
||||
pdf: { type: Boolean },
|
||||
@@ -69,6 +71,8 @@ const catalogo = new Schema(
|
||||
printable: { type: Boolean },
|
||||
indebug: { type: Boolean },
|
||||
maxnumlibri: { type: Number },
|
||||
showListaArgomenti: { type: Boolean},
|
||||
showListaCollane: { type: Boolean},
|
||||
|
||||
first_page: IDimensioni,
|
||||
last_page: IDimensioni,
|
||||
|
||||
@@ -298,16 +298,16 @@ MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function (
|
||||
const { User } = require('../models/user');
|
||||
|
||||
const myobj = {};
|
||||
myobj[field + '.' + subfield] = 1;
|
||||
myobj[field] = 1;
|
||||
|
||||
let arrrec = await User.findOne({
|
||||
const ris = await User.findOne({
|
||||
idapp,
|
||||
groupname,
|
||||
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
|
||||
}, myobj).then((ris) => ris ? ris._doc[field] : []);
|
||||
}, myobj);
|
||||
|
||||
if (arrrec.length > 0) {
|
||||
return arrrec.map(m => m.username);
|
||||
if (ris) {
|
||||
return ris[field].map(m => m.username);
|
||||
}
|
||||
return [];
|
||||
|
||||
@@ -441,7 +441,7 @@ MyGroupSchema.statics.getGroupsByUsername = async function (idapp, username, req
|
||||
listgroups,
|
||||
listSentRequestGroups,
|
||||
listRefusedGroups,
|
||||
mygroups: req.user.profile.mygroups,
|
||||
mygroups: await User.getMyGroupsById(req.user._id),
|
||||
};
|
||||
|
||||
} catch (e) {
|
||||
@@ -663,13 +663,13 @@ MyGroupSchema.statics.renameCircuitName = async function (idapp, oldcircuitname,
|
||||
|
||||
MyGroupSchema.statics.setReceiveRisGroup = async function (idapp, groupname) {
|
||||
|
||||
return await this.findOneAndUpdate({
|
||||
idapp, groupname,
|
||||
},
|
||||
{ $set: { 'lastdate_reqRisGroup': new Date() } }, { new: false }).lean().then((record) => {
|
||||
return !!record;
|
||||
});
|
||||
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);
|
||||
|
||||
@@ -353,7 +353,7 @@ MyHospSchema.statics.SettaAdTypeOffro_In_Hosps = async function () {
|
||||
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.nModified, 'records');
|
||||
console.log('Successfully updated adType for', result.modifiedCount, 'records');
|
||||
} catch (err) {
|
||||
console.error('Error updating adType:', err);
|
||||
}
|
||||
|
||||
@@ -56,6 +56,7 @@ const IDimensioni = new Schema({
|
||||
});
|
||||
const IPagina = new Schema({
|
||||
dimensioni: IDimensioni,
|
||||
testo_title: IText,
|
||||
testo_up: IText,
|
||||
testo_down: IText,
|
||||
});
|
||||
@@ -81,7 +82,7 @@ const INovita = new Schema(
|
||||
const IBestseller = new Schema(
|
||||
{
|
||||
show: Boolean,
|
||||
primiNInClassifica: Number,
|
||||
quantiFattRaggiunti: Number,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -129,9 +130,11 @@ const scheletroScheda = {
|
||||
|
||||
productTypes: [{ type: Number }],
|
||||
excludeproductTypes: [{ type: Number }],
|
||||
idTipologie: [{ type: Number }],
|
||||
idTipoFormato: [{ type: Number }],
|
||||
editore: [{ type: String }],
|
||||
argomenti: [{ type: String }],
|
||||
idCollane: [{ type: Number }],
|
||||
idCollane: [{ type: String }],
|
||||
author: { type: String },
|
||||
sort_field: { type: String },
|
||||
sort_dir: { type: Number },
|
||||
|
||||
@@ -22,6 +22,9 @@ const NewstosentSchema = new Schema({
|
||||
templemail_str: {
|
||||
type: String,
|
||||
},
|
||||
destnewsletter_str: {
|
||||
type: String,
|
||||
},
|
||||
activate: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
@@ -121,7 +124,10 @@ NewstosentSchema.statics.findNewsletterPending_To_Send = function (idapp) {
|
||||
starting_job: true,
|
||||
finish_job: false,
|
||||
processing_job: false,
|
||||
lastemailsent_Job: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 15) },
|
||||
$or: [
|
||||
{ lastemailsent_Job: { $gte: tools.IncDateNow(-1000 * 60 * 60 * 15) } },
|
||||
{ lastemailsent_Job: null }
|
||||
],
|
||||
idapp
|
||||
}).lean();
|
||||
};
|
||||
@@ -141,10 +147,10 @@ NewstosentSchema.statics.getlast = async function (idapp) {
|
||||
const Newstosent = this;
|
||||
|
||||
try {
|
||||
const mydoc = await Newstosent.find({ idapp }).sort({ datestartJob: -1 }).limit(1);
|
||||
return mydoc[0]._doc;
|
||||
const mydoc = await Newstosent.findOne({ idapp }).sort({ datestartJob: -1 }).lean();
|
||||
return mydoc || null;
|
||||
} catch (e) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -22,9 +22,9 @@ const orderSchema = new Schema({
|
||||
},
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'User' },
|
||||
status: {
|
||||
type: Number,
|
||||
type: Number, index: true
|
||||
},
|
||||
idProduct: { type: Schema.Types.ObjectId, ref: 'Product' },
|
||||
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' }],
|
||||
@@ -125,7 +125,8 @@ const orderSchema = new Schema({
|
||||
type: String
|
||||
},
|
||||
modify_at: {
|
||||
type: Date
|
||||
type: Date,
|
||||
index: true
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -548,41 +548,47 @@ module.exports.updateOrdersCartById = async function(id, newOrdersCart, callback
|
||||
id,
|
||||
deleted: false,
|
||||
}
|
||||
let mycart = null;
|
||||
try {
|
||||
const c = await OrdersCart.find(query);
|
||||
mycart = await OrdersCart.find(query);
|
||||
} catch (err) {
|
||||
console.log('ERR: updateOrdersCartById', err);
|
||||
if (err) throw err;
|
||||
}
|
||||
|
||||
//exist cart in databse
|
||||
if (c.length > 0) {
|
||||
return OrdersCart.findOneAndUpdate(
|
||||
{ _id: id },
|
||||
{
|
||||
$set: {
|
||||
items: newOrdersCart.items,
|
||||
totalQty: newOrdersCart.totalQty,
|
||||
totalQtyPreordered: newOrdersCart.totalQtyPreordered,
|
||||
totalPrice: newOrdersCart.totalPrice,
|
||||
totalPriceCalc: newOrdersCart.totalPriceCalc ? newOrdersCart.totalPriceCalc : newOrdersCart.totalPrice,
|
||||
userId: userId,
|
||||
status: newOrdersCart.status,
|
||||
numorder: newOrdersCart.numorder,
|
||||
numord_pers: newOrdersCart.numord_pers,
|
||||
note: newOrdersCart.note,
|
||||
modify_at: new Date(),
|
||||
}
|
||||
},
|
||||
{ new: true },
|
||||
callback
|
||||
)
|
||||
} else {
|
||||
//no cart in database
|
||||
return newOrdersCart.save(callback)
|
||||
try {
|
||||
//exist cart in databse
|
||||
if (mycart && mycart.length > 0) {
|
||||
return OrdersCart.findOneAndUpdate(
|
||||
{ _id: id },
|
||||
{
|
||||
$set: {
|
||||
items: newOrdersCart.items,
|
||||
totalQty: newOrdersCart.totalQty,
|
||||
totalQtyPreordered: newOrdersCart.totalQtyPreordered,
|
||||
totalPrice: newOrdersCart.totalPrice,
|
||||
totalPriceCalc: newOrdersCart.totalPriceCalc ? newOrdersCart.totalPriceCalc : newOrdersCart.totalPrice,
|
||||
userId: userId,
|
||||
status: newOrdersCart.status,
|
||||
numorder: newOrdersCart.numorder,
|
||||
numord_pers: newOrdersCart.numord_pers,
|
||||
note: newOrdersCart.note,
|
||||
modify_at: new Date(),
|
||||
}
|
||||
},
|
||||
{ new: true },
|
||||
callback
|
||||
)
|
||||
} else {
|
||||
//no cart in database
|
||||
return newOrdersCart.save(callback)
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Err updateOrdersCartById', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
module.exports.setFieldInOrdersById = async function (objtoset, myOrderCart) {
|
||||
|
||||
try {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -41,6 +41,7 @@ const productInfoSchema = new Schema({
|
||||
},
|
||||
name: {
|
||||
type: String,
|
||||
index: true,
|
||||
},
|
||||
description: {
|
||||
type: String,
|
||||
@@ -48,8 +49,11 @@ const productInfoSchema = new Schema({
|
||||
short_descr: {
|
||||
type: String,
|
||||
},
|
||||
idCatProds: [{ type: Schema.Types.ObjectId, ref: 'CatProd' }],
|
||||
idCatProds: [{ type: Schema.Types.ObjectId, ref: 'CatProd', index: true }],
|
||||
idSubCatProds: [{ type: Schema.Types.ObjectId, ref: 'SubCatProd' }],
|
||||
idStatoProdotto: {
|
||||
type: Number, index: true
|
||||
},
|
||||
color: {
|
||||
type: String
|
||||
},
|
||||
@@ -64,11 +68,9 @@ const productInfoSchema = new Schema({
|
||||
},
|
||||
unit: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
unit_lordo: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
sfuso: { // serve se moltiplicare le qta (es: 12 kg) oppure fare (2 x 20 ml)
|
||||
type: Boolean
|
||||
@@ -85,6 +87,9 @@ const productInfoSchema = new Schema({
|
||||
imagefile: {
|
||||
type: String,
|
||||
},
|
||||
image_not_found: {
|
||||
type: Boolean,
|
||||
},
|
||||
vers_img: {
|
||||
type: Number,
|
||||
},
|
||||
@@ -121,9 +126,9 @@ const productInfoSchema = new Schema({
|
||||
note: {
|
||||
type: String,
|
||||
},
|
||||
idAuthors: [{ type: Schema.Types.ObjectId, ref: 'Author' }],
|
||||
idCollana: { type: Number },
|
||||
idPublisher: { type: Schema.Types.ObjectId, ref: 'Publisher' },
|
||||
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,
|
||||
},
|
||||
@@ -132,6 +137,7 @@ const productInfoSchema = new Schema({
|
||||
},
|
||||
date_pub: {
|
||||
type: Date,
|
||||
index: 1,
|
||||
},
|
||||
date_pub_ts: {
|
||||
type: Number,
|
||||
@@ -143,13 +149,25 @@ const productInfoSchema = new Schema({
|
||||
date_updated: {
|
||||
type: Date,
|
||||
},
|
||||
|
||||
date_updated_fromGM: {
|
||||
type: Date,
|
||||
},
|
||||
|
||||
totVen: Number,
|
||||
totFat: Number,
|
||||
vLast3M: Number,
|
||||
fatLast3M: Number,
|
||||
vLast6M: Number,
|
||||
vLastY: Number,
|
||||
fatLast6M: Number,
|
||||
fatLast1Y: Number,
|
||||
fatLast2Y: Number,
|
||||
vLast6M: {
|
||||
type: Number,
|
||||
index: true,
|
||||
},
|
||||
vLast1Y: {
|
||||
type: Number, index: true
|
||||
},
|
||||
vLast2Y: Number,
|
||||
dataUltimoOrdine: Date,
|
||||
rank3M: Number,
|
||||
@@ -158,6 +176,7 @@ const productInfoSchema = new Schema({
|
||||
|
||||
descrizione_breve_macro: String,
|
||||
descrizione_completa_macro: String,
|
||||
descr_trafiletto_catalogo: String,
|
||||
sottotitolo: String,
|
||||
link_macro: String,
|
||||
|
||||
@@ -440,6 +459,103 @@ module.exports.correggiProductTypes = async function () {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.updateProductInfoByStats = async function (idapp) {
|
||||
let mylog = '';
|
||||
let mylog2 = '';
|
||||
let mylogtot = '';
|
||||
try {
|
||||
const ProductInfo = this;
|
||||
|
||||
const T_WEB_ArticoliFatturati = require('./t_web_articolifatturati');
|
||||
const T_WEB_Ordini = require('./t_web_ordini');
|
||||
|
||||
mylog = "Inizio Aggiornamento Statistiche... \n";
|
||||
mylogtot += mylog;
|
||||
console.log(mylog);
|
||||
|
||||
let countUpdate = 0;
|
||||
|
||||
countUpdate = await T_WEB_ArticoliFatturati.updateStatisticsFatt('', idapp, true);
|
||||
|
||||
// Itera sui risultati e aggiorna productInfo
|
||||
|
||||
mylog = `Aggiornati ${countUpdate} record di productInfo`;
|
||||
mylogtot += mylog;
|
||||
console.log(mylog);
|
||||
|
||||
mylog2 = "Inizio Aggiornamento Statistiche Ordini ... \n";
|
||||
mylogtot += mylog2;
|
||||
console.log(mylog2);
|
||||
|
||||
countUpdate = await T_WEB_Ordini.updateStatisticsOrders('', idapp, true);
|
||||
|
||||
mylog2 = `Aggiornati ${countUpdate} record di productInfo`;
|
||||
mylogtot += mylog2;
|
||||
|
||||
console.log(mylog2);
|
||||
|
||||
} catch (error) {
|
||||
mylog = "Errore durante l'aggiornamento di productInfo:" + error;
|
||||
console.error(mylog);
|
||||
}
|
||||
|
||||
return mylogtot;
|
||||
}
|
||||
|
||||
// crea setImgNotFound
|
||||
|
||||
module.exports.setImgNotFound = async function (id) {
|
||||
// set sul record id il flag image_not_found
|
||||
try {
|
||||
const ProductInfo = this;
|
||||
|
||||
await ProductInfo.updateOne(
|
||||
{ _id: id },
|
||||
{ $set: { image_not_found: true } }
|
||||
);
|
||||
console.log(`Flag image_not_found set for record with id: ${id}`);
|
||||
} catch (error) {
|
||||
console.error(`Error setting image_not_found flag for id ${id}:`, error);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// crea una funzione che mi rimuove il record "product" che utilizza productInfo, nel caso in cui date_updated_fromGM non esista
|
||||
module.exports.removeProductInfoWithoutDateUpdatedFromGM = async function (idapp) {
|
||||
const ProductInfo = this;
|
||||
|
||||
const globalTables = require('../tools/globalTables');
|
||||
const Product = globalTables.getTableByTableName('Product');
|
||||
|
||||
let mylog;
|
||||
|
||||
try {
|
||||
const arrproductInfo = await ProductInfo.find({ idapp, date_updated_fromGM: { $exists: false } });
|
||||
|
||||
if (arrproductInfo.length > 0 && arrproductInfo.length < 1000) {
|
||||
mylog = `Rimuovo ${arrproductInfo.length} productInfo senza date_updated_fromGM !!`
|
||||
console.log(mylog);
|
||||
|
||||
for (const productinfo of arrproductInfo) {
|
||||
// cerca nella tabella Product se esiste idProductInfo = _id e cancella tutti i record che hanno questa corrispondenza
|
||||
if (Product) {
|
||||
await Product.deleteMany({ idProductInfo: productinfo._id });
|
||||
}
|
||||
|
||||
// Ora rimuovi anche questo productInfo
|
||||
await ProductInfo.deleteOne({ _id: productinfo._id });
|
||||
}
|
||||
}
|
||||
|
||||
return mylog;
|
||||
} catch (error) {
|
||||
mylog += 'Error removing productInfo without date_updated_fromGM:' + error;
|
||||
console.error(mylog);
|
||||
}
|
||||
|
||||
return mylog;
|
||||
};
|
||||
|
||||
module.exports.createIndexes()
|
||||
.then(() => { })
|
||||
.catch((err) => { throw err; });
|
||||
|
||||
@@ -313,24 +313,21 @@ ProjectSchema.statics.getIdParentByIdProj = function (idProj) {
|
||||
|
||||
ProjectSchema.statics.creaProjMain = async function (idapp) {
|
||||
|
||||
const projmain = {
|
||||
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
|
||||
};
|
||||
|
||||
return await new Project(projmain).save()
|
||||
.then(ris => {
|
||||
console.log('ris', ris);
|
||||
if (!!ris)
|
||||
return ris._doc;
|
||||
else
|
||||
return null;
|
||||
});
|
||||
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 }
|
||||
);
|
||||
|
||||
};
|
||||
|
||||
|
||||
@@ -24,6 +24,9 @@ const PublisherSchema = new Schema({
|
||||
img: {
|
||||
type: String,
|
||||
},
|
||||
quanti: {
|
||||
type: Number,
|
||||
},
|
||||
});
|
||||
|
||||
var Publisher = module.exports = mongoose.model('Publisher', PublisherSchema);
|
||||
@@ -45,6 +48,71 @@ module.exports.findAllIdApp = async function (idapp) {
|
||||
return await Publisher.find(myfind).sort({ name: 1 }).lean();
|
||||
};
|
||||
|
||||
module.exports.getEditoriWithTitleCount = async function (idapp, updatedata) {
|
||||
try {
|
||||
|
||||
const myquery = [
|
||||
{ $match: { idapp } },
|
||||
{
|
||||
$lookup: {
|
||||
from: 'productinfos', // Nome della tua collezione productInfo
|
||||
localField: '_id',
|
||||
foreignField: 'idPublisher',
|
||||
as: 'products'
|
||||
}
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
myproducts: {
|
||||
$filter: {
|
||||
input: "$products",
|
||||
as: "prod",
|
||||
cond: {
|
||||
$in: ["$$prod.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; });
|
||||
|
||||
@@ -304,7 +304,7 @@ reactionSchema.statics.addFavorite = async function (req, idapp, username, id, t
|
||||
fav: true,
|
||||
}
|
||||
})
|
||||
ok = ris.ok;
|
||||
ok = ris.acknowledged;
|
||||
}
|
||||
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
|
||||
@@ -124,7 +124,7 @@ sendNotifSchema.index({ sender: 1 });*/
|
||||
sendNotifSchema.index({ idapp: 1, typedir: 1, typeid: 1, status: 1, sender: 1 });
|
||||
|
||||
|
||||
sendNotifSchema.statics.setNotifAsRead = function (idapp, username, idnotif) {
|
||||
sendNotifSchema.statics.setNotifAsRead = async function (idapp, username, idnotif) {
|
||||
const SendNotif = this;
|
||||
|
||||
if (!username)
|
||||
@@ -133,7 +133,7 @@ sendNotifSchema.statics.setNotifAsRead = function (idapp, username, idnotif) {
|
||||
try {
|
||||
|
||||
if (idnotif) {
|
||||
return SendNotif.findOneAndUpdate({
|
||||
return await SendNotif.findOneAndUpdate({
|
||||
$and: [
|
||||
{ idapp },
|
||||
{ dest: username },
|
||||
@@ -154,11 +154,11 @@ sendNotifSchema.statics.setNotifAsRead = function (idapp, username, idnotif) {
|
||||
}
|
||||
};
|
||||
|
||||
sendNotifSchema.statics.getRecNotif = function (id) {
|
||||
sendNotifSchema.statics.getRecNotif = async function (id) {
|
||||
const SendNotif = this;
|
||||
|
||||
try {
|
||||
return SendNotif.findById(id).lean();
|
||||
return await SendNotif.findById(id).lean();
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
@@ -602,7 +602,7 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
|
||||
|
||||
recnotif.tag = recnotif.tag ? recnotif.tag : tag;
|
||||
|
||||
if (!recnotif.descr) {
|
||||
if (!recnotif.descr) {
|
||||
recnotif.descr = newdescr;
|
||||
}
|
||||
|
||||
@@ -895,10 +895,9 @@ sendNotifSchema.statics.updateStatusAndDescr = async function (myrecnotif, onlys
|
||||
|
||||
|
||||
// Cerca il record e se lo trova lo aggiorna
|
||||
const myrec = await SendNotif.findOneAndUpdate(query, { $set: fields_to_update }, {
|
||||
new: false,
|
||||
returnNewDocument: true,
|
||||
});
|
||||
const myrec = await SendNotif.findOneAndUpdate(query,
|
||||
{ $set: fields_to_update },
|
||||
{ returnDocument: "after" }).lean();
|
||||
|
||||
if (myrec) {
|
||||
return { myrecout: myrec, save: true };
|
||||
|
||||
@@ -48,7 +48,7 @@ const SettingsSchema = new Schema({
|
||||
|
||||
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 }]
|
||||
{ field: 'value_str', type: tools.FieldType.string }, { field: 'value_num', type: tools.FieldType.number }]
|
||||
};
|
||||
|
||||
SettingsSchema.statics.executeQueryTable = function (idapp, params) {
|
||||
@@ -94,9 +94,9 @@ SettingsSchema.statics.findAllIdApp = async function (idapp, serv, crypted = fal
|
||||
try {
|
||||
let myfind = '';
|
||||
if (serv) {
|
||||
myfind = {idapp, serv};
|
||||
myfind = { idapp, serv };
|
||||
} else
|
||||
myfind = {idapp};
|
||||
myfind = { idapp };
|
||||
|
||||
// myfind = {...myfind, $or: [{ crypted: { $exists: false } }, { crypted: { $exists: true, $eq: crypted } }]};
|
||||
|
||||
@@ -109,14 +109,14 @@ SettingsSchema.statics.findAllIdApp = async function (idapp, serv, crypted = fal
|
||||
if (rec.crypted) {
|
||||
rec.value_str = ''
|
||||
}
|
||||
myarr.push({...rec});
|
||||
myarr.push({ ...rec });
|
||||
}
|
||||
} else {
|
||||
myarr = [...arrorig];
|
||||
}
|
||||
|
||||
return myarr;
|
||||
}catch (e) {
|
||||
} catch (e) {
|
||||
console.error('Settings: findAllIdApp', e);
|
||||
return null;
|
||||
}
|
||||
@@ -136,7 +136,9 @@ SettingsSchema.statics.setKeyNum = async function (idapp, key, value) {
|
||||
|
||||
return await myrec.save();
|
||||
} else {
|
||||
myrec = await Settings.findOneAndUpdate({ idapp, key }, { $set: { value_num: value } }, { new: false });
|
||||
myrec = await Settings.findOneAndUpdate({ idapp, key },
|
||||
{ $set: { value_num: value } },
|
||||
{ new: false });
|
||||
}
|
||||
|
||||
return myrec
|
||||
|
||||
@@ -55,6 +55,7 @@ const StatSchema = new Schema({
|
||||
diffusorilist: [],
|
||||
receiveRislist: [],
|
||||
receiveRislistgroup: [],
|
||||
listlinksreg: [],
|
||||
strettelist: [],
|
||||
num_transaz_tot: Number,
|
||||
tot_RIS_transati: Number,
|
||||
@@ -95,6 +96,7 @@ StatSchema.statics.calculateStats = async function (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),
|
||||
@@ -110,7 +112,10 @@ StatSchema.statics.calculateStats = async function (idapp) {
|
||||
|
||||
if (trova_se_oggi) {
|
||||
// Aggiorna il record di oggi:
|
||||
const ris = await Stat.findOneAndUpdate({ _id: trova_se_oggi._id }, { $set: datastat }, { new: true });
|
||||
const ris = await Stat.findOneAndUpdate(
|
||||
{ _id: trova_se_oggi._id },
|
||||
{ $set: datastat },
|
||||
{ returnDocument: "after" });
|
||||
// console.log('ris', ris);
|
||||
} else {
|
||||
// Aggiungi un nuovo record:
|
||||
|
||||
107
src/server/models/t_web_articoli.js
Executable file
107
src/server/models/t_web_articoli.js
Executable 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; });
|
||||
|
||||
199
src/server/models/t_web_articolifatturati.js
Executable file
199
src/server/models/t_web_articolifatturati.js
Executable file
@@ -0,0 +1,199 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
const ProductInfo = require('../models/productInfo');
|
||||
|
||||
// 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 ProductInfo.updateOne(
|
||||
{
|
||||
sku: stat.sku,
|
||||
idapp
|
||||
}, // Cerca il documento con lo stesso sku
|
||||
{
|
||||
$set: {
|
||||
fatLast3M: stat.fatLast3M,
|
||||
fatLast6M: stat.fatLast6M,
|
||||
fatLast1Y: stat.fatLast1Y,
|
||||
fatLast2Y: stat.fatLast2Y,
|
||||
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/server/models/t_web_disponibles.js
Executable file
52
src/server/models/t_web_disponibles.js
Executable 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/server/models/t_web_ordini.js
Executable file
200
src/server/models/t_web_ordini.js
Executable 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 ProductInfo = require('../models/productInfo');
|
||||
|
||||
// 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 ProductInfo.updateOne(
|
||||
{
|
||||
sku: stat.sku,
|
||||
idapp,
|
||||
}, // Cerca il documento con lo stesso sku
|
||||
{
|
||||
$set: {
|
||||
totVen: stat.totVen,
|
||||
vLast3M: stat.vLast3M,
|
||||
vLast6M: stat.vLast6M,
|
||||
vLast1Y: stat.vLast1Y,
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
54
src/server/models/t_web_statiprodotto.js
Executable file
54
src/server/models/t_web_statiprodotto.js
Executable file
@@ -0,0 +1,54 @@
|
||||
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
|
||||
}
|
||||
];
|
||||
|
||||
const rec = await T_WEB_StatiProdotto.aggregate(myquery);
|
||||
return rec;
|
||||
};
|
||||
|
||||
|
||||
54
src/server/models/t_web_tipiformato.js
Executable file
54
src/server/models/t_web_tipiformato.js
Executable file
@@ -0,0 +1,54 @@
|
||||
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
|
||||
}
|
||||
];
|
||||
|
||||
const rec = await T_WEB_TipiFormato.aggregate(myquery);
|
||||
return rec;
|
||||
};
|
||||
|
||||
|
||||
54
src/server/models/t_web_tipologie.js
Executable file
54
src/server/models/t_web_tipologie.js
Executable file
@@ -0,0 +1,54 @@
|
||||
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
|
||||
}
|
||||
];
|
||||
|
||||
const rec = await T_WEB_Tipologie.aggregate(myquery);
|
||||
return rec;
|
||||
};
|
||||
|
||||
|
||||
@@ -25,6 +25,15 @@ const TemplEmailSchema = new Schema({
|
||||
content: {
|
||||
type: String,
|
||||
},
|
||||
disclaimer: {
|
||||
type: String,
|
||||
},
|
||||
piedipagina: {
|
||||
type: String,
|
||||
},
|
||||
firma: {
|
||||
type: String,
|
||||
},
|
||||
img: {
|
||||
type: String,
|
||||
},
|
||||
|
||||
@@ -177,6 +177,12 @@ const UserSchema = new mongoose.Schema({
|
||||
news_on: {
|
||||
type: Boolean,
|
||||
},
|
||||
diario_on: {
|
||||
type: Boolean,
|
||||
},
|
||||
test: {
|
||||
type: Boolean,
|
||||
},
|
||||
email_errata: {
|
||||
type: Boolean,
|
||||
},
|
||||
@@ -435,6 +441,9 @@ const UserSchema = new mongoose.Schema({
|
||||
lastdate_reqRis: {
|
||||
type: Date,
|
||||
},
|
||||
lastdate_LinkReg: {
|
||||
type: Date,
|
||||
},
|
||||
notifs: [
|
||||
{
|
||||
_id: false,
|
||||
@@ -568,8 +577,6 @@ UserSchema.methods.generateAuthToken = function (req) {
|
||||
user.lasttimeonline = new Date();
|
||||
|
||||
return user.save().then(() => {
|
||||
// console.log('Salvato refreshToken su DB', refreshToken);
|
||||
// console.log("TOKEN CREATO IN LOGIN : " + token);
|
||||
return { token, refreshToken };
|
||||
}).catch(err => {
|
||||
console.log('Error', err.message);
|
||||
@@ -577,11 +584,11 @@ UserSchema.methods.generateAuthToken = function (req) {
|
||||
});
|
||||
};
|
||||
|
||||
UserSchema.statics.setOnLine = function (idapp, username) {
|
||||
UserSchema.statics.setOnLine = async function (idapp, username) {
|
||||
const User = this;
|
||||
|
||||
try {
|
||||
return User.findOneAndUpdate({ idapp, username }, { $set: { lasttimeonline: new Date() } });
|
||||
return await User.findOneAndUpdate({ idapp, username }, { $set: { lasttimeonline: new Date() } });
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
@@ -639,7 +646,7 @@ UserSchema.statics.canHavePower = function (perm) {
|
||||
try {
|
||||
let consentito = false;
|
||||
if (User.isAdmin(perm) || User.isManager(perm) ||
|
||||
User.isEditor(perm) || User.isFacilitatore(perm)) {
|
||||
User.isEditor(perm) || User.isCommerciale(perm) || User.isFacilitatore(perm)) {
|
||||
consentito = true;
|
||||
}
|
||||
|
||||
@@ -695,6 +702,14 @@ UserSchema.statics.isEditor = function (perm) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
UserSchema.statics.isCommerciale = function (perm) {
|
||||
try {
|
||||
return ((perm & shared_consts.Permissions.Commerciale) ===
|
||||
shared_consts.Permissions.Commerciale);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
UserSchema.statics.isGrafico = function (perm) {
|
||||
try {
|
||||
return ((perm & shared_consts.Permissions.Grafico) ===
|
||||
@@ -731,63 +746,110 @@ UserSchema.statics.isFacilitatore = function (perm) {
|
||||
}
|
||||
};
|
||||
|
||||
UserSchema.statics.findByToken = async function (token, typeaccess, con_auth, idapp) {
|
||||
/**
|
||||
* Finds a user by their authentication token.
|
||||
*
|
||||
* @param {string} token - The authentication token.
|
||||
* @param {string} typeaccess - The type of access associated with the token.
|
||||
* @param {boolean} con_auth - Whether to continue authentication if the token is expired.
|
||||
* @param {string} idapp - The application ID.
|
||||
* @returns {Promise<Object>} An object containing the user and a status code, indicating
|
||||
* whether the token is valid, expired, or invalid.
|
||||
* The user object is null if no user is found or the token is invalid.
|
||||
*
|
||||
* This function verifies the provided token and retrieves the corresponding user if the token is valid.
|
||||
* If the token is expired and `con_auth` is false, or if the token is invalid, it returns null for the user.
|
||||
* The status code reflects the validity of the token: valid, expired, or invalid.
|
||||
*/
|
||||
|
||||
UserSchema.statics.findByToken = async function (token, typeaccess, con_auth, withuser, withlean = false) {
|
||||
const User = this;
|
||||
let decoded;
|
||||
let code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN;
|
||||
let user = null;
|
||||
let decoded;
|
||||
const start = process.hrtime.bigint();
|
||||
const start_jwt = process.hrtime.bigint();
|
||||
|
||||
try {
|
||||
if (token) {
|
||||
decoded = jwt.verify(token, process.env.SIGNCODE);
|
||||
|
||||
code = server_constants.RIS_CODE_OK;
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
|
||||
if (e.expiredAt) {
|
||||
|
||||
code = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED;
|
||||
if (con_auth) {
|
||||
return { user: null, code };
|
||||
}
|
||||
} else {
|
||||
console.error('Err findByToken:', e);
|
||||
}
|
||||
if (!token) {
|
||||
console.warn('TOKEN VUOTO ! ');
|
||||
return { user, code };
|
||||
}
|
||||
|
||||
if (code === server_constants.RIS_CODE_OK) {
|
||||
|
||||
try {
|
||||
decoded = jwt.verify(token, process.env.SIGNCODE);
|
||||
code = server_constants.RIS_CODE_OK;
|
||||
} catch (err) {
|
||||
if (err.expiredAt) {
|
||||
code = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED;
|
||||
if (con_auth) return { user: null, code };
|
||||
} else {
|
||||
console.error('Err findByToken:', err);
|
||||
}
|
||||
return { user: null, code };
|
||||
}
|
||||
|
||||
const end_jwt = process.hrtime.bigint();
|
||||
// console.log(` jwt.verify impiega ${Math.round(Number(end_jwt - start_jwt) / 1e6) / 1000} secondi.`);
|
||||
|
||||
let project = undefined;
|
||||
|
||||
if (withuser) {
|
||||
const start_find = process.hrtime.bigint();
|
||||
if (withlean) {
|
||||
user = await User.findOne({
|
||||
_id: decoded.smart,
|
||||
tokens: {
|
||||
$elemMatch: {
|
||||
token,
|
||||
access: typeaccess,
|
||||
},
|
||||
},
|
||||
}, project).lean();
|
||||
} else {
|
||||
user = await User.findOne({
|
||||
_id: decoded.smart,
|
||||
tokens: {
|
||||
$elemMatch: {
|
||||
token,
|
||||
access: typeaccess,
|
||||
},
|
||||
},
|
||||
}, project);
|
||||
}
|
||||
const end_find = process.hrtime.bigint();
|
||||
// console.log(` User.findOne impiega ${Math.round(Number(end_find - start_find) / 1e6) / 1000} secondi.`);
|
||||
} else {
|
||||
|
||||
project = { perm: 1, _id: 1, idapp: 1, username: 1, deleted: 1, aportador_solidario: 1, aportador_solidario_nome_completo: 1, 'profile.socioresidente': 1 };
|
||||
|
||||
const start_find = process.hrtime.bigint();
|
||||
user = await User.findOne({
|
||||
'_id': decoded.smart,
|
||||
_id: decoded.smart,
|
||||
tokens: {
|
||||
$elemMatch: {
|
||||
token: token,
|
||||
token,
|
||||
access: typeaccess,
|
||||
},
|
||||
},
|
||||
});
|
||||
}, project).lean();
|
||||
const end_find = process.hrtime.bigint();
|
||||
// console.log(` User.findOne LEAN impiega ${Math.round(Number(end_find - start_find) / 1e6) / 1000} secondi.`);
|
||||
}
|
||||
|
||||
if (user) {
|
||||
let check_expiry_date = false
|
||||
// Controlla se il sito ha attivo il controllo del Token Scaduto
|
||||
if (tools.getEnableTokenExpiredByIdApp(user.idapp)) {
|
||||
check_expiry_date = true
|
||||
}
|
||||
|
||||
let tempo = Date.now() / 1000;
|
||||
|
||||
if (check_expiry_date && (decoded.exp < tempo)) {
|
||||
console.log('Il token è scaduto, generazione del nuovo token...');
|
||||
code = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED;
|
||||
} else {
|
||||
// TOKEN ANCORA VALIDO
|
||||
code = server_constants.RIS_CODE_OK;
|
||||
}
|
||||
if (user) {
|
||||
const checkExpiry = tools.getEnableTokenExpiredByIdApp(user.idapp);
|
||||
const currentTime = Date.now() / 1000;
|
||||
if (checkExpiry && decoded.exp < currentTime) {
|
||||
console.log('Il token è scaduto, generazione del nuovo token...');
|
||||
code = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED;
|
||||
}
|
||||
}
|
||||
|
||||
// const end = process.hrtime.bigint();
|
||||
// console.log(` findByToken impiega ${Math.round(Number(end - start) / 1e6) / 1000} secondi.`);
|
||||
|
||||
return { user, code };
|
||||
};
|
||||
|
||||
@@ -805,16 +867,16 @@ UserSchema.statics.findByTokenAnyAccess = function (token) {
|
||||
return User.findOne({
|
||||
'_id': decoded.smart,
|
||||
'tokens.token': token,
|
||||
});
|
||||
}).lean();
|
||||
};
|
||||
|
||||
UserSchema.statics.findByCredentials = function (idapp, username, password, pwdcrypted) {
|
||||
UserSchema.statics.findByCredentials = async function (idapp, username, password, pwdcrypted) {
|
||||
const User = this;
|
||||
let pwd = '';
|
||||
|
||||
let regexp = new RegExp(`^${username}$`, 'i');
|
||||
|
||||
return User.findOne({
|
||||
let user = await User.findOne({
|
||||
idapp,
|
||||
username: { $regex: regexp },
|
||||
$or: [
|
||||
@@ -828,58 +890,46 @@ UserSchema.statics.findByCredentials = function (idapp, username, password, pwdc
|
||||
},
|
||||
],
|
||||
|
||||
}).then((user) => {
|
||||
if (!user) {
|
||||
// Check if with email:
|
||||
return User.findOne({
|
||||
idapp, email: username.toLowerCase(),
|
||||
$or: [
|
||||
{ deleted: { $exists: false } },
|
||||
{ deleted: { $exists: true, $eq: false } }],
|
||||
});
|
||||
} else {
|
||||
return !user.deleted || (user.deleted && user.subaccount) ? user : null;
|
||||
}
|
||||
}).then((user) => {
|
||||
if (!user) {
|
||||
// Check with username telegram
|
||||
return User.findOne({
|
||||
idapp,
|
||||
'profile.username_telegram': username.toLowerCase(),
|
||||
$or: [
|
||||
{ deleted: { $exists: false } },
|
||||
{ deleted: { $exists: true, $eq: false } }],
|
||||
});
|
||||
} else {
|
||||
return !user.deleted || (user.deleted && user.subaccount) ? user : null;
|
||||
}
|
||||
}).then(user => {
|
||||
if (!user)
|
||||
return null;
|
||||
|
||||
pwd = user.password;
|
||||
|
||||
if (pwdcrypted) {
|
||||
if (pwd === user.password) {
|
||||
return user;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// Use bcrypt.compare to compare password and user.password
|
||||
// console.log("pwd1 " + password);
|
||||
// console.log("pwd2 " + pwd);
|
||||
bcrypt.compare(password, pwd, (err, res) => {
|
||||
if (res) {
|
||||
resolve(user);
|
||||
} else {
|
||||
return resolve(null);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
// Check if with email:
|
||||
user = await User.findOne({
|
||||
idapp, email: username.toLowerCase(),
|
||||
$or: [
|
||||
{ deleted: { $exists: false } },
|
||||
{ deleted: { $exists: true, $eq: false } }],
|
||||
});
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
// Check with username telegram
|
||||
user = await User.findOne({
|
||||
idapp,
|
||||
'profile.username_telegram': username.toLowerCase(),
|
||||
$or: [
|
||||
{ deleted: { $exists: false } },
|
||||
{ deleted: { $exists: true, $eq: false } }],
|
||||
});
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
pwd = user.password;
|
||||
|
||||
if (pwdcrypted) {
|
||||
if (pwd === user.password) {
|
||||
return user;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const res = await bcrypt.compare(password, pwd) ? user : null;
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
UserSchema.statics.findByUsername = async function (idapp, username, alsoemail, onlyifVerifiedByAportador) {
|
||||
@@ -1314,6 +1364,16 @@ UserSchema.statics.setaportador_solidario = async function (
|
||||
return !!myrec;
|
||||
};
|
||||
|
||||
UserSchema.statics.setNewsletterToAll = async function (
|
||||
idapp) {
|
||||
const User = this;
|
||||
|
||||
return await User.updateMany({
|
||||
idapp,
|
||||
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
|
||||
}, { $set: { 'news_on': true } },
|
||||
{ new: false });
|
||||
};
|
||||
UserSchema.statics.setNewsletter = async function (
|
||||
idapp, username, newsletter_on) {
|
||||
const User = this;
|
||||
@@ -1902,6 +1962,7 @@ UserSchema.statics.getUserProfileByUsername = async function (
|
||||
|
||||
if (perm === tools.Perm.PERM_NONE) {
|
||||
whatToShow = {
|
||||
idapp: 1,
|
||||
lang: 1,
|
||||
index: 1,
|
||||
username: 1,
|
||||
@@ -1952,6 +2013,7 @@ UserSchema.statics.getUserProfileByUsername = async function (
|
||||
|
||||
} else if (perm === tools.Perm.PERM_FRIEND) {
|
||||
whatToShow = {
|
||||
idapp: 1,
|
||||
lang: 1,
|
||||
index: 1,
|
||||
username: 1,
|
||||
@@ -2001,6 +2063,7 @@ UserSchema.statics.getUserProfileByUsername = async function (
|
||||
|
||||
} else if (perm === tools.Perm.PERM_ALL) {
|
||||
whatToShow = {
|
||||
idapp: 1,
|
||||
lang: 1,
|
||||
index: 1,
|
||||
username: 1,
|
||||
@@ -2150,17 +2213,14 @@ UserSchema.statics.getArrUsernameFromFieldByUsername = async function (
|
||||
idapp, username, field, subfield) {
|
||||
|
||||
const myobj = {};
|
||||
myobj[field + '.' + subfield] = 1;
|
||||
myobj[field + '.' + subfield + '.username'] = 1;
|
||||
|
||||
let arrrec = await User.findOne({
|
||||
const rec = await User.findOne({
|
||||
idapp, 'username': username,
|
||||
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
|
||||
}, myobj).then((ris) => ris ? ris._doc[field][subfield] : []);
|
||||
}, myobj);
|
||||
|
||||
if (arrrec && arrrec.length > 0) {
|
||||
return arrrec.map(m => m.username);
|
||||
}
|
||||
return [];
|
||||
return rec ? rec[field][subfield].map(m => m.username) : [];
|
||||
|
||||
};
|
||||
|
||||
@@ -3043,6 +3103,7 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn
|
||||
// console.log('setCircuitCmd', cmd);
|
||||
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
const telegrambot = require('../telegram/telegrambot');
|
||||
|
||||
let ris = null;
|
||||
let outres = {
|
||||
@@ -3281,72 +3342,85 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn
|
||||
outres = await Circuit.sendCoins(onlycheck, idapp, usernameOrig, extrarec);
|
||||
|
||||
if (outres.cansend) {
|
||||
// Invia una notifica di moneta alla persona
|
||||
//const out = await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action,
|
||||
// extrarec);
|
||||
//if (out)
|
||||
// outres.result = out.ris;
|
||||
} else {
|
||||
outres.cansend = false;
|
||||
}
|
||||
ris = true;
|
||||
// } else if ((cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) || (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE)) {
|
||||
// Before to accept, I see if it's already set !
|
||||
|
||||
ris = true;
|
||||
// } else if ((cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) || (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE)) {
|
||||
// Before to accept, I see if it's already set !
|
||||
/*outres = {
|
||||
cansend: false,
|
||||
errormsg: '',
|
||||
}; */
|
||||
|
||||
/*outres = {
|
||||
cansend: false,
|
||||
errormsg: '',
|
||||
}; */
|
||||
let outcheck = outres;
|
||||
|
||||
let outcheck = outres;
|
||||
|
||||
let risStatus = '';
|
||||
const status = await SendNotif.getStatus(extrarec.notifId);
|
||||
if (status === shared_consts.CircuitsNotif.STATUS_ACCEPTED) {
|
||||
risStatus = i18n.__('STATUS_SENT');
|
||||
} else if (status === shared_consts.CircuitsNotif.STATUS_REFUSED) {
|
||||
risStatus = i18n.__('STATUS_REFUSED');
|
||||
}
|
||||
// if (!await SendNotif.checkIfCoinsAlreadySent(extrarec.notifId)) {
|
||||
//if (!await Movement.checkIfCoinsAlreadySent(extrarec.notifId)) {
|
||||
if (true) {
|
||||
if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) {
|
||||
//outcheck = await Circuit.sendCoins(true, idapp, usernameOrig, extrarec);
|
||||
outcheck.cansend = true;
|
||||
outres.cansend = true;
|
||||
} else {
|
||||
outcheck.cansend = true;
|
||||
outres.cansend = true;
|
||||
let risStatus = '';
|
||||
const status = await SendNotif.getStatus(extrarec.notifId);
|
||||
if (status === shared_consts.CircuitsNotif.STATUS_ACCEPTED) {
|
||||
risStatus = i18n.__('STATUS_SENT');
|
||||
} else if (status === shared_consts.CircuitsNotif.STATUS_REFUSED) {
|
||||
risStatus = i18n.__('STATUS_REFUSED');
|
||||
}
|
||||
|
||||
cmd = shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT;
|
||||
|
||||
/*if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT && outcheck.cansend) {
|
||||
if (!await Movement.checkIfCoinsAlreadySent(extrarec.notifId)) {
|
||||
outres = await Circuit.sendCoins(false, idapp, usernameOrig, extrarec);
|
||||
|
||||
// if (!await SendNotif.checkIfCoinsAlreadySent(extrarec.notifId)) {
|
||||
//if (!await Movement.checkIfCoinsAlreadySent(extrarec.notifId)) {
|
||||
if (true) {
|
||||
if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) {
|
||||
//outcheck = await Circuit.sendCoins(true, idapp, usernameOrig, extrarec);
|
||||
outcheck.cansend = true;
|
||||
outres.cansend = true;
|
||||
} else {
|
||||
outcheck.cansend = false; //GIA INVIATO
|
||||
outcheck.cansend = true;
|
||||
outres.cansend = true;
|
||||
}
|
||||
} */
|
||||
|
||||
if (outcheck.cansend) {
|
||||
// Invia una notifica di moneta (accettata o rifiutata) alla persona
|
||||
const out = await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec);
|
||||
cmd = shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT;
|
||||
|
||||
if (outres && extrarec.groupname) {
|
||||
// Setta agli altri admin,
|
||||
/*if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT && outcheck.cansend) {
|
||||
if (!await Movement.checkIfCoinsAlreadySent(extrarec.notifId)) {
|
||||
outres = await Circuit.sendCoins(false, idapp, usernameOrig, extrarec);
|
||||
|
||||
} else {
|
||||
outcheck.cansend = false; //GIA INVIATO
|
||||
}
|
||||
} */
|
||||
|
||||
if (outcheck.cansend) {
|
||||
// Invia una notifica di moneta (accettata o rifiutata) alla persona
|
||||
const out = await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, extrarec);
|
||||
|
||||
if (outres && extrarec.groupname) {
|
||||
// Setta agli altri admin,
|
||||
}
|
||||
}
|
||||
|
||||
outres.recnotif = await SendNotif.getRecNotif(extrarec.notifId);
|
||||
outres.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER, shared_consts.QualiNotifs.OTHERS);
|
||||
if (await User.isAdminByUsername(idapp, username_action)) {
|
||||
outres.arrrecnotifcoins = await SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp);
|
||||
} else {
|
||||
outres.arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIFCOINS_FOR_USER, shared_consts.QualiNotifs.CIRCUITS);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (outres.errormsg) {
|
||||
let msgerr = '';
|
||||
let username_dest = extrarec.dest;
|
||||
if (outres.errorcode === shared_consts.SENDRIS_CODES.EXCEED_FIDO) {
|
||||
} else if (outres.errorcode === shared_consts.SENDRIS_CODES.EXCEED_QTAMAX) {
|
||||
// invia un messaggio al destinatario
|
||||
const msgDest = i18n.__('EXCEED_QTAMAX', usernameOrig, extrarec.qty.toString(), extrarec.circuitname);
|
||||
await telegrambot.sendMsgTelegram(idapp, username_dest, msgDest);
|
||||
|
||||
msgerr = i18n.__('EXCEED_QTAMAX_MITTENTE', username_dest);
|
||||
await telegrambot.sendMsgTelegram(idapp, usernameOrig, msgerr);
|
||||
}
|
||||
|
||||
outres.recnotif = await SendNotif.getRecNotif(extrarec.notifId);
|
||||
outres.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER, shared_consts.QualiNotifs.OTHERS);
|
||||
if (await User.isAdminByUsername(idapp, username_action)) {
|
||||
outres.arrrecnotifcoins = await SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp);
|
||||
} else {
|
||||
outres.arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIFCOINS_FOR_USER, shared_consts.QualiNotifs.CIRCUITS);
|
||||
}
|
||||
console.warn('🔴 ATTENZIONE! ', outres.errormsg + '\n(Mittente: ' + usernameOrig + ')');
|
||||
// await telegrambot.sendMsgTelegram(idapp, usernameOrig, msgOrig);
|
||||
|
||||
// Invia questo msg anche all'Admin
|
||||
await telegrambot.sendMsgTelegramToTheAdmin(idapp, outres.errormsg + '\n(Mittente: ' + usernameOrig + ')', true);
|
||||
|
||||
}
|
||||
|
||||
@@ -4832,6 +4906,15 @@ UserSchema.statics.getReceiveRISUsers = async function (idapp) {
|
||||
return ris;
|
||||
});
|
||||
|
||||
};
|
||||
UserSchema.statics.getListLinkReg = async function (idapp) {
|
||||
const User = this;
|
||||
|
||||
return await User.aggregate(User.getQueryListLinkReg(idapp, 8)).then(ris => {
|
||||
// console.table(ris);
|
||||
return ris;
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
UserSchema.statics.checkUser = async function (idapp, username) {
|
||||
@@ -5377,6 +5460,93 @@ UserSchema.statics.getQueryReceiveRISUsers = function (idapp, hours) {
|
||||
return query;
|
||||
};
|
||||
|
||||
UserSchema.statics.getQueryListLinkReg = function (idapp, hours) {
|
||||
|
||||
const query = [
|
||||
{
|
||||
$match: {
|
||||
idapp,
|
||||
'profile.lastdate_LinkReg': { $gte: tools.IncDateNow(-(1000 * 60 * 60 * hours)) },
|
||||
$or: [
|
||||
{ deleted: { $exists: false } },
|
||||
{ deleted: { $exists: true, $eq: false } }],
|
||||
},
|
||||
},
|
||||
{
|
||||
$group:
|
||||
{
|
||||
_id: "$username",
|
||||
count: {
|
||||
$sum: 1,
|
||||
},
|
||||
}
|
||||
},
|
||||
{ $sort: { 'profile.lastdate_linkReg': -1 } },
|
||||
{ $limit: 30 },
|
||||
{
|
||||
$lookup: {
|
||||
from: "users",
|
||||
let: {
|
||||
username: "$_id",
|
||||
idapp,
|
||||
},
|
||||
pipeline: [
|
||||
{
|
||||
$match: {
|
||||
$expr: {
|
||||
$and: [
|
||||
{
|
||||
$eq: [
|
||||
"$$username",
|
||||
"$username",
|
||||
],
|
||||
},
|
||||
{
|
||||
$eq: [
|
||||
"$$idapp",
|
||||
"$idapp",
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
as: "user",
|
||||
},
|
||||
},
|
||||
{ $unwind: "$user" },
|
||||
{
|
||||
$replaceRoot: {
|
||||
newRoot: {
|
||||
$mergeObjects: ["$user", "$$ROOT"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
count: 1,
|
||||
aportador_solidario: 1,
|
||||
username: 1,
|
||||
name: 1,
|
||||
surname: 1,
|
||||
lasttimeonline: 1,
|
||||
'profile.lastdate_linkReg': 1,
|
||||
'profile.mycircuits': 1,
|
||||
date_reg: 1,
|
||||
idapp: 1,
|
||||
"profile.img": 1,
|
||||
'profile.handshake': 1,
|
||||
'profile.note': 1,
|
||||
'profile.da_contattare': 1,
|
||||
perm: 1,
|
||||
},
|
||||
},
|
||||
];
|
||||
return query;
|
||||
};
|
||||
|
||||
UserSchema.statics.getUsersRegWeekly = function (idapp, nrec) {
|
||||
|
||||
const query = [
|
||||
@@ -5790,7 +5960,7 @@ UserSchema.statics.getExtraInfoByUsername = async function (idapp, username) {
|
||||
|
||||
let myuser = await User.findOne({ idapp, username }).lean();
|
||||
if (myuser) {
|
||||
myuserextra = await User.addExtraInfo(idapp, myuser, null);
|
||||
myuserextra = await User.addExtraInfo(idapp, myuser);
|
||||
return myuser.profile;
|
||||
}
|
||||
|
||||
@@ -5816,118 +5986,112 @@ UserSchema.statics.getProfilePerActivitiesByUsername = async function (idapp, us
|
||||
|
||||
};
|
||||
|
||||
UserSchema.statics.addExtraInfo = async function (idapp, recUser, recUserSave, version) {
|
||||
|
||||
UserSchema.statics.addExtraInfo = async function (idapp, recUser, version) {
|
||||
try {
|
||||
// tools.startTimeLog('addExtraInfo')
|
||||
|
||||
if (version) {
|
||||
let versattualeuser = 0;
|
||||
if (!recUser.profile.version) {
|
||||
recUser.version = 0;
|
||||
versattualeuser = 0;
|
||||
} else {
|
||||
versattualeuser = recUser.profile.version;
|
||||
}
|
||||
|
||||
// versattualeuser = 0; // TOGLIERE!
|
||||
|
||||
// Verifica e aggiornamento della versione (blocco sequenziale)
|
||||
if (version && recUser) {
|
||||
const versattualeuser = recUser?.profile?.version || 0;
|
||||
if (versattualeuser < version) {
|
||||
// Aggiornamento versione
|
||||
// Aggiorna la versione utente (eventuali chiamate dipendenti vanno eseguite in sequenza)
|
||||
recUser = await User.updateVersion(versattualeuser, recUser);
|
||||
|
||||
await User.findOneAndUpdate({ _id: recUser._id }, { $set: { 'profile.version': version } });
|
||||
}
|
||||
}
|
||||
|
||||
const listSentMyRequestFriends = await User.find({
|
||||
idapp,
|
||||
'profile.req_friends': {
|
||||
$elemMatch: { username: { $eq: recUser.username } },
|
||||
},
|
||||
$or: [
|
||||
{ deleted: { $exists: false } },
|
||||
{ deleted: { $exists: true, $eq: false } }],
|
||||
}, { username: 1 }).lean();
|
||||
// Esegui le query indipendenti in parallelo
|
||||
const [
|
||||
listSentMyRequestFriends,
|
||||
listSentMyRequestGroups,
|
||||
listRefusedGroups,
|
||||
listManageGroups,
|
||||
reactions,
|
||||
userstoverify,
|
||||
circuitobj,
|
||||
useraccounts,
|
||||
calcstat,
|
||||
calcOther
|
||||
] = await Promise.all([
|
||||
// Richiesta per gli amici a cui è stata mandata una richiesta
|
||||
User.find(
|
||||
{
|
||||
idapp,
|
||||
'profile.req_friends': { $elemMatch: { username: recUser.username } },
|
||||
$or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }]
|
||||
},
|
||||
{ username: 1 }
|
||||
).lean(),
|
||||
|
||||
recUser.profile.asked_friends = listSentMyRequestFriends
|
||||
? listSentMyRequestFriends
|
||||
: [];
|
||||
// Richiesta per i gruppi a cui è stata mandata una richiesta
|
||||
MyGroup.find(
|
||||
{
|
||||
idapp,
|
||||
'req_users': { $elemMatch: { username: recUser.username } },
|
||||
$or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }]
|
||||
},
|
||||
MyGroup.getWhatToShow_Unknown()
|
||||
).lean(),
|
||||
|
||||
const listSentMyRequestGroups = await MyGroup.find({
|
||||
idapp,
|
||||
'req_users': {
|
||||
$elemMatch: { username: { $eq: recUser.username } },
|
||||
},
|
||||
$or: [
|
||||
{ deleted: { $exists: false } },
|
||||
{ deleted: { $exists: true, $eq: false } }],
|
||||
}, MyGroup.getWhatToShow_Unknown()).lean();
|
||||
// Richiesta per i gruppi rifiutati
|
||||
MyGroup.find(
|
||||
{
|
||||
idapp,
|
||||
'refused_users': { $elemMatch: { username: recUser.username } },
|
||||
$or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }]
|
||||
},
|
||||
MyGroup.getWhatToShow_Unknown()
|
||||
).lean(),
|
||||
|
||||
recUser.profile.asked_groups = listSentMyRequestGroups
|
||||
? listSentMyRequestGroups
|
||||
: [];
|
||||
// Richiesta per i gruppi gestiti (admin)
|
||||
MyGroup.find(
|
||||
{
|
||||
idapp,
|
||||
'admins': { $elemMatch: { username: recUser.username } },
|
||||
$or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }]
|
||||
}
|
||||
).lean(),
|
||||
|
||||
const listRefusedGroups = await MyGroup.find({
|
||||
idapp,
|
||||
'refused_users': {
|
||||
$elemMatch: { username: { $eq: recUser.username } },
|
||||
},
|
||||
$or: [
|
||||
{ deleted: { $exists: false } },
|
||||
{ deleted: { $exists: true, $eq: false } }],
|
||||
}, MyGroup.getWhatToShow_Unknown()).lean();
|
||||
// Reazioni
|
||||
Reaction.find({ idapp, username: recUser.username }).lean(),
|
||||
|
||||
recUser.profile.refused_groups = listRefusedGroups
|
||||
? listRefusedGroups
|
||||
: [];
|
||||
// Altri utenti da verificare
|
||||
User.getUsersToVerify(idapp, recUser.username),
|
||||
|
||||
const listManageGroups = await MyGroup.find({
|
||||
idapp,
|
||||
'admins': {
|
||||
$elemMatch: { username: { $eq: recUser.username } },
|
||||
},
|
||||
$or: [
|
||||
{ deleted: { $exists: false } },
|
||||
{ deleted: { $exists: true, $eq: false } }],
|
||||
}).lean();
|
||||
// Circuiti associati
|
||||
Circuit.getCircuitsByUsername(idapp, recUser.username, recUser, 5),
|
||||
|
||||
recUser.profile.reaction = await Reaction.find({ idapp, username: recUser.username }).lean();
|
||||
// Conto degli account utente
|
||||
Account.getUserAccounts(idapp, recUser.username),
|
||||
|
||||
recUser.profile.userstoverify = await User.getUsersToVerify(idapp, recUser.username);
|
||||
// Statistiche dell'utente
|
||||
User.calculateStat(idapp, recUser.username),
|
||||
|
||||
recUser.profile.manage_mygroups = listManageGroups
|
||||
? listManageGroups
|
||||
: [];
|
||||
// Altri calcoli per l'utente
|
||||
User.calcOtherByUser(idapp, recUser._id)
|
||||
]);
|
||||
|
||||
// Circuit>
|
||||
|
||||
const circuitobj = await Circuit.getCircuitsByUsername(idapp, recUser.username, recUser, 5);
|
||||
|
||||
const useraccounts = await Account.getUserAccounts(idapp, recUser.username);
|
||||
|
||||
for (const group of listManageGroups) {
|
||||
const myaccounts = await Account.getGroupAccounts(idapp, group.groupname);
|
||||
if (myaccounts && myaccounts.length > 0)
|
||||
group.account = myaccounts[0];
|
||||
else
|
||||
group.account = null;
|
||||
}
|
||||
// Per ogni gruppo gestito, recupera gli account in parallelo
|
||||
const manageGroupsWithAccounts = await Promise.all(
|
||||
listManageGroups.map(async (group) => {
|
||||
const myaccounts = await Account.getGroupAccounts(idapp, group.groupname);
|
||||
return { ...group, account: (myaccounts && myaccounts.length > 0) ? myaccounts[0] : null };
|
||||
})
|
||||
);
|
||||
|
||||
// Assegna i risultati al profilo utente
|
||||
recUser.profile.asked_friends = listSentMyRequestFriends || [];
|
||||
recUser.profile.asked_groups = listSentMyRequestGroups || [];
|
||||
recUser.profile.refused_groups = listRefusedGroups || [];
|
||||
recUser.profile.reaction = reactions;
|
||||
recUser.profile.userstoverify = userstoverify;
|
||||
recUser.profile.manage_mygroups = manageGroupsWithAccounts;
|
||||
recUser.profile = { ...recUser.profile, ...circuitobj, useraccounts };
|
||||
|
||||
recUser.calcstat = await User.calculateStat(idapp, recUser.username);
|
||||
|
||||
recUser.profile.calc = await User.calcOtherByUser(idapp, recUser._id);
|
||||
|
||||
// tools.endTimeLog('addExtraInfo')
|
||||
recUser.calcstat = calcstat;
|
||||
recUser.profile.calc = calcOther;
|
||||
|
||||
return recUser;
|
||||
|
||||
} catch (e) {
|
||||
console.error('Err addExtraInfo', e);
|
||||
}
|
||||
|
||||
return recUser;
|
||||
};
|
||||
|
||||
@@ -6180,6 +6344,17 @@ UserSchema.statics.setReceiveRis = async function (idapp, username) {
|
||||
return !!record;
|
||||
});
|
||||
|
||||
};
|
||||
UserSchema.statics.setLinkReg = async function (idapp, username) {
|
||||
const User = this;
|
||||
|
||||
return await User.findOneAndUpdate({
|
||||
idapp, username,
|
||||
},
|
||||
{ $set: { 'profile.lastdate_LinkReg': new Date() } }, { new: false }).lean().then((record) => {
|
||||
return !!record;
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
UserSchema.statics.addNewSite = async function (idappPass, body) {
|
||||
@@ -6281,6 +6456,37 @@ UserSchema.statics.getnumAnnunci = async function (idapp) {
|
||||
|
||||
};
|
||||
|
||||
// crea una funzione per aggiornare il lasttimeonline e useragent
|
||||
UserSchema.statics.updateLastTimeAndUserAgent = async function (id, useragent) {
|
||||
const User = this;
|
||||
|
||||
// cerca lo user by id e aggiorna i campi
|
||||
// e ritorna il nuovo record
|
||||
const ris = await User.findOneAndUpdate(
|
||||
{ _id: id },
|
||||
{
|
||||
$set: {
|
||||
lasttimeonline: new Date(),
|
||||
useragent,
|
||||
retry_pwd: 0
|
||||
},
|
||||
},
|
||||
{ returnDocument: "after" }
|
||||
).lean();
|
||||
|
||||
return ris;
|
||||
}
|
||||
UserSchema.statics.getMyGroupsById = async function (id) {
|
||||
const User = this;
|
||||
|
||||
// cerca lo user by id e ritorna "profile.mygroups"
|
||||
const ris = await User.findOne({ _id: id }, { 'profile.mygroups': 1 }).lean();
|
||||
if (ris && ris.profile) {
|
||||
return ris.profile.mygroups;
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
UserSchema.statics.createNewSubRecord = async function (idapp, req) {
|
||||
const User = this;
|
||||
|
||||
@@ -6358,6 +6564,7 @@ const FuncUsers = {
|
||||
}
|
||||
};
|
||||
|
||||
UserSchema.index({ 'tokens.token': 1, 'tokens.access': 1 });
|
||||
|
||||
module.exports = {
|
||||
User, Hero, FuncUsers
|
||||
|
||||
481
src/server/modules/CronMod.js
Normal file
481
src/server/modules/CronMod.js
Normal file
@@ -0,0 +1,481 @@
|
||||
const { User } = require('../models/user');
|
||||
|
||||
const Hours = require('../models/hours');
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const tools = require('../tools/general');
|
||||
const shared_consts = require('../tools/shared_nodejs');
|
||||
|
||||
const server_constants = require('../tools/server_constants');
|
||||
|
||||
const { Settings } = require('../models/settings');
|
||||
const { MyBot } = require('../models/bot');
|
||||
const { MyElem } = require('../models/myelem');
|
||||
|
||||
const telegrambot = require('../telegram/telegrambot');
|
||||
|
||||
const Cart = require('../models/cart');
|
||||
const CartClass = require('../modules/Cart');
|
||||
const Product = require('../models/product');
|
||||
const ProductInfo = require('../models/productInfo');
|
||||
const CatProd = require('../models/catprod');
|
||||
const SubCatProd = require('../models/subcatprod');
|
||||
const Order = require('../models/order');
|
||||
const OrdersCart = require('../models/orderscart');
|
||||
const Variant = require('../models/variant');
|
||||
const TypedError = require('../modules/ErrorHandler');
|
||||
|
||||
const { MyGroup } = require('../models/mygroup');
|
||||
const { Circuit } = require('../models/circuit');
|
||||
const { Province } = require('../models/province');
|
||||
const { City } = require('../models/city');
|
||||
const { Account } = require('../models/account');
|
||||
|
||||
const Macro = require('../modules/Macro');
|
||||
|
||||
class CronMod {
|
||||
constructor() {}
|
||||
|
||||
async eseguiDbOp(idapp, mydata, req, res) {
|
||||
|
||||
let ris = await User.DbOp(idapp, mydata);
|
||||
|
||||
mydata.idapp = idapp;
|
||||
|
||||
const populate = require("../populate/populate");
|
||||
|
||||
const globalTables = require("../tools/globalTables");
|
||||
const { Reaction } = require("../models/reaction");
|
||||
|
||||
let mystr = "";
|
||||
|
||||
try {
|
||||
if (mydata.dbop === "") {
|
||||
// } else if (mydata.dbop === 'rigeneraTutto') {
|
||||
// await ListaIngresso.Esegui_CronTab(idapp, mydata);
|
||||
} else if (mydata.dbop === "ReplaceAllCircuits") {
|
||||
// ++ Replace All Circuitname with 'Circuito RIS %s'
|
||||
await Circuit.replaceAllCircuitNames(idapp);
|
||||
} else if (mydata.dbop === "eliminaCatProds") {
|
||||
await CatProd.deleteMany({ idapp });
|
||||
await SubCatProd.deleteMany({ idapp });
|
||||
} else if (mydata.dbop === "removeProductInfoWithoutDateUpdatedFromGM") {
|
||||
mystr = await ProductInfo.removeProductInfoWithoutDateUpdatedFromGM(idapp);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "StatMacro") {
|
||||
const macro = new Macro(idapp, {});
|
||||
mystr = await macro.getStat();
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "updateAllBook") {
|
||||
// chiama updateAllBook
|
||||
const { updateAllBook } = require("../controllers/articleController");
|
||||
|
||||
mystr = await updateAllBook(idapp, mydata.options);
|
||||
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "updateAllBooksAndRemoveCanc") {
|
||||
// chiama updateAllBooksAndRemoveCanc
|
||||
|
||||
const { updateAllBook } = require("../controllers/articleController");
|
||||
|
||||
console.log('updateAllBooksAndRemoveCanc...');
|
||||
|
||||
|
||||
mystr = await updateAllBook(idapp, {usaDBGMLocale: false, caricatutti: true, rimuovieventualiCancellati: true});
|
||||
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "creaUtentiTest") {
|
||||
let num = 0;
|
||||
lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1);
|
||||
let last = 1;
|
||||
if (lastrec) {
|
||||
last = lastrec[0].index;
|
||||
}
|
||||
if (!last) {
|
||||
last = 1;
|
||||
}
|
||||
|
||||
for (let ind = 0; ind < 100; ind++) {
|
||||
let myuser = new User();
|
||||
myuser._id = new ObjectId();
|
||||
myuser.index = last + ind + 1;
|
||||
myuser.idapp = idapp;
|
||||
myuser.password = "$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG";
|
||||
myuser.lang = "it";
|
||||
myuser.email = "miaemail@email.it";
|
||||
myuser.name = "U" + myuser.index;
|
||||
myuser.surname = "Ar" + myuser.index;
|
||||
myuser.verified_email = true;
|
||||
myuser.verified_by_aportador = true;
|
||||
if (myuser.index < 2) myuser.perm = "3";
|
||||
myuser.username = "Userna_" + myuser.name;
|
||||
myuser.profile.special_req = true;
|
||||
myuser.profile.nationality = "IT";
|
||||
await myuser.save();
|
||||
num++;
|
||||
}
|
||||
|
||||
ris = { num };
|
||||
/*} else if (mydata.dbop === 'visuPlacca') {
|
||||
|
||||
mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' +
|
||||
'NAVI CHE SALPANO DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) + '\n' +
|
||||
'AUGURI ALLA NUOVA SOGNATRICE !!!\n' +
|
||||
'✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨';
|
||||
|
||||
const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT');
|
||||
|
||||
for (let ind = 0; ind < 8; ind++) {
|
||||
mystr += await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col) + ind, false);
|
||||
mystr += tools.ACAPO;
|
||||
if (visu_nave_Bot && ind === 3) {
|
||||
await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true);
|
||||
mystr = '';
|
||||
}
|
||||
}
|
||||
|
||||
if (visu_nave_Bot)
|
||||
await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true);
|
||||
|
||||
ris = { mystr };
|
||||
*/
|
||||
} else if (mydata.dbop === "CorreggiTabHours") {
|
||||
ris = await Hours.correggiHours(idapp);
|
||||
} else if (mydata.dbop === "setVerifiedByAportadorToALL") {
|
||||
ris = await User.setVerifiedByAportadorToALL();
|
||||
} else if (mydata.dbop === "RewriteContribType") {
|
||||
ris = populate.rewriteTable("contribtypes");
|
||||
} else if (mydata.dbop === "ReplaceUsername") {
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
ris = globalTables.replaceUsername(req.body.idapp, mydata.search_username, mydata.replace_username);
|
||||
}
|
||||
} else if (mydata.dbop === "ExitFromAllCircuitWithZero") {
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
ris = globalTables.ExitFromAllCircuitWithZero(req.body.idapp, mydata.search_username);
|
||||
}
|
||||
} else if (mydata.dbop === "replaceAportadorSolidario") {
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
ris = globalTables.replaceAportadorSolidario(req.body.idapp, mydata.search_username, mydata.replace_username);
|
||||
}
|
||||
} else if (mydata.dbop === "SearchString") {
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
mystr = await globalTables.SearchString(req.body.idapp, mydata.search);
|
||||
}
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "UpdateCatDeleteEmpty") {
|
||||
mystr = await CatProd.updateCatDeleteEmpty(req.body.idapp);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "UpdateStatFatturato") {
|
||||
mystr = await ProductInfo.updateProductInfoByStats(req.body.idapp);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "MigrateMSSQLToMongoDb") {
|
||||
const { mssqlmigrateTables } = require("../controllers/articleController");
|
||||
|
||||
mystr = await mssqlmigrateTables(req);
|
||||
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "copyFrom1To14") {
|
||||
const idapporig = 1;
|
||||
const idappdest = 14;
|
||||
if (!idapporig || !idappdest) return;
|
||||
|
||||
const globalTables = require("../tools/globalTables");
|
||||
|
||||
//++ Todo: TO FIXIT !
|
||||
const mytablesstr = ["settings", "users", "templemail", "destnewsletter", "contribtypes", "bots", "cfgservers"];
|
||||
|
||||
try {
|
||||
let numrectot = 0;
|
||||
for (const table of mytablesstr) {
|
||||
const mytable = globalTables.getTableByTableName(table);
|
||||
|
||||
tools.mylogshow("copyfromapptoapp: ", table, mytable);
|
||||
|
||||
await mytable.DuplicateAllRecords(idapporig, idappdest).then((numrec) => {
|
||||
// tools.mylogshow(' REC TO MODIFY: ', rec);
|
||||
if (numrec) numrectot += numrec;
|
||||
});
|
||||
}
|
||||
|
||||
ris = true;
|
||||
} catch (e) {
|
||||
console.log("e", e);
|
||||
}
|
||||
} else if (mydata.dbop === "removeRecordsFav") {
|
||||
// Passa le tabelle da users sulle nuove tabelle:
|
||||
await User.removerecordsFavorite();
|
||||
} else if (mydata.dbop === "updateReactionsCounts") {
|
||||
await Reaction.updateReactionsCounts();
|
||||
} else if (mydata.dbop === "GeneraCSVOrdineProdotti") {
|
||||
await Order.GeneraCSVOrdineProdotti();
|
||||
} else if (mydata.dbop === "RemoveDeletedOrdersInOrderscart") {
|
||||
await Order.RemoveDeletedOrdersInOrderscart();
|
||||
} else if (mydata.dbop === "CheckTransazioniCircuiti") {
|
||||
await Circuit.CheckTransazioniCircuiti(false);
|
||||
} else if (mydata.dbop === "CorreggiTransazioniCircuiti") {
|
||||
await Circuit.CheckTransazioniCircuiti(true);
|
||||
} else if (mydata.dbop === "RemovePendentTransactions") {
|
||||
ris = await SendNotif.RemovePendentTransactions(idapp);
|
||||
} else if (mydata.dbop === "RemoveOldNotif90") {
|
||||
await SendNotif.RemoveOldNotif90(idapp);
|
||||
} else if (mydata.dbop === "RemoveOldNotif30") {
|
||||
await SendNotif.RemoveOldNotif30(idapp);
|
||||
} else if (mydata.dbop === "UpdateCoordProv") {
|
||||
await Province.setCoordinatesOnDB();
|
||||
} else if (mydata.dbop === "insertGeojsonToMongoDB") {
|
||||
await City.insertGeojsonToMongoDB("comuni_italia.geojson");
|
||||
} else if (mydata.dbop === "listCollectionsBySize") {
|
||||
mystr = await tools.listCollectionsBySize();
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "EnableNewsOn_ToAll") {
|
||||
mystr = await User.setNewsletterToAll(idapp);
|
||||
} else if (mydata.dbop === "MyElemSetIdPageInsteadThePah") {
|
||||
mystr = await MyElem.SetIdPageInsteadThePah(idapp);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === "AbilitaNewsletterALL") {
|
||||
await User.updateMany(
|
||||
{
|
||||
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
|
||||
},
|
||||
{ $set: { news_on: true } },
|
||||
{ new: false }
|
||||
);
|
||||
} else if (mydata.dbop === "SvuotaTuttiGliAccessiOnlineConToken") {
|
||||
await User.SvuotaTuttiGliAccessiOnlineConToken(idapp);
|
||||
} else if (mydata.dbop === "SettaAdTypeOffro_In_Hosps") {
|
||||
const { MyHosp } = require("../models/myhosp");
|
||||
|
||||
await MyHosp.SettaAdTypeOffro_In_Hosps(idapp);
|
||||
} else if (mydata.dbop === "removeRegulations") {
|
||||
await Circuit.updateMany({}, { $set: { regulation: "" } });
|
||||
} else if (mydata.dbop === "newRecordsFav") {
|
||||
// Passa le tabelle da users sulle nuove tabelle:
|
||||
await User.moverecordsFavorite(1);
|
||||
await User.moverecordsFavorite(2);
|
||||
await User.moverecordsFavorite(3);
|
||||
await User.moverecordsFavorite(4);
|
||||
await User.moverecordsFavorite(5);
|
||||
} else if (mydata.dbop === "emptyTabCatServiziBeni") {
|
||||
const { Sector } = require("../models/sector");
|
||||
const { SectorGood } = require("../models/sectorgood");
|
||||
const { Skill } = require("../models/skill");
|
||||
const { Good } = require("../models/good");
|
||||
|
||||
await Sector.deleteMany({});
|
||||
await SectorGood.deleteMany({});
|
||||
await Skill.deleteMany({});
|
||||
ris = await Good.deleteMany({});
|
||||
} else if (mydata.dbop === "emptyDbSkill") {
|
||||
// Svuota e Ricrea
|
||||
|
||||
const { Sector } = require("../models/sector");
|
||||
const { SectorGood } = require("../models/sectorgood");
|
||||
const { Skill } = require("../models/skill");
|
||||
const { Good } = require("../models/good");
|
||||
const { SubSkill } = require("../models/subskill");
|
||||
const { Contribtype } = require("../models/contribtype");
|
||||
const { AdType } = require("../models/adtype");
|
||||
const { AdTypeGood } = require("../models/adtypegood");
|
||||
const { StatusSkill } = require("../models/statusSkill");
|
||||
const { CatGrp } = require("../models/catgrp");
|
||||
|
||||
await Sector.deleteMany({});
|
||||
await SectorGood.deleteMany({});
|
||||
await Skill.deleteMany({});
|
||||
await Good.deleteMany({});
|
||||
await SubSkill.deleteMany({});
|
||||
await Contribtype.deleteMany({});
|
||||
await AdType.deleteMany({});
|
||||
await AdTypeGood.deleteMany({});
|
||||
await StatusSkill.deleteMany({});
|
||||
await CatGrp.deleteMany({});
|
||||
|
||||
ris = await populate.popolaTabelleNuove();
|
||||
} else if (mydata.dbop === "ricreaTabCitiesProvinces") {
|
||||
// Svuota e Ricrea
|
||||
|
||||
const { City } = require("../models/city");
|
||||
const { Province } = require("../models/province");
|
||||
|
||||
await City.deleteMany({});
|
||||
await Province.deleteMany({});
|
||||
|
||||
ris = await populate.popolaTabelleNuove();
|
||||
} else if (mydata.dbop === "PopulateTables") {
|
||||
ris = populate.popolaTabelleNuove();
|
||||
} else if (mydata.dbop === "dropProducts") {
|
||||
if (idapp) {
|
||||
const deleteProducts = await Product.deleteMany({ idapp });
|
||||
console.log(`Cancellati ${deleteProducts.deletedCount} record dalla collezione Product.`);
|
||||
|
||||
// Cancellazione dei record nella collezione ProductInfo
|
||||
const deleteProductInfo = await ProductInfo.deleteMany({ idapp });
|
||||
console.log(`Cancellati ${deleteProductInfo.deletedCount} record dalla collezione ProductInfo.`);
|
||||
}
|
||||
|
||||
ris = deleteProductInfo ? true : false;
|
||||
} else if (mydata.dbop === "dropCatProd") {
|
||||
const deleteCatProd = await CatProd.deleteMany({ idapp });
|
||||
} else if (mydata.dbop === "dropSubCatProd") {
|
||||
const deleteSubCatProd = await SubCatProd.deleteMany({ idapp });
|
||||
} else if (mydata.dbop === "dropAllOrders") {
|
||||
try {
|
||||
const deleteOrder = await Order.deleteMany({ idapp });
|
||||
const deleteOrdersCart = await OrdersCart.deleteMany({ idapp });
|
||||
const deleteCart = await Cart.deleteMany({ idapp });
|
||||
|
||||
ris = deleteCart;
|
||||
} catch (e) {
|
||||
console.error("Err:", e);
|
||||
}
|
||||
} else if (mydata.dbop === "SistemaGasOrdine") {
|
||||
const arrrec = await Product.find({}).lean();
|
||||
for (const rec of arrrec) {
|
||||
if (tools.isArray(rec.idGasordines) && rec.idGasordines.length > 0) {
|
||||
await Product.findByIdAndUpdate(rec._id, { $set: { idGasordine: rec.idGasordines[0] } });
|
||||
} else {
|
||||
await Product.findByIdAndUpdate(rec._id, { $set: { idGasordine: null } });
|
||||
}
|
||||
}
|
||||
} else if (mydata.dbop === "CopyPriceToCalc") {
|
||||
try {
|
||||
const arrrec = await OrdersCart.find({}).lean();
|
||||
for (const rec of arrrec) {
|
||||
await OrdersCart.findByIdAndUpdate(rec._id, { $set: { totalPriceCalc: rec.totalPrice } });
|
||||
}
|
||||
|
||||
const arrrec2 = await Order.find({}).lean();
|
||||
for (const rec of arrrec2) {
|
||||
await Order.findByIdAndUpdate(rec._id, { $set: { TotalPriceProductCalc: rec.TotalPriceProduct } });
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Err:", e);
|
||||
}
|
||||
} else if (mydata.dbop === "dropAllCarts") {
|
||||
ris = await Cart.deleteMany({ idapp });
|
||||
} else if (mydata.dbop === "RewriteCitiesTable") {
|
||||
ris = populate.rewriteTable("cities");
|
||||
} else if (mydata.dbop === "RewriteLevelsTable") {
|
||||
ris = populate.rewriteTable("levels");
|
||||
} else if (mydata.dbop === "RewriteProvincesTable") {
|
||||
ris = populate.rewriteTable("provinces");
|
||||
} else if (mydata.dbop === "emptyCityProvinces") {
|
||||
const { City } = require("../models/city");
|
||||
const { Province } = require("../models/province");
|
||||
|
||||
await City.deleteMany({});
|
||||
await Province.deleteMany({});
|
||||
} else if (mydata.dbop === "ConvTablesFromIntToString") {
|
||||
const { MySkill } = require("../models/myskill");
|
||||
const { MyBacheca } = require("../models/mybacheca");
|
||||
const { MyHosp } = require("../models/myhosp");
|
||||
const { MyGood } = require("../models/mygood");
|
||||
// const { MyGroup } = require('../models/mygroup');
|
||||
|
||||
console.log("INIZIO - Conversioni");
|
||||
// 'myskills',
|
||||
// 'mybachecas',
|
||||
// 'myhosps',
|
||||
// 'mygoods',
|
||||
// 'mygroups'
|
||||
|
||||
await ConvertiDaIntAStr(MySkill);
|
||||
await ConvertiDaIntAStr(MyBacheca);
|
||||
await ConvertiDaIntAStr(MyHosp);
|
||||
await ConvertiDaIntAStr(MyGood);
|
||||
await ConvertiDaIntAStr(MyGroup);
|
||||
|
||||
console.log("FINE - Conversioni");
|
||||
} else if (mydata.dbop === "Removeinteger") {
|
||||
const { MySkill } = require("../models/myskill");
|
||||
const { MyBacheca } = require("../models/mybacheca");
|
||||
const { MyHosp } = require("../models/myhosp");
|
||||
const { MyGood } = require("../models/mygood");
|
||||
// const { MyGroup } = require('../models/mygroup');
|
||||
|
||||
console.log("INIZIO - Rimozione");
|
||||
|
||||
await RimuoviInteri(MySkill);
|
||||
await RimuoviInteri(MyBacheca);
|
||||
await RimuoviInteri(MyHosp);
|
||||
await RimuoviInteri(MyGood);
|
||||
await RimuoviInteri(MyGroup);
|
||||
|
||||
console.log("FINE - Rimozione");
|
||||
} else if (mydata.dbop === "createAllCircuits") {
|
||||
const { Province } = require("../models/province");
|
||||
|
||||
const arrProv = await Province.find({});
|
||||
for (const recprov of arrProv) {
|
||||
await Circuit.createCircuitIfNotExist(req, idapp, recprov.prov);
|
||||
}
|
||||
} else if (mydata.dbop === "correggiProductTypes") {
|
||||
await ProductInfo.correggiProductTypes();
|
||||
} else if (mydata.dbop === "replaceProductImgToImageFile") {
|
||||
await ProductInfo.replaceProductImgToImageFile(true);
|
||||
} else if (mydata.dbop === "removeUploadProducts_Path") {
|
||||
await ProductInfo.replaceProductImgToImageFile(false);
|
||||
} else if (mydata.dbop === "correggiCircuitiANull") {
|
||||
await User.updateMany({}, { $pull: { "profile.mycircuits": { circuitname: null } } });
|
||||
} else if (mydata.dbop === "ImpostaMinMaxPersonali") {
|
||||
await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, "");
|
||||
} else if (mydata.dbop === "ImpostaMinMaxPersonaliCircuito") {
|
||||
await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
|
||||
} else if (mydata.dbop === "ImpostaMinMaxComunitari") {
|
||||
await Account.SetMinMaxComunitari(idapp, mydata.valmin, mydata.valmax);
|
||||
} else if (mydata.dbop === "ImpostaMinMaxCollettivi") {
|
||||
await Account.SetMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax);
|
||||
} else if (mydata.dbop === "ImpostaDefMinMaxPersonali") {
|
||||
await Circuit.SetDefMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
|
||||
} else if (mydata.dbop === "ImpostaDefMinMaxCollettivi") {
|
||||
await Circuit.SetDefMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
|
||||
} else if (mydata.dbop === "AbilitaTuttiCircuiti") {
|
||||
await Circuit.AbilitaTuttiCircuiti(idapp);
|
||||
} else if (mydata.dbop === "AzzeraRegolamentiTuttiCircuiti") {
|
||||
await Circuit.AzzeraRegolamentiTuttiCircuiti(idapp);
|
||||
} else if (mydata.dbop === "setstrProvByIdCityCircuits") {
|
||||
await Circuit.setstrProvByIdCityCircuits(idapp);
|
||||
} else if (mydata.dbop === "updateSaldoAndTransato_AllAccounts") {
|
||||
await Account.updateSaldoAndTransato_AllAccounts(idapp);
|
||||
} else if (mydata.dbop === "generateBotMenuRecords") {
|
||||
await MyBot.generateBotMenuRecords(idapp);
|
||||
} else if (mydata.dbop === "GenerateVapiKey") {
|
||||
await tools.generateVapiKey();
|
||||
|
||||
/*} else if (mydata.dbop === 'visuNave') {
|
||||
mystr = await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col));
|
||||
|
||||
const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT');
|
||||
if (visu_nave_Bot)
|
||||
telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true);
|
||||
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === 'getnavibyuser') {
|
||||
|
||||
let arrnavi = null;
|
||||
|
||||
const user = await User.getUserShortDataByUsername(idapp, mydata.username);
|
||||
if (user) {
|
||||
arrnavi = await Nave.getArrPosizioniByUsername(idapp, user.username);
|
||||
|
||||
for (let mynave of arrnavi) {
|
||||
mynave._doc.rec = await Nave.getNaveByRigaCol(idapp, mynave.riga, mynave.col);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ris = { data: arrnavi };
|
||||
|
||||
*/
|
||||
}
|
||||
|
||||
// console.log('ris', ris);
|
||||
|
||||
return ris;
|
||||
} catch (e) {
|
||||
console.log(e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CronMod;
|
||||
1118
src/server/modules/Macro.js
Normal file
1118
src/server/modules/Macro.js
Normal file
File diff suppressed because it is too large
Load Diff
149
src/server/modules/MssqlMigrator.js
Normal file
149
src/server/modules/MssqlMigrator.js
Normal file
@@ -0,0 +1,149 @@
|
||||
const axios = require('axios');
|
||||
|
||||
const mongoose = require('mongoose').set('debug', false)
|
||||
const Schema = mongoose.Schema;
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
mongoose.Promise = global.Promise;
|
||||
mongoose.level = "F";
|
||||
|
||||
|
||||
class MssqlMigrator {
|
||||
/**
|
||||
* Costruttore della classe MssqlMigrator
|
||||
* @param {string} serverUrl - URL del server che esegue le query MSSQL
|
||||
* @param {string} apiKey - API Key per l'autenticazione
|
||||
*/
|
||||
constructor() {
|
||||
this.serverUrl = process.env.SERVER_A_URL;
|
||||
this.apiKey = process.env.API_KEY_MSSQL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Migra una lista di tabelle MSSQL in MongoDB usando Mongoose
|
||||
* @param {string[]} tableNames - Lista dei nomi delle tabelle MSSQL
|
||||
* @returns {string} logs - Lista dei log di esecuzione
|
||||
*/
|
||||
async migrateTables(tableNames) {
|
||||
|
||||
try {
|
||||
|
||||
const numtables = tableNames.length;
|
||||
let indtab = 0;
|
||||
let indtabok = 0;
|
||||
const logs = [];
|
||||
for (const rectable of tableNames) {
|
||||
try {
|
||||
const tableName = rectable.table;
|
||||
const usaDataOra = rectable.usaDataOra;
|
||||
const fieldId = rectable.fieldId;
|
||||
|
||||
const percentuale = ((indtab / numtables) * 100).toFixed(2);
|
||||
logs.push(`\n>> Recupero dati da MSSQL per la tabella: ${tableName} - (Completamento: ${percentuale}%)`);
|
||||
console.log(logs[logs.length - 1]);
|
||||
let dataQuery = `SELECT * FROM ${tableName}`;
|
||||
|
||||
if (usaDataOra) {
|
||||
dataQuery = `SELECT T.* FROM ${tableName} T`;
|
||||
dataQuery += ` JOIN (
|
||||
SELECT ${fieldId}, MAX(DataOra) AS data
|
||||
FROM ${tableName}
|
||||
GROUP BY ${fieldId}
|
||||
) b ON T.${fieldId} = b.${fieldId} AND T.DataOra = b.data; `;
|
||||
}
|
||||
|
||||
console.log('query', dataQuery);
|
||||
|
||||
let dataResponse = null;
|
||||
|
||||
try {
|
||||
dataResponse = await axios.post(
|
||||
`${this.serverUrl}/query`,
|
||||
{ query: dataQuery },
|
||||
{ headers: { 'x-api-key': this.apiKey } },
|
||||
null,
|
||||
{ timeout: 900000 });
|
||||
} catch (error) {
|
||||
console.error('Error: ', error.response?.data?.error || error.message || error);
|
||||
if (error.message === 'socket hang up') {
|
||||
console.log('Error: hangup, waiting 5 seconds and retrying...');
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
|
||||
|
||||
dataResponse = await axios.post(
|
||||
`${this.serverUrl}/query`,
|
||||
{ query: dataQuery },
|
||||
{ headers: { 'x-api-key': this.apiKey } },
|
||||
null,
|
||||
{ timeout: 900000 });
|
||||
|
||||
} else {
|
||||
console.error('Unexpected error while fetching data from MSSQL:', error.message);
|
||||
// throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const records = dataResponse?.data;
|
||||
|
||||
if (!records || records.length === 0) {
|
||||
logs.push(`⚠️ Nessun record trovato per la tabella: ${tableName}`);
|
||||
console.log(logs[logs.length - 1]);
|
||||
continue;
|
||||
}
|
||||
|
||||
const sample = records[0];
|
||||
const schemaDef = {};
|
||||
|
||||
for (const key of Object.keys(sample)) {
|
||||
const value = sample[key];
|
||||
if (typeof value === 'string' && key.startsWith('Data') && !isNaN(Date.parse(value))) {
|
||||
schemaDef[key] = Date;
|
||||
} else if (typeof value === 'number') {
|
||||
schemaDef[key] = Number;
|
||||
} else if (typeof value === 'boolean') {
|
||||
schemaDef[key] = Boolean;
|
||||
} else if (value instanceof Date) {
|
||||
schemaDef[key] = Date;
|
||||
} else {
|
||||
schemaDef[key] = mongoose.Schema.Types.Mixed;
|
||||
}
|
||||
}
|
||||
|
||||
const dynamicSchema = new mongoose.Schema(schemaDef, { strict: false });
|
||||
const modelName = tableName.charAt(0).toUpperCase() + tableName.slice(1);
|
||||
|
||||
// Se il modello esiste già, lo riutilizziamo
|
||||
const DynamicModel = mongoose.models[modelName] || mongoose.model(modelName, dynamicSchema);
|
||||
|
||||
// ❗ Elimina tutti i documenti esistenti prima dell'inserimento
|
||||
await DynamicModel.deleteMany({});
|
||||
|
||||
logs.push(`✅ Inserimento di ${records.length} record nella collezione MongoDB: ${modelName}`);
|
||||
console.log(logs[logs.length - 1]);
|
||||
await DynamicModel.insertMany(records);
|
||||
|
||||
indtabok++;
|
||||
} catch (error) {
|
||||
logs.push(`❌ Errore con la tabella ${tableName}:`, error.message);
|
||||
console.log(logs[logs.length - 1]);
|
||||
}
|
||||
|
||||
indtab++;
|
||||
|
||||
|
||||
}
|
||||
|
||||
logs.push(`\n🎉 ${indtabok} tabelle su ${numtables} sono state migrate.`);
|
||||
console.log(logs[logs.length - 1]);
|
||||
return logs.join('\n');
|
||||
} catch (error) {
|
||||
logs.push(`❌ Errore migrateTables:`, error.message);
|
||||
console.log(logs[logs.length - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
module.exports = MssqlMigrator;
|
||||
3381
src/server/populate/cities_sardegna.js
Normal file
3381
src/server/populate/cities_sardegna.js
Normal file
File diff suppressed because it is too large
Load Diff
@@ -78,10 +78,11 @@ module.exports = {
|
||||
console.log(' ... Non inserito !');
|
||||
}
|
||||
|
||||
|
||||
} else {
|
||||
// Il documento esiste, lo aggiorniamo
|
||||
const ris = await table.updateOne({ _id: existingDoc._id }, { $set: rec });
|
||||
if (ris && ris.nModified > 0)
|
||||
if (ris && ris.modifiedCount > 0)
|
||||
numupdated++;
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@@ -18,10 +18,9 @@ module.exports = {
|
||||
{ _id: 16, reg: 'TAA', prov: 'BZ', descr: 'Bolzano', link_grp: 'https://t.me/c/1614195634/596?thread=594', link_telegram: '' },
|
||||
{ _id: 17, reg: 'LOM', prov: 'BS', descr: 'Brescia', link_grp: 'https://t.me/c/1614195634/490?thread=478', link_telegram: '' },
|
||||
{ _id: 18, reg: 'PUG', prov: 'BR', descr: 'Brindisi', link_grp: 'https://t.me/c/1614195634/536?thread=530', link_telegram: '' },
|
||||
{ _id: 19, reg: 'SAR', prov: 'CA', descr: 'Cagliari', link_grp: 'https://t.me/c/1614195634/546?thread=541', link_telegram: '' },
|
||||
{ _id: 19, reg: 'SAR', prov: 'CA', descr: 'Cagliari', link_grp: 'https://t.me/+9A0xl58CEI8zMWE0', link_telegram: '' },
|
||||
{ _id: 20, reg: 'SIC', prov: 'CL', descr: 'Caltanissetta', link_grp: 'https://t.me/c/1614195634/563?thread=554', link_telegram: '' },
|
||||
{ _id: 21, reg: 'MOL', prov: 'CB', descr: 'Campobasso', link_grp: 'https://t.me/c/1614195634/398?thread=396', link_telegram: '' },
|
||||
{ _id: 22, reg: 'SAR', prov: 'CI', descr: 'Carbonia-Iglesias', link_grp: '', link_telegram: '' },
|
||||
{ _id: 23, reg: 'CAM', prov: 'CE', descr: 'Caserta', link_grp: 'https://t.me/c/1614195634/414?thread=410', link_telegram: '' },
|
||||
{ _id: 24, reg: 'SIC', prov: 'CT', descr: 'Catania', link_grp: 'https://t.me/c/1614195634/564?thread=555', link_telegram: '' },
|
||||
{ _id: 25, reg: 'CAL', prov: 'CZ', descr: 'Catanzaro', link_grp: 'https://t.me/c/1614195634/378?thread=377', link_telegram: '' },
|
||||
@@ -62,7 +61,6 @@ module.exports = {
|
||||
{ _id: 60, reg: 'CAM', prov: 'NA', descr: 'Napoli', link_grp: 'https://t.me/c/1614195634/407?thread=406', link_telegram: '' },
|
||||
{ _id: 61, reg: 'PIE', prov: 'NO', descr: 'Novara', link_grp: 'https://t.me/c/1614195634/517?thread=508', link_telegram: '' },
|
||||
{ _id: 62, reg: 'SAR', prov: 'NU', descr: 'Nuoro', link_grp: 'https://t.me/c/1614195634/548?thread=542', link_telegram: '' },
|
||||
{ _id: 63, reg: 'SAR', prov: 'OT', descr: 'Olbia-Tempio', link_grp: '', link_telegram: '' },
|
||||
{ _id: 64, reg: 'SAR', prov: 'OR', descr: 'Oristano', link_grp: 'https://t.me/c/1614195634/550?thread=543', link_telegram: '' },
|
||||
{ _id: 65, reg: 'VEN', prov: 'PD', descr: 'Padova', link_grp: 'https://t.me/c/1614195634/610?thread=600', link_telegram: '' },
|
||||
{ _id: 66, reg: 'SIC', prov: 'PA', descr: 'Palermo', link_grp: 'https://t.me/c/1614195634/568?thread=558', link_telegram: '' },
|
||||
@@ -86,7 +84,6 @@ module.exports = {
|
||||
{ _id: 84, reg: 'LAZ', prov: 'RM', descr: 'Roma', link_grp: '', link_telegram: '' },
|
||||
{ _id: 85, reg: 'VEN', prov: 'RO', descr: 'Rovigo', link_grp: 'https://t.me/c/1614195634/611?thread=601', link_telegram: '' },
|
||||
{ _id: 86, reg: 'CAM', prov: 'SA', descr: 'Salerno', link_grp: 'https://t.me/c/1614195634/416?thread=412', link_telegram: '' },
|
||||
{ _id: 87, reg: 'SAR', prov: 'VS', descr: 'Medio Campidano', link_grp: '', link_telegram: '' },
|
||||
{ _id: 88, reg: 'SAR', prov: 'SS', descr: 'Sassari', link_grp: 'https://t.me/c/1614195634/551?thread=544', link_telegram: '' },
|
||||
{ _id: 89, reg: 'LIG', prov: 'SV', descr: 'Savona', link_grp: 'https://t.me/c/1614195634/395?thread=391', link_telegram: '' },
|
||||
{ _id: 90, reg: 'TOS', prov: 'SI', descr: 'Siena', link_grp: 'https://t.me/c/1614195634/592?thread=581', link_telegram: '' },
|
||||
@@ -96,7 +93,6 @@ module.exports = {
|
||||
{ _id: 94, reg: 'ABR', prov: 'TE', descr: 'Teramo', link_grp: 'https://t.me/c/1614195634/370?thread=369', link_telegram: '' },
|
||||
{ _id: 95, reg: 'UMB', prov: 'TR', descr: 'Terni', link_grp: 'https://t.me/c/1614195634/404?thread=402', link_telegram: '' },
|
||||
{ _id: 96, reg: 'PIE', prov: 'TO', descr: 'Torino', link_grp: 'https://t.me/c/1614195634/518?thread=509', link_telegram: '' },
|
||||
{ _id: 97, reg: 'SAR', prov: 'OG', descr: 'Ogliastra', link_grp: '', link_telegram: '' },
|
||||
{ _id: 98, reg: 'SIC', prov: 'TP', descr: 'Trapani', link_grp: 'https://t.me/c/1614195634/571?thread=561', link_telegram: '' },
|
||||
{ _id: 99, reg: 'TAA', prov: 'TN', descr: 'Trento', link_grp: 'https://t.me/c/1614195634/597?thread=595', link_telegram: '' },
|
||||
{ _id: 100, reg: 'VEN', prov: 'TV', descr: 'Treviso', link_grp: 'https://t.me/c/1614195634/612?thread=602', link_telegram: '' },
|
||||
@@ -119,8 +115,8 @@ module.exports = {
|
||||
{ _id: 117, reg: 'LAZ', prov: 'RM', descr: 'Roma Nord-Ovest', card: 'NORD-OVEST', link_grp: 'https://t.me/c/1614195634/62?thread=47', link_telegram: '' },
|
||||
{ _id: 118, reg: 'LAZ', prov: 'RM', descr: 'Roma Sud e Litorale', card: 'SUD', link_grp: 'https://t.me/c/1614195634/67?thread=43', link_telegram: '' },
|
||||
{ _id: 119, reg: 'PUG', prov: 'VAL', descr: 'Valle D\'Itria', link_grp: 'https://t.me/progettoriso/7016?thread=7015', link_telegram: '' },
|
||||
{ _id: 120, reg: 'SAR', prov: 'SUS', descr: 'Sud Sardegna', link_grp: 'https://t.me/c/1614195634/552?thread=545', link_telegram: '' },
|
||||
{ _id: 121, reg: 'ITA', prov: 'ITA', descr: 'Italia', link_grp: '', link_telegram: '' },
|
||||
{ _id: 122, reg: 'LOM', prov: 'MI', descr: 'Milano Est', card: 'EST', link_grp: '', link_telegram: '' },
|
||||
{ _id: 123, reg: 'SAR', prov: 'SU', descr: 'Sud Sardegna', link_grp: '', link_telegram: '' },
|
||||
],
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
const express = require("express");
|
||||
const { getArticlesSalesHandler, exportArticlesSalesByJSON, viewTable, queryTable } = require("../controllers/articleController");
|
||||
const { getArticlesSalesHandler, exportArticlesSalesByJSON, viewTable, saveTable, queryTable, updateAllBookRoute, mssqlmigrateTables } = require("../controllers/articleController");
|
||||
const { authenticate } = require("../middleware/authenticate");
|
||||
|
||||
const router = express.Router();
|
||||
@@ -9,7 +9,11 @@ router.post("/articles-sales", authenticate, getArticlesSalesHandler);
|
||||
router.post("/export-articles-sales-json", authenticate, exportArticlesSalesByJSON);
|
||||
|
||||
router.post("/view-table", authenticate, viewTable);
|
||||
router.post("/save-table", authenticate, saveTable);
|
||||
router.post("/query", authenticate, queryTable);
|
||||
router.post("/updateAllBook", authenticate, updateAllBookRoute);
|
||||
|
||||
router.post("/mssqlmigrateTables", authenticate, mssqlmigrateTables);
|
||||
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -4,7 +4,7 @@ const router = express.Router();
|
||||
const tools = require('../tools/general');
|
||||
const server_constants = require('../tools/server_constants');
|
||||
|
||||
const { authenticate } = require('../middleware/authenticate');
|
||||
const { authenticate, authenticate_withUser } = require('../middleware/authenticate');
|
||||
|
||||
const { Booking } = require('../models/booking');
|
||||
|
||||
@@ -24,7 +24,7 @@ const sendNotifBooking = async (res, idapp, user, recbooking) => {
|
||||
return await sendemail.sendEmail_CancelBooking(res, user.lang, user.email, user, idapp, recbooking);
|
||||
};
|
||||
|
||||
router.post('/', authenticate, (req, res) => {
|
||||
router.post('/', authenticate_withUser, (req, res) => {
|
||||
// tools.mylog('INIZIO - booking');
|
||||
// tools.mylog('req.body', req.body);
|
||||
const myrec = _.pick(req.body, tools.allfieldBooking());
|
||||
|
||||
@@ -181,25 +181,24 @@ router.put('/:userId', authenticate, async function (req, res, next) {
|
||||
const cart = await Cart.getCartByUserId(userId);
|
||||
|
||||
try {
|
||||
const p = await Product.getProductByID(productId);
|
||||
const myprod = await Product.getProductByID(productId);
|
||||
|
||||
let newCart = oldCart.add(p, productId, { color, size })
|
||||
let newCart = oldCart.add(myprod, productId, { color, size })
|
||||
|
||||
//exist cart in databse
|
||||
if (cart.length > 0) {
|
||||
await Cart.updateCartByUserId(
|
||||
userId,
|
||||
{
|
||||
try {
|
||||
const result = await Cart.updateCartByUserId(userId, {
|
||||
items: newCart.items,
|
||||
totalQty: newCart.totalQty,
|
||||
totalPrice: newCart.totalPrice,
|
||||
totalPriceCalc: newCart.totalPriceCalc,
|
||||
userId: userId
|
||||
},
|
||||
function (err, result) {
|
||||
if (err) return next(err)
|
||||
res.json(result)
|
||||
})
|
||||
});
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
}
|
||||
} else {
|
||||
//no cart in database
|
||||
let newCartobj = {
|
||||
@@ -242,13 +241,13 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res,
|
||||
let idapp = req.body.idapp;
|
||||
let cart_id = req.body.cart_id;
|
||||
let userId = req.params.userId;
|
||||
const user = req.user;
|
||||
|
||||
let status = req.body.status;
|
||||
let note = req.body.note;
|
||||
let options = req.body.options;
|
||||
|
||||
try {
|
||||
let mycart = await Cart.findOne({ _id: cart_id });
|
||||
let mycart = await Cart.findOne({ _id: cart_id }).lean();
|
||||
|
||||
if (!mycart) {
|
||||
return res.send({
|
||||
@@ -309,19 +308,21 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res,
|
||||
.then(async (orders) => {
|
||||
if (!!orders) {
|
||||
|
||||
await OrdersCart.updateCmd(orders[0], status, true, req, options);
|
||||
if (orders[0]) {
|
||||
await OrdersCart.updateCmd(orders[0], status, true, req, options);
|
||||
|
||||
// Invia la email dell'Ordine
|
||||
sendemail.sendEmail_OrderProduct(userDest.lang, idapp, orders[0], userDest)
|
||||
.then(async (ris) => {
|
||||
myorderCart = await OrdersCart.findById(idordercart).lean();
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
status: myris.status,
|
||||
orders: orders,
|
||||
recOrderCart: myorderCart
|
||||
// Invia la email dell'Ordine
|
||||
sendemail.sendEmail_OrderProduct(userDest.lang, idapp, orders[0], userDest)
|
||||
.then(async (ris) => {
|
||||
myorderCart = await OrdersCart.findById(idordercart).lean();
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
status: myris.status,
|
||||
orders: orders,
|
||||
recOrderCart: myorderCart
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
@@ -350,7 +351,6 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
|
||||
let idapp = req.body.idapp;
|
||||
let userId = req.params.userId;
|
||||
let order_id = req.body.order_id;
|
||||
const user = req.user;
|
||||
let status = req.body.status;
|
||||
let options = req.body.options;
|
||||
|
||||
@@ -402,7 +402,7 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
|
||||
|
||||
let orderscart = null;
|
||||
|
||||
if (User.isManager(user.perm)) {
|
||||
if (User.isManager(req.user.perm)) {
|
||||
// Prende Tutti gli Ordini !
|
||||
orderscart = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false);
|
||||
} else {
|
||||
@@ -423,7 +423,6 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
|
||||
//POST cart
|
||||
router.post('/:userId/gestord', authenticate, async function (req, res, next) {
|
||||
let idapp = req.body.idapp;
|
||||
const user = req.user;
|
||||
let idGasordine = req.body.idGasordine;
|
||||
|
||||
const { User } = require('../models/user');
|
||||
|
||||
@@ -9,7 +9,7 @@ const i18n = require('i18n');
|
||||
|
||||
const sharp = require('sharp');
|
||||
|
||||
const { authenticate, authenticate_noerror } = require(
|
||||
const { authenticate, authenticate_noerror, authenticate_noerror_WithUser, authenticate_noerror_WithUserLean } = require(
|
||||
'../middleware/authenticate');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
@@ -45,6 +45,7 @@ const { Contribtype } = require('../models/contribtype');
|
||||
const { PaymentType } = require('../models/paymenttype');
|
||||
const { Discipline } = require('../models/discipline');
|
||||
const { MyElem } = require('../models/myelem');
|
||||
const { Cron } = require('../models/cron');
|
||||
const { Skill } = require('../models/skill');
|
||||
const { Good } = require('../models/good');
|
||||
const { StatusSkill } = require('../models/statusSkill');
|
||||
@@ -84,6 +85,10 @@ const Department = require('../models/department');
|
||||
const { Category } = require('../models/category');
|
||||
const Group = require('../models/group');
|
||||
|
||||
const T_WEB_StatiProdotto = require('../models/t_web_statiprodotto');
|
||||
const T_WEB_Tipologie = require('../models/t_web_tipologie');
|
||||
const T_WEB_TipiFormato = require('../models/t_web_tipiformato');
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
const server_constants = require('../tools/server_constants');
|
||||
@@ -350,13 +355,14 @@ router.post('/settable', authenticate, async (req, res) => {
|
||||
|
||||
try {
|
||||
if (User.isAdmin(req.user.perm) || User.isManager(req.user.perm) ||
|
||||
User.isEditor(req.user.perm) || User.isFacilitatore(req.user.perm)) {
|
||||
User.isEditor(req.user.perm) || User.isCommerciale(req.user.perm) || User.isFacilitatore(req.user.perm)) {
|
||||
consentito = true;
|
||||
}
|
||||
|
||||
if ((!User.isAdmin(req.user.perm)
|
||||
&& !User.isManager(req.user.perm)
|
||||
&& !User.isEditor(req.user.perm)
|
||||
&& !User.isCommerciale(req.user.perm)
|
||||
&& !User.isGrafico(req.user.perm)
|
||||
&& !User.isFacilitatore(req.user.perm))
|
||||
&&
|
||||
@@ -514,7 +520,7 @@ router.post('/settable', authenticate, async (req, res) => {
|
||||
})
|
||||
.then(async (risult) => {
|
||||
let rec = null;
|
||||
if (risult && risult.ok === 1) {
|
||||
if (risult && risult.acknowledged) {
|
||||
rec = await mytable.findById(mytablerec._id).lean();
|
||||
} else {
|
||||
rec = risult;
|
||||
@@ -714,7 +720,7 @@ router.post('/gettable', authenticate_noerror, (req, res) => {
|
||||
params.table = sanitizeHtml(params.table);
|
||||
|
||||
if (!shared_consts.TABLES_ENABLE_GETTABLE_FOR_NOT_LOGGED.includes(params.table) && !req.user) {
|
||||
return res.status(403).send({});
|
||||
return res.status(req.code).send({});
|
||||
}
|
||||
|
||||
let idapp = req.user ? req.user.idapp : sanitizeHtml(params.idapp);
|
||||
@@ -804,9 +810,9 @@ router.post('/getexp', authenticate, (req, res) => {
|
||||
|
||||
});
|
||||
|
||||
router.post('/pickup', authenticate, (req, res) => {
|
||||
router.post('/pickup', authenticate_noerror, (req, res) => {
|
||||
const params = req.body;
|
||||
let idapp = req.user.idapp;
|
||||
let idapp = req.body.idapp;
|
||||
let mytable = globalTables.getTableByTableName(params.table);
|
||||
// console.log('mytable', mytable);
|
||||
if (!mytable) {
|
||||
@@ -990,7 +996,7 @@ async function upsertRecord(table, record, appId, newIdPage = null) {
|
||||
record.idPage = newIdPage;
|
||||
}
|
||||
const modif = await table.updateOne({ _id: record._id }, { $set: { ...record, idapp: appId } });
|
||||
wasModified = modif.nModified > 0;
|
||||
wasModified = modif.modifiedCount > 0;
|
||||
} else {
|
||||
// Se sono sulla tabella mypages
|
||||
if (table.modelName === 'MyPage') {
|
||||
@@ -1061,7 +1067,7 @@ async function importPage(req, idapp, jsonString) {
|
||||
const table = globalTables.getTableByTableName(tableName);
|
||||
|
||||
if (tableName === 'mypages') {
|
||||
if (User.isEditor(req.user.perm)) {
|
||||
if (User.isEditor(req.user.perm) || User.isCommerciale(req.user.perm)) {
|
||||
for (const page of myexp.mypages) {
|
||||
const { ImportedRecords, newId } = await upsertRecord(table, page, idapp);
|
||||
if (!newIdPage && newId) {
|
||||
@@ -1091,7 +1097,7 @@ async function importPage(req, idapp, jsonString) {
|
||||
const table = globalTables.getTableByTableName(tableName);
|
||||
|
||||
if (tableName === 'myelems') {
|
||||
if (User.isEditor(req.user.perm)) {
|
||||
if (User.isEditor(req.user.perm) || User.isCommerciale(req.user.perm)) {
|
||||
for (const elem of myexp.myelems) {
|
||||
const { ImportedRecords, newId } = await upsertRecord(table, elem, idapp, newIdPage);
|
||||
ImportedRecordstemp += ImportedRecords ? 1 : 0;
|
||||
@@ -1160,6 +1166,7 @@ router.post('/duppage', authenticate, async (req, res) => {
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
router.post('/exppage', authenticate, async (req, res) => {
|
||||
const params = req.body;
|
||||
const idapp = req.body.idapp;
|
||||
@@ -1253,6 +1260,7 @@ router.patch('/chval', authenticate, async (req, res) => {
|
||||
(!User.isAdmin(req.user.perm)
|
||||
&& !User.isManager(req.user.perm)
|
||||
&& !User.isEditor(req.user.perm)
|
||||
&& !User.isCommerciale(req.user.perm)
|
||||
&& !User.isFacilitatore(req.user.perm))
|
||||
&& (await !tools.ModificheConsentite(req, mydata.table, fieldsvalue, id)))
|
||||
&& !((mydata.table === 'accounts')
|
||||
@@ -1615,7 +1623,7 @@ router.get('/copyfromapptoapp/:idapporig/:idappdest', async (req, res) => {
|
||||
if (!idapporig || !idappdest || (idcode !== 'ASD3429Kjgà#@cvX'))
|
||||
res.status(400).send();
|
||||
|
||||
const mytablesstr = ['settings', 'users', 'templemail'];
|
||||
const mytablesstr = ['settings', 'users', 'templemail', 'destnewsletter'];
|
||||
|
||||
try {
|
||||
let numrectot = 0;
|
||||
@@ -1793,335 +1801,364 @@ router.post('/duprec/:table/:id', authenticate, async (req, res) => {
|
||||
|
||||
});
|
||||
|
||||
router.get('/loadsite/:userId/:idapp', authenticate_noerror, (req, res) => {
|
||||
router.get('/loadsite/:userId/:idapp', authenticate_noerror_WithUserLean, (req, res) => {
|
||||
load(req, res, '0');
|
||||
});
|
||||
|
||||
router.get('/loadsite/:userId/:idapp/:vers', authenticate_noerror,
|
||||
async (req, res) => {
|
||||
// Funzione di test per misurare le performance di MongoDB
|
||||
async function testMongoPerformance(ind, iterations = 20) {
|
||||
let logString = "";
|
||||
const log = (msg) => { logString += msg + "\n"; };
|
||||
|
||||
log(`Avvio del test ${ind} di performance MongoDB con ${iterations} iterazioni...`);
|
||||
|
||||
const timings = [];
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const start = process.hrtime();
|
||||
try {
|
||||
// Esegui una query semplice; sostituisci "User" con il tuo modello se necessario
|
||||
if (ind === 1) {
|
||||
await User.findOne({}).lean();
|
||||
} else {
|
||||
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiJQUk9WQU1TR0AxQSIsInNtYXJ0IjoiNjIwODAwYWRjMTI5ZDFlYmE3NjBiZWNiIiwiYWNjZXNzIjoiYXV0aCIsInVuIjoic3VyeWExOTc3IiwiaWF0IjoxNzQxODcyMzEwLCJleHAiOjE3NDE4Nzk1MTB9.SXJLmsS6EZVhaU7sUWYMnaqGpiiy8RfE9K43xTdxNuU';
|
||||
|
||||
await User.findByToken(token, 'auth', true, true);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
log(`Errore nell'iterazione ${i + 1}: ${err.message}`);
|
||||
}
|
||||
const diff = process.hrtime(start);
|
||||
const timeInSeconds = diff[0] + diff[1] / 1e9;
|
||||
timings.push(timeInSeconds);
|
||||
log(`Iterazione ${i + 1}: ${timeInSeconds.toFixed(3)} sec`);
|
||||
}
|
||||
|
||||
const totalTime = timings.reduce((acc, t) => acc + t, 0);
|
||||
const averageTime = totalTime / timings.length;
|
||||
const minTime = Math.min(...timings);
|
||||
const maxTime = Math.max(...timings);
|
||||
|
||||
log(`--- Risultati del test ${ind} ---`);
|
||||
log(`Tempo totale: ${totalTime.toFixed(3)} sec`);
|
||||
log(`Tempo medio: ${averageTime.toFixed(3)} sec`);
|
||||
log(`Tempo minimo: ${minTime.toFixed(3)} sec`);
|
||||
log(`Tempo massimo: ${maxTime.toFixed(3)} sec`);
|
||||
|
||||
return { totalTime, averageTime, minTime, maxTime, timings, log: logString };
|
||||
}
|
||||
|
||||
|
||||
// Supponendo di usare Express e di avere già definito "router"
|
||||
router.get('/testpao', async (req, res) => {
|
||||
try {
|
||||
let ind = req.query.ind;
|
||||
let numval = req.query.numval;
|
||||
const result = await testMongoPerformance(ind, numval);
|
||||
res.status(200).json({ log: result.log });
|
||||
} catch (error) {
|
||||
console.error("Errore nel test di performance:", error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
router.get('/loadsite/:userId/:idapp/:vers', authenticate_noerror_WithUserLean, async (req, res) => {
|
||||
try {
|
||||
let versionstr = req.params.vers;
|
||||
|
||||
let version = tools.getVersionint(versionstr);
|
||||
|
||||
return await load(req, res, version);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Errore durante il caricamento del sito:', error);
|
||||
res.status(500).json({ error: 'Errore interno del server' });
|
||||
}
|
||||
});
|
||||
|
||||
async function measurePromises(promises) {
|
||||
const keys = Object.keys(promises);
|
||||
const timings = {}; // memorizza il tempo per ogni promise
|
||||
const startTotal = process.hrtime(); // tempo iniziale totale
|
||||
|
||||
// Avvolgo ogni promise per misurare il tempo
|
||||
const wrappedPromises = keys.map(key => {
|
||||
const promise = promises[key];
|
||||
return (async () => {
|
||||
const start = process.hrtime(); // inizio timer per questa promise
|
||||
const result = await promise;
|
||||
const diff = process.hrtime(start);
|
||||
// Calcola i secondi (precisione in nanosecondi)
|
||||
const seconds = diff[0] + diff[1] / 1e9;
|
||||
timings[key] = seconds;
|
||||
return result;
|
||||
})();
|
||||
});
|
||||
|
||||
function load(req, res, version) {
|
||||
// Attendo tutte le promise in parallelo
|
||||
const results = await Promise.all(wrappedPromises);
|
||||
const diffTotal = process.hrtime(startTotal);
|
||||
const totalTime = diffTotal[0] + diffTotal[1] / 1e9;
|
||||
|
||||
let userId = '0';
|
||||
try {
|
||||
userId = req.user ? req.user._id.toString() : req.params.userId;
|
||||
} catch (e) {
|
||||
console.error('Err userId LOAD', e);
|
||||
userId = '0';
|
||||
}
|
||||
const idapp = req.params.idapp;
|
||||
// Ricostruisco l'oggetto data con i risultati
|
||||
const data = keys.reduce((acc, key, index) => {
|
||||
acc[key] = results[index];
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
let status = 200
|
||||
if (req.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) {
|
||||
status = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED
|
||||
}
|
||||
|
||||
|
||||
if (!version) {
|
||||
version = '0';
|
||||
}
|
||||
|
||||
let gestoredelSito = '0';
|
||||
if (!!req.user) {
|
||||
gestoredelSito = (User.isAdmin(req.user.perm) ||
|
||||
User.isManager(req.user.perm) ||
|
||||
User.isEditor(req.user.perm)) ? '1' : '0';
|
||||
}
|
||||
|
||||
// var category = req.params.category;
|
||||
|
||||
// tools.mylog('loadsite : ', req.params);
|
||||
|
||||
|
||||
let bookedevent = [];
|
||||
// let msgs = [];
|
||||
|
||||
let socioresidente = false;
|
||||
|
||||
if (req.user)
|
||||
socioresidente = req.user.profile.socioresidente;
|
||||
|
||||
if (userId !== '0') {
|
||||
// LOGGED WITH USERID
|
||||
bookedevent = Booking.findAllByUserIdAndIdApp(userId, idapp,
|
||||
gestoredelSito);
|
||||
}
|
||||
|
||||
// Extract all the todos of the userId only
|
||||
const eventlist = MyEvent.findAllIdApp(socioresidente, idapp);
|
||||
const operators = Operator.findAllIdApp(idapp);
|
||||
const internalpages = MyPage.findInternalPages(idapp);
|
||||
const wheres = Where.findAllIdApp(idapp);
|
||||
const contribtype = Contribtype.findAllIdApp(idapp);
|
||||
const paymenttype = PaymentType.findAllIdApp(idapp);
|
||||
const disciplines = Discipline.findAllIdApp(idapp);
|
||||
const myelems = MyElem.findAllIdApp(idapp);
|
||||
const myschedas = MyElem.findallSchedeTemplate(idapp);
|
||||
const settings = Settings.findAllIdApp(idapp, false, false);
|
||||
|
||||
const permissions = Permission.findAllIdApp();
|
||||
|
||||
// const versionstr = User....
|
||||
// let version = tools.getVersionint(versionstr);
|
||||
|
||||
let newstosent = Promise.resolve([]);
|
||||
let mailinglist = Promise.resolve([]);
|
||||
let mypage;
|
||||
if (version > 91)
|
||||
mypage = MyPage.findOnlyStruttRec(idapp);
|
||||
else
|
||||
mypage = MyPage.findAllIdApp(idapp);
|
||||
let calzoom = CalZoom.findAllIdApp(idapp);
|
||||
|
||||
let gallery = Promise.resolve([]);
|
||||
if (gestoredelSito) {
|
||||
gallery = Gallery.findAllIdApp(idapp);
|
||||
}
|
||||
|
||||
let producers = Producer.findAllIdApp(idapp);
|
||||
let groups = Group.findAllIdApp(idapp);
|
||||
|
||||
// ....
|
||||
let resps = User.getusersRespList(idapp);
|
||||
let workers = User.getusersWorkersList(idapp);
|
||||
let storehouses = Storehouse.findAllIdApp(idapp);
|
||||
let providers = Provider.findAllIdApp(idapp);
|
||||
let catprods = Product.getArrCatProds(idapp, shared_consts.PROD.BOTTEGA);
|
||||
let catprtotali = CatProd.getCatProdWithTitleCount(idapp);
|
||||
let collane = Collana.findAllIdApp(idapp);
|
||||
let catalogs = Catalog.findAllIdApp(idapp);
|
||||
let catprods_gas = Product.getArrCatProds(idapp, shared_consts.PROD.GAS);
|
||||
let subcatprods = SubCatProd.findAllIdApp(idapp);
|
||||
let gasordines = Gasordine.findAllIdApp(idapp);
|
||||
let catAI = CatAI.findAllIdApp(idapp);
|
||||
let ismanager = false;
|
||||
try {
|
||||
if (req.user)
|
||||
ismanager = User.isManager(req.user.perm)
|
||||
} catch (e) {
|
||||
}
|
||||
let products = Product.findAllIdApp(idapp, undefined, undefined, ismanager);
|
||||
let authors = Author.findAllIdApp(idapp);
|
||||
let publishers = Publisher.findAllIdApp(idapp);
|
||||
let productInfos = ProductInfo.findAllIdApp(idapp);
|
||||
let scontisticas = Scontistica.findAllIdApp(idapp);
|
||||
let departments = Department.findAllIdApp(idapp);
|
||||
let categories = Category.findAllIdApp(idapp);
|
||||
|
||||
|
||||
// SKILLS:
|
||||
let levels = Level.findAllIdApp(idapp);
|
||||
let adtypes = AdType.findAllIdApp(idapp);
|
||||
let adtypegoods = AdTypeGood.findAllIdApp(idapp);
|
||||
let skills = Skill.findAllIdApp(idapp);
|
||||
let goods = Good.findAllIdApp(idapp);
|
||||
//let subSkills = SubSkill.findAllIdApp(idapp);
|
||||
let statusSkills = StatusSkill.findAllIdApp(idapp);
|
||||
let sectors = Sector.findAllIdApp(idapp);
|
||||
let sectorgoods = SectorGood.findAllIdApp(idapp);
|
||||
let catgrps = CatGrp.findAllIdApp(idapp);
|
||||
let site = Site.findAllIdApp(idapp);
|
||||
let mygroups = MyGroup.findAllGroups(idapp);
|
||||
let listcircuits = Circuit.findAllIdApp(idapp);
|
||||
let provinces = Province.findAllIdApp(idapp);
|
||||
let cart = null;
|
||||
let orderscart = null;
|
||||
if (gestoredelSito) {
|
||||
newstosent = Newstosent.findAllIdApp(idapp);
|
||||
}
|
||||
|
||||
let calcstat = null;
|
||||
if (req.user) {
|
||||
calcstat = User.calculateStat(idapp, req.user.username);
|
||||
cart = Cart.getCartByUserId(req.user.id, idapp);
|
||||
if (ismanager) {
|
||||
// Prende Tutti gli Ordini !
|
||||
orderscart = OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false);
|
||||
} else {
|
||||
orderscart = OrdersCart.getOrdersCartByUserId(req.user.id, idapp, 0, false);
|
||||
}
|
||||
}
|
||||
let askedfriends = [];
|
||||
let myuserextra = null;
|
||||
if (req.user) {
|
||||
// askedfriends = User.getAskedFriendsByUsername(idapp, req.user.username);
|
||||
myuserextra = User.addExtraInfo(idapp, req.user._doc, req.user, version);
|
||||
}
|
||||
|
||||
return Promise.all([
|
||||
bookedevent,
|
||||
eventlist,
|
||||
operators,
|
||||
wheres,
|
||||
contribtype,
|
||||
settings,
|
||||
permissions,
|
||||
disciplines,
|
||||
newstosent,
|
||||
mailinglist,
|
||||
mypage,
|
||||
gallery,
|
||||
paymenttype,
|
||||
calcstat,
|
||||
calzoom,
|
||||
producers,
|
||||
cart,
|
||||
storehouses,
|
||||
departments,
|
||||
orderscart,
|
||||
groups,
|
||||
resps,
|
||||
workers,
|
||||
internalpages,
|
||||
levels,
|
||||
skills, //25
|
||||
//subSkills,
|
||||
myuserextra, // 26
|
||||
sectors, // 27
|
||||
statusSkills, //28
|
||||
provinces,
|
||||
catgrps,
|
||||
adtypes,
|
||||
adtypegoods,
|
||||
sectorgoods,
|
||||
goods,
|
||||
site,
|
||||
mygroups,
|
||||
listcircuits, // 37
|
||||
myelems, // 38
|
||||
categories, // 39
|
||||
providers,
|
||||
scontisticas,
|
||||
gasordines,
|
||||
products,
|
||||
productInfos,
|
||||
catprods, //45
|
||||
subcatprods,
|
||||
catprods_gas, //47
|
||||
catAI,
|
||||
authors,
|
||||
publishers,
|
||||
myschedas,
|
||||
collane,
|
||||
catalogs,
|
||||
catprtotali,
|
||||
]).then((arrdata) => {
|
||||
// console.table(arrdata);
|
||||
let myuser = req.user;
|
||||
if (myuser) {
|
||||
try {
|
||||
myuser = arrdata[26];
|
||||
if (myuser) {
|
||||
myuser.password = '';
|
||||
myuser.calcstat = arrdata[13];
|
||||
}
|
||||
} catch (e) { }
|
||||
}
|
||||
if (version < 91) {
|
||||
res.status(status).send({
|
||||
bookedevent: arrdata[0],
|
||||
eventlist: arrdata[1],
|
||||
operators: arrdata[2],
|
||||
wheres: arrdata[3],
|
||||
contribtype: arrdata[4],
|
||||
settings: arrdata[5],
|
||||
permissions: arrdata[6],
|
||||
disciplines: arrdata[7],
|
||||
newstosent: arrdata[8],
|
||||
mailinglist: arrdata[9],
|
||||
mypage: arrdata[10],
|
||||
gallery: arrdata[11],
|
||||
paymenttypes: arrdata[12],
|
||||
calzoom: arrdata[14],
|
||||
producers: arrdata[15],
|
||||
cart: arrdata[16],
|
||||
storehouses: arrdata[17],
|
||||
departments: arrdata[18],
|
||||
orders: arrdata[19],
|
||||
groups: arrdata[20],
|
||||
resps: arrdata[21],
|
||||
workers: arrdata[22],
|
||||
myuser,
|
||||
internalpages: arrdata[23],
|
||||
});
|
||||
} else {
|
||||
res.status(status).send({
|
||||
bookedevent: arrdata[0],
|
||||
eventlist: arrdata[1],
|
||||
operators: arrdata[2],
|
||||
wheres: arrdata[3],
|
||||
contribtype: arrdata[4],
|
||||
settings: arrdata[5],
|
||||
permissions: arrdata[6],
|
||||
disciplines: arrdata[7],
|
||||
newstosent: arrdata[8],
|
||||
mailinglist: arrdata[9],
|
||||
mypage: arrdata[10],
|
||||
gallery: arrdata[11],
|
||||
paymenttypes: arrdata[12],
|
||||
calzoom: arrdata[14],
|
||||
producers: arrdata[15],
|
||||
cart: arrdata[16],
|
||||
storehouses: arrdata[17],
|
||||
departments: arrdata[18],
|
||||
orders: arrdata[19],
|
||||
groups: arrdata[20],
|
||||
resps: arrdata[21],
|
||||
workers: arrdata[22],
|
||||
myuser,
|
||||
internalpages: arrdata[23],
|
||||
levels: arrdata[24],
|
||||
skills: arrdata[25],
|
||||
// subSkills: arrdata[26],
|
||||
// myuser arrdata[26]
|
||||
sectors: arrdata[27],
|
||||
statusSkills: arrdata[28],
|
||||
provinces: arrdata[29],
|
||||
catgrps: arrdata[30],
|
||||
adtypes: arrdata[31],
|
||||
adtypegoods: arrdata[32],
|
||||
sectorgoods: arrdata[33],
|
||||
goods: arrdata[34],
|
||||
site: arrdata[35],
|
||||
mygroups: arrdata[36],
|
||||
listcircuits: arrdata[37],
|
||||
myelems: arrdata[38],
|
||||
categories: arrdata[39],
|
||||
providers: arrdata[40],
|
||||
scontisticas: arrdata[41],
|
||||
gasordines: arrdata[42],
|
||||
products: arrdata[43],
|
||||
productInfos: arrdata[44],
|
||||
catprods: arrdata[45],
|
||||
subcatprods: arrdata[46],
|
||||
catprods_gas: arrdata[47],
|
||||
catAI: arrdata[48],
|
||||
code: req.code,
|
||||
authors: arrdata[49],
|
||||
publishers: arrdata[50],
|
||||
myschedas: arrdata[51],
|
||||
collane: arrdata[52],
|
||||
catalogs: arrdata[53],
|
||||
catprtotali: arrdata[54],
|
||||
});
|
||||
|
||||
const prova = 1;
|
||||
}
|
||||
|
||||
}).catch((e) => {
|
||||
console.log(e.message);
|
||||
res.status(400).send(e);
|
||||
});
|
||||
// Ordina le chiamate per tempo decrescente e prende le 10 più lente
|
||||
const slowCalls = Object.entries(timings)
|
||||
.sort(([, timeA], [, timeB]) => timeB - timeA)
|
||||
.slice(0, 10)
|
||||
.map(([key, time]) => ({ key, time }));
|
||||
|
||||
return { data, totalTime, slowCalls };
|
||||
}
|
||||
|
||||
|
||||
async function load(req, res, version = '0') {
|
||||
try {
|
||||
// console.log(' ... 1) richiesta LOAD');
|
||||
|
||||
// Estrazione e validazione degli input
|
||||
const userId = req.user ? req.user._id.toString() : req.params.userId || '0';
|
||||
const idapp = req.params.idapp;
|
||||
/*const status = req.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED
|
||||
? server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED
|
||||
: 200;*/
|
||||
|
||||
let status = req.code;
|
||||
if (status === server_constants.RIS_CODE_OK) {
|
||||
status = 200;
|
||||
}
|
||||
|
||||
const token = req.header('x-auth');
|
||||
// Se non ho il token, vado cmq stato a 200
|
||||
if (!token && status === server_constants.RIS_CODE_HTTP_INVALID_TOKEN) {
|
||||
status = 200;
|
||||
}
|
||||
|
||||
// Determina se l'utente ha determinati permessi
|
||||
const gestoredelSito = req.user &&
|
||||
(User.isAdmin(req.user.perm) || User.isManager(req.user.perm) || User.isEditor(req.user.perm))
|
||||
? '1'
|
||||
: '0';
|
||||
|
||||
const socioresidente = req.user && req.user.profile ? req.user.profile.socioresidente : false;
|
||||
|
||||
|
||||
// Costruzione dell'oggetto delle promesse
|
||||
const promises = {
|
||||
bookedevent: userId !== '0'
|
||||
? Booking.findAllByUserIdAndIdApp(userId, idapp, gestoredelSito)
|
||||
: Promise.resolve([]),
|
||||
eventlist: MyEvent.findAllIdApp(socioresidente, idapp),
|
||||
operators: Operator.findAllIdApp(idapp),
|
||||
wheres: Where.findAllIdApp(idapp),
|
||||
contribtype: Contribtype.findAllIdApp(idapp),
|
||||
settings: Settings.findAllIdApp(idapp, false, false),
|
||||
permissions: Permission.findAllIdApp(),
|
||||
disciplines: Discipline.findAllIdApp(idapp),
|
||||
newstosent: gestoredelSito
|
||||
? Newstosent.findAllIdApp(idapp)
|
||||
: Promise.resolve([]),
|
||||
mailinglist: Promise.resolve([]),
|
||||
mypage: version > 91
|
||||
? MyPage.findOnlyStruttRec(idapp)
|
||||
: MyPage.findAllIdApp(idapp),
|
||||
gallery: gestoredelSito
|
||||
? Gallery.findAllIdApp(idapp)
|
||||
: Promise.resolve([]),
|
||||
paymenttype: PaymentType.findAllIdApp(idapp),
|
||||
calcstat: req.user
|
||||
? User.calculateStat(idapp, req.user.username)
|
||||
: Promise.resolve(null),
|
||||
calzoom: CalZoom.findAllIdApp(idapp),
|
||||
producers: Producer.findAllIdApp(idapp),
|
||||
cart: req.user
|
||||
? Cart.getCartByUserId(req.user.id, idapp)
|
||||
: Promise.resolve(null),
|
||||
storehouses: Storehouse.findAllIdApp(idapp),
|
||||
departments: Department.findAllIdApp(idapp),
|
||||
orderscart: req.user
|
||||
? (User.isManager(req.user.perm)
|
||||
? OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false)
|
||||
: OrdersCart.getOrdersCartByUserId(req.user.id, idapp, 0, false))
|
||||
: Promise.resolve(null),
|
||||
groups: Group.findAllIdApp(idapp),
|
||||
resps: User.getusersRespList(idapp),
|
||||
workers: User.getusersWorkersList(idapp),
|
||||
internalpages: MyPage.findInternalPages(idapp),
|
||||
// Campi aggiuntivi per versioni >= 91
|
||||
levels: version >= 91 ? Level.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
skills: version >= 91 ? Skill.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
sectors: version >= 91 ? Sector.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
statusSkills: version >= 91 ? StatusSkill.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
provinces: version >= 91 ? Province.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
catgrps: version >= 91 ? CatGrp.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
adtypes: version >= 91 ? AdType.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
adtypegoods: version >= 91 ? AdTypeGood.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
sectorgoods: version >= 91 ? SectorGood.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
goods: version >= 91 ? Good.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
site: version >= 91 ? Site.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
mygroups: version >= 91 ? MyGroup.findAllGroups(idapp) : Promise.resolve([]),
|
||||
listcircuits: version >= 91 ? Circuit.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
myelems: version >= 91 ? MyElem.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
categories: version >= 91 ? Category.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
providers: version >= 91 ? Provider.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
scontisticas: version >= 91 ? Scontistica.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
gasordines: version >= 91 ? Gasordine.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
/*products: version >= 91
|
||||
? Product.findAllIdApp(idapp, undefined, undefined, req.user ? User.isManager(req.user.perm) : false)
|
||||
: Promise.resolve([]),*/
|
||||
products: Promise.resolve([]),
|
||||
// productInfos: version >= 91 ? ProductInfo.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
productInfos: Promise.resolve([]),
|
||||
catprods: version >= 91 ? Product.getArrCatProds(idapp, shared_consts.PROD.BOTTEGA) : Promise.resolve([]),
|
||||
subcatprods: version >= 91 ? SubCatProd.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
catprods_gas: version >= 91 ? Product.getArrCatProds(idapp, shared_consts.PROD.GAS) : Promise.resolve([]),
|
||||
catAI: version >= 91 ? CatAI.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
authors: version >= 91 ? Author.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
publishers: version >= 91 ? Publisher.getEditoriWithTitleCount(idapp) : Promise.resolve([]),
|
||||
myschedas: version >= 91 ? MyElem.findallSchedeTemplate(idapp) : Promise.resolve([]),
|
||||
collane: version >= 91 ? Collana.getCollaneWithTitleCount(idapp) : Promise.resolve([]),
|
||||
catalogs: version >= 91 ? Catalog.findAllIdApp(idapp) : Promise.resolve([]),
|
||||
catprtotali: version >= 91 ? CatProd.getCatProdWithTitleCount(idapp) : Promise.resolve([]),
|
||||
stati_prodotto: version >= 91 ? T_WEB_StatiProdotto.findAllIdApp() : Promise.resolve([]),
|
||||
tipologie: version >= 91 ? T_WEB_Tipologie.findAllIdApp() : Promise.resolve([]),
|
||||
tipoformato: version >= 91 ? T_WEB_TipiFormato.findAllIdApp() : Promise.resolve([]),
|
||||
crons: version >= 91 ? Cron.findAllIdApp() : Promise.resolve([]),
|
||||
myuserextra: req.user
|
||||
? User.addExtraInfo(idapp, req.user, version)
|
||||
: Promise.resolve(null)
|
||||
};
|
||||
|
||||
// Esecuzione parallela di tutte le promesse
|
||||
/*const keys = Object.keys(promises);
|
||||
const results = await Promise.all(Object.values(promises));
|
||||
const data = keys.reduce((acc, key, index) => {
|
||||
acc[key] = results[index];
|
||||
return acc;
|
||||
}, {});
|
||||
*/
|
||||
|
||||
const { data, totalTime, slowCalls } = await measurePromises(promises);
|
||||
// console.log('Risultati delle promise:', data);
|
||||
console.log('Tempo di esecuzione:', totalTime, 'secondi');
|
||||
//console.log('Le 10 chiamate più lente:', slowCalls);
|
||||
|
||||
// Aggiornamento delle informazioni dell'utente, se presente
|
||||
let myuser = req.user;
|
||||
if (myuser && data.myuserextra) {
|
||||
myuser = data.myuserextra;
|
||||
myuser.password = '';
|
||||
myuser.calcstat = data.calcstat;
|
||||
}
|
||||
|
||||
// Costruzione dell'oggetto di risposta in base alla versione
|
||||
let responseData;
|
||||
if (version < 91) {
|
||||
responseData = {
|
||||
bookedevent: data.bookedevent,
|
||||
eventlist: data.eventlist,
|
||||
operators: data.operators,
|
||||
wheres: data.wheres,
|
||||
contribtype: data.contribtype,
|
||||
settings: data.settings,
|
||||
permissions: data.permissions,
|
||||
disciplines: data.disciplines,
|
||||
newstosent: data.newstosent,
|
||||
mailinglist: data.mailinglist,
|
||||
mypage: data.mypage,
|
||||
gallery: data.gallery,
|
||||
paymenttypes: data.paymenttype,
|
||||
calzoom: data.calzoom,
|
||||
producers: data.producers,
|
||||
cart: data.cart,
|
||||
storehouses: data.storehouses,
|
||||
departments: data.departments,
|
||||
orders: data.orderscart,
|
||||
groups: data.groups,
|
||||
resps: data.resps,
|
||||
workers: data.workers,
|
||||
myuser,
|
||||
internalpages: data.internalpages
|
||||
};
|
||||
} else {
|
||||
responseData = {
|
||||
bookedevent: data.bookedevent,
|
||||
eventlist: data.eventlist,
|
||||
operators: data.operators,
|
||||
wheres: data.wheres,
|
||||
contribtype: data.contribtype,
|
||||
settings: data.settings,
|
||||
permissions: data.permissions,
|
||||
disciplines: data.disciplines,
|
||||
newstosent: data.newstosent,
|
||||
mailinglist: data.mailinglist,
|
||||
mypage: data.mypage,
|
||||
gallery: data.gallery,
|
||||
paymenttypes: data.paymenttype,
|
||||
calzoom: data.calzoom,
|
||||
producers: data.producers,
|
||||
cart: data.cart,
|
||||
storehouses: data.storehouses,
|
||||
departments: data.departments,
|
||||
orders: data.orderscart,
|
||||
groups: data.groups,
|
||||
resps: data.resps,
|
||||
workers: data.workers,
|
||||
myuser,
|
||||
internalpages: data.internalpages,
|
||||
levels: data.levels,
|
||||
skills: data.skills,
|
||||
sectors: data.sectors,
|
||||
statusSkills: data.statusSkills,
|
||||
provinces: data.provinces,
|
||||
catgrps: data.catgrps,
|
||||
adtypes: data.adtypes,
|
||||
adtypegoods: data.adtypegoods,
|
||||
sectorgoods: data.sectorgoods,
|
||||
goods: data.goods,
|
||||
site: data.site,
|
||||
mygroups: data.mygroups,
|
||||
listcircuits: data.listcircuits,
|
||||
myelems: data.myelems,
|
||||
categories: data.categories,
|
||||
providers: data.providers,
|
||||
scontisticas: data.scontisticas,
|
||||
gasordines: data.gasordines,
|
||||
products: data.products,
|
||||
productInfos: data.productInfos,
|
||||
catprods: data.catprods,
|
||||
subcatprods: data.subcatprods,
|
||||
catprods_gas: data.catprods_gas,
|
||||
catAI: data.catAI,
|
||||
code: req.code,
|
||||
authors: data.authors,
|
||||
publishers: data.publishers,
|
||||
myschedas: data.myschedas,
|
||||
collane: data.collane,
|
||||
catalogs: data.catalogs,
|
||||
catprtotali: data.catprtotali,
|
||||
stati_prodotto: data.stati_prodotto,
|
||||
tipologie: data.tipologie,
|
||||
tipoformato: data.tipoformato,
|
||||
crons: data.crons,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
// console.log(' ... 2) load dati caricati ...');
|
||||
res.status(status).send(responseData);
|
||||
} catch (e) {
|
||||
console.error('Errore in load:', e);
|
||||
res.status(400).send({ error: e.message });
|
||||
}
|
||||
};
|
||||
|
||||
router.get(process.env.LINK_CHECK_UPDATES, authenticate_noerror, async (req, res) => {
|
||||
const idapp = req.query.idapp;
|
||||
|
||||
@@ -2286,7 +2323,7 @@ function uploadFile(req, res, version) {
|
||||
if (tools.sulServer()) {
|
||||
dirmain = '';
|
||||
} else {
|
||||
dirmain = '/public';
|
||||
dirmain = server_constants.DIR_PUBLIC_LOCALE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2478,14 +2515,14 @@ function deleteFile(req, res, version) {
|
||||
const idapp = req.user.idapp;
|
||||
|
||||
if (!relativefile || relativefile.endsWith('/')) {
|
||||
res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
|
||||
}
|
||||
|
||||
try {
|
||||
let dirmain = '';
|
||||
if (version > 0) {
|
||||
if (!tools.sulServer()) {
|
||||
dirmain = '/public';
|
||||
dirmain = server_constants.DIR_PUBLIC_LOCALE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2493,12 +2530,12 @@ function deleteFile(req, res, version) {
|
||||
console.log('Delete file ' + relativefile);
|
||||
// ++ Move in the folder application !
|
||||
let fullpathfile = tools.getdirByIdApp(idapp) + dirmain + '/' +
|
||||
relativefile;
|
||||
relativefile.replace(/^\//, '');
|
||||
|
||||
tools.delete(fullpathfile, true, (err) => {
|
||||
if (err) console.log('err', err);
|
||||
if (err === undefined || err.errno === -2)
|
||||
res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
|
||||
@@ -59,9 +59,11 @@ router.post('/load', authenticate, async (req, res) => {
|
||||
|
||||
if (data.mycircuits) {
|
||||
for (let i = 0; i < data.mycircuits.length; i++) {
|
||||
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean();
|
||||
if (mycirc)
|
||||
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].name }).lean();
|
||||
if (mycirc) {
|
||||
data.mycircuits[i].account = await Account.getAccountByUsernameAndCircuitId(idapp, '', mycirc._id, true, true, groupname);
|
||||
data.mycircuits[i].account = tools.jsonCopy(data.mycircuits[i].account);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ const { User } = require('../models/user');
|
||||
const { MailingList } = require('../models/mailinglist');
|
||||
const { Newstosent } = require('../models/newstosent');
|
||||
const { TemplEmail } = require('../models/templemail');
|
||||
const { DestNewsletter } = require('../models/destnewsletter');
|
||||
const { OpzEmail } = require('../models/opzemail');
|
||||
const { Settings } = require('../models/settings');
|
||||
|
||||
@@ -254,12 +255,21 @@ router.post('/load', authenticate, async (req, res) => {
|
||||
idapp = req.body.idapp;
|
||||
locale = req.body.locale;
|
||||
|
||||
const ris = {
|
||||
newsstate: await getDataNewsletter(locale, idapp),
|
||||
serv_settings: await Settings.findAllIdApp(idapp, true, false),
|
||||
templemail: await TemplEmail.findAllIdApp(idapp, true),
|
||||
opzemail: await OpzEmail.findAllIdApp(idapp)
|
||||
};
|
||||
let ris;
|
||||
|
||||
try {
|
||||
ris = {
|
||||
newsstate: await getDataNewsletter(locale, idapp),
|
||||
serv_settings: await Settings.findAllIdApp(idapp, true, false),
|
||||
templemail: await TemplEmail.findAllIdApp(idapp, true),
|
||||
destnewsletter: await DestNewsletter.findAllIdApp(idapp, true),
|
||||
opzemail: await OpzEmail.findAllIdApp(idapp)
|
||||
};
|
||||
|
||||
} catch (e) {
|
||||
console.error('Errore load newsletter: ', e);
|
||||
ris = { code: server_constants.RIS_CODE_ERR, msg: e.message };
|
||||
}
|
||||
|
||||
return res.send(ris);
|
||||
});
|
||||
@@ -275,12 +285,19 @@ router.post('/setactivate', authenticate, async (req, res) => {
|
||||
activate,
|
||||
};
|
||||
|
||||
return await Newstosent.findOneAndUpdate({ _id: id }, { $set: rec }, { new: false }).then((item) => {
|
||||
const ris = getDataNewsletter(locale, idapp);
|
||||
try {
|
||||
const item = await Newstosent.findOneAndUpdate({ _id: id }, { $set: rec }, { new: false });
|
||||
|
||||
return res.send(ris);
|
||||
if (item) {
|
||||
const ris = await getDataNewsletter(locale, idapp);
|
||||
return res.send(ris);
|
||||
} else {
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: 'Record not found' });
|
||||
}
|
||||
|
||||
});
|
||||
} catch (e) {
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message });
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
@@ -296,7 +313,7 @@ router.post('/unsubscribe_user', async (req, res) => {
|
||||
if (myuser) {
|
||||
const hashcalc = tools.getHash(myuser.email + myuser.username);
|
||||
|
||||
if (hashcalc === hashemail) {
|
||||
if (hashcalc === hashemail) {
|
||||
await User.setNewsletter(idapp, myuser.username, false);
|
||||
|
||||
return res.send({
|
||||
@@ -329,28 +346,37 @@ router.post('/unsubscribe', (req, res) => {
|
||||
console.log('Remove_from_MailingList -> ', ris);
|
||||
|
||||
if (!!ris.myperson && mailchimpactive) {
|
||||
const subscriber_md5_email = tools.getmd5(ris.myperson.email);
|
||||
request
|
||||
.put('https://' + newsletter[idapp].mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + newsletter[idapp].listUniqueId + '/members/' + subscriber_md5_email)
|
||||
.set('Content-Type', 'application/json;charset=utf-8')
|
||||
.set('Authorization', 'Basic ' + new Buffer('any:' + newsletter[idapp].mailchimpApiKey).toString('base64'))
|
||||
.send({
|
||||
'email_address': ris.myperson.email,
|
||||
'status': server_constants.RIS_UNSUBSCRIBED_STR
|
||||
})
|
||||
.end(function (err, response) {
|
||||
console.log("STAT", response.status);
|
||||
try {
|
||||
const subscriber_md5_email = tools.getmd5(ris.myperson.email);
|
||||
request
|
||||
.put('https://' + newsletter[idapp].mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + newsletter[idapp].listUniqueId + '/members/' + subscriber_md5_email)
|
||||
.set('Content-Type', 'application/json;charset=utf-8')
|
||||
.set('Authorization', 'Basic ' + new Buffer('any:' + newsletter[idapp].mailchimpApiKey).toString('base64'))
|
||||
.send({
|
||||
'email_address': ris.myperson.email,
|
||||
'status': server_constants.RIS_UNSUBSCRIBED_STR
|
||||
})
|
||||
.end(function (err, response) {
|
||||
console.log("STAT", response.status);
|
||||
|
||||
if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
|
||||
res.send({
|
||||
code: server_constants.RIS_UNSUBSCRIBED_OK
|
||||
});
|
||||
} else {
|
||||
res.send({
|
||||
code: server_constants.RIS_SUBSCRIBED_ERR
|
||||
});
|
||||
}
|
||||
if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
|
||||
res.send({
|
||||
code: server_constants.RIS_UNSUBSCRIBED_OK
|
||||
});
|
||||
} else {
|
||||
res.send({
|
||||
code: server_constants.RIS_SUBSCRIBED_ERR
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
console.error('Errore unsubscribe -> ', e);
|
||||
res.send({
|
||||
code: server_constants.RIS_SUBSCRIBED_ERR,
|
||||
msg: e.message
|
||||
});
|
||||
}
|
||||
|
||||
} else {
|
||||
res.send({ code: ris.code, msg: ris.msg });
|
||||
|
||||
@@ -89,6 +89,8 @@ router.get('/id/:id', async function (req, res) {
|
||||
|
||||
var product = await Product.getProductById(id);
|
||||
|
||||
// console.log('Product ID', id, product);
|
||||
|
||||
if (product) {
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, product: product });
|
||||
} else {
|
||||
|
||||
@@ -99,7 +99,7 @@ router.post('/cmd', authenticate_noerror, async (req, res) => {
|
||||
}
|
||||
|
||||
|
||||
let state = (value && ris && ris.ok === 1) ? 1 : ((!value && ris && ris.ok === 1) ? -1 : 0);
|
||||
let state = (value && ris && ris.acknowledged) ? 1 : ((!value && ris && ris.acknowledged) ? -1 : 0);
|
||||
|
||||
const risreac = await Reaction.calcReactions(idapp, id, tab);
|
||||
if (risreac) {
|
||||
|
||||
@@ -4,7 +4,7 @@ const router = express.Router();
|
||||
const tools = require('../tools/general');
|
||||
const server_constants = require('../tools/server_constants');
|
||||
|
||||
const { authenticate } = require('../middleware/authenticate');
|
||||
const { authenticate, authenticate_noerror } = require('../middleware/authenticate');
|
||||
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
const { User } = require('../models/user');
|
||||
@@ -139,7 +139,7 @@ router.get('/delall/:username/:qualinotif/:idapp', authenticate, async (req, res
|
||||
|
||||
});
|
||||
|
||||
router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
|
||||
router.get('/:username/:lastdataread/:idapp', authenticate_noerror, (req, res) => {
|
||||
return getNotif(req, res);
|
||||
});
|
||||
|
||||
|
||||
@@ -90,20 +90,19 @@ router.post('/', authenticate, async (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
router.delete('/del', authenticate, (req, res) => {
|
||||
router.delete('/del', authenticate, async (req, res) => {
|
||||
// tools.mylog("TOKENREM = " + req.token);
|
||||
try {
|
||||
|
||||
|
||||
const browser = req.get('User-Agent');
|
||||
Subscription.findOneAndDelete(
|
||||
return await Subscription.findOneAndDelete(
|
||||
{ userId: req.user._id, access: req.access, browser }).then(() => {
|
||||
res.status(200).send();
|
||||
}, () => {
|
||||
res.status(400).send();
|
||||
});
|
||||
} catch (e) {
|
||||
|
||||
console.error('Err:', e.message);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ const { ObjectId } = require('mongodb');
|
||||
const sendemail = require('../sendemail');
|
||||
|
||||
const { Settings } = require('../models/settings');
|
||||
const CronMod = require('../modules/CronMod');
|
||||
|
||||
const { SendNotif } = require('../models/sendnotif');
|
||||
const { MyElem } = require('../models/myelem');
|
||||
@@ -31,7 +32,7 @@ const _ = require('lodash');
|
||||
|
||||
const reg = require('../reg/registration');
|
||||
|
||||
const { authenticate, authenticate_noerror } = require('../middleware/authenticate');
|
||||
const { authenticate, authenticate_noerror, authenticate_withUser } = require('../middleware/authenticate');
|
||||
|
||||
|
||||
const Cart = require('../models/cart');
|
||||
@@ -54,14 +55,15 @@ const { Account } = require('../models/account');
|
||||
const mongoose = require('mongoose').set('debug', false);
|
||||
|
||||
const Subscription = require('../models/subscribers');
|
||||
const Macro = require('../modules/Macro');
|
||||
|
||||
function existSubScribe(userId, access, browser) {
|
||||
return Subscription.findOne({ userId, access, browser }).then(itemsub => {
|
||||
async function existSubScribe(userId, access, browser) {
|
||||
try {
|
||||
const itemsub = await Subscription.findOne({ userId, access, browser }).lean();
|
||||
return itemsub;
|
||||
}).catch(err => {
|
||||
} catch (err) {
|
||||
return null;
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
function getMobileComplete(user) {
|
||||
@@ -393,7 +395,7 @@ router.post('/', async (req, res) => {
|
||||
} catch (e) {
|
||||
console.error(e.message);
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
|
||||
router.get('/:idapp/:username', async (req, res) => {
|
||||
@@ -445,7 +447,6 @@ router.patch('/:id', authenticate, (req, res) => {
|
||||
});
|
||||
|
||||
router.post('/lastmovs', authenticate, async (req, res) => {
|
||||
const username = req.user ? req.user.username : '';
|
||||
const nummov = req.body.nummov;
|
||||
const idapp = req.body.idapp;
|
||||
|
||||
@@ -497,12 +498,33 @@ router.post('/receiveris', authenticate, (req, res) => {
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/listlinkreg', authenticate, (req, res) => {
|
||||
const username = req.user ? req.user.username : '';
|
||||
const groupname = req.body.groupname;
|
||||
const idapp = req.body.idapp;
|
||||
|
||||
try {
|
||||
if (!username)
|
||||
return res.send({ code: server_constants.RIS_CODE_ERR });
|
||||
|
||||
return User.setLinkReg(idapp, username)
|
||||
.then(risult => {
|
||||
res.send({ code: server_constants.RIS_CODE_OK });
|
||||
}).catch((err) => {
|
||||
tools.mylog('ERRORE IN listlinkreg: ' + err.message);
|
||||
res.status(400).send();
|
||||
});
|
||||
} catch (e) {
|
||||
res.status(400).send();
|
||||
|
||||
};
|
||||
});
|
||||
|
||||
router.post('/profile', authenticate, (req, res) => {
|
||||
const usernameOrig = req.user ? req.user.username : '';
|
||||
const perm = req.user ? req.user.perm : tools.Perm.PERM_NONE;
|
||||
const username = req.body['username'];
|
||||
const idapp = req.body.idapp;
|
||||
const locale = req.body.locale;
|
||||
|
||||
//++Todo: controlla che tipo di dati ha il permesso di leggere
|
||||
|
||||
@@ -662,6 +684,8 @@ router.post('/newtok', async (req, res) => {
|
||||
try {
|
||||
const refreshToken = req.body.refreshToken;
|
||||
|
||||
// return res.status(403).send({ error: 'Refresh token non valido' });
|
||||
|
||||
if (!refreshToken) {
|
||||
return res.status(400).send({ error: 'Refresh token mancante' });
|
||||
}
|
||||
@@ -669,7 +693,7 @@ router.post('/newtok', async (req, res) => {
|
||||
const recFound = await User.findOne({ 'tokens.refreshToken': refreshToken });
|
||||
|
||||
if (!recFound) {
|
||||
return res.status(404).send({ error: 'Refresh token non valido' });
|
||||
return res.status(403).send({ error: 'Refresh token non valido' });
|
||||
}
|
||||
|
||||
const { token, refreshToken: newRefreshToken } = await recFound.generateAuthToken(req);
|
||||
@@ -712,11 +736,10 @@ function checkBlocked(req, res, next) {
|
||||
next();
|
||||
}
|
||||
|
||||
|
||||
router.post('/login', checkBlocked, (req, res) => {
|
||||
var body = _.pick(req.body,
|
||||
router.post('/login', checkBlocked, async (req, res) => {
|
||||
const body = _.pick(req.body,
|
||||
['username', 'password', 'idapp', 'keyappid', 'lang']);
|
||||
var user = new User(body);
|
||||
const userpass = new User(body);
|
||||
// const subs = _.pick(req.body, ['subs']);
|
||||
|
||||
// tools.mylog("LOG: u: " + user.username + " p:" + user.password);
|
||||
@@ -728,135 +751,89 @@ router.post('/login', checkBlocked, (req, res) => {
|
||||
|
||||
let resalreadysent = false;
|
||||
|
||||
const myuser = user;
|
||||
try {
|
||||
const user = await User.findByCredentials(userpass.idapp, userpass.username, userpass.password);
|
||||
|
||||
return User.findByCredentials(user.idapp, user.username, user.password).
|
||||
then(async (user) => {
|
||||
// tools.mylog("CREDENZIALI ! ");
|
||||
if (!user) {
|
||||
if (!user) {
|
||||
const rislogin = await User.tooManyLoginWrong(body.idapp, body.username, true);
|
||||
|
||||
const rislogin = await User.tooManyLoginWrong(body.idapp, body.username, true);
|
||||
if (rislogin.troppilogin) {
|
||||
let text = 'Troppe richieste di Login ERRATE: ' + body.username + ' [IP: ' + tools.getiPAddressUser(req) + '] Tentativi: ' + rislogin.retry_pwd;
|
||||
telegrambot.sendMsgTelegramToTheManagers(body.idapp, text);
|
||||
console.log('/login', text);
|
||||
res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: text });
|
||||
return false;
|
||||
}
|
||||
if (rislogin.troppilogin) {
|
||||
let text = 'Troppe richieste di Login ERRATE: ' + body.username + ' [IP: ' + tools.getiPAddressUser(req) + '] Tentativi: ' + rislogin.retry_pwd;
|
||||
telegrambot.sendMsgTelegramToTheManagers(body.idapp, text);
|
||||
console.log('/login', text);
|
||||
res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: text });
|
||||
return;
|
||||
}
|
||||
|
||||
await tools.snooze(3000);
|
||||
await tools.snooze(2000);
|
||||
|
||||
if (!failedLoginAttempts[body.username]) {
|
||||
failedLoginAttempts[body.username] = 1;
|
||||
} else {
|
||||
failedLoginAttempts[body.username]++;
|
||||
}
|
||||
if (!failedLoginAttempts[body.username]) {
|
||||
failedLoginAttempts[body.username] = 1;
|
||||
} else {
|
||||
failedLoginAttempts[body.username]++;
|
||||
}
|
||||
|
||||
let numvolteerrati = failedLoginAttempts[body.username];
|
||||
let numvolteerrati = failedLoginAttempts[body.username];
|
||||
|
||||
if (numvolteerrati > 2) {
|
||||
const msg = 'Tentativo (' + numvolteerrati + ') di Login ERRATO [' + body.username + ' , ' + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + ']';
|
||||
tools.mylogshow(msg);
|
||||
await telegrambot.sendMsgTelegramToTheAdmin(myuser.idapp, msg, true);
|
||||
tools.writeErrorLog(msg);
|
||||
}
|
||||
// telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg);
|
||||
if (numvolteerrati > 2) {
|
||||
const msg = 'Tentativo (' + numvolteerrati + ') di Login ERRATO [' + body.username + ' , ' + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + ']';
|
||||
tools.mylogshow(msg);
|
||||
await telegrambot.sendMsgTelegramToTheAdmin(req.body.idapp, msg, true);
|
||||
tools.writeErrorLog(msg);
|
||||
}
|
||||
|
||||
if (failedLoginAttempts[body.username] >= MAX_FAILED_ATTEMPTS) {
|
||||
blockUser(body.username);
|
||||
text = 'Troppi tentativi di accesso falliti. Utente bloccato (' + body.username + ')' + ' [IP: ' + tools.getiPAddressUser(req) + ']';
|
||||
tools.mylogshow(text);
|
||||
telegrambot.sendMsgTelegramToTheManagers(req.body.idapp, text);
|
||||
res.status(403).json({ message: text });
|
||||
resalreadysent = true;
|
||||
}
|
||||
|
||||
res.status(401).send({ code: server_constants.RIS_CODE_LOGIN_ERR });
|
||||
if (failedLoginAttempts[body.username] >= MAX_FAILED_ATTEMPTS) {
|
||||
blockUser(body.username);
|
||||
text = 'Troppi tentativi di accesso falliti. Utente bloccato (' + body.username + ')' + ' [IP: ' + tools.getiPAddressUser(req) + ']';
|
||||
tools.mylogshow(text);
|
||||
telegrambot.sendMsgTelegramToTheManagers(req.body.idapp, text);
|
||||
res.status(403).json({ message: text });
|
||||
resalreadysent = true;
|
||||
|
||||
}
|
||||
return user;
|
||||
}).
|
||||
then(user => {
|
||||
// console.log('Lgn-Ok');
|
||||
if (user) {
|
||||
return user.generateAuthToken(req).then((ris) => {
|
||||
var usertosend = new User();
|
||||
|
||||
shared_consts.fieldsUserToChange().forEach((field) => {
|
||||
usertosend[field] = user[field];
|
||||
});
|
||||
return res.status(401).send({ code: server_constants.RIS_CODE_LOGIN_ERR });
|
||||
} else {
|
||||
const myris = await user.generateAuthToken(req);
|
||||
|
||||
// usertosend._id = user._id.toHexString();
|
||||
// if (!User.isAdmin(req.user)) {
|
||||
// usertosend.ipaddr = user.ipaddr;
|
||||
// }
|
||||
const usertosend = new User();
|
||||
|
||||
// tools.mylog("user.verified_email:" + user.verified_email);
|
||||
// tools.mylog("usertosend.userId", usertosend.userId);
|
||||
shared_consts.fieldsUserToChange().forEach((field) => {
|
||||
usertosend[field] = user[field];
|
||||
});
|
||||
|
||||
return { usertosend, token: ris.token, refreshToken: ris.refreshToken };
|
||||
const subsExistonDb = await existSubScribe(usertosend._id, 'auth', req.get('User-Agent'));
|
||||
|
||||
}).then((myris) => {
|
||||
const access = 'auth';
|
||||
const browser = req.get('User-Agent');
|
||||
|
||||
// Check if already exist Subscribe
|
||||
return existSubScribe(myris.usertosend._id, access, browser).
|
||||
then(subscribe => {
|
||||
return (subscribe !== null);
|
||||
}).
|
||||
then(subsExistonDb => {
|
||||
// console.log('ESEGUITO OK')
|
||||
return {
|
||||
usertosend: myris.usertosend,
|
||||
token: myris.token,
|
||||
refreshToken: myris.refreshToken,
|
||||
subsExistonDb,
|
||||
};
|
||||
}).
|
||||
catch(err => {
|
||||
return {
|
||||
usertosend: myris.usertosend,
|
||||
token: myris.token,
|
||||
refreshToken: myris.refreshToken,
|
||||
subsExistonDb: false,
|
||||
};
|
||||
});
|
||||
}).then(myris => {
|
||||
// console.log('res', myris.token, myris.usertosend);
|
||||
|
||||
// SEND TOKEN AND CODE RESULT
|
||||
return res
|
||||
.header('x-auth', myris.token)
|
||||
.header('x-refrtok', myris.refreshToken)
|
||||
.send({
|
||||
usertosend: myris.usertosend,
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
subsExistonDb: myris.subsExistonDb,
|
||||
});
|
||||
|
||||
// tools.mylog("TROVATOOO!");
|
||||
|
||||
// tools.mylog('FINE LOGIN')
|
||||
res
|
||||
.header('x-auth', myris.token)
|
||||
.header('x-refrtok', myris.refreshToken)
|
||||
.send({
|
||||
usertosend,
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
subsExistonDb,
|
||||
});
|
||||
}
|
||||
}).
|
||||
catch((e) => {
|
||||
console.error('ERRORE IN LOGIN: ' + e.message);
|
||||
if (!resalreadysent)
|
||||
res.status(400).
|
||||
send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC, msgerr: e.message });
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
} catch (e) {
|
||||
console.error('ERRORE IN LOGIN: ' + e.message);
|
||||
if (!resalreadysent)
|
||||
res.status(400).
|
||||
send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC, msgerr: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/me/token', authenticate, (req, res) => {
|
||||
router.delete('/me/token', authenticate_withUser, (req, res) => {
|
||||
// tools.mylog("TOKENREM = " + req.token);
|
||||
req.user.removeToken(req.token).then(() => {
|
||||
res.status(200).send();
|
||||
}, () => {
|
||||
res.status(400).send();
|
||||
});
|
||||
try {
|
||||
req.user.removeToken(req.token).then(() => {
|
||||
res.status(200).send();
|
||||
}, () => {
|
||||
res.status(400).send();
|
||||
});
|
||||
} catch (e) {
|
||||
console.log('delete(/me/token', e.message);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/setperm', authenticate, (req, res) => {
|
||||
@@ -910,7 +887,7 @@ router.post('/groups', authenticate, (req, res) => {
|
||||
|
||||
});
|
||||
|
||||
router.post('/circuits', authenticate, (req, res) => {
|
||||
router.post('/circuits', authenticate_withUser, (req, res) => {
|
||||
const username = req.user.username;
|
||||
idapp = req.body.idapp;
|
||||
locale = req.body.locale;
|
||||
@@ -1075,506 +1052,6 @@ router.post('/circuits/cmd', authenticate, async (req, res) => {
|
||||
|
||||
});
|
||||
|
||||
async function eseguiDbOp(idapp, mydata, locale, req, res) {
|
||||
|
||||
let ris = await User.DbOp(idapp, mydata);
|
||||
|
||||
const populate = require('../populate/populate');
|
||||
|
||||
const globalTables = require('../tools/globalTables');
|
||||
const { Reaction } = require('../models/reaction');
|
||||
|
||||
let mystr = '';
|
||||
|
||||
try {
|
||||
|
||||
if (mydata.dbop === '') {
|
||||
|
||||
// } else if (mydata.dbop === 'rigeneraTutto') {
|
||||
// await ListaIngresso.Esegui_CronTab(idapp, mydata);
|
||||
} else if (mydata.dbop === 'ReplaceAllCircuits') {
|
||||
// ++ Replace All Circuitname with 'Circuito RIS %s'
|
||||
await Circuit.replaceAllCircuitNames(idapp);
|
||||
} else if (mydata.dbop === 'eliminaCatProds') {
|
||||
|
||||
await CatProd.deleteMany({ idapp });
|
||||
await SubCatProd.deleteMany({ idapp });
|
||||
} else if (mydata.dbop === 'creaUtentiTest') {
|
||||
|
||||
let num = 0;
|
||||
lastrec = await User.find({ idapp }).sort({ _id: -1 }).limit(1);
|
||||
let last = 1;
|
||||
if (lastrec) {
|
||||
last = lastrec[0].index;
|
||||
}
|
||||
if (!last) {
|
||||
last = 1;
|
||||
}
|
||||
|
||||
for (let ind = 0; ind < 100; ind++) {
|
||||
let myuser = new User();
|
||||
myuser._id = new ObjectId();
|
||||
myuser.index = last + ind + 1;
|
||||
myuser.idapp = idapp;
|
||||
myuser.password = '$2a$12$DEaX1h5saTUVC43f7kubyOAlah1xHDgqQTfSIux0.RFDT9WGbyCaG';
|
||||
myuser.lang = 'it';
|
||||
myuser.email = 'miaemail@email.it';
|
||||
myuser.name = 'U' + myuser.index;
|
||||
myuser.surname = 'Ar' + myuser.index;
|
||||
myuser.verified_email = true;
|
||||
myuser.verified_by_aportador = true;
|
||||
if (myuser.index < 2)
|
||||
myuser.perm = '3';
|
||||
myuser.username = 'Userna_' + myuser.name;
|
||||
myuser.profile.special_req = true;
|
||||
myuser.profile.nationality = 'IT';
|
||||
await myuser.save();
|
||||
num++;
|
||||
}
|
||||
|
||||
ris = { num };
|
||||
/*} else if (mydata.dbop === 'visuPlacca') {
|
||||
|
||||
mystr = '✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨\n' +
|
||||
'NAVI CHE SALPANO DALLA ' + mydata.riga + '.' + mydata.col + ' ALLA ' + mydata.riga + '.' + (parseInt(mydata.col) + 7) + '\n' +
|
||||
'AUGURI ALLA NUOVA SOGNATRICE !!!\n' +
|
||||
'✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨';
|
||||
|
||||
const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT');
|
||||
|
||||
for (let ind = 0; ind < 8; ind++) {
|
||||
mystr += await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col) + ind, false);
|
||||
mystr += tools.ACAPO;
|
||||
if (visu_nave_Bot && ind === 3) {
|
||||
await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true);
|
||||
mystr = '';
|
||||
}
|
||||
}
|
||||
|
||||
if (visu_nave_Bot)
|
||||
await telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true);
|
||||
|
||||
ris = { mystr };
|
||||
*/
|
||||
} else if (mydata.dbop === 'CorreggiTabHours') {
|
||||
|
||||
ris = await Hours.correggiHours(idapp);
|
||||
|
||||
} else if (mydata.dbop === 'setVerifiedByAportadorToALL') {
|
||||
|
||||
ris = await User.setVerifiedByAportadorToALL();
|
||||
|
||||
} else if (mydata.dbop === 'RewriteContribType') {
|
||||
|
||||
ris = populate.rewriteTable('contribtypes');
|
||||
|
||||
} else if (mydata.dbop === 'ReplaceUsername') {
|
||||
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
ris = globalTables.replaceUsername(req.body.idapp, mydata.search_username, mydata.replace_username);
|
||||
}
|
||||
} else if (mydata.dbop === 'ExitFromAllCircuitWithZero') {
|
||||
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
ris = globalTables.ExitFromAllCircuitWithZero(req.body.idapp, mydata.search_username);
|
||||
}
|
||||
} else if (mydata.dbop === 'replaceAportadorSolidario') {
|
||||
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
ris = globalTables.replaceAportadorSolidario(req.body.idapp, mydata.search_username, mydata.replace_username);
|
||||
}
|
||||
} else if (mydata.dbop === 'SearchString') {
|
||||
|
||||
if (User.isAdmin(req.user.perm)) {
|
||||
mystr = await globalTables.SearchString(req.body.idapp, mydata.search);
|
||||
}
|
||||
ris = { mystr };
|
||||
|
||||
} else if (mydata.dbop === 'copyFrom1To14') {
|
||||
const idapporig = 1;
|
||||
const idappdest = 14;
|
||||
if (!idapporig || !idappdest)
|
||||
return;
|
||||
|
||||
const globalTables = require('../tools/globalTables');
|
||||
|
||||
//++ Todo: TO FIXIT !
|
||||
const mytablesstr = [
|
||||
'settings',
|
||||
'users',
|
||||
'templemail',
|
||||
'contribtypes',
|
||||
'bots',
|
||||
'cfgservers'];
|
||||
|
||||
try {
|
||||
let numrectot = 0;
|
||||
for (const table of mytablesstr) {
|
||||
const mytable = globalTables.getTableByTableName(table);
|
||||
|
||||
tools.mylogshow('copyfromapptoapp: ', table, mytable);
|
||||
|
||||
await mytable.DuplicateAllRecords(idapporig, idappdest).
|
||||
then((numrec) => {
|
||||
// tools.mylogshow(' REC TO MODIFY: ', rec);
|
||||
if (numrec)
|
||||
numrectot += numrec;
|
||||
});
|
||||
}
|
||||
|
||||
ris = true;
|
||||
|
||||
} catch (e) {
|
||||
console.log('e', e);
|
||||
}
|
||||
|
||||
} else if (mydata.dbop === 'removeRecordsFav') {
|
||||
// Passa le tabelle da users sulle nuove tabelle:
|
||||
await User.removerecordsFavorite();
|
||||
|
||||
} else if (mydata.dbop === 'updateReactionsCounts') {
|
||||
await Reaction.updateReactionsCounts();
|
||||
} else if (mydata.dbop === 'GeneraCSVOrdineProdotti') {
|
||||
await Order.GeneraCSVOrdineProdotti();
|
||||
} else if (mydata.dbop === 'RemoveDeletedOrdersInOrderscart') {
|
||||
await Order.RemoveDeletedOrdersInOrderscart();
|
||||
} else if (mydata.dbop === 'CheckTransazioniCircuiti') {
|
||||
await Circuit.CheckTransazioniCircuiti(false);
|
||||
} else if (mydata.dbop === 'CorreggiTransazioniCircuiti') {
|
||||
await Circuit.CheckTransazioniCircuiti(true);
|
||||
} else if (mydata.dbop === 'RemovePendentTransactions') {
|
||||
ris = await SendNotif.RemovePendentTransactions(idapp);
|
||||
} else if (mydata.dbop === 'RemoveOldNotif90') {
|
||||
await SendNotif.RemoveOldNotif90(idapp);
|
||||
} else if (mydata.dbop === 'RemoveOldNotif30') {
|
||||
await SendNotif.RemoveOldNotif30(idapp);
|
||||
} else if (mydata.dbop === 'UpdateCoordProv') {
|
||||
await Province.setCoordinatesOnDB();
|
||||
} else if (mydata.dbop === 'insertGeojsonToMongoDB') {
|
||||
await City.insertGeojsonToMongoDB('comuni_italia.geojson');
|
||||
} else if (mydata.dbop === 'listCollectionsBySize') {
|
||||
mystr = await tools.listCollectionsBySize();
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === 'MyElemSetIdPageInsteadThePah') {
|
||||
mystr = await MyElem.SetIdPageInsteadThePah(idapp);
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === 'AbilitaNewsletterALL') {
|
||||
await User.updateMany({
|
||||
$or: [
|
||||
{ deleted: { $exists: false } },
|
||||
{ deleted: { $exists: true, $eq: false } }],
|
||||
|
||||
},
|
||||
{ $set: { news_on: true } },
|
||||
{ new: false });
|
||||
|
||||
} else if (mydata.dbop === 'SvuotaTuttiGliAccessiOnlineConToken') {
|
||||
await User.SvuotaTuttiGliAccessiOnlineConToken(idapp);
|
||||
} else if (mydata.dbop === 'SettaAdTypeOffro_In_Hosps') {
|
||||
const { MyHosp } = require('../models/myhosp');
|
||||
|
||||
await MyHosp.SettaAdTypeOffro_In_Hosps(idapp);
|
||||
} else if (mydata.dbop === 'removeRegulations') {
|
||||
await Circuit.updateMany({}, { $set: { regulation: '' } });
|
||||
|
||||
} else if (mydata.dbop === 'newRecordsFav') {
|
||||
// Passa le tabelle da users sulle nuove tabelle:
|
||||
await User.moverecordsFavorite(1);
|
||||
await User.moverecordsFavorite(2);
|
||||
await User.moverecordsFavorite(3);
|
||||
await User.moverecordsFavorite(4);
|
||||
await User.moverecordsFavorite(5);
|
||||
|
||||
} else if (mydata.dbop === 'emptyTabCatServiziBeni') {
|
||||
|
||||
const { Sector } = require('../models/sector');
|
||||
const { SectorGood } = require('../models/sectorgood');
|
||||
const { Skill } = require('../models/skill');
|
||||
const { Good } = require('../models/good');
|
||||
|
||||
await Sector.deleteMany({});
|
||||
await SectorGood.deleteMany({});
|
||||
await Skill.deleteMany({});
|
||||
ris = await Good.deleteMany({});
|
||||
|
||||
} else if (mydata.dbop === 'emptyDbSkill') {
|
||||
|
||||
// Svuota e Ricrea
|
||||
|
||||
const { Sector } = require('../models/sector');
|
||||
const { SectorGood } = require('../models/sectorgood');
|
||||
const { Skill } = require('../models/skill');
|
||||
const { Good } = require('../models/good');
|
||||
const { SubSkill } = require('../models/subskill');
|
||||
const { Contribtype } = require('../models/contribtype');
|
||||
const { AdType } = require('../models/adtype');
|
||||
const { AdTypeGood } = require('../models/adtypegood');
|
||||
const { StatusSkill } = require('../models/statusSkill');
|
||||
const { CatGrp } = require('../models/catgrp');
|
||||
|
||||
await Sector.deleteMany({});
|
||||
await SectorGood.deleteMany({});
|
||||
await Skill.deleteMany({});
|
||||
await Good.deleteMany({});
|
||||
await SubSkill.deleteMany({});
|
||||
await Contribtype.deleteMany({});
|
||||
await AdType.deleteMany({});
|
||||
await AdTypeGood.deleteMany({});
|
||||
await StatusSkill.deleteMany({});
|
||||
await CatGrp.deleteMany({});
|
||||
|
||||
ris = await populate.popolaTabelleNuove();
|
||||
|
||||
} else if (mydata.dbop === 'ricreaTabCitiesProvinces') {
|
||||
|
||||
// Svuota e Ricrea
|
||||
|
||||
const { City } = require('../models/city');
|
||||
const { Province } = require('../models/province');
|
||||
|
||||
await City.deleteMany({});
|
||||
await Province.deleteMany({});
|
||||
|
||||
ris = await populate.popolaTabelleNuove();
|
||||
|
||||
} else if (mydata.dbop === 'PopulateTables') {
|
||||
|
||||
ris = populate.popolaTabelleNuove();
|
||||
|
||||
} else if (mydata.dbop === 'dropProducts') {
|
||||
|
||||
if (idapp) {
|
||||
const deleteProducts = await Product.deleteMany({ idapp });
|
||||
console.log(`Cancellati ${deleteProducts.deletedCount} record dalla collezione Product.`);
|
||||
|
||||
// Cancellazione dei record nella collezione ProductInfo
|
||||
const deleteProductInfo = await ProductInfo.deleteMany({ idapp });
|
||||
console.log(`Cancellati ${deleteProductInfo.deletedCount} record dalla collezione ProductInfo.`);
|
||||
}
|
||||
|
||||
ris = deleteProductInfo ? true : false;
|
||||
|
||||
} else if (mydata.dbop === 'dropCatProd') {
|
||||
|
||||
const deleteCatProd = await CatProd.deleteMany({ idapp });
|
||||
|
||||
} else if (mydata.dbop === 'dropSubCatProd') {
|
||||
|
||||
const deleteSubCatProd = await SubCatProd.deleteMany({ idapp });
|
||||
|
||||
} else if (mydata.dbop === 'dropAllOrders') {
|
||||
|
||||
try {
|
||||
const deleteOrder = await Order.deleteMany({ idapp });
|
||||
const deleteOrdersCart = await OrdersCart.deleteMany({ idapp });
|
||||
const deleteCart = await Cart.deleteMany({ idapp });
|
||||
|
||||
ris = deleteCart;
|
||||
|
||||
} catch (e) {
|
||||
console.error('Err:', e);
|
||||
}
|
||||
} else if (mydata.dbop === 'SistemaGasOrdine') {
|
||||
const arrrec = await Product.find({}).lean();
|
||||
for (const rec of arrrec) {
|
||||
if (tools.isArray(rec.idGasordines) && rec.idGasordines.length > 0) {
|
||||
await Product.findByIdAndUpdate(rec._id, { $set: { idGasordine: rec.idGasordines[0] } })
|
||||
} else {
|
||||
await Product.findByIdAndUpdate(rec._id, { $set: { idGasordine: null } })
|
||||
}
|
||||
}
|
||||
|
||||
} else if (mydata.dbop === 'CopyPriceToCalc') {
|
||||
|
||||
try {
|
||||
const arrrec = await OrdersCart.find({}).lean();
|
||||
for (const rec of arrrec) {
|
||||
await OrdersCart.findByIdAndUpdate(rec._id, { $set: { totalPriceCalc: rec.totalPrice } })
|
||||
}
|
||||
|
||||
const arrrec2 = await Order.find({}).lean();
|
||||
for (const rec of arrrec2) {
|
||||
await Order.findByIdAndUpdate(rec._id, { $set: { TotalPriceProductCalc: rec.TotalPriceProduct } })
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error('Err:', e);
|
||||
}
|
||||
|
||||
} else if (mydata.dbop === 'dropAllCarts') {
|
||||
|
||||
ris = await Cart.deleteMany({ idapp });
|
||||
|
||||
} else if (mydata.dbop === 'RewriteCitiesTable') {
|
||||
|
||||
ris = populate.rewriteTable('cities');
|
||||
} else if (mydata.dbop === 'RewriteLevelsTable') {
|
||||
|
||||
ris = populate.rewriteTable('levels');
|
||||
|
||||
} else if (mydata.dbop === 'RewriteProvincesTable') {
|
||||
|
||||
ris = populate.rewriteTable('provinces');
|
||||
|
||||
} else if (mydata.dbop === 'emptyCityProvinces') {
|
||||
|
||||
const { City } = require('../models/city');
|
||||
const { Province } = require('../models/province');
|
||||
|
||||
await City.deleteMany({});
|
||||
await Province.deleteMany({});
|
||||
|
||||
} else if (mydata.dbop === 'ConvTablesFromIntToString') {
|
||||
|
||||
const { MySkill } = require('../models/myskill');
|
||||
const { MyBacheca } = require('../models/mybacheca');
|
||||
const { MyHosp } = require('../models/myhosp');
|
||||
const { MyGood } = require('../models/mygood');
|
||||
// const { MyGroup } = require('../models/mygroup');
|
||||
|
||||
console.log('INIZIO - Conversioni');
|
||||
// 'myskills',
|
||||
// 'mybachecas',
|
||||
// 'myhosps',
|
||||
// 'mygoods',
|
||||
// 'mygroups'
|
||||
|
||||
await ConvertiDaIntAStr(MySkill);
|
||||
await ConvertiDaIntAStr(MyBacheca);
|
||||
await ConvertiDaIntAStr(MyHosp);
|
||||
await ConvertiDaIntAStr(MyGood);
|
||||
await ConvertiDaIntAStr(MyGroup);
|
||||
|
||||
console.log('FINE - Conversioni');
|
||||
|
||||
} else if (mydata.dbop === 'Removeinteger') {
|
||||
|
||||
const { MySkill } = require('../models/myskill');
|
||||
const { MyBacheca } = require('../models/mybacheca');
|
||||
const { MyHosp } = require('../models/myhosp');
|
||||
const { MyGood } = require('../models/mygood');
|
||||
// const { MyGroup } = require('../models/mygroup');
|
||||
|
||||
console.log('INIZIO - Rimozione');
|
||||
|
||||
await RimuoviInteri(MySkill);
|
||||
await RimuoviInteri(MyBacheca);
|
||||
await RimuoviInteri(MyHosp);
|
||||
await RimuoviInteri(MyGood);
|
||||
await RimuoviInteri(MyGroup);
|
||||
|
||||
console.log('FINE - Rimozione');
|
||||
|
||||
|
||||
} else if (mydata.dbop === 'createAllCircuits') {
|
||||
const { Province } = require('../models/province');
|
||||
|
||||
const arrProv = await Province.find({});
|
||||
for (const recprov of arrProv) {
|
||||
await Circuit.createCircuitIfNotExist(req, idapp, recprov.prov);
|
||||
}
|
||||
|
||||
} else if (mydata.dbop === 'correggiProductTypes') {
|
||||
|
||||
await ProductInfo.correggiProductTypes();
|
||||
} else if (mydata.dbop === 'replaceProductImgToImageFile') {
|
||||
|
||||
await ProductInfo.replaceProductImgToImageFile(true);
|
||||
} else if (mydata.dbop === 'removeUploadProducts_Path') {
|
||||
|
||||
await ProductInfo.replaceProductImgToImageFile(false);
|
||||
|
||||
} else if (mydata.dbop === 'correggiCircuitiANull') {
|
||||
|
||||
|
||||
await User.updateMany(
|
||||
{},
|
||||
{ $pull: { "profile.mycircuits": { "circuitname": null } } }
|
||||
);
|
||||
|
||||
} else if (mydata.dbop === 'ImpostaMinMaxPersonali') {
|
||||
|
||||
await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, '');
|
||||
|
||||
} else if (mydata.dbop === 'ImpostaMinMaxPersonaliCircuito') {
|
||||
|
||||
await Account.SetMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
|
||||
|
||||
} else if (mydata.dbop === 'ImpostaMinMaxComunitari') {
|
||||
|
||||
await Account.SetMinMaxComunitari(idapp, mydata.valmin, mydata.valmax);
|
||||
|
||||
} else if (mydata.dbop === 'ImpostaMinMaxCollettivi') {
|
||||
|
||||
await Account.SetMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax);
|
||||
|
||||
} else if (mydata.dbop === 'ImpostaDefMinMaxPersonali') {
|
||||
|
||||
await Circuit.SetDefMinMaxPersonali(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
|
||||
|
||||
} else if (mydata.dbop === 'ImpostaDefMinMaxCollettivi') {
|
||||
|
||||
await Circuit.SetDefMinMaxCollettivi(idapp, mydata.valmin, mydata.valmax, mydata.circuitId);
|
||||
|
||||
} else if (mydata.dbop === 'AbilitaTuttiCircuiti') {
|
||||
|
||||
await Circuit.AbilitaTuttiCircuiti(idapp);
|
||||
|
||||
} else if (mydata.dbop === 'AzzeraRegolamentiTuttiCircuiti') {
|
||||
|
||||
await Circuit.AzzeraRegolamentiTuttiCircuiti(idapp);
|
||||
|
||||
} else if (mydata.dbop === 'setstrProvByIdCityCircuits') {
|
||||
|
||||
await Circuit.setstrProvByIdCityCircuits(idapp);
|
||||
|
||||
} else if (mydata.dbop === 'updateSaldoAndTransato_AllAccounts') {
|
||||
|
||||
await Account.updateSaldoAndTransato_AllAccounts(idapp);
|
||||
} else if (mydata.dbop === 'generateBotMenuRecords') {
|
||||
|
||||
|
||||
await MyBot.generateBotMenuRecords(idapp);
|
||||
|
||||
} else if (mydata.dbop === 'GenerateVapiKey') {
|
||||
|
||||
await tools.generateVapiKey();
|
||||
|
||||
/*} else if (mydata.dbop === 'visuNave') {
|
||||
mystr = await Nave.getNavePos(idapp, parseInt(mydata.riga), parseInt(mydata.col));
|
||||
|
||||
const visu_nave_Bot = await Settings.getValDbSettings(idapp, 'VISU_NAVE_BOT');
|
||||
if (visu_nave_Bot)
|
||||
telegrambot.sendMsgTelegramToTheAdmin(idapp, mystr, true);
|
||||
|
||||
ris = { mystr };
|
||||
} else if (mydata.dbop === 'getnavibyuser') {
|
||||
|
||||
let arrnavi = null;
|
||||
|
||||
const user = await User.getUserShortDataByUsername(idapp, mydata.username);
|
||||
if (user) {
|
||||
arrnavi = await Nave.getArrPosizioniByUsername(idapp, user.username);
|
||||
|
||||
for (let mynave of arrnavi) {
|
||||
mynave._doc.rec = await Nave.getNaveByRigaCol(idapp, mynave.riga, mynave.col);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ris = { data: arrnavi };
|
||||
|
||||
*/
|
||||
}
|
||||
|
||||
// console.log('ris', ris);
|
||||
|
||||
return ris;
|
||||
|
||||
} catch (e) {
|
||||
console.log(e.message);
|
||||
}
|
||||
};
|
||||
|
||||
async function ConvertiDaIntAStr(mytable) {
|
||||
try {
|
||||
@@ -1610,7 +1087,7 @@ async function ConvertiDaIntAStr(mytable) {
|
||||
const doc = await myrec.save();
|
||||
ind++;
|
||||
console.log('++Add (', ind, ')', doc._id);
|
||||
} catch (err) {
|
||||
} catch (err) {
|
||||
const myid = parseInt(err.keyValue._id, 10) + 0;
|
||||
const canc = await mytable.findOneAndDelete({ _id: myid });
|
||||
if (canc)
|
||||
@@ -1697,22 +1174,19 @@ router.post('/dbop', authenticate, async (req, res) => {
|
||||
locale = req.body.locale;
|
||||
|
||||
if (!User.isAdmin(req.user.perm)) {
|
||||
// If without permissions, exit
|
||||
return res.status(404).
|
||||
send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
|
||||
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED });
|
||||
}
|
||||
|
||||
try {
|
||||
let risOp = await eseguiDbOp(idapp, mydata, locale, req, res);
|
||||
|
||||
// ris = await User.updateMyData(ris, idapp, req.user.username);
|
||||
|
||||
res.send({ code: server_constants.RIS_CODE_OK, data: risOp });
|
||||
const cronMod = new CronMod();
|
||||
const risOp = await cronMod.eseguiDbOp(idapp, mydata, req, res);
|
||||
|
||||
return res.send({ code: server_constants.RIS_CODE_OK, data: risOp });
|
||||
|
||||
} catch (e) {
|
||||
res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e });
|
||||
|
||||
console.log(e.message);
|
||||
return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e.message });
|
||||
}
|
||||
|
||||
});
|
||||
@@ -1849,7 +1323,7 @@ router.post('/infomap', authenticate, async (req, res) => {
|
||||
|
||||
});
|
||||
|
||||
router.post('/mgt', authenticate, async (req, res) => {
|
||||
router.post('/mgt', authenticate_withUser, async (req, res) => {
|
||||
|
||||
const mydata = req.body.mydata;
|
||||
idapp = req.body.idapp;
|
||||
|
||||
@@ -12,6 +12,7 @@ const i18n = require('i18n');
|
||||
const { ObjectId } = require('mongodb');
|
||||
const { Settings } = require('./models/settings');
|
||||
const { TemplEmail } = require('./models/templemail');
|
||||
const { DestNewsletter } = require('./models/destnewsletter');
|
||||
const { Discipline } = require('./models/discipline');
|
||||
|
||||
const previewEmail = require('preview-email');
|
||||
@@ -57,6 +58,7 @@ module.exports = {
|
||||
|
||||
if (to === '')
|
||||
return false;
|
||||
|
||||
// console.log('mylocalsconf', mylocalsconf);
|
||||
|
||||
// console.log("check EMAIL :" + checkifSendEmail());
|
||||
@@ -88,7 +90,6 @@ module.exports = {
|
||||
// transport = this.getTransport(mylocalsconf);
|
||||
// }
|
||||
|
||||
// console.log('1 . transport', transport);
|
||||
|
||||
if (transport) {
|
||||
paramemail.transport = transport;
|
||||
@@ -166,7 +167,7 @@ module.exports = {
|
||||
else
|
||||
transport_preview.sendMail(mailOptions).then(console.log).catch(console.error);
|
||||
}
|
||||
|
||||
|
||||
} catch (e) {
|
||||
console.error('Errore Sendmail', e);
|
||||
}
|
||||
@@ -679,12 +680,20 @@ module.exports = {
|
||||
|
||||
replacefields: function (mylocalsconf) {
|
||||
try {
|
||||
mylocalsconf.dataemail.disclaimer_out = !!mylocalsconf.dataemail.disclaimer ? this.fieldsloop(mylocalsconf,
|
||||
mylocalsconf.dataemail.disclaimer) : '';
|
||||
mylocalsconf.dataemail.disc_bottom_out = !!mylocalsconf.dataemail.disc_bottom ? this.fieldsloop(mylocalsconf,
|
||||
mylocalsconf.dataemail.disc_bottom) : '';
|
||||
mylocalsconf.dataemail.disclaimer_out = !!mylocalsconf.dataemail.disclaimer ? this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.disclaimer) : '';
|
||||
mylocalsconf.dataemail.disc_bottom_out = !!mylocalsconf.dataemail.disc_bottom ? this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.disc_bottom) : '';
|
||||
mylocalsconf.dataemail.firma = !!mylocalsconf.dataemail.firma ? this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.firma) : '';
|
||||
|
||||
if (mylocalsconf.dataemail.templ) {
|
||||
if (mylocalsconf.dataemail.templ.disclaimer)
|
||||
mylocalsconf.dataemail.disclaimer_out = this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.templ.disclaimer);
|
||||
|
||||
if (mylocalsconf.dataemail.templ.piedipagina)
|
||||
mylocalsconf.dataemail.disc_bottom_out = this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.templ.piedipagina);
|
||||
|
||||
if (mylocalsconf.dataemail.templ.firma)
|
||||
mylocalsconf.dataemail.firma = this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.templ.firma);
|
||||
|
||||
mylocalsconf.dataemail.templ.testoheadermail_out = !!mylocalsconf.dataemail.templ.testoheadermail ? this.fieldsloop(mylocalsconf,
|
||||
mylocalsconf.dataemail.templ.testoheadermail) : '';
|
||||
|
||||
@@ -700,38 +709,53 @@ module.exports = {
|
||||
},
|
||||
|
||||
getdataemail: async (idapp, templemail_id) => {
|
||||
// console.log('getdataemail');
|
||||
const mydata = {
|
||||
content_after_events: await Settings.getValDbSettings(idapp, 'TEXT_AFTER_EV'),
|
||||
mailchimpactive: tools.BoolToInt(await Settings.getValDbSettings(idapp, 'MAILCHIMP_ON')),
|
||||
urltwitter: await Settings.getValDbSettings(idapp, 'URL_TWITTER'),
|
||||
urlfb: await Settings.getValDbSettings(idapp, 'URL_FACEBOOK'),
|
||||
urlyoutube: await Settings.getValDbSettings(idapp, 'URL_YOUTUBE'),
|
||||
urlinstagram: await Settings.getValDbSettings(idapp, 'URL_INSTAGRAM'),
|
||||
textpromo: await Settings.getValDbSettings(idapp, 'TEXT_PROMO'),
|
||||
disclaimer: await Settings.getValDbSettings(idapp, 'TEXT_DISCLAIMER'),
|
||||
disc_bottom: await Settings.getValDbSettings(idapp, 'TEXT_DISC_BOTTOM'),
|
||||
firma: await Settings.getValDbSettings(idapp, 'TEXT_SIGN'),
|
||||
|
||||
arrdiscipline: await Discipline.getDisciplineforNewsletter(idapp),
|
||||
disc_title: await Settings.getValDbSettings(idapp, 'DISC_TITLE'),
|
||||
height_logo: await Settings.getValDbSettings(idapp, 'HEIGHT_LOGO'),
|
||||
from: await Settings.getValDbSettings(idapp, 'EMAIL_FROM'),
|
||||
email_reply: await Settings.getValDbSettings(idapp, 'EMAIL_REPLY', ''),
|
||||
pwd_from: await Settings.getValDbSettings(idapp, 'PWD_FROM'),
|
||||
email_service: await Settings.getValDbSettings(idapp, 'EMAIL_SERVICE_SEND'),
|
||||
email_port: await Settings.getValDbSettings(idapp, 'EMAIL_PORT'),
|
||||
templemail_id: templemail_id ? templemail_id : await Settings.getValDbSettings(idapp, 'TEMPLEMAIL_ID'),
|
||||
};
|
||||
try {
|
||||
|
||||
// console.log(mydata.templemail_id);
|
||||
mydata.templ = await TemplEmail.findOne({ _id: mydata.templemail_id });
|
||||
// console.log(mydata.templ);
|
||||
const pwd_from = await Settings.getValDbSettings(idapp, 'PWD_FROM');
|
||||
|
||||
let mydata = {
|
||||
templemail_id: templemail_id ? templemail_id : await Settings.getValDbSettings(idapp, 'TEMPLEMAIL_ID'),
|
||||
destnewsletter_id: await Settings.getValDbSettings(idapp, 'TEMPLEMAIL_DEST'),
|
||||
};
|
||||
|
||||
mydata.templ = await TemplEmail.findOne({ _id: mydata.templemail_id }).lean();
|
||||
mydata.destnewsl = await DestNewsletter.findOne({ _id: mydata.destnewsletter_id }).lean();
|
||||
|
||||
// console.log('getdataemail');
|
||||
mydata = {
|
||||
...mydata,
|
||||
content_after_events: await Settings.getValDbSettings(idapp, 'TEXT_AFTER_EV'),
|
||||
mailchimpactive: tools.BoolToInt(await Settings.getValDbSettings(idapp, 'MAILCHIMP_ON')),
|
||||
urltwitter: await Settings.getValDbSettings(idapp, 'URL_TWITTER'),
|
||||
urlfb: await Settings.getValDbSettings(idapp, 'URL_FACEBOOK'),
|
||||
urlyoutube: await Settings.getValDbSettings(idapp, 'URL_YOUTUBE'),
|
||||
urlinstagram: await Settings.getValDbSettings(idapp, 'URL_INSTAGRAM'),
|
||||
textpromo: await Settings.getValDbSettings(idapp, 'TEXT_PROMO'),
|
||||
disc_bottom: await Settings.getValDbSettings(idapp, 'TEXT_DISC_BOTTOM'),
|
||||
|
||||
arrdiscipline: await Discipline.getDisciplineforNewsletter(idapp),
|
||||
disc_title: await Settings.getValDbSettings(idapp, 'DISC_TITLE'),
|
||||
height_logo: await Settings.getValDbSettings(idapp, 'HEIGHT_LOGO'),
|
||||
from: await Settings.getValDbSettings(idapp, 'EMAIL_FROM'),
|
||||
email_reply: await Settings.getValDbSettings(idapp, 'EMAIL_REPLY', ''),
|
||||
pwd_from: pwd_from,
|
||||
email_service: await Settings.getValDbSettings(idapp, 'EMAIL_SERVICE_SEND'),
|
||||
email_port: await Settings.getValDbSettings(idapp, 'EMAIL_PORT'),
|
||||
};
|
||||
|
||||
return mydata;
|
||||
|
||||
} catch (e) {
|
||||
console.error('Error getdataemail: ' + e);
|
||||
return null;
|
||||
}
|
||||
|
||||
return mydata;
|
||||
},
|
||||
|
||||
getTransport: (mylocalsconf) => {
|
||||
console.log('getTransport');
|
||||
|
||||
// Create Transport
|
||||
let smtpTransport = null;
|
||||
|
||||
@@ -883,9 +907,6 @@ module.exports = {
|
||||
|
||||
await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio);
|
||||
|
||||
//++Todo Extract List Email to send
|
||||
const userstosend = await MailingList.findAllIdAppSubscribed(idapp);
|
||||
|
||||
const myarrevents = await MyEvent.getLastEvents(idapp);
|
||||
|
||||
let mylocalsconf = {
|
||||
@@ -903,8 +924,24 @@ module.exports = {
|
||||
const mynewsrec = await Newstosent.findOne({ _id: id_newstosent });
|
||||
|
||||
try {
|
||||
mynewsrec.numemail_tot = userstosend.length;
|
||||
mynewsrec.templemail_str = mylocalsconf.dataemail.templ.subject;
|
||||
mynewsrec.destnewsletter_str = mylocalsconf.dataemail.destnewsl?.descr;
|
||||
|
||||
let userstosend = [];
|
||||
|
||||
if (mylocalsconf.dataemail.destnewsl?.tipodest_id === shared_consts.DESTNEWSLETTER.UTENTI) {
|
||||
userstosend = await MailingList.findAllIdAppSubscribed(idapp);
|
||||
} else if (mylocalsconf.dataemail.destnewsl?.tipodest_id === shared_consts.DESTNEWSLETTER.DIARIO) {
|
||||
userstosend = await MailingList.findAllIdAppDiarioSubscr(idapp);
|
||||
} else if (mylocalsconf.dataemail.destnewsl?.tipodest_id === shared_consts.DESTNEWSLETTER.TEST) {
|
||||
userstosend = await MailingList.findAllIdAppTestSubscr(idapp);
|
||||
} else {
|
||||
userstosend = await MailingList.findAllIdAppSubscribed(idapp);
|
||||
}
|
||||
|
||||
|
||||
mynewsrec.numemail_tot = userstosend.length;
|
||||
|
||||
mynewsrec.numemail_sent = await MailingList.getnumSent(idapp, id_newstosent);
|
||||
|
||||
const smtpTransport = this.getTransport(mylocalsconf);
|
||||
@@ -985,6 +1022,8 @@ module.exports = {
|
||||
|
||||
} catch (e) {
|
||||
|
||||
console.error('*** Errore su sendEmail_Newsletter: ! ', e.message);
|
||||
|
||||
const activate = await Newstosent.isActivated(id_newstosent);
|
||||
|
||||
if (!activate) {
|
||||
|
||||
@@ -2,13 +2,12 @@ require('./config/config');
|
||||
|
||||
// console.log(" lodash");
|
||||
|
||||
console.log("VERSIONE NODE.JS :", process.versions.node);
|
||||
console.log('VERSIONE NODE.JS :', process.versions.node);
|
||||
if (process.env.AUTH_MONGODB === undefined) {
|
||||
console.error("AUTH_MONGODB non presente. VARIABILI D'AMBIENTE NON SETTATI!");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
|
||||
const _ = require('lodash');
|
||||
// console.log(" cors");
|
||||
const cors = require('cors');
|
||||
@@ -42,7 +41,6 @@ const path = require('path');
|
||||
const cron = require('node-cron');
|
||||
console.log('Starting mongoose...');
|
||||
|
||||
|
||||
// console.log('Starting pem...');
|
||||
|
||||
// const pem = require('pem')
|
||||
@@ -78,7 +76,7 @@ connectToDatabase(connectionUrl, options)
|
||||
.then(() => {
|
||||
console.log('------------------------------------------------------------------');
|
||||
console.log('--------------- CONNESSIONE AL DB EFFETTUATA ! -----------------');
|
||||
console.log('------------------------------------------------------------------');
|
||||
console.log('------------------------------------------------------------------');
|
||||
|
||||
const { CfgServer } = require('./models/cfgserver');
|
||||
const { ObjectId } = require('mongodb');
|
||||
@@ -88,8 +86,7 @@ connectToDatabase(connectionUrl, options)
|
||||
|
||||
const printf = require('util').format;
|
||||
|
||||
myLoad().then(ris => {
|
||||
|
||||
myLoad().then((ris) => {
|
||||
const { User } = require('./models/user');
|
||||
|
||||
require('./models/todo');
|
||||
@@ -147,6 +144,9 @@ connectToDatabase(connectionUrl, options)
|
||||
|
||||
app.use(express.static('views'));
|
||||
|
||||
app.use(express.json({ limit: '100mb' }));
|
||||
app.use(express.urlencoded({ extended: true, limit: '100mb' }));
|
||||
|
||||
// app.use(express.static(path.join(__dirname, 'client')));
|
||||
|
||||
app.use(bodyParser.json());
|
||||
@@ -162,8 +162,8 @@ connectToDatabase(connectionUrl, options)
|
||||
// cookie: 'cook',
|
||||
directory: __dirname + '/locales',
|
||||
api: {
|
||||
'__': 'translate',
|
||||
'__n': 'translateN'
|
||||
__: 'translate',
|
||||
__n: 'translateN',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -173,14 +173,12 @@ connectToDatabase(connectionUrl, options)
|
||||
// res.sendFile(path.join(__dirname, 'service-worker.js')); // Modifica il percorso secondo la tua struttura
|
||||
});*/
|
||||
|
||||
|
||||
app.use(bodyParser.json());
|
||||
|
||||
// app.use(express.cookieParser());
|
||||
app.use(i18n.init);
|
||||
|
||||
console.log('Use Routes \...');
|
||||
|
||||
console.log('Use Routes ...');
|
||||
|
||||
// catch 404 and forward to error handler
|
||||
// app.use(function (req, res, next) {
|
||||
@@ -195,7 +193,6 @@ connectToDatabase(connectionUrl, options)
|
||||
// development error handler
|
||||
// will print stacktrace
|
||||
if (app.get('env') === 'development') {
|
||||
|
||||
app.use(function (err, req, res, next) {
|
||||
console.log('Server Error: ', err.message);
|
||||
// console.trace();
|
||||
@@ -205,16 +202,13 @@ connectToDatabase(connectionUrl, options)
|
||||
// error: err
|
||||
// });
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
console.log('*** PRODUCTION! ');
|
||||
}
|
||||
|
||||
if ((process.env.NODE_ENV === 'production') ||
|
||||
(process.env.NODE_ENV === 'test')) {
|
||||
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test') {
|
||||
}
|
||||
startServer(app, process.env.PORT);
|
||||
|
||||
@@ -252,30 +246,23 @@ connectToDatabase(connectionUrl, options)
|
||||
app.use('/aitools', aitools_router);
|
||||
app.use('/apisqlsrv', article_router);
|
||||
|
||||
|
||||
mystart();
|
||||
|
||||
});
|
||||
|
||||
|
||||
// app.use(throttle(1024 * 128)); // throttling bandwidth
|
||||
|
||||
async function myLoad() {
|
||||
|
||||
return tools.loadApps();
|
||||
}
|
||||
|
||||
async function mystart() {
|
||||
|
||||
// await estraiTutteLeImmagini();
|
||||
|
||||
console.log('Versione Server: ' + await tools.getVersServer());
|
||||
|
||||
console.log('Versione Server: ' + (await tools.getVersServer()));
|
||||
|
||||
await tools.getApps();
|
||||
|
||||
if (process.env.PROD !== 1) {
|
||||
|
||||
testmsgwebpush();
|
||||
|
||||
// tools.sendNotifToAdmin('Riparti', 'Riparti');
|
||||
@@ -291,12 +278,8 @@ connectToDatabase(connectionUrl, options)
|
||||
}
|
||||
|
||||
mycron();
|
||||
if (!process.env.VITE_DEBUG) {
|
||||
mycron();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
telegrambot = require('./telegram/telegrambot');
|
||||
|
||||
await inizia();
|
||||
@@ -312,14 +295,15 @@ connectToDatabase(connectionUrl, options)
|
||||
const mailchimpClientId = 'xxxxxxxxxxxxxxxx';
|
||||
|
||||
app.get('/mailchimp/auth/authorize', function (req, res) {
|
||||
res.redirect('https://login.mailchimp.com/oauth2/authorize?' +
|
||||
querystring.stringify({
|
||||
'response_type': 'code',
|
||||
'client_id': mailchimpClientId,
|
||||
'redirect_uri': 'http://127.0.0.1:3000/mailchimp/auth/callback',
|
||||
}));
|
||||
res.redirect(
|
||||
'https://login.mailchimp.com/oauth2/authorize?' +
|
||||
querystring.stringify({
|
||||
response_type: 'code',
|
||||
client_id: mailchimpClientId,
|
||||
redirect_uri: 'http://127.0.0.1:3000/mailchimp/auth/callback',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// -----------------
|
||||
@@ -332,22 +316,24 @@ connectToDatabase(connectionUrl, options)
|
||||
chiave: 'vers',
|
||||
userId: 'ALL',
|
||||
valore: '0.1.2',
|
||||
}];
|
||||
},
|
||||
];
|
||||
|
||||
let cfg = new CfgServer(cfgserv[0]).save();
|
||||
}
|
||||
|
||||
async function mycron() {
|
||||
|
||||
try {
|
||||
const sendemail = require('./sendemail');
|
||||
|
||||
const arr = await tools.getApps();
|
||||
const { Cron } = require('./models/cron');
|
||||
|
||||
const arr = await tools.getApps();
|
||||
for (const app of arr) {
|
||||
await sendemail.checkifPendingNewsletter(app.idapp);
|
||||
await sendemail.checkifSentNewsletter(app.idapp);
|
||||
|
||||
await Cron.startJobCron(app.idapp);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Err mycron', e);
|
||||
@@ -358,8 +344,7 @@ connectToDatabase(connectionUrl, options)
|
||||
for (const app of await tools.getApps()) {
|
||||
let enablecrontab = false;
|
||||
|
||||
enablecrontab = await Settings.getValDbSettings(app.idapp,
|
||||
tools.ENABLE_CRONTAB, false);
|
||||
enablecrontab = await Settings.getValDbSettings(app.idapp, tools.ENABLE_CRONTAB, false);
|
||||
|
||||
if (enablecrontab) {
|
||||
// ...
|
||||
@@ -369,12 +354,10 @@ connectToDatabase(connectionUrl, options)
|
||||
|
||||
async function mycron_everyday() {
|
||||
try {
|
||||
|
||||
const { User } = require('./models/user');
|
||||
|
||||
const arrapps = await tools.getApps();
|
||||
for (const app of arrapps) {
|
||||
|
||||
// Azzera le richieste di password:
|
||||
const usersblocked = await User.find({ idapp: app.idapp, retry_pwd: { $exists: true, $gte: 29 } }).lean();
|
||||
for (const user of usersblocked) {
|
||||
@@ -382,14 +365,12 @@ connectToDatabase(connectionUrl, options)
|
||||
let text = `⚠️⚠️⚠️ L\'utente ${user.username} (${user.name} ${user.surname}) viene sbloccato dal numero massimo di tentativi di richiesta password!\nTelerlo d\'occhio !\n@${user.profile.username_telegram}`;
|
||||
await telegrambot.sendMsgTelegramToTheAdminAllSites(text, false);
|
||||
}
|
||||
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('mycron_everyday: ', e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function testmsgwebpush() {
|
||||
const { User } = require('./models/user');
|
||||
|
||||
@@ -399,10 +380,10 @@ connectToDatabase(connectionUrl, options)
|
||||
User.find({ username: 'paoloar77', idapp: '1' }).then(async (arrusers) => {
|
||||
if (arrusers !== null) {
|
||||
for (const user of arrusers) {
|
||||
await tools.sendNotificationToUser(user._id, 'Server',
|
||||
'Il Server è Ripartito', '/', '', 'server', []).then(ris => {
|
||||
await tools
|
||||
.sendNotificationToUser(user._id, 'Server', 'Il Server è Ripartito', '/', '', 'server', [])
|
||||
.then((ris) => {
|
||||
if (ris) {
|
||||
|
||||
} else {
|
||||
// already sent the error on calling sendNotificationToUser
|
||||
}
|
||||
@@ -410,10 +391,16 @@ connectToDatabase(connectionUrl, options)
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
// Cron every X minutes
|
||||
// Esecuzione ogni 1 minuto (*/1 * * * *)
|
||||
// La sintassi di cron è:
|
||||
// 0 12 * * * comando
|
||||
// che significa: esegui il comando ogni giorno alle 12:00
|
||||
// La sintassi di node-cron è:
|
||||
// cron.schedule('0 12 * * *', () => {
|
||||
// che significa: esegui il comando ogni giorno alle 12:00
|
||||
// La sintassi di node-cron con */1 esegue il comando ogni 1 minuto
|
||||
cron.schedule('*/1 * * * *', () => {
|
||||
// console.log('Running Cron Job');
|
||||
// if (!process.env.VITE_DEBUG) {
|
||||
@@ -421,7 +408,7 @@ connectToDatabase(connectionUrl, options)
|
||||
// }
|
||||
});
|
||||
|
||||
// Cron every X minutes
|
||||
// Cron every 1 HOUR
|
||||
cron.schedule('*/60 * * * *', async () => {
|
||||
if (!process.env.VITE_DEBUG) {
|
||||
mycron_30min();
|
||||
@@ -438,17 +425,13 @@ connectToDatabase(connectionUrl, options)
|
||||
// tools.writelogfile('test', 'prova.txt');
|
||||
|
||||
async function resetProcessingJob() {
|
||||
|
||||
const { Newstosent } = require('./models/newstosent');
|
||||
|
||||
arrrec = await Newstosent.find({});
|
||||
|
||||
for (const rec of arrrec) {
|
||||
rec.processing_job = false;
|
||||
await Newstosent.findOneAndUpdate({ _id: rec.id }, { $set: rec }, { new: false }).
|
||||
then((item) => {
|
||||
|
||||
});
|
||||
await Newstosent.findOneAndUpdate({ _id: rec.id }, { $set: rec }, { new: false }).then((item) => {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -457,7 +440,6 @@ connectToDatabase(connectionUrl, options)
|
||||
//});
|
||||
|
||||
async function inizia() {
|
||||
|
||||
try {
|
||||
if (true) {
|
||||
const url = 'https://raw.githubusercontent.com/matteocontrini/comuni-json/master/comuni.json';
|
||||
@@ -468,19 +450,22 @@ connectToDatabase(connectionUrl, options)
|
||||
mycron_everyday();
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
await telegrambot.sendMsgTelegram(tools.FREEPLANET,
|
||||
await telegrambot.sendMsgTelegram(
|
||||
tools.FREEPLANET,
|
||||
shared_consts.ADMIN_USER_SERVER,
|
||||
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}!`);
|
||||
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}!`
|
||||
);
|
||||
|
||||
await telegrambot.sendMsgTelegramByIdTelegram(tools.FREEPLANET,
|
||||
await telegrambot.sendMsgTelegramByIdTelegram(
|
||||
tools.FREEPLANET,
|
||||
telegrambot.ADMIN_IDTELEGRAM_SERVER,
|
||||
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}\n` +
|
||||
`🔅 Il Server ${process.env.DATABASE} è appena ripartito!`);
|
||||
|
||||
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}\n` + `🔅 Il Server ${process.env.DATABASE} è appena ripartito!`
|
||||
);
|
||||
} else {
|
||||
|
||||
await telegrambot.sendMsgTelegramToTheAdminAllSites(`Ciao Admin\n` + `🔅🔅🔅 Il Server col BOT di {appname} è appena ripartito!`, false);
|
||||
|
||||
await telegrambot.sendMsgTelegramToTheAdminAllSites(
|
||||
`Ciao Admin\n` + `🔅🔅🔅 Il Server col BOT di {appname} è appena ripartito!`,
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
await Site.createFirstUserAdmin();
|
||||
@@ -490,13 +475,7 @@ connectToDatabase(connectionUrl, options)
|
||||
await Circuit.setDeperimentoOff();
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
//
|
||||
@@ -522,10 +501,8 @@ connectToDatabase(connectionUrl, options)
|
||||
|
||||
const globalTables = require('./tools/globalTables');
|
||||
|
||||
|
||||
const mytable = globalTables.getTableByTableName(table);
|
||||
if (!mytable)
|
||||
return;
|
||||
if (!mytable) return;
|
||||
|
||||
console.log('INIZIO - estraiImmagini', table);
|
||||
|
||||
@@ -536,13 +513,14 @@ connectToDatabase(connectionUrl, options)
|
||||
let dirmain = '';
|
||||
let filefrom = '';
|
||||
let filefrom2 = '';
|
||||
let dir = tools.getdirByIdApp(idapp) + dirmain + '/upload/';
|
||||
|
||||
try {
|
||||
if (!tools.sulServer()) {
|
||||
dirmain = '/public';
|
||||
dirmain = server_constants.DIR_PUBLIC_LOCALE;
|
||||
}
|
||||
|
||||
let dir = tools.getdirByIdApp(idapp) + dirmain + '/upload/';
|
||||
|
||||
for (const rec of arrlist) {
|
||||
const myuser = await User.findOne({ idapp, _id: rec.userId }).lean();
|
||||
if (myuser) {
|
||||
@@ -564,16 +542,12 @@ connectToDatabase(connectionUrl, options)
|
||||
console.log('creadir', folderprof);
|
||||
fs.mkdirSync(folderprof);
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
for (const photo of myphotos) {
|
||||
|
||||
if (photo.imagefile) {
|
||||
file = dir + 'profile/' + myuser.username + '/' + table + '/' +
|
||||
photo.imagefile;
|
||||
file = dir + 'profile/' + myuser.username + '/' + table + '/' + photo.imagefile;
|
||||
filefrom = dir + 'profile/undefined/' + table + '/' + photo.imagefile;
|
||||
filefrom2 = dir + 'profile/' + myuser.username + '/' + photo.imagefile;
|
||||
|
||||
@@ -606,7 +580,6 @@ connectToDatabase(connectionUrl, options)
|
||||
}
|
||||
|
||||
async function estraiTutteLeImmagini() {
|
||||
|
||||
await estraiImmagini('myskills');
|
||||
await estraiImmagini('mygoods');
|
||||
await estraiImmagini('mybachecas');
|
||||
@@ -651,30 +624,24 @@ connectToDatabase(connectionUrl, options)
|
||||
const langdest = 'it';
|
||||
|
||||
telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser);
|
||||
|
||||
}
|
||||
|
||||
if (false) {
|
||||
|
||||
const user = await User.findOne({
|
||||
idapp: 12,
|
||||
username: 'paolotest1',
|
||||
});
|
||||
|
||||
await sendemail.sendEmail_Registration('it', 'paolo@arcodiluce.it', user,
|
||||
'12', '');
|
||||
|
||||
await sendemail.sendEmail_Registration('it', 'paolo@arcodiluce.it', user, '12', '');
|
||||
}
|
||||
|
||||
if (false) {
|
||||
|
||||
const { User } = require('./models/user');
|
||||
|
||||
const idapp = tools.FREEPLANET;
|
||||
const idreg = 0;
|
||||
|
||||
try {
|
||||
|
||||
const user = await User.findOne({
|
||||
idapp,
|
||||
username: 'paoloar773',
|
||||
@@ -697,8 +664,7 @@ connectToDatabase(connectionUrl, options)
|
||||
user,
|
||||
};
|
||||
|
||||
await telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION,
|
||||
mylocalsconf);
|
||||
await telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION, mylocalsconf);
|
||||
} catch (e) {
|
||||
console.log('error ' + e);
|
||||
}
|
||||
@@ -706,7 +672,6 @@ connectToDatabase(connectionUrl, options)
|
||||
}
|
||||
|
||||
function getCredentials(hostname) {
|
||||
|
||||
if (NUOVO_METODO_TEST) {
|
||||
if (METODO_MULTI_CORS) {
|
||||
const fileprivkey = `/etc/letsencrypt/live/${hostname}/` + process.env.PATH_CERT_KEY;
|
||||
@@ -737,36 +702,22 @@ connectToDatabase(connectionUrl, options)
|
||||
};*/
|
||||
|
||||
try {
|
||||
const key = fs.readFileSync(fileprivkey, "utf8");
|
||||
const cert = fs.readFileSync(filecert, "utf8");
|
||||
const key = fs.readFileSync(fileprivkey, 'utf8');
|
||||
const cert = fs.readFileSync(filecert, 'utf8');
|
||||
return { key, cert };
|
||||
} catch (error) {
|
||||
console.error(`Errore nel caricamento delle credenziali per ${hostname}:`, error);
|
||||
// Gestisci l'errore, per esempio ritorna null o lancia un'eccezione
|
||||
}
|
||||
|
||||
} else {
|
||||
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
|
||||
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
|
||||
|
||||
const privateKey = fs.readFileSync(keyStream, "utf8");
|
||||
const certificate = fs.readFileSync(certificateStream, "utf8");
|
||||
const privateKey = fs.readFileSync(keyStream, 'utf8');
|
||||
const certificate = fs.readFileSync(certificateStream, 'utf8');
|
||||
|
||||
return { key: privateKey, cert: certificate };
|
||||
}
|
||||
} else if (process.env.HTTPS_LOCALHOST === "true") {
|
||||
try {
|
||||
return {
|
||||
key: fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8'),
|
||||
cert: fs.readFileSync(process.env.PATH_SERVER_CRT, 'utf8'),
|
||||
ciphers: 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
|
||||
honorCipherOrder: true,
|
||||
secureProtocol: 'TLSv1_2_method'
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Errore durante la lettura dei file di certificazione, error:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
// Caso di default non specificato, potrebbe essere necessario aggiungere una gestione degli errori qui
|
||||
}
|
||||
@@ -776,12 +727,13 @@ connectToDatabase(connectionUrl, options)
|
||||
const isProduction = ['production', 'test'].includes(process.env.NODE_ENV);
|
||||
|
||||
let domains = [];
|
||||
let domains_allowed = [];
|
||||
|
||||
try {
|
||||
if (process.env.DOMAINS)
|
||||
domains = JSON.parse(process.env.DOMAINS);
|
||||
if (process.env.DOMAINS) domains = JSON.parse(process.env.DOMAINS);
|
||||
if (process.env.DOMAINS_ALLOWED) domains_allowed = JSON.parse(process.env.DOMAINS_ALLOWED);
|
||||
} catch (error) {
|
||||
console.error("Errore durante la conversione della stringa DOMAINS:", error);
|
||||
console.error('Errore durante la conversione della stringa DOMAINS:', error);
|
||||
}
|
||||
|
||||
console.log('domains', domains);
|
||||
@@ -792,47 +744,73 @@ connectToDatabase(connectionUrl, options)
|
||||
console.log('isProduction', isProduction);
|
||||
|
||||
const NOCORS = false;
|
||||
const CORS_ENABLE_FOR_ALL_SITES = false;
|
||||
|
||||
const ISDEBUG = false;
|
||||
|
||||
let corsOptions = {};
|
||||
|
||||
if (NOCORS) {
|
||||
console.log('NOCORS')
|
||||
console.log('NOCORS');
|
||||
corsOptions = {
|
||||
exposedHeaders: ['x-auth', 'x-refrtok'], // Intestazioni da esporre al client
|
||||
};
|
||||
|
||||
} else {
|
||||
console.log('WITH CORS')
|
||||
let myorigin = '*';
|
||||
let credentials = false;
|
||||
console.log('WITH CORS');
|
||||
let credentials = true;
|
||||
|
||||
const allowedOrigins = domains.flatMap(domain => [
|
||||
`https://${domain.hostname}`,
|
||||
`https://api.${domain.hostname}`,
|
||||
`https://test.${domain.hostname}`,
|
||||
`https://testapi.${domain.hostname}`,
|
||||
`http://${domain.hostname}`,
|
||||
`http://api.${domain.hostname}`,
|
||||
`http://test.${domain.hostname}`,
|
||||
`http://testapi.${domain.hostname}`
|
||||
]);
|
||||
let allowedOrigins = null;
|
||||
|
||||
if (!isProduction) {
|
||||
allowedOrigins = 'https://localhost:3000';
|
||||
} else {
|
||||
allowedOrigins = domains.flatMap((domain) => [
|
||||
`https://${domain.hostname}`,
|
||||
`https://api.${domain.hostname}`,
|
||||
`https://test.${domain.hostname}`,
|
||||
`https://testapi.${domain.hostname}`,
|
||||
`http://${domain.hostname}`,
|
||||
`http://api.${domain.hostname}`,
|
||||
`http://test.${domain.hostname}`,
|
||||
`http://testapi.${domain.hostname}`,
|
||||
]);
|
||||
|
||||
// Aggiungi i domini da DOMAINS_ALLOWED
|
||||
allowedOrigins = allowedOrigins.concat(
|
||||
domains_allowed.map((domain) => [`https://${domain}`, `http://${domain}`]).flat()
|
||||
);
|
||||
}
|
||||
|
||||
console.log('allowedOrigins', allowedOrigins);
|
||||
|
||||
let myorigin = '*';
|
||||
|
||||
if (domains.length > 0) {
|
||||
myorigin = function (origin, callback) {
|
||||
// Array di domini consentiti
|
||||
myorigin = (origin, callback) => {
|
||||
try {
|
||||
// Validazione dell'input
|
||||
if (origin === undefined) {
|
||||
console.log('✅ Origin UNDEFINED... vado avanti lo stesso !');
|
||||
return callback(null, true);
|
||||
}
|
||||
if (!origin || typeof origin !== 'string' || !/^https?:\/\/[^\s/$.?#].[^\s]*$/.test(origin)) {
|
||||
console.error('❌ Origine non valida:', origin);
|
||||
return callback(new Error('Origine non valida'), false);
|
||||
}
|
||||
|
||||
// console.log('allowedOrigins', allowedOrigins);
|
||||
// Controllo delle origini consentite
|
||||
if (allowedOrigins.includes(origin)) {
|
||||
// console.log('✅ Origine consentita:', origin);
|
||||
return callback(null, true);
|
||||
}
|
||||
|
||||
// Permetti richieste senza origin (es. mobile apps)
|
||||
if (!origin || allowedOrigins.includes(origin)) {
|
||||
callback(null, true);
|
||||
} else {
|
||||
callback(new Error('❌ CORS non permesso per questa origine'));
|
||||
// Blocco delle origini non autorizzate
|
||||
console.warn('❌ Origine bloccata:', origin);
|
||||
return callback(new Error('CORS non permesso per questa origine'), false);
|
||||
} catch (error) {
|
||||
console.error("Errore durante la verifica dell'origine:", error.message);
|
||||
return callback(error, false);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Configurazione CORS dettagliata
|
||||
@@ -847,12 +825,12 @@ connectToDatabase(connectionUrl, options)
|
||||
'Accept',
|
||||
'Authorization',
|
||||
'x-auth',
|
||||
'x-refrtok'
|
||||
'x-refrtok',
|
||||
],
|
||||
exposedHeaders: ['x-auth', 'x-refrtok'],
|
||||
maxAge: 86400, // Preflight cache 24 ore
|
||||
preflightContinue: false,
|
||||
optionsSuccessStatus: 204
|
||||
optionsSuccessStatus: 204,
|
||||
};
|
||||
|
||||
// Applica CORS come primo middleware
|
||||
@@ -861,44 +839,20 @@ connectToDatabase(connectionUrl, options)
|
||||
// HO AGGIUNTO QUESTA RIGA PER IL CORS !!!!!!!
|
||||
app.use(express.json()); // Middleware per il parsing del corpo JSON
|
||||
|
||||
// Gestione specifica delle richieste OPTIONS
|
||||
/* app.options('*', function (req, res) {
|
||||
const origin = req.headers.origin;
|
||||
if (corsOptions.origin === '*' ||
|
||||
(typeof corsOptions.origin === 'function' &&
|
||||
corsOptions.origin.toString().includes(origin))) {
|
||||
|
||||
res.setHeader('Access-Control-Allow-Origin', origin);
|
||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
|
||||
res.setHeader('Access-Control-Allow-Headers',
|
||||
'Origin, X-Requested-With, Content-Type, Accept, Authorization, x-auth, x-refrtok');
|
||||
res.setHeader('Access-Control-Allow-Credentials', 'true');
|
||||
res.setHeader('Access-Control-Expose-Headers', 'x-auth, x-refrtok');
|
||||
res.setHeader('Access-Control-Max-Age', '86400');
|
||||
|
||||
res.status(204).end();
|
||||
} else {
|
||||
res.status(403).end();
|
||||
}
|
||||
});*/
|
||||
app.options('*', cors(corsOptions)); // Gestisce tutte le richieste OPTIONS
|
||||
|
||||
// Middleware per assicurarsi che gli headers CORS siano sempre presenti
|
||||
app.use((req, res, next) => {
|
||||
let origin = req.headers.origin;
|
||||
if (!origin) {
|
||||
origin = '*';
|
||||
}
|
||||
if (corsOptions.origin === '*' ||
|
||||
(typeof corsOptions.origin === 'function' &&
|
||||
corsOptions.origin.toString().includes(origin))) {
|
||||
|
||||
//console.log('Access-Control-Allow-Origin')
|
||||
// Middleware personalizzato per assicurare gli headers CORS
|
||||
/*app.use((req, res, next) => {
|
||||
const origin = req.headers.origin || '*';
|
||||
if (allowedOrigins.includes(origin) || corsOptions.origin === '*') {
|
||||
// console.log(' ... ORIGIN', origin);
|
||||
res.setHeader('Access-Control-Allow-Origin', origin);
|
||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
||||
res.setHeader('Access-Control-Allow-Credentials', 'true');
|
||||
res.setHeader('Access-Control-Expose-Headers', 'x-auth, x-refrtok');
|
||||
}
|
||||
next();
|
||||
});
|
||||
});*/
|
||||
|
||||
// Log middleware per debug
|
||||
app.use((req, res, next) => {
|
||||
@@ -925,11 +879,11 @@ connectToDatabase(connectionUrl, options)
|
||||
console.error('❌ Errore CORS:', {
|
||||
origin: req.headers.origin,
|
||||
method: req.method,
|
||||
path: req.path
|
||||
path: req.path,
|
||||
});
|
||||
res.status(403).json({
|
||||
error: '❌ CORS non permesso per questa origine (' + req.headers.origin + ')',
|
||||
origin: req.headers.origin
|
||||
origin: req.headers.origin,
|
||||
});
|
||||
} else {
|
||||
next(err);
|
||||
@@ -937,34 +891,42 @@ connectToDatabase(connectionUrl, options)
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (isProduction) {
|
||||
for (let i = 0; i < domains.length; i++) {
|
||||
const credentials = getCredentials(domains[i].hostname);
|
||||
const mycredentials = getCredentials(domains[i].hostname);
|
||||
// console.log('credentials: ', credentials);
|
||||
httpsServer = https.createServer(credentials, app);
|
||||
console.log('⭐️⭐️⭐️⭐️⭐️ HTTPS server: ' + domains[i].hostname + ' Port:', domains[i].port + (domains[i].website ? 'WebSite = ' + domains[i].website : ''));
|
||||
httpsServer = https.createServer(mycredentials, app);
|
||||
console.log(
|
||||
'⭐️⭐️⭐️⭐️⭐️ HTTPS server: ' + domains[i].hostname + ' Port:',
|
||||
domains[i].port + (domains[i].website ? 'WebSite = ' + domains[i].website : '')
|
||||
);
|
||||
httpsServer.listen(domains[i].port);
|
||||
}
|
||||
} else {
|
||||
if (process.env.HTTPS_LOCALHOST === "true") {
|
||||
let credentials = null;
|
||||
if (process.env.HTTPS_LOCALHOST === 'true') {
|
||||
let mycredentials = null;
|
||||
try {
|
||||
credentials = {
|
||||
key: fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8'),
|
||||
cert: fs.readFileSync(process.env.PATH_SERVER_CRT, 'utf8'),
|
||||
ciphers: 'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
|
||||
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
|
||||
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
|
||||
|
||||
const privateKey = fs.readFileSync(keyStream, 'utf8');
|
||||
const certificate = fs.readFileSync(certificateStream, 'utf8');
|
||||
|
||||
mycredentials = {
|
||||
key: privateKey,
|
||||
cert: certificate,
|
||||
ciphers:
|
||||
'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
|
||||
honorCipherOrder: true,
|
||||
secureProtocol: 'TLSv1_2_method'
|
||||
secureProtocol: 'TLSv1_2_method',
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Errore durante la lettura dei file di certificazione, error:', error.message);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (credentials) {
|
||||
httpsServer = https.createServer(credentials, app);
|
||||
if (mycredentials) {
|
||||
httpsServer = https.createServer(mycredentials, app);
|
||||
console.log('⭐️⭐️⭐️ HTTPS server IN LOCALE : port', port);
|
||||
httpsServer.listen(port);
|
||||
} else {
|
||||
@@ -976,7 +938,6 @@ connectToDatabase(connectionUrl, options)
|
||||
}
|
||||
|
||||
// console.log('credentials', credentials);
|
||||
|
||||
} else {
|
||||
httpServer = http.createServer(app);
|
||||
if (httpServer) {
|
||||
@@ -998,7 +959,6 @@ connectToDatabase(connectionUrl, options)
|
||||
}
|
||||
|
||||
if (wss) {
|
||||
|
||||
wss.on('connection', (ws) => {
|
||||
console.log('Client socket connected...');
|
||||
|
||||
@@ -1009,12 +969,10 @@ connectToDatabase(connectionUrl, options)
|
||||
const pty = require('node-pty');
|
||||
|
||||
ws.on('message', (message) => {
|
||||
|
||||
const parsedMessage = JSON.parse(message);
|
||||
|
||||
try {
|
||||
|
||||
if ((parsedMessage.type === 'start_script') && (User.isAdminById(parsedMessage.user_id))) {
|
||||
if (parsedMessage.type === 'start_script' && User.isAdminById(parsedMessage.user_id)) {
|
||||
if (scriptProcess) {
|
||||
scriptProcess.kill();
|
||||
}
|
||||
@@ -1028,7 +986,7 @@ connectToDatabase(connectionUrl, options)
|
||||
cols: 80,
|
||||
rows: 40,
|
||||
cwd: process.cwd(),
|
||||
env: process.env
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
let buffer = '';
|
||||
@@ -1039,11 +997,14 @@ connectToDatabase(connectionUrl, options)
|
||||
ws.send(JSON.stringify({ type: 'output', data: data }));
|
||||
|
||||
// Controlla se c'è una richiesta di input
|
||||
if (buffer && (buffer.endsWith(': ') || buffer.includes('? ') ||
|
||||
buffer.toLowerCase().includes('password')
|
||||
|| buffer.includes('Inserisci')
|
||||
|| buffer.includes('Inserted')
|
||||
|| buffer.includes('(Y'))
|
||||
if (
|
||||
buffer &&
|
||||
(buffer.endsWith(': ') ||
|
||||
buffer.includes('? ') ||
|
||||
buffer.toLowerCase().includes('password') ||
|
||||
buffer.includes('Inserisci') ||
|
||||
buffer.includes('Inserted') ||
|
||||
buffer.includes('(Y'))
|
||||
) {
|
||||
ws.send(JSON.stringify({ type: 'input_required', prompt: data.trim() }));
|
||||
buffer = '';
|
||||
@@ -1070,11 +1031,9 @@ connectToDatabase(connectionUrl, options)
|
||||
scriptProcess.write(parsedMessage.data + '\n');
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Errore durante l\'elaborazione del messaggio:', error.message);
|
||||
console.error("Errore durante l'elaborazione del messaggio:", error.message);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
@@ -1084,24 +1043,17 @@ connectToDatabase(connectionUrl, options)
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
} else {
|
||||
console.error('Nessuna Socket Aperta con WebSocket !!');
|
||||
}
|
||||
|
||||
|
||||
} catch (e) {
|
||||
console.log('error startServer: ' + e);
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
.catch(err => {
|
||||
console.error("Impossibile connettersi al database dopo diversi tentativi:", err);
|
||||
.catch((err) => {
|
||||
console.error('Impossibile connettersi al database dopo diversi tentativi:', err);
|
||||
process.exit(1); // Termina il processo se non riesce a connettersi
|
||||
});
|
||||
|
||||
|
||||
|
||||
module.exports = { app };
|
||||
|
||||
|
||||
@@ -33,39 +33,36 @@ const { MsgTemplate } = require('../models/msg_template');
|
||||
|
||||
const globalTables = require('../tools/globalTables');
|
||||
|
||||
const emoji = require('node-emoji');
|
||||
|
||||
const i18n = require('i18n');
|
||||
|
||||
let url = process.env.URL || 'https://<PUBLIC-URL>';
|
||||
|
||||
const Benvenuto = emoji.get('heartbeat') + emoji.get('heartbeat') +
|
||||
emoji.get('heartbeat') + ' Benvenuto!';
|
||||
const Benvenuto = '💓💓💓 Benvenuto/a!';
|
||||
|
||||
const emo = {
|
||||
JOY: emoji.get('joy'),
|
||||
JOY2: emoji.get('rolling_on_the_floor_laughing'),
|
||||
DANCER: emoji.get('dancer'),
|
||||
STARS: emoji.get('stars'),
|
||||
FIRE: emoji.get('fire'),
|
||||
SUN: emoji.get('sunrise'),
|
||||
TV: emoji.get('tv'),
|
||||
NEWSPAPER: emoji.get('newspaper'),
|
||||
KISS: emoji.get('kiss'),
|
||||
PENCIL: emoji.get('pencil2'),
|
||||
DREAM: emoji.get('beach_with_umbrella'),
|
||||
EYES: emoji.get('eyes'),
|
||||
DIZZY: emoji.get('dizzy'),
|
||||
ONE_HUNDRED: emoji.get('100'),
|
||||
SMILE_STAR: emoji.get('star-struck'),
|
||||
LEFT_FACING_FIST: emoji.get('left-facing_fist'),
|
||||
CHECK_VERDE: emoji.get('white_check_mark'),
|
||||
CHECK_GRIGIA: emoji.get('ballot_box_with_check'),
|
||||
CROSS_ROSSA: emoji.get('x'),
|
||||
ENVELOPE: emoji.get('envelope'),
|
||||
EXCLAMATION_MARK: emoji.get('exclamation'),
|
||||
QUESTION_MARK: emoji.get('question'),
|
||||
ARROW_RIGHT: emoji.get('arrow_right'),
|
||||
JOY: '😂',
|
||||
JOY2: '🤣',
|
||||
DANCER: '💃',
|
||||
STARS: '✨',
|
||||
FIRE: '🔥',
|
||||
SUN: '☀️',
|
||||
TV: '📺',
|
||||
NEWSPAPER: '🗞',
|
||||
KISS: '😘',
|
||||
PENCIL: '✏️',
|
||||
DREAM: '🏖',
|
||||
EYES: '😜',
|
||||
DIZZY: '💫',
|
||||
ONE_HUNDRED: '💯',
|
||||
SMILE_STAR: '🤩', // Star-struck
|
||||
LEFT_FACING_FIST: '🤛', // Left-facing fist
|
||||
CHECK_VERDE: '✅', // White check mark (verde)
|
||||
CHECK_GRIGIA: '☑️', // Ballot box with check (grigia)
|
||||
CROSS_ROSSA: '❌', // X (rossa)
|
||||
ENVELOPE: '✉️', // Envelope
|
||||
EXCLAMATION_MARK: '❗', // Exclamation mark
|
||||
QUESTION_MARK: '❓', // Question mark
|
||||
ARROW_RIGHT: '➡️', // Arrow pointing to the right
|
||||
INVITATI: '',
|
||||
HEART: '❤️',
|
||||
BLUE_HEART: '💙',
|
||||
@@ -229,134 +226,128 @@ const MsgRisp = {
|
||||
|
||||
function getemojibynumber(number) {
|
||||
if (number === 0) {
|
||||
return emoji.get('zero');
|
||||
return '0️⃣'; // zero
|
||||
} else if (number === 1) {
|
||||
return emoji.get('one');
|
||||
return '1️⃣'; // one
|
||||
} else if (number === 2) {
|
||||
return emoji.get('two');
|
||||
return '2️⃣'; // two
|
||||
} else if (number === 3) {
|
||||
return emoji.get('three');
|
||||
return '3️⃣'; // three
|
||||
} else if (number === 4) {
|
||||
return emoji.get('four');
|
||||
return '4️⃣'; // four
|
||||
} else if (number === 5) {
|
||||
return emoji.get('five');
|
||||
return '5️⃣'; // five
|
||||
} else if (number === 6) {
|
||||
return emoji.get('six');
|
||||
return '6️⃣'; // six
|
||||
} else if (number === 7) {
|
||||
return emoji.get('seven');
|
||||
return '7️⃣'; // seven
|
||||
} else if (number === 8) {
|
||||
return emoji.get('height');
|
||||
return '8️⃣'; // eight
|
||||
} else if (number === 9) {
|
||||
return emoji.get('nine');
|
||||
return '9️⃣'; // nine
|
||||
} else {
|
||||
return number;
|
||||
}
|
||||
}
|
||||
|
||||
const Menu = {
|
||||
LANG_IT: emoji.get('flag-it') + ' Italiano',
|
||||
LANG_EN: emoji.get('flag-gb') + ' English',
|
||||
LANG_ES: emoji.get('flag-es') + ' Español',
|
||||
LANG_FR: emoji.get('flag-fr') + ' Français',
|
||||
LANG_SI: emoji.get('flag-si') + ' Slovenski',
|
||||
LANG_PT: emoji.get('flag-pt') + ' Português',
|
||||
LANG: emoji.get('globe_with_meridians') + ' Language',
|
||||
CHAT_PERSONALE: emoji.get('female-office-worker') + emoji.get('computer'),
|
||||
LANG_IT: '🇮🇹 Italiano', // Bandiera italiana
|
||||
LANG_EN: '🇬🇧 English', // Bandiera del Regno Unito
|
||||
LANG_ES: '🇪🇸 Español', // Bandiera spagnola
|
||||
LANG_FR: '🇫🇷 Français', // Bandiera francese
|
||||
LANG_SI: '🇸🇮 Slovenski', // Bandiera slovena
|
||||
LANG_PT: '🇵🇹 Português', // Bandiera portoghese
|
||||
LANG: '🌐 Language', // Globo con meridiani
|
||||
CHAT_PERSONALE: '👩💼💻', // Donna impiegata + computer
|
||||
EXIT_TELEGRAM: 'exittotelegram',
|
||||
MSG_TO_USER: 'sendmsgto',
|
||||
ADMIN: emoji.get('information_desk_person') + ' Admin',
|
||||
AIUTO: '🔮 Help',
|
||||
ALTRO: emoji.get('newspaper') + ' Altro',
|
||||
SETPICPROFILE: '🖼 SetPicProfile',
|
||||
RESETPWD: '🔑 SetResetPwd',
|
||||
// MSG_TO_NAVE: emoji.get('incoming_envelope') + 'Msg_to_Navi',
|
||||
// MSG_NO_7_REQ: emoji.get('incoming_envelope') + 'No 7 Req.',
|
||||
// MSG_NO_9_REQ: emoji.get('incoming_envelope') + 'No 9 Req',
|
||||
// NESSUN_IMBARCO_7REQ: emoji.get('incoming_envelope') + 'No Imbarco (7 Req)',
|
||||
MSG_SI_INVITATI_NO_7REQ_INVITATI: emoji.get('incoming_envelope') +
|
||||
'Inv e NO 7 Req',
|
||||
MSGSTAFF: emoji.get('incoming_envelope') + ' Invia a STAFF',
|
||||
ADMIN: '💁♀️ Admin', // Persona al banco informazioni
|
||||
AIUTO: '🔮 Help', // Cristallo magico
|
||||
ALTRO: '📰 Altro', // Giornale
|
||||
SETPICPROFILE: '🖼 SetPicProfile', // Cornice con foto
|
||||
RESETPWD: '🔑 SetResetPwd', // Chiave
|
||||
MSG_SI_INVITATI_NO_7REQ_INVITATI: '📩Inv e NO 7 Req', // Busta
|
||||
MSGSTAFF: '📩 Invia a STAFF', // Busta
|
||||
MSGAPPARTIENE_CIRCUITI_RIS: 'Invia a Utenti dei Circuiti RIS',
|
||||
MSGPAOLO: emoji.get('incoming_envelope') + ' Invia a SURYA',
|
||||
RESTART_SRV: emoji.get('incoming_envelope') + 'Restart-NodeJs',
|
||||
REBOOT_SRV: emoji.get('incoming_envelope') + 'Reboot-VPS!',
|
||||
EXECSH: emoji.get('incoming_envelope') + 'ExecSH',
|
||||
LOG_SRV: '🖥Logserver.sh',
|
||||
MSGATUTTI: emoji.get('incoming_envelope') + ' Invia a TUTTI',
|
||||
MSGPAOLO: '📩 Invia a SURYA', // Busta
|
||||
RESTART_SRV: '📩Restart-NodeJs', // Busta
|
||||
REBOOT_SRV: '📩Reboot-VPS!', // Busta
|
||||
EXECSH: '📩ExecSH', // Busta
|
||||
LOG_SRV: '🖥Logserver.sh', // Monitor
|
||||
MSGATUTTI: '📩 Invia a TUTTI', // Busta
|
||||
it: {
|
||||
ACCEDI: emo.PERSON + ' Accedi',
|
||||
LAVAGNA: emoji.get('om_symbol') + ' Lavagna',
|
||||
LINK_CONDIVIDERE: emoji.get('link') + ' Link da condividere',
|
||||
ZOOM: emoji.get('information_source') + ' Zoom (Conferenze)',
|
||||
INFO: emoji.get('information_source') + ' Informazioni',
|
||||
ASSISTENZA: emoji.get('open_hands') + ' Le Chat',
|
||||
INDIETRO: emoji.get('back') + ' Indietro',
|
||||
SI: emoji.get('thumbsup') + ' SI',
|
||||
NO: emoji.get('thumbsdown') + ' NO',
|
||||
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Esci dalla Conversazione',
|
||||
ACCEDI: '👤 Accedi', // Persona
|
||||
LAVAGNA: '🕉 Lavagna', // Simbolo Om
|
||||
LINK_CONDIVIDERE: '🔗 Link da condividere', // Link
|
||||
ZOOM: 'ℹ️ Zoom (Conferenze)', // Informazione
|
||||
INFO: 'ℹ️ Informazioni', // Informazione
|
||||
ASSISTENZA: '👐 Le Chat', // Mani aperte
|
||||
INDIETRO: '🔙 Indietro', // Freccia indietro
|
||||
SI: '👍 SI', // Pollice su
|
||||
NO: '👎 NO', // Pollice giù
|
||||
ESCI_DA_CHAT: '📩 Esci dalla Conversazione', // Busta
|
||||
NUOVOSITO: '',
|
||||
},
|
||||
es: {
|
||||
ACCEDI: emo.PERSON + ' Entra',
|
||||
LAVAGNA: emoji.get('om_symbol') + ' Tablero',
|
||||
LINK_CONDIVIDERE: emoji.get('link') + ' Enlaces para compartir',
|
||||
ZOOM: emoji.get('information_source') + ' Zoom (Conferencias)',
|
||||
INFO: emoji.get('information_source') + ' Información',
|
||||
ASSISTENZA: emoji.get('open_hands') + ' Chats',
|
||||
INDIETRO: emoji.get('back') + ' Volver',
|
||||
SI: emoji.get('thumbsup') + ' SÍ',
|
||||
NO: emoji.get('thumbsdown') + ' NO',
|
||||
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Salir de la conversación',
|
||||
ACCEDI: '👤 Entra',
|
||||
LAVAGNA: '🕉 Tablero',
|
||||
LINK_CONDIVIDERE: '🔗 Enlaces para compartir',
|
||||
ZOOM: 'ℹ️ Zoom (Conferencias)',
|
||||
INFO: 'ℹ️ Información',
|
||||
ASSISTENZA: '👐 Chats',
|
||||
INDIETRO: '🔙 Volver',
|
||||
SI: '👍 SÍ',
|
||||
NO: '👎 NO',
|
||||
ESCI_DA_CHAT: '📩 Salir de la conversación',
|
||||
},
|
||||
fr: {
|
||||
ACCEDI: emo.PERSON + ' Entrez',
|
||||
LAVAGNA: emoji.get('om_symbol') + ' Tableau de bord',
|
||||
LINK_CONDIVIDERE: emoji.get('link') + ' Liens à partager',
|
||||
ZOOM: emoji.get('information_source') + ' Zoom (Conférences)',
|
||||
INFO: emoji.get('information_source') + ' Informations',
|
||||
ASSISTENZA: emoji.get('open_hands') + ' Les chats',
|
||||
INDIETRO: emoji.get('back') + ' Retour',
|
||||
SI: emoji.get('thumbsup') + ' OUI',
|
||||
NO: emoji.get('thumbsdown') + ' NON',
|
||||
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Quitter la conversation',
|
||||
ACCEDI: '👤 Entrez',
|
||||
LAVAGNA: '🕉 Tableau de bord',
|
||||
LINK_CONDIVIDERE: '🔗 Liens à partager',
|
||||
ZOOM: 'ℹ️ Zoom (Conférences)',
|
||||
INFO: 'ℹ️ Informations',
|
||||
ASSISTENZA: '👐 Les chats',
|
||||
INDIETRO: '🔙 Retour',
|
||||
SI: '👍 OUI',
|
||||
NO: '👎 NON',
|
||||
ESCI_DA_CHAT: '📩 Quitter la conversation',
|
||||
},
|
||||
si: {
|
||||
ACCEDI: emo.PERSON + ' Prijava',
|
||||
LAVAGNA: emoji.get('om_symbol') + ' Tabla',
|
||||
LINK_CONDIVIDERE: emoji.get('link') + ' Link za vpis oseb',
|
||||
ZOOM: emoji.get('information_source') + ' Zoom (Konference)',
|
||||
INFO: emoji.get('information_source') + ' Informacije',
|
||||
ASSISTENZA: emoji.get('open_hands') + ' jev klepet',
|
||||
INDIETRO: emoji.get('back') + ' Nazaj',
|
||||
SI: emoji.get('thumbsup') + ' DA',
|
||||
NO: emoji.get('thumbsdown') + ' NE',
|
||||
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Zaprite pogovor',
|
||||
ACCEDI: '👤 Prijava',
|
||||
LAVAGNA: '🕉 Tabla',
|
||||
LINK_CONDIVIDERE: '🔗 Link za vpis oseb',
|
||||
ZOOM: 'ℹ️ Zoom (Konference)',
|
||||
INFO: 'ℹ️ Informacije',
|
||||
ASSISTENZA: '👐 jev klepet',
|
||||
INDIETRO: '🔙 Nazaj',
|
||||
SI: '👍 DA',
|
||||
NO: '👎 NE',
|
||||
ESCI_DA_CHAT: '📩 Zaprite pogovor',
|
||||
},
|
||||
pt: {
|
||||
ACCEDI: emo.PERSON + ' Entre',
|
||||
LAVAGNA: emoji.get('om_symbol') + ' Tablero',
|
||||
LINK_CONDIVIDERE: emoji.get('link') + ' Links para compartilhar',
|
||||
ZOOM: emoji.get('information_source') + ' Zoom (Conferências)',
|
||||
INFO: emoji.get('information_source') + ' Informações',
|
||||
ASSISTENZA: emoji.get('open_hands') + ' Chats',
|
||||
INDIETRO: emoji.get('back') + ' Voltar',
|
||||
SI: emoji.get('thumbsup') + ' SIM',
|
||||
NO: emoji.get('thumbsdown') + ' NÃO',
|
||||
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Sair da Conversa',
|
||||
ACCEDI: '👤 Entre',
|
||||
LAVAGNA: '🕉 Tablero',
|
||||
LINK_CONDIVIDERE: '🔗 Links para compartilhar',
|
||||
ZOOM: 'ℹ️ Zoom (Conferências)',
|
||||
INFO: 'ℹ️ Informações',
|
||||
ASSISTENZA: '👐 Chats',
|
||||
INDIETRO: '🔙 Voltar',
|
||||
SI: '👍 SIM',
|
||||
NO: '👎 NÃO',
|
||||
ESCI_DA_CHAT: '📩 Sair da Conversa',
|
||||
},
|
||||
enUs: {
|
||||
ACCEDI: emo.PERSON + ' Enter',
|
||||
LAVAGNA: emoji.get('om_symbol') + ' DashBoard',
|
||||
LINK_CONDIVIDERE: emoji.get('link') + ' Link to Share',
|
||||
ZOOM: emoji.get('information_source') + ' Zoom (Conference)',
|
||||
INFO: emoji.get('information_source') + ' Info',
|
||||
ASSISTENZA: emoji.get('open_hands') + ' Chats',
|
||||
INDIETRO: emoji.get('back') + ' Back',
|
||||
SI: emoji.get('thumbsup') + ' YES',
|
||||
NO: emoji.get('thumbsdown') + ' NO',
|
||||
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Exit to the Conversation',
|
||||
ACCEDI: '👤 Enter',
|
||||
LAVAGNA: '🕉 DashBoard',
|
||||
LINK_CONDIVIDERE: '🔗 Link to Share',
|
||||
ZOOM: 'ℹ️ Zoom (Conference)',
|
||||
INFO: 'ℹ️ Info',
|
||||
ASSISTENZA: '👐 Chats',
|
||||
INDIETRO: '🔙 Back',
|
||||
SI: '👍 YES',
|
||||
NO: '👎 NO',
|
||||
ESCI_DA_CHAT: '📩 Exit to the Conversation',
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
const CONTA_SOLO = 'contasolo';
|
||||
@@ -483,8 +474,8 @@ const StatusMSGALL = {
|
||||
};
|
||||
|
||||
const txt = {
|
||||
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Scegli una voce di menu:' +
|
||||
emoji.get('dizzy'),
|
||||
MSG_SCEGLI_MENU: '💫' + ' Scegli una voce di menu:' +
|
||||
'💫',
|
||||
MSG_ASK_USERNAME_BO: 'Scrivete nel messaggio l\'username (SENZA SPAZI) o la email con cui vi siete registrati sul sito di %s:',
|
||||
MSG_ASK_USERNAME_INVITANTE: 'Scrivi nel messaggio <b>l\'USERNAME TELEGRAM</b> di chi ti ha INVITATO',
|
||||
MSG_NEW_REG: '<br><br>⁉️🙈 Per aiuto scrivi sulla <a href="https://t.me/riso_gruppo">Chat RISO</a><br>oppure direttamente a Surya (@surya1977) ☀️.',
|
||||
@@ -516,9 +507,9 @@ const txt = {
|
||||
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !',
|
||||
MSG_ISCRITTO_CONACREIS: emo.FIRE + '[%s] Si è appena Iscritto al Conacreis "%s"',
|
||||
MSG_ISCRITTO_ARCADEI: emo.FIRE + '[%s] Si è appena Iscritto ad Arcadei "%s"',
|
||||
MSG_MSG_SENT: emoji.get('envelope') + ' Messaggi Inviati !',
|
||||
MSG_MSG_TOSENT: emoji.get('envelope') + ' Messaggi da Inviare',
|
||||
MSG_MSG_INCORSO: emoji.get('envelope') + ' messaggi in corso... Inviati attualmente',
|
||||
MSG_MSG_SENT: '📨' + ' Messaggi Inviati !',
|
||||
MSG_MSG_TOSENT: '📨' + ' Messaggi da Inviare',
|
||||
MSG_MSG_INCORSO: '📨' + ' messaggi in corso... Inviati attualmente',
|
||||
MSG_SET_USERNAME_TELEGRAM: '[Prima di continuare con la registrazione in RISO.APP]\n' +
|
||||
'Segui questi passi per <b>IMPOSTARE UN USERNAME IN TELEGRAM</b>: \n\n' +
|
||||
'1. premi sull\'icona con <b>3 linee orizzontali</b>, in alto a sinistra (sull\'iPhone si chiama "Impostazioni").\n' +
|
||||
@@ -535,8 +526,8 @@ const txt = {
|
||||
};
|
||||
|
||||
const txt_es = {
|
||||
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Elija un elemento del menú:' +
|
||||
emoji.get('dizzy'),
|
||||
MSG_SCEGLI_MENU: '💫' + ' Elija un elemento del menú:' +
|
||||
'💫',
|
||||
MSG_ASK_USERNAME_BO: 'Escriba en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio de %s:',
|
||||
MSG_ERRORE_USERNAME: '¡Atención! Debes introducir sólo el nombre de usuario (40 caracteres como máximo)',
|
||||
MSG_ERRORE_USERNAME_NOT_FOUND: 'Para completar la verificación del telegrama BOT, ahora debe escribir en el mensaje el nombre de usuario o el correo electrónico con el que se registró en el sitio.:',
|
||||
@@ -561,15 +552,15 @@ const txt_es = {
|
||||
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
|
||||
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
|
||||
'🚫 %s Non è stato Ammesso !',
|
||||
MSG_MSG_SENT: emoji.get('envelope') + ' Mensajes enviados !',
|
||||
MSG_MSG_TOSENT: emoji.get('envelope') + ' Mensajes a enviar',
|
||||
MSG_MSG_INCORSO: emoji.get('envelope') +
|
||||
MSG_MSG_SENT: '📨' + ' Mensajes enviados !',
|
||||
MSG_MSG_TOSENT: '📨' + ' Mensajes a enviar',
|
||||
MSG_MSG_INCORSO: '📨' +
|
||||
' mensajes en progreso... Enviado actualmente',
|
||||
};
|
||||
|
||||
const txt_fr = {
|
||||
MSG_SCEGLI_MENU: emoji.get('dizzy') + 'Choisissez un élément de menu:' +
|
||||
emoji.get('dizzy'),
|
||||
MSG_SCEGLI_MENU: '💫' + 'Choisissez un élément de menu:' +
|
||||
'💫',
|
||||
MSG_ASK_USERNAME_BO: 'Écrivez dans le message l\'username ou l\'e-mail avec lequel vous vous êtes enregistré sur le site de %s: ',
|
||||
MSG_ERRORE_USERNAME: 'Attention! Vous devez insérer seulement l’username (40 caractères maximum)',
|
||||
MSG_ERRORE_USERNAME_NOT_FOUND: 'Pour Compléter la Vérification Telegram BOT, vous devez maintenant écrire dans le message ci-dessous l\'Username ou l\'adresse e-mail avec lequel vous vous êtes inscrit sur le site: ',
|
||||
@@ -594,14 +585,14 @@ const txt_fr = {
|
||||
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
|
||||
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
|
||||
'🚫 %s Non è stato Ammesso !',
|
||||
MSG_MSG_SENT: emoji.get('envelope') + ' Messages envoyés !',
|
||||
MSG_MSG_TOSENT: emoji.get('envelope') + ' Messages à envoyer',
|
||||
MSG_MSG_INCORSO: emoji.get('envelope') +
|
||||
MSG_MSG_SENT: '📨' + ' Messages envoyés !',
|
||||
MSG_MSG_TOSENT: '📨' + ' Messages à envoyer',
|
||||
MSG_MSG_INCORSO: '📨' +
|
||||
' messages en cours... Actuellement envoyé',
|
||||
};
|
||||
|
||||
const txt_si = {
|
||||
MSG_SCEGLI_MENU: emoji.get('dizzy') + 'Izbirni meni:' + emoji.get('dizzy'),
|
||||
MSG_SCEGLI_MENU: '💫' + 'Izbirni meni:' + '💫',
|
||||
MSG_ASK_USERNAME_BO: 'Vpiši svoje uporabniško ime in e-naslov s katerimi si se registriral na spletni strani %s: ',
|
||||
MSG_ERRORE_USERNAME: 'Pozor! Vpiši samo uporabniško ime (40 znakov) maksimalno',
|
||||
MSG_ERRORE_USERNAME_NOT_FOUND: 'Ponovno preverite telegram BOT Uporabniško ime ali e-poštno sporočilo, s katerim ste registrirali na spletni strani: ',
|
||||
@@ -628,8 +619,8 @@ const txt_si = {
|
||||
};
|
||||
|
||||
const txt_en = {
|
||||
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Choose a menu item:' +
|
||||
emoji.get('dizzy'),
|
||||
MSG_SCEGLI_MENU: '💫' + ' Choose a menu item:' +
|
||||
'💫',
|
||||
MSG_ASK_USERNAME_BO: 'Write in the message the username or email with which you registered on the site of %s:',
|
||||
MSG_ERRORE_USERNAME: 'Attention! You must enter only the username (40 characters maximum)',
|
||||
MSG_ERRORE_USERNAME_NOT_FOUND: 'To complete the Telegram BOT Verification, you must now write below in the message the Username OR the email with which you registered on the website:',
|
||||
@@ -655,15 +646,15 @@ const txt_en = {
|
||||
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
|
||||
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
|
||||
'🚫 %s Non è stato Ammesso !',
|
||||
MSG_MSG_SENT: emoji.get('envelope') + ' Sent Messages !',
|
||||
MSG_MSG_TOSENT: emoji.get('envelope') + ' Messages to Send',
|
||||
MSG_MSG_INCORSO: emoji.get('envelope') +
|
||||
MSG_MSG_SENT: '📨' + ' Sent Messages !',
|
||||
MSG_MSG_TOSENT: '📨' + ' Messages to Send',
|
||||
MSG_MSG_INCORSO: '📨' +
|
||||
' messages in progress... Currently sent',
|
||||
};
|
||||
|
||||
const txt_pt = {
|
||||
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Escolha um item do menu:' +
|
||||
emoji.get('dizzy'),
|
||||
MSG_SCEGLI_MENU: '💫' + ' Escolha um item do menu:' +
|
||||
'💫',
|
||||
MSG_ASK_USERNAME_BO: 'Escreva na mensagem o nome de usuário ou e-mail com o qual se registrou no site de %s:',
|
||||
MSG_ERRORE_USERNAME: 'Atenção! Você deve inserir apenas o nome de usuário (40 caracteres no máximo)',
|
||||
MSG_ERRORE_USERNAME_NOT_FOUND: 'Para completar a Verificação do Telegrama BOT, você deve agora escrever abaixo na mensagem o Nome de Usuário OU o e-mail com o qual você se registrou no site:',
|
||||
@@ -688,9 +679,9 @@ const txt_pt = {
|
||||
'🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
|
||||
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
|
||||
'🚫 %s Non è stato Ammesso !',
|
||||
MSG_MSG_SENT: emoji.get('envelope') + ' Mensagens Enviadas !',
|
||||
MSG_MSG_TOSENT: emoji.get('envelope') + ' Mensagens a enviar',
|
||||
MSG_MSG_INCORSO: emoji.get('envelope') +
|
||||
MSG_MSG_SENT: '📨' + ' Mensagens Enviadas !',
|
||||
MSG_MSG_TOSENT: '📨' + ' Mensagens a enviar',
|
||||
MSG_MSG_INCORSO: '📨' +
|
||||
' mensagens em progresso... Actualmente enviado',
|
||||
};
|
||||
|
||||
@@ -1764,7 +1755,7 @@ class Telegram {
|
||||
|
||||
risp += '!';
|
||||
} else if (MsgBot.COME_STAI.includes(testo.replace('?', ''))) {
|
||||
risp = 'Io Benone Grazie! ' + emoji.get('heartbeat') + ' E tu?';
|
||||
risp = 'Io Benone Grazie! ' + '💓' + ' E tu?';
|
||||
rec.statusmsg = Status.WAITFOR_RISPOSTA;
|
||||
rec.msgcodeprec = MsgBot.COME_STAI;
|
||||
} else if (MsgBot.CHI_SONO_IO.includes(testo.replace('?', ''))) {
|
||||
@@ -2284,7 +2275,7 @@ class Telegram {
|
||||
|
||||
let index = 1;
|
||||
downline.downline.forEach((user) => {
|
||||
mystr += emoji.get('star-struck') + ` ${index}°: `;
|
||||
mystr += '🌠' + ` ${index}°: `;
|
||||
mystr += (user.qualified) ? emo.CHECK_VERDE : emo.CROSS_ROSSA;
|
||||
mystr += `${user.name} ${user.surname} (${user.username})\n`;
|
||||
index++;
|
||||
@@ -4647,6 +4638,7 @@ if (true) {
|
||||
}
|
||||
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_CIRCUIT) {
|
||||
|
||||
console.log(' CLICK per Aggiungere ', data.username, 'nel circuito', circuit?.name);
|
||||
if (circuit) {
|
||||
// Aggiungilo nel Circuito
|
||||
cmd = shared_consts.CIRCUITCMD.SET;
|
||||
|
||||
@@ -56,8 +56,8 @@ const readline = require('readline');
|
||||
|
||||
// Code goes here
|
||||
const keySize = 256;
|
||||
const ivSize = 128;
|
||||
const iterations = 100;
|
||||
// const ivSize = 128;
|
||||
const iterations = 1000;
|
||||
|
||||
if (!!process.env.GCM_API_KEY && process.env.GCM_API_KEY !== '') {
|
||||
webpush.setGCMAPIKey(process.env.GCM_API_KEY);
|
||||
@@ -433,7 +433,8 @@ class ImageDownloader {
|
||||
initialDelay = 1000, // Ritardo iniziale
|
||||
maxDelay = 10000, // Ritardo massimo
|
||||
timeout = 30000, // Timeout della richiesta
|
||||
validateContentType = true // Verifica del tipo di contenuto
|
||||
validateContentType = true, // Verifica del tipo di contenuto
|
||||
nomefileoriginale = true,
|
||||
} = options;
|
||||
|
||||
// Funzione per il backoff esponenziale
|
||||
@@ -448,7 +449,6 @@ class ImageDownloader {
|
||||
fs.unlinkSync(filepath);
|
||||
}
|
||||
|
||||
const writer = fs.createWriteStream(filepath);
|
||||
if (attempt > 1)
|
||||
console.log(`📥 Tentativo ${attempt}/${maxRetries} - Scaricamento: ${url}`);
|
||||
|
||||
@@ -487,6 +487,28 @@ class ImageDownloader {
|
||||
downloadedBytes += chunk.length;
|
||||
});
|
||||
|
||||
let writer = null;
|
||||
|
||||
if (nomefileoriginale) {
|
||||
// Estrai il nome del file dall'URL o da Content-Disposition
|
||||
//let fileName = this.extractFileNameFromUrl(url) || this.extractFileNameFromHeaders(response.headers);
|
||||
let fileName = path.basename(response.data.responseUrl);
|
||||
|
||||
// Se il nome del file non è specificato, genera un nome predefinito
|
||||
if (!fileName) {
|
||||
fileName = `image_${Date.now()}.jpg`;
|
||||
}
|
||||
|
||||
// Genera il percorso completo del file
|
||||
const fullPath = path.join(path.dirname(filepath), fileName);
|
||||
|
||||
filepath = fullPath;
|
||||
|
||||
}
|
||||
|
||||
// Scrivi il file sul disco
|
||||
writer = fs.createWriteStream(filepath);
|
||||
|
||||
response.data.pipe(writer);
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
@@ -501,8 +523,11 @@ class ImageDownloader {
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
console.info(`✅ Immagine scaricata con successo in ${filepath}`);
|
||||
return true;
|
||||
|
||||
|
||||
return { ris: true, filepath };
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ Errore nel tentativo ${attempt}/${maxRetries}:`, error.message);
|
||||
@@ -512,9 +537,14 @@ class ImageDownloader {
|
||||
fs.unlinkSync(filepath);
|
||||
}
|
||||
|
||||
// se in error.message c'è '404' allora esci e ritorna code: 404
|
||||
if (error.message.includes('404')) {
|
||||
return { ris: false, code: 404 };
|
||||
}
|
||||
|
||||
if (attempt === maxRetries) {
|
||||
console.error(`Download fallito dopo ${maxRetries} tentativi: ${error.message}`);
|
||||
return false;
|
||||
return { ris: false };
|
||||
}
|
||||
|
||||
const delay = getDelay(attempt);
|
||||
@@ -523,6 +553,24 @@ class ImageDownloader {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Funzione per estrarre il nome del file dall'URL
|
||||
extractFileNameFromUrl(url) {
|
||||
const match = url.match(/\/([^/?#]+)(?:[?#]|$)/);
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
}
|
||||
|
||||
// Funzione per estrarre il nome del file da Content-Disposition
|
||||
extractFileNameFromHeaders(headers) {
|
||||
const contentDisposition = headers['content-disposition'];
|
||||
if (contentDisposition) {
|
||||
const match = contentDisposition.match(/filename="([^"]+)"/);
|
||||
if (match) {
|
||||
return decodeURIComponent(match[1]);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -542,6 +590,7 @@ module.exports = {
|
||||
RISO: '13',
|
||||
FIOREDELLAVITA: '15',
|
||||
PIUCHEBUONO: '17',
|
||||
MACRO: '18',
|
||||
|
||||
IDAPP_BOTONGROUP: '1000',
|
||||
|
||||
@@ -3380,7 +3429,7 @@ module.exports = {
|
||||
try {
|
||||
console.time(name);
|
||||
} catch (e) {
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -3861,47 +3910,79 @@ module.exports = {
|
||||
},
|
||||
|
||||
encrypt(msg, pass) {
|
||||
var salt = CryptoJS.lib.WordArray.random(128 / 8);
|
||||
try {
|
||||
// Genera salt e IV casuali
|
||||
const salt = CryptoJS.lib.WordArray.random(128 / 8); // 16 byte
|
||||
const iv = CryptoJS.lib.WordArray.random(128 / 8); // 16 byte
|
||||
|
||||
var key = CryptoJS.PBKDF2(pass, salt, {
|
||||
keySize: keySize / 32,
|
||||
iterations: iterations,
|
||||
});
|
||||
// Deriva la chiave usando PBKDF2
|
||||
const key = CryptoJS.PBKDF2(pass, salt, {
|
||||
keySize: keySize / 32,
|
||||
iterations: iterations,
|
||||
});
|
||||
|
||||
var iv = CryptoJS.lib.WordArray.random(128 / 8);
|
||||
// Critta il messaggio
|
||||
const encrypted = CryptoJS.AES.encrypt(msg, key, {
|
||||
iv: iv,
|
||||
padding: CryptoJS.pad.Pkcs7,
|
||||
mode: CryptoJS.mode.CBC,
|
||||
});
|
||||
|
||||
var encrypted = CryptoJS.AES.encrypt(msg, key, {
|
||||
iv: iv,
|
||||
padding: CryptoJS.pad.Pkcs7,
|
||||
mode: CryptoJS.mode.CBC,
|
||||
|
||||
});
|
||||
|
||||
// salt, iv will be hex 32 in length
|
||||
// append them to the ciphertext for use in decryption
|
||||
var transitmessage = salt.toString() + iv.toString() + encrypted.toString();
|
||||
return transitmessage;
|
||||
// Concatena salt, IV e ciphertext con un delimitatore
|
||||
const transitmessage = `${salt.toString()}|${iv.toString()}|${encrypted.toString()}`;
|
||||
return transitmessage;
|
||||
} catch (error) {
|
||||
console.error('❌❌❌ Errore durante la crittazione:', error.message);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
decrypt(transitmessage, pass) {
|
||||
var salt = CryptoJS.enc.Hex.parse(transitmessage.substr(0, 32));
|
||||
var iv = CryptoJS.enc.Hex.parse(transitmessage.substr(32, 32));
|
||||
var encrypted = transitmessage.substring(64);
|
||||
try {
|
||||
let saltHex, ivHex, encrypted;
|
||||
|
||||
var key = CryptoJS.PBKDF2(pass, salt, {
|
||||
keySize: keySize / 32,
|
||||
iterations: iterations,
|
||||
});
|
||||
// Controlla se il messaggio è nel nuovo formato (con delimitatore)
|
||||
if (transitmessage.includes('|')) {
|
||||
const parts = transitmessage.split('|');
|
||||
if (parts.length !== 3) {
|
||||
throw new Error('❌❌❌ Formato del messaggio non valido.');
|
||||
}
|
||||
[saltHex, ivHex, encrypted] = parts;
|
||||
} else {
|
||||
// Vecchio formato: salt (32 caratteri), IV (32 caratteri), ciphertext (resto)
|
||||
saltHex = transitmessage.substr(0, 32);
|
||||
ivHex = transitmessage.substr(32, 32);
|
||||
encrypted = transitmessage.substring(64);
|
||||
}
|
||||
|
||||
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
|
||||
iv: iv,
|
||||
padding: CryptoJS.pad.Pkcs7,
|
||||
mode: CryptoJS.mode.CBC,
|
||||
// Converte salt e IV da esadecimale
|
||||
const salt = CryptoJS.enc.Hex.parse(saltHex);
|
||||
const iv = CryptoJS.enc.Hex.parse(ivHex);
|
||||
|
||||
});
|
||||
return decrypted;
|
||||
// Deriva la chiave usando PBKDF2
|
||||
const key = CryptoJS.PBKDF2(pass, salt, {
|
||||
keySize: keySize / 32,
|
||||
iterations: iterations,
|
||||
});
|
||||
|
||||
// Decritta il messaggio
|
||||
const decrypted = CryptoJS.AES.decrypt(encrypted, key, {
|
||||
iv: iv,
|
||||
padding: CryptoJS.pad.Pkcs7,
|
||||
mode: CryptoJS.mode.CBC,
|
||||
});
|
||||
|
||||
// Restituisci il messaggio originale in formato UTF-8
|
||||
let ris = decrypted.toString(CryptoJS.enc.Utf8);
|
||||
|
||||
// console.log('RIS', ris);
|
||||
|
||||
return ris;
|
||||
} catch (error) {
|
||||
console.error('❌❌❌ Errore durante la decrittazione:', error.message);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
cryptdata(mydata) {
|
||||
if (mydata === '')
|
||||
return '';
|
||||
@@ -3911,13 +3992,17 @@ module.exports = {
|
||||
},
|
||||
|
||||
decryptdata(mydatacrypted) {
|
||||
if (mydatacrypted === '' || mydatacrypted === undefined)
|
||||
if (!mydatacrypted) return '';
|
||||
|
||||
try {
|
||||
// console.log('SECRK', process.env.SECRK);
|
||||
const decr = this.decrypt(mydatacrypted, process.env.SECRK);
|
||||
// console.log('decr:', mydatacrypted, '->', decr);
|
||||
return decr;
|
||||
} catch (error) {
|
||||
console.error('❌❌❌❌❌ Decryption error:', error);
|
||||
return '';
|
||||
// Decrypt
|
||||
// const bytes = CryptoJS.AES.decrypt(mydatacrypted.toString(), process.env.SECRK);
|
||||
// return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
|
||||
return this.decrypt(mydatacrypted, process.env.SECRK).
|
||||
toString(CryptoJS.enc.Utf8);
|
||||
}
|
||||
},
|
||||
|
||||
BoolToInt(mybool) {
|
||||
@@ -5831,7 +5916,7 @@ module.exports = {
|
||||
}
|
||||
if (mov.groupfrom) {
|
||||
userfrom += mov.groupfrom.groupname
|
||||
tipocontofrom = shared_consts.AccountType.COLLECTIVE_ACCOUNT
|
||||
tipocontofrom = shared_consts.AccountType.CONTO_DI_GRUPPO
|
||||
}
|
||||
if (mov.userfrom) {
|
||||
userfrom += mov.userfrom.username
|
||||
@@ -5844,7 +5929,7 @@ module.exports = {
|
||||
}
|
||||
if (mov.groupto) {
|
||||
userto += mov.groupto.groupname
|
||||
tipocontoto = shared_consts.AccountType.COLLECTIVE_ACCOUNT
|
||||
tipocontoto = shared_consts.AccountType.CONTO_DI_GRUPPO
|
||||
}
|
||||
if (mov.userto) {
|
||||
userto += mov.userto.username
|
||||
@@ -5982,8 +6067,233 @@ module.exports = {
|
||||
// Funzione per implementare il ritardo tra i tentativi
|
||||
sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Converte una data in formato italiano GG/MM/YYYY in un oggetto Date e restituisce il timestamp.
|
||||
* @param {string} dateString - La data in formato GG/MM/YYYY.
|
||||
* @returns {Object} - Un oggetto contenente la data (Date) e il timestamp (number).
|
||||
* Restituisce null se la data non è valida.
|
||||
*/
|
||||
convertiDataItaliana(dateString) {
|
||||
// Verifica che la data sia una stringa valida
|
||||
if (!dateString || typeof dateString !== 'string') {
|
||||
console.error("Input non valido: la data deve essere una stringa.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Rimuovi eventuali spazi bianchi e dividi la data in GG, MM, YYYY
|
||||
const [giorno, mese, anno] = dateString.trim().split('/').map(Number);
|
||||
|
||||
// Controlla che i valori siano stati estratti correttamente
|
||||
if (isNaN(giorno) || isNaN(mese) || isNaN(anno)) {
|
||||
console.error("Formato data non valido:", dateString);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Crea un oggetto Date (mese parte da 0 in JavaScript)
|
||||
const dateObj = new Date(anno, mese - 1, giorno);
|
||||
|
||||
// Verifica che la data sia valida
|
||||
if (isNaN(dateObj.getTime())) {
|
||||
console.error("Data non valida:", dateString);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Restituisci l'oggetto con la data e il timestamp
|
||||
return {
|
||||
date: dateObj,
|
||||
timestamp: dateObj.getTime()
|
||||
};
|
||||
},
|
||||
|
||||
getDateFromISOString(mydate) {
|
||||
const mydate2 = new Date(mydate)
|
||||
return mydate2
|
||||
},
|
||||
|
||||
async downloadImgIfMissing(productInfo) {
|
||||
|
||||
const ProductInfo = require('../models/productInfo');
|
||||
|
||||
try {
|
||||
if (this.sulServer()) {
|
||||
dirmain = '';
|
||||
} else {
|
||||
dirmain = server_constants.DIR_PUBLIC_LOCALE;
|
||||
}
|
||||
|
||||
const vecchiomodo = false;
|
||||
|
||||
if (productInfo.image_link && vecchiomodo) {
|
||||
|
||||
const relativeimg = productInfo.image_link.split('/').pop();
|
||||
const img = this.getdirByIdApp(productInfo.idapp) + dirmain +
|
||||
server_constants.DIR_UPLOAD + '/products/' + productInfo.image_link.split('/').pop();
|
||||
const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
|
||||
|
||||
let scaricaimg = !productInfo.imagefile || !fs.existsSync(savePath);
|
||||
|
||||
if (!productInfo.imagefile && fs.existsSync(savePath)) {
|
||||
// esiste il file, ma sul DB non è corretto
|
||||
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
|
||||
|
||||
if (stats.size > 0) { // Controlla se la dimensione del file è maggiore di zero
|
||||
// Esiste il file ed è non vuoto, ma sul DB non è corretto
|
||||
productInfo.imagefile = relativeimg;
|
||||
return { prodInfo: productInfo, aggiornatoimg: true };
|
||||
} else {
|
||||
scaricaimg = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (productInfo.imagefile && fs.existsSync(savePath)) {
|
||||
// esiste il file, ma sul DB non è corretto
|
||||
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
|
||||
|
||||
if (stats.size <= 0) { // Controlla se la dimensione del file è maggiore di zero
|
||||
scaricaimg = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (scaricaimg && vecchiomodo) {
|
||||
// Download image from the URL productInfo.image_link
|
||||
productInfo.imagefile = relativeimg;
|
||||
|
||||
const downloader = new ImageDownloader();
|
||||
|
||||
const aggiornatoimg = await downloader.downloadImage(productInfo.image_link, savePath,
|
||||
{
|
||||
maxRetries: 1,
|
||||
initialDelay: 300,
|
||||
timeout: 15000,
|
||||
}).then(result => {
|
||||
if (result) {
|
||||
// console.log('Download completato con successo!');
|
||||
} else {
|
||||
console.log('Download non riuscito.');
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
});
|
||||
return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris };
|
||||
}
|
||||
}
|
||||
|
||||
let fileesistente = false;
|
||||
if (productInfo.imagefile) {
|
||||
// controlla se esiste il file
|
||||
const img = this.getdirByIdApp(productInfo.idapp) + dirmain +
|
||||
server_constants.DIR_UPLOAD + '/products/' + productInfo.imagefile.split('/').pop();
|
||||
const filecompleto = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
|
||||
|
||||
// Se non esiste lo scarico !
|
||||
fileesistente = fs.existsSync(filecompleto);
|
||||
}
|
||||
|
||||
if (!vecchiomodo && (!productInfo.image_link || !fileesistente)) {
|
||||
|
||||
let scarica_da_sito = !productInfo.imagefile;
|
||||
|
||||
if (!scarica_da_sito && productInfo.imagefile) {
|
||||
scarica_da_sito = !fileesistente; // Se non esiste lo scarico !
|
||||
}
|
||||
|
||||
if (scarica_da_sito && !productInfo.image_not_found) {
|
||||
// date and time
|
||||
productInfo.imagefile = 'img_' + new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
|
||||
const img = this.getdirByIdApp(productInfo.idapp) + dirmain +
|
||||
server_constants.DIR_UPLOAD + '/products/' + productInfo.imagefile.split('/').pop();
|
||||
let savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
|
||||
|
||||
|
||||
let link = 'https://www.gruppomacro.com/copertine.php?id_gm=' + productInfo.sku
|
||||
|
||||
const downloader = new ImageDownloader();
|
||||
|
||||
|
||||
let aggiornatoimg;
|
||||
try {
|
||||
aggiornatoimg = await downloader.downloadImage(link, savePath,
|
||||
{
|
||||
maxRetries: 1,
|
||||
initialDelay: 300,
|
||||
timeout: 15000,
|
||||
nomefileoriginale: true,
|
||||
});
|
||||
} catch (e) {
|
||||
aggiornatoimg = { ris: false };
|
||||
}
|
||||
if (aggiornatoimg?.code === 404) {
|
||||
// non trovato quindi la prossima volta non richiederlo
|
||||
await ProductInfo.setImgNotFound(productInfo._id);
|
||||
}
|
||||
|
||||
|
||||
if (aggiornatoimg?.filepath) {
|
||||
const filenamebase = path.basename(aggiornatoimg.filepath);
|
||||
// const img = '/upload/products/' + filenamebase;
|
||||
productInfo.imagefile = filenamebase;
|
||||
}
|
||||
|
||||
return { prodInfo: productInfo, aggiornatoimg: aggiornatoimg.ris };
|
||||
} else {
|
||||
return { prodInfo: null, aggiornatoimg: false };
|
||||
}
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error('downloadImgIfMissing', e.message);
|
||||
}
|
||||
|
||||
return { prodInfo: null, aggiornatoimg: false };
|
||||
|
||||
},
|
||||
|
||||
removeAccents(mystr) {
|
||||
if (!mystr) return mystr;
|
||||
|
||||
const accentsMap = new Map([
|
||||
['á', 'a'], ['à', 'a'], ['ã', 'a'], ['ä', 'a'], ['â', 'a'],
|
||||
['é', 'e'], ['è', 'e'], ['ë', 'e'], ['ê', 'e'],
|
||||
['í', 'i'], ['ì', 'i'], ['ï', 'i'], ['î', 'i'],
|
||||
['ó', 'o'], ['ò', 'o'], ['ö', 'o'], ['ô', 'o'], ['õ', 'o'],
|
||||
['ú', 'u'], ['ù', 'u'], ['ü', 'u'], ['û', 'u'],
|
||||
['ç', 'c'], ['ñ', 'n'],
|
||||
]);
|
||||
|
||||
return Array.from(mystr).map(char => accentsMap.get(char) || char).join('');
|
||||
},
|
||||
|
||||
getDateYYYYMMDD_Today() {
|
||||
// Ottieni la data attuale nel formato YYYY-MM-DD
|
||||
const today = new Date();
|
||||
const formattedDate = today.toISOString().split('T')[0]; // Format YYYY-MM-DD
|
||||
return formattedDate
|
||||
},
|
||||
|
||||
|
||||
convertFullFileNameToURL(idapp, fullfilename) {
|
||||
const mydir = this.getdirByIdApp(idapp);
|
||||
const myhost = this.getHostByIdApp(idapp);
|
||||
|
||||
// ++ remove mydir from fullfilename and add myhost to generate a URL
|
||||
const url = fullfilename.replace(mydir, '').replace(/\\/g, '/'); // Replace backslashes with slashes
|
||||
const myurl = myhost + '/' + url;
|
||||
|
||||
console.log('myurl', myurl);
|
||||
return myurl;
|
||||
},
|
||||
|
||||
removePathDirByFileName(idapp, fullfilename) {
|
||||
const mydir = this.getdirByIdApp(idapp);
|
||||
|
||||
// ++ remove mydir from fullfilename and add myhost to generate a URL
|
||||
const filename = fullfilename.replace(mydir, '').replace(/\\/g, '/'); // Replace backslashes with slashes
|
||||
return filename;
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
@@ -47,12 +47,14 @@ const Pickup = require('../models/pickup');
|
||||
const { Newstosent } = require('../models/newstosent');
|
||||
const { MyPage } = require('../models/mypage');
|
||||
const { MyElem } = require('../models/myelem');
|
||||
const { Cron } = require('../models/cron');
|
||||
const { MyScheda } = require('../models/myscheda');
|
||||
const { MyBot } = require('../models/bot');
|
||||
const { CfgServer } = require('../models/cfgserver');
|
||||
const { CalZoom } = require('../models/calzoom');
|
||||
const { Gallery } = require('../models/gallery');
|
||||
const { TemplEmail } = require('../models/templemail');
|
||||
const { DestNewsletter } = require('../models/destnewsletter');
|
||||
const { OpzEmail } = require('../models/opzemail');
|
||||
const { MailingList } = require('../models/mailinglist');
|
||||
const { Settings } = require('../models/settings');
|
||||
@@ -76,6 +78,8 @@ const Collana = require('../models/collana');
|
||||
const CatAI = require('../models/catai');
|
||||
const { QueryAI } = require('../models/queryai');
|
||||
const SubCatProd = require('../models/subcatprod');
|
||||
const T_Web_StatiProdotto = require('../models/t_web_statiprodotto');
|
||||
const T_Web_Tipologie = require('../models/t_web_tipologie');
|
||||
const { Category } = require('../models/category');
|
||||
const ShareWithUs = require('../models/sharewithus');
|
||||
const Site = require('../models/site');
|
||||
@@ -143,6 +147,10 @@ module.exports = {
|
||||
mytable = QueryAI;
|
||||
else if (tablename === 'subcatprods')
|
||||
mytable = SubCatProd;
|
||||
else if (tablename === 't_web_statiprodottos')
|
||||
mytable = T_Web_StatiProdotto;
|
||||
else if (tablename === 't_web_tipologies')
|
||||
mytable = T_Web_Tipologie;
|
||||
else if (tablename === 'sharewithus')
|
||||
mytable = ShareWithUs;
|
||||
else if (tablename === 'sites')
|
||||
@@ -191,6 +199,8 @@ module.exports = {
|
||||
mytable = MyPage;
|
||||
else if (tablename === 'myelems')
|
||||
mytable = MyElem;
|
||||
else if (tablename === 'crons')
|
||||
mytable = Cron;
|
||||
else if (tablename === 'myschedas')
|
||||
mytable = MyScheda;
|
||||
else if (tablename === 'bots')
|
||||
@@ -201,6 +211,8 @@ module.exports = {
|
||||
mytable = CalZoom;
|
||||
else if (tablename === 'templemail')
|
||||
mytable = TemplEmail;
|
||||
else if (tablename === 'destnewsletter')
|
||||
mytable = DestNewsletter;
|
||||
else if (tablename === 'opzemail')
|
||||
mytable = OpzEmail;
|
||||
else if (tablename === 'settings')
|
||||
|
||||
@@ -101,6 +101,7 @@ module.exports = Object.freeze({
|
||||
PREFIX_IMG_SMALL: 'sm_',
|
||||
|
||||
DIR_UPLOAD: '/upload', //'/upload'
|
||||
DIR_PUBLIC_LOCALE: '/public',
|
||||
|
||||
Privacy: {
|
||||
all: 'all',
|
||||
|
||||
@@ -256,7 +256,7 @@ module.exports = {
|
||||
],
|
||||
TABLES_USER_ID: ['mygroups', 'myskills', 'mybachecas', 'myhosps', 'mygoods'],
|
||||
TABLES_CREATEDBY: ['mygroups', 'circuits', 'attivitas'],
|
||||
TABLES_UPDATE_LASTMODIFIED: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'bots', 'mygroups', 'circuits', 'attivitas', 'myelems', 'mypages', 'productinfos', 'products', 'catalogs'],
|
||||
TABLES_UPDATE_LASTMODIFIED: ['myskills', 'mybachecas', 'myhosps', 'mygoods', 'bots', 'mygroups', 'circuits', 'attivitas', 'myelems', 'mypages', 'productinfos', 'products', 'catalogs', 'crons'],
|
||||
|
||||
TABLES_FIELDS_DESCR_AND_CITY_AND_USER: ['myskills', 'mybachecas', 'myhosps', 'mygoods'],
|
||||
|
||||
@@ -359,6 +359,7 @@ module.exports = {
|
||||
Zoomeri: 32,
|
||||
Department: 64,
|
||||
Grafico: 128,
|
||||
Commerciale: 256,
|
||||
},
|
||||
|
||||
MessageOptions: {
|
||||
@@ -730,6 +731,8 @@ module.exports = {
|
||||
'profile',
|
||||
'calcstat',
|
||||
'news_on',
|
||||
'diario_on',
|
||||
'test',
|
||||
'aportador_solidario',
|
||||
'made_gift',
|
||||
'ind_order',
|
||||
@@ -823,6 +826,8 @@ module.exports = {
|
||||
mycities: 1,
|
||||
sector: 1,
|
||||
recCatGrp: 1,
|
||||
mycircuits: 1,
|
||||
lastdate_reqRisGroup: 1,
|
||||
}
|
||||
} else if (table === this.TABLES_CIRCUITS) {
|
||||
proj = {
|
||||
@@ -1163,7 +1168,7 @@ module.exports = {
|
||||
AUDIOLIBRO: 22,
|
||||
VIDEO: 23,
|
||||
CARTE: 25,
|
||||
// -----------
|
||||
// -----------
|
||||
NUOVO: 101,
|
||||
USATO: 102,
|
||||
DOWNLOAD: 103,
|
||||
@@ -1178,15 +1183,42 @@ module.exports = {
|
||||
|
||||
AccountType: {
|
||||
USER: 0,
|
||||
COLLECTIVE_ACCOUNT: 1,
|
||||
CONTO_DI_GRUPPO: 1,
|
||||
COMMUNITY_ACCOUNT: 2,
|
||||
},
|
||||
|
||||
CmdQueryMs: {
|
||||
GET: 0,
|
||||
SET: 1,
|
||||
UPDATE: 2,
|
||||
},
|
||||
|
||||
SENDRIS_CODES: {
|
||||
EXCEED_FIDO: 10,
|
||||
EXCEED_QTAMAX: 20,
|
||||
},
|
||||
|
||||
DESTNEWSLETTER: {
|
||||
LISTA_NEWSLETTER: 0,
|
||||
UTENTI: 1,
|
||||
DIARIO: 2,
|
||||
TEST: 10,
|
||||
},
|
||||
|
||||
STATUS_JOB: {
|
||||
NONE: 0,
|
||||
START: 1,
|
||||
FINISH: 10,
|
||||
PAUSE: 2,
|
||||
ERR: -10,
|
||||
},
|
||||
|
||||
TERMINATED_WHY: {
|
||||
END_NORMALLY: 1,
|
||||
END_WITHERROR: -50,
|
||||
TOOLONGTIME: -10,
|
||||
}
|
||||
|
||||
// Download, DVD, Epub, Mobi, Nuovo, PDF, Streaming, Usato
|
||||
|
||||
};
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.2.2
|
||||
1.2.42
|
||||
47
yarn.lock
47
yarn.lock
@@ -1899,7 +1899,7 @@ bser@2.1.1:
|
||||
dependencies:
|
||||
node-int64 "^0.4.0"
|
||||
|
||||
bson@^6.10.1, bson@^6.10.3:
|
||||
bson@^6.10.3:
|
||||
version "6.10.3"
|
||||
resolved "https://registry.yarnpkg.com/bson/-/bson-6.10.3.tgz#5f9a463af6b83e264bedd08b236d1356a30eda47"
|
||||
integrity sha512-MTxGsqgYTwfshYWTRdmZRC+M7FnG1b4y7RO7p2k3X24Wq0yv1m77Wsj0BzlPzd/IowgESfsruQCUToa7vbOpPQ==
|
||||
@@ -4001,10 +4001,10 @@ gulp-replace@^1.1.4:
|
||||
replacestream "^4.0.3"
|
||||
yargs-parser ">=5.0.0-security.0"
|
||||
|
||||
gulp-sass@^6.0.0:
|
||||
version "6.0.0"
|
||||
resolved "https://registry.yarnpkg.com/gulp-sass/-/gulp-sass-6.0.0.tgz#91e651d86baf53bf7de8a537b1a38ea839968a4b"
|
||||
integrity sha512-FGb4Uab4jnH2GnSfBGd6uW3+imvNodAGfsjGcUhEtpNYPVx+TK2tp5uh7MO0sSR7aIf1Sm544werc+zV7ejHHw==
|
||||
gulp-sass@^6.0.1:
|
||||
version "6.0.1"
|
||||
resolved "https://registry.yarnpkg.com/gulp-sass/-/gulp-sass-6.0.1.tgz#28d292b5e9ca143d763e14fce87d6723b6d1b749"
|
||||
integrity sha512-4wonidxB8lGPHvahelpGavUBJAuERSl+OIVxPCyQthK4lSJhZ/u3/qjFcyAtnMIXDl6fXTn34H4BXsN7gt54kQ==
|
||||
dependencies:
|
||||
lodash.clonedeep "^4.5.0"
|
||||
picocolors "^1.0.0"
|
||||
@@ -6023,7 +6023,16 @@ mongodb-connection-string-url@^3.0.0:
|
||||
"@types/whatwg-url" "^11.0.2"
|
||||
whatwg-url "^14.1.0 || ^13.0.0"
|
||||
|
||||
mongodb@^6.14.1, mongodb@~6.14.0:
|
||||
mongodb@^6.14.2:
|
||||
version "6.14.2"
|
||||
resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-6.14.2.tgz#56533105e62ce795cd10a205a6374ecd8d58ad49"
|
||||
integrity sha512-kMEHNo0F3P6QKDq17zcDuPeaywK/YaJVCEQRzPF3TOM/Bl9MFg64YE5Tu7ifj37qZJMhwU1tl2Ioivws5gRG5Q==
|
||||
dependencies:
|
||||
"@mongodb-js/saslprep" "^1.1.9"
|
||||
bson "^6.10.3"
|
||||
mongodb-connection-string-url "^3.0.0"
|
||||
|
||||
mongodb@~6.14.0:
|
||||
version "6.14.1"
|
||||
resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-6.14.1.tgz#ab1084c00eba5f736b9ac8a93055d7d3ad0725a8"
|
||||
integrity sha512-GnHWIm4GtgREkssWRv9vYKNvqwbLd8WL5hCW3nCqzI2OxEZ6Q5g6vc3J6L1Grz0x1hx1wmYAprLlRr3kzBLcJg==
|
||||
@@ -6032,12 +6041,12 @@ mongodb@^6.14.1, mongodb@~6.14.0:
|
||||
bson "^6.10.3"
|
||||
mongodb-connection-string-url "^3.0.0"
|
||||
|
||||
mongoose@^8.12.0:
|
||||
version "8.12.0"
|
||||
resolved "https://registry.yarnpkg.com/mongoose/-/mongoose-8.12.0.tgz#1d0313982b1b737a1552e05541980b04a3979375"
|
||||
integrity sha512-FXZIngJBTt/gvb6uHZHiROy3Mk3EOjNpD0m+GBRfG+twuEntnMjfxwcA94YbYIulf9LkBozt7H8w2OJpqHdUxA==
|
||||
mongoose@^8.12.1:
|
||||
version "8.12.1"
|
||||
resolved "https://registry.yarnpkg.com/mongoose/-/mongoose-8.12.1.tgz#20fdc9a6cff72b323e438c6b4492cd4d4e1dd989"
|
||||
integrity sha512-UW22y8QFVYmrb36hm8cGncfn4ARc/XsYWQwRTaj0gxtQk1rDuhzDO1eBantS+hTTatfAIS96LlRCJrcNHvW5+Q==
|
||||
dependencies:
|
||||
bson "^6.10.1"
|
||||
bson "^6.10.3"
|
||||
kareem "2.6.3"
|
||||
mongodb "~6.14.0"
|
||||
mpath "0.9.0"
|
||||
@@ -6072,10 +6081,10 @@ ms@2.1.3, ms@^2.0.0, ms@^2.1.1, ms@^2.1.3:
|
||||
resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2"
|
||||
integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==
|
||||
|
||||
multer@^1.4.5-lts.1:
|
||||
version "1.4.5-lts.1"
|
||||
resolved "https://registry.yarnpkg.com/multer/-/multer-1.4.5-lts.1.tgz#803e24ad1984f58edffbc79f56e305aec5cfd1ac"
|
||||
integrity sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==
|
||||
multer@^1.4.5-lts.2:
|
||||
version "1.4.5-lts.2"
|
||||
resolved "https://registry.yarnpkg.com/multer/-/multer-1.4.5-lts.2.tgz#340af065d8685dda846ec9e3d7655fcd50afba2d"
|
||||
integrity sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==
|
||||
dependencies:
|
||||
append-field "^1.0.0"
|
||||
busboy "^1.0.0"
|
||||
@@ -6465,10 +6474,10 @@ open@^10.1.0:
|
||||
is-inside-container "^1.0.0"
|
||||
is-wsl "^3.1.0"
|
||||
|
||||
openai@^4.86.1:
|
||||
version "4.86.1"
|
||||
resolved "https://registry.yarnpkg.com/openai/-/openai-4.86.1.tgz#4147252d5e6255e2ae716ea59b1d4e54a1c1472a"
|
||||
integrity sha512-x3iCLyaC3yegFVZaxOmrYJjitKxZ9hpVbLi+ZlT5UHuHTMlEQEbKXkGOM78z9qm2T5GF+XRUZCP2/aV4UPFPJQ==
|
||||
openai@^4.86.2:
|
||||
version "4.87.3"
|
||||
resolved "https://registry.yarnpkg.com/openai/-/openai-4.87.3.tgz#82679f09d91f0e8e9da94b9ee0369c44733577da"
|
||||
integrity sha512-d2D54fzMuBYTxMW8wcNmhT1rYKcTfMJ8t+4KjH2KtvYenygITiGBgHoIrzHwnDQWW+C5oCA+ikIR2jgPCFqcKQ==
|
||||
dependencies:
|
||||
"@types/node" "^18.11.18"
|
||||
"@types/node-fetch" "^2.6.4"
|
||||
|
||||
Reference in New Issue
Block a user