36 Commits

Author SHA1 Message Date
Surya Paolo
5ab24b2abd - Generazione PDF e per Stampa 2025-05-12 16:34:04 +02:00
Surya Paolo
09a05a11d5 Creazione Nutriben-natoropatia.it 2025-05-11 21:59:25 +02:00
Surya Paolo
6c254a6a8e - Export Lista
- Ordinamento
- PDF Risolto Salvataggio ed invio al server direttamente.
2025-05-08 23:32:19 +02:00
Surya Paolo
240a7be7f1 - Cron Completato 2025-05-08 00:53:33 +02:00
Surya Paolo
58839c32e1 - Aggiunta della funzione Cron
- Flag: Pubblicati OnLine + Solo CagalogoGenerale + Dettagli
2025-05-07 21:58:43 +02:00
Surya Paolo
b77a0579f1 - newsletter: prende la lista utenti (flag news_on)
- Abilita a Tutti la Newsletter news_on
- isCommerciale
- JobsInProgress
- PCB: Corretto Totali che era a zero
2025-05-06 18:19:09 +02:00
Surya Paolo
6e8d1fcff1 Aggiungere un campo "Vagliato dall'Editore" e aggiungere anche il campo "chi" e delle Note 2025-05-02 19:11:35 +02:00
Surya Paolo
192fd4706c - ordinamento aggiornare la pagina "templates" per Fatturati ultimo anno
- bestseller
2025-05-02 10:10:11 +02:00
Surya Paolo
fcc3755c19 - corretto scheda prodotto, record salvato 2025-05-01 00:20:16 +02:00
Surya Paolo
97abe8b46d corretto errore che se sbagliava password dava errore... myuser... 2025-04-30 14:43:45 +02:00
Surya Paolo
e40fbd550b - miglioramenti ricerca titoli e modifica del trafiletto
- miglior visualizzazione delle liste
2025-04-30 13:27:54 +02:00
Surya Paolo
3d4f8b0d04 - aggiornato scheda e rigenera lista
- corretto filtro sulla Collana
2025-04-29 02:30:19 +02:00
Surya Paolo
95793fd73f - Altri aggiornamenti della scheda 2025-04-24 19:31:40 +02:00
Surya Paolo
4b4e3963ac - scheda prodotto migliorata
- aggiornamento filtri
2025-04-24 01:03:27 +02:00
Surya Paolo
85e2df56e1 - ordinamento tabella titoli
- migliorata la lista degli argomenti
2025-04-23 01:59:45 +02:00
Surya Paolo
58431c144c aggiornamento cataloghi, search 2025-04-22 18:30:48 +02:00
Surya Paolo
ad45ce60ee - aggiornamento cataloghi.
possibilità di estrapolare i dati da GM direttamente
- migrazione delle tabelle di GM in locale
- corretto l'ordinamento del Catalogo
2025-04-18 13:23:59 +02:00
Surya Paolo
fba2ebd710 - Aggiornamento dal DB di GM al DB Locale 2025-04-16 23:28:29 +02:00
Surya Paolo
8e8a3204a7 Aggiornamento cataloghi... 2025-04-11 18:49:59 +02:00
Surya Paolo
e1ca4ef17f - aggiornamento catalogo: lista titoli del catalogo
- scheda prodotto libro
- migliorata tabella prodotto
2025-04-04 18:15:21 +02:00
Surya Paolo
5431fe118e - Ricerca Titolo per nome o autore o ISBN o codice articolo 2025-03-31 23:56:01 +02:00
Surya Paolo
789dc1dcae - sendcoins
- font
- catalogo
2025-03-26 23:23:48 +01:00
Surya Paolo
76bacf3f5a fix: non riuscivi ad acquistare i RIS al gruppo
- lista linkREG
2025-03-23 22:54:04 +01:00
Surya Paolo
d94cbde948 aggiornamenti vari... 2025-03-21 19:52:01 +01:00
Surya Paolo
dfe492df45 - corretto la registrazione 2025-03-15 15:35:35 +01:00
Surya Paolo
6c50f35b2b - fix: refresh token, codice di errore ... 2025-03-15 15:04:28 +01:00
Surya Paolo
a03c4cf613 - fix: refresh token, codice di errore ... 2025-03-15 14:52:33 +01:00
Surya Paolo
7d845355a9 - fix: authenticate_withUser mancava su alcuni...
- fix: '/signin' non riproponeva il login nel caso il token fosse invalido
2025-03-14 12:52:44 +01:00
Surya Paolo
aeb83a512b - fix: nModified è stato sostituito con modifiedCount
- .ok con .acknowledged
- coretto la chiamata per il REFRESH TOKEN !
2025-03-14 10:55:37 +01:00
Surya Paolo
e04247b1b6 - fix: ris da inviare al gruppo (nuovamente) e immagini rimaste ancora "images/" anzichè "/images/". 2025-03-13 18:58:26 +01:00
Surya Paolo
f713f66369 - fix: sistemato pagina gruppo che non si visualizzava (errore per modifica)
- fix: corretto il "Invia RIS" al gruppo.
2025-03-13 18:19:42 +01:00
Surya Paolo
f32bd189dc - fatta ottimizzazione della funzione addExtraInfo, chiamando parallelamente tutte le promise... 2025-03-13 12:48:23 +01:00
Surya Paolo
0017f04e45 - risolto problema della non attesa della PWA durante la chiamata a Node.js.
- risolto problema dell'ambiente in Locale HTTPS certificato installato aggiornato.
2025-03-13 12:05:16 +01:00
Surya Paolo
65b29a6eee - fixed: Se tenti d'inviare dei RIS a chi ha raggiunto il limite, deve comparirti un msg ed inviare un msg al destinatario ! 2025-03-12 22:42:43 +01:00
Surya Paolo
7827e49760 versione 1.2.14 :
- aggiornati i file di configurazione, ENV e script non funzionanti., package.
- corretto custom-service-worker.js con CORS
- ottimizzato il server, la chiamata Load iniziale (senza promise, con async/await).
2025-03-12 21:03:02 +01:00
Surya Paolo
d106a59bb5 - corretta configurazione
- fix problemi al database su piuchebuono una chiamata dava errore...
const c = ....
if (mycart && mycart.length > 0) {
2025-03-10 19:59:03 +01:00
89 changed files with 11121 additions and 4417 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@@ -21,8 +21,8 @@ DELAY_SENDEMAIL=2000
VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app
PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8 PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8
PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo
PATH_CERT_KEY=localhost.key PATH_CERT_KEY=localhost-key.pem
PATH_SERVER_CRT=localhost.crt PATH_SERVER_CRT=localhost.pem
PATH_SSL_ROOT_PEM=root.pem PATH_SSL_ROOT_PEM=root.pem
PATH_SSL_CHAIN_PEM=chain.pem PATH_SSL_CHAIN_PEM=chain.pem
GCM_API_KEY="" GCM_API_KEY=""
@@ -42,5 +42,5 @@ MIAB_HOST=box.lamiaposta.org
MIAB_ADMIN_EMAIL=admin@lamiaposta.org MIAB_ADMIN_EMAIL=admin@lamiaposta.org
MIAB_ADMIN_PASSWORD=passpao1pabox@1A MIAB_ADMIN_PASSWORD=passpao1pabox@1A
DS_API_KEY="sk-222e3addb3d8455d8b0516d93906eec7" 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"

View File

@@ -21,15 +21,15 @@ DELAY_SENDEMAIL=2000
VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app
PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8 PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8
PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo
PATH_CERT_KEY=localhost.key PATH_CERT_KEY=localhost-key.pem
PATH_SERVER_CRT=localhost.crt PATH_SERVER_CRT=localhost.pem
PATH_SSL_ROOT_PEM=root.pem PATH_SSL_ROOT_PEM=root.pem
PATH_SSL_CHAIN_PEM=chain.pem PATH_SSL_CHAIN_PEM=chain.pem
GCM_API_KEY="" GCM_API_KEY=""
PROD=0 PROD=0
PROJECT_DESCR_MAIN='__PROJECTS' PROJECT_DESCR_MAIN='__PROJECTS'
SECRK=Askb38v23jjDFaoskBOWj92axXCQ SECRK=Askb38v23jjDFaoskBOWj92axXCQ
TOKEN_LIFE=2h TOKEN_LIFE=1m
REFRESH_TOKEN_LIFE=14d REFRESH_TOKEN_LIFE=14d
FTPSERVER_HOST=139.162.166.31 FTPSERVER_HOST=139.162.166.31
FTPSERVER_PORT=21 FTPSERVER_PORT=21

View File

@@ -1,12 +1,12 @@
DATABASE=test_FreePlanet DATABASE=test_PiuCheBuono
UDB=paofreeplanet UDB=paofreeplanet
PDB=mypassword@1A PDB=mypassword@1A
SEND_EMAIL=0 SEND_EMAIL=0
SEND_EMAIL_ORDERS=1 SEND_EMAIL_ORDERS=1
PORT=3000 PORT=3000
appTelegram_TEST=["1","13"] appTelegram_TEST=["1","17"]
appTelegram=["1","13"] appTelegram=["1","17"]
appTelegram_DEVELOP=["13"] appTelegram_DEVELOP=["17"]
DOMAIN=mongodb://localhost:27017/ DOMAIN=mongodb://localhost:27017/
AUTH_MONGODB=0 AUTH_MONGODB=0
ENABLE_PUSHNOTIFICATION=1 ENABLE_PUSHNOTIFICATION=1
@@ -21,15 +21,15 @@ DELAY_SENDEMAIL=2000
VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app VAPI_KEY_SUBJECT=mailto:paolo@freeplanet.app
PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8 PUBLIC_VAPI_KEY=BDncvMiUZmjaCG2Kr1V9N0_33hOG-AuNSbHSvL24y2dzBiUjAxKm02emx5SeJvz2IGmtRf6YqCgopeQwCwUmZw8
PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo PRIVATE_VAPI_KEY=uB2-jQkrbysyDtqN3ziMBDsVn0wdEaDsksX81zoOGQo
PATH_CERT_KEY=localhost.key PATH_CERT_KEY=localhost-key.pem
PATH_SERVER_CRT=localhost.crt PATH_SERVER_CRT=localhost.pem
PATH_SSL_ROOT_PEM=root.pem PATH_SSL_ROOT_PEM=root.pem
PATH_SSL_CHAIN_PEM=chain.pem PATH_SSL_CHAIN_PEM=chain.pem
GCM_API_KEY="" GCM_API_KEY=""
PROD=0 PROD=0
PROJECT_DESCR_MAIN='__PROJECTS' PROJECT_DESCR_MAIN='__PROJECTS'
SECRK=Askb38v23jjDFaoskBOWj92axXCQ SECRK=Askb38v23jjDFaoskBOWj92axXCQ
TOKEN_LIFE=1m TOKEN_LIFE=2h
REFRESH_TOKEN_LIFE=14d REFRESH_TOKEN_LIFE=14d
FTPSERVER_HOST=139.162.166.31 FTPSERVER_HOST=139.162.166.31
FTPSERVER_PORT=21 FTPSERVER_PORT=21
@@ -38,4 +38,9 @@ FTPSERVER_PWD=ftpmypwd@1A_
AUTH_NEW_SITES=123123123 AUTH_NEW_SITES=123123123
SCRIPTS_DIR=admin_scripts SCRIPTS_DIR=admin_scripts
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] 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" DS_API_KEY="sk-222e3addb3d8455d8b0516d93906eec7"
SERVER_A_URL="http://51.77.156.69:3000"
API_KEY_MSSQL="m68yADSr123MIVIDA@154$DSAGVOK"

View File

@@ -10,8 +10,9 @@ ENABLE_PUSHNOTIFICATION=1
DIRECTORY_SERVER=/var/www/nodejs_piuchebuono_server DIRECTORY_SERVER=/var/www/nodejs_piuchebuono_server
SERVERDIR_WEBSITE=/var/www/piuchebuono.app SERVERDIR_WEBSITE=/var/www/piuchebuono.app
PORT_APP1="0" PORT_APP1="0"
DOMAIN=mongodb://localhost:32001/ DOMAIN_OFF=mongodb://localhost:32001/
DOMAIN_AUTH=mongodb://{username}:{password}@127.0.0.1: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_MONGODB=1
AUTH_DB_PASSING=1 AUTH_DB_PASSING=1
MONGODB_USER=admin MONGODB_USER=admin
@@ -33,15 +34,11 @@ TOKEN_LIFE=2h
REFRESH_TOKEN_LIFE=14d REFRESH_TOKEN_LIFE=14d
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNVZZ AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNVZZ
DOMAINS=[{"hostname":"piuchebuono.app","port":"3030"},{"hostname":"gruppomacro.app","port":"3010"}] DOMAINS=[{"hostname":"piuchebuono.app","port":"3030"},{"hostname":"gruppomacro.app","port":"3010"}]
DOMAINS_ALLOWED=[]
SCRIPTS_DIR=admin_scripts SCRIPTS_DIR=admin_scripts
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}]
MIAB_HOST=box.lamiaposta.org MIAB_HOST=box.lamiaposta.org
MIAB_ADMIN_EMAIL=admin@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"
#DB_CONNECTION=sqlsrv API_KEY_MSSQL="m68yADSr123MIVIDA@154$DSAGVOK"
DB_HOST_SQLSRVTEST=31.3.180.50
DB_PORT_SQLSRVTEST=14338
DB_DATABASE_SQLSRVTEST=ANAG_MACRO
DB_USERNAME_SQLSRVTEST=woo
DB_PASSWORD_SQLSRVTEST=4n4traPe@

View File

@@ -7,8 +7,9 @@ ENABLE_PUSHNOTIFICATION=1
DIRECTORY_SERVER=/var/www/nodejs_riso_server DIRECTORY_SERVER=/var/www/nodejs_riso_server
SERVERDIR_WEBSITE=/var/www/riso.app SERVERDIR_WEBSITE=/var/www/riso.app
PORT_APP1="0" PORT_APP1="0"
DOMAIN=mongodb://localhost:32015/ DOMAIN_OFF=mongodb://localhost:32015/
DOMAIN_AUTH=mongodb://{username}:{password}@127.0.0.1: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_MONGODB=1
AUTH_DB_PASSING=1 AUTH_DB_PASSING=1
MONGODB_USER=admin MONGODB_USER=admin
@@ -30,6 +31,7 @@ TOKEN_LIFE=2h
REFRESH_TOKEN_LIFE=14d REFRESH_TOKEN_LIFE=14d
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV
DOMAINS=[{"hostname":"riso.app","port":"3006"},{"hostname":"freeplanet.app","port":"3000"}] 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"}] #DOMAINS=[{"hostname":"abitaregliiblei.it","port":"3021"},{"hostname":"riso.app","port":"3005"}]
SCRIPTS_DIR=admin_scripts SCRIPTS_DIR=admin_scripts
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}]

View File

@@ -15,7 +15,7 @@ DOMAIN_AUTH=mongodb://{username}:{password}@127.0.0.1:32002/
AUTH_MONGODB=1 AUTH_MONGODB=1
AUTH_DB_PASSING=1 AUTH_DB_PASSING=1
MONGODB_USER=admin MONGODB_USER=admin
MONGODB_PWD=mypwadmin@1A MONGODB_PWD=mypwadminS1A
SIGNCODE=SU2134hncaskjdbo231oihJSDNHEI$1@AB SIGNCODE=SU2134hncaskjdbo231oihJSDNHEI$1@AB
VITE_DEBUG=0 VITE_DEBUG=0
LOCALE=0 LOCALE=0
@@ -35,8 +35,11 @@ TOKEN_LIFE=2h
REFRESH_TOKEN_LIFE=14d REFRESH_TOKEN_LIFE=14d
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV
DOMAINS=[{"hostname":"piuchebuono.app","port":"3031"},{"hostname":"gruppomacro.app","port":"3011"}] DOMAINS=[{"hostname":"piuchebuono.app","port":"3031"},{"hostname":"gruppomacro.app","port":"3011"}]
DOMAINS_ALLOWED=[]
SCRIPTS_DIR=admin_scripts SCRIPTS_DIR=admin_scripts
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}]
MIAB_HOST=box.lamiaposta.org MIAB_HOST=box.lamiaposta.org
MIAB_ADMIN_EMAIL=admin@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"

View File

@@ -28,10 +28,11 @@ PATH_SSL_CHAIN_PEM=chain.pem
PROD=0 PROD=0
PROJECT_DESCR_MAIN='__PROJECTS' PROJECT_DESCR_MAIN='__PROJECTS'
SECRK=iUUb38v23jjDFaosWj92axkBOXCQ SECRK=iUUb38v23jjDFaosWj92axkBOXCQ
TOKEN_LIFE=1m TOKEN_LIFE=2h
REFRESH_TOKEN_LIFE=14d REFRESH_TOKEN_LIFE=14d
AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV
DOMAINS=[{"hostname":"riso.app","port":"3005"}] 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 SCRIPTS_DIR=admin_scripts
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}]
MIAB_HOST=box.lamiaposta.org MIAB_HOST=box.lamiaposta.org

View File

@@ -2,8 +2,10 @@
source ./.env.prod.pcb 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 if [ "$1" = "" ]; then
read -p "$msg" risposta read -p "$msg" risposta
@@ -17,7 +19,6 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
echo "Sincronizzazione in corso PCB PRODUZIONE ... $DIRECTORY_SERVER/" echo "Sincronizzazione in corso PCB PRODUZIONE ... $DIRECTORY_SERVER/"
echo "" echo ""
# Configurazione # Configurazione
REMOTE_USER="pcbuser" REMOTE_USER="pcbuser"
REMOTE_HOST="pcb" REMOTE_HOST="pcb"
@@ -25,6 +26,10 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
REMOTE_DIR="$DIRECTORY_SERVER" REMOTE_DIR="$DIRECTORY_SERVER"
SSH_OPTIONS="-p $REMOTE_PORT" 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 # Array di cartelle e file da sincronizzare
SYNC_ITEMS=( SYNC_ITEMS=(
"css" "css"
@@ -54,7 +59,8 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
# Sincronizza i file specifici # Sincronizza i file specifici
rsync -avz -e "ssh $SSH_OPTIONS" \ 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 ""
echo "*** Copia del file package.json ... " 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" package.json "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/package.json"
echo "" echo ""
echo "*** Copia del file ecosystem.config.js ... " echo "*** Copia del file $CONFIG_JS in ecosystem.config.js ... "
rsync -avz -e "ssh $SSH_OPTIONS" \ 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 # Verifica il risultato
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
echo "Sincronizzazione completata con successo. SERVER PCB! " echo "Sincronizzazione completata con successo. SERVER PCB PRODUZIONE! "
else else
echo "Errore durante la sincronizzazione. Controlla l'output per i dettagli." echo "Errore durante la sincronizzazione. Controlla l'output per i dettagli."
fi fi
fi fi

View File

@@ -26,8 +26,8 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
REMOTE_DIR="$DIRECTORY_SERVER" REMOTE_DIR="$DIRECTORY_SERVER"
SSH_OPTIONS="-p $REMOTE_PORT" SSH_OPTIONS="-p $REMOTE_PORT"
CONFIG_JS="ecosystem.config.testriso.js" CONFIG_JS="ecosystem.config.pcb_test.js"
ENV_FILE=".env.test.risosrv" ENV_FILE=".env.test.pcb"
ENV_OUT=".env.test" ENV_OUT=".env.test"
# Array di cartelle e file da sincronizzare # Array di cartelle e file da sincronizzare
@@ -67,11 +67,6 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
rsync -avz -e "ssh $SSH_OPTIONS" \ rsync -avz -e "ssh $SSH_OPTIONS" \
package.json "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/package.json" 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 ""
echo "*** Copia del file $CONFIG_JS in ecosystem.config.js ... " echo "*** Copia del file $CONFIG_JS in ecosystem.config.js ... "
rsync -avz -e "ssh $SSH_OPTIONS" \ rsync -avz -e "ssh $SSH_OPTIONS" \

View File

@@ -22,13 +22,10 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
REMOTE_PORT="8822" REMOTE_PORT="8822"
REMOTE_DIR="$DIRECTORY_SERVER" REMOTE_DIR="$DIRECTORY_SERVER"
SSH_OPTIONS="-p $REMOTE_PORT" 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_FILE=".env.prod.riso"
ENV_OUT=".env.production" ENV_OUT=".env.production"
#ENV_FILE=".env.prod.pcb"
#ENV_OUT=".env.production"
# Array di cartelle e file da sincronizzare # Array di cartelle e file da sincronizzare
SYNC_ITEMS=( SYNC_ITEMS=(
"css" "css"

View File

@@ -22,7 +22,7 @@ if [[ $risposta == "Y" || $risposta == "y" ]]; then
REMOTE_PORT="8822" REMOTE_PORT="8822"
REMOTE_DIR="$DIRECTORY_SERVER" REMOTE_DIR="$DIRECTORY_SERVER"
SSH_OPTIONS="-p $REMOTE_PORT" SSH_OPTIONS="-p $REMOTE_PORT"
CONFIG_JS="ecosystem.config.testriso.js" CONFIG_JS="ecosystem.config.riso_test.js"
ENV_FILE=".env.test.risosrv" ENV_FILE=".env.test.risosrv"
ENV_OUT=".env.test" ENV_OUT=".env.test"

38
docs/aaa.json Normal file
View 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&nbsp;",
"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"
},

View File

@@ -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 };

View File

@@ -1,10 +1,11 @@
module.exports = { module.exports = {
apps: [ apps: [
{ {
name: "PiuCheBuono", name: "PiuCheBuono (Prod)",
script: "/var/www/nodejs_piuchebuono_server/src/server/server.js", script: "/var/www/nodejs_piuchebuono_server/src/server/server.js",
ignore_watch: ["node_modules", "logs"], ignore_watch: ["node_modules", "logs"],
//autorestart: true, interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node",
//autorestart: true,
instances: 1, instances: 1,
watch: false, watch: false,
env: { env: {

View File

@@ -5,7 +5,6 @@ module.exports = {
script: "/var/www/nodejs_test.piuchebuono_server/src/server/server.js", script: "/var/www/nodejs_test.piuchebuono_server/src/server/server.js",
ignore_watch: ["node_modules", "logs"], ignore_watch: ["node_modules", "logs"],
interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node", interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node",
//autorestart: true,
instances: 1, instances: 1,
watch: false, watch: false,
env: { env: {

View File

@@ -1,7 +1,7 @@
module.exports = { module.exports = {
apps: [ apps: [
{ {
name: "RISO", name: "RISO (Prod)",
script: "/var/www/nodejs_riso_server/src/server/server.js", script: "/var/www/nodejs_riso_server/src/server/server.js",
ignore_watch: ["node_modules", "logs"], ignore_watch: ["node_modules", "logs"],
interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node", interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node",

View File

@@ -6,7 +6,6 @@ module.exports = {
ignore_watch: ["node_modules", "logs"], ignore_watch: ["node_modules", "logs"],
interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node", interpreter: "/root/.nvm/versions/node/v22.13.1/bin/node",
watch: false, watch: false,
//autorestart: true,
instances: 1, instances: 1,
env_test: { env_test: {
"PORT": 3001, "PORT": 3001,

View File

@@ -18,232 +18,270 @@
- var baseimg = baseurl + '/' - var baseimg = baseurl + '/'
doctype html doctype html
html html
- if (dataemail.title) head
head meta(charset="utf-8")
title dataemail.subject 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 .logoContainer { text-align:center; padding:20px 0; }
//- these file names will be replace by gulp with proper css file paths .logoContainer img { max-width:200px; }
link(rel="stylesheet", href="../sass/basic.scss")
link(rel="stylesheet", href="../sass/one/styles.scss")
//- embdedded css allowed, but not sass .testomail { padding:10px; font-size:0.75rem; line-height:1.4; }
style.
.red {
background-color: #E84C50;
}
.full-width { .clpromo {
width: 100%; 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) body(yahoofix)
span(id='body_style', style='display:block') span#body_style(style='display:block')
table(class="topHeader", cellpadding="0", cellspacing="0", width="100%") // Header
- if (dataemail.height_logo) table(width="100%", cellpadding="0", cellspacing="0", align="center")
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)
tr tr
td.testomail td.logoContainer
p!= dataemail.templ.testoheadermail_out 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 tr
td.clpromo td.clpromo
p!= dataemail.textpromo p!= dataemail.textpromo
- if (dataemail.templ.content) // Main Content
table(cellpadding="0", cellspacing="0", width="95%", align="center") 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 tr
td(class="textIniContainer", valign="top") td.emailContainer
p!=dataemail.templ.content table(width="100%", cellpadding="0", cellspacing="0")
- 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 &nbsp;
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")
tr tr
td(class="column sectionArticleImage", valign="top") td.column.sectionArticleImage(width="150")
table(cellpadding="0", cellspacing="0", summary="", border="0") if event.news
- if (event.news) p.q-chip.bg-red.text-white Novità
tr img(src=baseimg + (event.img_small || event.img), alt=event.title)
td p.teacher= event.op1[0].name + ' ' + event.op1[0].surname
p(class="q-chip row inline no-wrap items-center cltexth5 chipnews shadow-5 glossy text-right bg-red text-white") Novità 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 tr
td td.button
img(src=baseimg + imgev, alt="", width="150") a(href=baseurl + '/event/' + event.typol + '?eventid=' + event._id, target="_blank") Apri l'Evento
p(class="teacher") #{teacher1} <br> #{teacher2} #{teacher3} #{teacher4}
td(class="column", valign="top")
table(cellpadding="0", cellspacing="0", summary="", border="0") tr
tr td.center_img
td(class="sectionContentTitle boldhigh", valign="top") a.button2(href=urlcal, target="_blank") Calendario Eventi
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
// Disciplines
if dataemail.templ.options.includes('SHOW_DISC')
tr
td.center
h2.cltitle_disc= dataemail.disc_title
each disc in dataemail.arrdiscipline
tr tr
table(cellpadding="0", cellspacing="0", summary="", border="0", align="center", class="") td.discContainer
tr table(width="100%", cellpadding="0", cellspacing="0")
td(class="whitespace", height="10")
p &nbsp;
tr
td.center_img(class="button2 hoverLink")
a(href=urlcal, title='Calendario Eventi', target='_blank') Calendario Eventi
tr
td(class="whitespace", height="10")
p &nbsp;
- if (dataemail.templ.options.includes('SHOW_DISC'))
tr
td(class="whitespace bg-white", height="20")
p(class="bg-white") &nbsp;
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")
tr tr
td(class="column sectionArticleImage", valign="top") td.column.sectionArticleImage(width="150")
table(cellpadding="0", cellspacing="0", summary="", border="0") img(src=baseimg + (disc.img_small || disc.img), alt=disc.label)
tr td.column
td p.LinkDisc
img(src=baseimg + imgdisc, alt="", width="150") a(href=baseurl + disc.linkpage, target="_blank")
td(class="column", valign="top") span.pDisc(style=`background-color:`+disc.color)= disc.label
p.sectionContent!= disc.description
table(cellpadding="0", cellspacing="0", summary="", border="0") // Additional Content
tr if dataemail.content_after_events
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 &nbsp;
- if (dataemail.content_after_events)
tr tr
table(cellpadding="0", cellspacing="0", summary="", border="0") td.testomail
tr p!=dataemail.content_after_events
td.testomail
p!=dataemail.content_after_events
tr
td(class="whitespace", height="20")
p &nbsp;
// Social Media // Social Media
table.socialMedia(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center") tr
tr td.socialMedia
td(class="whitespace", height="5") table(width="120", align="center", cellpadding="0", cellspacing="0")
p &nbsp; if dataemail.urlinstagram
tr td
td a(href=dataemail.urlinstagram)
table(width="120", cellpadding="0", cellspacing="0", summary="", border="0", align="center") img(src=imginstagram, alt="Instagram")
tr if dataemail.urltwitter
- if (dataemail.urlinstagram) td
td(width="32", align="center") a(href=dataemail.urltwitter)
a(href=dataemail.urlinstagram, title='Instagram') img(src=imgtwitter, alt="Twitter")
img(src=imginstagram, alt="Instagram", width="29") if dataemail.urlfb
- if (dataemail.urltwitter) td
td(width="32", align="center") a(href=dataemail.urlfb)
a(href=dataemail.urltwitter, title='Twitter') img(src=imgfb, alt="Facebook")
img(src=imgtwitter, alt="Twitter", width="29") if dataemail.urlyoutube
- if (dataemail.urlfb) td
td(width="32", align="center") a(href=dataemail.urlyoutube)
a(href=dataemail.urlfb, title='Facebook') img(src=imgyoutube, alt="YouTube")
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 &nbsp;
// Footer // Footer
table.footer(cellpadding="0", cellspacing="0", width="100%", summary="", border="0", align="center") tr
tr td.firma-container
td(class="whitespace", height="10") p!= dataemail.firma
p &nbsp; tr
tr td.disclaimer-container
td.firma p!= dataemail.disclaimer_out
p!= dataemail.firma tr
td.bottom-container
tr p!= dataemail.disc_bottom_out
td.disclaimer
p!= dataemail.disclaimer_out
tr
td.bottom
p!= dataemail.disc_bottom_out
tr
td(class="whitespace", height="10")
p &nbsp;

1
localhost-key.pem Symbolic link
View File

@@ -0,0 +1 @@
/Users/suryapaolo/certs/localhost-key.pem

1
localhost.pem Symbolic link
View File

@@ -0,0 +1 @@
/Users/suryapaolo/certs/localhost.pem

View File

@@ -438,4 +438,49 @@ Lun 03/03 ORE 01:06: [<b>Circuito RIS Arezzo</b>]: Inviate Monete da surya1977 a
Saldi: Saldi:
surya1977: -1.10 RIS] 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]

View File

@@ -40,7 +40,7 @@
"lodash": "^4.17.21", "lodash": "^4.17.21",
"mongodb": "^6.14.2", "mongodb": "^6.14.2",
"mongoose": "^8.12.1", "mongoose": "^8.12.1",
"multer": "^1.4.5-lts.1", "multer": "^1.4.5-lts.2",
"mysql": "^2.18.1", "mysql": "^2.18.1",
"node-cron": "^3.0.3", "node-cron": "^3.0.3",
"node-emoji": "^2.2.0", "node-emoji": "^2.2.0",

View File

@@ -46,8 +46,10 @@ const database = process.env.DATABASE || "test"; // Nome del database, default a
if (process.env.AUTH_DB_PASSING === "1") { if (process.env.AUTH_DB_PASSING === "1") {
// replace username and password in the process.env.DOMAIN // 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 = 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 { } else {
process.env.MONGODB_URI = domain + database; 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);

View File

@@ -1,12 +1,20 @@
const axios = require('axios');
const server_constants = require('../tools/server_constants'); const server_constants = require('../tools/server_constants');
const shared_consts = require('../tools/shared_nodejs'); 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 API_KEY = process.env.API_KEY_MSSQL;
const mongoose = require('mongoose').set('debug', false);
// Funzione per ottenere i dati // Funzione per ottenere i dati
const getArticlesSales = async () => { const getArticlesSales = async () => {
try { try {
@@ -18,8 +26,10 @@ const getArticlesSales = async () => {
COALESCE(o.totVen, 0) as totVen, COALESCE(u.totFat, 0) as totFat, 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(p.rank3M, 0) as rank3M, COALESCE(t.fatrank3M, 0) as fatrank3M,
COALESCE(q.rank6M, 0) as rank6M, COALESCE(r.rank1Y, 0) as rank1Y, 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(t.fat3mesi, 0) as fatLast3M,
COALESCE(q.venduti6mesi, 0) as vLast6M, COALESCE(r.venduti1anno, 0) as vLastY, 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 s.ultimoOrdine as dataUltimoOrdine
FROM T_WEB_Articoli a FROM T_WEB_Articoli a
LEFT JOIN (SELECT CodArticoloGM, SUM(Qta) as totVen FROM T_WEB_Ordini GROUP BY CodArticoloGM) o 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 date = new Date(dateValue);
const day = String(date.getDate()).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0');
const month = String(date.getMonth() + 1).padStart(2, '0'); const month = String(date.getMonth() + 1).padStart(2, '0');
@@ -75,14 +102,30 @@ const formatDate = (dateValue) => {
return `${day}/${month}/${year}`; 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 { try {
const myurl = SERVER_A_URL + '/query';
console.log('getTableContentBase...', myurl)
// Verifica se la tabella esiste // Verifica se la tabella esiste
const checkTableQuery = `SELECT COUNT(*) as tableExists FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '${options.nameTable}'`; 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 } 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.`; 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 }, { const columnsResponse = await axios.post(SERVER_A_URL + '/query', { query: columnsQuery }, {
headers: { 'x-api-key': API_KEY } headers: { 'x-api-key': API_KEY }
}); });
console.log(' risposta 2 (schema)...')
const tableColumns = columnsResponse.data.map(col => col.COLUMN_NAME); const tableColumns = columnsResponse.data.map(col => col.COLUMN_NAME);
// Mappatura per unire i campi (ID e Descrizione) // Mappatura per unire i campi (ID e Descrizione)
@@ -107,15 +151,62 @@ const getTableContent = async (options) => {
// Costruisce la query per recuperare i record // Costruisce la query per recuperare i record
let dataQuery = ""; let dataQuery = "";
let columnsToShow = 'T.*'; let records = [];
if (options.fieldGM) {
columnsToShow = 'T.' + options.fieldGM;
}
if (options.nameTable.toLowerCase() === 't_web_articoli') { if (options?.usaDBGMLocale) {
if (true) {
dataQuery = ` // Cerca il modello corrispondente alla tabella se esiste
SELECT TOP ${options.numrec} 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} ${columnsToShow}
` + (options.campispeciali ? ` ` + (options.campispeciali ? `
,f.DescrizioneStatoProdotto ,f.DescrizioneStatoProdotto
@@ -125,14 +216,14 @@ const getTableContent = async (options) => {
,z.AutoriCompleti ,z.AutoriCompleti
,i2.DescrArgomento ,i2.DescrArgomento
,z3.CasaEditrice` : ``) + (options.showQtaDisponibile ? ` ,q.QtaDisponibile ` : ``) + ,z3.CasaEditrice` : ``) + (options.showQtaDisponibile ? ` ,q.QtaDisponibile ` : ``) +
` FROM T_WEB_Articoli T ` FROM T_WEB_Articoli T
JOIN( JOIN(
SELECT IdArticolo, MAX(DataOra) AS data SELECT IdArticolo, MAX(DataOra) AS data
FROM T_WEB_Articoli FROM T_WEB_Articoli
GROUP BY IdArticolo GROUP BY IdArticolo
) b ON T.IdArticolo = b.IdArticolo AND T.DataOra = b.data ` ) b ON T.IdArticolo = b.IdArticolo AND T.DataOra = b.data `
+ (options.campispeciali ? + (options.campispeciali ?
` LEFT JOIN( ` LEFT JOIN(
SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto SELECT e.IdStatoProdotto, e.Descrizione as DescrizioneStatoProdotto
FROM T_WEB_StatiProdotto e FROM T_WEB_StatiProdotto e
JOIN( JOIN(
@@ -212,9 +303,9 @@ const getTableContent = async (options) => {
GROUP BY IdMarchioEditoriale GROUP BY IdMarchioEditoriale
) aa3 ON a3.IdMarchioEditoriale = aa3.IdMarchioEditoriale AND a3.DataOra = aa3.maxData ) aa3 ON a3.IdMarchioEditoriale = aa3.IdMarchioEditoriale AND a3.DataOra = aa3.maxData
) z3 ON T.IdMarchioEditoriale = z3.IdMarchioEditoriale ` ) z3 ON T.IdMarchioEditoriale = z3.IdMarchioEditoriale `
: ``) : ``)
+ (options.showQtaDisponibile ? + (options.showQtaDisponibile ?
` LEFT JOIN( ` LEFT JOIN(
SELECT o.Codice, o.QtaDisponibile SELECT o.Codice, o.QtaDisponibile
FROM T_WEB_Disponibile o FROM T_WEB_Disponibile o
JOIN( JOIN(
@@ -223,8 +314,8 @@ const getTableContent = async (options) => {
GROUP BY Codice GROUP BY Codice
) p ON o.Codice = p.Codice AND o.DataOra = p.data1 ) p ON o.Codice = p.Codice AND o.DataOra = p.data1
) q ON T.IdArticolo = q.Codice` : ``) ) q ON T.IdArticolo = q.Codice` : ``)
} else { } else {
dataQuery += ` dataQuery += `
SELECT TOP ${options.numrec} SELECT TOP ${options.numrec}
T.* T.*
FROM T_WEB_Articoli T FROM T_WEB_Articoli T
@@ -234,22 +325,28 @@ const getTableContent = async (options) => {
GROUP BY IdArticolo GROUP BY IdArticolo
) b ON T.IdArticolo = b.IdArticolo AND T.DataOra = b.data ) b ON T.IdArticolo = b.IdArticolo AND T.DataOra = b.data
`; `;
}
} else {
dataQuery = `SELECT TOP ${options.numrec || 10000} * FROM ${options.nameTable} `;
} }
} else { if (options.where && options.where.trim() !== "") {
dataQuery = `SELECT TOP ${options.numrec} * FROM ${options.nameTable} `; 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) { 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. // Determina quali colonne visualizzare.
@@ -272,13 +369,13 @@ const getTableContent = async (options) => {
.map(item => { .map(item => {
const trimmed = item.trim(); const trimmed = item.trim();
const parsed = Date.parse(trimmed); const parsed = Date.parse(trimmed);
return !isNaN(parsed) ? formatDate(trimmed) : trimmed; return !isNaN(parsed) ? this.formatDate(trimmed) : trimmed;
}) })
.join(', '); .join(', ');
} else { } else {
const parsed = Date.parse(value); const parsed = Date.parse(value);
if (!isNaN(parsed)) { 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 // Se c'è un solo record, visualizza una lista di chiavi e valori
const record = records[0]; const record = records[0];
output += ` output += `
< table border = '1' style = "border-collapse: collapse; width: 50%;" > <table border='1' style="border-collapse: collapse;" >
<thead> <thead>
<tr> <tr>
<th style="padding: 8px; background-color: #f2f2f2;">Campo</th> <th style="padding: 8px; background-color: #f2f2f2;">Campo</th>
@@ -314,7 +411,7 @@ const getTableContent = async (options) => {
}); });
output += ` output += `
</tbody> </tbody>
</table > </table>
`; `;
} else { } else {
// Se ci sono più record, visualizza una tabella con intestazioni // Se ci sono più record, visualizza una tabella con intestazioni
@@ -345,9 +442,26 @@ const getTableContent = async (options) => {
records.forEach(record => { records.forEach(record => {
let myrec = {} let myrec = {}
displayColumns.forEach(column => { if (options.recordraw) {
myrec[column] = `${getDisplayValue(record, column)} `; 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) output.push(myrec)
}); });
} }
@@ -355,7 +469,8 @@ const getTableContent = async (options) => {
return output; return output;
} catch (error) { } 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) { if (options.outhtml) {
output = ` 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 // Endpoint per mostrare i dati della tabella
exports.viewTable = async (req, res) => { exports.viewTable = async (req, res) => {
try { try {
const options = req.body.options; const options = req.body.options;
const tableContent = await getTableContent(options); const tableContent = await this.getTableContent(options);
let out = {}; let out = {};
if (options.outhtml) { if (options.outhtml) {
out = ` out = `
<h2>Tabella: ${options.nameTable}</h2> <h2 class="text-center">Tabella: ${options.nameTable}</h2>
${tableContent} <div class="text-h7 row justify-center text-blue">Query: ${options.where}<br></div>
<div class="row justify-center">
${tableContent}
</div>
` `
} else { } else {
out = tableContent; 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 }); return res.send({ code: server_constants.RIS_CODE_OK, data: out });
} catch (error) { } 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 // Endpoint per mostrare i dati della tabella
exports.queryTable = async (req, res) => { exports.queryTable = async (req, res) => {
try { try {
const options = req.body.options; const options = req.body.options;
const tableContent = await getTableContent(options); const tableContent = await this.getTableContent(options);
let out = {}; let out = {};
if (options.outhtml) { if (options.outhtml) {
out = ` out = `
<h2>Tabella: ${options.nameTable}</h2> <h2>Tabella: ${options.nameTable}</h2>
<div class="text-h7 row justify-center text-blue">Query: ${options.where}<br></div>
${tableContent} ${tableContent}
` `
} else { } else {
@@ -458,3 +853,107 @@ exports.queryTable = async (req, res) => {
return res.send({ code: server_constants.RIS_CODE_ERR, error }); 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);
}
}
}

View File

@@ -41,7 +41,7 @@ console.log('Mongoose Version ' + mongoose.version);
// URL di connessione // URL di connessione
const connectionUrl = process.env.MONGODB_URI; 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 // Funzione per connettersi al database con retry
async function connectToDatabase(uri, opts) { async function connectToDatabase(uri, opts) {
@@ -52,12 +52,12 @@ async function connectToDatabase(uri, opts) {
console.log("Sto provando a connettermi al database..."); console.log("Sto provando a connettermi al database...");
await mongoose.connect(uri); 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); console.log(' Database corrente:', mongoose.connection.name);
// Ottieni l'URL completo della connessione // 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 db = mongoose.connection;
const serverInfo = await db.db.admin().serverStatus(); // Ottieni lo stato del server const serverInfo = await db.db.admin().serverStatus(); // Ottieni lo stato del server

View File

@@ -104,8 +104,8 @@
"ID_CIRCUIT_COINS_ACCEPTED_TO_ME": "🔄 Hai inviato <strong>%s %s</strong> a %s sul '%s'.", "ID_CIRCUIT_COINS_ACCEPTED_TO_ME": "🔄 Hai inviato <strong>%s %s</strong> a %s sul '%s'.",
"ID_CIRCUIT_COINS_REFUSED": "%s %s rifiutati da %s sul '%s'.", "ID_CIRCUIT_COINS_REFUSED": "%s %s rifiutati da %s sul '%s'.",
"ID_CIRCUIT_COINS_REFUSED_TO_ME": "%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_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_QTAMAX": "⚠️ L'importo supera la quantità massima che il destinatario (%s) può accumulare",
"CIRCUIT_COINS_ALREADY_PROCESSED": "La richiesta è stata già processata. Stato %s", "CIRCUIT_COINS_ALREADY_PROCESSED": "La richiesta è stata già processata. Stato %s",
"STATUS_SENT": "Inviato", "STATUS_SENT": "Inviato",
"STATUS_REFUSED": "Rifiutato", "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.", "🚫 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 !", "🚫 %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 !", "✅ 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: %", "Good: %": "Good: %",
"Service: %": "Service: %" "Service: %": "Service: %"
} }

View File

@@ -11,123 +11,58 @@ const auth_default = (req, res, next) => {
}; };
const authenticate = (req, res, next) => { const authenticateMiddleware = async (req, res, next, withUser = false, lean = false, noError = false) => {
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) => {
try { try {
const token = req.header('x-auth'); const token = req.header('x-auth');
const refreshToken = req.header('x-refrtok'); const refreshToken = req.header('x-refrtok');
const logPrefix = noError ? (withUser ? (lean ? 'WITHUSERLEAN' : 'WITHUSER') : 'NOERROR') : 'AUTH';
if (!token) { if (!token) {
req.user = null; req.user = null;
req.token = null; req.token = null;
req.code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN; 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)) const user = await User.findByToken(token, 'auth', false, withUser, lean);
.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;
}
if (ris.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) { if (user.code !== server_constants.RIS_CODE_OK) {
return res.status(server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED).send(); 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(); if (user.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) {
}) console.log(` TOKEN SCADUTO ! `);
.catch((e) => { if (noError) {
console.error('Errore durante l\'autenticazione:', e); return next()
req.user = null; } else {
req.token = null; return res.status(server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED).send();
req.code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN; }
next(); }
});
// console.log(` ## ${logPrefix} NEXT ! AVANTI...`);
next();
} catch (e) { } catch (e) {
console.error('Errore nel middleware di autenticazione:', e); console.error('Errore nel middleware di autenticazione:', e);
req.user = null; req.user = null;
req.token = null; req.token = null;
req.code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN; 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 };

View File

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

View File

@@ -657,7 +657,7 @@ AccountSchema.statics.updateQtaMax = async function (idapp, username, groupname,
else else
risult = await Account.updateOne({ idapp, username, circuitId }, { $set: paramstoupdate }); 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) { AccountSchema.statics.getAccountsCircuitiNazionali = async function (idapp) {

View File

@@ -26,15 +26,27 @@ const CatalogSchema = new Schema({
}, },
title: { title: {
type: String, type: String,
index: true,
}, },
foto_collana: IImg, foto_collana: IImg,
idCollane: [{ idCollane: [{
type: String,
}],
idTipoFormato: [{
type: Number, type: Number,
}], }],
argomenti: [{ argomenti: [{
type: String, type: String,
}], }],
condition_andor: {
type: Number,
default: 0,
},
editore: [{ type: String }], editore: [{ type: String }],
descr_introduttiva: { descr_introduttiva: {
type: String, type: String,
}, },
@@ -57,9 +69,19 @@ const CatalogSchema = new Schema({
}, },
pdf_generato: String, pdf_generato: String,
pdf_generato_stampa: String,
data_generato: { data_generato: {
type: Date, type: Date,
}, },
data_generato_stampa: {
type: Date,
},
username_lista_generata: {
type: String,
},
data_lista_generata: {
type: Date,
},
pdf_online: String, pdf_online: String,
data_online: { data_online: {
type: Date, type: Date,
@@ -72,6 +94,11 @@ const CatalogSchema = new Schema({
date_updated: { date_updated: {
type: Date, 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); return tools.executeQueryTable(this, idapp, params, user);
}; };
CatalogSchema.statics.findAllIdApp = async function (idapp) { /*CatalogSchema.statics.OLD_findAllIdApp = async function (idapp) {
const Catalog = this; const Catalog = this;
const arrrec = await Catalog.aggregate([ const arrrec = await Catalog.aggregate([
@@ -117,6 +144,107 @@ CatalogSchema.statics.findAllIdApp = async function (idapp) {
]); ]);
return arrrec; 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); const Catalog = mongoose.model('Catalog', CatalogSchema);

View File

@@ -21,6 +21,7 @@ const CatProdSchema = new Schema({
}, },
name: { name: {
type: String, type: String,
index: 1,
}, },
descr_estesa: { descr_estesa: {
type: String, type: String,
@@ -34,6 +35,9 @@ const CatProdSchema = new Schema({
color: { color: {
type: String, type: String,
}, },
quanti: {
type: Number,
}
}); });
CatProdSchema.statics.getAllCategories = function (callback) { CatProdSchema.statics.getAllCategories = function (callback) {
@@ -58,13 +62,13 @@ CatProdSchema.statics.findAllIdApp = async function (idapp) {
return await CatProd.find(myfind).sort({ name: 1 }).lean(); return await CatProd.find(myfind).sort({ name: 1 }).lean();
}; };
CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp) { CatProdSchema.statics.updateCatDeleteEmpty = async function (idapp) {
try { try {
const result = await CatProd.aggregate([ const toDelete = await CatProd.aggregate([
{ $match: { idapp } }, { $match: { idapp } },
{ {
$lookup: { $lookup: {
from: 'productinfos', // Nome della tua collezione productInfo from: 'productinfos',
localField: '_id', localField: '_id',
foreignField: 'idCatProds', foreignField: 'idCatProds',
as: 'products' as: 'products'
@@ -77,9 +81,86 @@ CatProdSchema.statics.getCatProdWithTitleCount = async function (idapp) {
quanti: { $size: '$products' } // Conta il numero di prodotti per ciascun CatProd 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; return result;
} catch (error) { } catch (error) {
console.error('Error retrieving CatProd with title count:', error); console.error('Error retrieving CatProd with title count:', error);

View File

@@ -720,6 +720,7 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig
let ris = { let ris = {
result: false, result: false,
cansend: true, cansend: true,
errorcode: 0,
errormsg: '', errormsg: '',
rec: null, rec: null,
useraccounts: [], useraccounts: [],
@@ -768,11 +769,13 @@ CircuitSchema.statics.sendCoins = async function (onlycheck, idapp, usernameOrig
if (accountorigTable.saldo - myqty < -accountorigTable.fidoConcesso) { if (accountorigTable.saldo - myqty < -accountorigTable.fidoConcesso) {
ris.cansend = false; ris.cansend = false;
ris.errormsg = i18n.__('CIRCUIT_AMOUNT_EXCEED_FIDO', usernameOrig); ris.errormsg = i18n.__('CIRCUIT_AMOUNT_EXCEED_FIDO', usernameOrig);
ris.errorcode = shared_consts.SENDRIS_CODES.EXCEED_FIDO;
} }
if (accountdestTable.saldo + myqty > accountdestTable.qta_maxConcessa) { if (accountdestTable.saldo + myqty > accountdestTable.qta_maxConcessa) {
ris.cansend = false; ris.cansend = false;
ris.errormsg = i18n.__('CIRCUIT_AMOUNT_EXCEED_QTAMAX', extrarec.dest); 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); const ris = await Account.updateFido(idapp, username, groupname, circuitId, fido);
if (ris) { 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) };
} }
} }
} }

View File

@@ -256,7 +256,7 @@ CitySchema.statics.insertGeojsonToMongoDB = async function (nomefilejson) {
if (reccity) { if (reccity) {
const ris = await City.updateOne({ _id: reccity._id }, { $set: { geojson: citta } }); const ris = await City.updateOne({ _id: reccity._id }, { $set: { geojson: citta } });
if (ris.ok === 1) { if (ris.acknowledged) {
inseriti++; inseriti++;
} }
} }

View File

@@ -20,6 +20,7 @@ const CollanaSchema = new Schema({
}, },
title: { title: {
type: String, type: String,
index: true,
}, },
dataOra: { dataOra: {
type: Date, type: Date,
@@ -30,6 +31,9 @@ const CollanaSchema = new Schema({
enabledAlFresco: { enabledAlFresco: {
type: Boolean, type: Boolean,
}, },
quanti: {
type: Number,
},
}); });
@@ -52,6 +56,73 @@ module.exports.findAllIdApp = async function (idapp) {
return await Collana.find(myfind).sort({title: 1}).lean(); 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() module.exports.createIndexes()
.then(() => { }) .then(() => { })
.catch((err) => { throw err; }); .catch((err) => { throw err; });

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

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

View File

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

View File

@@ -39,6 +39,41 @@ MailingListSchema.statics.findAllIdAppSubscribed = function (idapp) {
return tools.findAllQueryIdApp(User, myfind); 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) { MailingListSchema.statics.getnumSent = async function (idapp, idUser) {
const myfind = { idapp, news_on: true, lastid_newstosent: idUser }; const myfind = { idapp, news_on: true, lastid_newstosent: idUser };

View File

@@ -61,7 +61,9 @@ const catalogo = new Schema(
excludeproductTypes: [{ type: Number }], excludeproductTypes: [{ type: Number }],
editore: [{ type: String }], editore: [{ type: String }],
argomenti: [{ type: String }], argomenti: [{ type: String }],
idCollane: [{ type: Number }], idCollane: [{ type: String }],
idTipologia: [{ type: Number }],
idTipoFormato: [{ type: Number }],
sort_field: { type: String }, sort_field: { type: String },
sort_dir: { type: Number }, sort_dir: { type: Number },
pdf: { type: Boolean }, pdf: { type: Boolean },
@@ -69,6 +71,8 @@ const catalogo = new Schema(
printable: { type: Boolean }, printable: { type: Boolean },
indebug: { type: Boolean }, indebug: { type: Boolean },
maxnumlibri: { type: Number }, maxnumlibri: { type: Number },
showListaArgomenti: { type: Boolean},
showListaCollane: { type: Boolean},
first_page: IDimensioni, first_page: IDimensioni,
last_page: IDimensioni, last_page: IDimensioni,

View File

@@ -298,16 +298,16 @@ MyGroupSchema.statics.getArrUsernameFromFieldByGroupname = async function (
const { User } = require('../models/user'); const { User } = require('../models/user');
const myobj = {}; const myobj = {};
myobj[field + '.' + subfield] = 1; myobj[field] = 1;
let arrrec = await User.findOne({ const ris = await User.findOne({
idapp, idapp,
groupname, groupname,
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
}, myobj).then((ris) => ris ? ris._doc[field] : []); }, myobj);
if (arrrec.length > 0) { if (ris) {
return arrrec.map(m => m.username); return ris[field].map(m => m.username);
} }
return []; return [];
@@ -441,7 +441,7 @@ MyGroupSchema.statics.getGroupsByUsername = async function (idapp, username, req
listgroups, listgroups,
listSentRequestGroups, listSentRequestGroups,
listRefusedGroups, listRefusedGroups,
mygroups: req.user.profile.mygroups, mygroups: await User.getMyGroupsById(req.user._id),
}; };
} catch (e) { } catch (e) {
@@ -663,13 +663,13 @@ MyGroupSchema.statics.renameCircuitName = async function (idapp, oldcircuitname,
MyGroupSchema.statics.setReceiveRisGroup = async function (idapp, groupname) { MyGroupSchema.statics.setReceiveRisGroup = async function (idapp, groupname) {
return await this.findOneAndUpdate({ const record = await this.findOneAndUpdate(
idapp, groupname, { idapp, groupname },
}, { $set: { 'lastdate_reqRisGroup': new Date() } },
{ $set: { 'lastdate_reqRisGroup': new Date() } }, { new: false }).lean().then((record) => { { new: false }
return !!record; ).lean();
});
return !!record; // Restituisce true se il record esiste, false altrimenti
}; };
const MyGroup = mongoose.model('MyGroup', MyGroupSchema); const MyGroup = mongoose.model('MyGroup', MyGroupSchema);

View File

@@ -353,7 +353,7 @@ MyHospSchema.statics.SettaAdTypeOffro_In_Hosps = async function () {
try { try {
// Set all records 'adType' to shared_consts.AdType.OFFRO // Set all records 'adType' to shared_consts.AdType.OFFRO
const result = await MyHosp.updateMany({}, { $set: { adType: 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) { } catch (err) {
console.error('Error updating adType:', err); console.error('Error updating adType:', err);
} }

View File

@@ -56,6 +56,7 @@ const IDimensioni = new Schema({
}); });
const IPagina = new Schema({ const IPagina = new Schema({
dimensioni: IDimensioni, dimensioni: IDimensioni,
testo_title: IText,
testo_up: IText, testo_up: IText,
testo_down: IText, testo_down: IText,
}); });
@@ -81,7 +82,7 @@ const INovita = new Schema(
const IBestseller = new Schema( const IBestseller = new Schema(
{ {
show: Boolean, show: Boolean,
primiNInClassifica: Number, quantiFattRaggiunti: Number,
} }
); );
@@ -129,9 +130,11 @@ const scheletroScheda = {
productTypes: [{ type: Number }], productTypes: [{ type: Number }],
excludeproductTypes: [{ type: Number }], excludeproductTypes: [{ type: Number }],
idTipologie: [{ type: Number }],
idTipoFormato: [{ type: Number }],
editore: [{ type: String }], editore: [{ type: String }],
argomenti: [{ type: String }], argomenti: [{ type: String }],
idCollane: [{ type: Number }], idCollane: [{ type: String }],
author: { type: String }, author: { type: String },
sort_field: { type: String }, sort_field: { type: String },
sort_dir: { type: Number }, sort_dir: { type: Number },

View File

@@ -22,6 +22,9 @@ const NewstosentSchema = new Schema({
templemail_str: { templemail_str: {
type: String, type: String,
}, },
destnewsletter_str: {
type: String,
},
activate: { activate: {
type: Boolean, type: Boolean,
default: false default: false
@@ -121,7 +124,10 @@ NewstosentSchema.statics.findNewsletterPending_To_Send = function (idapp) {
starting_job: true, starting_job: true,
finish_job: false, finish_job: false,
processing_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 idapp
}).lean(); }).lean();
}; };
@@ -141,10 +147,10 @@ NewstosentSchema.statics.getlast = async function (idapp) {
const Newstosent = this; const Newstosent = this;
try { try {
const mydoc = await Newstosent.find({ idapp }).sort({ datestartJob: -1 }).limit(1); const mydoc = await Newstosent.findOne({ idapp }).sort({ datestartJob: -1 }).lean();
return mydoc[0]._doc; return mydoc || null;
} catch (e) { } catch (e) {
return null return null;
} }
}; };

View File

@@ -22,9 +22,9 @@ const orderSchema = new Schema({
}, },
userId: { type: Schema.Types.ObjectId, ref: 'User' }, userId: { type: Schema.Types.ObjectId, ref: 'User' },
status: { 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' }, idProducer: { type: Schema.Types.ObjectId, ref: 'Producer' },
idStorehouse: { type: Schema.Types.ObjectId, ref: 'StoreHouse' }, idStorehouse: { type: Schema.Types.ObjectId, ref: 'StoreHouse' },
idScontisticas: [{ type: Schema.Types.ObjectId, ref: 'Scontistica' }], idScontisticas: [{ type: Schema.Types.ObjectId, ref: 'Scontistica' }],
@@ -125,7 +125,8 @@ const orderSchema = new Schema({
type: String type: String
}, },
modify_at: { modify_at: {
type: Date type: Date,
index: true
}, },
}); });

View File

@@ -548,41 +548,47 @@ module.exports.updateOrdersCartById = async function(id, newOrdersCart, callback
id, id,
deleted: false, deleted: false,
} }
let mycart = null;
try { try {
const c = await OrdersCart.find(query); mycart = await OrdersCart.find(query);
} catch (err) { } catch (err) {
console.log('ERR: updateOrdersCartById', err); console.log('ERR: updateOrdersCartById', err);
if (err) throw err; if (err) throw err;
} }
//exist cart in databse try {
if (c.length > 0) { //exist cart in databse
return OrdersCart.findOneAndUpdate( if (mycart && mycart.length > 0) {
{ _id: id }, return OrdersCart.findOneAndUpdate(
{ { _id: id },
$set: { {
items: newOrdersCart.items, $set: {
totalQty: newOrdersCart.totalQty, items: newOrdersCart.items,
totalQtyPreordered: newOrdersCart.totalQtyPreordered, totalQty: newOrdersCart.totalQty,
totalPrice: newOrdersCart.totalPrice, totalQtyPreordered: newOrdersCart.totalQtyPreordered,
totalPriceCalc: newOrdersCart.totalPriceCalc ? newOrdersCart.totalPriceCalc : newOrdersCart.totalPrice, totalPrice: newOrdersCart.totalPrice,
userId: userId, totalPriceCalc: newOrdersCart.totalPriceCalc ? newOrdersCart.totalPriceCalc : newOrdersCart.totalPrice,
status: newOrdersCart.status, userId: userId,
numorder: newOrdersCart.numorder, status: newOrdersCart.status,
numord_pers: newOrdersCart.numord_pers, numorder: newOrdersCart.numorder,
note: newOrdersCart.note, numord_pers: newOrdersCart.numord_pers,
modify_at: new Date(), note: newOrdersCart.note,
} modify_at: new Date(),
}, }
{ new: true }, },
callback { new: true },
) callback
} else { )
//no cart in database } else {
return newOrdersCart.save(callback) //no cart in database
return newOrdersCart.save(callback)
}
} catch (e) {
console.log('Err updateOrdersCartById', e.message);
} }
} }
module.exports.setFieldInOrdersById = async function (objtoset, myOrderCart) { module.exports.setFieldInOrdersById = async function (objtoset, myOrderCart) {
try { try {

File diff suppressed because it is too large Load Diff

View File

@@ -41,6 +41,7 @@ const productInfoSchema = new Schema({
}, },
name: { name: {
type: String, type: String,
index: true,
}, },
description: { description: {
type: String, type: String,
@@ -48,8 +49,11 @@ const productInfoSchema = new Schema({
short_descr: { short_descr: {
type: String, 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' }], idSubCatProds: [{ type: Schema.Types.ObjectId, ref: 'SubCatProd' }],
idStatoProdotto: {
type: Number, index: true
},
color: { color: {
type: String type: String
}, },
@@ -64,11 +68,9 @@ const productInfoSchema = new Schema({
}, },
unit: { unit: {
type: Number, type: Number,
default: 0,
}, },
unit_lordo: { unit_lordo: {
type: Number, type: Number,
default: 0,
}, },
sfuso: { // serve se moltiplicare le qta (es: 12 kg) oppure fare (2 x 20 ml) sfuso: { // serve se moltiplicare le qta (es: 12 kg) oppure fare (2 x 20 ml)
type: Boolean type: Boolean
@@ -85,6 +87,9 @@ const productInfoSchema = new Schema({
imagefile: { imagefile: {
type: String, type: String,
}, },
image_not_found: {
type: Boolean,
},
vers_img: { vers_img: {
type: Number, type: Number,
}, },
@@ -121,9 +126,9 @@ const productInfoSchema = new Schema({
note: { note: {
type: String, type: String,
}, },
idAuthors: [{ type: Schema.Types.ObjectId, ref: 'Author' }], idAuthors: [{ type: Schema.Types.ObjectId, ref: 'Author', index: true }],
idCollana: { type: Number }, idCollana: { type: Schema.Types.ObjectId, ref: 'Collana', index: true },
idPublisher: { type: Schema.Types.ObjectId, ref: 'Publisher' }, idPublisher: { type: Schema.Types.ObjectId, ref: 'Publisher', index: true },
collezione: { collezione: {
type: String, type: String,
}, },
@@ -132,6 +137,7 @@ const productInfoSchema = new Schema({
}, },
date_pub: { date_pub: {
type: Date, type: Date,
index: 1,
}, },
date_pub_ts: { date_pub_ts: {
type: Number, type: Number,
@@ -143,13 +149,25 @@ const productInfoSchema = new Schema({
date_updated: { date_updated: {
type: Date, type: Date,
}, },
date_updated_fromGM: {
type: Date,
},
totVen: Number, totVen: Number,
totFat: Number, totFat: Number,
vLast3M: Number, vLast3M: Number,
fatLast3M: Number, fatLast3M: Number,
vLast6M: Number, fatLast6M: Number,
vLastY: Number, fatLast1Y: Number,
fatLast2Y: Number,
vLast6M: {
type: Number,
index: true,
},
vLast1Y: {
type: Number, index: true
},
vLast2Y: Number, vLast2Y: Number,
dataUltimoOrdine: Date, dataUltimoOrdine: Date,
rank3M: Number, rank3M: Number,
@@ -158,6 +176,7 @@ const productInfoSchema = new Schema({
descrizione_breve_macro: String, descrizione_breve_macro: String,
descrizione_completa_macro: String, descrizione_completa_macro: String,
descr_trafiletto_catalogo: String,
sottotitolo: String, sottotitolo: String,
link_macro: 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() module.exports.createIndexes()
.then(() => { }) .then(() => { })
.catch((err) => { throw err; }); .catch((err) => { throw err; });

View File

@@ -313,24 +313,21 @@ ProjectSchema.statics.getIdParentByIdProj = function (idProj) {
ProjectSchema.statics.creaProjMain = async function (idapp) { ProjectSchema.statics.creaProjMain = async function (idapp) {
const projmain = { return await Project.findOneAndUpdate(
idapp, { idapp, descr: process.env.PROJECT_DESCR_MAIN },
descr: process.env.PROJECT_DESCR_MAIN, {
longdescr: process.env.PROJECT_DESCR_MAIN, $setOnInsert: {
typeproj: 1, idapp,
id_main_project: null, descr: process.env.PROJECT_DESCR_MAIN,
id_parent: null, longdescr: process.env.PROJECT_DESCR_MAIN,
privacyread: server_constants.Privacy.all typeproj: 1,
}; id_main_project: null,
id_parent: null,
return await new Project(projmain).save() privacyread: server_constants.Privacy.all
.then(ris => { }
console.log('ris', ris); },
if (!!ris) { upsert: true, new: true, runValidators: true }
return ris._doc; );
else
return null;
});
}; };

View File

@@ -24,6 +24,9 @@ const PublisherSchema = new Schema({
img: { img: {
type: String, type: String,
}, },
quanti: {
type: Number,
},
}); });
var Publisher = module.exports = mongoose.model('Publisher', PublisherSchema); 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(); 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() module.exports.createIndexes()
.then(() => { }) .then(() => { })
.catch((err) => { throw err; }); .catch((err) => { throw err; });

View File

@@ -304,7 +304,7 @@ reactionSchema.statics.addFavorite = async function (req, idapp, username, id, t
fav: true, fav: true,
} }
}) })
ok = ris.ok; ok = ris.acknowledged;
} }
const { SendNotif } = require('../models/sendnotif'); const { SendNotif } = require('../models/sendnotif');

View File

@@ -124,7 +124,7 @@ sendNotifSchema.index({ sender: 1 });*/
sendNotifSchema.index({ idapp: 1, typedir: 1, typeid: 1, status: 1, 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; const SendNotif = this;
if (!username) if (!username)
@@ -133,7 +133,7 @@ sendNotifSchema.statics.setNotifAsRead = function (idapp, username, idnotif) {
try { try {
if (idnotif) { if (idnotif) {
return SendNotif.findOneAndUpdate({ return await SendNotif.findOneAndUpdate({
$and: [ $and: [
{ idapp }, { idapp },
{ dest: username }, { 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; const SendNotif = this;
try { try {
return SendNotif.findById(id).lean(); return await SendNotif.findById(id).lean();
} catch (e) { } catch (e) {
return null; return null;
} }
@@ -602,7 +602,7 @@ sendNotifSchema.statics.getDescrAndLinkByRecNotif = async function (recnotif, us
recnotif.tag = recnotif.tag ? recnotif.tag : tag; recnotif.tag = recnotif.tag ? recnotif.tag : tag;
if (!recnotif.descr) { if (!recnotif.descr) {
recnotif.descr = newdescr; recnotif.descr = newdescr;
} }
@@ -895,10 +895,9 @@ sendNotifSchema.statics.updateStatusAndDescr = async function (myrecnotif, onlys
// Cerca il record e se lo trova lo aggiorna // Cerca il record e se lo trova lo aggiorna
const myrec = await SendNotif.findOneAndUpdate(query, { $set: fields_to_update }, { const myrec = await SendNotif.findOneAndUpdate(query,
new: false, { $set: fields_to_update },
returnNewDocument: true, { returnDocument: "after" }).lean();
});
if (myrec) { if (myrec) {
return { myrecout: myrec, save: true }; return { myrecout: myrec, save: true };

View File

@@ -48,7 +48,7 @@ const SettingsSchema = new Schema({
SettingsSchema.statics.getFieldsForSearch = function () { SettingsSchema.statics.getFieldsForSearch = function () {
return [{ field: 'key', type: tools.FieldType.string }, 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) { SettingsSchema.statics.executeQueryTable = function (idapp, params) {
@@ -94,9 +94,9 @@ SettingsSchema.statics.findAllIdApp = async function (idapp, serv, crypted = fal
try { try {
let myfind = ''; let myfind = '';
if (serv) { if (serv) {
myfind = {idapp, serv}; myfind = { idapp, serv };
} else } else
myfind = {idapp}; myfind = { idapp };
// myfind = {...myfind, $or: [{ crypted: { $exists: false } }, { crypted: { $exists: true, $eq: crypted } }]}; // 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) { if (rec.crypted) {
rec.value_str = '' rec.value_str = ''
} }
myarr.push({...rec}); myarr.push({ ...rec });
} }
} else { } else {
myarr = [...arrorig]; myarr = [...arrorig];
} }
return myarr; return myarr;
}catch (e) { } catch (e) {
console.error('Settings: findAllIdApp', e); console.error('Settings: findAllIdApp', e);
return null; return null;
} }
@@ -136,7 +136,9 @@ SettingsSchema.statics.setKeyNum = async function (idapp, key, value) {
return await myrec.save(); return await myrec.save();
} else { } 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 return myrec

View File

@@ -55,6 +55,7 @@ const StatSchema = new Schema({
diffusorilist: [], diffusorilist: [],
receiveRislist: [], receiveRislist: [],
receiveRislistgroup: [], receiveRislistgroup: [],
listlinksreg: [],
strettelist: [], strettelist: [],
num_transaz_tot: Number, num_transaz_tot: Number,
tot_RIS_transati: Number, tot_RIS_transati: Number,
@@ -95,6 +96,7 @@ StatSchema.statics.calculateStats = async function (idapp) {
lastsonline: await User.getLastOnlineUsers(idapp), lastsonline: await User.getLastOnlineUsers(idapp),
lastssharedlink: await User.getLastSharedLink(idapp), lastssharedlink: await User.getLastSharedLink(idapp),
diffusorilist: await User.getDiffusoriUsers(idapp), diffusorilist: await User.getDiffusoriUsers(idapp),
listlinksreg: await User.getListLinkReg(idapp),
receiveRislist: await User.getReceiveRISUsers(idapp), receiveRislist: await User.getReceiveRISUsers(idapp),
receiveRislistgroup: await MyGroup.getReceiveRISGroups(idapp), receiveRislistgroup: await MyGroup.getReceiveRISGroups(idapp),
strettelist: await User.getLastStretteDiManoUsers(idapp), strettelist: await User.getLastStretteDiManoUsers(idapp),
@@ -110,7 +112,10 @@ StatSchema.statics.calculateStats = async function (idapp) {
if (trova_se_oggi) { if (trova_se_oggi) {
// Aggiorna il record di 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); // console.log('ris', ris);
} else { } else {
// Aggiungi un nuovo record: // Aggiungi un nuovo record:

View File

@@ -0,0 +1,107 @@
mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
/**
* @typedef {Object} Article
* @property {bigint} Id
* @property {number} IdArticolo
* @property {string} Ean13
* @property {string} Titolo
* @property {string} ListaAutori
* @property {string} ListaArgomenti
* @property {number} IdStatoProdotto
* @property {number} PrezzoIvato
* @property {number} IdMarchioEditoriale
* @property {number} IdCollana
* @property {Date} DataPubblicazione
* @property {number} IdTipologia
* @property {number} IdTipoFormato
* @property {string} Misure
* @property {string} Pagine
* @property {string} Sottotitolo
* @property {string} Durata
* @property {string} Numero
* @property {string} Edizione
* @property {string} Ristampa
* @property {Date} DataInizioCampagna
* @property {Date} DataFineCampagna
* @property {number} ScontoCampagna
* @property {number} PrezzoIvatoScontatoCampagna
* @property {Date} DataOra
* @property {boolean} Enabled
* @property {number} IDTagGruppo
* @property {string} Utente
* @property {number} PercIva
* @property {number} IdTitoloOriginale
* @property {boolean} EnabledAlFresco
* @property {number} CodEdizione
* @property {string} FasciaEta
* @property {string} DescrizioneStatoProdotto
* @property {string} DescrizioneTipologia
* @property {string} DescrizioneFormato
* @property {string} DescrizioneCollana
* @property {string} DescrArgomento
* @property {string} AutoriCompleti
* @property {string} CasaEditrice
*/
const T_WEB_ArticoliSchema = new Schema({
IdArticolo: { type: Number },
Ean13: { type: String },
Titolo: { type: String },
ListaAutori: String,
ListaArgomenti: String,
IdStatoProdotto: Number,
PrezzoIvato: Number,
IdMarchioEditoriale: Number,
IdCollana: Number,
DataPubblicazione: Date,
IdTipologia: Number,
IdTipoFormato: Number,
Misure: String,
Pagine: String,
Sottotitolo: String,
Durata: String,
Numero: String,
Edizione: String,
Ristampa: String,
DataInizioCampagna: Date,
DataFineCampagna: Date,
ScontoCampagna: Number,
PrezzoIvatoScontatoCampagna: Number,
DataOra: Date,
Enabled: Boolean,
IDTagGruppo: Number,
Utente: String,
PercIva: Number,
IdTitoloOriginale: Number,
EnabledAlFresco: Boolean,
CodEdizione: Number,
FasciaEta: String,
DescrizioneStatoProdotto: String,
DescrizioneTipologia: String,
DescrizioneFormato: String,
DescrizioneCollana: String,
DescrArgomento: String,
AutoriCompleti: String,
CasaEditrice: String,
}, { collection: 't_web_articolis' });
module.exports = mongoose.model('T_WEB_Articoli', T_WEB_ArticoliSchema);
module.exports.createIndexes({ IdArticolo: 1, DataOra: -1 })
.then(() => { })
.catch((err) => { throw err; });

View File

@@ -0,0 +1,199 @@
const mongoose = require('mongoose');
const 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;
}
}

View File

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

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

@@ -0,0 +1,200 @@
// allo stesso modo di t_web_articolifatturati.js
// creami il modello t_web_ordini:
// Tabella: T_WEB_Ordini
/*Codice - decimal ()
IdInternet - varchar (50)
CodArticoloGM - varchar (50)
Qta - decimal ()
PrezzoLordo - decimal ()
PercSconto - decimal ()
Enabled - int ()
DataOra - datetime ()
SovraSconto - decimal ()
Descrizione - varchar (250)
PrimaCopiaDaSpedire - int ()
*/
const mongoose = require('mongoose');
const 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;
}
}

View 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;
};

View 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;
};

View 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;
};

View File

@@ -25,6 +25,15 @@ const TemplEmailSchema = new Schema({
content: { content: {
type: String, type: String,
}, },
disclaimer: {
type: String,
},
piedipagina: {
type: String,
},
firma: {
type: String,
},
img: { img: {
type: String, type: String,
}, },

View File

@@ -177,6 +177,12 @@ const UserSchema = new mongoose.Schema({
news_on: { news_on: {
type: Boolean, type: Boolean,
}, },
diario_on: {
type: Boolean,
},
test: {
type: Boolean,
},
email_errata: { email_errata: {
type: Boolean, type: Boolean,
}, },
@@ -435,6 +441,9 @@ const UserSchema = new mongoose.Schema({
lastdate_reqRis: { lastdate_reqRis: {
type: Date, type: Date,
}, },
lastdate_LinkReg: {
type: Date,
},
notifs: [ notifs: [
{ {
_id: false, _id: false,
@@ -568,8 +577,6 @@ UserSchema.methods.generateAuthToken = function (req) {
user.lasttimeonline = new Date(); user.lasttimeonline = new Date();
return user.save().then(() => { return user.save().then(() => {
// console.log('Salvato refreshToken su DB', refreshToken);
// console.log("TOKEN CREATO IN LOGIN : " + token);
return { token, refreshToken }; return { token, refreshToken };
}).catch(err => { }).catch(err => {
console.log('Error', err.message); 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; const User = this;
try { try {
return User.findOneAndUpdate({ idapp, username }, { $set: { lasttimeonline: new Date() } }); return await User.findOneAndUpdate({ idapp, username }, { $set: { lasttimeonline: new Date() } });
} catch (e) { } catch (e) {
} }
@@ -639,7 +646,7 @@ UserSchema.statics.canHavePower = function (perm) {
try { try {
let consentito = false; let consentito = false;
if (User.isAdmin(perm) || User.isManager(perm) || if (User.isAdmin(perm) || User.isManager(perm) ||
User.isEditor(perm) || User.isFacilitatore(perm)) { User.isEditor(perm) || User.isCommerciale(perm) || User.isFacilitatore(perm)) {
consentito = true; consentito = true;
} }
@@ -695,6 +702,14 @@ UserSchema.statics.isEditor = function (perm) {
return false; 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) { UserSchema.statics.isGrafico = function (perm) {
try { try {
return ((perm & shared_consts.Permissions.Grafico) === 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; const User = this;
let decoded;
let code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN; let code = server_constants.RIS_CODE_HTTP_INVALID_TOKEN;
let user = null; let user = null;
let decoded;
const start = process.hrtime.bigint();
const start_jwt = process.hrtime.bigint();
try { if (!token) {
if (token) { console.warn('TOKEN VUOTO ! ');
decoded = jwt.verify(token, process.env.SIGNCODE); return { user, code };
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 (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({ user = await User.findOne({
'_id': decoded.smart, _id: decoded.smart,
tokens: { tokens: {
$elemMatch: { $elemMatch: {
token: token, token,
access: typeaccess, 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 (user) {
const checkExpiry = tools.getEnableTokenExpiredByIdApp(user.idapp);
if (check_expiry_date && (decoded.exp < tempo)) { const currentTime = Date.now() / 1000;
console.log('Il token è scaduto, generazione del nuovo token...'); if (checkExpiry && decoded.exp < currentTime) {
code = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED; console.log('Il token è scaduto, generazione del nuovo token...');
} else { code = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED;
// TOKEN ANCORA VALIDO
code = server_constants.RIS_CODE_OK;
}
} }
} }
// const end = process.hrtime.bigint();
// console.log(` findByToken impiega ${Math.round(Number(end - start) / 1e6) / 1000} secondi.`);
return { user, code }; return { user, code };
}; };
@@ -805,16 +867,16 @@ UserSchema.statics.findByTokenAnyAccess = function (token) {
return User.findOne({ return User.findOne({
'_id': decoded.smart, '_id': decoded.smart,
'tokens.token': token, 'tokens.token': token,
}); }).lean();
}; };
UserSchema.statics.findByCredentials = function (idapp, username, password, pwdcrypted) { UserSchema.statics.findByCredentials = async function (idapp, username, password, pwdcrypted) {
const User = this; const User = this;
let pwd = ''; let pwd = '';
let regexp = new RegExp(`^${username}$`, 'i'); let regexp = new RegExp(`^${username}$`, 'i');
return User.findOne({ let user = await User.findOne({
idapp, idapp,
username: { $regex: regexp }, username: { $regex: regexp },
$or: [ $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) { UserSchema.statics.findByUsername = async function (idapp, username, alsoemail, onlyifVerifiedByAportador) {
@@ -1314,6 +1364,16 @@ UserSchema.statics.setaportador_solidario = async function (
return !!myrec; 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 ( UserSchema.statics.setNewsletter = async function (
idapp, username, newsletter_on) { idapp, username, newsletter_on) {
const User = this; const User = this;
@@ -1902,6 +1962,7 @@ UserSchema.statics.getUserProfileByUsername = async function (
if (perm === tools.Perm.PERM_NONE) { if (perm === tools.Perm.PERM_NONE) {
whatToShow = { whatToShow = {
idapp: 1,
lang: 1, lang: 1,
index: 1, index: 1,
username: 1, username: 1,
@@ -1952,6 +2013,7 @@ UserSchema.statics.getUserProfileByUsername = async function (
} else if (perm === tools.Perm.PERM_FRIEND) { } else if (perm === tools.Perm.PERM_FRIEND) {
whatToShow = { whatToShow = {
idapp: 1,
lang: 1, lang: 1,
index: 1, index: 1,
username: 1, username: 1,
@@ -2001,6 +2063,7 @@ UserSchema.statics.getUserProfileByUsername = async function (
} else if (perm === tools.Perm.PERM_ALL) { } else if (perm === tools.Perm.PERM_ALL) {
whatToShow = { whatToShow = {
idapp: 1,
lang: 1, lang: 1,
index: 1, index: 1,
username: 1, username: 1,
@@ -2150,17 +2213,14 @@ UserSchema.statics.getArrUsernameFromFieldByUsername = async function (
idapp, username, field, subfield) { idapp, username, field, subfield) {
const myobj = {}; const myobj = {};
myobj[field + '.' + subfield] = 1; myobj[field + '.' + subfield + '.username'] = 1;
let arrrec = await User.findOne({ const rec = await User.findOne({
idapp, 'username': username, idapp, 'username': username,
$or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }], $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }],
}, myobj).then((ris) => ris ? ris._doc[field][subfield] : []); }, myobj);
if (arrrec && arrrec.length > 0) { return rec ? rec[field][subfield].map(m => m.username) : [];
return arrrec.map(m => m.username);
}
return [];
}; };
@@ -3043,6 +3103,7 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn
// console.log('setCircuitCmd', cmd); // console.log('setCircuitCmd', cmd);
const { SendNotif } = require('../models/sendnotif'); const { SendNotif } = require('../models/sendnotif');
const telegrambot = require('../telegram/telegrambot');
let ris = null; let ris = null;
let outres = { let outres = {
@@ -3281,72 +3342,85 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn
outres = await Circuit.sendCoins(onlycheck, idapp, usernameOrig, extrarec); outres = await Circuit.sendCoins(onlycheck, idapp, usernameOrig, extrarec);
if (outres.cansend) { if (outres.cansend) {
// Invia una notifica di moneta alla persona ris = true;
//const out = await tools.sendNotificationByCircuit(idapp, usernameOrig, circuitname, cmd, false, true, username_action, // } else if ((cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) || (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE)) {
// extrarec); // Before to accept, I see if it's already set !
//if (out)
// outres.result = out.ris;
} else {
outres.cansend = false;
}
ris = true; /*outres = {
// } else if ((cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) || (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE)) { cansend: false,
// Before to accept, I see if it's already set ! errormsg: '',
}; */
/*outres = { let outcheck = outres;
cansend: false,
errormsg: '',
}; */
let outcheck = outres; let risStatus = '';
const status = await SendNotif.getStatus(extrarec.notifId);
let risStatus = ''; if (status === shared_consts.CircuitsNotif.STATUS_ACCEPTED) {
const status = await SendNotif.getStatus(extrarec.notifId); risStatus = i18n.__('STATUS_SENT');
if (status === shared_consts.CircuitsNotif.STATUS_ACCEPTED) { } else if (status === shared_consts.CircuitsNotif.STATUS_REFUSED) {
risStatus = i18n.__('STATUS_SENT'); risStatus = i18n.__('STATUS_REFUSED');
} 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;
} }
// if (!await SendNotif.checkIfCoinsAlreadySent(extrarec.notifId)) {
cmd = shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT; //if (!await Movement.checkIfCoinsAlreadySent(extrarec.notifId)) {
if (true) {
/*if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT && outcheck.cansend) { if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) {
if (!await Movement.checkIfCoinsAlreadySent(extrarec.notifId)) { //outcheck = await Circuit.sendCoins(true, idapp, usernameOrig, extrarec);
outres = await Circuit.sendCoins(false, idapp, usernameOrig, extrarec); outcheck.cansend = true;
outres.cansend = true;
} else { } else {
outcheck.cansend = false; //GIA INVIATO outcheck.cansend = true;
outres.cansend = true;
} }
} */
if (outcheck.cansend) { cmd = shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT;
// 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) { /*if (cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT && outcheck.cansend) {
// Setta agli altri admin, 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); console.warn('🔴 ATTENZIONE! ', outres.errormsg + '\n(Mittente: ' + usernameOrig + ')');
outres.arrrecnotif = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIF_FOR_USER, shared_consts.QualiNotifs.OTHERS); // await telegrambot.sendMsgTelegram(idapp, usernameOrig, msgOrig);
if (await User.isAdminByUsername(idapp, username_action)) {
outres.arrrecnotifcoins = await SendNotif.findAllNotifCoinsAllIdAndIdApp(idapp); // Invia questo msg anche all'Admin
} else { await telegrambot.sendMsgTelegramToTheAdmin(idapp, outres.errormsg + '\n(Mittente: ' + usernameOrig + ')', true);
outres.arrrecnotifcoins = await SendNotif.findAllNotifByUsernameIdAndIdApp(username_action, extrarec.lastdr, idapp, shared_consts.LIMIT_NOTIFCOINS_FOR_USER, shared_consts.QualiNotifs.CIRCUITS);
}
} }
@@ -4832,6 +4906,15 @@ UserSchema.statics.getReceiveRISUsers = async function (idapp) {
return ris; 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) { UserSchema.statics.checkUser = async function (idapp, username) {
@@ -5377,6 +5460,93 @@ UserSchema.statics.getQueryReceiveRISUsers = function (idapp, hours) {
return query; 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) { UserSchema.statics.getUsersRegWeekly = function (idapp, nrec) {
const query = [ const query = [
@@ -5790,7 +5960,7 @@ UserSchema.statics.getExtraInfoByUsername = async function (idapp, username) {
let myuser = await User.findOne({ idapp, username }).lean(); let myuser = await User.findOne({ idapp, username }).lean();
if (myuser) { if (myuser) {
myuserextra = await User.addExtraInfo(idapp, myuser, null); myuserextra = await User.addExtraInfo(idapp, myuser);
return myuser.profile; 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 { try {
// tools.startTimeLog('addExtraInfo') // Verifica e aggiornamento della versione (blocco sequenziale)
if (version && recUser) {
if (version) { const versattualeuser = recUser?.profile?.version || 0;
let versattualeuser = 0;
if (!recUser.profile.version) {
recUser.version = 0;
versattualeuser = 0;
} else {
versattualeuser = recUser.profile.version;
}
// versattualeuser = 0; // TOGLIERE!
if (versattualeuser < version) { if (versattualeuser < version) {
// Aggiornamento versione // Aggiorna la versione utente (eventuali chiamate dipendenti vanno eseguite in sequenza)
recUser = await User.updateVersion(versattualeuser, recUser); recUser = await User.updateVersion(versattualeuser, recUser);
await User.findOneAndUpdate({ _id: recUser._id }, { $set: { 'profile.version': version } }); await User.findOneAndUpdate({ _id: recUser._id }, { $set: { 'profile.version': version } });
} }
} }
const listSentMyRequestFriends = await User.find({ // Esegui le query indipendenti in parallelo
idapp, const [
'profile.req_friends': { listSentMyRequestFriends,
$elemMatch: { username: { $eq: recUser.username } }, listSentMyRequestGroups,
}, listRefusedGroups,
$or: [ listManageGroups,
{ deleted: { $exists: false } }, reactions,
{ deleted: { $exists: true, $eq: false } }], userstoverify,
}, { username: 1 }).lean(); 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 // Richiesta per i gruppi a cui è stata mandata una richiesta
? listSentMyRequestFriends 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({ // Richiesta per i gruppi rifiutati
idapp, MyGroup.find(
'req_users': { {
$elemMatch: { username: { $eq: recUser.username } }, idapp,
}, 'refused_users': { $elemMatch: { username: recUser.username } },
$or: [ $or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }]
{ deleted: { $exists: false } }, },
{ deleted: { $exists: true, $eq: false } }], MyGroup.getWhatToShow_Unknown()
}, MyGroup.getWhatToShow_Unknown()).lean(); ).lean(),
recUser.profile.asked_groups = listSentMyRequestGroups // Richiesta per i gruppi gestiti (admin)
? listSentMyRequestGroups MyGroup.find(
: []; {
idapp,
'admins': { $elemMatch: { username: recUser.username } },
$or: [{ deleted: { $exists: false } }, { deleted: { $eq: false } }]
}
).lean(),
const listRefusedGroups = await MyGroup.find({ // Reazioni
idapp, Reaction.find({ idapp, username: recUser.username }).lean(),
'refused_users': {
$elemMatch: { username: { $eq: recUser.username } },
},
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
}, MyGroup.getWhatToShow_Unknown()).lean();
recUser.profile.refused_groups = listRefusedGroups // Altri utenti da verificare
? listRefusedGroups User.getUsersToVerify(idapp, recUser.username),
: [];
const listManageGroups = await MyGroup.find({ // Circuiti associati
idapp, Circuit.getCircuitsByUsername(idapp, recUser.username, recUser, 5),
'admins': {
$elemMatch: { username: { $eq: recUser.username } },
},
$or: [
{ deleted: { $exists: false } },
{ deleted: { $exists: true, $eq: false } }],
}).lean();
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 // Altri calcoli per l'utente
? listManageGroups User.calcOtherByUser(idapp, recUser._id)
: []; ]);
// Circuit> // Per ogni gruppo gestito, recupera gli account in parallelo
const manageGroupsWithAccounts = await Promise.all(
const circuitobj = await Circuit.getCircuitsByUsername(idapp, recUser.username, recUser, 5); listManageGroups.map(async (group) => {
const myaccounts = await Account.getGroupAccounts(idapp, group.groupname);
const useraccounts = await Account.getUserAccounts(idapp, recUser.username); return { ...group, account: (myaccounts && myaccounts.length > 0) ? myaccounts[0] : null };
})
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;
}
// 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.profile = { ...recUser.profile, ...circuitobj, useraccounts };
recUser.calcstat = calcstat;
recUser.calcstat = await User.calculateStat(idapp, recUser.username); recUser.profile.calc = calcOther;
recUser.profile.calc = await User.calcOtherByUser(idapp, recUser._id);
// tools.endTimeLog('addExtraInfo')
return recUser; return recUser;
} catch (e) { } catch (e) {
console.error('Err addExtraInfo', e); console.error('Err addExtraInfo', e);
} }
return recUser; return recUser;
}; };
@@ -6180,6 +6344,17 @@ UserSchema.statics.setReceiveRis = async function (idapp, username) {
return !!record; 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) { 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) { UserSchema.statics.createNewSubRecord = async function (idapp, req) {
const User = this; const User = this;
@@ -6358,6 +6564,7 @@ const FuncUsers = {
} }
}; };
UserSchema.index({ 'tokens.token': 1, 'tokens.access': 1 });
module.exports = { module.exports = {
User, Hero, FuncUsers User, Hero, FuncUsers

View 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

File diff suppressed because it is too large Load Diff

View 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;

File diff suppressed because it is too large Load Diff

View File

@@ -78,10 +78,11 @@ module.exports = {
console.log(' ... Non inserito !'); console.log(' ... Non inserito !');
} }
} else { } else {
// Il documento esiste, lo aggiorniamo // Il documento esiste, lo aggiorniamo
const ris = await table.updateOne({ _id: existingDoc._id }, { $set: rec }); const ris = await table.updateOne({ _id: existingDoc._id }, { $set: rec });
if (ris && ris.nModified > 0) if (ris && ris.modifiedCount > 0)
numupdated++; numupdated++;
} }
} catch (e) { } catch (e) {

View File

@@ -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: 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: 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: 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: 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: 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: 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: 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: '' }, { _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: 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: 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: 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: 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: 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: '' }, { _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: 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: 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: 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: 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: 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: '' }, { _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: 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: 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: 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: 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: 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: '' }, { _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: 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: 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: 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: 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: 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

View File

@@ -1,5 +1,5 @@
const express = require("express"); 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 { authenticate } = require("../middleware/authenticate");
const router = express.Router(); const router = express.Router();
@@ -9,7 +9,11 @@ router.post("/articles-sales", authenticate, getArticlesSalesHandler);
router.post("/export-articles-sales-json", authenticate, exportArticlesSalesByJSON); router.post("/export-articles-sales-json", authenticate, exportArticlesSalesByJSON);
router.post("/view-table", authenticate, viewTable); router.post("/view-table", authenticate, viewTable);
router.post("/save-table", authenticate, saveTable);
router.post("/query", authenticate, queryTable); router.post("/query", authenticate, queryTable);
router.post("/updateAllBook", authenticate, updateAllBookRoute);
router.post("/mssqlmigrateTables", authenticate, mssqlmigrateTables);
module.exports = router; module.exports = router;

View File

@@ -4,7 +4,7 @@ const router = express.Router();
const tools = require('../tools/general'); const tools = require('../tools/general');
const server_constants = require('../tools/server_constants'); const server_constants = require('../tools/server_constants');
const { authenticate } = require('../middleware/authenticate'); const { authenticate, authenticate_withUser } = require('../middleware/authenticate');
const { Booking } = require('../models/booking'); 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); 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('INIZIO - booking');
// tools.mylog('req.body', req.body); // tools.mylog('req.body', req.body);
const myrec = _.pick(req.body, tools.allfieldBooking()); const myrec = _.pick(req.body, tools.allfieldBooking());

View File

@@ -181,25 +181,24 @@ router.put('/:userId', authenticate, async function (req, res, next) {
const cart = await Cart.getCartByUserId(userId); const cart = await Cart.getCartByUserId(userId);
try { 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 //exist cart in databse
if (cart.length > 0) { if (cart.length > 0) {
await Cart.updateCartByUserId( try {
userId, const result = await Cart.updateCartByUserId(userId, {
{
items: newCart.items, items: newCart.items,
totalQty: newCart.totalQty, totalQty: newCart.totalQty,
totalPrice: newCart.totalPrice, totalPrice: newCart.totalPrice,
totalPriceCalc: newCart.totalPriceCalc, totalPriceCalc: newCart.totalPriceCalc,
userId: userId userId: userId
}, });
function (err, result) { res.json(result);
if (err) return next(err) } catch (err) {
res.json(result) return next(err);
}) }
} else { } else {
//no cart in database //no cart in database
let newCartobj = { let newCartobj = {
@@ -242,13 +241,13 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res,
let idapp = req.body.idapp; let idapp = req.body.idapp;
let cart_id = req.body.cart_id; let cart_id = req.body.cart_id;
let userId = req.params.userId; let userId = req.params.userId;
const user = req.user;
let status = req.body.status; let status = req.body.status;
let note = req.body.note; let note = req.body.note;
let options = req.body.options; let options = req.body.options;
try { try {
let mycart = await Cart.findOne({ _id: cart_id }); let mycart = await Cart.findOne({ _id: cart_id }).lean();
if (!mycart) { if (!mycart) {
return res.send({ return res.send({
@@ -309,19 +308,21 @@ router.post('/:userId/createorderscart', authenticate, async function (req, res,
.then(async (orders) => { .then(async (orders) => {
if (!!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 // Invia la email dell'Ordine
sendemail.sendEmail_OrderProduct(userDest.lang, idapp, orders[0], userDest) sendemail.sendEmail_OrderProduct(userDest.lang, idapp, orders[0], userDest)
.then(async (ris) => { .then(async (ris) => {
myorderCart = await OrdersCart.findById(idordercart).lean(); myorderCart = await OrdersCart.findById(idordercart).lean();
return res.send({ return res.send({
code: server_constants.RIS_CODE_OK, code: server_constants.RIS_CODE_OK,
status: myris.status, status: myris.status,
orders: orders, orders: orders,
recOrderCart: myorderCart recOrderCart: myorderCart
});
}); });
}); }
} }
}); });
}) })
@@ -350,7 +351,6 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
let idapp = req.body.idapp; let idapp = req.body.idapp;
let userId = req.params.userId; let userId = req.params.userId;
let order_id = req.body.order_id; let order_id = req.body.order_id;
const user = req.user;
let status = req.body.status; let status = req.body.status;
let options = req.body.options; let options = req.body.options;
@@ -402,7 +402,7 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
let orderscart = null; let orderscart = null;
if (User.isManager(user.perm)) { if (User.isManager(req.user.perm)) {
// Prende Tutti gli Ordini ! // Prende Tutti gli Ordini !
orderscart = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false); orderscart = await OrdersCart.getOrdersCartByUserId('ALL', idapp, 0, false);
} else { } else {
@@ -423,7 +423,6 @@ router.post('/:userId/ordercartstatus', authenticate, async function (req, res,
//POST cart //POST cart
router.post('/:userId/gestord', authenticate, async function (req, res, next) { router.post('/:userId/gestord', authenticate, async function (req, res, next) {
let idapp = req.body.idapp; let idapp = req.body.idapp;
const user = req.user;
let idGasordine = req.body.idGasordine; let idGasordine = req.body.idGasordine;
const { User } = require('../models/user'); const { User } = require('../models/user');

View File

@@ -9,7 +9,7 @@ const i18n = require('i18n');
const sharp = require('sharp'); const sharp = require('sharp');
const { authenticate, authenticate_noerror } = require( const { authenticate, authenticate_noerror, authenticate_noerror_WithUser, authenticate_noerror_WithUserLean } = require(
'../middleware/authenticate'); '../middleware/authenticate');
const { ObjectId } = require('mongodb'); const { ObjectId } = require('mongodb');
@@ -45,6 +45,7 @@ const { Contribtype } = require('../models/contribtype');
const { PaymentType } = require('../models/paymenttype'); const { PaymentType } = require('../models/paymenttype');
const { Discipline } = require('../models/discipline'); const { Discipline } = require('../models/discipline');
const { MyElem } = require('../models/myelem'); const { MyElem } = require('../models/myelem');
const { Cron } = require('../models/cron');
const { Skill } = require('../models/skill'); const { Skill } = require('../models/skill');
const { Good } = require('../models/good'); const { Good } = require('../models/good');
const { StatusSkill } = require('../models/statusSkill'); const { StatusSkill } = require('../models/statusSkill');
@@ -84,6 +85,10 @@ const Department = require('../models/department');
const { Category } = require('../models/category'); const { Category } = require('../models/category');
const Group = require('../models/group'); 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 tools = require('../tools/general');
const server_constants = require('../tools/server_constants'); const server_constants = require('../tools/server_constants');
@@ -350,13 +355,14 @@ router.post('/settable', authenticate, async (req, res) => {
try { try {
if (User.isAdmin(req.user.perm) || User.isManager(req.user.perm) || 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; consentito = true;
} }
if ((!User.isAdmin(req.user.perm) if ((!User.isAdmin(req.user.perm)
&& !User.isManager(req.user.perm) && !User.isManager(req.user.perm)
&& !User.isEditor(req.user.perm) && !User.isEditor(req.user.perm)
&& !User.isCommerciale(req.user.perm)
&& !User.isGrafico(req.user.perm) && !User.isGrafico(req.user.perm)
&& !User.isFacilitatore(req.user.perm)) && !User.isFacilitatore(req.user.perm))
&& &&
@@ -514,7 +520,7 @@ router.post('/settable', authenticate, async (req, res) => {
}) })
.then(async (risult) => { .then(async (risult) => {
let rec = null; let rec = null;
if (risult && risult.ok === 1) { if (risult && risult.acknowledged) {
rec = await mytable.findById(mytablerec._id).lean(); rec = await mytable.findById(mytablerec._id).lean();
} else { } else {
rec = risult; rec = risult;
@@ -714,7 +720,7 @@ router.post('/gettable', authenticate_noerror, (req, res) => {
params.table = sanitizeHtml(params.table); params.table = sanitizeHtml(params.table);
if (!shared_consts.TABLES_ENABLE_GETTABLE_FOR_NOT_LOGGED.includes(params.table) && !req.user) { 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); 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; const params = req.body;
let idapp = req.user.idapp; let idapp = req.body.idapp;
let mytable = globalTables.getTableByTableName(params.table); let mytable = globalTables.getTableByTableName(params.table);
// console.log('mytable', mytable); // console.log('mytable', mytable);
if (!mytable) { if (!mytable) {
@@ -990,7 +996,7 @@ async function upsertRecord(table, record, appId, newIdPage = null) {
record.idPage = newIdPage; record.idPage = newIdPage;
} }
const modif = await table.updateOne({ _id: record._id }, { $set: { ...record, idapp: appId } }); const modif = await table.updateOne({ _id: record._id }, { $set: { ...record, idapp: appId } });
wasModified = modif.nModified > 0; wasModified = modif.modifiedCount > 0;
} else { } else {
// Se sono sulla tabella mypages // Se sono sulla tabella mypages
if (table.modelName === 'MyPage') { if (table.modelName === 'MyPage') {
@@ -1061,7 +1067,7 @@ async function importPage(req, idapp, jsonString) {
const table = globalTables.getTableByTableName(tableName); const table = globalTables.getTableByTableName(tableName);
if (tableName === 'mypages') { 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) { for (const page of myexp.mypages) {
const { ImportedRecords, newId } = await upsertRecord(table, page, idapp); const { ImportedRecords, newId } = await upsertRecord(table, page, idapp);
if (!newIdPage && newId) { if (!newIdPage && newId) {
@@ -1091,7 +1097,7 @@ async function importPage(req, idapp, jsonString) {
const table = globalTables.getTableByTableName(tableName); const table = globalTables.getTableByTableName(tableName);
if (tableName === 'myelems') { 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) { for (const elem of myexp.myelems) {
const { ImportedRecords, newId } = await upsertRecord(table, elem, idapp, newIdPage); const { ImportedRecords, newId } = await upsertRecord(table, elem, idapp, newIdPage);
ImportedRecordstemp += ImportedRecords ? 1 : 0; ImportedRecordstemp += ImportedRecords ? 1 : 0;
@@ -1160,6 +1166,7 @@ router.post('/duppage', authenticate, async (req, res) => {
} }
}); });
router.post('/exppage', authenticate, async (req, res) => { router.post('/exppage', authenticate, async (req, res) => {
const params = req.body; const params = req.body;
const idapp = req.body.idapp; const idapp = req.body.idapp;
@@ -1253,6 +1260,7 @@ router.patch('/chval', authenticate, async (req, res) => {
(!User.isAdmin(req.user.perm) (!User.isAdmin(req.user.perm)
&& !User.isManager(req.user.perm) && !User.isManager(req.user.perm)
&& !User.isEditor(req.user.perm) && !User.isEditor(req.user.perm)
&& !User.isCommerciale(req.user.perm)
&& !User.isFacilitatore(req.user.perm)) && !User.isFacilitatore(req.user.perm))
&& (await !tools.ModificheConsentite(req, mydata.table, fieldsvalue, id))) && (await !tools.ModificheConsentite(req, mydata.table, fieldsvalue, id)))
&& !((mydata.table === 'accounts') && !((mydata.table === 'accounts')
@@ -1615,7 +1623,7 @@ router.get('/copyfromapptoapp/:idapporig/:idappdest', async (req, res) => {
if (!idapporig || !idappdest || (idcode !== 'ASD3429Kjgà#@cvX')) if (!idapporig || !idappdest || (idcode !== 'ASD3429Kjgà#@cvX'))
res.status(400).send(); res.status(400).send();
const mytablesstr = ['settings', 'users', 'templemail']; const mytablesstr = ['settings', 'users', 'templemail', 'destnewsletter'];
try { try {
let numrectot = 0; 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'); load(req, res, '0');
}); });
router.get('/loadsite/:userId/:idapp/:vers', authenticate_noerror, // Funzione di test per misurare le performance di MongoDB
async (req, res) => { 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 versionstr = req.params.vers;
let version = tools.getVersionint(versionstr); let version = tools.getVersionint(versionstr);
return await load(req, res, version); 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'; // Ricostruisco l'oggetto data con i risultati
try { const data = keys.reduce((acc, key, index) => {
userId = req.user ? req.user._id.toString() : req.params.userId; acc[key] = results[index];
} catch (e) { return acc;
console.error('Err userId LOAD', e); }, {});
userId = '0';
}
const idapp = req.params.idapp;
let status = 200 // Ordina le chiamate per tempo decrescente e prende le 10 più lente
if (req.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) { const slowCalls = Object.entries(timings)
status = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED .sort(([, timeA], [, timeB]) => timeB - timeA)
} .slice(0, 10)
.map(([key, time]) => ({ key, time }));
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);
});
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) => { router.get(process.env.LINK_CHECK_UPDATES, authenticate_noerror, async (req, res) => {
const idapp = req.query.idapp; const idapp = req.query.idapp;
@@ -2286,7 +2323,7 @@ function uploadFile(req, res, version) {
if (tools.sulServer()) { if (tools.sulServer()) {
dirmain = ''; dirmain = '';
} else { } else {
dirmain = '/public'; dirmain = server_constants.DIR_PUBLIC_LOCALE;
} }
} }
@@ -2478,14 +2515,14 @@ function deleteFile(req, res, version) {
const idapp = req.user.idapp; const idapp = req.user.idapp;
if (!relativefile || relativefile.endsWith('/')) { if (!relativefile || relativefile.endsWith('/')) {
res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
} }
try { try {
let dirmain = ''; let dirmain = '';
if (version > 0) { if (version > 0) {
if (!tools.sulServer()) { 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); console.log('Delete file ' + relativefile);
// ++ Move in the folder application ! // ++ Move in the folder application !
let fullpathfile = tools.getdirByIdApp(idapp) + dirmain + '/' + let fullpathfile = tools.getdirByIdApp(idapp) + dirmain + '/' +
relativefile; relativefile.replace(/^\//, '');
tools.delete(fullpathfile, true, (err) => { tools.delete(fullpathfile, true, (err) => {
if (err) console.log('err', err); if (err) console.log('err', err);
if (err === undefined || err.errno === -2) 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) { } catch (e) {

View File

@@ -59,9 +59,11 @@ router.post('/load', authenticate, async (req, res) => {
if (data.mycircuits) { if (data.mycircuits) {
for (let i = 0; i < data.mycircuits.length; i++) { for (let i = 0; i < data.mycircuits.length; i++) {
const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].circuitname }).lean(); const mycirc = await Circuit.findOne({ idapp, name: data.mycircuits[i].name }).lean();
if (mycirc) if (mycirc) {
data.mycircuits[i].account = await Account.getAccountByUsernameAndCircuitId(idapp, '', mycirc._id, true, true, groupname); data.mycircuits[i].account = await Account.getAccountByUsernameAndCircuitId(idapp, '', mycirc._id, true, true, groupname);
data.mycircuits[i].account = tools.jsonCopy(data.mycircuits[i].account);
}
} }
} }

View File

@@ -10,6 +10,7 @@ const { User } = require('../models/user');
const { MailingList } = require('../models/mailinglist'); const { MailingList } = require('../models/mailinglist');
const { Newstosent } = require('../models/newstosent'); const { Newstosent } = require('../models/newstosent');
const { TemplEmail } = require('../models/templemail'); const { TemplEmail } = require('../models/templemail');
const { DestNewsletter } = require('../models/destnewsletter');
const { OpzEmail } = require('../models/opzemail'); const { OpzEmail } = require('../models/opzemail');
const { Settings } = require('../models/settings'); const { Settings } = require('../models/settings');
@@ -254,12 +255,21 @@ router.post('/load', authenticate, async (req, res) => {
idapp = req.body.idapp; idapp = req.body.idapp;
locale = req.body.locale; locale = req.body.locale;
const ris = { let ris;
newsstate: await getDataNewsletter(locale, idapp),
serv_settings: await Settings.findAllIdApp(idapp, true, false), try {
templemail: await TemplEmail.findAllIdApp(idapp, true), ris = {
opzemail: await OpzEmail.findAllIdApp(idapp) 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); return res.send(ris);
}); });
@@ -275,12 +285,19 @@ router.post('/setactivate', authenticate, async (req, res) => {
activate, activate,
}; };
return await Newstosent.findOneAndUpdate({ _id: id }, { $set: rec }, { new: false }).then((item) => { try {
const ris = getDataNewsletter(locale, idapp); 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) { if (myuser) {
const hashcalc = tools.getHash(myuser.email + myuser.username); const hashcalc = tools.getHash(myuser.email + myuser.username);
if (hashcalc === hashemail) { if (hashcalc === hashemail) {
await User.setNewsletter(idapp, myuser.username, false); await User.setNewsletter(idapp, myuser.username, false);
return res.send({ return res.send({
@@ -329,28 +346,37 @@ router.post('/unsubscribe', (req, res) => {
console.log('Remove_from_MailingList -> ', ris); console.log('Remove_from_MailingList -> ', ris);
if (!!ris.myperson && mailchimpactive) { if (!!ris.myperson && mailchimpactive) {
const subscriber_md5_email = tools.getmd5(ris.myperson.email); try {
request const subscriber_md5_email = tools.getmd5(ris.myperson.email);
.put('https://' + newsletter[idapp].mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + newsletter[idapp].listUniqueId + '/members/' + subscriber_md5_email) request
.set('Content-Type', 'application/json;charset=utf-8') .put('https://' + newsletter[idapp].mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + newsletter[idapp].listUniqueId + '/members/' + subscriber_md5_email)
.set('Authorization', 'Basic ' + new Buffer('any:' + newsletter[idapp].mailchimpApiKey).toString('base64')) .set('Content-Type', 'application/json;charset=utf-8')
.send({ .set('Authorization', 'Basic ' + new Buffer('any:' + newsletter[idapp].mailchimpApiKey).toString('base64'))
'email_address': ris.myperson.email, .send({
'status': server_constants.RIS_UNSUBSCRIBED_STR 'email_address': ris.myperson.email,
}) 'status': server_constants.RIS_UNSUBSCRIBED_STR
.end(function (err, response) { })
console.log("STAT", response.status); .end(function (err, response) {
console.log("STAT", response.status);
if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) { if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
res.send({ res.send({
code: server_constants.RIS_UNSUBSCRIBED_OK code: server_constants.RIS_UNSUBSCRIBED_OK
}); });
} else { } else {
res.send({ res.send({
code: server_constants.RIS_SUBSCRIBED_ERR 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 { } else {
res.send({ code: ris.code, msg: ris.msg }); res.send({ code: ris.code, msg: ris.msg });

View File

@@ -89,6 +89,8 @@ router.get('/id/:id', async function (req, res) {
var product = await Product.getProductById(id); var product = await Product.getProductById(id);
// console.log('Product ID', id, product);
if (product) { if (product) {
return res.send({ code: server_constants.RIS_CODE_OK, product: product }); return res.send({ code: server_constants.RIS_CODE_OK, product: product });
} else { } else {

View File

@@ -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); const risreac = await Reaction.calcReactions(idapp, id, tab);
if (risreac) { if (risreac) {

View File

@@ -4,7 +4,7 @@ const router = express.Router();
const tools = require('../tools/general'); const tools = require('../tools/general');
const server_constants = require('../tools/server_constants'); 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 { SendNotif } = require('../models/sendnotif');
const { User } = require('../models/user'); 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); return getNotif(req, res);
}); });

View File

@@ -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); // tools.mylog("TOKENREM = " + req.token);
try { try {
const browser = req.get('User-Agent'); const browser = req.get('User-Agent');
Subscription.findOneAndDelete( return await Subscription.findOneAndDelete(
{ userId: req.user._id, access: req.access, browser }).then(() => { { userId: req.user._id, access: req.access, browser }).then(() => {
res.status(200).send(); res.status(200).send();
}, () => { }, () => {
res.status(400).send(); res.status(400).send();
}); });
} catch (e) { } catch (e) {
console.error('Err:', e.message);
} }
}); });

View File

@@ -14,6 +14,7 @@ const { ObjectId } = require('mongodb');
const sendemail = require('../sendemail'); const sendemail = require('../sendemail');
const { Settings } = require('../models/settings'); const { Settings } = require('../models/settings');
const CronMod = require('../modules/CronMod');
const { SendNotif } = require('../models/sendnotif'); const { SendNotif } = require('../models/sendnotif');
const { MyElem } = require('../models/myelem'); const { MyElem } = require('../models/myelem');
@@ -31,7 +32,7 @@ const _ = require('lodash');
const reg = require('../reg/registration'); 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'); const Cart = require('../models/cart');
@@ -54,14 +55,15 @@ const { Account } = require('../models/account');
const mongoose = require('mongoose').set('debug', false); const mongoose = require('mongoose').set('debug', false);
const Subscription = require('../models/subscribers'); const Subscription = require('../models/subscribers');
const Macro = require('../modules/Macro');
function existSubScribe(userId, access, browser) { async function existSubScribe(userId, access, browser) {
return Subscription.findOne({ userId, access, browser }).then(itemsub => { try {
const itemsub = await Subscription.findOne({ userId, access, browser }).lean();
return itemsub; return itemsub;
}).catch(err => { } catch (err) {
return null; return null;
}); }
} }
function getMobileComplete(user) { function getMobileComplete(user) {
@@ -393,7 +395,7 @@ router.post('/', async (req, res) => {
} catch (e) { } catch (e) {
console.error(e.message); console.error(e.message);
} }
}); });
router.get('/:idapp/:username', async (req, res) => { router.get('/:idapp/:username', async (req, res) => {
@@ -445,7 +447,6 @@ router.patch('/:id', authenticate, (req, res) => {
}); });
router.post('/lastmovs', authenticate, async (req, res) => { router.post('/lastmovs', authenticate, async (req, res) => {
const username = req.user ? req.user.username : '';
const nummov = req.body.nummov; const nummov = req.body.nummov;
const idapp = req.body.idapp; 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) => { router.post('/profile', authenticate, (req, res) => {
const usernameOrig = req.user ? req.user.username : ''; const usernameOrig = req.user ? req.user.username : '';
const perm = req.user ? req.user.perm : tools.Perm.PERM_NONE; const perm = req.user ? req.user.perm : tools.Perm.PERM_NONE;
const username = req.body['username']; const username = req.body['username'];
const idapp = req.body.idapp; const idapp = req.body.idapp;
const locale = req.body.locale;
//++Todo: controlla che tipo di dati ha il permesso di leggere //++Todo: controlla che tipo di dati ha il permesso di leggere
@@ -662,6 +684,8 @@ router.post('/newtok', async (req, res) => {
try { try {
const refreshToken = req.body.refreshToken; const refreshToken = req.body.refreshToken;
// return res.status(403).send({ error: 'Refresh token non valido' });
if (!refreshToken) { if (!refreshToken) {
return res.status(400).send({ error: 'Refresh token mancante' }); 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 }); const recFound = await User.findOne({ 'tokens.refreshToken': refreshToken });
if (!recFound) { 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); const { token, refreshToken: newRefreshToken } = await recFound.generateAuthToken(req);
@@ -712,11 +736,10 @@ function checkBlocked(req, res, next) {
next(); next();
} }
router.post('/login', checkBlocked, async (req, res) => {
router.post('/login', checkBlocked, (req, res) => { const body = _.pick(req.body,
var body = _.pick(req.body,
['username', 'password', 'idapp', 'keyappid', 'lang']); ['username', 'password', 'idapp', 'keyappid', 'lang']);
var user = new User(body); const userpass = new User(body);
// const subs = _.pick(req.body, ['subs']); // const subs = _.pick(req.body, ['subs']);
// tools.mylog("LOG: u: " + user.username + " p:" + user.password); // tools.mylog("LOG: u: " + user.username + " p:" + user.password);
@@ -728,135 +751,89 @@ router.post('/login', checkBlocked, (req, res) => {
let resalreadysent = false; 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). if (!user) {
then(async (user) => { const rislogin = await User.tooManyLoginWrong(body.idapp, body.username, true);
// tools.mylog("CREDENZIALI ! ");
if (!user) {
const rislogin = await User.tooManyLoginWrong(body.idapp, body.username, true); if (rislogin.troppilogin) {
if (rislogin.troppilogin) { let text = 'Troppe richieste di Login ERRATE: ' + body.username + ' [IP: ' + tools.getiPAddressUser(req) + '] Tentativi: ' + rislogin.retry_pwd;
let text = 'Troppe richieste di Login ERRATE: ' + body.username + ' [IP: ' + tools.getiPAddressUser(req) + '] Tentativi: ' + rislogin.retry_pwd; telegrambot.sendMsgTelegramToTheManagers(body.idapp, text);
telegrambot.sendMsgTelegramToTheManagers(body.idapp, text); console.log('/login', text);
console.log('/login', text); res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: text });
res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: text }); return;
return false; }
}
await tools.snooze(3000); await tools.snooze(2000);
if (!failedLoginAttempts[body.username]) { if (!failedLoginAttempts[body.username]) {
failedLoginAttempts[body.username] = 1; failedLoginAttempts[body.username] = 1;
} else { } else {
failedLoginAttempts[body.username]++; failedLoginAttempts[body.username]++;
} }
let numvolteerrati = failedLoginAttempts[body.username]; let numvolteerrati = failedLoginAttempts[body.username];
if (numvolteerrati > 2) { if (numvolteerrati > 2) {
const msg = 'Tentativo (' + numvolteerrati + ') di Login ERRATO [' + body.username + ' , ' + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + ']'; const msg = 'Tentativo (' + numvolteerrati + ') di Login ERRATO [' + body.username + ' , ' + ']\n' + '[IP: ' + tools.getiPAddressUser(req) + ']';
tools.mylogshow(msg); tools.mylogshow(msg);
await telegrambot.sendMsgTelegramToTheAdmin(myuser.idapp, msg, true); await telegrambot.sendMsgTelegramToTheAdmin(req.body.idapp, msg, true);
tools.writeErrorLog(msg); tools.writeErrorLog(msg);
} }
// telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg);
if (failedLoginAttempts[body.username] >= MAX_FAILED_ATTEMPTS) { if (failedLoginAttempts[body.username] >= MAX_FAILED_ATTEMPTS) {
blockUser(body.username); blockUser(body.username);
text = 'Troppi tentativi di accesso falliti. Utente bloccato (' + body.username + ')' + ' [IP: ' + tools.getiPAddressUser(req) + ']'; text = 'Troppi tentativi di accesso falliti. Utente bloccato (' + body.username + ')' + ' [IP: ' + tools.getiPAddressUser(req) + ']';
tools.mylogshow(text); tools.mylogshow(text);
telegrambot.sendMsgTelegramToTheManagers(req.body.idapp, text); telegrambot.sendMsgTelegramToTheManagers(req.body.idapp, text);
res.status(403).json({ message: text }); res.status(403).json({ message: text });
resalreadysent = true;
}
res.status(401).send({ code: server_constants.RIS_CODE_LOGIN_ERR });
resalreadysent = true; 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) => { return res.status(401).send({ code: server_constants.RIS_CODE_LOGIN_ERR });
usertosend[field] = user[field]; } else {
}); const myris = await user.generateAuthToken(req);
// usertosend._id = user._id.toHexString(); const usertosend = new User();
// if (!User.isAdmin(req.user)) {
// usertosend.ipaddr = user.ipaddr;
// }
// tools.mylog("user.verified_email:" + user.verified_email); shared_consts.fieldsUserToChange().forEach((field) => {
// tools.mylog("usertosend.userId", usertosend.userId); 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) => { res
const access = 'auth'; .header('x-auth', myris.token)
const browser = req.get('User-Agent'); .header('x-refrtok', myris.refreshToken)
.send({
// Check if already exist Subscribe usertosend,
return existSubScribe(myris.usertosend._id, access, browser). code: server_constants.RIS_CODE_OK,
then(subscribe => { subsExistonDb,
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')
}); });
}
}). }
catch((e) => {
console.error('ERRORE IN LOGIN: ' + e.message);
if (!resalreadysent) } catch (e) {
res.status(400). console.error('ERRORE IN LOGIN: ' + e.message);
send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC, msgerr: 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); // tools.mylog("TOKENREM = " + req.token);
req.user.removeToken(req.token).then(() => { try {
res.status(200).send(); req.user.removeToken(req.token).then(() => {
}, () => { res.status(200).send();
res.status(400).send(); }, () => {
}); res.status(400).send();
});
} catch (e) {
console.log('delete(/me/token', e.message);
}
}); });
router.post('/setperm', authenticate, (req, res) => { 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; const username = req.user.username;
idapp = req.body.idapp; idapp = req.body.idapp;
locale = req.body.locale; 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) { async function ConvertiDaIntAStr(mytable) {
try { try {
@@ -1610,7 +1087,7 @@ async function ConvertiDaIntAStr(mytable) {
const doc = await myrec.save(); const doc = await myrec.save();
ind++; ind++;
console.log('++Add (', ind, ')', doc._id); console.log('++Add (', ind, ')', doc._id);
} catch (err) { } catch (err) {
const myid = parseInt(err.keyValue._id, 10) + 0; const myid = parseInt(err.keyValue._id, 10) + 0;
const canc = await mytable.findOneAndDelete({ _id: myid }); const canc = await mytable.findOneAndDelete({ _id: myid });
if (canc) if (canc)
@@ -1697,22 +1174,19 @@ router.post('/dbop', authenticate, async (req, res) => {
locale = req.body.locale; locale = req.body.locale;
if (!User.isAdmin(req.user.perm)) { if (!User.isAdmin(req.user.perm)) {
// If without permissions, exit return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED });
return res.status(404).
send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
} }
try { try {
let risOp = await eseguiDbOp(idapp, mydata, locale, req, res);
// ris = await User.updateMyData(ris, idapp, req.user.username); const cronMod = new CronMod();
const risOp = await cronMod.eseguiDbOp(idapp, mydata, req, res);
res.send({ code: server_constants.RIS_CODE_OK, data: risOp });
return res.send({ code: server_constants.RIS_CODE_OK, data: risOp });
} catch (e) { } catch (e) {
res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e });
console.log(e.message); 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; const mydata = req.body.mydata;
idapp = req.body.idapp; idapp = req.body.idapp;

View File

@@ -12,6 +12,7 @@ const i18n = require('i18n');
const { ObjectId } = require('mongodb'); const { ObjectId } = require('mongodb');
const { Settings } = require('./models/settings'); const { Settings } = require('./models/settings');
const { TemplEmail } = require('./models/templemail'); const { TemplEmail } = require('./models/templemail');
const { DestNewsletter } = require('./models/destnewsletter');
const { Discipline } = require('./models/discipline'); const { Discipline } = require('./models/discipline');
const previewEmail = require('preview-email'); const previewEmail = require('preview-email');
@@ -57,6 +58,7 @@ module.exports = {
if (to === '') if (to === '')
return false; return false;
// console.log('mylocalsconf', mylocalsconf); // console.log('mylocalsconf', mylocalsconf);
// console.log("check EMAIL :" + checkifSendEmail()); // console.log("check EMAIL :" + checkifSendEmail());
@@ -88,7 +90,6 @@ module.exports = {
// transport = this.getTransport(mylocalsconf); // transport = this.getTransport(mylocalsconf);
// } // }
// console.log('1 . transport', transport);
if (transport) { if (transport) {
paramemail.transport = transport; paramemail.transport = transport;
@@ -166,7 +167,7 @@ module.exports = {
else else
transport_preview.sendMail(mailOptions).then(console.log).catch(console.error); transport_preview.sendMail(mailOptions).then(console.log).catch(console.error);
} }
} catch (e) { } catch (e) {
console.error('Errore Sendmail', e); console.error('Errore Sendmail', e);
} }
@@ -679,12 +680,20 @@ module.exports = {
replacefields: function (mylocalsconf) { replacefields: function (mylocalsconf) {
try { try {
mylocalsconf.dataemail.disclaimer_out = !!mylocalsconf.dataemail.disclaimer ? this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.disclaimer_out = !!mylocalsconf.dataemail.disclaimer ? this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.disclaimer) : '';
mylocalsconf.dataemail.disclaimer) : ''; mylocalsconf.dataemail.disc_bottom_out = !!mylocalsconf.dataemail.disc_bottom ? this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.disc_bottom) : '';
mylocalsconf.dataemail.disc_bottom_out = !!mylocalsconf.dataemail.disc_bottom ? this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.firma = !!mylocalsconf.dataemail.firma ? this.fieldsloop(mylocalsconf, mylocalsconf.dataemail.firma) : '';
mylocalsconf.dataemail.disc_bottom) : '';
if (mylocalsconf.dataemail.templ) { 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_out = !!mylocalsconf.dataemail.templ.testoheadermail ? this.fieldsloop(mylocalsconf,
mylocalsconf.dataemail.templ.testoheadermail) : ''; mylocalsconf.dataemail.templ.testoheadermail) : '';
@@ -700,38 +709,53 @@ module.exports = {
}, },
getdataemail: async (idapp, templemail_id) => { 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), try {
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'),
};
// console.log(mydata.templemail_id); const pwd_from = await Settings.getValDbSettings(idapp, 'PWD_FROM');
mydata.templ = await TemplEmail.findOne({ _id: mydata.templemail_id });
// console.log(mydata.templ); 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) => { getTransport: (mylocalsconf) => {
console.log('getTransport');
// Create Transport // Create Transport
let smtpTransport = null; let smtpTransport = null;
@@ -883,9 +907,6 @@ module.exports = {
await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio); await telegrambot.sendMsgTelegramToTheManagers(idapp, msginizio);
//++Todo Extract List Email to send
const userstosend = await MailingList.findAllIdAppSubscribed(idapp);
const myarrevents = await MyEvent.getLastEvents(idapp); const myarrevents = await MyEvent.getLastEvents(idapp);
let mylocalsconf = { let mylocalsconf = {
@@ -903,8 +924,24 @@ module.exports = {
const mynewsrec = await Newstosent.findOne({ _id: id_newstosent }); const mynewsrec = await Newstosent.findOne({ _id: id_newstosent });
try { try {
mynewsrec.numemail_tot = userstosend.length;
mynewsrec.templemail_str = mylocalsconf.dataemail.templ.subject; 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); mynewsrec.numemail_sent = await MailingList.getnumSent(idapp, id_newstosent);
const smtpTransport = this.getTransport(mylocalsconf); const smtpTransport = this.getTransport(mylocalsconf);
@@ -985,6 +1022,8 @@ module.exports = {
} catch (e) { } catch (e) {
console.error('*** Errore su sendEmail_Newsletter: ! ', e.message);
const activate = await Newstosent.isActivated(id_newstosent); const activate = await Newstosent.isActivated(id_newstosent);
if (!activate) { if (!activate) {

View File

@@ -2,13 +2,12 @@ require('./config/config');
// console.log(" lodash"); // 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) { if (process.env.AUTH_MONGODB === undefined) {
console.error("AUTH_MONGODB non presente. VARIABILI D'AMBIENTE NON SETTATI!"); console.error("AUTH_MONGODB non presente. VARIABILI D'AMBIENTE NON SETTATI!");
process.exit(1); process.exit(1);
} }
const _ = require('lodash'); const _ = require('lodash');
// console.log(" cors"); // console.log(" cors");
const cors = require('cors'); const cors = require('cors');
@@ -42,7 +41,6 @@ const path = require('path');
const cron = require('node-cron'); const cron = require('node-cron');
console.log('Starting mongoose...'); console.log('Starting mongoose...');
// console.log('Starting pem...'); // console.log('Starting pem...');
// const pem = require('pem') // const pem = require('pem')
@@ -78,7 +76,7 @@ connectToDatabase(connectionUrl, options)
.then(() => { .then(() => {
console.log('------------------------------------------------------------------'); console.log('------------------------------------------------------------------');
console.log('--------------- CONNESSIONE AL DB EFFETTUATA ! -----------------'); console.log('--------------- CONNESSIONE AL DB EFFETTUATA ! -----------------');
console.log('------------------------------------------------------------------'); console.log('------------------------------------------------------------------');
const { CfgServer } = require('./models/cfgserver'); const { CfgServer } = require('./models/cfgserver');
const { ObjectId } = require('mongodb'); const { ObjectId } = require('mongodb');
@@ -88,8 +86,7 @@ connectToDatabase(connectionUrl, options)
const printf = require('util').format; const printf = require('util').format;
myLoad().then(ris => { myLoad().then((ris) => {
const { User } = require('./models/user'); const { User } = require('./models/user');
require('./models/todo'); require('./models/todo');
@@ -147,6 +144,9 @@ connectToDatabase(connectionUrl, options)
app.use(express.static('views')); 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(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json()); app.use(bodyParser.json());
@@ -162,8 +162,8 @@ connectToDatabase(connectionUrl, options)
// cookie: 'cook', // cookie: 'cook',
directory: __dirname + '/locales', directory: __dirname + '/locales',
api: { api: {
'__': 'translate', __: 'translate',
'__n': 'translateN' __n: 'translateN',
}, },
}); });
@@ -173,14 +173,12 @@ connectToDatabase(connectionUrl, options)
// res.sendFile(path.join(__dirname, 'service-worker.js')); // Modifica il percorso secondo la tua struttura // res.sendFile(path.join(__dirname, 'service-worker.js')); // Modifica il percorso secondo la tua struttura
});*/ });*/
app.use(bodyParser.json()); app.use(bodyParser.json());
// app.use(express.cookieParser()); // app.use(express.cookieParser());
app.use(i18n.init); app.use(i18n.init);
console.log('Use Routes \...'); console.log('Use Routes ...');
// catch 404 and forward to error handler // catch 404 and forward to error handler
// app.use(function (req, res, next) { // app.use(function (req, res, next) {
@@ -195,7 +193,6 @@ connectToDatabase(connectionUrl, options)
// development error handler // development error handler
// will print stacktrace // will print stacktrace
if (app.get('env') === 'development') { if (app.get('env') === 'development') {
app.use(function (err, req, res, next) { app.use(function (err, req, res, next) {
console.log('Server Error: ', err.message); console.log('Server Error: ', err.message);
// console.trace(); // console.trace();
@@ -205,16 +202,13 @@ connectToDatabase(connectionUrl, options)
// error: err // error: err
// }); // });
}); });
} }
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
console.log('*** PRODUCTION! '); console.log('*** PRODUCTION! ');
} }
if ((process.env.NODE_ENV === 'production') || if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test') {
(process.env.NODE_ENV === 'test')) {
} }
startServer(app, process.env.PORT); startServer(app, process.env.PORT);
@@ -252,30 +246,23 @@ connectToDatabase(connectionUrl, options)
app.use('/aitools', aitools_router); app.use('/aitools', aitools_router);
app.use('/apisqlsrv', article_router); app.use('/apisqlsrv', article_router);
mystart(); mystart();
}); });
// app.use(throttle(1024 * 128)); // throttling bandwidth // app.use(throttle(1024 * 128)); // throttling bandwidth
async function myLoad() { async function myLoad() {
return tools.loadApps(); return tools.loadApps();
} }
async function mystart() { async function mystart() {
// await estraiTutteLeImmagini(); // await estraiTutteLeImmagini();
console.log('Versione Server: ' + await tools.getVersServer()); console.log('Versione Server: ' + (await tools.getVersServer()));
await tools.getApps(); await tools.getApps();
if (process.env.PROD !== 1) { if (process.env.PROD !== 1) {
testmsgwebpush(); testmsgwebpush();
// tools.sendNotifToAdmin('Riparti', 'Riparti'); // tools.sendNotifToAdmin('Riparti', 'Riparti');
@@ -291,12 +278,8 @@ connectToDatabase(connectionUrl, options)
} }
mycron(); mycron();
if (!process.env.VITE_DEBUG) {
mycron();
}
} }
telegrambot = require('./telegram/telegrambot'); telegrambot = require('./telegram/telegrambot');
await inizia(); await inizia();
@@ -312,14 +295,15 @@ connectToDatabase(connectionUrl, options)
const mailchimpClientId = 'xxxxxxxxxxxxxxxx'; const mailchimpClientId = 'xxxxxxxxxxxxxxxx';
app.get('/mailchimp/auth/authorize', function (req, res) { app.get('/mailchimp/auth/authorize', function (req, res) {
res.redirect('https://login.mailchimp.com/oauth2/authorize?' + res.redirect(
querystring.stringify({ 'https://login.mailchimp.com/oauth2/authorize?' +
'response_type': 'code', querystring.stringify({
'client_id': mailchimpClientId, response_type: 'code',
'redirect_uri': 'http://127.0.0.1:3000/mailchimp/auth/callback', client_id: mailchimpClientId,
})); redirect_uri: 'http://127.0.0.1:3000/mailchimp/auth/callback',
})
);
}); });
} }
// ----------------- // -----------------
@@ -332,22 +316,24 @@ connectToDatabase(connectionUrl, options)
chiave: 'vers', chiave: 'vers',
userId: 'ALL', userId: 'ALL',
valore: '0.1.2', valore: '0.1.2',
}]; },
];
let cfg = new CfgServer(cfgserv[0]).save(); let cfg = new CfgServer(cfgserv[0]).save();
} }
async function mycron() { async function mycron() {
try { try {
const sendemail = require('./sendemail'); const sendemail = require('./sendemail');
const arr = await tools.getApps(); const { Cron } = require('./models/cron');
const arr = await tools.getApps();
for (const app of arr) { for (const app of arr) {
await sendemail.checkifPendingNewsletter(app.idapp); await sendemail.checkifPendingNewsletter(app.idapp);
await sendemail.checkifSentNewsletter(app.idapp); await sendemail.checkifSentNewsletter(app.idapp);
await Cron.startJobCron(app.idapp);
} }
} catch (e) { } catch (e) {
console.error('Err mycron', e); console.error('Err mycron', e);
@@ -358,8 +344,7 @@ connectToDatabase(connectionUrl, options)
for (const app of await tools.getApps()) { for (const app of await tools.getApps()) {
let enablecrontab = false; let enablecrontab = false;
enablecrontab = await Settings.getValDbSettings(app.idapp, enablecrontab = await Settings.getValDbSettings(app.idapp, tools.ENABLE_CRONTAB, false);
tools.ENABLE_CRONTAB, false);
if (enablecrontab) { if (enablecrontab) {
// ... // ...
@@ -369,12 +354,10 @@ connectToDatabase(connectionUrl, options)
async function mycron_everyday() { async function mycron_everyday() {
try { try {
const { User } = require('./models/user'); const { User } = require('./models/user');
const arrapps = await tools.getApps(); const arrapps = await tools.getApps();
for (const app of arrapps) { for (const app of arrapps) {
// Azzera le richieste di password: // Azzera le richieste di password:
const usersblocked = await User.find({ idapp: app.idapp, retry_pwd: { $exists: true, $gte: 29 } }).lean(); const usersblocked = await User.find({ idapp: app.idapp, retry_pwd: { $exists: true, $gte: 29 } }).lean();
for (const user of usersblocked) { 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}`; 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); await telegrambot.sendMsgTelegramToTheAdminAllSites(text, false);
} }
} }
} catch (e) { } catch (e) {
console.error('mycron_everyday: ', e); console.error('mycron_everyday: ', e);
} }
} }
function testmsgwebpush() { function testmsgwebpush() {
const { User } = require('./models/user'); const { User } = require('./models/user');
@@ -399,10 +380,10 @@ connectToDatabase(connectionUrl, options)
User.find({ username: 'paoloar77', idapp: '1' }).then(async (arrusers) => { User.find({ username: 'paoloar77', idapp: '1' }).then(async (arrusers) => {
if (arrusers !== null) { if (arrusers !== null) {
for (const user of arrusers) { for (const user of arrusers) {
await tools.sendNotificationToUser(user._id, 'Server', await tools
'Il Server è Ripartito', '/', '', 'server', []).then(ris => { .sendNotificationToUser(user._id, 'Server', 'Il Server è Ripartito', '/', '', 'server', [])
.then((ris) => {
if (ris) { if (ris) {
} else { } else {
// already sent the error on calling sendNotificationToUser // 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 * * * *', () => { cron.schedule('*/1 * * * *', () => {
// console.log('Running Cron Job'); // console.log('Running Cron Job');
// if (!process.env.VITE_DEBUG) { // if (!process.env.VITE_DEBUG) {
@@ -421,7 +408,7 @@ connectToDatabase(connectionUrl, options)
// } // }
}); });
// Cron every X minutes // Cron every 1 HOUR
cron.schedule('*/60 * * * *', async () => { cron.schedule('*/60 * * * *', async () => {
if (!process.env.VITE_DEBUG) { if (!process.env.VITE_DEBUG) {
mycron_30min(); mycron_30min();
@@ -438,17 +425,13 @@ connectToDatabase(connectionUrl, options)
// tools.writelogfile('test', 'prova.txt'); // tools.writelogfile('test', 'prova.txt');
async function resetProcessingJob() { async function resetProcessingJob() {
const { Newstosent } = require('./models/newstosent'); const { Newstosent } = require('./models/newstosent');
arrrec = await Newstosent.find({}); arrrec = await Newstosent.find({});
for (const rec of arrrec) { for (const rec of arrrec) {
rec.processing_job = false; rec.processing_job = false;
await Newstosent.findOneAndUpdate({ _id: rec.id }, { $set: rec }, { new: false }). await Newstosent.findOneAndUpdate({ _id: rec.id }, { $set: rec }, { new: false }).then((item) => {});
then((item) => {
});
} }
} }
@@ -457,7 +440,6 @@ connectToDatabase(connectionUrl, options)
//}); //});
async function inizia() { async function inizia() {
try { try {
if (true) { if (true) {
const url = 'https://raw.githubusercontent.com/matteocontrini/comuni-json/master/comuni.json'; const url = 'https://raw.githubusercontent.com/matteocontrini/comuni-json/master/comuni.json';
@@ -468,19 +450,22 @@ connectToDatabase(connectionUrl, options)
mycron_everyday(); mycron_everyday();
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
await telegrambot.sendMsgTelegram(tools.FREEPLANET, await telegrambot.sendMsgTelegram(
tools.FREEPLANET,
shared_consts.ADMIN_USER_SERVER, 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, telegrambot.ADMIN_IDTELEGRAM_SERVER,
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}\n` + `Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}\n` + `🔅 Il Server ${process.env.DATABASE} è appena ripartito!`
`🔅 Il Server ${process.env.DATABASE} è appena ripartito!`); );
} else { } else {
await telegrambot.sendMsgTelegramToTheAdminAllSites(
await telegrambot.sendMsgTelegramToTheAdminAllSites(`Ciao Admin\n` + `🔅🔅🔅 Il Server col BOT di {appname} è appena ripartito!`, false); `Ciao Admin\n` + `🔅🔅🔅 Il Server col BOT di {appname} è appena ripartito!`,
false
);
} }
await Site.createFirstUserAdmin(); await Site.createFirstUserAdmin();
@@ -490,13 +475,7 @@ connectToDatabase(connectionUrl, options)
await Circuit.setDeperimentoOff(); await Circuit.setDeperimentoOff();
*/ */
} catch (e) {}
} catch (e) {
}
} }
// //
@@ -522,10 +501,8 @@ connectToDatabase(connectionUrl, options)
const globalTables = require('./tools/globalTables'); const globalTables = require('./tools/globalTables');
const mytable = globalTables.getTableByTableName(table); const mytable = globalTables.getTableByTableName(table);
if (!mytable) if (!mytable) return;
return;
console.log('INIZIO - estraiImmagini', table); console.log('INIZIO - estraiImmagini', table);
@@ -536,13 +513,14 @@ connectToDatabase(connectionUrl, options)
let dirmain = ''; let dirmain = '';
let filefrom = ''; let filefrom = '';
let filefrom2 = ''; let filefrom2 = '';
let dir = tools.getdirByIdApp(idapp) + dirmain + '/upload/';
try { try {
if (!tools.sulServer()) { if (!tools.sulServer()) {
dirmain = '/public'; dirmain = server_constants.DIR_PUBLIC_LOCALE;
} }
let dir = tools.getdirByIdApp(idapp) + dirmain + '/upload/';
for (const rec of arrlist) { for (const rec of arrlist) {
const myuser = await User.findOne({ idapp, _id: rec.userId }).lean(); const myuser = await User.findOne({ idapp, _id: rec.userId }).lean();
if (myuser) { if (myuser) {
@@ -564,16 +542,12 @@ connectToDatabase(connectionUrl, options)
console.log('creadir', folderprof); console.log('creadir', folderprof);
fs.mkdirSync(folderprof); fs.mkdirSync(folderprof);
} }
} catch (e) { } catch (e) {}
}
} }
for (const photo of myphotos) { for (const photo of myphotos) {
if (photo.imagefile) { if (photo.imagefile) {
file = dir + 'profile/' + myuser.username + '/' + table + '/' + file = dir + 'profile/' + myuser.username + '/' + table + '/' + photo.imagefile;
photo.imagefile;
filefrom = dir + 'profile/undefined/' + table + '/' + photo.imagefile; filefrom = dir + 'profile/undefined/' + table + '/' + photo.imagefile;
filefrom2 = dir + 'profile/' + myuser.username + '/' + photo.imagefile; filefrom2 = dir + 'profile/' + myuser.username + '/' + photo.imagefile;
@@ -606,7 +580,6 @@ connectToDatabase(connectionUrl, options)
} }
async function estraiTutteLeImmagini() { async function estraiTutteLeImmagini() {
await estraiImmagini('myskills'); await estraiImmagini('myskills');
await estraiImmagini('mygoods'); await estraiImmagini('mygoods');
await estraiImmagini('mybachecas'); await estraiImmagini('mybachecas');
@@ -651,30 +624,24 @@ connectToDatabase(connectionUrl, options)
const langdest = 'it'; const langdest = 'it';
telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser); telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser);
} }
if (false) { if (false) {
const user = await User.findOne({ const user = await User.findOne({
idapp: 12, idapp: 12,
username: 'paolotest1', username: 'paolotest1',
}); });
await sendemail.sendEmail_Registration('it', 'paolo@arcodiluce.it', user, await sendemail.sendEmail_Registration('it', 'paolo@arcodiluce.it', user, '12', '');
'12', '');
} }
if (false) { if (false) {
const { User } = require('./models/user'); const { User } = require('./models/user');
const idapp = tools.FREEPLANET; const idapp = tools.FREEPLANET;
const idreg = 0; const idreg = 0;
try { try {
const user = await User.findOne({ const user = await User.findOne({
idapp, idapp,
username: 'paoloar773', username: 'paoloar773',
@@ -697,8 +664,7 @@ connectToDatabase(connectionUrl, options)
user, user,
}; };
await telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION, await telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION, mylocalsconf);
mylocalsconf);
} catch (e) { } catch (e) {
console.log('error ' + e); console.log('error ' + e);
} }
@@ -706,7 +672,6 @@ connectToDatabase(connectionUrl, options)
} }
function getCredentials(hostname) { function getCredentials(hostname) {
if (NUOVO_METODO_TEST) { if (NUOVO_METODO_TEST) {
if (METODO_MULTI_CORS) { if (METODO_MULTI_CORS) {
const fileprivkey = `/etc/letsencrypt/live/${hostname}/` + process.env.PATH_CERT_KEY; const fileprivkey = `/etc/letsencrypt/live/${hostname}/` + process.env.PATH_CERT_KEY;
@@ -737,36 +702,22 @@ connectToDatabase(connectionUrl, options)
};*/ };*/
try { try {
const key = fs.readFileSync(fileprivkey, "utf8"); const key = fs.readFileSync(fileprivkey, 'utf8');
const cert = fs.readFileSync(filecert, "utf8"); const cert = fs.readFileSync(filecert, 'utf8');
return { key, cert }; return { key, cert };
} catch (error) { } catch (error) {
console.error(`Errore nel caricamento delle credenziali per ${hostname}:`, error); console.error(`Errore nel caricamento delle credenziali per ${hostname}:`, error);
// Gestisci l'errore, per esempio ritorna null o lancia un'eccezione // Gestisci l'errore, per esempio ritorna null o lancia un'eccezione
} }
} else { } else {
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`); const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`); const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
const privateKey = fs.readFileSync(keyStream, "utf8"); const privateKey = fs.readFileSync(keyStream, 'utf8');
const certificate = fs.readFileSync(certificateStream, "utf8"); const certificate = fs.readFileSync(certificateStream, 'utf8');
return { key: privateKey, cert: certificate }; 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 // 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); const isProduction = ['production', 'test'].includes(process.env.NODE_ENV);
let domains = []; let domains = [];
let domains_allowed = [];
try { try {
if (process.env.DOMAINS) if (process.env.DOMAINS) domains = JSON.parse(process.env.DOMAINS);
domains = JSON.parse(process.env.DOMAINS); if (process.env.DOMAINS_ALLOWED) domains_allowed = JSON.parse(process.env.DOMAINS_ALLOWED);
} catch (error) { } 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); console.log('domains', domains);
@@ -792,47 +744,73 @@ connectToDatabase(connectionUrl, options)
console.log('isProduction', isProduction); console.log('isProduction', isProduction);
const NOCORS = false; const NOCORS = false;
const CORS_ENABLE_FOR_ALL_SITES = false;
const ISDEBUG = false; const ISDEBUG = false;
let corsOptions = {}; let corsOptions = {};
if (NOCORS) { if (NOCORS) {
console.log('NOCORS') console.log('NOCORS');
corsOptions = { corsOptions = {
exposedHeaders: ['x-auth', 'x-refrtok'], // Intestazioni da esporre al client exposedHeaders: ['x-auth', 'x-refrtok'], // Intestazioni da esporre al client
}; };
} else { } else {
console.log('WITH CORS') console.log('WITH CORS');
let myorigin = '*'; let credentials = true;
let credentials = false;
const allowedOrigins = domains.flatMap(domain => [ let allowedOrigins = null;
`https://${domain.hostname}`,
`https://api.${domain.hostname}`, if (!isProduction) {
`https://test.${domain.hostname}`, allowedOrigins = 'https://localhost:3000';
`https://testapi.${domain.hostname}`, } else {
`http://${domain.hostname}`, allowedOrigins = domains.flatMap((domain) => [
`http://api.${domain.hostname}`, `https://${domain.hostname}`,
`http://test.${domain.hostname}`, `https://api.${domain.hostname}`,
`http://testapi.${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) { if (domains.length > 0) {
myorigin = function (origin, callback) { myorigin = (origin, callback) => {
// Array di domini consentiti 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) // Blocco delle origini non autorizzate
if (!origin || allowedOrigins.includes(origin)) { console.warn('❌ Origine bloccata:', origin);
callback(null, true); return callback(new Error('CORS non permesso per questa origine'), false);
} else { } catch (error) {
callback(new Error('❌ CORS non permesso per questa origine')); console.error("Errore durante la verifica dell'origine:", error.message);
return callback(error, false);
} }
} };
} }
// Configurazione CORS dettagliata // Configurazione CORS dettagliata
@@ -847,12 +825,12 @@ connectToDatabase(connectionUrl, options)
'Accept', 'Accept',
'Authorization', 'Authorization',
'x-auth', 'x-auth',
'x-refrtok' 'x-refrtok',
], ],
exposedHeaders: ['x-auth', 'x-refrtok'], exposedHeaders: ['x-auth', 'x-refrtok'],
maxAge: 86400, // Preflight cache 24 ore maxAge: 86400, // Preflight cache 24 ore
preflightContinue: false, preflightContinue: false,
optionsSuccessStatus: 204 optionsSuccessStatus: 204,
}; };
// Applica CORS come primo middleware // Applica CORS come primo middleware
@@ -861,44 +839,20 @@ connectToDatabase(connectionUrl, options)
// HO AGGIUNTO QUESTA RIGA PER IL CORS !!!!!!! // HO AGGIUNTO QUESTA RIGA PER IL CORS !!!!!!!
app.use(express.json()); // Middleware per il parsing del corpo JSON app.use(express.json()); // Middleware per il parsing del corpo JSON
// Gestione specifica delle richieste OPTIONS app.options('*', cors(corsOptions)); // Gestisce tutte le 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();
}
});*/
// Middleware per assicurarsi che gli headers CORS siano sempre presenti // Middleware personalizzato per assicurare gli headers CORS
app.use((req, res, next) => { /*app.use((req, res, next) => {
let origin = req.headers.origin; const origin = req.headers.origin || '*';
if (!origin) { if (allowedOrigins.includes(origin) || corsOptions.origin === '*') {
origin = '*'; // console.log(' ... ORIGIN', origin);
}
if (corsOptions.origin === '*' ||
(typeof corsOptions.origin === 'function' &&
corsOptions.origin.toString().includes(origin))) {
//console.log('Access-Control-Allow-Origin')
res.setHeader('Access-Control-Allow-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-Allow-Credentials', 'true');
res.setHeader('Access-Control-Expose-Headers', 'x-auth, x-refrtok'); res.setHeader('Access-Control-Expose-Headers', 'x-auth, x-refrtok');
} }
next(); next();
}); });*/
// Log middleware per debug // Log middleware per debug
app.use((req, res, next) => { app.use((req, res, next) => {
@@ -925,11 +879,11 @@ connectToDatabase(connectionUrl, options)
console.error('❌ Errore CORS:', { console.error('❌ Errore CORS:', {
origin: req.headers.origin, origin: req.headers.origin,
method: req.method, method: req.method,
path: req.path path: req.path,
}); });
res.status(403).json({ res.status(403).json({
error: '❌ CORS non permesso per questa origine (' + req.headers.origin + ')', error: '❌ CORS non permesso per questa origine (' + req.headers.origin + ')',
origin: req.headers.origin origin: req.headers.origin,
}); });
} else { } else {
next(err); next(err);
@@ -937,34 +891,42 @@ connectToDatabase(connectionUrl, options)
}); });
} }
if (isProduction) { if (isProduction) {
for (let i = 0; i < domains.length; i++) { for (let i = 0; i < domains.length; i++) {
const credentials = getCredentials(domains[i].hostname); const mycredentials = getCredentials(domains[i].hostname);
// console.log('credentials: ', credentials); // console.log('credentials: ', credentials);
httpsServer = https.createServer(credentials, app); httpsServer = https.createServer(mycredentials, app);
console.log('⭐️⭐️⭐️⭐️⭐️ HTTPS server: ' + domains[i].hostname + ' Port:', domains[i].port + (domains[i].website ? 'WebSite = ' + domains[i].website : '')); console.log(
'⭐️⭐️⭐️⭐️⭐️ HTTPS server: ' + domains[i].hostname + ' Port:',
domains[i].port + (domains[i].website ? 'WebSite = ' + domains[i].website : '')
);
httpsServer.listen(domains[i].port); httpsServer.listen(domains[i].port);
} }
} else { } else {
if (process.env.HTTPS_LOCALHOST === "true") { if (process.env.HTTPS_LOCALHOST === 'true') {
let credentials = null; let mycredentials = null;
try { try {
credentials = { const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
key: fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8'), const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
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 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, honorCipherOrder: true,
secureProtocol: 'TLSv1_2_method' secureProtocol: 'TLSv1_2_method',
}; };
} catch (error) { } catch (error) {
console.error('Errore durante la lettura dei file di certificazione, error:', error.message); console.error('Errore durante la lettura dei file di certificazione, error:', error.message);
throw error; throw error;
} }
if (credentials) { if (mycredentials) {
httpsServer = https.createServer(credentials, app); httpsServer = https.createServer(mycredentials, app);
console.log('⭐️⭐️⭐️ HTTPS server IN LOCALE : port', port); console.log('⭐️⭐️⭐️ HTTPS server IN LOCALE : port', port);
httpsServer.listen(port); httpsServer.listen(port);
} else { } else {
@@ -976,7 +938,6 @@ connectToDatabase(connectionUrl, options)
} }
// console.log('credentials', credentials); // console.log('credentials', credentials);
} else { } else {
httpServer = http.createServer(app); httpServer = http.createServer(app);
if (httpServer) { if (httpServer) {
@@ -998,7 +959,6 @@ connectToDatabase(connectionUrl, options)
} }
if (wss) { if (wss) {
wss.on('connection', (ws) => { wss.on('connection', (ws) => {
console.log('Client socket connected...'); console.log('Client socket connected...');
@@ -1009,12 +969,10 @@ connectToDatabase(connectionUrl, options)
const pty = require('node-pty'); const pty = require('node-pty');
ws.on('message', (message) => { ws.on('message', (message) => {
const parsedMessage = JSON.parse(message); const parsedMessage = JSON.parse(message);
try { try {
if (parsedMessage.type === 'start_script' && User.isAdminById(parsedMessage.user_id)) {
if ((parsedMessage.type === 'start_script') && (User.isAdminById(parsedMessage.user_id))) {
if (scriptProcess) { if (scriptProcess) {
scriptProcess.kill(); scriptProcess.kill();
} }
@@ -1028,7 +986,7 @@ connectToDatabase(connectionUrl, options)
cols: 80, cols: 80,
rows: 40, rows: 40,
cwd: process.cwd(), cwd: process.cwd(),
env: process.env env: process.env,
}); });
let buffer = ''; let buffer = '';
@@ -1039,11 +997,14 @@ connectToDatabase(connectionUrl, options)
ws.send(JSON.stringify({ type: 'output', data: data })); ws.send(JSON.stringify({ type: 'output', data: data }));
// Controlla se c'è una richiesta di input // Controlla se c'è una richiesta di input
if (buffer && (buffer.endsWith(': ') || buffer.includes('? ') || if (
buffer.toLowerCase().includes('password') buffer &&
|| buffer.includes('Inserisci') (buffer.endsWith(': ') ||
|| buffer.includes('Inserted') buffer.includes('? ') ||
|| buffer.includes('(Y')) buffer.toLowerCase().includes('password') ||
buffer.includes('Inserisci') ||
buffer.includes('Inserted') ||
buffer.includes('(Y'))
) { ) {
ws.send(JSON.stringify({ type: 'input_required', prompt: data.trim() })); ws.send(JSON.stringify({ type: 'input_required', prompt: data.trim() }));
buffer = ''; buffer = '';
@@ -1070,11 +1031,9 @@ connectToDatabase(connectionUrl, options)
scriptProcess.write(parsedMessage.data + '\n'); scriptProcess.write(parsedMessage.data + '\n');
} }
} }
} catch (error) { } 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', () => { ws.on('close', () => {
@@ -1084,24 +1043,17 @@ connectToDatabase(connectionUrl, options)
} }
}); });
}); });
} else { } else {
console.error('Nessuna Socket Aperta con WebSocket !!'); console.error('Nessuna Socket Aperta con WebSocket !!');
} }
} catch (e) { } catch (e) {
console.log('error startServer: ' + e); console.log('error startServer: ' + e);
} }
} }
}) })
.catch(err => { .catch((err) => {
console.error("Impossibile connettersi al database dopo diversi tentativi:", err); console.error('Impossibile connettersi al database dopo diversi tentativi:', err);
process.exit(1); // Termina il processo se non riesce a connettersi process.exit(1); // Termina il processo se non riesce a connettersi
}); });
module.exports = { app }; module.exports = { app };

View File

@@ -33,39 +33,36 @@ const { MsgTemplate } = require('../models/msg_template');
const globalTables = require('../tools/globalTables'); const globalTables = require('../tools/globalTables');
const emoji = require('node-emoji');
const i18n = require('i18n'); const i18n = require('i18n');
let url = process.env.URL || 'https://<PUBLIC-URL>'; let url = process.env.URL || 'https://<PUBLIC-URL>';
const Benvenuto = emoji.get('heartbeat') + emoji.get('heartbeat') + const Benvenuto = '💓💓💓 Benvenuto/a!';
emoji.get('heartbeat') + ' Benvenuto!';
const emo = { const emo = {
JOY: emoji.get('joy'), JOY: '😂',
JOY2: emoji.get('rolling_on_the_floor_laughing'), JOY2: '🤣',
DANCER: emoji.get('dancer'), DANCER: '💃',
STARS: emoji.get('stars'), STARS: '✨',
FIRE: emoji.get('fire'), FIRE: '🔥',
SUN: emoji.get('sunrise'), SUN: '☀️',
TV: emoji.get('tv'), TV: '📺',
NEWSPAPER: emoji.get('newspaper'), NEWSPAPER: '🗞',
KISS: emoji.get('kiss'), KISS: '😘',
PENCIL: emoji.get('pencil2'), PENCIL: '✏️',
DREAM: emoji.get('beach_with_umbrella'), DREAM: '🏖',
EYES: emoji.get('eyes'), EYES: '😜',
DIZZY: emoji.get('dizzy'), DIZZY: '💫',
ONE_HUNDRED: emoji.get('100'), ONE_HUNDRED: '💯',
SMILE_STAR: emoji.get('star-struck'), SMILE_STAR: '🤩', // Star-struck
LEFT_FACING_FIST: emoji.get('left-facing_fist'), LEFT_FACING_FIST: '🤛', // Left-facing fist
CHECK_VERDE: emoji.get('white_check_mark'), CHECK_VERDE: '✅', // White check mark (verde)
CHECK_GRIGIA: emoji.get('ballot_box_with_check'), CHECK_GRIGIA: '☑️', // Ballot box with check (grigia)
CROSS_ROSSA: emoji.get('x'), CROSS_ROSSA: '', // X (rossa)
ENVELOPE: emoji.get('envelope'), ENVELOPE: '✉️', // Envelope
EXCLAMATION_MARK: emoji.get('exclamation'), EXCLAMATION_MARK: '❗', // Exclamation mark
QUESTION_MARK: emoji.get('question'), QUESTION_MARK: '❓', // Question mark
ARROW_RIGHT: emoji.get('arrow_right'), ARROW_RIGHT: '➡️', // Arrow pointing to the right
INVITATI: '', INVITATI: '',
HEART: '❤️', HEART: '❤️',
BLUE_HEART: '💙', BLUE_HEART: '💙',
@@ -229,134 +226,128 @@ const MsgRisp = {
function getemojibynumber(number) { function getemojibynumber(number) {
if (number === 0) { if (number === 0) {
return emoji.get('zero'); return '0⃣'; // zero
} else if (number === 1) { } else if (number === 1) {
return emoji.get('one'); return '1⃣'; // one
} else if (number === 2) { } else if (number === 2) {
return emoji.get('two'); return '2⃣'; // two
} else if (number === 3) { } else if (number === 3) {
return emoji.get('three'); return '3⃣'; // three
} else if (number === 4) { } else if (number === 4) {
return emoji.get('four'); return '4⃣'; // four
} else if (number === 5) { } else if (number === 5) {
return emoji.get('five'); return '5⃣'; // five
} else if (number === 6) { } else if (number === 6) {
return emoji.get('six'); return '6⃣'; // six
} else if (number === 7) { } else if (number === 7) {
return emoji.get('seven'); return '7⃣'; // seven
} else if (number === 8) { } else if (number === 8) {
return emoji.get('height'); return '8⃣'; // eight
} else if (number === 9) { } else if (number === 9) {
return emoji.get('nine'); return '9⃣'; // nine
} else { } else {
return number; return number;
} }
} }
const Menu = { const Menu = {
LANG_IT: emoji.get('flag-it') + ' Italiano', LANG_IT: '🇮🇹 Italiano', // Bandiera italiana
LANG_EN: emoji.get('flag-gb') + ' English', LANG_EN: '🇬🇧 English', // Bandiera del Regno Unito
LANG_ES: emoji.get('flag-es') + ' Español', LANG_ES: '🇪🇸 Español', // Bandiera spagnola
LANG_FR: emoji.get('flag-fr') + ' Français', LANG_FR: '🇫🇷 Français', // Bandiera francese
LANG_SI: emoji.get('flag-si') + ' Slovenski', LANG_SI: '🇸🇮 Slovenski', // Bandiera slovena
LANG_PT: emoji.get('flag-pt') + ' Português', LANG_PT: '🇵🇹 Português', // Bandiera portoghese
LANG: emoji.get('globe_with_meridians') + ' Language', LANG: '🌐 Language', // Globo con meridiani
CHAT_PERSONALE: emoji.get('female-office-worker') + emoji.get('computer'), CHAT_PERSONALE: '👩‍💼💻', // Donna impiegata + computer
EXIT_TELEGRAM: 'exittotelegram', EXIT_TELEGRAM: 'exittotelegram',
MSG_TO_USER: 'sendmsgto', MSG_TO_USER: 'sendmsgto',
ADMIN: emoji.get('information_desk_person') + ' Admin', ADMIN: '💁‍♀️ Admin', // Persona al banco informazioni
AIUTO: '🔮 Help', AIUTO: '🔮 Help', // Cristallo magico
ALTRO: emoji.get('newspaper') + ' Altro', ALTRO: '📰 Altro', // Giornale
SETPICPROFILE: '🖼 SetPicProfile', SETPICPROFILE: '🖼 SetPicProfile', // Cornice con foto
RESETPWD: '🔑 SetResetPwd', RESETPWD: '🔑 SetResetPwd', // Chiave
// MSG_TO_NAVE: emoji.get('incoming_envelope') + 'Msg_to_Navi', MSG_SI_INVITATI_NO_7REQ_INVITATI: '📩Inv e NO 7 Req', // Busta
// MSG_NO_7_REQ: emoji.get('incoming_envelope') + 'No 7 Req.', MSGSTAFF: '📩 Invia a STAFF', // Busta
// 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',
MSGAPPARTIENE_CIRCUITI_RIS: 'Invia a Utenti dei Circuiti RIS', MSGAPPARTIENE_CIRCUITI_RIS: 'Invia a Utenti dei Circuiti RIS',
MSGPAOLO: emoji.get('incoming_envelope') + ' Invia a SURYA', MSGPAOLO: '📩 Invia a SURYA', // Busta
RESTART_SRV: emoji.get('incoming_envelope') + 'Restart-NodeJs', RESTART_SRV: '📩Restart-NodeJs', // Busta
REBOOT_SRV: emoji.get('incoming_envelope') + 'Reboot-VPS!', REBOOT_SRV: '📩Reboot-VPS!', // Busta
EXECSH: emoji.get('incoming_envelope') + 'ExecSH', EXECSH: '📩ExecSH', // Busta
LOG_SRV: '🖥Logserver.sh', LOG_SRV: '🖥Logserver.sh', // Monitor
MSGATUTTI: emoji.get('incoming_envelope') + ' Invia a TUTTI', MSGATUTTI: '📩 Invia a TUTTI', // Busta
it: { it: {
ACCEDI: emo.PERSON + ' Accedi', ACCEDI: '👤 Accedi', // Persona
LAVAGNA: emoji.get('om_symbol') + ' Lavagna', LAVAGNA: '🕉 Lavagna', // Simbolo Om
LINK_CONDIVIDERE: emoji.get('link') + ' Link da condividere', LINK_CONDIVIDERE: '🔗 Link da condividere', // Link
ZOOM: emoji.get('information_source') + ' Zoom (Conferenze)', ZOOM: ' Zoom (Conferenze)', // Informazione
INFO: emoji.get('information_source') + ' Informazioni', INFO: ' Informazioni', // Informazione
ASSISTENZA: emoji.get('open_hands') + ' Le Chat', ASSISTENZA: '👐 Le Chat', // Mani aperte
INDIETRO: emoji.get('back') + ' Indietro', INDIETRO: '🔙 Indietro', // Freccia indietro
SI: emoji.get('thumbsup') + ' SI', SI: '👍 SI', // Pollice su
NO: emoji.get('thumbsdown') + ' NO', NO: '👎 NO', // Pollice giù
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Esci dalla Conversazione', ESCI_DA_CHAT: '📩 Esci dalla Conversazione', // Busta
NUOVOSITO: '', NUOVOSITO: '',
}, },
es: { es: {
ACCEDI: emo.PERSON + ' Entra', ACCEDI: '👤 Entra',
LAVAGNA: emoji.get('om_symbol') + ' Tablero', LAVAGNA: '🕉 Tablero',
LINK_CONDIVIDERE: emoji.get('link') + ' Enlaces para compartir', LINK_CONDIVIDERE: '🔗 Enlaces para compartir',
ZOOM: emoji.get('information_source') + ' Zoom (Conferencias)', ZOOM: ' Zoom (Conferencias)',
INFO: emoji.get('information_source') + ' Información', INFO: ' Información',
ASSISTENZA: emoji.get('open_hands') + ' Chats', ASSISTENZA: '👐 Chats',
INDIETRO: emoji.get('back') + ' Volver', INDIETRO: '🔙 Volver',
SI: emoji.get('thumbsup') + ' SÍ', SI: '👍 SÍ',
NO: emoji.get('thumbsdown') + ' NO', NO: '👎 NO',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Salir de la conversación', ESCI_DA_CHAT: '📩 Salir de la conversación',
}, },
fr: { fr: {
ACCEDI: emo.PERSON + ' Entrez', ACCEDI: '👤 Entrez',
LAVAGNA: emoji.get('om_symbol') + ' Tableau de bord', LAVAGNA: '🕉 Tableau de bord',
LINK_CONDIVIDERE: emoji.get('link') + ' Liens à partager', LINK_CONDIVIDERE: '🔗 Liens à partager',
ZOOM: emoji.get('information_source') + ' Zoom (Conférences)', ZOOM: ' Zoom (Conférences)',
INFO: emoji.get('information_source') + ' Informations', INFO: ' Informations',
ASSISTENZA: emoji.get('open_hands') + ' Les chats', ASSISTENZA: '👐 Les chats',
INDIETRO: emoji.get('back') + ' Retour', INDIETRO: '🔙 Retour',
SI: emoji.get('thumbsup') + ' OUI', SI: '👍 OUI',
NO: emoji.get('thumbsdown') + ' NON', NO: '👎 NON',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Quitter la conversation', ESCI_DA_CHAT: '📩 Quitter la conversation',
}, },
si: { si: {
ACCEDI: emo.PERSON + ' Prijava', ACCEDI: '👤 Prijava',
LAVAGNA: emoji.get('om_symbol') + ' Tabla', LAVAGNA: '🕉 Tabla',
LINK_CONDIVIDERE: emoji.get('link') + ' Link za vpis oseb', LINK_CONDIVIDERE: '🔗 Link za vpis oseb',
ZOOM: emoji.get('information_source') + ' Zoom (Konference)', ZOOM: ' Zoom (Konference)',
INFO: emoji.get('information_source') + ' Informacije', INFO: ' Informacije',
ASSISTENZA: emoji.get('open_hands') + ' jev klepet', ASSISTENZA: '👐 jev klepet',
INDIETRO: emoji.get('back') + ' Nazaj', INDIETRO: '🔙 Nazaj',
SI: emoji.get('thumbsup') + ' DA', SI: '👍 DA',
NO: emoji.get('thumbsdown') + ' NE', NO: '👎 NE',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Zaprite pogovor', ESCI_DA_CHAT: '📩 Zaprite pogovor',
}, },
pt: { pt: {
ACCEDI: emo.PERSON + ' Entre', ACCEDI: '👤 Entre',
LAVAGNA: emoji.get('om_symbol') + ' Tablero', LAVAGNA: '🕉 Tablero',
LINK_CONDIVIDERE: emoji.get('link') + ' Links para compartilhar', LINK_CONDIVIDERE: '🔗 Links para compartilhar',
ZOOM: emoji.get('information_source') + ' Zoom (Conferências)', ZOOM: ' Zoom (Conferências)',
INFO: emoji.get('information_source') + ' Informações', INFO: ' Informações',
ASSISTENZA: emoji.get('open_hands') + ' Chats', ASSISTENZA: '👐 Chats',
INDIETRO: emoji.get('back') + ' Voltar', INDIETRO: '🔙 Voltar',
SI: emoji.get('thumbsup') + ' SIM', SI: '👍 SIM',
NO: emoji.get('thumbsdown') + ' NÃO', NO: '👎 NÃO',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Sair da Conversa', ESCI_DA_CHAT: '📩 Sair da Conversa',
}, },
enUs: { enUs: {
ACCEDI: emo.PERSON + ' Enter', ACCEDI: '👤 Enter',
LAVAGNA: emoji.get('om_symbol') + ' DashBoard', LAVAGNA: '🕉 DashBoard',
LINK_CONDIVIDERE: emoji.get('link') + ' Link to Share', LINK_CONDIVIDERE: '🔗 Link to Share',
ZOOM: emoji.get('information_source') + ' Zoom (Conference)', ZOOM: ' Zoom (Conference)',
INFO: emoji.get('information_source') + ' Info', INFO: ' Info',
ASSISTENZA: emoji.get('open_hands') + ' Chats', ASSISTENZA: '👐 Chats',
INDIETRO: emoji.get('back') + ' Back', INDIETRO: '🔙 Back',
SI: emoji.get('thumbsup') + ' YES', SI: '👍 YES',
NO: emoji.get('thumbsdown') + ' NO', NO: '👎 NO',
ESCI_DA_CHAT: emoji.get('incoming_envelope') + ' Exit to the Conversation', ESCI_DA_CHAT: '📩 Exit to the Conversation',
}, },
}; };
const CONTA_SOLO = 'contasolo'; const CONTA_SOLO = 'contasolo';
@@ -483,8 +474,8 @@ const StatusMSGALL = {
}; };
const txt = { const txt = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Scegli una voce di menu:' + MSG_SCEGLI_MENU: '💫' + ' Scegli una voce di menu:' +
emoji.get('dizzy'), '💫',
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_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_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) ☀️.', 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_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + '🚫 %s Non è stato Ammesso !',
MSG_ISCRITTO_CONACREIS: emo.FIRE + '[%s] Si è appena Iscritto al Conacreis "%s"', 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_ISCRITTO_ARCADEI: emo.FIRE + '[%s] Si è appena Iscritto ad Arcadei "%s"',
MSG_MSG_SENT: emoji.get('envelope') + ' Messaggi Inviati !', MSG_MSG_SENT: '📨' + ' Messaggi Inviati !',
MSG_MSG_TOSENT: emoji.get('envelope') + ' Messaggi da Inviare', MSG_MSG_TOSENT: '📨' + ' Messaggi da Inviare',
MSG_MSG_INCORSO: emoji.get('envelope') + ' messaggi in corso... Inviati attualmente', MSG_MSG_INCORSO: '📨' + ' messaggi in corso... Inviati attualmente',
MSG_SET_USERNAME_TELEGRAM: '[Prima di continuare con la registrazione in RISO.APP]\n' + 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' + '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' + '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 = { const txt_es = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Elija un elemento del menú:' + MSG_SCEGLI_MENU: '💫' + ' Elija un elemento del menú:' +
emoji.get('dizzy'), '💫',
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_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: '¡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.:', 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 !', '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 %s Non è stato Ammesso !', '🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: emoji.get('envelope') + ' Mensajes enviados !', MSG_MSG_SENT: '📨' + ' Mensajes enviados !',
MSG_MSG_TOSENT: emoji.get('envelope') + ' Mensajes a enviar', MSG_MSG_TOSENT: '📨' + ' Mensajes a enviar',
MSG_MSG_INCORSO: emoji.get('envelope') + MSG_MSG_INCORSO: '📨' +
' mensajes en progreso... Enviado actualmente', ' mensajes en progreso... Enviado actualmente',
}; };
const txt_fr = { const txt_fr = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + 'Choisissez un élément de menu:' + MSG_SCEGLI_MENU: '💫' + 'Choisissez un élément de menu:' +
emoji.get('dizzy'), '💫',
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_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 lusername (40 caractères maximum)', MSG_ERRORE_USERNAME: 'Attention! Vous devez insérer seulement lusername (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: ', 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 !', '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 %s Non è stato Ammesso !', '🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: emoji.get('envelope') + ' Messages envoyés !', MSG_MSG_SENT: '📨' + ' Messages envoyés !',
MSG_MSG_TOSENT: emoji.get('envelope') + ' Messages à envoyer', MSG_MSG_TOSENT: '📨' + ' Messages à envoyer',
MSG_MSG_INCORSO: emoji.get('envelope') + MSG_MSG_INCORSO: '📨' +
' messages en cours... Actuellement envoyé', ' messages en cours... Actuellement envoyé',
}; };
const txt_si = { 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_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: '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: ', 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 = { const txt_en = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Choose a menu item:' + MSG_SCEGLI_MENU: '💫' + ' Choose a menu item:' +
emoji.get('dizzy'), '💫',
MSG_ASK_USERNAME_BO: 'Write in the message the username or email with which you registered on the site of %s:', 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: '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:', 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 !', '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 %s Non è stato Ammesso !', '🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: emoji.get('envelope') + ' Sent Messages !', MSG_MSG_SENT: '📨' + ' Sent Messages !',
MSG_MSG_TOSENT: emoji.get('envelope') + ' Messages to Send', MSG_MSG_TOSENT: '📨' + ' Messages to Send',
MSG_MSG_INCORSO: emoji.get('envelope') + MSG_MSG_INCORSO: '📨' +
' messages in progress... Currently sent', ' messages in progress... Currently sent',
}; };
const txt_pt = { const txt_pt = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Escolha um item do menu:' + MSG_SCEGLI_MENU: '💫' + ' Escolha um item do menu:' +
emoji.get('dizzy'), '💫',
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_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: '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:', 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 !', '🚫 Ci dispiace ma non sei stato Verificato correttamente dal tuo invitante %s.<br>Contattalo per farti abilitare !',
MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK + MSG_APORTADOR_NOT_CONFIRMED: emo.EXCLAMATION_MARK +
'🚫 %s Non è stato Ammesso !', '🚫 %s Non è stato Ammesso !',
MSG_MSG_SENT: emoji.get('envelope') + ' Mensagens Enviadas !', MSG_MSG_SENT: '📨' + ' Mensagens Enviadas !',
MSG_MSG_TOSENT: emoji.get('envelope') + ' Mensagens a enviar', MSG_MSG_TOSENT: '📨' + ' Mensagens a enviar',
MSG_MSG_INCORSO: emoji.get('envelope') + MSG_MSG_INCORSO: '📨' +
' mensagens em progresso... Actualmente enviado', ' mensagens em progresso... Actualmente enviado',
}; };
@@ -1764,7 +1755,7 @@ class Telegram {
risp += '!'; risp += '!';
} else if (MsgBot.COME_STAI.includes(testo.replace('?', ''))) { } 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.statusmsg = Status.WAITFOR_RISPOSTA;
rec.msgcodeprec = MsgBot.COME_STAI; rec.msgcodeprec = MsgBot.COME_STAI;
} else if (MsgBot.CHI_SONO_IO.includes(testo.replace('?', ''))) { } else if (MsgBot.CHI_SONO_IO.includes(testo.replace('?', ''))) {
@@ -2284,7 +2275,7 @@ class Telegram {
let index = 1; let index = 1;
downline.downline.forEach((user) => { downline.downline.forEach((user) => {
mystr += emoji.get('star-struck') + ` ${index}°: `; mystr += '🌠' + ` ${index}°: `;
mystr += (user.qualified) ? emo.CHECK_VERDE : emo.CROSS_ROSSA; mystr += (user.qualified) ? emo.CHECK_VERDE : emo.CROSS_ROSSA;
mystr += `${user.name} ${user.surname} (${user.username})\n`; mystr += `${user.name} ${user.surname} (${user.username})\n`;
index++; index++;
@@ -4647,6 +4638,7 @@ if (true) {
} }
} else if (data.action === InlineConferma.RISPOSTA_SI + shared_consts.CallFunz.RICHIESTA_CIRCUIT) { } 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) { if (circuit) {
// Aggiungilo nel Circuito // Aggiungilo nel Circuito
cmd = shared_consts.CIRCUITCMD.SET; cmd = shared_consts.CIRCUITCMD.SET;

View File

@@ -56,8 +56,8 @@ const readline = require('readline');
// Code goes here // Code goes here
const keySize = 256; const keySize = 256;
const ivSize = 128; // const ivSize = 128;
const iterations = 100; const iterations = 1000;
if (!!process.env.GCM_API_KEY && process.env.GCM_API_KEY !== '') { if (!!process.env.GCM_API_KEY && process.env.GCM_API_KEY !== '') {
webpush.setGCMAPIKey(process.env.GCM_API_KEY); webpush.setGCMAPIKey(process.env.GCM_API_KEY);
@@ -433,7 +433,8 @@ class ImageDownloader {
initialDelay = 1000, // Ritardo iniziale initialDelay = 1000, // Ritardo iniziale
maxDelay = 10000, // Ritardo massimo maxDelay = 10000, // Ritardo massimo
timeout = 30000, // Timeout della richiesta timeout = 30000, // Timeout della richiesta
validateContentType = true // Verifica del tipo di contenuto validateContentType = true, // Verifica del tipo di contenuto
nomefileoriginale = true,
} = options; } = options;
// Funzione per il backoff esponenziale // Funzione per il backoff esponenziale
@@ -448,7 +449,6 @@ class ImageDownloader {
fs.unlinkSync(filepath); fs.unlinkSync(filepath);
} }
const writer = fs.createWriteStream(filepath);
if (attempt > 1) if (attempt > 1)
console.log(`📥 Tentativo ${attempt}/${maxRetries} - Scaricamento: ${url}`); console.log(`📥 Tentativo ${attempt}/${maxRetries} - Scaricamento: ${url}`);
@@ -487,6 +487,28 @@ class ImageDownloader {
downloadedBytes += chunk.length; 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); response.data.pipe(writer);
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
@@ -501,8 +523,11 @@ class ImageDownloader {
}); });
}); });
console.info(`✅ Immagine scaricata con successo in ${filepath}`); console.info(`✅ Immagine scaricata con successo in ${filepath}`);
return true;
return { ris: true, filepath };
} catch (error) { } catch (error) {
console.error(`❌ Errore nel tentativo ${attempt}/${maxRetries}:`, error.message); console.error(`❌ Errore nel tentativo ${attempt}/${maxRetries}:`, error.message);
@@ -512,9 +537,14 @@ class ImageDownloader {
fs.unlinkSync(filepath); 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) { if (attempt === maxRetries) {
console.error(`Download fallito dopo ${maxRetries} tentativi: ${error.message}`); console.error(`Download fallito dopo ${maxRetries} tentativi: ${error.message}`);
return false; return { ris: false };
} }
const delay = getDelay(attempt); 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', RISO: '13',
FIOREDELLAVITA: '15', FIOREDELLAVITA: '15',
PIUCHEBUONO: '17', PIUCHEBUONO: '17',
MACRO: '18',
IDAPP_BOTONGROUP: '1000', IDAPP_BOTONGROUP: '1000',
@@ -3380,7 +3429,7 @@ module.exports = {
try { try {
console.time(name); console.time(name);
} catch (e) { } catch (e) {
} }
} }
}, },
@@ -3861,47 +3910,79 @@ module.exports = {
}, },
encrypt(msg, pass) { 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, { // Deriva la chiave usando PBKDF2
keySize: keySize / 32, const key = CryptoJS.PBKDF2(pass, salt, {
iterations: iterations, 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, { // Concatena salt, IV e ciphertext con un delimitatore
iv: iv, const transitmessage = `${salt.toString()}|${iv.toString()}|${encrypted.toString()}`;
padding: CryptoJS.pad.Pkcs7, return transitmessage;
mode: CryptoJS.mode.CBC, } catch (error) {
console.error('❌❌❌ Errore durante la crittazione:', error.message);
}); throw error;
}
// 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;
}, },
decrypt(transitmessage, pass) { decrypt(transitmessage, pass) {
var salt = CryptoJS.enc.Hex.parse(transitmessage.substr(0, 32)); try {
var iv = CryptoJS.enc.Hex.parse(transitmessage.substr(32, 32)); let saltHex, ivHex, encrypted;
var encrypted = transitmessage.substring(64);
var key = CryptoJS.PBKDF2(pass, salt, { // Controlla se il messaggio è nel nuovo formato (con delimitatore)
keySize: keySize / 32, if (transitmessage.includes('|')) {
iterations: iterations, 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, { // Converte salt e IV da esadecimale
iv: iv, const salt = CryptoJS.enc.Hex.parse(saltHex);
padding: CryptoJS.pad.Pkcs7, const iv = CryptoJS.enc.Hex.parse(ivHex);
mode: CryptoJS.mode.CBC,
}); // Deriva la chiave usando PBKDF2
return decrypted; 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) { cryptdata(mydata) {
if (mydata === '') if (mydata === '')
return ''; return '';
@@ -3911,13 +3992,17 @@ module.exports = {
}, },
decryptdata(mydatacrypted) { 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 ''; 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) { BoolToInt(mybool) {
@@ -5831,7 +5916,7 @@ module.exports = {
} }
if (mov.groupfrom) { if (mov.groupfrom) {
userfrom += mov.groupfrom.groupname userfrom += mov.groupfrom.groupname
tipocontofrom = shared_consts.AccountType.COLLECTIVE_ACCOUNT tipocontofrom = shared_consts.AccountType.CONTO_DI_GRUPPO
} }
if (mov.userfrom) { if (mov.userfrom) {
userfrom += mov.userfrom.username userfrom += mov.userfrom.username
@@ -5844,7 +5929,7 @@ module.exports = {
} }
if (mov.groupto) { if (mov.groupto) {
userto += mov.groupto.groupname userto += mov.groupto.groupname
tipocontoto = shared_consts.AccountType.COLLECTIVE_ACCOUNT tipocontoto = shared_consts.AccountType.CONTO_DI_GRUPPO
} }
if (mov.userto) { if (mov.userto) {
userto += mov.userto.username userto += mov.userto.username
@@ -5982,8 +6067,233 @@ module.exports = {
// Funzione per implementare il ritardo tra i tentativi // Funzione per implementare il ritardo tra i tentativi
sleep(ms) { sleep(ms) {
return new Promise(resolve => setTimeout(resolve, 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;
},
}; };

View File

@@ -47,12 +47,14 @@ const Pickup = require('../models/pickup');
const { Newstosent } = require('../models/newstosent'); const { Newstosent } = require('../models/newstosent');
const { MyPage } = require('../models/mypage'); const { MyPage } = require('../models/mypage');
const { MyElem } = require('../models/myelem'); const { MyElem } = require('../models/myelem');
const { Cron } = require('../models/cron');
const { MyScheda } = require('../models/myscheda'); const { MyScheda } = require('../models/myscheda');
const { MyBot } = require('../models/bot'); const { MyBot } = require('../models/bot');
const { CfgServer } = require('../models/cfgserver'); const { CfgServer } = require('../models/cfgserver');
const { CalZoom } = require('../models/calzoom'); const { CalZoom } = require('../models/calzoom');
const { Gallery } = require('../models/gallery'); const { Gallery } = require('../models/gallery');
const { TemplEmail } = require('../models/templemail'); const { TemplEmail } = require('../models/templemail');
const { DestNewsletter } = require('../models/destnewsletter');
const { OpzEmail } = require('../models/opzemail'); const { OpzEmail } = require('../models/opzemail');
const { MailingList } = require('../models/mailinglist'); const { MailingList } = require('../models/mailinglist');
const { Settings } = require('../models/settings'); const { Settings } = require('../models/settings');
@@ -76,6 +78,8 @@ const Collana = require('../models/collana');
const CatAI = require('../models/catai'); const CatAI = require('../models/catai');
const { QueryAI } = require('../models/queryai'); const { QueryAI } = require('../models/queryai');
const SubCatProd = require('../models/subcatprod'); 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 { Category } = require('../models/category');
const ShareWithUs = require('../models/sharewithus'); const ShareWithUs = require('../models/sharewithus');
const Site = require('../models/site'); const Site = require('../models/site');
@@ -143,6 +147,10 @@ module.exports = {
mytable = QueryAI; mytable = QueryAI;
else if (tablename === 'subcatprods') else if (tablename === 'subcatprods')
mytable = SubCatProd; 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') else if (tablename === 'sharewithus')
mytable = ShareWithUs; mytable = ShareWithUs;
else if (tablename === 'sites') else if (tablename === 'sites')
@@ -191,6 +199,8 @@ module.exports = {
mytable = MyPage; mytable = MyPage;
else if (tablename === 'myelems') else if (tablename === 'myelems')
mytable = MyElem; mytable = MyElem;
else if (tablename === 'crons')
mytable = Cron;
else if (tablename === 'myschedas') else if (tablename === 'myschedas')
mytable = MyScheda; mytable = MyScheda;
else if (tablename === 'bots') else if (tablename === 'bots')
@@ -201,6 +211,8 @@ module.exports = {
mytable = CalZoom; mytable = CalZoom;
else if (tablename === 'templemail') else if (tablename === 'templemail')
mytable = TemplEmail; mytable = TemplEmail;
else if (tablename === 'destnewsletter')
mytable = DestNewsletter;
else if (tablename === 'opzemail') else if (tablename === 'opzemail')
mytable = OpzEmail; mytable = OpzEmail;
else if (tablename === 'settings') else if (tablename === 'settings')

View File

@@ -101,6 +101,7 @@ module.exports = Object.freeze({
PREFIX_IMG_SMALL: 'sm_', PREFIX_IMG_SMALL: 'sm_',
DIR_UPLOAD: '/upload', //'/upload' DIR_UPLOAD: '/upload', //'/upload'
DIR_PUBLIC_LOCALE: '/public',
Privacy: { Privacy: {
all: 'all', all: 'all',

View File

@@ -256,7 +256,7 @@ module.exports = {
], ],
TABLES_USER_ID: ['mygroups', 'myskills', 'mybachecas', 'myhosps', 'mygoods'], TABLES_USER_ID: ['mygroups', 'myskills', 'mybachecas', 'myhosps', 'mygoods'],
TABLES_CREATEDBY: ['mygroups', 'circuits', 'attivitas'], 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'], TABLES_FIELDS_DESCR_AND_CITY_AND_USER: ['myskills', 'mybachecas', 'myhosps', 'mygoods'],
@@ -359,6 +359,7 @@ module.exports = {
Zoomeri: 32, Zoomeri: 32,
Department: 64, Department: 64,
Grafico: 128, Grafico: 128,
Commerciale: 256,
}, },
MessageOptions: { MessageOptions: {
@@ -730,6 +731,8 @@ module.exports = {
'profile', 'profile',
'calcstat', 'calcstat',
'news_on', 'news_on',
'diario_on',
'test',
'aportador_solidario', 'aportador_solidario',
'made_gift', 'made_gift',
'ind_order', 'ind_order',
@@ -823,6 +826,8 @@ module.exports = {
mycities: 1, mycities: 1,
sector: 1, sector: 1,
recCatGrp: 1, recCatGrp: 1,
mycircuits: 1,
lastdate_reqRisGroup: 1,
} }
} else if (table === this.TABLES_CIRCUITS) { } else if (table === this.TABLES_CIRCUITS) {
proj = { proj = {
@@ -1163,7 +1168,7 @@ module.exports = {
AUDIOLIBRO: 22, AUDIOLIBRO: 22,
VIDEO: 23, VIDEO: 23,
CARTE: 25, CARTE: 25,
// ----------- // -----------
NUOVO: 101, NUOVO: 101,
USATO: 102, USATO: 102,
DOWNLOAD: 103, DOWNLOAD: 103,
@@ -1178,15 +1183,42 @@ module.exports = {
AccountType: { AccountType: {
USER: 0, USER: 0,
COLLECTIVE_ACCOUNT: 1, CONTO_DI_GRUPPO: 1,
COMMUNITY_ACCOUNT: 2, COMMUNITY_ACCOUNT: 2,
}, },
CmdQueryMs: { CmdQueryMs: {
GET: 0, GET: 0,
SET: 1, 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 // Download, DVD, Epub, Mobi, Nuovo, PDF, Streaming, Usato
}; };

View File

@@ -1 +1 @@
1.2.2 1.2.42

View File

@@ -1899,7 +1899,7 @@ bser@2.1.1:
dependencies: dependencies:
node-int64 "^0.4.0" node-int64 "^0.4.0"
bson@^6.10.1, bson@^6.10.3: bson@^6.10.3:
version "6.10.3" version "6.10.3"
resolved "https://registry.yarnpkg.com/bson/-/bson-6.10.3.tgz#5f9a463af6b83e264bedd08b236d1356a30eda47" resolved "https://registry.yarnpkg.com/bson/-/bson-6.10.3.tgz#5f9a463af6b83e264bedd08b236d1356a30eda47"
integrity sha512-MTxGsqgYTwfshYWTRdmZRC+M7FnG1b4y7RO7p2k3X24Wq0yv1m77Wsj0BzlPzd/IowgESfsruQCUToa7vbOpPQ== integrity sha512-MTxGsqgYTwfshYWTRdmZRC+M7FnG1b4y7RO7p2k3X24Wq0yv1m77Wsj0BzlPzd/IowgESfsruQCUToa7vbOpPQ==
@@ -4001,10 +4001,10 @@ gulp-replace@^1.1.4:
replacestream "^4.0.3" replacestream "^4.0.3"
yargs-parser ">=5.0.0-security.0" yargs-parser ">=5.0.0-security.0"
gulp-sass@^6.0.0: gulp-sass@^6.0.1:
version "6.0.0" version "6.0.1"
resolved "https://registry.yarnpkg.com/gulp-sass/-/gulp-sass-6.0.0.tgz#91e651d86baf53bf7de8a537b1a38ea839968a4b" resolved "https://registry.yarnpkg.com/gulp-sass/-/gulp-sass-6.0.1.tgz#28d292b5e9ca143d763e14fce87d6723b6d1b749"
integrity sha512-FGb4Uab4jnH2GnSfBGd6uW3+imvNodAGfsjGcUhEtpNYPVx+TK2tp5uh7MO0sSR7aIf1Sm544werc+zV7ejHHw== integrity sha512-4wonidxB8lGPHvahelpGavUBJAuERSl+OIVxPCyQthK4lSJhZ/u3/qjFcyAtnMIXDl6fXTn34H4BXsN7gt54kQ==
dependencies: dependencies:
lodash.clonedeep "^4.5.0" lodash.clonedeep "^4.5.0"
picocolors "^1.0.0" picocolors "^1.0.0"
@@ -6023,7 +6023,16 @@ mongodb-connection-string-url@^3.0.0:
"@types/whatwg-url" "^11.0.2" "@types/whatwg-url" "^11.0.2"
whatwg-url "^14.1.0 || ^13.0.0" 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" version "6.14.1"
resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-6.14.1.tgz#ab1084c00eba5f736b9ac8a93055d7d3ad0725a8" resolved "https://registry.yarnpkg.com/mongodb/-/mongodb-6.14.1.tgz#ab1084c00eba5f736b9ac8a93055d7d3ad0725a8"
integrity sha512-GnHWIm4GtgREkssWRv9vYKNvqwbLd8WL5hCW3nCqzI2OxEZ6Q5g6vc3J6L1Grz0x1hx1wmYAprLlRr3kzBLcJg== integrity sha512-GnHWIm4GtgREkssWRv9vYKNvqwbLd8WL5hCW3nCqzI2OxEZ6Q5g6vc3J6L1Grz0x1hx1wmYAprLlRr3kzBLcJg==
@@ -6032,12 +6041,12 @@ mongodb@^6.14.1, mongodb@~6.14.0:
bson "^6.10.3" bson "^6.10.3"
mongodb-connection-string-url "^3.0.0" mongodb-connection-string-url "^3.0.0"
mongoose@^8.12.0: mongoose@^8.12.1:
version "8.12.0" version "8.12.1"
resolved "https://registry.yarnpkg.com/mongoose/-/mongoose-8.12.0.tgz#1d0313982b1b737a1552e05541980b04a3979375" resolved "https://registry.yarnpkg.com/mongoose/-/mongoose-8.12.1.tgz#20fdc9a6cff72b323e438c6b4492cd4d4e1dd989"
integrity sha512-FXZIngJBTt/gvb6uHZHiROy3Mk3EOjNpD0m+GBRfG+twuEntnMjfxwcA94YbYIulf9LkBozt7H8w2OJpqHdUxA== integrity sha512-UW22y8QFVYmrb36hm8cGncfn4ARc/XsYWQwRTaj0gxtQk1rDuhzDO1eBantS+hTTatfAIS96LlRCJrcNHvW5+Q==
dependencies: dependencies:
bson "^6.10.1" bson "^6.10.3"
kareem "2.6.3" kareem "2.6.3"
mongodb "~6.14.0" mongodb "~6.14.0"
mpath "0.9.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" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2"
integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==
multer@^1.4.5-lts.1: multer@^1.4.5-lts.2:
version "1.4.5-lts.1" version "1.4.5-lts.2"
resolved "https://registry.yarnpkg.com/multer/-/multer-1.4.5-lts.1.tgz#803e24ad1984f58edffbc79f56e305aec5cfd1ac" resolved "https://registry.yarnpkg.com/multer/-/multer-1.4.5-lts.2.tgz#340af065d8685dda846ec9e3d7655fcd50afba2d"
integrity sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ== integrity sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==
dependencies: dependencies:
append-field "^1.0.0" append-field "^1.0.0"
busboy "^1.0.0" busboy "^1.0.0"
@@ -6465,10 +6474,10 @@ open@^10.1.0:
is-inside-container "^1.0.0" is-inside-container "^1.0.0"
is-wsl "^3.1.0" is-wsl "^3.1.0"
openai@^4.86.1: openai@^4.86.2:
version "4.86.1" version "4.87.3"
resolved "https://registry.yarnpkg.com/openai/-/openai-4.86.1.tgz#4147252d5e6255e2ae716ea59b1d4e54a1c1472a" resolved "https://registry.yarnpkg.com/openai/-/openai-4.87.3.tgz#82679f09d91f0e8e9da94b9ee0369c44733577da"
integrity sha512-x3iCLyaC3yegFVZaxOmrYJjitKxZ9hpVbLi+ZlT5UHuHTMlEQEbKXkGOM78z9qm2T5GF+XRUZCP2/aV4UPFPJQ== integrity sha512-d2D54fzMuBYTxMW8wcNmhT1rYKcTfMJ8t+4KjH2KtvYenygITiGBgHoIrzHwnDQWW+C5oCA+ikIR2jgPCFqcKQ==
dependencies: dependencies:
"@types/node" "^18.11.18" "@types/node" "^18.11.18"
"@types/node-fetch" "^2.6.4" "@types/node-fetch" "^2.6.4"